1 /*
2 * Copyright (c) 2010, 2025, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
24
25 #include "cds/aotLinkedClassBulkLoader.hpp"
26 #include "code/scopeDesc.hpp"
27 #include "compiler/compilationPolicy.hpp"
28 #include "compiler/compileBroker.hpp"
29 #include "compiler/compilerDefinitions.inline.hpp"
30 #include "compiler/compilerOracle.hpp"
31 #include "memory/resourceArea.hpp"
32 #include "oops/method.inline.hpp"
33 #include "oops/methodData.hpp"
34 #include "oops/oop.inline.hpp"
35 #include "oops/trainingData.hpp"
36 #include "prims/jvmtiExport.hpp"
37 #include "runtime/arguments.hpp"
38 #include "runtime/deoptimization.hpp"
39 #include "runtime/frame.hpp"
40 #include "runtime/frame.inline.hpp"
41 #include "runtime/globals_extension.hpp"
42 #include "runtime/handles.inline.hpp"
43 #include "runtime/safepoint.hpp"
44 #include "runtime/safepointVerifiers.hpp"
45 #ifdef COMPILER1
46 #include "c1/c1_Compiler.hpp"
47 #endif
48 #ifdef COMPILER2
49 #include "opto/c2compiler.hpp"
50 #endif
51 #if INCLUDE_JVMCI
52 #include "jvmci/jvmci.hpp"
53 #endif
54
55 int64_t CompilationPolicy::_start_time = 0;
56 int CompilationPolicy::_c1_count = 0;
57 int CompilationPolicy::_c2_count = 0;
58 double CompilationPolicy::_increase_threshold_at_ratio = 0;
59
60 CompilationPolicy::TrainingReplayQueue CompilationPolicy::_training_replay_queue;
61
62 void compilationPolicy_init() {
63 CompilationPolicy::initialize();
64 }
65
66 int CompilationPolicy::compiler_count(CompLevel comp_level) {
67 if (is_c1_compile(comp_level)) {
68 return c1_count();
69 } else if (is_c2_compile(comp_level)) {
70 return c2_count();
71 }
72 return 0;
73 }
74
75 // Returns true if m must be compiled before executing it
76 // This is intended to force compiles for methods (usually for
77 // debugging) that would otherwise be interpreted for some reason.
78 bool CompilationPolicy::must_be_compiled(const methodHandle& m, int comp_level) {
79 // Don't allow Xcomp to cause compiles in replay mode
80 if (ReplayCompiles) return false;
81
82 if (m->has_compiled_code()) return false; // already compiled
83 if (!can_be_compiled(m, comp_level)) return false;
84
85 return !UseInterpreter || // must compile all methods
86 (AlwaysCompileLoopMethods && m->has_loops() && CompileBroker::should_compile_new_jobs()); // eagerly compile loop methods
87 }
88
89 void CompilationPolicy::maybe_compile_early(const methodHandle& m, TRAPS) {
90 if (m->method_holder()->is_not_initialized()) {
91 // 'is_not_initialized' means not only '!is_initialized', but also that
92 // initialization has not been started yet ('!being_initialized')
93 // Do not force compilation of methods in uninitialized classes.
94 return;
95 }
96 if (!m->is_native() && MethodTrainingData::have_data()) {
97 MethodTrainingData* mtd = MethodTrainingData::find_fast(m);
98 if (mtd == nullptr) {
99 return; // there is no training data recorded for m
100 }
101 CompLevel cur_level = static_cast<CompLevel>(m->highest_comp_level());
102 CompLevel next_level = trained_transition(m, cur_level, mtd, THREAD);
103 if (next_level != cur_level && can_be_compiled(m, next_level) && !CompileBroker::compilation_is_in_queue(m)) {
104 if (PrintTieredEvents) {
105 print_event(FORCE_COMPILE, m(), m(), InvocationEntryBci, next_level);
106 }
107 CompileBroker::compile_method(m, InvocationEntryBci, next_level, 0, CompileTask::Reason_MustBeCompiled, THREAD);
108 if (HAS_PENDING_EXCEPTION) {
109 CLEAR_PENDING_EXCEPTION;
110 }
111 }
112 }
113 }
114
115 void CompilationPolicy::compile_if_required(const methodHandle& m, TRAPS) {
116 if (!THREAD->can_call_java() || THREAD->is_Compiler_thread()) {
117 // don't force compilation, resolve was on behalf of compiler
118 return;
119 }
120 if (m->method_holder()->is_not_initialized()) {
121 // 'is_not_initialized' means not only '!is_initialized', but also that
122 // initialization has not been started yet ('!being_initialized')
123 // Do not force compilation of methods in uninitialized classes.
124 // Note that doing this would throw an assert later,
125 // in CompileBroker::compile_method.
126 // We sometimes use the link resolver to do reflective lookups
127 // even before classes are initialized.
128 return;
129 }
130
131 if (must_be_compiled(m)) {
132 // This path is unusual, mostly used by the '-Xcomp' stress test mode.
133 CompLevel level = initial_compile_level(m);
134 if (PrintTieredEvents) {
135 print_event(FORCE_COMPILE, m(), m(), InvocationEntryBci, level);
136 }
137 CompileBroker::compile_method(m, InvocationEntryBci, level, 0, CompileTask::Reason_MustBeCompiled, THREAD);
138 }
139 }
140
141 void CompilationPolicy::replay_training_at_init_impl(InstanceKlass* klass, JavaThread* current) {
142 if (!klass->has_init_deps_processed()) {
143 ResourceMark rm;
144 log_debug(training)("Replay training: %s", klass->external_name());
145
146 KlassTrainingData* ktd = KlassTrainingData::find(klass);
147 if (ktd != nullptr) {
148 guarantee(ktd->has_holder(), "");
149 ktd->notice_fully_initialized(); // sets klass->has_init_deps_processed bit
150 assert(klass->has_init_deps_processed(), "");
151 if (AOTCompileEagerly) {
152 ktd->iterate_comp_deps([&](CompileTrainingData* ctd) {
153 if (ctd->init_deps_left_acquire() == 0) {
154 MethodTrainingData* mtd = ctd->method();
155 if (mtd->has_holder()) {
156 const methodHandle mh(current, const_cast<Method*>(mtd->holder()));
157 CompilationPolicy::maybe_compile_early(mh, current);
158 }
159 }
160 });
161 }
162 }
163 }
164 }
165
166 void CompilationPolicy::replay_training_at_init(InstanceKlass* klass, JavaThread* current) {
167 assert(klass->is_initialized(), "");
168 if (TrainingData::have_data() && klass->in_aot_cache()) {
169 _training_replay_queue.push(klass, TrainingReplayQueue_lock, current);
170 }
171 }
172
173 // For TrainingReplayQueue
174 template<>
175 void CompilationPolicyUtils::Queue<InstanceKlass>::print_on(outputStream* st) {
176 int pos = 0;
177 for (QueueNode* cur = _head; cur != nullptr; cur = cur->next()) {
178 ResourceMark rm;
179 InstanceKlass* ik = cur->value();
180 st->print_cr("%3d: " INTPTR_FORMAT " %s", ++pos, p2i(ik), ik->external_name());
181 }
182 }
183
184 void CompilationPolicy::replay_training_at_init_loop(JavaThread* current) {
185 while (!CompileBroker::is_compilation_disabled_forever()) {
186 InstanceKlass* ik = _training_replay_queue.pop(TrainingReplayQueue_lock, current);
187 if (ik != nullptr) {
188 replay_training_at_init_impl(ik, current);
189 }
190 }
191 }
192
193 static inline CompLevel adjust_level_for_compilability_query(CompLevel comp_level) {
194 if (comp_level == CompLevel_any) {
195 if (CompilerConfig::is_c1_only()) {
196 comp_level = CompLevel_simple;
197 } else if (CompilerConfig::is_c2_or_jvmci_compiler_only()) {
198 comp_level = CompLevel_full_optimization;
199 }
200 }
201 return comp_level;
202 }
203
204 // Returns true if m is allowed to be compiled
205 bool CompilationPolicy::can_be_compiled(const methodHandle& m, int comp_level) {
206 // allow any levels for WhiteBox
207 assert(WhiteBoxAPI || comp_level == CompLevel_any || is_compile(comp_level), "illegal compilation level %d", comp_level);
208
209 if (m->is_abstract()) return false;
210 if (DontCompileHugeMethods && m->code_size() > HugeMethodLimit) return false;
211
212 // Math intrinsics should never be compiled as this can lead to
213 // monotonicity problems because the interpreter will prefer the
214 // compiled code to the intrinsic version. This can't happen in
215 // production because the invocation counter can't be incremented
216 // but we shouldn't expose the system to this problem in testing
217 // modes.
218 if (!AbstractInterpreter::can_be_compiled(m)) {
219 return false;
220 }
221 comp_level = adjust_level_for_compilability_query((CompLevel) comp_level);
222 if (comp_level == CompLevel_any || is_compile(comp_level)) {
223 return !m->is_not_compilable(comp_level);
224 }
225 return false;
226 }
227
228 // Returns true if m is allowed to be osr compiled
229 bool CompilationPolicy::can_be_osr_compiled(const methodHandle& m, int comp_level) {
230 bool result = false;
231 comp_level = adjust_level_for_compilability_query((CompLevel) comp_level);
232 if (comp_level == CompLevel_any || is_compile(comp_level)) {
233 result = !m->is_not_osr_compilable(comp_level);
234 }
235 return (result && can_be_compiled(m, comp_level));
236 }
237
238 bool CompilationPolicy::is_compilation_enabled() {
239 // NOTE: CompileBroker::should_compile_new_jobs() checks for UseCompiler
240 return CompileBroker::should_compile_new_jobs();
241 }
242
243 CompileTask* CompilationPolicy::select_task_helper(CompileQueue* compile_queue) {
244 // Remove unloaded methods from the queue
245 for (CompileTask* task = compile_queue->first(); task != nullptr; ) {
246 CompileTask* next = task->next();
247 if (task->is_unloaded()) {
248 compile_queue->remove_and_mark_stale(task);
249 }
250 task = next;
251 }
252 #if INCLUDE_JVMCI
253 if (UseJVMCICompiler && !BackgroundCompilation) {
254 /*
255 * In blocking compilation mode, the CompileBroker will make
256 * compilations submitted by a JVMCI compiler thread non-blocking. These
257 * compilations should be scheduled after all blocking compilations
258 * to service non-compiler related compilations sooner and reduce the
259 * chance of such compilations timing out.
260 */
261 for (CompileTask* task = compile_queue->first(); task != nullptr; task = task->next()) {
262 if (task->is_blocking()) {
263 return task;
264 }
265 }
266 }
267 #endif
268 return compile_queue->first();
269 }
270
271 // Simple methods are as good being compiled with C1 as C2.
272 // Determine if a given method is such a case.
273 bool CompilationPolicy::is_trivial(const methodHandle& method) {
274 if (method->is_accessor() ||
275 method->is_constant_getter()) {
276 return true;
277 }
278 return false;
279 }
280
281 bool CompilationPolicy::force_comp_at_level_simple(const methodHandle& method) {
282 if (CompilationModeFlag::quick_internal()) {
283 #if INCLUDE_JVMCI
284 if (UseJVMCICompiler) {
285 AbstractCompiler* comp = CompileBroker::compiler(CompLevel_full_optimization);
286 if (comp != nullptr && comp->is_jvmci() && ((JVMCICompiler*) comp)->force_comp_at_level_simple(method)) {
287 return true;
288 }
289 }
290 #endif
291 }
292 return false;
293 }
294
295 CompLevel CompilationPolicy::comp_level(Method* method) {
296 nmethod *nm = method->code();
297 if (nm != nullptr && nm->is_in_use()) {
298 return (CompLevel)nm->comp_level();
299 }
300 return CompLevel_none;
301 }
302
303 // Call and loop predicates determine whether a transition to a higher
304 // compilation level should be performed (pointers to predicate functions
305 // are passed to common()).
306 // Tier?LoadFeedback is basically a coefficient that determines of
307 // how many methods per compiler thread can be in the queue before
308 // the threshold values double.
309 class LoopPredicate : AllStatic {
310 public:
311 static bool apply_scaled(const methodHandle& method, CompLevel cur_level, int i, int b, double scale) {
312 double threshold_scaling;
313 if (CompilerOracle::has_option_value(method, CompileCommandEnum::CompileThresholdScaling, threshold_scaling)) {
314 scale *= threshold_scaling;
315 }
316 switch(cur_level) {
317 case CompLevel_none:
318 case CompLevel_limited_profile:
319 return b >= Tier3BackEdgeThreshold * scale;
320 case CompLevel_full_profile:
321 return b >= Tier4BackEdgeThreshold * scale;
322 default:
323 return true;
324 }
325 }
326
327 static bool apply(const methodHandle& method, CompLevel cur_level, int i, int b) {
328 double k = 1;
329 switch(cur_level) {
330 case CompLevel_none:
331 // Fall through
332 case CompLevel_limited_profile: {
333 k = CompilationPolicy::threshold_scale(CompLevel_full_profile, Tier3LoadFeedback);
334 break;
335 }
336 case CompLevel_full_profile: {
337 k = CompilationPolicy::threshold_scale(CompLevel_full_optimization, Tier4LoadFeedback);
338 break;
339 }
340 default:
341 return true;
342 }
343 return apply_scaled(method, cur_level, i, b, k);
344 }
345 };
346
347 class CallPredicate : AllStatic {
348 public:
349 static bool apply_scaled(const methodHandle& method, CompLevel cur_level, int i, int b, double scale) {
350 double threshold_scaling;
351 if (CompilerOracle::has_option_value(method, CompileCommandEnum::CompileThresholdScaling, threshold_scaling)) {
352 scale *= threshold_scaling;
353 }
354 switch(cur_level) {
355 case CompLevel_none:
356 case CompLevel_limited_profile:
357 return (i >= Tier3InvocationThreshold * scale) ||
358 (i >= Tier3MinInvocationThreshold * scale && i + b >= Tier3CompileThreshold * scale);
359 case CompLevel_full_profile:
360 return (i >= Tier4InvocationThreshold * scale) ||
361 (i >= Tier4MinInvocationThreshold * scale && i + b >= Tier4CompileThreshold * scale);
362 default:
363 return true;
364 }
365 }
366
367 static bool apply(const methodHandle& method, CompLevel cur_level, int i, int b) {
368 double k = 1;
369 switch(cur_level) {
370 case CompLevel_none:
371 case CompLevel_limited_profile: {
372 k = CompilationPolicy::threshold_scale(CompLevel_full_profile, Tier3LoadFeedback);
373 break;
374 }
375 case CompLevel_full_profile: {
376 k = CompilationPolicy::threshold_scale(CompLevel_full_optimization, Tier4LoadFeedback);
377 break;
378 }
379 default:
380 return true;
381 }
382 return apply_scaled(method, cur_level, i, b, k);
383 }
384 };
385
386 double CompilationPolicy::threshold_scale(CompLevel level, int feedback_k) {
387 int comp_count = compiler_count(level);
388 if (comp_count > 0 && feedback_k > 0) {
389 double queue_size = CompileBroker::queue_size(level);
390 double k = (double)queue_size / ((double)feedback_k * (double)comp_count) + 1;
391
392 // Increase C1 compile threshold when the code cache is filled more
393 // than specified by IncreaseFirstTierCompileThresholdAt percentage.
394 // The main intention is to keep enough free space for C2 compiled code
395 // to achieve peak performance if the code cache is under stress.
396 if (CompilerConfig::is_tiered() && !CompilationModeFlag::disable_intermediate() && is_c1_compile(level)) {
397 double current_reverse_free_ratio = CodeCache::reverse_free_ratio();
398 if (current_reverse_free_ratio > _increase_threshold_at_ratio) {
399 k *= exp(current_reverse_free_ratio - _increase_threshold_at_ratio);
400 }
401 }
402 return k;
403 }
404 return 1;
405 }
406
407 void CompilationPolicy::print_counters_on(outputStream* st, const char* prefix, Method* m) {
408 int invocation_count = m->invocation_count();
409 int backedge_count = m->backedge_count();
410 MethodData* mdh = m->method_data();
411 int mdo_invocations = 0, mdo_backedges = 0;
412 int mdo_invocations_start = 0, mdo_backedges_start = 0;
413 if (mdh != nullptr) {
414 mdo_invocations = mdh->invocation_count();
415 mdo_backedges = mdh->backedge_count();
416 mdo_invocations_start = mdh->invocation_count_start();
417 mdo_backedges_start = mdh->backedge_count_start();
418 }
419 st->print(" %stotal=%d,%d %smdo=%d(%d),%d(%d)", prefix,
420 invocation_count, backedge_count, prefix,
421 mdo_invocations, mdo_invocations_start,
422 mdo_backedges, mdo_backedges_start);
423 st->print(" %smax levels=%d,%d", prefix, m->highest_comp_level(), m->highest_osr_comp_level());
424 }
425
426 void CompilationPolicy::print_training_data_on(outputStream* st, const char* prefix, Method* method) {
427 methodHandle m(Thread::current(), method);
428 st->print(" %smtd: ", prefix);
429 MethodTrainingData* mtd = MethodTrainingData::find(m);
430 if (mtd == nullptr) {
431 st->print("null");
432 } else {
433 MethodData* md = mtd->final_profile();
434 st->print("mdo=");
435 if (md == nullptr) {
436 st->print("null");
437 } else {
438 int mdo_invocations = md->invocation_count();
439 int mdo_backedges = md->backedge_count();
440 int mdo_invocations_start = md->invocation_count_start();
441 int mdo_backedges_start = md->backedge_count_start();
442 st->print("%d(%d), %d(%d)", mdo_invocations, mdo_invocations_start, mdo_backedges, mdo_backedges_start);
443 }
444 CompileTrainingData* ctd = mtd->last_toplevel_compile(CompLevel_full_optimization);
445 st->print(", deps=");
446 if (ctd == nullptr) {
447 st->print("null");
448 } else {
449 st->print("%d", ctd->init_deps_left_acquire());
450 }
451 }
452 }
453
454 // Print an event.
455 void CompilationPolicy::print_event_on(outputStream *st, EventType type, Method* m, Method* im, int bci, CompLevel level) {
456 bool inlinee_event = m != im;
457
458 st->print("%lf: [", os::elapsedTime());
459
460 switch(type) {
461 case CALL:
462 st->print("call");
463 break;
464 case LOOP:
465 st->print("loop");
466 break;
467 case COMPILE:
468 st->print("compile");
469 break;
470 case FORCE_COMPILE:
471 st->print("force-compile");
472 break;
473 case REMOVE_FROM_QUEUE:
474 st->print("remove-from-queue");
475 break;
476 case UPDATE_IN_QUEUE:
477 st->print("update-in-queue");
478 break;
479 case REPROFILE:
480 st->print("reprofile");
481 break;
482 case MAKE_NOT_ENTRANT:
483 st->print("make-not-entrant");
484 break;
485 default:
486 st->print("unknown");
487 }
488
489 st->print(" level=%d ", level);
490
491 ResourceMark rm;
492 char *method_name = m->name_and_sig_as_C_string();
493 st->print("[%s", method_name);
494 if (inlinee_event) {
495 char *inlinee_name = im->name_and_sig_as_C_string();
496 st->print(" [%s]] ", inlinee_name);
497 }
498 else st->print("] ");
499 st->print("@%d queues=%d,%d", bci, CompileBroker::queue_size(CompLevel_full_profile),
500 CompileBroker::queue_size(CompLevel_full_optimization));
501
502 st->print(" rate=");
503 if (m->prev_time() == 0) st->print("n/a");
504 else st->print("%f", m->rate());
505
506 st->print(" k=%.2lf,%.2lf", threshold_scale(CompLevel_full_profile, Tier3LoadFeedback),
507 threshold_scale(CompLevel_full_optimization, Tier4LoadFeedback));
508
509 if (type != COMPILE) {
510 print_counters_on(st, "", m);
511 if (inlinee_event) {
512 print_counters_on(st, "inlinee ", im);
513 }
514 st->print(" compilable=");
515 bool need_comma = false;
516 if (!m->is_not_compilable(CompLevel_full_profile)) {
517 st->print("c1");
518 need_comma = true;
519 }
520 if (!m->is_not_osr_compilable(CompLevel_full_profile)) {
521 if (need_comma) st->print(",");
522 st->print("c1-osr");
523 need_comma = true;
524 }
525 if (!m->is_not_compilable(CompLevel_full_optimization)) {
526 if (need_comma) st->print(",");
527 st->print("c2");
528 need_comma = true;
529 }
530 if (!m->is_not_osr_compilable(CompLevel_full_optimization)) {
531 if (need_comma) st->print(",");
532 st->print("c2-osr");
533 }
534 st->print(" status=");
535 if (m->queued_for_compilation()) {
536 st->print("in-queue");
537 } else st->print("idle");
538
539 print_training_data_on(st, "", m);
540 if (inlinee_event) {
541 print_training_data_on(st, "inlinee ", im);
542 }
543 }
544 st->print_cr("]");
545
546 }
547
548 void CompilationPolicy::print_event(EventType type, Method* m, Method* im, int bci, CompLevel level) {
549 stringStream s;
550 print_event_on(&s, type, m, im, bci, level);
551 ResourceMark rm;
552 tty->print("%s", s.as_string());
553 }
554
555 void CompilationPolicy::initialize() {
556 if (!CompilerConfig::is_interpreter_only()) {
557 int count = CICompilerCount;
558 bool c1_only = CompilerConfig::is_c1_only();
559 bool c2_only = CompilerConfig::is_c2_or_jvmci_compiler_only();
560 int min_count = (c1_only || c2_only) ? 1 : 2;
561
562 #ifdef _LP64
563 // Turn on ergonomic compiler count selection
564 if (FLAG_IS_DEFAULT(CICompilerCountPerCPU) && FLAG_IS_DEFAULT(CICompilerCount)) {
565 FLAG_SET_DEFAULT(CICompilerCountPerCPU, true);
566 }
567 if (CICompilerCountPerCPU) {
568 // Simple log n seems to grow too slowly for tiered, try something faster: log n * log log n
569 int log_cpu = log2i(os::active_processor_count());
570 int loglog_cpu = log2i(MAX2(log_cpu, 1));
571 count = MAX2(log_cpu * loglog_cpu * 3 / 2, min_count);
572 // Make sure there is enough space in the code cache to hold all the compiler buffers
573 size_t c1_size = 0;
574 #ifdef COMPILER1
575 c1_size = Compiler::code_buffer_size();
576 #endif
577 size_t c2_size = 0;
578 #ifdef COMPILER2
579 c2_size = C2Compiler::initial_code_buffer_size();
580 #endif
581 size_t buffer_size = 0;
582 if (c1_only) {
583 buffer_size = c1_size;
584 } else if (c2_only) {
585 buffer_size = c2_size;
586 } else {
587 buffer_size = c1_size / 3 + 2 * c2_size / 3;
588 }
589 size_t max_count = (NonNMethodCodeHeapSize - (CodeCacheMinimumUseSpace DEBUG_ONLY(* 3))) / buffer_size;
590 if ((size_t)count > max_count) {
591 // Lower the compiler count such that all buffers fit into the code cache
592 count = MAX2((int)max_count, min_count);
593 }
594 FLAG_SET_ERGO(CICompilerCount, count);
595 }
596 #else
597 // On 32-bit systems, the number of compiler threads is limited to 3.
598 // On these systems, the virtual address space available to the JVM
599 // is usually limited to 2-4 GB (the exact value depends on the platform).
600 // As the compilers (especially C2) can consume a large amount of
601 // memory, scaling the number of compiler threads with the number of
602 // available cores can result in the exhaustion of the address space
603 /// available to the VM and thus cause the VM to crash.
604 if (FLAG_IS_DEFAULT(CICompilerCount)) {
605 count = 3;
606 FLAG_SET_ERGO(CICompilerCount, count);
607 }
608 #endif // _LP64
609
610 if (c1_only) {
611 // No C2 compiler threads are needed
612 set_c1_count(count);
613 } else if (c2_only) {
614 // No C1 compiler threads are needed
615 set_c2_count(count);
616 } else {
617 #if INCLUDE_JVMCI
618 if (UseJVMCICompiler && UseJVMCINativeLibrary) {
619 int libjvmci_count = MAX2((int) (count * JVMCINativeLibraryThreadFraction), 1);
620 int c1_count = MAX2(count - libjvmci_count, 1);
621 set_c2_count(libjvmci_count);
622 set_c1_count(c1_count);
623 } else
624 #endif
625 {
626 set_c1_count(MAX2(count / 3, 1));
627 set_c2_count(MAX2(count - c1_count(), 1));
628 }
629 }
630 assert(count == c1_count() + c2_count(), "inconsistent compiler thread count");
631 set_increase_threshold_at_ratio();
632 } else {
633 // Interpreter mode creates no compilers
634 FLAG_SET_ERGO(CICompilerCount, 0);
635 }
636 set_start_time(nanos_to_millis(os::javaTimeNanos()));
637 }
638
639
640 #ifdef ASSERT
641 bool CompilationPolicy::verify_level(CompLevel level) {
642 if (TieredCompilation && level > TieredStopAtLevel) {
643 return false;
644 }
645 // Check if there is a compiler to process the requested level
646 if (!CompilerConfig::is_c1_enabled() && is_c1_compile(level)) {
647 return false;
648 }
649 if (!CompilerConfig::is_c2_or_jvmci_compiler_enabled() && is_c2_compile(level)) {
650 return false;
651 }
652
653 // Interpreter level is always valid.
654 if (level == CompLevel_none) {
655 return true;
656 }
657 if (CompilationModeFlag::normal()) {
658 return true;
659 } else if (CompilationModeFlag::quick_only()) {
660 return level == CompLevel_simple;
661 } else if (CompilationModeFlag::high_only()) {
662 return level == CompLevel_full_optimization;
663 } else if (CompilationModeFlag::high_only_quick_internal()) {
664 return level == CompLevel_full_optimization || level == CompLevel_simple;
665 }
666 return false;
667 }
668 #endif
669
670
671 CompLevel CompilationPolicy::highest_compile_level() {
672 CompLevel level = CompLevel_none;
673 // Setup the maximum level available for the current compiler configuration.
674 if (!CompilerConfig::is_interpreter_only()) {
675 if (CompilerConfig::is_c2_or_jvmci_compiler_enabled()) {
676 level = CompLevel_full_optimization;
677 } else if (CompilerConfig::is_c1_enabled()) {
678 if (CompilerConfig::is_c1_simple_only()) {
679 level = CompLevel_simple;
680 } else {
681 level = CompLevel_full_profile;
682 }
683 }
684 }
685 // Clamp the maximum level with TieredStopAtLevel.
686 if (TieredCompilation) {
687 level = MIN2(level, (CompLevel) TieredStopAtLevel);
688 }
689
690 // Fix it up if after the clamping it has become invalid.
691 // Bring it monotonically down depending on the next available level for
692 // the compilation mode.
693 if (!CompilationModeFlag::normal()) {
694 // a) quick_only - levels 2,3,4 are invalid; levels -1,0,1 are valid;
695 // b) high_only - levels 1,2,3 are invalid; levels -1,0,4 are valid;
696 // c) high_only_quick_internal - levels 2,3 are invalid; levels -1,0,1,4 are valid.
697 if (CompilationModeFlag::quick_only()) {
698 if (level == CompLevel_limited_profile || level == CompLevel_full_profile || level == CompLevel_full_optimization) {
699 level = CompLevel_simple;
700 }
701 } else if (CompilationModeFlag::high_only()) {
702 if (level == CompLevel_simple || level == CompLevel_limited_profile || level == CompLevel_full_profile) {
703 level = CompLevel_none;
704 }
705 } else if (CompilationModeFlag::high_only_quick_internal()) {
706 if (level == CompLevel_limited_profile || level == CompLevel_full_profile) {
707 level = CompLevel_simple;
708 }
709 }
710 }
711
712 assert(verify_level(level), "Invalid highest compilation level: %d", level);
713 return level;
714 }
715
716 CompLevel CompilationPolicy::limit_level(CompLevel level) {
717 level = MIN2(level, highest_compile_level());
718 assert(verify_level(level), "Invalid compilation level: %d", level);
719 return level;
720 }
721
722 CompLevel CompilationPolicy::initial_compile_level(const methodHandle& method) {
723 CompLevel level = CompLevel_any;
724 if (CompilationModeFlag::normal()) {
725 level = CompLevel_full_profile;
726 } else if (CompilationModeFlag::quick_only()) {
727 level = CompLevel_simple;
728 } else if (CompilationModeFlag::high_only()) {
729 level = CompLevel_full_optimization;
730 } else if (CompilationModeFlag::high_only_quick_internal()) {
731 if (force_comp_at_level_simple(method)) {
732 level = CompLevel_simple;
733 } else {
734 level = CompLevel_full_optimization;
735 }
736 }
737 assert(level != CompLevel_any, "Unhandled compilation mode");
738 return limit_level(level);
739 }
740
741 // Set carry flags on the counters if necessary
742 void CompilationPolicy::handle_counter_overflow(const methodHandle& method) {
743 MethodCounters *mcs = method->method_counters();
744 if (mcs != nullptr) {
745 mcs->invocation_counter()->set_carry_on_overflow();
746 mcs->backedge_counter()->set_carry_on_overflow();
747 }
748 MethodData* mdo = method->method_data();
749 if (mdo != nullptr) {
750 mdo->invocation_counter()->set_carry_on_overflow();
751 mdo->backedge_counter()->set_carry_on_overflow();
752 }
753 }
754
755 // Called with the queue locked and with at least one element
756 CompileTask* CompilationPolicy::select_task(CompileQueue* compile_queue, JavaThread* THREAD) {
757 CompileTask *max_blocking_task = nullptr;
758 CompileTask *max_task = nullptr;
759 Method* max_method = nullptr;
760
761 int64_t t = nanos_to_millis(os::javaTimeNanos());
762 // Iterate through the queue and find a method with a maximum rate.
763 for (CompileTask* task = compile_queue->first(); task != nullptr;) {
764 CompileTask* next_task = task->next();
765 // If a method was unloaded or has been stale for some time, remove it from the queue.
766 // Blocking tasks and tasks submitted from whitebox API don't become stale
767 if (task->is_unloaded()) {
768 compile_queue->remove_and_mark_stale(task);
769 task = next_task;
770 continue;
771 }
772 if (task->is_blocking() && task->compile_reason() == CompileTask::Reason_Whitebox) {
773 // CTW tasks, submitted as blocking Whitebox requests, do not participate in rate
774 // selection and/or any level adjustments. Just return them in order.
775 return task;
776 }
777 Method* method = task->method();
778 methodHandle mh(THREAD, method);
779 if (task->can_become_stale() && is_stale(t, TieredCompileTaskTimeout, mh) && !is_old(mh)) {
780 if (PrintTieredEvents) {
781 print_event(REMOVE_FROM_QUEUE, method, method, task->osr_bci(), (CompLevel) task->comp_level());
782 }
783 method->clear_queued_for_compilation();
784 compile_queue->remove_and_mark_stale(task);
785 task = next_task;
786 continue;
787 }
788 update_rate(t, mh);
789 if (max_task == nullptr || compare_methods(method, max_method)) {
790 // Select a method with the highest rate
791 max_task = task;
792 max_method = method;
793 }
794
795 if (task->is_blocking()) {
796 if (max_blocking_task == nullptr || compare_methods(method, max_blocking_task->method())) {
797 max_blocking_task = task;
798 }
799 }
800
801 task = next_task;
802 }
803
804 if (max_blocking_task != nullptr) {
805 // In blocking compilation mode, the CompileBroker will make
806 // compilations submitted by a JVMCI compiler thread non-blocking. These
807 // compilations should be scheduled after all blocking compilations
808 // to service non-compiler related compilations sooner and reduce the
809 // chance of such compilations timing out.
810 max_task = max_blocking_task;
811 max_method = max_task->method();
812 }
813
814 methodHandle max_method_h(THREAD, max_method);
815
816 if (max_task != nullptr && max_task->comp_level() == CompLevel_full_profile && TieredStopAtLevel > CompLevel_full_profile &&
817 max_method != nullptr && is_method_profiled(max_method_h) && !Arguments::is_compiler_only()) {
818 max_task->set_comp_level(CompLevel_limited_profile);
819
820 if (CompileBroker::compilation_is_complete(max_method_h, max_task->osr_bci(), CompLevel_limited_profile)) {
821 if (PrintTieredEvents) {
822 print_event(REMOVE_FROM_QUEUE, max_method, max_method, max_task->osr_bci(), (CompLevel)max_task->comp_level());
823 }
824 compile_queue->remove_and_mark_stale(max_task);
825 max_method->clear_queued_for_compilation();
826 return nullptr;
827 }
828
829 if (PrintTieredEvents) {
830 print_event(UPDATE_IN_QUEUE, max_method, max_method, max_task->osr_bci(), (CompLevel)max_task->comp_level());
831 }
832 }
833 return max_task;
834 }
835
836 void CompilationPolicy::reprofile(ScopeDesc* trap_scope, bool is_osr) {
837 for (ScopeDesc* sd = trap_scope;; sd = sd->sender()) {
838 if (PrintTieredEvents) {
839 print_event(REPROFILE, sd->method(), sd->method(), InvocationEntryBci, CompLevel_none);
840 }
841 MethodData* mdo = sd->method()->method_data();
842 if (mdo != nullptr) {
843 mdo->reset_start_counters();
844 }
845 if (sd->is_top()) break;
846 }
847 }
848
849 nmethod* CompilationPolicy::event(const methodHandle& method, const methodHandle& inlinee,
850 int branch_bci, int bci, CompLevel comp_level, nmethod* nm, TRAPS) {
851 if (PrintTieredEvents) {
852 print_event(bci == InvocationEntryBci ? CALL : LOOP, method(), inlinee(), bci, comp_level);
853 }
854
855 if (comp_level == CompLevel_none &&
856 JvmtiExport::can_post_interpreter_events() &&
857 THREAD->is_interp_only_mode()) {
858 return nullptr;
859 }
860 if (ReplayCompiles) {
861 // Don't trigger other compiles in testing mode
862 return nullptr;
863 }
864
865 handle_counter_overflow(method);
866 if (method() != inlinee()) {
867 handle_counter_overflow(inlinee);
868 }
869
870 if (bci == InvocationEntryBci) {
871 method_invocation_event(method, inlinee, comp_level, nm, THREAD);
872 } else {
873 // method == inlinee if the event originated in the main method
874 method_back_branch_event(method, inlinee, bci, comp_level, nm, THREAD);
875 // Check if event led to a higher level OSR compilation
876 CompLevel expected_comp_level = MIN2(CompLevel_full_optimization, static_cast<CompLevel>(comp_level + 1));
877 if (!CompilationModeFlag::disable_intermediate() && inlinee->is_not_osr_compilable(expected_comp_level)) {
878 // It's not possible to reach the expected level so fall back to simple.
879 expected_comp_level = CompLevel_simple;
880 }
881 CompLevel max_osr_level = static_cast<CompLevel>(inlinee->highest_osr_comp_level());
882 if (max_osr_level >= expected_comp_level) { // fast check to avoid locking in a typical scenario
883 nmethod* osr_nm = inlinee->lookup_osr_nmethod_for(bci, expected_comp_level, false);
884 assert(osr_nm == nullptr || osr_nm->comp_level() >= expected_comp_level, "lookup_osr_nmethod_for is broken");
885 if (osr_nm != nullptr && osr_nm->comp_level() != comp_level) {
886 // Perform OSR with new nmethod
887 return osr_nm;
888 }
889 }
890 }
891 return nullptr;
892 }
893
894 // Check if the method can be compiled, change level if necessary
895 void CompilationPolicy::compile(const methodHandle& mh, int bci, CompLevel level, TRAPS) {
896 assert(verify_level(level), "Invalid compilation level requested: %d", level);
897
898 if (level == CompLevel_none) {
899 if (mh->has_compiled_code()) {
900 // Happens when we switch to interpreter to profile.
901 MutexLocker ml(Compile_lock);
902 NoSafepointVerifier nsv;
903 if (mh->has_compiled_code()) {
904 mh->code()->make_not_used();
905 }
906 // Deoptimize immediately (we don't have to wait for a compile).
907 JavaThread* jt = THREAD;
908 RegisterMap map(jt,
909 RegisterMap::UpdateMap::skip,
910 RegisterMap::ProcessFrames::include,
911 RegisterMap::WalkContinuation::skip);
912 frame fr = jt->last_frame().sender(&map);
913 Deoptimization::deoptimize_frame(jt, fr.id());
914 }
915 return;
916 }
917
918 // Check if the method can be compiled. Additional logic for TieredCompilation:
919 // If it cannot be compiled with C1, continue profiling in the interpreter
920 // and then compile with C2 (the transition function will request that,
921 // see common() ). If the method cannot be compiled with C2 but still can with C1, compile it with
922 // pure C1.
923 if ((bci == InvocationEntryBci && !can_be_compiled(mh, level))) {
924 if (!CompilationModeFlag::disable_intermediate() &&
925 level == CompLevel_full_optimization && can_be_compiled(mh, CompLevel_simple)) {
926 compile(mh, bci, CompLevel_simple, THREAD);
927 }
928 return;
929 }
930 if ((bci != InvocationEntryBci && !can_be_osr_compiled(mh, level))) {
931 if (!CompilationModeFlag::disable_intermediate() &&
932 level == CompLevel_full_optimization && can_be_osr_compiled(mh, CompLevel_simple)) {
933 nmethod* osr_nm = mh->lookup_osr_nmethod_for(bci, CompLevel_simple, false);
934 if (osr_nm != nullptr && osr_nm->comp_level() > CompLevel_simple) {
935 // Invalidate the existing OSR nmethod so that a compile at CompLevel_simple is permitted.
936 osr_nm->make_not_entrant(nmethod::InvalidationReason::OSR_INVALIDATION_FOR_COMPILING_WITH_C1);
937 }
938 compile(mh, bci, CompLevel_simple, THREAD);
939 }
940 return;
941 }
942 if (bci != InvocationEntryBci && mh->is_not_osr_compilable(level)) {
943 return;
944 }
945 if (!CompileBroker::compilation_is_in_queue(mh)) {
946 if (PrintTieredEvents) {
947 print_event(COMPILE, mh(), mh(), bci, level);
948 }
949 int hot_count = (bci == InvocationEntryBci) ? mh->invocation_count() : mh->backedge_count();
950 update_rate(nanos_to_millis(os::javaTimeNanos()), mh);
951 CompileBroker::compile_method(mh, bci, level, hot_count, CompileTask::Reason_Tiered, THREAD);
952 }
953 }
954
955 // update_rate() is called from select_task() while holding a compile queue lock.
956 void CompilationPolicy::update_rate(int64_t t, const methodHandle& method) {
957 // Skip update if counters are absent.
958 // Can't allocate them since we are holding compile queue lock.
959 if (method->method_counters() == nullptr) return;
960
961 if (is_old(method)) {
962 // We don't remove old methods from the queue,
963 // so we can just zero the rate.
964 method->set_rate(0);
965 return;
966 }
967
968 // We don't update the rate if we've just came out of a safepoint.
969 // delta_s is the time since last safepoint in milliseconds.
970 int64_t delta_s = t - SafepointTracing::end_of_last_safepoint_ms();
971 int64_t delta_t = t - (method->prev_time() != 0 ? method->prev_time() : start_time()); // milliseconds since the last measurement
972 // How many events were there since the last time?
973 int event_count = method->invocation_count() + method->backedge_count();
974 int delta_e = event_count - method->prev_event_count();
975
976 // We should be running for at least 1ms.
977 if (delta_s >= TieredRateUpdateMinTime) {
978 // And we must've taken the previous point at least 1ms before.
979 if (delta_t >= TieredRateUpdateMinTime && delta_e > 0) {
980 method->set_prev_time(t);
981 method->set_prev_event_count(event_count);
982 method->set_rate((float)delta_e / (float)delta_t); // Rate is events per millisecond
983 } else {
984 if (delta_t > TieredRateUpdateMaxTime && delta_e == 0) {
985 // If nothing happened for 25ms, zero the rate. Don't modify prev values.
986 method->set_rate(0);
987 }
988 }
989 }
990 }
991
992 // Check if this method has been stale for a given number of milliseconds.
993 // See select_task().
994 bool CompilationPolicy::is_stale(int64_t t, int64_t timeout, const methodHandle& method) {
995 int64_t delta_s = t - SafepointTracing::end_of_last_safepoint_ms();
996 int64_t delta_t = t - method->prev_time();
997 if (delta_t > timeout && delta_s > timeout) {
998 int event_count = method->invocation_count() + method->backedge_count();
999 int delta_e = event_count - method->prev_event_count();
1000 // Return true if there were no events.
1001 return delta_e == 0;
1002 }
1003 return false;
1004 }
1005
1006 // We don't remove old methods from the compile queue even if they have
1007 // very low activity. See select_task().
1008 bool CompilationPolicy::is_old(const methodHandle& method) {
1009 int i = method->invocation_count();
1010 int b = method->backedge_count();
1011 double k = TieredOldPercentage / 100.0;
1012
1013 return CallPredicate::apply_scaled(method, CompLevel_none, i, b, k) || LoopPredicate::apply_scaled(method, CompLevel_none, i, b, k);
1014 }
1015
1016 double CompilationPolicy::weight(Method* method) {
1017 return (double)(method->rate() + 1) * (method->invocation_count() + 1) * (method->backedge_count() + 1);
1018 }
1019
1020 // Apply heuristics and return true if x should be compiled before y
1021 bool CompilationPolicy::compare_methods(Method* x, Method* y) {
1022 if (x->highest_comp_level() > y->highest_comp_level()) {
1023 // recompilation after deopt
1024 return true;
1025 } else
1026 if (x->highest_comp_level() == y->highest_comp_level()) {
1027 if (weight(x) > weight(y)) {
1028 return true;
1029 }
1030 }
1031 return false;
1032 }
1033
1034 // Is method profiled enough?
1035 bool CompilationPolicy::is_method_profiled(const methodHandle& method) {
1036 MethodData* mdo = method->method_data();
1037 if (mdo != nullptr) {
1038 int i = mdo->invocation_count_delta();
1039 int b = mdo->backedge_count_delta();
1040 return CallPredicate::apply_scaled(method, CompLevel_full_profile, i, b, 1);
1041 }
1042 return false;
1043 }
1044
1045
1046 // Determine is a method is mature.
1047 bool CompilationPolicy::is_mature(MethodData* mdo) {
1048 if (Arguments::is_compiler_only()) {
1049 // Always report profiles as immature with -Xcomp
1050 return false;
1051 }
1052 methodHandle mh(Thread::current(), mdo->method());
1053 if (mdo != nullptr) {
1054 int i = mdo->invocation_count();
1055 int b = mdo->backedge_count();
1056 double k = ProfileMaturityPercentage / 100.0;
1057 return CallPredicate::apply_scaled(mh, CompLevel_full_profile, i, b, k) || LoopPredicate::apply_scaled(mh, CompLevel_full_profile, i, b, k);
1058 }
1059 return false;
1060 }
1061
1062 // If a method is old enough and is still in the interpreter we would want to
1063 // start profiling without waiting for the compiled method to arrive.
1064 // We also take the load on compilers into the account.
1065 bool CompilationPolicy::should_create_mdo(const methodHandle& method, CompLevel cur_level) {
1066 if (cur_level != CompLevel_none || force_comp_at_level_simple(method) || CompilationModeFlag::quick_only() || !ProfileInterpreter) {
1067 return false;
1068 }
1069
1070 if (TrainingData::have_data()) {
1071 MethodTrainingData* mtd = MethodTrainingData::find_fast(method);
1072 if (mtd != nullptr && mtd->saw_level(CompLevel_full_optimization)) {
1073 return true;
1074 }
1075 }
1076
1077 if (is_old(method)) {
1078 return true;
1079 }
1080
1081 int i = method->invocation_count();
1082 int b = method->backedge_count();
1083 double k = Tier0ProfilingStartPercentage / 100.0;
1084
1085 // If the top level compiler is not keeping up, delay profiling.
1086 if (CompileBroker::queue_size(CompLevel_full_optimization) <= Tier0Delay * compiler_count(CompLevel_full_optimization)) {
1087 return CallPredicate::apply_scaled(method, CompLevel_none, i, b, k) || LoopPredicate::apply_scaled(method, CompLevel_none, i, b, k);
1088 }
1089 return false;
1090 }
1091
1092 // Inlining control: if we're compiling a profiled method with C1 and the callee
1093 // is known to have OSRed in a C2 version, don't inline it.
1094 bool CompilationPolicy::should_not_inline(ciEnv* env, ciMethod* callee) {
1095 CompLevel comp_level = (CompLevel)env->comp_level();
1096 if (comp_level == CompLevel_full_profile ||
1097 comp_level == CompLevel_limited_profile) {
1098 return callee->highest_osr_comp_level() == CompLevel_full_optimization;
1099 }
1100 return false;
1101 }
1102
1103 // Create MDO if necessary.
1104 void CompilationPolicy::create_mdo(const methodHandle& mh, JavaThread* THREAD) {
1105 if (mh->is_native() ||
1106 mh->is_abstract() ||
1107 mh->is_accessor() ||
1108 mh->is_constant_getter()) {
1109 return;
1110 }
1111 if (mh->method_data() == nullptr) {
1112 Method::build_profiling_method_data(mh, CHECK_AND_CLEAR);
1113 }
1114 if (ProfileInterpreter && THREAD->has_last_Java_frame()) {
1115 MethodData* mdo = mh->method_data();
1116 if (mdo != nullptr) {
1117 frame last_frame = THREAD->last_frame();
1118 if (last_frame.is_interpreted_frame() && mh == last_frame.interpreter_frame_method()) {
1119 int bci = last_frame.interpreter_frame_bci();
1120 address dp = mdo->bci_to_dp(bci);
1121 last_frame.interpreter_frame_set_mdp(dp);
1122 }
1123 }
1124 }
1125 }
1126
1127 CompLevel CompilationPolicy::trained_transition_from_none(const methodHandle& method, CompLevel cur_level, MethodTrainingData* mtd, JavaThread* THREAD) {
1128 precond(mtd != nullptr);
1129 precond(cur_level == CompLevel_none);
1130
1131 if (mtd->only_inlined() && !mtd->saw_level(CompLevel_full_optimization)) {
1132 return CompLevel_none;
1133 }
1134
1135 bool training_has_profile = (mtd->final_profile() != nullptr);
1136 if (mtd->saw_level(CompLevel_full_optimization) && !training_has_profile) {
1137 return CompLevel_full_profile;
1138 }
1139
1140 CompLevel highest_training_level = static_cast<CompLevel>(mtd->highest_top_level());
1141 switch (highest_training_level) {
1142 case CompLevel_limited_profile:
1143 case CompLevel_full_profile:
1144 return CompLevel_limited_profile;
1145 case CompLevel_simple:
1146 return CompLevel_simple;
1147 case CompLevel_none:
1148 return CompLevel_none;
1149 default:
1150 break;
1151 }
1152
1153 // Now handle the case of level 4.
1154 assert(highest_training_level == CompLevel_full_optimization, "Unexpected compilation level: %d", highest_training_level);
1155 if (!training_has_profile) {
1156 // The method was a part of a level 4 compile, but don't have a stored profile,
1157 // we need to profile it.
1158 return CompLevel_full_profile;
1159 }
1160 const bool deopt = (static_cast<CompLevel>(method->highest_comp_level()) == CompLevel_full_optimization);
1161 // If we deopted, then we reprofile
1162 if (deopt && !is_method_profiled(method)) {
1163 return CompLevel_full_profile;
1164 }
1165
1166 CompileTrainingData* ctd = mtd->last_toplevel_compile(CompLevel_full_optimization);
1167 assert(ctd != nullptr, "Should have CTD for CompLevel_full_optimization");
1168 // With SkipTier2IfPossible and all deps satisfied, go to level 4 immediately
1169 if (SkipTier2IfPossible && ctd->init_deps_left_acquire() == 0) {
1170 if (method->method_data() == nullptr) {
1171 create_mdo(method, THREAD);
1172 }
1173 return CompLevel_full_optimization;
1174 }
1175
1176 // Otherwise go to level 2
1177 return CompLevel_limited_profile;
1178 }
1179
1180
1181 CompLevel CompilationPolicy::trained_transition_from_limited_profile(const methodHandle& method, CompLevel cur_level, MethodTrainingData* mtd, JavaThread* THREAD) {
1182 precond(mtd != nullptr);
1183 precond(cur_level == CompLevel_limited_profile);
1184
1185 // One of the main reasons that we can get here is that we're waiting for the stored C2 code to become ready.
1186
1187 // But first, check if we have a saved profile
1188 bool training_has_profile = (mtd->final_profile() != nullptr);
1189 if (!training_has_profile) {
1190 return CompLevel_full_profile;
1191 }
1192
1193
1194 assert(training_has_profile, "Have to have a profile to be here");
1195 // Check if the method is ready
1196 CompileTrainingData* ctd = mtd->last_toplevel_compile(CompLevel_full_optimization);
1197 if (ctd != nullptr && ctd->init_deps_left_acquire() == 0) {
1198 if (method->method_data() == nullptr) {
1199 create_mdo(method, THREAD);
1200 }
1201 return CompLevel_full_optimization;
1202 }
1203
1204 // Otherwise stay at the current level
1205 return CompLevel_limited_profile;
1206 }
1207
1208
1209 CompLevel CompilationPolicy::trained_transition_from_full_profile(const methodHandle& method, CompLevel cur_level, MethodTrainingData* mtd, JavaThread* THREAD) {
1210 precond(mtd != nullptr);
1211 precond(cur_level == CompLevel_full_profile);
1212
1213 CompLevel highest_training_level = static_cast<CompLevel>(mtd->highest_top_level());
1214 // We have method at the full profile level and we also know that it's possibly an important method.
1215 if (highest_training_level == CompLevel_full_optimization && !mtd->only_inlined()) {
1216 // Check if it is adequately profiled
1217 if (is_method_profiled(method)) {
1218 return CompLevel_full_optimization;
1219 }
1220 }
1221
1222 // Otherwise stay at the current level
1223 return CompLevel_full_profile;
1224 }
1225
1226 CompLevel CompilationPolicy::trained_transition(const methodHandle& method, CompLevel cur_level, MethodTrainingData* mtd, JavaThread* THREAD) {
1227 precond(MethodTrainingData::have_data());
1228
1229 // If there is no training data recorded for this method, bail out.
1230 if (mtd == nullptr) {
1231 return cur_level;
1232 }
1233
1234 CompLevel next_level = cur_level;
1235 switch(cur_level) {
1236 default: break;
1237 case CompLevel_none:
1238 next_level = trained_transition_from_none(method, cur_level, mtd, THREAD);
1239 break;
1240 case CompLevel_limited_profile:
1241 next_level = trained_transition_from_limited_profile(method, cur_level, mtd, THREAD);
1242 break;
1243 case CompLevel_full_profile:
1244 next_level = trained_transition_from_full_profile(method, cur_level, mtd, THREAD);
1245 break;
1246 }
1247
1248 // We don't have any special strategies for the C2-only compilation modes, so just fix up the levels for now.
1249 if (CompilationModeFlag::high_only_quick_internal() && CompLevel_simple < next_level && next_level < CompLevel_full_optimization) {
1250 return CompLevel_none;
1251 }
1252 if (CompilationModeFlag::high_only() && next_level < CompLevel_full_optimization) {
1253 return CompLevel_none;
1254 }
1255 return (cur_level != next_level) ? limit_level(next_level) : cur_level;
1256 }
1257
1258 /*
1259 * Method states:
1260 * 0 - interpreter (CompLevel_none)
1261 * 1 - pure C1 (CompLevel_simple)
1262 * 2 - C1 with invocation and backedge counting (CompLevel_limited_profile)
1263 * 3 - C1 with full profiling (CompLevel_full_profile)
1264 * 4 - C2 or Graal (CompLevel_full_optimization)
1265 *
1266 * Common state transition patterns:
1267 * a. 0 -> 3 -> 4.
1268 * The most common path. But note that even in this straightforward case
1269 * profiling can start at level 0 and finish at level 3.
1270 *
1271 * b. 0 -> 2 -> 3 -> 4.
1272 * This case occurs when the load on C2 is deemed too high. So, instead of transitioning
1273 * into state 3 directly and over-profiling while a method is in the C2 queue we transition to
1274 * level 2 and wait until the load on C2 decreases. This path is disabled for OSRs.
1275 *
1276 * c. 0 -> (3->2) -> 4.
1277 * In this case we enqueue a method for compilation at level 3, but the C1 queue is long enough
1278 * to enable the profiling to fully occur at level 0. In this case we change the compilation level
1279 * of the method to 2 while the request is still in-queue, because it'll allow it to run much faster
1280 * without full profiling while c2 is compiling.
1281 *
1282 * d. 0 -> 3 -> 1 or 0 -> 2 -> 1.
1283 * After a method was once compiled with C1 it can be identified as trivial and be compiled to
1284 * level 1. These transition can also occur if a method can't be compiled with C2 but can with C1.
1285 *
1286 * e. 0 -> 4.
1287 * This can happen if a method fails C1 compilation (it will still be profiled in the interpreter)
1288 * or because of a deopt that didn't require reprofiling (compilation won't happen in this case because
1289 * the compiled version already exists).
1290 *
1291 * Note that since state 0 can be reached from any other state via deoptimization different loops
1292 * are possible.
1293 *
1294 */
1295
1296 // Common transition function. Given a predicate determines if a method should transition to another level.
1297 template<typename Predicate>
1298 CompLevel CompilationPolicy::common(const methodHandle& method, CompLevel cur_level, JavaThread* THREAD, bool disable_feedback) {
1299 CompLevel next_level = cur_level;
1300
1301 if (force_comp_at_level_simple(method)) {
1302 next_level = CompLevel_simple;
1303 } else if (is_trivial(method) || method->is_native()) {
1304 // We do not care if there is profiling data for these methods, throw them to compiler.
1305 next_level = CompilationModeFlag::disable_intermediate() ? CompLevel_full_optimization : CompLevel_simple;
1306 } else if (MethodTrainingData::have_data()) {
1307 MethodTrainingData* mtd = MethodTrainingData::find_fast(method);
1308 if (mtd == nullptr) {
1309 // We haven't see compilations of this method in training. It's either very cold or the behavior changed.
1310 // Feed it to the standard TF with no profiling delay.
1311 next_level = standard_transition<Predicate>(method, cur_level, false /*delay_profiling*/, disable_feedback);
1312 } else {
1313 next_level = trained_transition(method, cur_level, mtd, THREAD);
1314 if (cur_level == next_level) {
1315 // trained_transtion() is going to return the same level if no startup/warmup optimizations apply.
1316 // In order to catch possible pathologies due to behavior change we feed the event to the regular
1317 // TF but with profiling delay.
1318 next_level = standard_transition<Predicate>(method, cur_level, true /*delay_profiling*/, disable_feedback);
1319 }
1320 }
1321 } else {
1322 next_level = standard_transition<Predicate>(method, cur_level, false /*delay_profiling*/, disable_feedback);
1323 }
1324 return (next_level != cur_level) ? limit_level(next_level) : next_level;
1325 }
1326
1327
1328 template<typename Predicate>
1329 CompLevel CompilationPolicy::standard_transition(const methodHandle& method, CompLevel cur_level, bool delay_profiling, bool disable_feedback) {
1330 CompLevel next_level = cur_level;
1331 switch(cur_level) {
1332 default: break;
1333 case CompLevel_none:
1334 next_level = transition_from_none<Predicate>(method, cur_level, delay_profiling, disable_feedback);
1335 break;
1336 case CompLevel_limited_profile:
1337 next_level = transition_from_limited_profile<Predicate>(method, cur_level, delay_profiling, disable_feedback);
1338 break;
1339 case CompLevel_full_profile:
1340 next_level = transition_from_full_profile<Predicate>(method, cur_level);
1341 break;
1342 }
1343 return next_level;
1344 }
1345
1346 template<typename Predicate> static inline bool apply_predicate(const methodHandle& method, CompLevel cur_level, int i, int b, bool delay_profiling, double delay_profiling_scale) {
1347 if (delay_profiling) {
1348 return Predicate::apply_scaled(method, cur_level, i, b, delay_profiling_scale);
1349 } else {
1350 return Predicate::apply(method, cur_level, i, b);
1351 }
1352 }
1353
1354 template<typename Predicate>
1355 CompLevel CompilationPolicy::transition_from_none(const methodHandle& method, CompLevel cur_level, bool delay_profiling, bool disable_feedback) {
1356 precond(cur_level == CompLevel_none);
1357 CompLevel next_level = cur_level;
1358 int i = method->invocation_count();
1359 int b = method->backedge_count();
1360 // If we were at full profile level, would we switch to full opt?
1361 if (transition_from_full_profile<Predicate>(method, CompLevel_full_profile) == CompLevel_full_optimization) {
1362 next_level = CompLevel_full_optimization;
1363 } else if (!CompilationModeFlag::disable_intermediate() && apply_predicate<Predicate>(method, cur_level, i, b, delay_profiling, Tier0ProfileDelayFactor)) {
1364 // C1-generated fully profiled code is about 30% slower than the limited profile
1365 // code that has only invocation and backedge counters. The observation is that
1366 // if C2 queue is large enough we can spend too much time in the fully profiled code
1367 // while waiting for C2 to pick the method from the queue. To alleviate this problem
1368 // we introduce a feedback on the C2 queue size. If the C2 queue is sufficiently long
1369 // we choose to compile a limited profiled version and then recompile with full profiling
1370 // when the load on C2 goes down.
1371 if (delay_profiling || (!disable_feedback && CompileBroker::queue_size(CompLevel_full_optimization) > Tier3DelayOn * compiler_count(CompLevel_full_optimization))) {
1372 next_level = CompLevel_limited_profile;
1373 } else {
1374 next_level = CompLevel_full_profile;
1375 }
1376 }
1377 return next_level;
1378 }
1379
1380 template<typename Predicate>
1381 CompLevel CompilationPolicy::transition_from_full_profile(const methodHandle& method, CompLevel cur_level) {
1382 precond(cur_level == CompLevel_full_profile);
1383 CompLevel next_level = cur_level;
1384 MethodData* mdo = method->method_data();
1385 if (mdo != nullptr) {
1386 if (mdo->would_profile() || CompilationModeFlag::disable_intermediate()) {
1387 int mdo_i = mdo->invocation_count_delta();
1388 int mdo_b = mdo->backedge_count_delta();
1389 if (Predicate::apply(method, cur_level, mdo_i, mdo_b)) {
1390 next_level = CompLevel_full_optimization;
1391 }
1392 } else {
1393 next_level = CompLevel_full_optimization;
1394 }
1395 }
1396 return next_level;
1397 }
1398
1399 template<typename Predicate>
1400 CompLevel CompilationPolicy::transition_from_limited_profile(const methodHandle& method, CompLevel cur_level, bool delay_profiling, bool disable_feedback) {
1401 precond(cur_level == CompLevel_limited_profile);
1402 CompLevel next_level = cur_level;
1403 int i = method->invocation_count();
1404 int b = method->backedge_count();
1405 MethodData* mdo = method->method_data();
1406 if (mdo != nullptr) {
1407 if (mdo->would_profile()) {
1408 if (disable_feedback || (CompileBroker::queue_size(CompLevel_full_optimization) <=
1409 Tier3DelayOff * compiler_count(CompLevel_full_optimization) &&
1410 apply_predicate<Predicate>(method, cur_level, i, b, delay_profiling, Tier2ProfileDelayFactor))) {
1411 next_level = CompLevel_full_profile;
1412 }
1413 } else {
1414 next_level = CompLevel_full_optimization;
1415 }
1416 } else {
1417 // If there is no MDO we need to profile
1418 if (disable_feedback || (CompileBroker::queue_size(CompLevel_full_optimization) <=
1419 Tier3DelayOff * compiler_count(CompLevel_full_optimization) &&
1420 apply_predicate<Predicate>(method, cur_level, i, b, delay_profiling, Tier2ProfileDelayFactor))) {
1421 next_level = CompLevel_full_profile;
1422 }
1423 }
1424 if (next_level == CompLevel_full_profile && is_method_profiled(method)) {
1425 next_level = CompLevel_full_optimization;
1426 }
1427 return next_level;
1428 }
1429
1430
1431 // Determine if a method should be compiled with a normal entry point at a different level.
1432 CompLevel CompilationPolicy::call_event(const methodHandle& method, CompLevel cur_level, JavaThread* THREAD) {
1433 CompLevel osr_level = MIN2((CompLevel) method->highest_osr_comp_level(), common<LoopPredicate>(method, cur_level, THREAD, true));
1434 CompLevel next_level = common<CallPredicate>(method, cur_level, THREAD, !TrainingData::have_data() && is_old(method));
1435
1436 // If OSR method level is greater than the regular method level, the levels should be
1437 // equalized by raising the regular method level in order to avoid OSRs during each
1438 // invocation of the method.
1439 if (osr_level == CompLevel_full_optimization && cur_level == CompLevel_full_profile) {
1440 MethodData* mdo = method->method_data();
1441 guarantee(mdo != nullptr, "MDO should not be nullptr");
1442 if (mdo->invocation_count() >= 1) {
1443 next_level = CompLevel_full_optimization;
1444 }
1445 } else {
1446 next_level = MAX2(osr_level, next_level);
1447 }
1448
1449 return next_level;
1450 }
1451
1452 // Determine if we should do an OSR compilation of a given method.
1453 CompLevel CompilationPolicy::loop_event(const methodHandle& method, CompLevel cur_level, JavaThread* THREAD) {
1454 CompLevel next_level = common<LoopPredicate>(method, cur_level, THREAD, true);
1455 if (cur_level == CompLevel_none) {
1456 // If there is a live OSR method that means that we deopted to the interpreter
1457 // for the transition.
1458 CompLevel osr_level = MIN2((CompLevel)method->highest_osr_comp_level(), next_level);
1459 if (osr_level > CompLevel_none) {
1460 return osr_level;
1461 }
1462 }
1463 return next_level;
1464 }
1465
1466 // Handle the invocation event.
1467 void CompilationPolicy::method_invocation_event(const methodHandle& mh, const methodHandle& imh,
1468 CompLevel level, nmethod* nm, TRAPS) {
1469 if (should_create_mdo(mh, level)) {
1470 create_mdo(mh, THREAD);
1471 }
1472 CompLevel next_level = call_event(mh, level, THREAD);
1473 if (next_level != level) {
1474 if (is_compilation_enabled() && !CompileBroker::compilation_is_in_queue(mh)) {
1475 compile(mh, InvocationEntryBci, next_level, THREAD);
1476 }
1477 }
1478 }
1479
1480 // Handle the back branch event. Notice that we can compile the method
1481 // with a regular entry from here.
1482 void CompilationPolicy::method_back_branch_event(const methodHandle& mh, const methodHandle& imh,
1483 int bci, CompLevel level, nmethod* nm, TRAPS) {
1484 if (should_create_mdo(mh, level)) {
1485 create_mdo(mh, THREAD);
1486 }
1487 // Check if MDO should be created for the inlined method
1488 if (should_create_mdo(imh, level)) {
1489 create_mdo(imh, THREAD);
1490 }
1491
1492 if (is_compilation_enabled()) {
1493 CompLevel next_osr_level = loop_event(imh, level, THREAD);
1494 CompLevel max_osr_level = (CompLevel)imh->highest_osr_comp_level();
1495 // At the very least compile the OSR version
1496 if (!CompileBroker::compilation_is_in_queue(imh) && (next_osr_level != level)) {
1497 compile(imh, bci, next_osr_level, CHECK);
1498 }
1499
1500 // Use loop event as an opportunity to also check if there's been
1501 // enough calls.
1502 CompLevel cur_level, next_level;
1503 if (mh() != imh()) { // If there is an enclosing method
1504 {
1505 guarantee(nm != nullptr, "Should have nmethod here");
1506 cur_level = comp_level(mh());
1507 next_level = call_event(mh, cur_level, THREAD);
1508
1509 if (max_osr_level == CompLevel_full_optimization) {
1510 // The inlinee OSRed to full opt, we need to modify the enclosing method to avoid deopts
1511 bool make_not_entrant = false;
1512 if (nm->is_osr_method()) {
1513 // This is an osr method, just make it not entrant and recompile later if needed
1514 make_not_entrant = true;
1515 } else {
1516 if (next_level != CompLevel_full_optimization) {
1517 // next_level is not full opt, so we need to recompile the
1518 // enclosing method without the inlinee
1519 cur_level = CompLevel_none;
1520 make_not_entrant = true;
1521 }
1522 }
1523 if (make_not_entrant) {
1524 if (PrintTieredEvents) {
1525 int osr_bci = nm->is_osr_method() ? nm->osr_entry_bci() : InvocationEntryBci;
1526 print_event(MAKE_NOT_ENTRANT, mh(), mh(), osr_bci, level);
1527 }
1528 nm->make_not_entrant(nmethod::InvalidationReason::OSR_INVALIDATION_BACK_BRANCH);
1529 }
1530 }
1531 // Fix up next_level if necessary to avoid deopts
1532 if (next_level == CompLevel_limited_profile && max_osr_level == CompLevel_full_profile) {
1533 next_level = CompLevel_full_profile;
1534 }
1535 if (cur_level != next_level) {
1536 if (!CompileBroker::compilation_is_in_queue(mh)) {
1537 compile(mh, InvocationEntryBci, next_level, THREAD);
1538 }
1539 }
1540 }
1541 } else {
1542 cur_level = comp_level(mh());
1543 next_level = call_event(mh, cur_level, THREAD);
1544 if (next_level != cur_level) {
1545 if (!CompileBroker::compilation_is_in_queue(mh)) {
1546 compile(mh, InvocationEntryBci, next_level, THREAD);
1547 }
1548 }
1549 }
1550 }
1551 }
1552