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