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