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