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