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