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