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