1 #ifdef USE_PRAGMA_IDENT_SRC
   2 #pragma ident "@(#)loopTransform.cpp    1.116 07/06/01 11:35:03 JVM"
   3 #endif
   4 /*
   5  * Copyright 2000-2007 Sun Microsystems, Inc.  All Rights Reserved.
   6  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   7  *
   8  * This code is free software; you can redistribute it and/or modify it
   9  * under the terms of the GNU General Public License version 2 only, as
  10  * published by the Free Software Foundation.
  11  *
  12  * This code is distributed in the hope that it will be useful, but WITHOUT
  13  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  14  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  15  * version 2 for more details (a copy is included in the LICENSE file that
  16  * accompanied this code).
  17  *
  18  * You should have received a copy of the GNU General Public License version
  19  * 2 along with this work; if not, write to the Free Software Foundation,
  20  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  21  *
  22  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
  23  * CA 95054 USA or visit www.sun.com if you need additional information or
  24  * have any questions.
  25  *  
  26  */
  27 
  28 #include "incls/_precompiled.incl"
  29 #include "incls/_loopTransform.cpp.incl"
  30 
  31 //------------------------------is_loop_exit-----------------------------------
  32 // Given an IfNode, return the loop-exiting projection or NULL if both 
  33 // arms remain in the loop.
  34 Node *IdealLoopTree::is_loop_exit(Node *iff) const {
  35   if( iff->outcnt() != 2 ) return NULL; // Ignore partially dead tests
  36   PhaseIdealLoop *phase = _phase;
  37   // Test is an IfNode, has 2 projections.  If BOTH are in the loop
  38   // we need loop unswitching instead of peeling.
  39   if( !is_member(phase->get_loop( iff->raw_out(0) )) )
  40     return iff->raw_out(0);
  41   if( !is_member(phase->get_loop( iff->raw_out(1) )) )
  42     return iff->raw_out(1);
  43   return NULL;
  44 }
  45 
  46 
  47 //=============================================================================
  48 
  49 
  50 //------------------------------record_for_igvn----------------------------
  51 // Put loop body on igvn work list
  52 void IdealLoopTree::record_for_igvn() {
  53   for( uint i = 0; i < _body.size(); i++ ) {
  54     Node *n = _body.at(i);
  55     _phase->_igvn._worklist.push(n);
  56   }
  57 }
  58 
  59 //------------------------------compute_profile_trip_cnt----------------------------
  60 // Compute loop trip count from profile data as
  61 //    (backedge_count + loop_exit_count) / loop_exit_count
  62 void IdealLoopTree::compute_profile_trip_cnt( PhaseIdealLoop *phase ) {
  63   if (!_head->is_CountedLoop()) {
  64     return;
  65   }
  66   CountedLoopNode* head = _head->as_CountedLoop();
  67   if (head->profile_trip_cnt() != COUNT_UNKNOWN) {
  68     return; // Already computed
  69   }
  70   float trip_cnt = (float)max_jint; // default is big
  71 
  72   Node* back = head->in(LoopNode::LoopBackControl);
  73   while (back != head) {
  74     if ((back->Opcode() == Op_IfTrue || back->Opcode() == Op_IfFalse) &&
  75         back->in(0) &&
  76         back->in(0)->is_If() &&
  77         back->in(0)->as_If()->_fcnt != COUNT_UNKNOWN &&
  78         back->in(0)->as_If()->_prob != PROB_UNKNOWN) {
  79       break;
  80     }
  81     back = phase->idom(back);
  82   }
  83   if (back != head) {
  84     assert((back->Opcode() == Op_IfTrue || back->Opcode() == Op_IfFalse) &&
  85            back->in(0), "if-projection exists");
  86     IfNode* back_if = back->in(0)->as_If();
  87     float loop_back_cnt = back_if->_fcnt * back_if->_prob;
  88 
  89     // Now compute a loop exit count
  90     float loop_exit_cnt = 0.0f;
  91     for( uint i = 0; i < _body.size(); i++ ) {
  92       Node *n = _body[i];
  93       if( n->is_If() ) {
  94         IfNode *iff = n->as_If();
  95         if( iff->_fcnt != COUNT_UNKNOWN && iff->_prob != PROB_UNKNOWN ) {
  96           Node *exit = is_loop_exit(iff);
  97           if( exit ) {
  98             float exit_prob = iff->_prob;
  99             if (exit->Opcode() == Op_IfFalse) exit_prob = 1.0 - exit_prob;
 100             if (exit_prob > PROB_MIN) {
 101               float exit_cnt = iff->_fcnt * exit_prob;
 102               loop_exit_cnt += exit_cnt;
 103             }
 104           }
 105         }
 106       }
 107     }
 108     if (loop_exit_cnt > 0.0f) {
 109       trip_cnt = (loop_back_cnt + loop_exit_cnt) / loop_exit_cnt;
 110     } else {
 111       // No exit count so use
 112       trip_cnt = loop_back_cnt;
 113     }
 114   }
 115 #ifndef PRODUCT
 116   if (TraceProfileTripCount) {
 117     tty->print_cr("compute_profile_trip_cnt  lp: %d cnt: %f\n", head->_idx, trip_cnt);
 118   }
 119 #endif
 120   head->set_profile_trip_cnt(trip_cnt);
 121 }
 122 
 123 //---------------------is_invariant_addition-----------------------------
 124 // Return nonzero index of invariant operand for an Add or Sub
 125 // of (nonconstant) invariant and variant values. Helper for reassoicate_invariants.
 126 int IdealLoopTree::is_invariant_addition(Node* n, PhaseIdealLoop *phase) {
 127   int op = n->Opcode();
 128   if (op == Op_AddI || op == Op_SubI) {
 129     bool in1_invar = this->is_invariant(n->in(1));
 130     bool in2_invar = this->is_invariant(n->in(2));
 131     if (in1_invar && !in2_invar) return 1;
 132     if (!in1_invar && in2_invar) return 2;
 133   }
 134   return 0;
 135 }
 136 
 137 //---------------------reassociate_add_sub-----------------------------
 138 // Reassociate invariant add and subtract expressions:
 139 //
 140 // inv1 + (x + inv2)  =>  ( inv1 + inv2) + x
 141 // (x + inv2) + inv1  =>  ( inv1 + inv2) + x
 142 // inv1 + (x - inv2)  =>  ( inv1 - inv2) + x
 143 // inv1 - (inv2 - x)  =>  ( inv1 - inv2) + x
 144 // (x + inv2) - inv1  =>  (-inv1 + inv2) + x
 145 // (x - inv2) + inv1  =>  ( inv1 - inv2) + x
 146 // (x - inv2) - inv1  =>  (-inv1 - inv2) + x
 147 // inv1 + (inv2 - x)  =>  ( inv1 + inv2) - x
 148 // inv1 - (x - inv2)  =>  ( inv1 + inv2) - x
 149 // (inv2 - x) + inv1  =>  ( inv1 + inv2) - x
 150 // (inv2 - x) - inv1  =>  (-inv1 + inv2) - x
 151 // inv1 - (x + inv2)  =>  ( inv1 - inv2) - x
 152 //
 153 Node* IdealLoopTree::reassociate_add_sub(Node* n1, PhaseIdealLoop *phase) {
 154   if (!n1->is_Add() && !n1->is_Sub() || n1->outcnt() == 0) return NULL;
 155   if (is_invariant(n1)) return NULL;
 156   int inv1_idx = is_invariant_addition(n1, phase);
 157   if (!inv1_idx) return NULL;
 158   // Don't mess with add of constant (igvn moves them to expression tree root.)
 159   if (n1->is_Add() && n1->in(2)->is_Con()) return NULL;
 160   Node* inv1 = n1->in(inv1_idx);
 161   Node* n2 = n1->in(3 - inv1_idx);
 162   int inv2_idx = is_invariant_addition(n2, phase);
 163   if (!inv2_idx) return NULL;
 164   Node* x    = n2->in(3 - inv2_idx);
 165   Node* inv2 = n2->in(inv2_idx);
 166 
 167   bool neg_x    = n2->is_Sub() && inv2_idx == 1;
 168   bool neg_inv2 = n2->is_Sub() && inv2_idx == 2;
 169   bool neg_inv1 = n1->is_Sub() && inv1_idx == 2;
 170   if (n1->is_Sub() && inv1_idx == 1) {
 171     neg_x    = !neg_x;
 172     neg_inv2 = !neg_inv2;
 173   }
 174   Node* inv1_c = phase->get_ctrl(inv1);
 175   Node* inv2_c = phase->get_ctrl(inv2);
 176   Node* n_inv1;
 177   if (neg_inv1) {
 178     Node *zero = phase->_igvn.intcon(0); 
 179     phase->set_ctrl(zero, phase->C->root());
 180     n_inv1 = new (phase->C, 3) SubINode(zero, inv1);
 181     phase->register_new_node(n_inv1, inv1_c);
 182   } else {
 183     n_inv1 = inv1;
 184   }
 185   Node* inv;
 186   if (neg_inv2) {
 187     inv = new (phase->C, 3) SubINode(n_inv1, inv2);
 188   } else {
 189     inv = new (phase->C, 3) AddINode(n_inv1, inv2);
 190   }
 191   phase->register_new_node(inv, phase->get_early_ctrl(inv));
 192 
 193   Node* addx;
 194   if (neg_x) {
 195     addx = new (phase->C, 3) SubINode(inv, x);
 196   } else {
 197     addx = new (phase->C, 3) AddINode(x, inv);
 198   }
 199   phase->register_new_node(addx, phase->get_ctrl(x));
 200   phase->_igvn.hash_delete(n1);
 201   phase->_igvn.subsume_node(n1, addx);
 202   return addx;
 203 }
 204 
 205 //---------------------reassociate_invariants-----------------------------
 206 // Reassociate invariant expressions:
 207 void IdealLoopTree::reassociate_invariants(PhaseIdealLoop *phase) {
 208   for (int i = _body.size() - 1; i >= 0; i--) {
 209     Node *n = _body.at(i);
 210     for (int j = 0; j < 5; j++) {
 211       Node* nn = reassociate_add_sub(n, phase);
 212       if (nn == NULL) break;
 213       n = nn; // again
 214     };
 215   }
 216 }
 217 
 218 //------------------------------policy_peeling---------------------------------
 219 // Return TRUE or FALSE if the loop should be peeled or not.  Peel if we can
 220 // make some loop-invariant test (usually a null-check) happen before the loop.
 221 bool IdealLoopTree::policy_peeling( PhaseIdealLoop *phase ) const {
 222   Node *test = ((IdealLoopTree*)this)->tail();
 223   int  body_size = ((IdealLoopTree*)this)->_body.size();
 224   int  uniq      = phase->C->unique();
 225   // Peeling does loop cloning which can result in O(N^2) node construction
 226   if( body_size > 255 /* Prevent overflow for large body_size */
 227       || (body_size * body_size + uniq > MaxNodeLimit) ) {
 228     return false;           // too large to safely clone
 229   }
 230   while( test != _head ) {      // Scan till run off top of loop
 231     if( test->is_If() ) {       // Test?
 232       Node *ctrl = phase->get_ctrl(test->in(1));
 233       if (ctrl->is_top())
 234         return false;           // Found dead test on live IF?  No peeling!
 235       // Standard IF only has one input value to check for loop invariance
 236       assert( test->Opcode() == Op_If || test->Opcode() == Op_CountedLoopEnd, "Check this code when new subtype is added");
 237       // Condition is not a member of this loop?
 238       if( !is_member(phase->get_loop(ctrl)) &&
 239           is_loop_exit(test) )
 240         return true;            // Found reason to peel!
 241     }
 242     // Walk up dominators to loop _head looking for test which is
 243     // executed on every path thru loop.
 244     test = phase->idom(test);
 245   }
 246   return false;
 247 }
 248 
 249 //------------------------------peeled_dom_test_elim---------------------------
 250 // If we got the effect of peeling, either by actually peeling or by making
 251 // a pre-loop which must execute at least once, we can remove all 
 252 // loop-invariant dominated tests in the main body.
 253 void PhaseIdealLoop::peeled_dom_test_elim( IdealLoopTree *loop, Node_List &old_new ) {
 254   bool progress = true;
 255   while( progress ) {
 256     progress = false;           // Reset for next iteration
 257     Node *prev = loop->_head->in(LoopNode::LoopBackControl);//loop->tail();
 258     Node *test = prev->in(0);
 259     while( test != loop->_head ) { // Scan till run off top of loop
 260       
 261       int p_op = prev->Opcode();
 262       if( (p_op == Op_IfFalse || p_op == Op_IfTrue) &&
 263           test->is_If() &&      // Test?
 264           !test->in(1)->is_Con() && // And not already obvious?
 265           // Condition is not a member of this loop?
 266           !loop->is_member(get_loop(get_ctrl(test->in(1))))){
 267         // Walk loop body looking for instances of this test
 268         for( uint i = 0; i < loop->_body.size(); i++ ) {
 269           Node *n = loop->_body.at(i);
 270           if( n->is_If() && n->in(1) == test->in(1) /*&& n != loop->tail()->in(0)*/ ) {
 271             // IfNode was dominated by version in peeled loop body
 272             progress = true;
 273             dominated_by( old_new[prev->_idx], n );
 274           }
 275         }
 276       }
 277       prev = test;
 278       test = idom(test);
 279     } // End of scan tests in loop
 280 
 281   } // End of while( progress )
 282 }
 283 
 284 //------------------------------do_peeling-------------------------------------
 285 // Peel the first iteration of the given loop.  
 286 // Step 1: Clone the loop body.  The clone becomes the peeled iteration.
 287 //         The pre-loop illegally has 2 control users (old & new loops).
 288 // Step 2: Make the old-loop fall-in edges point to the peeled iteration.
 289 //         Do this by making the old-loop fall-in edges act as if they came
 290 //         around the loopback from the prior iteration (follow the old-loop
 291 //         backedges) and then map to the new peeled iteration.  This leaves
 292 //         the pre-loop with only 1 user (the new peeled iteration), but the
 293 //         peeled-loop backedge has 2 users.
 294 // Step 3: Cut the backedge on the clone (so its not a loop) and remove the
 295 //         extra backedge user.
 296 void PhaseIdealLoop::do_peeling( IdealLoopTree *loop, Node_List &old_new ) {
 297 
 298   C->set_major_progress();
 299   // Peeling a 'main' loop in a pre/main/post situation obfuscates the
 300   // 'pre' loop from the main and the 'pre' can no longer have it's
 301   // iterations adjusted.  Therefore, we need to declare this loop as
 302   // no longer a 'main' loop; it will need new pre and post loops before
 303   // we can do further RCE.
 304   Node *h = loop->_head;
 305   if( h->is_CountedLoop() ) {
 306     CountedLoopNode *cl = h->as_CountedLoop();
 307     assert(cl->trip_count() > 0, "peeling a fully unrolled loop");
 308     cl->set_trip_count(cl->trip_count() - 1);
 309     if( cl->is_main_loop() ) {
 310       cl->set_normal_loop();
 311 #ifndef PRODUCT
 312       if( PrintOpto && VerifyLoopOptimizations ) {
 313         tty->print("Peeling a 'main' loop; resetting to 'normal' ");
 314         loop->dump_head();
 315       }
 316 #endif
 317     }
 318   }
 319 
 320   // Step 1: Clone the loop body.  The clone becomes the peeled iteration.
 321   //         The pre-loop illegally has 2 control users (old & new loops).
 322   clone_loop( loop, old_new, dom_depth(loop->_head) );
 323 
 324 
 325   // Step 2: Make the old-loop fall-in edges point to the peeled iteration.
 326   //         Do this by making the old-loop fall-in edges act as if they came
 327   //         around the loopback from the prior iteration (follow the old-loop
 328   //         backedges) and then map to the new peeled iteration.  This leaves
 329   //         the pre-loop with only 1 user (the new peeled iteration), but the
 330   //         peeled-loop backedge has 2 users.
 331   for (DUIterator_Fast jmax, j = loop->_head->fast_outs(jmax); j < jmax; j++) {
 332     Node* old = loop->_head->fast_out(j);
 333     if( old->in(0) == loop->_head && old->req() == 3 &&
 334         (old->is_Loop() || old->is_Phi()) ) {
 335       Node *new_exit_value = old_new[old->in(LoopNode::LoopBackControl)->_idx];
 336       if( !new_exit_value )     // Backedge value is ALSO loop invariant?
 337         // Then loop body backedge value remains the same.
 338         new_exit_value = old->in(LoopNode::LoopBackControl);
 339       _igvn.hash_delete(old);
 340       old->set_req(LoopNode::EntryControl, new_exit_value);
 341     }
 342   }
 343   
 344 
 345   // Step 3: Cut the backedge on the clone (so its not a loop) and remove the
 346   //         extra backedge user.
 347   Node *nnn = old_new[loop->_head->_idx];
 348   _igvn.hash_delete(nnn);
 349   nnn->set_req(LoopNode::LoopBackControl, C->top());
 350   for (DUIterator_Fast j2max, j2 = nnn->fast_outs(j2max); j2 < j2max; j2++) {
 351     Node* use = nnn->fast_out(j2);
 352     if( use->in(0) == nnn && use->req() == 3 && use->is_Phi() ) {
 353       _igvn.hash_delete(use);
 354       use->set_req(LoopNode::LoopBackControl, C->top());
 355     }
 356   }
 357 
 358 
 359   // Step 4: Correct dom-depth info.  Set to loop-head depth.
 360   int dd = dom_depth(loop->_head);
 361   set_idom(loop->_head, loop->_head->in(1), dd);
 362   for (uint j3 = 0; j3 < loop->_body.size(); j3++) {
 363     Node *old = loop->_body.at(j3);
 364     Node *nnn = old_new[old->_idx];
 365     if (!has_ctrl(nnn))
 366       set_idom(nnn, idom(nnn), dd-1);
 367     // While we're at it, remove any SafePoints from the peeled code
 368     if( old->Opcode() == Op_SafePoint ) {
 369       Node *nnn = old_new[old->_idx];
 370       lazy_replace(nnn,nnn->in(TypeFunc::Control));
 371     }
 372   }
 373 
 374   // Now force out all loop-invariant dominating tests.  The optimizer 
 375   // finds some, but we _know_ they are all useless.
 376   peeled_dom_test_elim(loop,old_new);
 377 
 378   loop->record_for_igvn();
 379 }
 380 
 381 //------------------------------policy_maximally_unroll------------------------
 382 // Return exact loop trip count, or 0 if not maximally unrolling
 383 bool IdealLoopTree::policy_maximally_unroll( PhaseIdealLoop *phase ) const {
 384   CountedLoopNode *cl = _head->as_CountedLoop();
 385   assert( cl->is_normal_loop(), "" );
 386 
 387   Node *init_n = cl->init_trip();
 388   Node *limit_n = cl->limit();
 389 
 390   // Non-constant bounds
 391   if( init_n   == NULL || !init_n->is_Con()  ||
 392       limit_n  == NULL || !limit_n->is_Con() ||
 393       // protect against stride not being a constant
 394       !cl->stride_is_con() ) {
 395     return false;
 396   }
 397   int init   = init_n->get_int();
 398   int limit  = limit_n->get_int();
 399   int span   = limit - init;
 400   int stride = cl->stride_con();
 401 
 402   if (init >= limit || stride > span) {
 403     // return a false (no maximally unroll) and the regular unroll/peel
 404     // route will make a small mess which CCP will fold away.
 405     return false;
 406   }
 407   uint trip_count = span/stride;   // trip_count can be greater than 2 Gig.
 408   assert( (int)trip_count*stride == span, "must divide evenly" );
 409 
 410   // Real policy: if we maximally unroll, does it get too big?
 411   // Allow the unrolled mess to get larger than standard loop
 412   // size.  After all, it will no longer be a loop.
 413   uint body_size    = _body.size();
 414   uint unroll_limit = (uint)LoopUnrollLimit * 4;
 415   assert( (intx)unroll_limit == LoopUnrollLimit * 4, "LoopUnrollLimit must fit in 32bits");
 416   cl->set_trip_count(trip_count);
 417   if( trip_count <= unroll_limit && body_size <= unroll_limit ) {
 418     uint new_body_size = body_size * trip_count;
 419     if (new_body_size <= unroll_limit &&
 420         body_size == new_body_size / trip_count &&
 421         // Unrolling can result in a large amount of node construction
 422         new_body_size < MaxNodeLimit - phase->C->unique()) {
 423       return true;    // maximally unroll
 424     }
 425   }
 426 
 427   return false;               // Do not maximally unroll
 428 }
 429 
 430 
 431 //------------------------------policy_unroll----------------------------------
 432 // Return TRUE or FALSE if the loop should be unrolled or not.  Unroll if 
 433 // the loop is a CountedLoop and the body is small enough.
 434 bool IdealLoopTree::policy_unroll( PhaseIdealLoop *phase ) const {
 435 
 436   CountedLoopNode *cl = _head->as_CountedLoop();
 437   assert( cl->is_normal_loop() || cl->is_main_loop(), "" );
 438 
 439   // protect against stride not being a constant
 440   if( !cl->stride_is_con() ) return false;
 441 
 442   // protect against over-unrolling
 443   if( cl->trip_count() <= 1 ) return false;
 444 
 445   int future_unroll_ct = cl->unrolled_count() * 2;
 446  
 447   // Don't unroll if the next round of unrolling would push us
 448   // over the expected trip count of the loop.  One is subtracted
 449   // from the expected trip count because the pre-loop normally
 450   // executes 1 iteration.
 451   if (UnrollLimitForProfileCheck > 0 &&
 452       cl->profile_trip_cnt() != COUNT_UNKNOWN &&
 453       future_unroll_ct        > UnrollLimitForProfileCheck &&
 454       (float)future_unroll_ct > cl->profile_trip_cnt() - 1.0) {
 455     return false;
 456   }
 457   
 458   // When unroll count is greater than LoopUnrollMin, don't unroll if:
 459   //   the residual iterations are more than 10% of the trip count
 460   //   and rounds of "unroll,optimize" are not making significant progress
 461   //   Progress defined as current size less than 20% larger than previous size.
 462   if (UseSuperWord && cl->node_count_before_unroll() > 0 &&
 463       future_unroll_ct > LoopUnrollMin &&
 464       (future_unroll_ct - 1) * 10.0 > cl->profile_trip_cnt() &&
 465       1.2 * cl->node_count_before_unroll() < (double)_body.size()) {
 466     return false;
 467   }
 468 
 469   Node *init_n = cl->init_trip();
 470   Node *limit_n = cl->limit();
 471   // Non-constant bounds.
 472   // Protect against over-unrolling when init or/and limit are not constant
 473   // (so that trip_count's init value is maxint) but iv range is known.
 474   if( init_n   == NULL || !init_n->is_Con()  ||
 475       limit_n  == NULL || !limit_n->is_Con() ) {
 476     Node* phi = cl->phi();
 477     if( phi != NULL ) {
 478       assert(phi->is_Phi() && phi->in(0) == _head, "Counted loop should have iv phi.");
 479       const TypeInt* iv_type = phase->_igvn.type(phi)->is_int();
 480       int next_stride = cl->stride_con() * 2; // stride after this unroll
 481       if( next_stride > 0 ) {
 482         if( iv_type->_lo + next_stride <= iv_type->_lo || // overflow
 483             iv_type->_lo + next_stride >  iv_type->_hi ) {
 484           return false;  // over-unrolling
 485         }
 486       } else if( next_stride < 0 ) {
 487         if( iv_type->_hi + next_stride >= iv_type->_hi || // overflow
 488             iv_type->_hi + next_stride <  iv_type->_lo ) {
 489           return false;  // over-unrolling
 490         }
 491       }
 492     }
 493   }
 494 
 495   // Adjust body_size to determine if we unroll or not
 496   uint body_size = _body.size();
 497   // Key test to unroll CaffeineMark's Logic test
 498   int xors_in_loop = 0;
 499   // Also count ModL, DivL and MulL which expand mightly
 500   for( uint k = 0; k < _body.size(); k++ ) {
 501     switch( _body.at(k)->Opcode() ) {
 502     case Op_XorI: xors_in_loop++; break; // CaffeineMark's Logic test
 503     case Op_ModL: body_size += 30; break;
 504     case Op_DivL: body_size += 30; break;
 505     case Op_MulL: body_size += 10; break;
 506     }
 507   }
 508 
 509   // Check for being too big
 510   if( body_size > (uint)LoopUnrollLimit ) { 
 511     if( xors_in_loop >= 4 && body_size < (uint)LoopUnrollLimit*4) return true;
 512     // Normal case: loop too big
 513     return false;
 514   }
 515   
 516   // Check for stride being a small enough constant
 517   if( abs(cl->stride_con()) > (1<<3) ) return false;
 518 
 519   // Unroll once!  (Each trip will soon do double iterations)
 520   return true;
 521 }
 522 
 523 //------------------------------policy_align-----------------------------------
 524 // Return TRUE or FALSE if the loop should be cache-line aligned.  Gather the
 525 // expression that does the alignment.  Note that only one array base can be
 526 // aligned in a loop (unless the VM guarentees mutual alignment).  Note that
 527 // if we vectorize short memory ops into longer memory ops, we may want to
 528 // increase alignment.
 529 bool IdealLoopTree::policy_align( PhaseIdealLoop *phase ) const {
 530   return false;
 531 }
 532 
 533 //------------------------------policy_range_check-----------------------------
 534 // Return TRUE or FALSE if the loop should be range-check-eliminated.
 535 // Actually we do iteration-splitting, a more powerful form of RCE.
 536 bool IdealLoopTree::policy_range_check( PhaseIdealLoop *phase ) const {
 537   if( !RangeCheckElimination ) return false;
 538 
 539   CountedLoopNode *cl = _head->as_CountedLoop();
 540   // If we unrolled with no intention of doing RCE and we later
 541   // changed our minds, we got no pre-loop.  Either we need to
 542   // make a new pre-loop, or we gotta disallow RCE.
 543   if( cl->is_main_no_pre_loop() ) return false; // Disallowed for now.
 544   Node *trip_counter = cl->phi();
 545 
 546   // Check loop body for tests of trip-counter plus loop-invariant vs
 547   // loop-invariant.
 548   for( uint i = 0; i < _body.size(); i++ ) {
 549     Node *iff = _body[i];
 550     if( iff->Opcode() == Op_If ) { // Test?
 551 
 552       // Comparing trip+off vs limit
 553       Node *bol = iff->in(1);
 554       if( bol->req() != 2 ) continue; // dead constant test
 555       Node *cmp = bol->in(1);
 556 
 557       Node *rc_exp = cmp->in(1);
 558       Node *limit = cmp->in(2);
 559 
 560       Node *limit_c = phase->get_ctrl(limit);
 561       if( limit_c == phase->C->top() ) 
 562         return false;           // Found dead test on live IF?  No RCE!
 563       if( is_member(phase->get_loop(limit_c) ) ) {
 564         // Compare might have operands swapped; commute them
 565         rc_exp = cmp->in(2);
 566         limit  = cmp->in(1);
 567         limit_c = phase->get_ctrl(limit);
 568         if( is_member(phase->get_loop(limit_c) ) ) 
 569           continue;             // Both inputs are loop varying; cannot RCE
 570       }
 571 
 572       if (!phase->is_scaled_iv_plus_offset(rc_exp, trip_counter, NULL, NULL)) {
 573         continue;
 574       }
 575       // Yeah!  Found a test like 'trip+off vs limit'
 576       // Test is an IfNode, has 2 projections.  If BOTH are in the loop
 577       // we need loop unswitching instead of iteration splitting.
 578       if( is_loop_exit(iff) )
 579         return true;            // Found reason to split iterations
 580     } // End of is IF
 581   }
 582 
 583   return false;
 584 }
 585 
 586 //------------------------------policy_peel_only-------------------------------
 587 // Return TRUE or FALSE if the loop should NEVER be RCE'd or aligned.  Useful
 588 // for unrolling loops with NO array accesses.
 589 bool IdealLoopTree::policy_peel_only( PhaseIdealLoop *phase ) const {
 590 
 591   for( uint i = 0; i < _body.size(); i++ )
 592     if( _body[i]->is_Mem() )
 593       return false;
 594 
 595   // No memory accesses at all!
 596   return true;
 597 }
 598 
 599 //------------------------------clone_up_backedge_goo--------------------------
 600 // If Node n lives in the back_ctrl block and cannot float, we clone a private 
 601 // version of n in preheader_ctrl block and return that, otherwise return n.
 602 Node *PhaseIdealLoop::clone_up_backedge_goo( Node *back_ctrl, Node *preheader_ctrl, Node *n ) {
 603   if( get_ctrl(n) != back_ctrl ) return n;
 604 
 605   Node *x = NULL;               // If required, a clone of 'n'
 606   // Check for 'n' being pinned in the backedge.
 607   if( n->in(0) && n->in(0) == back_ctrl ) {
 608     x = n->clone();             // Clone a copy of 'n' to preheader
 609     x->set_req( 0, preheader_ctrl ); // Fix x's control input to preheader
 610   }
 611 
 612   // Recursive fixup any other input edges into x.
 613   // If there are no changes we can just return 'n', otherwise
 614   // we need to clone a private copy and change it.
 615   for( uint i = 1; i < n->req(); i++ ) {
 616     Node *g = clone_up_backedge_goo( back_ctrl, preheader_ctrl, n->in(i) );
 617     if( g != n->in(i) ) {
 618       if( !x )
 619         x = n->clone();
 620       x->set_req(i, g);
 621     }
 622   }
 623   if( x ) {                     // x can legally float to pre-header location
 624     register_new_node( x, preheader_ctrl );
 625     return x;
 626   } else {                      // raise n to cover LCA of uses
 627     set_ctrl( n, find_non_split_ctrl(back_ctrl->in(0)) );
 628   }
 629   return n;
 630 }
 631 
 632 //------------------------------insert_pre_post_loops--------------------------
 633 // Insert pre and post loops.  If peel_only is set, the pre-loop can not have
 634 // more iterations added.  It acts as a 'peel' only, no lower-bound RCE, no
 635 // alignment.  Useful to unroll loops that do no array accesses.
 636 void PhaseIdealLoop::insert_pre_post_loops( IdealLoopTree *loop, Node_List &old_new, bool peel_only ) {
 637 
 638   C->set_major_progress();
 639 
 640   // Find common pieces of the loop being guarded with pre & post loops
 641   CountedLoopNode *main_head = loop->_head->as_CountedLoop();
 642   assert( main_head->is_normal_loop(), "" );
 643   CountedLoopEndNode *main_end = main_head->loopexit();
 644   assert( main_end->outcnt() == 2, "1 true, 1 false path only" );
 645   uint dd_main_head = dom_depth(main_head);
 646   uint max = main_head->outcnt();
 647 
 648   Node *pre_header= main_head->in(LoopNode::EntryControl);
 649   Node *init      = main_head->init_trip();
 650   Node *incr      = main_end ->incr();
 651   Node *limit     = main_end ->limit();
 652   Node *stride    = main_end ->stride();
 653   Node *cmp       = main_end ->cmp_node();
 654   BoolTest::mask b_test = main_end->test_trip();
 655 
 656   // Need only 1 user of 'bol' because I will be hacking the loop bounds.
 657   Node *bol = main_end->in(CountedLoopEndNode::TestValue);
 658   if( bol->outcnt() != 1 ) {
 659     bol = bol->clone();
 660     register_new_node(bol,main_end->in(CountedLoopEndNode::TestControl));
 661     _igvn.hash_delete(main_end);
 662     main_end->set_req(CountedLoopEndNode::TestValue, bol);
 663   }
 664   // Need only 1 user of 'cmp' because I will be hacking the loop bounds.
 665   if( cmp->outcnt() != 1 ) {
 666     cmp = cmp->clone();
 667     register_new_node(cmp,main_end->in(CountedLoopEndNode::TestControl));
 668     _igvn.hash_delete(bol);
 669     bol->set_req(1, cmp);
 670   }
 671 
 672   //------------------------------
 673   // Step A: Create Post-Loop.
 674   Node* main_exit = main_end->proj_out(false);
 675   assert( main_exit->Opcode() == Op_IfFalse, "" );
 676   int dd_main_exit = dom_depth(main_exit);
 677 
 678   // Step A1: Clone the loop body.  The clone becomes the post-loop.  The main
 679   // loop pre-header illegally has 2 control users (old & new loops).
 680   clone_loop( loop, old_new, dd_main_exit );
 681   assert( old_new[main_end ->_idx]->Opcode() == Op_CountedLoopEnd, "" );
 682   CountedLoopNode *post_head = old_new[main_head->_idx]->as_CountedLoop();
 683   post_head->set_post_loop(main_head);
 684 
 685   // Build the main-loop normal exit.
 686   IfFalseNode *new_main_exit = new (C, 1) IfFalseNode(main_end);
 687   _igvn.register_new_node_with_optimizer( new_main_exit );
 688   set_idom(new_main_exit, main_end, dd_main_exit );
 689   set_loop(new_main_exit, loop->_parent);
 690 
 691   // Step A2: Build a zero-trip guard for the post-loop.  After leaving the
 692   // main-loop, the post-loop may not execute at all.  We 'opaque' the incr
 693   // (the main-loop trip-counter exit value) because we will be changing
 694   // the exit value (via unrolling) so we cannot constant-fold away the zero
 695   // trip guard until all unrolling is done.
 696   Node *zer_opaq = new (C, 2) Opaque1Node(incr);
 697   Node *zer_cmp  = new (C, 3) CmpINode( zer_opaq, limit );
 698   Node *zer_bol  = new (C, 2) BoolNode( zer_cmp, b_test );
 699   register_new_node( zer_opaq, new_main_exit );
 700   register_new_node( zer_cmp , new_main_exit );
 701   register_new_node( zer_bol , new_main_exit );
 702 
 703   // Build the IfNode
 704   IfNode *zer_iff = new (C, 2) IfNode( new_main_exit, zer_bol, PROB_FAIR, COUNT_UNKNOWN );
 705   _igvn.register_new_node_with_optimizer( zer_iff );
 706   set_idom(zer_iff, new_main_exit, dd_main_exit);
 707   set_loop(zer_iff, loop->_parent);
 708 
 709   // Plug in the false-path, taken if we need to skip post-loop
 710   _igvn.hash_delete( main_exit );
 711   main_exit->set_req(0, zer_iff);
 712   _igvn._worklist.push(main_exit);
 713   set_idom(main_exit, zer_iff, dd_main_exit);
 714   set_idom(main_exit->unique_out(), zer_iff, dd_main_exit);
 715   // Make the true-path, must enter the post loop
 716   Node *zer_taken = new (C, 1) IfTrueNode( zer_iff );
 717   _igvn.register_new_node_with_optimizer( zer_taken );
 718   set_idom(zer_taken, zer_iff, dd_main_exit);
 719   set_loop(zer_taken, loop->_parent);
 720   // Plug in the true path
 721   _igvn.hash_delete( post_head );
 722   post_head->set_req(LoopNode::EntryControl, zer_taken);
 723   set_idom(post_head, zer_taken, dd_main_exit);
 724 
 725   // Step A3: Make the fall-in values to the post-loop come from the
 726   // fall-out values of the main-loop.
 727   for (DUIterator_Fast imax, i = main_head->fast_outs(imax); i < imax; i++) {
 728     Node* main_phi = main_head->fast_out(i);
 729     if( main_phi->is_Phi() && main_phi->in(0) == main_head && main_phi->outcnt() >0 ) {
 730       Node *post_phi = old_new[main_phi->_idx];
 731       Node *fallmain  = clone_up_backedge_goo(main_head->back_control(),
 732                                               post_head->init_control(),
 733                                               main_phi->in(LoopNode::LoopBackControl));
 734       _igvn.hash_delete(post_phi);
 735       post_phi->set_req( LoopNode::EntryControl, fallmain );
 736     }
 737   }
 738 
 739   // Update local caches for next stanza
 740   main_exit = new_main_exit;
 741 
 742 
 743   //------------------------------
 744   // Step B: Create Pre-Loop.
 745 
 746   // Step B1: Clone the loop body.  The clone becomes the pre-loop.  The main
 747   // loop pre-header illegally has 2 control users (old & new loops).
 748   clone_loop( loop, old_new, dd_main_head );
 749   CountedLoopNode*    pre_head = old_new[main_head->_idx]->as_CountedLoop();
 750   CountedLoopEndNode* pre_end  = old_new[main_end ->_idx]->as_CountedLoopEnd();
 751   pre_head->set_pre_loop(main_head);
 752   Node *pre_incr = old_new[incr->_idx];
 753 
 754   // Find the pre-loop normal exit.
 755   Node* pre_exit = pre_end->proj_out(false);
 756   assert( pre_exit->Opcode() == Op_IfFalse, "" );
 757   IfFalseNode *new_pre_exit = new (C, 1) IfFalseNode(pre_end);
 758   _igvn.register_new_node_with_optimizer( new_pre_exit );
 759   set_idom(new_pre_exit, pre_end, dd_main_head);
 760   set_loop(new_pre_exit, loop->_parent);
 761 
 762   // Step B2: Build a zero-trip guard for the main-loop.  After leaving the
 763   // pre-loop, the main-loop may not execute at all.  Later in life this
 764   // zero-trip guard will become the minimum-trip guard when we unroll
 765   // the main-loop.
 766   Node *min_opaq = new (C, 2) Opaque1Node(limit);
 767   Node *min_cmp  = new (C, 3) CmpINode( pre_incr, min_opaq );
 768   Node *min_bol  = new (C, 2) BoolNode( min_cmp, b_test );
 769   register_new_node( min_opaq, new_pre_exit );
 770   register_new_node( min_cmp , new_pre_exit );
 771   register_new_node( min_bol , new_pre_exit );
 772 
 773   // Build the IfNode
 774   IfNode *min_iff = new (C, 2) IfNode( new_pre_exit, min_bol, PROB_FAIR, COUNT_UNKNOWN );
 775   _igvn.register_new_node_with_optimizer( min_iff );
 776   set_idom(min_iff, new_pre_exit, dd_main_head);
 777   set_loop(min_iff, loop->_parent);
 778 
 779   // Plug in the false-path, taken if we need to skip main-loop
 780   _igvn.hash_delete( pre_exit );
 781   pre_exit->set_req(0, min_iff);
 782   set_idom(pre_exit, min_iff, dd_main_head);
 783   set_idom(pre_exit->unique_out(), min_iff, dd_main_head);
 784   // Make the true-path, must enter the main loop
 785   Node *min_taken = new (C, 1) IfTrueNode( min_iff );
 786   _igvn.register_new_node_with_optimizer( min_taken );
 787   set_idom(min_taken, min_iff, dd_main_head);
 788   set_loop(min_taken, loop->_parent);
 789   // Plug in the true path
 790   _igvn.hash_delete( main_head );
 791   main_head->set_req(LoopNode::EntryControl, min_taken);
 792   set_idom(main_head, min_taken, dd_main_head);
 793 
 794   // Step B3: Make the fall-in values to the main-loop come from the
 795   // fall-out values of the pre-loop.
 796   for (DUIterator_Fast i2max, i2 = main_head->fast_outs(i2max); i2 < i2max; i2++) {
 797     Node* main_phi = main_head->fast_out(i2);
 798     if( main_phi->is_Phi() && main_phi->in(0) == main_head && main_phi->outcnt() > 0 ) {
 799       Node *pre_phi = old_new[main_phi->_idx];
 800       Node *fallpre  = clone_up_backedge_goo(pre_head->back_control(),
 801                                              main_head->init_control(),
 802                                              pre_phi->in(LoopNode::LoopBackControl));
 803       _igvn.hash_delete(main_phi);
 804       main_phi->set_req( LoopNode::EntryControl, fallpre );
 805     }
 806   }
 807 
 808   // Step B4: Shorten the pre-loop to run only 1 iteration (for now).
 809   // RCE and alignment may change this later.
 810   Node *cmp_end = pre_end->cmp_node();
 811   assert( cmp_end->in(2) == limit, "" );
 812   Node *pre_limit = new (C, 3) AddINode( init, stride );
 813 
 814   // Save the original loop limit in this Opaque1 node for
 815   // use by range check elimination.
 816   Node *pre_opaq  = new (C, 3) Opaque1Node(pre_limit, limit);
 817 
 818   register_new_node( pre_limit, pre_head->in(0) );
 819   register_new_node( pre_opaq , pre_head->in(0) );
 820 
 821   // Since no other users of pre-loop compare, I can hack limit directly
 822   assert( cmp_end->outcnt() == 1, "no other users" );
 823   _igvn.hash_delete(cmp_end);
 824   cmp_end->set_req(2, peel_only ? pre_limit : pre_opaq);
 825 
 826   // Special case for not-equal loop bounds:
 827   // Change pre loop test, main loop test, and the
 828   // main loop guard test to use lt or gt depending on stride
 829   // direction:
 830   // positive stride use <
 831   // negative stride use >
 832 
 833   if (pre_end->in(CountedLoopEndNode::TestValue)->as_Bool()->_test._test == BoolTest::ne) {
 834 
 835     BoolTest::mask new_test = (main_end->stride_con() > 0) ? BoolTest::lt : BoolTest::gt;
 836     // Modify pre loop end condition
 837     Node* pre_bol = pre_end->in(CountedLoopEndNode::TestValue)->as_Bool();
 838     BoolNode* new_bol0 = new (C, 2) BoolNode(pre_bol->in(1), new_test);
 839     register_new_node( new_bol0, pre_head->in(0) );
 840     _igvn.hash_delete(pre_end);
 841     pre_end->set_req(CountedLoopEndNode::TestValue, new_bol0);
 842     // Modify main loop guard condition
 843     assert(min_iff->in(CountedLoopEndNode::TestValue) == min_bol, "guard okay");
 844     BoolNode* new_bol1 = new (C, 2) BoolNode(min_bol->in(1), new_test);
 845     register_new_node( new_bol1, new_pre_exit );
 846     _igvn.hash_delete(min_iff);
 847     min_iff->set_req(CountedLoopEndNode::TestValue, new_bol1);
 848     // Modify main loop end condition
 849     BoolNode* main_bol = main_end->in(CountedLoopEndNode::TestValue)->as_Bool();
 850     BoolNode* new_bol2 = new (C, 2) BoolNode(main_bol->in(1), new_test);
 851     register_new_node( new_bol2, main_end->in(CountedLoopEndNode::TestControl) );
 852     _igvn.hash_delete(main_end);
 853     main_end->set_req(CountedLoopEndNode::TestValue, new_bol2);
 854   }
 855 
 856   // Flag main loop
 857   main_head->set_main_loop();
 858   if( peel_only ) main_head->set_main_no_pre_loop();
 859 
 860   // It's difficult to be precise about the trip-counts
 861   // for the pre/post loops.  They are usually very short,
 862   // so guess that 4 trips is a reasonable value.
 863   post_head->set_profile_trip_cnt(4.0);
 864   pre_head->set_profile_trip_cnt(4.0);
 865 
 866   // Now force out all loop-invariant dominating tests.  The optimizer 
 867   // finds some, but we _know_ they are all useless.
 868   peeled_dom_test_elim(loop,old_new);
 869 }
 870 
 871 //------------------------------is_invariant-----------------------------
 872 // Return true if n is invariant
 873 bool IdealLoopTree::is_invariant(Node* n) const {
 874   Node *n_c = _phase->get_ctrl(n);
 875   if (n_c->is_top()) return false;
 876   return !is_member(_phase->get_loop(n_c));
 877 }
 878 
 879 
 880 //------------------------------do_unroll--------------------------------------
 881 // Unroll the loop body one step - make each trip do 2 iterations.
 882 void PhaseIdealLoop::do_unroll( IdealLoopTree *loop, Node_List &old_new, bool adjust_min_trip ) {
 883   assert( LoopUnrollLimit, "" );
 884 #ifndef PRODUCT
 885   if( PrintOpto && VerifyLoopOptimizations ) {
 886     tty->print("Unrolling ");
 887     loop->dump_head();
 888   }
 889 #endif
 890   CountedLoopNode *loop_head = loop->_head->as_CountedLoop();
 891   CountedLoopEndNode *loop_end = loop_head->loopexit();
 892   assert( loop_end, "" );
 893 
 894   // Remember loop node count before unrolling to detect
 895   // if rounds of unroll,optimize are making progress
 896   loop_head->set_node_count_before_unroll(loop->_body.size());
 897 
 898   Node *ctrl  = loop_head->in(LoopNode::EntryControl);
 899   Node *limit = loop_head->limit();
 900   Node *init  = loop_head->init_trip();
 901   Node *strid = loop_head->stride();
 902 
 903   Node *opaq = NULL;
 904   if( adjust_min_trip ) {       // If not maximally unrolling, need adjustment
 905     assert( loop_head->is_main_loop(), "" );
 906     assert( ctrl->Opcode() == Op_IfTrue || ctrl->Opcode() == Op_IfFalse, "" );
 907     Node *iff = ctrl->in(0);
 908     assert( iff->Opcode() == Op_If, "" );
 909     Node *bol = iff->in(1);
 910     assert( bol->Opcode() == Op_Bool, "" );
 911     Node *cmp = bol->in(1);
 912     assert( cmp->Opcode() == Op_CmpI, "" );
 913     opaq = cmp->in(2);
 914     // Occasionally it's possible for a pre-loop Opaque1 node to be
 915     // optimized away and then another round of loop opts attempted.
 916     // We can not optimize this particular loop in that case.
 917     if( opaq->Opcode() != Op_Opaque1 )
 918       return;                   // Cannot find pre-loop!  Bail out!
 919   }
 920 
 921   C->set_major_progress();
 922 
 923   // Adjust max trip count. The trip count is intentionally rounded
 924   // down here (e.g. 15-> 7-> 3-> 1) because if we unwittingly over-unroll,
 925   // the main, unrolled, part of the loop will never execute as it is protected
 926   // by the min-trip test.  See bug 4834191 for a case where we over-unrolled
 927   // and later determined that part of the unrolled loop was dead.
 928   loop_head->set_trip_count(loop_head->trip_count() / 2);
 929 
 930   // Double the count of original iterations in the unrolled loop body.
 931   loop_head->double_unrolled_count();
 932 
 933   // -----------
 934   // Step 2: Cut back the trip counter for an unroll amount of 2.
 935   // Loop will normally trip (limit - init)/stride_con.  Since it's a
 936   // CountedLoop this is exact (stride divides limit-init exactly).
 937   // We are going to double the loop body, so we want to knock off any
 938   // odd iteration: (trip_cnt & ~1).  Then back compute a new limit.
 939   Node *span = new (C, 3) SubINode( limit, init );
 940   register_new_node( span, ctrl );
 941   Node *trip = new (C, 3) DivINode( 0, span, strid );
 942   register_new_node( trip, ctrl );
 943   Node *mtwo = _igvn.intcon(-2);
 944   set_ctrl(mtwo, C->root());
 945   Node *rond = new (C, 3) AndINode( trip, mtwo );
 946   register_new_node( rond, ctrl );
 947   Node *spn2 = new (C, 3) MulINode( rond, strid );
 948   register_new_node( spn2, ctrl );
 949   Node *lim2 = new (C, 3) AddINode( spn2, init );
 950   register_new_node( lim2, ctrl );
 951 
 952   // Hammer in the new limit
 953   Node *ctrl2 = loop_end->in(0);
 954   Node *cmp2 = new (C, 3) CmpINode( loop_head->incr(), lim2 );
 955   register_new_node( cmp2, ctrl2 );
 956   Node *bol2 = new (C, 2) BoolNode( cmp2, loop_end->test_trip() );
 957   register_new_node( bol2, ctrl2 );
 958   _igvn.hash_delete(loop_end);
 959   loop_end->set_req(CountedLoopEndNode::TestValue, bol2);
 960 
 961   // Step 3: Find the min-trip test guaranteed before a 'main' loop.
 962   // Make it a 1-trip test (means at least 2 trips).
 963   if( adjust_min_trip ) {
 964     // Guard test uses an 'opaque' node which is not shared.  Hence I
 965     // can edit it's inputs directly.  Hammer in the new limit for the
 966     // minimum-trip guard.
 967     assert( opaq->outcnt() == 1, "" );
 968     _igvn.hash_delete(opaq);
 969     opaq->set_req(1, lim2);
 970   }
 971 
 972   // ---------
 973   // Step 4: Clone the loop body.  Move it inside the loop.  This loop body 
 974   // represents the odd iterations; since the loop trips an even number of
 975   // times its backedge is never taken.  Kill the backedge.
 976   uint dd = dom_depth(loop_head);
 977   clone_loop( loop, old_new, dd );
 978 
 979   // Make backedges of the clone equal to backedges of the original.
 980   // Make the fall-in from the original come from the fall-out of the clone.
 981   for (DUIterator_Fast jmax, j = loop_head->fast_outs(jmax); j < jmax; j++) {
 982     Node* phi = loop_head->fast_out(j);
 983     if( phi->is_Phi() && phi->in(0) == loop_head && phi->outcnt() > 0 ) {
 984       Node *newphi = old_new[phi->_idx];
 985       _igvn.hash_delete( phi );
 986       _igvn.hash_delete( newphi );
 987 
 988       phi   ->set_req(LoopNode::   EntryControl, newphi->in(LoopNode::LoopBackControl));
 989       newphi->set_req(LoopNode::LoopBackControl, phi   ->in(LoopNode::LoopBackControl));
 990       phi   ->set_req(LoopNode::LoopBackControl, C->top());
 991     }
 992   }  
 993   Node *clone_head = old_new[loop_head->_idx];
 994   _igvn.hash_delete( clone_head );
 995   loop_head ->set_req(LoopNode::   EntryControl, clone_head->in(LoopNode::LoopBackControl));
 996   clone_head->set_req(LoopNode::LoopBackControl, loop_head ->in(LoopNode::LoopBackControl));
 997   loop_head ->set_req(LoopNode::LoopBackControl, C->top());
 998   loop->_head = clone_head;     // New loop header
 999 
1000   set_idom(loop_head,  loop_head ->in(LoopNode::EntryControl), dd);
1001   set_idom(clone_head, clone_head->in(LoopNode::EntryControl), dd);
1002 
1003   // Kill the clone's backedge
1004   Node *newcle = old_new[loop_end->_idx];
1005   _igvn.hash_delete( newcle );
1006   Node *one = _igvn.intcon(1);
1007   set_ctrl(one, C->root());
1008   newcle->set_req(1, one);
1009   // Force clone into same loop body
1010   uint max = loop->_body.size();
1011   for( uint k = 0; k < max; k++ ) {
1012     Node *old = loop->_body.at(k);
1013     Node *nnn = old_new[old->_idx];
1014     loop->_body.push(nnn);
1015     if (!has_ctrl(old))
1016       set_loop(nnn, loop);
1017   }
1018 }
1019 
1020 //------------------------------do_maximally_unroll----------------------------
1021 
1022 void PhaseIdealLoop::do_maximally_unroll( IdealLoopTree *loop, Node_List &old_new ) {
1023   CountedLoopNode *cl = loop->_head->as_CountedLoop();
1024   assert( cl->trip_count() > 0, "");
1025 
1026   // If loop is tripping an odd number of times, peel odd iteration
1027   if( (cl->trip_count() & 1) == 1 ) {
1028     do_peeling( loop, old_new );
1029   }
1030 
1031   // Now its tripping an even number of times remaining.  Double loop body.
1032   // Do not adjust pre-guards; they are not needed and do not exist.
1033   if( cl->trip_count() > 0 ) { 
1034     do_unroll( loop, old_new, false );
1035   }
1036 }
1037 
1038 //------------------------------dominates_backedge---------------------------------
1039 // Returns true if ctrl is executed on every complete iteration
1040 bool IdealLoopTree::dominates_backedge(Node* ctrl) {
1041   assert(ctrl->is_CFG(), "must be control");
1042   Node* backedge = _head->as_Loop()->in(LoopNode::LoopBackControl);
1043   return _phase->dom_lca_internal(ctrl, backedge) == ctrl;
1044 }
1045 
1046 //------------------------------add_constraint---------------------------------
1047 // Constrain the main loop iterations so the condition:
1048 //    scale_con * I + offset  <  limit
1049 // always holds true.  That is, either increase the number of iterations in
1050 // the pre-loop or the post-loop until the condition holds true in the main 
1051 // loop.  Stride, scale, offset and limit are all loop invariant.  Further, 
1052 // stride and scale are constants (offset and limit often are).
1053 void PhaseIdealLoop::add_constraint( int stride_con, int scale_con, Node *offset, Node *limit, Node *pre_ctrl, Node **pre_limit, Node **main_limit ) {
1054 
1055   // Compute "I :: (limit-offset)/scale_con"
1056   Node *con = new (C, 3) SubINode( limit, offset );
1057   register_new_node( con, pre_ctrl );
1058   Node *scale = _igvn.intcon(scale_con);
1059   set_ctrl(scale, C->root());
1060   Node *X = new (C, 3) DivINode( 0, con, scale );
1061   register_new_node( X, pre_ctrl );
1062 
1063   // For positive stride, the pre-loop limit always uses a MAX function 
1064   // and the main loop a MIN function.  For negative stride these are
1065   // reversed.  
1066   
1067   // Also for positive stride*scale the affine function is increasing, so the 
1068   // pre-loop must check for underflow and the post-loop for overflow.
1069   // Negative stride*scale reverses this; pre-loop checks for overflow and
1070   // post-loop for underflow.
1071   if( stride_con*scale_con > 0 ) {
1072     // Compute I < (limit-offset)/scale_con
1073     // Adjust main-loop last iteration to be MIN/MAX(main_loop,X)
1074     *main_limit = (stride_con > 0) 
1075       ? (Node*)(new (C, 3) MinINode( *main_limit, X ))
1076       : (Node*)(new (C, 3) MaxINode( *main_limit, X ));
1077     register_new_node( *main_limit, pre_ctrl );
1078 
1079   } else {
1080     // Compute (limit-offset)/scale_con + SGN(-scale_con) <= I
1081     // Add the negation of the main-loop constraint to the pre-loop.
1082     // See footnote [++] below for a derivation of the limit expression.
1083     Node *incr = _igvn.intcon(scale_con > 0 ? -1 : 1);
1084     set_ctrl(incr, C->root());
1085     Node *adj = new (C, 3) AddINode( X, incr );
1086     register_new_node( adj, pre_ctrl );
1087     *pre_limit = (scale_con > 0)
1088       ? (Node*)new (C, 3) MinINode( *pre_limit, adj )
1089       : (Node*)new (C, 3) MaxINode( *pre_limit, adj );
1090     register_new_node( *pre_limit, pre_ctrl );
1091 
1092 //   [++] Here's the algebra that justifies the pre-loop limit expression:
1093 //   
1094 //   NOT( scale_con * I + offset  <  limit )
1095 //      ==
1096 //   scale_con * I + offset  >=  limit
1097 //      ==
1098 //   SGN(scale_con) * I  >=  (limit-offset)/|scale_con|
1099 //      ==
1100 //   (limit-offset)/|scale_con|   <=  I * SGN(scale_con)
1101 //      ==
1102 //   (limit-offset)/|scale_con|-1  <  I * SGN(scale_con)
1103 //      ==
1104 //   ( if (scale_con > 0) /*common case*/
1105 //       (limit-offset)/scale_con - 1  <  I
1106 //     else  
1107 //       (limit-offset)/scale_con + 1  >  I
1108 //    )
1109 //   ( if (scale_con > 0) /*common case*/
1110 //       (limit-offset)/scale_con + SGN(-scale_con)  <  I
1111 //     else  
1112 //       (limit-offset)/scale_con + SGN(-scale_con)  >  I
1113   }
1114 }
1115 
1116 
1117 //------------------------------is_scaled_iv---------------------------------
1118 // Return true if exp is a constant times an induction var
1119 bool PhaseIdealLoop::is_scaled_iv(Node* exp, Node* iv, int* p_scale) {
1120   if (exp == iv) {
1121     if (p_scale != NULL) {
1122       *p_scale = 1;
1123     }
1124     return true;
1125   }
1126   int opc = exp->Opcode();
1127   if (opc == Op_MulI) {
1128     if (exp->in(1) == iv && exp->in(2)->is_Con()) {
1129       if (p_scale != NULL) {
1130         *p_scale = exp->in(2)->get_int();
1131       }
1132       return true;
1133     }
1134     if (exp->in(2) == iv && exp->in(1)->is_Con()) {
1135       if (p_scale != NULL) {
1136         *p_scale = exp->in(1)->get_int();
1137       }
1138       return true;
1139     }
1140   } else if (opc == Op_LShiftI) {
1141     if (exp->in(1) == iv && exp->in(2)->is_Con()) {
1142       if (p_scale != NULL) {
1143         *p_scale = 1 << exp->in(2)->get_int();
1144       }
1145       return true;
1146     }
1147   }
1148   return false;
1149 }
1150 
1151 //-----------------------------is_scaled_iv_plus_offset------------------------------
1152 // Return true if exp is a simple induction variable expression: k1*iv + (invar + k2)
1153 bool PhaseIdealLoop::is_scaled_iv_plus_offset(Node* exp, Node* iv, int* p_scale, Node** p_offset, int depth) {
1154   if (is_scaled_iv(exp, iv, p_scale)) {
1155     if (p_offset != NULL) {
1156       Node *zero = _igvn.intcon(0); 
1157       set_ctrl(zero, C->root());
1158       *p_offset = zero;
1159     }
1160     return true;
1161   }
1162   int opc = exp->Opcode();
1163   if (opc == Op_AddI) {
1164     if (is_scaled_iv(exp->in(1), iv, p_scale)) {
1165       if (p_offset != NULL) {
1166         *p_offset = exp->in(2);
1167       }
1168       return true;
1169     }
1170     if (exp->in(2)->is_Con()) {
1171       Node* offset2 = NULL;
1172       if (depth < 2 &&
1173           is_scaled_iv_plus_offset(exp->in(1), iv, p_scale,
1174                                    p_offset != NULL ? &offset2 : NULL, depth+1)) {
1175         if (p_offset != NULL) {
1176           Node *ctrl_off2 = get_ctrl(offset2);
1177           Node* offset = new (C, 3) AddINode(offset2, exp->in(2));
1178           register_new_node(offset, ctrl_off2);
1179           *p_offset = offset;
1180         }
1181         return true;
1182       }
1183     }
1184   } else if (opc == Op_SubI) {
1185     if (is_scaled_iv(exp->in(1), iv, p_scale)) {
1186       if (p_offset != NULL) {
1187         Node *zero = _igvn.intcon(0); 
1188         set_ctrl(zero, C->root());
1189         Node *ctrl_off = get_ctrl(exp->in(2));
1190         Node* offset = new (C, 3) SubINode(zero, exp->in(2));
1191         register_new_node(offset, ctrl_off);
1192         *p_offset = offset;
1193       }
1194       return true;
1195     }
1196     if (is_scaled_iv(exp->in(2), iv, p_scale)) {
1197       if (p_offset != NULL) {
1198         *p_scale *= -1;
1199         *p_offset = exp->in(1);
1200       }
1201       return true;
1202     }
1203   }
1204   return false;
1205 }
1206 
1207 //------------------------------do_range_check---------------------------------
1208 // Eliminate range-checks and other trip-counter vs loop-invariant tests.
1209 void PhaseIdealLoop::do_range_check( IdealLoopTree *loop, Node_List &old_new ) {
1210 #ifndef PRODUCT
1211   if( PrintOpto && VerifyLoopOptimizations ) {
1212     tty->print("Range Check Elimination ");
1213     loop->dump_head();
1214   }
1215 #endif
1216   assert( RangeCheckElimination, "" );
1217   CountedLoopNode *cl = loop->_head->as_CountedLoop();
1218   assert( cl->is_main_loop(), "" );
1219 
1220   // Find the trip counter; we are iteration splitting based on it
1221   Node *trip_counter = cl->phi();
1222   // Find the main loop limit; we will trim it's iterations 
1223   // to not ever trip end tests
1224   Node *main_limit = cl->limit();
1225   // Find the pre-loop limit; we will expand it's iterations to
1226   // not ever trip low tests.
1227   Node *ctrl  = cl->in(LoopNode::EntryControl);
1228   assert( ctrl->Opcode() == Op_IfTrue || ctrl->Opcode() == Op_IfFalse, "" );
1229   Node *iffm = ctrl->in(0);
1230   assert( iffm->Opcode() == Op_If, "" );
1231   Node *p_f = iffm->in(0);
1232   assert( p_f->Opcode() == Op_IfFalse, "" );
1233   CountedLoopEndNode *pre_end = p_f->in(0)->as_CountedLoopEnd();
1234   assert( pre_end->loopnode()->is_pre_loop(), "" );
1235   Node *pre_opaq1 = pre_end->limit();
1236   // Occasionally it's possible for a pre-loop Opaque1 node to be
1237   // optimized away and then another round of loop opts attempted.
1238   // We can not optimize this particular loop in that case.
1239   if( pre_opaq1->Opcode() != Op_Opaque1 )
1240     return;
1241   Opaque1Node *pre_opaq = (Opaque1Node*)pre_opaq1;
1242   Node *pre_limit = pre_opaq->in(1);
1243 
1244   // Where do we put new limit calculations
1245   Node *pre_ctrl = pre_end->loopnode()->in(LoopNode::EntryControl);
1246 
1247   // Ensure the original loop limit is available from the
1248   // pre-loop Opaque1 node.
1249   Node *orig_limit = pre_opaq->original_loop_limit();
1250   if( orig_limit == NULL || _igvn.type(orig_limit) == Type::TOP )
1251     return;
1252 
1253   // Need to find the main-loop zero-trip guard
1254   Node *bolzm = iffm->in(1);
1255   assert( bolzm->Opcode() == Op_Bool, "" );
1256   Node *cmpzm = bolzm->in(1);
1257   assert( cmpzm->is_Cmp(), "" );
1258   Node *opqzm = cmpzm->in(2);
1259   if( opqzm->Opcode() != Op_Opaque1 )
1260     return;
1261   assert( opqzm->in(1) == main_limit, "do not understand situation" );
1262 
1263   // Must know if its a count-up or count-down loop
1264 
1265   // protect against stride not being a constant
1266   if ( !cl->stride_is_con() ) {
1267     return;
1268   }
1269   int stride_con = cl->stride_con();
1270   Node *zero = _igvn.intcon(0); 
1271   Node *one  = _igvn.intcon(1);
1272   set_ctrl(zero, C->root());
1273   set_ctrl(one,  C->root());
1274 
1275   // Range checks that do not dominate the loop backedge (ie.
1276   // conditionally executed) can lengthen the pre loop limit beyond
1277   // the original loop limit. To prevent this, the pre limit is
1278   // (for stride > 0) MINed with the original loop limit (MAXed
1279   // stride < 0) when some range_check (rc) is conditionally
1280   // executed.
1281   bool conditional_rc = false;
1282 
1283   // Check loop body for tests of trip-counter plus loop-invariant vs
1284   // loop-invariant.
1285   for( uint i = 0; i < loop->_body.size(); i++ ) {
1286     Node *iff = loop->_body[i];
1287     if( iff->Opcode() == Op_If ) { // Test?
1288 
1289       // Test is an IfNode, has 2 projections.  If BOTH are in the loop
1290       // we need loop unswitching instead of iteration splitting.
1291       Node *exit = loop->is_loop_exit(iff);
1292       if( !exit ) continue;
1293       int flip = (exit->Opcode() == Op_IfTrue) ? 1 : 0;
1294 
1295       // Get boolean condition to test
1296       Node *i1 = iff->in(1);
1297       if( !i1->is_Bool() ) continue;
1298       BoolNode *bol = i1->as_Bool();
1299       BoolTest b_test = bol->_test;
1300       // Flip sense of test if exit condition is flipped
1301       if( flip )
1302         b_test = b_test.negate();
1303 
1304       // Get compare
1305       Node *cmp = bol->in(1);
1306 
1307       // Look for trip_counter + offset vs limit
1308       Node *rc_exp = cmp->in(1);
1309       Node *limit  = cmp->in(2);
1310       jint scale_con= 1;        // Assume trip counter not scaled
1311 
1312       Node *limit_c = get_ctrl(limit);
1313       if( loop->is_member(get_loop(limit_c) ) ) {
1314         // Compare might have operands swapped; commute them
1315         b_test = b_test.commute();
1316         rc_exp = cmp->in(2);
1317         limit  = cmp->in(1);
1318         limit_c = get_ctrl(limit);
1319         if( loop->is_member(get_loop(limit_c) ) ) 
1320           continue;             // Both inputs are loop varying; cannot RCE
1321       }
1322       // Here we know 'limit' is loop invariant
1323 
1324       // 'limit' maybe pinned below the zero trip test (probably from a
1325       // previous round of rce), in which case, it can't be used in the
1326       // zero trip test expression which must occur before the zero test's if.
1327       if( limit_c == ctrl ) {
1328         continue;  // Don't rce this check but continue looking for other candidates.
1329       }
1330 
1331       // Check for scaled induction variable plus an offset
1332       Node *offset = NULL;
1333 
1334       if (!is_scaled_iv_plus_offset(rc_exp, trip_counter, &scale_con, &offset)) {
1335         continue;
1336       }
1337 
1338       Node *offset_c = get_ctrl(offset);
1339       if( loop->is_member( get_loop(offset_c) ) )
1340         continue;               // Offset is not really loop invariant
1341       // Here we know 'offset' is loop invariant.
1342 
1343       // As above for the 'limit', the 'offset' maybe pinned below the
1344       // zero trip test.
1345       if( offset_c == ctrl ) {
1346         continue; // Don't rce this check but continue looking for other candidates.
1347       }
1348 
1349       // At this point we have the expression as:
1350       //   scale_con * trip_counter + offset :: limit
1351       // where scale_con, offset and limit are loop invariant.  Trip_counter 
1352       // monotonically increases by stride_con, a constant.  Both (or either) 
1353       // stride_con and scale_con can be negative which will flip about the 
1354       // sense of the test.
1355 
1356       // Adjust pre and main loop limits to guard the correct iteration set
1357       if( cmp->Opcode() == Op_CmpU ) {// Unsigned compare is really 2 tests
1358         if( b_test._test == BoolTest::lt ) { // Range checks always use lt
1359           // The overflow limit: scale*I+offset < limit
1360           add_constraint( stride_con, scale_con, offset, limit, pre_ctrl, &pre_limit, &main_limit );
1361           // The underflow limit: 0 <= scale*I+offset.
1362           // Some math yields: -scale*I-(offset+1) < 0
1363           Node *plus_one = new (C, 3) AddINode( offset, one );
1364           register_new_node( plus_one, pre_ctrl );
1365           Node *neg_offset = new (C, 3) SubINode( zero, plus_one );
1366           register_new_node( neg_offset, pre_ctrl );
1367           add_constraint( stride_con, -scale_con, neg_offset, zero, pre_ctrl, &pre_limit, &main_limit );
1368           if (!conditional_rc) {
1369             conditional_rc = !loop->dominates_backedge(iff);
1370           }
1371         } else {
1372 #ifndef PRODUCT
1373           if( PrintOpto ) 
1374             tty->print_cr("missed RCE opportunity");
1375 #endif
1376           continue;             // In release mode, ignore it
1377         }
1378       } else {                  // Otherwise work on normal compares
1379         switch( b_test._test ) {
1380         case BoolTest::ge:      // Convert X >= Y to -X <= -Y
1381           scale_con = -scale_con;
1382           offset = new (C, 3) SubINode( zero, offset );
1383           register_new_node( offset, pre_ctrl );
1384           limit  = new (C, 3) SubINode( zero, limit  );
1385           register_new_node( limit, pre_ctrl );
1386           // Fall into LE case
1387         case BoolTest::le:      // Convert X <= Y to X < Y+1
1388           limit = new (C, 3) AddINode( limit, one );
1389           register_new_node( limit, pre_ctrl );
1390           // Fall into LT case
1391         case BoolTest::lt: 
1392           add_constraint( stride_con, scale_con, offset, limit, pre_ctrl, &pre_limit, &main_limit );
1393           if (!conditional_rc) {
1394             conditional_rc = !loop->dominates_backedge(iff);
1395           }
1396           break;
1397         default:
1398 #ifndef PRODUCT
1399           if( PrintOpto ) 
1400             tty->print_cr("missed RCE opportunity");
1401 #endif
1402           continue;             // Unhandled case
1403         }
1404       }
1405 
1406       // Kill the eliminated test
1407       C->set_major_progress();
1408       Node *kill_con = _igvn.intcon( 1-flip );
1409       set_ctrl(kill_con, C->root());
1410       _igvn.hash_delete(iff);
1411       iff->set_req(1, kill_con);
1412       _igvn._worklist.push(iff);
1413       // Find surviving projection
1414       assert(iff->is_If(), "");
1415       ProjNode* dp = ((IfNode*)iff)->proj_out(1-flip);
1416       // Find loads off the surviving projection; remove their control edge
1417       for (DUIterator_Fast imax, i = dp->fast_outs(imax); i < imax; i++) {
1418         Node* cd = dp->fast_out(i); // Control-dependent node
1419         if( cd->is_Load() ) {   // Loads can now float around in the loop
1420           _igvn.hash_delete(cd);
1421           // Allow the load to float around in the loop, or before it
1422           // but NOT before the pre-loop.
1423           cd->set_req(0, ctrl);   // ctrl, not NULL
1424           _igvn._worklist.push(cd);
1425           --i;
1426           --imax;
1427         }
1428       }
1429 
1430     } // End of is IF
1431 
1432   }
1433 
1434   // Update loop limits
1435   if (conditional_rc) {
1436     pre_limit = (stride_con > 0) ? (Node*)new (C,3) MinINode(pre_limit, orig_limit)
1437                                  : (Node*)new (C,3) MaxINode(pre_limit, orig_limit);
1438     register_new_node(pre_limit, pre_ctrl);
1439   }
1440   _igvn.hash_delete(pre_opaq);
1441   pre_opaq->set_req(1, pre_limit);
1442 
1443   // Note:: we are making the main loop limit no longer precise;
1444   // need to round up based on stride.
1445   if( stride_con != 1 && stride_con != -1 ) { // Cutout for common case
1446     // "Standard" round-up logic:  ([main_limit-init+(y-1)]/y)*y+init
1447     // Hopefully, compiler will optimize for powers of 2.
1448     Node *ctrl = get_ctrl(main_limit);
1449     Node *stride = cl->stride();
1450     Node *init = cl->init_trip();
1451     Node *span = new (C, 3) SubINode(main_limit,init);
1452     register_new_node(span,ctrl);
1453     Node *rndup = _igvn.intcon(stride_con + ((stride_con>0)?-1:1));
1454     Node *add = new (C, 3) AddINode(span,rndup);
1455     register_new_node(add,ctrl);
1456     Node *div = new (C, 3) DivINode(0,add,stride);
1457     register_new_node(div,ctrl);
1458     Node *mul = new (C, 3) MulINode(div,stride);
1459     register_new_node(mul,ctrl);
1460     Node *newlim = new (C, 3) AddINode(mul,init);
1461     register_new_node(newlim,ctrl);
1462     main_limit = newlim;
1463   }
1464 
1465   Node *main_cle = cl->loopexit();
1466   Node *main_bol = main_cle->in(1);
1467   // Hacking loop bounds; need private copies of exit test
1468   if( main_bol->outcnt() > 1 ) {// BoolNode shared?
1469     _igvn.hash_delete(main_cle);
1470     main_bol = main_bol->clone();// Clone a private BoolNode
1471     register_new_node( main_bol, main_cle->in(0) );
1472     main_cle->set_req(1,main_bol);
1473   }
1474   Node *main_cmp = main_bol->in(1);
1475   if( main_cmp->outcnt() > 1 ) { // CmpNode shared?
1476     _igvn.hash_delete(main_bol);
1477     main_cmp = main_cmp->clone();// Clone a private CmpNode
1478     register_new_node( main_cmp, main_cle->in(0) );
1479     main_bol->set_req(1,main_cmp);
1480   }
1481   // Hack the now-private loop bounds
1482   _igvn.hash_delete(main_cmp);
1483   main_cmp->set_req(2, main_limit);
1484   _igvn._worklist.push(main_cmp);
1485   // The OpaqueNode is unshared by design
1486   _igvn.hash_delete(opqzm);
1487   assert( opqzm->outcnt() == 1, "cannot hack shared node" );
1488   opqzm->set_req(1,main_limit);
1489   _igvn._worklist.push(opqzm);
1490 }
1491 
1492 //------------------------------DCE_loop_body----------------------------------
1493 // Remove simplistic dead code from loop body
1494 void IdealLoopTree::DCE_loop_body() {
1495   for( uint i = 0; i < _body.size(); i++ ) 
1496     if( _body.at(i)->outcnt() == 0 ) 
1497       _body.map( i--, _body.pop() );
1498 }
1499   
1500 
1501 //------------------------------adjust_loop_exit_prob--------------------------
1502 // Look for loop-exit tests with the 50/50 (or worse) guesses from the parsing stage.
1503 // Replace with a 1-in-10 exit guess.
1504 void IdealLoopTree::adjust_loop_exit_prob( PhaseIdealLoop *phase ) {
1505   Node *test = tail();
1506   while( test != _head ) {
1507     uint top = test->Opcode();
1508     if( top == Op_IfTrue || top == Op_IfFalse ) {
1509       int test_con = ((ProjNode*)test)->_con;
1510       assert(top == (uint)(test_con? Op_IfTrue: Op_IfFalse), "sanity");
1511       IfNode *iff = test->in(0)->as_If();
1512       if( iff->outcnt() == 2 ) {        // Ignore dead tests
1513         Node *bol = iff->in(1);
1514         if( bol && bol->req() > 1 && bol->in(1) && 
1515             ((bol->in(1)->Opcode() == Op_StorePConditional ) ||
1516              (bol->in(1)->Opcode() == Op_StoreLConditional ) ||
1517              (bol->in(1)->Opcode() == Op_CompareAndSwapI ) ||
1518              (bol->in(1)->Opcode() == Op_CompareAndSwapL ) ||
1519              (bol->in(1)->Opcode() == Op_CompareAndSwapP )))
1520           return;               // Allocation loops RARELY take backedge
1521         // Find the OTHER exit path from the IF
1522         Node* ex = iff->proj_out(1-test_con);
1523         float p = iff->_prob;
1524         if( !phase->is_member( this, ex ) && iff->_fcnt == COUNT_UNKNOWN ) {
1525           if( top == Op_IfTrue ) {
1526             if( p < (PROB_FAIR + PROB_UNLIKELY_MAG(3))) {
1527               iff->_prob = PROB_STATIC_FREQUENT;
1528             }
1529           } else {
1530             if( p > (PROB_FAIR - PROB_UNLIKELY_MAG(3))) {
1531               iff->_prob = PROB_STATIC_INFREQUENT;
1532             }
1533           }
1534         }
1535       }
1536     }
1537     test = phase->idom(test);
1538   }
1539 }
1540   
1541 
1542 //------------------------------policy_do_remove_empty_loop--------------------
1543 // Micro-benchmark spamming.  Policy is to always remove empty loops.
1544 // The 'DO' part is to replace the trip counter with the value it will
1545 // have on the last iteration.  This will break the loop.
1546 bool IdealLoopTree::policy_do_remove_empty_loop( PhaseIdealLoop *phase ) {
1547   // Minimum size must be empty loop
1548   if( _body.size() > 7/*number of nodes in an empty loop*/ ) return false;
1549 
1550   if( !_head->is_CountedLoop() ) return false;     // Dead loop
1551   CountedLoopNode *cl = _head->as_CountedLoop();
1552   if( !cl->loopexit() ) return false; // Malformed loop
1553   if( !phase->is_member(this,phase->get_ctrl(cl->loopexit()->in(CountedLoopEndNode::TestValue)) ) )
1554     return false;             // Infinite loop
1555 #ifndef PRODUCT
1556   if( PrintOpto ) 
1557     tty->print_cr("Removing empty loop");
1558 #endif
1559 #ifdef ASSERT
1560   // Ensure only one phi which is the iv.
1561   Node* iv = NULL;
1562   for (DUIterator_Fast imax, i = cl->fast_outs(imax); i < imax; i++) {
1563     Node* n = cl->fast_out(i);
1564     if (n->Opcode() == Op_Phi) {
1565       assert(iv == NULL, "Too many phis" );
1566       iv = n;
1567     }
1568   }
1569   assert(iv == cl->phi(), "Wrong phi" );
1570 #endif
1571   // Replace the phi at loop head with the final value of the last
1572   // iteration.  Then the CountedLoopEnd will collapse (backedge never
1573   // taken) and all loop-invariant uses of the exit values will be correct.
1574   Node *phi = cl->phi();
1575   Node *final = new (phase->C, 3) SubINode( cl->limit(), cl->stride() );
1576   phase->register_new_node(final,cl->in(LoopNode::EntryControl));
1577   phase->_igvn.hash_delete(phi);
1578   phase->_igvn.subsume_node(phi,final);
1579   phase->C->set_major_progress();
1580   return true;
1581 }
1582   
1583 
1584 //=============================================================================
1585 //------------------------------iteration_split_impl---------------------------
1586 void IdealLoopTree::iteration_split_impl( PhaseIdealLoop *phase, Node_List &old_new ) {
1587   // Check and remove empty loops (spam micro-benchmarks)
1588   if( policy_do_remove_empty_loop(phase) ) 
1589     return;                     // Here we removed an empty loop
1590 
1591   bool should_peel = policy_peeling(phase); // Should we peel?
1592 
1593   bool should_unswitch = policy_unswitching(phase);
1594 
1595   // Non-counted loops may be peeled; exactly 1 iteration is peeled.
1596   // This removes loop-invariant tests (usually null checks).
1597   if( !_head->is_CountedLoop() ) { // Non-counted loop
1598     if (PartialPeelLoop && phase->partial_peel(this, old_new)) {
1599       return;
1600     }
1601     if( should_peel ) {            // Should we peel?
1602 #ifndef PRODUCT
1603       if (PrintOpto) tty->print_cr("should_peel");
1604 #endif
1605       phase->do_peeling(this,old_new);
1606     } else if( should_unswitch ) {
1607       phase->do_unswitching(this, old_new);
1608     }
1609     return;
1610   }
1611   CountedLoopNode *cl = _head->as_CountedLoop();
1612 
1613   if( !cl->loopexit() ) return; // Ignore various kinds of broken loops
1614 
1615   // Do nothing special to pre- and post- loops
1616   if( cl->is_pre_loop() || cl->is_post_loop() ) return;
1617 
1618   // Compute loop trip count from profile data
1619   compute_profile_trip_cnt(phase);
1620 
1621   // Before attempting fancy unrolling, RCE or alignment, see if we want
1622   // to completely unroll this loop or do loop unswitching.
1623   if( cl->is_normal_loop() ) {
1624     bool should_maximally_unroll =  policy_maximally_unroll(phase);
1625     if( should_maximally_unroll ) {
1626       // Here we did some unrolling and peeling.  Eventually we will 
1627       // completely unroll this loop and it will no longer be a loop.
1628       phase->do_maximally_unroll(this,old_new);
1629       return;
1630     }
1631     if (should_unswitch) {
1632       phase->do_unswitching(this, old_new);
1633       return;
1634     }
1635   }
1636 
1637 
1638   // Counted loops may be peeled, may need some iterations run up
1639   // front for RCE, and may want to align loop refs to a cache
1640   // line.  Thus we clone a full loop up front whose trip count is
1641   // at least 1 (if peeling), but may be several more.
1642         
1643   // The main loop will start cache-line aligned with at least 1
1644   // iteration of the unrolled body (zero-trip test required) and
1645   // will have some range checks removed.
1646         
1647   // A post-loop will finish any odd iterations (leftover after
1648   // unrolling), plus any needed for RCE purposes.
1649 
1650   bool should_unroll = policy_unroll(phase);
1651   
1652   bool should_rce = policy_range_check(phase);
1653 
1654   bool should_align = policy_align(phase);
1655 
1656   // If not RCE'ing (iteration splitting) or Aligning, then we do not
1657   // need a pre-loop.  We may still need to peel an initial iteration but
1658   // we will not be needing an unknown number of pre-iterations.
1659   //
1660   // Basically, if may_rce_align reports FALSE first time through, 
1661   // we will not be able to later do RCE or Aligning on this loop.
1662   bool may_rce_align = !policy_peel_only(phase) || should_rce || should_align;
1663 
1664   // If we have any of these conditions (RCE, alignment, unrolling) met, then
1665   // we switch to the pre-/main-/post-loop model.  This model also covers
1666   // peeling.
1667   if( should_rce || should_align || should_unroll ) {
1668     if( cl->is_normal_loop() )  // Convert to 'pre/main/post' loops
1669       phase->insert_pre_post_loops(this,old_new, !may_rce_align);
1670 
1671     // Adjust the pre- and main-loop limits to let the pre and post loops run
1672     // with full checks, but the main-loop with no checks.  Remove said
1673     // checks from the main body.
1674     if( should_rce ) 
1675       phase->do_range_check(this,old_new);
1676 
1677     // Double loop body for unrolling.  Adjust the minimum-trip test (will do
1678     // twice as many iterations as before) and the main body limit (only do
1679     // an even number of trips).  If we are peeling, we might enable some RCE
1680     // and we'd rather unroll the post-RCE'd loop SO... do not unroll if
1681     // peeling.
1682     if( should_unroll && !should_peel ) 
1683       phase->do_unroll(this,old_new, true);
1684 
1685     // Adjust the pre-loop limits to align the main body
1686     // iterations.
1687     if( should_align )
1688       Unimplemented();
1689 
1690   } else {                      // Else we have an unchanged counted loop
1691     if( should_peel )           // Might want to peel but do nothing else
1692       phase->do_peeling(this,old_new);
1693   }
1694 }
1695 
1696 
1697 //=============================================================================
1698 //------------------------------iteration_split--------------------------------
1699 void IdealLoopTree::iteration_split( PhaseIdealLoop *phase, Node_List &old_new ) {
1700   // Recursively iteration split nested loops
1701   if( _child ) _child->iteration_split( phase, old_new );
1702 
1703   // Clean out prior deadwood
1704   DCE_loop_body();
1705 
1706 
1707   // Look for loop-exit tests with my 50/50 guesses from the Parsing stage.
1708   // Replace with a 1-in-10 exit guess.
1709   if( _parent /*not the root loop*/ && 
1710       !_irreducible && 
1711       // Also ignore the occasional dead backedge
1712       !tail()->is_top() ) {
1713     adjust_loop_exit_prob(phase);
1714   }
1715 
1716 
1717   // Gate unrolling, RCE and peeling efforts.
1718   if( !_child &&                // If not an inner loop, do not split
1719       !_irreducible &&
1720       !tail()->is_top() ) {     // Also ignore the occasional dead backedge
1721     if (!_has_call) {
1722       iteration_split_impl( phase, old_new );
1723     } else if (policy_unswitching(phase)) {
1724       phase->do_unswitching(this, old_new);
1725     }
1726   }
1727 
1728   // Minor offset re-organization to remove loop-fallout uses of 
1729   // trip counter.
1730   if( _head->is_CountedLoop() ) phase->reorg_offsets( this );
1731   if( _next ) _next->iteration_split( phase, old_new );
1732 }