1 /*
   2  * Copyright 1999-2008 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
  20  * CA 95054 USA or visit www.sun.com if you need additional information or
  21  * have any questions.
  22  *
  23  */
  24 
  25 #include "incls/_precompiled.incl"
  26 #include "incls/_loopopts.cpp.incl"
  27 
  28 //=============================================================================
  29 //------------------------------split_thru_phi---------------------------------
  30 // Split Node 'n' through merge point if there is enough win.
  31 Node *PhaseIdealLoop::split_thru_phi( Node *n, Node *region, int policy ) {
  32   if (n->Opcode() == Op_ConvI2L && n->bottom_type() != TypeLong::LONG) {
  33     // ConvI2L may have type information on it which is unsafe to push up
  34     // so disable this for now
  35     return NULL;
  36   }
  37   int wins = 0;
  38   assert( !n->is_CFG(), "" );
  39   assert( region->is_Region(), "" );
  40 
  41   const Type* type = n->bottom_type();
  42   const TypeOopPtr *t_oop = _igvn.type(n)->isa_oopptr();
  43   Node *phi;
  44   if( t_oop != NULL && t_oop->is_known_instance_field() ) {
  45     int iid    = t_oop->instance_id();
  46     int index  = C->get_alias_index(t_oop);
  47     int offset = t_oop->offset();
  48     phi = new (C,region->req()) PhiNode(region, type, NULL, iid, index, offset);
  49   } else {
  50     phi = new (C,region->req()) PhiNode(region, type);
  51   }
  52   uint old_unique = C->unique();
  53   for( uint i = 1; i < region->req(); i++ ) {
  54     Node *x;
  55     Node* the_clone = NULL;
  56     if( region->in(i) == C->top() ) {
  57       x = C->top();             // Dead path?  Use a dead data op
  58     } else {
  59       x = n->clone();           // Else clone up the data op
  60       the_clone = x;            // Remember for possible deletion.
  61       // Alter data node to use pre-phi inputs
  62       if( n->in(0) == region )
  63         x->set_req( 0, region->in(i) );
  64       for( uint j = 1; j < n->req(); j++ ) {
  65         Node *in = n->in(j);
  66         if( in->is_Phi() && in->in(0) == region )
  67           x->set_req( j, in->in(i) ); // Use pre-Phi input for the clone
  68       }
  69     }
  70     // Check for a 'win' on some paths
  71     const Type *t = x->Value(&_igvn);
  72 
  73     bool singleton = t->singleton();
  74 
  75     // A TOP singleton indicates that there are no possible values incoming
  76     // along a particular edge. In most cases, this is OK, and the Phi will
  77     // be eliminated later in an Ideal call. However, we can't allow this to
  78     // happen if the singleton occurs on loop entry, as the elimination of
  79     // the PhiNode may cause the resulting node to migrate back to a previous
  80     // loop iteration.
  81     if( singleton && t == Type::TOP ) {
  82       // Is_Loop() == false does not confirm the absence of a loop (e.g., an
  83       // irreducible loop may not be indicated by an affirmative is_Loop());
  84       // therefore, the only top we can split thru a phi is on a backedge of
  85       // a loop.
  86       singleton &= region->is_Loop() && (i != LoopNode::EntryControl);
  87     }
  88 
  89     if( singleton ) {
  90       wins++;
  91       x = ((PhaseGVN&)_igvn).makecon(t);
  92     } else {
  93       // We now call Identity to try to simplify the cloned node.
  94       // Note that some Identity methods call phase->type(this).
  95       // Make sure that the type array is big enough for
  96       // our new node, even though we may throw the node away.
  97       // (Note: This tweaking with igvn only works because x is a new node.)
  98       _igvn.set_type(x, t);
  99       // If x is a TypeNode, capture any more-precise type permanently into Node
 100       // othewise it will be not updated during igvn->transform since
 101       // igvn->type(x) is set to x->Value() already.
 102       x->raise_bottom_type(t);
 103       Node *y = x->Identity(&_igvn);
 104       if( y != x ) {
 105         wins++;
 106         x = y;
 107       } else {
 108         y = _igvn.hash_find(x);
 109         if( y ) {
 110           wins++;
 111           x = y;
 112         } else {
 113           // Else x is a new node we are keeping
 114           // We do not need register_new_node_with_optimizer
 115           // because set_type has already been called.
 116           _igvn._worklist.push(x);
 117         }
 118       }
 119     }
 120     if (x != the_clone && the_clone != NULL)
 121       _igvn.remove_dead_node(the_clone);
 122     phi->set_req( i, x );
 123   }
 124   // Too few wins?
 125   if( wins <= policy ) {
 126     _igvn.remove_dead_node(phi);
 127     return NULL;
 128   }
 129 
 130   // Record Phi
 131   register_new_node( phi, region );
 132 
 133   for( uint i2 = 1; i2 < phi->req(); i2++ ) {
 134     Node *x = phi->in(i2);
 135     // If we commoned up the cloned 'x' with another existing Node,
 136     // the existing Node picks up a new use.  We need to make the
 137     // existing Node occur higher up so it dominates its uses.
 138     Node *old_ctrl;
 139     IdealLoopTree *old_loop;
 140 
 141     // The occasional new node
 142     if( x->_idx >= old_unique ) {   // Found a new, unplaced node?
 143       old_ctrl = x->is_Con() ? C->root() : NULL;
 144       old_loop = NULL;              // Not in any prior loop
 145     } else {
 146       old_ctrl = x->is_Con() ? C->root() : get_ctrl(x);
 147       old_loop = get_loop(old_ctrl); // Get prior loop
 148     }
 149     // New late point must dominate new use
 150     Node *new_ctrl = dom_lca( old_ctrl, region->in(i2) );
 151     // Set new location
 152     set_ctrl(x, new_ctrl);
 153     IdealLoopTree *new_loop = get_loop( new_ctrl );
 154     // If changing loop bodies, see if we need to collect into new body
 155     if( old_loop != new_loop ) {
 156       if( old_loop && !old_loop->_child )
 157         old_loop->_body.yank(x);
 158       if( !new_loop->_child )
 159         new_loop->_body.push(x);  // Collect body info
 160     }
 161   }
 162 
 163   return phi;
 164 }
 165 
 166 //------------------------------dominated_by------------------------------------
 167 // Replace the dominated test with an obvious true or false.  Place it on the
 168 // IGVN worklist for later cleanup.  Move control-dependent data Nodes on the
 169 // live path up to the dominating control.
 170 void PhaseIdealLoop::dominated_by( Node *prevdom, Node *iff ) {
 171 #ifndef PRODUCT
 172   if( VerifyLoopOptimizations && PrintOpto ) tty->print_cr("dominating test");
 173 #endif
 174 
 175 
 176   // prevdom is the dominating projection of the dominating test.
 177   assert( iff->is_If(), "" );
 178   assert( iff->Opcode() == Op_If || iff->Opcode() == Op_CountedLoopEnd, "Check this code when new subtype is added");
 179   int pop = prevdom->Opcode();
 180   assert( pop == Op_IfFalse || pop == Op_IfTrue, "" );
 181   // 'con' is set to true or false to kill the dominated test.
 182   Node *con = _igvn.makecon(pop == Op_IfTrue ? TypeInt::ONE : TypeInt::ZERO);
 183   set_ctrl(con, C->root()); // Constant gets a new use
 184   // Hack the dominated test
 185   _igvn.hash_delete(iff);
 186   iff->set_req(1, con);
 187   _igvn._worklist.push(iff);
 188 
 189   // If I dont have a reachable TRUE and FALSE path following the IfNode then
 190   // I can assume this path reaches an infinite loop.  In this case it's not
 191   // important to optimize the data Nodes - either the whole compilation will
 192   // be tossed or this path (and all data Nodes) will go dead.
 193   if( iff->outcnt() != 2 ) return;
 194 
 195   // Make control-dependent data Nodes on the live path (path that will remain
 196   // once the dominated IF is removed) become control-dependent on the
 197   // dominating projection.
 198   Node* dp = ((IfNode*)iff)->proj_out(pop == Op_IfTrue);
 199   IdealLoopTree *old_loop = get_loop(dp);
 200 
 201   for (DUIterator_Fast imax, i = dp->fast_outs(imax); i < imax; i++) {
 202     Node* cd = dp->fast_out(i); // Control-dependent node
 203     if( cd->depends_only_on_test() ) {
 204       assert( cd->in(0) == dp, "" );
 205       _igvn.hash_delete( cd );
 206       cd->set_req(0, prevdom);
 207       set_early_ctrl( cd );
 208       _igvn._worklist.push(cd);
 209       IdealLoopTree *new_loop = get_loop(get_ctrl(cd));
 210       if( old_loop != new_loop ) {
 211         if( !old_loop->_child ) old_loop->_body.yank(cd);
 212         if( !new_loop->_child ) new_loop->_body.push(cd);
 213       }
 214       --i;
 215       --imax;
 216     }
 217   }
 218 }
 219 
 220 //------------------------------has_local_phi_input----------------------------
 221 // Return TRUE if 'n' has Phi inputs from its local block and no other
 222 // block-local inputs (all non-local-phi inputs come from earlier blocks)
 223 Node *PhaseIdealLoop::has_local_phi_input( Node *n ) {
 224   Node *n_ctrl = get_ctrl(n);
 225   // See if some inputs come from a Phi in this block, or from before
 226   // this block.
 227   uint i;
 228   for( i = 1; i < n->req(); i++ ) {
 229     Node *phi = n->in(i);
 230     if( phi->is_Phi() && phi->in(0) == n_ctrl )
 231       break;
 232   }
 233   if( i >= n->req() )
 234     return NULL;                // No Phi inputs; nowhere to clone thru
 235 
 236   // Check for inputs created between 'n' and the Phi input.  These
 237   // must split as well; they have already been given the chance
 238   // (courtesy of a post-order visit) and since they did not we must
 239   // recover the 'cost' of splitting them by being very profitable
 240   // when splitting 'n'.  Since this is unlikely we simply give up.
 241   for( i = 1; i < n->req(); i++ ) {
 242     Node *m = n->in(i);
 243     if( get_ctrl(m) == n_ctrl && !m->is_Phi() ) {
 244       // We allow the special case of AddP's with no local inputs.
 245       // This allows us to split-up address expressions.
 246       if (m->is_AddP() &&
 247           get_ctrl(m->in(2)) != n_ctrl &&
 248           get_ctrl(m->in(3)) != n_ctrl) {
 249         // Move the AddP up to dominating point
 250         set_ctrl_and_loop(m, find_non_split_ctrl(idom(n_ctrl)));
 251         continue;
 252       }
 253       return NULL;
 254     }
 255   }
 256 
 257   return n_ctrl;
 258 }
 259 
 260 //------------------------------remix_address_expressions----------------------
 261 // Rework addressing expressions to get the most loop-invariant stuff
 262 // moved out.  We'd like to do all associative operators, but it's especially
 263 // important (common) to do address expressions.
 264 Node *PhaseIdealLoop::remix_address_expressions( Node *n ) {
 265   if (!has_ctrl(n))  return NULL;
 266   Node *n_ctrl = get_ctrl(n);
 267   IdealLoopTree *n_loop = get_loop(n_ctrl);
 268 
 269   // See if 'n' mixes loop-varying and loop-invariant inputs and
 270   // itself is loop-varying.
 271 
 272   // Only interested in binary ops (and AddP)
 273   if( n->req() < 3 || n->req() > 4 ) return NULL;
 274 
 275   Node *n1_ctrl = get_ctrl(n->in(                    1));
 276   Node *n2_ctrl = get_ctrl(n->in(                    2));
 277   Node *n3_ctrl = get_ctrl(n->in(n->req() == 3 ? 2 : 3));
 278   IdealLoopTree *n1_loop = get_loop( n1_ctrl );
 279   IdealLoopTree *n2_loop = get_loop( n2_ctrl );
 280   IdealLoopTree *n3_loop = get_loop( n3_ctrl );
 281 
 282   // Does one of my inputs spin in a tighter loop than self?
 283   if( (n_loop->is_member( n1_loop ) && n_loop != n1_loop) ||
 284       (n_loop->is_member( n2_loop ) && n_loop != n2_loop) ||
 285       (n_loop->is_member( n3_loop ) && n_loop != n3_loop) )
 286     return NULL;                // Leave well enough alone
 287 
 288   // Is at least one of my inputs loop-invariant?
 289   if( n1_loop == n_loop &&
 290       n2_loop == n_loop &&
 291       n3_loop == n_loop )
 292     return NULL;                // No loop-invariant inputs
 293 
 294 
 295   int n_op = n->Opcode();
 296 
 297   // Replace expressions like ((V+I) << 2) with (V<<2 + I<<2).
 298   if( n_op == Op_LShiftI ) {
 299     // Scale is loop invariant
 300     Node *scale = n->in(2);
 301     Node *scale_ctrl = get_ctrl(scale);
 302     IdealLoopTree *scale_loop = get_loop(scale_ctrl );
 303     if( n_loop == scale_loop || !scale_loop->is_member( n_loop ) )
 304       return NULL;
 305     const TypeInt *scale_t = scale->bottom_type()->isa_int();
 306     if( scale_t && scale_t->is_con() && scale_t->get_con() >= 16 )
 307       return NULL;              // Dont bother with byte/short masking
 308     // Add must vary with loop (else shift would be loop-invariant)
 309     Node *add = n->in(1);
 310     Node *add_ctrl = get_ctrl(add);
 311     IdealLoopTree *add_loop = get_loop(add_ctrl);
 312     //assert( n_loop == add_loop, "" );
 313     if( n_loop != add_loop ) return NULL;  // happens w/ evil ZKM loops
 314 
 315     // Convert I-V into I+ (0-V); same for V-I
 316     if( add->Opcode() == Op_SubI &&
 317         _igvn.type( add->in(1) ) != TypeInt::ZERO ) {
 318       Node *zero = _igvn.intcon(0);
 319       set_ctrl(zero, C->root());
 320       Node *neg = new (C, 3) SubINode( _igvn.intcon(0), add->in(2) );
 321       register_new_node( neg, get_ctrl(add->in(2) ) );
 322       add = new (C, 3) AddINode( add->in(1), neg );
 323       register_new_node( add, add_ctrl );
 324     }
 325     if( add->Opcode() != Op_AddI ) return NULL;
 326     // See if one add input is loop invariant
 327     Node *add_var = add->in(1);
 328     Node *add_var_ctrl = get_ctrl(add_var);
 329     IdealLoopTree *add_var_loop = get_loop(add_var_ctrl );
 330     Node *add_invar = add->in(2);
 331     Node *add_invar_ctrl = get_ctrl(add_invar);
 332     IdealLoopTree *add_invar_loop = get_loop(add_invar_ctrl );
 333     if( add_var_loop == n_loop ) {
 334     } else if( add_invar_loop == n_loop ) {
 335       // Swap to find the invariant part
 336       add_invar = add_var;
 337       add_invar_ctrl = add_var_ctrl;
 338       add_invar_loop = add_var_loop;
 339       add_var = add->in(2);
 340       Node *add_var_ctrl = get_ctrl(add_var);
 341       IdealLoopTree *add_var_loop = get_loop(add_var_ctrl );
 342     } else                      // Else neither input is loop invariant
 343       return NULL;
 344     if( n_loop == add_invar_loop || !add_invar_loop->is_member( n_loop ) )
 345       return NULL;              // No invariant part of the add?
 346 
 347     // Yes!  Reshape address expression!
 348     Node *inv_scale = new (C, 3) LShiftINode( add_invar, scale );
 349     register_new_node( inv_scale, add_invar_ctrl );
 350     Node *var_scale = new (C, 3) LShiftINode( add_var, scale );
 351     register_new_node( var_scale, n_ctrl );
 352     Node *var_add = new (C, 3) AddINode( var_scale, inv_scale );
 353     register_new_node( var_add, n_ctrl );
 354     _igvn.hash_delete( n );
 355     _igvn.subsume_node( n, var_add );
 356     return var_add;
 357   }
 358 
 359   // Replace (I+V) with (V+I)
 360   if( n_op == Op_AddI ||
 361       n_op == Op_AddL ||
 362       n_op == Op_AddF ||
 363       n_op == Op_AddD ||
 364       n_op == Op_MulI ||
 365       n_op == Op_MulL ||
 366       n_op == Op_MulF ||
 367       n_op == Op_MulD ) {
 368     if( n2_loop == n_loop ) {
 369       assert( n1_loop != n_loop, "" );
 370       n->swap_edges(1, 2);
 371     }
 372   }
 373 
 374   // Replace ((I1 +p V) +p I2) with ((I1 +p I2) +p V),
 375   // but not if I2 is a constant.
 376   if( n_op == Op_AddP ) {
 377     if( n2_loop == n_loop && n3_loop != n_loop ) {
 378       if( n->in(2)->Opcode() == Op_AddP && !n->in(3)->is_Con() ) {
 379         Node *n22_ctrl = get_ctrl(n->in(2)->in(2));
 380         Node *n23_ctrl = get_ctrl(n->in(2)->in(3));
 381         IdealLoopTree *n22loop = get_loop( n22_ctrl );
 382         IdealLoopTree *n23_loop = get_loop( n23_ctrl );
 383         if( n22loop != n_loop && n22loop->is_member(n_loop) &&
 384             n23_loop == n_loop ) {
 385           Node *add1 = new (C, 4) AddPNode( n->in(1), n->in(2)->in(2), n->in(3) );
 386           // Stuff new AddP in the loop preheader
 387           register_new_node( add1, n_loop->_head->in(LoopNode::EntryControl) );
 388           Node *add2 = new (C, 4) AddPNode( n->in(1), add1, n->in(2)->in(3) );
 389           register_new_node( add2, n_ctrl );
 390           _igvn.hash_delete( n );
 391           _igvn.subsume_node( n, add2 );
 392           return add2;
 393         }
 394       }
 395     }
 396 
 397     // Replace (I1 +p (I2 + V)) with ((I1 +p I2) +p V)
 398     if( n2_loop != n_loop && n3_loop == n_loop ) {
 399       if( n->in(3)->Opcode() == Op_AddI ) {
 400         Node *V = n->in(3)->in(1);
 401         Node *I = n->in(3)->in(2);
 402         if( is_member(n_loop,get_ctrl(V)) ) {
 403         } else {
 404           Node *tmp = V; V = I; I = tmp;
 405         }
 406         if( !is_member(n_loop,get_ctrl(I)) ) {
 407           Node *add1 = new (C, 4) AddPNode( n->in(1), n->in(2), I );
 408           // Stuff new AddP in the loop preheader
 409           register_new_node( add1, n_loop->_head->in(LoopNode::EntryControl) );
 410           Node *add2 = new (C, 4) AddPNode( n->in(1), add1, V );
 411           register_new_node( add2, n_ctrl );
 412           _igvn.hash_delete( n );
 413           _igvn.subsume_node( n, add2 );
 414           return add2;
 415         }
 416       }
 417     }
 418   }
 419 
 420   return NULL;
 421 }
 422 
 423 //------------------------------conditional_move-------------------------------
 424 // Attempt to replace a Phi with a conditional move.  We have some pretty
 425 // strict profitability requirements.  All Phis at the merge point must
 426 // be converted, so we can remove the control flow.  We need to limit the
 427 // number of c-moves to a small handful.  All code that was in the side-arms
 428 // of the CFG diamond is now speculatively executed.  This code has to be
 429 // "cheap enough".  We are pretty much limited to CFG diamonds that merge
 430 // 1 or 2 items with a total of 1 or 2 ops executed speculatively.
 431 Node *PhaseIdealLoop::conditional_move( Node *region ) {
 432 
 433   assert( region->is_Region(), "sanity check" );
 434   if( region->req() != 3 ) return NULL;
 435 
 436   // Check for CFG diamond
 437   Node *lp = region->in(1);
 438   Node *rp = region->in(2);
 439   if( !lp || !rp ) return NULL;
 440   Node *lp_c = lp->in(0);
 441   if( lp_c == NULL || lp_c != rp->in(0) || !lp_c->is_If() ) return NULL;
 442   IfNode *iff = lp_c->as_If();
 443 
 444   // Check for highly predictable branch.  No point in CMOV'ing if
 445   // we are going to predict accurately all the time.
 446   // %%% This hides patterns produced by utility methods like Math.min.
 447   if( iff->_prob < PROB_UNLIKELY_MAG(3) ||
 448       iff->_prob > PROB_LIKELY_MAG(3) )
 449     return NULL;
 450 
 451   // Check for ops pinned in an arm of the diamond.
 452   // Can't remove the control flow in this case
 453   if( lp->outcnt() > 1 ) return NULL;
 454   if( rp->outcnt() > 1 ) return NULL;
 455 
 456   // Check profitability
 457   int cost = 0;
 458   int phis = 0;
 459   for (DUIterator_Fast imax, i = region->fast_outs(imax); i < imax; i++) {
 460     Node *out = region->fast_out(i);
 461     if( !out->is_Phi() ) continue; // Ignore other control edges, etc
 462     phis++;
 463     PhiNode* phi = out->as_Phi();
 464     switch (phi->type()->basic_type()) {
 465     case T_LONG:
 466       cost++;                   // Probably encodes as 2 CMOV's
 467     case T_INT:                 // These all CMOV fine
 468     case T_FLOAT:
 469     case T_DOUBLE:
 470     case T_ADDRESS:             // (RawPtr)
 471       cost++;
 472       break;
 473     case T_NARROWOOP: // Fall through
 474     case T_OBJECT: {            // Base oops are OK, but not derived oops
 475       const TypeOopPtr *tp = phi->type()->make_ptr()->isa_oopptr();
 476       // Derived pointers are Bad (tm): what's the Base (for GC purposes) of a
 477       // CMOVE'd derived pointer?  It's a CMOVE'd derived base.  Thus
 478       // CMOVE'ing a derived pointer requires we also CMOVE the base.  If we
 479       // have a Phi for the base here that we convert to a CMOVE all is well
 480       // and good.  But if the base is dead, we'll not make a CMOVE.  Later
 481       // the allocator will have to produce a base by creating a CMOVE of the
 482       // relevant bases.  This puts the allocator in the business of
 483       // manufacturing expensive instructions, generally a bad plan.
 484       // Just Say No to Conditionally-Moved Derived Pointers.
 485       if( tp && tp->offset() != 0 )
 486         return NULL;
 487       cost++;
 488       break;
 489     }
 490     default:
 491       return NULL;              // In particular, can't do memory or I/O
 492     }
 493     // Add in cost any speculative ops
 494     for( uint j = 1; j < region->req(); j++ ) {
 495       Node *proj = region->in(j);
 496       Node *inp = phi->in(j);
 497       if (get_ctrl(inp) == proj) { // Found local op
 498         cost++;
 499         // Check for a chain of dependent ops; these will all become
 500         // speculative in a CMOV.
 501         for( uint k = 1; k < inp->req(); k++ )
 502           if (get_ctrl(inp->in(k)) == proj)
 503             return NULL;        // Too much speculative goo
 504       }
 505     }
 506     // See if the Phi is used by a Cmp or Narrow oop Decode/Encode.
 507     // This will likely Split-If, a higher-payoff operation.
 508     for (DUIterator_Fast kmax, k = phi->fast_outs(kmax); k < kmax; k++) {
 509       Node* use = phi->fast_out(k);
 510       if( use->is_Cmp() || use->is_DecodeN() || use->is_EncodeP() )
 511         return NULL;
 512     }
 513   }
 514   if( cost >= ConditionalMoveLimit ) return NULL; // Too much goo
 515   Node* bol = iff->in(1);
 516   assert( bol->Opcode() == Op_Bool, "" );
 517   int cmp_op = bol->in(1)->Opcode();
 518   // It is expensive to generate flags from a float compare.
 519   // Avoid duplicated float compare.
 520   if( phis > 1 && (cmp_op == Op_CmpF || cmp_op == Op_CmpD)) return NULL;
 521 
 522   // --------------
 523   // Now replace all Phis with CMOV's
 524   Node *cmov_ctrl = iff->in(0);
 525   uint flip = (lp->Opcode() == Op_IfTrue);
 526   while( 1 ) {
 527     PhiNode* phi = NULL;
 528     for (DUIterator_Fast imax, i = region->fast_outs(imax); i < imax; i++) {
 529       Node *out = region->fast_out(i);
 530       if (out->is_Phi()) {
 531         phi = out->as_Phi();
 532         break;
 533       }
 534     }
 535     if (phi == NULL)  break;
 536 #ifndef PRODUCT
 537     if( PrintOpto && VerifyLoopOptimizations ) tty->print_cr("CMOV");
 538 #endif
 539     // Move speculative ops
 540     for( uint j = 1; j < region->req(); j++ ) {
 541       Node *proj = region->in(j);
 542       Node *inp = phi->in(j);
 543       if (get_ctrl(inp) == proj) { // Found local op
 544 #ifndef PRODUCT
 545         if( PrintOpto && VerifyLoopOptimizations ) {
 546           tty->print("  speculate: ");
 547           inp->dump();
 548         }
 549 #endif
 550         set_ctrl(inp, cmov_ctrl);
 551       }
 552     }
 553     Node *cmov = CMoveNode::make( C, cmov_ctrl, iff->in(1), phi->in(1+flip), phi->in(2-flip), _igvn.type(phi) );
 554     register_new_node( cmov, cmov_ctrl );
 555     _igvn.hash_delete(phi);
 556     _igvn.subsume_node( phi, cmov );
 557 #ifndef PRODUCT
 558     if( VerifyLoopOptimizations ) verify();
 559 #endif
 560   }
 561 
 562   // The useless CFG diamond will fold up later; see the optimization in
 563   // RegionNode::Ideal.
 564   _igvn._worklist.push(region);
 565 
 566   return iff->in(1);
 567 }
 568 
 569 //------------------------------split_if_with_blocks_pre-----------------------
 570 // Do the real work in a non-recursive function.  Data nodes want to be
 571 // cloned in the pre-order so they can feed each other nicely.
 572 Node *PhaseIdealLoop::split_if_with_blocks_pre( Node *n ) {
 573   // Cloning these guys is unlikely to win
 574   int n_op = n->Opcode();
 575   if( n_op == Op_MergeMem ) return n;
 576   if( n->is_Proj() ) return n;
 577   // Do not clone-up CmpFXXX variations, as these are always
 578   // followed by a CmpI
 579   if( n->is_Cmp() ) return n;
 580   // Attempt to use a conditional move instead of a phi/branch
 581   if( ConditionalMoveLimit > 0 && n_op == Op_Region ) {
 582     Node *cmov = conditional_move( n );
 583     if( cmov ) return cmov;
 584   }
 585   if( n->is_CFG() || n->is_LoadStore() )
 586     return n;
 587   if( n_op == Op_Opaque1 ||     // Opaque nodes cannot be mod'd
 588       n_op == Op_Opaque2 ) {
 589     if( !C->major_progress() )   // If chance of no more loop opts...
 590       _igvn._worklist.push(n);  // maybe we'll remove them
 591     return n;
 592   }
 593 
 594   if( n->is_Con() ) return n;   // No cloning for Con nodes
 595 
 596   Node *n_ctrl = get_ctrl(n);
 597   if( !n_ctrl ) return n;       // Dead node
 598 
 599   // Attempt to remix address expressions for loop invariants
 600   Node *m = remix_address_expressions( n );
 601   if( m ) return m;
 602 
 603   // Determine if the Node has inputs from some local Phi.
 604   // Returns the block to clone thru.
 605   Node *n_blk = has_local_phi_input( n );
 606   if( !n_blk ) return n;
 607   // Do not clone the trip counter through on a CountedLoop
 608   // (messes up the canonical shape).
 609   if( n_blk->is_CountedLoop() && n->Opcode() == Op_AddI ) return n;
 610 
 611   // Check for having no control input; not pinned.  Allow
 612   // dominating control.
 613   if( n->in(0) ) {
 614     Node *dom = idom(n_blk);
 615     if( dom_lca( n->in(0), dom ) != n->in(0) )
 616       return n;
 617   }
 618   // Policy: when is it profitable.  You must get more wins than
 619   // policy before it is considered profitable.  Policy is usually 0,
 620   // so 1 win is considered profitable.  Big merges will require big
 621   // cloning, so get a larger policy.
 622   int policy = n_blk->req() >> 2;
 623 
 624   // If the loop is a candidate for range check elimination,
 625   // delay splitting through it's phi until a later loop optimization
 626   if (n_blk->is_CountedLoop()) {
 627     IdealLoopTree *lp = get_loop(n_blk);
 628     if (lp && lp->_rce_candidate) {
 629       return n;
 630     }
 631   }
 632 
 633   // Use same limit as split_if_with_blocks_post
 634   if( C->unique() > 35000 ) return n; // Method too big
 635 
 636   // Split 'n' through the merge point if it is profitable
 637   Node *phi = split_thru_phi( n, n_blk, policy );
 638   if( !phi ) return n;
 639 
 640   // Found a Phi to split thru!
 641   // Replace 'n' with the new phi
 642   _igvn.hash_delete(n);
 643   _igvn.subsume_node( n, phi );
 644   // Moved a load around the loop, 'en-registering' something.
 645   if( n_blk->Opcode() == Op_Loop && n->is_Load() &&
 646       !phi->in(LoopNode::LoopBackControl)->is_Load() )
 647     C->set_major_progress();
 648 
 649   return phi;
 650 }
 651 
 652 static bool merge_point_too_heavy(Compile* C, Node* region) {
 653   // Bail out if the region and its phis have too many users.
 654   int weight = 0;
 655   for (DUIterator_Fast imax, i = region->fast_outs(imax); i < imax; i++) {
 656     weight += region->fast_out(i)->outcnt();
 657   }
 658   int nodes_left = MaxNodeLimit - C->unique();
 659   if (weight * 8 > nodes_left) {
 660 #ifndef PRODUCT
 661     if (PrintOpto)
 662       tty->print_cr("*** Split-if bails out:  %d nodes, region weight %d", C->unique(), weight);
 663 #endif
 664     return true;
 665   } else {
 666     return false;
 667   }
 668 }
 669 
 670 #ifdef _LP64
 671 static bool merge_point_safe(Node* region) {
 672   // 4799512: Stop split_if_with_blocks from splitting a block with a ConvI2LNode
 673   // having a PhiNode input. This sidesteps the dangerous case where the split
 674   // ConvI2LNode may become TOP if the input Value() does not
 675   // overlap the ConvI2L range, leaving a node which may not dominate its
 676   // uses.
 677   // A better fix for this problem can be found in the BugTraq entry, but
 678   // expediency for Mantis demands this hack.
 679   for (DUIterator_Fast imax, i = region->fast_outs(imax); i < imax; i++) {
 680     Node* n = region->fast_out(i);
 681     if (n->is_Phi()) {
 682       for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++) {
 683         Node* m = n->fast_out(j);
 684         if (m->Opcode() == Op_ConvI2L) {
 685           return false;
 686         }
 687       }
 688     }
 689   }
 690   return true;
 691 }
 692 #endif
 693 
 694 
 695 //------------------------------place_near_use---------------------------------
 696 // Place some computation next to use but not inside inner loops.
 697 // For inner loop uses move it to the preheader area.
 698 Node *PhaseIdealLoop::place_near_use( Node *useblock ) const {
 699   IdealLoopTree *u_loop = get_loop( useblock );
 700   return (u_loop->_irreducible || u_loop->_child)
 701     ? useblock
 702     : u_loop->_head->in(LoopNode::EntryControl);
 703 }
 704 
 705 
 706 //------------------------------split_if_with_blocks_post----------------------
 707 // Do the real work in a non-recursive function.  CFG hackery wants to be
 708 // in the post-order, so it can dirty the I-DOM info and not use the dirtied
 709 // info.
 710 void PhaseIdealLoop::split_if_with_blocks_post( Node *n ) {
 711 
 712   // Cloning Cmp through Phi's involves the split-if transform.
 713   // FastLock is not used by an If
 714   if( n->is_Cmp() && !n->is_FastLock() ) {
 715     if( C->unique() > 35000 ) return; // Method too big
 716 
 717     // Do not do 'split-if' if irreducible loops are present.
 718     if( _has_irreducible_loops )
 719       return;
 720 
 721     Node *n_ctrl = get_ctrl(n);
 722     // Determine if the Node has inputs from some local Phi.
 723     // Returns the block to clone thru.
 724     Node *n_blk = has_local_phi_input( n );
 725     if( n_blk != n_ctrl ) return;
 726 
 727     if( merge_point_too_heavy(C, n_ctrl) )
 728       return;
 729 
 730     if( n->outcnt() != 1 ) return; // Multiple bool's from 1 compare?
 731     Node *bol = n->unique_out();
 732     assert( bol->is_Bool(), "expect a bool here" );
 733     if( bol->outcnt() != 1 ) return;// Multiple branches from 1 compare?
 734     Node *iff = bol->unique_out();
 735 
 736     // Check some safety conditions
 737     if( iff->is_If() ) {        // Classic split-if?
 738       if( iff->in(0) != n_ctrl ) return; // Compare must be in same blk as if
 739     } else if (iff->is_CMove()) { // Trying to split-up a CMOVE
 740       if( get_ctrl(iff->in(2)) == n_ctrl ||
 741           get_ctrl(iff->in(3)) == n_ctrl )
 742         return;                 // Inputs not yet split-up
 743       if ( get_loop(n_ctrl) != get_loop(get_ctrl(iff)) ) {
 744         return;                 // Loop-invar test gates loop-varying CMOVE
 745       }
 746     } else {
 747       return;  // some other kind of node, such as an Allocate
 748     }
 749 
 750     // Do not do 'split-if' if some paths are dead.  First do dead code
 751     // elimination and then see if its still profitable.
 752     for( uint i = 1; i < n_ctrl->req(); i++ )
 753       if( n_ctrl->in(i) == C->top() )
 754         return;
 755 
 756     // When is split-if profitable?  Every 'win' on means some control flow
 757     // goes dead, so it's almost always a win.
 758     int policy = 0;
 759     // If trying to do a 'Split-If' at the loop head, it is only
 760     // profitable if the cmp folds up on BOTH paths.  Otherwise we
 761     // risk peeling a loop forever.
 762 
 763     // CNC - Disabled for now.  Requires careful handling of loop
 764     // body selection for the cloned code.  Also, make sure we check
 765     // for any input path not being in the same loop as n_ctrl.  For
 766     // irreducible loops we cannot check for 'n_ctrl->is_Loop()'
 767     // because the alternative loop entry points won't be converted
 768     // into LoopNodes.
 769     IdealLoopTree *n_loop = get_loop(n_ctrl);
 770     for( uint j = 1; j < n_ctrl->req(); j++ )
 771       if( get_loop(n_ctrl->in(j)) != n_loop )
 772         return;
 773 
 774 #ifdef _LP64
 775     // Check for safety of the merge point.
 776     if( !merge_point_safe(n_ctrl) ) {
 777       return;
 778     }
 779 #endif
 780 
 781     // Split compare 'n' through the merge point if it is profitable
 782     Node *phi = split_thru_phi( n, n_ctrl, policy );
 783     if( !phi ) return;
 784 
 785     // Found a Phi to split thru!
 786     // Replace 'n' with the new phi
 787     _igvn.hash_delete(n);
 788     _igvn.subsume_node( n, phi );
 789 
 790     // Now split the bool up thru the phi
 791     Node *bolphi = split_thru_phi( bol, n_ctrl, -1 );
 792     _igvn.hash_delete(bol);
 793     _igvn.subsume_node( bol, bolphi );
 794     assert( iff->in(1) == bolphi, "" );
 795     if( bolphi->Value(&_igvn)->singleton() )
 796       return;
 797 
 798     // Conditional-move?  Must split up now
 799     if( !iff->is_If() ) {
 800       Node *cmovphi = split_thru_phi( iff, n_ctrl, -1 );
 801       _igvn.hash_delete(iff);
 802       _igvn.subsume_node( iff, cmovphi );
 803       return;
 804     }
 805 
 806     // Now split the IF
 807     do_split_if( iff );
 808     return;
 809   }
 810 
 811   // Check for an IF ready to split; one that has its
 812   // condition codes input coming from a Phi at the block start.
 813   int n_op = n->Opcode();
 814 
 815   // Check for an IF being dominated by another IF same test
 816   if( n_op == Op_If ) {
 817     Node *bol = n->in(1);
 818     uint max = bol->outcnt();
 819     // Check for same test used more than once?
 820     if( n_op == Op_If && max > 1 && bol->is_Bool() ) {
 821       // Search up IDOMs to see if this IF is dominated.
 822       Node *cutoff = get_ctrl(bol);
 823 
 824       // Now search up IDOMs till cutoff, looking for a dominating test
 825       Node *prevdom = n;
 826       Node *dom = idom(prevdom);
 827       while( dom != cutoff ) {
 828         if( dom->req() > 1 && dom->in(1) == bol && prevdom->in(0) == dom ) {
 829           // Replace the dominated test with an obvious true or false.
 830           // Place it on the IGVN worklist for later cleanup.
 831           C->set_major_progress();
 832           dominated_by( prevdom, n );
 833 #ifndef PRODUCT
 834           if( VerifyLoopOptimizations ) verify();
 835 #endif
 836           return;
 837         }
 838         prevdom = dom;
 839         dom = idom(prevdom);
 840       }
 841     }
 842   }
 843 
 844   // See if a shared loop-varying computation has no loop-varying uses.
 845   // Happens if something is only used for JVM state in uncommon trap exits,
 846   // like various versions of induction variable+offset.  Clone the
 847   // computation per usage to allow it to sink out of the loop.
 848   if (has_ctrl(n) && !n->in(0)) {// n not dead and has no control edge (can float about)
 849     Node *n_ctrl = get_ctrl(n);
 850     IdealLoopTree *n_loop = get_loop(n_ctrl);
 851     if( n_loop != _ltree_root ) {
 852       DUIterator_Fast imax, i = n->fast_outs(imax);
 853       for (; i < imax; i++) {
 854         Node* u = n->fast_out(i);
 855         if( !has_ctrl(u) )     break; // Found control user
 856         IdealLoopTree *u_loop = get_loop(get_ctrl(u));
 857         if( u_loop == n_loop ) break; // Found loop-varying use
 858         if( n_loop->is_member( u_loop ) ) break; // Found use in inner loop
 859         if( u->Opcode() == Op_Opaque1 ) break; // Found loop limit, bugfix for 4677003
 860       }
 861       bool did_break = (i < imax);  // Did we break out of the previous loop?
 862       if (!did_break && n->outcnt() > 1) { // All uses in outer loops!
 863         Node *late_load_ctrl;
 864         if (n->is_Load()) {
 865           // If n is a load, get and save the result from get_late_ctrl(),
 866           // to be later used in calculating the control for n's clones.
 867           clear_dom_lca_tags();
 868           late_load_ctrl = get_late_ctrl(n, n_ctrl);
 869         }
 870         // If n is a load, and the late control is the same as the current
 871         // control, then the cloning of n is a pointless exercise, because
 872         // GVN will ensure that we end up where we started.
 873         if (!n->is_Load() || late_load_ctrl != n_ctrl) {
 874           for (DUIterator_Last jmin, j = n->last_outs(jmin); j >= jmin; ) {
 875             Node *u = n->last_out(j); // Clone private computation per use
 876             _igvn.hash_delete(u);
 877             _igvn._worklist.push(u);
 878             Node *x = n->clone(); // Clone computation
 879             Node *x_ctrl = NULL;
 880             if( u->is_Phi() ) {
 881               // Replace all uses of normal nodes.  Replace Phi uses
 882               // individually, so the seperate Nodes can sink down
 883               // different paths.
 884               uint k = 1;
 885               while( u->in(k) != n ) k++;
 886               u->set_req( k, x );
 887               // x goes next to Phi input path
 888               x_ctrl = u->in(0)->in(k);
 889               --j;
 890             } else {              // Normal use
 891               // Replace all uses
 892               for( uint k = 0; k < u->req(); k++ ) {
 893                 if( u->in(k) == n ) {
 894                   u->set_req( k, x );
 895                   --j;
 896                 }
 897               }
 898               x_ctrl = get_ctrl(u);
 899             }
 900 
 901             // Find control for 'x' next to use but not inside inner loops.
 902             // For inner loop uses get the preheader area.
 903             x_ctrl = place_near_use(x_ctrl);
 904 
 905             if (n->is_Load()) {
 906               // For loads, add a control edge to a CFG node outside of the loop
 907               // to force them to not combine and return back inside the loop
 908               // during GVN optimization (4641526).
 909               //
 910               // Because we are setting the actual control input, factor in
 911               // the result from get_late_ctrl() so we respect any
 912               // anti-dependences. (6233005).
 913               x_ctrl = dom_lca(late_load_ctrl, x_ctrl);
 914 
 915               // Don't allow the control input to be a CFG splitting node.
 916               // Such nodes should only have ProjNodes as outs, e.g. IfNode
 917               // should only have IfTrueNode and IfFalseNode (4985384).
 918               x_ctrl = find_non_split_ctrl(x_ctrl);
 919               assert(dom_depth(n_ctrl) <= dom_depth(x_ctrl), "n is later than its clone");
 920 
 921               x->set_req(0, x_ctrl);
 922             }
 923             register_new_node(x, x_ctrl);
 924 
 925             // Some institutional knowledge is needed here: 'x' is
 926             // yanked because if the optimizer runs GVN on it all the
 927             // cloned x's will common up and undo this optimization and
 928             // be forced back in the loop.  This is annoying because it
 929             // makes +VerifyOpto report false-positives on progress.  I
 930             // tried setting control edges on the x's to force them to
 931             // not combine, but the matching gets worried when it tries
 932             // to fold a StoreP and an AddP together (as part of an
 933             // address expression) and the AddP and StoreP have
 934             // different controls.
 935             if( !x->is_Load() && !x->is_DecodeN() ) _igvn._worklist.yank(x);
 936           }
 937           _igvn.remove_dead_node(n);
 938         }
 939       }
 940     }
 941   }
 942 
 943   // Check for Opaque2's who's loop has disappeared - who's input is in the
 944   // same loop nest as their output.  Remove 'em, they are no longer useful.
 945   if( n_op == Op_Opaque2 &&
 946       n->in(1) != NULL &&
 947       get_loop(get_ctrl(n)) == get_loop(get_ctrl(n->in(1))) ) {
 948     _igvn.add_users_to_worklist(n);
 949     _igvn.hash_delete(n);
 950     _igvn.subsume_node( n, n->in(1) );
 951   }
 952 }
 953 
 954 //------------------------------split_if_with_blocks---------------------------
 955 // Check for aggressive application of 'split-if' optimization,
 956 // using basic block level info.
 957 void PhaseIdealLoop::split_if_with_blocks( VectorSet &visited, Node_Stack &nstack ) {
 958   Node *n = C->root();
 959   visited.set(n->_idx); // first, mark node as visited
 960   // Do pre-visit work for root
 961   n = split_if_with_blocks_pre( n );
 962   uint cnt = n->outcnt();
 963   uint i   = 0;
 964   while (true) {
 965     // Visit all children
 966     if (i < cnt) {
 967       Node* use = n->raw_out(i);
 968       ++i;
 969       if (use->outcnt() != 0 && !visited.test_set(use->_idx)) {
 970         // Now do pre-visit work for this use
 971         use = split_if_with_blocks_pre( use );
 972         nstack.push(n, i); // Save parent and next use's index.
 973         n   = use;         // Process all children of current use.
 974         cnt = use->outcnt();
 975         i   = 0;
 976       }
 977     }
 978     else {
 979       // All of n's children have been processed, complete post-processing.
 980       if (cnt != 0 && !n->is_Con()) {
 981         assert(has_node(n), "no dead nodes");
 982         split_if_with_blocks_post( n );
 983       }
 984       if (nstack.is_empty()) {
 985         // Finished all nodes on stack.
 986         break;
 987       }
 988       // Get saved parent node and next use's index. Visit the rest of uses.
 989       n   = nstack.node();
 990       cnt = n->outcnt();
 991       i   = nstack.index();
 992       nstack.pop();
 993     }
 994   }
 995 }
 996 
 997 
 998 //=============================================================================
 999 //
1000 //                   C L O N E   A   L O O P   B O D Y
1001 //
1002 
1003 //------------------------------clone_iff--------------------------------------
1004 // Passed in a Phi merging (recursively) some nearly equivalent Bool/Cmps.
1005 // "Nearly" because all Nodes have been cloned from the original in the loop,
1006 // but the fall-in edges to the Cmp are different.  Clone bool/Cmp pairs
1007 // through the Phi recursively, and return a Bool.
1008 BoolNode *PhaseIdealLoop::clone_iff( PhiNode *phi, IdealLoopTree *loop ) {
1009 
1010   // Convert this Phi into a Phi merging Bools
1011   uint i;
1012   for( i = 1; i < phi->req(); i++ ) {
1013     Node *b = phi->in(i);
1014     if( b->is_Phi() ) {
1015       _igvn.hash_delete(phi);
1016       _igvn._worklist.push(phi);
1017       phi->set_req(i, clone_iff( b->as_Phi(), loop ));
1018     } else {
1019       assert( b->is_Bool(), "" );
1020     }
1021   }
1022 
1023   Node *sample_bool = phi->in(1);
1024   Node *sample_cmp  = sample_bool->in(1);
1025 
1026   // Make Phis to merge the Cmp's inputs.
1027   int size = phi->in(0)->req();
1028   PhiNode *phi1 = new (C, size) PhiNode( phi->in(0), Type::TOP );
1029   PhiNode *phi2 = new (C, size) PhiNode( phi->in(0), Type::TOP );
1030   for( i = 1; i < phi->req(); i++ ) {
1031     Node *n1 = phi->in(i)->in(1)->in(1);
1032     Node *n2 = phi->in(i)->in(1)->in(2);
1033     phi1->set_req( i, n1 );
1034     phi2->set_req( i, n2 );
1035     phi1->set_type( phi1->type()->meet(n1->bottom_type()) );
1036     phi2->set_type( phi2->type()->meet(n2->bottom_type()) );
1037   }
1038   // See if these Phis have been made before.
1039   // Register with optimizer
1040   Node *hit1 = _igvn.hash_find_insert(phi1);
1041   if( hit1 ) {                  // Hit, toss just made Phi
1042     _igvn.remove_dead_node(phi1); // Remove new phi
1043     assert( hit1->is_Phi(), "" );
1044     phi1 = (PhiNode*)hit1;      // Use existing phi
1045   } else {                      // Miss
1046     _igvn.register_new_node_with_optimizer(phi1);
1047   }
1048   Node *hit2 = _igvn.hash_find_insert(phi2);
1049   if( hit2 ) {                  // Hit, toss just made Phi
1050     _igvn.remove_dead_node(phi2); // Remove new phi
1051     assert( hit2->is_Phi(), "" );
1052     phi2 = (PhiNode*)hit2;      // Use existing phi
1053   } else {                      // Miss
1054     _igvn.register_new_node_with_optimizer(phi2);
1055   }
1056   // Register Phis with loop/block info
1057   set_ctrl(phi1, phi->in(0));
1058   set_ctrl(phi2, phi->in(0));
1059   // Make a new Cmp
1060   Node *cmp = sample_cmp->clone();
1061   cmp->set_req( 1, phi1 );
1062   cmp->set_req( 2, phi2 );
1063   _igvn.register_new_node_with_optimizer(cmp);
1064   set_ctrl(cmp, phi->in(0));
1065 
1066   // Make a new Bool
1067   Node *b = sample_bool->clone();
1068   b->set_req(1,cmp);
1069   _igvn.register_new_node_with_optimizer(b);
1070   set_ctrl(b, phi->in(0));
1071 
1072   assert( b->is_Bool(), "" );
1073   return (BoolNode*)b;
1074 }
1075 
1076 //------------------------------clone_bool-------------------------------------
1077 // Passed in a Phi merging (recursively) some nearly equivalent Bool/Cmps.
1078 // "Nearly" because all Nodes have been cloned from the original in the loop,
1079 // but the fall-in edges to the Cmp are different.  Clone bool/Cmp pairs
1080 // through the Phi recursively, and return a Bool.
1081 CmpNode *PhaseIdealLoop::clone_bool( PhiNode *phi, IdealLoopTree *loop ) {
1082   uint i;
1083   // Convert this Phi into a Phi merging Bools
1084   for( i = 1; i < phi->req(); i++ ) {
1085     Node *b = phi->in(i);
1086     if( b->is_Phi() ) {
1087       _igvn.hash_delete(phi);
1088       _igvn._worklist.push(phi);
1089       phi->set_req(i, clone_bool( b->as_Phi(), loop ));
1090     } else {
1091       assert( b->is_Cmp() || b->is_top(), "inputs are all Cmp or TOP" );
1092     }
1093   }
1094 
1095   Node *sample_cmp = phi->in(1);
1096 
1097   // Make Phis to merge the Cmp's inputs.
1098   int size = phi->in(0)->req();
1099   PhiNode *phi1 = new (C, size) PhiNode( phi->in(0), Type::TOP );
1100   PhiNode *phi2 = new (C, size) PhiNode( phi->in(0), Type::TOP );
1101   for( uint j = 1; j < phi->req(); j++ ) {
1102     Node *cmp_top = phi->in(j); // Inputs are all Cmp or TOP
1103     Node *n1, *n2;
1104     if( cmp_top->is_Cmp() ) {
1105       n1 = cmp_top->in(1);
1106       n2 = cmp_top->in(2);
1107     } else {
1108       n1 = n2 = cmp_top;
1109     }
1110     phi1->set_req( j, n1 );
1111     phi2->set_req( j, n2 );
1112     phi1->set_type( phi1->type()->meet(n1->bottom_type()) );
1113     phi2->set_type( phi2->type()->meet(n2->bottom_type()) );
1114   }
1115 
1116   // See if these Phis have been made before.
1117   // Register with optimizer
1118   Node *hit1 = _igvn.hash_find_insert(phi1);
1119   if( hit1 ) {                  // Hit, toss just made Phi
1120     _igvn.remove_dead_node(phi1); // Remove new phi
1121     assert( hit1->is_Phi(), "" );
1122     phi1 = (PhiNode*)hit1;      // Use existing phi
1123   } else {                      // Miss
1124     _igvn.register_new_node_with_optimizer(phi1);
1125   }
1126   Node *hit2 = _igvn.hash_find_insert(phi2);
1127   if( hit2 ) {                  // Hit, toss just made Phi
1128     _igvn.remove_dead_node(phi2); // Remove new phi
1129     assert( hit2->is_Phi(), "" );
1130     phi2 = (PhiNode*)hit2;      // Use existing phi
1131   } else {                      // Miss
1132     _igvn.register_new_node_with_optimizer(phi2);
1133   }
1134   // Register Phis with loop/block info
1135   set_ctrl(phi1, phi->in(0));
1136   set_ctrl(phi2, phi->in(0));
1137   // Make a new Cmp
1138   Node *cmp = sample_cmp->clone();
1139   cmp->set_req( 1, phi1 );
1140   cmp->set_req( 2, phi2 );
1141   _igvn.register_new_node_with_optimizer(cmp);
1142   set_ctrl(cmp, phi->in(0));
1143 
1144   assert( cmp->is_Cmp(), "" );
1145   return (CmpNode*)cmp;
1146 }
1147 
1148 //------------------------------sink_use---------------------------------------
1149 // If 'use' was in the loop-exit block, it now needs to be sunk
1150 // below the post-loop merge point.
1151 void PhaseIdealLoop::sink_use( Node *use, Node *post_loop ) {
1152   if (!use->is_CFG() && get_ctrl(use) == post_loop->in(2)) {
1153     set_ctrl(use, post_loop);
1154     for (DUIterator j = use->outs(); use->has_out(j); j++)
1155       sink_use(use->out(j), post_loop);
1156   }
1157 }
1158 
1159 //------------------------------clone_loop-------------------------------------
1160 //
1161 //                   C L O N E   A   L O O P   B O D Y
1162 //
1163 // This is the basic building block of the loop optimizations.  It clones an
1164 // entire loop body.  It makes an old_new loop body mapping; with this mapping
1165 // you can find the new-loop equivalent to an old-loop node.  All new-loop
1166 // nodes are exactly equal to their old-loop counterparts, all edges are the
1167 // same.  All exits from the old-loop now have a RegionNode that merges the
1168 // equivalent new-loop path.  This is true even for the normal "loop-exit"
1169 // condition.  All uses of loop-invariant old-loop values now come from (one
1170 // or more) Phis that merge their new-loop equivalents.
1171 //
1172 // This operation leaves the graph in an illegal state: there are two valid
1173 // control edges coming from the loop pre-header to both loop bodies.  I'll
1174 // definitely have to hack the graph after running this transform.
1175 //
1176 // From this building block I will further edit edges to perform loop peeling
1177 // or loop unrolling or iteration splitting (Range-Check-Elimination), etc.
1178 //
1179 // Parameter side_by_size_idom:
1180 //   When side_by_size_idom is NULL, the dominator tree is constructed for
1181 //      the clone loop to dominate the original.  Used in construction of
1182 //      pre-main-post loop sequence.
1183 //   When nonnull, the clone and original are side-by-side, both are
1184 //      dominated by the side_by_side_idom node.  Used in construction of
1185 //      unswitched loops.
1186 void PhaseIdealLoop::clone_loop( IdealLoopTree *loop, Node_List &old_new, int dd,
1187                                  Node* side_by_side_idom) {
1188 
1189   // Step 1: Clone the loop body.  Make the old->new mapping.
1190   uint i;
1191   for( i = 0; i < loop->_body.size(); i++ ) {
1192     Node *old = loop->_body.at(i);
1193     Node *nnn = old->clone();
1194     old_new.map( old->_idx, nnn );
1195     _igvn.register_new_node_with_optimizer(nnn);
1196   }
1197 
1198 
1199   // Step 2: Fix the edges in the new body.  If the old input is outside the
1200   // loop use it.  If the old input is INside the loop, use the corresponding
1201   // new node instead.
1202   for( i = 0; i < loop->_body.size(); i++ ) {
1203     Node *old = loop->_body.at(i);
1204     Node *nnn = old_new[old->_idx];
1205     // Fix CFG/Loop controlling the new node
1206     if (has_ctrl(old)) {
1207       set_ctrl(nnn, old_new[get_ctrl(old)->_idx]);
1208     } else {
1209       set_loop(nnn, loop->_parent);
1210       if (old->outcnt() > 0) {
1211         set_idom( nnn, old_new[idom(old)->_idx], dd );
1212       }
1213     }
1214     // Correct edges to the new node
1215     for( uint j = 0; j < nnn->req(); j++ ) {
1216         Node *n = nnn->in(j);
1217         if( n ) {
1218           IdealLoopTree *old_in_loop = get_loop( has_ctrl(n) ? get_ctrl(n) : n );
1219           if( loop->is_member( old_in_loop ) )
1220             nnn->set_req(j, old_new[n->_idx]);
1221         }
1222     }
1223     _igvn.hash_find_insert(nnn);
1224   }
1225   Node *newhead = old_new[loop->_head->_idx];
1226   set_idom(newhead, newhead->in(LoopNode::EntryControl), dd);
1227 
1228 
1229   // Step 3: Now fix control uses.  Loop varying control uses have already
1230   // been fixed up (as part of all input edges in Step 2).  Loop invariant
1231   // control uses must be either an IfFalse or an IfTrue.  Make a merge
1232   // point to merge the old and new IfFalse/IfTrue nodes; make the use
1233   // refer to this.
1234   ResourceArea *area = Thread::current()->resource_area();
1235   Node_List worklist(area);
1236   uint new_counter = C->unique();
1237   for( i = 0; i < loop->_body.size(); i++ ) {
1238     Node* old = loop->_body.at(i);
1239     if( !old->is_CFG() ) continue;
1240     Node* nnn = old_new[old->_idx];
1241 
1242     // Copy uses to a worklist, so I can munge the def-use info
1243     // with impunity.
1244     for (DUIterator_Fast jmax, j = old->fast_outs(jmax); j < jmax; j++)
1245       worklist.push(old->fast_out(j));
1246 
1247     while( worklist.size() ) {  // Visit all uses
1248       Node *use = worklist.pop();
1249       if (!has_node(use))  continue; // Ignore dead nodes
1250       IdealLoopTree *use_loop = get_loop( has_ctrl(use) ? get_ctrl(use) : use );
1251       if( !loop->is_member( use_loop ) && use->is_CFG() ) {
1252         // Both OLD and USE are CFG nodes here.
1253         assert( use->is_Proj(), "" );
1254 
1255         // Clone the loop exit control projection
1256         Node *newuse = use->clone();
1257         newuse->set_req(0,nnn);
1258         _igvn.register_new_node_with_optimizer(newuse);
1259         set_loop(newuse, use_loop);
1260         set_idom(newuse, nnn, dom_depth(nnn) + 1 );
1261 
1262         // We need a Region to merge the exit from the peeled body and the
1263         // exit from the old loop body.
1264         RegionNode *r = new (C, 3) RegionNode(3);
1265         // Map the old use to the new merge point
1266         old_new.map( use->_idx, r );
1267         uint dd_r = MIN2(dom_depth(newuse),dom_depth(use));
1268         assert( dd_r >= dom_depth(dom_lca(newuse,use)), "" );
1269 
1270         // The original user of 'use' uses 'r' instead.
1271         for (DUIterator_Last lmin, l = use->last_outs(lmin); l >= lmin;) {
1272           Node* useuse = use->last_out(l);
1273           _igvn.hash_delete(useuse);
1274           _igvn._worklist.push(useuse);
1275           uint uses_found = 0;
1276           if( useuse->in(0) == use ) {
1277             useuse->set_req(0, r);
1278             uses_found++;
1279             if( useuse->is_CFG() ) {
1280               assert( dom_depth(useuse) > dd_r, "" );
1281               set_idom(useuse, r, dom_depth(useuse));
1282             }
1283           }
1284           for( uint k = 1; k < useuse->req(); k++ ) {
1285             if( useuse->in(k) == use ) {
1286               useuse->set_req(k, r);
1287               uses_found++;
1288             }
1289           }
1290           l -= uses_found;    // we deleted 1 or more copies of this edge
1291         }
1292 
1293         // Now finish up 'r'
1294         r->set_req( 1, newuse );
1295         r->set_req( 2,    use );
1296         _igvn.register_new_node_with_optimizer(r);
1297         set_loop(r, use_loop);
1298         set_idom(r, !side_by_side_idom ? newuse->in(0) : side_by_side_idom, dd_r);
1299       } // End of if a loop-exit test
1300     }
1301   }
1302 
1303   // Step 4: If loop-invariant use is not control, it must be dominated by a
1304   // loop exit IfFalse/IfTrue.  Find "proper" loop exit.  Make a Region
1305   // there if needed.  Make a Phi there merging old and new used values.
1306   Node_List *split_if_set = NULL;
1307   Node_List *split_bool_set = NULL;
1308   Node_List *split_cex_set = NULL;
1309   for( i = 0; i < loop->_body.size(); i++ ) {
1310     Node* old = loop->_body.at(i);
1311     Node* nnn = old_new[old->_idx];
1312     // Copy uses to a worklist, so I can munge the def-use info
1313     // with impunity.
1314     for (DUIterator_Fast jmax, j = old->fast_outs(jmax); j < jmax; j++)
1315       worklist.push(old->fast_out(j));
1316 
1317     while( worklist.size() ) {
1318       Node *use = worklist.pop();
1319       if (!has_node(use))  continue; // Ignore dead nodes
1320       if (use->in(0) == C->top())  continue;
1321       IdealLoopTree *use_loop = get_loop( has_ctrl(use) ? get_ctrl(use) : use );
1322       // Check for data-use outside of loop - at least one of OLD or USE
1323       // must not be a CFG node.
1324       if( !loop->is_member( use_loop ) && (!old->is_CFG() || !use->is_CFG())) {
1325 
1326         // If the Data use is an IF, that means we have an IF outside of the
1327         // loop that is switching on a condition that is set inside of the
1328         // loop.  Happens if people set a loop-exit flag; then test the flag
1329         // in the loop to break the loop, then test is again outside of the
1330         // loop to determine which way the loop exited.
1331         if( use->is_If() || use->is_CMove() ) {
1332           // Since this code is highly unlikely, we lazily build the worklist
1333           // of such Nodes to go split.
1334           if( !split_if_set )
1335             split_if_set = new Node_List(area);
1336           split_if_set->push(use);
1337         }
1338         if( use->is_Bool() ) {
1339           if( !split_bool_set )
1340             split_bool_set = new Node_List(area);
1341           split_bool_set->push(use);
1342         }
1343         if( use->Opcode() == Op_CreateEx ) {
1344           if( !split_cex_set )
1345             split_cex_set = new Node_List(area);
1346           split_cex_set->push(use);
1347         }
1348 
1349 
1350         // Get "block" use is in
1351         uint idx = 0;
1352         while( use->in(idx) != old ) idx++;
1353         Node *prev = use->is_CFG() ? use : get_ctrl(use);
1354         assert( !loop->is_member( get_loop( prev ) ), "" );
1355         Node *cfg = prev->_idx >= new_counter
1356           ? prev->in(2)
1357           : idom(prev);
1358         if( use->is_Phi() )     // Phi use is in prior block
1359           cfg = prev->in(idx);  // NOT in block of Phi itself
1360         if (cfg->is_top()) {    // Use is dead?
1361           _igvn.hash_delete(use);
1362           _igvn._worklist.push(use);
1363           use->set_req(idx, C->top());
1364           continue;
1365         }
1366 
1367         while( !loop->is_member( get_loop( cfg ) ) ) {
1368           prev = cfg;
1369           cfg = cfg->_idx >= new_counter ? cfg->in(2) : idom(cfg);
1370         }
1371         // If the use occurs after merging several exits from the loop, then
1372         // old value must have dominated all those exits.  Since the same old
1373         // value was used on all those exits we did not need a Phi at this
1374         // merge point.  NOW we do need a Phi here.  Each loop exit value
1375         // is now merged with the peeled body exit; each exit gets its own
1376         // private Phi and those Phis need to be merged here.
1377         Node *phi;
1378         if( prev->is_Region() ) {
1379           if( idx == 0 ) {      // Updating control edge?
1380             phi = prev;         // Just use existing control
1381           } else {              // Else need a new Phi
1382             phi = PhiNode::make( prev, old );
1383             // Now recursively fix up the new uses of old!
1384             for( uint i = 1; i < prev->req(); i++ ) {
1385               worklist.push(phi); // Onto worklist once for each 'old' input
1386             }
1387           }
1388         } else {
1389           // Get new RegionNode merging old and new loop exits
1390           prev = old_new[prev->_idx];
1391           assert( prev, "just made this in step 7" );
1392           if( idx == 0 ) {      // Updating control edge?
1393             phi = prev;         // Just use existing control
1394           } else {              // Else need a new Phi
1395             // Make a new Phi merging data values properly
1396             phi = PhiNode::make( prev, old );
1397             phi->set_req( 1, nnn );
1398           }
1399         }
1400         // If inserting a new Phi, check for prior hits
1401         if( idx != 0 ) {
1402           Node *hit = _igvn.hash_find_insert(phi);
1403           if( hit == NULL ) {
1404            _igvn.register_new_node_with_optimizer(phi); // Register new phi
1405           } else {                                      // or
1406             // Remove the new phi from the graph and use the hit
1407             _igvn.remove_dead_node(phi);
1408             phi = hit;                                  // Use existing phi
1409           }
1410           set_ctrl(phi, prev);
1411         }
1412         // Make 'use' use the Phi instead of the old loop body exit value
1413         _igvn.hash_delete(use);
1414         _igvn._worklist.push(use);
1415         use->set_req(idx, phi);
1416         if( use->_idx >= new_counter ) { // If updating new phis
1417           // Not needed for correctness, but prevents a weak assert
1418           // in AddPNode from tripping (when we end up with different
1419           // base & derived Phis that will become the same after
1420           // IGVN does CSE).
1421           Node *hit = _igvn.hash_find_insert(use);
1422           if( hit )             // Go ahead and re-hash for hits.
1423             _igvn.subsume_node( use, hit );
1424         }
1425 
1426         // If 'use' was in the loop-exit block, it now needs to be sunk
1427         // below the post-loop merge point.
1428         sink_use( use, prev );
1429       }
1430     }
1431   }
1432 
1433   // Check for IFs that need splitting/cloning.  Happens if an IF outside of
1434   // the loop uses a condition set in the loop.  The original IF probably
1435   // takes control from one or more OLD Regions (which in turn get from NEW
1436   // Regions).  In any case, there will be a set of Phis for each merge point
1437   // from the IF up to where the original BOOL def exists the loop.
1438   if( split_if_set ) {
1439     while( split_if_set->size() ) {
1440       Node *iff = split_if_set->pop();
1441       if( iff->in(1)->is_Phi() ) {
1442         BoolNode *b = clone_iff( iff->in(1)->as_Phi(), loop );
1443         _igvn.hash_delete(iff);
1444         _igvn._worklist.push(iff);
1445         iff->set_req(1, b);
1446       }
1447     }
1448   }
1449   if( split_bool_set ) {
1450     while( split_bool_set->size() ) {
1451       Node *b = split_bool_set->pop();
1452       Node *phi = b->in(1);
1453       assert( phi->is_Phi(), "" );
1454       CmpNode *cmp = clone_bool( (PhiNode*)phi, loop );
1455       _igvn.hash_delete(b);
1456       _igvn._worklist.push(b);
1457       b->set_req(1, cmp);
1458     }
1459   }
1460   if( split_cex_set ) {
1461     while( split_cex_set->size() ) {
1462       Node *b = split_cex_set->pop();
1463       assert( b->in(0)->is_Region(), "" );
1464       assert( b->in(1)->is_Phi(), "" );
1465       assert( b->in(0)->in(0) == b->in(1)->in(0), "" );
1466       split_up( b, b->in(0), NULL );
1467     }
1468   }
1469 
1470 }
1471 
1472 
1473 //---------------------- stride_of_possible_iv -------------------------------------
1474 // Looks for an iff/bool/comp with one operand of the compare
1475 // being a cycle involving an add and a phi,
1476 // with an optional truncation (left-shift followed by a right-shift)
1477 // of the add. Returns zero if not an iv.
1478 int PhaseIdealLoop::stride_of_possible_iv(Node* iff) {
1479   Node* trunc1 = NULL;
1480   Node* trunc2 = NULL;
1481   const TypeInt* ttype = NULL;
1482   if (!iff->is_If() || iff->in(1) == NULL || !iff->in(1)->is_Bool()) {
1483     return 0;
1484   }
1485   BoolNode* bl = iff->in(1)->as_Bool();
1486   Node* cmp = bl->in(1);
1487   if (!cmp || cmp->Opcode() != Op_CmpI && cmp->Opcode() != Op_CmpU) {
1488     return 0;
1489   }
1490   // Must have an invariant operand
1491   if (is_member(get_loop(iff), get_ctrl(cmp->in(2)))) {
1492     return 0;
1493   }
1494   Node* add2 = NULL;
1495   Node* cmp1 = cmp->in(1);
1496   if (cmp1->is_Phi()) {
1497     // (If (Bool (CmpX phi:(Phi ...(Optional-trunc(AddI phi add2))) )))
1498     Node* phi = cmp1;
1499     for (uint i = 1; i < phi->req(); i++) {
1500       Node* in = phi->in(i);
1501       Node* add = CountedLoopNode::match_incr_with_optional_truncation(in,
1502                                 &trunc1, &trunc2, &ttype);
1503       if (add && add->in(1) == phi) {
1504         add2 = add->in(2);
1505         break;
1506       }
1507     }
1508   } else {
1509     // (If (Bool (CmpX addtrunc:(Optional-trunc((AddI (Phi ...addtrunc...) add2)) )))
1510     Node* addtrunc = cmp1;
1511     Node* add = CountedLoopNode::match_incr_with_optional_truncation(addtrunc,
1512                                 &trunc1, &trunc2, &ttype);
1513     if (add && add->in(1)->is_Phi()) {
1514       Node* phi = add->in(1);
1515       for (uint i = 1; i < phi->req(); i++) {
1516         if (phi->in(i) == addtrunc) {
1517           add2 = add->in(2);
1518           break;
1519         }
1520       }
1521     }
1522   }
1523   if (add2 != NULL) {
1524     const TypeInt* add2t = _igvn.type(add2)->is_int();
1525     if (add2t->is_con()) {
1526       return add2t->get_con();
1527     }
1528   }
1529   return 0;
1530 }
1531 
1532 
1533 //---------------------- stay_in_loop -------------------------------------
1534 // Return the (unique) control output node that's in the loop (if it exists.)
1535 Node* PhaseIdealLoop::stay_in_loop( Node* n, IdealLoopTree *loop) {
1536   Node* unique = NULL;
1537   if (!n) return NULL;
1538   for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
1539     Node* use = n->fast_out(i);
1540     if (!has_ctrl(use) && loop->is_member(get_loop(use))) {
1541       if (unique != NULL) {
1542         return NULL;
1543       }
1544       unique = use;
1545     }
1546   }
1547   return unique;
1548 }
1549 
1550 //------------------------------ register_node -------------------------------------
1551 // Utility to register node "n" with PhaseIdealLoop
1552 void PhaseIdealLoop::register_node(Node* n, IdealLoopTree *loop, Node* pred, int ddepth) {
1553   _igvn.register_new_node_with_optimizer(n);
1554   loop->_body.push(n);
1555   if (n->is_CFG()) {
1556     set_loop(n, loop);
1557     set_idom(n, pred, ddepth);
1558   } else {
1559     set_ctrl(n, pred);
1560   }
1561 }
1562 
1563 //------------------------------ proj_clone -------------------------------------
1564 // Utility to create an if-projection
1565 ProjNode* PhaseIdealLoop::proj_clone(ProjNode* p, IfNode* iff) {
1566   ProjNode* c = p->clone()->as_Proj();
1567   c->set_req(0, iff);
1568   return c;
1569 }
1570 
1571 //------------------------------ short_circuit_if -------------------------------------
1572 // Force the iff control output to be the live_proj
1573 Node* PhaseIdealLoop::short_circuit_if(IfNode* iff, ProjNode* live_proj) {
1574   int proj_con = live_proj->_con;
1575   assert(proj_con == 0 || proj_con == 1, "false or true projection");
1576   Node *con = _igvn.intcon(proj_con);
1577   set_ctrl(con, C->root());
1578   if (iff) {
1579     iff->set_req(1, con);
1580   }
1581   return con;
1582 }
1583 
1584 //------------------------------ insert_if_before_proj -------------------------------------
1585 // Insert a new if before an if projection (* - new node)
1586 //
1587 // before
1588 //           if(test)
1589 //           /     \
1590 //          v       v
1591 //    other-proj   proj (arg)
1592 //
1593 // after
1594 //           if(test)
1595 //           /     \
1596 //          /       v
1597 //         |      * proj-clone
1598 //         v          |
1599 //    other-proj      v
1600 //                * new_if(relop(cmp[IU](left,right)))
1601 //                  /  \
1602 //                 v    v
1603 //         * new-proj  proj
1604 //         (returned)
1605 //
1606 ProjNode* PhaseIdealLoop::insert_if_before_proj(Node* left, bool Signed, BoolTest::mask relop, Node* right, ProjNode* proj) {
1607   IfNode* iff = proj->in(0)->as_If();
1608   IdealLoopTree *loop = get_loop(proj);
1609   ProjNode *other_proj = iff->proj_out(!proj->is_IfTrue())->as_Proj();
1610   int ddepth = dom_depth(proj);
1611 
1612   _igvn.hash_delete(iff);
1613   _igvn._worklist.push(iff);
1614   _igvn.hash_delete(proj);
1615   _igvn._worklist.push(proj);
1616 
1617   proj->set_req(0, NULL);  // temporary disconnect
1618   ProjNode* proj2 = proj_clone(proj, iff);
1619   register_node(proj2, loop, iff, ddepth);
1620 
1621   Node* cmp = Signed ? (Node*) new (C,3)CmpINode(left, right) : (Node*) new (C,3)CmpUNode(left, right);
1622   register_node(cmp, loop, proj2, ddepth);
1623 
1624   BoolNode* bol = new (C,2)BoolNode(cmp, relop);
1625   register_node(bol, loop, proj2, ddepth);
1626 
1627   IfNode* new_if = new (C,2)IfNode(proj2, bol, iff->_prob, iff->_fcnt);
1628   register_node(new_if, loop, proj2, ddepth);
1629 
1630   proj->set_req(0, new_if); // reattach
1631   set_idom(proj, new_if, ddepth);
1632 
1633   ProjNode* new_exit = proj_clone(other_proj, new_if)->as_Proj();
1634   register_node(new_exit, get_loop(other_proj), new_if, ddepth);
1635 
1636   return new_exit;
1637 }
1638 
1639 //------------------------------ insert_region_before_proj -------------------------------------
1640 // Insert a region before an if projection (* - new node)
1641 //
1642 // before
1643 //           if(test)
1644 //          /      |
1645 //         v       |
1646 //       proj      v
1647 //               other-proj
1648 //
1649 // after
1650 //           if(test)
1651 //          /      |
1652 //         v       |
1653 // * proj-clone    v
1654 //         |     other-proj
1655 //         v
1656 // * new-region
1657 //         |
1658 //         v
1659 // *      dum_if
1660 //       /     \
1661 //      v       \
1662 // * dum-proj    v
1663 //              proj
1664 //
1665 RegionNode* PhaseIdealLoop::insert_region_before_proj(ProjNode* proj) {
1666   IfNode* iff = proj->in(0)->as_If();
1667   IdealLoopTree *loop = get_loop(proj);
1668   ProjNode *other_proj = iff->proj_out(!proj->is_IfTrue())->as_Proj();
1669   int ddepth = dom_depth(proj);
1670 
1671   _igvn.hash_delete(iff);
1672   _igvn._worklist.push(iff);
1673   _igvn.hash_delete(proj);
1674   _igvn._worklist.push(proj);
1675 
1676   proj->set_req(0, NULL);  // temporary disconnect
1677   ProjNode* proj2 = proj_clone(proj, iff);
1678   register_node(proj2, loop, iff, ddepth);
1679 
1680   RegionNode* reg = new (C,2)RegionNode(2);
1681   reg->set_req(1, proj2);
1682   register_node(reg, loop, iff, ddepth);
1683 
1684   IfNode* dum_if = new (C,2)IfNode(reg, short_circuit_if(NULL, proj), iff->_prob, iff->_fcnt);
1685   register_node(dum_if, loop, reg, ddepth);
1686 
1687   proj->set_req(0, dum_if); // reattach
1688   set_idom(proj, dum_if, ddepth);
1689 
1690   ProjNode* dum_proj = proj_clone(other_proj, dum_if);
1691   register_node(dum_proj, loop, dum_if, ddepth);
1692 
1693   return reg;
1694 }
1695 
1696 //------------------------------ insert_cmpi_loop_exit -------------------------------------
1697 // Clone a signed compare loop exit from an unsigned compare and
1698 // insert it before the unsigned cmp on the stay-in-loop path.
1699 // All new nodes inserted in the dominator tree between the original
1700 // if and it's projections.  The original if test is replaced with
1701 // a constant to force the stay-in-loop path.
1702 //
1703 // This is done to make sure that the original if and it's projections
1704 // still dominate the same set of control nodes, that the ctrl() relation
1705 // from data nodes to them is preserved, and that their loop nesting is
1706 // preserved.
1707 //
1708 // before
1709 //          if(i <u limit)    unsigned compare loop exit
1710 //         /       |
1711 //        v        v
1712 //   exit-proj   stay-in-loop-proj
1713 //
1714 // after
1715 //          if(stay-in-loop-const)  original if
1716 //         /       |
1717 //        /        v
1718 //       /  if(i <  limit)    new signed test
1719 //      /  /       |
1720 //     /  /        v
1721 //    /  /  if(i <u limit)    new cloned unsigned test
1722 //   /  /   /      |
1723 //   v  v  v       |
1724 //    region       |
1725 //        |        |
1726 //      dum-if     |
1727 //     /  |        |
1728 // ether  |        |
1729 //        v        v
1730 //   exit-proj   stay-in-loop-proj
1731 //
1732 IfNode* PhaseIdealLoop::insert_cmpi_loop_exit(IfNode* if_cmpu, IdealLoopTree *loop) {
1733   const bool Signed   = true;
1734   const bool Unsigned = false;
1735 
1736   BoolNode* bol = if_cmpu->in(1)->as_Bool();
1737   if (bol->_test._test != BoolTest::lt) return NULL;
1738   CmpNode* cmpu = bol->in(1)->as_Cmp();
1739   if (cmpu->Opcode() != Op_CmpU) return NULL;
1740   int stride = stride_of_possible_iv(if_cmpu);
1741   if (stride == 0) return NULL;
1742 
1743   ProjNode* lp_continue = stay_in_loop(if_cmpu, loop)->as_Proj();
1744   ProjNode* lp_exit     = if_cmpu->proj_out(!lp_continue->is_IfTrue())->as_Proj();
1745 
1746   Node* limit = NULL;
1747   if (stride > 0) {
1748     limit = cmpu->in(2);
1749   } else {
1750     limit = _igvn.makecon(TypeInt::ZERO);
1751     set_ctrl(limit, C->root());
1752   }
1753   // Create a new region on the exit path
1754   RegionNode* reg = insert_region_before_proj(lp_exit);
1755 
1756   // Clone the if-cmpu-true-false using a signed compare
1757   BoolTest::mask rel_i = stride > 0 ? bol->_test._test : BoolTest::ge;
1758   ProjNode* cmpi_exit = insert_if_before_proj(cmpu->in(1), Signed, rel_i, limit, lp_continue);
1759   reg->add_req(cmpi_exit);
1760 
1761   // Clone the if-cmpu-true-false
1762   BoolTest::mask rel_u = bol->_test._test;
1763   ProjNode* cmpu_exit = insert_if_before_proj(cmpu->in(1), Unsigned, rel_u, cmpu->in(2), lp_continue);
1764   reg->add_req(cmpu_exit);
1765 
1766   // Force original if to stay in loop.
1767   short_circuit_if(if_cmpu, lp_continue);
1768 
1769   return cmpi_exit->in(0)->as_If();
1770 }
1771 
1772 //------------------------------ remove_cmpi_loop_exit -------------------------------------
1773 // Remove a previously inserted signed compare loop exit.
1774 void PhaseIdealLoop::remove_cmpi_loop_exit(IfNode* if_cmp, IdealLoopTree *loop) {
1775   Node* lp_proj = stay_in_loop(if_cmp, loop);
1776   assert(if_cmp->in(1)->in(1)->Opcode() == Op_CmpI &&
1777          stay_in_loop(lp_proj, loop)->is_If() &&
1778          stay_in_loop(lp_proj, loop)->in(1)->in(1)->Opcode() == Op_CmpU, "inserted cmpi before cmpu");
1779   Node *con = _igvn.makecon(lp_proj->is_IfTrue() ? TypeInt::ONE : TypeInt::ZERO);
1780   set_ctrl(con, C->root());
1781   if_cmp->set_req(1, con);
1782 }
1783 
1784 //------------------------------ scheduled_nodelist -------------------------------------
1785 // Create a post order schedule of nodes that are in the
1786 // "member" set.  The list is returned in "sched".
1787 // The first node in "sched" is the loop head, followed by
1788 // nodes which have no inputs in the "member" set, and then
1789 // followed by the nodes that have an immediate input dependence
1790 // on a node in "sched".
1791 void PhaseIdealLoop::scheduled_nodelist( IdealLoopTree *loop, VectorSet& member, Node_List &sched ) {
1792 
1793   assert(member.test(loop->_head->_idx), "loop head must be in member set");
1794   Arena *a = Thread::current()->resource_area();
1795   VectorSet visited(a);
1796   Node_Stack nstack(a, loop->_body.size());
1797 
1798   Node* n  = loop->_head;  // top of stack is cached in "n"
1799   uint idx = 0;
1800   visited.set(n->_idx);
1801 
1802   // Initially push all with no inputs from within member set
1803   for(uint i = 0; i < loop->_body.size(); i++ ) {
1804     Node *elt = loop->_body.at(i);
1805     if (member.test(elt->_idx)) {
1806       bool found = false;
1807       for (uint j = 0; j < elt->req(); j++) {
1808         Node* def = elt->in(j);
1809         if (def && member.test(def->_idx) && def != elt) {
1810           found = true;
1811           break;
1812         }
1813       }
1814       if (!found && elt != loop->_head) {
1815         nstack.push(n, idx);
1816         n = elt;
1817         assert(!visited.test(n->_idx), "not seen yet");
1818         visited.set(n->_idx);
1819       }
1820     }
1821   }
1822 
1823   // traverse out's that are in the member set
1824   while (true) {
1825     if (idx < n->outcnt()) {
1826       Node* use = n->raw_out(idx);
1827       idx++;
1828       if (!visited.test_set(use->_idx)) {
1829         if (member.test(use->_idx)) {
1830           nstack.push(n, idx);
1831           n = use;
1832           idx = 0;
1833         }
1834       }
1835     } else {
1836       // All outputs processed
1837       sched.push(n);
1838       if (nstack.is_empty()) break;
1839       n   = nstack.node();
1840       idx = nstack.index();
1841       nstack.pop();
1842     }
1843   }
1844 }
1845 
1846 
1847 //------------------------------ has_use_in_set -------------------------------------
1848 // Has a use in the vector set
1849 bool PhaseIdealLoop::has_use_in_set( Node* n, VectorSet& vset ) {
1850   for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++) {
1851     Node* use = n->fast_out(j);
1852     if (vset.test(use->_idx)) {
1853       return true;
1854     }
1855   }
1856   return false;
1857 }
1858 
1859 
1860 //------------------------------ has_use_internal_to_set -------------------------------------
1861 // Has use internal to the vector set (ie. not in a phi at the loop head)
1862 bool PhaseIdealLoop::has_use_internal_to_set( Node* n, VectorSet& vset, IdealLoopTree *loop ) {
1863   Node* head  = loop->_head;
1864   for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++) {
1865     Node* use = n->fast_out(j);
1866     if (vset.test(use->_idx) && !(use->is_Phi() && use->in(0) == head)) {
1867       return true;
1868     }
1869   }
1870   return false;
1871 }
1872 
1873 
1874 //------------------------------ clone_for_use_outside_loop -------------------------------------
1875 // clone "n" for uses that are outside of loop
1876 void PhaseIdealLoop::clone_for_use_outside_loop( IdealLoopTree *loop, Node* n, Node_List& worklist ) {
1877 
1878   assert(worklist.size() == 0, "should be empty");
1879   for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++) {
1880     Node* use = n->fast_out(j);
1881     if( !loop->is_member(get_loop(has_ctrl(use) ? get_ctrl(use) : use)) ) {
1882       worklist.push(use);
1883     }
1884   }
1885   while( worklist.size() ) {
1886     Node *use = worklist.pop();
1887     if (!has_node(use) || use->in(0) == C->top()) continue;
1888     uint j;
1889     for (j = 0; j < use->req(); j++) {
1890       if (use->in(j) == n) break;
1891     }
1892     assert(j < use->req(), "must be there");
1893 
1894     // clone "n" and insert it between the inputs of "n" and the use outside the loop
1895     Node* n_clone = n->clone();
1896     _igvn.hash_delete(use);
1897     use->set_req(j, n_clone);
1898     _igvn._worklist.push(use);
1899     Node* use_c;
1900     if (!use->is_Phi()) {
1901       use_c = has_ctrl(use) ? get_ctrl(use) : use->in(0);
1902     } else {
1903       // Use in a phi is considered a use in the associated predecessor block
1904       use_c = use->in(0)->in(j);
1905     }
1906     if (use_c->is_CountedLoop()) {
1907       use_c = use_c->in(LoopNode::EntryControl);
1908     }
1909     set_ctrl(n_clone, use_c);
1910     assert(!loop->is_member(get_loop(use_c)), "should be outside loop");
1911     get_loop(use_c)->_body.push(n_clone);
1912     _igvn.register_new_node_with_optimizer(n_clone);
1913 #if !defined(PRODUCT)
1914     if (TracePartialPeeling) {
1915       tty->print_cr("loop exit cloning old: %d new: %d newbb: %d", n->_idx, n_clone->_idx, get_ctrl(n_clone)->_idx);
1916     }
1917 #endif
1918   }
1919 }
1920 
1921 
1922 //------------------------------ clone_for_special_use_inside_loop -------------------------------------
1923 // clone "n" for special uses that are in the not_peeled region.
1924 // If these def-uses occur in separate blocks, the code generator
1925 // marks the method as not compilable.  For example, if a "BoolNode"
1926 // is in a different basic block than the "IfNode" that uses it, then
1927 // the compilation is aborted in the code generator.
1928 void PhaseIdealLoop::clone_for_special_use_inside_loop( IdealLoopTree *loop, Node* n,
1929                                                         VectorSet& not_peel, Node_List& sink_list, Node_List& worklist ) {
1930   if (n->is_Phi() || n->is_Load()) {
1931     return;
1932   }
1933   assert(worklist.size() == 0, "should be empty");
1934   for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++) {
1935     Node* use = n->fast_out(j);
1936     if ( not_peel.test(use->_idx) &&
1937          (use->is_If() || use->is_CMove() || use->is_Bool()) &&
1938          use->in(1) == n)  {
1939       worklist.push(use);
1940     }
1941   }
1942   if (worklist.size() > 0) {
1943     // clone "n" and insert it between inputs of "n" and the use
1944     Node* n_clone = n->clone();
1945     loop->_body.push(n_clone);
1946     _igvn.register_new_node_with_optimizer(n_clone);
1947     set_ctrl(n_clone, get_ctrl(n));
1948     sink_list.push(n_clone);
1949     not_peel <<= n_clone->_idx;  // add n_clone to not_peel set.
1950 #if !defined(PRODUCT)
1951     if (TracePartialPeeling) {
1952       tty->print_cr("special not_peeled cloning old: %d new: %d", n->_idx, n_clone->_idx);
1953     }
1954 #endif
1955     while( worklist.size() ) {
1956       Node *use = worklist.pop();
1957       _igvn.hash_delete(use);
1958       _igvn._worklist.push(use);
1959       for (uint j = 1; j < use->req(); j++) {
1960         if (use->in(j) == n) {
1961           use->set_req(j, n_clone);
1962         }
1963       }
1964     }
1965   }
1966 }
1967 
1968 
1969 //------------------------------ insert_phi_for_loop -------------------------------------
1970 // Insert phi(lp_entry_val, back_edge_val) at use->in(idx) for loop lp if phi does not already exist
1971 void PhaseIdealLoop::insert_phi_for_loop( Node* use, uint idx, Node* lp_entry_val, Node* back_edge_val, LoopNode* lp ) {
1972   Node *phi = PhiNode::make(lp, back_edge_val);
1973   phi->set_req(LoopNode::EntryControl, lp_entry_val);
1974   // Use existing phi if it already exists
1975   Node *hit = _igvn.hash_find_insert(phi);
1976   if( hit == NULL ) {
1977     _igvn.register_new_node_with_optimizer(phi);
1978     set_ctrl(phi, lp);
1979   } else {
1980     // Remove the new phi from the graph and use the hit
1981     _igvn.remove_dead_node(phi);
1982     phi = hit;
1983   }
1984   _igvn.hash_delete(use);
1985   _igvn._worklist.push(use);
1986   use->set_req(idx, phi);
1987 }
1988 
1989 #ifdef ASSERT
1990 //------------------------------ is_valid_loop_partition -------------------------------------
1991 // Validate the loop partition sets: peel and not_peel
1992 bool PhaseIdealLoop::is_valid_loop_partition( IdealLoopTree *loop, VectorSet& peel, Node_List& peel_list,
1993                                               VectorSet& not_peel ) {
1994   uint i;
1995   // Check that peel_list entries are in the peel set
1996   for (i = 0; i < peel_list.size(); i++) {
1997     if (!peel.test(peel_list.at(i)->_idx)) {
1998       return false;
1999     }
2000   }
2001   // Check at loop members are in one of peel set or not_peel set
2002   for (i = 0; i < loop->_body.size(); i++ ) {
2003     Node *def  = loop->_body.at(i);
2004     uint di = def->_idx;
2005     // Check that peel set elements are in peel_list
2006     if (peel.test(di)) {
2007       if (not_peel.test(di)) {
2008         return false;
2009       }
2010       // Must be in peel_list also
2011       bool found = false;
2012       for (uint j = 0; j < peel_list.size(); j++) {
2013         if (peel_list.at(j)->_idx == di) {
2014           found = true;
2015           break;
2016         }
2017       }
2018       if (!found) {
2019         return false;
2020       }
2021     } else if (not_peel.test(di)) {
2022       if (peel.test(di)) {
2023         return false;
2024       }
2025     } else {
2026       return false;
2027     }
2028   }
2029   return true;
2030 }
2031 
2032 //------------------------------ is_valid_clone_loop_exit_use -------------------------------------
2033 // Ensure a use outside of loop is of the right form
2034 bool PhaseIdealLoop::is_valid_clone_loop_exit_use( IdealLoopTree *loop, Node* use, uint exit_idx) {
2035   Node *use_c = has_ctrl(use) ? get_ctrl(use) : use;
2036   return (use->is_Phi() &&
2037           use_c->is_Region() && use_c->req() == 3 &&
2038           (use_c->in(exit_idx)->Opcode() == Op_IfTrue ||
2039            use_c->in(exit_idx)->Opcode() == Op_IfFalse ||
2040            use_c->in(exit_idx)->Opcode() == Op_JumpProj) &&
2041           loop->is_member( get_loop( use_c->in(exit_idx)->in(0) ) ) );
2042 }
2043 
2044 //------------------------------ is_valid_clone_loop_form -------------------------------------
2045 // Ensure that all uses outside of loop are of the right form
2046 bool PhaseIdealLoop::is_valid_clone_loop_form( IdealLoopTree *loop, Node_List& peel_list,
2047                                                uint orig_exit_idx, uint clone_exit_idx) {
2048   uint len = peel_list.size();
2049   for (uint i = 0; i < len; i++) {
2050     Node *def = peel_list.at(i);
2051 
2052     for (DUIterator_Fast jmax, j = def->fast_outs(jmax); j < jmax; j++) {
2053       Node *use = def->fast_out(j);
2054       Node *use_c = has_ctrl(use) ? get_ctrl(use) : use;
2055       if (!loop->is_member(get_loop(use_c))) {
2056         // use is not in the loop, check for correct structure
2057         if (use->in(0) == def) {
2058           // Okay
2059         } else if (!is_valid_clone_loop_exit_use(loop, use, orig_exit_idx)) {
2060           return false;
2061         }
2062       }
2063     }
2064   }
2065   return true;
2066 }
2067 #endif
2068 
2069 //------------------------------ partial_peel -------------------------------------
2070 // Partially peel (aka loop rotation) the top portion of a loop (called
2071 // the peel section below) by cloning it and placing one copy just before
2072 // the new loop head and the other copy at the bottom of the new loop.
2073 //
2074 //    before                       after                where it came from
2075 //
2076 //    stmt1                        stmt1
2077 //  loop:                          stmt2                     clone
2078 //    stmt2                        if condA goto exitA       clone
2079 //    if condA goto exitA        new_loop:                   new
2080 //    stmt3                        stmt3                     clone
2081 //    if !condB goto loop          if condB goto exitB       clone
2082 //  exitB:                         stmt2                     orig
2083 //    stmt4                        if !condA goto new_loop   orig
2084 //  exitA:                         goto exitA
2085 //                               exitB:
2086 //                                 stmt4
2087 //                               exitA:
2088 //
2089 // Step 1: find the cut point: an exit test on probable
2090 //         induction variable.
2091 // Step 2: schedule (with cloning) operations in the peel
2092 //         section that can be executed after the cut into
2093 //         the section that is not peeled.  This may need
2094 //         to clone operations into exit blocks.  For
2095 //         instance, a reference to A[i] in the not-peel
2096 //         section and a reference to B[i] in an exit block
2097 //         may cause a left-shift of i by 2 to be placed
2098 //         in the peel block.  This step will clone the left
2099 //         shift into the exit block and sink the left shift
2100 //         from the peel to the not-peel section.
2101 // Step 3: clone the loop, retarget the control, and insert
2102 //         phis for values that are live across the new loop
2103 //         head.  This is very dependent on the graph structure
2104 //         from clone_loop.  It creates region nodes for
2105 //         exit control and associated phi nodes for values
2106 //         flow out of the loop through that exit.  The region
2107 //         node is dominated by the clone's control projection.
2108 //         So the clone's peel section is placed before the
2109 //         new loop head, and the clone's not-peel section is
2110 //         forms the top part of the new loop.  The original
2111 //         peel section forms the tail of the new loop.
2112 // Step 4: update the dominator tree and recompute the
2113 //         dominator depth.
2114 //
2115 //                   orig
2116 //
2117 //                  stmt1
2118 //                    |
2119 //                    v
2120 //                   loop<----+
2121 //                     |      |
2122 //                   stmt2    |
2123 //                     |      |
2124 //                     v      |
2125 //                    ifA     |
2126 //                   / |      |
2127 //                  v  v      |
2128 //               false true   ^  <-- last_peel
2129 //               /     |      |
2130 //              /   ===|==cut |
2131 //             /     stmt3    |  <-- first_not_peel
2132 //            /        |      |
2133 //            |        v      |
2134 //            v       ifB     |
2135 //          exitA:   / \      |
2136 //                  /   \     |
2137 //                 v     v    |
2138 //               false true   |
2139 //               /       \    |
2140 //              /         ----+
2141 //             |
2142 //             v
2143 //           exitB:
2144 //           stmt4
2145 //
2146 //
2147 //            after clone loop
2148 //
2149 //                   stmt1
2150 //                 /       \
2151 //        clone   /         \   orig
2152 //               /           \
2153 //              /             \
2154 //             v               v
2155 //   +---->loop                loop<----+
2156 //   |      |                    |      |
2157 //   |    stmt2                stmt2    |
2158 //   |      |                    |      |
2159 //   |      v                    v      |
2160 //   |      ifA                 ifA     |
2161 //   |      | \                / |      |
2162 //   |      v  v              v  v      |
2163 //   ^    true  false      false true   ^  <-- last_peel
2164 //   |      |   ^   \       /    |      |
2165 //   | cut==|==  \   \     /  ===|==cut |
2166 //   |    stmt3   \   \   /    stmt3    |  <-- first_not_peel
2167 //   |      |    dom   | |       |      |
2168 //   |      v      \  1v v2      v      |
2169 //   |      ifB     regionA     ifB     |
2170 //   |      / \        |       / \      |
2171 //   |     /   \       v      /   \     |
2172 //   |    v     v    exitA:  v     v    |
2173 //   |    true  false      false true   |
2174 //   |    /     ^   \      /       \    |
2175 //   +----       \   \    /         ----+
2176 //               dom  \  /
2177 //                 \  1v v2
2178 //                  regionB
2179 //                     |
2180 //                     v
2181 //                   exitB:
2182 //                   stmt4
2183 //
2184 //
2185 //           after partial peel
2186 //
2187 //                  stmt1
2188 //                 /
2189 //        clone   /             orig
2190 //               /          TOP
2191 //              /             \
2192 //             v               v
2193 //    TOP->region             region----+
2194 //          |                    |      |
2195 //        stmt2                stmt2    |
2196 //          |                    |      |
2197 //          v                    v      |
2198 //          ifA                 ifA     |
2199 //          | \                / |      |
2200 //          v  v              v  v      |
2201 //        true  false      false true   |     <-- last_peel
2202 //          |   ^   \       /    +------|---+
2203 //  +->newloop   \   \     /  === ==cut |   |
2204 //  |     stmt3   \   \   /     TOP     |   |
2205 //  |       |    dom   | |      stmt3   |   | <-- first_not_peel
2206 //  |       v      \  1v v2      v      |   |
2207 //  |       ifB     regionA     ifB     ^   v
2208 //  |       / \        |       / \      |   |
2209 //  |      /   \       v      /   \     |   |
2210 //  |     v     v    exitA:  v     v    |   |
2211 //  |     true  false      false true   |   |
2212 //  |     /     ^   \      /       \    |   |
2213 //  |    |       \   \    /         v   |   |
2214 //  |    |       dom  \  /         TOP  |   |
2215 //  |    |         \  1v v2             |   |
2216 //  ^    v          regionB             |   |
2217 //  |    |             |                |   |
2218 //  |    |             v                ^   v
2219 //  |    |           exitB:             |   |
2220 //  |    |           stmt4              |   |
2221 //  |    +------------>-----------------+   |
2222 //  |                                       |
2223 //  +-----------------<---------------------+
2224 //
2225 //
2226 //              final graph
2227 //
2228 //                  stmt1
2229 //                    |
2230 //                    v
2231 //         ........> ifA clone
2232 //         :        / |
2233 //        dom      /  |
2234 //         :      v   v
2235 //         :  false   true
2236 //         :  |       |
2237 //         :  |     stmt2 clone
2238 //         :  |       |
2239 //         :  |       v
2240 //         :  |    newloop<-----+
2241 //         :  |        |        |
2242 //         :  |     stmt3 clone |
2243 //         :  |        |        |
2244 //         :  |        v        |
2245 //         :  |       ifB       |
2246 //         :  |      / \        |
2247 //         :  |     v   v       |
2248 //         :  |  false true     |
2249 //         :  |   |     |       |
2250 //         :  |   v    stmt2    |
2251 //         :  | exitB:  |       |
2252 //         :  | stmt4   v       |
2253 //         :  |       ifA orig  |
2254 //         :  |      /  \       |
2255 //         :  |     /    \      |
2256 //         :  |    v     v      |
2257 //         :  |  false  true    |
2258 //         :  |  /        \     |
2259 //         :  v  v         -----+
2260 //          RegionA
2261 //             |
2262 //             v
2263 //           exitA
2264 //
2265 bool PhaseIdealLoop::partial_peel( IdealLoopTree *loop, Node_List &old_new ) {
2266 
2267   if (!loop->_head->is_Loop()) {
2268     return false;  }
2269 
2270   LoopNode *head  = loop->_head->as_Loop();
2271 
2272   if (head->is_partial_peel_loop() || head->partial_peel_has_failed()) {
2273     return false;
2274   }
2275 
2276   // Check for complex exit control
2277   for(uint ii = 0; ii < loop->_body.size(); ii++ ) {
2278     Node *n = loop->_body.at(ii);
2279     int opc = n->Opcode();
2280     if (n->is_Call()        ||
2281         opc == Op_Catch     ||
2282         opc == Op_CatchProj ||
2283         opc == Op_Jump      ||
2284         opc == Op_JumpProj) {
2285 #if !defined(PRODUCT)
2286       if (TracePartialPeeling) {
2287         tty->print_cr("\nExit control too complex: lp: %d", head->_idx);
2288       }
2289 #endif
2290       return false;
2291     }
2292   }
2293 
2294   int dd = dom_depth(head);
2295 
2296   // Step 1: find cut point
2297 
2298   // Walk up dominators to loop head looking for first loop exit
2299   // which is executed on every path thru loop.
2300   IfNode *peel_if = NULL;
2301   IfNode *peel_if_cmpu = NULL;
2302 
2303   Node *iff = loop->tail();
2304   while( iff != head ) {
2305     if( iff->is_If() ) {
2306       Node *ctrl = get_ctrl(iff->in(1));
2307       if (ctrl->is_top()) return false; // Dead test on live IF.
2308       // If loop-varying exit-test, check for induction variable
2309       if( loop->is_member(get_loop(ctrl)) &&
2310           loop->is_loop_exit(iff) &&
2311           is_possible_iv_test(iff)) {
2312         Node* cmp = iff->in(1)->in(1);
2313         if (cmp->Opcode() == Op_CmpI) {
2314           peel_if = iff->as_If();
2315         } else {
2316           assert(cmp->Opcode() == Op_CmpU, "must be CmpI or CmpU");
2317           peel_if_cmpu = iff->as_If();
2318         }
2319       }
2320     }
2321     iff = idom(iff);
2322   }
2323   // Prefer signed compare over unsigned compare.
2324   IfNode* new_peel_if = NULL;
2325   if (peel_if == NULL) {
2326     if (!PartialPeelAtUnsignedTests || peel_if_cmpu == NULL) {
2327       return false;   // No peel point found
2328     }
2329     new_peel_if = insert_cmpi_loop_exit(peel_if_cmpu, loop);
2330     if (new_peel_if == NULL) {
2331       return false;   // No peel point found
2332     }
2333     peel_if = new_peel_if;
2334   }
2335   Node* last_peel        = stay_in_loop(peel_if, loop);
2336   Node* first_not_peeled = stay_in_loop(last_peel, loop);
2337   if (first_not_peeled == NULL || first_not_peeled == head) {
2338     return false;
2339   }
2340 
2341 #if !defined(PRODUCT)
2342   if (TracePartialPeeling) {
2343     tty->print_cr("before partial peel one iteration");
2344     Node_List wl;
2345     Node* t = head->in(2);
2346     while (true) {
2347       wl.push(t);
2348       if (t == head) break;
2349       t = idom(t);
2350     }
2351     while (wl.size() > 0) {
2352       Node* tt = wl.pop();
2353       tt->dump();
2354       if (tt == last_peel) tty->print_cr("-- cut --");
2355     }
2356   }
2357 #endif
2358   ResourceArea *area = Thread::current()->resource_area();
2359   VectorSet peel(area);
2360   VectorSet not_peel(area);
2361   Node_List peel_list(area);
2362   Node_List worklist(area);
2363   Node_List sink_list(area);
2364 
2365   // Set of cfg nodes to peel are those that are executable from
2366   // the head through last_peel.
2367   assert(worklist.size() == 0, "should be empty");
2368   worklist.push(head);
2369   peel.set(head->_idx);
2370   while (worklist.size() > 0) {
2371     Node *n = worklist.pop();
2372     if (n != last_peel) {
2373       for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++) {
2374         Node* use = n->fast_out(j);
2375         if (use->is_CFG() &&
2376             loop->is_member(get_loop(use)) &&
2377             !peel.test_set(use->_idx)) {
2378           worklist.push(use);
2379         }
2380       }
2381     }
2382   }
2383 
2384   // Set of non-cfg nodes to peel are those that are control
2385   // dependent on the cfg nodes.
2386   uint i;
2387   for(i = 0; i < loop->_body.size(); i++ ) {
2388     Node *n = loop->_body.at(i);
2389     Node *n_c = has_ctrl(n) ? get_ctrl(n) : n;
2390     if (peel.test(n_c->_idx)) {
2391       peel.set(n->_idx);
2392     } else {
2393       not_peel.set(n->_idx);
2394     }
2395   }
2396 
2397   // Step 2: move operations from the peeled section down into the
2398   //         not-peeled section
2399 
2400   // Get a post order schedule of nodes in the peel region
2401   // Result in right-most operand.
2402   scheduled_nodelist(loop, peel, peel_list );
2403 
2404   assert(is_valid_loop_partition(loop, peel, peel_list, not_peel), "bad partition");
2405 
2406   // For future check for too many new phis
2407   uint old_phi_cnt = 0;
2408   for (DUIterator_Fast jmax, j = head->fast_outs(jmax); j < jmax; j++) {
2409     Node* use = head->fast_out(j);
2410     if (use->is_Phi()) old_phi_cnt++;
2411   }
2412 
2413 #if !defined(PRODUCT)
2414   if (TracePartialPeeling) {
2415     tty->print_cr("\npeeled list");
2416   }
2417 #endif
2418 
2419   // Evacuate nodes in peel region into the not_peeled region if possible
2420   uint new_phi_cnt = 0;
2421   for (i = 0; i < peel_list.size();) {
2422     Node* n = peel_list.at(i);
2423 #if !defined(PRODUCT)
2424   if (TracePartialPeeling) n->dump();
2425 #endif
2426     bool incr = true;
2427     if ( !n->is_CFG() ) {
2428 
2429       if ( has_use_in_set(n, not_peel) ) {
2430 
2431         // If not used internal to the peeled region,
2432         // move "n" from peeled to not_peeled region.
2433 
2434         if ( !has_use_internal_to_set(n, peel, loop) ) {
2435 
2436           // if not pinned and not a load (which maybe anti-dependent on a store)
2437           // and not a CMove (Matcher expects only bool->cmove).
2438           if ( n->in(0) == NULL && !n->is_Load() && !n->is_CMove() ) {
2439             clone_for_use_outside_loop( loop, n, worklist );
2440 
2441             sink_list.push(n);
2442             peel     >>= n->_idx; // delete n from peel set.
2443             not_peel <<= n->_idx; // add n to not_peel set.
2444             peel_list.remove(i);
2445             incr = false;
2446 #if !defined(PRODUCT)
2447             if (TracePartialPeeling) {
2448               tty->print_cr("sink to not_peeled region: %d newbb: %d",
2449                             n->_idx, get_ctrl(n)->_idx);
2450             }
2451 #endif
2452           }
2453         } else {
2454           // Otherwise check for special def-use cases that span
2455           // the peel/not_peel boundary such as bool->if
2456           clone_for_special_use_inside_loop( loop, n, not_peel, sink_list, worklist );
2457           new_phi_cnt++;
2458         }
2459       }
2460     }
2461     if (incr) i++;
2462   }
2463 
2464   if (new_phi_cnt > old_phi_cnt + PartialPeelNewPhiDelta) {
2465 #if !defined(PRODUCT)
2466     if (TracePartialPeeling) {
2467       tty->print_cr("\nToo many new phis: %d  old %d new cmpi: %c",
2468                     new_phi_cnt, old_phi_cnt, new_peel_if != NULL?'T':'F');
2469     }
2470 #endif
2471     if (new_peel_if != NULL) {
2472       remove_cmpi_loop_exit(new_peel_if, loop);
2473     }
2474     // Inhibit more partial peeling on this loop
2475     assert(!head->is_partial_peel_loop(), "not partial peeled");
2476     head->mark_partial_peel_failed();
2477     return false;
2478   }
2479 
2480   // Step 3: clone loop, retarget control, and insert new phis
2481 
2482   // Create new loop head for new phis and to hang
2483   // the nodes being moved (sinked) from the peel region.
2484   LoopNode* new_head = new (C, 3) LoopNode(last_peel, last_peel);
2485   _igvn.register_new_node_with_optimizer(new_head);
2486   assert(first_not_peeled->in(0) == last_peel, "last_peel <- first_not_peeled");
2487   first_not_peeled->set_req(0, new_head);
2488   set_loop(new_head, loop);
2489   loop->_body.push(new_head);
2490   not_peel.set(new_head->_idx);
2491   set_idom(new_head, last_peel, dom_depth(first_not_peeled));
2492   set_idom(first_not_peeled, new_head, dom_depth(first_not_peeled));
2493 
2494   while (sink_list.size() > 0) {
2495     Node* n = sink_list.pop();
2496     set_ctrl(n, new_head);
2497   }
2498 
2499   assert(is_valid_loop_partition(loop, peel, peel_list, not_peel), "bad partition");
2500 
2501   clone_loop( loop, old_new, dd );
2502 
2503   const uint clone_exit_idx = 1;
2504   const uint orig_exit_idx  = 2;
2505   assert(is_valid_clone_loop_form( loop, peel_list, orig_exit_idx, clone_exit_idx ), "bad clone loop");
2506 
2507   Node* head_clone             = old_new[head->_idx];
2508   LoopNode* new_head_clone     = old_new[new_head->_idx]->as_Loop();
2509   Node* orig_tail_clone        = head_clone->in(2);
2510 
2511   // Add phi if "def" node is in peel set and "use" is not
2512 
2513   for(i = 0; i < peel_list.size(); i++ ) {
2514     Node *def  = peel_list.at(i);
2515     if (!def->is_CFG()) {
2516       for (DUIterator_Fast jmax, j = def->fast_outs(jmax); j < jmax; j++) {
2517         Node *use = def->fast_out(j);
2518         if (has_node(use) && use->in(0) != C->top() &&
2519             (!peel.test(use->_idx) ||
2520              (use->is_Phi() && use->in(0) == head)) ) {
2521           worklist.push(use);
2522         }
2523       }
2524       while( worklist.size() ) {
2525         Node *use = worklist.pop();
2526         for (uint j = 1; j < use->req(); j++) {
2527           Node* n = use->in(j);
2528           if (n == def) {
2529 
2530             // "def" is in peel set, "use" is not in peel set
2531             // or "use" is in the entry boundary (a phi) of the peel set
2532 
2533             Node* use_c = has_ctrl(use) ? get_ctrl(use) : use;
2534 
2535             if ( loop->is_member(get_loop( use_c )) ) {
2536               // use is in loop
2537               if (old_new[use->_idx] != NULL) { // null for dead code
2538                 Node* use_clone = old_new[use->_idx];
2539                 _igvn.hash_delete(use);
2540                 use->set_req(j, C->top());
2541                 _igvn._worklist.push(use);
2542                 insert_phi_for_loop( use_clone, j, old_new[def->_idx], def, new_head_clone );
2543               }
2544             } else {
2545               assert(is_valid_clone_loop_exit_use(loop, use, orig_exit_idx), "clone loop format");
2546               // use is not in the loop, check if the live range includes the cut
2547               Node* lp_if = use_c->in(orig_exit_idx)->in(0);
2548               if (not_peel.test(lp_if->_idx)) {
2549                 assert(j == orig_exit_idx, "use from original loop");
2550                 insert_phi_for_loop( use, clone_exit_idx, old_new[def->_idx], def, new_head_clone );
2551               }
2552             }
2553           }
2554         }
2555       }
2556     }
2557   }
2558 
2559   // Step 3b: retarget control
2560 
2561   // Redirect control to the new loop head if a cloned node in
2562   // the not_peeled region has control that points into the peeled region.
2563   // This necessary because the cloned peeled region will be outside
2564   // the loop.
2565   //                            from    to
2566   //          cloned-peeled    <---+
2567   //    new_head_clone:            |    <--+
2568   //          cloned-not_peeled  in(0)    in(0)
2569   //          orig-peeled
2570 
2571   for(i = 0; i < loop->_body.size(); i++ ) {
2572     Node *n = loop->_body.at(i);
2573     if (!n->is_CFG()           && n->in(0) != NULL        &&
2574         not_peel.test(n->_idx) && peel.test(n->in(0)->_idx)) {
2575       Node* n_clone = old_new[n->_idx];
2576       _igvn.hash_delete(n_clone);
2577       n_clone->set_req(0, new_head_clone);
2578       _igvn._worklist.push(n_clone);
2579     }
2580   }
2581 
2582   // Backedge of the surviving new_head (the clone) is original last_peel
2583   _igvn.hash_delete(new_head_clone);
2584   new_head_clone->set_req(LoopNode::LoopBackControl, last_peel);
2585   _igvn._worklist.push(new_head_clone);
2586 
2587   // Cut first node in original not_peel set
2588   _igvn.hash_delete(new_head);
2589   new_head->set_req(LoopNode::EntryControl, C->top());
2590   new_head->set_req(LoopNode::LoopBackControl, C->top());
2591   _igvn._worklist.push(new_head);
2592 
2593   // Copy head_clone back-branch info to original head
2594   // and remove original head's loop entry and
2595   // clone head's back-branch
2596   _igvn.hash_delete(head);
2597   _igvn.hash_delete(head_clone);
2598   head->set_req(LoopNode::EntryControl, head_clone->in(LoopNode::LoopBackControl));
2599   head->set_req(LoopNode::LoopBackControl, C->top());
2600   head_clone->set_req(LoopNode::LoopBackControl, C->top());
2601   _igvn._worklist.push(head);
2602   _igvn._worklist.push(head_clone);
2603 
2604   // Similarly modify the phis
2605   for (DUIterator_Fast kmax, k = head->fast_outs(kmax); k < kmax; k++) {
2606     Node* use = head->fast_out(k);
2607     if (use->is_Phi() && use->outcnt() > 0) {
2608       Node* use_clone = old_new[use->_idx];
2609       _igvn.hash_delete(use);
2610       _igvn.hash_delete(use_clone);
2611       use->set_req(LoopNode::EntryControl, use_clone->in(LoopNode::LoopBackControl));
2612       use->set_req(LoopNode::LoopBackControl, C->top());
2613       use_clone->set_req(LoopNode::LoopBackControl, C->top());
2614       _igvn._worklist.push(use);
2615       _igvn._worklist.push(use_clone);
2616     }
2617   }
2618 
2619   // Step 4: update dominator tree and dominator depth
2620 
2621   set_idom(head, orig_tail_clone, dd);
2622   recompute_dom_depth();
2623 
2624   // Inhibit more partial peeling on this loop
2625   new_head_clone->set_partial_peel_loop();
2626   C->set_major_progress();
2627 
2628 #if !defined(PRODUCT)
2629   if (TracePartialPeeling) {
2630     tty->print_cr("\nafter partial peel one iteration");
2631     Node_List wl(area);
2632     Node* t = last_peel;
2633     while (true) {
2634       wl.push(t);
2635       if (t == head_clone) break;
2636       t = idom(t);
2637     }
2638     while (wl.size() > 0) {
2639       Node* tt = wl.pop();
2640       if (tt == head) tty->print_cr("orig head");
2641       else if (tt == new_head_clone) tty->print_cr("new head");
2642       else if (tt == head_clone) tty->print_cr("clone head");
2643       tt->dump();
2644     }
2645   }
2646 #endif
2647   return true;
2648 }
2649 
2650 //------------------------------reorg_offsets----------------------------------
2651 // Reorganize offset computations to lower register pressure.  Mostly
2652 // prevent loop-fallout uses of the pre-incremented trip counter (which are
2653 // then alive with the post-incremented trip counter forcing an extra
2654 // register move)
2655 void PhaseIdealLoop::reorg_offsets( IdealLoopTree *loop ) {
2656 
2657   CountedLoopNode *cl = loop->_head->as_CountedLoop();
2658   CountedLoopEndNode *cle = cl->loopexit();
2659   if( !cle ) return;            // The occasional dead loop
2660   // Find loop exit control
2661   Node *exit = cle->proj_out(false);
2662   assert( exit->Opcode() == Op_IfFalse, "" );
2663 
2664   // Check for the special case of folks using the pre-incremented
2665   // trip-counter on the fall-out path (forces the pre-incremented
2666   // and post-incremented trip counter to be live at the same time).
2667   // Fix this by adjusting to use the post-increment trip counter.
2668   Node *phi = cl->phi();
2669   if( !phi ) return;            // Dead infinite loop
2670   bool progress = true;
2671   while (progress) {
2672     progress = false;
2673     for (DUIterator_Fast imax, i = phi->fast_outs(imax); i < imax; i++) {
2674       Node* use = phi->fast_out(i);   // User of trip-counter
2675       if (!has_ctrl(use))  continue;
2676       Node *u_ctrl = get_ctrl(use);
2677       if( use->is_Phi() ) {
2678         u_ctrl = NULL;
2679         for( uint j = 1; j < use->req(); j++ )
2680           if( use->in(j) == phi )
2681             u_ctrl = dom_lca( u_ctrl, use->in(0)->in(j) );
2682       }
2683       IdealLoopTree *u_loop = get_loop(u_ctrl);
2684       // Look for loop-invariant use
2685       if( u_loop == loop ) continue;
2686       if( loop->is_member( u_loop ) ) continue;
2687       // Check that use is live out the bottom.  Assuming the trip-counter
2688       // update is right at the bottom, uses of of the loop middle are ok.
2689       if( dom_lca( exit, u_ctrl ) != exit ) continue;
2690       // protect against stride not being a constant
2691       if( !cle->stride_is_con() ) continue;
2692       // Hit!  Refactor use to use the post-incremented tripcounter.
2693       // Compute a post-increment tripcounter.
2694       Node *opaq = new (C, 2) Opaque2Node( C, cle->incr() );
2695       register_new_node( opaq, u_ctrl );
2696       Node *neg_stride = _igvn.intcon(-cle->stride_con());
2697       set_ctrl(neg_stride, C->root());
2698       Node *post = new (C, 3) AddINode( opaq, neg_stride);
2699       register_new_node( post, u_ctrl );
2700       _igvn.hash_delete(use);
2701       _igvn._worklist.push(use);
2702       for( uint j = 1; j < use->req(); j++ )
2703         if( use->in(j) == phi )
2704           use->set_req(j, post);
2705       // Since DU info changed, rerun loop
2706       progress = true;
2707       break;
2708     }
2709   }
2710 
2711 }