1 /*
  2  * Copyright (c) 2010, 2025, Oracle and/or its affiliates. All rights reserved.
  3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  4  *
  5  * This code is free software; you can redistribute it and/or modify it
  6  * under the terms of the GNU General Public License version 2 only, as
  7  * published by the Free Software Foundation.
  8  *
  9  * This code is distributed in the hope that it will be useful, but WITHOUT
 10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 12  * version 2 for more details (a copy is included in the LICENSE file that
 13  * accompanied this code).
 14  *
 15  * You should have received a copy of the GNU General Public License version
 16  * 2 along with this work; if not, write to the Free Software Foundation,
 17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 18  *
 19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 20  * or visit www.oracle.com if you need additional information or have any
 21  * questions.
 22  *
 23  */
 24 
 25 #ifndef SHARE_COMPILER_COMPILATIONPOLICY_HPP
 26 #define SHARE_COMPILER_COMPILATIONPOLICY_HPP
 27 
 28 #include "code/nmethod.hpp"
 29 #include "compiler/compileBroker.hpp"
 30 #include "oops/methodData.hpp"
 31 #include "oops/trainingData.hpp"
 32 #include "utilities/globalDefinitions.hpp"
 33 
 34 namespace CompilationPolicyUtils {
 35 template<typename T>
 36 class Queue {
 37   class QueueNode : public CHeapObj<mtCompiler> {
 38     T* _value;
 39     QueueNode* _next;
 40   public:
 41     QueueNode(T* value, QueueNode* next) : _value(value), _next(next) { }
 42     T* value() const { return _value; }
 43     void set_next(QueueNode* next) { _next = next; }
 44     QueueNode* next() const { return _next; }
 45   };
 46 
 47   QueueNode* _head;
 48   QueueNode* _tail;
 49   int _processing;
 50 
 51   void push_unlocked(T* value) {
 52     QueueNode* n = new QueueNode(value, nullptr);
 53     if (_tail != nullptr) {
 54       _tail->set_next(n);
 55     }
 56     _tail = n;
 57     if (_head == nullptr) {
 58       _head = _tail;
 59     }
 60   }
 61   T* pop_unlocked() {
 62     QueueNode* n = _head;
 63     if (_head != nullptr) {
 64       _head = _head->next();
 65     }
 66     if (_head == nullptr) {
 67       _tail = _head;
 68     }
 69     T* value = nullptr;
 70     if (n != nullptr) {
 71       value = n->value();
 72       delete n;
 73     }
 74     return value;
 75   }
 76 public:
 77   Queue() : _head(nullptr), _tail(nullptr) { }
 78   void push(T* value, Monitor* lock, JavaThread* current) {
 79     MonitorLocker locker(current, lock);
 80     push_unlocked(value);
 81     locker.notify_all();
 82   }
 83 
 84   bool is_empty_unlocked() const { return _head == nullptr; }
 85   bool is_processing_unlocked() const { return _processing > 0; }
 86 
 87   T* pop(Monitor* lock, JavaThread* current) {
 88     MonitorLocker locker(current, lock);
 89     while (is_empty_unlocked() && !CompileBroker::is_compilation_disabled_forever()) {
 90       locker.wait();
 91     }
 92     T* value = pop_unlocked();
 93     return value;
 94   }
 95 
 96   T* try_pop(Monitor* lock, JavaThread* current) {
 97     MonitorLocker locker(current, lock);
 98     T* value = pop_unlocked();
 99     return value;
100   }
101   void print_on(outputStream* st);
102 };
103 } // namespace CompilationPolicyUtils
104 
105 class CompileTask;
106 class CompileQueue;
107 /*
108  *  The system supports 5 execution levels:
109  *  * level 0 - interpreter (Profiling is tracked by a MethodData object, or MDO in short)
110  *  * level 1 - C1 with full optimization (no profiling)
111  *  * level 2 - C1 with invocation and backedge counters
112  *  * level 3 - C1 with full profiling (level 2 + All other MDO profiling information)
113  *  * level 4 - C2 with full profile guided optimization
114  *
115  * The MethodData object is created by both the interpreter or either compiler to store any
116  * profiling information collected on a method (ciMethod::ensure_method_data() for C1 and C2
117  * and CompilationPolicy::create_mdo() for the interpreter). Both the interpreter and code
118  * compiled by C1 at level 3 will constantly update profiling information in the MDO during
119  * execution. The information in the MDO is then used by C1 and C2 during compilation, via
120  * the compiler interface (ciMethodXXX).
121  * See ciMethod.cpp and ciMethodData.cpp for information transfer from an MDO to the compilers
122  * through the compiler interface.
123  *
124  * Levels 0, 2 and 3 periodically notify the runtime about the current value of the counters
125  * (invocation counters and backedge counters). The frequency of these notifications is
126  * different at each level. These notifications are used by the policy to decide what transition
127  * to make.
128  *
129  * Execution starts at level 0 (interpreter), then the policy can decide either to compile the
130  * method at level 3 or level 2. The decision is based on the following factors:
131  *    1. The length of the C2 queue determines the next level. The observation is that level 2
132  * is generally faster than level 3 by about 30%, therefore we would want to minimize the time
133  * a method spends at level 3. We should only spend the time at level 3 that is necessary to get
134  * adequate profiling. So, if the C2 queue is long enough it is more beneficial to go first to
135  * level 2, because if we transitioned to level 3 we would be stuck there until our C2 compile
136  * request makes its way through the long queue. When the load on C2 recedes we are going to
137  * recompile at level 3 and start gathering profiling information.
138  *    2. The length of C1 queue is used to dynamically adjust the thresholds, so as to introduce
139  * additional filtering if the compiler is overloaded. The rationale is that by the time a
140  * method gets compiled it can become unused, so it doesn't make sense to put too much onto the
141  * queue.
142  *
143  * After profiling is completed at level 3 the transition is made to level 4. Again, the length
144  * of the C2 queue is used as a feedback to adjust the thresholds.
145  *
146  * After the first C1 compile some basic information is determined about the code like the number
147  * of the blocks and the number of the loops. Based on that it can be decided that a method
148  * is trivial and compiling it with C1 will yield the same code. In this case the method is
149  * compiled at level 1 instead of 4.
150  *
151  * We also support profiling at level 0. If C1 is slow enough to produce the level 3 version of
152  * the code and the C2 queue is sufficiently small we can decide to start profiling in the
153  * interpreter (and continue profiling in the compiled code once the level 3 version arrives).
154  * If the profiling at level 0 is fully completed before level 3 version is produced, a level 2
155  * version is compiled instead in order to run faster waiting for a level 4 version.
156  *
157  * Compile queues are implemented as priority queues - for each method in the queue we compute
158  * the event rate (the number of invocation and backedge counter increments per unit of time).
159  * When getting an element off the queue we pick the one with the largest rate. Maintaining the
160  * rate also allows us to remove stale methods (the ones that got on the queue but stopped
161  * being used shortly after that).
162 */
163 
164 /* Command line options:
165  * - Tier?InvokeNotifyFreqLog and Tier?BackedgeNotifyFreqLog control the frequency of method
166  *   invocation and backedge notifications. Basically every n-th invocation or backedge a mutator thread
167  *   makes a call into the runtime.
168  *
169  * - Tier?InvocationThreshold, Tier?CompileThreshold, Tier?BackEdgeThreshold, Tier?MinInvocationThreshold control
170  *   compilation thresholds.
171  *   Level 2 thresholds are not used and are provided for option-compatibility and potential future use.
172  *   Other thresholds work as follows:
173  *
174  *   Transition from interpreter (level 0) to C1 with full profiling (level 3) happens when
175  *   the following predicate is true (X is the level):
176  *
177  *   i > TierXInvocationThreshold * s || (i > TierXMinInvocationThreshold * s  && i + b > TierXCompileThreshold * s),
178  *
179  *   where $i$ is the number of method invocations, $b$ number of backedges and $s$ is the scaling
180  *   coefficient that will be discussed further.
181  *   The intuition is to equalize the time that is spend profiling each method.
182  *   The same predicate is used to control the transition from level 3 to level 4 (C2). It should be
183  *   noted though that the thresholds are relative. Moreover i and b for the 0->3 transition come
184  *   from Method* and for 3->4 transition they come from MDO (since profiled invocations are
185  *   counted separately). Finally, if a method does not contain anything worth profiling, a transition
186  *   from level 3 to level 4 occurs without considering thresholds (e.g., with fewer invocations than
187  *   what is specified by Tier4InvocationThreshold).
188  *
189  *   OSR transitions are controlled simply with b > TierXBackEdgeThreshold * s predicates.
190  *
191  * - Tier?LoadFeedback options are used to automatically scale the predicates described above depending
192  *   on the compiler load. The scaling coefficients are computed as follows:
193  *
194  *   s = queue_size_X / (TierXLoadFeedback * compiler_count_X) + 1,
195  *
196  *   where queue_size_X is the current size of the compiler queue of level X, and compiler_count_X
197  *   is the number of level X compiler threads.
198  *
199  *   Basically these parameters describe how many methods should be in the compile queue
200  *   per compiler thread before the scaling coefficient increases by one.
201  *
202  *   This feedback provides the mechanism to automatically control the flow of compilation requests
203  *   depending on the machine speed, mutator load and other external factors.
204  *
205  * - Tier3DelayOn and Tier3DelayOff parameters control another important feedback loop.
206  *   Consider the following observation: a method compiled with full profiling (level 3)
207  *   is about 30% slower than a method at level 2 (just invocation and backedge counters, no MDO).
208  *   Normally, the following transitions will occur: 0->3->4. The problem arises when the C2 queue
209  *   gets congested and the 3->4 transition is delayed. While the method is the C2 queue it continues
210  *   executing at level 3 for much longer time than is required by the predicate and at suboptimal speed.
211  *   The idea is to dynamically change the behavior of the system in such a way that if a substantial
212  *   load on C2 is detected we would first do the 0->2 transition allowing a method to run faster.
213  *   And then when the load decreases to allow 2->3 transitions.
214  *
215  *   Tier3Delay* parameters control this switching mechanism.
216  *   Tier3DelayOn is the number of methods in the C2 queue per compiler thread after which the policy
217  *   no longer does 0->3 transitions but does 0->2 transitions instead.
218  *   Tier3DelayOff switches the original behavior back when the number of methods in the C2 queue
219  *   per compiler thread falls below the specified amount.
220  *   The hysteresis is necessary to avoid jitter.
221  *
222  * - TieredCompileTaskTimeout is the amount of time an idle method can spend in the compile queue.
223  *   Basically, since we use the event rate d(i + b)/dt as a value of priority when selecting a method to
224  *   compile from the compile queue, we also can detect stale methods for which the rate has been
225  *   0 for some time in the same iteration. Stale methods can appear in the queue when an application
226  *   abruptly changes its behavior.
227  *
228  * - TieredStopAtLevel, is used mostly for testing. It allows to bypass the policy logic and stick
229  *   to a given level. For example it's useful to set TieredStopAtLevel = 1 in order to compile everything
230  *   with pure c1.
231  *
232  * - Tier0ProfilingStartPercentage allows the interpreter to start profiling when the inequalities in the
233  *   0->3 predicate are already exceeded by the given percentage but the level 3 version of the
234  *   method is still not ready. We can even go directly from level 0 to 4 if c1 doesn't produce a compiled
235  *   version in time. This reduces the overall transition to level 4 and decreases the startup time.
236  *   Note that this behavior is also guarded by the Tier3Delay mechanism: when the c2 queue is too long
237  *   these is not reason to start profiling prematurely.
238  *
239  * - TieredRateUpdateMinTime and TieredRateUpdateMaxTime are parameters of the rate computation.
240  *   Basically, the rate is not computed more frequently than TieredRateUpdateMinTime and is considered
241  *   to be zero if no events occurred in TieredRateUpdateMaxTime.
242  */
243 
244 class CompilationPolicy : AllStatic {
245   friend class CallPredicate;
246   friend class LoopPredicate;
247   friend class RecompilationPolicy;
248 
249   typedef CompilationPolicyUtils::Queue<InstanceKlass> TrainingReplayQueue;
250 
251   static int64_t _start_time;
252   static int _c1_count, _c2_count, _ac_count;
253   static double _increase_threshold_at_ratio;
254   static TrainingReplayQueue _training_replay_queue;
255 
256   // Set carry flags in the counters (in Method* and MDO).
257   inline static void handle_counter_overflow(const methodHandle& method);
258 #ifdef ASSERT
259   // Verify that a level is consistent with the compilation mode
260   static bool verify_level(CompLevel level);
261 #endif
262   // Clamp the request level according to various constraints.
263   inline static CompLevel limit_level(CompLevel level);
264   // Common transition function. Given a predicate determines if a method should transition to another level.
265   template<typename Predicate>
266   static CompLevel common(const methodHandle& method, CompLevel cur_level, JavaThread* THREAD, bool disable_feedback = false);
267 
268   template<typename Predicate>
269   static CompLevel transition_from_none(const methodHandle& method, CompLevel cur_level, bool delay_profiling, bool disable_feedback);
270   template<typename Predicate>
271   static CompLevel transition_from_limited_profile(const methodHandle& method, CompLevel cur_level, bool delay_profiling, bool disable_feedback);
272   template<typename Predicate>
273   static CompLevel transition_from_full_profile(const methodHandle& method, CompLevel cur_level);
274   template<typename Predicate>
275   static CompLevel standard_transition(const methodHandle& method, CompLevel cur_level, bool delayprof, bool disable_feedback);
276 
277   static CompLevel trained_transition_from_none(const methodHandle& method, CompLevel cur_level, MethodTrainingData* mtd, JavaThread* THREAD);
278   static CompLevel trained_transition_from_limited_profile(const methodHandle& method, CompLevel cur_level, MethodTrainingData* mtd, JavaThread* THREAD);
279   static CompLevel trained_transition_from_full_profile(const methodHandle& method, CompLevel cur_level, MethodTrainingData* mtd, JavaThread* THREAD);
280   static CompLevel trained_transition(const methodHandle& method, CompLevel cur_level, MethodTrainingData* mtd, JavaThread* THREAD);
281 
282   // Transition functions.
283   // call_event determines if a method should be compiled at a different
284   // level with a regular invocation entry.
285   static CompLevel call_event(const methodHandle& method, CompLevel cur_level, JavaThread* THREAD);
286   // loop_event checks if a method should be OSR compiled at a different
287   // level.
288   static CompLevel loop_event(const methodHandle& method, CompLevel cur_level, JavaThread* THREAD);
289   static void print_counters_on(outputStream* st, const char* prefix, Method* m);
290   static void print_training_data_on(outputStream* st, const char* prefix, Method* method);
291   // Has a method been long around?
292   // We don't remove old methods from the compile queue even if they have
293   // very low activity (see select_task()).
294   inline static bool is_old(const methodHandle& method);
295   // Was a given method inactive for a given number of milliseconds.
296   // If it is, we would remove it from the queue (see select_task()).
297   inline static bool is_stale(int64_t t, int64_t timeout, const methodHandle& method);
298   // Compute the weight of the method for the compilation scheduling
299   inline static double weight(Method* method);
300   // Apply heuristics and return true if x should be compiled before y
301   inline static bool compare_methods(Method* x, Method* y);
302   inline static bool compare_tasks(CompileTask* x, CompileTask* y);
303   // Compute event rate for a given method. The rate is the number of event (invocations + backedges)
304   // per millisecond.
305   inline static void update_rate(int64_t t, const methodHandle& method);
306   // Compute threshold scaling coefficient
307   inline static double threshold_scale(CompLevel level, int feedback_k);
308   // If a method is old enough and is still in the interpreter we would want to
309   // start profiling without waiting for the compiled method to arrive. This function
310   // determines whether we should do that.
311   inline static bool should_create_mdo(const methodHandle& method, CompLevel cur_level);
312   // Create MDO if necessary.
313   static void create_mdo(const methodHandle& mh, JavaThread* THREAD);
314   // Is method profiled enough?
315   static bool is_method_profiled(const methodHandle& method);
316 
317   static void set_c1_count(int x) { _c1_count = x;    }
318   static void set_c2_count(int x) { _c2_count = x;    }
319   static void set_ac_count(int x) { _ac_count = x;    }
320 
321   enum EventType { CALL, LOOP, COMPILE, FORCE_COMPILE, FORCE_RECOMPILE, REMOVE_FROM_QUEUE, UPDATE_IN_QUEUE, REPROFILE, MAKE_NOT_ENTRANT };
322   static void print_event_on(outputStream *st, EventType type, Method* m, Method* im, int bci, CompLevel level);
323   static void print_event(EventType type, Method* m, Method* im, int bci, CompLevel level);
324   // Check if the method can be compiled, change level if necessary
325   static void compile(const methodHandle& mh, int bci, CompLevel level, TRAPS);
326   // Simple methods are as good being compiled with C1 as C2.
327   // This function tells if it's such a function.
328   inline static bool is_trivial(const methodHandle& method);
329   // Force method to be compiled at CompLevel_simple?
330   inline static bool force_comp_at_level_simple(const methodHandle& method);
331 
332   // Get a compilation level for a given method.
333   static CompLevel comp_level(Method* method);
334   static void method_invocation_event(const methodHandle& method, const methodHandle& inlinee,
335                                       CompLevel level, nmethod* nm, TRAPS);
336   static void method_back_branch_event(const methodHandle& method, const methodHandle& inlinee,
337                                       int bci, CompLevel level, nmethod* nm, TRAPS);
338 
339   static void set_increase_threshold_at_ratio() { _increase_threshold_at_ratio = 100 / (100 - (double)IncreaseFirstTierCompileThresholdAt); }
340   static void set_start_time(int64_t t) { _start_time = t;    }
341   static int64_t start_time()           { return _start_time; }
342 
343   // m must be compiled before executing it
344   static bool must_be_compiled(const methodHandle& m, int comp_level = CompLevel_any);
345   static void maybe_compile_early(const methodHandle& m, TRAPS);
346   static void replay_training_at_init_impl(InstanceKlass* klass, JavaThread* current);
347  public:
348   static int min_invocations() { return Tier4MinInvocationThreshold; }
349   static int c1_count() { return _c1_count; }
350   static int c2_count() { return _c2_count; }
351   static int ac_count() { return _ac_count; }
352   static int compiler_count(CompLevel comp_level);
353   // If m must_be_compiled then request a compilation from the CompileBroker.
354   // This supports the -Xcomp option.
355   static void compile_if_required(const methodHandle& m, TRAPS);
356 
357   static void replay_training_at_init(InstanceKlass* klass, JavaThread* current);
358   static void replay_training_at_init_loop(JavaThread* current);
359 
360   // m is allowed to be compiled
361   static bool can_be_compiled(const methodHandle& m, int comp_level = CompLevel_any);
362   // m is allowed to be osr compiled
363   static bool can_be_osr_compiled(const methodHandle& m, int comp_level = CompLevel_any);
364   static bool is_compilation_enabled();
365 
366   static CompileTask* select_task_helper(CompileQueue* compile_queue);
367   // Return initial compile level to use with Xcomp (depends on compilation mode).
368   static void reprofile(ScopeDesc* trap_scope, bool is_osr);
369   static nmethod* event(const methodHandle& method, const methodHandle& inlinee,
370                         int branch_bci, int bci, CompLevel comp_level, nmethod* nm, TRAPS);
371   // Select task is called by CompileBroker. We should return a task or nullptr.
372   static CompileTask* select_task(CompileQueue* compile_queue, JavaThread* THREAD);
373   // Tell the runtime if we think a given method is adequately profiled.
374   static bool is_mature(MethodData* mdo);
375   // Initialize: set compiler thread count
376   static void initialize();
377   static bool should_not_inline(ciEnv* env, ciMethod* callee);
378 
379   // Return desired initial compilation level for Xcomp
380   static CompLevel initial_compile_level(const methodHandle& method);
381   // Return highest level possible
382   static CompLevel highest_compile_level();
383   static void dump();
384 
385   static void sample_load_average();
386   static bool have_recompilation_work();
387   static bool recompilation_step(int step, TRAPS);
388 };
389 
390 #endif // SHARE_COMPILER_COMPILATIONPOLICY_HPP