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