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