1 /*
   2  * Copyright (c) 1999, 2026, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "gc/shared/barrierSet.hpp"
  26 #include "gc/shared/c2/barrierSetC2.hpp"
  27 #include "memory/allocation.inline.hpp"
  28 #include "memory/resourceArea.hpp"
  29 #include "opto/addnode.hpp"
  30 #include "opto/callnode.hpp"
  31 #include "opto/castnode.hpp"
  32 #include "opto/connode.hpp"
  33 #include "opto/divnode.hpp"
  34 #include "opto/loopnode.hpp"
  35 #include "opto/matcher.hpp"
  36 #include "opto/movenode.hpp"
  37 #include "opto/mulnode.hpp"
  38 #include "opto/opaquenode.hpp"
  39 #include "opto/rootnode.hpp"
  40 #include "opto/subnode.hpp"
  41 #include "opto/subtypenode.hpp"
  42 #include "opto/superword.hpp"
  43 #include "opto/vectornode.hpp"
  44 #include "utilities/checkedCast.hpp"
  45 #include "utilities/macros.hpp"
  46 
  47 //=============================================================================
  48 //------------------------------split_thru_phi---------------------------------
  49 // Split Node 'n' through merge point if there is enough win.
  50 Node* PhaseIdealLoop::split_thru_phi(Node* n, Node* region, int policy) {
  51   if ((n->Opcode() == Op_ConvI2L && n->bottom_type() != TypeLong::LONG) ||
  52       (n->Opcode() == Op_ConvL2I && n->bottom_type() != TypeInt::INT)) {
  53     // ConvI2L/ConvL2I may have type information on it which is unsafe to push up
  54     // so disable this for now
  55     return nullptr;
  56   }
  57 
  58   // Splitting range check CastIIs through a loop induction Phi can
  59   // cause new Phis to be created that are left unrelated to the loop
  60   // induction Phi and prevent optimizations (vectorization)
  61   if (n->Opcode() == Op_CastII && region->is_CountedLoop() &&
  62       n->in(1) == region->as_CountedLoop()->phi()) {
  63     return nullptr;
  64   }
  65 
  66   if (cannot_split_division(n, region)) {
  67     return nullptr;
  68   }
  69 
  70   SplitThruPhiWins wins(region);
  71   assert(!n->is_CFG(), "");
  72   assert(region->is_Region(), "");
  73 
  74   const Type* type = n->bottom_type();
  75   const TypeOopPtr* t_oop = _igvn.type(n)->isa_oopptr();
  76   Node* phi;
  77   if (t_oop != nullptr && t_oop->is_known_instance_field()) {
  78     int iid    = t_oop->instance_id();
  79     int index  = C->get_alias_index(t_oop);
  80     int offset = t_oop->offset();
  81     phi = new PhiNode(region, type, nullptr, iid, index, offset);
  82   } else {
  83     phi = PhiNode::make_blank(region, n);
  84   }
  85   uint old_unique = C->unique();
  86   for (uint i = 1; i < region->req(); i++) {
  87     Node* x;
  88     Node* the_clone = nullptr;
  89     if (region->in(i) == C->top()) {
  90       x = C->top();             // Dead path?  Use a dead data op
  91     } else {
  92       x = n->clone();           // Else clone up the data op
  93       the_clone = x;            // Remember for possible deletion.
  94       // Alter data node to use pre-phi inputs
  95       if (n->in(0) == region)
  96         x->set_req( 0, region->in(i) );
  97       for (uint j = 1; j < n->req(); j++) {
  98         Node* in = n->in(j);
  99         if (in->is_Phi() && in->in(0) == region)
 100           x->set_req(j, in->in(i)); // Use pre-Phi input for the clone
 101       }
 102     }
 103     // Check for a 'win' on some paths
 104     const Type* t = x->Value(&_igvn);
 105 
 106     bool singleton = t->singleton();
 107 
 108     // A TOP singleton indicates that there are no possible values incoming
 109     // along a particular edge. In most cases, this is OK, and the Phi will
 110     // be eliminated later in an Ideal call. However, we can't allow this to
 111     // happen if the singleton occurs on loop entry, as the elimination of
 112     // the PhiNode may cause the resulting node to migrate back to a previous
 113     // loop iteration.
 114     if (singleton && t == Type::TOP) {
 115       // Is_Loop() == false does not confirm the absence of a loop (e.g., an
 116       // irreducible loop may not be indicated by an affirmative is_Loop());
 117       // therefore, the only top we can split thru a phi is on a backedge of
 118       // a loop.
 119       singleton &= region->is_Loop() && (i != LoopNode::EntryControl);
 120     }
 121 
 122     if (singleton) {
 123       wins.add_win(i);
 124       x = makecon(t);
 125     } else {
 126       // We now call Identity to try to simplify the cloned node.
 127       // Note that some Identity methods call phase->type(this).
 128       // Make sure that the type array is big enough for
 129       // our new node, even though we may throw the node away.
 130       // (Note: This tweaking with igvn only works because x is a new node.)
 131       _igvn.set_type(x, t);
 132       // If x is a TypeNode, capture any more-precise type permanently into Node
 133       // otherwise it will be not updated during igvn->transform since
 134       // igvn->type(x) is set to x->Value() already.
 135       x->raise_bottom_type(t);
 136       Node* y = x->Identity(&_igvn);
 137       if (y != x) {
 138         wins.add_win(i);
 139         x = y;
 140       } else {
 141         y = _igvn.hash_find(x);
 142         if (y == nullptr) {
 143           y = similar_subtype_check(x, region->in(i));
 144         }
 145         if (y) {
 146           wins.add_win(i);
 147           x = y;
 148         } else {
 149           // Else x is a new node we are keeping
 150           // We do not need register_new_node_with_optimizer
 151           // because set_type has already been called.
 152           _igvn._worklist.push(x);
 153         }
 154       }
 155     }
 156 
 157     phi->set_req( i, x );
 158 
 159     if (the_clone == nullptr) {
 160       continue;
 161     }
 162 
 163     if (the_clone != x) {
 164       _igvn.remove_dead_node(the_clone, PhaseIterGVN::NodeOrigin::Speculative);
 165     } else if (region->is_Loop() && i == LoopNode::LoopBackControl &&
 166                n->is_Load() && can_move_to_inner_loop(n, region->as_Loop(), x)) {
 167       // it is not a win if 'x' moved from an outer to an inner loop
 168       // this edge case can only happen for Load nodes
 169       wins.reset();
 170       break;
 171     }
 172   }
 173   // Too few wins?
 174   if (!wins.profitable(policy)) {
 175     _igvn.remove_dead_node(phi, PhaseIterGVN::NodeOrigin::Speculative);
 176     return nullptr;
 177   }
 178 
 179   // Record Phi
 180   register_new_node( phi, region );
 181 
 182   for (uint i2 = 1; i2 < phi->req(); i2++) {
 183     Node *x = phi->in(i2);
 184     // If we commoned up the cloned 'x' with another existing Node,
 185     // the existing Node picks up a new use.  We need to make the
 186     // existing Node occur higher up so it dominates its uses.
 187     Node *old_ctrl;
 188     IdealLoopTree *old_loop;
 189 
 190     if (x->is_Con()) {
 191       assert(get_ctrl(x) == C->root(), "constant control is not root");
 192       continue;
 193     }
 194     // The occasional new node
 195     if (x->_idx >= old_unique) {     // Found a new, unplaced node?
 196       old_ctrl = nullptr;
 197       old_loop = nullptr;               // Not in any prior loop
 198     } else {
 199       old_ctrl = get_ctrl(x);
 200       old_loop = get_loop(old_ctrl); // Get prior loop
 201     }
 202     // New late point must dominate new use
 203     Node *new_ctrl = dom_lca(old_ctrl, region->in(i2));
 204     if (new_ctrl == old_ctrl) // Nothing is changed
 205       continue;
 206 
 207     IdealLoopTree *new_loop = get_loop(new_ctrl);
 208 
 209     // Don't move x into a loop if its uses are
 210     // outside of loop. Otherwise x will be cloned
 211     // for each use outside of this loop.
 212     IdealLoopTree *use_loop = get_loop(region);
 213     if (!new_loop->is_member(use_loop) &&
 214         (old_loop == nullptr || !new_loop->is_member(old_loop))) {
 215       // Take early control, later control will be recalculated
 216       // during next iteration of loop optimizations.
 217       new_ctrl = get_early_ctrl(x);
 218       new_loop = get_loop(new_ctrl);
 219     }
 220     // Set new location
 221     set_ctrl(x, new_ctrl);
 222     // If changing loop bodies, see if we need to collect into new body
 223     if (old_loop != new_loop) {
 224       if (old_loop && !old_loop->_child)
 225         old_loop->_body.yank(x);
 226       if (!new_loop->_child)
 227         new_loop->_body.push(x);  // Collect body info
 228     }
 229   }
 230 
 231   split_thru_phi_yank_old_nodes(n, region);
 232   _igvn.replace_node(n, phi);
 233 
 234 #ifndef PRODUCT
 235   if (TraceLoopOpts) {
 236     tty->print_cr("Split %d %s through %d Phi in %d %s",
 237                   n->_idx, n->Name(), phi->_idx, region->_idx, region->Name());
 238   }
 239 #endif // !PRODUCT
 240 
 241   return phi;
 242 }
 243 
 244 // If the region is a Loop, we are removing the old n,
 245 // and need to yank it from the _body. If any phi we
 246 // just split through now has no use any more, it also
 247 // has to be removed.
 248 void PhaseIdealLoop::split_thru_phi_yank_old_nodes(Node* n, Node* region) {
 249   IdealLoopTree* region_loop = get_loop(region);
 250   if (region->is_Loop() && region_loop->is_innermost()) {
 251     region_loop->_body.yank(n);
 252     for (uint j = 1; j < n->req(); j++) {
 253       PhiNode* phi = n->in(j)->isa_Phi();
 254       // Check that phi belongs to the region and only has n as a use.
 255       if (phi != nullptr &&
 256           phi->in(0) == region &&
 257           phi->unique_multiple_edges_out_or_null() == n) {
 258         assert(get_ctrl(phi) == region, "sanity");
 259         assert(get_ctrl(n) == region, "sanity");
 260         region_loop->_body.yank(phi);
 261       }
 262     }
 263   }
 264 }
 265 
 266 // Test whether node 'x' can move into an inner loop relative to node 'n'.
 267 // Note: The test is not exact. Returns true if 'x' COULD end up in an inner loop,
 268 // BUT it can also return true and 'x' is in the outer loop
 269 bool PhaseIdealLoop::can_move_to_inner_loop(Node* n, LoopNode* n_loop, Node* x) {
 270   IdealLoopTree* n_loop_tree = get_loop(n_loop);
 271   IdealLoopTree* x_loop_tree = get_loop(get_early_ctrl(x));
 272   // x_loop_tree should be outer or same loop as n_loop_tree
 273   return !x_loop_tree->is_member(n_loop_tree);
 274 }
 275 
 276 // Subtype checks that carry profile data don't common so look for a replacement by following edges
 277 Node* PhaseIdealLoop::similar_subtype_check(const Node* x, Node* r_in) {
 278   if (x->is_SubTypeCheck()) {
 279     Node* in1 = x->in(1);
 280     for (DUIterator_Fast imax, i = in1->fast_outs(imax); i < imax; i++) {
 281       Node* u = in1->fast_out(i);
 282       if (u != x && u->is_SubTypeCheck() && u->in(1) == x->in(1) && u->in(2) == x->in(2)) {
 283         for (DUIterator_Fast jmax, j = u->fast_outs(jmax); j < jmax; j++) {
 284           Node* bol = u->fast_out(j);
 285           for (DUIterator_Fast kmax, k = bol->fast_outs(kmax); k < kmax; k++) {
 286             Node* iff = bol->fast_out(k);
 287             // Only dominating subtype checks are interesting: otherwise we risk replacing a subtype check by another with
 288             // unrelated profile
 289             if (iff->is_If() && is_dominator(iff, r_in)) {
 290               return u;
 291             }
 292           }
 293         }
 294       }
 295     }
 296   }
 297   return nullptr;
 298 }
 299 
 300 // Return true if 'n' is a Div or Mod node (without zero check If node which was removed earlier) with a loop phi divisor
 301 // of a trip-counted (integer or long) loop with a backedge input that could be zero (include zero in its type range). In
 302 // this case, we cannot split the division to the backedge as it could freely float above the loop exit check resulting in
 303 // a division by zero. This situation is possible because the type of an increment node of an iv phi (trip-counter) could
 304 // include zero while the iv phi does not (see PhiNode::Value() for trip-counted loops where we improve types of iv phis).
 305 // We also need to check other loop phis as they could have been created in the same split-if pass when applying
 306 // PhaseIdealLoop::split_thru_phi() to split nodes through an iv phi.
 307 bool PhaseIdealLoop::cannot_split_division(const Node* n, const Node* region) const {
 308   const Type* zero;
 309   switch (n->Opcode()) {
 310     case Op_DivI:
 311     case Op_ModI:
 312     case Op_UDivI:
 313     case Op_UModI:
 314       zero = TypeInt::ZERO;
 315       break;
 316     case Op_DivL:
 317     case Op_ModL:
 318     case Op_UDivL:
 319     case Op_UModL:
 320       zero = TypeLong::ZERO;
 321       break;
 322     default:
 323       return false;
 324   }
 325 
 326   if (n->in(0) != nullptr) {
 327     // Cannot split through phi if Div or Mod node has a control dependency to a zero check.
 328     return true;
 329   }
 330 
 331   Node* divisor = n->in(2);
 332   return is_divisor_loop_phi(divisor, region) &&
 333          loop_phi_backedge_type_contains_zero(divisor, zero);
 334 }
 335 
 336 bool PhaseIdealLoop::is_divisor_loop_phi(const Node* divisor, const Node* loop) {
 337   return loop->is_Loop() && divisor->is_Phi() && divisor->in(0) == loop;
 338 }
 339 
 340 bool PhaseIdealLoop::loop_phi_backedge_type_contains_zero(const Node* phi_divisor, const Type* zero) const {
 341     return _igvn.type(phi_divisor->in(LoopNode::LoopBackControl))->filter_speculative(zero) != Type::TOP;
 342 }
 343 
 344 //------------------------------dominated_by------------------------------------
 345 // Replace the dominated test with an obvious true or false.  Place it on the
 346 // IGVN worklist for later cleanup.  Move control-dependent data Nodes on the
 347 // live path up to the dominating control.
 348 void PhaseIdealLoop::dominated_by(IfProjNode* prevdom, IfNode* iff, bool flip, bool prevdom_not_imply_this) {
 349   if (VerifyLoopOptimizations && PrintOpto) { tty->print_cr("dominating test"); }
 350 
 351   // prevdom is the dominating projection of the dominating test.
 352   assert(iff->Opcode() == Op_If ||
 353          iff->Opcode() == Op_CountedLoopEnd ||
 354          iff->Opcode() == Op_LongCountedLoopEnd ||
 355          iff->Opcode() == Op_RangeCheck ||
 356          iff->Opcode() == Op_ParsePredicate,
 357         "Check this code when new subtype is added");
 358 
 359   int pop = prevdom->Opcode();
 360   assert( pop == Op_IfFalse || pop == Op_IfTrue, "" );
 361   if (flip) {
 362     if (pop == Op_IfTrue)
 363       pop = Op_IfFalse;
 364     else
 365       pop = Op_IfTrue;
 366   }
 367   // 'con' is set to true or false to kill the dominated test.
 368   Node* con = makecon(pop == Op_IfTrue ? TypeInt::ONE : TypeInt::ZERO);
 369   // Hack the dominated test
 370   _igvn.replace_input_of(iff, 1, con);
 371 
 372   // If I don't have a reachable TRUE and FALSE path following the IfNode then
 373   // I can assume this path reaches an infinite loop.  In this case it's not
 374   // important to optimize the data Nodes - either the whole compilation will
 375   // be tossed or this path (and all data Nodes) will go dead.
 376   if (iff->outcnt() != 2) {
 377     return;
 378   }
 379 
 380   // Make control-dependent data Nodes on the live path (path that will remain
 381   // once the dominated IF is removed) become control-dependent on the
 382   // dominating projection.
 383   Node* dp = iff->proj_out_or_null(pop == Op_IfTrue);
 384 
 385   if (dp == nullptr) {
 386     return;
 387   }
 388 
 389   rewire_safe_outputs_to_dominator(dp, prevdom, prevdom_not_imply_this);
 390 }
 391 
 392 void PhaseIdealLoop::rewire_safe_outputs_to_dominator(Node* source, Node* dominator, const bool dominator_not_imply_source) {
 393   IdealLoopTree* old_loop = get_loop(source);
 394 
 395   for (DUIterator_Fast imax, i = source->fast_outs(imax); i < imax; i++) {
 396     Node* out = source->fast_out(i); // Control-dependent node
 397     if (out->depends_only_on_test()) {
 398       assert(out->in(0) == source, "must be control dependent on source");
 399       _igvn.replace_input_of(out, 0, dominator);
 400       if (dominator_not_imply_source) {
 401         // Because of Loop Predication, Loads and range check Cast nodes that are control dependent on this range
 402         // check (that is about to be removed) now depend on multiple dominating Hoisted Check Predicates. After the
 403         // removal of this range check, these control dependent nodes end up at the lowest/nearest dominating predicate
 404         // in the graph. To ensure that these Loads/Casts do not float above any of the dominating checks (even when the
 405         // lowest dominating check is later replaced by yet another dominating check), we need to pin them at the lowest
 406         // dominating check.
 407         Node* clone = out->pin_node_under_control();
 408         if (clone != nullptr) {
 409           clone = _igvn.register_new_node_with_optimizer(clone, out);
 410           _igvn.replace_node(out, clone);
 411           out = clone;
 412         }
 413       }
 414       set_early_ctrl(out, false);
 415       IdealLoopTree* new_loop = get_loop(get_ctrl(out));
 416       if (old_loop != new_loop) {
 417         if (!old_loop->_child) {
 418           old_loop->_body.yank(out);
 419         }
 420         if (!new_loop->_child) {
 421           new_loop->_body.push(out);
 422         }
 423       }
 424       --i;
 425       --imax;
 426     }
 427   }
 428 }
 429 
 430 //------------------------------has_local_phi_input----------------------------
 431 // Return TRUE if 'n' has Phi inputs from its local block and no other
 432 // block-local inputs (all non-local-phi inputs come from earlier blocks)
 433 Node *PhaseIdealLoop::has_local_phi_input( Node *n ) {
 434   Node *n_ctrl = get_ctrl(n);
 435   // See if some inputs come from a Phi in this block, or from before
 436   // this block.
 437   uint i;
 438   for( i = 1; i < n->req(); i++ ) {
 439     Node *phi = n->in(i);
 440     if( phi->is_Phi() && phi->in(0) == n_ctrl )
 441       break;
 442   }
 443   if( i >= n->req() )
 444     return nullptr;                // No Phi inputs; nowhere to clone thru
 445 
 446   // Check for inputs created between 'n' and the Phi input.  These
 447   // must split as well; they have already been given the chance
 448   // (courtesy of a post-order visit) and since they did not we must
 449   // recover the 'cost' of splitting them by being very profitable
 450   // when splitting 'n'.  Since this is unlikely we simply give up.
 451   for( i = 1; i < n->req(); i++ ) {
 452     Node *m = n->in(i);
 453     if( get_ctrl(m) == n_ctrl && !m->is_Phi() ) {
 454       // We allow the special case of AddP's with no local inputs.
 455       // This allows us to split-up address expressions.
 456       if (m->is_AddP() &&
 457           get_ctrl(m->in(AddPNode::Base)) != n_ctrl &&
 458           get_ctrl(m->in(AddPNode::Address)) != n_ctrl &&
 459           get_ctrl(m->in(AddPNode::Offset)) != n_ctrl) {
 460         // Move the AddP up to the dominating point. That's fine because control of m's inputs
 461         // must dominate get_ctrl(m) == n_ctrl and we just checked that the input controls are != n_ctrl.
 462         Node* c = find_non_split_ctrl(idom(n_ctrl));
 463         if (c->is_OuterStripMinedLoop()) {
 464           c->as_Loop()->verify_strip_mined(1);
 465           c = c->in(LoopNode::EntryControl);
 466         }
 467         set_ctrl_and_loop(m, c);
 468         continue;
 469       }
 470       return nullptr;
 471     }
 472     assert(n->is_Phi() || m->is_Phi() || is_dominator(get_ctrl(m), n_ctrl), "m has strange control");
 473   }
 474 
 475   return n_ctrl;
 476 }
 477 
 478 // Replace expressions like ((V+I) << 2) with (V<<2 + I<<2).
 479 Node* PhaseIdealLoop::remix_address_expressions_add_left_shift(Node* n, IdealLoopTree* n_loop, Node* n_ctrl, BasicType bt) {
 480   assert(bt == T_INT || bt == T_LONG, "only for integers");
 481   int n_op = n->Opcode();
 482 
 483   if (n_op == Op_LShift(bt)) {
 484     // Scale is loop invariant
 485     Node* scale = n->in(2);
 486     Node* scale_ctrl = get_ctrl(scale);
 487     IdealLoopTree* scale_loop = get_loop(scale_ctrl);
 488     if (n_loop == scale_loop || !scale_loop->is_member(n_loop)) {
 489       return nullptr;
 490     }
 491     const TypeInt* scale_t = scale->bottom_type()->isa_int();
 492     if (scale_t != nullptr && scale_t->is_con() && scale_t->get_con() >= 16) {
 493       return nullptr;              // Dont bother with byte/short masking
 494     }
 495     // Add must vary with loop (else shift would be loop-invariant)
 496     Node* add = n->in(1);
 497     Node* add_ctrl = get_ctrl(add);
 498     IdealLoopTree* add_loop = get_loop(add_ctrl);
 499     if (n_loop != add_loop) {
 500       return nullptr;  // happens w/ evil ZKM loops
 501     }
 502 
 503     // Convert I-V into I+ (0-V); same for V-I
 504     if (add->Opcode() == Op_Sub(bt) &&
 505         _igvn.type(add->in(1)) != TypeInteger::zero(bt)) {
 506       assert(add->Opcode() == Op_SubI || add->Opcode() == Op_SubL, "");
 507       Node* zero = integercon(0, bt);
 508       Node* neg = SubNode::make(zero, add->in(2), bt);
 509       register_new_node_with_ctrl_of(neg, add->in(2));
 510       add = AddNode::make(add->in(1), neg, bt);
 511       register_new_node(add, add_ctrl);
 512     }
 513     if (add->Opcode() != Op_Add(bt)) return nullptr;
 514     assert(add->Opcode() == Op_AddI || add->Opcode() == Op_AddL, "");
 515     // See if one add input is loop invariant
 516     Node* add_var = add->in(1);
 517     Node* add_var_ctrl = get_ctrl(add_var);
 518     IdealLoopTree* add_var_loop = get_loop(add_var_ctrl);
 519     Node* add_invar = add->in(2);
 520     Node* add_invar_ctrl = get_ctrl(add_invar);
 521     IdealLoopTree* add_invar_loop = get_loop(add_invar_ctrl);
 522     if (add_invar_loop == n_loop) {
 523       // Swap to find the invariant part
 524       add_invar = add_var;
 525       add_invar_ctrl = add_var_ctrl;
 526       add_invar_loop = add_var_loop;
 527       add_var = add->in(2);
 528     } else if (add_var_loop != n_loop) { // Else neither input is loop invariant
 529       return nullptr;
 530     }
 531     if (n_loop == add_invar_loop || !add_invar_loop->is_member(n_loop)) {
 532       return nullptr;              // No invariant part of the add?
 533     }
 534 
 535     // Yes!  Reshape address expression!
 536     Node* inv_scale = LShiftNode::make(add_invar, scale, bt);
 537     Node* inv_scale_ctrl =
 538             dom_depth(add_invar_ctrl) > dom_depth(scale_ctrl) ?
 539             add_invar_ctrl : scale_ctrl;
 540     register_new_node(inv_scale, inv_scale_ctrl);
 541     Node* var_scale = LShiftNode::make(add_var, scale, bt);
 542     register_new_node(var_scale, n_ctrl);
 543     Node* var_add = AddNode::make(var_scale, inv_scale, bt);
 544     register_new_node(var_add, n_ctrl);
 545     _igvn.replace_node(n, var_add);
 546     return var_add;
 547   }
 548   return nullptr;
 549 }
 550 
 551 //------------------------------remix_address_expressions----------------------
 552 // Rework addressing expressions to get the most loop-invariant stuff
 553 // moved out.  We'd like to do all associative operators, but it's especially
 554 // important (common) to do address expressions.
 555 Node* PhaseIdealLoop::remix_address_expressions(Node* n) {
 556   if (!has_ctrl(n))  return nullptr;
 557   Node* n_ctrl = get_ctrl(n);
 558   IdealLoopTree* n_loop = get_loop(n_ctrl);
 559 
 560   // See if 'n' mixes loop-varying and loop-invariant inputs and
 561   // itself is loop-varying.
 562 
 563   // Only interested in binary ops (and AddP)
 564   if (n->req() < 3 || n->req() > 4) return nullptr;
 565 
 566   Node* n1_ctrl = get_ctrl(n->in(                    1));
 567   Node* n2_ctrl = get_ctrl(n->in(                    2));
 568   Node* n3_ctrl = get_ctrl(n->in(n->req() == 3 ? 2 : 3));
 569   IdealLoopTree* n1_loop = get_loop(n1_ctrl);
 570   IdealLoopTree* n2_loop = get_loop(n2_ctrl);
 571   IdealLoopTree* n3_loop = get_loop(n3_ctrl);
 572 
 573   // Does one of my inputs spin in a tighter loop than self?
 574   if ((n_loop->is_member(n1_loop) && n_loop != n1_loop) ||
 575       (n_loop->is_member(n2_loop) && n_loop != n2_loop) ||
 576       (n_loop->is_member(n3_loop) && n_loop != n3_loop)) {
 577     return nullptr;                // Leave well enough alone
 578   }
 579 
 580   // Is at least one of my inputs loop-invariant?
 581   if (n1_loop == n_loop &&
 582       n2_loop == n_loop &&
 583       n3_loop == n_loop) {
 584     return nullptr;                // No loop-invariant inputs
 585   }
 586 
 587   Node* res = remix_address_expressions_add_left_shift(n, n_loop, n_ctrl, T_INT);
 588   if (res != nullptr) {
 589     return res;
 590   }
 591   res = remix_address_expressions_add_left_shift(n, n_loop, n_ctrl, T_LONG);
 592   if (res != nullptr) {
 593     return res;
 594   }
 595 
 596   int n_op = n->Opcode();
 597   // Replace (I+V) with (V+I)
 598   if (n_op == Op_AddI ||
 599       n_op == Op_AddL ||
 600       n_op == Op_AddF ||
 601       n_op == Op_AddD ||
 602       n_op == Op_MulI ||
 603       n_op == Op_MulL ||
 604       n_op == Op_MulF ||
 605       n_op == Op_MulD) {
 606     if (n2_loop == n_loop) {
 607       assert(n1_loop != n_loop, "");
 608       n->swap_edges(1, 2);
 609     }
 610   }
 611 
 612   // Replace ((I1 +p V) +p I2) with ((I1 +p I2) +p V),
 613   // but not if I2 is a constant. Skip for irreducible loops.
 614   if (n_op == Op_AddP && n_loop->_head->is_Loop()) {
 615     if (n2_loop == n_loop && n3_loop != n_loop) {
 616       if (n->in(2)->Opcode() == Op_AddP && !n->in(3)->is_Con()) {
 617         Node* n22_ctrl = get_ctrl(n->in(2)->in(2));
 618         Node* n23_ctrl = get_ctrl(n->in(2)->in(3));
 619         IdealLoopTree* n22loop = get_loop(n22_ctrl);
 620         IdealLoopTree* n23_loop = get_loop(n23_ctrl);
 621         if (n22loop != n_loop && n22loop->is_member(n_loop) &&
 622             n23_loop == n_loop) {
 623           Node* add1 = AddPNode::make_with_base(n->in(1), n->in(2)->in(2), n->in(3));
 624           // Stuff new AddP in the loop preheader
 625           register_new_node(add1, n_loop->_head->as_Loop()->skip_strip_mined(1)->in(LoopNode::EntryControl));
 626           Node* add2 = AddPNode::make_with_base(n->in(1), add1, n->in(2)->in(3));
 627           register_new_node(add2, n_ctrl);
 628           _igvn.replace_node(n, add2);
 629           return add2;
 630         }
 631       }
 632     }
 633 
 634     // Replace (I1 +p (I2 + V)) with ((I1 +p I2) +p V)
 635     if (n2_loop != n_loop && n3_loop == n_loop) {
 636       if (n->in(3)->Opcode() == Op_AddX) {
 637         Node* V = n->in(3)->in(1);
 638         Node* I = n->in(3)->in(2);
 639         if (ctrl_is_member(n_loop, V)) {
 640         } else {
 641           Node *tmp = V; V = I; I = tmp;
 642         }
 643         if (!ctrl_is_member(n_loop, I)) {
 644           Node* add1 = AddPNode::make_with_base(n->in(1), n->in(2), I);
 645           // Stuff new AddP in the loop preheader
 646           register_new_node(add1, n_loop->_head->as_Loop()->skip_strip_mined(1)->in(LoopNode::EntryControl));
 647           Node* add2 = AddPNode::make_with_base(n->in(1), add1, V);
 648           register_new_node(add2, n_ctrl);
 649           _igvn.replace_node(n, add2);
 650           return add2;
 651         }
 652       }
 653     }
 654   }
 655 
 656   return nullptr;
 657 }
 658 
 659 // Optimize ((in1[2*i] * in2[2*i]) + (in1[2*i+1] * in2[2*i+1]))
 660 Node *PhaseIdealLoop::convert_add_to_muladd(Node* n) {
 661   assert(n->Opcode() == Op_AddI, "sanity");
 662   Node * nn = nullptr;
 663   Node * in1 = n->in(1);
 664   Node * in2 = n->in(2);
 665   if (in1->Opcode() == Op_MulI && in2->Opcode() == Op_MulI) {
 666     IdealLoopTree* loop_n = get_loop(get_ctrl(n));
 667     if (loop_n->is_counted() &&
 668         loop_n->_head->as_Loop()->is_valid_counted_loop(T_INT) &&
 669         Matcher::match_rule_supported(Op_MulAddVS2VI) &&
 670         Matcher::match_rule_supported(Op_MulAddS2I)) {
 671       Node* mul_in1 = in1->in(1);
 672       Node* mul_in2 = in1->in(2);
 673       Node* mul_in3 = in2->in(1);
 674       Node* mul_in4 = in2->in(2);
 675       if (mul_in1->Opcode() == Op_LoadS &&
 676           mul_in2->Opcode() == Op_LoadS &&
 677           mul_in3->Opcode() == Op_LoadS &&
 678           mul_in4->Opcode() == Op_LoadS) {
 679         IdealLoopTree* loop1 = get_loop(get_ctrl(mul_in1));
 680         IdealLoopTree* loop2 = get_loop(get_ctrl(mul_in2));
 681         IdealLoopTree* loop3 = get_loop(get_ctrl(mul_in3));
 682         IdealLoopTree* loop4 = get_loop(get_ctrl(mul_in4));
 683         IdealLoopTree* loop5 = get_loop(get_ctrl(in1));
 684         IdealLoopTree* loop6 = get_loop(get_ctrl(in2));
 685         // All nodes should be in the same counted loop.
 686         if (loop_n == loop1 && loop_n == loop2 && loop_n == loop3 &&
 687             loop_n == loop4 && loop_n == loop5 && loop_n == loop6) {
 688           Node* adr1 = mul_in1->in(MemNode::Address);
 689           Node* adr2 = mul_in2->in(MemNode::Address);
 690           Node* adr3 = mul_in3->in(MemNode::Address);
 691           Node* adr4 = mul_in4->in(MemNode::Address);
 692           if (adr1->is_AddP() && adr2->is_AddP() && adr3->is_AddP() && adr4->is_AddP()) {
 693             if ((adr1->in(AddPNode::Base) == adr3->in(AddPNode::Base)) &&
 694                 (adr2->in(AddPNode::Base) == adr4->in(AddPNode::Base))) {
 695               nn = new MulAddS2INode(mul_in1, mul_in2, mul_in3, mul_in4);
 696               register_new_node_with_ctrl_of(nn, n);
 697               _igvn.replace_node(n, nn);
 698               return nn;
 699             } else if ((adr1->in(AddPNode::Base) == adr4->in(AddPNode::Base)) &&
 700                        (adr2->in(AddPNode::Base) == adr3->in(AddPNode::Base))) {
 701               nn = new MulAddS2INode(mul_in1, mul_in2, mul_in4, mul_in3);
 702               register_new_node_with_ctrl_of(nn, n);
 703               _igvn.replace_node(n, nn);
 704               return nn;
 705             }
 706           }
 707         }
 708       }
 709     }
 710   }
 711   return nn;
 712 }
 713 
 714 //------------------------------conditional_move-------------------------------
 715 // Attempt to replace a Phi with a conditional move.  We have some pretty
 716 // strict profitability requirements.  All Phis at the merge point must
 717 // be converted, so we can remove the control flow.  We need to limit the
 718 // number of c-moves to a small handful.  All code that was in the side-arms
 719 // of the CFG diamond is now speculatively executed.  This code has to be
 720 // "cheap enough".  We are pretty much limited to CFG diamonds that merge
 721 // 1 or 2 items with a total of 1 or 2 ops executed speculatively.
 722 Node *PhaseIdealLoop::conditional_move( Node *region ) {
 723 
 724   assert(region->is_Region(), "sanity check");
 725   if (region->req() != 3) return nullptr;
 726 
 727   // Check for CFG diamond
 728   Node *lp = region->in(1);
 729   Node *rp = region->in(2);
 730   if (!lp || !rp) return nullptr;
 731   Node *lp_c = lp->in(0);
 732   if (lp_c == nullptr || lp_c != rp->in(0) || !lp_c->is_If()) return nullptr;
 733   IfNode *iff = lp_c->as_If();
 734 
 735   // Check for ops pinned in an arm of the diamond.
 736   // Can't remove the control flow in this case
 737   if (lp->outcnt() > 1) return nullptr;
 738   if (rp->outcnt() > 1) return nullptr;
 739 
 740   IdealLoopTree* r_loop = get_loop(region);
 741   assert(r_loop == get_loop(iff), "sanity");
 742   // Always convert to CMOVE if all results are used only outside this loop.
 743   bool used_inside_loop = (r_loop == _ltree_root);
 744 
 745   // Check profitability
 746   int cost = 0;
 747   int phis = 0;
 748   for (DUIterator_Fast imax, i = region->fast_outs(imax); i < imax; i++) {
 749     Node *out = region->fast_out(i);
 750     if (!out->is_Phi()) continue; // Ignore other control edges, etc
 751     phis++;
 752     PhiNode* phi = out->as_Phi();
 753     BasicType bt = phi->type()->basic_type();
 754     switch (bt) {
 755     case T_DOUBLE:
 756     case T_FLOAT:
 757       if (C->use_cmove()) {
 758         continue; //TODO: maybe we want to add some cost
 759       }
 760       cost += Matcher::float_cmove_cost(); // Could be very expensive
 761       break;
 762     case T_LONG: {
 763       cost += Matcher::long_cmove_cost(); // May encodes as 2 CMOV's
 764     }
 765     case T_INT:                 // These all CMOV fine
 766     case T_ADDRESS: {           // (RawPtr)
 767       cost++;
 768       break;
 769     }
 770     case T_NARROWOOP: // Fall through
 771     case T_OBJECT: {            // Base oops are OK, but not derived oops
 772       const TypeOopPtr *tp = phi->type()->make_ptr()->isa_oopptr();
 773       // Derived pointers are Bad (tm): what's the Base (for GC purposes) of a
 774       // CMOVE'd derived pointer?  It's a CMOVE'd derived base.  Thus
 775       // CMOVE'ing a derived pointer requires we also CMOVE the base.  If we
 776       // have a Phi for the base here that we convert to a CMOVE all is well
 777       // and good.  But if the base is dead, we'll not make a CMOVE.  Later
 778       // the allocator will have to produce a base by creating a CMOVE of the
 779       // relevant bases.  This puts the allocator in the business of
 780       // manufacturing expensive instructions, generally a bad plan.
 781       // Just Say No to Conditionally-Moved Derived Pointers.
 782       if (tp && tp->offset() != 0)
 783         return nullptr;
 784       cost++;
 785       break;
 786     }
 787     default:
 788       return nullptr;              // In particular, can't do memory or I/O
 789     }
 790     // Add in cost any speculative ops
 791     for (uint j = 1; j < region->req(); j++) {
 792       Node *proj = region->in(j);
 793       Node *inp = phi->in(j);
 794       if (get_ctrl(inp) == proj) { // Found local op
 795         cost++;
 796         // Check for a chain of dependent ops; these will all become
 797         // speculative in a CMOV.
 798         for (uint k = 1; k < inp->req(); k++)
 799           if (get_ctrl(inp->in(k)) == proj)
 800             cost += ConditionalMoveLimit; // Too much speculative goo
 801       }
 802     }
 803     // See if the Phi is used by a Cmp or Narrow oop Decode/Encode.
 804     // This will likely Split-If, a higher-payoff operation.
 805     for (DUIterator_Fast kmax, k = phi->fast_outs(kmax); k < kmax; k++) {
 806       Node* use = phi->fast_out(k);
 807       if (use->is_Cmp() || use->is_DecodeNarrowPtr() || use->is_EncodeNarrowPtr())
 808         cost += ConditionalMoveLimit;
 809       // Is there a use inside the loop?
 810       // Note: check only basic types since CMoveP is pinned.
 811       if (!used_inside_loop && is_java_primitive(bt)) {
 812         IdealLoopTree* u_loop = get_loop(has_ctrl(use) ? get_ctrl(use) : use);
 813         if (r_loop == u_loop || r_loop->is_member(u_loop)) {
 814           used_inside_loop = true;
 815         }
 816       }
 817     }
 818   }//for
 819   Node* bol = iff->in(1);
 820   assert(!bol->is_OpaqueInitializedAssertionPredicate(), "Initialized Assertion Predicates cannot form a diamond with Halt");
 821   if (bol->is_OpaqueTemplateAssertionPredicate()) {
 822     // Ignore Template Assertion Predicates with OpaqueTemplateAssertionPredicate nodes.
 823     return nullptr;
 824   }
 825   if (bol->is_OpaqueMultiversioning()) {
 826     assert(bol->as_OpaqueMultiversioning()->is_useless(), "Must be useless, i.e. fast main loop has already disappeared.");
 827     // Ignore multiversion_if that just lost its loops. The OpaqueMultiversioning is marked useless,
 828     // and will make the multiversion_if constant fold in the next IGVN round.
 829     return nullptr;
 830   }
 831   if (!bol->is_Bool()) {
 832     assert(false, "Expected Bool, but got %s", NodeClassNames[bol->Opcode()]);
 833     return nullptr;
 834   }
 835   int cmp_op = bol->in(1)->Opcode();
 836   if (cmp_op == Op_SubTypeCheck) { // SubTypeCheck expansion expects an IfNode
 837     return nullptr;
 838   }
 839   // It is expensive to generate flags from a float compare.
 840   // Avoid duplicated float compare.
 841   if (phis > 1 && (cmp_op == Op_CmpF || cmp_op == Op_CmpD)) return nullptr;
 842 
 843   float infrequent_prob = PROB_UNLIKELY_MAG(3);
 844   // Ignore cost and blocks frequency if CMOVE can be moved outside the loop.
 845   if (used_inside_loop) {
 846     if (cost >= ConditionalMoveLimit) return nullptr; // Too much goo
 847 
 848     // BlockLayoutByFrequency optimization moves infrequent branch
 849     // from hot path. No point in CMOV'ing in such case (110 is used
 850     // instead of 100 to take into account not exactness of float value).
 851     if (BlockLayoutByFrequency) {
 852       infrequent_prob = MAX2(infrequent_prob, (float)BlockLayoutMinDiamondPercentage/110.0f);
 853     }
 854   }
 855   // Check for highly predictable branch.  No point in CMOV'ing if
 856   // we are going to predict accurately all the time.
 857   if (C->use_cmove() && (cmp_op == Op_CmpF || cmp_op == Op_CmpD)) {
 858     //keep going
 859   } else if (iff->_prob < infrequent_prob ||
 860       iff->_prob > (1.0f - infrequent_prob))
 861     return nullptr;
 862 
 863   // --------------
 864   // Now replace all Phis with CMOV's
 865   Node *cmov_ctrl = iff->in(0);
 866   uint flip = (lp->Opcode() == Op_IfTrue);
 867   Node_List wq;
 868   while (1) {
 869     PhiNode* phi = nullptr;
 870     for (DUIterator_Fast imax, i = region->fast_outs(imax); i < imax; i++) {
 871       Node *out = region->fast_out(i);
 872       if (out->is_Phi()) {
 873         phi = out->as_Phi();
 874         break;
 875       }
 876     }
 877     if (phi == nullptr || _igvn.type(phi) == Type::TOP || !CMoveNode::supported(_igvn.type(phi))) {
 878       break;
 879     }
 880     // Move speculative ops
 881     wq.push(phi);
 882     while (wq.size() > 0) {
 883       Node *n = wq.pop();
 884       for (uint j = 1; j < n->req(); j++) {
 885         Node* m = n->in(j);
 886         if (m != nullptr && !is_dominator(get_ctrl(m), cmov_ctrl)) {
 887           set_ctrl(m, cmov_ctrl);
 888           wq.push(m);
 889         }
 890       }
 891     }
 892     Node* cmov = CMoveNode::make(iff->in(1), phi->in(1+flip), phi->in(2-flip), _igvn.type(phi));
 893     register_new_node(cmov, cmov_ctrl);
 894     _igvn.replace_node(phi, cmov);
 895 #ifndef PRODUCT
 896     if (TraceLoopOpts) {
 897       tty->print("CMOV  ");
 898       r_loop->dump_head();
 899       if (Verbose) {
 900         bol->in(1)->dump(1);
 901         cmov->dump(1);
 902       }
 903     }
 904     DEBUG_ONLY( if (VerifyLoopOptimizations) { verify(); } );
 905 #endif
 906   }
 907 
 908   // The useless CFG diamond will fold up later; see the optimization in
 909   // RegionNode::Ideal.
 910   _igvn._worklist.push(region);
 911 
 912   return iff->in(1);
 913 }
 914 
 915 static void enqueue_cfg_uses(Node* m, Unique_Node_List& wq) {
 916   for (DUIterator_Fast imax, i = m->fast_outs(imax); i < imax; i++) {
 917     Node* u = m->fast_out(i);
 918     if (u->is_CFG()) {
 919       if (u->is_NeverBranch()) {
 920         u = u->as_NeverBranch()->proj_out(0);
 921         enqueue_cfg_uses(u, wq);
 922       } else {
 923         wq.push(u);
 924       }
 925     }
 926   }
 927 }
 928 
 929 // Try moving a store out of a loop, right before the loop
 930 Node* PhaseIdealLoop::try_move_store_before_loop(Node* n, Node *n_ctrl) {
 931   // Store has to be first in the loop body
 932   IdealLoopTree *n_loop = get_loop(n_ctrl);
 933   if (n->is_Store() && n_loop != _ltree_root &&
 934       n_loop->is_loop() && n_loop->_head->is_Loop() &&
 935       n->in(0) != nullptr) {
 936     Node* address = n->in(MemNode::Address);
 937     Node* value = n->in(MemNode::ValueIn);
 938     Node* mem = n->in(MemNode::Memory);
 939 
 940     // - address and value must be loop invariant
 941     // - memory must be a memory Phi for the loop
 942     // - Store must be the only store on this memory slice in the
 943     // loop: if there's another store following this one then value
 944     // written at iteration i by the second store could be overwritten
 945     // at iteration i+n by the first store: it's not safe to move the
 946     // first store out of the loop
 947     // - nothing must observe the memory Phi: it guarantees no read
 948     // before the store, we are also guaranteed the store post
 949     // dominates the loop head (ignoring a possible early
 950     // exit). Otherwise there would be extra Phi involved between the
 951     // loop's Phi and the store.
 952     // - there must be no early exit from the loop before the Store
 953     // (such an exit most of the time would be an extra use of the
 954     // memory Phi but sometimes is a bottom memory Phi that takes the
 955     // store as input).
 956 
 957     if (!ctrl_is_member(n_loop, address) &&
 958         !ctrl_is_member(n_loop, value) &&
 959         mem->is_Phi() && mem->in(0) == n_loop->_head &&
 960         mem->outcnt() == 1 &&
 961         mem->in(LoopNode::LoopBackControl) == n) {
 962 
 963       assert(n_loop->_tail != nullptr, "need a tail");
 964       assert(is_dominator(n_ctrl, n_loop->_tail), "store control must not be in a branch in the loop");
 965 
 966       // Verify that there's no early exit of the loop before the store.
 967       bool ctrl_ok = false;
 968       {
 969         // Follow control from loop head until n, we exit the loop or
 970         // we reach the tail
 971         ResourceMark rm;
 972         Unique_Node_List wq;
 973         wq.push(n_loop->_head);
 974 
 975         for (uint next = 0; next < wq.size(); ++next) {
 976           Node *m = wq.at(next);
 977           if (m == n->in(0)) {
 978             ctrl_ok = true;
 979             continue;
 980           }
 981           assert(!has_ctrl(m), "should be CFG");
 982           if (!n_loop->is_member(get_loop(m)) || m == n_loop->_tail) {
 983             ctrl_ok = false;
 984             break;
 985           }
 986           enqueue_cfg_uses(m, wq);
 987           if (wq.size() > 10) {
 988             ctrl_ok = false;
 989             break;
 990           }
 991         }
 992       }
 993       if (ctrl_ok) {
 994         // move the Store
 995         _igvn.replace_input_of(mem, LoopNode::LoopBackControl, mem);
 996         _igvn.replace_input_of(n, 0, n_loop->_head->as_Loop()->skip_strip_mined()->in(LoopNode::EntryControl));
 997         _igvn.replace_input_of(n, MemNode::Memory, mem->in(LoopNode::EntryControl));
 998         // Disconnect the phi now. An empty phi can confuse other
 999         // optimizations in this pass of loop opts.
1000         _igvn.replace_node(mem, mem->in(LoopNode::EntryControl));
1001         n_loop->_body.yank(mem);
1002 
1003         set_ctrl_and_loop(n, n->in(0));
1004 
1005         return n;
1006       }
1007     }
1008   }
1009   return nullptr;
1010 }
1011 
1012 // Try moving a store out of a loop, right after the loop
1013 void PhaseIdealLoop::try_move_store_after_loop(Node* n) {
1014   if (n->is_Store() && n->in(0) != nullptr) {
1015     Node *n_ctrl = get_ctrl(n);
1016     IdealLoopTree *n_loop = get_loop(n_ctrl);
1017     // Store must be in a loop
1018     if (n_loop != _ltree_root && !n_loop->_irreducible) {
1019       Node* address = n->in(MemNode::Address);
1020       Node* value = n->in(MemNode::ValueIn);
1021       // address must be loop invariant
1022       if (!ctrl_is_member(n_loop, address)) {
1023         // Store must be last on this memory slice in the loop and
1024         // nothing in the loop must observe it
1025         Node* phi = nullptr;
1026         for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
1027           Node* u = n->fast_out(i);
1028           if (has_ctrl(u)) { // control use?
1029             if (!ctrl_is_member(n_loop, u)) {
1030               continue;
1031             }
1032             if (u->is_Phi() && u->in(0) == n_loop->_head) {
1033               assert(_igvn.type(u) == Type::MEMORY, "bad phi");
1034               // multiple phis on the same slice are possible
1035               if (phi != nullptr) {
1036                 return;
1037               }
1038               phi = u;
1039               continue;
1040             }
1041           }
1042           return;
1043         }
1044         if (phi != nullptr) {
1045           // Nothing in the loop before the store (next iteration)
1046           // must observe the stored value
1047           bool mem_ok = true;
1048           {
1049             ResourceMark rm;
1050             Unique_Node_List wq;
1051             wq.push(phi);
1052             for (uint next = 0; next < wq.size() && mem_ok; ++next) {
1053               Node *m = wq.at(next);
1054               for (DUIterator_Fast imax, i = m->fast_outs(imax); i < imax && mem_ok; i++) {
1055                 Node* u = m->fast_out(i);
1056                 if (u->is_Store() || u->is_Phi()) {
1057                   if (u != n) {
1058                     wq.push(u);
1059                     mem_ok = (wq.size() <= 10);
1060                   }
1061                 } else {
1062                   mem_ok = false;
1063                   break;
1064                 }
1065               }
1066             }
1067           }
1068           if (mem_ok) {
1069             // Move the store out of the loop if the LCA of all
1070             // users (except for the phi) is outside the loop.
1071             Node* hook = new Node(1);
1072             hook->init_req(0, n_ctrl); // Add an input to prevent hook from being dead
1073             _igvn.rehash_node_delayed(phi);
1074             int count = phi->replace_edge(n, hook, &_igvn);
1075             assert(count > 0, "inconsistent phi");
1076 
1077             // Compute latest point this store can go
1078             Node* lca = get_late_ctrl(n, get_ctrl(n));
1079             if (lca->is_OuterStripMinedLoop()) {
1080               lca = lca->in(LoopNode::EntryControl);
1081             }
1082             if (n_loop->is_member(get_loop(lca))) {
1083               // LCA is in the loop - bail out
1084               _igvn.replace_node(hook, n);
1085               return;
1086             }
1087 #ifdef ASSERT
1088             if (n_loop->_head->is_Loop() && n_loop->_head->as_Loop()->is_strip_mined()) {
1089               assert(n_loop->_head->Opcode() == Op_CountedLoop, "outer loop is a strip mined");
1090               n_loop->_head->as_Loop()->verify_strip_mined(1);
1091               Node* outer = n_loop->_head->as_CountedLoop()->outer_loop();
1092               IdealLoopTree* outer_loop = get_loop(outer);
1093               assert(n_loop->_parent == outer_loop, "broken loop tree");
1094               assert(get_loop(lca) == outer_loop, "safepoint in outer loop consume all memory state");
1095             }
1096 #endif
1097             lca = place_outside_loop(lca, n_loop);
1098             assert(!n_loop->is_member(get_loop(lca)), "control must not be back in the loop");
1099             assert(get_loop(lca)->_nest < n_loop->_nest || get_loop(lca)->_head->as_Loop()->is_in_infinite_subgraph(), "must not be moved into inner loop");
1100 
1101             // Move store out of the loop
1102             _igvn.replace_node(hook, n->in(MemNode::Memory));
1103             _igvn.replace_input_of(n, 0, lca);
1104             set_ctrl_and_loop(n, lca);
1105 
1106             // Disconnect the phi now. An empty phi can confuse other
1107             // optimizations in this pass of loop opts..
1108             if (phi->in(LoopNode::LoopBackControl) == phi) {
1109               _igvn.replace_node(phi, phi->in(LoopNode::EntryControl));
1110               n_loop->_body.yank(phi);
1111             }
1112           }
1113         }
1114       }
1115     }
1116   }
1117 }
1118 
1119 //------------------------------split_if_with_blocks_pre-----------------------
1120 // Do the real work in a non-recursive function.  Data nodes want to be
1121 // cloned in the pre-order so they can feed each other nicely.
1122 Node *PhaseIdealLoop::split_if_with_blocks_pre( Node *n ) {
1123   // Cloning these guys is unlikely to win
1124   int n_op = n->Opcode();
1125   if (n_op == Op_MergeMem) {
1126     return n;
1127   }
1128   if (n->is_Proj()) {
1129     return n;
1130   }
1131   // Do not clone-up CmpFXXX variations, as these are always
1132   // followed by a CmpI
1133   if (n->is_Cmp()) {
1134     return n;
1135   }
1136   // Attempt to use a conditional move instead of a phi/branch
1137   if (ConditionalMoveLimit > 0 && n_op == Op_Region) {
1138     Node *cmov = conditional_move( n );
1139     if (cmov) {
1140       return cmov;
1141     }
1142   }
1143   if (n->is_CFG() || n->is_LoadStore()) {
1144     return n;
1145   }
1146   if (n->is_Opaque1()) { // Opaque nodes cannot be mod'd
1147     if (!C->major_progress()) {   // If chance of no more loop opts...
1148       _igvn._worklist.push(n);  // maybe we'll remove them
1149     }
1150     return n;
1151   }
1152 
1153   if (n->is_Con()) {
1154     return n;   // No cloning for Con nodes
1155   }
1156 
1157   Node *n_ctrl = get_ctrl(n);
1158   if (!n_ctrl) {
1159     return n;       // Dead node
1160   }
1161 
1162   Node* res = try_move_store_before_loop(n, n_ctrl);
1163   if (res != nullptr) {
1164     return n;
1165   }
1166 
1167   // Attempt to remix address expressions for loop invariants
1168   Node *m = remix_address_expressions( n );
1169   if( m ) return m;
1170 
1171   if (n_op == Op_AddI) {
1172     Node *nn = convert_add_to_muladd( n );
1173     if ( nn ) return nn;
1174   }
1175 
1176   if (n->is_ConstraintCast() && n->as_ConstraintCast()->dependency().narrows_type()) {
1177     Node* dom_cast = n->as_ConstraintCast()->dominating_cast(&_igvn, this);
1178     // ConstraintCastNode::dominating_cast() uses node control input to determine domination.
1179     // Node control inputs don't necessarily agree with loop control info (due to
1180     // transformations happened in between), thus additional dominance check is needed
1181     // to keep loop info valid.
1182     if (dom_cast != nullptr && is_dominator(get_ctrl(dom_cast), get_ctrl(n))) {
1183       _igvn.replace_node(n, dom_cast);
1184       return dom_cast;
1185     }
1186   }
1187 
1188   // Determine if the Node has inputs from some local Phi.
1189   // Returns the block to clone thru.
1190   Node *n_blk = has_local_phi_input( n );
1191   if( !n_blk ) return n;
1192 
1193   // Do not clone the trip counter through on a CountedLoop
1194   // (messes up the canonical shape).
1195   if (((n_blk->is_CountedLoop() || (n_blk->is_Loop() && n_blk->as_Loop()->is_loop_nest_inner_loop())) && n->Opcode() == Op_AddI) ||
1196       (n_blk->is_LongCountedLoop() && n->Opcode() == Op_AddL)) {
1197     return n;
1198   }
1199   // Pushing a shift through the iv Phi can get in the way of addressing optimizations or range check elimination
1200   if (n_blk->is_BaseCountedLoop() && n->Opcode() == Op_LShift(n_blk->as_BaseCountedLoop()->bt()) &&
1201       n->in(1) == n_blk->as_BaseCountedLoop()->phi()) {
1202     return n;
1203   }
1204 
1205   // Check for having no control input; not pinned.  Allow
1206   // dominating control.
1207   if (n->in(0)) {
1208     Node *dom = idom(n_blk);
1209     if (dom_lca(n->in(0), dom) != n->in(0)) {
1210       return n;
1211     }
1212   }
1213   // Policy: when is it profitable.  You must get more wins than
1214   // policy before it is considered profitable.  Policy is usually 0,
1215   // so 1 win is considered profitable.  Big merges will require big
1216   // cloning, so get a larger policy.
1217   int policy = n_blk->req() >> 2;
1218 
1219   // If the loop is a candidate for range check elimination,
1220   // delay splitting through it's phi until a later loop optimization
1221   if (n_blk->is_BaseCountedLoop()) {
1222     IdealLoopTree *lp = get_loop(n_blk);
1223     if (lp && lp->_rce_candidate) {
1224       return n;
1225     }
1226   }
1227 
1228   if (must_throttle_split_if()) return n;
1229 
1230   // Split 'n' through the merge point if it is profitable, replacing it with a new phi.
1231   Node* phi = split_thru_phi(n, n_blk, policy);
1232   if (phi == nullptr) { return n; }
1233 
1234   // Moved a load around the loop, 'en-registering' something.
1235   if (n_blk->is_Loop() && n->is_Load() &&
1236       !phi->in(LoopNode::LoopBackControl)->is_Load())
1237     C->set_major_progress();
1238 
1239   return phi;
1240 }
1241 
1242 static bool merge_point_too_heavy(Compile* C, Node* region) {
1243   // Bail out if the region and its phis have too many users.
1244   int weight = 0;
1245   for (DUIterator_Fast imax, i = region->fast_outs(imax); i < imax; i++) {
1246     weight += region->fast_out(i)->outcnt();
1247   }
1248   int nodes_left = C->max_node_limit() - C->live_nodes();
1249   if (weight * 8 > nodes_left) {
1250     if (PrintOpto) {
1251       tty->print_cr("*** Split-if bails out:  %d nodes, region weight %d", C->unique(), weight);
1252     }
1253     return true;
1254   } else {
1255     return false;
1256   }
1257 }
1258 
1259 static bool merge_point_safe(Node* region) {
1260   // 4799512: Stop split_if_with_blocks from splitting a block with a ConvI2LNode
1261   // having a PhiNode input. This sidesteps the dangerous case where the split
1262   // ConvI2LNode may become TOP if the input Value() does not
1263   // overlap the ConvI2L range, leaving a node which may not dominate its
1264   // uses.
1265   // A better fix for this problem can be found in the BugTraq entry, but
1266   // expediency for Mantis demands this hack.
1267 #ifdef _LP64
1268   for (DUIterator_Fast imax, i = region->fast_outs(imax); i < imax; i++) {
1269     Node* n = region->fast_out(i);
1270     if (n->is_Phi()) {
1271       for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++) {
1272         Node* m = n->fast_out(j);
1273         if (m->Opcode() == Op_ConvI2L)
1274           return false;
1275         if (m->is_CastII()) {
1276           return false;
1277         }
1278       }
1279     }
1280   }
1281 #endif
1282   return true;
1283 }
1284 
1285 
1286 //------------------------------place_outside_loop---------------------------------
1287 // Place some computation outside of this loop on the path to the use passed as argument
1288 Node* PhaseIdealLoop::place_outside_loop(Node* useblock, IdealLoopTree* loop) const {
1289   Node* head = loop->_head;
1290   assert(!loop->is_member(get_loop(useblock)), "must be outside loop");
1291   if (head->is_Loop() && head->as_Loop()->is_strip_mined()) {
1292     loop = loop->_parent;
1293     assert(loop->_head->is_OuterStripMinedLoop(), "malformed strip mined loop");
1294   }
1295 
1296   // Pick control right outside the loop
1297   for (;;) {
1298     Node* dom = idom(useblock);
1299     if (loop->is_member(get_loop(dom))) {
1300       break;
1301     }
1302     useblock = dom;
1303   }
1304   assert(find_non_split_ctrl(useblock) == useblock, "should be non split control");
1305   return useblock;
1306 }
1307 
1308 
1309 bool PhaseIdealLoop::identical_backtoback_ifs(Node *n) {
1310   if (!n->is_If()) {
1311     return false;
1312   }
1313   if (n->outcnt() != n->as_If()->required_outcnt()) {
1314     assert(false, "malformed IfNode with %d outputs", n->outcnt());
1315     return false;
1316   }
1317   if (n->is_BaseCountedLoopEnd()) {
1318     return false;
1319   }
1320   if (!n->in(0)->is_Region()) {
1321     return false;
1322   }
1323 
1324   Node* region = n->in(0);
1325   Node* dom = idom(region);
1326   if (!dom->is_If() ||  !n->as_If()->same_condition(dom, &_igvn)) {
1327     return false;
1328   }
1329   IfNode* dom_if = dom->as_If();
1330   IfTrueNode* proj_true = dom_if->true_proj();
1331   IfFalseNode* proj_false = dom_if->false_proj();
1332 
1333   for (uint i = 1; i < region->req(); i++) {
1334     if (is_dominator(proj_true, region->in(i))) {
1335       continue;
1336     }
1337     if (is_dominator(proj_false, region->in(i))) {
1338       continue;
1339     }
1340     return false;
1341   }
1342 
1343   return true;
1344 }
1345 
1346 
1347 bool PhaseIdealLoop::can_split_if(Node* n_ctrl) {
1348   if (must_throttle_split_if()) {
1349     return false;
1350   }
1351 
1352   // Do not do 'split-if' if irreducible loops are present.
1353   if (_has_irreducible_loops) {
1354     return false;
1355   }
1356 
1357   if (merge_point_too_heavy(C, n_ctrl)) {
1358     return false;
1359   }
1360 
1361   // Do not do 'split-if' if some paths are dead.  First do dead code
1362   // elimination and then see if its still profitable.
1363   for (uint i = 1; i < n_ctrl->req(); i++) {
1364     if (n_ctrl->in(i) == C->top()) {
1365       return false;
1366     }
1367   }
1368 
1369   // If trying to do a 'Split-If' at the loop head, it is only
1370   // profitable if the cmp folds up on BOTH paths.  Otherwise we
1371   // risk peeling a loop forever.
1372 
1373   // CNC - Disabled for now.  Requires careful handling of loop
1374   // body selection for the cloned code.  Also, make sure we check
1375   // for any input path not being in the same loop as n_ctrl.  For
1376   // irreducible loops we cannot check for 'n_ctrl->is_Loop()'
1377   // because the alternative loop entry points won't be converted
1378   // into LoopNodes.
1379   IdealLoopTree *n_loop = get_loop(n_ctrl);
1380   for (uint j = 1; j < n_ctrl->req(); j++) {
1381     if (get_loop(n_ctrl->in(j)) != n_loop) {
1382       return false;
1383     }
1384   }
1385 
1386   // Check for safety of the merge point.
1387   if (!merge_point_safe(n_ctrl)) {
1388     return false;
1389   }
1390 
1391   return true;
1392 }
1393 
1394 // Detect if the node is the inner strip-mined loop
1395 // Return: null if it's not the case, or the exit of outer strip-mined loop
1396 static Node* is_inner_of_stripmined_loop(const Node* out) {
1397   Node* out_le = nullptr;
1398 
1399   if (out->is_CountedLoopEnd()) {
1400       const CountedLoopNode* loop = out->as_CountedLoopEnd()->loopnode();
1401 
1402       if (loop != nullptr && loop->is_strip_mined()) {
1403         out_le = loop->in(LoopNode::EntryControl)->as_OuterStripMinedLoop()->outer_loop_exit();
1404       }
1405   }
1406 
1407   return out_le;
1408 }
1409 
1410 //------------------------------split_if_with_blocks_post----------------------
1411 // Do the real work in a non-recursive function.  CFG hackery wants to be
1412 // in the post-order, so it can dirty the I-DOM info and not use the dirtied
1413 // info.
1414 void PhaseIdealLoop::split_if_with_blocks_post(Node *n) {
1415 
1416   // Cloning Cmp through Phi's involves the split-if transform.
1417   // FastLock is not used by an If
1418   if (n->is_Cmp() && !n->is_FastLock()) {
1419     Node *n_ctrl = get_ctrl(n);
1420     // Determine if the Node has inputs from some local Phi.
1421     // Returns the block to clone thru.
1422     Node *n_blk = has_local_phi_input(n);
1423     if (n_blk != n_ctrl) {
1424       return;
1425     }
1426 
1427     if (!can_split_if(n_ctrl)) {
1428       return;
1429     }
1430 
1431     if (n->outcnt() != 1) {
1432       return; // Multiple bool's from 1 compare?
1433     }
1434     Node *bol = n->unique_out();
1435     assert(bol->is_Bool(), "expect a bool here");
1436     if (bol->outcnt() != 1) {
1437       return;// Multiple branches from 1 compare?
1438     }
1439     Node *iff = bol->unique_out();
1440 
1441     // Check some safety conditions
1442     if (iff->is_If()) {        // Classic split-if?
1443       if (iff->outcnt() != iff->as_If()->required_outcnt()) {
1444         assert(false, "malformed IfNode with %d outputs", iff->outcnt());
1445         return;
1446       } else if (iff->in(0) != n_ctrl) {
1447         return; // Compare must be in same blk as if
1448       }
1449     } else if (iff->is_CMove()) { // Trying to split-up a CMOVE
1450       // Can't split CMove with different control.
1451       if (get_ctrl(iff) != n_ctrl) {
1452         return;
1453       }
1454       if (get_ctrl(iff->in(2)) == n_ctrl ||
1455           get_ctrl(iff->in(3)) == n_ctrl) {
1456         return;                 // Inputs not yet split-up
1457       }
1458       if (get_loop(n_ctrl) != get_loop(get_ctrl(iff))) {
1459         return;                 // Loop-invar test gates loop-varying CMOVE
1460       }
1461     } else {
1462       return;  // some other kind of node, such as an Allocate
1463     }
1464 
1465     // When is split-if profitable?  Every 'win' on means some control flow
1466     // goes dead, so it's almost always a win.
1467     int policy = 0;
1468     // Split compare 'n' through the merge point if it is profitable
1469     Node *phi = split_thru_phi( n, n_ctrl, policy);
1470     if (!phi) {
1471       return;
1472     }
1473 
1474     // Now split the bool up thru the phi
1475     Node* bolphi = split_thru_phi(bol, n_ctrl, -1);
1476     guarantee(bolphi != nullptr, "null boolean phi node");
1477     assert(iff->in(1) == bolphi, "");
1478 
1479     if (bolphi->Value(&_igvn)->singleton()) {
1480       return;
1481     }
1482 
1483     // Conditional-move?  Must split up now
1484     if (!iff->is_If()) {
1485       Node* cmovphi = split_thru_phi(iff, n_ctrl, -1);
1486       return;
1487     }
1488 
1489     // Now split the IF
1490     C->print_method(PHASE_BEFORE_SPLIT_IF, 4, iff);
1491 #ifndef PRODUCT
1492     if (TraceLoopOpts || TraceSplitIf) {
1493       tty->print_cr("Split-If: %d %s", iff->_idx, iff->Name());
1494     }
1495 #endif
1496     do_split_if(iff);
1497     C->print_method(PHASE_AFTER_SPLIT_IF, 4, iff);
1498     return;
1499   }
1500 
1501   // Two identical ifs back to back can be merged
1502   if (try_merge_identical_ifs(n)) {
1503     return;
1504   }
1505 
1506   // Check for an IF ready to split; one that has its
1507   // condition codes input coming from a Phi at the block start.
1508   int n_op = n->Opcode();
1509 
1510   // Check for an IF being dominated by another IF same test
1511   if (n_op == Op_If ||
1512       n_op == Op_RangeCheck) {
1513     Node *bol = n->in(1);
1514     uint max = bol->outcnt();
1515     // Check for same test used more than once?
1516     if (bol->is_Bool() && (max > 1 || bol->in(1)->is_SubTypeCheck())) {
1517       // Search up IDOMs to see if this IF is dominated.
1518       Node* cmp = bol->in(1);
1519       Node *cutoff = cmp->is_SubTypeCheck() ? dom_lca(get_ctrl(cmp->in(1)), get_ctrl(cmp->in(2))) : get_ctrl(bol);
1520 
1521       // Now search up IDOMs till cutoff, looking for a dominating test
1522       Node *prevdom = n;
1523       Node *dom = idom(prevdom);
1524       while (dom != cutoff) {
1525         if (dom->req() > 1 && n->as_If()->same_condition(dom, &_igvn) && prevdom->in(0) == dom &&
1526             safe_for_if_replacement(dom)) {
1527           // It's invalid to move control dependent data nodes in the inner
1528           // strip-mined loop, because:
1529           //  1) break validation of LoopNode::verify_strip_mined()
1530           //  2) move code with side-effect in strip-mined loop
1531           // Move to the exit of outer strip-mined loop in that case.
1532           Node* out_le = is_inner_of_stripmined_loop(dom);
1533           if (out_le != nullptr) {
1534             prevdom = out_le;
1535           }
1536           // Replace the dominated test with an obvious true or false.
1537           // Place it on the IGVN worklist for later cleanup.
1538           C->set_major_progress();
1539           // Split if: pin array accesses that are control dependent on a range check and moved to a regular if,
1540           // to prevent an array load from floating above its range check. There are three cases:
1541           // 1. Move from RangeCheck "a" to RangeCheck "b": don't need to pin. If we ever remove b, then we pin
1542           //    all its array accesses at that point.
1543           // 2. We move from RangeCheck "a" to regular if "b": need to pin. If we ever remove b, then its array
1544           //    accesses would start to float, since we don't pin at that point.
1545           // 3. If we move from regular if: don't pin. All array accesses are already assumed to be pinned.
1546           bool pin_array_access_nodes =  n->Opcode() == Op_RangeCheck &&
1547                                          prevdom->in(0)->Opcode() != Op_RangeCheck;
1548           dominated_by(prevdom->as_IfProj(), n->as_If(), false, pin_array_access_nodes);
1549           DEBUG_ONLY( if (VerifyLoopOptimizations) { verify(); } );
1550           return;
1551         }
1552         prevdom = dom;
1553         dom = idom(prevdom);
1554       }
1555     }
1556   }
1557 
1558   try_sink_out_of_loop(n);
1559   if (C->failing()) {
1560     return;
1561   }
1562 
1563   try_move_store_after_loop(n);
1564 }
1565 
1566 // Transform:
1567 //
1568 // if (some_condition) {
1569 //   // body 1
1570 // } else {
1571 //   // body 2
1572 // }
1573 // if (some_condition) {
1574 //   // body 3
1575 // } else {
1576 //   // body 4
1577 // }
1578 //
1579 // into:
1580 //
1581 //
1582 // if (some_condition) {
1583 //   // body 1
1584 //   // body 3
1585 // } else {
1586 //   // body 2
1587 //   // body 4
1588 // }
1589 bool PhaseIdealLoop::try_merge_identical_ifs(Node* n) {
1590   if (identical_backtoback_ifs(n) && can_split_if(n->in(0))) {
1591     Node *n_ctrl = n->in(0);
1592     IfNode* dom_if = idom(n_ctrl)->as_If();
1593     if (n->in(1) != dom_if->in(1)) {
1594       assert(n->in(1)->in(1)->is_SubTypeCheck() &&
1595              (n->in(1)->in(1)->as_SubTypeCheck()->method() != nullptr ||
1596               dom_if->in(1)->in(1)->as_SubTypeCheck()->method() != nullptr), "only for subtype checks with profile data attached");
1597       _igvn.replace_input_of(n, 1, dom_if->in(1));
1598     }
1599     IfTrueNode* dom_proj_true = dom_if->true_proj();
1600     IfFalseNode* dom_proj_false = dom_if->false_proj();
1601 
1602     // Now split the IF
1603     RegionNode* new_false_region;
1604     RegionNode* new_true_region;
1605 #ifndef PRODUCT
1606     if (TraceLoopOpts || TraceSplitIf) {
1607       tty->print_cr("Split-If Merging Identical Ifs: Dom-If: %d %s, If: %d %s", dom_if->_idx, dom_if->Name(), n->_idx, n->Name());
1608     }
1609 #endif
1610     do_split_if(n, &new_false_region, &new_true_region);
1611     assert(new_false_region->req() == new_true_region->req(), "");
1612 #ifdef ASSERT
1613     for (uint i = 1; i < new_false_region->req(); ++i) {
1614       assert(new_false_region->in(i)->in(0) == new_true_region->in(i)->in(0), "unexpected shape following split if");
1615       assert(i == new_false_region->req() - 1 || new_false_region->in(i)->in(0)->in(1) == new_false_region->in(i + 1)->in(0)->in(1), "unexpected shape following split if");
1616     }
1617 #endif
1618     assert(new_false_region->in(1)->in(0)->in(1) == dom_if->in(1), "dominating if and dominated if after split must share test");
1619 
1620     // We now have:
1621     // if (some_condition) {
1622     //   // body 1
1623     //   if (some_condition) {
1624     //     body3: // new_true_region
1625     //     // body3
1626     //   } else {
1627     //     goto body4;
1628     //   }
1629     // } else {
1630     //   // body 2
1631     //  if (some_condition) {
1632     //     goto body3;
1633     //   } else {
1634     //     body4:   // new_false_region
1635     //     // body4;
1636     //   }
1637     // }
1638     //
1639 
1640     // clone pinned nodes thru the resulting regions
1641     push_pinned_nodes_thru_region(dom_if, new_true_region);
1642     push_pinned_nodes_thru_region(dom_if, new_false_region);
1643 
1644     // Optimize out the cloned ifs. Because pinned nodes were cloned, this also allows a CastPP that would be dependent
1645     // on a projection of n to have the dom_if as a control dependency. We don't want the CastPP to end up with an
1646     // unrelated control dependency.
1647     for (uint i = 1; i < new_false_region->req(); i++) {
1648       if (is_dominator(dom_proj_true, new_false_region->in(i))) {
1649         dominated_by(dom_proj_true, new_false_region->in(i)->in(0)->as_If());
1650       } else {
1651         assert(is_dominator(dom_proj_false, new_false_region->in(i)), "bad if");
1652         dominated_by(dom_proj_false, new_false_region->in(i)->in(0)->as_If());
1653       }
1654     }
1655     return true;
1656   }
1657   return false;
1658 }
1659 
1660 void PhaseIdealLoop::push_pinned_nodes_thru_region(IfNode* dom_if, Node* region) {
1661   for (DUIterator i = region->outs(); region->has_out(i); i++) {
1662     Node* u = region->out(i);
1663     if (!has_ctrl(u) || u->is_Phi() || !u->depends_only_on_test()) {
1664       continue;
1665     }
1666     assert(u->in(0) == region, "not a control dependent node?");
1667     uint j = 1;
1668     for (; j < u->req(); ++j) {
1669       Node* in = u->in(j);
1670       if (!is_dominator(ctrl_or_self(in), dom_if)) {
1671         break;
1672       }
1673     }
1674     if (j == u->req()) {
1675       Node *phi = PhiNode::make_blank(region, u);
1676       for (uint k = 1; k < region->req(); ++k) {
1677         Node* clone = u->clone();
1678         clone->set_req(0, region->in(k));
1679         register_new_node(clone, region->in(k));
1680         phi->init_req(k, clone);
1681       }
1682       register_new_node(phi, region);
1683       _igvn.replace_node(u, phi);
1684       --i;
1685     }
1686   }
1687 }
1688 
1689 bool PhaseIdealLoop::safe_for_if_replacement(const Node* dom) const {
1690   if (!dom->is_CountedLoopEnd()) {
1691     return true;
1692   }
1693   CountedLoopEndNode* le = dom->as_CountedLoopEnd();
1694   CountedLoopNode* cl = le->loopnode();
1695   if (cl == nullptr) {
1696     return true;
1697   }
1698   if (!cl->is_main_loop()) {
1699     return true;
1700   }
1701   if (cl->is_canonical_loop_entry() == nullptr) {
1702     return true;
1703   }
1704   // Further unrolling is possible so loop exit condition might change
1705   return false;
1706 }
1707 
1708 // See if a shared loop-varying computation has no loop-varying uses.
1709 // Happens if something is only used for JVM state in uncommon trap exits,
1710 // like various versions of induction variable+offset.  Clone the
1711 // computation per usage to allow it to sink out of the loop.
1712 void PhaseIdealLoop::try_sink_out_of_loop(Node* n) {
1713   bool is_raw_to_oop_cast = n->is_ConstraintCast() &&
1714                             n->in(1)->bottom_type()->isa_rawptr() &&
1715                             !n->bottom_type()->isa_rawptr();
1716 
1717   if (has_ctrl(n) &&
1718       !n->is_Phi() &&
1719       !n->is_Bool() &&
1720       !n->is_Proj() &&
1721       !n->is_MergeMem() &&
1722       !n->is_CMove() &&
1723       !n->is_OpaqueConstantBool() &&
1724       !n->is_OpaqueInitializedAssertionPredicate() &&
1725       !n->is_OpaqueTemplateAssertionPredicate() &&
1726       !is_raw_to_oop_cast && // don't extend live ranges of raw oops
1727       n->Opcode() != Op_CreateEx &&
1728       (KillPathsReachableByDeadTypeNode || !n->is_Type())
1729       ) {
1730     Node *n_ctrl = get_ctrl(n);
1731     IdealLoopTree *n_loop = get_loop(n_ctrl);
1732 
1733     if (n->in(0) != nullptr) {
1734       IdealLoopTree* loop_ctrl = get_loop(n->in(0));
1735       if (n_loop != loop_ctrl && n_loop->is_member(loop_ctrl)) {
1736         // n has a control input inside a loop but get_ctrl() is member of an outer loop. This could happen, for example,
1737         // for Div nodes inside a loop (control input inside loop) without a use except for an UCT (outside the loop).
1738         // Rewire control of n to right outside of the loop, regardless if its input(s) are later sunk or not.
1739         Node* maybe_pinned_n = n;
1740         Node* outside_ctrl = place_outside_loop(n_ctrl, loop_ctrl);
1741         if (!would_sink_below_pre_loop_exit(loop_ctrl, outside_ctrl)) {
1742           if (n->depends_only_on_test()) {
1743             // If this node depends_only_on_test, it will be rewired to a control input that is not
1744             // the correct test. As a result, it must be pinned otherwise it can be incorrectly
1745             // rewired to a dominating test equivalent to the new control.
1746             Node* pinned_clone = n->pin_node_under_control();
1747             if (pinned_clone != nullptr) {
1748               register_new_node(pinned_clone, n_ctrl);
1749               maybe_pinned_n = pinned_clone;
1750               _igvn.replace_node(n, pinned_clone);
1751             }
1752           }
1753           _igvn.replace_input_of(maybe_pinned_n, 0, outside_ctrl);
1754         }
1755       }
1756     }
1757     if (n_loop != _ltree_root && n->outcnt() > 1) {
1758       // Compute early control: needed for anti-dependence analysis. It's also possible that as a result of
1759       // previous transformations in this loop opts round, the node can be hoisted now: early control will tell us.
1760       Node* early_ctrl = compute_early_ctrl(n, n_ctrl);
1761       if (n_loop->is_member(get_loop(early_ctrl)) && // check that this one can't be hoisted now
1762           ctrl_of_all_uses_out_of_loop(n, early_ctrl, n_loop)) { // All uses in outer loops!
1763         if (n->is_Store() || n->is_LoadStore()) {
1764             assert(false, "no node with a side effect");
1765             C->record_failure("no node with a side effect");
1766             return;
1767         }
1768         Node* outer_loop_clone = nullptr;
1769         for (DUIterator_Last jmin, j = n->last_outs(jmin); j >= jmin;) {
1770           Node* u = n->last_out(j); // Clone private computation per use
1771           _igvn.rehash_node_delayed(u);
1772           Node* x = nullptr;
1773           if (n->in(0) != nullptr && n->depends_only_on_test()) {
1774             // If this node depends_only_on_test, it will be rewired to a control input that is not
1775             // the correct test. As a result, it must be pinned otherwise it can be incorrectly
1776             // rewired to a dominating test equivalent to the new control.
1777             x = n->pin_node_under_control();
1778           }
1779           if (x == nullptr) {
1780             x = n->clone();
1781           }
1782           Node* x_ctrl = nullptr;
1783           if (u->is_Phi()) {
1784             // Replace all uses of normal nodes.  Replace Phi uses
1785             // individually, so the separate Nodes can sink down
1786             // different paths.
1787             uint k = 1;
1788             while (u->in(k) != n) k++;
1789             u->set_req(k, x);
1790             // x goes next to Phi input path
1791             x_ctrl = u->in(0)->in(k);
1792             // Find control for 'x' next to use but not inside inner loops.
1793             x_ctrl = place_outside_loop(x_ctrl, n_loop);
1794             --j;
1795           } else {              // Normal use
1796             if (has_ctrl(u)) {
1797               x_ctrl = get_ctrl(u);
1798             } else {
1799               x_ctrl = u->in(0);
1800             }
1801             // Find control for 'x' next to use but not inside inner loops.
1802             x_ctrl = place_outside_loop(x_ctrl, n_loop);
1803             // Replace all uses
1804             if (u->is_ConstraintCast() && _igvn.type(n)->higher_equal(u->bottom_type()) && u->in(0) == x_ctrl) {
1805               // If we're sinking a chain of data nodes, we might have inserted a cast to pin the use which is not necessary
1806               // anymore now that we're going to pin n as well
1807               _igvn.replace_node(u, x);
1808               --j;
1809             } else {
1810               int nb = u->replace_edge(n, x, &_igvn);
1811               j -= nb;
1812             }
1813           }
1814 
1815           if (n->is_Load()) {
1816             // For loads, add a control edge to a CFG node outside of the loop
1817             // to force them to not combine and return back inside the loop
1818             // during GVN optimization (4641526).
1819             assert(x_ctrl == get_late_ctrl_with_anti_dep(x->as_Load(), early_ctrl, x_ctrl), "anti-dependences were already checked");
1820 
1821             IdealLoopTree* x_loop = get_loop(x_ctrl);
1822             Node* x_head = x_loop->_head;
1823             if (x_head->is_Loop() && x_head->is_OuterStripMinedLoop()) {
1824               // Do not add duplicate LoadNodes to the outer strip mined loop
1825               if (outer_loop_clone != nullptr) {
1826                 _igvn.replace_node(x, outer_loop_clone);
1827                 continue;
1828               }
1829               outer_loop_clone = x;
1830             }
1831             x->set_req(0, x_ctrl);
1832           } else if (n->in(0) != nullptr){
1833             x->set_req(0, x_ctrl);
1834           }
1835           assert(dom_depth(n_ctrl) <= dom_depth(x_ctrl), "n is later than its clone");
1836           assert(!n_loop->is_member(get_loop(x_ctrl)), "should have moved out of loop");
1837           register_new_node(x, x_ctrl);
1838 
1839           // Chain of AddP nodes: (AddP base (AddP base (AddP base )))
1840           // All AddP nodes must keep the same base after sinking so:
1841           // 1- We don't add a CastPP here until the last one of the chain is sunk: if part of the chain is not sunk,
1842           // their bases remain the same.
1843           // (see 2- below)
1844           assert(!x->is_AddP() || !x->in(AddPNode::Address)->is_AddP() ||
1845                  x->in(AddPNode::Address)->in(AddPNode::Base) == x->in(AddPNode::Base) ||
1846                  !x->in(AddPNode::Address)->in(AddPNode::Base)->eqv_uncast(x->in(AddPNode::Base)), "unexpected AddP shape");
1847           if (x->in(0) == nullptr && !x->is_DecodeNarrowPtr() &&
1848               !(x->is_AddP() && x->in(AddPNode::Address)->is_AddP() && x->in(AddPNode::Address)->in(AddPNode::Base) == x->in(AddPNode::Base))) {
1849             assert(!x->is_Load(), "load should be pinned");
1850             // Use a cast node to pin clone out of loop
1851             Node* cast = nullptr;
1852             for (uint k = 0; k < x->req(); k++) {
1853               Node* in = x->in(k);
1854               if (in != nullptr && ctrl_is_member(n_loop, in)) {
1855                 const Type* in_t = _igvn.type(in);
1856                 cast = ConstraintCastNode::make_cast_for_type(x_ctrl, in, in_t,
1857                                                               ConstraintCastNode::DependencyType::NonFloatingNonNarrowing, nullptr);
1858               }
1859               if (cast != nullptr) {
1860                 Node* prev = _igvn.hash_find_insert(cast);
1861                 if (prev != nullptr && get_ctrl(prev) == x_ctrl) {
1862                   cast->destruct(&_igvn);
1863                   cast = prev;
1864                 } else {
1865                   register_new_node(cast, x_ctrl);
1866                 }
1867                 x->replace_edge(in, cast);
1868                 // Chain of AddP nodes:
1869                 // 2- A CastPP of the base is only added now that all AddP nodes are sunk
1870                 if (x->is_AddP() && k == AddPNode::Base) {
1871                   update_addp_chain_base(x, n->in(AddPNode::Base), cast);
1872                 }
1873                 break;
1874               }
1875             }
1876             assert(cast != nullptr, "must have added a cast to pin the node");
1877           }
1878         }
1879         _igvn.remove_dead_node(n, PhaseIterGVN::NodeOrigin::Graph);
1880       }
1881       _dom_lca_tags_round = 0;
1882     }
1883   }
1884 }
1885 
1886 void PhaseIdealLoop::update_addp_chain_base(Node* x, Node* old_base, Node* new_base) {
1887   ResourceMark rm;
1888   Node_List wq;
1889   wq.push(x);
1890   while (wq.size() != 0) {
1891     Node* n = wq.pop();
1892     for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
1893       Node* u = n->fast_out(i);
1894       if (u->is_AddP() && u->in(AddPNode::Base) == old_base) {
1895         _igvn.replace_input_of(u, AddPNode::Base, new_base);
1896         wq.push(u);
1897       }
1898     }
1899   }
1900 }
1901 
1902 // Compute the early control of a node by following its inputs until we reach
1903 // nodes that are pinned. Then compute the LCA of the control of all pinned nodes.
1904 Node* PhaseIdealLoop::compute_early_ctrl(Node* n, Node* n_ctrl) {
1905   Node* early_ctrl = nullptr;
1906   ResourceMark rm;
1907   Unique_Node_List wq;
1908   wq.push(n);
1909   for (uint i = 0; i < wq.size(); i++) {
1910     Node* m = wq.at(i);
1911     Node* c = nullptr;
1912     if (m->is_CFG()) {
1913       c = m;
1914     } else if (m->pinned()) {
1915       c = m->in(0);
1916     } else {
1917       for (uint j = 0; j < m->req(); j++) {
1918         Node* in = m->in(j);
1919         if (in != nullptr) {
1920           wq.push(in);
1921         }
1922       }
1923     }
1924     if (c != nullptr) {
1925       assert(is_dominator(c, n_ctrl), "control input must dominate current control");
1926       if (early_ctrl == nullptr || is_dominator(early_ctrl, c)) {
1927         early_ctrl = c;
1928       }
1929     }
1930   }
1931   assert(is_dominator(early_ctrl, n_ctrl), "early control must dominate current control");
1932   return early_ctrl;
1933 }
1934 
1935 bool PhaseIdealLoop::ctrl_of_all_uses_out_of_loop(const Node* n, Node* n_ctrl, IdealLoopTree* n_loop) {
1936   for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
1937     Node* u = n->fast_out(i);
1938     if (u->is_Opaque1()) {
1939       return false;  // Found loop limit, bugfix for 4677003
1940     }
1941     if (u->is_Phi()) {
1942       for (uint j = 1; j < u->req(); ++j) {
1943         if (u->in(j) == n && !ctrl_of_use_out_of_loop(n, n_ctrl, n_loop, u->in(0)->in(j))) {
1944           return false;
1945         }
1946       }
1947     } else {
1948       Node* ctrl = has_ctrl(u) ? get_ctrl(u) : u->in(0);
1949       if (!ctrl_of_use_out_of_loop(n, n_ctrl, n_loop, ctrl)) {
1950         return false;
1951       }
1952     }
1953   }
1954   return true;
1955 }
1956 
1957 // Sinking a node from a pre loop to its main loop pins the node between the pre and main loops. If that node is input
1958 // to a check that's eliminated by range check elimination, it becomes input to an expression that feeds into the exit
1959 // test of the pre loop above the point in the graph where it's pinned. This results in a broken graph. One way to avoid
1960 // it would be to not eliminate the check in the main loop. Instead, we prevent sinking of the node here so better code
1961 // is generated for the main loop.
1962 bool PhaseIdealLoop::would_sink_below_pre_loop_exit(IdealLoopTree* n_loop, Node* ctrl) {
1963   if (n_loop->_head->is_CountedLoop() && n_loop->_head->as_CountedLoop()->is_pre_loop()) {
1964     CountedLoopNode* pre_loop = n_loop->_head->as_CountedLoop();
1965     if (is_dominator(pre_loop->loopexit(), ctrl)) {
1966       return true;
1967     }
1968   }
1969   return false;
1970 }
1971 
1972 bool PhaseIdealLoop::ctrl_of_use_out_of_loop(const Node* n, Node* n_ctrl, IdealLoopTree* n_loop, Node* ctrl) {
1973   if (n->is_Load()) {
1974     // We can't reuse tags in PhaseIdealLoop::dom_lca_for_get_late_ctrl_internal() so make sure each call to
1975     // get_late_ctrl_with_anti_dep() uses its own tag
1976     _dom_lca_tags_round++;
1977     assert(_dom_lca_tags_round != 0, "shouldn't wrap around");
1978 
1979     ctrl = get_late_ctrl_with_anti_dep(n->as_Load(), n_ctrl, ctrl);
1980   }
1981   IdealLoopTree *u_loop = get_loop(ctrl);
1982   if (u_loop == n_loop) {
1983     return false; // Found loop-varying use
1984   }
1985   if (n_loop->is_member(u_loop)) {
1986     return false; // Found use in inner loop
1987   }
1988   if (would_sink_below_pre_loop_exit(n_loop, ctrl)) {
1989     return false;
1990   }
1991   return true;
1992 }
1993 
1994 //------------------------------split_if_with_blocks---------------------------
1995 // Check for aggressive application of 'split-if' optimization,
1996 // using basic block level info.
1997 void PhaseIdealLoop::split_if_with_blocks(VectorSet &visited, Node_Stack &nstack) {
1998   Node* root = C->root();
1999   visited.set(root->_idx); // first, mark root as visited
2000   // Do pre-visit work for root
2001   Node* n   = split_if_with_blocks_pre(root);
2002   uint  cnt = n->outcnt();
2003   uint  i   = 0;
2004 
2005   while (true) {
2006     // Visit all children
2007     if (i < cnt) {
2008       Node* use = n->raw_out(i);
2009       ++i;
2010       if (use->outcnt() != 0 && !visited.test_set(use->_idx)) {
2011         // Now do pre-visit work for this use
2012         use = split_if_with_blocks_pre(use);
2013         nstack.push(n, i); // Save parent and next use's index.
2014         n   = use;         // Process all children of current use.
2015         cnt = use->outcnt();
2016         i   = 0;
2017       }
2018     }
2019     else {
2020       // All of n's children have been processed, complete post-processing.
2021       if (cnt != 0 && !n->is_Con()) {
2022         assert(has_node(n), "no dead nodes");
2023         split_if_with_blocks_post(n);
2024         if (C->failing()) {
2025           return;
2026         }
2027       }
2028       if (must_throttle_split_if()) {
2029         nstack.clear();
2030       }
2031       if (nstack.is_empty()) {
2032         // Finished all nodes on stack.
2033         break;
2034       }
2035       // Get saved parent node and next use's index. Visit the rest of uses.
2036       n   = nstack.node();
2037       cnt = n->outcnt();
2038       i   = nstack.index();
2039       nstack.pop();
2040     }
2041   }
2042 }
2043 
2044 
2045 //=============================================================================
2046 //
2047 //                   C L O N E   A   L O O P   B O D Y
2048 //
2049 
2050 //------------------------------clone_iff--------------------------------------
2051 // Passed in a Phi merging (recursively) some nearly equivalent Bool/Cmps.
2052 // "Nearly" because all Nodes have been cloned from the original in the loop,
2053 // but the fall-in edges to the Cmp are different.  Clone bool/Cmp pairs
2054 // through the Phi recursively, and return a Bool.
2055 Node* PhaseIdealLoop::clone_iff(PhiNode* phi) {
2056 
2057   // Convert this Phi into a Phi merging Bools
2058   uint i;
2059   for (i = 1; i < phi->req(); i++) {
2060     Node* b = phi->in(i);
2061     if (b->is_Phi()) {
2062       _igvn.replace_input_of(phi, i, clone_iff(b->as_Phi()));
2063     } else {
2064       assert(b->is_Bool() || b->is_OpaqueConstantBool() || b->is_OpaqueInitializedAssertionPredicate(),
2065              "bool, non-null check with OpaqueConstantBool or Initialized Assertion Predicate with its Opaque node");
2066     }
2067   }
2068   Node* n = phi->in(1);
2069   Node* sample_opaque = nullptr;
2070   Node *sample_bool = nullptr;
2071   if (n->is_OpaqueConstantBool() || n->is_OpaqueInitializedAssertionPredicate()) {
2072     sample_opaque = n;
2073     sample_bool = n->in(1);
2074     assert(sample_bool->is_Bool(), "wrong type");
2075   } else {
2076     sample_bool = n;
2077   }
2078   Node *sample_cmp = sample_bool->in(1);
2079 
2080   // Make Phis to merge the Cmp's inputs.
2081   PhiNode *phi1 = new PhiNode(phi->in(0), Type::TOP);
2082   PhiNode *phi2 = new PhiNode(phi->in(0), Type::TOP);
2083   for (i = 1; i < phi->req(); i++) {
2084     Node *n1 = sample_opaque == nullptr ? phi->in(i)->in(1)->in(1) : phi->in(i)->in(1)->in(1)->in(1);
2085     Node *n2 = sample_opaque == nullptr ? phi->in(i)->in(1)->in(2) : phi->in(i)->in(1)->in(1)->in(2);
2086     phi1->set_req(i, n1);
2087     phi2->set_req(i, n2);
2088     phi1->set_type(phi1->type()->meet_speculative(n1->bottom_type()));
2089     phi2->set_type(phi2->type()->meet_speculative(n2->bottom_type()));
2090   }
2091   // See if these Phis have been made before.
2092   // Register with optimizer
2093   Node *hit1 = _igvn.hash_find_insert(phi1);
2094   if (hit1) {                   // Hit, toss just made Phi
2095     _igvn.remove_dead_node(phi1, PhaseIterGVN::NodeOrigin::Speculative); // Remove new phi
2096     assert(hit1->is_Phi(), "" );
2097     phi1 = (PhiNode*)hit1;      // Use existing phi
2098   } else {                      // Miss
2099     _igvn.register_new_node_with_optimizer(phi1);
2100   }
2101   Node *hit2 = _igvn.hash_find_insert(phi2);
2102   if (hit2) {                   // Hit, toss just made Phi
2103     _igvn.remove_dead_node(phi2, PhaseIterGVN::NodeOrigin::Speculative); // Remove new phi
2104     assert(hit2->is_Phi(), "" );
2105     phi2 = (PhiNode*)hit2;      // Use existing phi
2106   } else {                      // Miss
2107     _igvn.register_new_node_with_optimizer(phi2);
2108   }
2109   // Register Phis with loop/block info
2110   set_ctrl(phi1, phi->in(0));
2111   set_ctrl(phi2, phi->in(0));
2112   // Make a new Cmp
2113   Node *cmp = sample_cmp->clone();
2114   cmp->set_req(1, phi1);
2115   cmp->set_req(2, phi2);
2116   _igvn.register_new_node_with_optimizer(cmp);
2117   set_ctrl(cmp, phi->in(0));
2118 
2119   // Make a new Bool
2120   Node *b = sample_bool->clone();
2121   b->set_req(1,cmp);
2122   _igvn.register_new_node_with_optimizer(b);
2123   set_ctrl(b, phi->in(0));
2124 
2125   if (sample_opaque != nullptr) {
2126     Node* opaque = sample_opaque->clone();
2127     opaque->set_req(1, b);
2128     _igvn.register_new_node_with_optimizer(opaque);
2129     set_ctrl(opaque, phi->in(0));
2130     return opaque;
2131   }
2132 
2133   assert(b->is_Bool(), "");
2134   return b;
2135 }
2136 
2137 //------------------------------clone_bool-------------------------------------
2138 // Passed in a Phi merging (recursively) some nearly equivalent Bool/Cmps.
2139 // "Nearly" because all Nodes have been cloned from the original in the loop,
2140 // but the fall-in edges to the Cmp are different.  Clone bool/Cmp pairs
2141 // through the Phi recursively, and return a Bool.
2142 CmpNode*PhaseIdealLoop::clone_bool(PhiNode* phi) {
2143   uint i;
2144   // Convert this Phi into a Phi merging Bools
2145   for( i = 1; i < phi->req(); i++ ) {
2146     Node *b = phi->in(i);
2147     if( b->is_Phi() ) {
2148       _igvn.replace_input_of(phi, i, clone_bool(b->as_Phi()));
2149     } else {
2150       assert( b->is_Cmp() || b->is_top(), "inputs are all Cmp or TOP" );
2151     }
2152   }
2153 
2154   Node *sample_cmp = phi->in(1);
2155 
2156   // Make Phis to merge the Cmp's inputs.
2157   PhiNode *phi1 = new PhiNode( phi->in(0), Type::TOP );
2158   PhiNode *phi2 = new PhiNode( phi->in(0), Type::TOP );
2159   for( uint j = 1; j < phi->req(); j++ ) {
2160     Node *cmp_top = phi->in(j); // Inputs are all Cmp or TOP
2161     Node *n1, *n2;
2162     if( cmp_top->is_Cmp() ) {
2163       n1 = cmp_top->in(1);
2164       n2 = cmp_top->in(2);
2165     } else {
2166       n1 = n2 = cmp_top;
2167     }
2168     phi1->set_req( j, n1 );
2169     phi2->set_req( j, n2 );
2170     phi1->set_type(phi1->type()->meet_speculative(n1->bottom_type()));
2171     phi2->set_type(phi2->type()->meet_speculative(n2->bottom_type()));
2172   }
2173 
2174   // See if these Phis have been made before.
2175   // Register with optimizer
2176   Node *hit1 = _igvn.hash_find_insert(phi1);
2177   if( hit1 ) {                  // Hit, toss just made Phi
2178     _igvn.remove_dead_node(phi1, PhaseIterGVN::NodeOrigin::Speculative); // Remove new phi
2179     assert( hit1->is_Phi(), "" );
2180     phi1 = (PhiNode*)hit1;      // Use existing phi
2181   } else {                      // Miss
2182     _igvn.register_new_node_with_optimizer(phi1);
2183   }
2184   Node *hit2 = _igvn.hash_find_insert(phi2);
2185   if( hit2 ) {                  // Hit, toss just made Phi
2186     _igvn.remove_dead_node(phi2, PhaseIterGVN::NodeOrigin::Speculative); // Remove new phi
2187     assert( hit2->is_Phi(), "" );
2188     phi2 = (PhiNode*)hit2;      // Use existing phi
2189   } else {                      // Miss
2190     _igvn.register_new_node_with_optimizer(phi2);
2191   }
2192   // Register Phis with loop/block info
2193   set_ctrl(phi1, phi->in(0));
2194   set_ctrl(phi2, phi->in(0));
2195   // Make a new Cmp
2196   Node *cmp = sample_cmp->clone();
2197   cmp->set_req( 1, phi1 );
2198   cmp->set_req( 2, phi2 );
2199   _igvn.register_new_node_with_optimizer(cmp);
2200   set_ctrl(cmp, phi->in(0));
2201 
2202   assert( cmp->is_Cmp(), "" );
2203   return (CmpNode*)cmp;
2204 }
2205 
2206 void PhaseIdealLoop::clone_loop_handle_data_uses(Node* old, Node_List &old_new,
2207                                                  IdealLoopTree* loop, IdealLoopTree* outer_loop,
2208                                                  Node_List*& split_if_set, Node_List*& split_bool_set,
2209                                                  Node_List*& split_cex_set, Node_List& worklist,
2210                                                  uint new_counter, CloneLoopMode mode) {
2211   Node* nnn = old_new[old->_idx];
2212   // Copy uses to a worklist, so I can munge the def-use info
2213   // with impunity.
2214   for (DUIterator_Fast jmax, j = old->fast_outs(jmax); j < jmax; j++)
2215     worklist.push(old->fast_out(j));
2216 
2217   while( worklist.size() ) {
2218     Node *use = worklist.pop();
2219     if (!has_node(use))  continue; // Ignore dead nodes
2220     if (use->in(0) == C->top())  continue;
2221     IdealLoopTree *use_loop = get_loop( has_ctrl(use) ? get_ctrl(use) : use );
2222     // Check for data-use outside of loop - at least one of OLD or USE
2223     // must not be a CFG node.
2224 #ifdef ASSERT
2225     if (loop->_head->as_Loop()->is_strip_mined() && outer_loop->is_member(use_loop) && !loop->is_member(use_loop) && old_new[use->_idx] == nullptr) {
2226       Node* sfpt = loop->_head->as_CountedLoop()->outer_safepoint();
2227       assert(mode != IgnoreStripMined, "incorrect cloning mode");
2228       assert((mode == ControlAroundStripMined && use == sfpt) || !use->is_reachable_from_root(), "missed a node");
2229     }
2230 #endif
2231     if (!loop->is_member(use_loop) && !outer_loop->is_member(use_loop) && (!old->is_CFG() || !use->is_CFG())) {
2232 
2233       // If the Data use is an IF, that means we have an IF outside the
2234       // loop that is switching on a condition that is set inside the
2235       // loop.  Happens if people set a loop-exit flag; then test the flag
2236       // in the loop to break the loop, then test is again outside the
2237       // loop to determine which way the loop exited.
2238       //
2239       // For several uses we need to make sure that there is no phi between,
2240       // the use and the Bool/Cmp. We therefore clone the Bool/Cmp down here
2241       // to avoid such a phi in between.
2242       // For example, it is unexpected that there is a Phi between an
2243       // AllocateArray node and its ValidLengthTest input that could cause
2244       // split if to break.
2245       assert(!use->is_OpaqueTemplateAssertionPredicate(),
2246              "should not clone a Template Assertion Predicate which should be removed once it's useless");
2247       if (use->is_If() || use->is_CMove() || use->is_OpaqueConstantBool() || use->is_OpaqueInitializedAssertionPredicate() ||
2248           (use->Opcode() == Op_AllocateArray && use->in(AllocateNode::ValidLengthTest) == old)) {
2249         // Since this code is highly unlikely, we lazily build the worklist
2250         // of such Nodes to go split.
2251         if (!split_if_set) {
2252           split_if_set = new Node_List();
2253         }
2254         split_if_set->push(use);
2255       }
2256       if (use->is_Bool()) {
2257         if (!split_bool_set) {
2258           split_bool_set = new Node_List();
2259         }
2260         split_bool_set->push(use);
2261       }
2262       if (use->Opcode() == Op_CreateEx) {
2263         if (!split_cex_set) {
2264           split_cex_set = new Node_List();
2265         }
2266         split_cex_set->push(use);
2267       }
2268 
2269 
2270       // Get "block" use is in
2271       uint idx = 0;
2272       while( use->in(idx) != old ) idx++;
2273       Node *prev = use->is_CFG() ? use : get_ctrl(use);
2274       assert(!loop->is_member(get_loop(prev)) && !outer_loop->is_member(get_loop(prev)), "" );
2275       Node* cfg = (prev->_idx >= new_counter && prev->is_Region())
2276         ? prev->in(2)
2277         : idom(prev);
2278       if( use->is_Phi() )     // Phi use is in prior block
2279         cfg = prev->in(idx);  // NOT in block of Phi itself
2280       if (cfg->is_top()) {    // Use is dead?
2281         _igvn.replace_input_of(use, idx, C->top());
2282         continue;
2283       }
2284 
2285       // If use is referenced through control edge... (idx == 0)
2286       if (mode == IgnoreStripMined && idx == 0) {
2287         LoopNode *head = loop->_head->as_Loop();
2288         if (head->is_strip_mined() && is_dominator(head->outer_loop_exit(), prev)) {
2289           // That node is outside the inner loop, leave it outside the
2290           // outer loop as well to not confuse verification code.
2291           assert(!loop->_parent->is_member(use_loop), "should be out of the outer loop");
2292           _igvn.replace_input_of(use, 0, head->outer_loop_exit());
2293           continue;
2294         }
2295       }
2296 
2297       while(!outer_loop->is_member(get_loop(cfg))) {
2298         prev = cfg;
2299         cfg = (cfg->_idx >= new_counter && cfg->is_Region()) ? cfg->in(2) : idom(cfg);
2300       }
2301       // If the use occurs after merging several exits from the loop, then
2302       // old value must have dominated all those exits.  Since the same old
2303       // value was used on all those exits we did not need a Phi at this
2304       // merge point.  NOW we do need a Phi here.  Each loop exit value
2305       // is now merged with the peeled body exit; each exit gets its own
2306       // private Phi and those Phis need to be merged here.
2307       Node *phi;
2308       if( prev->is_Region() ) {
2309         if( idx == 0 ) {      // Updating control edge?
2310           phi = prev;         // Just use existing control
2311         } else {              // Else need a new Phi
2312           phi = PhiNode::make( prev, old );
2313           // Now recursively fix up the new uses of old!
2314           for( uint i = 1; i < prev->req(); i++ ) {
2315             worklist.push(phi); // Onto worklist once for each 'old' input
2316           }
2317         }
2318       } else {
2319         // Get new RegionNode merging old and new loop exits
2320         prev = old_new[prev->_idx];
2321         assert( prev, "just made this in step 7" );
2322         if( idx == 0) {      // Updating control edge?
2323           phi = prev;         // Just use existing control
2324         } else {              // Else need a new Phi
2325           // Make a new Phi merging data values properly
2326           phi = PhiNode::make( prev, old );
2327           phi->set_req( 1, nnn );
2328         }
2329       }
2330       // If inserting a new Phi, check for prior hits
2331       if( idx != 0 ) {
2332         Node *hit = _igvn.hash_find_insert(phi);
2333         if( hit == nullptr ) {
2334           _igvn.register_new_node_with_optimizer(phi); // Register new phi
2335         } else {                                      // or
2336           // Remove the new phi from the graph and use the hit
2337           _igvn.remove_dead_node(phi, phi == prev ? PhaseIterGVN::NodeOrigin::Graph : PhaseIterGVN::NodeOrigin::Speculative);
2338           phi = hit;                                  // Use existing phi
2339         }
2340         set_ctrl(phi, prev);
2341       }
2342       // Make 'use' use the Phi instead of the old loop body exit value
2343       assert(use->in(idx) == old, "old is still input of use");
2344       // We notify all uses of old, including use, and the indirect uses,
2345       // that may now be optimized because we have replaced old with phi.
2346       _igvn.add_users_to_worklist(old);
2347       if (idx == 0 && use->depends_only_on_test()) {
2348         // If this node depends_only_on_test, it will be rewired to a control input that is not the
2349         // correct test. As a result, it must be pinned otherwise it can be incorrectly rewired to
2350         // a dominating test equivalent to the new control.
2351         Node* pinned_clone = use->pin_node_under_control();
2352         if (pinned_clone != nullptr) {
2353           pinned_clone->set_req(0, phi);
2354           register_new_node_with_ctrl_of(pinned_clone, use);
2355           _igvn.replace_node(use, pinned_clone);
2356           continue;
2357         }
2358       }
2359       _igvn.replace_input_of(use, idx, phi);
2360       if( use->_idx >= new_counter ) { // If updating new phis
2361         // Not needed for correctness, but prevents a weak assert
2362         // in AddPNode from tripping (when we end up with different
2363         // base & derived Phis that will become the same after
2364         // IGVN does CSE).
2365         Node *hit = _igvn.hash_find_insert(use);
2366         if( hit )             // Go ahead and re-hash for hits.
2367           _igvn.replace_node( use, hit );
2368       }
2369     }
2370   }
2371 }
2372 
2373 static void collect_nodes_in_outer_loop_not_reachable_from_sfpt(Node* n, const IdealLoopTree *loop, const IdealLoopTree* outer_loop,
2374                                                                 const Node_List &old_new, Unique_Node_List& wq, PhaseIdealLoop* phase,
2375                                                                 bool check_old_new) {
2376   for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++) {
2377     Node* u = n->fast_out(j);
2378     assert(check_old_new || old_new[u->_idx] == nullptr, "shouldn't have been cloned");
2379     if (!u->is_CFG() && (!check_old_new || old_new[u->_idx] == nullptr)) {
2380       assert(!phase->ctrl_is_member(loop, u) || !loop->_body.contains(u), "can be in outer loop or out of both loops only");
2381       if (!phase->ctrl_is_member(loop, u)) {
2382         if (phase->ctrl_is_member(outer_loop, u)) {
2383           wq.push(u);
2384         } else {
2385           // nodes pinned with control in the outer loop but not referenced from the safepoint must be moved out of
2386           // the outer loop too
2387           Node* u_c = u->in(0);
2388           if (u_c != nullptr) {
2389             IdealLoopTree* u_c_loop = phase->get_loop(u_c);
2390             if (outer_loop->is_member(u_c_loop) && !loop->is_member(u_c_loop)) {
2391               wq.push(u);
2392             }
2393           }
2394         }
2395       }
2396     }
2397   }
2398 }
2399 
2400 void PhaseIdealLoop::clone_outer_loop(LoopNode* head, CloneLoopMode mode, IdealLoopTree *loop,
2401                                       IdealLoopTree* outer_loop, int dd, Node_List &old_new,
2402                                       Node_List& extra_data_nodes) {
2403   if (head->is_strip_mined() && mode != IgnoreStripMined) {
2404     CountedLoopNode* cl = head->as_CountedLoop();
2405     Node* l = cl->outer_loop();
2406     Node* tail = cl->outer_loop_tail();
2407     IfNode* le = cl->outer_loop_end();
2408     Node* sfpt = cl->outer_safepoint();
2409     CountedLoopEndNode* cle = cl->loopexit();
2410     CountedLoopNode* new_cl = old_new[cl->_idx]->as_CountedLoop();
2411     CountedLoopEndNode* new_cle = new_cl->as_CountedLoop()->loopexit_or_null();
2412     IfFalseNode* cle_out = cle->false_proj();
2413 
2414     Node* new_sfpt = nullptr;
2415     Node* new_cle_out = cle_out->clone();
2416     old_new.map(cle_out->_idx, new_cle_out);
2417     if (mode == CloneIncludesStripMined) {
2418       // clone outer loop body
2419       Node* new_l = l->clone();
2420       Node* new_tail = tail->clone();
2421       IfNode* new_le = le->clone()->as_If();
2422       new_sfpt = sfpt->clone();
2423 
2424       set_loop(new_l, outer_loop->_parent);
2425       set_idom(new_l, new_l->in(LoopNode::EntryControl), dd);
2426       set_loop(new_cle_out, outer_loop->_parent);
2427       set_idom(new_cle_out, new_cle, dd);
2428       set_loop(new_sfpt, outer_loop->_parent);
2429       set_idom(new_sfpt, new_cle_out, dd);
2430       set_loop(new_le, outer_loop->_parent);
2431       set_idom(new_le, new_sfpt, dd);
2432       set_loop(new_tail, outer_loop->_parent);
2433       set_idom(new_tail, new_le, dd);
2434       set_idom(new_cl, new_l, dd);
2435 
2436       old_new.map(l->_idx, new_l);
2437       old_new.map(tail->_idx, new_tail);
2438       old_new.map(le->_idx, new_le);
2439       old_new.map(sfpt->_idx, new_sfpt);
2440 
2441       new_l->set_req(LoopNode::LoopBackControl, new_tail);
2442       new_l->set_req(0, new_l);
2443       new_tail->set_req(0, new_le);
2444       new_le->set_req(0, new_sfpt);
2445       new_sfpt->set_req(0, new_cle_out);
2446       new_cle_out->set_req(0, new_cle);
2447       new_cl->set_req(LoopNode::EntryControl, new_l);
2448 
2449       _igvn.register_new_node_with_optimizer(new_l);
2450       _igvn.register_new_node_with_optimizer(new_tail);
2451       _igvn.register_new_node_with_optimizer(new_le);
2452     } else {
2453       Node *newhead = old_new[loop->_head->_idx];
2454       newhead->as_Loop()->clear_strip_mined();
2455       _igvn.replace_input_of(newhead, LoopNode::EntryControl, newhead->in(LoopNode::EntryControl)->in(LoopNode::EntryControl));
2456       set_idom(newhead, newhead->in(LoopNode::EntryControl), dd);
2457     }
2458     // Look at data node that were assigned a control in the outer
2459     // loop: they are kept in the outer loop by the safepoint so start
2460     // from the safepoint node's inputs.
2461     IdealLoopTree* outer_loop = get_loop(l);
2462     Node_Stack stack(2);
2463     stack.push(sfpt, 1);
2464     uint new_counter = C->unique();
2465     while (stack.size() > 0) {
2466       Node* n = stack.node();
2467       uint i = stack.index();
2468       while (i < n->req() &&
2469              (n->in(i) == nullptr ||
2470               !has_ctrl(n->in(i)) ||
2471               get_loop(get_ctrl(n->in(i))) != outer_loop ||
2472               (old_new[n->in(i)->_idx] != nullptr && old_new[n->in(i)->_idx]->_idx >= new_counter))) {
2473         i++;
2474       }
2475       if (i < n->req()) {
2476         stack.set_index(i+1);
2477         stack.push(n->in(i), 0);
2478       } else {
2479         assert(old_new[n->_idx] == nullptr || n == sfpt || old_new[n->_idx]->_idx < new_counter, "no clone yet");
2480         Node* m = n == sfpt ? new_sfpt : n->clone();
2481         if (m != nullptr) {
2482           for (uint i = 0; i < n->req(); i++) {
2483             if (m->in(i) != nullptr && old_new[m->in(i)->_idx] != nullptr) {
2484               m->set_req(i, old_new[m->in(i)->_idx]);
2485             }
2486           }
2487         } else {
2488           assert(n == sfpt && mode != CloneIncludesStripMined, "where's the safepoint clone?");
2489         }
2490         if (n != sfpt) {
2491           extra_data_nodes.push(n);
2492           _igvn.register_new_node_with_optimizer(m);
2493           assert(get_ctrl(n) == cle_out, "what other control?");
2494           set_ctrl(m, new_cle_out);
2495           old_new.map(n->_idx, m);
2496         }
2497         stack.pop();
2498       }
2499     }
2500     if (mode == CloneIncludesStripMined) {
2501       _igvn.register_new_node_with_optimizer(new_sfpt);
2502       _igvn.register_new_node_with_optimizer(new_cle_out);
2503     }
2504     // Some other transformation may have pessimistically assigned some
2505     // data nodes to the outer loop. Set their control so they are out
2506     // of the outer loop.
2507     ResourceMark rm;
2508     Unique_Node_List wq;
2509     for (uint i = 0; i < extra_data_nodes.size(); i++) {
2510       Node* old = extra_data_nodes.at(i);
2511       collect_nodes_in_outer_loop_not_reachable_from_sfpt(old, loop, outer_loop, old_new, wq, this, true);
2512     }
2513 
2514     for (uint i = 0; i < loop->_body.size(); i++) {
2515       Node* old = loop->_body.at(i);
2516       collect_nodes_in_outer_loop_not_reachable_from_sfpt(old, loop, outer_loop, old_new, wq, this, true);
2517     }
2518 
2519     Node* inner_out = sfpt->in(0);
2520     if (inner_out->outcnt() > 1) {
2521       collect_nodes_in_outer_loop_not_reachable_from_sfpt(inner_out, loop, outer_loop, old_new, wq, this, true);
2522     }
2523 
2524     Node* new_ctrl = cl->outer_loop_exit();
2525     assert(get_loop(new_ctrl) != outer_loop, "must be out of the loop nest");
2526     for (uint i = 0; i < wq.size(); i++) {
2527       Node* n = wq.at(i);
2528       set_ctrl(n, new_ctrl);
2529       if (n->in(0) != nullptr) {
2530         _igvn.replace_input_of(n, 0, new_ctrl);
2531       }
2532       collect_nodes_in_outer_loop_not_reachable_from_sfpt(n, loop, outer_loop, old_new, wq, this, false);
2533     }
2534   } else {
2535     Node *newhead = old_new[loop->_head->_idx];
2536     set_idom(newhead, newhead->in(LoopNode::EntryControl), dd);
2537   }
2538 }
2539 
2540 //------------------------------clone_loop-------------------------------------
2541 //
2542 //                   C L O N E   A   L O O P   B O D Y
2543 //
2544 // This is the basic building block of the loop optimizations.  It clones an
2545 // entire loop body.  It makes an old_new loop body mapping; with this mapping
2546 // you can find the new-loop equivalent to an old-loop node.  All new-loop
2547 // nodes are exactly equal to their old-loop counterparts, all edges are the
2548 // same.  All exits from the old-loop now have a RegionNode that merges the
2549 // equivalent new-loop path.  This is true even for the normal "loop-exit"
2550 // condition.  All uses of loop-invariant old-loop values now come from (one
2551 // or more) Phis that merge their new-loop equivalents.
2552 //
2553 // This operation leaves the graph in an illegal state: there are two valid
2554 // control edges coming from the loop pre-header to both loop bodies.  I'll
2555 // definitely have to hack the graph after running this transform.
2556 //
2557 // From this building block I will further edit edges to perform loop peeling
2558 // or loop unrolling or iteration splitting (Range-Check-Elimination), etc.
2559 //
2560 // Parameter side_by_size_idom:
2561 //   When side_by_size_idom is null, the dominator tree is constructed for
2562 //      the clone loop to dominate the original.  Used in construction of
2563 //      pre-main-post loop sequence.
2564 //   When nonnull, the clone and original are side-by-side, both are
2565 //      dominated by the side_by_side_idom node.  Used in construction of
2566 //      unswitched loops.
2567 void PhaseIdealLoop::clone_loop( IdealLoopTree *loop, Node_List &old_new, int dd,
2568                                 CloneLoopMode mode, Node* side_by_side_idom) {
2569 
2570   LoopNode* head = loop->_head->as_Loop();
2571   head->verify_strip_mined(1);
2572 
2573   if (C->do_vector_loop() && PrintOpto) {
2574     const char* mname = C->method()->name()->as_quoted_ascii();
2575     if (mname != nullptr) {
2576       tty->print("PhaseIdealLoop::clone_loop: for vectorize method %s\n", mname);
2577     }
2578   }
2579 
2580   CloneMap& cm = C->clone_map();
2581   if (C->do_vector_loop()) {
2582     cm.set_clone_idx(cm.max_gen()+1);
2583 #ifndef PRODUCT
2584     if (PrintOpto) {
2585       tty->print_cr("PhaseIdealLoop::clone_loop: _clone_idx %d", cm.clone_idx());
2586       loop->dump_head();
2587     }
2588 #endif
2589   }
2590 
2591   // Step 1: Clone the loop body.  Make the old->new mapping.
2592   clone_loop_body(loop->_body, old_new, &cm);
2593 
2594   IdealLoopTree* outer_loop = (head->is_strip_mined() && mode != IgnoreStripMined) ? get_loop(head->as_CountedLoop()->outer_loop()) : loop;
2595 
2596   // Step 2: Fix the edges in the new body.  If the old input is outside the
2597   // loop use it.  If the old input is INside the loop, use the corresponding
2598   // new node instead.
2599   fix_body_edges(loop->_body, loop, old_new, dd, outer_loop->_parent, false);
2600 
2601   Node_List extra_data_nodes; // data nodes in the outer strip mined loop
2602   clone_outer_loop(head, mode, loop, outer_loop, dd, old_new, extra_data_nodes);
2603 
2604   // Step 3: Now fix control uses.  Loop varying control uses have already
2605   // been fixed up (as part of all input edges in Step 2).  Loop invariant
2606   // control uses must be either an IfFalse or an IfTrue.  Make a merge
2607   // point to merge the old and new IfFalse/IfTrue nodes; make the use
2608   // refer to this.
2609   Node_List worklist;
2610   uint new_counter = C->unique();
2611   fix_ctrl_uses(loop->_body, loop, old_new, mode, side_by_side_idom, &cm, worklist);
2612 
2613   // Step 4: If loop-invariant use is not control, it must be dominated by a
2614   // loop exit IfFalse/IfTrue.  Find "proper" loop exit.  Make a Region
2615   // there if needed.  Make a Phi there merging old and new used values.
2616   Node_List *split_if_set = nullptr;
2617   Node_List *split_bool_set = nullptr;
2618   Node_List *split_cex_set = nullptr;
2619   fix_data_uses(loop->_body, loop, mode, outer_loop, new_counter, old_new, worklist, split_if_set, split_bool_set, split_cex_set);
2620 
2621   for (uint i = 0; i < extra_data_nodes.size(); i++) {
2622     Node* old = extra_data_nodes.at(i);
2623     clone_loop_handle_data_uses(old, old_new, loop, outer_loop, split_if_set,
2624                                 split_bool_set, split_cex_set, worklist, new_counter,
2625                                 mode);
2626   }
2627 
2628   // Check for IFs that need splitting/cloning.  Happens if an IF outside of
2629   // the loop uses a condition set in the loop.  The original IF probably
2630   // takes control from one or more OLD Regions (which in turn get from NEW
2631   // Regions).  In any case, there will be a set of Phis for each merge point
2632   // from the IF up to where the original BOOL def exists the loop.
2633   finish_clone_loop(split_if_set, split_bool_set, split_cex_set);
2634 
2635 }
2636 
2637 void PhaseIdealLoop::finish_clone_loop(Node_List* split_if_set, Node_List* split_bool_set, Node_List* split_cex_set) {
2638   if (split_if_set) {
2639     while (split_if_set->size()) {
2640       Node *iff = split_if_set->pop();
2641       uint input = iff->Opcode() == Op_AllocateArray ? AllocateNode::ValidLengthTest : 1;
2642       if (iff->in(input)->is_Phi()) {
2643         Node *b = clone_iff(iff->in(input)->as_Phi());
2644         _igvn.replace_input_of(iff, input, b);
2645       }
2646     }
2647   }
2648   if (split_bool_set) {
2649     while (split_bool_set->size()) {
2650       Node *b = split_bool_set->pop();
2651       Node *phi = b->in(1);
2652       assert(phi->is_Phi(), "");
2653       CmpNode *cmp = clone_bool((PhiNode*) phi);
2654       _igvn.replace_input_of(b, 1, cmp);
2655     }
2656   }
2657   if (split_cex_set) {
2658     while (split_cex_set->size()) {
2659       Node *b = split_cex_set->pop();
2660       assert(b->in(0)->is_Region(), "");
2661       assert(b->in(1)->is_Phi(), "");
2662       assert(b->in(0)->in(0) == b->in(1)->in(0), "");
2663       split_up(b, b->in(0), nullptr);
2664     }
2665   }
2666 }
2667 
2668 void PhaseIdealLoop::fix_data_uses(Node_List& body, IdealLoopTree* loop, CloneLoopMode mode, IdealLoopTree* outer_loop,
2669                                    uint new_counter, Node_List &old_new, Node_List &worklist, Node_List*& split_if_set,
2670                                    Node_List*& split_bool_set, Node_List*& split_cex_set) {
2671   for(uint i = 0; i < body.size(); i++ ) {
2672     Node* old = body.at(i);
2673     clone_loop_handle_data_uses(old, old_new, loop, outer_loop, split_if_set,
2674                                 split_bool_set, split_cex_set, worklist, new_counter,
2675                                 mode);
2676   }
2677 }
2678 
2679 void PhaseIdealLoop::fix_ctrl_uses(const Node_List& body, const IdealLoopTree* loop, Node_List &old_new, CloneLoopMode mode,
2680                                    Node* side_by_side_idom, CloneMap* cm, Node_List &worklist) {
2681   LoopNode* head = loop->_head->as_Loop();
2682   for(uint i = 0; i < body.size(); i++ ) {
2683     Node* old = body.at(i);
2684     if( !old->is_CFG() ) continue;
2685 
2686     // Copy uses to a worklist, so I can munge the def-use info
2687     // with impunity.
2688     for (DUIterator_Fast jmax, j = old->fast_outs(jmax); j < jmax; j++) {
2689       worklist.push(old->fast_out(j));
2690     }
2691 
2692     while (worklist.size()) {  // Visit all uses
2693       Node *use = worklist.pop();
2694       if (!has_node(use))  continue; // Ignore dead nodes
2695       IdealLoopTree *use_loop = get_loop(has_ctrl(use) ? get_ctrl(use) : use );
2696       if (!loop->is_member(use_loop) && use->is_CFG()) {
2697         // Both OLD and USE are CFG nodes here.
2698         assert(use->is_Proj(), "" );
2699         Node* nnn = old_new[old->_idx];
2700 
2701         Node* newuse = nullptr;
2702         if (head->is_strip_mined() && mode != IgnoreStripMined) {
2703           CountedLoopNode* cl = head->as_CountedLoop();
2704           CountedLoopEndNode* cle = cl->loopexit();
2705           // is use the projection that exits the loop from the CountedLoopEndNode?
2706           if (use->in(0) == cle) {
2707             IfFalseNode* cle_out = use->as_IfFalse();
2708             IfNode* le = cl->outer_loop_end();
2709             use = le->false_proj();
2710             use_loop = get_loop(use);
2711             if (mode == CloneIncludesStripMined) {
2712               nnn = old_new[le->_idx];
2713             } else {
2714               newuse = old_new[cle_out->_idx];
2715             }
2716           }
2717         }
2718         if (newuse == nullptr) {
2719           newuse = use->clone();
2720         }
2721 
2722         // Clone the loop exit control projection
2723         if (C->do_vector_loop() && cm != nullptr) {
2724           cm->verify_insert_and_clone(use, newuse, cm->clone_idx());
2725         }
2726         newuse->set_req(0,nnn);
2727         _igvn.register_new_node_with_optimizer(newuse);
2728         set_loop(newuse, use_loop);
2729         set_idom(newuse, nnn, dom_depth(nnn) + 1 );
2730 
2731         // We need a Region to merge the exit from the peeled body and the
2732         // exit from the old loop body.
2733         RegionNode *r = new RegionNode(3);
2734         uint dd_r = MIN2(dom_depth(newuse), dom_depth(use));
2735         assert(dd_r >= dom_depth(dom_lca(newuse, use)), "" );
2736 
2737         // The original user of 'use' uses 'r' instead.
2738         for (DUIterator_Last lmin, l = use->last_outs(lmin); l >= lmin;) {
2739           Node* useuse = use->last_out(l);
2740           _igvn.rehash_node_delayed(useuse);
2741           uint uses_found = 0;
2742           if (useuse->in(0) == use) {
2743             useuse->set_req(0, r);
2744             uses_found++;
2745             if (useuse->is_CFG()) {
2746               // This is not a dom_depth > dd_r because when new
2747               // control flow is constructed by a loop opt, a node and
2748               // its dominator can end up at the same dom_depth
2749               assert(dom_depth(useuse) >= dd_r, "");
2750               set_idom(useuse, r, dom_depth(useuse));
2751             }
2752           }
2753           for (uint k = 1; k < useuse->req(); k++) {
2754             if( useuse->in(k) == use ) {
2755               useuse->set_req(k, r);
2756               uses_found++;
2757               if (useuse->is_Loop() && k == LoopNode::EntryControl) {
2758                 // This is not a dom_depth > dd_r because when new
2759                 // control flow is constructed by a loop opt, a node
2760                 // and its dominator can end up at the same dom_depth
2761                 assert(dom_depth(useuse) >= dd_r , "");
2762                 set_idom(useuse, r, dom_depth(useuse));
2763               }
2764             }
2765           }
2766           l -= uses_found;    // we deleted 1 or more copies of this edge
2767         }
2768 
2769         assert(use->is_Proj(), "loop exit should be projection");
2770         // replace_node_and_forward_ctrl() below moves all nodes that are:
2771         // - control dependent on the loop exit or
2772         // - have control set to the loop exit
2773         // below the post-loop merge point.
2774         // replace_node_and_forward_ctrl() takes a dead control as first input.
2775         // To make it possible to use it, the loop exit projection is cloned and becomes the
2776         // new exit projection. The initial one becomes dead and is "replaced" by the region.
2777         Node* use_clone = use->clone();
2778         register_control(use_clone, use_loop, idom(use), dom_depth(use));
2779         // Now finish up 'r'
2780         r->set_req(1, newuse);
2781         r->set_req(2, use_clone);
2782         _igvn.register_new_node_with_optimizer(r);
2783         set_loop(r, use_loop);
2784         set_idom(r, (side_by_side_idom == nullptr) ? newuse->in(0) : side_by_side_idom, dd_r);
2785         replace_node_and_forward_ctrl(use, r);
2786         // Map the (cloned) old use to the new merge point
2787         old_new.map(use_clone->_idx, r);
2788       } // End of if a loop-exit test
2789     }
2790   }
2791 }
2792 
2793 void PhaseIdealLoop::fix_body_edges(const Node_List &body, IdealLoopTree* loop, const Node_List &old_new, int dd,
2794                                     IdealLoopTree* parent, bool partial) {
2795   for(uint i = 0; i < body.size(); i++ ) {
2796     Node *old = body.at(i);
2797     Node *nnn = old_new[old->_idx];
2798     // Fix CFG/Loop controlling the new node
2799     if (has_ctrl(old)) {
2800       set_ctrl(nnn, old_new[get_ctrl(old)->_idx]);
2801     } else {
2802       set_loop(nnn, parent);
2803       if (old->outcnt() > 0) {
2804         Node* dom = idom(old);
2805         if (old_new[dom->_idx] != nullptr) {
2806           dom = old_new[dom->_idx];
2807           set_idom(nnn, dom, dd );
2808         }
2809       }
2810     }
2811     // Correct edges to the new node
2812     for (uint j = 0; j < nnn->req(); j++) {
2813         Node *n = nnn->in(j);
2814         if (n != nullptr) {
2815           IdealLoopTree *old_in_loop = get_loop(has_ctrl(n) ? get_ctrl(n) : n);
2816           if (loop->is_member(old_in_loop)) {
2817             if (old_new[n->_idx] != nullptr) {
2818               nnn->set_req(j, old_new[n->_idx]);
2819             } else {
2820               assert(!body.contains(n), "");
2821               assert(partial, "node not cloned");
2822             }
2823           }
2824         }
2825     }
2826     _igvn.hash_find_insert(nnn);
2827   }
2828 }
2829 
2830 void PhaseIdealLoop::clone_loop_body(const Node_List& body, Node_List &old_new, CloneMap* cm) {
2831   for (uint i = 0; i < body.size(); i++) {
2832     Node* old = body.at(i);
2833     Node* nnn = old->clone();
2834     old_new.map(old->_idx, nnn);
2835     if (C->do_vector_loop() && cm != nullptr) {
2836       cm->verify_insert_and_clone(old, nnn, cm->clone_idx());
2837     }
2838     _igvn.register_new_node_with_optimizer(nnn);
2839   }
2840 }
2841 
2842 
2843 //---------------------- stride_of_possible_iv -------------------------------------
2844 // Looks for an iff/bool/comp with one operand of the compare
2845 // being a cycle involving an add and a phi,
2846 // with an optional truncation (left-shift followed by a right-shift)
2847 // of the add. Returns zero if not an iv.
2848 int PhaseIdealLoop::stride_of_possible_iv(Node* iff) {
2849   const TypeInteger* ttype = nullptr;
2850   if (!iff->is_If() || iff->in(1) == nullptr || !iff->in(1)->is_Bool()) {
2851     return 0;
2852   }
2853   BoolNode* bl = iff->in(1)->as_Bool();
2854   Node* cmp = bl->in(1);
2855   if (!cmp || (cmp->Opcode() != Op_CmpI && cmp->Opcode() != Op_CmpU)) {
2856     return 0;
2857   }
2858   // Must have an invariant operand
2859   if (ctrl_is_member(get_loop(iff), cmp->in(2))) {
2860     return 0;
2861   }
2862   Node* add2 = nullptr;
2863   Node* cmp1 = cmp->in(1);
2864   if (cmp1->is_Phi()) {
2865     // (If (Bool (CmpX phi:(Phi ...(Optional-trunc(AddI phi add2))) )))
2866     Node* phi = cmp1;
2867     for (uint i = 1; i < phi->req(); i++) {
2868       Node* in = phi->in(i);
2869       CountedLoopConverter::TruncatedIncrement add(T_INT);
2870       add.build(in);
2871       if (add.is_valid() && add.incr()->in(1) == phi) {
2872         add2 = add.incr()->in(2);
2873         break;
2874       }
2875     }
2876   } else {
2877     // (If (Bool (CmpX addtrunc:(Optional-trunc((AddI (Phi ...addtrunc...) add2)) )))
2878     Node* addtrunc = cmp1;
2879     CountedLoopConverter::TruncatedIncrement add(T_INT);
2880     add.build(addtrunc);
2881     if (add.is_valid() && add.incr()->in(1)->is_Phi()) {
2882       Node* phi = add.incr()->in(1);
2883       for (uint i = 1; i < phi->req(); i++) {
2884         if (phi->in(i) == addtrunc) {
2885           add2 = add.incr()->in(2);
2886           break;
2887         }
2888       }
2889     }
2890   }
2891   if (add2 != nullptr) {
2892     const TypeInt* add2t = _igvn.type(add2)->is_int();
2893     if (add2t->is_con()) {
2894       return add2t->get_con();
2895     }
2896   }
2897   return 0;
2898 }
2899 
2900 
2901 //---------------------- stay_in_loop -------------------------------------
2902 // Return the (unique) control output node that's in the loop (if it exists.)
2903 Node* PhaseIdealLoop::stay_in_loop( Node* n, IdealLoopTree *loop) {
2904   Node* unique = nullptr;
2905   if (!n) return nullptr;
2906   for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
2907     Node* use = n->fast_out(i);
2908     if (!has_ctrl(use) && loop->is_member(get_loop(use))) {
2909       if (unique != nullptr) {
2910         return nullptr;
2911       }
2912       unique = use;
2913     }
2914   }
2915   return unique;
2916 }
2917 
2918 //------------------------------ register_node -------------------------------------
2919 // Utility to register node "n" with PhaseIdealLoop
2920 void PhaseIdealLoop::register_node(Node* n, IdealLoopTree* loop, Node* pred, uint ddepth) {
2921   _igvn.register_new_node_with_optimizer(n);
2922   loop->_body.push(n);
2923   if (n->is_CFG()) {
2924     set_loop(n, loop);
2925     set_idom(n, pred, ddepth);
2926   } else {
2927     set_ctrl(n, pred);
2928   }
2929 }
2930 
2931 //------------------------------ proj_clone -------------------------------------
2932 // Utility to create an if-projection
2933 ProjNode* PhaseIdealLoop::proj_clone(ProjNode* p, IfNode* iff) {
2934   ProjNode* c = p->clone()->as_Proj();
2935   c->set_req(0, iff);
2936   return c;
2937 }
2938 
2939 //------------------------------ short_circuit_if -------------------------------------
2940 // Force the iff control output to be the live_proj
2941 Node* PhaseIdealLoop::short_circuit_if(IfNode* iff, ProjNode* live_proj) {
2942   guarantee(live_proj != nullptr, "null projection");
2943   int proj_con = live_proj->_con;
2944   assert(proj_con == 0 || proj_con == 1, "false or true projection");
2945   Node* con = intcon(proj_con);
2946   if (iff) {
2947     iff->set_req(1, con);
2948   }
2949   return con;
2950 }
2951 
2952 //------------------------------ insert_if_before_proj -------------------------------------
2953 // Insert a new if before an if projection (* - new node)
2954 //
2955 // before
2956 //           if(test)
2957 //           /     \
2958 //          v       v
2959 //    other-proj   proj (arg)
2960 //
2961 // after
2962 //           if(test)
2963 //           /     \
2964 //          /       v
2965 //         |      * proj-clone
2966 //         v          |
2967 //    other-proj      v
2968 //                * new_if(relop(cmp[IU](left,right)))
2969 //                  /  \
2970 //                 v    v
2971 //         * new-proj  proj
2972 //         (returned)
2973 //
2974 ProjNode* PhaseIdealLoop::insert_if_before_proj(Node* left, bool Signed, BoolTest::mask relop, Node* right, ProjNode* proj) {
2975   IfNode* iff = proj->in(0)->as_If();
2976   IdealLoopTree *loop = get_loop(proj);
2977   ProjNode *other_proj = iff->proj_out(!proj->is_IfTrue())->as_Proj();
2978   uint ddepth = dom_depth(proj);
2979 
2980   _igvn.rehash_node_delayed(iff);
2981   _igvn.rehash_node_delayed(proj);
2982 
2983   proj->set_req(0, nullptr);  // temporary disconnect
2984   ProjNode* proj2 = proj_clone(proj, iff);
2985   register_node(proj2, loop, iff, ddepth);
2986 
2987   Node* cmp = Signed ? (Node*) new CmpINode(left, right) : (Node*) new CmpUNode(left, right);
2988   register_node(cmp, loop, proj2, ddepth);
2989 
2990   BoolNode* bol = new BoolNode(cmp, relop);
2991   register_node(bol, loop, proj2, ddepth);
2992 
2993   int opcode = iff->Opcode();
2994   assert(opcode == Op_If || opcode == Op_RangeCheck, "unexpected opcode");
2995   IfNode* new_if = IfNode::make_with_same_profile(iff, proj2, bol);
2996   register_node(new_if, loop, proj2, ddepth);
2997 
2998   proj->set_req(0, new_if); // reattach
2999   set_idom(proj, new_if, ddepth);
3000 
3001   ProjNode* new_exit = proj_clone(other_proj, new_if)->as_Proj();
3002   guarantee(new_exit != nullptr, "null exit node");
3003   register_node(new_exit, get_loop(other_proj), new_if, ddepth);
3004 
3005   return new_exit;
3006 }
3007 
3008 //------------------------------ insert_region_before_proj -------------------------------------
3009 // Insert a region before an if projection (* - new node)
3010 //
3011 // before
3012 //           if(test)
3013 //          /      |
3014 //         v       |
3015 //       proj      v
3016 //               other-proj
3017 //
3018 // after
3019 //           if(test)
3020 //          /      |
3021 //         v       |
3022 // * proj-clone    v
3023 //         |     other-proj
3024 //         v
3025 // * new-region
3026 //         |
3027 //         v
3028 // *      dum_if
3029 //       /     \
3030 //      v       \
3031 // * dum-proj    v
3032 //              proj
3033 //
3034 RegionNode* PhaseIdealLoop::insert_region_before_proj(ProjNode* proj) {
3035   IfNode* iff = proj->in(0)->as_If();
3036   IdealLoopTree *loop = get_loop(proj);
3037   ProjNode *other_proj = iff->proj_out(!proj->is_IfTrue())->as_Proj();
3038   uint ddepth = dom_depth(proj);
3039 
3040   _igvn.rehash_node_delayed(iff);
3041   _igvn.rehash_node_delayed(proj);
3042 
3043   proj->set_req(0, nullptr);  // temporary disconnect
3044   ProjNode* proj2 = proj_clone(proj, iff);
3045   register_node(proj2, loop, iff, ddepth);
3046 
3047   RegionNode* reg = new RegionNode(2);
3048   reg->set_req(1, proj2);
3049   register_node(reg, loop, iff, ddepth);
3050 
3051   IfNode* dum_if = new IfNode(reg, short_circuit_if(nullptr, proj), iff->_prob, iff->_fcnt);
3052   register_node(dum_if, loop, reg, ddepth);
3053 
3054   proj->set_req(0, dum_if); // reattach
3055   set_idom(proj, dum_if, ddepth);
3056 
3057   ProjNode* dum_proj = proj_clone(other_proj, dum_if);
3058   register_node(dum_proj, loop, dum_if, ddepth);
3059 
3060   return reg;
3061 }
3062 
3063 // Idea
3064 // ----
3065 // Partial Peeling tries to rotate the loop in such a way that it can later be turned into a counted loop. Counted loops
3066 // require a signed loop exit test. When calling this method, we've only found a suitable unsigned test to partial peel
3067 // with. Therefore, we try to split off a signed loop exit test from the unsigned test such that it can be used as new
3068 // loop exit while keeping the unsigned test unchanged and preserving the same behavior as if we've used the unsigned
3069 // test alone instead:
3070 //
3071 // Before Partial Peeling:
3072 //   Loop:
3073 //     <peeled section>
3074 //     Split off signed loop exit test
3075 //     <-- CUT HERE -->
3076 //     Unchanged unsigned loop exit test
3077 //     <rest of unpeeled section>
3078 //     goto Loop
3079 //
3080 // After Partial Peeling:
3081 //   <cloned peeled section>
3082 //   Cloned split off signed loop exit test
3083 //   Loop:
3084 //     Unchanged unsigned loop exit test
3085 //     <rest of unpeeled section>
3086 //     <peeled section>
3087 //     Split off signed loop exit test
3088 //     goto Loop
3089 //
3090 // Details
3091 // -------
3092 // Before:
3093 //          if (i <u limit)    Unsigned loop exit condition
3094 //         /       |
3095 //        v        v
3096 //   exit-proj   stay-in-loop-proj
3097 //
3098 // Split off a signed loop exit test (i.e. with CmpI) from an unsigned loop exit test (i.e. with CmpU) and insert it
3099 // before the CmpU on the stay-in-loop path and keep both tests:
3100 //
3101 //          if (i <u limit)    Signed loop exit test
3102 //        /        |
3103 //       /  if (i <u limit)    Unsigned loop exit test
3104 //      /  /       |
3105 //     v  v        v
3106 //  exit-region  stay-in-loop-proj
3107 //
3108 // Implementation
3109 // --------------
3110 // We need to make sure that the new signed loop exit test is properly inserted into the graph such that the unsigned
3111 // loop exit test still dominates the same set of control nodes, the ctrl() relation from data nodes to both loop
3112 // exit tests is preserved, and their loop nesting is correct.
3113 //
3114 // To achieve that, we clone the unsigned loop exit test completely (leave it unchanged), insert the signed loop exit
3115 // test above it and kill the original unsigned loop exit test by setting it's condition to a constant
3116 // (i.e. stay-in-loop-const in graph below) such that IGVN can fold it later:
3117 //
3118 //           if (stay-in-loop-const)  Killed original unsigned loop exit test
3119 //          /       |
3120 //         /        v
3121 //        /  if (i <  limit)          Split off signed loop exit test
3122 //       /  /       |
3123 //      /  /        v
3124 //     /  /  if (i <u limit)          Cloned unsigned loop exit test
3125 //    /  /   /      |
3126 //   v  v  v        |
3127 //  exit-region     |
3128 //        |         |
3129 //    dummy-if      |
3130 //     /  |         |
3131 // dead   |         |
3132 //        v         v
3133 //   exit-proj   stay-in-loop-proj
3134 //
3135 // Note: The dummy-if is inserted to create a region to merge the loop exits between the original to be killed unsigned
3136 //       loop exit test and its exit projection while keeping the exit projection (also see insert_region_before_proj()).
3137 //
3138 // Requirements
3139 // ------------
3140 // Note that we can only split off a signed loop exit test from the unsigned loop exit test when the behavior is exactly
3141 // the same as before with only a single unsigned test. This is only possible if certain requirements are met.
3142 // Otherwise, we need to bail out (see comments in the code below).
3143 IfNode* PhaseIdealLoop::insert_cmpi_loop_exit(IfNode* if_cmpu, IdealLoopTree* loop) {
3144   const bool Signed   = true;
3145   const bool Unsigned = false;
3146 
3147   BoolNode* bol = if_cmpu->in(1)->as_Bool();
3148   if (bol->_test._test != BoolTest::lt) {
3149     return nullptr;
3150   }
3151   CmpNode* cmpu = bol->in(1)->as_Cmp();
3152   assert(cmpu->Opcode() == Op_CmpU, "must be unsigned comparison");
3153 
3154   int stride = stride_of_possible_iv(if_cmpu);
3155   if (stride == 0) {
3156     return nullptr;
3157   }
3158 
3159   Node* lp_proj = stay_in_loop(if_cmpu, loop);
3160   guarantee(lp_proj != nullptr, "null loop node");
3161 
3162   ProjNode* lp_continue = lp_proj->as_Proj();
3163   ProjNode* lp_exit     = if_cmpu->proj_out(!lp_continue->is_IfTrue())->as_Proj();
3164   if (!lp_exit->is_IfFalse()) {
3165     // The loop exit condition is (i <u limit) ==> (i >= 0 && i < limit).
3166     // We therefore can't add a single exit condition.
3167     return nullptr;
3168   }
3169   // The unsigned loop exit condition is
3170   //   !(i <u  limit)
3171   // =   i >=u limit
3172   //
3173   // First, we note that for any x for which
3174   //   0 <= x <= INT_MAX
3175   // we can convert x to an unsigned int and still get the same guarantee:
3176   //   0 <=  (uint) x <=  INT_MAX = (uint) INT_MAX
3177   //   0 <=u (uint) x <=u INT_MAX = (uint) INT_MAX   (LEMMA)
3178   //
3179   // With that in mind, if
3180   //   limit >= 0             (COND)
3181   // then the unsigned loop exit condition
3182   //   i >=u limit            (ULE)
3183   // is equivalent to
3184   //   i < 0 || i >= limit    (SLE-full)
3185   // because either i is negative and therefore always greater than MAX_INT when converting to unsigned
3186   //   (uint) i >=u MAX_INT >= limit >= 0
3187   // or otherwise
3188   //   i >= limit >= 0
3189   // holds due to (LEMMA).
3190   //
3191   // For completeness, a counterexample with limit < 0:
3192   // Assume i = -3 and limit = -2:
3193   //   i  < 0
3194   //   -2 < 0
3195   // is true and thus also "i < 0 || i >= limit". But
3196   //   i  >=u limit
3197   //   -3 >=u -2
3198   // is false.
3199   Node* limit = cmpu->in(2);
3200   const TypeInt* type_limit = _igvn.type(limit)->is_int();
3201   if (type_limit->_lo < 0) {
3202     return nullptr;
3203   }
3204 
3205   // We prove below that we can extract a single signed loop exit condition from (SLE-full), depending on the stride:
3206   //   stride < 0:
3207   //     i < 0        (SLE = SLE-negative)
3208   //   stride > 0:
3209   //     i >= limit   (SLE = SLE-positive)
3210   // such that we have the following graph before Partial Peeling with stride > 0 (similar for stride < 0):
3211   //
3212   // Loop:
3213   //   <peeled section>
3214   //   i >= limit    (SLE-positive)
3215   //   <-- CUT HERE -->
3216   //   i >=u limit   (ULE)
3217   //   <rest of unpeeled section>
3218   //   goto Loop
3219   //
3220   // We exit the loop if:
3221   //   (SLE) is true OR (ULE) is true
3222   // However, if (SLE) is true then (ULE) also needs to be true to ensure the exact same behavior. Otherwise, we wrongly
3223   // exit a loop that should not have been exited if we did not apply Partial Peeling. More formally, we need to ensure:
3224   //   (SLE) IMPLIES (ULE)
3225   // This indeed holds when (COND) is given:
3226   // - stride > 0:
3227   //       i >=  limit             // (SLE = SLE-positive)
3228   //       i >=  limit >= 0        // (COND)
3229   //       i >=u limit >= 0        // (LEMMA)
3230   //     which is the unsigned loop exit condition (ULE).
3231   // - stride < 0:
3232   //       i        <  0           // (SLE = SLE-negative)
3233   //       (uint) i >u MAX_INT     // (NEG) all negative values are greater than MAX_INT when converted to unsigned
3234   //       MAX_INT >= limit >= 0   // (COND)
3235   //       MAX_INT >=u limit >= 0  // (LEMMA)
3236   //     and thus from (NEG) and (LEMMA):
3237   //       i >=u limit
3238   //     which is the unsigned loop exit condition (ULE).
3239   //
3240   //
3241   // After Partial Peeling, we have the following structure for stride > 0 (similar for stride < 0):
3242   //   <cloned peeled section>
3243   //   i >= limit (SLE-positive)
3244   //   Loop:
3245   //     i >=u limit (ULE)
3246   //     <rest of unpeeled section>
3247   //     <peeled section>
3248   //     i >= limit (SLE-positive)
3249   //     goto Loop
3250   Node* rhs_cmpi;
3251   if (stride > 0) {
3252     rhs_cmpi = limit; // For i >= limit
3253   } else {
3254     rhs_cmpi = makecon(TypeInt::ZERO); // For i < 0
3255   }
3256   // Create a new region on the exit path
3257   RegionNode* reg = insert_region_before_proj(lp_exit);
3258   guarantee(reg != nullptr, "null region node");
3259 
3260   // Clone the if-cmpu-true-false using a signed compare
3261   BoolTest::mask rel_i = stride > 0 ? bol->_test._test : BoolTest::ge;
3262   ProjNode* cmpi_exit = insert_if_before_proj(cmpu->in(1), Signed, rel_i, rhs_cmpi, lp_continue);
3263   reg->add_req(cmpi_exit);
3264 
3265   // Clone the if-cmpu-true-false
3266   BoolTest::mask rel_u = bol->_test._test;
3267   ProjNode* cmpu_exit = insert_if_before_proj(cmpu->in(1), Unsigned, rel_u, cmpu->in(2), lp_continue);
3268   reg->add_req(cmpu_exit);
3269 
3270   // Force original if to stay in loop.
3271   short_circuit_if(if_cmpu, lp_continue);
3272 
3273   return cmpi_exit->in(0)->as_If();
3274 }
3275 
3276 //------------------------------ remove_cmpi_loop_exit -------------------------------------
3277 // Remove a previously inserted signed compare loop exit.
3278 void PhaseIdealLoop::remove_cmpi_loop_exit(IfNode* if_cmp, IdealLoopTree *loop) {
3279   Node* lp_proj = stay_in_loop(if_cmp, loop);
3280   assert(if_cmp->in(1)->in(1)->Opcode() == Op_CmpI &&
3281          stay_in_loop(lp_proj, loop)->is_If() &&
3282          stay_in_loop(lp_proj, loop)->in(1)->in(1)->Opcode() == Op_CmpU, "inserted cmpi before cmpu");
3283   Node* con = makecon(lp_proj->is_IfTrue() ? TypeInt::ONE : TypeInt::ZERO);
3284   if_cmp->set_req(1, con);
3285 }
3286 
3287 //------------------------------ scheduled_nodelist -------------------------------------
3288 // Create a post order schedule of nodes that are in the
3289 // "member" set.  The list is returned in "sched".
3290 // The first node in "sched" is the loop head, followed by
3291 // nodes which have no inputs in the "member" set, and then
3292 // followed by the nodes that have an immediate input dependence
3293 // on a node in "sched".
3294 void PhaseIdealLoop::scheduled_nodelist( IdealLoopTree *loop, VectorSet& member, Node_List &sched ) {
3295 
3296   assert(member.test(loop->_head->_idx), "loop head must be in member set");
3297   VectorSet visited;
3298   Node_Stack nstack(loop->_body.size());
3299 
3300   Node* n  = loop->_head;  // top of stack is cached in "n"
3301   uint idx = 0;
3302   visited.set(n->_idx);
3303 
3304   // Initially push all with no inputs from within member set
3305   for(uint i = 0; i < loop->_body.size(); i++ ) {
3306     Node *elt = loop->_body.at(i);
3307     if (member.test(elt->_idx)) {
3308       bool found = false;
3309       for (uint j = 0; j < elt->req(); j++) {
3310         Node* def = elt->in(j);
3311         if (def && member.test(def->_idx) && def != elt) {
3312           found = true;
3313           break;
3314         }
3315       }
3316       if (!found && elt != loop->_head) {
3317         nstack.push(n, idx);
3318         n = elt;
3319         assert(!visited.test(n->_idx), "not seen yet");
3320         visited.set(n->_idx);
3321       }
3322     }
3323   }
3324 
3325   // traverse out's that are in the member set
3326   while (true) {
3327     if (idx < n->outcnt()) {
3328       Node* use = n->raw_out(idx);
3329       idx++;
3330       if (!visited.test_set(use->_idx)) {
3331         if (member.test(use->_idx)) {
3332           nstack.push(n, idx);
3333           n = use;
3334           idx = 0;
3335         }
3336       }
3337     } else {
3338       // All outputs processed
3339       sched.push(n);
3340       if (nstack.is_empty()) break;
3341       n   = nstack.node();
3342       idx = nstack.index();
3343       nstack.pop();
3344     }
3345   }
3346 }
3347 
3348 
3349 //------------------------------ has_use_in_set -------------------------------------
3350 // Has a use in the vector set
3351 bool PhaseIdealLoop::has_use_in_set( Node* n, VectorSet& vset ) {
3352   for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++) {
3353     Node* use = n->fast_out(j);
3354     if (vset.test(use->_idx)) {
3355       return true;
3356     }
3357   }
3358   return false;
3359 }
3360 
3361 
3362 //------------------------------ has_use_internal_to_set -------------------------------------
3363 // Has use internal to the vector set (ie. not in a phi at the loop head)
3364 bool PhaseIdealLoop::has_use_internal_to_set( Node* n, VectorSet& vset, IdealLoopTree *loop ) {
3365   Node* head  = loop->_head;
3366   for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++) {
3367     Node* use = n->fast_out(j);
3368     if (vset.test(use->_idx) && !(use->is_Phi() && use->in(0) == head)) {
3369       return true;
3370     }
3371   }
3372   return false;
3373 }
3374 
3375 
3376 //------------------------------ clone_for_use_outside_loop -------------------------------------
3377 // clone "n" for uses that are outside of loop
3378 int PhaseIdealLoop::clone_for_use_outside_loop( IdealLoopTree *loop, Node* n, Node_List& worklist ) {
3379   int cloned = 0;
3380   assert(worklist.size() == 0, "should be empty");
3381   for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++) {
3382     Node* use = n->fast_out(j);
3383     if( !loop->is_member(get_loop(has_ctrl(use) ? get_ctrl(use) : use)) ) {
3384       worklist.push(use);
3385     }
3386   }
3387 
3388   if (C->check_node_count(worklist.size() + NodeLimitFudgeFactor,
3389                           "Too many clones required in clone_for_use_outside_loop in partial peeling")) {
3390     return -1;
3391   }
3392 
3393   while( worklist.size() ) {
3394     Node *use = worklist.pop();
3395     if (!has_node(use) || use->in(0) == C->top()) continue;
3396     uint j;
3397     for (j = 0; j < use->req(); j++) {
3398       if (use->in(j) == n) break;
3399     }
3400     assert(j < use->req(), "must be there");
3401 
3402     // clone "n" and insert it between the inputs of "n" and the use outside the loop
3403     Node* n_clone = n->clone();
3404     _igvn.replace_input_of(use, j, n_clone);
3405     cloned++;
3406     Node* use_c;
3407     if (!use->is_Phi()) {
3408       use_c = has_ctrl(use) ? get_ctrl(use) : use->in(0);
3409     } else {
3410       // Use in a phi is considered a use in the associated predecessor block
3411       use_c = use->in(0)->in(j);
3412     }
3413     set_ctrl(n_clone, use_c);
3414     assert(!loop->is_member(get_loop(use_c)), "should be outside loop");
3415     get_loop(use_c)->_body.push(n_clone);
3416     _igvn.register_new_node_with_optimizer(n_clone);
3417 #ifndef PRODUCT
3418     if (TracePartialPeeling) {
3419       tty->print_cr("loop exit cloning old: %d new: %d newbb: %d", n->_idx, n_clone->_idx, get_ctrl(n_clone)->_idx);
3420     }
3421 #endif
3422   }
3423   return cloned;
3424 }
3425 
3426 
3427 //------------------------------ clone_for_special_use_inside_loop -------------------------------------
3428 // clone "n" for special uses that are in the not_peeled region.
3429 // If these def-uses occur in separate blocks, the code generator
3430 // marks the method as not compilable.  For example, if a "BoolNode"
3431 // is in a different basic block than the "IfNode" that uses it, then
3432 // the compilation is aborted in the code generator.
3433 void PhaseIdealLoop::clone_for_special_use_inside_loop( IdealLoopTree *loop, Node* n,
3434                                                         VectorSet& not_peel, Node_List& sink_list, Node_List& worklist ) {
3435   if (n->is_Phi() || n->is_Load()) {
3436     return;
3437   }
3438   assert(worklist.size() == 0, "should be empty");
3439   for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++) {
3440     Node* use = n->fast_out(j);
3441     if ( not_peel.test(use->_idx) &&
3442          (use->is_If() || use->is_CMove() || use->is_Bool() || use->is_OpaqueInitializedAssertionPredicate()) &&
3443          use->in(1) == n)  {
3444       worklist.push(use);
3445     }
3446   }
3447   if (worklist.size() > 0) {
3448     // clone "n" and insert it between inputs of "n" and the use
3449     Node* n_clone = n->clone();
3450     loop->_body.push(n_clone);
3451     _igvn.register_new_node_with_optimizer(n_clone);
3452     set_ctrl(n_clone, get_ctrl(n));
3453     sink_list.push(n_clone);
3454     not_peel.set(n_clone->_idx);
3455 #ifndef PRODUCT
3456     if (TracePartialPeeling) {
3457       tty->print_cr("special not_peeled cloning old: %d new: %d", n->_idx, n_clone->_idx);
3458     }
3459 #endif
3460     while( worklist.size() ) {
3461       Node *use = worklist.pop();
3462       _igvn.rehash_node_delayed(use);
3463       for (uint j = 1; j < use->req(); j++) {
3464         if (use->in(j) == n) {
3465           use->set_req(j, n_clone);
3466         }
3467       }
3468     }
3469   }
3470 }
3471 
3472 
3473 //------------------------------ insert_phi_for_loop -------------------------------------
3474 // Insert phi(lp_entry_val, back_edge_val) at use->in(idx) for loop lp if phi does not already exist
3475 void PhaseIdealLoop::insert_phi_for_loop( Node* use, uint idx, Node* lp_entry_val, Node* back_edge_val, LoopNode* lp ) {
3476   Node *phi = PhiNode::make(lp, back_edge_val);
3477   phi->set_req(LoopNode::EntryControl, lp_entry_val);
3478   // Use existing phi if it already exists
3479   Node *hit = _igvn.hash_find_insert(phi);
3480   if( hit == nullptr ) {
3481     _igvn.register_new_node_with_optimizer(phi);
3482     set_ctrl(phi, lp);
3483   } else {
3484     // Remove the new phi from the graph and use the hit
3485     _igvn.remove_dead_node(phi, PhaseIterGVN::NodeOrigin::Speculative);
3486     phi = hit;
3487   }
3488   _igvn.replace_input_of(use, idx, phi);
3489 }
3490 
3491 #ifdef ASSERT
3492 //------------------------------ is_valid_loop_partition -------------------------------------
3493 // Validate the loop partition sets: peel and not_peel
3494 bool PhaseIdealLoop::is_valid_loop_partition( IdealLoopTree *loop, VectorSet& peel, Node_List& peel_list,
3495                                               VectorSet& not_peel ) {
3496   uint i;
3497   // Check that peel_list entries are in the peel set
3498   for (i = 0; i < peel_list.size(); i++) {
3499     if (!peel.test(peel_list.at(i)->_idx)) {
3500       return false;
3501     }
3502   }
3503   // Check at loop members are in one of peel set or not_peel set
3504   for (i = 0; i < loop->_body.size(); i++ ) {
3505     Node *def  = loop->_body.at(i);
3506     uint di = def->_idx;
3507     // Check that peel set elements are in peel_list
3508     if (peel.test(di)) {
3509       if (not_peel.test(di)) {
3510         return false;
3511       }
3512       // Must be in peel_list also
3513       bool found = false;
3514       for (uint j = 0; j < peel_list.size(); j++) {
3515         if (peel_list.at(j)->_idx == di) {
3516           found = true;
3517           break;
3518         }
3519       }
3520       if (!found) {
3521         return false;
3522       }
3523     } else if (not_peel.test(di)) {
3524       if (peel.test(di)) {
3525         return false;
3526       }
3527     } else {
3528       return false;
3529     }
3530   }
3531   return true;
3532 }
3533 
3534 //------------------------------ is_valid_clone_loop_exit_use -------------------------------------
3535 // Ensure a use outside of loop is of the right form
3536 bool PhaseIdealLoop::is_valid_clone_loop_exit_use( IdealLoopTree *loop, Node* use, uint exit_idx) {
3537   Node *use_c = has_ctrl(use) ? get_ctrl(use) : use;
3538   return (use->is_Phi() &&
3539           use_c->is_Region() && use_c->req() == 3 &&
3540           (use_c->in(exit_idx)->Opcode() == Op_IfTrue ||
3541            use_c->in(exit_idx)->Opcode() == Op_IfFalse ||
3542            use_c->in(exit_idx)->Opcode() == Op_JumpProj) &&
3543           loop->is_member( get_loop( use_c->in(exit_idx)->in(0) ) ) );
3544 }
3545 
3546 //------------------------------ is_valid_clone_loop_form -------------------------------------
3547 // Ensure that all uses outside of loop are of the right form
3548 bool PhaseIdealLoop::is_valid_clone_loop_form( IdealLoopTree *loop, Node_List& peel_list,
3549                                                uint orig_exit_idx, uint clone_exit_idx) {
3550   uint len = peel_list.size();
3551   for (uint i = 0; i < len; i++) {
3552     Node *def = peel_list.at(i);
3553 
3554     for (DUIterator_Fast jmax, j = def->fast_outs(jmax); j < jmax; j++) {
3555       Node *use = def->fast_out(j);
3556       Node *use_c = has_ctrl(use) ? get_ctrl(use) : use;
3557       if (!loop->is_member(get_loop(use_c))) {
3558         // use is not in the loop, check for correct structure
3559         if (use->in(0) == def) {
3560           // Okay
3561         } else if (!is_valid_clone_loop_exit_use(loop, use, orig_exit_idx)) {
3562           return false;
3563         }
3564       }
3565     }
3566   }
3567   return true;
3568 }
3569 #endif
3570 
3571 //------------------------------ partial_peel -------------------------------------
3572 // Partially peel (aka loop rotation) the top portion of a loop (called
3573 // the peel section below) by cloning it and placing one copy just before
3574 // the new loop head and the other copy at the bottom of the new loop.
3575 //
3576 //    before                       after                where it came from
3577 //
3578 //    stmt1                        stmt1
3579 //  loop:                          stmt2                     clone
3580 //    stmt2                        if condA goto exitA       clone
3581 //    if condA goto exitA        new_loop:                   new
3582 //    stmt3                        stmt3                     clone
3583 //    if !condB goto loop          if condB goto exitB       clone
3584 //  exitB:                         stmt2                     orig
3585 //    stmt4                        if !condA goto new_loop   orig
3586 //  exitA:                         goto exitA
3587 //                               exitB:
3588 //                                 stmt4
3589 //                               exitA:
3590 //
3591 // Step 1: find the cut point: an exit test on probable
3592 //         induction variable.
3593 // Step 2: schedule (with cloning) operations in the peel
3594 //         section that can be executed after the cut into
3595 //         the section that is not peeled.  This may need
3596 //         to clone operations into exit blocks.  For
3597 //         instance, a reference to A[i] in the not-peel
3598 //         section and a reference to B[i] in an exit block
3599 //         may cause a left-shift of i by 2 to be placed
3600 //         in the peel block.  This step will clone the left
3601 //         shift into the exit block and sink the left shift
3602 //         from the peel to the not-peel section.
3603 // Step 3: clone the loop, retarget the control, and insert
3604 //         phis for values that are live across the new loop
3605 //         head.  This is very dependent on the graph structure
3606 //         from clone_loop.  It creates region nodes for
3607 //         exit control and associated phi nodes for values
3608 //         flow out of the loop through that exit.  The region
3609 //         node is dominated by the clone's control projection.
3610 //         So the clone's peel section is placed before the
3611 //         new loop head, and the clone's not-peel section is
3612 //         forms the top part of the new loop.  The original
3613 //         peel section forms the tail of the new loop.
3614 // Step 4: update the dominator tree and recompute the
3615 //         dominator depth.
3616 //
3617 //                   orig
3618 //
3619 //                   stmt1
3620 //                     |
3621 //                     v
3622 //                 predicates
3623 //                     |
3624 //                     v
3625 //                   loop<----+
3626 //                     |      |
3627 //                   stmt2    |
3628 //                     |      |
3629 //                     v      |
3630 //                    ifA     |
3631 //                   / |      |
3632 //                  v  v      |
3633 //               false true   ^  <-- last_peel
3634 //               /     |      |
3635 //              /   ===|==cut |
3636 //             /     stmt3    |  <-- first_not_peel
3637 //            /        |      |
3638 //            |        v      |
3639 //            v       ifB     |
3640 //          exitA:   / \      |
3641 //                  /   \     |
3642 //                 v     v    |
3643 //               false true   |
3644 //               /       \    |
3645 //              /         ----+
3646 //             |
3647 //             v
3648 //           exitB:
3649 //           stmt4
3650 //
3651 //
3652 //            after clone loop
3653 //
3654 //                   stmt1
3655 //                     |
3656 //                     v
3657 //                predicates
3658 //                 /       \
3659 //        clone   /         \   orig
3660 //               /           \
3661 //              /             \
3662 //             v               v
3663 //   +---->loop                loop<----+
3664 //   |      |                    |      |
3665 //   |    stmt2                stmt2    |
3666 //   |      |                    |      |
3667 //   |      v                    v      |
3668 //   |      ifA                 ifA     |
3669 //   |      | \                / |      |
3670 //   |      v  v              v  v      |
3671 //   ^    true  false      false true   ^  <-- last_peel
3672 //   |      |   ^   \       /    |      |
3673 //   | cut==|==  \   \     /  ===|==cut |
3674 //   |    stmt3   \   \   /    stmt3    |  <-- first_not_peel
3675 //   |      |    dom   | |       |      |
3676 //   |      v      \  1v v2      v      |
3677 //   |      ifB     regionA     ifB     |
3678 //   |      / \        |       / \      |
3679 //   |     /   \       v      /   \     |
3680 //   |    v     v    exitA:  v     v    |
3681 //   |    true  false      false true   |
3682 //   |    /     ^   \      /       \    |
3683 //   +----       \   \    /         ----+
3684 //               dom  \  /
3685 //                 \  1v v2
3686 //                  regionB
3687 //                     |
3688 //                     v
3689 //                   exitB:
3690 //                   stmt4
3691 //
3692 //
3693 //           after partial peel
3694 //
3695 //                  stmt1
3696 //                     |
3697 //                     v
3698 //                predicates
3699 //                 /
3700 //        clone   /             orig
3701 //               /          TOP
3702 //              /             \
3703 //             v               v
3704 //    TOP->loop                loop----+
3705 //          |                    |      |
3706 //        stmt2                stmt2    |
3707 //          |                    |      |
3708 //          v                    v      |
3709 //          ifA                 ifA     |
3710 //          | \                / |      |
3711 //          v  v              v  v      |
3712 //        true  false      false true   |     <-- last_peel
3713 //          |   ^   \       /    +------|---+
3714 //  +->newloop   \   \     /  === ==cut |   |
3715 //  |     stmt3   \   \   /     TOP     |   |
3716 //  |       |    dom   | |      stmt3   |   | <-- first_not_peel
3717 //  |       v      \  1v v2      v      |   |
3718 //  |       ifB     regionA     ifB     ^   v
3719 //  |       / \        |       / \      |   |
3720 //  |      /   \       v      /   \     |   |
3721 //  |     v     v    exitA:  v     v    |   |
3722 //  |     true  false      false true   |   |
3723 //  |     /     ^   \      /       \    |   |
3724 //  |    |       \   \    /         v   |   |
3725 //  |    |       dom  \  /         TOP  |   |
3726 //  |    |         \  1v v2             |   |
3727 //  ^    v          regionB             |   |
3728 //  |    |             |                |   |
3729 //  |    |             v                ^   v
3730 //  |    |           exitB:             |   |
3731 //  |    |           stmt4              |   |
3732 //  |    +------------>-----------------+   |
3733 //  |                                       |
3734 //  +-----------------<---------------------+
3735 //
3736 //
3737 //              final graph
3738 //
3739 //                  stmt1
3740 //                    |
3741 //                    v
3742 //                predicates
3743 //                    |
3744 //                    v
3745 //                  stmt2 clone
3746 //                    |
3747 //                    v
3748 //         ........> ifA clone
3749 //         :        / |
3750 //        dom      /  |
3751 //         :      v   v
3752 //         :  false   true
3753 //         :  |       |
3754 //         :  |       v
3755 //         :  |    newloop<-----+
3756 //         :  |        |        |
3757 //         :  |     stmt3 clone |
3758 //         :  |        |        |
3759 //         :  |        v        |
3760 //         :  |       ifB       |
3761 //         :  |      / \        |
3762 //         :  |     v   v       |
3763 //         :  |  false true     |
3764 //         :  |   |     |       |
3765 //         :  |   v    stmt2    |
3766 //         :  | exitB:  |       |
3767 //         :  | stmt4   v       |
3768 //         :  |       ifA orig  |
3769 //         :  |      /  \       |
3770 //         :  |     /    \      |
3771 //         :  |    v     v      |
3772 //         :  |  false  true    |
3773 //         :  |  /        \     |
3774 //         :  v  v         -----+
3775 //          RegionA
3776 //             |
3777 //             v
3778 //           exitA
3779 //
3780 bool PhaseIdealLoop::partial_peel( IdealLoopTree *loop, Node_List &old_new ) {
3781 
3782   assert(!loop->_head->is_CountedLoop(), "Non-counted loop only");
3783   if (!loop->_head->is_Loop()) {
3784     return false;
3785   }
3786   LoopNode *head = loop->_head->as_Loop();
3787 
3788   if (head->is_partial_peel_loop() || head->partial_peel_has_failed()) {
3789     return false;
3790   }
3791 
3792   // Check for complex exit control
3793   for (uint ii = 0; ii < loop->_body.size(); ii++) {
3794     Node *n = loop->_body.at(ii);
3795     int opc = n->Opcode();
3796     if (n->is_Call()        ||
3797         opc == Op_Catch     ||
3798         opc == Op_CatchProj ||
3799         opc == Op_Jump      ||
3800         opc == Op_JumpProj) {
3801 #ifndef PRODUCT
3802       if (TracePartialPeeling) {
3803         tty->print_cr("\nExit control too complex: lp: %d", head->_idx);
3804       }
3805 #endif
3806       return false;
3807     }
3808   }
3809 
3810   int dd = dom_depth(head);
3811 
3812   // Step 1: find cut point
3813 
3814   // Walk up dominators to loop head looking for first loop exit
3815   // which is executed on every path thru loop.
3816   IfNode *peel_if = nullptr;
3817   IfNode *peel_if_cmpu = nullptr;
3818 
3819   Node *iff = loop->tail();
3820   while (iff != head) {
3821     if (iff->is_If()) {
3822       Node *ctrl = get_ctrl(iff->in(1));
3823       if (ctrl->is_top()) return false; // Dead test on live IF.
3824       // If loop-varying exit-test, check for induction variable
3825       if (loop->is_member(get_loop(ctrl)) &&
3826           loop->is_loop_exit(iff) &&
3827           is_possible_iv_test(iff)) {
3828         Node* cmp = iff->in(1)->in(1);
3829         if (cmp->Opcode() == Op_CmpI) {
3830           peel_if = iff->as_If();
3831         } else {
3832           assert(cmp->Opcode() == Op_CmpU, "must be CmpI or CmpU");
3833           peel_if_cmpu = iff->as_If();
3834         }
3835       }
3836     }
3837     iff = idom(iff);
3838   }
3839 
3840   // Prefer signed compare over unsigned compare.
3841   IfNode* new_peel_if = nullptr;
3842   if (peel_if == nullptr) {
3843     if (!PartialPeelAtUnsignedTests || peel_if_cmpu == nullptr) {
3844       return false;   // No peel point found
3845     }
3846     new_peel_if = insert_cmpi_loop_exit(peel_if_cmpu, loop);
3847     if (new_peel_if == nullptr) {
3848       return false;   // No peel point found
3849     }
3850     peel_if = new_peel_if;
3851   }
3852   Node* last_peel        = stay_in_loop(peel_if, loop);
3853   Node* first_not_peeled = stay_in_loop(last_peel, loop);
3854   if (first_not_peeled == nullptr || first_not_peeled == head) {
3855     return false;
3856   }
3857 
3858 #ifndef PRODUCT
3859   if (TraceLoopOpts) {
3860     tty->print("PartialPeel  ");
3861     loop->dump_head();
3862   }
3863 
3864   if (TracePartialPeeling) {
3865     tty->print_cr("before partial peel one iteration");
3866     Node_List wl;
3867     Node* t = head->in(2);
3868     while (true) {
3869       wl.push(t);
3870       if (t == head) break;
3871       t = idom(t);
3872     }
3873     while (wl.size() > 0) {
3874       Node* tt = wl.pop();
3875       tt->dump();
3876       if (tt == last_peel) tty->print_cr("-- cut --");
3877     }
3878   }
3879 #endif
3880 
3881   C->print_method(PHASE_BEFORE_PARTIAL_PEELING, 4, head);
3882 
3883   VectorSet peel;
3884   VectorSet not_peel;
3885   Node_List peel_list;
3886   Node_List worklist;
3887   Node_List sink_list;
3888 
3889   uint estimate = loop->est_loop_clone_sz(1);
3890   if (exceeding_node_budget(estimate)) {
3891     return false;
3892   }
3893 
3894   // Set of cfg nodes to peel are those that are executable from
3895   // the head through last_peel.
3896   assert(worklist.size() == 0, "should be empty");
3897   worklist.push(head);
3898   peel.set(head->_idx);
3899   while (worklist.size() > 0) {
3900     Node *n = worklist.pop();
3901     if (n != last_peel) {
3902       for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++) {
3903         Node* use = n->fast_out(j);
3904         if (use->is_CFG() &&
3905             loop->is_member(get_loop(use)) &&
3906             !peel.test_set(use->_idx)) {
3907           worklist.push(use);
3908         }
3909       }
3910     }
3911   }
3912 
3913   // Set of non-cfg nodes to peel are those that are control
3914   // dependent on the cfg nodes.
3915   for (uint i = 0; i < loop->_body.size(); i++) {
3916     Node *n = loop->_body.at(i);
3917     Node *n_c = has_ctrl(n) ? get_ctrl(n) : n;
3918     if (peel.test(n_c->_idx)) {
3919       peel.set(n->_idx);
3920     } else {
3921       not_peel.set(n->_idx);
3922     }
3923   }
3924 
3925   // Step 2: move operations from the peeled section down into the
3926   //         not-peeled section
3927 
3928   // Get a post order schedule of nodes in the peel region
3929   // Result in right-most operand.
3930   scheduled_nodelist(loop, peel, peel_list);
3931 
3932   assert(is_valid_loop_partition(loop, peel, peel_list, not_peel), "bad partition");
3933 
3934   // For future check for too many new phis
3935   uint old_phi_cnt = 0;
3936   for (DUIterator_Fast jmax, j = head->fast_outs(jmax); j < jmax; j++) {
3937     Node* use = head->fast_out(j);
3938     if (use->is_Phi()) old_phi_cnt++;
3939   }
3940 
3941 #ifndef PRODUCT
3942   if (TracePartialPeeling) {
3943     tty->print_cr("\npeeled list");
3944   }
3945 #endif
3946 
3947   // Evacuate nodes in peel region into the not_peeled region if possible
3948   bool too_many_clones = false;
3949   uint new_phi_cnt = 0;
3950   uint cloned_for_outside_use = 0;
3951   for (uint i = 0; i < peel_list.size();) {
3952     Node* n = peel_list.at(i);
3953 #ifndef PRODUCT
3954   if (TracePartialPeeling) n->dump();
3955 #endif
3956     bool incr = true;
3957     if (!n->is_CFG()) {
3958       if (has_use_in_set(n, not_peel)) {
3959         // If not used internal to the peeled region,
3960         // move "n" from peeled to not_peeled region.
3961         if (!has_use_internal_to_set(n, peel, loop)) {
3962           // if not pinned and not a load (which maybe anti-dependent on a store)
3963           // and not a CMove (Matcher expects only bool->cmove).
3964           if (n->in(0) == nullptr && !n->is_Load() && !n->is_CMove()) {
3965             int new_clones = clone_for_use_outside_loop(loop, n, worklist);
3966             if (C->failing()) return false;
3967             if (new_clones == -1) {
3968               too_many_clones = true;
3969               break;
3970             }
3971             cloned_for_outside_use += new_clones;
3972             sink_list.push(n);
3973             peel.remove(n->_idx);
3974             not_peel.set(n->_idx);
3975             peel_list.remove(i);
3976             incr = false;
3977 #ifndef PRODUCT
3978             if (TracePartialPeeling) {
3979               tty->print_cr("sink to not_peeled region: %d newbb: %d",
3980                             n->_idx, get_ctrl(n)->_idx);
3981             }
3982 #endif
3983           }
3984         } else {
3985           // Otherwise check for special def-use cases that span
3986           // the peel/not_peel boundary such as bool->if
3987           clone_for_special_use_inside_loop(loop, n, not_peel, sink_list, worklist);
3988           new_phi_cnt++;
3989         }
3990       }
3991     }
3992     if (incr) i++;
3993   }
3994 
3995   estimate += cloned_for_outside_use + new_phi_cnt;
3996   bool exceed_node_budget = !may_require_nodes(estimate);
3997   bool exceed_phi_limit = new_phi_cnt > old_phi_cnt + PartialPeelNewPhiDelta;
3998 
3999   if (too_many_clones || exceed_node_budget || exceed_phi_limit) {
4000 #ifndef PRODUCT
4001     if (TracePartialPeeling && exceed_phi_limit) {
4002       tty->print_cr("\nToo many new phis: %d  old %d new cmpi: %c",
4003                     new_phi_cnt, old_phi_cnt, new_peel_if != nullptr?'T':'F');
4004     }
4005 #endif
4006     if (new_peel_if != nullptr) {
4007       remove_cmpi_loop_exit(new_peel_if, loop);
4008     }
4009     // Inhibit more partial peeling on this loop
4010     assert(!head->is_partial_peel_loop(), "not partial peeled");
4011     head->mark_partial_peel_failed();
4012     if (cloned_for_outside_use > 0) {
4013       // Terminate this round of loop opts because
4014       // the graph outside this loop was changed.
4015       C->set_major_progress();
4016       return true;
4017     }
4018     return false;
4019   }
4020 
4021   // Step 3: clone loop, retarget control, and insert new phis
4022 
4023   // Create new loop head for new phis and to hang
4024   // the nodes being moved (sinked) from the peel region.
4025   LoopNode* new_head = new LoopNode(last_peel, last_peel);
4026   new_head->set_unswitch_count(head->unswitch_count()); // Preserve
4027   _igvn.register_new_node_with_optimizer(new_head);
4028   assert(first_not_peeled->in(0) == last_peel, "last_peel <- first_not_peeled");
4029   _igvn.replace_input_of(first_not_peeled, 0, new_head);
4030   set_loop(new_head, loop);
4031   loop->_body.push(new_head);
4032   not_peel.set(new_head->_idx);
4033   set_idom(new_head, last_peel, dom_depth(first_not_peeled));
4034   set_idom(first_not_peeled, new_head, dom_depth(first_not_peeled));
4035 
4036   while (sink_list.size() > 0) {
4037     Node* n = sink_list.pop();
4038     set_ctrl(n, new_head);
4039   }
4040 
4041   assert(is_valid_loop_partition(loop, peel, peel_list, not_peel), "bad partition");
4042 
4043   clone_loop(loop, old_new, dd, IgnoreStripMined);
4044 
4045   const uint clone_exit_idx = 1;
4046   const uint orig_exit_idx  = 2;
4047   assert(is_valid_clone_loop_form(loop, peel_list, orig_exit_idx, clone_exit_idx), "bad clone loop");
4048 
4049   Node* head_clone             = old_new[head->_idx];
4050   LoopNode* new_head_clone     = old_new[new_head->_idx]->as_Loop();
4051   Node* orig_tail_clone        = head_clone->in(2);
4052 
4053   // Add phi if "def" node is in peel set and "use" is not
4054 
4055   for (uint i = 0; i < peel_list.size(); i++) {
4056     Node *def  = peel_list.at(i);
4057     if (!def->is_CFG()) {
4058       for (DUIterator_Fast jmax, j = def->fast_outs(jmax); j < jmax; j++) {
4059         Node *use = def->fast_out(j);
4060         if (has_node(use) && use->in(0) != C->top() &&
4061             (!peel.test(use->_idx) ||
4062              (use->is_Phi() && use->in(0) == head)) ) {
4063           worklist.push(use);
4064         }
4065       }
4066       while( worklist.size() ) {
4067         Node *use = worklist.pop();
4068         for (uint j = 1; j < use->req(); j++) {
4069           Node* n = use->in(j);
4070           if (n == def) {
4071 
4072             // "def" is in peel set, "use" is not in peel set
4073             // or "use" is in the entry boundary (a phi) of the peel set
4074 
4075             Node* use_c = has_ctrl(use) ? get_ctrl(use) : use;
4076 
4077             if ( loop->is_member(get_loop( use_c )) ) {
4078               // use is in loop
4079               if (old_new[use->_idx] != nullptr) { // null for dead code
4080                 Node* use_clone = old_new[use->_idx];
4081                 _igvn.replace_input_of(use, j, C->top());
4082                 insert_phi_for_loop( use_clone, j, old_new[def->_idx], def, new_head_clone );
4083               }
4084             } else {
4085               assert(is_valid_clone_loop_exit_use(loop, use, orig_exit_idx), "clone loop format");
4086               // use is not in the loop, check if the live range includes the cut
4087               Node* lp_if = use_c->in(orig_exit_idx)->in(0);
4088               if (not_peel.test(lp_if->_idx)) {
4089                 assert(j == orig_exit_idx, "use from original loop");
4090                 insert_phi_for_loop( use, clone_exit_idx, old_new[def->_idx], def, new_head_clone );
4091               }
4092             }
4093           }
4094         }
4095       }
4096     }
4097   }
4098 
4099   // Step 3b: retarget control
4100 
4101   // Redirect control to the new loop head if a cloned node in
4102   // the not_peeled region has control that points into the peeled region.
4103   // This necessary because the cloned peeled region will be outside
4104   // the loop.
4105   //                            from    to
4106   //          cloned-peeled    <---+
4107   //    new_head_clone:            |    <--+
4108   //          cloned-not_peeled  in(0)    in(0)
4109   //          orig-peeled
4110 
4111   for (uint i = 0; i < loop->_body.size(); i++) {
4112     Node *n = loop->_body.at(i);
4113     if (!n->is_CFG()           && n->in(0) != nullptr        &&
4114         not_peel.test(n->_idx) && peel.test(n->in(0)->_idx)) {
4115       Node* n_clone = old_new[n->_idx];
4116       if (n_clone->depends_only_on_test()) {
4117         // If this node depends_only_on_test, it will be rewire to the loop head, which is not the
4118         // correct test
4119         Node* pinned_clone = n_clone->pin_node_under_control();
4120         if (pinned_clone != nullptr) {
4121           register_new_node_with_ctrl_of(pinned_clone, n_clone);
4122           old_new.map(n->_idx, pinned_clone);
4123           _igvn.replace_node(n_clone, pinned_clone);
4124           n_clone = pinned_clone;
4125         }
4126       }
4127       _igvn.replace_input_of(n_clone, 0, new_head_clone);
4128     }
4129   }
4130 
4131   // Backedge of the surviving new_head (the clone) is original last_peel
4132   _igvn.replace_input_of(new_head_clone, LoopNode::LoopBackControl, last_peel);
4133 
4134   // Cut first node in original not_peel set
4135   _igvn.rehash_node_delayed(new_head);                     // Multiple edge updates:
4136   new_head->set_req(LoopNode::EntryControl,    C->top());  //   use rehash_node_delayed / set_req instead of
4137   new_head->set_req(LoopNode::LoopBackControl, C->top());  //   multiple replace_input_of calls
4138 
4139   // Copy head_clone back-branch info to original head
4140   // and remove original head's loop entry and
4141   // clone head's back-branch
4142   _igvn.rehash_node_delayed(head); // Multiple edge updates
4143   head->set_req(LoopNode::EntryControl,    head_clone->in(LoopNode::LoopBackControl));
4144   head->set_req(LoopNode::LoopBackControl, C->top());
4145   _igvn.replace_input_of(head_clone, LoopNode::LoopBackControl, C->top());
4146 
4147   // Similarly modify the phis
4148   for (DUIterator_Fast kmax, k = head->fast_outs(kmax); k < kmax; k++) {
4149     Node* use = head->fast_out(k);
4150     if (use->is_Phi() && use->outcnt() > 0) {
4151       Node* use_clone = old_new[use->_idx];
4152       _igvn.rehash_node_delayed(use); // Multiple edge updates
4153       use->set_req(LoopNode::EntryControl,    use_clone->in(LoopNode::LoopBackControl));
4154       use->set_req(LoopNode::LoopBackControl, C->top());
4155       _igvn.replace_input_of(use_clone, LoopNode::LoopBackControl, C->top());
4156     }
4157   }
4158 
4159   // Step 4: update dominator tree and dominator depth
4160 
4161   set_idom(head, orig_tail_clone, dd);
4162   recompute_dom_depth();
4163 
4164   // Inhibit more partial peeling on this loop
4165   new_head_clone->set_partial_peel_loop();
4166   C->set_major_progress();
4167   loop->record_for_igvn();
4168 
4169 #ifndef PRODUCT
4170   if (TracePartialPeeling) {
4171     tty->print_cr("\nafter partial peel one iteration");
4172     Node_List wl;
4173     Node* t = last_peel;
4174     while (true) {
4175       wl.push(t);
4176       if (t == head_clone) break;
4177       t = idom(t);
4178     }
4179     while (wl.size() > 0) {
4180       Node* tt = wl.pop();
4181       if (tt == head) tty->print_cr("orig head");
4182       else if (tt == new_head_clone) tty->print_cr("new head");
4183       else if (tt == head_clone) tty->print_cr("clone head");
4184       tt->dump();
4185     }
4186   }
4187 #endif
4188 
4189   C->print_method(PHASE_AFTER_PARTIAL_PEELING, 4, new_head_clone);
4190 
4191   return true;
4192 }
4193 
4194 #ifdef ASSERT
4195 
4196 // Moves Template Assertion Predicates to a target loop by cloning and killing the old ones. The target loop is the
4197 // original, not-cloned loop. This is currently only used with StressLoopBackedge which is a develop flag only and
4198 // false with product builds. We can therefore guard it with an ifdef. More details can be found at the use-site.
4199 class MoveAssertionPredicatesVisitor : public PredicateVisitor {
4200   ClonePredicateToTargetLoop _clone_predicate_to_loop;
4201   PhaseIdealLoop* const _phase;
4202 
4203 public:
4204   MoveAssertionPredicatesVisitor(LoopNode* target_loop_head,
4205                                  const NodeInSingleLoopBody &node_in_loop_body,
4206                                  PhaseIdealLoop* phase)
4207     : _clone_predicate_to_loop(target_loop_head, node_in_loop_body, phase),
4208       _phase(phase) {
4209   }
4210   NONCOPYABLE(MoveAssertionPredicatesVisitor);
4211 
4212   using PredicateVisitor::visit;
4213 
4214   void visit(const TemplateAssertionPredicate& template_assertion_predicate) override {
4215     _clone_predicate_to_loop.clone_template_assertion_predicate(template_assertion_predicate);
4216     template_assertion_predicate.kill(_phase->igvn());
4217   }
4218 };
4219 #endif // ASSERT
4220 
4221 // Transform:
4222 //
4223 // loop<-----------------+
4224 //  |                    |
4225 // stmt1 stmt2 .. stmtn  |
4226 //  |     |        |     |
4227 //  \     |       /      |
4228 //    v   v     v        |
4229 //       region          |
4230 //         |             |
4231 //     shared_stmt       |
4232 //         |             |
4233 //         v             |
4234 //         if            |
4235 //         / \           |
4236 //        |   -----------+
4237 //        v
4238 //
4239 // into:
4240 //
4241 //    loop<-------------------+
4242 //     |                      |
4243 //     v                      |
4244 // +->loop                    |
4245 // |   |                      |
4246 // |  stmt1 stmt2 .. stmtn    |
4247 // |   |     |        |       |
4248 // |   |      \       /       |
4249 // |   |       v     v        |
4250 // |   |        region1       |
4251 // |   |           |          |
4252 // |  shared_stmt shared_stmt |
4253 // |   |           |          |
4254 // |   v           v          |
4255 // |   if          if         |
4256 // |   /\          / \        |
4257 // +--   |         |   -------+
4258 //       \         /
4259 //        v       v
4260 //         region2
4261 //
4262 // (region2 is shown to merge mirrored projections of the loop exit
4263 // ifs to make the diagram clearer but they really merge the same
4264 // projection)
4265 //
4266 // Conditions for this transformation to trigger:
4267 // - the path through stmt1 is frequent enough
4268 // - the inner loop will be turned into a counted loop after transformation
4269 bool PhaseIdealLoop::duplicate_loop_backedge(IdealLoopTree *loop, Node_List &old_new) {
4270   if (!DuplicateBackedge) {
4271     return false;
4272   }
4273   assert(!loop->_head->is_CountedLoop() || StressDuplicateBackedge, "Non-counted loop only");
4274   if (!loop->_head->is_Loop()) {
4275     return false;
4276   }
4277 
4278   uint estimate = loop->est_loop_clone_sz(1);
4279   if (exceeding_node_budget(estimate)) {
4280     return false;
4281   }
4282 
4283   LoopNode *head = loop->_head->as_Loop();
4284 
4285   Node* region = nullptr;
4286   IfNode* exit_test = nullptr;
4287   uint inner;
4288   float f;
4289 #ifdef ASSERT
4290   if (StressDuplicateBackedge) {
4291     if (head->is_strip_mined()) {
4292       return false;
4293     }
4294     Node* c = head->in(LoopNode::LoopBackControl);
4295 
4296     while (c != head) {
4297       if (c->is_Region()) {
4298         region = c;
4299       }
4300       c = idom(c);
4301     }
4302 
4303     if (region == nullptr) {
4304       return false;
4305     }
4306 
4307     inner = 1;
4308   } else
4309 #endif //ASSERT
4310   {
4311     // Is the shape of the loop that of a counted loop...
4312     Node* back_control = loop_exit_control(loop);
4313     if (back_control == nullptr) {
4314       return false;
4315     }
4316 
4317     LoopExitTest loop_exit(back_control, loop, this);
4318     loop_exit.build();
4319     if (!loop_exit.is_valid_with_bt(T_INT)) {
4320       return false;
4321     }
4322 
4323     const Node* loop_incr = loop_exit.incr();
4324 
4325     // With an extra phi for the candidate iv?
4326     // Or the region node is the loop head
4327     if (!loop_incr->is_Phi() || loop_incr->in(0) == head) {
4328       return false;
4329     }
4330 
4331     PathFrequency pf(head, this);
4332     region = loop_incr->in(0);
4333 
4334     // Go over all paths for the extra phi's region and see if that
4335     // path is frequent enough and would match the expected iv shape
4336     // if the extra phi is removed
4337     inner = 0;
4338     for (uint i = 1; i < loop_incr->req(); ++i) {
4339       CountedLoopConverter::TruncatedIncrement increment(T_INT);
4340       increment.build(loop_incr->in(i));
4341       if (!increment.is_valid()) {
4342         continue;
4343       }
4344       assert(increment.incr()->Opcode() == Op_AddI, "wrong increment code");
4345 
4346       LoopIVStride stride = LoopIVStride(T_INT);
4347       stride.build(increment.incr());
4348       if (!stride.is_valid()) {
4349         continue;
4350       }
4351 
4352       PhiNode* phi = loop_iv_phi(stride.xphi(), nullptr, head);
4353       if (phi == nullptr ||
4354           (increment.outer_trunc() == nullptr && phi->in(LoopNode::LoopBackControl) != loop_exit.incr()) ||
4355           (increment.outer_trunc() != nullptr && phi->in(LoopNode::LoopBackControl) != increment.outer_trunc())) {
4356         return false;
4357       }
4358 
4359       f = pf.to(region->in(i));
4360       if (f > 0.5) {
4361         inner = i;
4362         break;
4363       }
4364     }
4365 
4366     if (inner == 0) {
4367       return false;
4368     }
4369 
4370     exit_test = back_control->in(0)->as_If();
4371   }
4372 
4373   if (idom(region)->is_Catch()) {
4374     return false;
4375   }
4376 
4377   // Collect all control nodes that need to be cloned (shared_stmt in the diagram)
4378   Unique_Node_List wq;
4379   wq.push(head->in(LoopNode::LoopBackControl));
4380   for (uint i = 0; i < wq.size(); i++) {
4381     Node* c = wq.at(i);
4382     assert(get_loop(c) == loop, "not in the right loop?");
4383     if (c->is_Region()) {
4384       if (c != region) {
4385         for (uint j = 1; j < c->req(); ++j) {
4386           wq.push(c->in(j));
4387         }
4388       }
4389     } else {
4390       wq.push(c->in(0));
4391     }
4392     assert(!is_strict_dominator(c, region), "shouldn't go above region");
4393   }
4394 
4395   Node* region_dom = idom(region);
4396 
4397   // Can't do the transformation if this would cause a membar pair to
4398   // be split
4399   for (uint i = 0; i < wq.size(); i++) {
4400     Node* c = wq.at(i);
4401     if (c->is_MemBar() && (c->as_MemBar()->trailing_store() || c->as_MemBar()->trailing_load_store())) {
4402       assert(c->as_MemBar()->leading_membar()->trailing_membar() == c, "bad membar pair");
4403       if (!wq.member(c->as_MemBar()->leading_membar())) {
4404         return false;
4405       }
4406     }
4407   }
4408   C->print_method(PHASE_BEFORE_DUPLICATE_LOOP_BACKEDGE, 4, head);
4409 
4410   // Collect data nodes that need to be clones as well
4411   int dd = dom_depth(head);
4412 
4413   for (uint i = 0; i < loop->_body.size(); ++i) {
4414     Node* n = loop->_body.at(i);
4415     if (has_ctrl(n)) {
4416       Node* c = get_ctrl(n);
4417       if (wq.member(c)) {
4418         wq.push(n);
4419       }
4420     } else {
4421       set_idom(n, idom(n), dd);
4422     }
4423   }
4424 
4425   // clone shared_stmt
4426   clone_loop_body(wq, old_new, nullptr);
4427 
4428   Node* region_clone = old_new[region->_idx];
4429   region_clone->set_req(inner, C->top());
4430   set_idom(region, region->in(inner), dd);
4431 
4432   // Prepare the outer loop
4433   Node* outer_head = new LoopNode(head->in(LoopNode::EntryControl), old_new[head->in(LoopNode::LoopBackControl)->_idx]);
4434   register_control(outer_head, loop->_parent, outer_head->in(LoopNode::EntryControl));
4435   _igvn.replace_input_of(head, LoopNode::EntryControl, outer_head);
4436   set_idom(head, outer_head, dd);
4437 
4438   fix_body_edges(wq, loop, old_new, dd, loop->_parent, true);
4439 
4440   // Make one of the shared_stmt copies only reachable from stmt1, the
4441   // other only from stmt2..stmtn.
4442   Node* dom = nullptr;
4443   for (uint i = 1; i < region->req(); ++i) {
4444     if (i != inner) {
4445       _igvn.replace_input_of(region, i, C->top());
4446     }
4447     Node* in = region_clone->in(i);
4448     if (in->is_top()) {
4449       continue;
4450     }
4451     if (dom == nullptr) {
4452       dom = in;
4453     } else {
4454       dom = dom_lca(dom, in);
4455     }
4456   }
4457 
4458   set_idom(region_clone, dom, dd);
4459 
4460   // Set up the outer loop
4461   for (uint i = 0; i < head->outcnt(); i++) {
4462     Node* u = head->raw_out(i);
4463     if (u->is_Phi()) {
4464       Node* outer_phi = u->clone();
4465       outer_phi->set_req(0, outer_head);
4466       Node* backedge = old_new[u->in(LoopNode::LoopBackControl)->_idx];
4467       if (backedge == nullptr) {
4468         backedge = u->in(LoopNode::LoopBackControl);
4469       }
4470       outer_phi->set_req(LoopNode::LoopBackControl, backedge);
4471       register_new_node(outer_phi, outer_head);
4472       _igvn.replace_input_of(u, LoopNode::EntryControl, outer_phi);
4473     }
4474   }
4475 
4476   // create control and data nodes for out of loop uses (including region2)
4477   Node_List worklist;
4478   uint new_counter = C->unique();
4479   fix_ctrl_uses(wq, loop, old_new, ControlAroundStripMined, outer_head, nullptr, worklist);
4480 
4481   Node_List *split_if_set = nullptr;
4482   Node_List *split_bool_set = nullptr;
4483   Node_List *split_cex_set = nullptr;
4484   fix_data_uses(wq, loop, ControlAroundStripMined, loop->skip_strip_mined(), new_counter, old_new, worklist,
4485                 split_if_set, split_bool_set, split_cex_set);
4486 
4487   finish_clone_loop(split_if_set, split_bool_set, split_cex_set);
4488 
4489   if (exit_test != nullptr) {
4490     float cnt = exit_test->_fcnt;
4491     if (cnt != COUNT_UNKNOWN) {
4492       exit_test->_fcnt = cnt * f;
4493       old_new[exit_test->_idx]->as_If()->_fcnt = cnt * (1 - f);
4494     }
4495   }
4496 
4497 #ifdef ASSERT
4498   if (StressDuplicateBackedge && head->is_CountedLoop()) {
4499     // The Template Assertion Predicates from the old counted loop are now at the new outer loop - clone them to
4500     // the inner counted loop and kill the old ones. We only need to do this with debug builds because
4501     // StressDuplicateBackedge is a devlop flag and false by default. Without StressDuplicateBackedge 'head' will be a
4502     // non-counted loop, and thus we have no Template Assertion Predicates above the old loop to move down.
4503     PredicateIterator predicate_iterator(outer_head->in(LoopNode::EntryControl));
4504     NodeInSingleLoopBody node_in_body(this, loop);
4505     MoveAssertionPredicatesVisitor move_assertion_predicates_visitor(head, node_in_body, this);
4506     predicate_iterator.for_each(move_assertion_predicates_visitor);
4507   }
4508 #endif // ASSERT
4509 
4510   C->set_major_progress();
4511 
4512   C->print_method(PHASE_AFTER_DUPLICATE_LOOP_BACKEDGE, 4, outer_head);
4513 
4514   return true;
4515 }
4516 
4517 // AutoVectorize the loop: replace scalar ops with vector ops.
4518 PhaseIdealLoop::AutoVectorizeStatus
4519 PhaseIdealLoop::auto_vectorize(IdealLoopTree* lpt, VSharedData &vshared) {
4520   // Counted loop only
4521   if (!lpt->is_counted()) {
4522     return AutoVectorizeStatus::Impossible;
4523   }
4524 
4525   // Main-loop only
4526   CountedLoopNode* cl = lpt->_head->as_CountedLoop();
4527   if (!cl->is_main_loop()) {
4528     return AutoVectorizeStatus::Impossible;
4529   }
4530 
4531   VLoop vloop(lpt, false);
4532   if (!vloop.check_preconditions()) {
4533     return AutoVectorizeStatus::TriedAndFailed;
4534   }
4535 
4536   // Ensure the shared data is cleared before each use
4537   vshared.clear();
4538 
4539   const VLoopAnalyzer vloop_analyzer(vloop, vshared);
4540   if (!vloop_analyzer.success()) {
4541     return AutoVectorizeStatus::TriedAndFailed;
4542   }
4543 
4544   SuperWord sw(vloop_analyzer);
4545   if (!sw.transform_loop()) {
4546     return AutoVectorizeStatus::TriedAndFailed;
4547   }
4548 
4549   return AutoVectorizeStatus::Success;
4550 }
4551 
4552 // Just before insert_pre_post_loops, we can multiversion the loop:
4553 //
4554 //              multiversion_if
4555 //               |       |
4556 //         fast_loop   slow_loop
4557 //
4558 // In the fast_loop we can make speculative assumptions, and put the
4559 // conditions into the multiversion_if. If the conditions hold at runtime,
4560 // we enter the fast_loop, if the conditions fail, we take the slow_loop
4561 // instead which does not make any of the speculative assumptions.
4562 //
4563 // Note: we only multiversion the loop if the loop does not have any
4564 //       auto vectorization check Predicate. If we have that predicate,
4565 //       then we can simply add the speculative assumption checks to
4566 //       that Predicate. This means we do not need to duplicate the
4567 //       loop - we have a smaller graph and save compile time. Should
4568 //       the conditions ever fail, then we deopt / trap at the Predicate
4569 //       and recompile without that Predicate. At that point we will
4570 //       multiversion the loop, so that we can still have speculative
4571 //       runtime checks.
4572 //
4573 // We perform the multiversioning when the loop is still in its single
4574 // iteration form, even before we insert pre and post loops. This makes
4575 // the cloning much simpler. However, this means that both the fast
4576 // and the slow loop have to be optimized independently (adding pre
4577 // and post loops, unrolling the main loop, auto-vectorize etc.). And
4578 // we may end up not needing any speculative assumptions in the fast_loop
4579 // and then rejecting the slow_loop by constant folding the multiversion_if.
4580 //
4581 // Therefore, we "delay" the optimization of the slow_loop until we add
4582 // at least one speculative assumption for the fast_loop. If we never
4583 // add such a speculative runtime check, the OpaqueMultiversioningNode
4584 // of the multiversion_if constant folds to true after loop opts, and the
4585 // multiversion_if folds away the "delayed" slow_loop. If we add any
4586 // speculative assumption, then we notify the OpaqueMultiversioningNode
4587 // with "notify_slow_loop_that_it_can_resume_optimizations".
4588 //
4589 // Note: new runtime checks can be added to the multiversion_if with
4590 //       PhaseIdealLoop::create_new_if_for_multiversion
4591 void PhaseIdealLoop::maybe_multiversion_for_auto_vectorization_runtime_checks(IdealLoopTree* lpt, Node_List& old_new) {
4592   CountedLoopNode* cl = lpt->_head->as_CountedLoop();
4593   LoopNode* outer_loop = cl->skip_strip_mined();
4594   Node* entry = outer_loop->in(LoopNode::EntryControl);
4595 
4596   // Check we have multiversioning enabled, and are not already multiversioned.
4597   if (!LoopMultiversioning || cl->is_multiversion()) { return; }
4598 
4599   // Check that we do not have a parse-predicate where we can add the runtime checks
4600   // during auto-vectorization.
4601   const Predicates predicates(entry);
4602   const PredicateBlock* predicate_block = predicates.auto_vectorization_check_block();
4603   if (predicate_block->has_parse_predicate()) { return; }
4604 
4605   // Check node budget.
4606   uint estimate = lpt->est_loop_clone_sz(2);
4607   if (!may_require_nodes(estimate)) { return; }
4608 
4609   do_multiversioning(lpt, old_new);
4610 }
4611 
4612 void DataNodeGraph::clone_data_nodes(Node* new_ctrl) {
4613   for (uint i = 0; i < _data_nodes.size(); i++) {
4614     clone(_data_nodes[i], new_ctrl);
4615   }
4616 }
4617 
4618 // Clone the given node and set it up properly. Set 'new_ctrl' as ctrl.
4619 void DataNodeGraph::clone(Node* node, Node* new_ctrl) {
4620   Node* clone = node->clone();
4621   _phase->igvn().register_new_node_with_optimizer(clone);
4622   _orig_to_new.put(node, clone);
4623   _phase->set_ctrl(clone, new_ctrl);
4624   if (node->is_CastII()) {
4625     clone->set_req(0, new_ctrl);
4626   }
4627 }
4628 
4629 // Rewire the data inputs of all (unprocessed) cloned nodes, whose inputs are still pointing to the same inputs as their
4630 // corresponding orig nodes, to the newly cloned inputs to create a separate cloned graph.
4631 void DataNodeGraph::rewire_clones_to_cloned_inputs() {
4632   _orig_to_new.iterate_all([&](Node* node, Node* clone) {
4633     for (uint i = 1; i < node->req(); i++) {
4634       Node** cloned_input = _orig_to_new.get(node->in(i));
4635       if (cloned_input != nullptr) {
4636         // Input was also cloned -> rewire clone to the cloned input.
4637         _phase->igvn().replace_input_of(clone, i, *cloned_input);
4638       }
4639     }
4640   });
4641 }
4642 
4643 // Clone all non-OpaqueLoop* nodes and apply the provided transformation strategy for OpaqueLoop* nodes.
4644 // Set 'new_ctrl' as ctrl for all cloned non-OpaqueLoop* nodes.
4645 void DataNodeGraph::clone_data_nodes_and_transform_opaque_loop_nodes(
4646     const TransformStrategyForOpaqueLoopNodes& transform_strategy,
4647     Node* new_ctrl) {
4648   for (uint i = 0; i < _data_nodes.size(); i++) {
4649     Node* data_node = _data_nodes[i];
4650     if (data_node->is_Opaque1()) {
4651       transform_opaque_node(transform_strategy, data_node);
4652     } else {
4653       clone(data_node, new_ctrl);
4654     }
4655   }
4656 }
4657 
4658 void DataNodeGraph::transform_opaque_node(const TransformStrategyForOpaqueLoopNodes& transform_strategy, Node* node) {
4659   Node* transformed_node;
4660   if (node->is_OpaqueLoopInit()) {
4661     transformed_node = transform_strategy.transform_opaque_init(node->as_OpaqueLoopInit());
4662   } else {
4663     assert(node->is_OpaqueLoopStride(), "must be OpaqueLoopStrideNode");
4664     transformed_node = transform_strategy.transform_opaque_stride(node->as_OpaqueLoopStride());
4665   }
4666   // Add an orig->new mapping to correctly update the inputs of the copied graph in rewire_clones_to_cloned_inputs().
4667   _orig_to_new.put(node, transformed_node);
4668 }