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 "code/scopeDesc.hpp"
  26 #include "compiler/compilationPolicy.hpp"
  27 #include "compiler/compileBroker.hpp"
  28 #include "compiler/compilerDefinitions.inline.hpp"
  29 #include "compiler/compilerOracle.hpp"
  30 #include "memory/resourceArea.hpp"
  31 #include "oops/methodData.hpp"
  32 #include "oops/method.inline.hpp"
  33 #include "oops/oop.inline.hpp"
  34 #include "prims/jvmtiExport.hpp"
  35 #include "runtime/arguments.hpp"
  36 #include "runtime/deoptimization.hpp"
  37 #include "runtime/frame.hpp"
  38 #include "runtime/frame.inline.hpp"
  39 #include "runtime/globals_extension.hpp"
  40 #include "runtime/handles.inline.hpp"
  41 #include "runtime/safepoint.hpp"
  42 #include "runtime/safepointVerifiers.hpp"
  43 #ifdef COMPILER1
  44 #include "c1/c1_Compiler.hpp"
  45 #endif
  46 #ifdef COMPILER2
  47 #include "opto/c2compiler.hpp"
  48 #endif
  49 #if INCLUDE_JVMCI
  50 #include "jvmci/jvmci.hpp"
  51 #endif
  52 
  53 jlong CompilationPolicy::_start_time = 0;
  54 int CompilationPolicy::_c1_count = 0;
  55 int CompilationPolicy::_c2_count = 0;
  56 double CompilationPolicy::_increase_threshold_at_ratio = 0;
  57 
  58 void compilationPolicy_init() {
  59   CompilationPolicy::initialize();
  60 }
  61 
  62 int CompilationPolicy::compiler_count(CompLevel comp_level) {
  63   if (is_c1_compile(comp_level)) {
  64     return c1_count();
  65   } else if (is_c2_compile(comp_level)) {
  66     return c2_count();
  67   }
  68   return 0;
  69 }
  70 
  71 // Returns true if m must be compiled before executing it
  72 // This is intended to force compiles for methods (usually for
  73 // debugging) that would otherwise be interpreted for some reason.
  74 bool CompilationPolicy::must_be_compiled(const methodHandle& m, int comp_level) {
  75   // Don't allow Xcomp to cause compiles in replay mode
  76   if (ReplayCompiles) return false;
  77 
  78   if (m->has_compiled_code()) return false;       // already compiled
  79   if (!can_be_compiled(m, comp_level)) return false;
  80 
  81   return !UseInterpreter ||                                              // must compile all methods
  82          (AlwaysCompileLoopMethods && m->has_loops() && CompileBroker::should_compile_new_jobs()); // eagerly compile loop methods
  83 }
  84 
  85 void CompilationPolicy::compile_if_required(const methodHandle& m, TRAPS) {
  86   if (must_be_compiled(m)) {
  87     // This path is unusual, mostly used by the '-Xcomp' stress test mode.
  88 
  89     if (!THREAD->can_call_java() || THREAD->is_Compiler_thread()) {
  90       // don't force compilation, resolve was on behalf of compiler
  91       return;
  92     }
  93     if (m->method_holder()->is_not_initialized()) {
  94       // 'is_not_initialized' means not only '!is_initialized', but also that
  95       // initialization has not been started yet ('!being_initialized')
  96       // Do not force compilation of methods in uninitialized classes.
  97       // Note that doing this would throw an assert later,
  98       // in CompileBroker::compile_method.
  99       // We sometimes use the link resolver to do reflective lookups
 100       // even before classes are initialized.
 101       return;
 102     }
 103     CompLevel level = initial_compile_level(m);
 104     if (PrintTieredEvents) {
 105       print_event(COMPILE, m(), m(), InvocationEntryBci, level);
 106     }
 107     CompileBroker::compile_method(m, InvocationEntryBci, level, methodHandle(), 0, CompileTask::Reason_MustBeCompiled, THREAD);
 108   }
 109 }
 110 
 111 static inline CompLevel adjust_level_for_compilability_query(CompLevel comp_level) {
 112   if (comp_level == CompLevel_any) {
 113      if (CompilerConfig::is_c1_only()) {
 114        comp_level = CompLevel_simple;
 115      } else if (CompilerConfig::is_c2_or_jvmci_compiler_only()) {
 116        comp_level = CompLevel_full_optimization;
 117      }
 118   }
 119   return comp_level;
 120 }
 121 
 122 // Returns true if m is allowed to be compiled
 123 bool CompilationPolicy::can_be_compiled(const methodHandle& m, int comp_level) {
 124   // allow any levels for WhiteBox
 125   assert(WhiteBoxAPI || comp_level == CompLevel_any || is_compile(comp_level), "illegal compilation level");
 126 
 127   if (m->is_abstract()) return false;
 128   if (DontCompileHugeMethods && m->code_size() > HugeMethodLimit) return false;
 129 
 130   // Math intrinsics should never be compiled as this can lead to
 131   // monotonicity problems because the interpreter will prefer the
 132   // compiled code to the intrinsic version.  This can't happen in
 133   // production because the invocation counter can't be incremented
 134   // but we shouldn't expose the system to this problem in testing
 135   // modes.
 136   if (!AbstractInterpreter::can_be_compiled(m)) {
 137     return false;
 138   }
 139   comp_level = adjust_level_for_compilability_query((CompLevel) comp_level);
 140   if (comp_level == CompLevel_any || is_compile(comp_level)) {
 141     return !m->is_not_compilable(comp_level);
 142   }
 143   return false;
 144 }
 145 
 146 // Returns true if m is allowed to be osr compiled
 147 bool CompilationPolicy::can_be_osr_compiled(const methodHandle& m, int comp_level) {
 148   bool result = false;
 149   comp_level = adjust_level_for_compilability_query((CompLevel) comp_level);
 150   if (comp_level == CompLevel_any || is_compile(comp_level)) {
 151     result = !m->is_not_osr_compilable(comp_level);
 152   }
 153   return (result && can_be_compiled(m, comp_level));
 154 }
 155 
 156 bool CompilationPolicy::is_compilation_enabled() {
 157   // NOTE: CompileBroker::should_compile_new_jobs() checks for UseCompiler
 158   return CompileBroker::should_compile_new_jobs();
 159 }
 160 
 161 CompileTask* CompilationPolicy::select_task_helper(CompileQueue* compile_queue) {
 162   // Remove unloaded methods from the queue
 163   for (CompileTask* task = compile_queue->first(); task != nullptr; ) {
 164     CompileTask* next = task->next();
 165     if (task->is_unloaded()) {
 166       compile_queue->remove_and_mark_stale(task);
 167     }
 168     task = next;
 169   }
 170 #if INCLUDE_JVMCI
 171   if (UseJVMCICompiler && !BackgroundCompilation) {
 172     /*
 173      * In blocking compilation mode, the CompileBroker will make
 174      * compilations submitted by a JVMCI compiler thread non-blocking. These
 175      * compilations should be scheduled after all blocking compilations
 176      * to service non-compiler related compilations sooner and reduce the
 177      * chance of such compilations timing out.
 178      */
 179     for (CompileTask* task = compile_queue->first(); task != nullptr; task = task->next()) {
 180       if (task->is_blocking()) {
 181         return task;
 182       }
 183     }
 184   }
 185 #endif
 186   return compile_queue->first();
 187 }
 188 
 189 // Simple methods are as good being compiled with C1 as C2.
 190 // Determine if a given method is such a case.
 191 bool CompilationPolicy::is_trivial(const methodHandle& method) {
 192   if (method->is_accessor() ||
 193       method->is_constant_getter()) {
 194     return true;
 195   }
 196   return false;
 197 }
 198 
 199 bool CompilationPolicy::force_comp_at_level_simple(const methodHandle& method) {
 200   if (CompilationModeFlag::quick_internal()) {
 201 #if INCLUDE_JVMCI
 202     if (UseJVMCICompiler) {
 203       AbstractCompiler* comp = CompileBroker::compiler(CompLevel_full_optimization);
 204       if (comp != nullptr && comp->is_jvmci() && ((JVMCICompiler*) comp)->force_comp_at_level_simple(method)) {
 205         return true;
 206       }
 207     }
 208 #endif
 209   }
 210   return false;
 211 }
 212 
 213 CompLevel CompilationPolicy::comp_level(Method* method) {
 214   nmethod *nm = method->code();
 215   if (nm != nullptr && nm->is_in_use()) {
 216     return (CompLevel)nm->comp_level();
 217   }
 218   return CompLevel_none;
 219 }
 220 
 221 // Call and loop predicates determine whether a transition to a higher
 222 // compilation level should be performed (pointers to predicate functions
 223 // are passed to common()).
 224 // Tier?LoadFeedback is basically a coefficient that determines of
 225 // how many methods per compiler thread can be in the queue before
 226 // the threshold values double.
 227 class LoopPredicate : AllStatic {
 228 public:
 229   static bool apply_scaled(const methodHandle& method, CompLevel cur_level, int i, int b, double scale) {
 230     double threshold_scaling;
 231     if (CompilerOracle::has_option_value(method, CompileCommandEnum::CompileThresholdScaling, threshold_scaling)) {
 232       scale *= threshold_scaling;
 233     }
 234     switch(cur_level) {
 235     case CompLevel_none:
 236     case CompLevel_limited_profile:
 237       return b >= Tier3BackEdgeThreshold * scale;
 238     case CompLevel_full_profile:
 239       return b >= Tier4BackEdgeThreshold * scale;
 240     default:
 241       return true;
 242     }
 243   }
 244 
 245   static bool apply(const methodHandle& method, CompLevel cur_level, int i, int b) {
 246     double k = 1;
 247     switch(cur_level) {
 248     case CompLevel_none:
 249     // Fall through
 250     case CompLevel_limited_profile: {
 251       k = CompilationPolicy::threshold_scale(CompLevel_full_profile, Tier3LoadFeedback);
 252       break;
 253     }
 254     case CompLevel_full_profile: {
 255       k = CompilationPolicy::threshold_scale(CompLevel_full_optimization, Tier4LoadFeedback);
 256       break;
 257     }
 258     default:
 259       return true;
 260     }
 261     return apply_scaled(method, cur_level, i, b, k);
 262   }
 263 };
 264 
 265 class CallPredicate : AllStatic {
 266 public:
 267   static bool apply_scaled(const methodHandle& method, CompLevel cur_level, int i, int b, double scale) {
 268     double threshold_scaling;
 269     if (CompilerOracle::has_option_value(method, CompileCommandEnum::CompileThresholdScaling, threshold_scaling)) {
 270       scale *= threshold_scaling;
 271     }
 272     switch(cur_level) {
 273     case CompLevel_none:
 274     case CompLevel_limited_profile:
 275       return (i >= Tier3InvocationThreshold * scale) ||
 276              (i >= Tier3MinInvocationThreshold * scale && i + b >= Tier3CompileThreshold * scale);
 277     case CompLevel_full_profile:
 278       return (i >= Tier4InvocationThreshold * scale) ||
 279              (i >= Tier4MinInvocationThreshold * scale && i + b >= Tier4CompileThreshold * scale);
 280     default:
 281      return true;
 282     }
 283   }
 284 
 285   static bool apply(const methodHandle& method, CompLevel cur_level, int i, int b) {
 286     double k = 1;
 287     switch(cur_level) {
 288     case CompLevel_none:
 289     case CompLevel_limited_profile: {
 290       k = CompilationPolicy::threshold_scale(CompLevel_full_profile, Tier3LoadFeedback);
 291       break;
 292     }
 293     case CompLevel_full_profile: {
 294       k = CompilationPolicy::threshold_scale(CompLevel_full_optimization, Tier4LoadFeedback);
 295       break;
 296     }
 297     default:
 298       return true;
 299     }
 300     return apply_scaled(method, cur_level, i, b, k);
 301   }
 302 };
 303 
 304 double CompilationPolicy::threshold_scale(CompLevel level, int feedback_k) {
 305   int comp_count = compiler_count(level);
 306   if (comp_count > 0) {
 307     double queue_size = CompileBroker::queue_size(level);
 308     double k = (double)queue_size / ((double)feedback_k * (double)comp_count) + 1;
 309 
 310     // Increase C1 compile threshold when the code cache is filled more
 311     // than specified by IncreaseFirstTierCompileThresholdAt percentage.
 312     // The main intention is to keep enough free space for C2 compiled code
 313     // to achieve peak performance if the code cache is under stress.
 314     if (CompilerConfig::is_tiered() && !CompilationModeFlag::disable_intermediate() && is_c1_compile(level))  {
 315       double current_reverse_free_ratio = CodeCache::reverse_free_ratio();
 316       if (current_reverse_free_ratio > _increase_threshold_at_ratio) {
 317         k *= exp(current_reverse_free_ratio - _increase_threshold_at_ratio);
 318       }
 319     }
 320     return k;
 321   }
 322   return 1;
 323 }
 324 
 325 void CompilationPolicy::print_counters(const char* prefix, const Method* m) {
 326   int invocation_count = m->invocation_count();
 327   int backedge_count = m->backedge_count();
 328   MethodData* mdh = m->method_data();
 329   int mdo_invocations = 0, mdo_backedges = 0;
 330   int mdo_invocations_start = 0, mdo_backedges_start = 0;
 331   if (mdh != nullptr) {
 332     mdo_invocations = mdh->invocation_count();
 333     mdo_backedges = mdh->backedge_count();
 334     mdo_invocations_start = mdh->invocation_count_start();
 335     mdo_backedges_start = mdh->backedge_count_start();
 336   }
 337   tty->print(" %stotal=%d,%d %smdo=%d(%d),%d(%d)", prefix,
 338       invocation_count, backedge_count, prefix,
 339       mdo_invocations, mdo_invocations_start,
 340       mdo_backedges, mdo_backedges_start);
 341   tty->print(" %smax levels=%d,%d", prefix,
 342       m->highest_comp_level(), m->highest_osr_comp_level());
 343 }
 344 
 345 // Print an event.
 346 void CompilationPolicy::print_event(EventType type, const Method* m, const Method* im, int bci, CompLevel level) {
 347   bool inlinee_event = m != im;
 348 
 349   ttyLocker tty_lock;
 350   tty->print("%lf: [", os::elapsedTime());
 351 
 352   switch(type) {
 353   case CALL:
 354     tty->print("call");
 355     break;
 356   case LOOP:
 357     tty->print("loop");
 358     break;
 359   case COMPILE:
 360     tty->print("compile");
 361     break;
 362   case REMOVE_FROM_QUEUE:
 363     tty->print("remove-from-queue");
 364     break;
 365   case UPDATE_IN_QUEUE:
 366     tty->print("update-in-queue");
 367     break;
 368   case REPROFILE:
 369     tty->print("reprofile");
 370     break;
 371   case MAKE_NOT_ENTRANT:
 372     tty->print("make-not-entrant");
 373     break;
 374   default:
 375     tty->print("unknown");
 376   }
 377 
 378   tty->print(" level=%d ", level);
 379 
 380   ResourceMark rm;
 381   char *method_name = m->name_and_sig_as_C_string();
 382   tty->print("[%s", method_name);
 383   if (inlinee_event) {
 384     char *inlinee_name = im->name_and_sig_as_C_string();
 385     tty->print(" [%s]] ", inlinee_name);
 386   }
 387   else tty->print("] ");
 388   tty->print("@%d queues=%d,%d", bci, CompileBroker::queue_size(CompLevel_full_profile),
 389                                       CompileBroker::queue_size(CompLevel_full_optimization));
 390 
 391   tty->print(" rate=");
 392   if (m->prev_time() == 0) tty->print("n/a");
 393   else tty->print("%f", m->rate());
 394 
 395   tty->print(" k=%.2lf,%.2lf", threshold_scale(CompLevel_full_profile, Tier3LoadFeedback),
 396                                threshold_scale(CompLevel_full_optimization, Tier4LoadFeedback));
 397 
 398   if (type != COMPILE) {
 399     print_counters("", m);
 400     if (inlinee_event) {
 401       print_counters("inlinee ", im);
 402     }
 403     tty->print(" compilable=");
 404     bool need_comma = false;
 405     if (!m->is_not_compilable(CompLevel_full_profile)) {
 406       tty->print("c1");
 407       need_comma = true;
 408     }
 409     if (!m->is_not_osr_compilable(CompLevel_full_profile)) {
 410       if (need_comma) tty->print(",");
 411       tty->print("c1-osr");
 412       need_comma = true;
 413     }
 414     if (!m->is_not_compilable(CompLevel_full_optimization)) {
 415       if (need_comma) tty->print(",");
 416       tty->print("c2");
 417       need_comma = true;
 418     }
 419     if (!m->is_not_osr_compilable(CompLevel_full_optimization)) {
 420       if (need_comma) tty->print(",");
 421       tty->print("c2-osr");
 422     }
 423     tty->print(" status=");
 424     if (m->queued_for_compilation()) {
 425       tty->print("in-queue");
 426     } else tty->print("idle");
 427   }
 428   tty->print_cr("]");
 429 }
 430 
 431 void CompilationPolicy::initialize() {
 432   if (!CompilerConfig::is_interpreter_only()) {
 433     int count = CICompilerCount;
 434     bool c1_only = CompilerConfig::is_c1_only();
 435     bool c2_only = CompilerConfig::is_c2_or_jvmci_compiler_only();
 436 
 437 #ifdef _LP64
 438     // Turn on ergonomic compiler count selection
 439     if (FLAG_IS_DEFAULT(CICompilerCountPerCPU) && FLAG_IS_DEFAULT(CICompilerCount)) {
 440       FLAG_SET_DEFAULT(CICompilerCountPerCPU, true);
 441     }
 442     if (CICompilerCountPerCPU) {
 443       // Simple log n seems to grow too slowly for tiered, try something faster: log n * log log n
 444       int log_cpu = log2i(os::active_processor_count());
 445       int loglog_cpu = log2i(MAX2(log_cpu, 1));
 446       count = MAX2(log_cpu * loglog_cpu * 3 / 2, 2);
 447       // Make sure there is enough space in the code cache to hold all the compiler buffers
 448       size_t c1_size = 0;
 449 #ifdef COMPILER1
 450       c1_size = Compiler::code_buffer_size();
 451 #endif
 452       size_t c2_size = 0;
 453 #ifdef COMPILER2
 454       c2_size = C2Compiler::initial_code_buffer_size();
 455 #endif
 456       size_t buffer_size = c1_only ? c1_size : (c1_size/3 + 2*c2_size/3);
 457       int max_count = (ReservedCodeCacheSize - (CodeCacheMinimumUseSpace DEBUG_ONLY(* 3))) / (int)buffer_size;
 458       if (count > max_count) {
 459         // Lower the compiler count such that all buffers fit into the code cache
 460         count = MAX2(max_count, c1_only ? 1 : 2);
 461       }
 462       FLAG_SET_ERGO(CICompilerCount, count);
 463     }
 464 #else
 465     // On 32-bit systems, the number of compiler threads is limited to 3.
 466     // On these systems, the virtual address space available to the JVM
 467     // is usually limited to 2-4 GB (the exact value depends on the platform).
 468     // As the compilers (especially C2) can consume a large amount of
 469     // memory, scaling the number of compiler threads with the number of
 470     // available cores can result in the exhaustion of the address space
 471     /// available to the VM and thus cause the VM to crash.
 472     if (FLAG_IS_DEFAULT(CICompilerCount)) {
 473       count = 3;
 474       FLAG_SET_ERGO(CICompilerCount, count);
 475     }
 476 #endif
 477 
 478     if (c1_only) {
 479       // No C2 compiler thread required
 480       set_c1_count(count);
 481     } else if (c2_only) {
 482       set_c2_count(count);
 483     } else {
 484 #if INCLUDE_JVMCI
 485       if (UseJVMCICompiler && UseJVMCINativeLibrary) {
 486         int libjvmci_count = MAX2((int) (count * JVMCINativeLibraryThreadFraction), 1);
 487         int c1_count = MAX2(count - libjvmci_count, 1);
 488         set_c2_count(libjvmci_count);
 489         set_c1_count(c1_count);
 490       } else
 491 #endif
 492       {
 493         set_c1_count(MAX2(count / 3, 1));
 494         set_c2_count(MAX2(count - c1_count(), 1));
 495       }
 496     }
 497     assert(count == c1_count() + c2_count(), "inconsistent compiler thread count");
 498     set_increase_threshold_at_ratio();
 499   }
 500   set_start_time(nanos_to_millis(os::javaTimeNanos()));
 501 }
 502 
 503 
 504 #ifdef ASSERT
 505 bool CompilationPolicy::verify_level(CompLevel level) {
 506   if (TieredCompilation && level > TieredStopAtLevel) {
 507     return false;
 508   }
 509   // Check if there is a compiler to process the requested level
 510   if (!CompilerConfig::is_c1_enabled() && is_c1_compile(level)) {
 511     return false;
 512   }
 513   if (!CompilerConfig::is_c2_or_jvmci_compiler_enabled() && is_c2_compile(level)) {
 514     return false;
 515   }
 516 
 517   // Interpreter level is always valid.
 518   if (level == CompLevel_none) {
 519     return true;
 520   }
 521   if (CompilationModeFlag::normal()) {
 522     return true;
 523   } else if (CompilationModeFlag::quick_only()) {
 524     return level == CompLevel_simple;
 525   } else if (CompilationModeFlag::high_only()) {
 526     return level == CompLevel_full_optimization;
 527   } else if (CompilationModeFlag::high_only_quick_internal()) {
 528     return level == CompLevel_full_optimization || level == CompLevel_simple;
 529   }
 530   return false;
 531 }
 532 #endif
 533 
 534 
 535 CompLevel CompilationPolicy::highest_compile_level() {
 536   CompLevel level = CompLevel_none;
 537   // Setup the maximum level available for the current compiler configuration.
 538   if (!CompilerConfig::is_interpreter_only()) {
 539     if (CompilerConfig::is_c2_or_jvmci_compiler_enabled()) {
 540       level = CompLevel_full_optimization;
 541     } else if (CompilerConfig::is_c1_enabled()) {
 542       if (CompilerConfig::is_c1_simple_only()) {
 543         level = CompLevel_simple;
 544       } else {
 545         level = CompLevel_full_profile;
 546       }
 547     }
 548   }
 549   // Clamp the maximum level with TieredStopAtLevel.
 550   if (TieredCompilation) {
 551     level = MIN2(level, (CompLevel) TieredStopAtLevel);
 552   }
 553 
 554   // Fix it up if after the clamping it has become invalid.
 555   // Bring it monotonically down depending on the next available level for
 556   // the compilation mode.
 557   if (!CompilationModeFlag::normal()) {
 558     // a) quick_only - levels 2,3,4 are invalid; levels -1,0,1 are valid;
 559     // b) high_only - levels 1,2,3 are invalid; levels -1,0,4 are valid;
 560     // c) high_only_quick_internal - levels 2,3 are invalid; levels -1,0,1,4 are valid.
 561     if (CompilationModeFlag::quick_only()) {
 562       if (level == CompLevel_limited_profile || level == CompLevel_full_profile || level == CompLevel_full_optimization) {
 563         level = CompLevel_simple;
 564       }
 565     } else if (CompilationModeFlag::high_only()) {
 566       if (level == CompLevel_simple || level == CompLevel_limited_profile || level == CompLevel_full_profile) {
 567         level = CompLevel_none;
 568       }
 569     } else if (CompilationModeFlag::high_only_quick_internal()) {
 570       if (level == CompLevel_limited_profile || level == CompLevel_full_profile) {
 571         level = CompLevel_simple;
 572       }
 573     }
 574   }
 575 
 576   assert(verify_level(level), "Invalid highest compilation level: %d", level);
 577   return level;
 578 }
 579 
 580 CompLevel CompilationPolicy::limit_level(CompLevel level) {
 581   level = MIN2(level, highest_compile_level());
 582   assert(verify_level(level), "Invalid compilation level: %d", level);
 583   return level;
 584 }
 585 
 586 CompLevel CompilationPolicy::initial_compile_level(const methodHandle& method) {
 587   CompLevel level = CompLevel_any;
 588   if (CompilationModeFlag::normal()) {
 589     level = CompLevel_full_profile;
 590   } else if (CompilationModeFlag::quick_only()) {
 591     level = CompLevel_simple;
 592   } else if (CompilationModeFlag::high_only()) {
 593     level = CompLevel_full_optimization;
 594   } else if (CompilationModeFlag::high_only_quick_internal()) {
 595     if (force_comp_at_level_simple(method)) {
 596       level = CompLevel_simple;
 597     } else {
 598       level = CompLevel_full_optimization;
 599     }
 600   }
 601   assert(level != CompLevel_any, "Unhandled compilation mode");
 602   return limit_level(level);
 603 }
 604 
 605 // Set carry flags on the counters if necessary
 606 void CompilationPolicy::handle_counter_overflow(const methodHandle& method) {
 607   MethodCounters *mcs = method->method_counters();
 608   if (mcs != nullptr) {
 609     mcs->invocation_counter()->set_carry_on_overflow();
 610     mcs->backedge_counter()->set_carry_on_overflow();
 611   }
 612   MethodData* mdo = method->method_data();
 613   if (mdo != nullptr) {
 614     mdo->invocation_counter()->set_carry_on_overflow();
 615     mdo->backedge_counter()->set_carry_on_overflow();
 616   }
 617 }
 618 
 619 // Called with the queue locked and with at least one element
 620 CompileTask* CompilationPolicy::select_task(CompileQueue* compile_queue) {
 621   CompileTask *max_blocking_task = nullptr;
 622   CompileTask *max_task = nullptr;
 623   Method* max_method = nullptr;
 624 
 625   jlong t = nanos_to_millis(os::javaTimeNanos());
 626   // Iterate through the queue and find a method with a maximum rate.
 627   for (CompileTask* task = compile_queue->first(); task != nullptr;) {
 628     CompileTask* next_task = task->next();
 629     // If a method was unloaded or has been stale for some time, remove it from the queue.
 630     // Blocking tasks and tasks submitted from whitebox API don't become stale
 631     if (task->is_unloaded()) {
 632       compile_queue->remove_and_mark_stale(task);
 633       task = next_task;
 634       continue;
 635     }
 636     Method* method = task->method();
 637     methodHandle mh(Thread::current(), method);
 638     if (task->can_become_stale() && is_stale(t, TieredCompileTaskTimeout, mh) && !is_old(mh)) {
 639       if (PrintTieredEvents) {
 640         print_event(REMOVE_FROM_QUEUE, method, method, task->osr_bci(), (CompLevel) task->comp_level());
 641       }
 642       method->clear_queued_for_compilation();
 643       compile_queue->remove_and_mark_stale(task);
 644       task = next_task;
 645       continue;
 646     }
 647     update_rate(t, mh);
 648     if (max_task == nullptr || compare_methods(method, max_method)) {
 649       // Select a method with the highest rate
 650       max_task = task;
 651       max_method = method;
 652     }
 653 
 654     if (task->is_blocking()) {
 655       if (max_blocking_task == nullptr || compare_methods(method, max_blocking_task->method())) {
 656         max_blocking_task = task;
 657       }
 658     }
 659 
 660     task = next_task;
 661   }
 662 
 663   if (max_blocking_task != nullptr) {
 664     // In blocking compilation mode, the CompileBroker will make
 665     // compilations submitted by a JVMCI compiler thread non-blocking. These
 666     // compilations should be scheduled after all blocking compilations
 667     // to service non-compiler related compilations sooner and reduce the
 668     // chance of such compilations timing out.
 669     max_task = max_blocking_task;
 670     max_method = max_task->method();
 671   }
 672 
 673   methodHandle max_method_h(Thread::current(), max_method);
 674 
 675   if (max_task != nullptr && max_task->comp_level() == CompLevel_full_profile && TieredStopAtLevel > CompLevel_full_profile &&
 676       max_method != nullptr && is_method_profiled(max_method_h) && !Arguments::is_compiler_only()) {
 677     max_task->set_comp_level(CompLevel_limited_profile);
 678 
 679     if (CompileBroker::compilation_is_complete(max_method_h, max_task->osr_bci(), CompLevel_limited_profile)) {
 680       if (PrintTieredEvents) {
 681         print_event(REMOVE_FROM_QUEUE, max_method, max_method, max_task->osr_bci(), (CompLevel)max_task->comp_level());
 682       }
 683       compile_queue->remove_and_mark_stale(max_task);
 684       max_method->clear_queued_for_compilation();
 685       return nullptr;
 686     }
 687 
 688     if (PrintTieredEvents) {
 689       print_event(UPDATE_IN_QUEUE, max_method, max_method, max_task->osr_bci(), (CompLevel)max_task->comp_level());
 690     }
 691   }
 692 
 693   return max_task;
 694 }
 695 
 696 void CompilationPolicy::reprofile(ScopeDesc* trap_scope, bool is_osr) {
 697   for (ScopeDesc* sd = trap_scope;; sd = sd->sender()) {
 698     if (PrintTieredEvents) {
 699       print_event(REPROFILE, sd->method(), sd->method(), InvocationEntryBci, CompLevel_none);
 700     }
 701     MethodData* mdo = sd->method()->method_data();
 702     if (mdo != nullptr) {
 703       mdo->reset_start_counters();
 704     }
 705     if (sd->is_top()) break;
 706   }
 707 }
 708 
 709 nmethod* CompilationPolicy::event(const methodHandle& method, const methodHandle& inlinee,
 710                                       int branch_bci, int bci, CompLevel comp_level, nmethod* nm, TRAPS) {
 711   if (PrintTieredEvents) {
 712     print_event(bci == InvocationEntryBci ? CALL : LOOP, method(), inlinee(), bci, comp_level);
 713   }
 714 
 715   if (comp_level == CompLevel_none &&
 716       JvmtiExport::can_post_interpreter_events() &&
 717       THREAD->is_interp_only_mode()) {
 718     return nullptr;
 719   }
 720   if (ReplayCompiles) {
 721     // Don't trigger other compiles in testing mode
 722     return nullptr;
 723   }
 724 
 725   handle_counter_overflow(method);
 726   if (method() != inlinee()) {
 727     handle_counter_overflow(inlinee);
 728   }
 729 
 730   if (bci == InvocationEntryBci) {
 731     method_invocation_event(method, inlinee, comp_level, nm, THREAD);
 732   } else {
 733     // method == inlinee if the event originated in the main method
 734     method_back_branch_event(method, inlinee, bci, comp_level, nm, THREAD);
 735     // Check if event led to a higher level OSR compilation
 736     CompLevel expected_comp_level = MIN2(CompLevel_full_optimization, static_cast<CompLevel>(comp_level + 1));
 737     if (!CompilationModeFlag::disable_intermediate() && inlinee->is_not_osr_compilable(expected_comp_level)) {
 738       // It's not possible to reach the expected level so fall back to simple.
 739       expected_comp_level = CompLevel_simple;
 740     }
 741     CompLevel max_osr_level = static_cast<CompLevel>(inlinee->highest_osr_comp_level());
 742     if (max_osr_level >= expected_comp_level) { // fast check to avoid locking in a typical scenario
 743       nmethod* osr_nm = inlinee->lookup_osr_nmethod_for(bci, expected_comp_level, false);
 744       assert(osr_nm == nullptr || osr_nm->comp_level() >= expected_comp_level, "lookup_osr_nmethod_for is broken");
 745       if (osr_nm != nullptr && osr_nm->comp_level() != comp_level) {
 746         // Perform OSR with new nmethod
 747         return osr_nm;
 748       }
 749     }
 750   }
 751   return nullptr;
 752 }
 753 
 754 // Check if the method can be compiled, change level if necessary
 755 void CompilationPolicy::compile(const methodHandle& mh, int bci, CompLevel level, TRAPS) {
 756   assert(verify_level(level), "Invalid compilation level requested: %d", level);
 757 
 758   if (level == CompLevel_none) {
 759     if (mh->has_compiled_code()) {
 760       // Happens when we switch to interpreter to profile.
 761       MutexLocker ml(Compile_lock);
 762       NoSafepointVerifier nsv;
 763       if (mh->has_compiled_code()) {
 764         mh->code()->make_not_used();
 765       }
 766       // Deoptimize immediately (we don't have to wait for a compile).
 767       JavaThread* jt = THREAD;
 768       RegisterMap map(jt,
 769                       RegisterMap::UpdateMap::skip,
 770                       RegisterMap::ProcessFrames::include,
 771                       RegisterMap::WalkContinuation::skip);
 772       frame fr = jt->last_frame().sender(&map);
 773       Deoptimization::deoptimize_frame(jt, fr.id());
 774     }
 775     return;
 776   }
 777 
 778   if (!CompilationModeFlag::disable_intermediate()) {
 779     // Check if the method can be compiled. If it cannot be compiled with C1, continue profiling
 780     // in the interpreter and then compile with C2 (the transition function will request that,
 781     // see common() ). If the method cannot be compiled with C2 but still can with C1, compile it with
 782     // pure C1.
 783     if ((bci == InvocationEntryBci && !can_be_compiled(mh, level))) {
 784       if (level == CompLevel_full_optimization && can_be_compiled(mh, CompLevel_simple)) {
 785         compile(mh, bci, CompLevel_simple, THREAD);
 786       }
 787       return;
 788     }
 789     if ((bci != InvocationEntryBci && !can_be_osr_compiled(mh, level))) {
 790       if (level == CompLevel_full_optimization && can_be_osr_compiled(mh, CompLevel_simple)) {
 791         nmethod* osr_nm = mh->lookup_osr_nmethod_for(bci, CompLevel_simple, false);
 792         if (osr_nm != nullptr && osr_nm->comp_level() > CompLevel_simple) {
 793           // Invalidate the existing OSR nmethod so that a compile at CompLevel_simple is permitted.
 794           osr_nm->make_not_entrant();
 795         }
 796         compile(mh, bci, CompLevel_simple, THREAD);
 797       }
 798       return;
 799     }
 800   }
 801   if (bci != InvocationEntryBci && mh->is_not_osr_compilable(level)) {
 802     return;
 803   }
 804   if (!CompileBroker::compilation_is_in_queue(mh)) {
 805     if (PrintTieredEvents) {
 806       print_event(COMPILE, mh(), mh(), bci, level);
 807     }
 808     int hot_count = (bci == InvocationEntryBci) ? mh->invocation_count() : mh->backedge_count();
 809     update_rate(nanos_to_millis(os::javaTimeNanos()), mh);
 810     CompileBroker::compile_method(mh, bci, level, mh, hot_count, CompileTask::Reason_Tiered, THREAD);
 811   }
 812 }
 813 
 814 // update_rate() is called from select_task() while holding a compile queue lock.
 815 void CompilationPolicy::update_rate(jlong t, const methodHandle& method) {
 816   // Skip update if counters are absent.
 817   // Can't allocate them since we are holding compile queue lock.
 818   if (method->method_counters() == nullptr)  return;
 819 
 820   if (is_old(method)) {
 821     // We don't remove old methods from the queue,
 822     // so we can just zero the rate.
 823     method->set_rate(0);
 824     return;
 825   }
 826 
 827   // We don't update the rate if we've just came out of a safepoint.
 828   // delta_s is the time since last safepoint in milliseconds.
 829   jlong delta_s = t - SafepointTracing::end_of_last_safepoint_ms();
 830   jlong delta_t = t - (method->prev_time() != 0 ? method->prev_time() : start_time()); // milliseconds since the last measurement
 831   // How many events were there since the last time?
 832   int event_count = method->invocation_count() + method->backedge_count();
 833   int delta_e = event_count - method->prev_event_count();
 834 
 835   // We should be running for at least 1ms.
 836   if (delta_s >= TieredRateUpdateMinTime) {
 837     // And we must've taken the previous point at least 1ms before.
 838     if (delta_t >= TieredRateUpdateMinTime && delta_e > 0) {
 839       method->set_prev_time(t);
 840       method->set_prev_event_count(event_count);
 841       method->set_rate((float)delta_e / (float)delta_t); // Rate is events per millisecond
 842     } else {
 843       if (delta_t > TieredRateUpdateMaxTime && delta_e == 0) {
 844         // If nothing happened for 25ms, zero the rate. Don't modify prev values.
 845         method->set_rate(0);
 846       }
 847     }
 848   }
 849 }
 850 
 851 // Check if this method has been stale for a given number of milliseconds.
 852 // See select_task().
 853 bool CompilationPolicy::is_stale(jlong t, jlong timeout, const methodHandle& method) {
 854   jlong delta_s = t - SafepointTracing::end_of_last_safepoint_ms();
 855   jlong delta_t = t - method->prev_time();
 856   if (delta_t > timeout && delta_s > timeout) {
 857     int event_count = method->invocation_count() + method->backedge_count();
 858     int delta_e = event_count - method->prev_event_count();
 859     // Return true if there were no events.
 860     return delta_e == 0;
 861   }
 862   return false;
 863 }
 864 
 865 // We don't remove old methods from the compile queue even if they have
 866 // very low activity. See select_task().
 867 bool CompilationPolicy::is_old(const methodHandle& method) {
 868   int i = method->invocation_count();
 869   int b = method->backedge_count();
 870   double k = TieredOldPercentage / 100.0;
 871 
 872   return CallPredicate::apply_scaled(method, CompLevel_none, i, b, k) || LoopPredicate::apply_scaled(method, CompLevel_none, i, b, k);
 873 }
 874 
 875 double CompilationPolicy::weight(Method* method) {
 876   return (double)(method->rate() + 1) * (method->invocation_count() + 1) * (method->backedge_count() + 1);
 877 }
 878 
 879 // Apply heuristics and return true if x should be compiled before y
 880 bool CompilationPolicy::compare_methods(Method* x, Method* y) {
 881   if (x->highest_comp_level() > y->highest_comp_level()) {
 882     // recompilation after deopt
 883     return true;
 884   } else
 885     if (x->highest_comp_level() == y->highest_comp_level()) {
 886       if (weight(x) > weight(y)) {
 887         return true;
 888       }
 889     }
 890   return false;
 891 }
 892 
 893 // Is method profiled enough?
 894 bool CompilationPolicy::is_method_profiled(const methodHandle& method) {
 895   MethodData* mdo = method->method_data();
 896   if (mdo != nullptr) {
 897     int i = mdo->invocation_count_delta();
 898     int b = mdo->backedge_count_delta();
 899     return CallPredicate::apply_scaled(method, CompLevel_full_profile, i, b, 1);
 900   }
 901   return false;
 902 }
 903 
 904 
 905 // Determine is a method is mature.
 906 bool CompilationPolicy::is_mature(Method* method) {
 907   if (Arguments::is_compiler_only()) {
 908     // Always report profiles as immature with -Xcomp
 909     return false;
 910   }
 911   methodHandle mh(Thread::current(), method);
 912   MethodData* mdo = method->method_data();
 913   if (mdo != nullptr) {
 914     int i = mdo->invocation_count();
 915     int b = mdo->backedge_count();
 916     double k = ProfileMaturityPercentage / 100.0;
 917     return CallPredicate::apply_scaled(mh, CompLevel_full_profile, i, b, k) || LoopPredicate::apply_scaled(mh, CompLevel_full_profile, i, b, k);
 918   }
 919   return false;
 920 }
 921 
 922 // If a method is old enough and is still in the interpreter we would want to
 923 // start profiling without waiting for the compiled method to arrive.
 924 // We also take the load on compilers into the account.
 925 bool CompilationPolicy::should_create_mdo(const methodHandle& method, CompLevel cur_level) {
 926   if (cur_level != CompLevel_none || force_comp_at_level_simple(method) || CompilationModeFlag::quick_only() || !ProfileInterpreter) {
 927     return false;
 928   }
 929   if (is_old(method)) {
 930     return true;
 931   }
 932   int i = method->invocation_count();
 933   int b = method->backedge_count();
 934   double k = Tier0ProfilingStartPercentage / 100.0;
 935 
 936   // If the top level compiler is not keeping up, delay profiling.
 937   if (CompileBroker::queue_size(CompLevel_full_optimization) <= Tier0Delay * compiler_count(CompLevel_full_optimization)) {
 938     return CallPredicate::apply_scaled(method, CompLevel_none, i, b, k) || LoopPredicate::apply_scaled(method, CompLevel_none, i, b, k);
 939   }
 940   return false;
 941 }
 942 
 943 // Inlining control: if we're compiling a profiled method with C1 and the callee
 944 // is known to have OSRed in a C2 version, don't inline it.
 945 bool CompilationPolicy::should_not_inline(ciEnv* env, ciMethod* callee) {
 946   CompLevel comp_level = (CompLevel)env->comp_level();
 947   if (comp_level == CompLevel_full_profile ||
 948       comp_level == CompLevel_limited_profile) {
 949     return callee->highest_osr_comp_level() == CompLevel_full_optimization;
 950   }
 951   return false;
 952 }
 953 
 954 // Create MDO if necessary.
 955 void CompilationPolicy::create_mdo(const methodHandle& mh, JavaThread* THREAD) {
 956   if (mh->is_native() ||
 957       mh->is_abstract() ||
 958       mh->is_accessor() ||
 959       mh->is_constant_getter()) {
 960     return;
 961   }
 962   if (mh->method_data() == nullptr) {
 963     Method::build_profiling_method_data(mh, CHECK_AND_CLEAR);
 964   }
 965   if (ProfileInterpreter) {
 966     MethodData* mdo = mh->method_data();
 967     if (mdo != nullptr) {
 968       frame last_frame = THREAD->last_frame();
 969       if (last_frame.is_interpreted_frame() && mh == last_frame.interpreter_frame_method()) {
 970         int bci = last_frame.interpreter_frame_bci();
 971         address dp = mdo->bci_to_dp(bci);
 972         last_frame.interpreter_frame_set_mdp(dp);
 973       }
 974     }
 975   }
 976 }
 977 
 978 
 979 
 980 /*
 981  * Method states:
 982  *   0 - interpreter (CompLevel_none)
 983  *   1 - pure C1 (CompLevel_simple)
 984  *   2 - C1 with invocation and backedge counting (CompLevel_limited_profile)
 985  *   3 - C1 with full profiling (CompLevel_full_profile)
 986  *   4 - C2 or Graal (CompLevel_full_optimization)
 987  *
 988  * Common state transition patterns:
 989  * a. 0 -> 3 -> 4.
 990  *    The most common path. But note that even in this straightforward case
 991  *    profiling can start at level 0 and finish at level 3.
 992  *
 993  * b. 0 -> 2 -> 3 -> 4.
 994  *    This case occurs when the load on C2 is deemed too high. So, instead of transitioning
 995  *    into state 3 directly and over-profiling while a method is in the C2 queue we transition to
 996  *    level 2 and wait until the load on C2 decreases. This path is disabled for OSRs.
 997  *
 998  * c. 0 -> (3->2) -> 4.
 999  *    In this case we enqueue a method for compilation at level 3, but the C1 queue is long enough
1000  *    to enable the profiling to fully occur at level 0. In this case we change the compilation level
1001  *    of the method to 2 while the request is still in-queue, because it'll allow it to run much faster
1002  *    without full profiling while c2 is compiling.
1003  *
1004  * d. 0 -> 3 -> 1 or 0 -> 2 -> 1.
1005  *    After a method was once compiled with C1 it can be identified as trivial and be compiled to
1006  *    level 1. These transition can also occur if a method can't be compiled with C2 but can with C1.
1007  *
1008  * e. 0 -> 4.
1009  *    This can happen if a method fails C1 compilation (it will still be profiled in the interpreter)
1010  *    or because of a deopt that didn't require reprofiling (compilation won't happen in this case because
1011  *    the compiled version already exists).
1012  *
1013  * Note that since state 0 can be reached from any other state via deoptimization different loops
1014  * are possible.
1015  *
1016  */
1017 
1018 // Common transition function. Given a predicate determines if a method should transition to another level.
1019 template<typename Predicate>
1020 CompLevel CompilationPolicy::common(const methodHandle& method, CompLevel cur_level, bool disable_feedback) {
1021   CompLevel next_level = cur_level;
1022   int i = method->invocation_count();
1023   int b = method->backedge_count();
1024 
1025   if (force_comp_at_level_simple(method)) {
1026     next_level = CompLevel_simple;
1027   } else {
1028     if (is_trivial(method) || method->is_native()) {
1029       next_level = CompilationModeFlag::disable_intermediate() ? CompLevel_full_optimization : CompLevel_simple;
1030     } else {
1031       switch(cur_level) {
1032       default: break;
1033       case CompLevel_none:
1034         // If we were at full profile level, would we switch to full opt?
1035         if (common<Predicate>(method, CompLevel_full_profile, disable_feedback) == CompLevel_full_optimization) {
1036           next_level = CompLevel_full_optimization;
1037         } else if (!CompilationModeFlag::disable_intermediate() && Predicate::apply(method, cur_level, i, b)) {
1038           // C1-generated fully profiled code is about 30% slower than the limited profile
1039           // code that has only invocation and backedge counters. The observation is that
1040           // if C2 queue is large enough we can spend too much time in the fully profiled code
1041           // while waiting for C2 to pick the method from the queue. To alleviate this problem
1042           // we introduce a feedback on the C2 queue size. If the C2 queue is sufficiently long
1043           // we choose to compile a limited profiled version and then recompile with full profiling
1044           // when the load on C2 goes down.
1045           if (!disable_feedback && CompileBroker::queue_size(CompLevel_full_optimization) >
1046               Tier3DelayOn * compiler_count(CompLevel_full_optimization)) {
1047             next_level = CompLevel_limited_profile;
1048           } else {
1049             next_level = CompLevel_full_profile;
1050           }
1051         }
1052         break;
1053       case CompLevel_limited_profile:
1054         if (is_method_profiled(method)) {
1055           // Special case: we got here because this method was fully profiled in the interpreter.
1056           next_level = CompLevel_full_optimization;
1057         } else {
1058           MethodData* mdo = method->method_data();
1059           if (mdo != nullptr) {
1060             if (mdo->would_profile()) {
1061               if (disable_feedback || (CompileBroker::queue_size(CompLevel_full_optimization) <=
1062                                        Tier3DelayOff * compiler_count(CompLevel_full_optimization) &&
1063                                        Predicate::apply(method, cur_level, i, b))) {
1064                 next_level = CompLevel_full_profile;
1065               }
1066             } else {
1067               next_level = CompLevel_full_optimization;
1068             }
1069           } else {
1070             // If there is no MDO we need to profile
1071             if (disable_feedback || (CompileBroker::queue_size(CompLevel_full_optimization) <=
1072                                      Tier3DelayOff * compiler_count(CompLevel_full_optimization) &&
1073                                      Predicate::apply(method, cur_level, i, b))) {
1074               next_level = CompLevel_full_profile;
1075             }
1076           }
1077         }
1078         break;
1079       case CompLevel_full_profile:
1080         {
1081           MethodData* mdo = method->method_data();
1082           if (mdo != nullptr) {
1083             if (mdo->would_profile() || CompilationModeFlag::disable_intermediate()) {
1084               int mdo_i = mdo->invocation_count_delta();
1085               int mdo_b = mdo->backedge_count_delta();
1086               if (Predicate::apply(method, cur_level, mdo_i, mdo_b)) {
1087                 next_level = CompLevel_full_optimization;
1088               }
1089             } else {
1090               next_level = CompLevel_full_optimization;
1091             }
1092           }
1093         }
1094         break;
1095       }
1096     }
1097   }
1098   return (next_level != cur_level) ? limit_level(next_level) : next_level;
1099 }
1100 
1101 
1102 
1103 // Determine if a method should be compiled with a normal entry point at a different level.
1104 CompLevel CompilationPolicy::call_event(const methodHandle& method, CompLevel cur_level, Thread* thread) {
1105   CompLevel osr_level = MIN2((CompLevel) method->highest_osr_comp_level(), common<LoopPredicate>(method, cur_level, true));
1106   CompLevel next_level = common<CallPredicate>(method, cur_level, is_old(method));
1107 
1108   // If OSR method level is greater than the regular method level, the levels should be
1109   // equalized by raising the regular method level in order to avoid OSRs during each
1110   // invocation of the method.
1111   if (osr_level == CompLevel_full_optimization && cur_level == CompLevel_full_profile) {
1112     MethodData* mdo = method->method_data();
1113     guarantee(mdo != nullptr, "MDO should not be nullptr");
1114     if (mdo->invocation_count() >= 1) {
1115       next_level = CompLevel_full_optimization;
1116     }
1117   } else {
1118     next_level = MAX2(osr_level, next_level);
1119   }
1120   return next_level;
1121 }
1122 
1123 // Determine if we should do an OSR compilation of a given method.
1124 CompLevel CompilationPolicy::loop_event(const methodHandle& method, CompLevel cur_level, Thread* thread) {
1125   CompLevel next_level = common<LoopPredicate>(method, cur_level, true);
1126   if (cur_level == CompLevel_none) {
1127     // If there is a live OSR method that means that we deopted to the interpreter
1128     // for the transition.
1129     CompLevel osr_level = MIN2((CompLevel)method->highest_osr_comp_level(), next_level);
1130     if (osr_level > CompLevel_none) {
1131       return osr_level;
1132     }
1133   }
1134   return next_level;
1135 }
1136 
1137 // Handle the invocation event.
1138 void CompilationPolicy::method_invocation_event(const methodHandle& mh, const methodHandle& imh,
1139                                                       CompLevel level, nmethod* nm, TRAPS) {
1140   if (should_create_mdo(mh, level)) {
1141     create_mdo(mh, THREAD);
1142   }
1143   CompLevel next_level = call_event(mh, level, THREAD);
1144   if (next_level != level) {
1145     if (is_compilation_enabled() && !CompileBroker::compilation_is_in_queue(mh)) {
1146       compile(mh, InvocationEntryBci, next_level, THREAD);
1147     }
1148   }
1149 }
1150 
1151 // Handle the back branch event. Notice that we can compile the method
1152 // with a regular entry from here.
1153 void CompilationPolicy::method_back_branch_event(const methodHandle& mh, const methodHandle& imh,
1154                                                      int bci, CompLevel level, nmethod* nm, TRAPS) {
1155   if (should_create_mdo(mh, level)) {
1156     create_mdo(mh, THREAD);
1157   }
1158   // Check if MDO should be created for the inlined method
1159   if (should_create_mdo(imh, level)) {
1160     create_mdo(imh, THREAD);
1161   }
1162 
1163   if (is_compilation_enabled()) {
1164     CompLevel next_osr_level = loop_event(imh, level, THREAD);
1165     CompLevel max_osr_level = (CompLevel)imh->highest_osr_comp_level();
1166     // At the very least compile the OSR version
1167     if (!CompileBroker::compilation_is_in_queue(imh) && (next_osr_level != level)) {
1168       compile(imh, bci, next_osr_level, CHECK);
1169     }
1170 
1171     // Use loop event as an opportunity to also check if there's been
1172     // enough calls.
1173     CompLevel cur_level, next_level;
1174     if (mh() != imh()) { // If there is an enclosing method
1175       {
1176         guarantee(nm != nullptr, "Should have nmethod here");
1177         cur_level = comp_level(mh());
1178         next_level = call_event(mh, cur_level, THREAD);
1179 
1180         if (max_osr_level == CompLevel_full_optimization) {
1181           // The inlinee OSRed to full opt, we need to modify the enclosing method to avoid deopts
1182           bool make_not_entrant = false;
1183           if (nm->is_osr_method()) {
1184             // This is an osr method, just make it not entrant and recompile later if needed
1185             make_not_entrant = true;
1186           } else {
1187             if (next_level != CompLevel_full_optimization) {
1188               // next_level is not full opt, so we need to recompile the
1189               // enclosing method without the inlinee
1190               cur_level = CompLevel_none;
1191               make_not_entrant = true;
1192             }
1193           }
1194           if (make_not_entrant) {
1195             if (PrintTieredEvents) {
1196               int osr_bci = nm->is_osr_method() ? nm->osr_entry_bci() : InvocationEntryBci;
1197               print_event(MAKE_NOT_ENTRANT, mh(), mh(), osr_bci, level);
1198             }
1199             nm->make_not_entrant();
1200           }
1201         }
1202         // Fix up next_level if necessary to avoid deopts
1203         if (next_level == CompLevel_limited_profile && max_osr_level == CompLevel_full_profile) {
1204           next_level = CompLevel_full_profile;
1205         }
1206         if (cur_level != next_level) {
1207           if (!CompileBroker::compilation_is_in_queue(mh)) {
1208             compile(mh, InvocationEntryBci, next_level, THREAD);
1209           }
1210         }
1211       }
1212     } else {
1213       cur_level = comp_level(mh());
1214       next_level = call_event(mh, cur_level, THREAD);
1215       if (next_level != cur_level) {
1216         if (!CompileBroker::compilation_is_in_queue(mh)) {
1217           compile(mh, InvocationEntryBci, next_level, THREAD);
1218         }
1219       }
1220     }
1221   }
1222 }
1223