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