1 /*
   2  * Copyright (c) 2010, 2018, 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 "compiler/compileBroker.hpp"
  27 #include "compiler/compilerOracle.hpp"
  28 #include "memory/resourceArea.hpp"
  29 #include "runtime/arguments.hpp"
  30 #include "runtime/handles.inline.hpp"
  31 #include "runtime/safepointVerifiers.hpp"
  32 #include "runtime/tieredThresholdPolicy.hpp"
  33 #include "code/scopeDesc.hpp"
  34 #include "oops/method.inline.hpp"
  35 #if INCLUDE_JVMCI
  36 #include "jvmci/jvmciRuntime.hpp"
  37 #endif
  38 
  39 #ifdef TIERED
  40 
  41 #include "c1/c1_Compiler.hpp"
  42 #include "opto/c2compiler.hpp"
  43 
  44 template<CompLevel level>
  45 bool TieredThresholdPolicy::call_predicate_helper(int i, int b, double scale, Method* method) {
  46   double threshold_scaling;
  47   if (CompilerOracle::has_option_value(method, "CompileThresholdScaling", threshold_scaling)) {
  48     scale *= threshold_scaling;
  49   }
  50   switch(level) {
  51   case CompLevel_aot:
  52     return (i >= Tier3AOTInvocationThreshold * scale) ||
  53            (i >= Tier3AOTMinInvocationThreshold * scale && i + b >= Tier3AOTCompileThreshold * scale);
  54   case CompLevel_none:
  55   case CompLevel_limited_profile:
  56     return (i >= Tier3InvocationThreshold * scale) ||
  57            (i >= Tier3MinInvocationThreshold * scale && i + b >= Tier3CompileThreshold * scale);
  58   case CompLevel_full_profile:
  59    return (i >= Tier4InvocationThreshold * scale) ||
  60           (i >= Tier4MinInvocationThreshold * scale && i + b >= Tier4CompileThreshold * scale);
  61   }
  62   return true;
  63 }
  64 
  65 template<CompLevel level>
  66 bool TieredThresholdPolicy::loop_predicate_helper(int i, int b, double scale, Method* method) {
  67   double threshold_scaling;
  68   if (CompilerOracle::has_option_value(method, "CompileThresholdScaling", threshold_scaling)) {
  69     scale *= threshold_scaling;
  70   }
  71   switch(level) {
  72   case CompLevel_aot:
  73     return b >= Tier3AOTBackEdgeThreshold * scale;
  74   case CompLevel_none:
  75   case CompLevel_limited_profile:
  76     return b >= Tier3BackEdgeThreshold * scale;
  77   case CompLevel_full_profile:
  78     return b >= Tier4BackEdgeThreshold * scale;
  79   }
  80   return true;
  81 }
  82 
  83 // Simple methods are as good being compiled with C1 as C2.
  84 // Determine if a given method is such a case.
  85 bool TieredThresholdPolicy::is_trivial(Method* method) {
  86   if (method->is_accessor() ||
  87       method->is_constant_getter()) {
  88     return true;
  89   }
  90 #if INCLUDE_JVMCI
  91   if (UseJVMCICompiler) {
  92     AbstractCompiler* comp = CompileBroker::compiler(CompLevel_full_optimization);
  93     if (TieredCompilation && comp != NULL && comp->is_trivial(method)) {
  94       return true;
  95     }
  96   }
  97 #endif
  98   if (method->has_loops() || method->code_size() >= 15) {
  99     return false;
 100   }
 101   MethodData* mdo = method->method_data();
 102   if (mdo != NULL && !mdo->would_profile() &&
 103       (method->code_size() < 5  || (mdo->num_blocks() < 4))) {
 104     return true;
 105   }
 106   return false;
 107 }
 108 
 109 inline CompLevel TieredThresholdPolicy::comp_level(Method* method) {
 110   CompiledMethod *nm = method->code();
 111   if (nm != NULL && nm->is_in_use()) {
 112     return (CompLevel)nm->comp_level();
 113   }
 114   return CompLevel_none;
 115 }
 116 
 117 void TieredThresholdPolicy::print_counters(const char* prefix, const methodHandle& mh) {
 118   int invocation_count = mh->invocation_count();
 119   int backedge_count = mh->backedge_count();
 120   MethodData* mdh = mh->method_data();
 121   int mdo_invocations = 0, mdo_backedges = 0;
 122   int mdo_invocations_start = 0, mdo_backedges_start = 0;
 123   if (mdh != NULL) {
 124     mdo_invocations = mdh->invocation_count();
 125     mdo_backedges = mdh->backedge_count();
 126     mdo_invocations_start = mdh->invocation_count_start();
 127     mdo_backedges_start = mdh->backedge_count_start();
 128   }
 129   tty->print(" %stotal=%d,%d %smdo=%d(%d),%d(%d)", prefix,
 130       invocation_count, backedge_count, prefix,
 131       mdo_invocations, mdo_invocations_start,
 132       mdo_backedges, mdo_backedges_start);
 133   tty->print(" %smax levels=%d,%d", prefix,
 134       mh->highest_comp_level(), mh->highest_osr_comp_level());
 135 }
 136 
 137 // Print an event.
 138 void TieredThresholdPolicy::print_event(EventType type, const methodHandle& mh, const methodHandle& imh,
 139                                         int bci, CompLevel level) {
 140   bool inlinee_event = mh() != imh();
 141 
 142   ttyLocker tty_lock;
 143   tty->print("%lf: [", os::elapsedTime());
 144 
 145   switch(type) {
 146   case CALL:
 147     tty->print("call");
 148     break;
 149   case LOOP:
 150     tty->print("loop");
 151     break;
 152   case COMPILE:
 153     tty->print("compile");
 154     break;
 155   case REMOVE_FROM_QUEUE:
 156     tty->print("remove-from-queue");
 157     break;
 158   case UPDATE_IN_QUEUE:
 159     tty->print("update-in-queue");
 160     break;
 161   case REPROFILE:
 162     tty->print("reprofile");
 163     break;
 164   case MAKE_NOT_ENTRANT:
 165     tty->print("make-not-entrant");
 166     break;
 167   default:
 168     tty->print("unknown");
 169   }
 170 
 171   tty->print(" level=%d ", level);
 172 
 173   ResourceMark rm;
 174   char *method_name = mh->name_and_sig_as_C_string();
 175   tty->print("[%s", method_name);
 176   if (inlinee_event) {
 177     char *inlinee_name = imh->name_and_sig_as_C_string();
 178     tty->print(" [%s]] ", inlinee_name);
 179   }
 180   else tty->print("] ");
 181   tty->print("@%d queues=%d,%d", bci, CompileBroker::queue_size(CompLevel_full_profile),
 182                                       CompileBroker::queue_size(CompLevel_full_optimization));
 183 
 184   print_specific(type, mh, imh, bci, level);
 185 
 186   if (type != COMPILE) {
 187     print_counters("", mh);
 188     if (inlinee_event) {
 189       print_counters("inlinee ", imh);
 190     }
 191     tty->print(" compilable=");
 192     bool need_comma = false;
 193     if (!mh->is_not_compilable(CompLevel_full_profile)) {
 194       tty->print("c1");
 195       need_comma = true;
 196     }
 197     if (!mh->is_not_osr_compilable(CompLevel_full_profile)) {
 198       if (need_comma) tty->print(",");
 199       tty->print("c1-osr");
 200       need_comma = true;
 201     }
 202     if (!mh->is_not_compilable(CompLevel_full_optimization)) {
 203       if (need_comma) tty->print(",");
 204       tty->print("c2");
 205       need_comma = true;
 206     }
 207     if (!mh->is_not_osr_compilable(CompLevel_full_optimization)) {
 208       if (need_comma) tty->print(",");
 209       tty->print("c2-osr");
 210     }
 211     tty->print(" status=");
 212     if (mh->queued_for_compilation()) {
 213       tty->print("in-queue");
 214     } else tty->print("idle");
 215   }
 216   tty->print_cr("]");
 217 }
 218 
 219 void TieredThresholdPolicy::initialize() {
 220   int count = CICompilerCount;
 221   bool c1_only = TieredStopAtLevel < CompLevel_full_optimization;
 222 #ifdef _LP64
 223   // Turn on ergonomic compiler count selection
 224   if (FLAG_IS_DEFAULT(CICompilerCountPerCPU) && FLAG_IS_DEFAULT(CICompilerCount)) {
 225     FLAG_SET_DEFAULT(CICompilerCountPerCPU, true);
 226   }
 227   if (CICompilerCountPerCPU) {
 228     // Simple log n seems to grow too slowly for tiered, try something faster: log n * log log n
 229     int log_cpu = log2_int(os::active_processor_count());
 230     int loglog_cpu = log2_int(MAX2(log_cpu, 1));
 231     count = MAX2(log_cpu * loglog_cpu * 3 / 2, 2);
 232     // Make sure there is enough space in the code cache to hold all the compiler buffers
 233     size_t c1_size = Compiler::code_buffer_size();
 234     size_t c2_size = C2Compiler::initial_code_buffer_size();
 235     size_t buffer_size = c1_only ? c1_size : (c1_size/3 + 2*c2_size/3);
 236     int max_count = (ReservedCodeCacheSize - (CodeCacheMinimumUseSpace DEBUG_ONLY(* 3))) / (int)buffer_size;
 237     if (count > max_count) {
 238       // Lower the compiler count such that all buffers fit into the code cache
 239       count = MAX2(max_count, c1_only ? 1 : 2);
 240     }
 241     FLAG_SET_ERGO(intx, CICompilerCount, count);
 242   }
 243 #else
 244   // On 32-bit systems, the number of compiler threads is limited to 3.
 245   // On these systems, the virtual address space available to the JVM
 246   // is usually limited to 2-4 GB (the exact value depends on the platform).
 247   // As the compilers (especially C2) can consume a large amount of
 248   // memory, scaling the number of compiler threads with the number of
 249   // available cores can result in the exhaustion of the address space
 250   /// available to the VM and thus cause the VM to crash.
 251   if (FLAG_IS_DEFAULT(CICompilerCount)) {
 252     count = 3;
 253     FLAG_SET_ERGO(intx, CICompilerCount, count);
 254   }
 255 #endif
 256 
 257   if (c1_only) {
 258     // No C2 compiler thread required
 259     set_c1_count(count);
 260   } else {
 261     set_c1_count(MAX2(count / 3, 1));
 262     set_c2_count(MAX2(count - c1_count(), 1));
 263   }
 264   assert(count == c1_count() + c2_count(), "inconsistent compiler thread count");
 265 
 266   // Some inlining tuning
 267 #ifdef X86
 268   if (FLAG_IS_DEFAULT(InlineSmallCode)) {
 269     FLAG_SET_DEFAULT(InlineSmallCode, 2000);
 270   }
 271 #endif
 272 
 273 #if defined SPARC || defined AARCH64
 274   if (FLAG_IS_DEFAULT(InlineSmallCode)) {
 275     FLAG_SET_DEFAULT(InlineSmallCode, 2500);
 276   }
 277 #endif
 278 
 279   set_increase_threshold_at_ratio();
 280   set_start_time(os::javaTimeMillis());
 281 }
 282 
 283 void TieredThresholdPolicy::set_carry_if_necessary(InvocationCounter *counter) {
 284   if (!counter->carry() && counter->count() > InvocationCounter::count_limit / 2) {
 285     counter->set_carry_flag();
 286   }
 287 }
 288 
 289 // Set carry flags on the counters if necessary
 290 void TieredThresholdPolicy::handle_counter_overflow(Method* method) {
 291   MethodCounters *mcs = method->method_counters();
 292   if (mcs != NULL) {
 293     set_carry_if_necessary(mcs->invocation_counter());
 294     set_carry_if_necessary(mcs->backedge_counter());
 295   }
 296   MethodData* mdo = method->method_data();
 297   if (mdo != NULL) {
 298     set_carry_if_necessary(mdo->invocation_counter());
 299     set_carry_if_necessary(mdo->backedge_counter());
 300   }
 301 }
 302 
 303 // Called with the queue locked and with at least one element
 304 CompileTask* TieredThresholdPolicy::select_task(CompileQueue* compile_queue) {
 305   CompileTask *max_blocking_task = NULL;
 306   CompileTask *max_task = NULL;
 307   Method* max_method = NULL;
 308   jlong t = os::javaTimeMillis();
 309   // Iterate through the queue and find a method with a maximum rate.
 310   for (CompileTask* task = compile_queue->first(); task != NULL;) {
 311     CompileTask* next_task = task->next();
 312     Method* method = task->method();
 313     update_rate(t, method);
 314     if (max_task == NULL) {
 315       max_task = task;
 316       max_method = method;
 317     } else {
 318       // If a method has been stale for some time, remove it from the queue.
 319       // Blocking tasks and tasks submitted from whitebox API don't become stale
 320       if (task->can_become_stale() && is_stale(t, TieredCompileTaskTimeout, method) && !is_old(method)) {
 321         if (PrintTieredEvents) {
 322           print_event(REMOVE_FROM_QUEUE, method, method, task->osr_bci(), (CompLevel)task->comp_level());
 323         }
 324         compile_queue->remove_and_mark_stale(task);
 325         method->clear_queued_for_compilation();
 326         task = next_task;
 327         continue;
 328       }
 329 
 330       // Select a method with a higher rate
 331       if (compare_methods(method, max_method)) {
 332         max_task = task;
 333         max_method = method;
 334       }
 335     }
 336 
 337     if (task->is_blocking()) {
 338       if (max_blocking_task == NULL || compare_methods(method, max_blocking_task->method())) {
 339         max_blocking_task = task;
 340       }
 341     }
 342 
 343     task = next_task;
 344   }
 345 
 346   if (max_blocking_task != NULL) {
 347     // In blocking compilation mode, the CompileBroker will make
 348     // compilations submitted by a JVMCI compiler thread non-blocking. These
 349     // compilations should be scheduled after all blocking compilations
 350     // to service non-compiler related compilations sooner and reduce the
 351     // chance of such compilations timing out.
 352     max_task = max_blocking_task;
 353     max_method = max_task->method();
 354   }
 355 
 356   if (max_task != NULL && max_task->comp_level() == CompLevel_full_profile &&
 357       TieredStopAtLevel > CompLevel_full_profile &&
 358       max_method != NULL && is_method_profiled(max_method)) {
 359     max_task->set_comp_level(CompLevel_limited_profile);
 360 
 361     if (CompileBroker::compilation_is_complete(max_method, max_task->osr_bci(), CompLevel_limited_profile)) {
 362       if (PrintTieredEvents) {
 363         print_event(REMOVE_FROM_QUEUE, max_method, max_method, max_task->osr_bci(), (CompLevel)max_task->comp_level());
 364       }
 365       compile_queue->remove_and_mark_stale(max_task);
 366       max_method->clear_queued_for_compilation();
 367       return NULL;
 368     }
 369 
 370     if (PrintTieredEvents) {
 371       print_event(UPDATE_IN_QUEUE, max_method, max_method, max_task->osr_bci(), (CompLevel)max_task->comp_level());
 372     }
 373   }
 374 
 375   return max_task;
 376 }
 377 
 378 void TieredThresholdPolicy::reprofile(ScopeDesc* trap_scope, bool is_osr) {
 379   for (ScopeDesc* sd = trap_scope;; sd = sd->sender()) {
 380     if (PrintTieredEvents) {
 381       methodHandle mh(sd->method());
 382       print_event(REPROFILE, mh, mh, InvocationEntryBci, CompLevel_none);
 383     }
 384     MethodData* mdo = sd->method()->method_data();
 385     if (mdo != NULL) {
 386       mdo->reset_start_counters();
 387     }
 388     if (sd->is_top()) break;
 389   }
 390 }
 391 
 392 nmethod* TieredThresholdPolicy::event(const methodHandle& method, const methodHandle& inlinee,
 393                                       int branch_bci, int bci, CompLevel comp_level, CompiledMethod* nm, JavaThread* thread) {
 394   if (comp_level == CompLevel_none &&
 395       JvmtiExport::can_post_interpreter_events() &&
 396       thread->is_interp_only_mode()) {
 397     return NULL;
 398   }
 399   if (CompileTheWorld || ReplayCompiles) {
 400     // Don't trigger other compiles in testing mode
 401     return NULL;
 402   }
 403 
 404   handle_counter_overflow(method());
 405   if (method() != inlinee()) {
 406     handle_counter_overflow(inlinee());
 407   }
 408 
 409   if (PrintTieredEvents) {
 410     print_event(bci == InvocationEntryBci ? CALL : LOOP, method, inlinee, bci, comp_level);
 411   }
 412 
 413   if (bci == InvocationEntryBci) {
 414     method_invocation_event(method, inlinee, comp_level, nm, thread);
 415   } else {
 416     // method == inlinee if the event originated in the main method
 417     method_back_branch_event(method, inlinee, bci, comp_level, nm, thread);
 418     // Check if event led to a higher level OSR compilation
 419     nmethod* osr_nm = inlinee->lookup_osr_nmethod_for(bci, comp_level, false);
 420     if (osr_nm != NULL && osr_nm->comp_level() > comp_level) {
 421       // Perform OSR with new nmethod
 422       return osr_nm;
 423     }
 424   }
 425   return NULL;
 426 }
 427 
 428 // Check if the method can be compiled, change level if necessary
 429 void TieredThresholdPolicy::compile(const methodHandle& mh, int bci, CompLevel level, JavaThread* thread) {
 430   assert(level <= TieredStopAtLevel, "Invalid compilation level");
 431   if (level == CompLevel_none) {
 432     return;
 433   }
 434   if (level == CompLevel_aot) {
 435     if (mh->has_aot_code()) {
 436       if (PrintTieredEvents) {
 437         print_event(COMPILE, mh, mh, bci, level);
 438       }
 439       MutexLocker ml(Compile_lock);
 440       NoSafepointVerifier nsv;
 441       if (mh->has_aot_code() && mh->code() != mh->aot_code()) {
 442         mh->aot_code()->make_entrant();
 443         if (mh->has_compiled_code()) {
 444           mh->code()->make_not_entrant();
 445         }
 446         Method::set_code(mh, mh->aot_code());
 447       }
 448     }
 449     return;
 450   }
 451 
 452   // Check if the method can be compiled. If it cannot be compiled with C1, continue profiling
 453   // in the interpreter and then compile with C2 (the transition function will request that,
 454   // see common() ). If the method cannot be compiled with C2 but still can with C1, compile it with
 455   // pure C1.
 456   if (!can_be_compiled(mh, level)) {
 457     if (level == CompLevel_full_optimization && can_be_compiled(mh, CompLevel_simple)) {
 458         compile(mh, bci, CompLevel_simple, thread);
 459     }
 460     return;
 461   }
 462   if (bci != InvocationEntryBci && mh->is_not_osr_compilable(level)) {
 463     return;
 464   }
 465   if (!CompileBroker::compilation_is_in_queue(mh)) {
 466     if (PrintTieredEvents) {
 467       print_event(COMPILE, mh, mh, bci, level);
 468     }
 469     submit_compile(mh, bci, level, thread);
 470   }
 471 }
 472 
 473 // Update the rate and submit compile
 474 void TieredThresholdPolicy::submit_compile(const methodHandle& mh, int bci, CompLevel level, JavaThread* thread) {
 475   int hot_count = (bci == InvocationEntryBci) ? mh->invocation_count() : mh->backedge_count();
 476   update_rate(os::javaTimeMillis(), mh());
 477   CompileBroker::compile_method(mh, bci, level, mh, hot_count, CompileTask::Reason_Tiered, thread);
 478 }
 479 
 480 // Print an event.
 481 void TieredThresholdPolicy::print_specific(EventType type, const methodHandle& mh, const methodHandle& imh,
 482                                              int bci, CompLevel level) {
 483   tty->print(" rate=");
 484   if (mh->prev_time() == 0) tty->print("n/a");
 485   else tty->print("%f", mh->rate());
 486 
 487   tty->print(" k=%.2lf,%.2lf", threshold_scale(CompLevel_full_profile, Tier3LoadFeedback),
 488                                threshold_scale(CompLevel_full_optimization, Tier4LoadFeedback));
 489 
 490 }
 491 
 492 // update_rate() is called from select_task() while holding a compile queue lock.
 493 void TieredThresholdPolicy::update_rate(jlong t, Method* m) {
 494   // Skip update if counters are absent.
 495   // Can't allocate them since we are holding compile queue lock.
 496   if (m->method_counters() == NULL)  return;
 497 
 498   if (is_old(m)) {
 499     // We don't remove old methods from the queue,
 500     // so we can just zero the rate.
 501     m->set_rate(0);
 502     return;
 503   }
 504 
 505   // We don't update the rate if we've just came out of a safepoint.
 506   // delta_s is the time since last safepoint in milliseconds.
 507   jlong delta_s = t - SafepointSynchronize::end_of_last_safepoint();
 508   jlong delta_t = t - (m->prev_time() != 0 ? m->prev_time() : start_time()); // milliseconds since the last measurement
 509   // How many events were there since the last time?
 510   int event_count = m->invocation_count() + m->backedge_count();
 511   int delta_e = event_count - m->prev_event_count();
 512 
 513   // We should be running for at least 1ms.
 514   if (delta_s >= TieredRateUpdateMinTime) {
 515     // And we must've taken the previous point at least 1ms before.
 516     if (delta_t >= TieredRateUpdateMinTime && delta_e > 0) {
 517       m->set_prev_time(t);
 518       m->set_prev_event_count(event_count);
 519       m->set_rate((float)delta_e / (float)delta_t); // Rate is events per millisecond
 520     } else {
 521       if (delta_t > TieredRateUpdateMaxTime && delta_e == 0) {
 522         // If nothing happened for 25ms, zero the rate. Don't modify prev values.
 523         m->set_rate(0);
 524       }
 525     }
 526   }
 527 }
 528 
 529 // Check if this method has been stale from a given number of milliseconds.
 530 // See select_task().
 531 bool TieredThresholdPolicy::is_stale(jlong t, jlong timeout, Method* m) {
 532   jlong delta_s = t - SafepointSynchronize::end_of_last_safepoint();
 533   jlong delta_t = t - m->prev_time();
 534   if (delta_t > timeout && delta_s > timeout) {
 535     int event_count = m->invocation_count() + m->backedge_count();
 536     int delta_e = event_count - m->prev_event_count();
 537     // Return true if there were no events.
 538     return delta_e == 0;
 539   }
 540   return false;
 541 }
 542 
 543 // We don't remove old methods from the compile queue even if they have
 544 // very low activity. See select_task().
 545 bool TieredThresholdPolicy::is_old(Method* method) {
 546   return method->invocation_count() > 50000 || method->backedge_count() > 500000;
 547 }
 548 
 549 double TieredThresholdPolicy::weight(Method* method) {
 550   return (double)(method->rate() + 1) *
 551     (method->invocation_count() + 1) * (method->backedge_count() + 1);
 552 }
 553 
 554 // Apply heuristics and return true if x should be compiled before y
 555 bool TieredThresholdPolicy::compare_methods(Method* x, Method* y) {
 556   if (x->highest_comp_level() > y->highest_comp_level()) {
 557     // recompilation after deopt
 558     return true;
 559   } else
 560     if (x->highest_comp_level() == y->highest_comp_level()) {
 561       if (weight(x) > weight(y)) {
 562         return true;
 563       }
 564     }
 565   return false;
 566 }
 567 
 568 // Is method profiled enough?
 569 bool TieredThresholdPolicy::is_method_profiled(Method* method) {
 570   MethodData* mdo = method->method_data();
 571   if (mdo != NULL) {
 572     int i = mdo->invocation_count_delta();
 573     int b = mdo->backedge_count_delta();
 574     return call_predicate_helper<CompLevel_full_profile>(i, b, 1, method);
 575   }
 576   return false;
 577 }
 578 
 579 double TieredThresholdPolicy::threshold_scale(CompLevel level, int feedback_k) {
 580   double queue_size = CompileBroker::queue_size(level);
 581   int comp_count = compiler_count(level);
 582   double k = queue_size / (feedback_k * comp_count) + 1;
 583 
 584   // Increase C1 compile threshold when the code cache is filled more
 585   // than specified by IncreaseFirstTierCompileThresholdAt percentage.
 586   // The main intention is to keep enough free space for C2 compiled code
 587   // to achieve peak performance if the code cache is under stress.
 588   if ((TieredStopAtLevel == CompLevel_full_optimization) && (level != CompLevel_full_optimization))  {
 589     double current_reverse_free_ratio = CodeCache::reverse_free_ratio(CodeCache::get_code_blob_type(level));
 590     if (current_reverse_free_ratio > _increase_threshold_at_ratio) {
 591       k *= exp(current_reverse_free_ratio - _increase_threshold_at_ratio);
 592     }
 593   }
 594   return k;
 595 }
 596 
 597 // Call and loop predicates determine whether a transition to a higher
 598 // compilation level should be performed (pointers to predicate functions
 599 // are passed to common()).
 600 // Tier?LoadFeedback is basically a coefficient that determines of
 601 // how many methods per compiler thread can be in the queue before
 602 // the threshold values double.
 603 bool TieredThresholdPolicy::loop_predicate(int i, int b, CompLevel cur_level, Method* method) {
 604   switch(cur_level) {
 605   case CompLevel_aot: {
 606     double k = threshold_scale(CompLevel_full_profile, Tier3LoadFeedback);
 607     return loop_predicate_helper<CompLevel_aot>(i, b, k, method);
 608   }
 609   case CompLevel_none:
 610   case CompLevel_limited_profile: {
 611     double k = threshold_scale(CompLevel_full_profile, Tier3LoadFeedback);
 612     return loop_predicate_helper<CompLevel_none>(i, b, k, method);
 613   }
 614   case CompLevel_full_profile: {
 615     double k = threshold_scale(CompLevel_full_optimization, Tier4LoadFeedback);
 616     return loop_predicate_helper<CompLevel_full_profile>(i, b, k, method);
 617   }
 618   default:
 619     return true;
 620   }
 621 }
 622 
 623 bool TieredThresholdPolicy::call_predicate(int i, int b, CompLevel cur_level, Method* method) {
 624   switch(cur_level) {
 625   case CompLevel_aot: {
 626     double k = threshold_scale(CompLevel_full_profile, Tier3LoadFeedback);
 627     return call_predicate_helper<CompLevel_aot>(i, b, k, method);
 628   }
 629   case CompLevel_none:
 630   case CompLevel_limited_profile: {
 631     double k = threshold_scale(CompLevel_full_profile, Tier3LoadFeedback);
 632     return call_predicate_helper<CompLevel_none>(i, b, k, method);
 633   }
 634   case CompLevel_full_profile: {
 635     double k = threshold_scale(CompLevel_full_optimization, Tier4LoadFeedback);
 636     return call_predicate_helper<CompLevel_full_profile>(i, b, k, method);
 637   }
 638   default:
 639     return true;
 640   }
 641 }
 642 
 643 // Determine is a method is mature.
 644 bool TieredThresholdPolicy::is_mature(Method* method) {
 645   if (is_trivial(method)) return true;
 646   MethodData* mdo = method->method_data();
 647   if (mdo != NULL) {
 648     int i = mdo->invocation_count();
 649     int b = mdo->backedge_count();
 650     double k = ProfileMaturityPercentage / 100.0;
 651     return call_predicate_helper<CompLevel_full_profile>(i, b, k, method) ||
 652            loop_predicate_helper<CompLevel_full_profile>(i, b, k, method);
 653   }
 654   return false;
 655 }
 656 
 657 // If a method is old enough and is still in the interpreter we would want to
 658 // start profiling without waiting for the compiled method to arrive.
 659 // We also take the load on compilers into the account.
 660 bool TieredThresholdPolicy::should_create_mdo(Method* method, CompLevel cur_level) {
 661   if (cur_level == CompLevel_none &&
 662       CompileBroker::queue_size(CompLevel_full_optimization) <=
 663       Tier3DelayOn * compiler_count(CompLevel_full_optimization)) {
 664     int i = method->invocation_count();
 665     int b = method->backedge_count();
 666     double k = Tier0ProfilingStartPercentage / 100.0;
 667     return call_predicate_helper<CompLevel_none>(i, b, k, method) || loop_predicate_helper<CompLevel_none>(i, b, k, method);
 668   }
 669   return false;
 670 }
 671 
 672 // Inlining control: if we're compiling a profiled method with C1 and the callee
 673 // is known to have OSRed in a C2 version, don't inline it.
 674 bool TieredThresholdPolicy::should_not_inline(ciEnv* env, ciMethod* callee) {
 675   CompLevel comp_level = (CompLevel)env->comp_level();
 676   if (comp_level == CompLevel_full_profile ||
 677       comp_level == CompLevel_limited_profile) {
 678     return callee->highest_osr_comp_level() == CompLevel_full_optimization;
 679   }
 680   return false;
 681 }
 682 
 683 // Create MDO if necessary.
 684 void TieredThresholdPolicy::create_mdo(const methodHandle& mh, JavaThread* THREAD) {
 685   if (mh->is_native() ||
 686       mh->is_abstract() ||
 687       mh->is_accessor() ||
 688       mh->is_constant_getter()) {
 689     return;
 690   }
 691   if (mh->method_data() == NULL) {
 692     Method::build_interpreter_method_data(mh, CHECK_AND_CLEAR);
 693   }
 694 }
 695 
 696 
 697 /*
 698  * Method states:
 699  *   0 - interpreter (CompLevel_none)
 700  *   1 - pure C1 (CompLevel_simple)
 701  *   2 - C1 with invocation and backedge counting (CompLevel_limited_profile)
 702  *   3 - C1 with full profiling (CompLevel_full_profile)
 703  *   4 - C2 (CompLevel_full_optimization)
 704  *
 705  * Common state transition patterns:
 706  * a. 0 -> 3 -> 4.
 707  *    The most common path. But note that even in this straightforward case
 708  *    profiling can start at level 0 and finish at level 3.
 709  *
 710  * b. 0 -> 2 -> 3 -> 4.
 711  *    This case occurs when the load on C2 is deemed too high. So, instead of transitioning
 712  *    into state 3 directly and over-profiling while a method is in the C2 queue we transition to
 713  *    level 2 and wait until the load on C2 decreases. This path is disabled for OSRs.
 714  *
 715  * c. 0 -> (3->2) -> 4.
 716  *    In this case we enqueue a method for compilation at level 3, but the C1 queue is long enough
 717  *    to enable the profiling to fully occur at level 0. In this case we change the compilation level
 718  *    of the method to 2 while the request is still in-queue, because it'll allow it to run much faster
 719  *    without full profiling while c2 is compiling.
 720  *
 721  * d. 0 -> 3 -> 1 or 0 -> 2 -> 1.
 722  *    After a method was once compiled with C1 it can be identified as trivial and be compiled to
 723  *    level 1. These transition can also occur if a method can't be compiled with C2 but can with C1.
 724  *
 725  * e. 0 -> 4.
 726  *    This can happen if a method fails C1 compilation (it will still be profiled in the interpreter)
 727  *    or because of a deopt that didn't require reprofiling (compilation won't happen in this case because
 728  *    the compiled version already exists).
 729  *
 730  * Note that since state 0 can be reached from any other state via deoptimization different loops
 731  * are possible.
 732  *
 733  */
 734 
 735 // Common transition function. Given a predicate determines if a method should transition to another level.
 736 CompLevel TieredThresholdPolicy::common(Predicate p, Method* method, CompLevel cur_level, bool disable_feedback) {
 737   CompLevel next_level = cur_level;
 738   int i = method->invocation_count();
 739   int b = method->backedge_count();
 740 
 741   if (is_trivial(method)) {
 742     next_level = CompLevel_simple;
 743   } else {
 744     switch(cur_level) {
 745       default: break;
 746       case CompLevel_aot: {
 747       // If we were at full profile level, would we switch to full opt?
 748       if (common(p, method, CompLevel_full_profile, disable_feedback) == CompLevel_full_optimization) {
 749         next_level = CompLevel_full_optimization;
 750       } else if (disable_feedback || (CompileBroker::queue_size(CompLevel_full_optimization) <=
 751                                Tier3DelayOff * compiler_count(CompLevel_full_optimization) &&
 752                                (this->*p)(i, b, cur_level, method))) {
 753         next_level = CompLevel_full_profile;
 754       }
 755     }
 756     break;
 757     case CompLevel_none:
 758       // If we were at full profile level, would we switch to full opt?
 759       if (common(p, method, CompLevel_full_profile, disable_feedback) == CompLevel_full_optimization) {
 760         next_level = CompLevel_full_optimization;
 761       } else if ((this->*p)(i, b, cur_level, method)) {
 762 #if INCLUDE_JVMCI
 763         if (EnableJVMCI && UseJVMCICompiler) {
 764           // Since JVMCI takes a while to warm up, its queue inevitably backs up during
 765           // early VM execution. As of 2014-06-13, JVMCI's inliner assumes that the root
 766           // compilation method and all potential inlinees have mature profiles (which
 767           // includes type profiling). If it sees immature profiles, JVMCI's inliner
 768           // can perform pathologically bad (e.g., causing OutOfMemoryErrors due to
 769           // exploring/inlining too many graphs). Since a rewrite of the inliner is
 770           // in progress, we simply disable the dialing back heuristic for now and will
 771           // revisit this decision once the new inliner is completed.
 772           next_level = CompLevel_full_profile;
 773         } else
 774 #endif
 775         {
 776           // C1-generated fully profiled code is about 30% slower than the limited profile
 777           // code that has only invocation and backedge counters. The observation is that
 778           // if C2 queue is large enough we can spend too much time in the fully profiled code
 779           // while waiting for C2 to pick the method from the queue. To alleviate this problem
 780           // we introduce a feedback on the C2 queue size. If the C2 queue is sufficiently long
 781           // we choose to compile a limited profiled version and then recompile with full profiling
 782           // when the load on C2 goes down.
 783           if (!disable_feedback && CompileBroker::queue_size(CompLevel_full_optimization) >
 784               Tier3DelayOn * compiler_count(CompLevel_full_optimization)) {
 785             next_level = CompLevel_limited_profile;
 786           } else {
 787             next_level = CompLevel_full_profile;
 788           }
 789         }
 790       }
 791       break;
 792     case CompLevel_limited_profile:
 793       if (is_method_profiled(method)) {
 794         // Special case: we got here because this method was fully profiled in the interpreter.
 795         next_level = CompLevel_full_optimization;
 796       } else {
 797         MethodData* mdo = method->method_data();
 798         if (mdo != NULL) {
 799           if (mdo->would_profile()) {
 800             if (disable_feedback || (CompileBroker::queue_size(CompLevel_full_optimization) <=
 801                                      Tier3DelayOff * compiler_count(CompLevel_full_optimization) &&
 802                                      (this->*p)(i, b, cur_level, method))) {
 803               next_level = CompLevel_full_profile;
 804             }
 805           } else {
 806             next_level = CompLevel_full_optimization;
 807           }
 808         } else {
 809           // If there is no MDO we need to profile
 810           if (disable_feedback || (CompileBroker::queue_size(CompLevel_full_optimization) <=
 811                                    Tier3DelayOff * compiler_count(CompLevel_full_optimization) &&
 812                                    (this->*p)(i, b, cur_level, method))) {
 813             next_level = CompLevel_full_profile;
 814           }
 815         }
 816       }
 817       break;
 818     case CompLevel_full_profile:
 819       {
 820         MethodData* mdo = method->method_data();
 821         if (mdo != NULL) {
 822           if (mdo->would_profile()) {
 823             int mdo_i = mdo->invocation_count_delta();
 824             int mdo_b = mdo->backedge_count_delta();
 825             if ((this->*p)(mdo_i, mdo_b, cur_level, method)) {
 826               next_level = CompLevel_full_optimization;
 827             }
 828           } else {
 829             next_level = CompLevel_full_optimization;
 830           }
 831         }
 832       }
 833       break;
 834     }
 835   }
 836   return MIN2(next_level, (CompLevel)TieredStopAtLevel);
 837 }
 838 
 839 // Determine if a method should be compiled with a normal entry point at a different level.
 840 CompLevel TieredThresholdPolicy::call_event(Method* method, CompLevel cur_level, JavaThread * thread) {
 841   CompLevel osr_level = MIN2((CompLevel) method->highest_osr_comp_level(),
 842                              common(&TieredThresholdPolicy::loop_predicate, method, cur_level, true));
 843   CompLevel next_level = common(&TieredThresholdPolicy::call_predicate, method, cur_level);
 844 
 845   // If OSR method level is greater than the regular method level, the levels should be
 846   // equalized by raising the regular method level in order to avoid OSRs during each
 847   // invocation of the method.
 848   if (osr_level == CompLevel_full_optimization && cur_level == CompLevel_full_profile) {
 849     MethodData* mdo = method->method_data();
 850     guarantee(mdo != NULL, "MDO should not be NULL");
 851     if (mdo->invocation_count() >= 1) {
 852       next_level = CompLevel_full_optimization;
 853     }
 854   } else {
 855     next_level = MAX2(osr_level, next_level);
 856   }
 857 #if INCLUDE_JVMCI
 858   if (UseJVMCICompiler) {
 859     next_level = JVMCIRuntime::adjust_comp_level(method, false, next_level, thread);
 860   }
 861 #endif
 862   return next_level;
 863 }
 864 
 865 // Determine if we should do an OSR compilation of a given method.
 866 CompLevel TieredThresholdPolicy::loop_event(Method* method, CompLevel cur_level, JavaThread* thread) {
 867   CompLevel next_level = common(&TieredThresholdPolicy::loop_predicate, method, cur_level, true);
 868   if (cur_level == CompLevel_none) {
 869     // If there is a live OSR method that means that we deopted to the interpreter
 870     // for the transition.
 871     CompLevel osr_level = MIN2((CompLevel)method->highest_osr_comp_level(), next_level);
 872     if (osr_level > CompLevel_none) {
 873       return osr_level;
 874     }
 875   }
 876 #if INCLUDE_JVMCI
 877   if (UseJVMCICompiler) {
 878     next_level = JVMCIRuntime::adjust_comp_level(method, true, next_level, thread);
 879   }
 880 #endif
 881   return next_level;
 882 }
 883 
 884 bool TieredThresholdPolicy::maybe_switch_to_aot(const methodHandle& mh, CompLevel cur_level, CompLevel next_level, JavaThread* thread) {
 885   if (UseAOT && !delay_compilation_during_startup()) {
 886     if (cur_level == CompLevel_full_profile || cur_level == CompLevel_none) {
 887       // If the current level is full profile or interpreter and we're switching to any other level,
 888       // activate the AOT code back first so that we won't waste time overprofiling.
 889       compile(mh, InvocationEntryBci, CompLevel_aot, thread);
 890       // Fall through for JIT compilation.
 891     }
 892     if (next_level == CompLevel_limited_profile && cur_level != CompLevel_aot && mh->has_aot_code()) {
 893       // If the next level is limited profile, use the aot code (if there is any),
 894       // since it's essentially the same thing.
 895       compile(mh, InvocationEntryBci, CompLevel_aot, thread);
 896       // Not need to JIT, we're done.
 897       return true;
 898     }
 899   }
 900   return false;
 901 }
 902 
 903 
 904 // Handle the invocation event.
 905 void TieredThresholdPolicy::method_invocation_event(const methodHandle& mh, const methodHandle& imh,
 906                                                       CompLevel level, CompiledMethod* nm, JavaThread* thread) {
 907   if (should_create_mdo(mh(), level)) {
 908     create_mdo(mh, thread);
 909   }
 910   CompLevel next_level = call_event(mh(), level, thread);
 911   if (next_level != level) {
 912     if (maybe_switch_to_aot(mh, level, next_level, thread)) {
 913       // No JITting necessary
 914       return;
 915     }
 916     if (is_compilation_enabled() && !CompileBroker::compilation_is_in_queue(mh)) {
 917       compile(mh, InvocationEntryBci, next_level, thread);
 918     }
 919   }
 920 }
 921 
 922 // Handle the back branch event. Notice that we can compile the method
 923 // with a regular entry from here.
 924 void TieredThresholdPolicy::method_back_branch_event(const methodHandle& mh, const methodHandle& imh,
 925                                                      int bci, CompLevel level, CompiledMethod* nm, JavaThread* thread) {
 926   if (should_create_mdo(mh(), level)) {
 927     create_mdo(mh, thread);
 928   }
 929   // Check if MDO should be created for the inlined method
 930   if (should_create_mdo(imh(), level)) {
 931     create_mdo(imh, thread);
 932   }
 933 
 934   if (is_compilation_enabled()) {
 935     CompLevel next_osr_level = loop_event(imh(), level, thread);
 936     CompLevel max_osr_level = (CompLevel)imh->highest_osr_comp_level();
 937     // At the very least compile the OSR version
 938     if (!CompileBroker::compilation_is_in_queue(imh) && (next_osr_level != level)) {
 939       compile(imh, bci, next_osr_level, thread);
 940     }
 941 
 942     // Use loop event as an opportunity to also check if there's been
 943     // enough calls.
 944     CompLevel cur_level, next_level;
 945     if (mh() != imh()) { // If there is an enclosing method
 946       if (level == CompLevel_aot) {
 947         // Recompile the enclosing method to prevent infinite OSRs. Stay at AOT level while it's compiling.
 948         if (max_osr_level != CompLevel_none && !CompileBroker::compilation_is_in_queue(mh)) {
 949           compile(mh, InvocationEntryBci, MIN2((CompLevel)TieredStopAtLevel, CompLevel_full_profile), thread);
 950         }
 951       } else {
 952         // Current loop event level is not AOT
 953         guarantee(nm != NULL, "Should have nmethod here");
 954         cur_level = comp_level(mh());
 955         next_level = call_event(mh(), cur_level, thread);
 956 
 957         if (max_osr_level == CompLevel_full_optimization) {
 958           // The inlinee OSRed to full opt, we need to modify the enclosing method to avoid deopts
 959           bool make_not_entrant = false;
 960           if (nm->is_osr_method()) {
 961             // This is an osr method, just make it not entrant and recompile later if needed
 962             make_not_entrant = true;
 963           } else {
 964             if (next_level != CompLevel_full_optimization) {
 965               // next_level is not full opt, so we need to recompile the
 966               // enclosing method without the inlinee
 967               cur_level = CompLevel_none;
 968               make_not_entrant = true;
 969             }
 970           }
 971           if (make_not_entrant) {
 972             if (PrintTieredEvents) {
 973               int osr_bci = nm->is_osr_method() ? nm->osr_entry_bci() : InvocationEntryBci;
 974               print_event(MAKE_NOT_ENTRANT, mh(), mh(), osr_bci, level);
 975             }
 976             nm->make_not_entrant();
 977           }
 978         }
 979         // Fix up next_level if necessary to avoid deopts
 980         if (next_level == CompLevel_limited_profile && max_osr_level == CompLevel_full_profile) {
 981           next_level = CompLevel_full_profile;
 982         }
 983         if (cur_level != next_level) {
 984           if (!maybe_switch_to_aot(mh, cur_level, next_level, thread) && !CompileBroker::compilation_is_in_queue(mh)) {
 985             compile(mh, InvocationEntryBci, next_level, thread);
 986           }
 987         }
 988       }
 989     } else {
 990       cur_level = comp_level(mh());
 991       next_level = call_event(mh(), cur_level, thread);
 992       if (next_level != cur_level) {
 993         if (!maybe_switch_to_aot(mh, cur_level, next_level, thread) && !CompileBroker::compilation_is_in_queue(mh)) {
 994           compile(mh, InvocationEntryBci, next_level, thread);
 995         }
 996       }
 997     }
 998   }
 999 }
1000 
1001 #endif