1 /*
2 * Copyright (c) 1998, 2026, 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_OPTO_LOOPNODE_HPP
26 #define SHARE_OPTO_LOOPNODE_HPP
27
28 #include "opto/cfgnode.hpp"
29 #include "opto/multnode.hpp"
30 #include "opto/phaseX.hpp"
31 #include "opto/predicates.hpp"
32 #include "opto/subnode.hpp"
33 #include "opto/type.hpp"
34 #include "utilities/checkedCast.hpp"
35
36 class CmpNode;
37 class BaseCountedLoopEndNode;
38 class CountedLoopNode;
39 class IdealLoopTree;
40 class LoopNode;
41 class Node;
42 class OuterStripMinedLoopEndNode;
43 class PredicateBlock;
44 class PathFrequency;
45 class PhaseIdealLoop;
46 class UnswitchCandidate;
47 class LoopSelector;
48 class UnswitchedLoopSelector;
49 class VectorSet;
50 class VSharedData;
51 class Invariance;
52 struct small_cache;
53
54 //
55 // I D E A L I Z E D L O O P S
56 //
57 // Idealized loops are the set of loops I perform more interesting
58 // transformations on, beyond simple hoisting.
59
60 //------------------------------LoopNode---------------------------------------
61 // Simple loop header. Fall in path on left, loop-back path on right.
62 class LoopNode : public RegionNode {
63 // Size is bigger to hold the flags. However, the flags do not change
64 // the semantics so it does not appear in the hash & cmp functions.
65 virtual uint size_of() const { return sizeof(*this); }
66 protected:
67 uint _loop_flags;
68 // Names for flag bitfields
69 enum { Normal=0, Pre=1, Main=2, Post=3, PreMainPostFlagsMask=3,
70 MainHasNoPreLoop = 1<<2,
71 HasExactTripCount = 1<<3,
72 InnerLoop = 1<<4,
73 PartialPeelLoop = 1<<5,
74 PartialPeelFailed = 1<<6,
75 WasSlpAnalyzed = 1<<7,
76 PassedSlpAnalysis = 1<<8,
77 DoUnrollOnly = 1<<9,
78 VectorizedLoop = 1<<10,
79 HasAtomicPostLoop = 1<<11,
80 StripMined = 1<<12,
81 SubwordLoop = 1<<13,
82 ProfileTripFailed = 1<<14,
83 LoopNestInnerLoop = 1<<15,
84 LoopNestLongOuterLoop = 1<<16,
85 MultiversionFastLoop = 1<<17,
86 MultiversionSlowLoop = 2<<17,
87 MultiversionDelayedSlowLoop = 3<<17,
88 MultiversionFlagsMask = 3<<17,
89 FlatArrays = 1<<18};
90 char _unswitch_count;
91 enum { _unswitch_max=3 };
92
93 // Expected trip count from profile data
94 float _profile_trip_cnt;
95
96 public:
97 // Names for edge indices
98 enum { Self=0, EntryControl, LoopBackControl };
99
100 bool is_inner_loop() const { return _loop_flags & InnerLoop; }
101 void set_inner_loop() { _loop_flags |= InnerLoop; }
102
103 bool is_vectorized_loop() const { return _loop_flags & VectorizedLoop; }
104 bool is_partial_peel_loop() const { return _loop_flags & PartialPeelLoop; }
105 void set_partial_peel_loop() { _loop_flags |= PartialPeelLoop; }
106 bool partial_peel_has_failed() const { return _loop_flags & PartialPeelFailed; }
107 bool is_strip_mined() const { return _loop_flags & StripMined; }
108 bool is_profile_trip_failed() const { return _loop_flags & ProfileTripFailed; }
109 bool is_subword_loop() const { return _loop_flags & SubwordLoop; }
110 bool is_loop_nest_inner_loop() const { return _loop_flags & LoopNestInnerLoop; }
111 bool is_loop_nest_outer_loop() const { return _loop_flags & LoopNestLongOuterLoop; }
112 bool is_flat_arrays() const { return _loop_flags & FlatArrays; }
113
114 void mark_partial_peel_failed() { _loop_flags |= PartialPeelFailed; }
115 void mark_was_slp() { _loop_flags |= WasSlpAnalyzed; }
116 void mark_passed_slp() { _loop_flags |= PassedSlpAnalysis; }
117 void mark_do_unroll_only() { _loop_flags |= DoUnrollOnly; }
118 void mark_loop_vectorized() { _loop_flags |= VectorizedLoop; }
119 void mark_has_atomic_post_loop() { _loop_flags |= HasAtomicPostLoop; }
120 void mark_strip_mined() { _loop_flags |= StripMined; }
121 void clear_strip_mined() { _loop_flags &= ~StripMined; }
122 void mark_profile_trip_failed() { _loop_flags |= ProfileTripFailed; }
123 void mark_subword_loop() { _loop_flags |= SubwordLoop; }
124 void mark_loop_nest_inner_loop() { _loop_flags |= LoopNestInnerLoop; }
125 void mark_loop_nest_outer_loop() { _loop_flags |= LoopNestLongOuterLoop; }
126 void mark_flat_arrays() { _loop_flags |= FlatArrays; }
127
128 int unswitch_max() { return _unswitch_max; }
129 int unswitch_count() { return _unswitch_count; }
130
131 void set_unswitch_count(int val) {
132 assert (val <= unswitch_max(), "too many unswitches");
133 _unswitch_count = val;
134 }
135
136 void set_profile_trip_cnt(float ptc) { _profile_trip_cnt = ptc; }
137 float profile_trip_cnt() { return _profile_trip_cnt; }
138
139 #ifndef PRODUCT
140 uint _stress_peeling_attempts = 0;
141 #endif
142
143 LoopNode(Node *entry, Node *backedge)
144 : RegionNode(3), _loop_flags(0), _unswitch_count(0),
145 _profile_trip_cnt(COUNT_UNKNOWN) {
146 init_class_id(Class_Loop);
147 init_req(EntryControl, entry);
148 init_req(LoopBackControl, backedge);
149 }
150
151 virtual Node *Ideal(PhaseGVN *phase, bool can_reshape);
152 virtual int Opcode() const;
153 bool can_be_counted_loop(PhaseValues* phase) const {
154 return req() == 3 && in(0) != nullptr &&
155 in(1) != nullptr && phase->type(in(1)) != Type::TOP &&
156 in(2) != nullptr && phase->type(in(2)) != Type::TOP;
157 }
158 bool is_valid_counted_loop(BasicType bt) const;
159 #ifndef PRODUCT
160 virtual void dump_spec(outputStream *st) const;
161 #endif
162
163 void verify_strip_mined(int expect_skeleton) const NOT_DEBUG_RETURN;
164 virtual LoopNode* skip_strip_mined(int expect_skeleton = 1) { return this; }
165 virtual IfTrueNode* outer_loop_tail() const { ShouldNotReachHere(); return nullptr; }
166 virtual OuterStripMinedLoopEndNode* outer_loop_end() const { ShouldNotReachHere(); return nullptr; }
167 virtual IfFalseNode* outer_loop_exit() const { ShouldNotReachHere(); return nullptr; }
168 virtual SafePointNode* outer_safepoint() const { ShouldNotReachHere(); return nullptr; }
169 };
170
171 //------------------------------Counted Loops----------------------------------
172 // Counted loops are all trip-counted loops, with exactly 1 trip-counter exit
173 // path (and maybe some other exit paths). The trip-counter exit is always
174 // last in the loop. The trip-counter have to stride by a constant;
175 // the exit value is also loop invariant.
176
177 // CountedLoopNodes and CountedLoopEndNodes come in matched pairs. The
178 // CountedLoopNode has the incoming loop control and the loop-back-control
179 // which is always the IfTrue before the matching CountedLoopEndNode. The
180 // CountedLoopEndNode has an incoming control (possibly not the
181 // CountedLoopNode if there is control flow in the loop), the post-increment
182 // trip-counter value, and the limit. The trip-counter value is always of
183 // the form (Op old-trip-counter stride). The old-trip-counter is produced
184 // by a Phi connected to the CountedLoopNode. The stride is constant.
185 // The Op is any commutable opcode, including Add, Mul, Xor. The
186 // CountedLoopEndNode also takes in the loop-invariant limit value.
187
188 // From a CountedLoopNode I can reach the matching CountedLoopEndNode via the
189 // loop-back control. From CountedLoopEndNodes I can reach CountedLoopNodes
190 // via the old-trip-counter from the Op node.
191
192 //------------------------------CountedLoopNode--------------------------------
193 // CountedLoopNodes head simple counted loops. CountedLoopNodes have as
194 // inputs the incoming loop-start control and the loop-back control, so they
195 // act like RegionNodes. They also take in the initial trip counter, the
196 // loop-invariant stride and the loop-invariant limit value. CountedLoopNodes
197 // produce a loop-body control and the trip counter value. Since
198 // CountedLoopNodes behave like RegionNodes I still have a standard CFG model.
199
200 class BaseCountedLoopNode : public LoopNode {
201 public:
202 BaseCountedLoopNode(Node *entry, Node *backedge)
203 : LoopNode(entry, backedge) {
204 }
205
206 Node *init_control() const { return in(EntryControl); }
207 Node *back_control() const { return in(LoopBackControl); }
208
209 Node* init_trip() const;
210 Node* stride() const;
211 bool stride_is_con() const;
212 Node* limit() const;
213 Node* incr() const;
214 Node* phi() const;
215
216 BaseCountedLoopEndNode* loopexit_or_null() const;
217 BaseCountedLoopEndNode* loopexit() const;
218
219 virtual BasicType bt() const = 0;
220
221 jlong stride_con() const;
222
223 static BaseCountedLoopNode* make(Node* entry, Node* backedge, BasicType bt);
224
225 virtual void set_trip_count(julong tc) = 0;
226 virtual julong trip_count() const = 0;
227
228 bool has_exact_trip_count() const { return (_loop_flags & HasExactTripCount) != 0; }
229 void set_exact_trip_count(julong tc) {
230 set_trip_count(tc);
231 _loop_flags |= HasExactTripCount;
232 }
233 void set_nonexact_trip_count() {
234 _loop_flags &= ~HasExactTripCount;
235 }
236 };
237
238
239 class CountedLoopNode : public BaseCountedLoopNode {
240 // Size is bigger to hold _main_idx. However, _main_idx does not change
241 // the semantics so it does not appear in the hash & cmp functions.
242 virtual uint size_of() const { return sizeof(*this); }
243
244 // For Pre- and Post-loops during debugging ONLY, this holds the index of
245 // the Main CountedLoop. Used to assert that we understand the graph shape.
246 node_idx_t _main_idx;
247
248 // Known trip count calculated by compute_exact_trip_count()
249 uint _trip_count;
250
251 // Log2 of original loop bodies in unrolled loop
252 int _unrolled_count_log2;
253
254 // Node count prior to last unrolling - used to decide if
255 // unroll,optimize,unroll,optimize,... is making progress
256 int _node_count_before_unroll;
257
258 // If slp analysis is performed we record the maximum
259 // vector mapped unroll factor here
260 int _slp_maximum_unroll_factor;
261
262 public:
263 CountedLoopNode(Node *entry, Node *backedge)
264 : BaseCountedLoopNode(entry, backedge), _main_idx(0), _trip_count(max_juint),
265 _unrolled_count_log2(0), _node_count_before_unroll(0),
266 _slp_maximum_unroll_factor(0) {
267 init_class_id(Class_CountedLoop);
268 // Initialize _trip_count to the largest possible value.
269 // Will be reset (lower) if the loop's trip count is known.
270 }
271
272 virtual int Opcode() const;
273 virtual Node *Ideal(PhaseGVN *phase, bool can_reshape);
274
275 CountedLoopEndNode* loopexit_or_null() const { return (CountedLoopEndNode*) BaseCountedLoopNode::loopexit_or_null(); }
276 CountedLoopEndNode* loopexit() const { return (CountedLoopEndNode*) BaseCountedLoopNode::loopexit(); }
277 int stride_con() const;
278
279 // A 'main' loop has a pre-loop and a post-loop. The 'main' loop
280 // can run short a few iterations and may start a few iterations in.
281 // It will be RCE'd and unrolled and aligned.
282
283 // A following 'post' loop will run any remaining iterations. Used
284 // during Range Check Elimination, the 'post' loop will do any final
285 // iterations with full checks. Also used by Loop Unrolling, where
286 // the 'post' loop will do any epilog iterations needed. Basically,
287 // a 'post' loop can not profitably be further unrolled or RCE'd.
288
289 // A preceding 'pre' loop will run at least 1 iteration (to do peeling),
290 // it may do under-flow checks for RCE and may do alignment iterations
291 // so the following main loop 'knows' that it is striding down cache
292 // lines.
293
294 // A 'main' loop that is ONLY unrolled or peeled, never RCE'd or
295 // Aligned, may be missing it's pre-loop.
296 bool is_normal_loop () const { return (_loop_flags&PreMainPostFlagsMask) == Normal; }
297 bool is_pre_loop () const { return (_loop_flags&PreMainPostFlagsMask) == Pre; }
298 bool is_main_loop () const { return (_loop_flags&PreMainPostFlagsMask) == Main; }
299 bool is_post_loop () const { return (_loop_flags&PreMainPostFlagsMask) == Post; }
300 bool was_slp_analyzed () const { return (_loop_flags&WasSlpAnalyzed) == WasSlpAnalyzed; }
301 bool has_passed_slp () const { return (_loop_flags&PassedSlpAnalysis) == PassedSlpAnalysis; }
302 bool is_unroll_only () const { return (_loop_flags&DoUnrollOnly) == DoUnrollOnly; }
303 bool is_main_no_pre_loop() const { return _loop_flags & MainHasNoPreLoop; }
304 bool has_atomic_post_loop () const { return (_loop_flags & HasAtomicPostLoop) == HasAtomicPostLoop; }
305 void set_main_no_pre_loop() { _loop_flags |= MainHasNoPreLoop; }
306
307 IfNode* find_multiversion_if_from_multiversion_fast_main_loop();
308
309 int main_idx() const { return _main_idx; }
310
311 void set_trip_count(julong tc) {
312 assert(tc < max_juint, "Cannot set trip count to max_juint");
313 _trip_count = checked_cast<uint>(tc);
314 }
315 julong trip_count() const { return _trip_count; }
316
317 void set_pre_loop (CountedLoopNode *main) { assert(is_normal_loop(),""); _loop_flags |= Pre ; _main_idx = main->_idx; }
318 void set_main_loop ( ) { assert(is_normal_loop(),""); _loop_flags |= Main; }
319 void set_post_loop (CountedLoopNode *main) { assert(is_normal_loop(),""); _loop_flags |= Post; _main_idx = main->_idx; }
320 void set_normal_loop( ) { _loop_flags &= ~PreMainPostFlagsMask; }
321
322 void set_notpassed_slp() {
323 _loop_flags &= ~PassedSlpAnalysis;
324 }
325
326 void double_unrolled_count() { _unrolled_count_log2++; }
327 int unrolled_count() { return 1 << MIN2(_unrolled_count_log2, BitsPerInt-3); }
328
329 void set_node_count_before_unroll(int ct) { _node_count_before_unroll = ct; }
330 int node_count_before_unroll() { return _node_count_before_unroll; }
331 void set_slp_max_unroll(int unroll_factor) { _slp_maximum_unroll_factor = unroll_factor; }
332 int slp_max_unroll() const { return _slp_maximum_unroll_factor; }
333
334 // Multiversioning allows us to duplicate a CountedLoop, and have two versions, and the multiversion_if
335 // decides which one is taken:
336 // (1) fast_loop: We enter this loop by default, by default the multiversion_if has its condition set to
337 // "true", guarded by a OpaqueMultiversioning. If we want to make a speculative assumption
338 // for an optimization, we can add the runtime-check to the multiversion_if, and if the
339 // assumption fails we take the slow_loop instead, where we do not make the same speculative
340 // assumption.
341 // We call it the "fast_loop" because it has more optimizations, enabled by the speculative
342 // runtime-checks at the multiversion_if, and we expect the fast_loop to execute faster.
343 // (2) slow_loop: By default, it is not taken, until a runtime-check is added to the multiversion_if while
344 // optimizing the fast_looop. If such a runtime-check is never added, then after loop-opts
345 // the multiversion_if constant folds to true, and the slow_loop is folded away. To save
346 // compile time, we delay the optimization of the slow_loop until a runtime-check is added
347 // to the multiversion_if, at which point we resume optimizations for the slow_loop.
348 // We call it the "slow_loop" because it has fewer optimizations, since this is the fall-back
349 // loop where we do not make any of the speculative assumptions we make for the fast_loop.
350 // Hence, we expect the slow_loop to execute slower.
351 bool is_multiversion() const { return (_loop_flags & MultiversionFlagsMask) != Normal; }
352 bool is_multiversion_fast_loop() const { return (_loop_flags & MultiversionFlagsMask) == MultiversionFastLoop; }
353 bool is_multiversion_slow_loop() const { return (_loop_flags & MultiversionFlagsMask) == MultiversionSlowLoop; }
354 bool is_multiversion_delayed_slow_loop() const { return (_loop_flags & MultiversionFlagsMask) == MultiversionDelayedSlowLoop; }
355 void set_multiversion_fast_loop() { assert(!is_multiversion(), ""); _loop_flags |= MultiversionFastLoop; }
356 void set_multiversion_slow_loop() { assert(!is_multiversion(), ""); _loop_flags |= MultiversionSlowLoop; }
357 void set_multiversion_delayed_slow_loop() { assert(!is_multiversion(), ""); _loop_flags |= MultiversionDelayedSlowLoop; }
358 void set_no_multiversion() { assert( is_multiversion(), ""); _loop_flags &= ~MultiversionFlagsMask; }
359
360 virtual LoopNode* skip_strip_mined(int expect_skeleton = 1);
361 OuterStripMinedLoopNode* outer_loop() const;
362 virtual IfTrueNode* outer_loop_tail() const;
363 virtual OuterStripMinedLoopEndNode* outer_loop_end() const;
364 virtual IfFalseNode* outer_loop_exit() const;
365 virtual SafePointNode* outer_safepoint() const;
366
367 Node* skip_assertion_predicates_with_halt();
368
369 virtual BasicType bt() const {
370 return T_INT;
371 }
372
373 Node* is_canonical_loop_entry();
374 CountedLoopEndNode* find_pre_loop_end();
375
376 Node* uncasted_init_trip(bool uncasted);
377
378 #ifndef PRODUCT
379 virtual void dump_spec(outputStream *st) const;
380 #endif
381 };
382
383 class LongCountedLoopNode : public BaseCountedLoopNode {
384 private:
385 virtual uint size_of() const { return sizeof(*this); }
386
387 // Known trip count calculated by compute_exact_trip_count()
388 julong _trip_count;
389
390 public:
391 LongCountedLoopNode(Node *entry, Node *backedge)
392 : BaseCountedLoopNode(entry, backedge), _trip_count(max_julong) {
393 init_class_id(Class_LongCountedLoop);
394 }
395
396 virtual int Opcode() const;
397
398 virtual BasicType bt() const {
399 return T_LONG;
400 }
401
402 void set_trip_count(julong tc) {
403 assert(tc < max_julong, "Cannot set trip count to max_julong");
404 _trip_count = tc;
405 }
406 julong trip_count() const { return _trip_count; }
407
408 LongCountedLoopEndNode* loopexit_or_null() const { return (LongCountedLoopEndNode*) BaseCountedLoopNode::loopexit_or_null(); }
409 LongCountedLoopEndNode* loopexit() const { return (LongCountedLoopEndNode*) BaseCountedLoopNode::loopexit(); }
410 };
411
412
413 //------------------------------CountedLoopEndNode-----------------------------
414 // CountedLoopEndNodes end simple trip counted loops. They act much like
415 // IfNodes.
416
417 class BaseCountedLoopEndNode : public IfNode {
418 public:
419 enum { TestControl, TestValue };
420 BaseCountedLoopEndNode(Node *control, Node *test, float prob, float cnt)
421 : IfNode(control, test, prob, cnt) {
422 init_class_id(Class_BaseCountedLoopEnd);
423 }
424
425 Node *cmp_node() const { return (in(TestValue)->req() >=2) ? in(TestValue)->in(1) : nullptr; }
426 Node* incr() const { Node* tmp = cmp_node(); return (tmp && tmp->req() == 3) ? tmp->in(1) : nullptr; }
427 Node* limit() const { Node* tmp = cmp_node(); return (tmp && tmp->req() == 3) ? tmp->in(2) : nullptr; }
428 Node* stride() const { Node* tmp = incr(); return (tmp && tmp->req() == 3) ? tmp->in(2) : nullptr; }
429 Node* init_trip() const { Node* tmp = phi(); return (tmp && tmp->req() == 3) ? tmp->in(1) : nullptr; }
430 bool stride_is_con() const { Node *tmp = stride(); return (tmp != nullptr && tmp->is_Con()); }
431
432 PhiNode* phi() const {
433 Node* tmp = incr();
434 if (tmp && tmp->req() == 3) {
435 Node* phi = tmp->in(1);
436 if (phi->is_Phi()) {
437 return phi->as_Phi();
438 }
439 }
440 return nullptr;
441 }
442
443 BaseCountedLoopNode* loopnode() const {
444 // The CountedLoopNode that goes with this CountedLoopEndNode may
445 // have been optimized out by the IGVN so be cautious with the
446 // pattern matching on the graph
447 PhiNode* iv_phi = phi();
448 if (iv_phi == nullptr) {
449 return nullptr;
450 }
451 Node* ln = iv_phi->in(0);
452 if (!ln->is_BaseCountedLoop() || ln->as_BaseCountedLoop()->loopexit_or_null() != this) {
453 return nullptr;
454 }
455 if (ln->as_BaseCountedLoop()->bt() != bt()) {
456 return nullptr;
457 }
458 return ln->as_BaseCountedLoop();
459 }
460
461 BoolTest::mask test_trip() const { return in(TestValue)->as_Bool()->_test._test; }
462
463 jlong stride_con() const;
464 virtual BasicType bt() const = 0;
465
466 static BaseCountedLoopEndNode* make(Node* control, Node* test, float prob, float cnt, BasicType bt);
467 };
468
469 class CountedLoopEndNode : public BaseCountedLoopEndNode {
470 public:
471
472 CountedLoopEndNode(Node *control, Node *test, float prob, float cnt)
473 : BaseCountedLoopEndNode(control, test, prob, cnt) {
474 init_class_id(Class_CountedLoopEnd);
475 }
476 virtual int Opcode() const;
477
478 CountedLoopNode* loopnode() const {
479 return (CountedLoopNode*) BaseCountedLoopEndNode::loopnode();
480 }
481
482 virtual BasicType bt() const {
483 return T_INT;
484 }
485
486 #ifndef PRODUCT
487 virtual void dump_spec(outputStream *st) const;
488 #endif
489 };
490
491 class LongCountedLoopEndNode : public BaseCountedLoopEndNode {
492 public:
493 LongCountedLoopEndNode(Node *control, Node *test, float prob, float cnt)
494 : BaseCountedLoopEndNode(control, test, prob, cnt) {
495 init_class_id(Class_LongCountedLoopEnd);
496 }
497
498 LongCountedLoopNode* loopnode() const {
499 return (LongCountedLoopNode*) BaseCountedLoopEndNode::loopnode();
500 }
501
502 virtual int Opcode() const;
503
504 virtual BasicType bt() const {
505 return T_LONG;
506 }
507 };
508
509
510 inline BaseCountedLoopEndNode* BaseCountedLoopNode::loopexit_or_null() const {
511 Node* bctrl = back_control();
512 if (bctrl == nullptr) return nullptr;
513
514 Node* lexit = bctrl->in(0);
515 if (!lexit->is_BaseCountedLoopEnd()) {
516 return nullptr;
517 }
518 BaseCountedLoopEndNode* result = lexit->as_BaseCountedLoopEnd();
519 if (result->bt() != bt()) {
520 return nullptr;
521 }
522 return result;
523 }
524
525 inline BaseCountedLoopEndNode* BaseCountedLoopNode::loopexit() const {
526 BaseCountedLoopEndNode* cle = loopexit_or_null();
527 assert(cle != nullptr, "loopexit is null");
528 return cle;
529 }
530
531 inline Node* BaseCountedLoopNode::init_trip() const {
532 BaseCountedLoopEndNode* cle = loopexit_or_null();
533 return cle != nullptr ? cle->init_trip() : nullptr;
534 }
535 inline Node* BaseCountedLoopNode::stride() const {
536 BaseCountedLoopEndNode* cle = loopexit_or_null();
537 return cle != nullptr ? cle->stride() : nullptr;
538 }
539
540 inline bool BaseCountedLoopNode::stride_is_con() const {
541 BaseCountedLoopEndNode* cle = loopexit_or_null();
542 return cle != nullptr && cle->stride_is_con();
543 }
544 inline Node* BaseCountedLoopNode::limit() const {
545 BaseCountedLoopEndNode* cle = loopexit_or_null();
546 return cle != nullptr ? cle->limit() : nullptr;
547 }
548 inline Node* BaseCountedLoopNode::incr() const {
549 BaseCountedLoopEndNode* cle = loopexit_or_null();
550 return cle != nullptr ? cle->incr() : nullptr;
551 }
552 inline Node* BaseCountedLoopNode::phi() const {
553 BaseCountedLoopEndNode* cle = loopexit_or_null();
554 return cle != nullptr ? cle->phi() : nullptr;
555 }
556
557 inline jlong BaseCountedLoopNode::stride_con() const {
558 BaseCountedLoopEndNode* cle = loopexit_or_null();
559 return cle != nullptr ? cle->stride_con() : 0;
560 }
561
562
563 //------------------------------LoopLimitNode-----------------------------
564 // Counted Loop limit node which represents exact final iterator value:
565 // trip_count = (limit - init_trip + stride - 1)/stride
566 // final_value= trip_count * stride + init_trip.
567 // Use HW instructions to calculate it when it can overflow in integer.
568 // Note, final_value should fit into integer since counted loop has
569 // limit check: limit <= max_int-stride.
570 class LoopLimitNode : public Node {
571 enum { Init=1, Limit=2, Stride=3 };
572 public:
573 LoopLimitNode( Compile* C, Node *init, Node *limit, Node *stride ) : Node(nullptr,init,limit,stride) {
574 // Put it on the Macro nodes list to optimize during macro nodes expansion.
575 init_flags(Flag_is_macro);
576 C->add_macro_node(this);
577 }
578 virtual int Opcode() const;
579 virtual const Type *bottom_type() const { return TypeInt::INT; }
580 virtual uint ideal_reg() const { return Op_RegI; }
581 virtual const Type* Value(PhaseGVN* phase) const;
582 virtual Node *Ideal(PhaseGVN *phase, bool can_reshape);
583 virtual Node* Identity(PhaseGVN* phase);
584 };
585
586 // Support for strip mining
587 class OuterStripMinedLoopNode : public LoopNode {
588 private:
589 void fix_sunk_stores_when_back_to_counted_loop(PhaseIterGVN* igvn, PhaseIdealLoop* iloop) const;
590 void handle_sunk_stores_when_finishing_construction(PhaseIterGVN* igvn);
591
592 public:
593 OuterStripMinedLoopNode(Compile* C, Node *entry, Node *backedge)
594 : LoopNode(entry, backedge) {
595 init_class_id(Class_OuterStripMinedLoop);
596 init_flags(Flag_is_macro);
597 C->add_macro_node(this);
598 }
599
600 virtual int Opcode() const;
601
602 virtual IfTrueNode* outer_loop_tail() const;
603 virtual OuterStripMinedLoopEndNode* outer_loop_end() const;
604 virtual IfFalseNode* outer_loop_exit() const;
605 virtual SafePointNode* outer_safepoint() const;
606 CountedLoopNode* inner_counted_loop() const { return unique_ctrl_out()->as_CountedLoop(); }
607 CountedLoopEndNode* inner_counted_loop_end() const { return inner_counted_loop()->loopexit(); }
608 IfFalseNode* inner_loop_exit() const { return inner_counted_loop_end()->false_proj(); }
609
610 void adjust_strip_mined_loop(PhaseIterGVN* igvn);
611
612 void remove_outer_loop_and_safepoint(PhaseIterGVN* igvn) const;
613
614 void transform_to_counted_loop(PhaseIterGVN* igvn, PhaseIdealLoop* iloop);
615
616 static Node* register_new_node(Node* node, LoopNode* ctrl, PhaseIterGVN* igvn, PhaseIdealLoop* iloop);
617
618 Node* register_control(Node* node, Node* loop, Node* idom, PhaseIterGVN* igvn,
619 PhaseIdealLoop* iloop);
620 };
621
622 class OuterStripMinedLoopEndNode : public IfNode {
623 public:
624 OuterStripMinedLoopEndNode(Node *control, Node *test, float prob, float cnt)
625 : IfNode(control, test, prob, cnt) {
626 init_class_id(Class_OuterStripMinedLoopEnd);
627 }
628
629 virtual int Opcode() const;
630
631 virtual const Type* Value(PhaseGVN* phase) const;
632 virtual Node *Ideal(PhaseGVN *phase, bool can_reshape);
633
634 bool is_expanded(PhaseGVN *phase) const;
635 };
636
637 // -----------------------------IdealLoopTree----------------------------------
638 class IdealLoopTree : public ResourceObj {
639 public:
640 IdealLoopTree *_parent; // Parent in loop tree
641 IdealLoopTree *_next; // Next sibling in loop tree
642 IdealLoopTree *_child; // First child in loop tree
643
644 // The head-tail backedge defines the loop.
645 // If a loop has multiple backedges, this is addressed during cleanup where
646 // we peel off the multiple backedges, merging all edges at the bottom and
647 // ensuring that one proper backedge flow into the loop.
648 Node *_head; // Head of loop
649 Node *_tail; // Tail of loop
650 inline Node *tail(); // Handle lazy update of _tail field
651 inline Node *head(); // Handle lazy update of _head field
652 PhaseIdealLoop* _phase;
653 int _local_loop_unroll_limit;
654 int _local_loop_unroll_factor;
655
656 Node_List _body; // Loop body for inner loops
657
658 uint16_t _nest; // Nesting depth
659 uint8_t _irreducible:1, // True if irreducible
660 _has_call:1, // True if has call safepoint
661 _has_sfpt:1, // True if has non-call safepoint
662 _rce_candidate:1, // True if candidate for range check elimination
663 _has_range_checks:1,
664 _has_range_checks_computed:1;
665
666 Node_List* _safepts; // List of safepoints in this loop
667 Node_List* _required_safept; // A inner loop cannot delete these safepts;
668 bool _allow_optimizations; // Allow loop optimizations
669
670 IdealLoopTree(PhaseIdealLoop* phase, Node* head, Node* tail);
671
672 // Is 'l' a member of 'this'?
673 bool is_member(const IdealLoopTree *l) const; // Test for nested membership
674
675 // Set loop nesting depth. Accumulate has_call bits.
676 int set_nest( uint depth );
677
678 // Split out multiple fall-in edges from the loop header. Move them to a
679 // private RegionNode before the loop. This becomes the loop landing pad.
680 void split_fall_in( PhaseIdealLoop *phase, int fall_in_cnt );
681
682 // Split out the outermost loop from this shared header.
683 void split_outer_loop( PhaseIdealLoop *phase );
684
685 // Merge all the backedges from the shared header into a private Region.
686 // Feed that region as the one backedge to this loop.
687 void merge_many_backedges( PhaseIdealLoop *phase );
688
689 // Split shared headers and insert loop landing pads.
690 // Insert a LoopNode to replace the RegionNode.
691 // Returns TRUE if loop tree is structurally changed.
692 bool beautify_loops( PhaseIdealLoop *phase );
693
694 // Perform optimization to use the loop predicates for null checks and range checks.
695 // Applies to any loop level (not just the innermost one)
696 bool loop_predication( PhaseIdealLoop *phase);
697 bool can_apply_loop_predication();
698
699 // Perform iteration-splitting on inner loops. Split iterations to
700 // avoid range checks or one-shot null checks. Returns false if the
701 // current round of loop opts should stop.
702 bool iteration_split( PhaseIdealLoop *phase, Node_List &old_new );
703
704 // Driver for various flavors of iteration splitting. Returns false
705 // if the current round of loop opts should stop.
706 bool iteration_split_impl( PhaseIdealLoop *phase, Node_List &old_new );
707
708 // Given dominators, try to find loops with calls that must always be
709 // executed (call dominates loop tail). These loops do not need non-call
710 // safepoints (ncsfpt).
711 void check_safepts(VectorSet &visited, Node_List &stack);
712
713 // Allpaths backwards scan from loop tail, terminating each path at first safepoint
714 // encountered.
715 void allpaths_check_safepts(VectorSet &visited, Node_List &stack);
716
717 // Remove safepoints from loop. Optionally keeping one.
718 void remove_safepoints(PhaseIdealLoop* phase, bool keep_one);
719
720 // Convert to counted loops where possible
721 void counted_loop( PhaseIdealLoop *phase );
722
723 // Check for Node being a loop-breaking test
724 Node *is_loop_exit(Node *iff) const;
725
726 // Remove simplistic dead code from loop body
727 void DCE_loop_body();
728
729 // Look for loop-exit tests with my 50/50 guesses from the Parsing stage.
730 // Replace with a 1-in-10 exit guess.
731 void adjust_loop_exit_prob( PhaseIdealLoop *phase );
732
733 // Return TRUE or FALSE if the loop should never be RCE'd or aligned.
734 // Useful for unrolling loops with NO array accesses.
735 bool policy_peel_only( PhaseIdealLoop *phase ) const;
736
737 // Return TRUE or FALSE if the loop should be unswitched -- clone
738 // loop with an invariant test
739 bool policy_unswitching( PhaseIdealLoop *phase ) const;
740 bool no_unswitch_candidate() const;
741
742 // Micro-benchmark spamming. Remove empty loops.
743 bool do_remove_empty_loop( PhaseIdealLoop *phase );
744
745 // Convert one-iteration loop into normal code.
746 bool do_one_iteration_loop( PhaseIdealLoop *phase );
747
748 // Return TRUE or FALSE if the loop should be peeled or not. Peel if we can
749 // move some loop-invariant test (usually a null-check) before the loop.
750 bool policy_peeling(PhaseIdealLoop *phase);
751
752 uint estimate_peeling(PhaseIdealLoop *phase);
753
754 // Return TRUE or FALSE if the loop should be maximally unrolled. Stash any
755 // known trip count in the counted loop node.
756 bool policy_maximally_unroll(PhaseIdealLoop *phase) const;
757
758 // Return TRUE or FALSE if the loop should be unrolled or not. Apply unroll
759 // if the loop is a counted loop and the loop body is small enough.
760 bool policy_unroll(PhaseIdealLoop *phase);
761
762 // Loop analyses to map to a maximal superword unrolling for vectorization.
763 void policy_unroll_slp_analysis(CountedLoopNode *cl, PhaseIdealLoop *phase, int future_unroll_ct);
764
765 // Return TRUE or FALSE if the loop should be range-check-eliminated.
766 // Gather a list of IF tests that are dominated by iteration splitting;
767 // also gather the end of the first split and the start of the 2nd split.
768 bool policy_range_check(PhaseIdealLoop* phase, bool provisional, BasicType bt) const;
769
770 // Return TRUE if "iff" is a range check.
771 bool is_range_check_if(IfProjNode* if_success_proj, PhaseIdealLoop* phase, Invariance& invar DEBUG_ONLY(COMMA ProjNode* predicate_proj)) const;
772 bool is_range_check_if(IfProjNode* if_success_proj, PhaseIdealLoop* phase, BasicType bt, Node* iv, Node*& range, Node*& offset,
773 jlong& scale) const;
774
775 // Estimate the number of nodes required when cloning a loop (body).
776 uint est_loop_clone_sz(uint factor) const;
777 // Estimate the number of nodes required when unrolling a loop (body).
778 uint est_loop_unroll_sz(uint factor) const;
779
780 // Compute loop trip count if possible
781 void compute_trip_count(PhaseIdealLoop* phase, BasicType bt);
782
783 // Compute loop trip count from profile data
784 float compute_profile_trip_cnt_helper(Node* n);
785 void compute_profile_trip_cnt( PhaseIdealLoop *phase );
786
787 // Reassociate invariant expressions.
788 void reassociate_invariants(PhaseIdealLoop *phase);
789 // Reassociate invariant binary expressions.
790 Node* reassociate(Node* n1, PhaseIdealLoop *phase);
791 // Reassociate invariant add, subtract, and compare expressions.
792 Node* reassociate_add_sub_cmp(Node* n1, int inv1_idx, int inv2_idx, PhaseIdealLoop* phase);
793 // Return nonzero index of invariant operand if invariant and variant
794 // are combined with an associative binary. Helper for reassociate_invariants.
795 int find_invariant(Node* n, PhaseIdealLoop *phase);
796 // Return TRUE if "n" is associative.
797 bool is_associative(Node* n, Node* base=nullptr);
798 // Return TRUE if "n" is an associative cmp node.
799 bool is_associative_cmp(Node* n);
800
801 // Return true if n is invariant
802 bool is_invariant(Node* n) const;
803
804 // Put loop body on igvn work list
805 void record_for_igvn();
806
807 bool is_root() { return _parent == nullptr; }
808 // A proper/reducible loop w/o any (occasional) dead back-edge.
809 bool is_loop() { return !_irreducible && !tail()->is_top(); }
810 bool is_counted() { return is_loop() && _head->is_CountedLoop(); }
811 bool is_innermost() { return is_loop() && _child == nullptr; }
812
813 void remove_main_post_loops(CountedLoopNode *cl, PhaseIdealLoop *phase);
814
815 bool compute_has_range_checks() const;
816 bool range_checks_present() {
817 if (!_has_range_checks_computed) {
818 if (compute_has_range_checks()) {
819 _has_range_checks = 1;
820 }
821 _has_range_checks_computed = 1;
822 }
823 return _has_range_checks;
824 }
825
826 // Return the parent's IdealLoopTree for a strip mined loop which is the outer strip mined loop.
827 // In all other cases, return this.
828 IdealLoopTree* skip_strip_mined() {
829 return _head->as_Loop()->is_strip_mined() ? _parent : this;
830 }
831
832 #ifndef PRODUCT
833 void dump_head(); // Dump loop head only
834 void dump(); // Dump this loop recursively
835 #endif
836
837 #ifdef ASSERT
838 GrowableArray<IdealLoopTree*> collect_sorted_children() const;
839 bool verify_tree(IdealLoopTree* loop_verify) const;
840 #endif
841
842 private:
843 enum { EMPTY_LOOP_SIZE = 7 }; // Number of nodes in an empty loop.
844
845 // Estimate the number of nodes resulting from control and data flow merge.
846 uint est_loop_flow_merge_sz() const;
847
848 // Check if the number of residual iterations is large with unroll_cnt.
849 // Return true if the residual iterations are more than 10% of the trip count.
850 bool is_residual_iters_large(int unroll_cnt, CountedLoopNode *cl) const {
851 return (unroll_cnt - 1) * (100.0 / LoopPercentProfileLimit) > cl->profile_trip_cnt();
852 }
853
854 void collect_loop_core_nodes(PhaseIdealLoop* phase, Unique_Node_List& wq) const;
855
856 bool empty_loop_with_data_nodes(PhaseIdealLoop* phase) const;
857
858 void enqueue_data_nodes(PhaseIdealLoop* phase, Unique_Node_List& empty_loop_nodes, Unique_Node_List& wq) const;
859
860 bool process_safepoint(PhaseIdealLoop* phase, Unique_Node_List& empty_loop_nodes, Unique_Node_List& wq,
861 Node* sfpt) const;
862
863 bool empty_loop_candidate(PhaseIdealLoop* phase) const;
864
865 bool empty_loop_with_extra_nodes_candidate(PhaseIdealLoop* phase) const;
866 };
867
868 // -----------------------------PhaseIdealLoop---------------------------------
869 // Computes the mapping from Nodes to IdealLoopTrees. Organizes IdealLoopTrees
870 // into a loop tree. Drives the loop-based transformations on the ideal graph.
871 class PhaseIdealLoop : public PhaseTransform {
872 friend class IdealLoopTree;
873 friend class SuperWord;
874 friend class ShenandoahBarrierC2Support;
875 friend class AutoNodeBudget;
876
877 Arena _arena; // For data whose lifetime is a single pass of loop optimizations
878
879 // Map loop membership for CFG nodes, and ctrl for non-CFG nodes.
880 //
881 // Exception: dead CFG nodes may instead have a ctrl/idom forwarding
882 // installed. See: forward_ctrl
883 Node_List _loop_or_ctrl;
884
885 // Pre-computed def-use info
886 PhaseIterGVN &_igvn;
887
888 // Head of loop tree
889 IdealLoopTree* _ltree_root;
890
891 // Array of pre-order numbers, plus post-visited bit.
892 // ZERO for not pre-visited. EVEN for pre-visited but not post-visited.
893 // ODD for post-visited. Other bits are the pre-order number.
894 uint *_preorders;
895 uint _max_preorder;
896
897 ReallocMark _nesting; // Safety checks for arena reallocation
898
899 const PhaseIdealLoop* _verify_me;
900 bool _verify_only;
901
902 // Allocate _preorders[] array
903 void allocate_preorders() {
904 _max_preorder = C->unique()+8;
905 _preorders = NEW_RESOURCE_ARRAY(uint, _max_preorder);
906 memset(_preorders, 0, sizeof(uint) * _max_preorder);
907 }
908
909 // Allocate _preorders[] array
910 void reallocate_preorders() {
911 _nesting.check(); // Check if a potential re-allocation in the resource arena is safe
912 if ( _max_preorder < C->unique() ) {
913 _preorders = REALLOC_RESOURCE_ARRAY(uint, _preorders, _max_preorder, C->unique());
914 _max_preorder = C->unique();
915 }
916 memset(_preorders, 0, sizeof(uint) * _max_preorder);
917 }
918
919 // Check to grow _preorders[] array for the case when build_loop_tree_impl()
920 // adds new nodes.
921 void check_grow_preorders( ) {
922 _nesting.check(); // Check if a potential re-allocation in the resource arena is safe
923 if ( _max_preorder < C->unique() ) {
924 uint newsize = _max_preorder<<1; // double size of array
925 _preorders = REALLOC_RESOURCE_ARRAY(uint, _preorders, _max_preorder, newsize);
926 memset(&_preorders[_max_preorder],0,sizeof(uint)*(newsize-_max_preorder));
927 _max_preorder = newsize;
928 }
929 }
930 // Check for pre-visited. Zero for NOT visited; non-zero for visited.
931 int is_visited( Node *n ) const { return _preorders[n->_idx]; }
932 // Pre-order numbers are written to the Nodes array as low-bit-set values.
933 void set_preorder_visited( Node *n, int pre_order ) {
934 assert( !is_visited( n ), "already set" );
935 _preorders[n->_idx] = (pre_order<<1);
936 };
937 // Return pre-order number.
938 int get_preorder( Node *n ) const { assert( is_visited(n), "" ); return _preorders[n->_idx]>>1; }
939
940 // Check for being post-visited.
941 // Should be previsited already (checked with assert(is_visited(n))).
942 int is_postvisited( Node *n ) const { assert( is_visited(n), "" ); return _preorders[n->_idx]&1; }
943
944 // Mark as post visited
945 void set_postvisited( Node *n ) { assert( !is_postvisited( n ), "" ); _preorders[n->_idx] |= 1; }
946
947 public:
948 // Set/get control node out. Set lower bit to distinguish from IdealLoopTree
949 // Returns true if "n" is a data node, false if it's a CFG node.
950 //
951 // Exception:
952 // control nodes that are dead because of "replace_node_and_forward_ctrl"
953 // or have otherwise modified their ctrl state by "forward_ctrl".
954 // They return "true", because they have a ctrl "forwarding" to the other ctrl node they
955 // were replaced with.
956 bool has_ctrl(const Node* n) const { return ((intptr_t)_loop_or_ctrl[n->_idx]) & 1; }
957
958 private:
959 // clear out dead code after build_loop_late
960 Node_List _deadlist;
961 Node_List _zero_trip_guard_opaque_nodes;
962 Node_List _multiversion_opaque_nodes;
963
964 // Support for faster execution of get_late_ctrl()/dom_lca()
965 // when a node has many uses and dominator depth is deep.
966 GrowableArray<jlong> _dom_lca_tags;
967 uint _dom_lca_tags_round;
968 void init_dom_lca_tags();
969
970 // Helper for debugging bad dominance relationships
971 bool verify_dominance(Node* n, Node* use, Node* LCA, Node* early);
972
973 Node* compute_lca_of_uses(Node* n, Node* early, bool verify = false);
974
975 // Inline wrapper for frequent cases:
976 // 1) only one use
977 // 2) a use is the same as the current LCA passed as 'n1'
978 Node *dom_lca_for_get_late_ctrl( Node *lca, Node *n, Node *tag ) {
979 assert( n->is_CFG(), "" );
980 // Fast-path null lca
981 if( lca != nullptr && lca != n ) {
982 assert( lca->is_CFG(), "" );
983 // find LCA of all uses
984 n = dom_lca_for_get_late_ctrl_internal( lca, n, tag );
985 }
986 return find_non_split_ctrl(n);
987 }
988 Node *dom_lca_for_get_late_ctrl_internal( Node *lca, Node *n, Node *tag );
989
990 // Helper function for directing control inputs away from CFG split points.
991 Node *find_non_split_ctrl( Node *ctrl ) const {
992 if (ctrl != nullptr) {
993 if (ctrl->is_MultiBranch()) {
994 ctrl = ctrl->in(0);
995 }
996 assert(ctrl->is_CFG(), "CFG");
997 }
998 return ctrl;
999 }
1000
1001 void cast_incr_before_loop(Node* incr, Node* ctrl, CountedLoopNode* loop);
1002
1003 #ifdef ASSERT
1004 static void ensure_zero_trip_guard_proj(Node* node, bool is_main_loop);
1005 #endif
1006 private:
1007 static void get_opaque_template_assertion_predicate_nodes(ParsePredicateSuccessProj* parse_predicate_proj,
1008 Unique_Node_List& list);
1009 void update_main_loop_assertion_predicates(CountedLoopNode* new_main_loop_head, int stride_con_before_unroll);
1010 void initialize_assertion_predicates_for_peeled_loop(CountedLoopNode* peeled_loop_head,
1011 CountedLoopNode* remaining_loop_head,
1012 uint first_node_index_in_cloned_loop_body,
1013 const Node_List& old_new);
1014 void initialize_assertion_predicates_for_main_loop(CountedLoopNode* pre_loop_head,
1015 CountedLoopNode* main_loop_head,
1016 uint first_node_index_in_pre_loop_body,
1017 uint last_node_index_in_pre_loop_body,
1018 DEBUG_ONLY(uint last_node_index_from_backedge_goo COMMA)
1019 const Node_List& old_new);
1020 void initialize_assertion_predicates_for_post_loop(CountedLoopNode* main_loop_head, CountedLoopNode* post_loop_head,
1021 uint first_node_index_in_cloned_loop_body);
1022 void create_assertion_predicates_at_loop(CountedLoopNode* source_loop_head, CountedLoopNode* target_loop_head,
1023 const NodeInLoopBody& _node_in_loop_body, bool kill_old_template);
1024 void create_assertion_predicates_at_main_or_post_loop(CountedLoopNode* source_loop_head,
1025 CountedLoopNode* target_loop_head,
1026 const NodeInLoopBody& _node_in_loop_body,
1027 bool kill_old_template);
1028 void rewire_old_target_loop_entry_dependency_to_new_entry(CountedLoopNode* target_loop_head,
1029 const Node* old_target_loop_entry,
1030 uint node_index_before_new_assertion_predicate_nodes);
1031 void log_loop_tree();
1032
1033 public:
1034
1035 PhaseIterGVN &igvn() const { return _igvn; }
1036
1037 Arena* arena() { return &_arena; };
1038
1039 bool has_node(const Node* n) const {
1040 guarantee(n != nullptr, "No Node.");
1041 return _loop_or_ctrl[n->_idx] != nullptr;
1042 }
1043 // check if transform created new nodes that need _ctrl recorded
1044 Node *get_late_ctrl( Node *n, Node *early );
1045 Node *get_early_ctrl( Node *n );
1046 Node *get_early_ctrl_for_expensive(Node *n, Node* earliest);
1047 void set_early_ctrl(Node* n, bool update_body);
1048 void set_subtree_ctrl(Node* n, bool update_body);
1049 void set_ctrl( Node *n, Node *ctrl ) {
1050 assert( !has_node(n) || has_ctrl(n), "" );
1051 assert( ctrl->in(0), "cannot set dead control node" );
1052 assert( ctrl == find_non_split_ctrl(ctrl), "must set legal crtl" );
1053 _loop_or_ctrl.map(n->_idx, (Node*)((intptr_t)ctrl + 1));
1054 }
1055 void set_root_as_ctrl(Node* n) {
1056 assert(!has_node(n) || has_ctrl(n), "");
1057 _loop_or_ctrl.map(n->_idx, (Node*)((intptr_t)C->root() + 1));
1058 }
1059 // Set control and update loop membership
1060 void set_ctrl_and_loop(Node* n, Node* ctrl) {
1061 IdealLoopTree* old_loop = get_loop(get_ctrl(n));
1062 IdealLoopTree* new_loop = get_loop(ctrl);
1063 if (old_loop != new_loop) {
1064 if (old_loop->_child == nullptr) old_loop->_body.yank(n);
1065 if (new_loop->_child == nullptr) new_loop->_body.push(n);
1066 }
1067 set_ctrl(n, ctrl);
1068 }
1069
1070 // Retrieves the ctrl for a data node i.
1071 Node* get_ctrl(const Node* i) {
1072 assert(has_node(i) && has_ctrl(i), "must be data node with ctrl");
1073 Node* n = get_ctrl_no_update(i);
1074 // We store the found ctrl in the side-table again. In most cases,
1075 // this is a no-op, since we just read from _loop_or_ctrl. But in cases
1076 // where there was a ctrl forwarding via dead ctrl nodes, this shortens the path.
1077 // See: forward_ctrl
1078 _loop_or_ctrl.map(i->_idx, (Node*)((intptr_t)n + 1));
1079 assert(has_node(i) && has_ctrl(i), "must still be data node with ctrl");
1080 assert(n == find_non_split_ctrl(n), "must return legal ctrl");
1081 return n;
1082 }
1083
1084 bool is_dominator(Node* dominator, Node* n);
1085 bool is_strict_dominator(Node* dominator, Node* n);
1086
1087 // return get_ctrl for a data node and self(n) for a CFG node
1088 Node* ctrl_or_self(Node* n) {
1089 if (has_ctrl(n))
1090 return get_ctrl(n);
1091 else {
1092 assert (n->is_CFG(), "must be a CFG node");
1093 return n;
1094 }
1095 }
1096
1097 private:
1098 Node* get_ctrl_no_update_helper(const Node* i) const {
1099 // We expect only data nodes (which must have a ctrl set), or
1100 // dead ctrl nodes that have a ctrl "forwarding".
1101 // See: forward_ctrl.
1102 assert(has_ctrl(i), "only data nodes or ctrl nodes with ctrl forwarding expected");
1103 return (Node*)(((intptr_t)_loop_or_ctrl[i->_idx]) & ~1);
1104 }
1105
1106 // Compute the ctrl of node i, jumping over ctrl forwardings.
1107 Node* get_ctrl_no_update(const Node* i) const {
1108 assert(has_ctrl(i), "only data nodes expected");
1109 Node* n = get_ctrl_no_update_helper(i);
1110 if (n->in(0) == nullptr) {
1111 // We encountered a dead CFG node.
1112 // If everything went right, this dead CFG node should have had a ctrl
1113 // forwarding installed, using "forward_ctrl". We now have to jump from
1114 // the old (dead) ctrl node to the new (live) ctrl node, in possibly
1115 // multiple ctrl forwarding steps.
1116 do {
1117 n = get_ctrl_no_update_helper(n);
1118 } while (n->in(0) == nullptr);
1119 n = find_non_split_ctrl(n);
1120 }
1121 return n;
1122 }
1123
1124 public:
1125 // Check for loop being set
1126 // "n" must be a control node. Returns true if "n" is known to be in a loop.
1127 bool has_loop( Node *n ) const {
1128 assert(!has_node(n) || !has_ctrl(n), "");
1129 return has_node(n);
1130 }
1131 // Set loop
1132 void set_loop( Node *n, IdealLoopTree *loop ) {
1133 _loop_or_ctrl.map(n->_idx, (Node*)loop);
1134 }
1135
1136 // Install a ctrl "forwarding" from an old (dead) control node.
1137 // This is a "lazy" update of the "get_ctrl" and "idom" mechanism:
1138 // - Install a forwarding from old_node (dead ctrl) to new_node.
1139 // - When querying "get_ctrl": jump from data node over possibly
1140 // multiple dead ctrl nodes with ctrl forwarding to eventually
1141 // reach a live ctrl node. Shorten the path to avoid chasing the
1142 // forwarding in the future.
1143 // - When querying "idom": from some node get its old idom, which
1144 // may be dead but has an idom forwarding to the new and live
1145 // idom. Shorten the path to avoid chasing the forwarding in the
1146 // future.
1147 // Note: while the "idom" information is stored in the "_idom"
1148 // side-table, the idom forwarding piggybacks on the ctrl
1149 // forwarding on "_loop_or_ctrl".
1150 // Using "forward_ctrl" allows us to only edit the entry for the old
1151 // dead node now, and we do not have to update all the nodes that had
1152 // the old_node as their "get_ctrl" or "idom". We clean up the forwarding
1153 // links when we query "get_ctrl" or "idom" for these nodes the next time.
1154 void forward_ctrl(Node* old_node, Node* new_node) {
1155 assert(!has_ctrl(old_node) && old_node->is_CFG() && old_node->in(0) == nullptr,
1156 "must be dead ctrl (CFG) node");
1157 assert(!has_ctrl(new_node) && new_node->is_CFG() && new_node->in(0) != nullptr,
1158 "must be live ctrl (CFG) node");
1159 assert(old_node != new_node, "no cycles please");
1160 // Re-use the side array slot for this node to provide the
1161 // forwarding pointer.
1162 _loop_or_ctrl.map(old_node->_idx, (Node*)((intptr_t)new_node + 1));
1163 assert(has_ctrl(old_node), "must have installed ctrl forwarding");
1164 }
1165
1166 // Replace the old ctrl node with a new ctrl node.
1167 // - Update the node inputs of all uses.
1168 // - Lazily update the ctrl and idom info of all uses, via a ctrl/idom forwarding.
1169 void replace_node_and_forward_ctrl(Node* old_node, Node* new_node) {
1170 _igvn.replace_node(old_node, new_node);
1171 forward_ctrl(old_node, new_node);
1172 }
1173
1174 private:
1175
1176 // Place 'n' in some loop nest, where 'n' is a CFG node
1177 void build_loop_tree();
1178 int build_loop_tree_impl(Node* n, int pre_order);
1179 // Insert loop into the existing loop tree. 'innermost' is a leaf of the
1180 // loop tree, not the root.
1181 IdealLoopTree *sort( IdealLoopTree *loop, IdealLoopTree *innermost );
1182
1183 #ifdef ASSERT
1184 // verify that regions in irreducible loops are marked is_in_irreducible_loop
1185 void verify_regions_in_irreducible_loops();
1186 bool is_in_irreducible_loop(RegionNode* region);
1187 #endif
1188
1189 // Place Data nodes in some loop nest
1190 void build_loop_early( VectorSet &visited, Node_List &worklist, Node_Stack &nstack );
1191 void build_loop_late ( VectorSet &visited, Node_List &worklist, Node_Stack &nstack );
1192 void build_loop_late_post_work(Node* n, bool pinned);
1193 void build_loop_late_post(Node* n);
1194 void verify_strip_mined_scheduling(Node *n, Node* least);
1195
1196 // Array of immediate dominance info for each CFG node indexed by node idx
1197 private:
1198 uint _idom_size;
1199 Node **_idom; // Array of immediate dominators
1200 uint *_dom_depth; // Used for fast LCA test
1201 GrowableArray<uint>* _dom_stk; // For recomputation of dom depth
1202 LoopOptsMode _mode;
1203
1204 // build the loop tree and perform any requested optimizations
1205 void build_and_optimize();
1206
1207 // Dominators for the sea of nodes
1208 void Dominators();
1209
1210 // Compute the Ideal Node to Loop mapping
1211 PhaseIdealLoop(PhaseIterGVN& igvn, LoopOptsMode mode) :
1212 PhaseTransform(Ideal_Loop),
1213 _arena(mtCompiler, Arena::Tag::tag_idealloop),
1214 _loop_or_ctrl(&_arena),
1215 _igvn(igvn),
1216 _verify_me(nullptr),
1217 _verify_only(false),
1218 _mode(mode),
1219 _nodes_required(UINT_MAX) {
1220 assert(mode != LoopOptsVerify, "wrong constructor to verify IdealLoop");
1221 build_and_optimize();
1222 }
1223
1224 #ifndef PRODUCT
1225 // Verify that verify_me made the same decisions as a fresh run
1226 // or only verify that the graph is valid if verify_me is null.
1227 PhaseIdealLoop(PhaseIterGVN& igvn, const PhaseIdealLoop* verify_me = nullptr) :
1228 PhaseTransform(Ideal_Loop),
1229 _arena(mtCompiler, Arena::Tag::tag_idealloop),
1230 _loop_or_ctrl(&_arena),
1231 _igvn(igvn),
1232 _verify_me(verify_me),
1233 _verify_only(verify_me == nullptr),
1234 _mode(LoopOptsVerify),
1235 _nodes_required(UINT_MAX) {
1236 DEBUG_ONLY(C->set_phase_verify_ideal_loop();)
1237 build_and_optimize();
1238 DEBUG_ONLY(C->reset_phase_verify_ideal_loop();)
1239 }
1240 #endif
1241
1242 Node* insert_convert_node_if_needed(BasicType target, Node* input);
1243
1244 Node* idom_no_update(Node* d) const {
1245 return idom_no_update(d->_idx);
1246 }
1247
1248 Node* idom_no_update(uint node_idx) const {
1249 assert(node_idx < _idom_size, "oob");
1250 Node* n = _idom[node_idx];
1251 assert(n != nullptr,"Bad immediate dominator info.");
1252 while (n->in(0) == nullptr) { // Skip dead CFG nodes
1253 // We encountered a dead CFG node.
1254 // If everything went right, this dead CFG node should have had an idom
1255 // forwarding installed, using "forward_ctrl". We now have to jump from
1256 // the old (dead) idom node to the new (live) idom node, in possibly
1257 // multiple idom forwarding steps.
1258 // Note that we piggyback on "_loop_or_ctrl" to do the forwarding,
1259 // since we forward both "get_ctrl" and "idom" from the dead to the
1260 // new live ctrl/idom nodes.
1261 n = (Node*)(((intptr_t)_loop_or_ctrl[n->_idx]) & ~1);
1262 assert(n != nullptr,"Bad immediate dominator info.");
1263 }
1264 return n;
1265 }
1266
1267 public:
1268 Node* idom(Node* n) const {
1269 return idom(n->_idx);
1270 }
1271
1272 Node* idom(uint node_idx) const {
1273 Node* n = idom_no_update(node_idx);
1274 // We store the found idom in the side-table again. In most cases,
1275 // this is a no-op, since we just read from _idom. But in cases where
1276 // there was an idom forwarding via dead idom nodes, this shortens the path.
1277 // See: forward_ctrl
1278 _idom[node_idx] = n;
1279 return n;
1280 }
1281
1282 uint dom_depth(Node* d) const {
1283 guarantee(d != nullptr, "Null dominator info.");
1284 guarantee(d->_idx < _idom_size, "");
1285 return _dom_depth[d->_idx];
1286 }
1287 void set_idom(Node* d, Node* n, uint dom_depth);
1288 // Locally compute IDOM using dom_lca call
1289 Node *compute_idom( Node *region ) const;
1290 // Recompute dom_depth
1291 void recompute_dom_depth();
1292
1293 // Is safept not required by an outer loop?
1294 bool is_deleteable_safept(Node* sfpt) const;
1295
1296 // Replace parallel induction variable (parallel to trip counter)
1297 void replace_parallel_iv(IdealLoopTree *loop);
1298
1299 Node *dom_lca( Node *n1, Node *n2 ) const {
1300 return find_non_split_ctrl(dom_lca_internal(n1, n2));
1301 }
1302 Node *dom_lca_internal( Node *n1, Node *n2 ) const;
1303
1304 Node* dominated_node(Node* c1, Node* c2) {
1305 assert(is_dominator(c1, c2) || is_dominator(c2, c1), "nodes must be related");
1306 return is_dominator(c1, c2) ? c2 : c1;
1307 }
1308
1309 // Return control node that's dominated by the 2 others
1310 Node* dominated_node(Node* c1, Node* c2, Node* c3) {
1311 return dominated_node(c1, dominated_node(c2, c3));
1312 }
1313
1314 // Build and verify the loop tree without modifying the graph. This
1315 // is useful to verify that all inputs properly dominate their uses.
1316 static void verify(PhaseIterGVN& igvn) {
1317 #ifdef ASSERT
1318 ResourceMark rm;
1319 Compile::TracePhase tp(_t_idealLoopVerify);
1320 PhaseIdealLoop v(igvn);
1321 #endif
1322 }
1323
1324 // Recommended way to use PhaseIdealLoop.
1325 // Run PhaseIdealLoop in some mode and allocates a local scope for memory allocations.
1326 static void optimize(PhaseIterGVN &igvn, LoopOptsMode mode) {
1327 ResourceMark rm;
1328 PhaseIdealLoop v(igvn, mode);
1329
1330 Compile* C = Compile::current();
1331 if (!C->failing()) {
1332 // Cleanup any modified bits
1333 igvn.optimize();
1334 if (C->failing()) { return; }
1335 v.log_loop_tree();
1336 }
1337 }
1338
1339 // True if the method has at least 1 irreducible loop
1340 bool _has_irreducible_loops;
1341
1342 // Per-Node transform
1343 virtual Node* transform(Node* n) { return nullptr; }
1344
1345 Node* loop_exit_control(const IdealLoopTree* loop) const;
1346
1347 class LoopExitTest {
1348 bool _is_valid;
1349
1350 const Node* _back_control;
1351 const IdealLoopTree* _loop;
1352 PhaseIdealLoop* _phase;
1353
1354 Node* _cmp;
1355 Node* _incr;
1356 Node* _limit;
1357 BoolTest::mask _mask;
1358 float _cl_prob;
1359
1360 public:
1361 LoopExitTest(const Node* back_control, const IdealLoopTree* loop, PhaseIdealLoop* phase) :
1362 _is_valid(false),
1363 _back_control(back_control),
1364 _loop(loop),
1365 _phase(phase),
1366 _cmp(nullptr),
1367 _incr(nullptr),
1368 _limit(nullptr),
1369 _mask(BoolTest::illegal),
1370 _cl_prob(0.0f) {}
1371
1372 void build();
1373 void canonicalize_mask(jlong stride_con);
1374
1375 bool is_valid_with_bt(BasicType bt) const {
1376 return _is_valid && _cmp != nullptr && _cmp->Opcode() == Op_Cmp(bt);
1377 }
1378
1379 bool should_include_limit() const { return _mask == BoolTest::le || _mask == BoolTest::ge; }
1380
1381 CmpNode* cmp() const { return _cmp->as_Cmp(); }
1382 Node* incr() const { return _incr; }
1383 Node* limit() const { return _limit; }
1384 BoolTest::mask mask() const { return _mask; }
1385 float cl_prob() const { return _cl_prob; }
1386 };
1387
1388 class LoopIVIncr {
1389 bool _is_valid;
1390
1391 const Node* _head;
1392 const IdealLoopTree* _loop;
1393
1394 Node* _incr;
1395 Node* _phi_incr;
1396
1397 public:
1398 LoopIVIncr(const Node* head, const IdealLoopTree* loop) :
1399 _is_valid(false),
1400 _head(head),
1401 _loop(loop),
1402 _incr(nullptr),
1403 _phi_incr(nullptr) {}
1404
1405 void build(Node* old_incr);
1406
1407 bool is_valid() const { return _is_valid; }
1408 bool is_valid_with_bt(const BasicType bt) const {
1409 return _is_valid && _incr->Opcode() == Op_Add(bt);
1410 }
1411
1412 Node* incr() const { return _incr; }
1413 Node* phi_incr() const { return _phi_incr; }
1414 };
1415
1416 class LoopIVStride {
1417 bool _is_valid;
1418
1419 BasicType _iv_bt;
1420 Node* _stride_node;
1421 Node* _xphi;
1422
1423 public:
1424 LoopIVStride(BasicType iv_bt) :
1425 _is_valid(false),
1426 _iv_bt(iv_bt),
1427 _stride_node(nullptr),
1428 _xphi(nullptr) {}
1429
1430 void build(const Node* incr);
1431
1432 bool is_valid() const { return _is_valid && _stride_node != nullptr; }
1433 Node* stride_node() const { return _stride_node; }
1434 Node* xphi() const { return _xphi; }
1435
1436 jlong compute_non_zero_stride_con(BoolTest::mask mask, BasicType iv_bt) const;
1437 };
1438
1439 static PhiNode* loop_iv_phi(const Node* xphi, const Node* phi_incr, const Node* head);
1440
1441 bool try_convert_to_counted_loop(Node* head, IdealLoopTree*& loop, BasicType iv_bt);
1442
1443 Node* loop_nest_replace_iv(Node* iv_to_replace, Node* inner_iv, Node* outer_phi, Node* inner_head, BasicType bt);
1444 bool create_loop_nest(IdealLoopTree* loop, Node_List &old_new);
1445
1446 void add_parse_predicate(Deoptimization::DeoptReason reason, Node* inner_head, IdealLoopTree* loop, SafePointNode* sfpt);
1447 SafePointNode* find_safepoint(Node* back_control, const Node* head, const IdealLoopTree* loop);
1448
1449 void add_parse_predicates(IdealLoopTree* outer_ilt, LoopNode* inner_head, SafePointNode* cloned_sfpt);
1450
1451 IdealLoopTree* insert_outer_loop(IdealLoopTree* loop, LoopNode* outer_l, Node* outer_ift);
1452 IdealLoopTree* create_outer_strip_mined_loop(Node* init_control,
1453 IdealLoopTree* loop, float cl_prob, float le_fcnt,
1454 Node*& entry_control, Node*& iffalse);
1455
1456 Node* exact_limit( IdealLoopTree *loop );
1457
1458 // Return a post-walked LoopNode
1459 IdealLoopTree* get_loop(const Node* n) const {
1460 // Dead nodes have no loop, so return the top level loop instead
1461 if (!has_node(n)) return _ltree_root;
1462 assert(!has_ctrl(n), "");
1463 return (IdealLoopTree*)_loop_or_ctrl[n->_idx];
1464 }
1465
1466 IdealLoopTree* ltree_root() const { return _ltree_root; }
1467
1468 // Is 'n' a (nested) member of 'loop'?
1469 bool is_member(const IdealLoopTree* loop, const Node* n) const {
1470 return loop->is_member(get_loop(n));
1471 }
1472
1473 // is the control for 'n' a (nested) member of 'loop'?
1474 bool ctrl_is_member(const IdealLoopTree* loop, const Node* n) {
1475 return is_member(loop, get_ctrl(n));
1476 }
1477
1478 // This is the basic building block of the loop optimizations. It clones an
1479 // entire loop body. It makes an old_new loop body mapping; with this
1480 // mapping you can find the new-loop equivalent to an old-loop node. All
1481 // new-loop nodes are exactly equal to their old-loop counterparts, all
1482 // edges are the same. All exits from the old-loop now have a RegionNode
1483 // that merges the equivalent new-loop path. This is true even for the
1484 // normal "loop-exit" condition. All uses of loop-invariant old-loop values
1485 // now come from (one or more) Phis that merge their new-loop equivalents.
1486 // Parameter side_by_side_idom:
1487 // When side_by_size_idom is null, the dominator tree is constructed for
1488 // the clone loop to dominate the original. Used in construction of
1489 // pre-main-post loop sequence.
1490 // When nonnull, the clone and original are side-by-side, both are
1491 // dominated by the passed in side_by_side_idom node. Used in
1492 // construction of unswitched loops.
1493 enum CloneLoopMode {
1494 IgnoreStripMined = 0, // Only clone inner strip mined loop
1495 CloneIncludesStripMined = 1, // clone both inner and outer strip mined loops
1496 ControlAroundStripMined = 2 // Only clone inner strip mined loop,
1497 // result control flow branches
1498 // either to inner clone or outer
1499 // strip mined loop.
1500 };
1501 void clone_loop( IdealLoopTree *loop, Node_List &old_new, int dom_depth,
1502 CloneLoopMode mode, Node* side_by_side_idom = nullptr);
1503 void clone_loop_handle_data_uses(Node* old, Node_List &old_new,
1504 IdealLoopTree* loop, IdealLoopTree* companion_loop,
1505 Node_List*& split_if_set, Node_List*& split_bool_set,
1506 Node_List*& split_cex_set, Node_List& worklist,
1507 uint new_counter, CloneLoopMode mode);
1508 void clone_outer_loop(LoopNode* head, CloneLoopMode mode, IdealLoopTree *loop,
1509 IdealLoopTree* outer_loop, int dd, Node_List &old_new,
1510 Node_List& extra_data_nodes);
1511
1512 // If we got the effect of peeling, either by actually peeling or by
1513 // making a pre-loop which must execute at least once, we can remove
1514 // all loop-invariant dominated tests in the main body.
1515 void peeled_dom_test_elim( IdealLoopTree *loop, Node_List &old_new );
1516
1517 // Generate code to do a loop peel for the given loop (and body).
1518 // old_new is a temp array.
1519 void do_peeling( IdealLoopTree *loop, Node_List &old_new );
1520
1521 // Add pre and post loops around the given loop. These loops are used
1522 // during RCE, unrolling and aligning loops.
1523 void insert_pre_post_loops( IdealLoopTree *loop, Node_List &old_new, bool peel_only );
1524
1525 // Find the last store in the body of an OuterStripMinedLoop when following memory uses
1526 Node *find_last_store_in_outer_loop(Node* store, const IdealLoopTree* outer_loop);
1527
1528 // Add post loop after the given loop.
1529 Node *insert_post_loop(IdealLoopTree* loop, Node_List& old_new,
1530 CountedLoopNode* main_head, CountedLoopEndNode* main_end,
1531 Node* incr, Node* limit, CountedLoopNode*& post_head);
1532
1533 // Add a vector post loop between a vector main loop and the current post loop
1534 void insert_vector_post_loop(IdealLoopTree *loop, Node_List &old_new);
1535 // If Node n lives in the back_ctrl block, we clone a private version of n
1536 // in preheader_ctrl block and return that, otherwise return n.
1537 Node *clone_up_backedge_goo( Node *back_ctrl, Node *preheader_ctrl, Node *n, VectorSet &visited, Node_Stack &clones );
1538
1539 // Take steps to maximally unroll the loop. Peel any odd iterations, then
1540 // unroll to do double iterations. The next round of major loop transforms
1541 // will repeat till the doubled loop body does all remaining iterations in 1
1542 // pass.
1543 void do_maximally_unroll( IdealLoopTree *loop, Node_List &old_new );
1544
1545 // Unroll the loop body one step - make each trip do 2 iterations.
1546 void do_unroll( IdealLoopTree *loop, Node_List &old_new, bool adjust_min_trip );
1547
1548 // Return true if exp is a constant times an induction var
1549 bool is_scaled_iv(Node* exp, Node* iv, BasicType bt, jlong* p_scale, bool* p_short_scale, int depth = 0);
1550
1551 bool is_iv(Node* exp, Node* iv, BasicType bt);
1552
1553 // Return true if exp is a scaled induction var plus (or minus) constant
1554 bool is_scaled_iv_plus_offset(Node* exp, Node* iv, BasicType bt, jlong* p_scale, Node** p_offset, bool* p_short_scale = nullptr, int depth = 0);
1555 bool is_scaled_iv_plus_offset(Node* exp, Node* iv, int* p_scale, Node** p_offset) {
1556 jlong long_scale;
1557 if (is_scaled_iv_plus_offset(exp, iv, T_INT, &long_scale, p_offset)) {
1558 int int_scale = checked_cast<int>(long_scale);
1559 if (p_scale != nullptr) {
1560 *p_scale = int_scale;
1561 }
1562 return true;
1563 }
1564 return false;
1565 }
1566 // Helper for finding more complex matches to is_scaled_iv_plus_offset.
1567 bool is_scaled_iv_plus_extra_offset(Node* exp1, Node* offset2, Node* iv,
1568 BasicType bt,
1569 jlong* p_scale, Node** p_offset,
1570 bool* p_short_scale, int depth);
1571
1572 // Create a new if above the uncommon_trap_if_pattern for the predicate to be promoted
1573 IfTrueNode* create_new_if_for_predicate(const ParsePredicateSuccessProj* parse_predicate_proj, Node* new_entry,
1574 Deoptimization::DeoptReason reason, int opcode,
1575 bool rewire_uncommon_proj_phi_inputs = false);
1576
1577 private:
1578 // Helper functions for create_new_if_for_predicate()
1579 void set_ctrl_of_nodes_with_same_ctrl(Node* start_node, ProjNode* old_uncommon_proj, Node* new_uncommon_proj);
1580 Unique_Node_List find_nodes_with_same_ctrl(Node* node, const ProjNode* ctrl);
1581 Node* clone_nodes_with_same_ctrl(Node* start_node, ProjNode* old_uncommon_proj, Node* new_uncommon_proj);
1582 void fix_cloned_data_node_controls(const ProjNode* orig, Node* new_uncommon_proj,
1583 const OrigToNewHashtable& orig_to_clone);
1584
1585 public:
1586 void register_control(Node* n, IdealLoopTree *loop, Node* pred, bool update_body = true);
1587
1588 // Replace the control input of 'node' with 'new_control' and set the dom depth to the one of 'new_control'.
1589 void replace_control(Node* node, Node* new_control) {
1590 _igvn.replace_input_of(node, 0, new_control);
1591 set_idom(node, new_control, dom_depth(new_control));
1592 }
1593
1594 void replace_loop_entry(LoopNode* loop_head, Node* new_entry) {
1595 _igvn.replace_input_of(loop_head, LoopNode::EntryControl, new_entry);
1596 set_idom(loop_head, new_entry, dom_depth(new_entry));
1597 }
1598
1599 // Construct a range check for a predicate if
1600 BoolNode* rc_predicate(Node* ctrl, int scale, Node* offset, Node* init, Node* limit,
1601 jint stride, Node* range, bool upper, bool& overflow);
1602
1603 // Implementation of the loop predication to promote checks outside the loop
1604 bool loop_predication_impl(IdealLoopTree *loop);
1605
1606 private:
1607 bool loop_predication_impl_helper(IdealLoopTree* loop, IfProjNode* if_success_proj,
1608 ParsePredicateSuccessProj* parse_predicate_proj, CountedLoopNode* cl, ConNode* zero,
1609 Invariance& invar, Deoptimization::DeoptReason deopt_reason);
1610 bool can_create_loop_predicates(const PredicateBlock* profiled_loop_predicate_block) const;
1611 bool loop_predication_should_follow_branches(IdealLoopTree* loop, float& loop_trip_cnt);
1612 void loop_predication_follow_branches(Node *c, IdealLoopTree *loop, float loop_trip_cnt,
1613 PathFrequency& pf, Node_Stack& stack, VectorSet& seen,
1614 Node_List& if_proj_list);
1615 IfTrueNode* create_template_assertion_predicate(CountedLoopNode* loop_head, ParsePredicateNode* parse_predicate,
1616 IfProjNode* new_control, int scale, Node* offset, Node* range);
1617 void eliminate_hoisted_range_check(IfTrueNode* hoisted_check_proj, IfTrueNode* template_assertion_predicate_proj);
1618
1619 // Helper function to collect predicate for eliminating the useless ones
1620 void eliminate_useless_predicates() const;
1621
1622 void eliminate_useless_zero_trip_guard();
1623 void eliminate_useless_multiversion_if();
1624
1625 public:
1626 // Change the control input of expensive nodes to allow commoning by
1627 // IGVN when it is guaranteed to not result in a more frequent
1628 // execution of the expensive node. Return true if progress.
1629 bool process_expensive_nodes();
1630
1631 // Check whether node has become unreachable
1632 bool is_node_unreachable(Node *n) const {
1633 return !has_node(n) || n->is_unreachable(_igvn);
1634 }
1635
1636 // Eliminate range-checks and other trip-counter vs loop-invariant tests.
1637 void do_range_check(IdealLoopTree* loop);
1638
1639 // Clone loop with an invariant test (that does not exit) and
1640 // insert a clone of the test that selects which version to
1641 // execute.
1642 void do_unswitching(IdealLoopTree* loop, Node_List& old_new);
1643
1644 IfNode* find_unswitch_candidates(const IdealLoopTree* loop, Node_List& flat_array_checks) const;
1645 IfNode* find_unswitch_candidate_from_idoms(const IdealLoopTree* loop) const;
1646
1647 private:
1648 static bool has_control_dependencies_from_predicates(LoopNode* head);
1649 static void revert_to_normal_loop(const LoopNode* loop_head);
1650
1651 void hoist_invariant_check_casts(const IdealLoopTree* loop, const Node_List& old_new,
1652 const UnswitchCandidate& unswitch_candidate, const IfNode* loop_selector);
1653 void add_unswitched_loop_version_bodies_to_igvn(IdealLoopTree* loop, const Node_List& old_new);
1654 static void increment_unswitch_counts(LoopNode* original_head, LoopNode* new_head);
1655 void remove_unswitch_candidate_from_loops(const Node_List& old_new, const UnswitchedLoopSelector& unswitched_loop_selector);
1656 #ifndef PRODUCT
1657 static void trace_loop_unswitching_count(IdealLoopTree* loop, LoopNode* original_head);
1658 static void trace_loop_unswitching_impossible(const LoopNode* original_head);
1659 static void trace_loop_unswitching_result(const UnswitchedLoopSelector& unswitched_loop_selector,
1660 const UnswitchCandidate& unswitch_candidate,
1661 const LoopNode* original_head, const LoopNode* new_head);
1662 static void trace_loop_multiversioning_result(const LoopSelector& loop_selector,
1663 const LoopNode* original_head, const LoopNode* new_head);
1664 #endif
1665
1666 public:
1667
1668 // Range Check Elimination uses this function!
1669 // Constrain the main loop iterations so the affine function:
1670 // low_limit <= scale_con * I + offset < upper_limit
1671 // always holds true. That is, either increase the number of iterations in
1672 // the pre-loop or the post-loop until the condition holds true in the main
1673 // loop. Scale_con, offset and limit are all loop invariant.
1674 void add_constraint(jlong stride_con, jlong scale_con, Node* offset, Node* low_limit, Node* upper_limit, Node* pre_ctrl, Node** pre_limit, Node** main_limit);
1675 // Helper function for add_constraint().
1676 Node* adjust_limit(bool reduce, Node* scale, Node* offset, Node* rc_limit, Node* old_limit, Node* pre_ctrl, bool round);
1677
1678 // Partially peel loop up through last_peel node.
1679 bool partial_peel( IdealLoopTree *loop, Node_List &old_new );
1680 bool duplicate_loop_backedge(IdealLoopTree *loop, Node_List &old_new);
1681
1682 // AutoVectorize the loop: replace scalar ops with vector ops.
1683 enum AutoVectorizeStatus {
1684 Impossible, // This loop has the wrong shape to even try vectorization.
1685 Success, // We just successfully vectorized the loop.
1686 TriedAndFailed, // We tried to vectorize, but failed.
1687 };
1688 AutoVectorizeStatus auto_vectorize(IdealLoopTree* lpt, VSharedData &vshared);
1689
1690 void maybe_multiversion_for_auto_vectorization_runtime_checks(IdealLoopTree* lpt, Node_List& old_new);
1691 void do_multiversioning(IdealLoopTree* lpt, Node_List& old_new);
1692 IfTrueNode* create_new_if_for_multiversion(IfTrueNode* multiversioning_fast_proj);
1693 bool try_resume_optimizations_for_delayed_slow_loop(IdealLoopTree* lpt);
1694
1695 // Create a scheduled list of nodes control dependent on ctrl set.
1696 void scheduled_nodelist( IdealLoopTree *loop, VectorSet& ctrl, Node_List &sched );
1697 // Has a use in the vector set
1698 bool has_use_in_set( Node* n, VectorSet& vset );
1699 // Has use internal to the vector set (ie. not in a phi at the loop head)
1700 bool has_use_internal_to_set( Node* n, VectorSet& vset, IdealLoopTree *loop );
1701 // clone "n" for uses that are outside of loop
1702 int clone_for_use_outside_loop( IdealLoopTree *loop, Node* n, Node_List& worklist );
1703 // clone "n" for special uses that are in the not_peeled region
1704 void clone_for_special_use_inside_loop( IdealLoopTree *loop, Node* n,
1705 VectorSet& not_peel, Node_List& sink_list, Node_List& worklist );
1706 // Insert phi(lp_entry_val, back_edge_val) at use->in(idx) for loop lp if phi does not already exist
1707 void insert_phi_for_loop( Node* use, uint idx, Node* lp_entry_val, Node* back_edge_val, LoopNode* lp );
1708 #ifdef ASSERT
1709 // Validate the loop partition sets: peel and not_peel
1710 bool is_valid_loop_partition( IdealLoopTree *loop, VectorSet& peel, Node_List& peel_list, VectorSet& not_peel );
1711 // Ensure that uses outside of loop are of the right form
1712 bool is_valid_clone_loop_form( IdealLoopTree *loop, Node_List& peel_list,
1713 uint orig_exit_idx, uint clone_exit_idx);
1714 bool is_valid_clone_loop_exit_use( IdealLoopTree *loop, Node* use, uint exit_idx);
1715 #endif
1716
1717 // Returns nonzero constant stride if-node is a possible iv test (otherwise returns zero.)
1718 int stride_of_possible_iv( Node* iff );
1719 bool is_possible_iv_test( Node* iff ) { return stride_of_possible_iv(iff) != 0; }
1720 // Return the (unique) control output node that's in the loop (if it exists.)
1721 Node* stay_in_loop( Node* n, IdealLoopTree *loop);
1722 // Insert a signed compare loop exit cloned from an unsigned compare.
1723 IfNode* insert_cmpi_loop_exit(IfNode* if_cmpu, IdealLoopTree *loop);
1724 void remove_cmpi_loop_exit(IfNode* if_cmp, IdealLoopTree *loop);
1725 // Utility to register node "n" with PhaseIdealLoop
1726 void register_node(Node* n, IdealLoopTree* loop, Node* pred, uint ddepth);
1727 // Utility to create an if-projection
1728 ProjNode* proj_clone(ProjNode* p, IfNode* iff);
1729 // Force the iff control output to be the live_proj
1730 Node* short_circuit_if(IfNode* iff, ProjNode* live_proj);
1731 // Insert a region before an if projection
1732 RegionNode* insert_region_before_proj(ProjNode* proj);
1733 // Insert a new if before an if projection
1734 ProjNode* insert_if_before_proj(Node* left, bool Signed, BoolTest::mask relop, Node* right, ProjNode* proj);
1735
1736 // Passed in a Phi merging (recursively) some nearly equivalent Bool/Cmps.
1737 // "Nearly" because all Nodes have been cloned from the original in the loop,
1738 // but the fall-in edges to the Cmp are different. Clone bool/Cmp pairs
1739 // through the Phi recursively, and return a Bool.
1740 Node* clone_iff(PhiNode* phi);
1741 CmpNode* clone_bool(PhiNode* phi);
1742
1743
1744 // Rework addressing expressions to get the most loop-invariant stuff
1745 // moved out. We'd like to do all associative operators, but it's especially
1746 // important (common) to do address expressions.
1747 Node* remix_address_expressions(Node* n);
1748 Node* remix_address_expressions_add_left_shift(Node* n, IdealLoopTree* n_loop, Node* n_ctrl, BasicType bt);
1749
1750 // Convert add to muladd to generate MuladdS2I under certain criteria
1751 Node * convert_add_to_muladd(Node * n);
1752
1753 // Attempt to use a conditional move instead of a phi/branch
1754 Node *conditional_move( Node *n );
1755
1756 // Check for aggressive application of 'split-if' optimization,
1757 // using basic block level info.
1758 void split_if_with_blocks ( VectorSet &visited, Node_Stack &nstack);
1759 Node *split_if_with_blocks_pre ( Node *n );
1760 void split_if_with_blocks_post( Node *n );
1761 Node *has_local_phi_input( Node *n );
1762 // Mark an IfNode as being dominated by a prior test,
1763 // without actually altering the CFG (and hence IDOM info).
1764 void dominated_by(IfProjNode* prevdom, IfNode* iff, bool flip = false, bool prev_dom_not_imply_this = false);
1765 void rewire_safe_outputs_to_dominator(Node* source, Node* dominator, bool dominator_not_imply_source);
1766
1767 // Split Node 'n' through merge point
1768 RegionNode* split_thru_region(Node* n, RegionNode* region);
1769 // Split Node 'n' through merge point if there is enough win.
1770 Node *split_thru_phi( Node *n, Node *region, int policy );
1771 // Found an If getting its condition-code input from a Phi in the
1772 // same block. Split thru the Region.
1773 void do_split_if(Node *iff, RegionNode** new_false_region = nullptr, RegionNode** new_true_region = nullptr);
1774
1775 private:
1776 // Class to keep track of wins in split_thru_phi.
1777 class SplitThruPhiWins {
1778 private:
1779 // Region containing the phi we are splitting through.
1780 const Node* _region;
1781
1782 // Sum of all wins regardless of where they happen. This applies to Loops phis as well as non-loop phis.
1783 int _total_wins;
1784
1785 // For Loops, wins have different impact depending on if they happen on loop entry or on the backedge.
1786 // Number of wins on a loop entry edge if the split is through a loop head,
1787 // otherwise 0. Entry edge wins only pay dividends once on loop entry.
1788 int _loop_entry_wins;
1789 // Number of wins on a loop back-edge, which pay dividends on every iteration.
1790 int _loop_back_wins;
1791
1792 public:
1793 SplitThruPhiWins(const Node* region) :
1794 _region(region),
1795 _total_wins(0),
1796 _loop_entry_wins(0),
1797 _loop_back_wins(0) {};
1798
1799 void reset() {_total_wins = 0; _loop_entry_wins = 0; _loop_back_wins = 0;}
1800 void add_win(int ctrl_index) {
1801 if (_region->is_Loop() && ctrl_index == LoopNode::EntryControl) {
1802 _loop_entry_wins++;
1803 } else if (_region->is_Loop() && ctrl_index == LoopNode::LoopBackControl) {
1804 _loop_back_wins++;
1805 }
1806 _total_wins++;
1807 }
1808 // Is this split profitable with respect to the policy?
1809 bool profitable(int policy) const {
1810 assert(_region->is_Loop() || (_loop_entry_wins == 0 && _loop_back_wins == 0), "wins on loop edges without a loop");
1811 assert(!_region->is_Loop() || _total_wins == _loop_entry_wins + _loop_back_wins, "missed some win");
1812 // In general this means that the split has to have more wins than specified
1813 // in the policy. However, for loops we need to take into account where the
1814 // wins happen. We need to be careful when splitting, because splitting nodes
1815 // related to the iv through the phi can sufficiently rearrange the loop
1816 // structure to prevent RCE and thus vectorization. Thus, we only deem splitting
1817 // profitable if the win of a split is not on the entry edge, as such wins
1818 // only pay off once and have a high chance of messing up the loop structure.
1819 return (_loop_entry_wins == 0 && _total_wins > policy) ||
1820 // If there are wins on the entry edge but the backadge also has sufficient wins,
1821 // there is sufficient profitability to spilt regardless of the risk of messing
1822 // up the loop structure.
1823 _loop_back_wins > policy ||
1824 // If the policy is less than 0, a split is always profitable, i.e. we always
1825 // split. This is needed when we split a node and then must also split a
1826 // dependant node, i.e. spliting a Bool node after splitting a Cmp node.
1827 policy < 0;
1828 }
1829 };
1830
1831
1832 void split_thru_phi_yank_old_nodes(Node* n, Node* region);
1833
1834 public:
1835
1836 // Conversion of fill/copy patterns into intrinsic versions
1837 bool do_intrinsify_fill();
1838 bool intrinsify_fill(IdealLoopTree* lpt);
1839 bool match_fill_loop(IdealLoopTree* lpt, Node*& store, Node*& store_value,
1840 Node*& shift, Node*& offset);
1841
1842 private:
1843 // Helper functions
1844 Node *spinup( Node *iff, Node *new_false, Node *new_true, Node *region, Node *phi, small_cache *cache );
1845 Node *find_use_block( Node *use, Node *def, Node *old_false, Node *new_false, Node *old_true, Node *new_true );
1846 void handle_use( Node *use, Node *def, small_cache *cache, Node *region_dom, Node *new_false, Node *new_true, Node *old_false, Node *old_true );
1847 bool split_up( Node *n, Node *blk1, Node *blk2 );
1848
1849 Node* place_outside_loop(Node* useblock, IdealLoopTree* loop) const;
1850 Node* try_move_store_before_loop(Node* n, Node *n_ctrl);
1851 void try_move_store_after_loop(Node* n);
1852 void move_flat_array_check_out_of_loop(Node* n);
1853 bool identical_backtoback_ifs(Node *n);
1854 bool flat_array_element_type_check(Node *n);
1855 bool can_split_if(Node *n_ctrl);
1856 bool cannot_split_division(const Node* n, const Node* region) const;
1857 static bool is_divisor_loop_phi(const Node* divisor, const Node* loop);
1858 bool loop_phi_backedge_type_contains_zero(const Node* phi_divisor, const Type* zero) const;
1859
1860 // Determine if a method is too big for a/another round of split-if, based on
1861 // a magic (approximate) ratio derived from the equally magic constant 35000,
1862 // previously used for this purpose (but without relating to the node limit).
1863 bool must_throttle_split_if() {
1864 uint threshold = C->max_node_limit() * 2 / 5;
1865 return C->live_nodes() > threshold;
1866 }
1867
1868 // A simplistic node request tracking mechanism, where
1869 // = UINT_MAX Request not valid or made final.
1870 // < UINT_MAX Nodes currently requested (estimate).
1871 uint _nodes_required;
1872
1873 enum { REQUIRE_MIN = 70 };
1874
1875 uint nodes_required() const { return _nodes_required; }
1876
1877 // Given the _currently_ available number of nodes, check whether there is
1878 // "room" for an additional request or not, considering the already required
1879 // number of nodes. Return TRUE if the new request is exceeding the node
1880 // budget limit, otherwise return FALSE. Note that this interpretation will
1881 // act pessimistic on additional requests when new nodes have already been
1882 // generated since the 'begin'. This behaviour fits with the intention that
1883 // node estimates/requests should be made upfront.
1884 bool exceeding_node_budget(uint required = 0) {
1885 assert(C->live_nodes() < C->max_node_limit(), "sanity");
1886 uint available = C->max_node_limit() - C->live_nodes();
1887 return available < required + _nodes_required + REQUIRE_MIN;
1888 }
1889
1890 uint require_nodes(uint require, uint minreq = REQUIRE_MIN) {
1891 precond(require > 0);
1892 _nodes_required += MAX2(require, minreq);
1893 return _nodes_required;
1894 }
1895
1896 bool may_require_nodes(uint require, uint minreq = REQUIRE_MIN) {
1897 return !exceeding_node_budget(require) && require_nodes(require, minreq) > 0;
1898 }
1899
1900 uint require_nodes_begin() {
1901 assert(_nodes_required == UINT_MAX, "Bad state (begin).");
1902 _nodes_required = 0;
1903 return C->live_nodes();
1904 }
1905
1906 // When a node request is final, optionally check that the requested number
1907 // of nodes was reasonably correct with respect to the number of new nodes
1908 // introduced since the last 'begin'. Always check that we have not exceeded
1909 // the maximum node limit.
1910 void require_nodes_final(uint live_at_begin, bool check_estimate) {
1911 assert(_nodes_required < UINT_MAX, "Bad state (final).");
1912
1913 #ifdef ASSERT
1914 if (check_estimate) {
1915 // Check that the node budget request was not off by too much (x2).
1916 // Should this be the case we _surely_ need to improve the estimates
1917 // used in our budget calculations.
1918 if (C->live_nodes() - live_at_begin > 2 * _nodes_required) {
1919 log_info(compilation)("Bad node estimate: actual = %d >> request = %d",
1920 C->live_nodes() - live_at_begin, _nodes_required);
1921 }
1922 }
1923 #endif
1924 // Assert that we have stayed within the node budget limit.
1925 assert(C->live_nodes() < C->max_node_limit(),
1926 "Exceeding node budget limit: %d + %d > %d (request = %d)",
1927 C->live_nodes() - live_at_begin, live_at_begin,
1928 C->max_node_limit(), _nodes_required);
1929
1930 _nodes_required = UINT_MAX;
1931 }
1932
1933 private:
1934
1935 bool _created_loop_node;
1936 DEBUG_ONLY(void dump_idoms(Node* early, Node* wrong_lca);)
1937 NOT_PRODUCT(void dump_idoms_in_reverse(const Node* n, const Node_List& idom_list) const;)
1938
1939 public:
1940 void set_created_loop_node() { _created_loop_node = true; }
1941 bool created_loop_node() { return _created_loop_node; }
1942 void register_new_node(Node* n, Node* blk);
1943 void register_new_node_with_ctrl_of(Node* new_node, Node* ctrl_of) {
1944 register_new_node(new_node, get_ctrl(ctrl_of));
1945 }
1946
1947 Node* clone_and_register(Node* n, Node* ctrl) {
1948 n = n->clone();
1949 register_new_node(n, ctrl);
1950 return n;
1951 }
1952
1953 #ifdef ASSERT
1954 void dump_bad_graph(const char* msg, Node* n, Node* early, Node* LCA);
1955 #endif
1956
1957 #ifndef PRODUCT
1958 void dump() const;
1959 void dump_idom(Node* n) const { dump_idom(n, 1000); } // For debugging
1960 void dump_idom(Node* n, uint count) const;
1961 void get_idoms(Node* n, uint count, Unique_Node_List& idoms) const;
1962 void dump(IdealLoopTree* loop, uint rpo_idx, Node_List &rpo_list) const;
1963 IdealLoopTree* get_loop_idx(Node* n) const {
1964 // Dead nodes have no loop, so return the top level loop instead
1965 return _loop_or_ctrl[n->_idx] ? (IdealLoopTree*)_loop_or_ctrl[n->_idx] : _ltree_root;
1966 }
1967 // Print some stats
1968 static void print_statistics();
1969 static int _loop_invokes; // Count of PhaseIdealLoop invokes
1970 static int _loop_work; // Sum of PhaseIdealLoop x _unique
1971 static volatile int _long_loop_candidates;
1972 static volatile int _long_loop_nests;
1973 #endif
1974
1975 #ifdef ASSERT
1976 void verify() const;
1977 bool verify_idom_and_nodes(Node* root, const PhaseIdealLoop* phase_verify) const;
1978 bool verify_idom(Node* n, const PhaseIdealLoop* phase_verify) const;
1979 bool verify_loop_ctrl(Node* n, const PhaseIdealLoop* phase_verify) const;
1980 #endif
1981
1982 void rpo(Node* start, Node_Stack &stk, VectorSet &visited, Node_List &rpo_list) const;
1983
1984 void check_counted_loop_shape(IdealLoopTree* loop, Node* head, BasicType bt) NOT_DEBUG_RETURN;
1985
1986 LoopNode* create_inner_head(IdealLoopTree* loop, BaseCountedLoopNode* head, IfNode* exit_test);
1987
1988
1989 int extract_long_range_checks(const IdealLoopTree* loop, jint stride_con, int iters_limit, PhiNode* phi,
1990 Node_List &range_checks);
1991
1992 void transform_long_range_checks(int stride_con, const Node_List &range_checks, Node* outer_phi,
1993 Node* inner_iters_actual_int, Node* inner_phi,
1994 Node* iv_add, LoopNode* inner_head);
1995
1996 Node* get_late_ctrl_with_anti_dep(LoadNode* n, Node* early, Node* LCA);
1997
1998 bool ctrl_of_use_out_of_loop(const Node* n, Node* n_ctrl, IdealLoopTree* n_loop, Node* ctrl);
1999
2000 bool ctrl_of_all_uses_out_of_loop(const Node* n, Node* n_ctrl, IdealLoopTree* n_loop);
2001
2002 bool would_sink_below_pre_loop_exit(IdealLoopTree* n_loop, Node* ctrl);
2003
2004 Node* compute_early_ctrl(Node* n, Node* n_ctrl);
2005
2006 void try_sink_out_of_loop(Node* n);
2007
2008 Node* clamp(Node* R, Node* L, Node* H);
2009
2010 bool safe_for_if_replacement(const Node* dom) const;
2011
2012 void push_pinned_nodes_thru_region(IfNode* dom_if, Node* region);
2013
2014 bool try_merge_identical_ifs(Node* n);
2015
2016 void clone_loop_body(const Node_List& body, Node_List &old_new, CloneMap* cm);
2017
2018 void fix_body_edges(const Node_List &body, IdealLoopTree* loop, const Node_List &old_new, int dd,
2019 IdealLoopTree* parent, bool partial);
2020
2021 void fix_ctrl_uses(const Node_List& body, const IdealLoopTree* loop, Node_List &old_new, CloneLoopMode mode,
2022 Node* side_by_side_idom, CloneMap* cm, Node_List &worklist);
2023
2024 void fix_data_uses(Node_List& body, IdealLoopTree* loop, CloneLoopMode mode, IdealLoopTree* outer_loop,
2025 uint new_counter, Node_List& old_new, Node_List& worklist, Node_List*& split_if_set,
2026 Node_List*& split_bool_set, Node_List*& split_cex_set);
2027
2028 void finish_clone_loop(Node_List* split_if_set, Node_List* split_bool_set, Node_List* split_cex_set);
2029
2030 bool at_relevant_ctrl(Node* n, const Node* blk1, const Node* blk2);
2031
2032 bool clone_cmp_loadklass_down(Node* n, const Node* blk1, const Node* blk2);
2033 void clone_loadklass_nodes_at_cmp_index(const Node* n, Node* cmp, int i);
2034 bool clone_cmp_down(Node* n, const Node* blk1, const Node* blk2);
2035 void clone_template_assertion_expression_down(Node* node);
2036
2037 Node* similar_subtype_check(const Node* x, Node* r_in);
2038
2039 void update_addp_chain_base(Node* x, Node* old_base, Node* new_base);
2040
2041 bool can_move_to_inner_loop(Node* n, LoopNode* n_loop, Node* x);
2042
2043 void pin_nodes_dependent_on(Node* ctrl, bool old_iff_is_rangecheck);
2044
2045 void collect_flat_array_checks(const IdealLoopTree* loop, Node_List& flat_array_checks) const;
2046
2047 Node* ensure_node_and_inputs_are_above_pre_end(CountedLoopEndNode* pre_end, Node* node);
2048
2049 Node* new_assertion_predicate_opaque_init(Node* entry_control, Node* init, Node* int_zero);
2050
2051 bool try_make_short_running_loop(IdealLoopTree* loop, jint stride_con, const Node_List& range_checks, const uint iters_limit);
2052
2053 ConINode* intcon(jint i);
2054
2055 ConLNode* longcon(jlong i);
2056
2057 ConNode* makecon(const Type* t);
2058
2059 ConNode* integercon(jlong l, BasicType bt);
2060
2061 ConNode* zerocon(BasicType bt);
2062 };
2063
2064 class CountedLoopConverter {
2065 friend class PhaseIdealLoop;
2066
2067 // Match increment with optional truncation
2068 class TruncatedIncrement {
2069 bool _is_valid;
2070
2071 BasicType _bt;
2072
2073 Node* _incr;
2074 Node* _outer_trunc;
2075 Node* _inner_trunc;
2076 const TypeInteger* _trunc_type;
2077
2078 public:
2079 TruncatedIncrement(BasicType bt) :
2080 _is_valid(false),
2081 _bt(bt),
2082 _incr(nullptr),
2083 _outer_trunc(nullptr),
2084 _inner_trunc(nullptr),
2085 _trunc_type(nullptr) {}
2086
2087 void build(Node* expr);
2088
2089 bool is_valid() const { return _is_valid; }
2090 Node* incr() const { return _incr; }
2091
2092 // Optional truncation for: CHAR: (i+1)&0x7fff, BYTE: ((i+1)<<8)>>8, or SHORT: ((i+1)<<16)>>16
2093 Node* outer_trunc() const { return _outer_trunc; } // the outermost truncating node (either the & or the final >>)
2094 Node* inner_trunc() const { return _inner_trunc; } // the inner truncating node, if applicable (the << in a <</>> pair)
2095 const TypeInteger* trunc_type() const { return _trunc_type; }
2096 };
2097
2098 class LoopStructure {
2099 bool _is_valid;
2100
2101 const Node* _head;
2102 const IdealLoopTree* _loop;
2103 PhaseIdealLoop* _phase;
2104 BasicType _iv_bt;
2105
2106 Node* _back_control;
2107 PhaseIdealLoop::LoopExitTest _exit_test;
2108 PhaseIdealLoop::LoopIVIncr _iv_incr;
2109 TruncatedIncrement _truncated_increment;
2110 PhaseIdealLoop::LoopIVStride _stride;
2111 PhiNode* _phi;
2112 SafePointNode* _safepoint;
2113
2114 public:
2115 LoopStructure(const Node* head, const IdealLoopTree* loop, PhaseIdealLoop* phase, const BasicType iv_bt) :
2116 _is_valid(false),
2117 _head(head),
2118 _loop(loop),
2119 _phase(phase),
2120 _iv_bt(iv_bt),
2121 _back_control(_phase->loop_exit_control(_loop)),
2122 _exit_test(_back_control, _loop, _phase),
2123 _iv_incr(_head, _loop),
2124 _truncated_increment(_iv_bt),
2125 _stride(PhaseIdealLoop::LoopIVStride(_iv_bt)),
2126 _phi(nullptr),
2127 _safepoint(nullptr) {}
2128
2129 void build();
2130
2131 jlong final_limit_correction() const; // compute adjusted loop limit correction
2132 bool is_infinite_loop() const;
2133
2134 bool is_valid() const { return _is_valid; }
2135
2136 Node* back_control() const { return _back_control; }
2137 PhaseIdealLoop::LoopExitTest& exit_test() { return _exit_test; }
2138 PhaseIdealLoop::LoopIVIncr& iv_incr() { return _iv_incr; }
2139 TruncatedIncrement& truncated_increment() { return _truncated_increment; }
2140 PhaseIdealLoop::LoopIVStride& stride() { return _stride; }
2141 PhiNode* phi() const { return _phi; }
2142 SafePointNode* sfpt() const { return _safepoint; }
2143 jlong stride_con() const { return _stride.compute_non_zero_stride_con(_exit_test.mask(), _iv_bt); }
2144 Node* limit() const { return _exit_test.limit(); }
2145 };
2146
2147 PhaseIdealLoop* const _phase;
2148 Node* const _head;
2149 IdealLoopTree* const _loop;
2150 const BasicType _iv_bt;
2151
2152 LoopStructure _structure;
2153 bool _should_insert_stride_overflow_limit_check = false;
2154 bool _should_insert_init_trip_limit_check = false;
2155
2156 DEBUG_ONLY(bool _checked_for_counted_loop = false;)
2157
2158 // stats for PhaseIdealLoop::print_statistics()
2159 static volatile int _long_loop_counted_loops;
2160
2161 // Return a type based on condition control flow
2162 const TypeInt* filtered_type(Node* n, Node* n_ctrl);
2163 const TypeInt* filtered_type(Node* n) { return filtered_type(n, nullptr); }
2164 // Helpers for filtered type
2165 const TypeInt* filtered_type_from_dominators(Node* val, Node* val_ctrl);
2166
2167 void insert_loop_limit_check_predicate(const ParsePredicateSuccessProj* loop_limit_check_parse_proj, Node* bol) const;
2168 void insert_stride_overflow_limit_check() const;
2169 void insert_init_trip_limit_check() const;
2170 bool has_dominating_loop_limit_check(Node* init_trip, Node* limit, jlong stride_con, BasicType iv_bt,
2171 Node* loop_entry) const;
2172
2173 bool is_iv_overflowing(const TypeInteger* init_t, jlong stride_con, Node* phi_increment, BoolTest::mask mask) const;
2174 bool has_truncation_wrap(const TruncatedIncrement& truncation, Node* phi, jlong stride_con);
2175 SafePointNode* find_safepoint(Node* iftrue);
2176 bool is_safepoint_invalid(SafePointNode* sfpt) const;
2177
2178 public:
2179 CountedLoopConverter(PhaseIdealLoop* phase, Node* head, IdealLoopTree* loop, const BasicType iv_bt)
2180 : _phase(phase),
2181 _head(head),
2182 _loop(loop),
2183 _iv_bt(iv_bt),
2184 _structure(LoopStructure(_head, _loop, _phase, _iv_bt)) {
2185 assert(phase != nullptr, "must be"); // Fail early if mandatory parameters are null.
2186 assert(head != nullptr, "must be");
2187 assert(loop != nullptr, "must be");
2188 assert(iv_bt == T_INT || iv_bt == T_LONG, "either int or long loops");
2189 }
2190
2191 bool is_counted_loop();
2192 IdealLoopTree* convert();
2193
2194 DEBUG_ONLY(bool should_stress_long_counted_loop();)
2195 DEBUG_ONLY(bool stress_long_counted_loop();)
2196
2197 enum StrideOverflowState {
2198 Overflow = -1,
2199 NoOverflow = 0,
2200 RequireLimitCheck = 1
2201 };
2202 static StrideOverflowState check_stride_overflow(jlong final_correction, const TypeInteger* limit_t, BasicType bt);
2203 };
2204
2205 class AutoNodeBudget : public StackObj
2206 {
2207 public:
2208 enum budget_check_t { BUDGET_CHECK, NO_BUDGET_CHECK };
2209
2210 AutoNodeBudget(PhaseIdealLoop* phase, budget_check_t chk = BUDGET_CHECK)
2211 : _phase(phase),
2212 _check_at_final(chk == BUDGET_CHECK),
2213 _nodes_at_begin(0)
2214 {
2215 precond(_phase != nullptr);
2216
2217 _nodes_at_begin = _phase->require_nodes_begin();
2218 }
2219
2220 ~AutoNodeBudget() {
2221 #ifndef PRODUCT
2222 if (TraceLoopOpts) {
2223 uint request = _phase->nodes_required();
2224 uint delta = _phase->C->live_nodes() - _nodes_at_begin;
2225
2226 if (request < delta) {
2227 tty->print_cr("Exceeding node budget: %d < %d", request, delta);
2228 } else {
2229 uint const REQUIRE_MIN = PhaseIdealLoop::REQUIRE_MIN;
2230 // Identify the worst estimates as "poor" ones.
2231 if (request > REQUIRE_MIN && delta > 0) {
2232 if ((delta > REQUIRE_MIN && request > 3 * delta) ||
2233 (delta <= REQUIRE_MIN && request > 10 * delta)) {
2234 tty->print_cr("Poor node estimate: %d >> %d", request, delta);
2235 }
2236 }
2237 }
2238 }
2239 #endif // PRODUCT
2240 _phase->require_nodes_final(_nodes_at_begin, _check_at_final);
2241 }
2242
2243 private:
2244 PhaseIdealLoop* _phase;
2245 bool _check_at_final;
2246 uint _nodes_at_begin;
2247 };
2248
2249 inline Node* IdealLoopTree::tail() {
2250 // Handle lazy update of _tail field.
2251 if (_tail->in(0) == nullptr) {
2252 _tail = _phase->get_ctrl(_tail);
2253 }
2254 return _tail;
2255 }
2256
2257 inline Node* IdealLoopTree::head() {
2258 // Handle lazy update of _head field.
2259 if (_head->in(0) == nullptr) {
2260 _head = _phase->get_ctrl(_head);
2261 }
2262 return _head;
2263 }
2264
2265 // Iterate over the loop tree using a preorder, left-to-right traversal.
2266 //
2267 // Example that visits all counted loops from within PhaseIdealLoop
2268 //
2269 // for (LoopTreeIterator iter(_ltree_root); !iter.done(); iter.next()) {
2270 // IdealLoopTree* lpt = iter.current();
2271 // if (!lpt->is_counted()) continue;
2272 // ...
2273 class LoopTreeIterator : public StackObj {
2274 private:
2275 IdealLoopTree* _root;
2276 IdealLoopTree* _curnt;
2277
2278 public:
2279 LoopTreeIterator(IdealLoopTree* root) : _root(root), _curnt(root) {}
2280
2281 bool done() { return _curnt == nullptr; } // Finished iterating?
2282
2283 void next(); // Advance to next loop tree
2284
2285 IdealLoopTree* current() { return _curnt; } // Return current value of iterator.
2286 };
2287
2288 // Compute probability of reaching some CFG node from a fixed
2289 // dominating CFG node
2290 class PathFrequency {
2291 private:
2292 Node* _dom; // frequencies are computed relative to this node
2293 Node_Stack _stack;
2294 GrowableArray<float> _freqs_stack; // keep track of intermediate result at regions
2295 GrowableArray<float> _freqs; // cache frequencies
2296 PhaseIdealLoop* _phase;
2297
2298 float check_and_truncate_frequency(float f) {
2299 assert(f >= 0, "Incorrect frequency");
2300 // We do not perform an exact (f <= 1) check
2301 // this would be error prone with rounding of floats.
2302 // Performing a check like (f <= 1+eps) would be of benefit,
2303 // however, it is not evident how to determine such an eps,
2304 // given that an arbitrary number of add/mul operations
2305 // are performed on these frequencies.
2306 return (f > 1) ? 1 : f;
2307 }
2308
2309 public:
2310 PathFrequency(Node* dom, PhaseIdealLoop* phase)
2311 : _dom(dom), _stack(0), _phase(phase) {
2312 }
2313
2314 float to(Node* n);
2315 };
2316
2317 // Class to clone a data node graph by taking a list of data nodes. This is done in 2 steps:
2318 // 1. Clone the data nodes
2319 // 2. Fix the cloned data inputs pointing to the old nodes to the cloned inputs by using an old->new mapping.
2320 class DataNodeGraph : public StackObj {
2321 PhaseIdealLoop* const _phase;
2322 const Unique_Node_List& _data_nodes;
2323 OrigToNewHashtable _orig_to_new;
2324
2325 public:
2326 DataNodeGraph(const Unique_Node_List& data_nodes, PhaseIdealLoop* phase)
2327 : _phase(phase),
2328 _data_nodes(data_nodes),
2329 // Use 107 as best guess which is the first resize value in ResizeableHashTable::large_table_sizes.
2330 _orig_to_new(107, MaxNodeLimit)
2331 {
2332 #ifdef ASSERT
2333 for (uint i = 0; i < data_nodes.size(); i++) {
2334 assert(!data_nodes[i]->is_CFG(), "only data nodes");
2335 }
2336 #endif
2337 }
2338 NONCOPYABLE(DataNodeGraph);
2339
2340 private:
2341 void clone(Node* node, Node* new_ctrl);
2342 void clone_data_nodes(Node* new_ctrl);
2343 void clone_data_nodes_and_transform_opaque_loop_nodes(const TransformStrategyForOpaqueLoopNodes& transform_strategy,
2344 Node* new_ctrl);
2345 void rewire_clones_to_cloned_inputs();
2346 void transform_opaque_node(const TransformStrategyForOpaqueLoopNodes& transform_strategy, Node* node);
2347
2348 public:
2349 // Clone the provided data node collection and rewire the clones in such a way to create an identical graph copy.
2350 // Set 'new_ctrl' as ctrl for the cloned nodes.
2351 const OrigToNewHashtable& clone(Node* new_ctrl) {
2352 assert(_orig_to_new.number_of_entries() == 0, "should not call this method twice in a row");
2353 clone_data_nodes(new_ctrl);
2354 rewire_clones_to_cloned_inputs();
2355 return _orig_to_new;
2356 }
2357
2358 // Create a copy of the data nodes provided to the constructor by doing the following:
2359 // Clone all non-OpaqueLoop* nodes and rewire them to create an identical subgraph copy. For the OpaqueLoop* nodes,
2360 // apply the provided transformation strategy and include the transformed node into the subgraph copy to get a complete
2361 // "cloned-and-transformed" graph copy. For all newly cloned nodes (which could also be new OpaqueLoop* nodes), set
2362 // `new_ctrl` as ctrl.
2363 const OrigToNewHashtable& clone_with_opaque_loop_transform_strategy(
2364 const TransformStrategyForOpaqueLoopNodes& transform_strategy,
2365 Node* new_ctrl) {
2366 clone_data_nodes_and_transform_opaque_loop_nodes(transform_strategy, new_ctrl);
2367 rewire_clones_to_cloned_inputs();
2368 return _orig_to_new;
2369 }
2370 };
2371 #endif // SHARE_OPTO_LOOPNODE_HPP