1 /*
   2  * Copyright (c) 1998, 2025, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "ci/ciMethodData.hpp"
  27 #include "compiler/compileLog.hpp"
  28 #include "gc/shared/barrierSet.hpp"
  29 #include "gc/shared/c2/barrierSetC2.hpp"
  30 #include "libadt/vectset.hpp"
  31 #include "memory/allocation.inline.hpp"
  32 #include "memory/resourceArea.hpp"
  33 #include "opto/addnode.hpp"
  34 #include "opto/arraycopynode.hpp"
  35 #include "opto/callnode.hpp"
  36 #include "opto/castnode.hpp"
  37 #include "opto/connode.hpp"
  38 #include "opto/convertnode.hpp"
  39 #include "opto/divnode.hpp"
  40 #include "opto/idealGraphPrinter.hpp"
  41 #include "opto/loopnode.hpp"
  42 #include "opto/movenode.hpp"
  43 #include "opto/mulnode.hpp"
  44 #include "opto/opaquenode.hpp"
  45 #include "opto/predicates.hpp"
  46 #include "opto/rootnode.hpp"
  47 #include "opto/runtime.hpp"
  48 #include "opto/vectorization.hpp"
  49 #include "runtime/sharedRuntime.hpp"
  50 #include "utilities/checkedCast.hpp"
  51 #include "utilities/powerOfTwo.hpp"
  52 
  53 //=============================================================================
  54 //--------------------------is_cloop_ind_var-----------------------------------
  55 // Determine if a node is a counted loop induction variable.
  56 // NOTE: The method is declared in "node.hpp".
  57 bool Node::is_cloop_ind_var() const {
  58   return (is_Phi() &&
  59           as_Phi()->region()->is_CountedLoop() &&
  60           as_Phi()->region()->as_CountedLoop()->phi() == this);
  61 }
  62 
  63 //=============================================================================
  64 //------------------------------dump_spec--------------------------------------
  65 // Dump special per-node info
  66 #ifndef PRODUCT
  67 void LoopNode::dump_spec(outputStream *st) const {
  68   RegionNode::dump_spec(st);
  69   if (is_inner_loop()) st->print( "inner " );
  70   if (is_partial_peel_loop()) st->print( "partial_peel " );
  71   if (partial_peel_has_failed()) st->print( "partial_peel_failed " );
  72 }
  73 #endif
  74 
  75 //------------------------------is_valid_counted_loop-------------------------
  76 bool LoopNode::is_valid_counted_loop(BasicType bt) const {
  77   if (is_BaseCountedLoop() && as_BaseCountedLoop()->bt() == bt) {
  78     BaseCountedLoopNode*    l  = as_BaseCountedLoop();
  79     BaseCountedLoopEndNode* le = l->loopexit_or_null();
  80     if (le != nullptr &&
  81         le->proj_out_or_null(1 /* true */) == l->in(LoopNode::LoopBackControl)) {
  82       Node* phi  = l->phi();
  83       Node* exit = le->proj_out_or_null(0 /* false */);
  84       if (exit != nullptr && exit->Opcode() == Op_IfFalse &&
  85           phi != nullptr && phi->is_Phi() &&
  86           phi->in(LoopNode::LoopBackControl) == l->incr() &&
  87           le->loopnode() == l && le->stride_is_con()) {
  88         return true;
  89       }
  90     }
  91   }
  92   return false;
  93 }
  94 
  95 //------------------------------get_early_ctrl---------------------------------
  96 // Compute earliest legal control
  97 Node *PhaseIdealLoop::get_early_ctrl( Node *n ) {
  98   assert( !n->is_Phi() && !n->is_CFG(), "this code only handles data nodes" );
  99   uint i;
 100   Node *early;
 101   if (n->in(0) && !n->is_expensive()) {
 102     early = n->in(0);
 103     if (!early->is_CFG()) // Might be a non-CFG multi-def
 104       early = get_ctrl(early);        // So treat input as a straight data input
 105     i = 1;
 106   } else {
 107     early = get_ctrl(n->in(1));
 108     i = 2;
 109   }
 110   uint e_d = dom_depth(early);
 111   assert( early, "" );
 112   for (; i < n->req(); i++) {
 113     Node *cin = get_ctrl(n->in(i));
 114     assert( cin, "" );
 115     // Keep deepest dominator depth
 116     uint c_d = dom_depth(cin);
 117     if (c_d > e_d) {           // Deeper guy?
 118       early = cin;              // Keep deepest found so far
 119       e_d = c_d;
 120     } else if (c_d == e_d &&    // Same depth?
 121                early != cin) { // If not equal, must use slower algorithm
 122       // If same depth but not equal, one _must_ dominate the other
 123       // and we want the deeper (i.e., dominated) guy.
 124       Node *n1 = early;
 125       Node *n2 = cin;
 126       while (1) {
 127         n1 = idom(n1);          // Walk up until break cycle
 128         n2 = idom(n2);
 129         if (n1 == cin ||        // Walked early up to cin
 130             dom_depth(n2) < c_d)
 131           break;                // early is deeper; keep him
 132         if (n2 == early ||      // Walked cin up to early
 133             dom_depth(n1) < c_d) {
 134           early = cin;          // cin is deeper; keep him
 135           break;
 136         }
 137       }
 138       e_d = dom_depth(early);   // Reset depth register cache
 139     }
 140   }
 141 
 142   // Return earliest legal location
 143   assert(early == find_non_split_ctrl(early), "unexpected early control");
 144 
 145   if (n->is_expensive() && !_verify_only && !_verify_me) {
 146     assert(n->in(0), "should have control input");
 147     early = get_early_ctrl_for_expensive(n, early);
 148   }
 149 
 150   return early;
 151 }
 152 
 153 //------------------------------get_early_ctrl_for_expensive---------------------------------
 154 // Move node up the dominator tree as high as legal while still beneficial
 155 Node *PhaseIdealLoop::get_early_ctrl_for_expensive(Node *n, Node* earliest) {
 156   assert(n->in(0) && n->is_expensive(), "expensive node with control input here");
 157   assert(OptimizeExpensiveOps, "optimization off?");
 158 
 159   Node* ctl = n->in(0);
 160   assert(ctl->is_CFG(), "expensive input 0 must be cfg");
 161   uint min_dom_depth = dom_depth(earliest);
 162 #ifdef ASSERT
 163   if (!is_dominator(ctl, earliest) && !is_dominator(earliest, ctl)) {
 164     dump_bad_graph("Bad graph detected in get_early_ctrl_for_expensive", n, earliest, ctl);
 165     assert(false, "Bad graph detected in get_early_ctrl_for_expensive");
 166   }
 167 #endif
 168   if (dom_depth(ctl) < min_dom_depth) {
 169     return earliest;
 170   }
 171 
 172   while (true) {
 173     Node* next = ctl;
 174     // Moving the node out of a loop on the projection of an If
 175     // confuses Loop Predication. So, once we hit a loop in an If branch
 176     // that doesn't branch to an UNC, we stop. The code that process
 177     // expensive nodes will notice the loop and skip over it to try to
 178     // move the node further up.
 179     if (ctl->is_CountedLoop() && ctl->in(1) != nullptr && ctl->in(1)->in(0) != nullptr && ctl->in(1)->in(0)->is_If()) {
 180       if (!ctl->in(1)->as_Proj()->is_uncommon_trap_if_pattern()) {
 181         break;
 182       }
 183       next = idom(ctl->in(1)->in(0));
 184     } else if (ctl->is_Proj()) {
 185       // We only move it up along a projection if the projection is
 186       // the single control projection for its parent: same code path,
 187       // if it's a If with UNC or fallthrough of a call.
 188       Node* parent_ctl = ctl->in(0);
 189       if (parent_ctl == nullptr) {
 190         break;
 191       } else if (parent_ctl->is_CountedLoopEnd() && parent_ctl->as_CountedLoopEnd()->loopnode() != nullptr) {
 192         next = parent_ctl->as_CountedLoopEnd()->loopnode()->init_control();
 193       } else if (parent_ctl->is_If()) {
 194         if (!ctl->as_Proj()->is_uncommon_trap_if_pattern()) {
 195           break;
 196         }
 197         assert(idom(ctl) == parent_ctl, "strange");
 198         next = idom(parent_ctl);
 199       } else if (ctl->is_CatchProj()) {
 200         if (ctl->as_Proj()->_con != CatchProjNode::fall_through_index) {
 201           break;
 202         }
 203         assert(parent_ctl->in(0)->in(0)->is_Call(), "strange graph");
 204         next = parent_ctl->in(0)->in(0)->in(0);
 205       } else {
 206         // Check if parent control has a single projection (this
 207         // control is the only possible successor of the parent
 208         // control). If so, we can try to move the node above the
 209         // parent control.
 210         int nb_ctl_proj = 0;
 211         for (DUIterator_Fast imax, i = parent_ctl->fast_outs(imax); i < imax; i++) {
 212           Node *p = parent_ctl->fast_out(i);
 213           if (p->is_Proj() && p->is_CFG()) {
 214             nb_ctl_proj++;
 215             if (nb_ctl_proj > 1) {
 216               break;
 217             }
 218           }
 219         }
 220 
 221         if (nb_ctl_proj > 1) {
 222           break;
 223         }
 224         assert(parent_ctl->is_Start() || parent_ctl->is_MemBar() || parent_ctl->is_Call() ||
 225                BarrierSet::barrier_set()->barrier_set_c2()->is_gc_barrier_node(parent_ctl), "unexpected node");
 226         assert(idom(ctl) == parent_ctl, "strange");
 227         next = idom(parent_ctl);
 228       }
 229     } else {
 230       next = idom(ctl);
 231     }
 232     if (next->is_Root() || next->is_Start() || dom_depth(next) < min_dom_depth) {
 233       break;
 234     }
 235     ctl = next;
 236   }
 237 
 238   if (ctl != n->in(0)) {
 239     _igvn.replace_input_of(n, 0, ctl);
 240     _igvn.hash_insert(n);
 241   }
 242 
 243   return ctl;
 244 }
 245 
 246 
 247 //------------------------------set_early_ctrl---------------------------------
 248 // Set earliest legal control
 249 void PhaseIdealLoop::set_early_ctrl(Node* n, bool update_body) {
 250   Node *early = get_early_ctrl(n);
 251 
 252   // Record earliest legal location
 253   set_ctrl(n, early);
 254   IdealLoopTree *loop = get_loop(early);
 255   if (update_body && loop->_child == nullptr) {
 256     loop->_body.push(n);
 257   }
 258 }
 259 
 260 //------------------------------set_subtree_ctrl-------------------------------
 261 // set missing _ctrl entries on new nodes
 262 void PhaseIdealLoop::set_subtree_ctrl(Node* n, bool update_body) {
 263   // Already set?  Get out.
 264   if (_loop_or_ctrl[n->_idx]) return;
 265   // Recursively set _loop_or_ctrl array to indicate where the Node goes
 266   uint i;
 267   for (i = 0; i < n->req(); ++i) {
 268     Node *m = n->in(i);
 269     if (m && m != C->root()) {
 270       set_subtree_ctrl(m, update_body);
 271     }
 272   }
 273 
 274   // Fixup self
 275   set_early_ctrl(n, update_body);
 276 }
 277 
 278 IdealLoopTree* PhaseIdealLoop::insert_outer_loop(IdealLoopTree* loop, LoopNode* outer_l, Node* outer_ift) {
 279   IdealLoopTree* outer_ilt = new IdealLoopTree(this, outer_l, outer_ift);
 280   IdealLoopTree* parent = loop->_parent;
 281   IdealLoopTree* sibling = parent->_child;
 282   if (sibling == loop) {
 283     parent->_child = outer_ilt;
 284   } else {
 285     while (sibling->_next != loop) {
 286       sibling = sibling->_next;
 287     }
 288     sibling->_next = outer_ilt;
 289   }
 290   outer_ilt->_next = loop->_next;
 291   outer_ilt->_parent = parent;
 292   outer_ilt->_child = loop;
 293   outer_ilt->_nest = loop->_nest;
 294   loop->_parent = outer_ilt;
 295   loop->_next = nullptr;
 296   loop->_nest++;
 297   assert(loop->_nest <= SHRT_MAX, "sanity");
 298   return outer_ilt;
 299 }
 300 
 301 // Create a skeleton strip mined outer loop: a Loop head before the
 302 // inner strip mined loop, a safepoint and an exit condition guarded
 303 // by an opaque node after the inner strip mined loop with a backedge
 304 // to the loop head. The inner strip mined loop is left as it is. Only
 305 // once loop optimizations are over, do we adjust the inner loop exit
 306 // condition to limit its number of iterations, set the outer loop
 307 // exit condition and add Phis to the outer loop head. Some loop
 308 // optimizations that operate on the inner strip mined loop need to be
 309 // aware of the outer strip mined loop: loop unswitching needs to
 310 // clone the outer loop as well as the inner, unrolling needs to only
 311 // clone the inner loop etc. No optimizations need to change the outer
 312 // strip mined loop as it is only a skeleton.
 313 IdealLoopTree* PhaseIdealLoop::create_outer_strip_mined_loop(BoolNode *test, Node *cmp, Node *init_control,
 314                                                              IdealLoopTree* loop, float cl_prob, float le_fcnt,
 315                                                              Node*& entry_control, Node*& iffalse) {
 316   Node* outer_test = intcon(0);
 317   Node *orig = iffalse;
 318   iffalse = iffalse->clone();
 319   _igvn.register_new_node_with_optimizer(iffalse);
 320   set_idom(iffalse, idom(orig), dom_depth(orig));
 321 
 322   IfNode *outer_le = new OuterStripMinedLoopEndNode(iffalse, outer_test, cl_prob, le_fcnt);
 323   Node *outer_ift = new IfTrueNode (outer_le);
 324   Node* outer_iff = orig;
 325   _igvn.replace_input_of(outer_iff, 0, outer_le);
 326 
 327   LoopNode *outer_l = new OuterStripMinedLoopNode(C, init_control, outer_ift);
 328   entry_control = outer_l;
 329 
 330   IdealLoopTree* outer_ilt = insert_outer_loop(loop, outer_l, outer_ift);
 331 
 332   set_loop(iffalse, outer_ilt);
 333   // When this code runs, loop bodies have not yet been populated.
 334   const bool body_populated = false;
 335   register_control(outer_le, outer_ilt, iffalse, body_populated);
 336   register_control(outer_ift, outer_ilt, outer_le, body_populated);
 337   set_idom(outer_iff, outer_le, dom_depth(outer_le));
 338   _igvn.register_new_node_with_optimizer(outer_l);
 339   set_loop(outer_l, outer_ilt);
 340   set_idom(outer_l, init_control, dom_depth(init_control)+1);
 341 
 342   return outer_ilt;
 343 }
 344 
 345 void PhaseIdealLoop::insert_loop_limit_check_predicate(ParsePredicateSuccessProj* loop_limit_check_parse_proj,
 346                                                        Node* cmp_limit, Node* bol) {
 347   assert(loop_limit_check_parse_proj->in(0)->is_ParsePredicate(), "must be parse predicate");
 348   Node* new_predicate_proj = create_new_if_for_predicate(loop_limit_check_parse_proj, nullptr,
 349                                                          Deoptimization::Reason_loop_limit_check,
 350                                                          Op_If);
 351   Node* iff = new_predicate_proj->in(0);
 352   cmp_limit = _igvn.register_new_node_with_optimizer(cmp_limit);
 353   bol = _igvn.register_new_node_with_optimizer(bol);
 354   set_subtree_ctrl(bol, false);
 355   _igvn.replace_input_of(iff, 1, bol);
 356 
 357 #ifndef PRODUCT
 358   // report that the loop predication has been actually performed
 359   // for this loop
 360   if (TraceLoopLimitCheck) {
 361     tty->print_cr("Counted Loop Limit Check generated:");
 362     debug_only( bol->dump(2); )
 363   }
 364 #endif
 365 }
 366 
 367 Node* PhaseIdealLoop::loop_exit_control(Node* x, IdealLoopTree* loop) {
 368   // Counted loop head must be a good RegionNode with only 3 not null
 369   // control input edges: Self, Entry, LoopBack.
 370   if (x->in(LoopNode::Self) == nullptr || x->req() != 3 || loop->_irreducible) {
 371     return nullptr;
 372   }
 373   Node *init_control = x->in(LoopNode::EntryControl);
 374   Node *back_control = x->in(LoopNode::LoopBackControl);
 375   if (init_control == nullptr || back_control == nullptr) {   // Partially dead
 376     return nullptr;
 377   }
 378   // Must also check for TOP when looking for a dead loop
 379   if (init_control->is_top() || back_control->is_top()) {
 380     return nullptr;
 381   }
 382 
 383   // Allow funny placement of Safepoint
 384   if (back_control->Opcode() == Op_SafePoint) {
 385     back_control = back_control->in(TypeFunc::Control);
 386   }
 387 
 388   // Controlling test for loop
 389   Node *iftrue = back_control;
 390   uint iftrue_op = iftrue->Opcode();
 391   if (iftrue_op != Op_IfTrue &&
 392       iftrue_op != Op_IfFalse) {
 393     // I have a weird back-control.  Probably the loop-exit test is in
 394     // the middle of the loop and I am looking at some trailing control-flow
 395     // merge point.  To fix this I would have to partially peel the loop.
 396     return nullptr; // Obscure back-control
 397   }
 398 
 399   // Get boolean guarding loop-back test
 400   Node *iff = iftrue->in(0);
 401   if (get_loop(iff) != loop || !iff->in(1)->is_Bool()) {
 402     return nullptr;
 403   }
 404   return iftrue;
 405 }
 406 
 407 Node* PhaseIdealLoop::loop_exit_test(Node* back_control, IdealLoopTree* loop, Node*& incr, Node*& limit, BoolTest::mask& bt, float& cl_prob) {
 408   Node* iftrue = back_control;
 409   uint iftrue_op = iftrue->Opcode();
 410   Node* iff = iftrue->in(0);
 411   BoolNode* test = iff->in(1)->as_Bool();
 412   bt = test->_test._test;
 413   cl_prob = iff->as_If()->_prob;
 414   if (iftrue_op == Op_IfFalse) {
 415     bt = BoolTest(bt).negate();
 416     cl_prob = 1.0 - cl_prob;
 417   }
 418   // Get backedge compare
 419   Node* cmp = test->in(1);
 420   if (!cmp->is_Cmp()) {
 421     return nullptr;
 422   }
 423 
 424   // Find the trip-counter increment & limit.  Limit must be loop invariant.
 425   incr  = cmp->in(1);
 426   limit = cmp->in(2);
 427 
 428   // ---------
 429   // need 'loop()' test to tell if limit is loop invariant
 430   // ---------
 431 
 432   if (!is_member(loop, get_ctrl(incr))) { // Swapped trip counter and limit?
 433     Node* tmp = incr;            // Then reverse order into the CmpI
 434     incr = limit;
 435     limit = tmp;
 436     bt = BoolTest(bt).commute(); // And commute the exit test
 437   }
 438   if (is_member(loop, get_ctrl(limit))) { // Limit must be loop-invariant
 439     return nullptr;
 440   }
 441   if (!is_member(loop, get_ctrl(incr))) { // Trip counter must be loop-variant
 442     return nullptr;
 443   }
 444   return cmp;
 445 }
 446 
 447 Node* PhaseIdealLoop::loop_iv_incr(Node* incr, Node* x, IdealLoopTree* loop, Node*& phi_incr) {
 448   if (incr->is_Phi()) {
 449     if (incr->as_Phi()->region() != x || incr->req() != 3) {
 450       return nullptr; // Not simple trip counter expression
 451     }
 452     phi_incr = incr;
 453     incr = phi_incr->in(LoopNode::LoopBackControl); // Assume incr is on backedge of Phi
 454     if (!is_member(loop, get_ctrl(incr))) { // Trip counter must be loop-variant
 455       return nullptr;
 456     }
 457   }
 458   return incr;
 459 }
 460 
 461 Node* PhaseIdealLoop::loop_iv_stride(Node* incr, IdealLoopTree* loop, Node*& xphi) {
 462   assert(incr->Opcode() == Op_AddI || incr->Opcode() == Op_AddL, "caller resp.");
 463   // Get merge point
 464   xphi = incr->in(1);
 465   Node *stride = incr->in(2);
 466   if (!stride->is_Con()) {     // Oops, swap these
 467     if (!xphi->is_Con()) {     // Is the other guy a constant?
 468       return nullptr;          // Nope, unknown stride, bail out
 469     }
 470     Node *tmp = xphi;          // 'incr' is commutative, so ok to swap
 471     xphi = stride;
 472     stride = tmp;
 473   }
 474   return stride;
 475 }
 476 
 477 PhiNode* PhaseIdealLoop::loop_iv_phi(Node* xphi, Node* phi_incr, Node* x, IdealLoopTree* loop) {
 478   if (!xphi->is_Phi()) {
 479     return nullptr; // Too much math on the trip counter
 480   }
 481   if (phi_incr != nullptr && phi_incr != xphi) {
 482     return nullptr;
 483   }
 484   PhiNode *phi = xphi->as_Phi();
 485 
 486   // Phi must be of loop header; backedge must wrap to increment
 487   if (phi->region() != x) {
 488     return nullptr;
 489   }
 490   return phi;
 491 }
 492 
 493 static int check_stride_overflow(jlong final_correction, const TypeInteger* limit_t, BasicType bt) {
 494   if (final_correction > 0) {
 495     if (limit_t->lo_as_long() > (max_signed_integer(bt) - final_correction)) {
 496       return -1;
 497     }
 498     if (limit_t->hi_as_long() > (max_signed_integer(bt) - final_correction)) {
 499       return 1;
 500     }
 501   } else {
 502     if (limit_t->hi_as_long() < (min_signed_integer(bt) - final_correction)) {
 503       return -1;
 504     }
 505     if (limit_t->lo_as_long() < (min_signed_integer(bt) - final_correction)) {
 506       return 1;
 507     }
 508   }
 509   return 0;
 510 }
 511 
 512 static bool condition_stride_ok(BoolTest::mask bt, jlong stride_con) {
 513   // If the condition is inverted and we will be rolling
 514   // through MININT to MAXINT, then bail out.
 515   if (bt == BoolTest::eq || // Bail out, but this loop trips at most twice!
 516       // Odd stride
 517       (bt == BoolTest::ne && stride_con != 1 && stride_con != -1) ||
 518       // Count down loop rolls through MAXINT
 519       ((bt == BoolTest::le || bt == BoolTest::lt) && stride_con < 0) ||
 520       // Count up loop rolls through MININT
 521       ((bt == BoolTest::ge || bt == BoolTest::gt) && stride_con > 0)) {
 522     return false; // Bail out
 523   }
 524   return true;
 525 }
 526 
 527 Node* PhaseIdealLoop::loop_nest_replace_iv(Node* iv_to_replace, Node* inner_iv, Node* outer_phi, Node* inner_head,
 528                                            BasicType bt) {
 529   Node* iv_as_long;
 530   if (bt == T_LONG) {
 531     iv_as_long = new ConvI2LNode(inner_iv, TypeLong::INT);
 532     register_new_node(iv_as_long, inner_head);
 533   } else {
 534     iv_as_long = inner_iv;
 535   }
 536   Node* iv_replacement = AddNode::make(outer_phi, iv_as_long, bt);
 537   register_new_node(iv_replacement, inner_head);
 538   for (DUIterator_Last imin, i = iv_to_replace->last_outs(imin); i >= imin;) {
 539     Node* u = iv_to_replace->last_out(i);
 540 #ifdef ASSERT
 541     if (!is_dominator(inner_head, ctrl_or_self(u))) {
 542       assert(u->is_Phi(), "should be a Phi");
 543       for (uint j = 1; j < u->req(); j++) {
 544         if (u->in(j) == iv_to_replace) {
 545           assert(is_dominator(inner_head, u->in(0)->in(j)), "iv use above loop?");
 546         }
 547       }
 548     }
 549 #endif
 550     _igvn.rehash_node_delayed(u);
 551     int nb = u->replace_edge(iv_to_replace, iv_replacement, &_igvn);
 552     i -= nb;
 553   }
 554   return iv_replacement;
 555 }
 556 
 557 // Add a Parse Predicate with an uncommon trap on the failing/false path. Normal control will continue on the true path.
 558 void PhaseIdealLoop::add_parse_predicate(Deoptimization::DeoptReason reason, Node* inner_head, IdealLoopTree* loop,
 559                                          SafePointNode* sfpt) {
 560   if (!C->too_many_traps(reason)) {
 561     ParsePredicateNode* parse_predicate = new ParsePredicateNode(inner_head->in(LoopNode::EntryControl), reason, &_igvn);
 562     register_control(parse_predicate, loop, inner_head->in(LoopNode::EntryControl));
 563     Node* if_false = new IfFalseNode(parse_predicate);
 564     register_control(if_false, _ltree_root, parse_predicate);
 565     Node* if_true = new IfTrueNode(parse_predicate);
 566     register_control(if_true, loop, parse_predicate);
 567 
 568     int trap_request = Deoptimization::make_trap_request(reason, Deoptimization::Action_maybe_recompile);
 569     address call_addr = OptoRuntime::uncommon_trap_blob()->entry_point();
 570     const TypePtr* no_memory_effects = nullptr;
 571     JVMState* jvms = sfpt->jvms();
 572     CallNode* unc = new CallStaticJavaNode(OptoRuntime::uncommon_trap_Type(), call_addr, "uncommon_trap",
 573                                            no_memory_effects);
 574 
 575     Node* mem = nullptr;
 576     Node* i_o = nullptr;
 577     if (sfpt->is_Call()) {
 578       mem = sfpt->proj_out(TypeFunc::Memory);
 579       i_o = sfpt->proj_out(TypeFunc::I_O);
 580     } else {
 581       mem = sfpt->memory();
 582       i_o = sfpt->i_o();
 583     }
 584 
 585     Node *frame = new ParmNode(C->start(), TypeFunc::FramePtr);
 586     register_new_node(frame, C->start());
 587     Node *ret = new ParmNode(C->start(), TypeFunc::ReturnAdr);
 588     register_new_node(ret, C->start());
 589 
 590     unc->init_req(TypeFunc::Control, if_false);
 591     unc->init_req(TypeFunc::I_O, i_o);
 592     unc->init_req(TypeFunc::Memory, mem); // may gc ptrs
 593     unc->init_req(TypeFunc::FramePtr, frame);
 594     unc->init_req(TypeFunc::ReturnAdr, ret);
 595     unc->init_req(TypeFunc::Parms+0, _igvn.intcon(trap_request));
 596     unc->set_cnt(PROB_UNLIKELY_MAG(4));
 597     unc->copy_call_debug_info(&_igvn, sfpt);
 598 
 599     for (uint i = TypeFunc::Parms; i < unc->req(); i++) {
 600       set_subtree_ctrl(unc->in(i), false);
 601     }
 602     register_control(unc, _ltree_root, if_false);
 603 
 604     Node* ctrl = new ProjNode(unc, TypeFunc::Control);
 605     register_control(ctrl, _ltree_root, unc);
 606     Node* halt = new HaltNode(ctrl, frame, "uncommon trap returned which should never happen" PRODUCT_ONLY(COMMA /*reachable*/false));
 607     register_control(halt, _ltree_root, ctrl);
 608     _igvn.add_input_to(C->root(), halt);
 609 
 610     _igvn.replace_input_of(inner_head, LoopNode::EntryControl, if_true);
 611     set_idom(inner_head, if_true, dom_depth(inner_head));
 612   }
 613 }
 614 
 615 // Find a safepoint node that dominates the back edge. We need a
 616 // SafePointNode so we can use its jvm state to create empty
 617 // predicates.
 618 static bool no_side_effect_since_safepoint(Compile* C, Node* x, Node* mem, MergeMemNode* mm, PhaseIdealLoop* phase) {
 619   SafePointNode* safepoint = nullptr;
 620   for (DUIterator_Fast imax, i = x->fast_outs(imax); i < imax; i++) {
 621     Node* u = x->fast_out(i);
 622     if (u->is_memory_phi()) {
 623       Node* m = u->in(LoopNode::LoopBackControl);
 624       if (u->adr_type() == TypePtr::BOTTOM) {
 625         if (m->is_MergeMem() && mem->is_MergeMem()) {
 626           if (m != mem DEBUG_ONLY(|| true)) {
 627             // MergeMemStream can modify m, for example to adjust the length to mem.
 628             // This is unfortunate, and probably unnecessary. But as it is, we need
 629             // to add m to the igvn worklist, else we may have a modified node that
 630             // is not on the igvn worklist.
 631             phase->igvn()._worklist.push(m);
 632             for (MergeMemStream mms(m->as_MergeMem(), mem->as_MergeMem()); mms.next_non_empty2(); ) {
 633               if (!mms.is_empty()) {
 634                 if (mms.memory() != mms.memory2()) {
 635                   return false;
 636                 }
 637 #ifdef ASSERT
 638                 if (mms.alias_idx() != Compile::AliasIdxBot) {
 639                   mm->set_memory_at(mms.alias_idx(), mem->as_MergeMem()->base_memory());
 640                 }
 641 #endif
 642               }
 643             }
 644           }
 645         } else if (mem->is_MergeMem()) {
 646           if (m != mem->as_MergeMem()->base_memory()) {
 647             return false;
 648           }
 649         } else {
 650           return false;
 651         }
 652       } else {
 653         if (mem->is_MergeMem()) {
 654           if (m != mem->as_MergeMem()->memory_at(C->get_alias_index(u->adr_type()))) {
 655             return false;
 656           }
 657 #ifdef ASSERT
 658           mm->set_memory_at(C->get_alias_index(u->adr_type()), mem->as_MergeMem()->base_memory());
 659 #endif
 660         } else {
 661           if (m != mem) {
 662             return false;
 663           }
 664         }
 665       }
 666     }
 667   }
 668   return true;
 669 }
 670 
 671 SafePointNode* PhaseIdealLoop::find_safepoint(Node* back_control, Node* x, IdealLoopTree* loop) {
 672   IfNode* exit_test = back_control->in(0)->as_If();
 673   SafePointNode* safepoint = nullptr;
 674   if (exit_test->in(0)->is_SafePoint() && exit_test->in(0)->outcnt() == 1) {
 675     safepoint = exit_test->in(0)->as_SafePoint();
 676   } else {
 677     Node* c = back_control;
 678     while (c != x && c->Opcode() != Op_SafePoint) {
 679       c = idom(c);
 680     }
 681 
 682     if (c->Opcode() == Op_SafePoint) {
 683       safepoint = c->as_SafePoint();
 684     }
 685 
 686     if (safepoint == nullptr) {
 687       return nullptr;
 688     }
 689 
 690     Node* mem = safepoint->in(TypeFunc::Memory);
 691 
 692     // We can only use that safepoint if there's no side effect between the backedge and the safepoint.
 693 
 694     // mm is the memory state at the safepoint (when it's a MergeMem)
 695     // no_side_effect_since_safepoint() goes over the memory state at the backedge. It resets the mm input for each
 696     // component of the memory state it encounters so it points to the base memory. Once no_side_effect_since_safepoint()
 697     // is done, if no side effect after the safepoint was found, mm should transform to the base memory: the states at
 698     // the backedge and safepoint are the same so all components of the memory state at the safepoint should have been
 699     // reset.
 700     MergeMemNode* mm = nullptr;
 701 #ifdef ASSERT
 702     if (mem->is_MergeMem()) {
 703       mm = mem->clone()->as_MergeMem();
 704       _igvn._worklist.push(mm);
 705       for (MergeMemStream mms(mem->as_MergeMem()); mms.next_non_empty(); ) {
 706         // Loop invariant memory state won't be reset by no_side_effect_since_safepoint(). Do it here.
 707         // Escape Analysis can add state to mm that it doesn't add to the backedge memory Phis, breaking verification
 708         // code that relies on mm. Clear that extra state here.
 709         if (mms.alias_idx() != Compile::AliasIdxBot &&
 710             (loop != get_loop(ctrl_or_self(mms.memory())) ||
 711              (mms.adr_type()->isa_oop_ptr() && mms.adr_type()->is_known_instance()))) {
 712           mm->set_memory_at(mms.alias_idx(), mem->as_MergeMem()->base_memory());
 713         }
 714       }
 715     }
 716 #endif
 717     if (!no_side_effect_since_safepoint(C, x, mem, mm, this)) {
 718       safepoint = nullptr;
 719     } else {
 720       assert(mm == nullptr|| _igvn.transform(mm) == mem->as_MergeMem()->base_memory(), "all memory state should have been processed");
 721     }
 722 #ifdef ASSERT
 723     if (mm != nullptr) {
 724       _igvn.remove_dead_node(mm);
 725     }
 726 #endif
 727   }
 728   return safepoint;
 729 }
 730 
 731 // If the loop has the shape of a counted loop but with a long
 732 // induction variable, transform the loop in a loop nest: an inner
 733 // loop that iterates for at most max int iterations with an integer
 734 // induction variable and an outer loop that iterates over the full
 735 // range of long values from the initial loop in (at most) max int
 736 // steps. That is:
 737 //
 738 // x: for (long phi = init; phi < limit; phi += stride) {
 739 //   // phi := Phi(L, init, incr)
 740 //   // incr := AddL(phi, longcon(stride))
 741 //   long incr = phi + stride;
 742 //   ... use phi and incr ...
 743 // }
 744 //
 745 // OR:
 746 //
 747 // x: for (long phi = init; (phi += stride) < limit; ) {
 748 //   // phi := Phi(L, AddL(init, stride), incr)
 749 //   // incr := AddL(phi, longcon(stride))
 750 //   long incr = phi + stride;
 751 //   ... use phi and (phi + stride) ...
 752 // }
 753 //
 754 // ==transform=>
 755 //
 756 // const ulong inner_iters_limit = INT_MAX - stride - 1;  //near 0x7FFFFFF0
 757 // assert(stride <= inner_iters_limit);  // else abort transform
 758 // assert((extralong)limit + stride <= LONG_MAX);  // else deopt
 759 // outer_head: for (long outer_phi = init;;) {
 760 //   // outer_phi := Phi(outer_head, init, AddL(outer_phi, I2L(inner_phi)))
 761 //   ulong inner_iters_max = (ulong) MAX(0, ((extralong)limit + stride - outer_phi));
 762 //   long inner_iters_actual = MIN(inner_iters_limit, inner_iters_max);
 763 //   assert(inner_iters_actual == (int)inner_iters_actual);
 764 //   int inner_phi, inner_incr;
 765 //   x: for (inner_phi = 0;; inner_phi = inner_incr) {
 766 //     // inner_phi := Phi(x, intcon(0), inner_incr)
 767 //     // inner_incr := AddI(inner_phi, intcon(stride))
 768 //     inner_incr = inner_phi + stride;
 769 //     if (inner_incr < inner_iters_actual) {
 770 //       ... use phi=>(outer_phi+inner_phi) ...
 771 //       continue;
 772 //     }
 773 //     else break;
 774 //   }
 775 //   if ((outer_phi+inner_phi) < limit)  //OR (outer_phi+inner_incr) < limit
 776 //     continue;
 777 //   else break;
 778 // }
 779 //
 780 // The same logic is used to transform an int counted loop that contains long range checks into a loop nest of 2 int
 781 // loops with long range checks transformed to int range checks in the inner loop.
 782 bool PhaseIdealLoop::create_loop_nest(IdealLoopTree* loop, Node_List &old_new) {
 783   Node* x = loop->_head;
 784   // Only for inner loops
 785   if (loop->_child != nullptr || !x->is_BaseCountedLoop() || x->as_Loop()->is_loop_nest_outer_loop()) {
 786     return false;
 787   }
 788 
 789   if (x->is_CountedLoop() && !x->as_CountedLoop()->is_main_loop() && !x->as_CountedLoop()->is_normal_loop()) {
 790     return false;
 791   }
 792 
 793   BaseCountedLoopNode* head = x->as_BaseCountedLoop();
 794   BasicType bt = x->as_BaseCountedLoop()->bt();
 795 
 796   check_counted_loop_shape(loop, x, bt);
 797 
 798 #ifndef PRODUCT
 799   if (bt == T_LONG) {
 800     Atomic::inc(&_long_loop_candidates);
 801   }
 802 #endif
 803 
 804   jlong stride_con_long = head->stride_con();
 805   assert(stride_con_long != 0, "missed some peephole opt");
 806   // We can't iterate for more than max int at a time.
 807   if (stride_con_long != (jint)stride_con_long || stride_con_long == min_jint) {
 808     assert(bt == T_LONG, "only for long loops");
 809     return false;
 810   }
 811   jint stride_con = checked_cast<jint>(stride_con_long);
 812   // The number of iterations for the integer count loop: guarantee no
 813   // overflow: max_jint - stride_con max. -1 so there's no need for a
 814   // loop limit check if the exit test is <= or >=.
 815   int iters_limit = max_jint - ABS(stride_con) - 1;
 816 #ifdef ASSERT
 817   if (bt == T_LONG && StressLongCountedLoop > 0) {
 818     iters_limit = iters_limit / StressLongCountedLoop;
 819   }
 820 #endif
 821   // At least 2 iterations so counted loop construction doesn't fail
 822   if (iters_limit/ABS(stride_con) < 2) {
 823     return false;
 824   }
 825 
 826   PhiNode* phi = head->phi()->as_Phi();
 827   Node* incr = head->incr();
 828 
 829   Node* back_control = head->in(LoopNode::LoopBackControl);
 830 
 831   // data nodes on back branch not supported
 832   if (back_control->outcnt() > 1) {
 833     return false;
 834   }
 835 
 836   Node* limit = head->limit();
 837   // We'll need to use the loop limit before the inner loop is entered
 838   if (!is_dominator(get_ctrl(limit), x)) {
 839     return false;
 840   }
 841 
 842   IfNode* exit_test = head->loopexit();
 843 
 844   assert(back_control->Opcode() == Op_IfTrue, "wrong projection for back edge");
 845 
 846   Node_List range_checks;
 847   iters_limit = extract_long_range_checks(loop, stride_con, iters_limit, phi, range_checks);
 848 
 849   if (bt == T_INT) {
 850     // The only purpose of creating a loop nest is to handle long range checks. If there are none, do not proceed further.
 851     if (range_checks.size() == 0) {
 852       return false;
 853     }
 854   }
 855 
 856   // Take what we know about the number of iterations of the long counted loop into account when computing the limit of
 857   // the inner loop.
 858   const Node* init = head->init_trip();
 859   const TypeInteger* lo = _igvn.type(init)->is_integer(bt);
 860   const TypeInteger* hi = _igvn.type(limit)->is_integer(bt);
 861   if (stride_con < 0) {
 862     swap(lo, hi);
 863   }
 864   if (hi->hi_as_long() <= lo->lo_as_long()) {
 865     // not a loop after all
 866     return false;
 867   }
 868 
 869   if (range_checks.size() > 0) {
 870     // This transformation requires peeling one iteration. Also, if it has range checks and they are eliminated by Loop
 871     // Predication, then 2 Hoisted Check Predicates are added for one range check. Finally, transforming a long range
 872     // check requires extra logic to be executed before the loop is entered and for the outer loop. As a result, the
 873     // transformations can't pay off for a small number of iterations: roughly, if the loop runs for 3 iterations, it's
 874     // going to execute as many range checks once transformed with range checks eliminated (1 peeled iteration with
 875     // range checks + 2 predicates per range checks) as it would have not transformed. It also has to pay for the extra
 876     // logic on loop entry and for the outer loop.
 877     loop->compute_trip_count(this);
 878     if (head->is_CountedLoop() && head->as_CountedLoop()->has_exact_trip_count()) {
 879       if (head->as_CountedLoop()->trip_count() <= 3) {
 880         return false;
 881       }
 882     } else {
 883       loop->compute_profile_trip_cnt(this);
 884       if (!head->is_profile_trip_failed() && head->profile_trip_cnt() <= 3) {
 885         return false;
 886       }
 887     }
 888   }
 889 
 890   julong orig_iters = (julong)hi->hi_as_long() - lo->lo_as_long();
 891   iters_limit = checked_cast<int>(MIN2((julong)iters_limit, orig_iters));
 892 
 893   // We need a safepoint to insert Parse Predicates for the inner loop.
 894   SafePointNode* safepoint;
 895   if (bt == T_INT && head->as_CountedLoop()->is_strip_mined()) {
 896     // Loop is strip mined: use the safepoint of the outer strip mined loop
 897     OuterStripMinedLoopNode* outer_loop = head->as_CountedLoop()->outer_loop();
 898     assert(outer_loop != nullptr, "no outer loop");
 899     safepoint = outer_loop->outer_safepoint();
 900     outer_loop->transform_to_counted_loop(&_igvn, this);
 901     exit_test = head->loopexit();
 902   } else {
 903     safepoint = find_safepoint(back_control, x, loop);
 904   }
 905 
 906   Node* exit_branch = exit_test->proj_out(false);
 907   Node* entry_control = head->in(LoopNode::EntryControl);
 908 
 909   // Clone the control flow of the loop to build an outer loop
 910   Node* outer_back_branch = back_control->clone();
 911   Node* outer_exit_test = new IfNode(exit_test->in(0), exit_test->in(1), exit_test->_prob, exit_test->_fcnt);
 912   Node* inner_exit_branch = exit_branch->clone();
 913 
 914   LoopNode* outer_head = new LoopNode(entry_control, outer_back_branch);
 915   IdealLoopTree* outer_ilt = insert_outer_loop(loop, outer_head, outer_back_branch);
 916 
 917   const bool body_populated = true;
 918   register_control(outer_head, outer_ilt, entry_control, body_populated);
 919 
 920   _igvn.register_new_node_with_optimizer(inner_exit_branch);
 921   set_loop(inner_exit_branch, outer_ilt);
 922   set_idom(inner_exit_branch, exit_test, dom_depth(exit_branch));
 923 
 924   outer_exit_test->set_req(0, inner_exit_branch);
 925   register_control(outer_exit_test, outer_ilt, inner_exit_branch, body_populated);
 926 
 927   _igvn.replace_input_of(exit_branch, 0, outer_exit_test);
 928   set_idom(exit_branch, outer_exit_test, dom_depth(exit_branch));
 929 
 930   outer_back_branch->set_req(0, outer_exit_test);
 931   register_control(outer_back_branch, outer_ilt, outer_exit_test, body_populated);
 932 
 933   _igvn.replace_input_of(x, LoopNode::EntryControl, outer_head);
 934   set_idom(x, outer_head, dom_depth(x));
 935 
 936   // add an iv phi to the outer loop and use it to compute the inner
 937   // loop iteration limit
 938   Node* outer_phi = phi->clone();
 939   outer_phi->set_req(0, outer_head);
 940   register_new_node(outer_phi, outer_head);
 941 
 942   Node* inner_iters_max = nullptr;
 943   if (stride_con > 0) {
 944     inner_iters_max = MaxNode::max_diff_with_zero(limit, outer_phi, TypeInteger::bottom(bt), _igvn);
 945   } else {
 946     inner_iters_max = MaxNode::max_diff_with_zero(outer_phi, limit, TypeInteger::bottom(bt), _igvn);
 947   }
 948 
 949   Node* inner_iters_limit = _igvn.integercon(iters_limit, bt);
 950   // inner_iters_max may not fit in a signed integer (iterating from
 951   // Long.MIN_VALUE to Long.MAX_VALUE for instance). Use an unsigned
 952   // min.
 953   const TypeInteger* inner_iters_actual_range = TypeInteger::make(0, iters_limit, Type::WidenMin, bt);
 954   Node* inner_iters_actual = MaxNode::unsigned_min(inner_iters_max, inner_iters_limit, inner_iters_actual_range, _igvn);
 955 
 956   Node* inner_iters_actual_int;
 957   if (bt == T_LONG) {
 958     inner_iters_actual_int = new ConvL2INode(inner_iters_actual);
 959     _igvn.register_new_node_with_optimizer(inner_iters_actual_int);
 960     // When the inner loop is transformed to a counted loop, a loop limit check is not expected to be needed because
 961     // the loop limit is less or equal to max_jint - stride - 1 (if stride is positive but a similar argument exists for
 962     // a negative stride). We add a CastII here to guarantee that, when the counted loop is created in a subsequent loop
 963     // opts pass, an accurate range of values for the limits is found.
 964     const TypeInt* inner_iters_actual_int_range = TypeInt::make(0, iters_limit, Type::WidenMin);
 965     inner_iters_actual_int = new CastIINode(outer_head, inner_iters_actual_int, inner_iters_actual_int_range, ConstraintCastNode::UnconditionalDependency);
 966     _igvn.register_new_node_with_optimizer(inner_iters_actual_int);
 967   } else {
 968     inner_iters_actual_int = inner_iters_actual;
 969   }
 970 
 971   Node* int_zero = intcon(0);
 972   if (stride_con < 0) {
 973     inner_iters_actual_int = new SubINode(int_zero, inner_iters_actual_int);
 974     _igvn.register_new_node_with_optimizer(inner_iters_actual_int);
 975   }
 976 
 977   // Clone the iv data nodes as an integer iv
 978   Node* int_stride = intcon(stride_con);
 979   Node* inner_phi = new PhiNode(x->in(0), TypeInt::INT);
 980   Node* inner_incr = new AddINode(inner_phi, int_stride);
 981   Node* inner_cmp = nullptr;
 982   inner_cmp = new CmpINode(inner_incr, inner_iters_actual_int);
 983   Node* inner_bol = new BoolNode(inner_cmp, exit_test->in(1)->as_Bool()->_test._test);
 984   inner_phi->set_req(LoopNode::EntryControl, int_zero);
 985   inner_phi->set_req(LoopNode::LoopBackControl, inner_incr);
 986   register_new_node(inner_phi, x);
 987   register_new_node(inner_incr, x);
 988   register_new_node(inner_cmp, x);
 989   register_new_node(inner_bol, x);
 990 
 991   _igvn.replace_input_of(exit_test, 1, inner_bol);
 992 
 993   // Clone inner loop phis to outer loop
 994   for (uint i = 0; i < head->outcnt(); i++) {
 995     Node* u = head->raw_out(i);
 996     if (u->is_Phi() && u != inner_phi && u != phi) {
 997       assert(u->in(0) == head, "inconsistent");
 998       Node* clone = u->clone();
 999       clone->set_req(0, outer_head);
1000       register_new_node(clone, outer_head);
1001       _igvn.replace_input_of(u, LoopNode::EntryControl, clone);
1002     }
1003   }
1004 
1005   // Replace inner loop long iv phi as inner loop int iv phi + outer
1006   // loop iv phi
1007   Node* iv_add = loop_nest_replace_iv(phi, inner_phi, outer_phi, head, bt);
1008 
1009   set_subtree_ctrl(inner_iters_actual_int, body_populated);
1010 
1011   LoopNode* inner_head = create_inner_head(loop, head, exit_test);
1012 
1013   // Summary of steps from initial loop to loop nest:
1014   //
1015   // == old IR nodes =>
1016   //
1017   // entry_control: {...}
1018   // x:
1019   // for (long phi = init;;) {
1020   //   // phi := Phi(x, init, incr)
1021   //   // incr := AddL(phi, longcon(stride))
1022   //   exit_test:
1023   //   if (phi < limit)
1024   //     back_control: fallthrough;
1025   //   else
1026   //     exit_branch: break;
1027   //   long incr = phi + stride;
1028   //   ... use phi and incr ...
1029   //   phi = incr;
1030   // }
1031   //
1032   // == new IR nodes (just before final peel) =>
1033   //
1034   // entry_control: {...}
1035   // long adjusted_limit = limit + stride;  //because phi_incr != nullptr
1036   // assert(!limit_check_required || (extralong)limit + stride == adjusted_limit);  // else deopt
1037   // ulong inner_iters_limit = max_jint - ABS(stride) - 1;  //near 0x7FFFFFF0
1038   // outer_head:
1039   // for (long outer_phi = init;;) {
1040   //   // outer_phi := phi->clone(), in(0):=outer_head, => Phi(outer_head, init, incr)
1041   //   // REPLACE phi  => AddL(outer_phi, I2L(inner_phi))
1042   //   // REPLACE incr => AddL(outer_phi, I2L(inner_incr))
1043   //   // SO THAT outer_phi := Phi(outer_head, init, AddL(outer_phi, I2L(inner_incr)))
1044   //   ulong inner_iters_max = (ulong) MAX(0, ((extralong)adjusted_limit - outer_phi) * SGN(stride));
1045   //   int inner_iters_actual_int = (int) MIN(inner_iters_limit, inner_iters_max) * SGN(stride);
1046   //   inner_head: x: //in(1) := outer_head
1047   //   int inner_phi;
1048   //   for (inner_phi = 0;;) {
1049   //     // inner_phi := Phi(x, intcon(0), inner_phi + stride)
1050   //     int inner_incr = inner_phi + stride;
1051   //     bool inner_bol = (inner_incr < inner_iters_actual_int);
1052   //     exit_test: //exit_test->in(1) := inner_bol;
1053   //     if (inner_bol) // WAS (phi < limit)
1054   //       back_control: fallthrough;
1055   //     else
1056   //       inner_exit_branch: break;  //exit_branch->clone()
1057   //     ... use phi=>(outer_phi+inner_phi) ...
1058   //     inner_phi = inner_phi + stride;  // inner_incr
1059   //   }
1060   //   outer_exit_test:  //exit_test->clone(), in(0):=inner_exit_branch
1061   //   if ((outer_phi+inner_phi) < limit)  // WAS (phi < limit)
1062   //     outer_back_branch: fallthrough;  //back_control->clone(), in(0):=outer_exit_test
1063   //   else
1064   //     exit_branch: break;  //in(0) := outer_exit_test
1065   // }
1066 
1067   if (bt == T_INT) {
1068     outer_phi = new ConvI2LNode(outer_phi);
1069     register_new_node(outer_phi, outer_head);
1070   }
1071 
1072   transform_long_range_checks(stride_con, range_checks, outer_phi, inner_iters_actual_int,
1073                               inner_phi, iv_add, inner_head);
1074   // Peel one iteration of the loop and use the safepoint at the end
1075   // of the peeled iteration to insert Parse Predicates. If no well
1076   // positioned safepoint peel to guarantee a safepoint in the outer
1077   // loop.
1078   if (safepoint != nullptr || !loop->_has_call) {
1079     old_new.clear();
1080     do_peeling(loop, old_new);
1081   } else {
1082     C->set_major_progress();
1083   }
1084 
1085   if (safepoint != nullptr) {
1086     SafePointNode* cloned_sfpt = old_new[safepoint->_idx]->as_SafePoint();
1087 
1088     if (UseLoopPredicate) {
1089       add_parse_predicate(Deoptimization::Reason_predicate, inner_head, outer_ilt, cloned_sfpt);
1090     }
1091     if (UseProfiledLoopPredicate) {
1092       add_parse_predicate(Deoptimization::Reason_profile_predicate, inner_head, outer_ilt, cloned_sfpt);
1093     }
1094     add_parse_predicate(Deoptimization::Reason_loop_limit_check, inner_head, outer_ilt, cloned_sfpt);
1095   }
1096 
1097 #ifndef PRODUCT
1098   if (bt == T_LONG) {
1099     Atomic::inc(&_long_loop_nests);
1100   }
1101 #endif
1102 
1103   inner_head->mark_loop_nest_inner_loop();
1104   outer_head->mark_loop_nest_outer_loop();
1105 
1106   return true;
1107 }
1108 
1109 int PhaseIdealLoop::extract_long_range_checks(const IdealLoopTree* loop, jint stride_con, int iters_limit, PhiNode* phi,
1110                                               Node_List& range_checks) {
1111   const jlong min_iters = 2;
1112   jlong reduced_iters_limit = iters_limit;
1113   jlong original_iters_limit = iters_limit;
1114   for (uint i = 0; i < loop->_body.size(); i++) {
1115     Node* c = loop->_body.at(i);
1116     if (c->is_IfProj() && c->in(0)->is_RangeCheck()) {
1117       IfProjNode* if_proj = c->as_IfProj();
1118       CallStaticJavaNode* call = if_proj->is_uncommon_trap_if_pattern();
1119       if (call != nullptr) {
1120         Node* range = nullptr;
1121         Node* offset = nullptr;
1122         jlong scale = 0;
1123         if (loop->is_range_check_if(if_proj, this, T_LONG, phi, range, offset, scale) &&
1124             loop->is_invariant(range) && loop->is_invariant(offset) &&
1125             scale != min_jlong &&
1126             original_iters_limit / ABS(scale) >= min_iters * ABS(stride_con)) {
1127           assert(scale == (jint)scale, "scale should be an int");
1128           reduced_iters_limit = MIN2(reduced_iters_limit, original_iters_limit/ABS(scale));
1129           range_checks.push(c);
1130         }
1131       }
1132     }
1133   }
1134 
1135   return checked_cast<int>(reduced_iters_limit);
1136 }
1137 
1138 // One execution of the inner loop covers a sub-range of the entire iteration range of the loop: [A,Z), aka [A=init,
1139 // Z=limit). If the loop has at least one trip (which is the case here), the iteration variable i always takes A as its
1140 // first value, followed by A+S (S is the stride), next A+2S, etc. The limit is exclusive, so that the final value B of
1141 // i is never Z.  It will be B=Z-1 if S=1, or B=Z+1 if S=-1.
1142 
1143 // If |S|>1 the formula for the last value B would require a floor operation, specifically B=floor((Z-sgn(S)-A)/S)*S+A,
1144 // which is B=Z-sgn(S)U for some U in [1,|S|].  So when S>0, i ranges as i:[A,Z) or i:[A,B=Z-U], or else (in reverse)
1145 // as i:(Z,A] or i:[B=Z+U,A].  It will become important to reason about this inclusive range [A,B] or [B,A].
1146 
1147 // Within the loop there may be many range checks.  Each such range check (R.C.) is of the form 0 <= i*K+L < R, where K
1148 // is a scale factor applied to the loop iteration variable i, and L is some offset; K, L, and R are loop-invariant.
1149 // Because R is never negative (see below), this check can always be simplified to an unsigned check i*K+L <u R.
1150 
1151 // When a long loop over a 64-bit variable i (outer_iv) is decomposed into a series of shorter sub-loops over a 32-bit
1152 // variable j (inner_iv), j ranges over a shorter interval j:[0,B_2] or [0,Z_2) (assuming S > 0), where the limit is
1153 // chosen to prevent various cases of 32-bit overflow (including multiplications j*K below).  In the sub-loop the
1154 // logical value i is offset from j by a 64-bit constant C, so i ranges in i:C+[0,Z_2).
1155 
1156 // For S<0, j ranges (in reverse!) through j:[-|B_2|,0] or (-|Z_2|,0].  For either sign of S, we can say i=j+C and j
1157 // ranges through 32-bit ranges [A_2,B_2] or [B_2,A_2] (A_2=0 of course).
1158 
1159 // The disjoint union of all the C+[A_2,B_2] ranges from the sub-loops must be identical to the whole range [A,B].
1160 // Assuming S>0, the first C must be A itself, and the next C value is the previous C+B_2, plus S.  If |S|=1, the next
1161 // C value is also the previous C+Z_2.  In each sub-loop, j counts from j=A_2=0 and i counts from C+0 and exits at
1162 // j=B_2 (i=C+B_2), just before it gets to i=C+Z_2.  Both i and j count up (from C and 0) if S>0; otherwise they count
1163 // down (from C and 0 again).
1164 
1165 // Returning to range checks, we see that each i*K+L <u R expands to (C+j)*K+L <u R, or j*K+Q <u R, where Q=(C*K+L).
1166 // (Recall that K and L and R are loop-invariant scale, offset and range values for a particular R.C.)  This is still a
1167 // 64-bit comparison, so the range check elimination logic will not apply to it.  (The R.C.E. transforms operate only on
1168 // 32-bit indexes and comparisons, because they use 64-bit temporary values to avoid overflow; see
1169 // PhaseIdealLoop::add_constraint.)
1170 
1171 // We must transform this comparison so that it gets the same answer, but by means of a 32-bit R.C. (using j not i) of
1172 // the form j*K+L_2 <u32 R_2.  Note that L_2 and R_2 must be loop-invariant, but only with respect to the sub-loop.  Thus, the
1173 // problem reduces to computing values for L_2 and R_2 (for each R.C. in the loop) in the loop header for the sub-loop.
1174 // Then the standard R.C.E. transforms can take those as inputs and further compute the necessary minimum and maximum
1175 // values for the 32-bit counter j within which the range checks can be eliminated.
1176 
1177 // So, given j*K+Q <u R, we need to find some j*K+L_2 <u32 R_2, where L_2 and R_2 fit in 32 bits, and the 32-bit operations do
1178 // not overflow. We also need to cover the cases where i*K+L (= j*K+Q) overflows to a 64-bit negative, since that is
1179 // allowed as an input to the R.C., as long as the R.C. as a whole fails.
1180 
1181 // If 32-bit multiplication j*K might overflow, we adjust the sub-loop limit Z_2 closer to zero to reduce j's range.
1182 
1183 // For each R.C. j*K+Q <u32 R, the range of mathematical values of j*K+Q in the sub-loop is [Q_min, Q_max], where
1184 // Q_min=Q and Q_max=B_2*K+Q (if S>0 and K>0), Q_min=A_2*K+Q and Q_max=Q (if S<0 and K>0),
1185 // Q_min=B_2*K+Q and Q_max=Q if (S>0 and K<0), Q_min=Q and Q_max=A_2*K+Q (if S<0 and K<0)
1186 
1187 // Note that the first R.C. value is always Q=(S*K>0 ? Q_min : Q_max).  Also Q_{min,max} = Q + {min,max}(A_2*K,B_2*K).
1188 // If S*K>0 then, as the loop iterations progress, each R.C. value i*K+L = j*K+Q goes up from Q=Q_min towards Q_max.
1189 // If S*K<0 then j*K+Q starts at Q=Q_max and goes down towards Q_min.
1190 
1191 // Case A: Some Negatives (but no overflow).
1192 // Number line:
1193 // |s64_min   .    .    .    0    .    .    .   s64_max|
1194 // |    .  Q_min..Q_max .    0    .    .    .     .    |  s64 negative
1195 // |    .     .    .    .    R=0  R<   R<   R<    R<   |  (against R values)
1196 // |    .     .    .  Q_min..0..Q_max  .    .     .    |  small mixed
1197 // |    .     .    .    .    R    R    R<   R<    R<   |  (against R values)
1198 //
1199 // R values which are out of range (>Q_max+1) are reduced to max(0,Q_max+1).  They are marked on the number line as R<.
1200 //
1201 // So, if Q_min <s64 0, then use this test:
1202 // j*K + s32_trunc(Q_min) <u32 clamp(R, 0, Q_max+1) if S*K>0 (R.C.E. steps upward)
1203 // j*K + s32_trunc(Q_max) <u32 clamp(R, 0, Q_max+1) if S*K<0 (R.C.E. steps downward)
1204 // Both formulas reduce to adding j*K to the 32-bit truncated value of the first R.C. expression value, Q:
1205 // j*K + s32_trunc(Q) <u32 clamp(R, 0, Q_max+1) for all S,K
1206 
1207 // If the 32-bit truncation loses information, no harm is done, since certainly the clamp also will return R_2=zero.
1208 
1209 // Case B: No Negatives.
1210 // Number line:
1211 // |s64_min   .    .    .    0    .    .    .   s64_max|
1212 // |    .     .    .    .    0 Q_min..Q_max .     .    |  small positive
1213 // |    .     .    .    .    R>   R    R    R<    R<   |  (against R values)
1214 // |    .     .    .    .    0    . Q_min..Q_max  .    |  s64 positive
1215 // |    .     .    .    .    R>   R>   R    R     R<   |  (against R values)
1216 //
1217 // R values which are out of range (<Q_min or >Q_max+1) are reduced as marked: R> up to Q_min, R< down to Q_max+1.
1218 // Then the whole comparison is shifted left by Q_min, so it can take place at zero, which is a nice 32-bit value.
1219 //
1220 // So, if both Q_min, Q_max+1 >=s64 0, then use this test:
1221 // j*K + 0         <u32 clamp(R, Q_min, Q_max+1) - Q_min if S*K>0
1222 // More generally:
1223 // j*K + Q - Q_min <u32 clamp(R, Q_min, Q_max+1) - Q_min for all S,K
1224 
1225 // Case C: Overflow in the 64-bit domain
1226 // Number line:
1227 // |..Q_max-2^64   .    .    0    .    .    .   Q_min..|  s64 overflow
1228 // |    .     .    .    .    R>   R>   R>   R>    R    |  (against R values)
1229 //
1230 // In this case, Q_min >s64 Q_max+1, even though the mathematical values of Q_min and Q_max+1 are correctly ordered.
1231 // The formulas from the previous case can be used, except that the bad upper bound Q_max is replaced by max_jlong.
1232 // (In fact, we could use any replacement bound from R to max_jlong inclusive, as the input to the clamp function.)
1233 //
1234 // So if Q_min >=s64 0 but Q_max+1 <s64 0, use this test:
1235 // j*K + 0         <u32 clamp(R, Q_min, max_jlong) - Q_min if S*K>0
1236 // More generally:
1237 // j*K + Q - Q_min <u32 clamp(R, Q_min, max_jlong) - Q_min for all S,K
1238 //
1239 // Dropping the bad bound means only Q_min is used to reduce the range of R:
1240 // j*K + Q - Q_min <u32 max(Q_min, R) - Q_min for all S,K
1241 //
1242 // Here the clamp function is a 64-bit min/max that reduces the dynamic range of its R operand to the required [L,H]:
1243 //     clamp(X, L, H) := max(L, min(X, H))
1244 // When degenerately L > H, it returns L not H.
1245 //
1246 // All of the formulas above can be merged into a single one:
1247 //     L_clamp = Q_min < 0 ? 0 : Q_min        --whether and how far to left-shift
1248 //     H_clamp = Q_max+1 < Q_min ? max_jlong : Q_max+1
1249 //             = Q_max+1 < 0 && Q_min >= 0 ? max_jlong : Q_max+1
1250 //     Q_first = Q = (S*K>0 ? Q_min : Q_max) = (C*K+L)
1251 //     R_clamp = clamp(R, L_clamp, H_clamp)   --reduced dynamic range
1252 //     replacement R.C.:
1253 //       j*K + Q_first - L_clamp <u32 R_clamp - L_clamp
1254 //     or equivalently:
1255 //       j*K + L_2 <u32 R_2
1256 //     where
1257 //       L_2 = Q_first - L_clamp
1258 //       R_2 = R_clamp - L_clamp
1259 //
1260 // Note on why R is never negative:
1261 //
1262 // Various details of this transformation would break badly if R could be negative, so this transformation only
1263 // operates after obtaining hard evidence that R<0 is impossible.  For example, if R comes from a LoadRange node, we
1264 // know R cannot be negative.  For explicit checks (of both int and long) a proof is constructed in
1265 // inline_preconditions_checkIndex, which triggers an uncommon trap if R<0, then wraps R in a ConstraintCastNode with a
1266 // non-negative type.  Later on, when IdealLoopTree::is_range_check_if looks for an optimizable R.C., it checks that
1267 // the type of that R node is non-negative.  Any "wild" R node that could be negative is not treated as an optimizable
1268 // R.C., but R values from a.length and inside checkIndex are good to go.
1269 //
1270 void PhaseIdealLoop::transform_long_range_checks(int stride_con, const Node_List &range_checks, Node* outer_phi,
1271                                                  Node* inner_iters_actual_int, Node* inner_phi,
1272                                                  Node* iv_add, LoopNode* inner_head) {
1273   Node* long_zero = longcon(0);
1274   Node* int_zero = intcon(0);
1275   Node* long_one = longcon(1);
1276   Node* int_stride = intcon(checked_cast<int>(stride_con));
1277 
1278   for (uint i = 0; i < range_checks.size(); i++) {
1279     ProjNode* proj = range_checks.at(i)->as_Proj();
1280     ProjNode* unc_proj = proj->other_if_proj();
1281     RangeCheckNode* rc = proj->in(0)->as_RangeCheck();
1282     jlong scale = 0;
1283     Node* offset = nullptr;
1284     Node* rc_bol = rc->in(1);
1285     Node* rc_cmp = rc_bol->in(1);
1286     if (rc_cmp->Opcode() == Op_CmpU) {
1287       // could be shared and have already been taken care of
1288       continue;
1289     }
1290     bool short_scale = false;
1291     bool ok = is_scaled_iv_plus_offset(rc_cmp->in(1), iv_add, T_LONG, &scale, &offset, &short_scale);
1292     assert(ok, "inconsistent: was tested before");
1293     Node* range = rc_cmp->in(2);
1294     Node* c = rc->in(0);
1295     Node* entry_control = inner_head->in(LoopNode::EntryControl);
1296 
1297     Node* R = range;
1298     Node* K = longcon(scale);
1299 
1300     Node* L = offset;
1301 
1302     if (short_scale) {
1303       // This converts:
1304       // (int)i*K + L <u64 R
1305       // with K an int into:
1306       // i*(long)K + L <u64 unsigned_min((long)max_jint + L + 1, R)
1307       // to protect against an overflow of (int)i*K
1308       //
1309       // Because if (int)i*K overflows, there are K,L where:
1310       // (int)i*K + L <u64 R is false because (int)i*K+L overflows to a negative which becomes a huge u64 value.
1311       // But if i*(long)K + L is >u64 (long)max_jint and still is <u64 R, then
1312       // i*(long)K + L <u64 R is true.
1313       //
1314       // As a consequence simply converting i*K + L <u64 R to i*(long)K + L <u64 R could cause incorrect execution.
1315       //
1316       // It's always true that:
1317       // (int)i*K <u64 (long)max_jint + 1
1318       // which implies (int)i*K + L <u64 (long)max_jint + 1 + L
1319       // As a consequence:
1320       // i*(long)K + L <u64 unsigned_min((long)max_jint + L + 1, R)
1321       // is always false in case of overflow of i*K
1322       //
1323       // Note, there are also K,L where i*K overflows and
1324       // i*K + L <u64 R is true, but
1325       // i*(long)K + L <u64 unsigned_min((long)max_jint + L + 1, R) is false
1326       // So this transformation could cause spurious deoptimizations and failed range check elimination
1327       // (but not incorrect execution) for unlikely corner cases with overflow.
1328       // If this causes problems in practice, we could maybe direct execution to a post-loop, instead of deoptimizing.
1329       Node* max_jint_plus_one_long = longcon((jlong)max_jint + 1);
1330       Node* max_range = new AddLNode(max_jint_plus_one_long, L);
1331       register_new_node(max_range, entry_control);
1332       R = MaxNode::unsigned_min(R, max_range, TypeLong::POS, _igvn);
1333       set_subtree_ctrl(R, true);
1334     }
1335 
1336     Node* C = outer_phi;
1337 
1338     // Start with 64-bit values:
1339     //   i*K + L <u64 R
1340     //   (C+j)*K + L <u64 R
1341     //   j*K + Q <u64 R    where Q = Q_first = C*K+L
1342     Node* Q_first = new MulLNode(C, K);
1343     register_new_node(Q_first, entry_control);
1344     Q_first = new AddLNode(Q_first, L);
1345     register_new_node(Q_first, entry_control);
1346 
1347     // Compute endpoints of the range of values j*K + Q.
1348     //  Q_min = (j=0)*K + Q;  Q_max = (j=B_2)*K + Q
1349     Node* Q_min = Q_first;
1350 
1351     // Compute the exact ending value B_2 (which is really A_2 if S < 0)
1352     Node* B_2 = new LoopLimitNode(this->C, int_zero, inner_iters_actual_int, int_stride);
1353     register_new_node(B_2, entry_control);
1354     B_2 = new SubINode(B_2, int_stride);
1355     register_new_node(B_2, entry_control);
1356     B_2 = new ConvI2LNode(B_2);
1357     register_new_node(B_2, entry_control);
1358 
1359     Node* Q_max = new MulLNode(B_2, K);
1360     register_new_node(Q_max, entry_control);
1361     Q_max = new AddLNode(Q_max, Q_first);
1362     register_new_node(Q_max, entry_control);
1363 
1364     if (scale * stride_con < 0) {
1365       swap(Q_min, Q_max);
1366     }
1367     // Now, mathematically, Q_max > Q_min, and they are close enough so that (Q_max-Q_min) fits in 32 bits.
1368 
1369     // L_clamp = Q_min < 0 ? 0 : Q_min
1370     Node* Q_min_cmp = new CmpLNode(Q_min, long_zero);
1371     register_new_node(Q_min_cmp, entry_control);
1372     Node* Q_min_bool = new BoolNode(Q_min_cmp, BoolTest::lt);
1373     register_new_node(Q_min_bool, entry_control);
1374     Node* L_clamp = new CMoveLNode(Q_min_bool, Q_min, long_zero, TypeLong::LONG);
1375     register_new_node(L_clamp, entry_control);
1376     // (This could also be coded bitwise as L_clamp = Q_min & ~(Q_min>>63).)
1377 
1378     Node* Q_max_plus_one = new AddLNode(Q_max, long_one);
1379     register_new_node(Q_max_plus_one, entry_control);
1380 
1381     // H_clamp = Q_max+1 < Q_min ? max_jlong : Q_max+1
1382     // (Because Q_min and Q_max are close, the overflow check could also be encoded as Q_max+1 < 0 & Q_min >= 0.)
1383     Node* max_jlong_long = longcon(max_jlong);
1384     Node* Q_max_cmp = new CmpLNode(Q_max_plus_one, Q_min);
1385     register_new_node(Q_max_cmp, entry_control);
1386     Node* Q_max_bool = new BoolNode(Q_max_cmp, BoolTest::lt);
1387     register_new_node(Q_max_bool, entry_control);
1388     Node* H_clamp = new CMoveLNode(Q_max_bool, Q_max_plus_one, max_jlong_long, TypeLong::LONG);
1389     register_new_node(H_clamp, entry_control);
1390     // (This could also be coded bitwise as H_clamp = ((Q_max+1)<<1 | M)>>>1 where M = (Q_max+1)>>63 & ~Q_min>>63.)
1391 
1392     // R_2 = clamp(R, L_clamp, H_clamp) - L_clamp
1393     // that is:  R_2 = clamp(R, L_clamp=0, H_clamp=Q_max)      if Q_min < 0
1394     // or else:  R_2 = clamp(R, L_clamp,   H_clamp) - Q_min    if Q_min >= 0
1395     // and also: R_2 = clamp(R, L_clamp,   Q_max+1) - L_clamp  if Q_min < Q_max+1 (no overflow)
1396     // or else:  R_2 = clamp(R, L_clamp, *no limit*)- L_clamp  if Q_max+1 < Q_min (overflow)
1397     Node* R_2 = clamp(R, L_clamp, H_clamp);
1398     R_2 = new SubLNode(R_2, L_clamp);
1399     register_new_node(R_2, entry_control);
1400     R_2 = new ConvL2INode(R_2, TypeInt::POS);
1401     register_new_node(R_2, entry_control);
1402 
1403     // L_2 = Q_first - L_clamp
1404     // We are subtracting L_clamp from both sides of the <u32 comparison.
1405     // If S*K>0, then Q_first == 0 and the R.C. expression at -L_clamp and steps upward to Q_max-L_clamp.
1406     // If S*K<0, then Q_first != 0 and the R.C. expression starts high and steps downward to Q_min-L_clamp.
1407     Node* L_2 = new SubLNode(Q_first, L_clamp);
1408     register_new_node(L_2, entry_control);
1409     L_2 = new ConvL2INode(L_2, TypeInt::INT);
1410     register_new_node(L_2, entry_control);
1411 
1412     // Transform the range check using the computed values L_2/R_2
1413     // from:   i*K + L   <u64 R
1414     // to:     j*K + L_2 <u32 R_2
1415     // that is:
1416     //   (j*K + Q_first) - L_clamp <u32 clamp(R, L_clamp, H_clamp) - L_clamp
1417     K = intcon(checked_cast<int>(scale));
1418     Node* scaled_iv = new MulINode(inner_phi, K);
1419     register_new_node(scaled_iv, c);
1420     Node* scaled_iv_plus_offset = new AddINode(scaled_iv, L_2);
1421     register_new_node(scaled_iv_plus_offset, c);
1422 
1423     Node* new_rc_cmp = new CmpUNode(scaled_iv_plus_offset, R_2);
1424     register_new_node(new_rc_cmp, c);
1425 
1426     _igvn.replace_input_of(rc_bol, 1, new_rc_cmp);
1427   }
1428 }
1429 
1430 Node* PhaseIdealLoop::clamp(Node* R, Node* L, Node* H) {
1431   Node* min = MaxNode::signed_min(R, H, TypeLong::LONG, _igvn);
1432   set_subtree_ctrl(min, true);
1433   Node* max = MaxNode::signed_max(L, min, TypeLong::LONG, _igvn);
1434   set_subtree_ctrl(max, true);
1435   return max;
1436 }
1437 
1438 LoopNode* PhaseIdealLoop::create_inner_head(IdealLoopTree* loop, BaseCountedLoopNode* head,
1439                                             IfNode* exit_test) {
1440   LoopNode* new_inner_head = new LoopNode(head->in(1), head->in(2));
1441   IfNode* new_inner_exit = new IfNode(exit_test->in(0), exit_test->in(1), exit_test->_prob, exit_test->_fcnt);
1442   _igvn.register_new_node_with_optimizer(new_inner_head);
1443   _igvn.register_new_node_with_optimizer(new_inner_exit);
1444   loop->_body.push(new_inner_head);
1445   loop->_body.push(new_inner_exit);
1446   loop->_body.yank(head);
1447   loop->_body.yank(exit_test);
1448   set_loop(new_inner_head, loop);
1449   set_loop(new_inner_exit, loop);
1450   set_idom(new_inner_head, idom(head), dom_depth(head));
1451   set_idom(new_inner_exit, idom(exit_test), dom_depth(exit_test));
1452   lazy_replace(head, new_inner_head);
1453   lazy_replace(exit_test, new_inner_exit);
1454   loop->_head = new_inner_head;
1455   return new_inner_head;
1456 }
1457 
1458 #ifdef ASSERT
1459 void PhaseIdealLoop::check_counted_loop_shape(IdealLoopTree* loop, Node* x, BasicType bt) {
1460   Node* back_control = loop_exit_control(x, loop);
1461   assert(back_control != nullptr, "no back control");
1462 
1463   BoolTest::mask mask = BoolTest::illegal;
1464   float cl_prob = 0;
1465   Node* incr = nullptr;
1466   Node* limit = nullptr;
1467 
1468   Node* cmp = loop_exit_test(back_control, loop, incr, limit, mask, cl_prob);
1469   assert(cmp != nullptr && cmp->Opcode() == Op_Cmp(bt), "no exit test");
1470 
1471   Node* phi_incr = nullptr;
1472   incr = loop_iv_incr(incr, x, loop, phi_incr);
1473   assert(incr != nullptr && incr->Opcode() == Op_Add(bt), "no incr");
1474 
1475   Node* xphi = nullptr;
1476   Node* stride = loop_iv_stride(incr, loop, xphi);
1477 
1478   assert(stride != nullptr, "no stride");
1479 
1480   PhiNode* phi = loop_iv_phi(xphi, phi_incr, x, loop);
1481 
1482   assert(phi != nullptr && phi->in(LoopNode::LoopBackControl) == incr, "No phi");
1483 
1484   jlong stride_con = stride->get_integer_as_long(bt);
1485 
1486   assert(condition_stride_ok(mask, stride_con), "illegal condition");
1487 
1488   assert(mask != BoolTest::ne, "unexpected condition");
1489   assert(phi_incr == nullptr, "bad loop shape");
1490   assert(cmp->in(1) == incr, "bad exit test shape");
1491 
1492   // Safepoint on backedge not supported
1493   assert(x->in(LoopNode::LoopBackControl)->Opcode() != Op_SafePoint, "no safepoint on backedge");
1494 }
1495 #endif
1496 
1497 #ifdef ASSERT
1498 // convert an int counted loop to a long counted to stress handling of
1499 // long counted loops
1500 bool PhaseIdealLoop::convert_to_long_loop(Node* cmp, Node* phi, IdealLoopTree* loop) {
1501   Unique_Node_List iv_nodes;
1502   Node_List old_new;
1503   iv_nodes.push(cmp);
1504   bool failed = false;
1505 
1506   for (uint i = 0; i < iv_nodes.size() && !failed; i++) {
1507     Node* n = iv_nodes.at(i);
1508     switch(n->Opcode()) {
1509       case Op_Phi: {
1510         Node* clone = new PhiNode(n->in(0), TypeLong::LONG);
1511         old_new.map(n->_idx, clone);
1512         break;
1513       }
1514       case Op_CmpI: {
1515         Node* clone = new CmpLNode(nullptr, nullptr);
1516         old_new.map(n->_idx, clone);
1517         break;
1518       }
1519       case Op_AddI: {
1520         Node* clone = new AddLNode(nullptr, nullptr);
1521         old_new.map(n->_idx, clone);
1522         break;
1523       }
1524       case Op_CastII: {
1525         failed = true;
1526         break;
1527       }
1528       default:
1529         DEBUG_ONLY(n->dump());
1530         fatal("unexpected");
1531     }
1532 
1533     for (uint i = 1; i < n->req(); i++) {
1534       Node* in = n->in(i);
1535       if (in == nullptr) {
1536         continue;
1537       }
1538       if (loop->is_member(get_loop(get_ctrl(in)))) {
1539         iv_nodes.push(in);
1540       }
1541     }
1542   }
1543 
1544   if (failed) {
1545     for (uint i = 0; i < iv_nodes.size(); i++) {
1546       Node* n = iv_nodes.at(i);
1547       Node* clone = old_new[n->_idx];
1548       if (clone != nullptr) {
1549         _igvn.remove_dead_node(clone);
1550       }
1551     }
1552     return false;
1553   }
1554 
1555   for (uint i = 0; i < iv_nodes.size(); i++) {
1556     Node* n = iv_nodes.at(i);
1557     Node* clone = old_new[n->_idx];
1558     for (uint i = 1; i < n->req(); i++) {
1559       Node* in = n->in(i);
1560       if (in == nullptr) {
1561         continue;
1562       }
1563       Node* in_clone = old_new[in->_idx];
1564       if (in_clone == nullptr) {
1565         assert(_igvn.type(in)->isa_int(), "");
1566         in_clone = new ConvI2LNode(in);
1567         _igvn.register_new_node_with_optimizer(in_clone);
1568         set_subtree_ctrl(in_clone, false);
1569       }
1570       if (in_clone->in(0) == nullptr) {
1571         in_clone->set_req(0, C->top());
1572         clone->set_req(i, in_clone);
1573         in_clone->set_req(0, nullptr);
1574       } else {
1575         clone->set_req(i, in_clone);
1576       }
1577     }
1578     _igvn.register_new_node_with_optimizer(clone);
1579   }
1580   set_ctrl(old_new[phi->_idx], phi->in(0));
1581 
1582   for (uint i = 0; i < iv_nodes.size(); i++) {
1583     Node* n = iv_nodes.at(i);
1584     Node* clone = old_new[n->_idx];
1585     set_subtree_ctrl(clone, false);
1586     Node* m = n->Opcode() == Op_CmpI ? clone : nullptr;
1587     for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
1588       Node* u = n->fast_out(i);
1589       if (iv_nodes.member(u)) {
1590         continue;
1591       }
1592       if (m == nullptr) {
1593         m = new ConvL2INode(clone);
1594         _igvn.register_new_node_with_optimizer(m);
1595         set_subtree_ctrl(m, false);
1596       }
1597       _igvn.rehash_node_delayed(u);
1598       int nb = u->replace_edge(n, m, &_igvn);
1599       --i, imax -= nb;
1600     }
1601   }
1602   return true;
1603 }
1604 #endif
1605 
1606 //------------------------------is_counted_loop--------------------------------
1607 bool PhaseIdealLoop::is_counted_loop(Node* x, IdealLoopTree*&loop, BasicType iv_bt) {
1608   PhaseGVN *gvn = &_igvn;
1609 
1610   Node* back_control = loop_exit_control(x, loop);
1611   if (back_control == nullptr) {
1612     return false;
1613   }
1614 
1615   BoolTest::mask bt = BoolTest::illegal;
1616   float cl_prob = 0;
1617   Node* incr = nullptr;
1618   Node* limit = nullptr;
1619   Node* cmp = loop_exit_test(back_control, loop, incr, limit, bt, cl_prob);
1620   if (cmp == nullptr || cmp->Opcode() != Op_Cmp(iv_bt)) {
1621     return false; // Avoid pointer & float & 64-bit compares
1622   }
1623 
1624   // Trip-counter increment must be commutative & associative.
1625   if (incr->Opcode() == Op_Cast(iv_bt)) {
1626     incr = incr->in(1);
1627   }
1628 
1629   Node* phi_incr = nullptr;
1630   incr = loop_iv_incr(incr, x, loop, phi_incr);
1631   if (incr == nullptr) {
1632     return false;
1633   }
1634 
1635   Node* trunc1 = nullptr;
1636   Node* trunc2 = nullptr;
1637   const TypeInteger* iv_trunc_t = nullptr;
1638   Node* orig_incr = incr;
1639   if (!(incr = CountedLoopNode::match_incr_with_optional_truncation(incr, &trunc1, &trunc2, &iv_trunc_t, iv_bt))) {
1640     return false; // Funny increment opcode
1641   }
1642   assert(incr->Opcode() == Op_Add(iv_bt), "wrong increment code");
1643 
1644   Node* xphi = nullptr;
1645   Node* stride = loop_iv_stride(incr, loop, xphi);
1646 
1647   if (stride == nullptr) {
1648     return false;
1649   }
1650 
1651   if (xphi->Opcode() == Op_Cast(iv_bt)) {
1652     xphi = xphi->in(1);
1653   }
1654 
1655   // Stride must be constant
1656   jlong stride_con = stride->get_integer_as_long(iv_bt);
1657   assert(stride_con != 0, "missed some peephole opt");
1658 
1659   PhiNode* phi = loop_iv_phi(xphi, phi_incr, x, loop);
1660 
1661   if (phi == nullptr ||
1662       (trunc1 == nullptr && phi->in(LoopNode::LoopBackControl) != incr) ||
1663       (trunc1 != nullptr && phi->in(LoopNode::LoopBackControl) != trunc1)) {
1664     return false;
1665   }
1666 
1667   Node* iftrue = back_control;
1668   uint iftrue_op = iftrue->Opcode();
1669   Node* iff = iftrue->in(0);
1670   BoolNode* test = iff->in(1)->as_Bool();
1671 
1672   const TypeInteger* limit_t = gvn->type(limit)->is_integer(iv_bt);
1673   if (trunc1 != nullptr) {
1674     // When there is a truncation, we must be sure that after the truncation
1675     // the trip counter will end up higher than the limit, otherwise we are looking
1676     // at an endless loop. Can happen with range checks.
1677 
1678     // Example:
1679     // int i = 0;
1680     // while (true)
1681     //    sum + = array[i];
1682     //    i++;
1683     //    i = i && 0x7fff;
1684     //  }
1685     //
1686     // If the array is shorter than 0x8000 this exits through a AIOOB
1687     //  - Counted loop transformation is ok
1688     // If the array is longer then this is an endless loop
1689     //  - No transformation can be done.
1690 
1691     const TypeInteger* incr_t = gvn->type(orig_incr)->is_integer(iv_bt);
1692     if (limit_t->hi_as_long() > incr_t->hi_as_long()) {
1693       // if the limit can have a higher value than the increment (before the phi)
1694       return false;
1695     }
1696   }
1697 
1698   Node *init_trip = phi->in(LoopNode::EntryControl);
1699 
1700   // If iv trunc type is smaller than int, check for possible wrap.
1701   if (!TypeInteger::bottom(iv_bt)->higher_equal(iv_trunc_t)) {
1702     assert(trunc1 != nullptr, "must have found some truncation");
1703 
1704     // Get a better type for the phi (filtered thru if's)
1705     const TypeInteger* phi_ft = filtered_type(phi);
1706 
1707     // Can iv take on a value that will wrap?
1708     //
1709     // Ensure iv's limit is not within "stride" of the wrap value.
1710     //
1711     // Example for "short" type
1712     //    Truncation ensures value is in the range -32768..32767 (iv_trunc_t)
1713     //    If the stride is +10, then the last value of the induction
1714     //    variable before the increment (phi_ft->_hi) must be
1715     //    <= 32767 - 10 and (phi_ft->_lo) must be >= -32768 to
1716     //    ensure no truncation occurs after the increment.
1717 
1718     if (stride_con > 0) {
1719       if (iv_trunc_t->hi_as_long() - phi_ft->hi_as_long() < stride_con ||
1720           iv_trunc_t->lo_as_long() > phi_ft->lo_as_long()) {
1721         return false;  // truncation may occur
1722       }
1723     } else if (stride_con < 0) {
1724       if (iv_trunc_t->lo_as_long() - phi_ft->lo_as_long() > stride_con ||
1725           iv_trunc_t->hi_as_long() < phi_ft->hi_as_long()) {
1726         return false;  // truncation may occur
1727       }
1728     }
1729     // No possibility of wrap so truncation can be discarded
1730     // Promote iv type to Int
1731   } else {
1732     assert(trunc1 == nullptr && trunc2 == nullptr, "no truncation for int");
1733   }
1734 
1735   if (!condition_stride_ok(bt, stride_con)) {
1736     return false;
1737   }
1738 
1739   const TypeInteger* init_t = gvn->type(init_trip)->is_integer(iv_bt);
1740 
1741   if (stride_con > 0) {
1742     if (init_t->lo_as_long() > max_signed_integer(iv_bt) - stride_con) {
1743       return false; // cyclic loop
1744     }
1745   } else {
1746     if (init_t->hi_as_long() < min_signed_integer(iv_bt) - stride_con) {
1747       return false; // cyclic loop
1748     }
1749   }
1750 
1751   if (phi_incr != nullptr && bt != BoolTest::ne) {
1752     // check if there is a possibility of IV overflowing after the first increment
1753     if (stride_con > 0) {
1754       if (init_t->hi_as_long() > max_signed_integer(iv_bt) - stride_con) {
1755         return false;
1756       }
1757     } else {
1758       if (init_t->lo_as_long() < min_signed_integer(iv_bt) - stride_con) {
1759         return false;
1760       }
1761     }
1762   }
1763 
1764   // =================================================
1765   // ---- SUCCESS!   Found A Trip-Counted Loop!  -----
1766   //
1767 
1768   if (x->Opcode() == Op_Region) {
1769     // x has not yet been transformed to Loop or LongCountedLoop.
1770     // This should only happen if we are inside an infinite loop.
1771     // It happens like this:
1772     //   build_loop_tree -> do not attach infinite loop and nested loops
1773     //   beautify_loops  -> does not transform the infinite and nested loops to LoopNode, because not attached yet
1774     //   build_loop_tree -> find and attach infinite and nested loops
1775     //   counted_loop    -> nested Regions are not yet transformed to LoopNodes, we land here
1776     assert(x->as_Region()->is_in_infinite_subgraph(),
1777            "x can only be a Region and not Loop if inside infinite loop");
1778     // Come back later when Region is transformed to LoopNode
1779     return false;
1780   }
1781 
1782   assert(x->Opcode() == Op_Loop || x->Opcode() == Op_LongCountedLoop, "regular loops only");
1783   C->print_method(PHASE_BEFORE_CLOOPS, 3, x);
1784 
1785   // ===================================================
1786   // We can only convert this loop to a counted loop if we can guarantee that the iv phi will never overflow at runtime.
1787   // This is an implicit assumption taken by some loop optimizations. We therefore must ensure this property at all cost.
1788   // At this point, we've already excluded some trivial cases where an overflow could have been proven statically.
1789   // But even though we cannot prove that an overflow will *not* happen, we still want to speculatively convert this loop
1790   // to a counted loop. This can be achieved by adding additional iv phi overflow checks before the loop. If they fail,
1791   // we trap and resume execution before the loop without having executed any iteration of the loop, yet.
1792   //
1793   // These additional iv phi overflow checks can be inserted as Loop Limit Check Predicates above the Loop Limit Check
1794   // Parse Predicate which captures a JVM state just before the entry of the loop. If there is no such Parse Predicate,
1795   // we cannot generate a Loop Limit Check Predicate and thus cannot speculatively convert the loop to a counted loop.
1796   //
1797   // In the following, we only focus on int loops with stride > 0 to keep things simple. The argumentation and proof
1798   // for stride < 0 is analogously. For long loops, we would replace max_int with max_long.
1799   //
1800   //
1801   // The loop to be converted does not always need to have the often used shape:
1802   //
1803   //                                                 i = init
1804   //     i = init                                loop:
1805   //     do {                                        ...
1806   //         // ...               equivalent         i+=stride
1807   //         i+=stride               <==>            if (i < limit)
1808   //     } while (i < limit);                          goto loop
1809   //                                             exit:
1810   //                                                 ...
1811   //
1812   // where the loop exit check uses the post-incremented iv phi and a '<'-operator.
1813   //
1814   // We could also have '<='-operator (or '>='-operator for negative strides) or use the pre-incremented iv phi value
1815   // in the loop exit check:
1816   //
1817   //         i = init
1818   //     loop:
1819   //         ...
1820   //         if (i <= limit)
1821   //             i+=stride
1822   //             goto loop
1823   //     exit:
1824   //         ...
1825   //
1826   // Let's define the following terms:
1827   // - iv_pre_i: The pre-incremented iv phi before the i-th iteration.
1828   // - iv_post_i: The post-incremented iv phi after the i-th iteration.
1829   //
1830   // The iv_pre_i and iv_post_i have the following relation:
1831   //      iv_pre_i + stride = iv_post_i
1832   //
1833   // When converting a loop to a counted loop, we want to have a canonicalized loop exit check of the form:
1834   //     iv_post_i < adjusted_limit
1835   //
1836   // If that is not the case, we need to canonicalize the loop exit check by using different values for adjusted_limit:
1837   // (LE1) iv_post_i < limit: Already canonicalized. We can directly use limit as adjusted_limit.
1838   //           -> adjusted_limit = limit.
1839   // (LE2) iv_post_i <= limit:
1840   //           iv_post_i < limit + 1
1841   //           -> adjusted limit = limit + 1
1842   // (LE3) iv_pre_i < limit:
1843   //           iv_pre_i + stride < limit + stride
1844   //           iv_post_i < limit + stride
1845   //           -> adjusted_limit = limit + stride
1846   // (LE4) iv_pre_i <= limit:
1847   //           iv_pre_i < limit + 1
1848   //           iv_pre_i + stride < limit + stride + 1
1849   //           iv_post_i < limit + stride + 1
1850   //           -> adjusted_limit = limit + stride + 1
1851   //
1852   // Note that:
1853   //     (AL) limit <= adjusted_limit.
1854   //
1855   // The following loop invariant has to hold for counted loops with n iterations (i.e. loop exit check true after n-th
1856   // loop iteration) and a canonicalized loop exit check to guarantee that no iv_post_i over- or underflows:
1857   // (INV) For i = 1..n, min_int <= iv_post_i <= max_int
1858   //
1859   // To prove (INV), we require the following two conditions/assumptions:
1860   // (i): adjusted_limit - 1 + stride <= max_int
1861   // (ii): init < limit
1862   //
1863   // If we can prove (INV), we know that there can be no over- or underflow of any iv phi value. We prove (INV) by
1864   // induction by assuming (i) and (ii).
1865   //
1866   // Proof by Induction
1867   // ------------------
1868   // > Base case (i = 1): We show that (INV) holds after the first iteration:
1869   //     min_int <= iv_post_1 = init + stride <= max_int
1870   // Proof:
1871   //     First, we note that (ii) implies
1872   //         (iii) init <= limit - 1
1873   //     max_int >= adjusted_limit - 1 + stride   [using (i)]
1874   //             >= limit - 1 + stride            [using (AL)]
1875   //             >= init + stride                 [using (iii)]
1876   //             >= min_int                       [using stride > 0, no underflow]
1877   // Thus, no overflow happens after the first iteration and (INV) holds for i = 1.
1878   //
1879   // Note that to prove the base case we need (i) and (ii).
1880   //
1881   // > Induction Hypothesis (i = j, j > 1): Assume that (INV) holds after the j-th iteration:
1882   //     min_int <= iv_post_j <= max_int
1883   // > Step case (i = j + 1): We show that (INV) also holds after the j+1-th iteration:
1884   //     min_int <= iv_post_{j+1} = iv_post_j + stride <= max_int
1885   // Proof:
1886   // If iv_post_j >= adjusted_limit:
1887   //     We exit the loop after the j-th iteration, and we don't execute the j+1-th iteration anymore. Thus, there is
1888   //     also no iv_{j+1}. Since (INV) holds for iv_j, there is nothing left to prove.
1889   // If iv_post_j < adjusted_limit:
1890   //     First, we note that:
1891   //         (iv) iv_post_j <= adjusted_limit - 1
1892   //     max_int >= adjusted_limit - 1 + stride    [using (i)]
1893   //             >= iv_post_j + stride             [using (iv)]
1894   //             >= min_int                        [using stride > 0, no underflow]
1895   //
1896   // Note that to prove the step case we only need (i).
1897   //
1898   // Thus, by assuming (i) and (ii), we proved (INV).
1899   //
1900   //
1901   // It is therefore enough to add the following two Loop Limit Check Predicates to check assumptions (i) and (ii):
1902   //
1903   // (1) Loop Limit Check Predicate for (i):
1904   //     Using (i): adjusted_limit - 1 + stride <= max_int
1905   //
1906   //     This condition is now restated to use limit instead of adjusted_limit:
1907   //
1908   //     To prevent an overflow of adjusted_limit -1 + stride itself, we rewrite this check to
1909   //         max_int - stride + 1 >= adjusted_limit
1910   //     We can merge the two constants into
1911   //         canonicalized_correction = stride - 1
1912   //     which gives us
1913   //        max_int - canonicalized_correction >= adjusted_limit
1914   //
1915   //     To directly use limit instead of adjusted_limit in the predicate condition, we split adjusted_limit into:
1916   //         adjusted_limit = limit + limit_correction
1917   //     Since stride > 0 and limit_correction <= stride + 1, we can restate this with no over- or underflow into:
1918   //         max_int - canonicalized_correction - limit_correction >= limit
1919   //     Since canonicalized_correction and limit_correction are both constants, we can replace them with a new constant:
1920   //         (v) final_correction = canonicalized_correction + limit_correction
1921   //
1922   //     which gives us:
1923   //
1924   //     Final predicate condition:
1925   //         max_int - final_correction >= limit
1926   //
1927   //     However, we need to be careful that (v) does not over- or underflow.
1928   //     We know that:
1929   //         canonicalized_correction = stride - 1
1930   //     and
1931   //         limit_correction <= stride + 1
1932   //     and thus
1933   //         canonicalized_correction + limit_correction <= 2 * stride
1934   //     To prevent an over- or underflow of (v), we must ensure that
1935   //         2 * stride <= max_int
1936   //     which can safely be checked without over- or underflow with
1937   //         (vi) stride != min_int AND abs(stride) <= max_int / 2
1938   //
1939   //     We could try to further optimize the cases where (vi) does not hold but given that such large strides are
1940   //     very uncommon and the loop would only run for a very few iterations anyway, we simply bail out if (vi) fails.
1941   //
1942   // (2) Loop Limit Check Predicate for (ii):
1943   //     Using (ii): init < limit
1944   //
1945   //     This Loop Limit Check Predicate is not required if we can prove at compile time that either:
1946   //        (2.1) type(init) < type(limit)
1947   //             In this case, we know:
1948   //                 all possible values of init < all possible values of limit
1949   //             and we can skip the predicate.
1950   //
1951   //        (2.2) init < limit is already checked before (i.e. found as a dominating check)
1952   //            In this case, we do not need to re-check the condition and can skip the predicate.
1953   //            This is often found for while- and for-loops which have the following shape:
1954   //
1955   //                if (init < limit) { // Dominating test. Do not need the Loop Limit Check Predicate below.
1956   //                    i = init;
1957   //                    if (init >= limit) { trap(); } // Here we would insert the Loop Limit Check Predicate
1958   //                    do {
1959   //                        i += stride;
1960   //                    } while (i < limit);
1961   //                }
1962   //
1963   //        (2.3) init + stride <= max_int
1964   //            In this case, there is no overflow of the iv phi after the first loop iteration.
1965   //            In the proof of the base case above we showed that init + stride <= max_int by using assumption (ii):
1966   //                init < limit
1967   //            In the proof of the step case above, we did not need (ii) anymore. Therefore, if we already know at
1968   //            compile time that init + stride <= max_int then we have trivially proven the base case and that
1969   //            there is no overflow of the iv phi after the first iteration. In this case, we don't need to check (ii)
1970   //            again and can skip the predicate.
1971 
1972   // Check (vi) and bail out if the stride is too big.
1973   if (stride_con == min_signed_integer(iv_bt) || (ABS(stride_con) > max_signed_integer(iv_bt) / 2)) {
1974     return false;
1975   }
1976 
1977   // Accounting for (LE3) and (LE4) where we use pre-incremented phis in the loop exit check.
1978   const jlong limit_correction_for_pre_iv_exit_check = (phi_incr != nullptr) ? stride_con : 0;
1979 
1980   // Accounting for (LE2) and (LE4) where we use <= or >= in the loop exit check.
1981   const bool includes_limit = (bt == BoolTest::le || bt == BoolTest::ge);
1982   const jlong limit_correction_for_le_ge_exit_check = (includes_limit ? (stride_con > 0 ? 1 : -1) : 0);
1983 
1984   const jlong limit_correction = limit_correction_for_pre_iv_exit_check + limit_correction_for_le_ge_exit_check;
1985   const jlong canonicalized_correction = stride_con + (stride_con > 0 ? -1 : 1);
1986   const jlong final_correction = canonicalized_correction + limit_correction;
1987 
1988   int sov = check_stride_overflow(final_correction, limit_t, iv_bt);
1989   Node* init_control = x->in(LoopNode::EntryControl);
1990 
1991   // If sov==0, limit's type always satisfies the condition, for
1992   // example, when it is an array length.
1993   if (sov != 0) {
1994     if (sov < 0) {
1995       return false;  // Bailout: integer overflow is certain.
1996     }
1997     // (1) Loop Limit Check Predicate is required because we could not statically prove that
1998     //     limit + final_correction = adjusted_limit - 1 + stride <= max_int
1999     assert(!x->as_Loop()->is_loop_nest_inner_loop(), "loop was transformed");
2000     const Predicates predicates(init_control);
2001     const PredicateBlock* loop_limit_check_predicate_block = predicates.loop_limit_check_predicate_block();
2002     if (!loop_limit_check_predicate_block->has_parse_predicate()) {
2003       // The Loop Limit Check Parse Predicate is not generated if this method trapped here before.
2004 #ifdef ASSERT
2005       if (TraceLoopLimitCheck) {
2006         tty->print("Missing Loop Limit Check Parse Predicate:");
2007         loop->dump_head();
2008         x->dump(1);
2009       }
2010 #endif
2011       return false;
2012     }
2013 
2014     ParsePredicateNode* loop_limit_check_parse_predicate = loop_limit_check_predicate_block->parse_predicate();
2015     if (!is_dominator(get_ctrl(limit), loop_limit_check_parse_predicate->in(0))) {
2016       return false;
2017     }
2018 
2019     Node* cmp_limit;
2020     Node* bol;
2021 
2022     if (stride_con > 0) {
2023       cmp_limit = CmpNode::make(limit, _igvn.integercon(max_signed_integer(iv_bt) - final_correction, iv_bt), iv_bt);
2024       bol = new BoolNode(cmp_limit, BoolTest::le);
2025     } else {
2026       cmp_limit = CmpNode::make(limit, _igvn.integercon(min_signed_integer(iv_bt) - final_correction, iv_bt), iv_bt);
2027       bol = new BoolNode(cmp_limit, BoolTest::ge);
2028     }
2029 
2030     insert_loop_limit_check_predicate(init_control->as_IfTrue(), cmp_limit, bol);
2031   }
2032 
2033   // (2.3)
2034   const bool init_plus_stride_could_overflow =
2035           (stride_con > 0 && init_t->hi_as_long() > max_signed_integer(iv_bt) - stride_con) ||
2036           (stride_con < 0 && init_t->lo_as_long() < min_signed_integer(iv_bt) - stride_con);
2037   // (2.1)
2038   const bool init_gte_limit = (stride_con > 0 && init_t->hi_as_long() >= limit_t->lo_as_long()) ||
2039                               (stride_con < 0 && init_t->lo_as_long() <= limit_t->hi_as_long());
2040 
2041   if (init_gte_limit && // (2.1)
2042      ((bt == BoolTest::ne || init_plus_stride_could_overflow) && // (2.3)
2043       !has_dominating_loop_limit_check(init_trip, limit, stride_con, iv_bt, init_control))) { // (2.2)
2044     // (2) Iteration Loop Limit Check Predicate is required because neither (2.1), (2.2), nor (2.3) holds.
2045     // We use the following condition:
2046     // - stride > 0: init < limit
2047     // - stride < 0: init > limit
2048     //
2049     // This predicate is always required if we have a non-equal-operator in the loop exit check (where stride = 1 is
2050     // a requirement). We transform the loop exit check by using a less-than-operator. By doing so, we must always
2051     // check that init < limit. Otherwise, we could have a different number of iterations at runtime.
2052 
2053     const Predicates predicates(init_control);
2054     const PredicateBlock* loop_limit_check_predicate_block = predicates.loop_limit_check_predicate_block();
2055     if (!loop_limit_check_predicate_block->has_parse_predicate()) {
2056       // The Loop Limit Check Parse Predicate is not generated if this method trapped here before.
2057 #ifdef ASSERT
2058       if (TraceLoopLimitCheck) {
2059         tty->print("Missing Loop Limit Check Parse Predicate:");
2060         loop->dump_head();
2061         x->dump(1);
2062       }
2063 #endif
2064       return false;
2065     }
2066 
2067     ParsePredicateNode* loop_limit_check_parse_predicate = loop_limit_check_predicate_block->parse_predicate();
2068     Node* parse_predicate_entry = loop_limit_check_parse_predicate->in(0);
2069     if (!is_dominator(get_ctrl(limit), parse_predicate_entry) ||
2070         !is_dominator(get_ctrl(init_trip), parse_predicate_entry)) {
2071       return false;
2072     }
2073 
2074     Node* cmp_limit;
2075     Node* bol;
2076 
2077     if (stride_con > 0) {
2078       cmp_limit = CmpNode::make(init_trip, limit, iv_bt);
2079       bol = new BoolNode(cmp_limit, BoolTest::lt);
2080     } else {
2081       cmp_limit = CmpNode::make(init_trip, limit, iv_bt);
2082       bol = new BoolNode(cmp_limit, BoolTest::gt);
2083     }
2084 
2085     insert_loop_limit_check_predicate(init_control->as_IfTrue(), cmp_limit, bol);
2086   }
2087 
2088   if (bt == BoolTest::ne) {
2089     // Now we need to canonicalize the loop condition if it is 'ne'.
2090     assert(stride_con == 1 || stride_con == -1, "simple increment only - checked before");
2091     if (stride_con > 0) {
2092       // 'ne' can be replaced with 'lt' only when init < limit. This is ensured by the inserted predicate above.
2093       bt = BoolTest::lt;
2094     } else {
2095       assert(stride_con < 0, "must be");
2096       // 'ne' can be replaced with 'gt' only when init > limit. This is ensured by the inserted predicate above.
2097       bt = BoolTest::gt;
2098     }
2099   }
2100 
2101   Node* sfpt = nullptr;
2102   if (loop->_child == nullptr) {
2103     sfpt = find_safepoint(back_control, x, loop);
2104   } else {
2105     sfpt = iff->in(0);
2106     if (sfpt->Opcode() != Op_SafePoint) {
2107       sfpt = nullptr;
2108     }
2109   }
2110 
2111   if (x->in(LoopNode::LoopBackControl)->Opcode() == Op_SafePoint) {
2112     Node* backedge_sfpt = x->in(LoopNode::LoopBackControl);
2113     if (((iv_bt == T_INT && LoopStripMiningIter != 0) ||
2114          iv_bt == T_LONG) &&
2115         sfpt == nullptr) {
2116       // Leaving the safepoint on the backedge and creating a
2117       // CountedLoop will confuse optimizations. We can't move the
2118       // safepoint around because its jvm state wouldn't match a new
2119       // location. Give up on that loop.
2120       return false;
2121     }
2122     if (is_deleteable_safept(backedge_sfpt)) {
2123       lazy_replace(backedge_sfpt, iftrue);
2124       if (loop->_safepts != nullptr) {
2125         loop->_safepts->yank(backedge_sfpt);
2126       }
2127       loop->_tail = iftrue;
2128     }
2129   }
2130 
2131 
2132 #ifdef ASSERT
2133   if (iv_bt == T_INT &&
2134       !x->as_Loop()->is_loop_nest_inner_loop() &&
2135       StressLongCountedLoop > 0 &&
2136       trunc1 == nullptr &&
2137       convert_to_long_loop(cmp, phi, loop)) {
2138     return false;
2139   }
2140 #endif
2141 
2142   Node* adjusted_limit = limit;
2143   if (phi_incr != nullptr) {
2144     // If compare points directly to the phi we need to adjust
2145     // the compare so that it points to the incr. Limit have
2146     // to be adjusted to keep trip count the same and we
2147     // should avoid int overflow.
2148     //
2149     //   i = init; do {} while(i++ < limit);
2150     // is converted to
2151     //   i = init; do {} while(++i < limit+1);
2152     //
2153     adjusted_limit = gvn->transform(AddNode::make(limit, stride, iv_bt));
2154   }
2155 
2156   if (includes_limit) {
2157     // The limit check guaranties that 'limit <= (max_jint - stride)' so
2158     // we can convert 'i <= limit' to 'i < limit+1' since stride != 0.
2159     //
2160     Node* one = (stride_con > 0) ? gvn->integercon( 1, iv_bt) : gvn->integercon(-1, iv_bt);
2161     adjusted_limit = gvn->transform(AddNode::make(adjusted_limit, one, iv_bt));
2162     if (bt == BoolTest::le)
2163       bt = BoolTest::lt;
2164     else if (bt == BoolTest::ge)
2165       bt = BoolTest::gt;
2166     else
2167       ShouldNotReachHere();
2168   }
2169   set_subtree_ctrl(adjusted_limit, false);
2170 
2171   // Build a canonical trip test.
2172   // Clone code, as old values may be in use.
2173   incr = incr->clone();
2174   incr->set_req(1,phi);
2175   incr->set_req(2,stride);
2176   incr = _igvn.register_new_node_with_optimizer(incr);
2177   set_early_ctrl(incr, false);
2178   _igvn.rehash_node_delayed(phi);
2179   phi->set_req_X( LoopNode::LoopBackControl, incr, &_igvn );
2180 
2181   // If phi type is more restrictive than Int, raise to
2182   // Int to prevent (almost) infinite recursion in igvn
2183   // which can only handle integer types for constants or minint..maxint.
2184   if (!TypeInteger::bottom(iv_bt)->higher_equal(phi->bottom_type())) {
2185     Node* nphi = PhiNode::make(phi->in(0), phi->in(LoopNode::EntryControl), TypeInteger::bottom(iv_bt));
2186     nphi->set_req(LoopNode::LoopBackControl, phi->in(LoopNode::LoopBackControl));
2187     nphi = _igvn.register_new_node_with_optimizer(nphi);
2188     set_ctrl(nphi, get_ctrl(phi));
2189     _igvn.replace_node(phi, nphi);
2190     phi = nphi->as_Phi();
2191   }
2192   cmp = cmp->clone();
2193   cmp->set_req(1,incr);
2194   cmp->set_req(2, adjusted_limit);
2195   cmp = _igvn.register_new_node_with_optimizer(cmp);
2196   set_ctrl(cmp, iff->in(0));
2197 
2198   test = test->clone()->as_Bool();
2199   (*(BoolTest*)&test->_test)._test = bt;
2200   test->set_req(1,cmp);
2201   _igvn.register_new_node_with_optimizer(test);
2202   set_ctrl(test, iff->in(0));
2203 
2204   // Replace the old IfNode with a new LoopEndNode
2205   Node *lex = _igvn.register_new_node_with_optimizer(BaseCountedLoopEndNode::make(iff->in(0), test, cl_prob, iff->as_If()->_fcnt, iv_bt));
2206   IfNode *le = lex->as_If();
2207   uint dd = dom_depth(iff);
2208   set_idom(le, le->in(0), dd); // Update dominance for loop exit
2209   set_loop(le, loop);
2210 
2211   // Get the loop-exit control
2212   Node *iffalse = iff->as_If()->proj_out(!(iftrue_op == Op_IfTrue));
2213 
2214   // Need to swap loop-exit and loop-back control?
2215   if (iftrue_op == Op_IfFalse) {
2216     Node *ift2=_igvn.register_new_node_with_optimizer(new IfTrueNode (le));
2217     Node *iff2=_igvn.register_new_node_with_optimizer(new IfFalseNode(le));
2218 
2219     loop->_tail = back_control = ift2;
2220     set_loop(ift2, loop);
2221     set_loop(iff2, get_loop(iffalse));
2222 
2223     // Lazy update of 'get_ctrl' mechanism.
2224     lazy_replace(iffalse, iff2);
2225     lazy_replace(iftrue,  ift2);
2226 
2227     // Swap names
2228     iffalse = iff2;
2229     iftrue  = ift2;
2230   } else {
2231     _igvn.rehash_node_delayed(iffalse);
2232     _igvn.rehash_node_delayed(iftrue);
2233     iffalse->set_req_X( 0, le, &_igvn );
2234     iftrue ->set_req_X( 0, le, &_igvn );
2235   }
2236 
2237   set_idom(iftrue,  le, dd+1);
2238   set_idom(iffalse, le, dd+1);
2239   assert(iff->outcnt() == 0, "should be dead now");
2240   lazy_replace( iff, le ); // fix 'get_ctrl'
2241 
2242   Node* entry_control = init_control;
2243   bool strip_mine_loop = iv_bt == T_INT &&
2244                          loop->_child == nullptr &&
2245                          sfpt != nullptr &&
2246                          !loop->_has_call &&
2247                          is_deleteable_safept(sfpt);
2248   IdealLoopTree* outer_ilt = nullptr;
2249   if (strip_mine_loop) {
2250     outer_ilt = create_outer_strip_mined_loop(test, cmp, init_control, loop,
2251                                               cl_prob, le->_fcnt, entry_control,
2252                                               iffalse);
2253   }
2254 
2255   // Now setup a new CountedLoopNode to replace the existing LoopNode
2256   BaseCountedLoopNode *l = BaseCountedLoopNode::make(entry_control, back_control, iv_bt);
2257   l->set_unswitch_count(x->as_Loop()->unswitch_count()); // Preserve
2258   // The following assert is approximately true, and defines the intention
2259   // of can_be_counted_loop.  It fails, however, because phase->type
2260   // is not yet initialized for this loop and its parts.
2261   //assert(l->can_be_counted_loop(this), "sanity");
2262   _igvn.register_new_node_with_optimizer(l);
2263   set_loop(l, loop);
2264   loop->_head = l;
2265   // Fix all data nodes placed at the old loop head.
2266   // Uses the lazy-update mechanism of 'get_ctrl'.
2267   lazy_replace( x, l );
2268   set_idom(l, entry_control, dom_depth(entry_control) + 1);
2269 
2270   if (iv_bt == T_INT && (LoopStripMiningIter == 0 || strip_mine_loop)) {
2271     // Check for immediately preceding SafePoint and remove
2272     if (sfpt != nullptr && (strip_mine_loop || is_deleteable_safept(sfpt))) {
2273       if (strip_mine_loop) {
2274         Node* outer_le = outer_ilt->_tail->in(0);
2275         Node* sfpt_clone = sfpt->clone();
2276         sfpt_clone->set_req(0, iffalse);
2277         outer_le->set_req(0, sfpt_clone);
2278 
2279         Node* polladdr = sfpt_clone->in(TypeFunc::Parms);
2280         if (polladdr != nullptr && polladdr->is_Load()) {
2281           // Polling load should be pinned outside inner loop.
2282           Node* new_polladdr = polladdr->clone();
2283           new_polladdr->set_req(0, iffalse);
2284           _igvn.register_new_node_with_optimizer(new_polladdr, polladdr);
2285           set_ctrl(new_polladdr, iffalse);
2286           sfpt_clone->set_req(TypeFunc::Parms, new_polladdr);
2287         }
2288         // When this code runs, loop bodies have not yet been populated.
2289         const bool body_populated = false;
2290         register_control(sfpt_clone, outer_ilt, iffalse, body_populated);
2291         set_idom(outer_le, sfpt_clone, dom_depth(sfpt_clone));
2292       }
2293       lazy_replace(sfpt, sfpt->in(TypeFunc::Control));
2294       if (loop->_safepts != nullptr) {
2295         loop->_safepts->yank(sfpt);
2296       }
2297     }
2298   }
2299 
2300 #ifdef ASSERT
2301   assert(l->is_valid_counted_loop(iv_bt), "counted loop shape is messed up");
2302   assert(l == loop->_head && l->phi() == phi && l->loopexit_or_null() == lex, "" );
2303 #endif
2304 #ifndef PRODUCT
2305   if (TraceLoopOpts) {
2306     tty->print("Counted      ");
2307     loop->dump_head();
2308   }
2309 #endif
2310 
2311   C->print_method(PHASE_AFTER_CLOOPS, 3, l);
2312 
2313   // Capture bounds of the loop in the induction variable Phi before
2314   // subsequent transformation (iteration splitting) obscures the
2315   // bounds
2316   l->phi()->as_Phi()->set_type(l->phi()->Value(&_igvn));
2317 
2318   if (strip_mine_loop) {
2319     l->mark_strip_mined();
2320     l->verify_strip_mined(1);
2321     outer_ilt->_head->as_Loop()->verify_strip_mined(1);
2322     loop = outer_ilt;
2323   }
2324 
2325 #ifndef PRODUCT
2326   if (x->as_Loop()->is_loop_nest_inner_loop() && iv_bt == T_LONG) {
2327     Atomic::inc(&_long_loop_counted_loops);
2328   }
2329 #endif
2330   if (iv_bt == T_LONG && x->as_Loop()->is_loop_nest_outer_loop()) {
2331     l->mark_loop_nest_outer_loop();
2332   }
2333 
2334   return true;
2335 }
2336 
2337 // Check if there is a dominating loop limit check of the form 'init < limit' starting at the loop entry.
2338 // If there is one, then we do not need to create an additional Loop Limit Check Predicate.
2339 bool PhaseIdealLoop::has_dominating_loop_limit_check(Node* init_trip, Node* limit, const jlong stride_con,
2340                                                      const BasicType iv_bt, Node* loop_entry) {
2341   // Eagerly call transform() on the Cmp and Bool node to common them up if possible. This is required in order to
2342   // successfully find a dominated test with the If node below.
2343   Node* cmp_limit;
2344   Node* bol;
2345   if (stride_con > 0) {
2346     cmp_limit = _igvn.transform(CmpNode::make(init_trip, limit, iv_bt));
2347     bol = _igvn.transform(new BoolNode(cmp_limit, BoolTest::lt));
2348   } else {
2349     cmp_limit = _igvn.transform(CmpNode::make(init_trip, limit, iv_bt));
2350     bol = _igvn.transform(new BoolNode(cmp_limit, BoolTest::gt));
2351   }
2352 
2353   // Check if there is already a dominating init < limit check. If so, we do not need a Loop Limit Check Predicate.
2354   IfNode* iff = new IfNode(loop_entry, bol, PROB_MIN, COUNT_UNKNOWN);
2355   // Also add fake IfProj nodes in order to call transform() on the newly created IfNode.
2356   IfFalseNode* if_false = new IfFalseNode(iff);
2357   IfTrueNode* if_true = new IfTrueNode(iff);
2358   Node* dominated_iff = _igvn.transform(iff);
2359   // ConI node? Found dominating test (IfNode::dominated_by() returns a ConI node).
2360   const bool found_dominating_test = dominated_iff != nullptr && dominated_iff->is_ConI();
2361 
2362   // Kill the If with its projections again in the next IGVN round by cutting it off from the graph.
2363   _igvn.replace_input_of(iff, 0, C->top());
2364   _igvn.replace_input_of(iff, 1, C->top());
2365   return found_dominating_test;
2366 }
2367 
2368 //----------------------exact_limit-------------------------------------------
2369 Node* PhaseIdealLoop::exact_limit( IdealLoopTree *loop ) {
2370   assert(loop->_head->is_CountedLoop(), "");
2371   CountedLoopNode *cl = loop->_head->as_CountedLoop();
2372   assert(cl->is_valid_counted_loop(T_INT), "");
2373 
2374   if (cl->stride_con() == 1 ||
2375       cl->stride_con() == -1 ||
2376       cl->limit()->Opcode() == Op_LoopLimit) {
2377     // Old code has exact limit (it could be incorrect in case of int overflow).
2378     // Loop limit is exact with stride == 1. And loop may already have exact limit.
2379     return cl->limit();
2380   }
2381   Node *limit = nullptr;
2382 #ifdef ASSERT
2383   BoolTest::mask bt = cl->loopexit()->test_trip();
2384   assert(bt == BoolTest::lt || bt == BoolTest::gt, "canonical test is expected");
2385 #endif
2386   if (cl->has_exact_trip_count()) {
2387     // Simple case: loop has constant boundaries.
2388     // Use jlongs to avoid integer overflow.
2389     int stride_con = cl->stride_con();
2390     jlong  init_con = cl->init_trip()->get_int();
2391     jlong limit_con = cl->limit()->get_int();
2392     julong trip_cnt = cl->trip_count();
2393     jlong final_con = init_con + trip_cnt*stride_con;
2394     int final_int = (int)final_con;
2395     // The final value should be in integer range since the loop
2396     // is counted and the limit was checked for overflow.
2397     assert(final_con == (jlong)final_int, "final value should be integer");
2398     limit = _igvn.intcon(final_int);
2399   } else {
2400     // Create new LoopLimit node to get exact limit (final iv value).
2401     limit = new LoopLimitNode(C, cl->init_trip(), cl->limit(), cl->stride());
2402     register_new_node(limit, cl->in(LoopNode::EntryControl));
2403   }
2404   assert(limit != nullptr, "sanity");
2405   return limit;
2406 }
2407 
2408 //------------------------------Ideal------------------------------------------
2409 // Return a node which is more "ideal" than the current node.
2410 // Attempt to convert into a counted-loop.
2411 Node *LoopNode::Ideal(PhaseGVN *phase, bool can_reshape) {
2412   if (!can_be_counted_loop(phase) && !is_OuterStripMinedLoop()) {
2413     phase->C->set_major_progress();
2414   }
2415   return RegionNode::Ideal(phase, can_reshape);
2416 }
2417 
2418 #ifdef ASSERT
2419 void LoopNode::verify_strip_mined(int expect_skeleton) const {
2420   const OuterStripMinedLoopNode* outer = nullptr;
2421   const CountedLoopNode* inner = nullptr;
2422   if (is_strip_mined()) {
2423     if (!is_valid_counted_loop(T_INT)) {
2424       return; // Skip malformed counted loop
2425     }
2426     assert(is_CountedLoop(), "no Loop should be marked strip mined");
2427     inner = as_CountedLoop();
2428     outer = inner->in(LoopNode::EntryControl)->as_OuterStripMinedLoop();
2429   } else if (is_OuterStripMinedLoop()) {
2430     outer = this->as_OuterStripMinedLoop();
2431     inner = outer->unique_ctrl_out()->as_CountedLoop();
2432     assert(inner->is_valid_counted_loop(T_INT) && inner->is_strip_mined(), "OuterStripMinedLoop should have been removed");
2433     assert(!is_strip_mined(), "outer loop shouldn't be marked strip mined");
2434   }
2435   if (inner != nullptr || outer != nullptr) {
2436     assert(inner != nullptr && outer != nullptr, "missing loop in strip mined nest");
2437     Node* outer_tail = outer->in(LoopNode::LoopBackControl);
2438     Node* outer_le = outer_tail->in(0);
2439     assert(outer_le->Opcode() == Op_OuterStripMinedLoopEnd, "tail of outer loop should be an If");
2440     Node* sfpt = outer_le->in(0);
2441     assert(sfpt->Opcode() == Op_SafePoint, "where's the safepoint?");
2442     Node* inner_out = sfpt->in(0);
2443     CountedLoopEndNode* cle = inner_out->in(0)->as_CountedLoopEnd();
2444     assert(cle == inner->loopexit_or_null(), "mismatch");
2445     bool has_skeleton = outer_le->in(1)->bottom_type()->singleton() && outer_le->in(1)->bottom_type()->is_int()->get_con() == 0;
2446     if (has_skeleton) {
2447       assert(expect_skeleton == 1 || expect_skeleton == -1, "unexpected skeleton node");
2448       assert(outer->outcnt() == 2, "only control nodes");
2449     } else {
2450       assert(expect_skeleton == 0 || expect_skeleton == -1, "no skeleton node?");
2451       uint phis = 0;
2452       uint be_loads = 0;
2453       Node* be = inner->in(LoopNode::LoopBackControl);
2454       for (DUIterator_Fast imax, i = inner->fast_outs(imax); i < imax; i++) {
2455         Node* u = inner->fast_out(i);
2456         if (u->is_Phi()) {
2457           phis++;
2458           for (DUIterator_Fast jmax, j = be->fast_outs(jmax); j < jmax; j++) {
2459             Node* n = be->fast_out(j);
2460             if (n->is_Load()) {
2461               assert(n->in(0) == be || n->find_prec_edge(be) > 0, "should be on the backedge");
2462               do {
2463                 n = n->raw_out(0);
2464               } while (!n->is_Phi());
2465               if (n == u) {
2466                 be_loads++;
2467                 break;
2468               }
2469             }
2470           }
2471         }
2472       }
2473       assert(be_loads <= phis, "wrong number phis that depends on a pinned load");
2474       for (DUIterator_Fast imax, i = outer->fast_outs(imax); i < imax; i++) {
2475         Node* u = outer->fast_out(i);
2476         assert(u == outer || u == inner || u->is_Phi(), "nothing between inner and outer loop");
2477       }
2478       uint stores = 0;
2479       for (DUIterator_Fast imax, i = inner_out->fast_outs(imax); i < imax; i++) {
2480         Node* u = inner_out->fast_out(i);
2481         if (u->is_Store()) {
2482           stores++;
2483         }
2484       }
2485       // Late optimization of loads on backedge can cause Phi of outer loop to be eliminated but Phi of inner loop is
2486       // not guaranteed to be optimized out.
2487       assert(outer->outcnt() >= phis + 2 - be_loads && outer->outcnt() <= phis + 2 + stores + 1, "only phis");
2488     }
2489     assert(sfpt->outcnt() == 1, "no data node");
2490     assert(outer_tail->outcnt() == 1 || !has_skeleton, "no data node");
2491   }
2492 }
2493 #endif
2494 
2495 //=============================================================================
2496 //------------------------------Ideal------------------------------------------
2497 // Return a node which is more "ideal" than the current node.
2498 // Attempt to convert into a counted-loop.
2499 Node *CountedLoopNode::Ideal(PhaseGVN *phase, bool can_reshape) {
2500   return RegionNode::Ideal(phase, can_reshape);
2501 }
2502 
2503 //------------------------------dump_spec--------------------------------------
2504 // Dump special per-node info
2505 #ifndef PRODUCT
2506 void CountedLoopNode::dump_spec(outputStream *st) const {
2507   LoopNode::dump_spec(st);
2508   if (stride_is_con()) {
2509     st->print("stride: %d ",stride_con());
2510   }
2511   if (is_pre_loop ()) st->print("pre of N%d" , _main_idx);
2512   if (is_main_loop()) st->print("main of N%d", _idx);
2513   if (is_post_loop()) st->print("post of N%d", _main_idx);
2514   if (is_strip_mined()) st->print(" strip mined");
2515 }
2516 #endif
2517 
2518 //=============================================================================
2519 jlong BaseCountedLoopEndNode::stride_con() const {
2520   return stride()->bottom_type()->is_integer(bt())->get_con_as_long(bt());
2521 }
2522 
2523 
2524 BaseCountedLoopEndNode* BaseCountedLoopEndNode::make(Node* control, Node* test, float prob, float cnt, BasicType bt) {
2525   if (bt == T_INT) {
2526     return new CountedLoopEndNode(control, test, prob, cnt);
2527   }
2528   assert(bt == T_LONG, "unsupported");
2529   return new LongCountedLoopEndNode(control, test, prob, cnt);
2530 }
2531 
2532 //=============================================================================
2533 //------------------------------Value-----------------------------------------
2534 const Type* LoopLimitNode::Value(PhaseGVN* phase) const {
2535   const Type* init_t   = phase->type(in(Init));
2536   const Type* limit_t  = phase->type(in(Limit));
2537   const Type* stride_t = phase->type(in(Stride));
2538   // Either input is TOP ==> the result is TOP
2539   if (init_t   == Type::TOP) return Type::TOP;
2540   if (limit_t  == Type::TOP) return Type::TOP;
2541   if (stride_t == Type::TOP) return Type::TOP;
2542 
2543   int stride_con = stride_t->is_int()->get_con();
2544   if (stride_con == 1)
2545     return bottom_type();  // Identity
2546 
2547   if (init_t->is_int()->is_con() && limit_t->is_int()->is_con()) {
2548     // Use jlongs to avoid integer overflow.
2549     jlong init_con   =  init_t->is_int()->get_con();
2550     jlong limit_con  = limit_t->is_int()->get_con();
2551     int  stride_m   = stride_con - (stride_con > 0 ? 1 : -1);
2552     jlong trip_count = (limit_con - init_con + stride_m)/stride_con;
2553     jlong final_con  = init_con + stride_con*trip_count;
2554     int final_int = (int)final_con;
2555     // The final value should be in integer range in almost all cases,
2556     // since the loop is counted and the limit was checked for overflow.
2557     // There some exceptions, for example:
2558     // - During CCP, there might be a temporary overflow from PhiNodes, see JDK-8309266.
2559     // - During PhaseIdealLoop::split_thru_phi, the LoopLimitNode floats possibly far above
2560     //   the loop and its predicates, and we might get constants on one side of the phi that
2561     //   would lead to overflows. Such a code path would never lead us to enter the loop
2562     //   because of the loop limit overflow check that happens after the LoopLimitNode
2563     //   computation with overflow, but before we enter the loop, see JDK-8335747.
2564     if (final_con == (jlong)final_int) {
2565       return TypeInt::make(final_int);
2566     } else {
2567       return bottom_type();
2568     }
2569   }
2570 
2571   return bottom_type(); // TypeInt::INT
2572 }
2573 
2574 //------------------------------Ideal------------------------------------------
2575 // Return a node which is more "ideal" than the current node.
2576 Node *LoopLimitNode::Ideal(PhaseGVN *phase, bool can_reshape) {
2577   if (phase->type(in(Init))   == Type::TOP ||
2578       phase->type(in(Limit))  == Type::TOP ||
2579       phase->type(in(Stride)) == Type::TOP)
2580     return nullptr;  // Dead
2581 
2582   int stride_con = phase->type(in(Stride))->is_int()->get_con();
2583   if (stride_con == 1)
2584     return nullptr;  // Identity
2585 
2586   // Delay following optimizations until all loop optimizations
2587   // done to keep Ideal graph simple.
2588   if (!can_reshape || !phase->C->post_loop_opts_phase()) {
2589     phase->C->record_for_post_loop_opts_igvn(this);
2590     return nullptr;
2591   }
2592 
2593   const TypeInt* init_t  = phase->type(in(Init) )->is_int();
2594   const TypeInt* limit_t = phase->type(in(Limit))->is_int();
2595   jlong stride_p;
2596   jlong lim, ini;
2597   julong max;
2598   if (stride_con > 0) {
2599     stride_p = stride_con;
2600     lim = limit_t->_hi;
2601     ini = init_t->_lo;
2602     max = (julong)max_jint;
2603   } else {
2604     stride_p = -(jlong)stride_con;
2605     lim = init_t->_hi;
2606     ini = limit_t->_lo;
2607     max = (julong)(juint)min_jint; // double cast to get 0x0000000080000000, not 0xffffffff80000000
2608   }
2609   julong range = lim - ini + stride_p;
2610   if (range <= max) {
2611     // Convert to integer expression if it is not overflow.
2612     Node* stride_m = phase->intcon(stride_con - (stride_con > 0 ? 1 : -1));
2613     Node *range = phase->transform(new SubINode(in(Limit), in(Init)));
2614     Node *bias  = phase->transform(new AddINode(range, stride_m));
2615     Node *trip  = phase->transform(new DivINode(nullptr, bias, in(Stride)));
2616     Node *span  = phase->transform(new MulINode(trip, in(Stride)));
2617     return new AddINode(span, in(Init)); // exact limit
2618   }
2619 
2620   if (is_power_of_2(stride_p) ||                // divisor is 2^n
2621       !Matcher::has_match_rule(Op_LoopLimit)) { // or no specialized Mach node?
2622     // Convert to long expression to avoid integer overflow
2623     // and let igvn optimizer convert this division.
2624     //
2625     Node*   init   = phase->transform( new ConvI2LNode(in(Init)));
2626     Node*  limit   = phase->transform( new ConvI2LNode(in(Limit)));
2627     Node* stride   = phase->longcon(stride_con);
2628     Node* stride_m = phase->longcon(stride_con - (stride_con > 0 ? 1 : -1));
2629 
2630     Node *range = phase->transform(new SubLNode(limit, init));
2631     Node *bias  = phase->transform(new AddLNode(range, stride_m));
2632     Node *span;
2633     if (stride_con > 0 && is_power_of_2(stride_p)) {
2634       // bias >= 0 if stride >0, so if stride is 2^n we can use &(-stride)
2635       // and avoid generating rounding for division. Zero trip guard should
2636       // guarantee that init < limit but sometimes the guard is missing and
2637       // we can get situation when init > limit. Note, for the empty loop
2638       // optimization zero trip guard is generated explicitly which leaves
2639       // only RCE predicate where exact limit is used and the predicate
2640       // will simply fail forcing recompilation.
2641       Node* neg_stride   = phase->longcon(-stride_con);
2642       span = phase->transform(new AndLNode(bias, neg_stride));
2643     } else {
2644       Node *trip  = phase->transform(new DivLNode(nullptr, bias, stride));
2645       span = phase->transform(new MulLNode(trip, stride));
2646     }
2647     // Convert back to int
2648     Node *span_int = phase->transform(new ConvL2INode(span));
2649     return new AddINode(span_int, in(Init)); // exact limit
2650   }
2651 
2652   return nullptr;    // No progress
2653 }
2654 
2655 //------------------------------Identity---------------------------------------
2656 // If stride == 1 return limit node.
2657 Node* LoopLimitNode::Identity(PhaseGVN* phase) {
2658   int stride_con = phase->type(in(Stride))->is_int()->get_con();
2659   if (stride_con == 1 || stride_con == -1)
2660     return in(Limit);
2661   return this;
2662 }
2663 
2664 //=============================================================================
2665 //----------------------match_incr_with_optional_truncation--------------------
2666 // Match increment with optional truncation:
2667 // CHAR: (i+1)&0x7fff, BYTE: ((i+1)<<8)>>8, or SHORT: ((i+1)<<16)>>16
2668 // Return null for failure. Success returns the increment node.
2669 Node* CountedLoopNode::match_incr_with_optional_truncation(Node* expr, Node** trunc1, Node** trunc2,
2670                                                            const TypeInteger** trunc_type,
2671                                                            BasicType bt) {
2672   // Quick cutouts:
2673   if (expr == nullptr || expr->req() != 3)  return nullptr;
2674 
2675   Node *t1 = nullptr;
2676   Node *t2 = nullptr;
2677   Node* n1 = expr;
2678   int   n1op = n1->Opcode();
2679   const TypeInteger* trunc_t = TypeInteger::bottom(bt);
2680 
2681   if (bt == T_INT) {
2682     // Try to strip (n1 & M) or (n1 << N >> N) from n1.
2683     if (n1op == Op_AndI &&
2684         n1->in(2)->is_Con() &&
2685         n1->in(2)->bottom_type()->is_int()->get_con() == 0x7fff) {
2686       // %%% This check should match any mask of 2**K-1.
2687       t1 = n1;
2688       n1 = t1->in(1);
2689       n1op = n1->Opcode();
2690       trunc_t = TypeInt::CHAR;
2691     } else if (n1op == Op_RShiftI &&
2692                n1->in(1) != nullptr &&
2693                n1->in(1)->Opcode() == Op_LShiftI &&
2694                n1->in(2) == n1->in(1)->in(2) &&
2695                n1->in(2)->is_Con()) {
2696       jint shift = n1->in(2)->bottom_type()->is_int()->get_con();
2697       // %%% This check should match any shift in [1..31].
2698       if (shift == 16 || shift == 8) {
2699         t1 = n1;
2700         t2 = t1->in(1);
2701         n1 = t2->in(1);
2702         n1op = n1->Opcode();
2703         if (shift == 16) {
2704           trunc_t = TypeInt::SHORT;
2705         } else if (shift == 8) {
2706           trunc_t = TypeInt::BYTE;
2707         }
2708       }
2709     }
2710   }
2711 
2712   // If (maybe after stripping) it is an AddI, we won:
2713   if (n1op == Op_Add(bt)) {
2714     *trunc1 = t1;
2715     *trunc2 = t2;
2716     *trunc_type = trunc_t;
2717     return n1;
2718   }
2719 
2720   // failed
2721   return nullptr;
2722 }
2723 
2724 LoopNode* CountedLoopNode::skip_strip_mined(int expect_skeleton) {
2725   if (is_strip_mined() && in(EntryControl) != nullptr && in(EntryControl)->is_OuterStripMinedLoop()) {
2726     verify_strip_mined(expect_skeleton);
2727     return in(EntryControl)->as_Loop();
2728   }
2729   return this;
2730 }
2731 
2732 OuterStripMinedLoopNode* CountedLoopNode::outer_loop() const {
2733   assert(is_strip_mined(), "not a strip mined loop");
2734   Node* c = in(EntryControl);
2735   if (c == nullptr || c->is_top() || !c->is_OuterStripMinedLoop()) {
2736     return nullptr;
2737   }
2738   return c->as_OuterStripMinedLoop();
2739 }
2740 
2741 IfTrueNode* OuterStripMinedLoopNode::outer_loop_tail() const {
2742   Node* c = in(LoopBackControl);
2743   if (c == nullptr || c->is_top()) {
2744     return nullptr;
2745   }
2746   return c->as_IfTrue();
2747 }
2748 
2749 IfTrueNode* CountedLoopNode::outer_loop_tail() const {
2750   LoopNode* l = outer_loop();
2751   if (l == nullptr) {
2752     return nullptr;
2753   }
2754   return l->outer_loop_tail();
2755 }
2756 
2757 OuterStripMinedLoopEndNode* OuterStripMinedLoopNode::outer_loop_end() const {
2758   IfTrueNode* proj = outer_loop_tail();
2759   if (proj == nullptr) {
2760     return nullptr;
2761   }
2762   Node* c = proj->in(0);
2763   if (c == nullptr || c->is_top() || c->outcnt() != 2) {
2764     return nullptr;
2765   }
2766   return c->as_OuterStripMinedLoopEnd();
2767 }
2768 
2769 OuterStripMinedLoopEndNode* CountedLoopNode::outer_loop_end() const {
2770   LoopNode* l = outer_loop();
2771   if (l == nullptr) {
2772     return nullptr;
2773   }
2774   return l->outer_loop_end();
2775 }
2776 
2777 IfFalseNode* OuterStripMinedLoopNode::outer_loop_exit() const {
2778   IfNode* le = outer_loop_end();
2779   if (le == nullptr) {
2780     return nullptr;
2781   }
2782   Node* c = le->proj_out_or_null(false);
2783   if (c == nullptr) {
2784     return nullptr;
2785   }
2786   return c->as_IfFalse();
2787 }
2788 
2789 IfFalseNode* CountedLoopNode::outer_loop_exit() const {
2790   LoopNode* l = outer_loop();
2791   if (l == nullptr) {
2792     return nullptr;
2793   }
2794   return l->outer_loop_exit();
2795 }
2796 
2797 SafePointNode* OuterStripMinedLoopNode::outer_safepoint() const {
2798   IfNode* le = outer_loop_end();
2799   if (le == nullptr) {
2800     return nullptr;
2801   }
2802   Node* c = le->in(0);
2803   if (c == nullptr || c->is_top()) {
2804     return nullptr;
2805   }
2806   assert(c->Opcode() == Op_SafePoint, "broken outer loop");
2807   return c->as_SafePoint();
2808 }
2809 
2810 SafePointNode* CountedLoopNode::outer_safepoint() const {
2811   LoopNode* l = outer_loop();
2812   if (l == nullptr) {
2813     return nullptr;
2814   }
2815   return l->outer_safepoint();
2816 }
2817 
2818 Node* CountedLoopNode::skip_assertion_predicates_with_halt() {
2819   Node* ctrl = in(LoopNode::EntryControl);
2820   if (ctrl == nullptr) {
2821     // Dying loop.
2822     return nullptr;
2823   }
2824   if (is_main_loop()) {
2825     ctrl = skip_strip_mined()->in(LoopNode::EntryControl);
2826   }
2827   if (is_main_loop() || is_post_loop()) {
2828     AssertionPredicates assertion_predicates(ctrl);
2829     return assertion_predicates.entry();
2830   }
2831   return ctrl;
2832 }
2833 
2834 
2835 int CountedLoopNode::stride_con() const {
2836   CountedLoopEndNode* cle = loopexit_or_null();
2837   return cle != nullptr ? cle->stride_con() : 0;
2838 }
2839 
2840 BaseCountedLoopNode* BaseCountedLoopNode::make(Node* entry, Node* backedge, BasicType bt) {
2841   if (bt == T_INT) {
2842     return new CountedLoopNode(entry, backedge);
2843   }
2844   assert(bt == T_LONG, "unsupported");
2845   return new LongCountedLoopNode(entry, backedge);
2846 }
2847 
2848 void OuterStripMinedLoopNode::fix_sunk_stores(CountedLoopEndNode* inner_cle, LoopNode* inner_cl, PhaseIterGVN* igvn,
2849                                               PhaseIdealLoop* iloop) {
2850   Node* cle_out = inner_cle->proj_out(false);
2851   Node* cle_tail = inner_cle->proj_out(true);
2852   if (cle_out->outcnt() > 1) {
2853     // Look for chains of stores that were sunk
2854     // out of the inner loop and are in the outer loop
2855     for (DUIterator_Fast imax, i = cle_out->fast_outs(imax); i < imax; i++) {
2856       Node* u = cle_out->fast_out(i);
2857       if (u->is_Store()) {
2858         int alias_idx = igvn->C->get_alias_index(u->adr_type());
2859         Node* first = u;
2860         for (;;) {
2861           Node* next = first->in(MemNode::Memory);
2862           if (!next->is_Store() || next->in(0) != cle_out) {
2863             break;
2864           }
2865           assert(igvn->C->get_alias_index(next->adr_type()) == alias_idx, "");
2866           first = next;
2867         }
2868         Node* last = u;
2869         for (;;) {
2870           Node* next = nullptr;
2871           for (DUIterator_Fast jmax, j = last->fast_outs(jmax); j < jmax; j++) {
2872             Node* uu = last->fast_out(j);
2873             if (uu->is_Store() && uu->in(0) == cle_out) {
2874               assert(next == nullptr, "only one in the outer loop");
2875               next = uu;
2876               assert(igvn->C->get_alias_index(next->adr_type()) == alias_idx, "");
2877             }
2878           }
2879           if (next == nullptr) {
2880             break;
2881           }
2882           last = next;
2883         }
2884         Node* phi = nullptr;
2885         for (DUIterator_Fast jmax, j = inner_cl->fast_outs(jmax); j < jmax; j++) {
2886           Node* uu = inner_cl->fast_out(j);
2887           if (uu->is_Phi()) {
2888             Node* be = uu->in(LoopNode::LoopBackControl);
2889             if (be->is_Store() && be->in(0) == inner_cl->in(LoopNode::LoopBackControl)) {
2890               assert(igvn->C->get_alias_index(uu->adr_type()) != alias_idx && igvn->C->get_alias_index(uu->adr_type()) != Compile::AliasIdxBot, "unexpected store");
2891             }
2892             if (be == last || be == first->in(MemNode::Memory)) {
2893               assert(igvn->C->get_alias_index(uu->adr_type()) == alias_idx || igvn->C->get_alias_index(uu->adr_type()) == Compile::AliasIdxBot, "unexpected alias");
2894               assert(phi == nullptr, "only one phi");
2895               phi = uu;
2896             }
2897           }
2898         }
2899 #ifdef ASSERT
2900         for (DUIterator_Fast jmax, j = inner_cl->fast_outs(jmax); j < jmax; j++) {
2901           Node* uu = inner_cl->fast_out(j);
2902           if (uu->is_memory_phi()) {
2903             if (uu->adr_type() == igvn->C->get_adr_type(igvn->C->get_alias_index(u->adr_type()))) {
2904               assert(phi == uu, "what's that phi?");
2905             } else if (uu->adr_type() == TypePtr::BOTTOM) {
2906               Node* n = uu->in(LoopNode::LoopBackControl);
2907               uint limit = igvn->C->live_nodes();
2908               uint i = 0;
2909               while (n != uu) {
2910                 i++;
2911                 assert(i < limit, "infinite loop");
2912                 if (n->is_Proj()) {
2913                   n = n->in(0);
2914                 } else if (n->is_SafePoint() || n->is_MemBar()) {
2915                   n = n->in(TypeFunc::Memory);
2916                 } else if (n->is_Phi()) {
2917                   n = n->in(1);
2918                 } else if (n->is_MergeMem()) {
2919                   n = n->as_MergeMem()->memory_at(igvn->C->get_alias_index(u->adr_type()));
2920                 } else if (n->is_Store() || n->is_LoadStore() || n->is_ClearArray()) {
2921                   n = n->in(MemNode::Memory);
2922                 } else {
2923                   n->dump();
2924                   ShouldNotReachHere();
2925                 }
2926               }
2927             }
2928           }
2929         }
2930 #endif
2931         if (phi == nullptr) {
2932           // If an entire chains was sunk, the
2933           // inner loop has no phi for that memory
2934           // slice, create one for the outer loop
2935           phi = PhiNode::make(inner_cl, first->in(MemNode::Memory), Type::MEMORY,
2936                               igvn->C->get_adr_type(igvn->C->get_alias_index(u->adr_type())));
2937           phi->set_req(LoopNode::LoopBackControl, last);
2938           phi = register_new_node(phi, inner_cl, igvn, iloop);
2939           igvn->replace_input_of(first, MemNode::Memory, phi);
2940         } else {
2941           // Or fix the outer loop fix to include
2942           // that chain of stores.
2943           Node* be = phi->in(LoopNode::LoopBackControl);
2944           assert(!(be->is_Store() && be->in(0) == inner_cl->in(LoopNode::LoopBackControl)), "store on the backedge + sunk stores: unsupported");
2945           if (be == first->in(MemNode::Memory)) {
2946             if (be == phi->in(LoopNode::LoopBackControl)) {
2947               igvn->replace_input_of(phi, LoopNode::LoopBackControl, last);
2948             } else {
2949               igvn->replace_input_of(be, MemNode::Memory, last);
2950             }
2951           } else {
2952 #ifdef ASSERT
2953             if (be == phi->in(LoopNode::LoopBackControl)) {
2954               assert(phi->in(LoopNode::LoopBackControl) == last, "");
2955             } else {
2956               assert(be->in(MemNode::Memory) == last, "");
2957             }
2958 #endif
2959           }
2960         }
2961       }
2962     }
2963   }
2964 }
2965 
2966 void OuterStripMinedLoopNode::adjust_strip_mined_loop(PhaseIterGVN* igvn) {
2967   // Look for the outer & inner strip mined loop, reduce number of
2968   // iterations of the inner loop, set exit condition of outer loop,
2969   // construct required phi nodes for outer loop.
2970   CountedLoopNode* inner_cl = unique_ctrl_out()->as_CountedLoop();
2971   assert(inner_cl->is_strip_mined(), "inner loop should be strip mined");
2972   if (LoopStripMiningIter == 0) {
2973     remove_outer_loop_and_safepoint(igvn);
2974     return;
2975   }
2976   if (LoopStripMiningIter == 1) {
2977     transform_to_counted_loop(igvn, nullptr);
2978     return;
2979   }
2980   Node* inner_iv_phi = inner_cl->phi();
2981   if (inner_iv_phi == nullptr) {
2982     IfNode* outer_le = outer_loop_end();
2983     Node* iff = igvn->transform(new IfNode(outer_le->in(0), outer_le->in(1), outer_le->_prob, outer_le->_fcnt));
2984     igvn->replace_node(outer_le, iff);
2985     inner_cl->clear_strip_mined();
2986     return;
2987   }
2988   CountedLoopEndNode* inner_cle = inner_cl->loopexit();
2989 
2990   int stride = inner_cl->stride_con();
2991   // For a min int stride, LoopStripMiningIter * stride overflows the int range for all values of LoopStripMiningIter
2992   // except 0 or 1. Those values are handled early on in this method and causes the method to return. So for a min int
2993   // stride, the method is guaranteed to return at the next check below.
2994   jlong scaled_iters_long = ((jlong)LoopStripMiningIter) * ABS((jlong)stride);
2995   int scaled_iters = (int)scaled_iters_long;
2996   if ((jlong)scaled_iters != scaled_iters_long) {
2997     // Remove outer loop and safepoint (too few iterations)
2998     remove_outer_loop_and_safepoint(igvn);
2999     return;
3000   }
3001   jlong short_scaled_iters = LoopStripMiningIterShortLoop * ABS(stride);
3002   const TypeInt* inner_iv_t = igvn->type(inner_iv_phi)->is_int();
3003   jlong iter_estimate = (jlong)inner_iv_t->_hi - (jlong)inner_iv_t->_lo;
3004   assert(iter_estimate > 0, "broken");
3005   if (iter_estimate <= short_scaled_iters) {
3006     // Remove outer loop and safepoint: loop executes less than LoopStripMiningIterShortLoop
3007     remove_outer_loop_and_safepoint(igvn);
3008     return;
3009   }
3010   if (iter_estimate <= scaled_iters_long) {
3011     // We would only go through one iteration of
3012     // the outer loop: drop the outer loop but
3013     // keep the safepoint so we don't run for
3014     // too long without a safepoint
3015     IfNode* outer_le = outer_loop_end();
3016     Node* iff = igvn->transform(new IfNode(outer_le->in(0), outer_le->in(1), outer_le->_prob, outer_le->_fcnt));
3017     igvn->replace_node(outer_le, iff);
3018     inner_cl->clear_strip_mined();
3019     return;
3020   }
3021 
3022   Node* cle_tail = inner_cle->proj_out(true);
3023   ResourceMark rm;
3024   Node_List old_new;
3025   if (cle_tail->outcnt() > 1) {
3026     // Look for nodes on backedge of inner loop and clone them
3027     Unique_Node_List backedge_nodes;
3028     for (DUIterator_Fast imax, i = cle_tail->fast_outs(imax); i < imax; i++) {
3029       Node* u = cle_tail->fast_out(i);
3030       if (u != inner_cl) {
3031         assert(!u->is_CFG(), "control flow on the backedge?");
3032         backedge_nodes.push(u);
3033       }
3034     }
3035     uint last = igvn->C->unique();
3036     for (uint next = 0; next < backedge_nodes.size(); next++) {
3037       Node* n = backedge_nodes.at(next);
3038       old_new.map(n->_idx, n->clone());
3039       for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
3040         Node* u = n->fast_out(i);
3041         assert(!u->is_CFG(), "broken");
3042         if (u->_idx >= last) {
3043           continue;
3044         }
3045         if (!u->is_Phi()) {
3046           backedge_nodes.push(u);
3047         } else {
3048           assert(u->in(0) == inner_cl, "strange phi on the backedge");
3049         }
3050       }
3051     }
3052     // Put the clones on the outer loop backedge
3053     Node* le_tail = outer_loop_tail();
3054     for (uint next = 0; next < backedge_nodes.size(); next++) {
3055       Node *n = old_new[backedge_nodes.at(next)->_idx];
3056       for (uint i = 1; i < n->req(); i++) {
3057         if (n->in(i) != nullptr && old_new[n->in(i)->_idx] != nullptr) {
3058           n->set_req(i, old_new[n->in(i)->_idx]);
3059         }
3060       }
3061       if (n->in(0) != nullptr && n->in(0) == cle_tail) {
3062         n->set_req(0, le_tail);
3063       }
3064       igvn->register_new_node_with_optimizer(n);
3065     }
3066   }
3067 
3068   Node* iv_phi = nullptr;
3069   // Make a clone of each phi in the inner loop
3070   // for the outer loop
3071   for (uint i = 0; i < inner_cl->outcnt(); i++) {
3072     Node* u = inner_cl->raw_out(i);
3073     if (u->is_Phi()) {
3074       assert(u->in(0) == inner_cl, "inconsistent");
3075       Node* phi = u->clone();
3076       phi->set_req(0, this);
3077       Node* be = old_new[phi->in(LoopNode::LoopBackControl)->_idx];
3078       if (be != nullptr) {
3079         phi->set_req(LoopNode::LoopBackControl, be);
3080       }
3081       phi = igvn->transform(phi);
3082       igvn->replace_input_of(u, LoopNode::EntryControl, phi);
3083       if (u == inner_iv_phi) {
3084         iv_phi = phi;
3085       }
3086     }
3087   }
3088 
3089   if (iv_phi != nullptr) {
3090     // Now adjust the inner loop's exit condition
3091     Node* limit = inner_cl->limit();
3092     // If limit < init for stride > 0 (or limit > init for stride < 0),
3093     // the loop body is run only once. Given limit - init (init - limit resp.)
3094     // would be negative, the unsigned comparison below would cause
3095     // the loop body to be run for LoopStripMiningIter.
3096     Node* max = nullptr;
3097     if (stride > 0) {
3098       max = MaxNode::max_diff_with_zero(limit, iv_phi, TypeInt::INT, *igvn);
3099     } else {
3100       max = MaxNode::max_diff_with_zero(iv_phi, limit, TypeInt::INT, *igvn);
3101     }
3102     // sub is positive and can be larger than the max signed int
3103     // value. Use an unsigned min.
3104     Node* const_iters = igvn->intcon(scaled_iters);
3105     Node* min = MaxNode::unsigned_min(max, const_iters, TypeInt::make(0, scaled_iters, Type::WidenMin), *igvn);
3106     // min is the number of iterations for the next inner loop execution:
3107     // unsigned_min(max(limit - iv_phi, 0), scaled_iters) if stride > 0
3108     // unsigned_min(max(iv_phi - limit, 0), scaled_iters) if stride < 0
3109 
3110     Node* new_limit = nullptr;
3111     if (stride > 0) {
3112       new_limit = igvn->transform(new AddINode(min, iv_phi));
3113     } else {
3114       new_limit = igvn->transform(new SubINode(iv_phi, min));
3115     }
3116     Node* inner_cmp = inner_cle->cmp_node();
3117     Node* inner_bol = inner_cle->in(CountedLoopEndNode::TestValue);
3118     Node* outer_bol = inner_bol;
3119     // cmp node for inner loop may be shared
3120     inner_cmp = inner_cmp->clone();
3121     inner_cmp->set_req(2, new_limit);
3122     inner_bol = inner_bol->clone();
3123     inner_bol->set_req(1, igvn->transform(inner_cmp));
3124     igvn->replace_input_of(inner_cle, CountedLoopEndNode::TestValue, igvn->transform(inner_bol));
3125     // Set the outer loop's exit condition too
3126     igvn->replace_input_of(outer_loop_end(), 1, outer_bol);
3127   } else {
3128     assert(false, "should be able to adjust outer loop");
3129     IfNode* outer_le = outer_loop_end();
3130     Node* iff = igvn->transform(new IfNode(outer_le->in(0), outer_le->in(1), outer_le->_prob, outer_le->_fcnt));
3131     igvn->replace_node(outer_le, iff);
3132     inner_cl->clear_strip_mined();
3133   }
3134 }
3135 
3136 void OuterStripMinedLoopNode::transform_to_counted_loop(PhaseIterGVN* igvn, PhaseIdealLoop* iloop) {
3137   CountedLoopNode* inner_cl = unique_ctrl_out()->as_CountedLoop();
3138   CountedLoopEndNode* cle = inner_cl->loopexit();
3139   Node* inner_test = cle->in(1);
3140   IfNode* outer_le = outer_loop_end();
3141   CountedLoopEndNode* inner_cle = inner_cl->loopexit();
3142   Node* safepoint = outer_safepoint();
3143 
3144   fix_sunk_stores(inner_cle, inner_cl, igvn, iloop);
3145 
3146   // make counted loop exit test always fail
3147   ConINode* zero = igvn->intcon(0);
3148   if (iloop != nullptr) {
3149     iloop->set_root_as_ctrl(zero);
3150   }
3151   igvn->replace_input_of(cle, 1, zero);
3152   // replace outer loop end with CountedLoopEndNode with formers' CLE's exit test
3153   Node* new_end = new CountedLoopEndNode(outer_le->in(0), inner_test, cle->_prob, cle->_fcnt);
3154   register_control(new_end, inner_cl, outer_le->in(0), igvn, iloop);
3155   if (iloop == nullptr) {
3156     igvn->replace_node(outer_le, new_end);
3157   } else {
3158     iloop->lazy_replace(outer_le, new_end);
3159   }
3160   // the backedge of the inner loop must be rewired to the new loop end
3161   Node* backedge = cle->proj_out(true);
3162   igvn->replace_input_of(backedge, 0, new_end);
3163   if (iloop != nullptr) {
3164     iloop->set_idom(backedge, new_end, iloop->dom_depth(new_end) + 1);
3165   }
3166   // make the outer loop go away
3167   igvn->replace_input_of(in(LoopBackControl), 0, igvn->C->top());
3168   igvn->replace_input_of(this, LoopBackControl, igvn->C->top());
3169   inner_cl->clear_strip_mined();
3170   if (iloop != nullptr) {
3171     Unique_Node_List wq;
3172     wq.push(safepoint);
3173 
3174     IdealLoopTree* outer_loop_ilt = iloop->get_loop(this);
3175     IdealLoopTree* loop = iloop->get_loop(inner_cl);
3176 
3177     for (uint i = 0; i < wq.size(); i++) {
3178       Node* n = wq.at(i);
3179       for (uint j = 0; j < n->req(); ++j) {
3180         Node* in = n->in(j);
3181         if (in == nullptr || in->is_CFG()) {
3182           continue;
3183         }
3184         if (iloop->get_loop(iloop->get_ctrl(in)) != outer_loop_ilt) {
3185           continue;
3186         }
3187         assert(!loop->_body.contains(in), "");
3188         loop->_body.push(in);
3189         wq.push(in);
3190       }
3191     }
3192     iloop->set_loop(safepoint, loop);
3193     loop->_body.push(safepoint);
3194     iloop->set_loop(safepoint->in(0), loop);
3195     loop->_body.push(safepoint->in(0));
3196     outer_loop_ilt->_tail = igvn->C->top();
3197   }
3198 }
3199 
3200 void OuterStripMinedLoopNode::remove_outer_loop_and_safepoint(PhaseIterGVN* igvn) const {
3201   CountedLoopNode* inner_cl = unique_ctrl_out()->as_CountedLoop();
3202   Node* outer_sfpt = outer_safepoint();
3203   Node* outer_out = outer_loop_exit();
3204   igvn->replace_node(outer_out, outer_sfpt->in(0));
3205   igvn->replace_input_of(outer_sfpt, 0, igvn->C->top());
3206   inner_cl->clear_strip_mined();
3207 }
3208 
3209 Node* OuterStripMinedLoopNode::register_new_node(Node* node, LoopNode* ctrl, PhaseIterGVN* igvn, PhaseIdealLoop* iloop) {
3210   if (iloop == nullptr) {
3211     return igvn->transform(node);
3212   }
3213   iloop->register_new_node(node, ctrl);
3214   return node;
3215 }
3216 
3217 Node* OuterStripMinedLoopNode::register_control(Node* node, Node* loop, Node* idom, PhaseIterGVN* igvn,
3218                                                 PhaseIdealLoop* iloop) {
3219   if (iloop == nullptr) {
3220     return igvn->transform(node);
3221   }
3222   iloop->register_control(node, iloop->get_loop(loop), idom);
3223   return node;
3224 }
3225 
3226 const Type* OuterStripMinedLoopEndNode::Value(PhaseGVN* phase) const {
3227   if (!in(0)) return Type::TOP;
3228   if (phase->type(in(0)) == Type::TOP)
3229     return Type::TOP;
3230 
3231   // Until expansion, the loop end condition is not set so this should not constant fold.
3232   if (is_expanded(phase)) {
3233     return IfNode::Value(phase);
3234   }
3235 
3236   return TypeTuple::IFBOTH;
3237 }
3238 
3239 bool OuterStripMinedLoopEndNode::is_expanded(PhaseGVN *phase) const {
3240   // The outer strip mined loop head only has Phi uses after expansion
3241   if (phase->is_IterGVN()) {
3242     Node* backedge = proj_out_or_null(true);
3243     if (backedge != nullptr) {
3244       Node* head = backedge->unique_ctrl_out_or_null();
3245       if (head != nullptr && head->is_OuterStripMinedLoop()) {
3246         if (head->find_out_with(Op_Phi) != nullptr) {
3247           return true;
3248         }
3249       }
3250     }
3251   }
3252   return false;
3253 }
3254 
3255 Node *OuterStripMinedLoopEndNode::Ideal(PhaseGVN *phase, bool can_reshape) {
3256   if (remove_dead_region(phase, can_reshape))  return this;
3257 
3258   return nullptr;
3259 }
3260 
3261 //------------------------------filtered_type--------------------------------
3262 // Return a type based on condition control flow
3263 // A successful return will be a type that is restricted due
3264 // to a series of dominating if-tests, such as:
3265 //    if (i < 10) {
3266 //       if (i > 0) {
3267 //          here: "i" type is [1..10)
3268 //       }
3269 //    }
3270 // or a control flow merge
3271 //    if (i < 10) {
3272 //       do {
3273 //          phi( , ) -- at top of loop type is [min_int..10)
3274 //         i = ?
3275 //       } while ( i < 10)
3276 //
3277 const TypeInt* PhaseIdealLoop::filtered_type( Node *n, Node* n_ctrl) {
3278   assert(n && n->bottom_type()->is_int(), "must be int");
3279   const TypeInt* filtered_t = nullptr;
3280   if (!n->is_Phi()) {
3281     assert(n_ctrl != nullptr || n_ctrl == C->top(), "valid control");
3282     filtered_t = filtered_type_from_dominators(n, n_ctrl);
3283 
3284   } else {
3285     Node* phi    = n->as_Phi();
3286     Node* region = phi->in(0);
3287     assert(n_ctrl == nullptr || n_ctrl == region, "ctrl parameter must be region");
3288     if (region && region != C->top()) {
3289       for (uint i = 1; i < phi->req(); i++) {
3290         Node* val   = phi->in(i);
3291         Node* use_c = region->in(i);
3292         const TypeInt* val_t = filtered_type_from_dominators(val, use_c);
3293         if (val_t != nullptr) {
3294           if (filtered_t == nullptr) {
3295             filtered_t = val_t;
3296           } else {
3297             filtered_t = filtered_t->meet(val_t)->is_int();
3298           }
3299         }
3300       }
3301     }
3302   }
3303   const TypeInt* n_t = _igvn.type(n)->is_int();
3304   if (filtered_t != nullptr) {
3305     n_t = n_t->join(filtered_t)->is_int();
3306   }
3307   return n_t;
3308 }
3309 
3310 
3311 //------------------------------filtered_type_from_dominators--------------------------------
3312 // Return a possibly more restrictive type for val based on condition control flow of dominators
3313 const TypeInt* PhaseIdealLoop::filtered_type_from_dominators( Node* val, Node *use_ctrl) {
3314   if (val->is_Con()) {
3315      return val->bottom_type()->is_int();
3316   }
3317   uint if_limit = 10; // Max number of dominating if's visited
3318   const TypeInt* rtn_t = nullptr;
3319 
3320   if (use_ctrl && use_ctrl != C->top()) {
3321     Node* val_ctrl = get_ctrl(val);
3322     uint val_dom_depth = dom_depth(val_ctrl);
3323     Node* pred = use_ctrl;
3324     uint if_cnt = 0;
3325     while (if_cnt < if_limit) {
3326       if ((pred->Opcode() == Op_IfTrue || pred->Opcode() == Op_IfFalse)) {
3327         if_cnt++;
3328         const TypeInt* if_t = IfNode::filtered_int_type(&_igvn, val, pred);
3329         if (if_t != nullptr) {
3330           if (rtn_t == nullptr) {
3331             rtn_t = if_t;
3332           } else {
3333             rtn_t = rtn_t->join(if_t)->is_int();
3334           }
3335         }
3336       }
3337       pred = idom(pred);
3338       if (pred == nullptr || pred == C->top()) {
3339         break;
3340       }
3341       // Stop if going beyond definition block of val
3342       if (dom_depth(pred) < val_dom_depth) {
3343         break;
3344       }
3345     }
3346   }
3347   return rtn_t;
3348 }
3349 
3350 
3351 //------------------------------dump_spec--------------------------------------
3352 // Dump special per-node info
3353 #ifndef PRODUCT
3354 void CountedLoopEndNode::dump_spec(outputStream *st) const {
3355   if( in(TestValue) != nullptr && in(TestValue)->is_Bool() ) {
3356     BoolTest bt( test_trip()); // Added this for g++.
3357 
3358     st->print("[");
3359     bt.dump_on(st);
3360     st->print("]");
3361   }
3362   st->print(" ");
3363   IfNode::dump_spec(st);
3364 }
3365 #endif
3366 
3367 //=============================================================================
3368 //------------------------------is_member--------------------------------------
3369 // Is 'l' a member of 'this'?
3370 bool IdealLoopTree::is_member(const IdealLoopTree *l) const {
3371   while( l->_nest > _nest ) l = l->_parent;
3372   return l == this;
3373 }
3374 
3375 //------------------------------set_nest---------------------------------------
3376 // Set loop tree nesting depth.  Accumulate _has_call bits.
3377 int IdealLoopTree::set_nest( uint depth ) {
3378   assert(depth <= SHRT_MAX, "sanity");
3379   _nest = depth;
3380   int bits = _has_call;
3381   if( _child ) bits |= _child->set_nest(depth+1);
3382   if( bits ) _has_call = 1;
3383   if( _next  ) bits |= _next ->set_nest(depth  );
3384   return bits;
3385 }
3386 
3387 //------------------------------split_fall_in----------------------------------
3388 // Split out multiple fall-in edges from the loop header.  Move them to a
3389 // private RegionNode before the loop.  This becomes the loop landing pad.
3390 void IdealLoopTree::split_fall_in( PhaseIdealLoop *phase, int fall_in_cnt ) {
3391   PhaseIterGVN &igvn = phase->_igvn;
3392   uint i;
3393 
3394   // Make a new RegionNode to be the landing pad.
3395   RegionNode* landing_pad = new RegionNode(fall_in_cnt + 1);
3396   phase->set_loop(landing_pad,_parent);
3397   // If _head was irreducible loop entry, landing_pad may now be too
3398   landing_pad->set_loop_status(_head->as_Region()->loop_status());
3399   // Gather all the fall-in control paths into the landing pad
3400   uint icnt = fall_in_cnt;
3401   uint oreq = _head->req();
3402   for( i = oreq-1; i>0; i-- )
3403     if( !phase->is_member( this, _head->in(i) ) )
3404       landing_pad->set_req(icnt--,_head->in(i));
3405 
3406   // Peel off PhiNode edges as well
3407   for (DUIterator_Fast jmax, j = _head->fast_outs(jmax); j < jmax; j++) {
3408     Node *oj = _head->fast_out(j);
3409     if( oj->is_Phi() ) {
3410       PhiNode* old_phi = oj->as_Phi();
3411       assert( old_phi->region() == _head, "" );
3412       igvn.hash_delete(old_phi);   // Yank from hash before hacking edges
3413       Node *p = PhiNode::make_blank(landing_pad, old_phi);
3414       uint icnt = fall_in_cnt;
3415       for( i = oreq-1; i>0; i-- ) {
3416         if( !phase->is_member( this, _head->in(i) ) ) {
3417           p->init_req(icnt--, old_phi->in(i));
3418           // Go ahead and clean out old edges from old phi
3419           old_phi->del_req(i);
3420         }
3421       }
3422       // Search for CSE's here, because ZKM.jar does a lot of
3423       // loop hackery and we need to be a little incremental
3424       // with the CSE to avoid O(N^2) node blow-up.
3425       Node *p2 = igvn.hash_find_insert(p); // Look for a CSE
3426       if( p2 ) {                // Found CSE
3427         p->destruct(&igvn);     // Recover useless new node
3428         p = p2;                 // Use old node
3429       } else {
3430         igvn.register_new_node_with_optimizer(p, old_phi);
3431       }
3432       // Make old Phi refer to new Phi.
3433       old_phi->add_req(p);
3434       // Check for the special case of making the old phi useless and
3435       // disappear it.  In JavaGrande I have a case where this useless
3436       // Phi is the loop limit and prevents recognizing a CountedLoop
3437       // which in turn prevents removing an empty loop.
3438       Node *id_old_phi = old_phi->Identity(&igvn);
3439       if( id_old_phi != old_phi ) { // Found a simple identity?
3440         // Note that I cannot call 'replace_node' here, because
3441         // that will yank the edge from old_phi to the Region and
3442         // I'm mid-iteration over the Region's uses.
3443         for (DUIterator_Last imin, i = old_phi->last_outs(imin); i >= imin; ) {
3444           Node* use = old_phi->last_out(i);
3445           igvn.rehash_node_delayed(use);
3446           uint uses_found = 0;
3447           for (uint j = 0; j < use->len(); j++) {
3448             if (use->in(j) == old_phi) {
3449               if (j < use->req()) use->set_req (j, id_old_phi);
3450               else                use->set_prec(j, id_old_phi);
3451               uses_found++;
3452             }
3453           }
3454           i -= uses_found;    // we deleted 1 or more copies of this edge
3455         }
3456       }
3457       igvn._worklist.push(old_phi);
3458     }
3459   }
3460   // Finally clean out the fall-in edges from the RegionNode
3461   for( i = oreq-1; i>0; i-- ) {
3462     if( !phase->is_member( this, _head->in(i) ) ) {
3463       _head->del_req(i);
3464     }
3465   }
3466   igvn.rehash_node_delayed(_head);
3467   // Transform landing pad
3468   igvn.register_new_node_with_optimizer(landing_pad, _head);
3469   // Insert landing pad into the header
3470   _head->add_req(landing_pad);
3471 }
3472 
3473 //------------------------------split_outer_loop-------------------------------
3474 // Split out the outermost loop from this shared header.
3475 void IdealLoopTree::split_outer_loop( PhaseIdealLoop *phase ) {
3476   PhaseIterGVN &igvn = phase->_igvn;
3477 
3478   // Find index of outermost loop; it should also be my tail.
3479   uint outer_idx = 1;
3480   while( _head->in(outer_idx) != _tail ) outer_idx++;
3481 
3482   // Make a LoopNode for the outermost loop.
3483   Node *ctl = _head->in(LoopNode::EntryControl);
3484   Node *outer = new LoopNode( ctl, _head->in(outer_idx) );
3485   outer = igvn.register_new_node_with_optimizer(outer, _head);
3486   phase->set_created_loop_node();
3487 
3488   // Outermost loop falls into '_head' loop
3489   _head->set_req(LoopNode::EntryControl, outer);
3490   _head->del_req(outer_idx);
3491   // Split all the Phis up between '_head' loop and 'outer' loop.
3492   for (DUIterator_Fast jmax, j = _head->fast_outs(jmax); j < jmax; j++) {
3493     Node *out = _head->fast_out(j);
3494     if( out->is_Phi() ) {
3495       PhiNode *old_phi = out->as_Phi();
3496       assert( old_phi->region() == _head, "" );
3497       Node *phi = PhiNode::make_blank(outer, old_phi);
3498       phi->init_req(LoopNode::EntryControl,    old_phi->in(LoopNode::EntryControl));
3499       phi->init_req(LoopNode::LoopBackControl, old_phi->in(outer_idx));
3500       phi = igvn.register_new_node_with_optimizer(phi, old_phi);
3501       // Make old Phi point to new Phi on the fall-in path
3502       igvn.replace_input_of(old_phi, LoopNode::EntryControl, phi);
3503       old_phi->del_req(outer_idx);
3504     }
3505   }
3506 
3507   // Use the new loop head instead of the old shared one
3508   _head = outer;
3509   phase->set_loop(_head, this);
3510 }
3511 
3512 //------------------------------fix_parent-------------------------------------
3513 static void fix_parent( IdealLoopTree *loop, IdealLoopTree *parent ) {
3514   loop->_parent = parent;
3515   if( loop->_child ) fix_parent( loop->_child, loop   );
3516   if( loop->_next  ) fix_parent( loop->_next , parent );
3517 }
3518 
3519 //------------------------------estimate_path_freq-----------------------------
3520 static float estimate_path_freq( Node *n ) {
3521   // Try to extract some path frequency info
3522   IfNode *iff;
3523   for( int i = 0; i < 50; i++ ) { // Skip through a bunch of uncommon tests
3524     uint nop = n->Opcode();
3525     if( nop == Op_SafePoint ) {   // Skip any safepoint
3526       n = n->in(0);
3527       continue;
3528     }
3529     if( nop == Op_CatchProj ) {   // Get count from a prior call
3530       // Assume call does not always throw exceptions: means the call-site
3531       // count is also the frequency of the fall-through path.
3532       assert( n->is_CatchProj(), "" );
3533       if( ((CatchProjNode*)n)->_con != CatchProjNode::fall_through_index )
3534         return 0.0f;            // Assume call exception path is rare
3535       Node *call = n->in(0)->in(0)->in(0);
3536       assert( call->is_Call(), "expect a call here" );
3537       const JVMState *jvms = ((CallNode*)call)->jvms();
3538       ciMethodData* methodData = jvms->method()->method_data();
3539       if (!methodData->is_mature())  return 0.0f; // No call-site data
3540       ciProfileData* data = methodData->bci_to_data(jvms->bci());
3541       if ((data == nullptr) || !data->is_CounterData()) {
3542         // no call profile available, try call's control input
3543         n = n->in(0);
3544         continue;
3545       }
3546       return data->as_CounterData()->count()/FreqCountInvocations;
3547     }
3548     // See if there's a gating IF test
3549     Node *n_c = n->in(0);
3550     if( !n_c->is_If() ) break;       // No estimate available
3551     iff = n_c->as_If();
3552     if( iff->_fcnt != COUNT_UNKNOWN )   // Have a valid count?
3553       // Compute how much count comes on this path
3554       return ((nop == Op_IfTrue) ? iff->_prob : 1.0f - iff->_prob) * iff->_fcnt;
3555     // Have no count info.  Skip dull uncommon-trap like branches.
3556     if( (nop == Op_IfTrue  && iff->_prob < PROB_LIKELY_MAG(5)) ||
3557         (nop == Op_IfFalse && iff->_prob > PROB_UNLIKELY_MAG(5)) )
3558       break;
3559     // Skip through never-taken branch; look for a real loop exit.
3560     n = iff->in(0);
3561   }
3562   return 0.0f;                  // No estimate available
3563 }
3564 
3565 //------------------------------merge_many_backedges---------------------------
3566 // Merge all the backedges from the shared header into a private Region.
3567 // Feed that region as the one backedge to this loop.
3568 void IdealLoopTree::merge_many_backedges( PhaseIdealLoop *phase ) {
3569   uint i;
3570 
3571   // Scan for the top 2 hottest backedges
3572   float hotcnt = 0.0f;
3573   float warmcnt = 0.0f;
3574   uint hot_idx = 0;
3575   // Loop starts at 2 because slot 1 is the fall-in path
3576   for( i = 2; i < _head->req(); i++ ) {
3577     float cnt = estimate_path_freq(_head->in(i));
3578     if( cnt > hotcnt ) {       // Grab hottest path
3579       warmcnt = hotcnt;
3580       hotcnt = cnt;
3581       hot_idx = i;
3582     } else if( cnt > warmcnt ) { // And 2nd hottest path
3583       warmcnt = cnt;
3584     }
3585   }
3586 
3587   // See if the hottest backedge is worthy of being an inner loop
3588   // by being much hotter than the next hottest backedge.
3589   if( hotcnt <= 0.0001 ||
3590       hotcnt < 2.0*warmcnt ) hot_idx = 0;// No hot backedge
3591 
3592   // Peel out the backedges into a private merge point; peel
3593   // them all except optionally hot_idx.
3594   PhaseIterGVN &igvn = phase->_igvn;
3595 
3596   Node *hot_tail = nullptr;
3597   // Make a Region for the merge point
3598   Node *r = new RegionNode(1);
3599   for( i = 2; i < _head->req(); i++ ) {
3600     if( i != hot_idx )
3601       r->add_req( _head->in(i) );
3602     else hot_tail = _head->in(i);
3603   }
3604   igvn.register_new_node_with_optimizer(r, _head);
3605   // Plug region into end of loop _head, followed by hot_tail
3606   while( _head->req() > 3 ) _head->del_req( _head->req()-1 );
3607   igvn.replace_input_of(_head, 2, r);
3608   if( hot_idx ) _head->add_req(hot_tail);
3609 
3610   // Split all the Phis up between '_head' loop and the Region 'r'
3611   for (DUIterator_Fast jmax, j = _head->fast_outs(jmax); j < jmax; j++) {
3612     Node *out = _head->fast_out(j);
3613     if( out->is_Phi() ) {
3614       PhiNode* n = out->as_Phi();
3615       igvn.hash_delete(n);      // Delete from hash before hacking edges
3616       Node *hot_phi = nullptr;
3617       Node *phi = new PhiNode(r, n->type(), n->adr_type());
3618       // Check all inputs for the ones to peel out
3619       uint j = 1;
3620       for( uint i = 2; i < n->req(); i++ ) {
3621         if( i != hot_idx )
3622           phi->set_req( j++, n->in(i) );
3623         else hot_phi = n->in(i);
3624       }
3625       // Register the phi but do not transform until whole place transforms
3626       igvn.register_new_node_with_optimizer(phi, n);
3627       // Add the merge phi to the old Phi
3628       while( n->req() > 3 ) n->del_req( n->req()-1 );
3629       igvn.replace_input_of(n, 2, phi);
3630       if( hot_idx ) n->add_req(hot_phi);
3631     }
3632   }
3633 
3634 
3635   // Insert a new IdealLoopTree inserted below me.  Turn it into a clone
3636   // of self loop tree.  Turn self into a loop headed by _head and with
3637   // tail being the new merge point.
3638   IdealLoopTree *ilt = new IdealLoopTree( phase, _head, _tail );
3639   phase->set_loop(_tail,ilt);   // Adjust tail
3640   _tail = r;                    // Self's tail is new merge point
3641   phase->set_loop(r,this);
3642   ilt->_child = _child;         // New guy has my children
3643   _child = ilt;                 // Self has new guy as only child
3644   ilt->_parent = this;          // new guy has self for parent
3645   ilt->_nest = _nest;           // Same nesting depth (for now)
3646 
3647   // Starting with 'ilt', look for child loop trees using the same shared
3648   // header.  Flatten these out; they will no longer be loops in the end.
3649   IdealLoopTree **pilt = &_child;
3650   while( ilt ) {
3651     if( ilt->_head == _head ) {
3652       uint i;
3653       for( i = 2; i < _head->req(); i++ )
3654         if( _head->in(i) == ilt->_tail )
3655           break;                // Still a loop
3656       if( i == _head->req() ) { // No longer a loop
3657         // Flatten ilt.  Hang ilt's "_next" list from the end of
3658         // ilt's '_child' list.  Move the ilt's _child up to replace ilt.
3659         IdealLoopTree **cp = &ilt->_child;
3660         while( *cp ) cp = &(*cp)->_next;   // Find end of child list
3661         *cp = ilt->_next;       // Hang next list at end of child list
3662         *pilt = ilt->_child;    // Move child up to replace ilt
3663         ilt->_head = nullptr;   // Flag as a loop UNIONED into parent
3664         ilt = ilt->_child;      // Repeat using new ilt
3665         continue;               // do not advance over ilt->_child
3666       }
3667       assert( ilt->_tail == hot_tail, "expected to only find the hot inner loop here" );
3668       phase->set_loop(_head,ilt);
3669     }
3670     pilt = &ilt->_child;        // Advance to next
3671     ilt = *pilt;
3672   }
3673 
3674   if( _child ) fix_parent( _child, this );
3675 }
3676 
3677 //------------------------------beautify_loops---------------------------------
3678 // Split shared headers and insert loop landing pads.
3679 // Insert a LoopNode to replace the RegionNode.
3680 // Return TRUE if loop tree is structurally changed.
3681 bool IdealLoopTree::beautify_loops( PhaseIdealLoop *phase ) {
3682   bool result = false;
3683   // Cache parts in locals for easy
3684   PhaseIterGVN &igvn = phase->_igvn;
3685 
3686   igvn.hash_delete(_head);      // Yank from hash before hacking edges
3687 
3688   // Check for multiple fall-in paths.  Peel off a landing pad if need be.
3689   int fall_in_cnt = 0;
3690   for( uint i = 1; i < _head->req(); i++ )
3691     if( !phase->is_member( this, _head->in(i) ) )
3692       fall_in_cnt++;
3693   assert( fall_in_cnt, "at least 1 fall-in path" );
3694   if( fall_in_cnt > 1 )         // Need a loop landing pad to merge fall-ins
3695     split_fall_in( phase, fall_in_cnt );
3696 
3697   // Swap inputs to the _head and all Phis to move the fall-in edge to
3698   // the left.
3699   fall_in_cnt = 1;
3700   while( phase->is_member( this, _head->in(fall_in_cnt) ) )
3701     fall_in_cnt++;
3702   if( fall_in_cnt > 1 ) {
3703     // Since I am just swapping inputs I do not need to update def-use info
3704     Node *tmp = _head->in(1);
3705     igvn.rehash_node_delayed(_head);
3706     _head->set_req( 1, _head->in(fall_in_cnt) );
3707     _head->set_req( fall_in_cnt, tmp );
3708     // Swap also all Phis
3709     for (DUIterator_Fast imax, i = _head->fast_outs(imax); i < imax; i++) {
3710       Node* phi = _head->fast_out(i);
3711       if( phi->is_Phi() ) {
3712         igvn.rehash_node_delayed(phi); // Yank from hash before hacking edges
3713         tmp = phi->in(1);
3714         phi->set_req( 1, phi->in(fall_in_cnt) );
3715         phi->set_req( fall_in_cnt, tmp );
3716       }
3717     }
3718   }
3719   assert( !phase->is_member( this, _head->in(1) ), "left edge is fall-in" );
3720   assert(  phase->is_member( this, _head->in(2) ), "right edge is loop" );
3721 
3722   // If I am a shared header (multiple backedges), peel off the many
3723   // backedges into a private merge point and use the merge point as
3724   // the one true backedge.
3725   if (_head->req() > 3) {
3726     // Merge the many backedges into a single backedge but leave
3727     // the hottest backedge as separate edge for the following peel.
3728     if (!_irreducible) {
3729       merge_many_backedges( phase );
3730     }
3731 
3732     // When recursively beautify my children, split_fall_in can change
3733     // loop tree structure when I am an irreducible loop. Then the head
3734     // of my children has a req() not bigger than 3. Here we need to set
3735     // result to true to catch that case in order to tell the caller to
3736     // rebuild loop tree. See issue JDK-8244407 for details.
3737     result = true;
3738   }
3739 
3740   // If I have one hot backedge, peel off myself loop.
3741   // I better be the outermost loop.
3742   if (_head->req() > 3 && !_irreducible) {
3743     split_outer_loop( phase );
3744     result = true;
3745 
3746   } else if (!_head->is_Loop() && !_irreducible) {
3747     // Make a new LoopNode to replace the old loop head
3748     Node *l = new LoopNode( _head->in(1), _head->in(2) );
3749     l = igvn.register_new_node_with_optimizer(l, _head);
3750     phase->set_created_loop_node();
3751     // Go ahead and replace _head
3752     phase->_igvn.replace_node( _head, l );
3753     _head = l;
3754     phase->set_loop(_head, this);
3755   }
3756 
3757   // Now recursively beautify nested loops
3758   if( _child ) result |= _child->beautify_loops( phase );
3759   if( _next  ) result |= _next ->beautify_loops( phase );
3760   return result;
3761 }
3762 
3763 //------------------------------allpaths_check_safepts----------------------------
3764 // Allpaths backwards scan. Starting at the head, traversing all backedges, and the body. Terminating each path at first
3765 // safepoint encountered.  Helper for check_safepts.
3766 void IdealLoopTree::allpaths_check_safepts(VectorSet &visited, Node_List &stack) {
3767   assert(stack.size() == 0, "empty stack");
3768   stack.push(_head);
3769   visited.clear();
3770   visited.set(_head->_idx);
3771   while (stack.size() > 0) {
3772     Node* n = stack.pop();
3773     if (n->is_Call() && n->as_Call()->guaranteed_safepoint()) {
3774       // Terminate this path
3775     } else if (n->Opcode() == Op_SafePoint) {
3776       if (_phase->get_loop(n) != this) {
3777         if (_required_safept == nullptr) _required_safept = new Node_List();
3778         // save the first we run into on that path: closest to the tail if the head has a single backedge
3779         _required_safept->push(n);
3780       }
3781       // Terminate this path
3782     } else {
3783       uint start = n->is_Region() ? 1 : 0;
3784       uint end   = n->is_Region() && (!n->is_Loop() || n == _head) ? n->req() : start + 1;
3785       for (uint i = start; i < end; i++) {
3786         Node* in = n->in(i);
3787         assert(in->is_CFG(), "must be");
3788         if (!visited.test_set(in->_idx) && is_member(_phase->get_loop(in))) {
3789           stack.push(in);
3790         }
3791       }
3792     }
3793   }
3794 }
3795 
3796 //------------------------------check_safepts----------------------------
3797 // Given dominators, try to find loops with calls that must always be
3798 // executed (call dominates loop tail).  These loops do not need non-call
3799 // safepoints (ncsfpt).
3800 //
3801 // A complication is that a safepoint in a inner loop may be needed
3802 // by an outer loop. In the following, the inner loop sees it has a
3803 // call (block 3) on every path from the head (block 2) to the
3804 // backedge (arc 3->2).  So it deletes the ncsfpt (non-call safepoint)
3805 // in block 2, _but_ this leaves the outer loop without a safepoint.
3806 //
3807 //          entry  0
3808 //                 |
3809 //                 v
3810 // outer 1,2    +->1
3811 //              |  |
3812 //              |  v
3813 //              |  2<---+  ncsfpt in 2
3814 //              |_/|\   |
3815 //                 | v  |
3816 // inner 2,3      /  3  |  call in 3
3817 //               /   |  |
3818 //              v    +--+
3819 //        exit  4
3820 //
3821 //
3822 // This method creates a list (_required_safept) of ncsfpt nodes that must
3823 // be protected is created for each loop. When a ncsfpt maybe deleted, it
3824 // is first looked for in the lists for the outer loops of the current loop.
3825 //
3826 // The insights into the problem:
3827 //  A) counted loops are okay
3828 //  B) innermost loops are okay (only an inner loop can delete
3829 //     a ncsfpt needed by an outer loop)
3830 //  C) a loop is immune from an inner loop deleting a safepoint
3831 //     if the loop has a call on the idom-path
3832 //  D) a loop is also immune if it has a ncsfpt (non-call safepoint) on the
3833 //     idom-path that is not in a nested loop
3834 //  E) otherwise, an ncsfpt on the idom-path that is nested in an inner
3835 //     loop needs to be prevented from deletion by an inner loop
3836 //
3837 // There are two analyses:
3838 //  1) The first, and cheaper one, scans the loop body from
3839 //     tail to head following the idom (immediate dominator)
3840 //     chain, looking for the cases (C,D,E) above.
3841 //     Since inner loops are scanned before outer loops, there is summary
3842 //     information about inner loops.  Inner loops can be skipped over
3843 //     when the tail of an inner loop is encountered.
3844 //
3845 //  2) The second, invoked if the first fails to find a call or ncsfpt on
3846 //     the idom path (which is rare), scans all predecessor control paths
3847 //     from the tail to the head, terminating a path when a call or sfpt
3848 //     is encountered, to find the ncsfpt's that are closest to the tail.
3849 //
3850 void IdealLoopTree::check_safepts(VectorSet &visited, Node_List &stack) {
3851   // Bottom up traversal
3852   IdealLoopTree* ch = _child;
3853   if (_child) _child->check_safepts(visited, stack);
3854   if (_next)  _next ->check_safepts(visited, stack);
3855 
3856   if (!_head->is_CountedLoop() && !_has_sfpt && _parent != nullptr) {
3857     bool  has_call         = false;    // call on dom-path
3858     bool  has_local_ncsfpt = false;    // ncsfpt on dom-path at this loop depth
3859     Node* nonlocal_ncsfpt  = nullptr;  // ncsfpt on dom-path at a deeper depth
3860     if (!_irreducible) {
3861       // Scan the dom-path nodes from tail to head
3862       for (Node* n = tail(); n != _head; n = _phase->idom(n)) {
3863         if (n->is_Call() && n->as_Call()->guaranteed_safepoint()) {
3864           has_call = true;
3865           _has_sfpt = 1;          // Then no need for a safept!
3866           break;
3867         } else if (n->Opcode() == Op_SafePoint) {
3868           if (_phase->get_loop(n) == this) {
3869             has_local_ncsfpt = true;
3870             break;
3871           }
3872           if (nonlocal_ncsfpt == nullptr) {
3873             nonlocal_ncsfpt = n; // save the one closest to the tail
3874           }
3875         } else {
3876           IdealLoopTree* nlpt = _phase->get_loop(n);
3877           if (this != nlpt) {
3878             // If at an inner loop tail, see if the inner loop has already
3879             // recorded seeing a call on the dom-path (and stop.)  If not,
3880             // jump to the head of the inner loop.
3881             assert(is_member(nlpt), "nested loop");
3882             Node* tail = nlpt->_tail;
3883             if (tail->in(0)->is_If()) tail = tail->in(0);
3884             if (n == tail) {
3885               // If inner loop has call on dom-path, so does outer loop
3886               if (nlpt->_has_sfpt) {
3887                 has_call = true;
3888                 _has_sfpt = 1;
3889                 break;
3890               }
3891               // Skip to head of inner loop
3892               assert(_phase->is_dominator(_head, nlpt->_head), "inner head dominated by outer head");
3893               n = nlpt->_head;
3894               if (_head == n) {
3895                 // this and nlpt (inner loop) have the same loop head. This should not happen because
3896                 // during beautify_loops we call merge_many_backedges. However, infinite loops may not
3897                 // have been attached to the loop-tree during build_loop_tree before beautify_loops,
3898                 // but then attached in the build_loop_tree afterwards, and so still have unmerged
3899                 // backedges. Check if we are indeed in an infinite subgraph, and terminate the scan,
3900                 // since we have reached the loop head of this.
3901                 assert(_head->as_Region()->is_in_infinite_subgraph(),
3902                        "only expect unmerged backedges in infinite loops");
3903                 break;
3904               }
3905             }
3906           }
3907         }
3908       }
3909     }
3910     // Record safept's that this loop needs preserved when an
3911     // inner loop attempts to delete it's safepoints.
3912     if (_child != nullptr && !has_call && !has_local_ncsfpt) {
3913       if (nonlocal_ncsfpt != nullptr) {
3914         if (_required_safept == nullptr) _required_safept = new Node_List();
3915         _required_safept->push(nonlocal_ncsfpt);
3916       } else {
3917         // Failed to find a suitable safept on the dom-path.  Now use
3918         // an all paths walk from tail to head, looking for safepoints to preserve.
3919         allpaths_check_safepts(visited, stack);
3920       }
3921     }
3922   }
3923 }
3924 
3925 //---------------------------is_deleteable_safept----------------------------
3926 // Is safept not required by an outer loop?
3927 bool PhaseIdealLoop::is_deleteable_safept(Node* sfpt) {
3928   assert(sfpt->Opcode() == Op_SafePoint, "");
3929   IdealLoopTree* lp = get_loop(sfpt)->_parent;
3930   while (lp != nullptr) {
3931     Node_List* sfpts = lp->_required_safept;
3932     if (sfpts != nullptr) {
3933       for (uint i = 0; i < sfpts->size(); i++) {
3934         if (sfpt == sfpts->at(i))
3935           return false;
3936       }
3937     }
3938     lp = lp->_parent;
3939   }
3940   return true;
3941 }
3942 
3943 //---------------------------replace_parallel_iv-------------------------------
3944 // Replace parallel induction variable (parallel to trip counter)
3945 // This optimization looks for patterns similar to:
3946 //
3947 //    int a = init2;
3948 //    for (int iv = init; iv < limit; iv += stride_con) {
3949 //      a += stride_con2;
3950 //    }
3951 //
3952 // and transforms it to:
3953 //
3954 //    int iv2 = init2
3955 //    int iv = init
3956 //    loop:
3957 //      if (iv >= limit) goto exit
3958 //      iv += stride_con
3959 //      iv2 = init2 + (iv - init) * (stride_con2 / stride_con)
3960 //      goto loop
3961 //    exit:
3962 //    ...
3963 //
3964 // Such transformation introduces more optimization opportunities. In this
3965 // particular example, the loop can be eliminated entirely given that
3966 // `stride_con2 / stride_con` is exact  (i.e., no remainder). Checks are in
3967 // place to only perform this optimization if such a division is exact. This
3968 // example will be transformed into its semantic equivalence:
3969 //
3970 //     int iv2 = (iv * stride_con2 / stride_con) + (init2 - (init * stride_con2 / stride_con))
3971 //
3972 // which corresponds to the structure of transformed subgraph.
3973 //
3974 // However, if there is a mismatch between types of the loop and the parallel
3975 // induction variable (e.g., a long-typed IV in an int-typed loop), type
3976 // conversions are required:
3977 //
3978 //     long iv2 = ((long) iv * stride_con2 / stride_con) + (init2 - ((long) init * stride_con2 / stride_con))
3979 //
3980 void PhaseIdealLoop::replace_parallel_iv(IdealLoopTree *loop) {
3981   assert(loop->_head->is_CountedLoop(), "");
3982   CountedLoopNode *cl = loop->_head->as_CountedLoop();
3983   if (!cl->is_valid_counted_loop(T_INT)) {
3984     return;         // skip malformed counted loop
3985   }
3986   Node *incr = cl->incr();
3987   if (incr == nullptr) {
3988     return;         // Dead loop?
3989   }
3990   Node *init = cl->init_trip();
3991   Node *phi  = cl->phi();
3992   jlong stride_con = cl->stride_con();
3993 
3994   // Visit all children, looking for Phis
3995   for (DUIterator i = cl->outs(); cl->has_out(i); i++) {
3996     Node *out = cl->out(i);
3997     // Look for other phis (secondary IVs). Skip dead ones
3998     if (!out->is_Phi() || out == phi || !has_node(out)) {
3999       continue;
4000     }
4001 
4002     PhiNode* phi2 = out->as_Phi();
4003     Node* incr2 = phi2->in(LoopNode::LoopBackControl);
4004     // Look for induction variables of the form:  X += constant
4005     if (phi2->region() != loop->_head ||
4006         incr2->req() != 3 ||
4007         incr2->in(1)->uncast() != phi2 ||
4008         incr2 == incr ||
4009         (incr2->Opcode() != Op_AddI && incr2->Opcode() != Op_AddL) ||
4010         !incr2->in(2)->is_Con()) {
4011       continue;
4012     }
4013 
4014     if (incr2->in(1)->is_ConstraintCast() &&
4015         !(incr2->in(1)->in(0)->is_IfProj() && incr2->in(1)->in(0)->in(0)->is_RangeCheck())) {
4016       // Skip AddI->CastII->Phi case if CastII is not controlled by local RangeCheck
4017       continue;
4018     }
4019     // Check for parallel induction variable (parallel to trip counter)
4020     // via an affine function.  In particular, count-down loops with
4021     // count-up array indices are common. We only RCE references off
4022     // the trip-counter, so we need to convert all these to trip-counter
4023     // expressions.
4024     Node* init2 = phi2->in(LoopNode::EntryControl);
4025 
4026     // Determine the basic type of the stride constant (and the iv being incremented).
4027     BasicType stride_con2_bt = incr2->Opcode() == Op_AddI ? T_INT : T_LONG;
4028     jlong stride_con2 = incr2->in(2)->get_integer_as_long(stride_con2_bt);
4029 
4030     // The ratio of the two strides cannot be represented as an int
4031     // if stride_con2 is min_jint (or min_jlong, respectively) and
4032     // stride_con is -1.
4033     if (stride_con2 == min_signed_integer(stride_con2_bt) && stride_con == -1) {
4034       continue;
4035     }
4036 
4037     // The general case here gets a little tricky.  We want to find the
4038     // GCD of all possible parallel IV's and make a new IV using this
4039     // GCD for the loop.  Then all possible IVs are simple multiples of
4040     // the GCD.  In practice, this will cover very few extra loops.
4041     // Instead we require 'stride_con2' to be a multiple of 'stride_con',
4042     // where +/-1 is the common case, but other integer multiples are
4043     // also easy to handle.
4044     jlong ratio_con = stride_con2 / stride_con;
4045 
4046     if ((ratio_con * stride_con) != stride_con2) { // Check for exact (no remainder)
4047         continue;
4048     }
4049 
4050 #ifndef PRODUCT
4051     if (TraceLoopOpts) {
4052       tty->print("Parallel IV: %d ", phi2->_idx);
4053       loop->dump_head();
4054     }
4055 #endif
4056 
4057     // Convert to using the trip counter.  The parallel induction
4058     // variable differs from the trip counter by a loop-invariant
4059     // amount, the difference between their respective initial values.
4060     // It is scaled by the 'ratio_con'.
4061     Node* ratio = integercon(ratio_con, stride_con2_bt);
4062 
4063     Node* init_converted = insert_convert_node_if_needed(stride_con2_bt, init);
4064     Node* phi_converted = insert_convert_node_if_needed(stride_con2_bt, phi);
4065 
4066     Node* ratio_init = MulNode::make(init_converted, ratio, stride_con2_bt);
4067     _igvn.register_new_node_with_optimizer(ratio_init, init_converted);
4068     set_early_ctrl(ratio_init, false);
4069 
4070     Node* diff = SubNode::make(init2, ratio_init, stride_con2_bt);
4071     _igvn.register_new_node_with_optimizer(diff, init2);
4072     set_early_ctrl(diff, false);
4073 
4074     Node* ratio_idx = MulNode::make(phi_converted, ratio, stride_con2_bt);
4075     _igvn.register_new_node_with_optimizer(ratio_idx, phi_converted);
4076     set_ctrl(ratio_idx, cl);
4077 
4078     Node* add = AddNode::make(ratio_idx, diff, stride_con2_bt);
4079     _igvn.register_new_node_with_optimizer(add);
4080     set_ctrl(add, cl);
4081 
4082     _igvn.replace_node( phi2, add );
4083     // Sometimes an induction variable is unused
4084     if (add->outcnt() == 0) {
4085       _igvn.remove_dead_node(add);
4086     }
4087     --i; // deleted this phi; rescan starting with next position
4088   }
4089 }
4090 
4091 Node* PhaseIdealLoop::insert_convert_node_if_needed(BasicType target, Node* input) {
4092   BasicType source = _igvn.type(input)->basic_type();
4093   if (source == target) {
4094     return input;
4095   }
4096 
4097   Node* converted = ConvertNode::create_convert(source, target, input);
4098   _igvn.register_new_node_with_optimizer(converted, input);
4099   set_early_ctrl(converted, false);
4100 
4101   return converted;
4102 }
4103 
4104 void IdealLoopTree::remove_safepoints(PhaseIdealLoop* phase, bool keep_one) {
4105   Node* keep = nullptr;
4106   if (keep_one) {
4107     // Look for a safepoint on the idom-path.
4108     for (Node* i = tail(); i != _head; i = phase->idom(i)) {
4109       if (i->Opcode() == Op_SafePoint && phase->get_loop(i) == this) {
4110         keep = i;
4111         break; // Found one
4112       }
4113     }
4114   }
4115 
4116   // Don't remove any safepoints if it is requested to keep a single safepoint and
4117   // no safepoint was found on idom-path. It is not safe to remove any safepoint
4118   // in this case since there's no safepoint dominating all paths in the loop body.
4119   bool prune = !keep_one || keep != nullptr;
4120 
4121   // Delete other safepoints in this loop.
4122   Node_List* sfpts = _safepts;
4123   if (prune && sfpts != nullptr) {
4124     assert(keep == nullptr || keep->Opcode() == Op_SafePoint, "not safepoint");
4125     for (uint i = 0; i < sfpts->size(); i++) {
4126       Node* n = sfpts->at(i);
4127       assert(phase->get_loop(n) == this, "");
4128       if (n != keep && phase->is_deleteable_safept(n)) {
4129         phase->lazy_replace(n, n->in(TypeFunc::Control));
4130       }
4131     }
4132   }
4133 }
4134 
4135 //------------------------------counted_loop-----------------------------------
4136 // Convert to counted loops where possible
4137 void IdealLoopTree::counted_loop( PhaseIdealLoop *phase ) {
4138 
4139   // For grins, set the inner-loop flag here
4140   if (!_child) {
4141     if (_head->is_Loop()) _head->as_Loop()->set_inner_loop();
4142   }
4143 
4144   IdealLoopTree* loop = this;
4145   if (_head->is_CountedLoop() ||
4146       phase->is_counted_loop(_head, loop, T_INT)) {
4147 
4148     if (LoopStripMiningIter == 0 || _head->as_CountedLoop()->is_strip_mined()) {
4149       // Indicate we do not need a safepoint here
4150       _has_sfpt = 1;
4151     }
4152 
4153     // Remove safepoints
4154     bool keep_one_sfpt = !(_has_call || _has_sfpt);
4155     remove_safepoints(phase, keep_one_sfpt);
4156 
4157     // Look for induction variables
4158     phase->replace_parallel_iv(this);
4159   } else if (_head->is_LongCountedLoop() ||
4160              phase->is_counted_loop(_head, loop, T_LONG)) {
4161     remove_safepoints(phase, true);
4162   } else {
4163     assert(!_head->is_Loop() || !_head->as_Loop()->is_loop_nest_inner_loop(), "transformation to counted loop should not fail");
4164     if (_parent != nullptr && !_irreducible) {
4165       // Not a counted loop. Keep one safepoint.
4166       bool keep_one_sfpt = true;
4167       remove_safepoints(phase, keep_one_sfpt);
4168     }
4169   }
4170 
4171   // Recursively
4172   assert(loop->_child != this || (loop->_head->as_Loop()->is_OuterStripMinedLoop() && _head->as_CountedLoop()->is_strip_mined()), "what kind of loop was added?");
4173   assert(loop->_child != this || (loop->_child->_child == nullptr && loop->_child->_next == nullptr), "would miss some loops");
4174   if (loop->_child && loop->_child != this) loop->_child->counted_loop(phase);
4175   if (loop->_next)  loop->_next ->counted_loop(phase);
4176 }
4177 
4178 
4179 // The Estimated Loop Clone Size:
4180 //   CloneFactor * (~112% * BodySize + BC) + CC + FanOutTerm,
4181 // where  BC and  CC are  totally ad-hoc/magic  "body" and "clone" constants,
4182 // respectively, used to ensure that the node usage estimates made are on the
4183 // safe side, for the most part. The FanOutTerm is an attempt to estimate the
4184 // possible additional/excessive nodes generated due to data and control flow
4185 // merging, for edges reaching outside the loop.
4186 uint IdealLoopTree::est_loop_clone_sz(uint factor) const {
4187 
4188   precond(0 < factor && factor < 16);
4189 
4190   uint const bc = 13;
4191   uint const cc = 17;
4192   uint const sz = _body.size() + (_body.size() + 7) / 2;
4193   uint estimate = factor * (sz + bc) + cc;
4194 
4195   assert((estimate - cc) / factor == sz + bc, "overflow");
4196 
4197   return estimate + est_loop_flow_merge_sz();
4198 }
4199 
4200 // The Estimated Loop (full-) Unroll Size:
4201 //   UnrollFactor * (~106% * BodySize) + CC + FanOutTerm,
4202 // where CC is a (totally) ad-hoc/magic "clone" constant, used to ensure that
4203 // node usage estimates made are on the safe side, for the most part. This is
4204 // a "light" version of the loop clone size calculation (above), based on the
4205 // assumption that most of the loop-construct overhead will be unraveled when
4206 // (fully) unrolled. Defined for unroll factors larger or equal to one (>=1),
4207 // including an overflow check and returning UINT_MAX in case of an overflow.
4208 uint IdealLoopTree::est_loop_unroll_sz(uint factor) const {
4209 
4210   precond(factor > 0);
4211 
4212   // Take into account that after unroll conjoined heads and tails will fold.
4213   uint const b0 = _body.size() - EMPTY_LOOP_SIZE;
4214   uint const cc = 7;
4215   uint const sz = b0 + (b0 + 15) / 16;
4216   uint estimate = factor * sz + cc;
4217 
4218   if ((estimate - cc) / factor != sz) {
4219     return UINT_MAX;
4220   }
4221 
4222   return estimate + est_loop_flow_merge_sz();
4223 }
4224 
4225 // Estimate the growth effect (in nodes) of merging control and data flow when
4226 // cloning a loop body, based on the amount of  control and data flow reaching
4227 // outside of the (current) loop body.
4228 uint IdealLoopTree::est_loop_flow_merge_sz() const {
4229 
4230   uint ctrl_edge_out_cnt = 0;
4231   uint data_edge_out_cnt = 0;
4232 
4233   for (uint i = 0; i < _body.size(); i++) {
4234     Node* node = _body.at(i);
4235     uint outcnt = node->outcnt();
4236 
4237     for (uint k = 0; k < outcnt; k++) {
4238       Node* out = node->raw_out(k);
4239       if (out == nullptr) continue;
4240       if (out->is_CFG()) {
4241         if (!is_member(_phase->get_loop(out))) {
4242           ctrl_edge_out_cnt++;
4243         }
4244       } else if (_phase->has_ctrl(out)) {
4245         Node* ctrl = _phase->get_ctrl(out);
4246         assert(ctrl != nullptr, "must be");
4247         assert(ctrl->is_CFG(), "must be");
4248         if (!is_member(_phase->get_loop(ctrl))) {
4249           data_edge_out_cnt++;
4250         }
4251       }
4252     }
4253   }
4254   // Use data and control count (x2.0) in estimate iff both are > 0. This is
4255   // a rather pessimistic estimate for the most part, in particular for some
4256   // complex loops, but still not enough to capture all loops.
4257   if (ctrl_edge_out_cnt > 0 && data_edge_out_cnt > 0) {
4258     return 2 * (ctrl_edge_out_cnt + data_edge_out_cnt);
4259   }
4260   return 0;
4261 }
4262 
4263 #ifndef PRODUCT
4264 //------------------------------dump_head--------------------------------------
4265 // Dump 1 liner for loop header info
4266 void IdealLoopTree::dump_head() {
4267   tty->sp(2 * _nest);
4268   tty->print("Loop: N%d/N%d ", _head->_idx, _tail->_idx);
4269   if (_irreducible) tty->print(" IRREDUCIBLE");
4270   Node* entry = _head->is_Loop() ? _head->as_Loop()->skip_strip_mined(-1)->in(LoopNode::EntryControl)
4271                                  : _head->in(LoopNode::EntryControl);
4272   const Predicates predicates(entry);
4273   if (predicates.loop_limit_check_predicate_block()->is_non_empty()) {
4274     tty->print(" limit_check");
4275   }
4276   if (UseProfiledLoopPredicate && predicates.profiled_loop_predicate_block()->is_non_empty()) {
4277     tty->print(" profile_predicated");
4278   }
4279   if (UseLoopPredicate && predicates.loop_predicate_block()->is_non_empty()) {
4280     tty->print(" predicated");
4281   }
4282   if (_head->is_CountedLoop()) {
4283     CountedLoopNode *cl = _head->as_CountedLoop();
4284     tty->print(" counted");
4285 
4286     Node* init_n = cl->init_trip();
4287     if (init_n  != nullptr &&  init_n->is_Con())
4288       tty->print(" [%d,", cl->init_trip()->get_int());
4289     else
4290       tty->print(" [int,");
4291     Node* limit_n = cl->limit();
4292     if (limit_n  != nullptr &&  limit_n->is_Con())
4293       tty->print("%d),", cl->limit()->get_int());
4294     else
4295       tty->print("int),");
4296     int stride_con  = cl->stride_con();
4297     if (stride_con > 0) tty->print("+");
4298     tty->print("%d", stride_con);
4299 
4300     tty->print(" (%0.f iters) ", cl->profile_trip_cnt());
4301 
4302     if (cl->is_pre_loop ()) tty->print(" pre" );
4303     if (cl->is_main_loop()) tty->print(" main");
4304     if (cl->is_post_loop()) tty->print(" post");
4305     if (cl->is_vectorized_loop()) tty->print(" vector");
4306     if (range_checks_present()) tty->print(" rc ");
4307   }
4308   if (_has_call) tty->print(" has_call");
4309   if (_has_sfpt) tty->print(" has_sfpt");
4310   if (_rce_candidate) tty->print(" rce");
4311   if (_safepts != nullptr && _safepts->size() > 0) {
4312     tty->print(" sfpts={"); _safepts->dump_simple(); tty->print(" }");
4313   }
4314   if (_required_safept != nullptr && _required_safept->size() > 0) {
4315     tty->print(" req={"); _required_safept->dump_simple(); tty->print(" }");
4316   }
4317   if (Verbose) {
4318     tty->print(" body={"); _body.dump_simple(); tty->print(" }");
4319   }
4320   if (_head->is_Loop() && _head->as_Loop()->is_strip_mined()) {
4321     tty->print(" strip_mined");
4322   }
4323   tty->cr();
4324 }
4325 
4326 //------------------------------dump-------------------------------------------
4327 // Dump loops by loop tree
4328 void IdealLoopTree::dump() {
4329   dump_head();
4330   if (_child) _child->dump();
4331   if (_next)  _next ->dump();
4332 }
4333 
4334 #endif
4335 
4336 static void log_loop_tree_helper(IdealLoopTree* root, IdealLoopTree* loop, CompileLog* log) {
4337   if (loop == root) {
4338     if (loop->_child != nullptr) {
4339       log->begin_head("loop_tree");
4340       log->end_head();
4341       log_loop_tree_helper(root, loop->_child, log);
4342       log->tail("loop_tree");
4343       assert(loop->_next == nullptr, "what?");
4344     }
4345   } else if (loop != nullptr) {
4346     Node* head = loop->_head;
4347     log->begin_head("loop");
4348     log->print(" idx='%d' ", head->_idx);
4349     if (loop->_irreducible) log->print("irreducible='1' ");
4350     if (head->is_Loop()) {
4351       if (head->as_Loop()->is_inner_loop())        log->print("inner_loop='1' ");
4352       if (head->as_Loop()->is_partial_peel_loop()) log->print("partial_peel_loop='1' ");
4353     } else if (head->is_CountedLoop()) {
4354       CountedLoopNode* cl = head->as_CountedLoop();
4355       if (cl->is_pre_loop())  log->print("pre_loop='%d' ",  cl->main_idx());
4356       if (cl->is_main_loop()) log->print("main_loop='%d' ", cl->_idx);
4357       if (cl->is_post_loop()) log->print("post_loop='%d' ", cl->main_idx());
4358     }
4359     log->end_head();
4360     log_loop_tree_helper(root, loop->_child, log);
4361     log->tail("loop");
4362     log_loop_tree_helper(root, loop->_next, log);
4363   }
4364 }
4365 
4366 void PhaseIdealLoop::log_loop_tree() {
4367   if (C->log() != nullptr) {
4368     log_loop_tree_helper(_ltree_root, _ltree_root, C->log());
4369   }
4370 }
4371 
4372 // Eliminate all Parse and Template Assertion Predicates that are not associated with a loop anymore. The eliminated
4373 // predicates will be removed during the next round of IGVN.
4374 void PhaseIdealLoop::eliminate_useless_predicates() {
4375   if (C->parse_predicate_count() == 0 && C->template_assertion_predicate_count() == 0) {
4376     return; // No predicates left.
4377   }
4378 
4379   eliminate_useless_parse_predicates();
4380   eliminate_useless_template_assertion_predicates();
4381 }
4382 
4383 // Eliminate all Parse Predicates that do not belong to a loop anymore by marking them useless. These will be removed
4384 // during the next round of IGVN.
4385 void PhaseIdealLoop::eliminate_useless_parse_predicates() {
4386   mark_all_parse_predicates_useless();
4387   if (C->has_loops()) {
4388     mark_loop_associated_parse_predicates_useful();
4389   }
4390   add_useless_parse_predicates_to_igvn_worklist();
4391 }
4392 
4393 void PhaseIdealLoop::mark_all_parse_predicates_useless() const {
4394   for (int i = 0; i < C->parse_predicate_count(); i++) {
4395     C->parse_predicate(i)->mark_useless();
4396   }
4397 }
4398 
4399 void PhaseIdealLoop::mark_loop_associated_parse_predicates_useful() {
4400   for (LoopTreeIterator iterator(_ltree_root); !iterator.done(); iterator.next()) {
4401     IdealLoopTree* loop = iterator.current();
4402     if (loop->can_apply_loop_predication()) {
4403       mark_useful_parse_predicates_for_loop(loop);
4404     }
4405   }
4406 }
4407 
4408 // This visitor marks all visited Parse Predicates useful.
4409 class ParsePredicateUsefulMarker : public PredicateVisitor {
4410  public:
4411   using PredicateVisitor::visit;
4412 
4413   void visit(const ParsePredicate& parse_predicate) override {
4414     parse_predicate.head()->mark_useful();
4415   }
4416 };
4417 
4418 void PhaseIdealLoop::mark_useful_parse_predicates_for_loop(IdealLoopTree* loop) {
4419   Node* entry = loop->_head->as_Loop()->skip_strip_mined()->in(LoopNode::EntryControl);
4420   const PredicateIterator predicate_iterator(entry);
4421   ParsePredicateUsefulMarker useful_marker;
4422   predicate_iterator.for_each(useful_marker);
4423 }
4424 
4425 void PhaseIdealLoop::add_useless_parse_predicates_to_igvn_worklist() {
4426   for (int i = 0; i < C->parse_predicate_count(); i++) {
4427     ParsePredicateNode* parse_predicate_node = C->parse_predicate(i);
4428     if (parse_predicate_node->is_useless()) {
4429       _igvn._worklist.push(parse_predicate_node);
4430     }
4431   }
4432 }
4433 
4434 
4435 // Eliminate all Template Assertion Predicates that do not belong to their originally associated loop anymore by
4436 // replacing the OpaqueTemplateAssertionPredicate node of the If node with true. These nodes will be removed during the
4437 // next round of IGVN.
4438 void PhaseIdealLoop::eliminate_useless_template_assertion_predicates() {
4439   Unique_Node_List useful_predicates;
4440   if (C->has_loops()) {
4441     collect_useful_template_assertion_predicates(useful_predicates);
4442   }
4443   eliminate_useless_template_assertion_predicates(useful_predicates);
4444 }
4445 
4446 void PhaseIdealLoop::collect_useful_template_assertion_predicates(Unique_Node_List& useful_predicates) {
4447   for (LoopTreeIterator iterator(_ltree_root); !iterator.done(); iterator.next()) {
4448     IdealLoopTree* loop = iterator.current();
4449     if (loop->can_apply_loop_predication()) {
4450       collect_useful_template_assertion_predicates_for_loop(loop, useful_predicates);
4451     }
4452   }
4453 }
4454 
4455 void PhaseIdealLoop::collect_useful_template_assertion_predicates_for_loop(IdealLoopTree* loop,
4456                                                                            Unique_Node_List &useful_predicates) {
4457   Node* entry = loop->_head->as_Loop()->skip_strip_mined()->in(LoopNode::EntryControl);
4458   const Predicates predicates(entry);
4459   if (UseProfiledLoopPredicate) {
4460     const PredicateBlock* profiled_loop_predicate_block = predicates.profiled_loop_predicate_block();
4461     if (profiled_loop_predicate_block->has_parse_predicate()) {
4462       ParsePredicateSuccessProj* parse_predicate_proj = profiled_loop_predicate_block->parse_predicate_success_proj();
4463       get_opaque_template_assertion_predicate_nodes(parse_predicate_proj, useful_predicates);
4464     }
4465   }
4466 
4467   if (UseLoopPredicate) {
4468     const PredicateBlock* loop_predicate_block = predicates.loop_predicate_block();
4469     if (loop_predicate_block->has_parse_predicate()) {
4470       ParsePredicateSuccessProj* parse_predicate_proj = loop_predicate_block->parse_predicate_success_proj();
4471       get_opaque_template_assertion_predicate_nodes(parse_predicate_proj, useful_predicates);
4472     }
4473   }
4474 }
4475 
4476 void PhaseIdealLoop::eliminate_useless_template_assertion_predicates(Unique_Node_List& useful_predicates) {
4477   for (int i = C->template_assertion_predicate_count(); i > 0; i--) {
4478     OpaqueTemplateAssertionPredicateNode* opaque_node =
4479         C->template_assertion_predicate_opaq_node(i - 1)->as_OpaqueTemplateAssertionPredicate();
4480     if (!useful_predicates.member(opaque_node)) { // not in the useful list
4481       ConINode* one = intcon(1);
4482       _igvn.replace_node(opaque_node, one);
4483     }
4484   }
4485 }
4486 
4487 // If a post or main loop is removed due to an assert predicate, the opaque that guards the loop is not needed anymore
4488 void PhaseIdealLoop::eliminate_useless_zero_trip_guard() {
4489   if (_zero_trip_guard_opaque_nodes.size() == 0) {
4490     return;
4491   }
4492   Unique_Node_List useful_zero_trip_guard_opaques_nodes;
4493   for (LoopTreeIterator iter(_ltree_root); !iter.done(); iter.next()) {
4494     IdealLoopTree* lpt = iter.current();
4495     if (lpt->_child == nullptr && lpt->is_counted()) {
4496       CountedLoopNode* head = lpt->_head->as_CountedLoop();
4497       Node* opaque = head->is_canonical_loop_entry();
4498       if (opaque != nullptr) {
4499         useful_zero_trip_guard_opaques_nodes.push(opaque);
4500       }
4501     }
4502   }
4503   for (uint i = 0; i < _zero_trip_guard_opaque_nodes.size(); ++i) {
4504     OpaqueZeroTripGuardNode* opaque = ((OpaqueZeroTripGuardNode*)_zero_trip_guard_opaque_nodes.at(i));
4505     DEBUG_ONLY(CountedLoopNode* guarded_loop = opaque->guarded_loop());
4506     if (!useful_zero_trip_guard_opaques_nodes.member(opaque)) {
4507       IfNode* iff = opaque->if_node();
4508       IdealLoopTree* loop = get_loop(iff);
4509       while (loop != _ltree_root && loop != nullptr) {
4510         loop = loop->_parent;
4511       }
4512       if (loop == nullptr) {
4513         // unreachable from _ltree_root: zero trip guard is in a newly discovered infinite loop.
4514         // We can't tell if the opaque node is useful or not
4515         assert(guarded_loop == nullptr || guarded_loop->is_in_infinite_subgraph(), "");
4516       } else {
4517         assert(guarded_loop == nullptr, "");
4518         this->_igvn.replace_node(opaque, opaque->in(1));
4519       }
4520     } else {
4521       assert(guarded_loop != nullptr, "");
4522     }
4523   }
4524 }
4525 
4526 //------------------------process_expensive_nodes-----------------------------
4527 // Expensive nodes have their control input set to prevent the GVN
4528 // from commoning them and as a result forcing the resulting node to
4529 // be in a more frequent path. Use CFG information here, to change the
4530 // control inputs so that some expensive nodes can be commoned while
4531 // not executed more frequently.
4532 bool PhaseIdealLoop::process_expensive_nodes() {
4533   assert(OptimizeExpensiveOps, "optimization off?");
4534 
4535   // Sort nodes to bring similar nodes together
4536   C->sort_expensive_nodes();
4537 
4538   bool progress = false;
4539 
4540   for (int i = 0; i < C->expensive_count(); ) {
4541     Node* n = C->expensive_node(i);
4542     int start = i;
4543     // Find nodes similar to n
4544     i++;
4545     for (; i < C->expensive_count() && Compile::cmp_expensive_nodes(n, C->expensive_node(i)) == 0; i++);
4546     int end = i;
4547     // And compare them two by two
4548     for (int j = start; j < end; j++) {
4549       Node* n1 = C->expensive_node(j);
4550       if (is_node_unreachable(n1)) {
4551         continue;
4552       }
4553       for (int k = j+1; k < end; k++) {
4554         Node* n2 = C->expensive_node(k);
4555         if (is_node_unreachable(n2)) {
4556           continue;
4557         }
4558 
4559         assert(n1 != n2, "should be pair of nodes");
4560 
4561         Node* c1 = n1->in(0);
4562         Node* c2 = n2->in(0);
4563 
4564         Node* parent_c1 = c1;
4565         Node* parent_c2 = c2;
4566 
4567         // The call to get_early_ctrl_for_expensive() moves the
4568         // expensive nodes up but stops at loops that are in a if
4569         // branch. See whether we can exit the loop and move above the
4570         // If.
4571         if (c1->is_Loop()) {
4572           parent_c1 = c1->in(1);
4573         }
4574         if (c2->is_Loop()) {
4575           parent_c2 = c2->in(1);
4576         }
4577 
4578         if (parent_c1 == parent_c2) {
4579           _igvn._worklist.push(n1);
4580           _igvn._worklist.push(n2);
4581           continue;
4582         }
4583 
4584         // Look for identical expensive node up the dominator chain.
4585         if (is_dominator(c1, c2)) {
4586           c2 = c1;
4587         } else if (is_dominator(c2, c1)) {
4588           c1 = c2;
4589         } else if (parent_c1->is_Proj() && parent_c1->in(0)->is_If() &&
4590                    parent_c2->is_Proj() && parent_c1->in(0) == parent_c2->in(0)) {
4591           // Both branches have the same expensive node so move it up
4592           // before the if.
4593           c1 = c2 = idom(parent_c1->in(0));
4594         }
4595         // Do the actual moves
4596         if (n1->in(0) != c1) {
4597           _igvn.replace_input_of(n1, 0, c1);
4598           progress = true;
4599         }
4600         if (n2->in(0) != c2) {
4601           _igvn.replace_input_of(n2, 0, c2);
4602           progress = true;
4603         }
4604       }
4605     }
4606   }
4607 
4608   return progress;
4609 }
4610 
4611 //=============================================================================
4612 //----------------------------build_and_optimize-------------------------------
4613 // Create a PhaseLoop.  Build the ideal Loop tree.  Map each Ideal Node to
4614 // its corresponding LoopNode.  If 'optimize' is true, do some loop cleanups.
4615 void PhaseIdealLoop::build_and_optimize() {
4616   assert(!C->post_loop_opts_phase(), "no loop opts allowed");
4617 
4618   bool do_split_ifs = (_mode == LoopOptsDefault);
4619   bool skip_loop_opts = (_mode == LoopOptsNone);
4620   bool do_max_unroll = (_mode == LoopOptsMaxUnroll);
4621 
4622 
4623   int old_progress = C->major_progress();
4624   uint orig_worklist_size = _igvn._worklist.size();
4625 
4626   // Reset major-progress flag for the driver's heuristics
4627   C->clear_major_progress();
4628 
4629 #ifndef PRODUCT
4630   // Capture for later assert
4631   uint unique = C->unique();
4632   _loop_invokes++;
4633   _loop_work += unique;
4634 #endif
4635 
4636   // True if the method has at least 1 irreducible loop
4637   _has_irreducible_loops = false;
4638 
4639   _created_loop_node = false;
4640 
4641   VectorSet visited;
4642   // Pre-grow the mapping from Nodes to IdealLoopTrees.
4643   _loop_or_ctrl.map(C->unique(), nullptr);
4644   memset(_loop_or_ctrl.adr(), 0, wordSize * C->unique());
4645 
4646   // Pre-build the top-level outermost loop tree entry
4647   _ltree_root = new IdealLoopTree( this, C->root(), C->root() );
4648   // Do not need a safepoint at the top level
4649   _ltree_root->_has_sfpt = 1;
4650 
4651   // Initialize Dominators.
4652   // Checked in clone_loop_predicate() during beautify_loops().
4653   _idom_size = 0;
4654   _idom      = nullptr;
4655   _dom_depth = nullptr;
4656   _dom_stk   = nullptr;
4657 
4658   // Empty pre-order array
4659   allocate_preorders();
4660 
4661   // Build a loop tree on the fly.  Build a mapping from CFG nodes to
4662   // IdealLoopTree entries.  Data nodes are NOT walked.
4663   build_loop_tree();
4664   // Check for bailout, and return
4665   if (C->failing()) {
4666     return;
4667   }
4668 
4669   // Verify that the has_loops() flag set at parse time is consistent with the just built loop tree. When the back edge
4670   // is an exception edge, parsing doesn't set has_loops().
4671   assert(_ltree_root->_child == nullptr || C->has_loops() || C->has_exception_backedge(), "parsing found no loops but there are some");
4672   // No loops after all
4673   if( !_ltree_root->_child && !_verify_only ) C->set_has_loops(false);
4674 
4675   // There should always be an outer loop containing the Root and Return nodes.
4676   // If not, we have a degenerate empty program.  Bail out in this case.
4677   if (!has_node(C->root())) {
4678     if (!_verify_only) {
4679       C->clear_major_progress();
4680       assert(false, "empty program detected during loop optimization");
4681       C->record_method_not_compilable("empty program detected during loop optimization");
4682     }
4683     return;
4684   }
4685 
4686   BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
4687   // Nothing to do, so get out
4688   bool stop_early = !C->has_loops() && !skip_loop_opts && !do_split_ifs && !do_max_unroll && !_verify_me &&
4689           !_verify_only && !bs->is_gc_specific_loop_opts_pass(_mode);
4690   bool do_expensive_nodes = C->should_optimize_expensive_nodes(_igvn);
4691   bool strip_mined_loops_expanded = bs->strip_mined_loops_expanded(_mode);
4692   if (stop_early && !do_expensive_nodes) {
4693     return;
4694   }
4695 
4696   // Set loop nesting depth
4697   _ltree_root->set_nest( 0 );
4698 
4699   // Split shared headers and insert loop landing pads.
4700   // Do not bother doing this on the Root loop of course.
4701   if( !_verify_me && !_verify_only && _ltree_root->_child ) {
4702     C->print_method(PHASE_BEFORE_BEAUTIFY_LOOPS, 3);
4703     if( _ltree_root->_child->beautify_loops( this ) ) {
4704       // Re-build loop tree!
4705       _ltree_root->_child = nullptr;
4706       _loop_or_ctrl.clear();
4707       reallocate_preorders();
4708       build_loop_tree();
4709       // Check for bailout, and return
4710       if (C->failing()) {
4711         return;
4712       }
4713       // Reset loop nesting depth
4714       _ltree_root->set_nest( 0 );
4715 
4716       C->print_method(PHASE_AFTER_BEAUTIFY_LOOPS, 3);
4717     }
4718   }
4719 
4720   // Build Dominators for elision of null checks & loop finding.
4721   // Since nodes do not have a slot for immediate dominator, make
4722   // a persistent side array for that info indexed on node->_idx.
4723   _idom_size = C->unique();
4724   _idom      = NEW_RESOURCE_ARRAY( Node*, _idom_size );
4725   _dom_depth = NEW_RESOURCE_ARRAY( uint,  _idom_size );
4726   _dom_stk   = nullptr; // Allocated on demand in recompute_dom_depth
4727   memset( _dom_depth, 0, _idom_size * sizeof(uint) );
4728 
4729   Dominators();
4730 
4731   if (!_verify_only) {
4732     // As a side effect, Dominators removed any unreachable CFG paths
4733     // into RegionNodes.  It doesn't do this test against Root, so
4734     // we do it here.
4735     for( uint i = 1; i < C->root()->req(); i++ ) {
4736       if (!_loop_or_ctrl[C->root()->in(i)->_idx]) { // Dead path into Root?
4737         _igvn.delete_input_of(C->root(), i);
4738         i--;                      // Rerun same iteration on compressed edges
4739       }
4740     }
4741 
4742     // Given dominators, try to find inner loops with calls that must
4743     // always be executed (call dominates loop tail).  These loops do
4744     // not need a separate safepoint.
4745     Node_List cisstack;
4746     _ltree_root->check_safepts(visited, cisstack);
4747   }
4748 
4749   // Walk the DATA nodes and place into loops.  Find earliest control
4750   // node.  For CFG nodes, the _loop_or_ctrl array starts out and remains
4751   // holding the associated IdealLoopTree pointer.  For DATA nodes, the
4752   // _loop_or_ctrl array holds the earliest legal controlling CFG node.
4753 
4754   // Allocate stack with enough space to avoid frequent realloc
4755   int stack_size = (C->live_nodes() >> 1) + 16; // (live_nodes>>1)+16 from Java2D stats
4756   Node_Stack nstack(stack_size);
4757 
4758   visited.clear();
4759   Node_List worklist;
4760   // Don't need C->root() on worklist since
4761   // it will be processed among C->top() inputs
4762   worklist.push(C->top());
4763   visited.set(C->top()->_idx); // Set C->top() as visited now
4764   build_loop_early( visited, worklist, nstack );
4765 
4766   // Given early legal placement, try finding counted loops.  This placement
4767   // is good enough to discover most loop invariants.
4768   if (!_verify_me && !_verify_only && !strip_mined_loops_expanded) {
4769     _ltree_root->counted_loop( this );
4770   }
4771 
4772   // Find latest loop placement.  Find ideal loop placement.
4773   visited.clear();
4774   init_dom_lca_tags();
4775   // Need C->root() on worklist when processing outs
4776   worklist.push(C->root());
4777   NOT_PRODUCT( C->verify_graph_edges(); )
4778   worklist.push(C->top());
4779   build_loop_late( visited, worklist, nstack );
4780   if (C->failing()) { return; }
4781 
4782   if (_verify_only) {
4783     C->restore_major_progress(old_progress);
4784     assert(C->unique() == unique, "verification _mode made Nodes? ? ?");
4785     assert(_igvn._worklist.size() == orig_worklist_size, "shouldn't push anything");
4786     return;
4787   }
4788 
4789   // clear out the dead code after build_loop_late
4790   while (_deadlist.size()) {
4791     _igvn.remove_globally_dead_node(_deadlist.pop());
4792   }
4793 
4794   eliminate_useless_zero_trip_guard();
4795 
4796   if (stop_early) {
4797     assert(do_expensive_nodes, "why are we here?");
4798     if (process_expensive_nodes()) {
4799       // If we made some progress when processing expensive nodes then
4800       // the IGVN may modify the graph in a way that will allow us to
4801       // make some more progress: we need to try processing expensive
4802       // nodes again.
4803       C->set_major_progress();
4804     }
4805     return;
4806   }
4807 
4808   // Some parser-inserted loop predicates could never be used by loop
4809   // predication or they were moved away from loop during some optimizations.
4810   // For example, peeling. Eliminate them before next loop optimizations.
4811   eliminate_useless_predicates();
4812 
4813 #ifndef PRODUCT
4814   C->verify_graph_edges();
4815   if (_verify_me) {             // Nested verify pass?
4816     // Check to see if the verify _mode is broken
4817     assert(C->unique() == unique, "non-optimize _mode made Nodes? ? ?");
4818     return;
4819   }
4820   DEBUG_ONLY( if (VerifyLoopOptimizations) { verify(); } );
4821   if (TraceLoopOpts && C->has_loops()) {
4822     _ltree_root->dump();
4823   }
4824 #endif
4825 
4826   if (skip_loop_opts) {
4827     C->restore_major_progress(old_progress);
4828     return;
4829   }
4830 
4831   if (do_max_unroll) {
4832     for (LoopTreeIterator iter(_ltree_root); !iter.done(); iter.next()) {
4833       IdealLoopTree* lpt = iter.current();
4834       if (lpt->is_innermost() && lpt->_allow_optimizations && !lpt->_has_call && lpt->is_counted()) {
4835         lpt->compute_trip_count(this);
4836         if (!lpt->do_one_iteration_loop(this) &&
4837             !lpt->do_remove_empty_loop(this)) {
4838           AutoNodeBudget node_budget(this);
4839           if (lpt->_head->as_CountedLoop()->is_normal_loop() &&
4840               lpt->policy_maximally_unroll(this)) {
4841             memset( worklist.adr(), 0, worklist.max()*sizeof(Node*) );
4842             do_maximally_unroll(lpt, worklist);
4843           }
4844         }
4845       }
4846     }
4847 
4848     C->restore_major_progress(old_progress);
4849     return;
4850   }
4851 
4852   if (bs->optimize_loops(this, _mode, visited, nstack, worklist)) {
4853     return;
4854   }
4855 
4856   if (ReassociateInvariants && !C->major_progress()) {
4857     // Reassociate invariants and prep for split_thru_phi
4858     for (LoopTreeIterator iter(_ltree_root); !iter.done(); iter.next()) {
4859       IdealLoopTree* lpt = iter.current();
4860       if (!lpt->is_loop()) {
4861         continue;
4862       }
4863       Node* head = lpt->_head;
4864       if (!head->is_BaseCountedLoop() || !lpt->is_innermost()) continue;
4865 
4866       // check for vectorized loops, any reassociation of invariants was already done
4867       if (head->is_CountedLoop()) {
4868         if (head->as_CountedLoop()->is_unroll_only()) {
4869           continue;
4870         } else {
4871           AutoNodeBudget node_budget(this);
4872           lpt->reassociate_invariants(this);
4873         }
4874       }
4875       // Because RCE opportunities can be masked by split_thru_phi,
4876       // look for RCE candidates and inhibit split_thru_phi
4877       // on just their loop-phi's for this pass of loop opts
4878       if (SplitIfBlocks && do_split_ifs &&
4879           head->as_BaseCountedLoop()->is_valid_counted_loop(head->as_BaseCountedLoop()->bt()) &&
4880           (lpt->policy_range_check(this, true, T_LONG) ||
4881            (head->is_CountedLoop() && lpt->policy_range_check(this, true, T_INT)))) {
4882         lpt->_rce_candidate = 1; // = true
4883       }
4884     }
4885   }
4886 
4887   // Check for aggressive application of split-if and other transforms
4888   // that require basic-block info (like cloning through Phi's)
4889   if (!C->major_progress() && SplitIfBlocks && do_split_ifs) {
4890     visited.clear();
4891     split_if_with_blocks(visited, nstack);
4892     if (C->failing()) {
4893       return;
4894     }
4895     DEBUG_ONLY( if (VerifyLoopOptimizations) { verify(); } );
4896   }
4897 
4898   if (!C->major_progress() && do_expensive_nodes && process_expensive_nodes()) {
4899     C->set_major_progress();
4900   }
4901 
4902   // Perform loop predication before iteration splitting
4903   if (UseLoopPredicate && C->has_loops() && !C->major_progress() && (C->parse_predicate_count() > 0)) {
4904     _ltree_root->_child->loop_predication(this);
4905   }
4906 
4907   if (OptimizeFill && UseLoopPredicate && C->has_loops() && !C->major_progress()) {
4908     if (do_intrinsify_fill()) {
4909       C->set_major_progress();
4910     }
4911   }
4912 
4913   // Perform iteration-splitting on inner loops.  Split iterations to avoid
4914   // range checks or one-shot null checks.
4915 
4916   // If split-if's didn't hack the graph too bad (no CFG changes)
4917   // then do loop opts.
4918   if (C->has_loops() && !C->major_progress()) {
4919     memset( worklist.adr(), 0, worklist.max()*sizeof(Node*) );
4920     _ltree_root->_child->iteration_split( this, worklist );
4921     // No verify after peeling!  GCM has hoisted code out of the loop.
4922     // After peeling, the hoisted code could sink inside the peeled area.
4923     // The peeling code does not try to recompute the best location for
4924     // all the code before the peeled area, so the verify pass will always
4925     // complain about it.
4926   }
4927 
4928   // Check for bailout, and return
4929   if (C->failing()) {
4930     return;
4931   }
4932 
4933   // Do verify graph edges in any case
4934   NOT_PRODUCT( C->verify_graph_edges(); );
4935 
4936   if (!do_split_ifs) {
4937     // We saw major progress in Split-If to get here.  We forced a
4938     // pass with unrolling and not split-if, however more split-if's
4939     // might make progress.  If the unrolling didn't make progress
4940     // then the major-progress flag got cleared and we won't try
4941     // another round of Split-If.  In particular the ever-common
4942     // instance-of/check-cast pattern requires at least 2 rounds of
4943     // Split-If to clear out.
4944     C->set_major_progress();
4945   }
4946 
4947   // Repeat loop optimizations if new loops were seen
4948   if (created_loop_node()) {
4949     C->set_major_progress();
4950   }
4951 
4952   // Keep loop predicates and perform optimizations with them
4953   // until no more loop optimizations could be done.
4954   // After that switch predicates off and do more loop optimizations.
4955   if (!C->major_progress() && (C->parse_predicate_count() > 0)) {
4956     C->mark_parse_predicate_nodes_useless(_igvn);
4957     assert(C->parse_predicate_count() == 0, "should be zero now");
4958      if (TraceLoopOpts) {
4959        tty->print_cr("PredicatesOff");
4960      }
4961      C->set_major_progress();
4962   }
4963 
4964   // Auto-vectorize main-loop
4965   if (C->do_superword() && C->has_loops() && !C->major_progress()) {
4966     Compile::TracePhase tp(_t_autoVectorize);
4967 
4968     // Shared data structures for all AutoVectorizations, to reduce allocations
4969     // of large arrays.
4970     VSharedData vshared;
4971     for (LoopTreeIterator iter(_ltree_root); !iter.done(); iter.next()) {
4972       IdealLoopTree* lpt = iter.current();
4973       AutoVectorizeStatus status = auto_vectorize(lpt, vshared);
4974 
4975       if (status == AutoVectorizeStatus::TriedAndFailed) {
4976         // We tried vectorization, but failed. From now on only unroll the loop.
4977         CountedLoopNode* cl = lpt->_head->as_CountedLoop();
4978         if (cl->has_passed_slp()) {
4979           C->set_major_progress();
4980           cl->set_notpassed_slp();
4981           cl->mark_do_unroll_only();
4982         }
4983       }
4984     }
4985   }
4986 
4987   // Move UnorderedReduction out of counted loop. Can be introduced by AutoVectorization.
4988   if (C->has_loops() && !C->major_progress()) {
4989     for (LoopTreeIterator iter(_ltree_root); !iter.done(); iter.next()) {
4990       IdealLoopTree* lpt = iter.current();
4991       if (lpt->is_counted() && lpt->is_innermost()) {
4992         move_unordered_reduction_out_of_loop(lpt);
4993       }
4994     }
4995   }
4996 }
4997 
4998 #ifndef PRODUCT
4999 //------------------------------print_statistics-------------------------------
5000 int PhaseIdealLoop::_loop_invokes=0;// Count of PhaseIdealLoop invokes
5001 int PhaseIdealLoop::_loop_work=0; // Sum of PhaseIdealLoop x unique
5002 volatile int PhaseIdealLoop::_long_loop_candidates=0; // Number of long loops seen
5003 volatile int PhaseIdealLoop::_long_loop_nests=0; // Number of long loops successfully transformed to a nest
5004 volatile int PhaseIdealLoop::_long_loop_counted_loops=0; // Number of long loops successfully transformed to a counted loop
5005 void PhaseIdealLoop::print_statistics() {
5006   tty->print_cr("PhaseIdealLoop=%d, sum _unique=%d, long loops=%d/%d/%d", _loop_invokes, _loop_work, _long_loop_counted_loops, _long_loop_nests, _long_loop_candidates);
5007 }
5008 #endif
5009 
5010 #ifdef ASSERT
5011 // Build a verify-only PhaseIdealLoop, and see that it agrees with "this".
5012 void PhaseIdealLoop::verify() const {
5013   ResourceMark rm;
5014   int old_progress = C->major_progress();
5015   bool success = true;
5016 
5017   PhaseIdealLoop phase_verify(_igvn, this);
5018   if (C->failing_internal()) {
5019     return;
5020   }
5021 
5022   // Verify ctrl and idom of every node.
5023   success &= verify_idom_and_nodes(C->root(), &phase_verify);
5024 
5025   // Verify loop-tree.
5026   success &= _ltree_root->verify_tree(phase_verify._ltree_root);
5027 
5028   assert(success, "VerifyLoopOptimizations failed");
5029 
5030   // Major progress was cleared by creating a verify version of PhaseIdealLoop.
5031   C->restore_major_progress(old_progress);
5032 }
5033 
5034 // Perform a BFS starting at n, through all inputs.
5035 // Call verify_idom and verify_node on all nodes of BFS traversal.
5036 bool PhaseIdealLoop::verify_idom_and_nodes(Node* root, const PhaseIdealLoop* phase_verify) const {
5037   Unique_Node_List worklist;
5038   worklist.push(root);
5039   bool success = true;
5040   for (uint i = 0; i < worklist.size(); i++) {
5041     Node* n = worklist.at(i);
5042     // process node
5043     success &= verify_idom(n, phase_verify);
5044     success &= verify_loop_ctrl(n, phase_verify);
5045     // visit inputs
5046     for (uint j = 0; j < n->req(); j++) {
5047       if (n->in(j) != nullptr) {
5048         worklist.push(n->in(j));
5049       }
5050     }
5051   }
5052   return success;
5053 }
5054 
5055 // Verify dominator structure (IDOM).
5056 bool PhaseIdealLoop::verify_idom(Node* n, const PhaseIdealLoop* phase_verify) const {
5057   // Verify IDOM for all CFG nodes (except root).
5058   if (!n->is_CFG() || n->is_Root()) {
5059     return true; // pass
5060   }
5061 
5062   if (n->_idx >= _idom_size) {
5063     tty->print("CFG Node with no idom: ");
5064     n->dump();
5065     return false; // fail
5066   }
5067 
5068   Node* id = idom_no_update(n);
5069   Node* id_verify = phase_verify->idom_no_update(n);
5070   if (id != id_verify) {
5071     tty->print("Mismatching idom for node: ");
5072     n->dump();
5073     tty->print("  We have idom: ");
5074     id->dump();
5075     tty->print("  Verify has idom: ");
5076     id_verify->dump();
5077     tty->cr();
5078     return false; // fail
5079   }
5080   return true; // pass
5081 }
5082 
5083 // Verify "_loop_or_ctrl": control and loop membership.
5084 //  (0) _loop_or_ctrl[i] == nullptr -> node not reachable.
5085 //  (1) has_ctrl -> check lowest bit. 1 -> data node. 0 -> ctrl node.
5086 //  (2) has_ctrl true: get_ctrl_no_update returns ctrl of data node.
5087 //  (3) has_ctrl false: get_loop_idx returns IdealLoopTree for ctrl node.
5088 bool PhaseIdealLoop::verify_loop_ctrl(Node* n, const PhaseIdealLoop* phase_verify) const {
5089   const uint i = n->_idx;
5090   // The loop-tree was built from def to use (top-down).
5091   // The verification happens from use to def (bottom-up).
5092   // We may thus find nodes during verification that are not in the loop-tree.
5093   if (_loop_or_ctrl[i] == nullptr || phase_verify->_loop_or_ctrl[i] == nullptr) {
5094     if (_loop_or_ctrl[i] != nullptr || phase_verify->_loop_or_ctrl[i] != nullptr) {
5095       tty->print_cr("Was reachable in only one. this %d, verify %d.",
5096                  _loop_or_ctrl[i] != nullptr, phase_verify->_loop_or_ctrl[i] != nullptr);
5097       n->dump();
5098       return false; // fail
5099     }
5100     // Not reachable for both.
5101     return true; // pass
5102   }
5103 
5104   if (n->is_CFG() == has_ctrl(n)) {
5105     tty->print_cr("Exactly one should be true: %d for is_CFG, %d for has_ctrl.", n->is_CFG(), has_ctrl(n));
5106     n->dump();
5107     return false; // fail
5108   }
5109 
5110   if (has_ctrl(n) != phase_verify->has_ctrl(n)) {
5111     tty->print_cr("Mismatch has_ctrl: %d for this, %d for verify.", has_ctrl(n), phase_verify->has_ctrl(n));
5112     n->dump();
5113     return false; // fail
5114   } else if (has_ctrl(n)) {
5115     assert(phase_verify->has_ctrl(n), "sanity");
5116     // n is a data node.
5117     // Verify that its ctrl is the same.
5118 
5119     // Broken part of VerifyLoopOptimizations (A)
5120     // Reason:
5121     //   BUG, wrong control set for example in
5122     //   PhaseIdealLoop::split_if_with_blocks
5123     //   at "set_ctrl(x, new_ctrl);"
5124     /*
5125     if( _loop_or_ctrl[i] != loop_verify->_loop_or_ctrl[i] &&
5126         get_ctrl_no_update(n) != loop_verify->get_ctrl_no_update(n) ) {
5127       tty->print("Mismatched control setting for: ");
5128       n->dump();
5129       if( fail++ > 10 ) return;
5130       Node *c = get_ctrl_no_update(n);
5131       tty->print("We have it as: ");
5132       if( c->in(0) ) c->dump();
5133         else tty->print_cr("N%d",c->_idx);
5134       tty->print("Verify thinks: ");
5135       if( loop_verify->has_ctrl(n) )
5136         loop_verify->get_ctrl_no_update(n)->dump();
5137       else
5138         loop_verify->get_loop_idx(n)->dump();
5139       tty->cr();
5140     }
5141     */
5142     return true; // pass
5143   } else {
5144     assert(!phase_verify->has_ctrl(n), "sanity");
5145     // n is a ctrl node.
5146     // Verify that not has_ctrl, and that get_loop_idx is the same.
5147 
5148     // Broken part of VerifyLoopOptimizations (B)
5149     // Reason:
5150     //   NeverBranch node for example is added to loop outside its scope.
5151     //   Once we run build_loop_tree again, it is added to the correct loop.
5152     /*
5153     if (!C->major_progress()) {
5154       // Loop selection can be messed up if we did a major progress
5155       // operation, like split-if.  Do not verify in that case.
5156       IdealLoopTree *us = get_loop_idx(n);
5157       IdealLoopTree *them = loop_verify->get_loop_idx(n);
5158       if( us->_head != them->_head ||  us->_tail != them->_tail ) {
5159         tty->print("Unequals loops for: ");
5160         n->dump();
5161         if( fail++ > 10 ) return;
5162         tty->print("We have it as: ");
5163         us->dump();
5164         tty->print("Verify thinks: ");
5165         them->dump();
5166         tty->cr();
5167       }
5168     }
5169     */
5170     return true; // pass
5171   }
5172 }
5173 
5174 static int compare_tree(IdealLoopTree* const& a, IdealLoopTree* const& b) {
5175   assert(a != nullptr && b != nullptr, "must be");
5176   return a->_head->_idx - b->_head->_idx;
5177 }
5178 
5179 GrowableArray<IdealLoopTree*> IdealLoopTree::collect_sorted_children() const {
5180   GrowableArray<IdealLoopTree*> children;
5181   IdealLoopTree* child = _child;
5182   while (child != nullptr) {
5183     assert(child->_parent == this, "all must be children of this");
5184     children.insert_sorted<compare_tree>(child);
5185     child = child->_next;
5186   }
5187   return children;
5188 }
5189 
5190 // Verify that tree structures match. Because the CFG can change, siblings
5191 // within the loop tree can be reordered. We attempt to deal with that by
5192 // reordering the verify's loop tree if possible.
5193 bool IdealLoopTree::verify_tree(IdealLoopTree* loop_verify) const {
5194   assert(_head == loop_verify->_head, "mismatched loop head");
5195   assert(this->_parent != nullptr || this->_next == nullptr, "is_root_loop implies has_no_sibling");
5196 
5197   // Collect the children
5198   GrowableArray<IdealLoopTree*> children = collect_sorted_children();
5199   GrowableArray<IdealLoopTree*> children_verify = loop_verify->collect_sorted_children();
5200 
5201   bool success = true;
5202 
5203   // Compare the two children lists
5204   for (int i = 0, j = 0; i < children.length() || j < children_verify.length(); ) {
5205     IdealLoopTree* child        = nullptr;
5206     IdealLoopTree* child_verify = nullptr;
5207     // Read from both lists, if possible.
5208     if (i < children.length()) {
5209       child = children.at(i);
5210     }
5211     if (j < children_verify.length()) {
5212       child_verify = children_verify.at(j);
5213     }
5214     assert(child != nullptr || child_verify != nullptr, "must find at least one");
5215     if (child != nullptr && child_verify != nullptr && child->_head != child_verify->_head) {
5216       // We found two non-equal children. Select the smaller one.
5217       if (child->_head->_idx < child_verify->_head->_idx) {
5218         child_verify = nullptr;
5219       } else {
5220         child = nullptr;
5221       }
5222     }
5223     // Process the two children, or potentially log the failure if we only found one.
5224     if (child_verify == nullptr) {
5225       if (child->_irreducible && Compile::current()->major_progress()) {
5226         // Irreducible loops can pick a different header (one of its entries).
5227       } else {
5228         tty->print_cr("We have a loop that verify does not have");
5229         child->dump();
5230         success = false;
5231       }
5232       i++; // step for this
5233     } else if (child == nullptr) {
5234       if (child_verify->_irreducible && Compile::current()->major_progress()) {
5235         // Irreducible loops can pick a different header (one of its entries).
5236       } else if (child_verify->_head->as_Region()->is_in_infinite_subgraph()) {
5237         // Infinite loops do not get attached to the loop-tree on their first visit.
5238         // "this" runs before "loop_verify". It is thus possible that we find the
5239         // infinite loop only for "child_verify". Only finding it with "child" would
5240         // mean that we lost it, which is not ok.
5241       } else {
5242         tty->print_cr("Verify has a loop that we do not have");
5243         child_verify->dump();
5244         success = false;
5245       }
5246       j++; // step for verify
5247     } else {
5248       assert(child->_head == child_verify->_head, "We have both and they are equal");
5249       success &= child->verify_tree(child_verify); // Recursion
5250       i++; // step for this
5251       j++; // step for verify
5252     }
5253   }
5254 
5255   // Broken part of VerifyLoopOptimizations (D)
5256   // Reason:
5257   //   split_if has to update the _tail, if it is modified. But that is done by
5258   //   checking to what loop the iff belongs to. That info can be wrong, and then
5259   //   we do not update the _tail correctly.
5260   /*
5261   Node *tail = _tail;           // Inline a non-updating version of
5262   while( !tail->in(0) )         // the 'tail()' call.
5263     tail = tail->in(1);
5264   assert( tail == loop->_tail, "mismatched loop tail" );
5265   */
5266 
5267   if (_head->is_CountedLoop()) {
5268     CountedLoopNode *cl = _head->as_CountedLoop();
5269 
5270     Node* ctrl     = cl->init_control();
5271     Node* back     = cl->back_control();
5272     assert(ctrl != nullptr && ctrl->is_CFG(), "sane loop in-ctrl");
5273     assert(back != nullptr && back->is_CFG(), "sane loop backedge");
5274     cl->loopexit(); // assert implied
5275   }
5276 
5277   // Broken part of VerifyLoopOptimizations (E)
5278   // Reason:
5279   //   PhaseIdealLoop::split_thru_region creates new nodes for loop that are not added
5280   //   to the loop body. Or maybe they are not added to the correct loop.
5281   //   at "Node* x = n->clone();"
5282   /*
5283   // Innermost loops need to verify loop bodies,
5284   // but only if no 'major_progress'
5285   int fail = 0;
5286   if (!Compile::current()->major_progress() && _child == nullptr) {
5287     for( uint i = 0; i < _body.size(); i++ ) {
5288       Node *n = _body.at(i);
5289       if (n->outcnt() == 0)  continue; // Ignore dead
5290       uint j;
5291       for( j = 0; j < loop->_body.size(); j++ )
5292         if( loop->_body.at(j) == n )
5293           break;
5294       if( j == loop->_body.size() ) { // Not found in loop body
5295         // Last ditch effort to avoid assertion: Its possible that we
5296         // have some users (so outcnt not zero) but are still dead.
5297         // Try to find from root.
5298         if (Compile::current()->root()->find(n->_idx)) {
5299           fail++;
5300           tty->print("We have that verify does not: ");
5301           n->dump();
5302         }
5303       }
5304     }
5305     for( uint i2 = 0; i2 < loop->_body.size(); i2++ ) {
5306       Node *n = loop->_body.at(i2);
5307       if (n->outcnt() == 0)  continue; // Ignore dead
5308       uint j;
5309       for( j = 0; j < _body.size(); j++ )
5310         if( _body.at(j) == n )
5311           break;
5312       if( j == _body.size() ) { // Not found in loop body
5313         // Last ditch effort to avoid assertion: Its possible that we
5314         // have some users (so outcnt not zero) but are still dead.
5315         // Try to find from root.
5316         if (Compile::current()->root()->find(n->_idx)) {
5317           fail++;
5318           tty->print("Verify has that we do not: ");
5319           n->dump();
5320         }
5321       }
5322     }
5323     assert( !fail, "loop body mismatch" );
5324   }
5325   */
5326   return success;
5327 }
5328 #endif
5329 
5330 //------------------------------set_idom---------------------------------------
5331 void PhaseIdealLoop::set_idom(Node* d, Node* n, uint dom_depth) {
5332   _nesting.check(); // Check if a potential reallocation in the resource arena is safe
5333   uint idx = d->_idx;
5334   if (idx >= _idom_size) {
5335     uint newsize = next_power_of_2(idx);
5336     _idom      = REALLOC_RESOURCE_ARRAY( Node*,     _idom,_idom_size,newsize);
5337     _dom_depth = REALLOC_RESOURCE_ARRAY( uint, _dom_depth,_idom_size,newsize);
5338     memset( _dom_depth + _idom_size, 0, (newsize - _idom_size) * sizeof(uint) );
5339     _idom_size = newsize;
5340   }
5341   _idom[idx] = n;
5342   _dom_depth[idx] = dom_depth;
5343 }
5344 
5345 //------------------------------recompute_dom_depth---------------------------------------
5346 // The dominator tree is constructed with only parent pointers.
5347 // This recomputes the depth in the tree by first tagging all
5348 // nodes as "no depth yet" marker.  The next pass then runs up
5349 // the dom tree from each node marked "no depth yet", and computes
5350 // the depth on the way back down.
5351 void PhaseIdealLoop::recompute_dom_depth() {
5352   uint no_depth_marker = C->unique();
5353   uint i;
5354   // Initialize depth to "no depth yet" and realize all lazy updates
5355   for (i = 0; i < _idom_size; i++) {
5356     // Only indices with a _dom_depth has a Node* or null (otherwise uninitialized).
5357     if (_dom_depth[i] > 0 && _idom[i] != nullptr) {
5358       _dom_depth[i] = no_depth_marker;
5359 
5360       // heal _idom if it has a fwd mapping in _loop_or_ctrl
5361       if (_idom[i]->in(0) == nullptr) {
5362         idom(i);
5363       }
5364     }
5365   }
5366   if (_dom_stk == nullptr) {
5367     uint init_size = C->live_nodes() / 100; // Guess that 1/100 is a reasonable initial size.
5368     if (init_size < 10) init_size = 10;
5369     _dom_stk = new GrowableArray<uint>(init_size);
5370   }
5371   // Compute new depth for each node.
5372   for (i = 0; i < _idom_size; i++) {
5373     uint j = i;
5374     // Run up the dom tree to find a node with a depth
5375     while (_dom_depth[j] == no_depth_marker) {
5376       _dom_stk->push(j);
5377       j = _idom[j]->_idx;
5378     }
5379     // Compute the depth on the way back down this tree branch
5380     uint dd = _dom_depth[j] + 1;
5381     while (_dom_stk->length() > 0) {
5382       uint j = _dom_stk->pop();
5383       _dom_depth[j] = dd;
5384       dd++;
5385     }
5386   }
5387 }
5388 
5389 //------------------------------sort-------------------------------------------
5390 // Insert 'loop' into the existing loop tree.  'innermost' is a leaf of the
5391 // loop tree, not the root.
5392 IdealLoopTree *PhaseIdealLoop::sort( IdealLoopTree *loop, IdealLoopTree *innermost ) {
5393   if( !innermost ) return loop; // New innermost loop
5394 
5395   int loop_preorder = get_preorder(loop->_head); // Cache pre-order number
5396   assert( loop_preorder, "not yet post-walked loop" );
5397   IdealLoopTree **pp = &innermost;      // Pointer to previous next-pointer
5398   IdealLoopTree *l = *pp;               // Do I go before or after 'l'?
5399 
5400   // Insert at start of list
5401   while( l ) {                  // Insertion sort based on pre-order
5402     if( l == loop ) return innermost; // Already on list!
5403     int l_preorder = get_preorder(l->_head); // Cache pre-order number
5404     assert( l_preorder, "not yet post-walked l" );
5405     // Check header pre-order number to figure proper nesting
5406     if( loop_preorder > l_preorder )
5407       break;                    // End of insertion
5408     // If headers tie (e.g., shared headers) check tail pre-order numbers.
5409     // Since I split shared headers, you'd think this could not happen.
5410     // BUT: I must first do the preorder numbering before I can discover I
5411     // have shared headers, so the split headers all get the same preorder
5412     // number as the RegionNode they split from.
5413     if( loop_preorder == l_preorder &&
5414         get_preorder(loop->_tail) < get_preorder(l->_tail) )
5415       break;                    // Also check for shared headers (same pre#)
5416     pp = &l->_parent;           // Chain up list
5417     l = *pp;
5418   }
5419   // Link into list
5420   // Point predecessor to me
5421   *pp = loop;
5422   // Point me to successor
5423   IdealLoopTree *p = loop->_parent;
5424   loop->_parent = l;            // Point me to successor
5425   if( p ) sort( p, innermost ); // Insert my parents into list as well
5426   return innermost;
5427 }
5428 
5429 //------------------------------build_loop_tree--------------------------------
5430 // I use a modified Vick/Tarjan algorithm.  I need pre- and a post- visit
5431 // bits.  The _loop_or_ctrl[] array is mapped by Node index and holds a null for
5432 // not-yet-pre-walked, pre-order # for pre-but-not-post-walked and holds the
5433 // tightest enclosing IdealLoopTree for post-walked.
5434 //
5435 // During my forward walk I do a short 1-layer lookahead to see if I can find
5436 // a loop backedge with that doesn't have any work on the backedge.  This
5437 // helps me construct nested loops with shared headers better.
5438 //
5439 // Once I've done the forward recursion, I do the post-work.  For each child
5440 // I check to see if there is a backedge.  Backedges define a loop!  I
5441 // insert an IdealLoopTree at the target of the backedge.
5442 //
5443 // During the post-work I also check to see if I have several children
5444 // belonging to different loops.  If so, then this Node is a decision point
5445 // where control flow can choose to change loop nests.  It is at this
5446 // decision point where I can figure out how loops are nested.  At this
5447 // time I can properly order the different loop nests from my children.
5448 // Note that there may not be any backedges at the decision point!
5449 //
5450 // Since the decision point can be far removed from the backedges, I can't
5451 // order my loops at the time I discover them.  Thus at the decision point
5452 // I need to inspect loop header pre-order numbers to properly nest my
5453 // loops.  This means I need to sort my childrens' loops by pre-order.
5454 // The sort is of size number-of-control-children, which generally limits
5455 // it to size 2 (i.e., I just choose between my 2 target loops).
5456 void PhaseIdealLoop::build_loop_tree() {
5457   // Allocate stack of size C->live_nodes()/2 to avoid frequent realloc
5458   GrowableArray <Node *> bltstack(C->live_nodes() >> 1);
5459   Node *n = C->root();
5460   bltstack.push(n);
5461   int pre_order = 1;
5462   int stack_size;
5463 
5464   while ( ( stack_size = bltstack.length() ) != 0 ) {
5465     n = bltstack.top(); // Leave node on stack
5466     if ( !is_visited(n) ) {
5467       // ---- Pre-pass Work ----
5468       // Pre-walked but not post-walked nodes need a pre_order number.
5469 
5470       set_preorder_visited( n, pre_order ); // set as visited
5471 
5472       // ---- Scan over children ----
5473       // Scan first over control projections that lead to loop headers.
5474       // This helps us find inner-to-outer loops with shared headers better.
5475 
5476       // Scan children's children for loop headers.
5477       for ( int i = n->outcnt() - 1; i >= 0; --i ) {
5478         Node* m = n->raw_out(i);       // Child
5479         if( m->is_CFG() && !is_visited(m) ) { // Only for CFG children
5480           // Scan over children's children to find loop
5481           for (DUIterator_Fast jmax, j = m->fast_outs(jmax); j < jmax; j++) {
5482             Node* l = m->fast_out(j);
5483             if( is_visited(l) &&       // Been visited?
5484                 !is_postvisited(l) &&  // But not post-visited
5485                 get_preorder(l) < pre_order ) { // And smaller pre-order
5486               // Found!  Scan the DFS down this path before doing other paths
5487               bltstack.push(m);
5488               break;
5489             }
5490           }
5491         }
5492       }
5493       pre_order++;
5494     }
5495     else if ( !is_postvisited(n) ) {
5496       // Note: build_loop_tree_impl() adds out edges on rare occasions,
5497       // such as com.sun.rsasign.am::a.
5498       // For non-recursive version, first, process current children.
5499       // On next iteration, check if additional children were added.
5500       for ( int k = n->outcnt() - 1; k >= 0; --k ) {
5501         Node* u = n->raw_out(k);
5502         if ( u->is_CFG() && !is_visited(u) ) {
5503           bltstack.push(u);
5504         }
5505       }
5506       if ( bltstack.length() == stack_size ) {
5507         // There were no additional children, post visit node now
5508         (void)bltstack.pop(); // Remove node from stack
5509         pre_order = build_loop_tree_impl(n, pre_order);
5510         // Check for bailout
5511         if (C->failing()) {
5512           return;
5513         }
5514         // Check to grow _preorders[] array for the case when
5515         // build_loop_tree_impl() adds new nodes.
5516         check_grow_preorders();
5517       }
5518     }
5519     else {
5520       (void)bltstack.pop(); // Remove post-visited node from stack
5521     }
5522   }
5523   DEBUG_ONLY(verify_regions_in_irreducible_loops();)
5524 }
5525 
5526 //------------------------------build_loop_tree_impl---------------------------
5527 int PhaseIdealLoop::build_loop_tree_impl(Node* n, int pre_order) {
5528   // ---- Post-pass Work ----
5529   // Pre-walked but not post-walked nodes need a pre_order number.
5530 
5531   // Tightest enclosing loop for this Node
5532   IdealLoopTree *innermost = nullptr;
5533 
5534   // For all children, see if any edge is a backedge.  If so, make a loop
5535   // for it.  Then find the tightest enclosing loop for the self Node.
5536   for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
5537     Node* m = n->fast_out(i);   // Child
5538     if (n == m) continue;      // Ignore control self-cycles
5539     if (!m->is_CFG()) continue;// Ignore non-CFG edges
5540 
5541     IdealLoopTree *l;           // Child's loop
5542     if (!is_postvisited(m)) {  // Child visited but not post-visited?
5543       // Found a backedge
5544       assert(get_preorder(m) < pre_order, "should be backedge");
5545       // Check for the RootNode, which is already a LoopNode and is allowed
5546       // to have multiple "backedges".
5547       if (m == C->root()) {     // Found the root?
5548         l = _ltree_root;        // Root is the outermost LoopNode
5549       } else {                  // Else found a nested loop
5550         // Insert a LoopNode to mark this loop.
5551         l = new IdealLoopTree(this, m, n);
5552       } // End of Else found a nested loop
5553       if (!has_loop(m)) {        // If 'm' does not already have a loop set
5554         set_loop(m, l);         // Set loop header to loop now
5555       }
5556     } else {                    // Else not a nested loop
5557       if (!_loop_or_ctrl[m->_idx]) continue; // Dead code has no loop
5558       IdealLoopTree* m_loop = get_loop(m);
5559       l = m_loop;          // Get previously determined loop
5560       // If successor is header of a loop (nest), move up-loop till it
5561       // is a member of some outer enclosing loop.  Since there are no
5562       // shared headers (I've split them already) I only need to go up
5563       // at most 1 level.
5564       while (l && l->_head == m) { // Successor heads loop?
5565         l = l->_parent;         // Move up 1 for me
5566       }
5567       // If this loop is not properly parented, then this loop
5568       // has no exit path out, i.e. its an infinite loop.
5569       if (!l) {
5570         // Make loop "reachable" from root so the CFG is reachable.  Basically
5571         // insert a bogus loop exit that is never taken.  'm', the loop head,
5572         // points to 'n', one (of possibly many) fall-in paths.  There may be
5573         // many backedges as well.
5574 
5575         if (!_verify_only) {
5576           // Insert the NeverBranch between 'm' and it's control user.
5577           NeverBranchNode *iff = new NeverBranchNode( m );
5578           _igvn.register_new_node_with_optimizer(iff);
5579           set_loop(iff, m_loop);
5580           Node *if_t = new CProjNode( iff, 0 );
5581           _igvn.register_new_node_with_optimizer(if_t);
5582           set_loop(if_t, m_loop);
5583 
5584           Node* cfg = nullptr;       // Find the One True Control User of m
5585           for (DUIterator_Fast jmax, j = m->fast_outs(jmax); j < jmax; j++) {
5586             Node* x = m->fast_out(j);
5587             if (x->is_CFG() && x != m && x != iff)
5588               { cfg = x; break; }
5589           }
5590           assert(cfg != nullptr, "must find the control user of m");
5591           uint k = 0;             // Probably cfg->in(0)
5592           while( cfg->in(k) != m ) k++; // But check in case cfg is a Region
5593           _igvn.replace_input_of(cfg, k, if_t); // Now point to NeverBranch
5594 
5595           // Now create the never-taken loop exit
5596           Node *if_f = new CProjNode( iff, 1 );
5597           _igvn.register_new_node_with_optimizer(if_f);
5598           set_loop(if_f, _ltree_root);
5599           // Find frame ptr for Halt.  Relies on the optimizer
5600           // V-N'ing.  Easier and quicker than searching through
5601           // the program structure.
5602           Node *frame = new ParmNode( C->start(), TypeFunc::FramePtr );
5603           _igvn.register_new_node_with_optimizer(frame);
5604           // Halt & Catch Fire
5605           Node* halt = new HaltNode(if_f, frame, "never-taken loop exit reached");
5606           _igvn.register_new_node_with_optimizer(halt);
5607           set_loop(halt, _ltree_root);
5608           _igvn.add_input_to(C->root(), halt);
5609         }
5610         set_loop(C->root(), _ltree_root);
5611         // move to outer most loop with same header
5612         l = m_loop;
5613         while (true) {
5614           IdealLoopTree* next = l->_parent;
5615           if (next == nullptr || next->_head != m) {
5616             break;
5617           }
5618           l = next;
5619         }
5620         // properly insert infinite loop in loop tree
5621         sort(_ltree_root, l);
5622         // fix child link from parent
5623         IdealLoopTree* p = l->_parent;
5624         l->_next = p->_child;
5625         p->_child = l;
5626         // code below needs enclosing loop
5627         l = l->_parent;
5628       }
5629     }
5630     if (is_postvisited(l->_head)) {
5631       // We are currently visiting l, but its head has already been post-visited.
5632       // l is irreducible: we just found a second entry m.
5633       _has_irreducible_loops = true;
5634       RegionNode* secondary_entry = m->as_Region();
5635       DEBUG_ONLY(secondary_entry->verify_can_be_irreducible_entry();)
5636 
5637       // Walk up the loop-tree, mark all loops that are already post-visited as irreducible
5638       // Since m is a secondary entry to them all.
5639       while( is_postvisited(l->_head) ) {
5640         l->_irreducible = 1; // = true
5641         RegionNode* head = l->_head->as_Region();
5642         DEBUG_ONLY(head->verify_can_be_irreducible_entry();)
5643         l = l->_parent;
5644         // Check for bad CFG here to prevent crash, and bailout of compile
5645         if (l == nullptr) {
5646 #ifndef PRODUCT
5647           if (TraceLoopOpts) {
5648             tty->print_cr("bailout: unhandled CFG: infinite irreducible loop");
5649             m->dump();
5650           }
5651 #endif
5652           // This is a rare case that we do not want to handle in C2.
5653           C->record_method_not_compilable("unhandled CFG detected during loop optimization");
5654           return pre_order;
5655         }
5656       }
5657     }
5658     if (!_verify_only) {
5659       C->set_has_irreducible_loop(_has_irreducible_loops);
5660     }
5661 
5662     // This Node might be a decision point for loops.  It is only if
5663     // it's children belong to several different loops.  The sort call
5664     // does a trivial amount of work if there is only 1 child or all
5665     // children belong to the same loop.  If however, the children
5666     // belong to different loops, the sort call will properly set the
5667     // _parent pointers to show how the loops nest.
5668     //
5669     // In any case, it returns the tightest enclosing loop.
5670     innermost = sort( l, innermost );
5671   }
5672 
5673   // Def-use info will have some dead stuff; dead stuff will have no
5674   // loop decided on.
5675 
5676   // Am I a loop header?  If so fix up my parent's child and next ptrs.
5677   if( innermost && innermost->_head == n ) {
5678     assert( get_loop(n) == innermost, "" );
5679     IdealLoopTree *p = innermost->_parent;
5680     IdealLoopTree *l = innermost;
5681     while (p && l->_head == n) {
5682       l->_next = p->_child;     // Put self on parents 'next child'
5683       p->_child = l;            // Make self as first child of parent
5684       l = p;                    // Now walk up the parent chain
5685       p = l->_parent;
5686     }
5687   } else {
5688     // Note that it is possible for a LoopNode to reach here, if the
5689     // backedge has been made unreachable (hence the LoopNode no longer
5690     // denotes a Loop, and will eventually be removed).
5691 
5692     // Record tightest enclosing loop for self.  Mark as post-visited.
5693     set_loop(n, innermost);
5694     // Also record has_call flag early on
5695     if (innermost) {
5696       if( n->is_Call() && !n->is_CallLeaf() && !n->is_macro() ) {
5697         // Do not count uncommon calls
5698         if( !n->is_CallStaticJava() || !n->as_CallStaticJava()->_name ) {
5699           Node *iff = n->in(0)->in(0);
5700           // No any calls for vectorized loops.
5701           if (C->do_superword() ||
5702               !iff->is_If() ||
5703               (n->in(0)->Opcode() == Op_IfFalse && (1.0 - iff->as_If()->_prob) >= 0.01) ||
5704               iff->as_If()->_prob >= 0.01) {
5705             innermost->_has_call = 1;
5706           }
5707         }
5708       } else if( n->is_Allocate() && n->as_Allocate()->_is_scalar_replaceable ) {
5709         // Disable loop optimizations if the loop has a scalar replaceable
5710         // allocation. This disabling may cause a potential performance lost
5711         // if the allocation is not eliminated for some reason.
5712         innermost->_allow_optimizations = false;
5713         innermost->_has_call = 1; // = true
5714       } else if (n->Opcode() == Op_SafePoint) {
5715         // Record all safepoints in this loop.
5716         if (innermost->_safepts == nullptr) innermost->_safepts = new Node_List();
5717         innermost->_safepts->push(n);
5718       }
5719     }
5720   }
5721 
5722   // Flag as post-visited now
5723   set_postvisited(n);
5724   return pre_order;
5725 }
5726 
5727 #ifdef ASSERT
5728 //--------------------------verify_regions_in_irreducible_loops----------------
5729 // Iterate down from Root through CFG, verify for every region:
5730 // if it is in an irreducible loop it must be marked as such
5731 void PhaseIdealLoop::verify_regions_in_irreducible_loops() {
5732   ResourceMark rm;
5733   if (!_has_irreducible_loops) {
5734     // last build_loop_tree has not found any irreducible loops
5735     // hence no region has to be marked is_in_irreduible_loop
5736     return;
5737   }
5738 
5739   RootNode* root = C->root();
5740   Unique_Node_List worklist; // visit all nodes once
5741   worklist.push(root);
5742   bool failure = false;
5743   for (uint i = 0; i < worklist.size(); i++) {
5744     Node* n = worklist.at(i);
5745     if (n->is_Region()) {
5746       RegionNode* region = n->as_Region();
5747       if (is_in_irreducible_loop(region) &&
5748           region->loop_status() == RegionNode::LoopStatus::Reducible) {
5749         failure = true;
5750         tty->print("irreducible! ");
5751         region->dump();
5752       }
5753     }
5754     for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++) {
5755       Node* use = n->fast_out(j);
5756       if (use->is_CFG()) {
5757         worklist.push(use); // push if was not pushed before
5758       }
5759     }
5760   }
5761   assert(!failure, "region in irreducible loop was marked as reducible");
5762 }
5763 
5764 //---------------------------is_in_irreducible_loop-------------------------
5765 // Analogous to ciTypeFlow::Block::is_in_irreducible_loop
5766 bool PhaseIdealLoop::is_in_irreducible_loop(RegionNode* region) {
5767   if (!_has_irreducible_loops) {
5768     return false; // no irreducible loop in graph
5769   }
5770   IdealLoopTree* l = get_loop(region); // l: innermost loop that contains region
5771   do {
5772     if (l->_irreducible) {
5773       return true; // found it
5774     }
5775     if (l == _ltree_root) {
5776       return false; // reached root, terimnate
5777     }
5778     l = l->_parent;
5779   } while (l != nullptr);
5780   assert(region->is_in_infinite_subgraph(), "must be in infinite subgraph");
5781   // We have "l->_parent == nullptr", which happens only for infinite loops,
5782   // where no parent is attached to the loop. We did not find any irreducible
5783   // loop from this block out to lp. Thus lp only has one entry, and no exit
5784   // (it is infinite and reducible). We can always rewrite an infinite loop
5785   // that is nested inside other loops:
5786   // while(condition) { infinite_loop; }
5787   // with an equivalent program where the infinite loop is an outermost loop
5788   // that is not nested in any loop:
5789   // while(condition) { break; } infinite_loop;
5790   // Thus, we can understand lp as an outermost loop, and can terminate and
5791   // conclude: this block is in no irreducible loop.
5792   return false;
5793 }
5794 #endif
5795 
5796 //------------------------------build_loop_early-------------------------------
5797 // Put Data nodes into some loop nest, by setting the _loop_or_ctrl[]->loop mapping.
5798 // First pass computes the earliest controlling node possible.  This is the
5799 // controlling input with the deepest dominating depth.
5800 void PhaseIdealLoop::build_loop_early( VectorSet &visited, Node_List &worklist, Node_Stack &nstack ) {
5801   while (worklist.size() != 0) {
5802     // Use local variables nstack_top_n & nstack_top_i to cache values
5803     // on nstack's top.
5804     Node *nstack_top_n = worklist.pop();
5805     uint  nstack_top_i = 0;
5806 //while_nstack_nonempty:
5807     while (true) {
5808       // Get parent node and next input's index from stack's top.
5809       Node  *n = nstack_top_n;
5810       uint   i = nstack_top_i;
5811       uint cnt = n->req(); // Count of inputs
5812       if (i == 0) {        // Pre-process the node.
5813         if( has_node(n) &&            // Have either loop or control already?
5814             !has_ctrl(n) ) {          // Have loop picked out already?
5815           // During "merge_many_backedges" we fold up several nested loops
5816           // into a single loop.  This makes the members of the original
5817           // loop bodies pointing to dead loops; they need to move up
5818           // to the new UNION'd larger loop.  I set the _head field of these
5819           // dead loops to null and the _parent field points to the owning
5820           // loop.  Shades of UNION-FIND algorithm.
5821           IdealLoopTree *ilt;
5822           while( !(ilt = get_loop(n))->_head ) {
5823             // Normally I would use a set_loop here.  But in this one special
5824             // case, it is legal (and expected) to change what loop a Node
5825             // belongs to.
5826             _loop_or_ctrl.map(n->_idx, (Node*)(ilt->_parent));
5827           }
5828           // Remove safepoints ONLY if I've already seen I don't need one.
5829           // (the old code here would yank a 2nd safepoint after seeing a
5830           // first one, even though the 1st did not dominate in the loop body
5831           // and thus could be avoided indefinitely)
5832           if( !_verify_only && !_verify_me && ilt->_has_sfpt && n->Opcode() == Op_SafePoint &&
5833               is_deleteable_safept(n)) {
5834             Node *in = n->in(TypeFunc::Control);
5835             lazy_replace(n,in);       // Pull safepoint now
5836             if (ilt->_safepts != nullptr) {
5837               ilt->_safepts->yank(n);
5838             }
5839             // Carry on with the recursion "as if" we are walking
5840             // only the control input
5841             if( !visited.test_set( in->_idx ) ) {
5842               worklist.push(in);      // Visit this guy later, using worklist
5843             }
5844             // Get next node from nstack:
5845             // - skip n's inputs processing by setting i > cnt;
5846             // - we also will not call set_early_ctrl(n) since
5847             //   has_node(n) == true (see the condition above).
5848             i = cnt + 1;
5849           }
5850         }
5851       } // if (i == 0)
5852 
5853       // Visit all inputs
5854       bool done = true;       // Assume all n's inputs will be processed
5855       while (i < cnt) {
5856         Node *in = n->in(i);
5857         ++i;
5858         if (in == nullptr) continue;
5859         if (in->pinned() && !in->is_CFG())
5860           set_ctrl(in, in->in(0));
5861         int is_visited = visited.test_set( in->_idx );
5862         if (!has_node(in)) {  // No controlling input yet?
5863           assert( !in->is_CFG(), "CFG Node with no controlling input?" );
5864           assert( !is_visited, "visit only once" );
5865           nstack.push(n, i);  // Save parent node and next input's index.
5866           nstack_top_n = in;  // Process current input now.
5867           nstack_top_i = 0;
5868           done = false;       // Not all n's inputs processed.
5869           break; // continue while_nstack_nonempty;
5870         } else if (!is_visited) {
5871           // This guy has a location picked out for him, but has not yet
5872           // been visited.  Happens to all CFG nodes, for instance.
5873           // Visit him using the worklist instead of recursion, to break
5874           // cycles.  Since he has a location already we do not need to
5875           // find his location before proceeding with the current Node.
5876           worklist.push(in);  // Visit this guy later, using worklist
5877         }
5878       }
5879       if (done) {
5880         // All of n's inputs have been processed, complete post-processing.
5881 
5882         // Compute earliest point this Node can go.
5883         // CFG, Phi, pinned nodes already know their controlling input.
5884         if (!has_node(n)) {
5885           // Record earliest legal location
5886           set_early_ctrl(n, false);
5887         }
5888         if (nstack.is_empty()) {
5889           // Finished all nodes on stack.
5890           // Process next node on the worklist.
5891           break;
5892         }
5893         // Get saved parent node and next input's index.
5894         nstack_top_n = nstack.node();
5895         nstack_top_i = nstack.index();
5896         nstack.pop();
5897       }
5898     } // while (true)
5899   }
5900 }
5901 
5902 //------------------------------dom_lca_internal--------------------------------
5903 // Pair-wise LCA
5904 Node *PhaseIdealLoop::dom_lca_internal( Node *n1, Node *n2 ) const {
5905   if( !n1 ) return n2;          // Handle null original LCA
5906   assert( n1->is_CFG(), "" );
5907   assert( n2->is_CFG(), "" );
5908   // find LCA of all uses
5909   uint d1 = dom_depth(n1);
5910   uint d2 = dom_depth(n2);
5911   while (n1 != n2) {
5912     if (d1 > d2) {
5913       n1 =      idom(n1);
5914       d1 = dom_depth(n1);
5915     } else if (d1 < d2) {
5916       n2 =      idom(n2);
5917       d2 = dom_depth(n2);
5918     } else {
5919       // Here d1 == d2.  Due to edits of the dominator-tree, sections
5920       // of the tree might have the same depth.  These sections have
5921       // to be searched more carefully.
5922 
5923       // Scan up all the n1's with equal depth, looking for n2.
5924       Node *t1 = idom(n1);
5925       while (dom_depth(t1) == d1) {
5926         if (t1 == n2)  return n2;
5927         t1 = idom(t1);
5928       }
5929       // Scan up all the n2's with equal depth, looking for n1.
5930       Node *t2 = idom(n2);
5931       while (dom_depth(t2) == d2) {
5932         if (t2 == n1)  return n1;
5933         t2 = idom(t2);
5934       }
5935       // Move up to a new dominator-depth value as well as up the dom-tree.
5936       n1 = t1;
5937       n2 = t2;
5938       d1 = dom_depth(n1);
5939       d2 = dom_depth(n2);
5940     }
5941   }
5942   return n1;
5943 }
5944 
5945 //------------------------------compute_idom-----------------------------------
5946 // Locally compute IDOM using dom_lca call.  Correct only if the incoming
5947 // IDOMs are correct.
5948 Node *PhaseIdealLoop::compute_idom( Node *region ) const {
5949   assert( region->is_Region(), "" );
5950   Node *LCA = nullptr;
5951   for( uint i = 1; i < region->req(); i++ ) {
5952     if( region->in(i) != C->top() )
5953       LCA = dom_lca( LCA, region->in(i) );
5954   }
5955   return LCA;
5956 }
5957 
5958 bool PhaseIdealLoop::verify_dominance(Node* n, Node* use, Node* LCA, Node* early) {
5959   bool had_error = false;
5960 #ifdef ASSERT
5961   if (early != C->root()) {
5962     // Make sure that there's a dominance path from LCA to early
5963     Node* d = LCA;
5964     while (d != early) {
5965       if (d == C->root()) {
5966         dump_bad_graph("Bad graph detected in compute_lca_of_uses", n, early, LCA);
5967         tty->print_cr("*** Use %d isn't dominated by def %d ***", use->_idx, n->_idx);
5968         had_error = true;
5969         break;
5970       }
5971       d = idom(d);
5972     }
5973   }
5974 #endif
5975   return had_error;
5976 }
5977 
5978 
5979 Node* PhaseIdealLoop::compute_lca_of_uses(Node* n, Node* early, bool verify) {
5980   // Compute LCA over list of uses
5981   bool had_error = false;
5982   Node *LCA = nullptr;
5983   for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax && LCA != early; i++) {
5984     Node* c = n->fast_out(i);
5985     if (_loop_or_ctrl[c->_idx] == nullptr)
5986       continue;                 // Skip the occasional dead node
5987     if( c->is_Phi() ) {         // For Phis, we must land above on the path
5988       for( uint j=1; j<c->req(); j++ ) {// For all inputs
5989         if( c->in(j) == n ) {   // Found matching input?
5990           Node *use = c->in(0)->in(j);
5991           if (_verify_only && use->is_top()) continue;
5992           LCA = dom_lca_for_get_late_ctrl( LCA, use, n );
5993           if (verify) had_error = verify_dominance(n, use, LCA, early) || had_error;
5994         }
5995       }
5996     } else {
5997       // For CFG data-users, use is in the block just prior
5998       Node *use = has_ctrl(c) ? get_ctrl(c) : c->in(0);
5999       LCA = dom_lca_for_get_late_ctrl( LCA, use, n );
6000       if (verify) had_error = verify_dominance(n, use, LCA, early) || had_error;
6001     }
6002   }
6003   assert(!had_error, "bad dominance");
6004   return LCA;
6005 }
6006 
6007 // Check the shape of the graph at the loop entry. In some cases,
6008 // the shape of the graph does not match the shape outlined below.
6009 // That is caused by the Opaque1 node "protecting" the shape of
6010 // the graph being removed by, for example, the IGVN performed
6011 // in PhaseIdealLoop::build_and_optimize().
6012 //
6013 // After the Opaque1 node has been removed, optimizations (e.g., split-if,
6014 // loop unswitching, and IGVN, or a combination of them) can freely change
6015 // the graph's shape. As a result, the graph shape outlined below cannot
6016 // be guaranteed anymore.
6017 Node* CountedLoopNode::is_canonical_loop_entry() {
6018   if (!is_main_loop() && !is_post_loop()) {
6019     return nullptr;
6020   }
6021   Node* ctrl = skip_assertion_predicates_with_halt();
6022 
6023   if (ctrl == nullptr || (!ctrl->is_IfTrue() && !ctrl->is_IfFalse())) {
6024     return nullptr;
6025   }
6026   Node* iffm = ctrl->in(0);
6027   if (iffm == nullptr || iffm->Opcode() != Op_If) {
6028     return nullptr;
6029   }
6030   Node* bolzm = iffm->in(1);
6031   if (bolzm == nullptr || !bolzm->is_Bool()) {
6032     return nullptr;
6033   }
6034   Node* cmpzm = bolzm->in(1);
6035   if (cmpzm == nullptr || !cmpzm->is_Cmp()) {
6036     return nullptr;
6037   }
6038 
6039   uint input = is_main_loop() ? 2 : 1;
6040   if (input >= cmpzm->req() || cmpzm->in(input) == nullptr) {
6041     return nullptr;
6042   }
6043   bool res = cmpzm->in(input)->Opcode() == Op_OpaqueZeroTripGuard;
6044 #ifdef ASSERT
6045   bool found_opaque = false;
6046   for (uint i = 1; i < cmpzm->req(); i++) {
6047     Node* opnd = cmpzm->in(i);
6048     if (opnd && opnd->is_Opaque1()) {
6049       found_opaque = true;
6050       break;
6051     }
6052   }
6053   assert(found_opaque == res, "wrong pattern");
6054 #endif
6055   return res ? cmpzm->in(input) : nullptr;
6056 }
6057 
6058 // Find pre loop end from main loop. Returns nullptr if none.
6059 CountedLoopEndNode* CountedLoopNode::find_pre_loop_end() {
6060   assert(is_main_loop(), "Can only find pre-loop from main-loop");
6061   // The loop cannot be optimized if the graph shape at the loop entry is
6062   // inappropriate.
6063   if (is_canonical_loop_entry() == nullptr) {
6064     return nullptr;
6065   }
6066 
6067   Node* p_f = skip_assertion_predicates_with_halt()->in(0)->in(0);
6068   if (!p_f->is_IfFalse() || !p_f->in(0)->is_CountedLoopEnd()) {
6069     return nullptr;
6070   }
6071   CountedLoopEndNode* pre_end = p_f->in(0)->as_CountedLoopEnd();
6072   CountedLoopNode* loop_node = pre_end->loopnode();
6073   if (loop_node == nullptr || !loop_node->is_pre_loop()) {
6074     return nullptr;
6075   }
6076   return pre_end;
6077 }
6078 
6079 //------------------------------get_late_ctrl----------------------------------
6080 // Compute latest legal control.
6081 Node *PhaseIdealLoop::get_late_ctrl( Node *n, Node *early ) {
6082   assert(early != nullptr, "early control should not be null");
6083 
6084   Node* LCA = compute_lca_of_uses(n, early);
6085 #ifdef ASSERT
6086   if (LCA == C->root() && LCA != early) {
6087     // def doesn't dominate uses so print some useful debugging output
6088     compute_lca_of_uses(n, early, true);
6089   }
6090 #endif
6091 
6092   if (n->is_Load() && LCA != early) {
6093     LCA = get_late_ctrl_with_anti_dep(n->as_Load(), early, LCA);
6094   }
6095 
6096   assert(LCA == find_non_split_ctrl(LCA), "unexpected late control");
6097   return LCA;
6098 }
6099 
6100 // if this is a load, check for anti-dependent stores
6101 // We use a conservative algorithm to identify potential interfering
6102 // instructions and for rescheduling the load.  The users of the memory
6103 // input of this load are examined.  Any use which is not a load and is
6104 // dominated by early is considered a potentially interfering store.
6105 // This can produce false positives.
6106 Node* PhaseIdealLoop::get_late_ctrl_with_anti_dep(LoadNode* n, Node* early, Node* LCA) {
6107   int load_alias_idx = C->get_alias_index(n->adr_type());
6108   if (C->alias_type(load_alias_idx)->is_rewritable()) {
6109     Unique_Node_List worklist;
6110 
6111     Node* mem = n->in(MemNode::Memory);
6112     for (DUIterator_Fast imax, i = mem->fast_outs(imax); i < imax; i++) {
6113       Node* s = mem->fast_out(i);
6114       worklist.push(s);
6115     }
6116     for (uint i = 0; i < worklist.size() && LCA != early; i++) {
6117       Node* s = worklist.at(i);
6118       if (s->is_Load() || s->Opcode() == Op_SafePoint ||
6119           (s->is_CallStaticJava() && s->as_CallStaticJava()->uncommon_trap_request() != 0) ||
6120           s->is_Phi()) {
6121         continue;
6122       } else if (s->is_MergeMem()) {
6123         for (DUIterator_Fast imax, i = s->fast_outs(imax); i < imax; i++) {
6124           Node* s1 = s->fast_out(i);
6125           worklist.push(s1);
6126         }
6127       } else {
6128         Node* sctrl = has_ctrl(s) ? get_ctrl(s) : s->in(0);
6129         assert(sctrl != nullptr || !s->is_reachable_from_root(), "must have control");
6130         if (sctrl != nullptr && !sctrl->is_top() && is_dominator(early, sctrl)) {
6131           const TypePtr* adr_type = s->adr_type();
6132           if (s->is_ArrayCopy()) {
6133             // Copy to known instance needs destination type to test for aliasing
6134             const TypePtr* dest_type = s->as_ArrayCopy()->_dest_type;
6135             if (dest_type != TypeOopPtr::BOTTOM) {
6136               adr_type = dest_type;
6137             }
6138           }
6139           if (C->can_alias(adr_type, load_alias_idx)) {
6140             LCA = dom_lca_for_get_late_ctrl(LCA, sctrl, n);
6141           } else if (s->is_CFG() && s->is_Multi()) {
6142             // Look for the memory use of s (that is the use of its memory projection)
6143             for (DUIterator_Fast imax, i = s->fast_outs(imax); i < imax; i++) {
6144               Node* s1 = s->fast_out(i);
6145               assert(s1->is_Proj(), "projection expected");
6146               if (_igvn.type(s1) == Type::MEMORY) {
6147                 for (DUIterator_Fast jmax, j = s1->fast_outs(jmax); j < jmax; j++) {
6148                   Node* s2 = s1->fast_out(j);
6149                   worklist.push(s2);
6150                 }
6151               }
6152             }
6153           }
6154         }
6155       }
6156     }
6157     // For Phis only consider Region's inputs that were reached by following the memory edges
6158     if (LCA != early) {
6159       for (uint i = 0; i < worklist.size(); i++) {
6160         Node* s = worklist.at(i);
6161         if (s->is_Phi() && C->can_alias(s->adr_type(), load_alias_idx)) {
6162           Node* r = s->in(0);
6163           for (uint j = 1; j < s->req(); j++) {
6164             Node* in = s->in(j);
6165             Node* r_in = r->in(j);
6166             // We can't reach any node from a Phi because we don't enqueue Phi's uses above
6167             if (((worklist.member(in) && !in->is_Phi()) || in == mem) && is_dominator(early, r_in)) {
6168               LCA = dom_lca_for_get_late_ctrl(LCA, r_in, n);
6169             }
6170           }
6171         }
6172       }
6173     }
6174   }
6175   return LCA;
6176 }
6177 
6178 // Is CFG node 'dominator' dominating node 'n'?
6179 bool PhaseIdealLoop::is_dominator(Node* dominator, Node* n) {
6180   if (dominator == n) {
6181     return true;
6182   }
6183   assert(dominator->is_CFG() && n->is_CFG(), "must have CFG nodes");
6184   uint dd = dom_depth(dominator);
6185   while (dom_depth(n) >= dd) {
6186     if (n == dominator) {
6187       return true;
6188     }
6189     n = idom(n);
6190   }
6191   return false;
6192 }
6193 
6194 // Is CFG node 'dominator' strictly dominating node 'n'?
6195 bool PhaseIdealLoop::is_strict_dominator(Node* dominator, Node* n) {
6196   return dominator != n && is_dominator(dominator, n);
6197 }
6198 
6199 //------------------------------dom_lca_for_get_late_ctrl_internal-------------
6200 // Pair-wise LCA with tags.
6201 // Tag each index with the node 'tag' currently being processed
6202 // before advancing up the dominator chain using idom().
6203 // Later calls that find a match to 'tag' know that this path has already
6204 // been considered in the current LCA (which is input 'n1' by convention).
6205 // Since get_late_ctrl() is only called once for each node, the tag array
6206 // does not need to be cleared between calls to get_late_ctrl().
6207 // Algorithm trades a larger constant factor for better asymptotic behavior
6208 //
6209 Node *PhaseIdealLoop::dom_lca_for_get_late_ctrl_internal(Node *n1, Node *n2, Node *tag_node) {
6210   uint d1 = dom_depth(n1);
6211   uint d2 = dom_depth(n2);
6212   jlong tag = tag_node->_idx | (((jlong)_dom_lca_tags_round) << 32);
6213 
6214   do {
6215     if (d1 > d2) {
6216       // current lca is deeper than n2
6217       _dom_lca_tags.at_put_grow(n1->_idx, tag);
6218       n1 =      idom(n1);
6219       d1 = dom_depth(n1);
6220     } else if (d1 < d2) {
6221       // n2 is deeper than current lca
6222       jlong memo = _dom_lca_tags.at_grow(n2->_idx, 0);
6223       if (memo == tag) {
6224         return n1;    // Return the current LCA
6225       }
6226       _dom_lca_tags.at_put_grow(n2->_idx, tag);
6227       n2 =      idom(n2);
6228       d2 = dom_depth(n2);
6229     } else {
6230       // Here d1 == d2.  Due to edits of the dominator-tree, sections
6231       // of the tree might have the same depth.  These sections have
6232       // to be searched more carefully.
6233 
6234       // Scan up all the n1's with equal depth, looking for n2.
6235       _dom_lca_tags.at_put_grow(n1->_idx, tag);
6236       Node *t1 = idom(n1);
6237       while (dom_depth(t1) == d1) {
6238         if (t1 == n2)  return n2;
6239         _dom_lca_tags.at_put_grow(t1->_idx, tag);
6240         t1 = idom(t1);
6241       }
6242       // Scan up all the n2's with equal depth, looking for n1.
6243       _dom_lca_tags.at_put_grow(n2->_idx, tag);
6244       Node *t2 = idom(n2);
6245       while (dom_depth(t2) == d2) {
6246         if (t2 == n1)  return n1;
6247         _dom_lca_tags.at_put_grow(t2->_idx, tag);
6248         t2 = idom(t2);
6249       }
6250       // Move up to a new dominator-depth value as well as up the dom-tree.
6251       n1 = t1;
6252       n2 = t2;
6253       d1 = dom_depth(n1);
6254       d2 = dom_depth(n2);
6255     }
6256   } while (n1 != n2);
6257   return n1;
6258 }
6259 
6260 //------------------------------init_dom_lca_tags------------------------------
6261 // Tag could be a node's integer index, 32bits instead of 64bits in some cases
6262 // Intended use does not involve any growth for the array, so it could
6263 // be of fixed size.
6264 void PhaseIdealLoop::init_dom_lca_tags() {
6265   uint limit = C->unique() + 1;
6266   _dom_lca_tags.at_grow(limit, 0);
6267   _dom_lca_tags_round = 0;
6268 #ifdef ASSERT
6269   for (uint i = 0; i < limit; ++i) {
6270     assert(_dom_lca_tags.at(i) == 0, "Must be distinct from each node pointer");
6271   }
6272 #endif // ASSERT
6273 }
6274 
6275 //------------------------------build_loop_late--------------------------------
6276 // Put Data nodes into some loop nest, by setting the _loop_or_ctrl[]->loop mapping.
6277 // Second pass finds latest legal placement, and ideal loop placement.
6278 void PhaseIdealLoop::build_loop_late( VectorSet &visited, Node_List &worklist, Node_Stack &nstack ) {
6279   while (worklist.size() != 0) {
6280     Node *n = worklist.pop();
6281     // Only visit once
6282     if (visited.test_set(n->_idx)) continue;
6283     uint cnt = n->outcnt();
6284     uint   i = 0;
6285     while (true) {
6286       assert(_loop_or_ctrl[n->_idx], "no dead nodes");
6287       // Visit all children
6288       if (i < cnt) {
6289         Node* use = n->raw_out(i);
6290         ++i;
6291         // Check for dead uses.  Aggressively prune such junk.  It might be
6292         // dead in the global sense, but still have local uses so I cannot
6293         // easily call 'remove_dead_node'.
6294         if (_loop_or_ctrl[use->_idx] != nullptr || use->is_top()) { // Not dead?
6295           // Due to cycles, we might not hit the same fixed point in the verify
6296           // pass as we do in the regular pass.  Instead, visit such phis as
6297           // simple uses of the loop head.
6298           if( use->in(0) && (use->is_CFG() || use->is_Phi()) ) {
6299             if( !visited.test(use->_idx) )
6300               worklist.push(use);
6301           } else if( !visited.test_set(use->_idx) ) {
6302             nstack.push(n, i); // Save parent and next use's index.
6303             n   = use;         // Process all children of current use.
6304             cnt = use->outcnt();
6305             i   = 0;
6306           }
6307         } else {
6308           // Do not visit around the backedge of loops via data edges.
6309           // push dead code onto a worklist
6310           _deadlist.push(use);
6311         }
6312       } else {
6313         // All of n's children have been processed, complete post-processing.
6314         build_loop_late_post(n);
6315         if (C->failing()) { return; }
6316         if (nstack.is_empty()) {
6317           // Finished all nodes on stack.
6318           // Process next node on the worklist.
6319           break;
6320         }
6321         // Get saved parent node and next use's index. Visit the rest of uses.
6322         n   = nstack.node();
6323         cnt = n->outcnt();
6324         i   = nstack.index();
6325         nstack.pop();
6326       }
6327     }
6328   }
6329 }
6330 
6331 // Verify that no data node is scheduled in the outer loop of a strip
6332 // mined loop.
6333 void PhaseIdealLoop::verify_strip_mined_scheduling(Node *n, Node* least) {
6334 #ifdef ASSERT
6335   if (get_loop(least)->_nest == 0) {
6336     return;
6337   }
6338   IdealLoopTree* loop = get_loop(least);
6339   Node* head = loop->_head;
6340   if (head->is_OuterStripMinedLoop() &&
6341       // Verification can't be applied to fully built strip mined loops
6342       head->as_Loop()->outer_loop_end()->in(1)->find_int_con(-1) == 0) {
6343     Node* sfpt = head->as_Loop()->outer_safepoint();
6344     ResourceMark rm;
6345     Unique_Node_List wq;
6346     wq.push(sfpt);
6347     for (uint i = 0; i < wq.size(); i++) {
6348       Node *m = wq.at(i);
6349       for (uint i = 1; i < m->req(); i++) {
6350         Node* nn = m->in(i);
6351         if (nn == n) {
6352           return;
6353         }
6354         if (nn != nullptr && has_ctrl(nn) && get_loop(get_ctrl(nn)) == loop) {
6355           wq.push(nn);
6356         }
6357       }
6358     }
6359     ShouldNotReachHere();
6360   }
6361 #endif
6362 }
6363 
6364 
6365 //------------------------------build_loop_late_post---------------------------
6366 // Put Data nodes into some loop nest, by setting the _loop_or_ctrl[]->loop mapping.
6367 // Second pass finds latest legal placement, and ideal loop placement.
6368 void PhaseIdealLoop::build_loop_late_post(Node *n) {
6369   build_loop_late_post_work(n, true);
6370 }
6371 
6372 // Class to visit all predicates in a predicate chain to find out which are dominated by a given node. Keeps track of
6373 // the entry to the earliest predicate that is still dominated by the given dominator. This class is used when trying to
6374 // legally skip all predicates when figuring out the latest placement such that a node does not interfere with Loop
6375 // Predication or creating a Loop Limit Check Predicate later.
6376 class DominatedPredicates : public UnifiedPredicateVisitor {
6377   Node* const _dominator;
6378   Node* _earliest_dominated_predicate_entry;
6379   bool _should_continue;
6380   PhaseIdealLoop* const _phase;
6381 
6382  public:
6383   DominatedPredicates(Node* dominator, Node* start_node, PhaseIdealLoop* phase)
6384       : _dominator(dominator),
6385         _earliest_dominated_predicate_entry(start_node),
6386         _should_continue(true),
6387         _phase(phase) {}
6388   NONCOPYABLE(DominatedPredicates);
6389 
6390   bool should_continue() const override {
6391     return _should_continue;
6392   }
6393 
6394   // Returns the entry to the earliest predicate that is still dominated by the given dominator (all could be dominated).
6395   Node* earliest_dominated_predicate_entry() const {
6396     return _earliest_dominated_predicate_entry;
6397   }
6398 
6399   void visit_predicate(const Predicate& predicate) override {
6400     Node* entry = predicate.entry();
6401     if (_phase->is_strict_dominator(entry, _dominator)) {
6402       _should_continue = false;
6403     } else {
6404       _earliest_dominated_predicate_entry = entry;
6405     }
6406   }
6407 };
6408 
6409 void PhaseIdealLoop::build_loop_late_post_work(Node *n, bool pinned) {
6410 
6411   if (n->req() == 2 && (n->Opcode() == Op_ConvI2L || n->Opcode() == Op_CastII) && !C->major_progress() && !_verify_only) {
6412     _igvn._worklist.push(n);  // Maybe we'll normalize it, if no more loops.
6413   }
6414 
6415 #ifdef ASSERT
6416   if (_verify_only && !n->is_CFG()) {
6417     // Check def-use domination.
6418     // We would like to expose this check in product but it appears to be expensive.
6419     compute_lca_of_uses(n, get_ctrl(n), true /* verify */);
6420   }
6421 #endif
6422 
6423   // CFG and pinned nodes already handled
6424   if( n->in(0) ) {
6425     if( n->in(0)->is_top() ) return; // Dead?
6426 
6427     // We'd like +VerifyLoopOptimizations to not believe that Mod's/Loads
6428     // _must_ be pinned (they have to observe their control edge of course).
6429     // Unlike Stores (which modify an unallocable resource, the memory
6430     // state), Mods/Loads can float around.  So free them up.
6431     switch( n->Opcode() ) {
6432     case Op_DivI:
6433     case Op_DivF:
6434     case Op_DivD:
6435     case Op_ModI:
6436     case Op_ModF:
6437     case Op_ModD:
6438     case Op_LoadB:              // Same with Loads; they can sink
6439     case Op_LoadUB:             // during loop optimizations.
6440     case Op_LoadUS:
6441     case Op_LoadD:
6442     case Op_LoadF:
6443     case Op_LoadI:
6444     case Op_LoadKlass:
6445     case Op_LoadNKlass:
6446     case Op_LoadL:
6447     case Op_LoadS:
6448     case Op_LoadP:
6449     case Op_LoadN:
6450     case Op_LoadRange:
6451     case Op_LoadD_unaligned:
6452     case Op_LoadL_unaligned:
6453     case Op_StrComp:            // Does a bunch of load-like effects
6454     case Op_StrEquals:
6455     case Op_StrIndexOf:
6456     case Op_StrIndexOfChar:
6457     case Op_AryEq:
6458     case Op_VectorizedHashCode:
6459     case Op_CountPositives:
6460       pinned = false;
6461     }
6462     if (n->is_CMove() || n->is_ConstraintCast()) {
6463       pinned = false;
6464     }
6465     if( pinned ) {
6466       IdealLoopTree *chosen_loop = get_loop(n->is_CFG() ? n : get_ctrl(n));
6467       if( !chosen_loop->_child )       // Inner loop?
6468         chosen_loop->_body.push(n); // Collect inner loops
6469       return;
6470     }
6471   } else {                      // No slot zero
6472     if( n->is_CFG() ) {         // CFG with no slot 0 is dead
6473       _loop_or_ctrl.map(n->_idx,nullptr); // No block setting, it's globally dead
6474       return;
6475     }
6476     assert(!n->is_CFG() || n->outcnt() == 0, "");
6477   }
6478 
6479   // Do I have a "safe range" I can select over?
6480   Node *early = get_ctrl(n);// Early location already computed
6481 
6482   // Compute latest point this Node can go
6483   Node *LCA = get_late_ctrl( n, early );
6484   // LCA is null due to uses being dead
6485   if( LCA == nullptr ) {
6486 #ifdef ASSERT
6487     for (DUIterator i1 = n->outs(); n->has_out(i1); i1++) {
6488       assert(_loop_or_ctrl[n->out(i1)->_idx] == nullptr, "all uses must also be dead");
6489     }
6490 #endif
6491     _loop_or_ctrl.map(n->_idx, nullptr); // This node is useless
6492     _deadlist.push(n);
6493     return;
6494   }
6495   assert(LCA != nullptr && !LCA->is_top(), "no dead nodes");
6496 
6497   Node *legal = LCA;            // Walk 'legal' up the IDOM chain
6498   Node *least = legal;          // Best legal position so far
6499   while( early != legal ) {     // While not at earliest legal
6500     if (legal->is_Start() && !early->is_Root()) {
6501 #ifdef ASSERT
6502       // Bad graph. Print idom path and fail.
6503       dump_bad_graph("Bad graph detected in build_loop_late", n, early, LCA);
6504       assert(false, "Bad graph detected in build_loop_late");
6505 #endif
6506       C->record_method_not_compilable("Bad graph detected in build_loop_late");
6507       return;
6508     }
6509     // Find least loop nesting depth
6510     legal = idom(legal);        // Bump up the IDOM tree
6511     // Check for lower nesting depth
6512     if( get_loop(legal)->_nest < get_loop(least)->_nest )
6513       least = legal;
6514   }
6515   assert(early == legal || legal != C->root(), "bad dominance of inputs");
6516 
6517   if (least != early) {
6518     // Move the node above predicates as far up as possible so a
6519     // following pass of Loop Predication doesn't hoist a predicate
6520     // that depends on it above that node.
6521     const PredicateIterator predicate_iterator(least);
6522     DominatedPredicates dominated_predicates(early, least, this);
6523     predicate_iterator.for_each(dominated_predicates);
6524     least = dominated_predicates.earliest_dominated_predicate_entry();
6525   }
6526   // Try not to place code on a loop entry projection
6527   // which can inhibit range check elimination.
6528   if (least != early && !BarrierSet::barrier_set()->barrier_set_c2()->is_gc_specific_loop_opts_pass(_mode)) {
6529     Node* ctrl_out = least->unique_ctrl_out_or_null();
6530     if (ctrl_out != nullptr && ctrl_out->is_Loop() &&
6531         least == ctrl_out->in(LoopNode::EntryControl) &&
6532         (ctrl_out->is_CountedLoop() || ctrl_out->is_OuterStripMinedLoop())) {
6533       Node* least_dom = idom(least);
6534       if (get_loop(least_dom)->is_member(get_loop(least))) {
6535         least = least_dom;
6536       }
6537     }
6538   }
6539   // Don't extend live ranges of raw oops
6540   if (least != early && n->is_ConstraintCast() && n->in(1)->bottom_type()->isa_rawptr() &&
6541       !n->bottom_type()->isa_rawptr()) {
6542     least = early;
6543   }
6544 
6545 #ifdef ASSERT
6546   // Broken part of VerifyLoopOptimizations (F)
6547   // Reason:
6548   //   _verify_me->get_ctrl_no_update(n) seems to return wrong result
6549   /*
6550   // If verifying, verify that 'verify_me' has a legal location
6551   // and choose it as our location.
6552   if( _verify_me ) {
6553     Node *v_ctrl = _verify_me->get_ctrl_no_update(n);
6554     Node *legal = LCA;
6555     while( early != legal ) {   // While not at earliest legal
6556       if( legal == v_ctrl ) break;  // Check for prior good location
6557       legal = idom(legal)      ;// Bump up the IDOM tree
6558     }
6559     // Check for prior good location
6560     if( legal == v_ctrl ) least = legal; // Keep prior if found
6561   }
6562   */
6563 #endif
6564 
6565   // Assign discovered "here or above" point
6566   least = find_non_split_ctrl(least);
6567   verify_strip_mined_scheduling(n, least);
6568   set_ctrl(n, least);
6569 
6570   // Collect inner loop bodies
6571   IdealLoopTree *chosen_loop = get_loop(least);
6572   if( !chosen_loop->_child )   // Inner loop?
6573     chosen_loop->_body.push(n);// Collect inner loops
6574 
6575   if (!_verify_only && n->Opcode() == Op_OpaqueZeroTripGuard) {
6576     _zero_trip_guard_opaque_nodes.push(n);
6577   }
6578 
6579 }
6580 
6581 #ifdef ASSERT
6582 void PhaseIdealLoop::dump_bad_graph(const char* msg, Node* n, Node* early, Node* LCA) {
6583   tty->print_cr("%s", msg);
6584   tty->print("n: "); n->dump();
6585   tty->print("early(n): "); early->dump();
6586   if (n->in(0) != nullptr  && !n->in(0)->is_top() &&
6587       n->in(0) != early && !n->in(0)->is_Root()) {
6588     tty->print("n->in(0): "); n->in(0)->dump();
6589   }
6590   for (uint i = 1; i < n->req(); i++) {
6591     Node* in1 = n->in(i);
6592     if (in1 != nullptr && in1 != n && !in1->is_top()) {
6593       tty->print("n->in(%d): ", i); in1->dump();
6594       Node* in1_early = get_ctrl(in1);
6595       tty->print("early(n->in(%d)): ", i); in1_early->dump();
6596       if (in1->in(0) != nullptr     && !in1->in(0)->is_top() &&
6597           in1->in(0) != in1_early && !in1->in(0)->is_Root()) {
6598         tty->print("n->in(%d)->in(0): ", i); in1->in(0)->dump();
6599       }
6600       for (uint j = 1; j < in1->req(); j++) {
6601         Node* in2 = in1->in(j);
6602         if (in2 != nullptr && in2 != n && in2 != in1 && !in2->is_top()) {
6603           tty->print("n->in(%d)->in(%d): ", i, j); in2->dump();
6604           Node* in2_early = get_ctrl(in2);
6605           tty->print("early(n->in(%d)->in(%d)): ", i, j); in2_early->dump();
6606           if (in2->in(0) != nullptr     && !in2->in(0)->is_top() &&
6607               in2->in(0) != in2_early && !in2->in(0)->is_Root()) {
6608             tty->print("n->in(%d)->in(%d)->in(0): ", i, j); in2->in(0)->dump();
6609           }
6610         }
6611       }
6612     }
6613   }
6614   tty->cr();
6615   tty->print("LCA(n): "); LCA->dump();
6616   for (uint i = 0; i < n->outcnt(); i++) {
6617     Node* u1 = n->raw_out(i);
6618     if (u1 == n)
6619       continue;
6620     tty->print("n->out(%d): ", i); u1->dump();
6621     if (u1->is_CFG()) {
6622       for (uint j = 0; j < u1->outcnt(); j++) {
6623         Node* u2 = u1->raw_out(j);
6624         if (u2 != u1 && u2 != n && u2->is_CFG()) {
6625           tty->print("n->out(%d)->out(%d): ", i, j); u2->dump();
6626         }
6627       }
6628     } else {
6629       Node* u1_later = get_ctrl(u1);
6630       tty->print("later(n->out(%d)): ", i); u1_later->dump();
6631       if (u1->in(0) != nullptr     && !u1->in(0)->is_top() &&
6632           u1->in(0) != u1_later && !u1->in(0)->is_Root()) {
6633         tty->print("n->out(%d)->in(0): ", i); u1->in(0)->dump();
6634       }
6635       for (uint j = 0; j < u1->outcnt(); j++) {
6636         Node* u2 = u1->raw_out(j);
6637         if (u2 == n || u2 == u1)
6638           continue;
6639         tty->print("n->out(%d)->out(%d): ", i, j); u2->dump();
6640         if (!u2->is_CFG()) {
6641           Node* u2_later = get_ctrl(u2);
6642           tty->print("later(n->out(%d)->out(%d)): ", i, j); u2_later->dump();
6643           if (u2->in(0) != nullptr     && !u2->in(0)->is_top() &&
6644               u2->in(0) != u2_later && !u2->in(0)->is_Root()) {
6645             tty->print("n->out(%d)->in(0): ", i); u2->in(0)->dump();
6646           }
6647         }
6648       }
6649     }
6650   }
6651   dump_idoms(early, LCA);
6652   tty->cr();
6653 }
6654 
6655 // Class to compute the real LCA given an early node and a wrong LCA in a bad graph.
6656 class RealLCA {
6657   const PhaseIdealLoop* _phase;
6658   Node* _early;
6659   Node* _wrong_lca;
6660   uint _early_index;
6661   int _wrong_lca_index;
6662 
6663   // Given idom chains of early and wrong LCA: Walk through idoms starting at StartNode and find the first node which
6664   // is different: Return the previously visited node which must be the real LCA.
6665   // The node lists also contain _early and _wrong_lca, respectively.
6666   Node* find_real_lca(Unique_Node_List& early_with_idoms, Unique_Node_List& wrong_lca_with_idoms) {
6667     int early_index = early_with_idoms.size() - 1;
6668     int wrong_lca_index = wrong_lca_with_idoms.size() - 1;
6669     bool found_difference = false;
6670     do {
6671       if (early_with_idoms[early_index] != wrong_lca_with_idoms[wrong_lca_index]) {
6672         // First time early and wrong LCA idoms differ. Real LCA must be at the previous index.
6673         found_difference = true;
6674         break;
6675       }
6676       early_index--;
6677       wrong_lca_index--;
6678     } while (wrong_lca_index >= 0);
6679 
6680     assert(early_index >= 0, "must always find an LCA - cannot be early");
6681     _early_index = early_index;
6682     _wrong_lca_index = wrong_lca_index;
6683     Node* real_lca = early_with_idoms[_early_index + 1]; // Plus one to skip _early.
6684     assert(found_difference || real_lca == _wrong_lca, "wrong LCA dominates early and is therefore the real LCA");
6685     return real_lca;
6686   }
6687 
6688   void dump(Node* real_lca) {
6689     tty->cr();
6690     tty->print_cr("idoms of early \"%d %s\":", _early->_idx, _early->Name());
6691     _phase->dump_idom(_early, _early_index + 1);
6692 
6693     tty->cr();
6694     tty->print_cr("idoms of (wrong) LCA \"%d %s\":", _wrong_lca->_idx, _wrong_lca->Name());
6695     _phase->dump_idom(_wrong_lca, _wrong_lca_index + 1);
6696 
6697     tty->cr();
6698     tty->print("Real LCA of early \"%d %s\" (idom[%d]) and wrong LCA \"%d %s\"",
6699                _early->_idx, _early->Name(), _early_index, _wrong_lca->_idx, _wrong_lca->Name());
6700     if (_wrong_lca_index >= 0) {
6701       tty->print(" (idom[%d])", _wrong_lca_index);
6702     }
6703     tty->print_cr(":");
6704     real_lca->dump();
6705   }
6706 
6707  public:
6708   RealLCA(const PhaseIdealLoop* phase, Node* early, Node* wrong_lca)
6709       : _phase(phase), _early(early), _wrong_lca(wrong_lca), _early_index(0), _wrong_lca_index(0) {
6710     assert(!wrong_lca->is_Start(), "StartNode is always a common dominator");
6711   }
6712 
6713   void compute_and_dump() {
6714     ResourceMark rm;
6715     Unique_Node_List early_with_idoms;
6716     Unique_Node_List wrong_lca_with_idoms;
6717     early_with_idoms.push(_early);
6718     wrong_lca_with_idoms.push(_wrong_lca);
6719     _phase->get_idoms(_early, 10000, early_with_idoms);
6720     _phase->get_idoms(_wrong_lca, 10000, wrong_lca_with_idoms);
6721     Node* real_lca = find_real_lca(early_with_idoms, wrong_lca_with_idoms);
6722     dump(real_lca);
6723   }
6724 };
6725 
6726 // Dump the idom chain of early, of the wrong LCA and dump the real LCA of early and wrong LCA.
6727 void PhaseIdealLoop::dump_idoms(Node* early, Node* wrong_lca) {
6728   assert(!is_dominator(early, wrong_lca), "sanity check that early does not dominate wrong lca");
6729   assert(!has_ctrl(early) && !has_ctrl(wrong_lca), "sanity check, no data nodes");
6730 
6731   RealLCA real_lca(this, early, wrong_lca);
6732   real_lca.compute_and_dump();
6733 }
6734 #endif // ASSERT
6735 
6736 #ifndef PRODUCT
6737 //------------------------------dump-------------------------------------------
6738 void PhaseIdealLoop::dump() const {
6739   ResourceMark rm;
6740   Node_Stack stack(C->live_nodes() >> 2);
6741   Node_List rpo_list;
6742   VectorSet visited;
6743   visited.set(C->top()->_idx);
6744   rpo(C->root(), stack, visited, rpo_list);
6745   // Dump root loop indexed by last element in PO order
6746   dump(_ltree_root, rpo_list.size(), rpo_list);
6747 }
6748 
6749 void PhaseIdealLoop::dump(IdealLoopTree* loop, uint idx, Node_List &rpo_list) const {
6750   loop->dump_head();
6751 
6752   // Now scan for CFG nodes in the same loop
6753   for (uint j = idx; j > 0; j--) {
6754     Node* n = rpo_list[j-1];
6755     if (!_loop_or_ctrl[n->_idx])      // Skip dead nodes
6756       continue;
6757 
6758     if (get_loop(n) != loop) { // Wrong loop nest
6759       if (get_loop(n)->_head == n &&    // Found nested loop?
6760           get_loop(n)->_parent == loop)
6761         dump(get_loop(n), rpo_list.size(), rpo_list);     // Print it nested-ly
6762       continue;
6763     }
6764 
6765     // Dump controlling node
6766     tty->sp(2 * loop->_nest);
6767     tty->print("C");
6768     if (n == C->root()) {
6769       n->dump();
6770     } else {
6771       Node* cached_idom   = idom_no_update(n);
6772       Node* computed_idom = n->in(0);
6773       if (n->is_Region()) {
6774         computed_idom = compute_idom(n);
6775         // computed_idom() will return n->in(0) when idom(n) is an IfNode (or
6776         // any MultiBranch ctrl node), so apply a similar transform to
6777         // the cached idom returned from idom_no_update.
6778         cached_idom = find_non_split_ctrl(cached_idom);
6779       }
6780       tty->print(" ID:%d", computed_idom->_idx);
6781       n->dump();
6782       if (cached_idom != computed_idom) {
6783         tty->print_cr("*** BROKEN IDOM!  Computed as: %d, cached as: %d",
6784                       computed_idom->_idx, cached_idom->_idx);
6785       }
6786     }
6787     // Dump nodes it controls
6788     for (uint k = 0; k < _loop_or_ctrl.max(); k++) {
6789       // (k < C->unique() && get_ctrl(find(k)) == n)
6790       if (k < C->unique() && _loop_or_ctrl[k] == (Node*)((intptr_t)n + 1)) {
6791         Node* m = C->root()->find(k);
6792         if (m && m->outcnt() > 0) {
6793           if (!(has_ctrl(m) && get_ctrl_no_update(m) == n)) {
6794             tty->print_cr("*** BROKEN CTRL ACCESSOR!  _loop_or_ctrl[k] is %p, ctrl is %p",
6795                           _loop_or_ctrl[k], has_ctrl(m) ? get_ctrl_no_update(m) : nullptr);
6796           }
6797           tty->sp(2 * loop->_nest + 1);
6798           m->dump();
6799         }
6800       }
6801     }
6802   }
6803 }
6804 
6805 void PhaseIdealLoop::dump_idom(Node* n, const uint count) const {
6806   if (has_ctrl(n)) {
6807     tty->print_cr("No idom for data nodes");
6808   } else {
6809     ResourceMark rm;
6810     Unique_Node_List idoms;
6811     get_idoms(n, count, idoms);
6812     dump_idoms_in_reverse(n, idoms);
6813   }
6814 }
6815 
6816 void PhaseIdealLoop::get_idoms(Node* n, const uint count, Unique_Node_List& idoms) const {
6817   Node* next = n;
6818   for (uint i = 0; !next->is_Start() && i < count; i++) {
6819     next = idom(next);
6820     assert(!idoms.member(next), "duplicated idom is not possible");
6821     idoms.push(next);
6822   }
6823 }
6824 
6825 void PhaseIdealLoop::dump_idoms_in_reverse(const Node* n, const Node_List& idom_list) const {
6826   Node* next;
6827   uint padding = 3;
6828   uint node_index_padding_width = static_cast<int>(log10(static_cast<double>(C->unique()))) + 1;
6829   for (int i = idom_list.size() - 1; i >= 0; i--) {
6830     if (i == 9 || i == 99) {
6831       padding++;
6832     }
6833     next = idom_list[i];
6834     tty->print_cr("idom[%d]:%*c%*d  %s", i, padding, ' ', node_index_padding_width, next->_idx, next->Name());
6835   }
6836   tty->print_cr("n:      %*c%*d  %s", padding, ' ', node_index_padding_width, n->_idx, n->Name());
6837 }
6838 #endif // NOT PRODUCT
6839 
6840 // Collect a R-P-O for the whole CFG.
6841 // Result list is in post-order (scan backwards for RPO)
6842 void PhaseIdealLoop::rpo(Node* start, Node_Stack &stk, VectorSet &visited, Node_List &rpo_list) const {
6843   stk.push(start, 0);
6844   visited.set(start->_idx);
6845 
6846   while (stk.is_nonempty()) {
6847     Node* m   = stk.node();
6848     uint  idx = stk.index();
6849     if (idx < m->outcnt()) {
6850       stk.set_index(idx + 1);
6851       Node* n = m->raw_out(idx);
6852       if (n->is_CFG() && !visited.test_set(n->_idx)) {
6853         stk.push(n, 0);
6854       }
6855     } else {
6856       rpo_list.push(m);
6857       stk.pop();
6858     }
6859   }
6860 }
6861 
6862 ConINode* PhaseIdealLoop::intcon(jint i) {
6863   ConINode* node = _igvn.intcon(i);
6864   set_root_as_ctrl(node);
6865   return node;
6866 }
6867 
6868 ConLNode* PhaseIdealLoop::longcon(jlong i) {
6869   ConLNode* node = _igvn.longcon(i);
6870   set_root_as_ctrl(node);
6871   return node;
6872 }
6873 
6874 ConNode* PhaseIdealLoop::makecon(const Type* t) {
6875   ConNode* node = _igvn.makecon(t);
6876   set_root_as_ctrl(node);
6877   return node;
6878 }
6879 
6880 ConNode* PhaseIdealLoop::integercon(jlong l, BasicType bt) {
6881   ConNode* node = _igvn.integercon(l, bt);
6882   set_root_as_ctrl(node);
6883   return node;
6884 }
6885 
6886 ConNode* PhaseIdealLoop::zerocon(BasicType bt) {
6887   ConNode* node = _igvn.zerocon(bt);
6888   set_root_as_ctrl(node);
6889   return node;
6890 }
6891 
6892 
6893 //=============================================================================
6894 //------------------------------LoopTreeIterator-------------------------------
6895 
6896 // Advance to next loop tree using a preorder, left-to-right traversal.
6897 void LoopTreeIterator::next() {
6898   assert(!done(), "must not be done.");
6899   if (_curnt->_child != nullptr) {
6900     _curnt = _curnt->_child;
6901   } else if (_curnt->_next != nullptr) {
6902     _curnt = _curnt->_next;
6903   } else {
6904     while (_curnt != _root && _curnt->_next == nullptr) {
6905       _curnt = _curnt->_parent;
6906     }
6907     if (_curnt == _root) {
6908       _curnt = nullptr;
6909       assert(done(), "must be done.");
6910     } else {
6911       assert(_curnt->_next != nullptr, "must be more to do");
6912       _curnt = _curnt->_next;
6913     }
6914   }
6915 }