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