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