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