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