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