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