runtime-profiler.cc 7.93 KB
Newer Older
1
// Copyright 2012 the V8 project authors. All rights reserved.
2 3
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
4

5
#include "src/runtime-profiler.h"
6

7
#include "src/assembler.h"
8
#include "src/base/platform/platform.h"
9 10
#include "src/bootstrapper.h"
#include "src/compilation-cache.h"
11
#include "src/compiler.h"
12
#include "src/execution.h"
13
#include "src/frames-inl.h"
14
#include "src/global-handles.h"
15
#include "src/interpreter/interpreter.h"
16
#include "src/tracing/trace-event.h"
17 18 19 20

namespace v8 {
namespace internal {

21 22 23 24
// Number of times a function has to be seen on the stack before it is
// optimized.
static const int kProfilerTicksBeforeOptimization = 2;

25 26 27
// The number of ticks required for optimizing a function increases with
// the size of the bytecode. This is in addition to the
// kProfilerTicksBeforeOptimization required for any function.
28
static const int kBytecodeSizeAllowancePerTick = 1200;
29

30
// Maximum size in bytes of generate code for a function to allow OSR.
31
static const int kOSRBytecodeSizeAllowanceBase = 180;
32

33
static const int kOSRBytecodeSizeAllowancePerTick = 48;
34

35 36
// Maximum size in bytes of generated code for a function to be optimized
// the very first time it is seen on the stack.
37
static const int kMaxBytecodeSizeForEarlyOpt = 90;
38

39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
#define OPTIMIZATION_REASON_LIST(V)                            \
  V(DoNotOptimize, "do not optimize")                          \
  V(HotAndStable, "hot and stable")                            \
  V(SmallFunction, "small function")

enum class OptimizationReason : uint8_t {
#define OPTIMIZATION_REASON_CONSTANTS(Constant, message) k##Constant,
  OPTIMIZATION_REASON_LIST(OPTIMIZATION_REASON_CONSTANTS)
#undef OPTIMIZATION_REASON_CONSTANTS
};

char const* OptimizationReasonToString(OptimizationReason reason) {
  static char const* reasons[] = {
#define OPTIMIZATION_REASON_TEXTS(Constant, message) message,
      OPTIMIZATION_REASON_LIST(OPTIMIZATION_REASON_TEXTS)
#undef OPTIMIZATION_REASON_TEXTS
  };
  size_t const index = static_cast<size_t>(reason);
  DCHECK_LT(index, arraysize(reasons));
  return reasons[index];
}

std::ostream& operator<<(std::ostream& os, OptimizationReason reason) {
  return os << OptimizationReasonToString(reason);
}
64

65 66
RuntimeProfiler::RuntimeProfiler(Isolate* isolate)
    : isolate_(isolate),
67
      any_ic_changed_(false) {
68 69
}

70
static void TraceRecompile(JSFunction function, const char* reason,
71
                           const char* type) {
72
  if (FLAG_trace_opt) {
73
    PrintF("[marking ");
74
    function->ShortPrint();
75
    PrintF(" for %s recompilation, reason: %s", type, reason);
76 77
    PrintF("]\n");
  }
78
}
79

80
void RuntimeProfiler::Optimize(JSFunction function, OptimizationReason reason) {
81 82
  DCHECK_NE(reason, OptimizationReason::kDoNotOptimize);
  TraceRecompile(function, OptimizationReasonToString(reason), "optimized");
83
  function->MarkForOptimization(ConcurrencyMode::kConcurrent);
84 85
}

86
void RuntimeProfiler::AttemptOnStackReplacement(InterpretedFrame* frame,
87
                                                int loop_nesting_levels) {
88
  JSFunction function = frame->function();
89
  SharedFunctionInfo shared = function->shared();
90
  if (!FLAG_use_osr || !shared->IsUserJavaScript()) {
91 92 93
    return;
  }

94
  // If the code is not optimizable, don't try OSR.
95
  if (shared->optimization_disabled()) return;
96

97 98 99
  // We're using on-stack replacement: Store new loop nesting level in
  // BytecodeArray header so that certain back edges in any interpreter frame
  // for this bytecode will trigger on-stack replacement for that frame.
100
  if (FLAG_trace_osr) {
101
    PrintF("[OSR - arming back edges in ");
102
    function->PrintName();
103
    PrintF("]\n");
104 105
  }

106
  DCHECK_EQ(StackFrame::INTERPRETED, frame->type());
107 108
  int level = frame->GetBytecodeArray()->osr_loop_nesting_level();
  frame->GetBytecodeArray()->set_osr_loop_nesting_level(
109
      Min(level + loop_nesting_levels, AbstractCode::kMaxLoopNestingMarker));
110 111
}

112
void RuntimeProfiler::MaybeOptimize(JSFunction function,
113
                                    InterpretedFrame* frame) {
114 115 116 117 118 119 120 121
  if (function->IsInOptimizationQueue()) {
    if (FLAG_trace_opt_verbose) {
      PrintF("[function ");
      function->PrintName();
      PrintF(" is already in optimization queue]\n");
    }
    return;
  }
122 123

  if (FLAG_always_osr) {
124
    AttemptOnStackReplacement(frame, AbstractCode::kMaxLoopNestingMarker);
125
    // Fall through and do a normal optimized compile as well.
126
  } else if (MaybeOSR(function, frame)) {
127 128 129
    return;
  }

130
  if (function->shared()->optimization_disabled()) return;
131

132 133
  OptimizationReason reason =
      ShouldOptimize(function, function->shared()->GetBytecodeArray());
134 135 136 137 138 139

  if (reason != OptimizationReason::kDoNotOptimize) {
    Optimize(function, reason);
  }
}

140
bool RuntimeProfiler::MaybeOSR(JSFunction function, InterpretedFrame* frame) {
141
  int ticks = function->feedback_vector()->profiler_ticks();
142 143 144
  // TODO(rmcilroy): Also ensure we only OSR top-level code if it is smaller
  // than kMaxToplevelSourceSize.

145 146 147
  if (function->IsMarkedForOptimization() ||
      function->IsMarkedForConcurrentOptimization() ||
      function->HasOptimizedCode()) {
148 149 150
    // Attempt OSR if we are still running interpreted code even though the
    // the function has long been marked or even already been optimized.
    int64_t allowance =
151 152
        kOSRBytecodeSizeAllowanceBase +
        static_cast<int64_t>(ticks) * kOSRBytecodeSizeAllowancePerTick;
153
    if (function->shared()->GetBytecodeArray()->length() <= allowance) {
154 155 156 157 158 159 160
      AttemptOnStackReplacement(frame);
    }
    return true;
  }
  return false;
}

161
OptimizationReason RuntimeProfiler::ShouldOptimize(JSFunction function,
162
                                                   BytecodeArray bytecode) {
163
  int ticks = function->feedback_vector()->profiler_ticks();
164 165
  int ticks_for_optimization =
      kProfilerTicksBeforeOptimization +
166
      (bytecode->length() / kBytecodeSizeAllowancePerTick);
167
  if (ticks >= ticks_for_optimization) {
168
    return OptimizationReason::kHotAndStable;
169 170
  } else if (!any_ic_changed_ &&
             bytecode->length() < kMaxBytecodeSizeForEarlyOpt) {
171 172
    // If no IC was patched since the last tick and this function is very
    // small, optimistically optimize it now.
173 174 175 176 177 178 179 180 181 182
    return OptimizationReason::kSmallFunction;
  } else if (FLAG_trace_opt_verbose) {
    PrintF("[not yet optimizing ");
    function->PrintName();
    PrintF(", not enough ticks: %d/%d and ", ticks,
           kProfilerTicksBeforeOptimization);
    if (any_ic_changed_) {
      PrintF("ICs changed]\n");
    } else {
      PrintF(" too large for small function optimization: %d/%d]\n",
183
             bytecode->length(), kMaxBytecodeSizeForEarlyOpt);
184
    }
185
  }
186
  return OptimizationReason::kDoNotOptimize;
187 188
}

189
void RuntimeProfiler::MarkCandidatesForOptimization() {
190
  HandleScope scope(isolate_);
191

Mythri's avatar
Mythri committed
192
  if (!isolate_->use_optimizer()) return;
193

194
  DisallowHeapAllocation no_gc;
195 196
  TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("v8.compile"),
               "V8.MarkCandidatesForOptimization");
197

198 199 200
  // Run through the JavaScript frames and collect them. If we already
  // have a sample of the function, we mark it for optimizations
  // (eagerly or lazily).
201
  int frame_count = 0;
202
  int frame_count_limit = FLAG_frame_count;
203
  for (JavaScriptFrameIterator it(isolate_);
204
       frame_count++ < frame_count_limit && !it.done();
205 206
       it.Advance()) {
    JavaScriptFrame* frame = it.frame();
207
    if (!frame->is_interpreted()) continue;
208

209
    JSFunction function = frame->function();
210
    DCHECK(function->shared()->is_compiled());
211 212
    if (!function->shared()->IsInterpreted()) continue;

213 214
    if (!function->has_feedback_vector()) continue;

215
    MaybeOptimize(function, InterpretedFrame::cast(frame));
216

217 218
    // TODO(leszeks): Move this increment to before the maybe optimize checks,
    // and update the tests to assume the increment has already happened.
219
    int ticks = function->feedback_vector()->profiler_ticks();
220
    if (ticks < Smi::kMaxValue) {
221
      function->feedback_vector()->set_profiler_ticks(ticks + 1);
222
    }
223
  }
224
  any_ic_changed_ = false;
225 226
}

227 228
}  // namespace internal
}  // namespace v8