summaryrefslogtreecommitdiff
path: root/deps/v8/src/execution/tiering-manager.cc
blob: ce51a184f41812a776daa30f7758d726f3e18473 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
// Copyright 2012 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "src/execution/tiering-manager.h"

#include "src/base/platform/platform.h"
#include "src/baseline/baseline-batch-compiler.h"
#include "src/baseline/baseline.h"
#include "src/codegen/assembler.h"
#include "src/codegen/compilation-cache.h"
#include "src/codegen/compiler.h"
#include "src/codegen/pending-optimization-table.h"
#include "src/common/globals.h"
#include "src/diagnostics/code-tracer.h"
#include "src/execution/execution.h"
#include "src/execution/frames-inl.h"
#include "src/flags/flags.h"
#include "src/handles/global-handles.h"
#include "src/init/bootstrapper.h"
#include "src/interpreter/interpreter.h"
#include "src/objects/code-kind.h"
#include "src/objects/code.h"
#include "src/tracing/trace-event.h"

namespace v8 {
namespace internal {

#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];
}

#undef OPTIMIZATION_REASON_LIST

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

class OptimizationDecision {
 public:
  static constexpr OptimizationDecision Maglev() {
    // TODO(v8:7700): Consider using another reason here.
    return {OptimizationReason::kHotAndStable, CodeKind::MAGLEV,
            ConcurrencyMode::kConcurrent};
  }
  static constexpr OptimizationDecision TurbofanHotAndStable() {
    return {OptimizationReason::kHotAndStable, CodeKind::TURBOFAN,
            ConcurrencyMode::kConcurrent};
  }
  static constexpr OptimizationDecision TurbofanSmallFunction() {
    return {OptimizationReason::kSmallFunction, CodeKind::TURBOFAN,
            ConcurrencyMode::kConcurrent};
  }
  static constexpr OptimizationDecision DoNotOptimize() {
    return {OptimizationReason::kDoNotOptimize,
            // These values don't matter but we have to pass something.
            CodeKind::TURBOFAN, ConcurrencyMode::kConcurrent};
  }

  constexpr bool should_optimize() const {
    return optimization_reason != OptimizationReason::kDoNotOptimize;
  }

  OptimizationReason optimization_reason;
  CodeKind code_kind;
  ConcurrencyMode concurrency_mode;

 private:
  OptimizationDecision() = default;
  constexpr OptimizationDecision(OptimizationReason optimization_reason,
                                 CodeKind code_kind,
                                 ConcurrencyMode concurrency_mode)
      : optimization_reason(optimization_reason),
        code_kind(code_kind),
        concurrency_mode(concurrency_mode) {}
};
// Since we pass by value:
static_assert(sizeof(OptimizationDecision) <= kInt32Size);

namespace {

void TraceInOptimizationQueue(JSFunction function, CodeKind current_code_kind) {
  if (v8_flags.trace_opt_verbose) {
    PrintF("[not marking function %s (%s) for optimization: already queued]\n",
           function.DebugNameCStr().get(), CodeKindToString(current_code_kind));
  }
}

void TraceHeuristicOptimizationDisallowed(JSFunction function) {
  if (v8_flags.trace_opt_verbose) {
    PrintF(
        "[not marking function %s for optimization: marked with "
        "%%PrepareFunctionForOptimization for manual optimization]\n",
        function.DebugNameCStr().get());
  }
}

void TraceRecompile(Isolate* isolate, JSFunction function,
                    OptimizationDecision d) {
  if (v8_flags.trace_opt) {
    CodeTracer::Scope scope(isolate->GetCodeTracer());
    PrintF(scope.file(), "[marking ");
    function.ShortPrint(scope.file());
    PrintF(scope.file(), " for optimization to %s, %s, reason: %s",
           CodeKindToString(d.code_kind), ToString(d.concurrency_mode),
           OptimizationReasonToString(d.optimization_reason));
    PrintF(scope.file(), "]\n");
  }
}

}  // namespace

void TraceManualRecompile(JSFunction function, CodeKind code_kind,
                          ConcurrencyMode concurrency_mode) {
  if (v8_flags.trace_opt) {
    PrintF("[manually marking ");
    function.ShortPrint();
    PrintF(" for optimization to %s, %s]\n", CodeKindToString(code_kind),
           ToString(concurrency_mode));
  }
}

void TieringManager::Optimize(JSFunction function, OptimizationDecision d) {
  DCHECK(d.should_optimize());
  TraceRecompile(isolate_, function, d);
  function.MarkForOptimization(isolate_, d.code_kind, d.concurrency_mode);
}

namespace {

bool TiersUpToMaglev(CodeKind code_kind) {
  // TODO(v8:7700): Flip the UNLIKELY when appropriate.
  return V8_UNLIKELY(v8_flags.maglev) &&
         CodeKindIsUnoptimizedJSFunction(code_kind);
}

bool TiersUpToMaglev(base::Optional<CodeKind> code_kind) {
  return code_kind.has_value() && TiersUpToMaglev(code_kind.value());
}

int InterruptBudgetFor(base::Optional<CodeKind> code_kind,
                       TieringState tiering_state, int bytecode_length) {
  if (IsRequestTurbofan(tiering_state) ||
      (code_kind.has_value() && code_kind.value() == CodeKind::TURBOFAN)) {
    return v8_flags.invocation_count_for_osr * bytecode_length;
  }
  return TiersUpToMaglev(code_kind) && tiering_state == TieringState::kNone
             ? v8_flags.invocation_count_for_maglev * bytecode_length
             : v8_flags.interrupt_budget;
}

}  // namespace

// static
int TieringManager::InterruptBudgetFor(Isolate* isolate, JSFunction function) {
  DCHECK(function.shared().is_compiled());
  const int bytecode_length =
      function.shared().GetBytecodeArray(isolate).length();
  if (function.has_feedback_vector()) {
    if (bytecode_length > v8_flags.max_optimized_bytecode_size) {
      // Decrease times of interrupt budget underflow, the reason of not setting
      // to INT_MAX is the interrupt budget may overflow when doing add
      // operation for forward jump.
      return INT_MAX / 2;
    }
    return ::i::InterruptBudgetFor(function.GetActiveTier(),
                                   function.tiering_state(), bytecode_length);
  }

  DCHECK(!function.has_feedback_vector());
  return bytecode_length *
         v8_flags.interrupt_budget_factor_for_feedback_allocation;
}

// static
int TieringManager::InitialInterruptBudget() {
  return V8_LIKELY(v8_flags.lazy_feedback_allocation)
             ? v8_flags.interrupt_budget_for_feedback_allocation
             : v8_flags.interrupt_budget;
}

namespace {

void TrySetOsrUrgency(Isolate* isolate, JSFunction function, int osr_urgency) {
  SharedFunctionInfo shared = function.shared();
  if (V8_UNLIKELY(!v8_flags.use_osr)) return;
  if (V8_UNLIKELY(shared.optimization_disabled())) return;

  // We've passed all checks - bump the OSR urgency.

  FeedbackVector fv = function.feedback_vector();
  if (V8_UNLIKELY(v8_flags.trace_osr)) {
    CodeTracer::Scope scope(isolate->GetCodeTracer());
    PrintF(scope.file(),
           "[OSR - setting osr urgency. function: %s, old urgency: %d, new "
           "urgency: %d]\n",
           function.DebugNameCStr().get(), fv.osr_urgency(), osr_urgency);
  }

  DCHECK_GE(osr_urgency, fv.osr_urgency());  // Never lower urgency here.
  fv.set_osr_urgency(osr_urgency);
}

void TryIncrementOsrUrgency(Isolate* isolate, JSFunction function) {
  int old_urgency = function.feedback_vector().osr_urgency();
  int new_urgency = std::min(old_urgency + 1, FeedbackVector::kMaxOsrUrgency);
  TrySetOsrUrgency(isolate, function, new_urgency);
}

void TryRequestOsrAtNextOpportunity(Isolate* isolate, JSFunction function) {
  TrySetOsrUrgency(isolate, function, FeedbackVector::kMaxOsrUrgency);
}

bool ShouldOptimizeAsSmallFunction(int bytecode_size, bool any_ic_changed) {
  return !any_ic_changed &&
         bytecode_size < v8_flags.max_bytecode_size_for_early_opt;
}

}  // namespace

void TieringManager::RequestOsrAtNextOpportunity(JSFunction function) {
  DisallowGarbageCollection no_gc;
  TryRequestOsrAtNextOpportunity(isolate_, function);
}

void TieringManager::MaybeOptimizeFrame(JSFunction function,
                                        CodeKind current_code_kind) {
  const TieringState tiering_state = function.feedback_vector().tiering_state();
  const TieringState osr_tiering_state =
      function.feedback_vector().osr_tiering_state();
  // Attenzione! Update this constant in case the condition below changes.
  static_assert(kTieringStateInProgressBlocksTierup);
  if (V8_UNLIKELY(IsInProgress(tiering_state)) ||
      V8_UNLIKELY(IsInProgress(osr_tiering_state))) {
    // Note: This effectively disables further tiering actions (e.g. OSR, or
    // tiering up into Maglev) for the function while it is being compiled.
    TraceInOptimizationQueue(function, current_code_kind);
    return;
  }

  if (V8_UNLIKELY(v8_flags.testing_d8_test_runner) &&
      ManualOptimizationTable::IsMarkedForManualOptimization(isolate_,
                                                             function)) {
    TraceHeuristicOptimizationDisallowed(function);
    return;
  }

  // TODO(v8:7700): Consider splitting this up for Maglev/Turbofan.
  if (V8_UNLIKELY(function.shared().optimization_disabled())) return;

  if (V8_UNLIKELY(v8_flags.always_osr)) {
    TryRequestOsrAtNextOpportunity(isolate_, function);
    // Continue below and do a normal optimized compile as well.
  }

  // Baseline OSR uses a separate mechanism and must not be considered here,
  // therefore we limit to kOptimizedJSFunctionCodeKindsMask.
  // TODO(v8:7700): Change the condition below for Maglev OSR once it is
  // implemented.
  if (IsRequestTurbofan(tiering_state) ||
      function.HasAvailableCodeKind(CodeKind::TURBOFAN)) {
    // OSR kicks in only once we've previously decided to tier up, but we are
    // still in a lower-tier frame (this implies a long-running loop).
    TryIncrementOsrUrgency(isolate_, function);

    // Return unconditionally and don't run through the optimization decision
    // again; we've already decided to tier up previously.
    return;
  }

  DCHECK(!IsRequestTurbofan(tiering_state));
  DCHECK(!function.HasAvailableCodeKind(CodeKind::TURBOFAN));
  OptimizationDecision d =
      ShouldOptimize(function.feedback_vector(), current_code_kind);
  // We might be stuck in a baseline frame that wants to tier up to Maglev, but
  // is in a loop, and can't OSR, because Maglev doesn't have OSR. Allow it to
  // skip over Maglev by re-checking ShouldOptimize as if we were in Maglev.
  // TODO(v8:7700): Remove this when Maglev can OSR.
  static_assert(!CodeKindCanOSR(CodeKind::MAGLEV));
  if (d.should_optimize() && d.code_kind == CodeKind::MAGLEV) {
    bool is_marked_for_maglev_optimization =
        IsRequestMaglev(tiering_state) ||
        function.HasAvailableCodeKind(CodeKind::MAGLEV);
    if (is_marked_for_maglev_optimization) {
      d = ShouldOptimize(function.feedback_vector(), CodeKind::MAGLEV);
    }
  }

  if (d.should_optimize()) Optimize(function, d);
}

OptimizationDecision TieringManager::ShouldOptimize(
    FeedbackVector feedback_vector, CodeKind current_code_kind,
    bool after_next_tick) {
  SharedFunctionInfo shared = feedback_vector.shared_function_info();
  if (TiersUpToMaglev(current_code_kind) &&
      shared.PassesFilter(v8_flags.maglev_filter) &&
      !shared.maglev_compilation_failed()) {
    if (any_ic_changed_) return OptimizationDecision::DoNotOptimize();
    return OptimizationDecision::Maglev();
  } else if (current_code_kind == CodeKind::TURBOFAN) {
    // Already in the top tier.
    return OptimizationDecision::DoNotOptimize();
  }

  if (!v8_flags.turbofan || !shared.PassesFilter(v8_flags.turbo_filter)) {
    return OptimizationDecision::DoNotOptimize();
  }

  BytecodeArray bytecode = shared.GetBytecodeArray(isolate_);
  if (bytecode.length() > v8_flags.max_optimized_bytecode_size) {
    return OptimizationDecision::DoNotOptimize();
  }
  const int ticks =
      feedback_vector.profiler_ticks() + (after_next_tick ? 1 : 0);
  const int ticks_for_optimization =
      v8_flags.ticks_before_optimization +
      (bytecode.length() / v8_flags.bytecode_size_allowance_per_tick);
  if (ticks >= ticks_for_optimization) {
    return OptimizationDecision::TurbofanHotAndStable();
  } else if (ShouldOptimizeAsSmallFunction(bytecode.length(),
                                           any_ic_changed_)) {
    // If no IC was patched since the last tick and this function is very
    // small, optimistically optimize it now.
    return OptimizationDecision::TurbofanSmallFunction();
  } else if (!after_next_tick && v8_flags.trace_opt_verbose) {
    PrintF("[not yet optimizing %s, not enough ticks: %d/%d and ",
           shared.DebugNameCStr().get(), ticks, ticks_for_optimization);
    if (any_ic_changed_) {
      PrintF("ICs changed]\n");
    } else {
      PrintF(" too large for small function optimization: %d/%d]\n",
             bytecode.length(),
             v8_flags.max_bytecode_size_for_early_opt.value());
    }
  }

  return OptimizationDecision::DoNotOptimize();
}

void TieringManager::NotifyICChanged(FeedbackVector vector) {
  if (v8_flags.global_ic_updated_flag) {
    any_ic_changed_ = true;
  }
  if (v8_flags.reset_interrupt_on_ic_update) {
    CodeKind code_kind = vector.has_optimized_code()
                             ? vector.optimized_code().kind()
                         : vector.shared_function_info().HasBaselineCode()
                             ? CodeKind::BASELINE
                             : CodeKind::INTERPRETED_FUNCTION;
    OptimizationDecision decision = ShouldOptimize(vector, code_kind, true);
    if (decision.should_optimize()) {
      SharedFunctionInfo shared = vector.shared_function_info();
      int bytecode_length = shared.GetBytecodeArray(isolate_).length();
      FeedbackCell cell = vector.parent_feedback_cell();
      int minimum = v8_flags.minimum_invocations_after_ic_update;
      int new_budget = minimum * bytecode_length;
      int current_budget = cell.interrupt_budget();
      if (new_budget > current_budget) {
        if (v8_flags.trace_opt_verbose) {
          PrintF("[delaying optimization of %s, IC changed]\n",
                 shared.DebugNameCStr().get());
        }
        cell.set_interrupt_budget(new_budget);
      }
    }
  }
}

TieringManager::OnInterruptTickScope::OnInterruptTickScope(
    TieringManager* profiler)
    : profiler_(profiler) {
  TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("v8.compile"),
               "V8.MarkCandidatesForOptimization");
}

TieringManager::OnInterruptTickScope::~OnInterruptTickScope() {
  profiler_->any_ic_changed_ = false;
}

void TieringManager::OnInterruptTick(Handle<JSFunction> function,
                                     CodeKind code_kind) {
  IsCompiledScope is_compiled_scope(
      function->shared().is_compiled_scope(isolate_));

  // Remember whether the function had a vector at this point. This is relevant
  // later since the configuration 'Ignition without a vector' can be
  // considered a tier on its own. We begin tiering up to tiers higher than
  // Sparkplug only when reaching this point *with* a feedback vector.
  const bool had_feedback_vector = function->has_feedback_vector();

  // Ensure that the feedback vector has been allocated.
  if (!had_feedback_vector) {
    JSFunction::CreateAndAttachFeedbackVector(isolate_, function,
                                              &is_compiled_scope);
    DCHECK(is_compiled_scope.is_compiled());
    // Also initialize the invocation count here. This is only really needed for
    // OSR. When we OSR functions with lazy feedback allocation we want to have
    // a non zero invocation count so we can inline functions.
    function->feedback_vector().set_invocation_count(1, kRelaxedStore);
  }

  DCHECK(function->has_feedback_vector());
  DCHECK(function->shared().is_compiled());
  DCHECK(function->shared().HasBytecodeArray());

  // TODO(jgruber): Consider integrating this into a linear tiering system
  // controlled by TieringState in which the order is always
  // Ignition-Sparkplug-Turbofan, and only a single tierup is requested at
  // once.
  // It's unclear whether this is possible and/or makes sense - for example,
  // batching compilation can introduce arbitrary latency between the SP
  // compile request and fulfillment, which doesn't work with strictly linear
  // tiering.
  if (CanCompileWithBaseline(isolate_, function->shared()) &&
      function->ActiveTierIsIgnition()) {
    if (v8_flags.baseline_batch_compilation) {
      isolate_->baseline_batch_compiler()->EnqueueFunction(function);
    } else {
      IsCompiledScope is_compiled_scope(
          function->shared().is_compiled_scope(isolate_));
      Compiler::CompileBaseline(isolate_, function, Compiler::CLEAR_EXCEPTION,
                                &is_compiled_scope);
    }
    function->shared().set_sparkplug_compiled(true);
  }

  // We only tier up beyond sparkplug if we already had a feedback vector.
  if (!had_feedback_vector) {
    // The interrupt budget has already been set by
    // JSFunction::CreateAndAttachFeedbackVector.
    return;
  }

  // Don't tier up if Turbofan is disabled.
  // TODO(jgruber): Update this for a multi-tier world.
  if (V8_UNLIKELY(!isolate_->use_optimizer())) {
    function->SetInterruptBudget(isolate_);
    return;
  }

  // --- We've decided to proceed for now. ---

  DisallowGarbageCollection no_gc;
  OnInterruptTickScope scope(this);
  JSFunction function_obj = *function;

  function_obj.feedback_vector().SaturatingIncrementProfilerTicks();

  MaybeOptimizeFrame(function_obj, code_kind);

  // Make sure to set the interrupt budget after maybe starting an optimization,
  // so that the interrupt budget size takes into account tiering state.
  DCHECK(had_feedback_vector);
  function->SetInterruptBudget(isolate_);
}

}  // namespace internal
}  // namespace v8