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