1 /*
   2  * Copyright (c) 1998, 2016, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "ci/ciMethodData.hpp"
  27 #include "compiler/compileLog.hpp"
  28 #include "libadt/vectset.hpp"
  29 #include "memory/allocation.inline.hpp"
  30 #include "memory/resourceArea.hpp"
  31 #include "opto/addnode.hpp"
  32 #include "opto/callnode.hpp"
  33 #include "opto/connode.hpp"
  34 #include "opto/convertnode.hpp"
  35 #include "opto/divnode.hpp"
  36 #include "opto/idealGraphPrinter.hpp"
  37 #include "opto/loopnode.hpp"
  38 #include "opto/mulnode.hpp"
  39 #include "opto/rootnode.hpp"
  40 #include "opto/superword.hpp"
  41 
  42 //=============================================================================
  43 //------------------------------is_loop_iv-------------------------------------
  44 // Determine if a node is Counted loop induction variable.
  45 // The method is declared in node.hpp.
  46 const Node* Node::is_loop_iv() const {
  47   if (this->is_Phi() && !this->as_Phi()->is_copy() &&
  48       this->as_Phi()->region()->is_CountedLoop() &&
  49       this->as_Phi()->region()->as_CountedLoop()->phi() == this) {
  50     return this;
  51   } else {
  52     return NULL;
  53   }
  54 }
  55 
  56 //=============================================================================
  57 //------------------------------dump_spec--------------------------------------
  58 // Dump special per-node info
  59 #ifndef PRODUCT
  60 void LoopNode::dump_spec(outputStream *st) const {
  61   if (is_inner_loop()) st->print( "inner " );
  62   if (is_partial_peel_loop()) st->print( "partial_peel " );
  63   if (partial_peel_has_failed()) st->print( "partial_peel_failed " );
  64 }
  65 #endif
  66 
  67 //------------------------------is_valid_counted_loop-------------------------
  68 bool LoopNode::is_valid_counted_loop() const {
  69   if (is_CountedLoop()) {
  70     CountedLoopNode*    l  = as_CountedLoop();
  71     CountedLoopEndNode* le = l->loopexit();
  72     if (le != NULL &&
  73         le->proj_out(1 /* true */) == l->in(LoopNode::LoopBackControl)) {
  74       Node* phi  = l->phi();
  75       Node* exit = le->proj_out(0 /* false */);
  76       if (exit != NULL && exit->Opcode() == Op_IfFalse &&
  77           phi != NULL && phi->is_Phi() &&
  78           phi->in(LoopNode::LoopBackControl) == l->incr() &&
  79           le->loopnode() == l && le->stride_is_con()) {
  80         return true;
  81       }
  82     }
  83   }
  84   return false;
  85 }
  86 
  87 //------------------------------get_early_ctrl---------------------------------
  88 // Compute earliest legal control
  89 Node *PhaseIdealLoop::get_early_ctrl( Node *n ) {
  90   assert( !n->is_Phi() && !n->is_CFG(), "this code only handles data nodes" );
  91   uint i;
  92   Node *early;
  93   if (n->in(0) && !n->is_expensive()) {
  94     early = n->in(0);
  95     if (!early->is_CFG()) // Might be a non-CFG multi-def
  96       early = get_ctrl(early);        // So treat input as a straight data input
  97     i = 1;
  98   } else {
  99     early = get_ctrl(n->in(1));
 100     i = 2;
 101   }
 102   uint e_d = dom_depth(early);
 103   assert( early, "" );
 104   for (; i < n->req(); i++) {
 105     Node *cin = get_ctrl(n->in(i));
 106     assert( cin, "" );
 107     // Keep deepest dominator depth
 108     uint c_d = dom_depth(cin);
 109     if (c_d > e_d) {           // Deeper guy?
 110       early = cin;              // Keep deepest found so far
 111       e_d = c_d;
 112     } else if (c_d == e_d &&    // Same depth?
 113                early != cin) { // If not equal, must use slower algorithm
 114       // If same depth but not equal, one _must_ dominate the other
 115       // and we want the deeper (i.e., dominated) guy.
 116       Node *n1 = early;
 117       Node *n2 = cin;
 118       while (1) {
 119         n1 = idom(n1);          // Walk up until break cycle
 120         n2 = idom(n2);
 121         if (n1 == cin ||        // Walked early up to cin
 122             dom_depth(n2) < c_d)
 123           break;                // early is deeper; keep him
 124         if (n2 == early ||      // Walked cin up to early
 125             dom_depth(n1) < c_d) {
 126           early = cin;          // cin is deeper; keep him
 127           break;
 128         }
 129       }
 130       e_d = dom_depth(early);   // Reset depth register cache
 131     }
 132   }
 133 
 134   // Return earliest legal location
 135   assert(early == find_non_split_ctrl(early), "unexpected early control");
 136 
 137   if (n->is_expensive() && !_verify_only && !_verify_me) {
 138     assert(n->in(0), "should have control input");
 139     early = get_early_ctrl_for_expensive(n, early);
 140   }
 141 
 142   return early;
 143 }
 144 
 145 //------------------------------get_early_ctrl_for_expensive---------------------------------
 146 // Move node up the dominator tree as high as legal while still beneficial
 147 Node *PhaseIdealLoop::get_early_ctrl_for_expensive(Node *n, Node* earliest) {
 148   assert(n->in(0) && n->is_expensive(), "expensive node with control input here");
 149   assert(OptimizeExpensiveOps, "optimization off?");
 150 
 151   Node* ctl = n->in(0);
 152   assert(ctl->is_CFG(), "expensive input 0 must be cfg");
 153   uint min_dom_depth = dom_depth(earliest);
 154 #ifdef ASSERT
 155   if (!is_dominator(ctl, earliest) && !is_dominator(earliest, ctl)) {
 156     dump_bad_graph("Bad graph detected in get_early_ctrl_for_expensive", n, earliest, ctl);
 157     assert(false, "Bad graph detected in get_early_ctrl_for_expensive");
 158   }
 159 #endif
 160   if (dom_depth(ctl) < min_dom_depth) {
 161     return earliest;
 162   }
 163 
 164   while (1) {
 165     Node *next = ctl;
 166     // Moving the node out of a loop on the projection of a If
 167     // confuses loop predication. So once we hit a Loop in a If branch
 168     // that doesn't branch to an UNC, we stop. The code that process
 169     // expensive nodes will notice the loop and skip over it to try to
 170     // move the node further up.
 171     if (ctl->is_CountedLoop() && ctl->in(1) != NULL && ctl->in(1)->in(0) != NULL && ctl->in(1)->in(0)->is_If()) {
 172       if (!ctl->in(1)->as_Proj()->is_uncommon_trap_if_pattern(Deoptimization::Reason_none)) {
 173         break;
 174       }
 175       next = idom(ctl->in(1)->in(0));
 176     } else if (ctl->is_Proj()) {
 177       // We only move it up along a projection if the projection is
 178       // the single control projection for its parent: same code path,
 179       // if it's a If with UNC or fallthrough of a call.
 180       Node* parent_ctl = ctl->in(0);
 181       if (parent_ctl == NULL) {
 182         break;
 183       } else if (parent_ctl->is_CountedLoopEnd() && parent_ctl->as_CountedLoopEnd()->loopnode() != NULL) {
 184         next = parent_ctl->as_CountedLoopEnd()->loopnode()->init_control();
 185       } else if (parent_ctl->is_If()) {
 186         if (!ctl->as_Proj()->is_uncommon_trap_if_pattern(Deoptimization::Reason_none)) {
 187           break;
 188         }
 189         assert(idom(ctl) == parent_ctl, "strange");
 190         next = idom(parent_ctl);
 191       } else if (ctl->is_CatchProj()) {
 192         if (ctl->as_Proj()->_con != CatchProjNode::fall_through_index) {
 193           break;
 194         }
 195         assert(parent_ctl->in(0)->in(0)->is_Call(), "strange graph");
 196         next = parent_ctl->in(0)->in(0)->in(0);
 197       } else {
 198         // Check if parent control has a single projection (this
 199         // control is the only possible successor of the parent
 200         // control). If so, we can try to move the node above the
 201         // parent control.
 202         int nb_ctl_proj = 0;
 203         for (DUIterator_Fast imax, i = parent_ctl->fast_outs(imax); i < imax; i++) {
 204           Node *p = parent_ctl->fast_out(i);
 205           if (p->is_Proj() && p->is_CFG()) {
 206             nb_ctl_proj++;
 207             if (nb_ctl_proj > 1) {
 208               break;
 209             }
 210           }
 211         }
 212 
 213         if (nb_ctl_proj > 1) {
 214           break;
 215         }
 216         assert(parent_ctl->is_Start() || parent_ctl->is_MemBar() || parent_ctl->is_Call(), "unexpected node");
 217         assert(idom(ctl) == parent_ctl, "strange");
 218         next = idom(parent_ctl);
 219       }
 220     } else {
 221       next = idom(ctl);
 222     }
 223     if (next->is_Root() || next->is_Start() || dom_depth(next) < min_dom_depth) {
 224       break;
 225     }
 226     ctl = next;
 227   }
 228 
 229   if (ctl != n->in(0)) {
 230     _igvn.replace_input_of(n, 0, ctl);
 231     _igvn.hash_insert(n);
 232   }
 233 
 234   return ctl;
 235 }
 236 
 237 
 238 //------------------------------set_early_ctrl---------------------------------
 239 // Set earliest legal control
 240 void PhaseIdealLoop::set_early_ctrl( Node *n ) {
 241   Node *early = get_early_ctrl(n);
 242 
 243   // Record earliest legal location
 244   set_ctrl(n, early);
 245 }
 246 
 247 //------------------------------set_subtree_ctrl-------------------------------
 248 // set missing _ctrl entries on new nodes
 249 void PhaseIdealLoop::set_subtree_ctrl( Node *n ) {
 250   // Already set?  Get out.
 251   if( _nodes[n->_idx] ) return;
 252   // Recursively set _nodes array to indicate where the Node goes
 253   uint i;
 254   for( i = 0; i < n->req(); ++i ) {
 255     Node *m = n->in(i);
 256     if( m && m != C->root() )
 257       set_subtree_ctrl( m );
 258   }
 259 
 260   // Fixup self
 261   set_early_ctrl( n );
 262 }
 263 
 264 //------------------------------is_counted_loop--------------------------------
 265 bool PhaseIdealLoop::is_counted_loop( Node *x, IdealLoopTree *loop ) {
 266   PhaseGVN *gvn = &_igvn;
 267 
 268   // Counted loop head must be a good RegionNode with only 3 not NULL
 269   // control input edges: Self, Entry, LoopBack.
 270   if (x->in(LoopNode::Self) == NULL || x->req() != 3 || loop->_irreducible) {
 271     return false;
 272   }
 273   Node *init_control = x->in(LoopNode::EntryControl);
 274   Node *back_control = x->in(LoopNode::LoopBackControl);
 275   if (init_control == NULL || back_control == NULL)    // Partially dead
 276     return false;
 277   // Must also check for TOP when looking for a dead loop
 278   if (init_control->is_top() || back_control->is_top())
 279     return false;
 280 
 281   // Allow funny placement of Safepoint
 282   if (back_control->Opcode() == Op_SafePoint) {
 283     if (UseCountedLoopSafepoints) {
 284       // Leaving the safepoint on the backedge and creating a
 285       // CountedLoop will confuse optimizations. We can't move the
 286       // safepoint around because its jvm state wouldn't match a new
 287       // location. Give up on that loop.
 288       return false;
 289     }
 290     back_control = back_control->in(TypeFunc::Control);
 291   }
 292 
 293   // Controlling test for loop
 294   Node *iftrue = back_control;
 295   uint iftrue_op = iftrue->Opcode();
 296   if (iftrue_op != Op_IfTrue &&
 297       iftrue_op != Op_IfFalse)
 298     // I have a weird back-control.  Probably the loop-exit test is in
 299     // the middle of the loop and I am looking at some trailing control-flow
 300     // merge point.  To fix this I would have to partially peel the loop.
 301     return false; // Obscure back-control
 302 
 303   // Get boolean guarding loop-back test
 304   Node *iff = iftrue->in(0);
 305   if (get_loop(iff) != loop || !iff->in(1)->is_Bool())
 306     return false;
 307   BoolNode *test = iff->in(1)->as_Bool();
 308   BoolTest::mask bt = test->_test._test;
 309   float cl_prob = iff->as_If()->_prob;
 310   if (iftrue_op == Op_IfFalse) {
 311     bt = BoolTest(bt).negate();
 312     cl_prob = 1.0 - cl_prob;
 313   }
 314   // Get backedge compare
 315   Node *cmp = test->in(1);
 316   int cmp_op = cmp->Opcode();
 317   if (cmp_op != Op_CmpI)
 318     return false;                // Avoid pointer & float compares
 319 
 320   // Find the trip-counter increment & limit.  Limit must be loop invariant.
 321   Node *incr  = cmp->in(1);
 322   Node *limit = cmp->in(2);
 323 
 324   // ---------
 325   // need 'loop()' test to tell if limit is loop invariant
 326   // ---------
 327 
 328   if (!is_member(loop, get_ctrl(incr))) { // Swapped trip counter and limit?
 329     Node *tmp = incr;            // Then reverse order into the CmpI
 330     incr = limit;
 331     limit = tmp;
 332     bt = BoolTest(bt).commute(); // And commute the exit test
 333   }
 334   if (is_member(loop, get_ctrl(limit))) // Limit must be loop-invariant
 335     return false;
 336   if (!is_member(loop, get_ctrl(incr))) // Trip counter must be loop-variant
 337     return false;
 338 
 339   Node* phi_incr = NULL;
 340   // Trip-counter increment must be commutative & associative.
 341   if (incr->Opcode() == Op_CastII) {
 342     incr = incr->in(1);
 343   }
 344   if (incr->is_Phi()) {
 345     if (incr->as_Phi()->region() != x || incr->req() != 3)
 346       return false; // Not simple trip counter expression
 347     phi_incr = incr;
 348     incr = phi_incr->in(LoopNode::LoopBackControl); // Assume incr is on backedge of Phi
 349     if (!is_member(loop, get_ctrl(incr))) // Trip counter must be loop-variant
 350       return false;
 351   }
 352 
 353   Node* trunc1 = NULL;
 354   Node* trunc2 = NULL;
 355   const TypeInt* iv_trunc_t = NULL;
 356   if (!(incr = CountedLoopNode::match_incr_with_optional_truncation(incr, &trunc1, &trunc2, &iv_trunc_t))) {
 357     return false; // Funny increment opcode
 358   }
 359   assert(incr->Opcode() == Op_AddI, "wrong increment code");
 360 
 361   // Get merge point
 362   Node *xphi = incr->in(1);
 363   Node *stride = incr->in(2);
 364   if (!stride->is_Con()) {     // Oops, swap these
 365     if (!xphi->is_Con())       // Is the other guy a constant?
 366       return false;             // Nope, unknown stride, bail out
 367     Node *tmp = xphi;           // 'incr' is commutative, so ok to swap
 368     xphi = stride;
 369     stride = tmp;
 370   }
 371   if (xphi->Opcode() == Op_CastII) {
 372     xphi = xphi->in(1);
 373   }
 374   // Stride must be constant
 375   int stride_con = stride->get_int();
 376   if (stride_con == 0)
 377     return false; // missed some peephole opt
 378 
 379   if (!xphi->is_Phi())
 380     return false; // Too much math on the trip counter
 381   if (phi_incr != NULL && phi_incr != xphi)
 382     return false;
 383   PhiNode *phi = xphi->as_Phi();
 384 
 385   // Phi must be of loop header; backedge must wrap to increment
 386   if (phi->region() != x)
 387     return false;
 388   if (trunc1 == NULL && phi->in(LoopNode::LoopBackControl) != incr ||
 389       trunc1 != NULL && phi->in(LoopNode::LoopBackControl) != trunc1) {
 390     return false;
 391   }
 392   Node *init_trip = phi->in(LoopNode::EntryControl);
 393 
 394   // If iv trunc type is smaller than int, check for possible wrap.
 395   if (!TypeInt::INT->higher_equal(iv_trunc_t)) {
 396     assert(trunc1 != NULL, "must have found some truncation");
 397 
 398     // Get a better type for the phi (filtered thru if's)
 399     const TypeInt* phi_ft = filtered_type(phi);
 400 
 401     // Can iv take on a value that will wrap?
 402     //
 403     // Ensure iv's limit is not within "stride" of the wrap value.
 404     //
 405     // Example for "short" type
 406     //    Truncation ensures value is in the range -32768..32767 (iv_trunc_t)
 407     //    If the stride is +10, then the last value of the induction
 408     //    variable before the increment (phi_ft->_hi) must be
 409     //    <= 32767 - 10 and (phi_ft->_lo) must be >= -32768 to
 410     //    ensure no truncation occurs after the increment.
 411 
 412     if (stride_con > 0) {
 413       if (iv_trunc_t->_hi - phi_ft->_hi < stride_con ||
 414           iv_trunc_t->_lo > phi_ft->_lo) {
 415         return false;  // truncation may occur
 416       }
 417     } else if (stride_con < 0) {
 418       if (iv_trunc_t->_lo - phi_ft->_lo > stride_con ||
 419           iv_trunc_t->_hi < phi_ft->_hi) {
 420         return false;  // truncation may occur
 421       }
 422     }
 423     // No possibility of wrap so truncation can be discarded
 424     // Promote iv type to Int
 425   } else {
 426     assert(trunc1 == NULL && trunc2 == NULL, "no truncation for int");
 427   }
 428 
 429   // If the condition is inverted and we will be rolling
 430   // through MININT to MAXINT, then bail out.
 431   if (bt == BoolTest::eq || // Bail out, but this loop trips at most twice!
 432       // Odd stride
 433       bt == BoolTest::ne && stride_con != 1 && stride_con != -1 ||
 434       // Count down loop rolls through MAXINT
 435       (bt == BoolTest::le || bt == BoolTest::lt) && stride_con < 0 ||
 436       // Count up loop rolls through MININT
 437       (bt == BoolTest::ge || bt == BoolTest::gt) && stride_con > 0) {
 438     return false; // Bail out
 439   }
 440 
 441   const TypeInt* init_t = gvn->type(init_trip)->is_int();
 442   const TypeInt* limit_t = gvn->type(limit)->is_int();
 443 
 444   if (stride_con > 0) {
 445     jlong init_p = (jlong)init_t->_lo + stride_con;
 446     if (init_p > (jlong)max_jint || init_p > (jlong)limit_t->_hi)
 447       return false; // cyclic loop or this loop trips only once
 448   } else {
 449     jlong init_p = (jlong)init_t->_hi + stride_con;
 450     if (init_p < (jlong)min_jint || init_p < (jlong)limit_t->_lo)
 451       return false; // cyclic loop or this loop trips only once
 452   }
 453 
 454   if (phi_incr != NULL) {
 455     // check if there is a possiblity of IV overflowing after the first increment
 456     if (stride_con > 0) {
 457       if (init_t->_hi > max_jint - stride_con) {
 458         return false;
 459       }
 460     } else {
 461       if (init_t->_lo < min_jint - stride_con) {
 462         return false;
 463       }
 464     }
 465   }
 466 
 467   // =================================================
 468   // ---- SUCCESS!   Found A Trip-Counted Loop!  -----
 469   //
 470   assert(x->Opcode() == Op_Loop, "regular loops only");
 471   C->print_method(PHASE_BEFORE_CLOOPS, 3);
 472 
 473   Node *hook = new Node(6);
 474 
 475   // ===================================================
 476   // Generate loop limit check to avoid integer overflow
 477   // in cases like next (cyclic loops):
 478   //
 479   // for (i=0; i <= max_jint; i++) {}
 480   // for (i=0; i <  max_jint; i+=2) {}
 481   //
 482   //
 483   // Limit check predicate depends on the loop test:
 484   //
 485   // for(;i != limit; i++)       --> limit <= (max_jint)
 486   // for(;i <  limit; i+=stride) --> limit <= (max_jint - stride + 1)
 487   // for(;i <= limit; i+=stride) --> limit <= (max_jint - stride    )
 488   //
 489 
 490   // Check if limit is excluded to do more precise int overflow check.
 491   bool incl_limit = (bt == BoolTest::le || bt == BoolTest::ge);
 492   int stride_m  = stride_con - (incl_limit ? 0 : (stride_con > 0 ? 1 : -1));
 493 
 494   // If compare points directly to the phi we need to adjust
 495   // the compare so that it points to the incr. Limit have
 496   // to be adjusted to keep trip count the same and the
 497   // adjusted limit should be checked for int overflow.
 498   if (phi_incr != NULL) {
 499     stride_m  += stride_con;
 500   }
 501 
 502   if (limit->is_Con()) {
 503     int limit_con = limit->get_int();
 504     if ((stride_con > 0 && limit_con > (max_jint - stride_m)) ||
 505         (stride_con < 0 && limit_con < (min_jint - stride_m))) {
 506       // Bailout: it could be integer overflow.
 507       return false;
 508     }
 509   } else if ((stride_con > 0 && limit_t->_hi <= (max_jint - stride_m)) ||
 510              (stride_con < 0 && limit_t->_lo >= (min_jint - stride_m))) {
 511       // Limit's type may satisfy the condition, for example,
 512       // when it is an array length.
 513   } else {
 514     // Generate loop's limit check.
 515     // Loop limit check predicate should be near the loop.
 516     ProjNode *limit_check_proj = find_predicate_insertion_point(init_control, Deoptimization::Reason_loop_limit_check);
 517     if (!limit_check_proj) {
 518       // The limit check predicate is not generated if this method trapped here before.
 519 #ifdef ASSERT
 520       if (TraceLoopLimitCheck) {
 521         tty->print("missing loop limit check:");
 522         loop->dump_head();
 523         x->dump(1);
 524       }
 525 #endif
 526       return false;
 527     }
 528 
 529     IfNode* check_iff = limit_check_proj->in(0)->as_If();
 530     Node* cmp_limit;
 531     Node* bol;
 532 
 533     if (stride_con > 0) {
 534       cmp_limit = new CmpINode(limit, _igvn.intcon(max_jint - stride_m));
 535       bol = new BoolNode(cmp_limit, BoolTest::le);
 536     } else {
 537       cmp_limit = new CmpINode(limit, _igvn.intcon(min_jint - stride_m));
 538       bol = new BoolNode(cmp_limit, BoolTest::ge);
 539     }
 540     cmp_limit = _igvn.register_new_node_with_optimizer(cmp_limit);
 541     bol = _igvn.register_new_node_with_optimizer(bol);
 542     set_subtree_ctrl(bol);
 543 
 544     // Replace condition in original predicate but preserve Opaque node
 545     // so that previous predicates could be found.
 546     assert(check_iff->in(1)->Opcode() == Op_Conv2B &&
 547            check_iff->in(1)->in(1)->Opcode() == Op_Opaque1, "");
 548     Node* opq = check_iff->in(1)->in(1);
 549     _igvn.replace_input_of(opq, 1, bol);
 550     // Update ctrl.
 551     set_ctrl(opq, check_iff->in(0));
 552     set_ctrl(check_iff->in(1), check_iff->in(0));
 553 
 554 #ifndef PRODUCT
 555     // report that the loop predication has been actually performed
 556     // for this loop
 557     if (TraceLoopLimitCheck) {
 558       tty->print_cr("Counted Loop Limit Check generated:");
 559       debug_only( bol->dump(2); )
 560     }
 561 #endif
 562   }
 563 
 564   if (phi_incr != NULL) {
 565     // If compare points directly to the phi we need to adjust
 566     // the compare so that it points to the incr. Limit have
 567     // to be adjusted to keep trip count the same and we
 568     // should avoid int overflow.
 569     //
 570     //   i = init; do {} while(i++ < limit);
 571     // is converted to
 572     //   i = init; do {} while(++i < limit+1);
 573     //
 574     limit = gvn->transform(new AddINode(limit, stride));
 575   }
 576 
 577   // Now we need to canonicalize loop condition.
 578   if (bt == BoolTest::ne) {
 579     assert(stride_con == 1 || stride_con == -1, "simple increment only");
 580     // 'ne' can be replaced with 'lt' only when init < limit.
 581     if (stride_con > 0 && init_t->_hi < limit_t->_lo)
 582       bt = BoolTest::lt;
 583     // 'ne' can be replaced with 'gt' only when init > limit.
 584     if (stride_con < 0 && init_t->_lo > limit_t->_hi)
 585       bt = BoolTest::gt;
 586   }
 587 
 588   if (incl_limit) {
 589     // The limit check guaranties that 'limit <= (max_jint - stride)' so
 590     // we can convert 'i <= limit' to 'i < limit+1' since stride != 0.
 591     //
 592     Node* one = (stride_con > 0) ? gvn->intcon( 1) : gvn->intcon(-1);
 593     limit = gvn->transform(new AddINode(limit, one));
 594     if (bt == BoolTest::le)
 595       bt = BoolTest::lt;
 596     else if (bt == BoolTest::ge)
 597       bt = BoolTest::gt;
 598     else
 599       ShouldNotReachHere();
 600   }
 601   set_subtree_ctrl( limit );
 602 
 603   if (!UseCountedLoopSafepoints) {
 604     // Check for SafePoint on backedge and remove
 605     Node *sfpt = x->in(LoopNode::LoopBackControl);
 606     if (sfpt->Opcode() == Op_SafePoint && is_deleteable_safept(sfpt)) {
 607       lazy_replace( sfpt, iftrue );
 608       if (loop->_safepts != NULL) {
 609         loop->_safepts->yank(sfpt);
 610       }
 611       loop->_tail = iftrue;
 612     }
 613   }
 614 
 615   // Build a canonical trip test.
 616   // Clone code, as old values may be in use.
 617   incr = incr->clone();
 618   incr->set_req(1,phi);
 619   incr->set_req(2,stride);
 620   incr = _igvn.register_new_node_with_optimizer(incr);
 621   set_early_ctrl( incr );
 622   _igvn.rehash_node_delayed(phi);
 623   phi->set_req_X( LoopNode::LoopBackControl, incr, &_igvn );
 624 
 625   // If phi type is more restrictive than Int, raise to
 626   // Int to prevent (almost) infinite recursion in igvn
 627   // which can only handle integer types for constants or minint..maxint.
 628   if (!TypeInt::INT->higher_equal(phi->bottom_type())) {
 629     Node* nphi = PhiNode::make(phi->in(0), phi->in(LoopNode::EntryControl), TypeInt::INT);
 630     nphi->set_req(LoopNode::LoopBackControl, phi->in(LoopNode::LoopBackControl));
 631     nphi = _igvn.register_new_node_with_optimizer(nphi);
 632     set_ctrl(nphi, get_ctrl(phi));
 633     _igvn.replace_node(phi, nphi);
 634     phi = nphi->as_Phi();
 635   }
 636   cmp = cmp->clone();
 637   cmp->set_req(1,incr);
 638   cmp->set_req(2,limit);
 639   cmp = _igvn.register_new_node_with_optimizer(cmp);
 640   set_ctrl(cmp, iff->in(0));
 641 
 642   test = test->clone()->as_Bool();
 643   (*(BoolTest*)&test->_test)._test = bt;
 644   test->set_req(1,cmp);
 645   _igvn.register_new_node_with_optimizer(test);
 646   set_ctrl(test, iff->in(0));
 647 
 648   // Replace the old IfNode with a new LoopEndNode
 649   Node *lex = _igvn.register_new_node_with_optimizer(new CountedLoopEndNode( iff->in(0), test, cl_prob, iff->as_If()->_fcnt ));
 650   IfNode *le = lex->as_If();
 651   uint dd = dom_depth(iff);
 652   set_idom(le, le->in(0), dd); // Update dominance for loop exit
 653   set_loop(le, loop);
 654 
 655   // Get the loop-exit control
 656   Node *iffalse = iff->as_If()->proj_out(!(iftrue_op == Op_IfTrue));
 657 
 658   // Need to swap loop-exit and loop-back control?
 659   if (iftrue_op == Op_IfFalse) {
 660     Node *ift2=_igvn.register_new_node_with_optimizer(new IfTrueNode (le));
 661     Node *iff2=_igvn.register_new_node_with_optimizer(new IfFalseNode(le));
 662 
 663     loop->_tail = back_control = ift2;
 664     set_loop(ift2, loop);
 665     set_loop(iff2, get_loop(iffalse));
 666 
 667     // Lazy update of 'get_ctrl' mechanism.
 668     lazy_replace(iffalse, iff2);
 669     lazy_replace(iftrue,  ift2);
 670 
 671     // Swap names
 672     iffalse = iff2;
 673     iftrue  = ift2;
 674   } else {
 675     _igvn.rehash_node_delayed(iffalse);
 676     _igvn.rehash_node_delayed(iftrue);
 677     iffalse->set_req_X( 0, le, &_igvn );
 678     iftrue ->set_req_X( 0, le, &_igvn );
 679   }
 680 
 681   set_idom(iftrue,  le, dd+1);
 682   set_idom(iffalse, le, dd+1);
 683   assert(iff->outcnt() == 0, "should be dead now");
 684   lazy_replace( iff, le ); // fix 'get_ctrl'
 685 
 686   // Now setup a new CountedLoopNode to replace the existing LoopNode
 687   CountedLoopNode *l = new CountedLoopNode(init_control, back_control);
 688   l->set_unswitch_count(x->as_Loop()->unswitch_count()); // Preserve
 689   // The following assert is approximately true, and defines the intention
 690   // of can_be_counted_loop.  It fails, however, because phase->type
 691   // is not yet initialized for this loop and its parts.
 692   //assert(l->can_be_counted_loop(this), "sanity");
 693   _igvn.register_new_node_with_optimizer(l);
 694   set_loop(l, loop);
 695   loop->_head = l;
 696   // Fix all data nodes placed at the old loop head.
 697   // Uses the lazy-update mechanism of 'get_ctrl'.
 698   lazy_replace( x, l );
 699   set_idom(l, init_control, dom_depth(x));
 700 
 701   if (!UseCountedLoopSafepoints) {
 702     // Check for immediately preceding SafePoint and remove
 703     Node *sfpt2 = le->in(0);
 704     if (sfpt2->Opcode() == Op_SafePoint && is_deleteable_safept(sfpt2)) {
 705       lazy_replace( sfpt2, sfpt2->in(TypeFunc::Control));
 706       if (loop->_safepts != NULL) {
 707         loop->_safepts->yank(sfpt2);
 708       }
 709     }
 710   }
 711 
 712   // Free up intermediate goo
 713   _igvn.remove_dead_node(hook);
 714 
 715 #ifdef ASSERT
 716   assert(l->is_valid_counted_loop(), "counted loop shape is messed up");
 717   assert(l == loop->_head && l->phi() == phi && l->loopexit() == lex, "" );
 718 #endif
 719 #ifndef PRODUCT
 720   if (TraceLoopOpts) {
 721     tty->print("Counted      ");
 722     loop->dump_head();
 723   }
 724 #endif
 725 
 726   C->print_method(PHASE_AFTER_CLOOPS, 3);
 727 
 728   // Capture bounds of the loop in the induction variable Phi before
 729   // subsequent transformation (iteration splitting) obscures the
 730   // bounds
 731   l->phi()->as_Phi()->set_type(l->phi()->Value(&_igvn));
 732 
 733   return true;
 734 }
 735 
 736 //----------------------exact_limit-------------------------------------------
 737 Node* PhaseIdealLoop::exact_limit( IdealLoopTree *loop ) {
 738   assert(loop->_head->is_CountedLoop(), "");
 739   CountedLoopNode *cl = loop->_head->as_CountedLoop();
 740   assert(cl->is_valid_counted_loop(), "");
 741 
 742   if (ABS(cl->stride_con()) == 1 ||
 743       cl->limit()->Opcode() == Op_LoopLimit) {
 744     // Old code has exact limit (it could be incorrect in case of int overflow).
 745     // Loop limit is exact with stride == 1. And loop may already have exact limit.
 746     return cl->limit();
 747   }
 748   Node *limit = NULL;
 749 #ifdef ASSERT
 750   BoolTest::mask bt = cl->loopexit()->test_trip();
 751   assert(bt == BoolTest::lt || bt == BoolTest::gt, "canonical test is expected");
 752 #endif
 753   if (cl->has_exact_trip_count()) {
 754     // Simple case: loop has constant boundaries.
 755     // Use jlongs to avoid integer overflow.
 756     int stride_con = cl->stride_con();
 757     jlong  init_con = cl->init_trip()->get_int();
 758     jlong limit_con = cl->limit()->get_int();
 759     julong trip_cnt = cl->trip_count();
 760     jlong final_con = init_con + trip_cnt*stride_con;
 761     int final_int = (int)final_con;
 762     // The final value should be in integer range since the loop
 763     // is counted and the limit was checked for overflow.
 764     assert(final_con == (jlong)final_int, "final value should be integer");
 765     limit = _igvn.intcon(final_int);
 766   } else {
 767     // Create new LoopLimit node to get exact limit (final iv value).
 768     limit = new LoopLimitNode(C, cl->init_trip(), cl->limit(), cl->stride());
 769     register_new_node(limit, cl->in(LoopNode::EntryControl));
 770   }
 771   assert(limit != NULL, "sanity");
 772   return limit;
 773 }
 774 
 775 //------------------------------Ideal------------------------------------------
 776 // Return a node which is more "ideal" than the current node.
 777 // Attempt to convert into a counted-loop.
 778 Node *LoopNode::Ideal(PhaseGVN *phase, bool can_reshape) {
 779   if (!can_be_counted_loop(phase)) {
 780     phase->C->set_major_progress();
 781   }
 782   return RegionNode::Ideal(phase, can_reshape);
 783 }
 784 
 785 
 786 //=============================================================================
 787 //------------------------------Ideal------------------------------------------
 788 // Return a node which is more "ideal" than the current node.
 789 // Attempt to convert into a counted-loop.
 790 Node *CountedLoopNode::Ideal(PhaseGVN *phase, bool can_reshape) {
 791   return RegionNode::Ideal(phase, can_reshape);
 792 }
 793 
 794 //------------------------------dump_spec--------------------------------------
 795 // Dump special per-node info
 796 #ifndef PRODUCT
 797 void CountedLoopNode::dump_spec(outputStream *st) const {
 798   LoopNode::dump_spec(st);
 799   if (stride_is_con()) {
 800     st->print("stride: %d ",stride_con());
 801   }
 802   if (is_pre_loop ()) st->print("pre of N%d" , _main_idx);
 803   if (is_main_loop()) st->print("main of N%d", _idx);
 804   if (is_post_loop()) st->print("post of N%d", _main_idx);
 805 }
 806 #endif
 807 
 808 //=============================================================================
 809 int CountedLoopEndNode::stride_con() const {
 810   return stride()->bottom_type()->is_int()->get_con();
 811 }
 812 
 813 //=============================================================================
 814 //------------------------------Value-----------------------------------------
 815 const Type* LoopLimitNode::Value(PhaseGVN* phase) const {
 816   const Type* init_t   = phase->type(in(Init));
 817   const Type* limit_t  = phase->type(in(Limit));
 818   const Type* stride_t = phase->type(in(Stride));
 819   // Either input is TOP ==> the result is TOP
 820   if (init_t   == Type::TOP) return Type::TOP;
 821   if (limit_t  == Type::TOP) return Type::TOP;
 822   if (stride_t == Type::TOP) return Type::TOP;
 823 
 824   int stride_con = stride_t->is_int()->get_con();
 825   if (stride_con == 1)
 826     return NULL;  // Identity
 827 
 828   if (init_t->is_int()->is_con() && limit_t->is_int()->is_con()) {
 829     // Use jlongs to avoid integer overflow.
 830     jlong init_con   =  init_t->is_int()->get_con();
 831     jlong limit_con  = limit_t->is_int()->get_con();
 832     int  stride_m   = stride_con - (stride_con > 0 ? 1 : -1);
 833     jlong trip_count = (limit_con - init_con + stride_m)/stride_con;
 834     jlong final_con  = init_con + stride_con*trip_count;
 835     int final_int = (int)final_con;
 836     // The final value should be in integer range since the loop
 837     // is counted and the limit was checked for overflow.
 838     assert(final_con == (jlong)final_int, "final value should be integer");
 839     return TypeInt::make(final_int);
 840   }
 841 
 842   return bottom_type(); // TypeInt::INT
 843 }
 844 
 845 //------------------------------Ideal------------------------------------------
 846 // Return a node which is more "ideal" than the current node.
 847 Node *LoopLimitNode::Ideal(PhaseGVN *phase, bool can_reshape) {
 848   if (phase->type(in(Init))   == Type::TOP ||
 849       phase->type(in(Limit))  == Type::TOP ||
 850       phase->type(in(Stride)) == Type::TOP)
 851     return NULL;  // Dead
 852 
 853   int stride_con = phase->type(in(Stride))->is_int()->get_con();
 854   if (stride_con == 1)
 855     return NULL;  // Identity
 856 
 857   if (in(Init)->is_Con() && in(Limit)->is_Con())
 858     return NULL;  // Value
 859 
 860   // Delay following optimizations until all loop optimizations
 861   // done to keep Ideal graph simple.
 862   if (!can_reshape || phase->C->major_progress())
 863     return NULL;
 864 
 865   const TypeInt* init_t  = phase->type(in(Init) )->is_int();
 866   const TypeInt* limit_t = phase->type(in(Limit))->is_int();
 867   int stride_p;
 868   jlong lim, ini;
 869   julong max;
 870   if (stride_con > 0) {
 871     stride_p = stride_con;
 872     lim = limit_t->_hi;
 873     ini = init_t->_lo;
 874     max = (julong)max_jint;
 875   } else {
 876     stride_p = -stride_con;
 877     lim = init_t->_hi;
 878     ini = limit_t->_lo;
 879     max = (julong)min_jint;
 880   }
 881   julong range = lim - ini + stride_p;
 882   if (range <= max) {
 883     // Convert to integer expression if it is not overflow.
 884     Node* stride_m = phase->intcon(stride_con - (stride_con > 0 ? 1 : -1));
 885     Node *range = phase->transform(new SubINode(in(Limit), in(Init)));
 886     Node *bias  = phase->transform(new AddINode(range, stride_m));
 887     Node *trip  = phase->transform(new DivINode(0, bias, in(Stride)));
 888     Node *span  = phase->transform(new MulINode(trip, in(Stride)));
 889     return new AddINode(span, in(Init)); // exact limit
 890   }
 891 
 892   if (is_power_of_2(stride_p) ||                // divisor is 2^n
 893       !Matcher::has_match_rule(Op_LoopLimit)) { // or no specialized Mach node?
 894     // Convert to long expression to avoid integer overflow
 895     // and let igvn optimizer convert this division.
 896     //
 897     Node*   init   = phase->transform( new ConvI2LNode(in(Init)));
 898     Node*  limit   = phase->transform( new ConvI2LNode(in(Limit)));
 899     Node* stride   = phase->longcon(stride_con);
 900     Node* stride_m = phase->longcon(stride_con - (stride_con > 0 ? 1 : -1));
 901 
 902     Node *range = phase->transform(new SubLNode(limit, init));
 903     Node *bias  = phase->transform(new AddLNode(range, stride_m));
 904     Node *span;
 905     if (stride_con > 0 && is_power_of_2(stride_p)) {
 906       // bias >= 0 if stride >0, so if stride is 2^n we can use &(-stride)
 907       // and avoid generating rounding for division. Zero trip guard should
 908       // guarantee that init < limit but sometimes the guard is missing and
 909       // we can get situation when init > limit. Note, for the empty loop
 910       // optimization zero trip guard is generated explicitly which leaves
 911       // only RCE predicate where exact limit is used and the predicate
 912       // will simply fail forcing recompilation.
 913       Node* neg_stride   = phase->longcon(-stride_con);
 914       span = phase->transform(new AndLNode(bias, neg_stride));
 915     } else {
 916       Node *trip  = phase->transform(new DivLNode(0, bias, stride));
 917       span = phase->transform(new MulLNode(trip, stride));
 918     }
 919     // Convert back to int
 920     Node *span_int = phase->transform(new ConvL2INode(span));
 921     return new AddINode(span_int, in(Init)); // exact limit
 922   }
 923 
 924   return NULL;    // No progress
 925 }
 926 
 927 //------------------------------Identity---------------------------------------
 928 // If stride == 1 return limit node.
 929 Node* LoopLimitNode::Identity(PhaseGVN* phase) {
 930   int stride_con = phase->type(in(Stride))->is_int()->get_con();
 931   if (stride_con == 1 || stride_con == -1)
 932     return in(Limit);
 933   return this;
 934 }
 935 
 936 //=============================================================================
 937 //----------------------match_incr_with_optional_truncation--------------------
 938 // Match increment with optional truncation:
 939 // CHAR: (i+1)&0x7fff, BYTE: ((i+1)<<8)>>8, or SHORT: ((i+1)<<16)>>16
 940 // Return NULL for failure. Success returns the increment node.
 941 Node* CountedLoopNode::match_incr_with_optional_truncation(
 942                       Node* expr, Node** trunc1, Node** trunc2, const TypeInt** trunc_type) {
 943   // Quick cutouts:
 944   if (expr == NULL || expr->req() != 3)  return NULL;
 945 
 946   Node *t1 = NULL;
 947   Node *t2 = NULL;
 948   const TypeInt* trunc_t = TypeInt::INT;
 949   Node* n1 = expr;
 950   int   n1op = n1->Opcode();
 951 
 952   // Try to strip (n1 & M) or (n1 << N >> N) from n1.
 953   if (n1op == Op_AndI &&
 954       n1->in(2)->is_Con() &&
 955       n1->in(2)->bottom_type()->is_int()->get_con() == 0x7fff) {
 956     // %%% This check should match any mask of 2**K-1.
 957     t1 = n1;
 958     n1 = t1->in(1);
 959     n1op = n1->Opcode();
 960     trunc_t = TypeInt::CHAR;
 961   } else if (n1op == Op_RShiftI &&
 962              n1->in(1) != NULL &&
 963              n1->in(1)->Opcode() == Op_LShiftI &&
 964              n1->in(2) == n1->in(1)->in(2) &&
 965              n1->in(2)->is_Con()) {
 966     jint shift = n1->in(2)->bottom_type()->is_int()->get_con();
 967     // %%% This check should match any shift in [1..31].
 968     if (shift == 16 || shift == 8) {
 969       t1 = n1;
 970       t2 = t1->in(1);
 971       n1 = t2->in(1);
 972       n1op = n1->Opcode();
 973       if (shift == 16) {
 974         trunc_t = TypeInt::SHORT;
 975       } else if (shift == 8) {
 976         trunc_t = TypeInt::BYTE;
 977       }
 978     }
 979   }
 980 
 981   // If (maybe after stripping) it is an AddI, we won:
 982   if (n1op == Op_AddI) {
 983     *trunc1 = t1;
 984     *trunc2 = t2;
 985     *trunc_type = trunc_t;
 986     return n1;
 987   }
 988 
 989   // failed
 990   return NULL;
 991 }
 992 
 993 
 994 //------------------------------filtered_type--------------------------------
 995 // Return a type based on condition control flow
 996 // A successful return will be a type that is restricted due
 997 // to a series of dominating if-tests, such as:
 998 //    if (i < 10) {
 999 //       if (i > 0) {
1000 //          here: "i" type is [1..10)
1001 //       }
1002 //    }
1003 // or a control flow merge
1004 //    if (i < 10) {
1005 //       do {
1006 //          phi( , ) -- at top of loop type is [min_int..10)
1007 //         i = ?
1008 //       } while ( i < 10)
1009 //
1010 const TypeInt* PhaseIdealLoop::filtered_type( Node *n, Node* n_ctrl) {
1011   assert(n && n->bottom_type()->is_int(), "must be int");
1012   const TypeInt* filtered_t = NULL;
1013   if (!n->is_Phi()) {
1014     assert(n_ctrl != NULL || n_ctrl == C->top(), "valid control");
1015     filtered_t = filtered_type_from_dominators(n, n_ctrl);
1016 
1017   } else {
1018     Node* phi    = n->as_Phi();
1019     Node* region = phi->in(0);
1020     assert(n_ctrl == NULL || n_ctrl == region, "ctrl parameter must be region");
1021     if (region && region != C->top()) {
1022       for (uint i = 1; i < phi->req(); i++) {
1023         Node* val   = phi->in(i);
1024         Node* use_c = region->in(i);
1025         const TypeInt* val_t = filtered_type_from_dominators(val, use_c);
1026         if (val_t != NULL) {
1027           if (filtered_t == NULL) {
1028             filtered_t = val_t;
1029           } else {
1030             filtered_t = filtered_t->meet(val_t)->is_int();
1031           }
1032         }
1033       }
1034     }
1035   }
1036   const TypeInt* n_t = _igvn.type(n)->is_int();
1037   if (filtered_t != NULL) {
1038     n_t = n_t->join(filtered_t)->is_int();
1039   }
1040   return n_t;
1041 }
1042 
1043 
1044 //------------------------------filtered_type_from_dominators--------------------------------
1045 // Return a possibly more restrictive type for val based on condition control flow of dominators
1046 const TypeInt* PhaseIdealLoop::filtered_type_from_dominators( Node* val, Node *use_ctrl) {
1047   if (val->is_Con()) {
1048      return val->bottom_type()->is_int();
1049   }
1050   uint if_limit = 10; // Max number of dominating if's visited
1051   const TypeInt* rtn_t = NULL;
1052 
1053   if (use_ctrl && use_ctrl != C->top()) {
1054     Node* val_ctrl = get_ctrl(val);
1055     uint val_dom_depth = dom_depth(val_ctrl);
1056     Node* pred = use_ctrl;
1057     uint if_cnt = 0;
1058     while (if_cnt < if_limit) {
1059       if ((pred->Opcode() == Op_IfTrue || pred->Opcode() == Op_IfFalse)) {
1060         if_cnt++;
1061         const TypeInt* if_t = IfNode::filtered_int_type(&_igvn, val, pred);
1062         if (if_t != NULL) {
1063           if (rtn_t == NULL) {
1064             rtn_t = if_t;
1065           } else {
1066             rtn_t = rtn_t->join(if_t)->is_int();
1067           }
1068         }
1069       }
1070       pred = idom(pred);
1071       if (pred == NULL || pred == C->top()) {
1072         break;
1073       }
1074       // Stop if going beyond definition block of val
1075       if (dom_depth(pred) < val_dom_depth) {
1076         break;
1077       }
1078     }
1079   }
1080   return rtn_t;
1081 }
1082 
1083 
1084 //------------------------------dump_spec--------------------------------------
1085 // Dump special per-node info
1086 #ifndef PRODUCT
1087 void CountedLoopEndNode::dump_spec(outputStream *st) const {
1088   if( in(TestValue) != NULL && in(TestValue)->is_Bool() ) {
1089     BoolTest bt( test_trip()); // Added this for g++.
1090 
1091     st->print("[");
1092     bt.dump_on(st);
1093     st->print("]");
1094   }
1095   st->print(" ");
1096   IfNode::dump_spec(st);
1097 }
1098 #endif
1099 
1100 //=============================================================================
1101 //------------------------------is_member--------------------------------------
1102 // Is 'l' a member of 'this'?
1103 bool IdealLoopTree::is_member(const IdealLoopTree *l) const {
1104   while( l->_nest > _nest ) l = l->_parent;
1105   return l == this;
1106 }
1107 
1108 //------------------------------set_nest---------------------------------------
1109 // Set loop tree nesting depth.  Accumulate _has_call bits.
1110 int IdealLoopTree::set_nest( uint depth ) {
1111   _nest = depth;
1112   int bits = _has_call;
1113   if( _child ) bits |= _child->set_nest(depth+1);
1114   if( bits ) _has_call = 1;
1115   if( _next  ) bits |= _next ->set_nest(depth  );
1116   return bits;
1117 }
1118 
1119 //------------------------------split_fall_in----------------------------------
1120 // Split out multiple fall-in edges from the loop header.  Move them to a
1121 // private RegionNode before the loop.  This becomes the loop landing pad.
1122 void IdealLoopTree::split_fall_in( PhaseIdealLoop *phase, int fall_in_cnt ) {
1123   PhaseIterGVN &igvn = phase->_igvn;
1124   uint i;
1125 
1126   // Make a new RegionNode to be the landing pad.
1127   Node *landing_pad = new RegionNode( fall_in_cnt+1 );
1128   phase->set_loop(landing_pad,_parent);
1129   // Gather all the fall-in control paths into the landing pad
1130   uint icnt = fall_in_cnt;
1131   uint oreq = _head->req();
1132   for( i = oreq-1; i>0; i-- )
1133     if( !phase->is_member( this, _head->in(i) ) )
1134       landing_pad->set_req(icnt--,_head->in(i));
1135 
1136   // Peel off PhiNode edges as well
1137   for (DUIterator_Fast jmax, j = _head->fast_outs(jmax); j < jmax; j++) {
1138     Node *oj = _head->fast_out(j);
1139     if( oj->is_Phi() ) {
1140       PhiNode* old_phi = oj->as_Phi();
1141       assert( old_phi->region() == _head, "" );
1142       igvn.hash_delete(old_phi);   // Yank from hash before hacking edges
1143       Node *p = PhiNode::make_blank(landing_pad, old_phi);
1144       uint icnt = fall_in_cnt;
1145       for( i = oreq-1; i>0; i-- ) {
1146         if( !phase->is_member( this, _head->in(i) ) ) {
1147           p->init_req(icnt--, old_phi->in(i));
1148           // Go ahead and clean out old edges from old phi
1149           old_phi->del_req(i);
1150         }
1151       }
1152       // Search for CSE's here, because ZKM.jar does a lot of
1153       // loop hackery and we need to be a little incremental
1154       // with the CSE to avoid O(N^2) node blow-up.
1155       Node *p2 = igvn.hash_find_insert(p); // Look for a CSE
1156       if( p2 ) {                // Found CSE
1157         p->destruct();          // Recover useless new node
1158         p = p2;                 // Use old node
1159       } else {
1160         igvn.register_new_node_with_optimizer(p, old_phi);
1161       }
1162       // Make old Phi refer to new Phi.
1163       old_phi->add_req(p);
1164       // Check for the special case of making the old phi useless and
1165       // disappear it.  In JavaGrande I have a case where this useless
1166       // Phi is the loop limit and prevents recognizing a CountedLoop
1167       // which in turn prevents removing an empty loop.
1168       Node *id_old_phi = old_phi->Identity( &igvn );
1169       if( id_old_phi != old_phi ) { // Found a simple identity?
1170         // Note that I cannot call 'replace_node' here, because
1171         // that will yank the edge from old_phi to the Region and
1172         // I'm mid-iteration over the Region's uses.
1173         for (DUIterator_Last imin, i = old_phi->last_outs(imin); i >= imin; ) {
1174           Node* use = old_phi->last_out(i);
1175           igvn.rehash_node_delayed(use);
1176           uint uses_found = 0;
1177           for (uint j = 0; j < use->len(); j++) {
1178             if (use->in(j) == old_phi) {
1179               if (j < use->req()) use->set_req (j, id_old_phi);
1180               else                use->set_prec(j, id_old_phi);
1181               uses_found++;
1182             }
1183           }
1184           i -= uses_found;    // we deleted 1 or more copies of this edge
1185         }
1186       }
1187       igvn._worklist.push(old_phi);
1188     }
1189   }
1190   // Finally clean out the fall-in edges from the RegionNode
1191   for( i = oreq-1; i>0; i-- ) {
1192     if( !phase->is_member( this, _head->in(i) ) ) {
1193       _head->del_req(i);
1194     }
1195   }
1196   igvn.rehash_node_delayed(_head);
1197   // Transform landing pad
1198   igvn.register_new_node_with_optimizer(landing_pad, _head);
1199   // Insert landing pad into the header
1200   _head->add_req(landing_pad);
1201 }
1202 
1203 //------------------------------split_outer_loop-------------------------------
1204 // Split out the outermost loop from this shared header.
1205 void IdealLoopTree::split_outer_loop( PhaseIdealLoop *phase ) {
1206   PhaseIterGVN &igvn = phase->_igvn;
1207 
1208   // Find index of outermost loop; it should also be my tail.
1209   uint outer_idx = 1;
1210   while( _head->in(outer_idx) != _tail ) outer_idx++;
1211 
1212   // Make a LoopNode for the outermost loop.
1213   Node *ctl = _head->in(LoopNode::EntryControl);
1214   Node *outer = new LoopNode( ctl, _head->in(outer_idx) );
1215   outer = igvn.register_new_node_with_optimizer(outer, _head);
1216   phase->set_created_loop_node();
1217 
1218   // Outermost loop falls into '_head' loop
1219   _head->set_req(LoopNode::EntryControl, outer);
1220   _head->del_req(outer_idx);
1221   // Split all the Phis up between '_head' loop and 'outer' loop.
1222   for (DUIterator_Fast jmax, j = _head->fast_outs(jmax); j < jmax; j++) {
1223     Node *out = _head->fast_out(j);
1224     if( out->is_Phi() ) {
1225       PhiNode *old_phi = out->as_Phi();
1226       assert( old_phi->region() == _head, "" );
1227       Node *phi = PhiNode::make_blank(outer, old_phi);
1228       phi->init_req(LoopNode::EntryControl,    old_phi->in(LoopNode::EntryControl));
1229       phi->init_req(LoopNode::LoopBackControl, old_phi->in(outer_idx));
1230       phi = igvn.register_new_node_with_optimizer(phi, old_phi);
1231       // Make old Phi point to new Phi on the fall-in path
1232       igvn.replace_input_of(old_phi, LoopNode::EntryControl, phi);
1233       old_phi->del_req(outer_idx);
1234     }
1235   }
1236 
1237   // Use the new loop head instead of the old shared one
1238   _head = outer;
1239   phase->set_loop(_head, this);
1240 }
1241 
1242 //------------------------------fix_parent-------------------------------------
1243 static void fix_parent( IdealLoopTree *loop, IdealLoopTree *parent ) {
1244   loop->_parent = parent;
1245   if( loop->_child ) fix_parent( loop->_child, loop   );
1246   if( loop->_next  ) fix_parent( loop->_next , parent );
1247 }
1248 
1249 //------------------------------estimate_path_freq-----------------------------
1250 static float estimate_path_freq( Node *n ) {
1251   // Try to extract some path frequency info
1252   IfNode *iff;
1253   for( int i = 0; i < 50; i++ ) { // Skip through a bunch of uncommon tests
1254     uint nop = n->Opcode();
1255     if( nop == Op_SafePoint ) {   // Skip any safepoint
1256       n = n->in(0);
1257       continue;
1258     }
1259     if( nop == Op_CatchProj ) {   // Get count from a prior call
1260       // Assume call does not always throw exceptions: means the call-site
1261       // count is also the frequency of the fall-through path.
1262       assert( n->is_CatchProj(), "" );
1263       if( ((CatchProjNode*)n)->_con != CatchProjNode::fall_through_index )
1264         return 0.0f;            // Assume call exception path is rare
1265       Node *call = n->in(0)->in(0)->in(0);
1266       assert( call->is_Call(), "expect a call here" );
1267       const JVMState *jvms = ((CallNode*)call)->jvms();
1268       ciMethodData* methodData = jvms->method()->method_data();
1269       if (!methodData->is_mature())  return 0.0f; // No call-site data
1270       ciProfileData* data = methodData->bci_to_data(jvms->bci());
1271       if ((data == NULL) || !data->is_CounterData()) {
1272         // no call profile available, try call's control input
1273         n = n->in(0);
1274         continue;
1275       }
1276       return data->as_CounterData()->count()/FreqCountInvocations;
1277     }
1278     // See if there's a gating IF test
1279     Node *n_c = n->in(0);
1280     if( !n_c->is_If() ) break;       // No estimate available
1281     iff = n_c->as_If();
1282     if( iff->_fcnt != COUNT_UNKNOWN )   // Have a valid count?
1283       // Compute how much count comes on this path
1284       return ((nop == Op_IfTrue) ? iff->_prob : 1.0f - iff->_prob) * iff->_fcnt;
1285     // Have no count info.  Skip dull uncommon-trap like branches.
1286     if( (nop == Op_IfTrue  && iff->_prob < PROB_LIKELY_MAG(5)) ||
1287         (nop == Op_IfFalse && iff->_prob > PROB_UNLIKELY_MAG(5)) )
1288       break;
1289     // Skip through never-taken branch; look for a real loop exit.
1290     n = iff->in(0);
1291   }
1292   return 0.0f;                  // No estimate available
1293 }
1294 
1295 //------------------------------merge_many_backedges---------------------------
1296 // Merge all the backedges from the shared header into a private Region.
1297 // Feed that region as the one backedge to this loop.
1298 void IdealLoopTree::merge_many_backedges( PhaseIdealLoop *phase ) {
1299   uint i;
1300 
1301   // Scan for the top 2 hottest backedges
1302   float hotcnt = 0.0f;
1303   float warmcnt = 0.0f;
1304   uint hot_idx = 0;
1305   // Loop starts at 2 because slot 1 is the fall-in path
1306   for( i = 2; i < _head->req(); i++ ) {
1307     float cnt = estimate_path_freq(_head->in(i));
1308     if( cnt > hotcnt ) {       // Grab hottest path
1309       warmcnt = hotcnt;
1310       hotcnt = cnt;
1311       hot_idx = i;
1312     } else if( cnt > warmcnt ) { // And 2nd hottest path
1313       warmcnt = cnt;
1314     }
1315   }
1316 
1317   // See if the hottest backedge is worthy of being an inner loop
1318   // by being much hotter than the next hottest backedge.
1319   if( hotcnt <= 0.0001 ||
1320       hotcnt < 2.0*warmcnt ) hot_idx = 0;// No hot backedge
1321 
1322   // Peel out the backedges into a private merge point; peel
1323   // them all except optionally hot_idx.
1324   PhaseIterGVN &igvn = phase->_igvn;
1325 
1326   Node *hot_tail = NULL;
1327   // Make a Region for the merge point
1328   Node *r = new RegionNode(1);
1329   for( i = 2; i < _head->req(); i++ ) {
1330     if( i != hot_idx )
1331       r->add_req( _head->in(i) );
1332     else hot_tail = _head->in(i);
1333   }
1334   igvn.register_new_node_with_optimizer(r, _head);
1335   // Plug region into end of loop _head, followed by hot_tail
1336   while( _head->req() > 3 ) _head->del_req( _head->req()-1 );
1337   igvn.replace_input_of(_head, 2, r);
1338   if( hot_idx ) _head->add_req(hot_tail);
1339 
1340   // Split all the Phis up between '_head' loop and the Region 'r'
1341   for (DUIterator_Fast jmax, j = _head->fast_outs(jmax); j < jmax; j++) {
1342     Node *out = _head->fast_out(j);
1343     if( out->is_Phi() ) {
1344       PhiNode* n = out->as_Phi();
1345       igvn.hash_delete(n);      // Delete from hash before hacking edges
1346       Node *hot_phi = NULL;
1347       Node *phi = new PhiNode(r, n->type(), n->adr_type());
1348       // Check all inputs for the ones to peel out
1349       uint j = 1;
1350       for( uint i = 2; i < n->req(); i++ ) {
1351         if( i != hot_idx )
1352           phi->set_req( j++, n->in(i) );
1353         else hot_phi = n->in(i);
1354       }
1355       // Register the phi but do not transform until whole place transforms
1356       igvn.register_new_node_with_optimizer(phi, n);
1357       // Add the merge phi to the old Phi
1358       while( n->req() > 3 ) n->del_req( n->req()-1 );
1359       igvn.replace_input_of(n, 2, phi);
1360       if( hot_idx ) n->add_req(hot_phi);
1361     }
1362   }
1363 
1364 
1365   // Insert a new IdealLoopTree inserted below me.  Turn it into a clone
1366   // of self loop tree.  Turn self into a loop headed by _head and with
1367   // tail being the new merge point.
1368   IdealLoopTree *ilt = new IdealLoopTree( phase, _head, _tail );
1369   phase->set_loop(_tail,ilt);   // Adjust tail
1370   _tail = r;                    // Self's tail is new merge point
1371   phase->set_loop(r,this);
1372   ilt->_child = _child;         // New guy has my children
1373   _child = ilt;                 // Self has new guy as only child
1374   ilt->_parent = this;          // new guy has self for parent
1375   ilt->_nest = _nest;           // Same nesting depth (for now)
1376 
1377   // Starting with 'ilt', look for child loop trees using the same shared
1378   // header.  Flatten these out; they will no longer be loops in the end.
1379   IdealLoopTree **pilt = &_child;
1380   while( ilt ) {
1381     if( ilt->_head == _head ) {
1382       uint i;
1383       for( i = 2; i < _head->req(); i++ )
1384         if( _head->in(i) == ilt->_tail )
1385           break;                // Still a loop
1386       if( i == _head->req() ) { // No longer a loop
1387         // Flatten ilt.  Hang ilt's "_next" list from the end of
1388         // ilt's '_child' list.  Move the ilt's _child up to replace ilt.
1389         IdealLoopTree **cp = &ilt->_child;
1390         while( *cp ) cp = &(*cp)->_next;   // Find end of child list
1391         *cp = ilt->_next;       // Hang next list at end of child list
1392         *pilt = ilt->_child;    // Move child up to replace ilt
1393         ilt->_head = NULL;      // Flag as a loop UNIONED into parent
1394         ilt = ilt->_child;      // Repeat using new ilt
1395         continue;               // do not advance over ilt->_child
1396       }
1397       assert( ilt->_tail == hot_tail, "expected to only find the hot inner loop here" );
1398       phase->set_loop(_head,ilt);
1399     }
1400     pilt = &ilt->_child;        // Advance to next
1401     ilt = *pilt;
1402   }
1403 
1404   if( _child ) fix_parent( _child, this );
1405 }
1406 
1407 //------------------------------beautify_loops---------------------------------
1408 // Split shared headers and insert loop landing pads.
1409 // Insert a LoopNode to replace the RegionNode.
1410 // Return TRUE if loop tree is structurally changed.
1411 bool IdealLoopTree::beautify_loops( PhaseIdealLoop *phase ) {
1412   bool result = false;
1413   // Cache parts in locals for easy
1414   PhaseIterGVN &igvn = phase->_igvn;
1415 
1416   igvn.hash_delete(_head);      // Yank from hash before hacking edges
1417 
1418   // Check for multiple fall-in paths.  Peel off a landing pad if need be.
1419   int fall_in_cnt = 0;
1420   for( uint i = 1; i < _head->req(); i++ )
1421     if( !phase->is_member( this, _head->in(i) ) )
1422       fall_in_cnt++;
1423   assert( fall_in_cnt, "at least 1 fall-in path" );
1424   if( fall_in_cnt > 1 )         // Need a loop landing pad to merge fall-ins
1425     split_fall_in( phase, fall_in_cnt );
1426 
1427   // Swap inputs to the _head and all Phis to move the fall-in edge to
1428   // the left.
1429   fall_in_cnt = 1;
1430   while( phase->is_member( this, _head->in(fall_in_cnt) ) )
1431     fall_in_cnt++;
1432   if( fall_in_cnt > 1 ) {
1433     // Since I am just swapping inputs I do not need to update def-use info
1434     Node *tmp = _head->in(1);
1435     igvn.rehash_node_delayed(_head);
1436     _head->set_req( 1, _head->in(fall_in_cnt) );
1437     _head->set_req( fall_in_cnt, tmp );
1438     // Swap also all Phis
1439     for (DUIterator_Fast imax, i = _head->fast_outs(imax); i < imax; i++) {
1440       Node* phi = _head->fast_out(i);
1441       if( phi->is_Phi() ) {
1442         igvn.rehash_node_delayed(phi); // Yank from hash before hacking edges
1443         tmp = phi->in(1);
1444         phi->set_req( 1, phi->in(fall_in_cnt) );
1445         phi->set_req( fall_in_cnt, tmp );
1446       }
1447     }
1448   }
1449   assert( !phase->is_member( this, _head->in(1) ), "left edge is fall-in" );
1450   assert(  phase->is_member( this, _head->in(2) ), "right edge is loop" );
1451 
1452   // If I am a shared header (multiple backedges), peel off the many
1453   // backedges into a private merge point and use the merge point as
1454   // the one true backedge.
1455   if( _head->req() > 3 ) {
1456     // Merge the many backedges into a single backedge but leave
1457     // the hottest backedge as separate edge for the following peel.
1458     merge_many_backedges( phase );
1459     result = true;
1460   }
1461 
1462   // If I have one hot backedge, peel off myself loop.
1463   // I better be the outermost loop.
1464   if (_head->req() > 3 && !_irreducible) {
1465     split_outer_loop( phase );
1466     result = true;
1467 
1468   } else if (!_head->is_Loop() && !_irreducible) {
1469     // Make a new LoopNode to replace the old loop head
1470     Node *l = new LoopNode( _head->in(1), _head->in(2) );
1471     l = igvn.register_new_node_with_optimizer(l, _head);
1472     phase->set_created_loop_node();
1473     // Go ahead and replace _head
1474     phase->_igvn.replace_node( _head, l );
1475     _head = l;
1476     phase->set_loop(_head, this);
1477   }
1478 
1479   // Now recursively beautify nested loops
1480   if( _child ) result |= _child->beautify_loops( phase );
1481   if( _next  ) result |= _next ->beautify_loops( phase );
1482   return result;
1483 }
1484 
1485 //------------------------------allpaths_check_safepts----------------------------
1486 // Allpaths backwards scan from loop tail, terminating each path at first safepoint
1487 // encountered.  Helper for check_safepts.
1488 void IdealLoopTree::allpaths_check_safepts(VectorSet &visited, Node_List &stack) {
1489   assert(stack.size() == 0, "empty stack");
1490   stack.push(_tail);
1491   visited.Clear();
1492   visited.set(_tail->_idx);
1493   while (stack.size() > 0) {
1494     Node* n = stack.pop();
1495     if (n->is_Call() && n->as_Call()->guaranteed_safepoint()) {
1496       // Terminate this path
1497     } else if (n->Opcode() == Op_SafePoint) {
1498       if (_phase->get_loop(n) != this) {
1499         if (_required_safept == NULL) _required_safept = new Node_List();
1500         _required_safept->push(n);  // save the one closest to the tail
1501       }
1502       // Terminate this path
1503     } else {
1504       uint start = n->is_Region() ? 1 : 0;
1505       uint end   = n->is_Region() && !n->is_Loop() ? n->req() : start + 1;
1506       for (uint i = start; i < end; i++) {
1507         Node* in = n->in(i);
1508         assert(in->is_CFG(), "must be");
1509         if (!visited.test_set(in->_idx) && is_member(_phase->get_loop(in))) {
1510           stack.push(in);
1511         }
1512       }
1513     }
1514   }
1515 }
1516 
1517 //------------------------------check_safepts----------------------------
1518 // Given dominators, try to find loops with calls that must always be
1519 // executed (call dominates loop tail).  These loops do not need non-call
1520 // safepoints (ncsfpt).
1521 //
1522 // A complication is that a safepoint in a inner loop may be needed
1523 // by an outer loop. In the following, the inner loop sees it has a
1524 // call (block 3) on every path from the head (block 2) to the
1525 // backedge (arc 3->2).  So it deletes the ncsfpt (non-call safepoint)
1526 // in block 2, _but_ this leaves the outer loop without a safepoint.
1527 //
1528 //          entry  0
1529 //                 |
1530 //                 v
1531 // outer 1,2    +->1
1532 //              |  |
1533 //              |  v
1534 //              |  2<---+  ncsfpt in 2
1535 //              |_/|\   |
1536 //                 | v  |
1537 // inner 2,3      /  3  |  call in 3
1538 //               /   |  |
1539 //              v    +--+
1540 //        exit  4
1541 //
1542 //
1543 // This method creates a list (_required_safept) of ncsfpt nodes that must
1544 // be protected is created for each loop. When a ncsfpt maybe deleted, it
1545 // is first looked for in the lists for the outer loops of the current loop.
1546 //
1547 // The insights into the problem:
1548 //  A) counted loops are okay
1549 //  B) innermost loops are okay (only an inner loop can delete
1550 //     a ncsfpt needed by an outer loop)
1551 //  C) a loop is immune from an inner loop deleting a safepoint
1552 //     if the loop has a call on the idom-path
1553 //  D) a loop is also immune if it has a ncsfpt (non-call safepoint) on the
1554 //     idom-path that is not in a nested loop
1555 //  E) otherwise, an ncsfpt on the idom-path that is nested in an inner
1556 //     loop needs to be prevented from deletion by an inner loop
1557 //
1558 // There are two analyses:
1559 //  1) The first, and cheaper one, scans the loop body from
1560 //     tail to head following the idom (immediate dominator)
1561 //     chain, looking for the cases (C,D,E) above.
1562 //     Since inner loops are scanned before outer loops, there is summary
1563 //     information about inner loops.  Inner loops can be skipped over
1564 //     when the tail of an inner loop is encountered.
1565 //
1566 //  2) The second, invoked if the first fails to find a call or ncsfpt on
1567 //     the idom path (which is rare), scans all predecessor control paths
1568 //     from the tail to the head, terminating a path when a call or sfpt
1569 //     is encountered, to find the ncsfpt's that are closest to the tail.
1570 //
1571 void IdealLoopTree::check_safepts(VectorSet &visited, Node_List &stack) {
1572   // Bottom up traversal
1573   IdealLoopTree* ch = _child;
1574   if (_child) _child->check_safepts(visited, stack);
1575   if (_next)  _next ->check_safepts(visited, stack);
1576 
1577   if (!_head->is_CountedLoop() && !_has_sfpt && _parent != NULL && !_irreducible) {
1578     bool  has_call         = false; // call on dom-path
1579     bool  has_local_ncsfpt = false; // ncsfpt on dom-path at this loop depth
1580     Node* nonlocal_ncsfpt  = NULL;  // ncsfpt on dom-path at a deeper depth
1581     // Scan the dom-path nodes from tail to head
1582     for (Node* n = tail(); n != _head; n = _phase->idom(n)) {
1583       if (n->is_Call() && n->as_Call()->guaranteed_safepoint()) {
1584         has_call = true;
1585         _has_sfpt = 1;          // Then no need for a safept!
1586         break;
1587       } else if (n->Opcode() == Op_SafePoint) {
1588         if (_phase->get_loop(n) == this) {
1589           has_local_ncsfpt = true;
1590           break;
1591         }
1592         if (nonlocal_ncsfpt == NULL) {
1593           nonlocal_ncsfpt = n; // save the one closest to the tail
1594         }
1595       } else {
1596         IdealLoopTree* nlpt = _phase->get_loop(n);
1597         if (this != nlpt) {
1598           // If at an inner loop tail, see if the inner loop has already
1599           // recorded seeing a call on the dom-path (and stop.)  If not,
1600           // jump to the head of the inner loop.
1601           assert(is_member(nlpt), "nested loop");
1602           Node* tail = nlpt->_tail;
1603           if (tail->in(0)->is_If()) tail = tail->in(0);
1604           if (n == tail) {
1605             // If inner loop has call on dom-path, so does outer loop
1606             if (nlpt->_has_sfpt) {
1607               has_call = true;
1608               _has_sfpt = 1;
1609               break;
1610             }
1611             // Skip to head of inner loop
1612             assert(_phase->is_dominator(_head, nlpt->_head), "inner head dominated by outer head");
1613             n = nlpt->_head;
1614           }
1615         }
1616       }
1617     }
1618     // Record safept's that this loop needs preserved when an
1619     // inner loop attempts to delete it's safepoints.
1620     if (_child != NULL && !has_call && !has_local_ncsfpt) {
1621       if (nonlocal_ncsfpt != NULL) {
1622         if (_required_safept == NULL) _required_safept = new Node_List();
1623         _required_safept->push(nonlocal_ncsfpt);
1624       } else {
1625         // Failed to find a suitable safept on the dom-path.  Now use
1626         // an all paths walk from tail to head, looking for safepoints to preserve.
1627         allpaths_check_safepts(visited, stack);
1628       }
1629     }
1630   }
1631 }
1632 
1633 //---------------------------is_deleteable_safept----------------------------
1634 // Is safept not required by an outer loop?
1635 bool PhaseIdealLoop::is_deleteable_safept(Node* sfpt) {
1636   assert(sfpt->Opcode() == Op_SafePoint, "");
1637   IdealLoopTree* lp = get_loop(sfpt)->_parent;
1638   while (lp != NULL) {
1639     Node_List* sfpts = lp->_required_safept;
1640     if (sfpts != NULL) {
1641       for (uint i = 0; i < sfpts->size(); i++) {
1642         if (sfpt == sfpts->at(i))
1643           return false;
1644       }
1645     }
1646     lp = lp->_parent;
1647   }
1648   return true;
1649 }
1650 
1651 //---------------------------replace_parallel_iv-------------------------------
1652 // Replace parallel induction variable (parallel to trip counter)
1653 void PhaseIdealLoop::replace_parallel_iv(IdealLoopTree *loop) {
1654   assert(loop->_head->is_CountedLoop(), "");
1655   CountedLoopNode *cl = loop->_head->as_CountedLoop();
1656   if (!cl->is_valid_counted_loop())
1657     return;         // skip malformed counted loop
1658   Node *incr = cl->incr();
1659   if (incr == NULL)
1660     return;         // Dead loop?
1661   Node *init = cl->init_trip();
1662   Node *phi  = cl->phi();
1663   int stride_con = cl->stride_con();
1664 
1665   // Visit all children, looking for Phis
1666   for (DUIterator i = cl->outs(); cl->has_out(i); i++) {
1667     Node *out = cl->out(i);
1668     // Look for other phis (secondary IVs). Skip dead ones
1669     if (!out->is_Phi() || out == phi || !has_node(out))
1670       continue;
1671     PhiNode* phi2 = out->as_Phi();
1672     Node *incr2 = phi2->in( LoopNode::LoopBackControl );
1673     // Look for induction variables of the form:  X += constant
1674     if (phi2->region() != loop->_head ||
1675         incr2->req() != 3 ||
1676         incr2->in(1) != phi2 ||
1677         incr2 == incr ||
1678         incr2->Opcode() != Op_AddI ||
1679         !incr2->in(2)->is_Con())
1680       continue;
1681 
1682     // Check for parallel induction variable (parallel to trip counter)
1683     // via an affine function.  In particular, count-down loops with
1684     // count-up array indices are common. We only RCE references off
1685     // the trip-counter, so we need to convert all these to trip-counter
1686     // expressions.
1687     Node *init2 = phi2->in( LoopNode::EntryControl );
1688     int stride_con2 = incr2->in(2)->get_int();
1689 
1690     // The ratio of the two strides cannot be represented as an int
1691     // if stride_con2 is min_int and stride_con is -1.
1692     if (stride_con2 == min_jint && stride_con == -1) {
1693       continue;
1694     }
1695 
1696     // The general case here gets a little tricky.  We want to find the
1697     // GCD of all possible parallel IV's and make a new IV using this
1698     // GCD for the loop.  Then all possible IVs are simple multiples of
1699     // the GCD.  In practice, this will cover very few extra loops.
1700     // Instead we require 'stride_con2' to be a multiple of 'stride_con',
1701     // where +/-1 is the common case, but other integer multiples are
1702     // also easy to handle.
1703     int ratio_con = stride_con2/stride_con;
1704 
1705     if ((ratio_con * stride_con) == stride_con2) { // Check for exact
1706 #ifndef PRODUCT
1707       if (TraceLoopOpts) {
1708         tty->print("Parallel IV: %d ", phi2->_idx);
1709         loop->dump_head();
1710       }
1711 #endif
1712       // Convert to using the trip counter.  The parallel induction
1713       // variable differs from the trip counter by a loop-invariant
1714       // amount, the difference between their respective initial values.
1715       // It is scaled by the 'ratio_con'.
1716       Node* ratio = _igvn.intcon(ratio_con);
1717       set_ctrl(ratio, C->root());
1718       Node* ratio_init = new MulINode(init, ratio);
1719       _igvn.register_new_node_with_optimizer(ratio_init, init);
1720       set_early_ctrl(ratio_init);
1721       Node* diff = new SubINode(init2, ratio_init);
1722       _igvn.register_new_node_with_optimizer(diff, init2);
1723       set_early_ctrl(diff);
1724       Node* ratio_idx = new MulINode(phi, ratio);
1725       _igvn.register_new_node_with_optimizer(ratio_idx, phi);
1726       set_ctrl(ratio_idx, cl);
1727       Node* add = new AddINode(ratio_idx, diff);
1728       _igvn.register_new_node_with_optimizer(add);
1729       set_ctrl(add, cl);
1730       _igvn.replace_node( phi2, add );
1731       // Sometimes an induction variable is unused
1732       if (add->outcnt() == 0) {
1733         _igvn.remove_dead_node(add);
1734       }
1735       --i; // deleted this phi; rescan starting with next position
1736       continue;
1737     }
1738   }
1739 }
1740 
1741 void IdealLoopTree::remove_safepoints(PhaseIdealLoop* phase, bool keep_one) {
1742   Node* keep = NULL;
1743   if (keep_one) {
1744     // Look for a safepoint on the idom-path.
1745     for (Node* i = tail(); i != _head; i = phase->idom(i)) {
1746       if (i->Opcode() == Op_SafePoint && phase->get_loop(i) == this) {
1747         keep = i;
1748         break; // Found one
1749       }
1750     }
1751   }
1752 
1753   // Don't remove any safepoints if it is requested to keep a single safepoint and
1754   // no safepoint was found on idom-path. It is not safe to remove any safepoint
1755   // in this case since there's no safepoint dominating all paths in the loop body.
1756   bool prune = !keep_one || keep != NULL;
1757 
1758   // Delete other safepoints in this loop.
1759   Node_List* sfpts = _safepts;
1760   if (prune && sfpts != NULL) {
1761     assert(keep == NULL || keep->Opcode() == Op_SafePoint, "not safepoint");
1762     for (uint i = 0; i < sfpts->size(); i++) {
1763       Node* n = sfpts->at(i);
1764       assert(phase->get_loop(n) == this, "");
1765       if (n != keep && phase->is_deleteable_safept(n)) {
1766         phase->lazy_replace(n, n->in(TypeFunc::Control));
1767       }
1768     }
1769   }
1770 }
1771 
1772 //------------------------------counted_loop-----------------------------------
1773 // Convert to counted loops where possible
1774 void IdealLoopTree::counted_loop( PhaseIdealLoop *phase ) {
1775 
1776   // For grins, set the inner-loop flag here
1777   if (!_child) {
1778     if (_head->is_Loop()) _head->as_Loop()->set_inner_loop();
1779   }
1780 
1781   if (_head->is_CountedLoop() ||
1782       phase->is_counted_loop(_head, this)) {
1783 
1784     if (!UseCountedLoopSafepoints) {
1785       // Indicate we do not need a safepoint here
1786       _has_sfpt = 1;
1787     }
1788 
1789     // Remove safepoints
1790     bool keep_one_sfpt = !(_has_call || _has_sfpt);
1791     remove_safepoints(phase, keep_one_sfpt);
1792 
1793     // Look for induction variables
1794     phase->replace_parallel_iv(this);
1795 
1796   } else if (_parent != NULL && !_irreducible) {
1797     // Not a counted loop. Keep one safepoint.
1798     bool keep_one_sfpt = true;
1799     remove_safepoints(phase, keep_one_sfpt);
1800   }
1801 
1802   // Recursively
1803   if (_child) _child->counted_loop( phase );
1804   if (_next)  _next ->counted_loop( phase );
1805 }
1806 
1807 #ifndef PRODUCT
1808 //------------------------------dump_head--------------------------------------
1809 // Dump 1 liner for loop header info
1810 void IdealLoopTree::dump_head( ) const {
1811   for (uint i=0; i<_nest; i++)
1812     tty->print("  ");
1813   tty->print("Loop: N%d/N%d ",_head->_idx,_tail->_idx);
1814   if (_irreducible) tty->print(" IRREDUCIBLE");
1815   Node* entry = _head->in(LoopNode::EntryControl);
1816   Node* predicate = PhaseIdealLoop::find_predicate_insertion_point(entry, Deoptimization::Reason_loop_limit_check);
1817   if (predicate != NULL ) {
1818     tty->print(" limit_check");
1819     entry = entry->in(0)->in(0);
1820   }
1821   if (UseLoopPredicate) {
1822     entry = PhaseIdealLoop::find_predicate_insertion_point(entry, Deoptimization::Reason_predicate);
1823     if (entry != NULL) {
1824       tty->print(" predicated");
1825     }
1826   }
1827   if (_head->is_CountedLoop()) {
1828     CountedLoopNode *cl = _head->as_CountedLoop();
1829     tty->print(" counted");
1830 
1831     Node* init_n = cl->init_trip();
1832     if (init_n  != NULL &&  init_n->is_Con())
1833       tty->print(" [%d,", cl->init_trip()->get_int());
1834     else
1835       tty->print(" [int,");
1836     Node* limit_n = cl->limit();
1837     if (limit_n  != NULL &&  limit_n->is_Con())
1838       tty->print("%d),", cl->limit()->get_int());
1839     else
1840       tty->print("int),");
1841     int stride_con  = cl->stride_con();
1842     if (stride_con > 0) tty->print("+");
1843     tty->print("%d", stride_con);
1844 
1845     tty->print(" (%0.f iters) ", cl->profile_trip_cnt());
1846 
1847     if (cl->is_pre_loop ()) tty->print(" pre" );
1848     if (cl->is_main_loop()) tty->print(" main");
1849     if (cl->is_post_loop()) tty->print(" post");
1850     if (cl->is_vectorized_loop()) tty->print(" vector");
1851     if (cl->range_checks_present()) tty->print(" rc ");
1852     if (cl->is_multiversioned()) tty->print(" multi ");
1853   }
1854   if (_has_call) tty->print(" has_call");
1855   if (_has_sfpt) tty->print(" has_sfpt");
1856   if (_rce_candidate) tty->print(" rce");
1857   if (_safepts != NULL && _safepts->size() > 0) {
1858     tty->print(" sfpts={"); _safepts->dump_simple(); tty->print(" }");
1859   }
1860   if (_required_safept != NULL && _required_safept->size() > 0) {
1861     tty->print(" req={"); _required_safept->dump_simple(); tty->print(" }");
1862   }
1863   if (Verbose) {
1864     tty->print(" body={"); _body.dump_simple(); tty->print(" }");
1865   }
1866   tty->cr();
1867 }
1868 
1869 //------------------------------dump-------------------------------------------
1870 // Dump loops by loop tree
1871 void IdealLoopTree::dump( ) const {
1872   dump_head();
1873   if (_child) _child->dump();
1874   if (_next)  _next ->dump();
1875 }
1876 
1877 #endif
1878 
1879 static void log_loop_tree(IdealLoopTree* root, IdealLoopTree* loop, CompileLog* log) {
1880   if (loop == root) {
1881     if (loop->_child != NULL) {
1882       log->begin_head("loop_tree");
1883       log->end_head();
1884       if( loop->_child ) log_loop_tree(root, loop->_child, log);
1885       log->tail("loop_tree");
1886       assert(loop->_next == NULL, "what?");
1887     }
1888   } else {
1889     Node* head = loop->_head;
1890     log->begin_head("loop");
1891     log->print(" idx='%d' ", head->_idx);
1892     if (loop->_irreducible) log->print("irreducible='1' ");
1893     if (head->is_Loop()) {
1894       if (head->as_Loop()->is_inner_loop()) log->print("inner_loop='1' ");
1895       if (head->as_Loop()->is_partial_peel_loop()) log->print("partial_peel_loop='1' ");
1896     }
1897     if (head->is_CountedLoop()) {
1898       CountedLoopNode* cl = head->as_CountedLoop();
1899       if (cl->is_pre_loop())  log->print("pre_loop='%d' ",  cl->main_idx());
1900       if (cl->is_main_loop()) log->print("main_loop='%d' ", cl->_idx);
1901       if (cl->is_post_loop()) log->print("post_loop='%d' ",  cl->main_idx());
1902     }
1903     log->end_head();
1904     if( loop->_child ) log_loop_tree(root, loop->_child, log);
1905     log->tail("loop");
1906     if( loop->_next  ) log_loop_tree(root, loop->_next, log);
1907   }
1908 }
1909 
1910 //---------------------collect_potentially_useful_predicates-----------------------
1911 // Helper function to collect potentially useful predicates to prevent them from
1912 // being eliminated by PhaseIdealLoop::eliminate_useless_predicates
1913 void PhaseIdealLoop::collect_potentially_useful_predicates(
1914                          IdealLoopTree * loop, Unique_Node_List &useful_predicates) {
1915   if (loop->_child) { // child
1916     collect_potentially_useful_predicates(loop->_child, useful_predicates);
1917   }
1918 
1919   // self (only loops that we can apply loop predication may use their predicates)
1920   if (loop->_head->is_Loop() &&
1921       !loop->_irreducible    &&
1922       !loop->tail()->is_top()) {
1923     LoopNode* lpn = loop->_head->as_Loop();
1924     Node* entry = lpn->in(LoopNode::EntryControl);
1925     Node* predicate_proj = find_predicate(entry); // loop_limit_check first
1926     if (predicate_proj != NULL ) { // right pattern that can be used by loop predication
1927       assert(entry->in(0)->in(1)->in(1)->Opcode() == Op_Opaque1, "must be");
1928       useful_predicates.push(entry->in(0)->in(1)->in(1)); // good one
1929       entry = entry->in(0)->in(0);
1930     }
1931     predicate_proj = find_predicate(entry); // Predicate
1932     if (predicate_proj != NULL ) {
1933       useful_predicates.push(entry->in(0)->in(1)->in(1)); // good one
1934     }
1935   }
1936 
1937   if (loop->_next) { // sibling
1938     collect_potentially_useful_predicates(loop->_next, useful_predicates);
1939   }
1940 }
1941 
1942 //------------------------eliminate_useless_predicates-----------------------------
1943 // Eliminate all inserted predicates if they could not be used by loop predication.
1944 // Note: it will also eliminates loop limits check predicate since it also uses
1945 // Opaque1 node (see Parse::add_predicate()).
1946 void PhaseIdealLoop::eliminate_useless_predicates() {
1947   if (C->predicate_count() == 0)
1948     return; // no predicate left
1949 
1950   Unique_Node_List useful_predicates; // to store useful predicates
1951   if (C->has_loops()) {
1952     collect_potentially_useful_predicates(_ltree_root->_child, useful_predicates);
1953   }
1954 
1955   for (int i = C->predicate_count(); i > 0; i--) {
1956      Node * n = C->predicate_opaque1_node(i-1);
1957      assert(n->Opcode() == Op_Opaque1, "must be");
1958      if (!useful_predicates.member(n)) { // not in the useful list
1959        _igvn.replace_node(n, n->in(1));
1960      }
1961   }
1962 }
1963 
1964 //------------------------process_expensive_nodes-----------------------------
1965 // Expensive nodes have their control input set to prevent the GVN
1966 // from commoning them and as a result forcing the resulting node to
1967 // be in a more frequent path. Use CFG information here, to change the
1968 // control inputs so that some expensive nodes can be commoned while
1969 // not executed more frequently.
1970 bool PhaseIdealLoop::process_expensive_nodes() {
1971   assert(OptimizeExpensiveOps, "optimization off?");
1972 
1973   // Sort nodes to bring similar nodes together
1974   C->sort_expensive_nodes();
1975 
1976   bool progress = false;
1977 
1978   for (int i = 0; i < C->expensive_count(); ) {
1979     Node* n = C->expensive_node(i);
1980     int start = i;
1981     // Find nodes similar to n
1982     i++;
1983     for (; i < C->expensive_count() && Compile::cmp_expensive_nodes(n, C->expensive_node(i)) == 0; i++);
1984     int end = i;
1985     // And compare them two by two
1986     for (int j = start; j < end; j++) {
1987       Node* n1 = C->expensive_node(j);
1988       if (is_node_unreachable(n1)) {
1989         continue;
1990       }
1991       for (int k = j+1; k < end; k++) {
1992         Node* n2 = C->expensive_node(k);
1993         if (is_node_unreachable(n2)) {
1994           continue;
1995         }
1996 
1997         assert(n1 != n2, "should be pair of nodes");
1998 
1999         Node* c1 = n1->in(0);
2000         Node* c2 = n2->in(0);
2001 
2002         Node* parent_c1 = c1;
2003         Node* parent_c2 = c2;
2004 
2005         // The call to get_early_ctrl_for_expensive() moves the
2006         // expensive nodes up but stops at loops that are in a if
2007         // branch. See whether we can exit the loop and move above the
2008         // If.
2009         if (c1->is_Loop()) {
2010           parent_c1 = c1->in(1);
2011         }
2012         if (c2->is_Loop()) {
2013           parent_c2 = c2->in(1);
2014         }
2015 
2016         if (parent_c1 == parent_c2) {
2017           _igvn._worklist.push(n1);
2018           _igvn._worklist.push(n2);
2019           continue;
2020         }
2021 
2022         // Look for identical expensive node up the dominator chain.
2023         if (is_dominator(c1, c2)) {
2024           c2 = c1;
2025         } else if (is_dominator(c2, c1)) {
2026           c1 = c2;
2027         } else if (parent_c1->is_Proj() && parent_c1->in(0)->is_If() &&
2028                    parent_c2->is_Proj() && parent_c1->in(0) == parent_c2->in(0)) {
2029           // Both branches have the same expensive node so move it up
2030           // before the if.
2031           c1 = c2 = idom(parent_c1->in(0));
2032         }
2033         // Do the actual moves
2034         if (n1->in(0) != c1) {
2035           _igvn.hash_delete(n1);
2036           n1->set_req(0, c1);
2037           _igvn.hash_insert(n1);
2038           _igvn._worklist.push(n1);
2039           progress = true;
2040         }
2041         if (n2->in(0) != c2) {
2042           _igvn.hash_delete(n2);
2043           n2->set_req(0, c2);
2044           _igvn.hash_insert(n2);
2045           _igvn._worklist.push(n2);
2046           progress = true;
2047         }
2048       }
2049     }
2050   }
2051 
2052   return progress;
2053 }
2054 
2055 
2056 //=============================================================================
2057 //----------------------------build_and_optimize-------------------------------
2058 // Create a PhaseLoop.  Build the ideal Loop tree.  Map each Ideal Node to
2059 // its corresponding LoopNode.  If 'optimize' is true, do some loop cleanups.
2060 void PhaseIdealLoop::build_and_optimize(bool do_split_ifs, bool skip_loop_opts) {
2061   ResourceMark rm;
2062 
2063   int old_progress = C->major_progress();
2064   uint orig_worklist_size = _igvn._worklist.size();
2065 
2066   // Reset major-progress flag for the driver's heuristics
2067   C->clear_major_progress();
2068 
2069 #ifndef PRODUCT
2070   // Capture for later assert
2071   uint unique = C->unique();
2072   _loop_invokes++;
2073   _loop_work += unique;
2074 #endif
2075 
2076   // True if the method has at least 1 irreducible loop
2077   _has_irreducible_loops = false;
2078 
2079   _created_loop_node = false;
2080 
2081   Arena *a = Thread::current()->resource_area();
2082   VectorSet visited(a);
2083   // Pre-grow the mapping from Nodes to IdealLoopTrees.
2084   _nodes.map(C->unique(), NULL);
2085   memset(_nodes.adr(), 0, wordSize * C->unique());
2086 
2087   // Pre-build the top-level outermost loop tree entry
2088   _ltree_root = new IdealLoopTree( this, C->root(), C->root() );
2089   // Do not need a safepoint at the top level
2090   _ltree_root->_has_sfpt = 1;
2091 
2092   // Initialize Dominators.
2093   // Checked in clone_loop_predicate() during beautify_loops().
2094   _idom_size = 0;
2095   _idom      = NULL;
2096   _dom_depth = NULL;
2097   _dom_stk   = NULL;
2098 
2099   // Empty pre-order array
2100   allocate_preorders();
2101 
2102   // Build a loop tree on the fly.  Build a mapping from CFG nodes to
2103   // IdealLoopTree entries.  Data nodes are NOT walked.
2104   build_loop_tree();
2105   // Check for bailout, and return
2106   if (C->failing()) {
2107     return;
2108   }
2109 
2110   // No loops after all
2111   if( !_ltree_root->_child && !_verify_only ) C->set_has_loops(false);
2112 
2113   // There should always be an outer loop containing the Root and Return nodes.
2114   // If not, we have a degenerate empty program.  Bail out in this case.
2115   if (!has_node(C->root())) {
2116     if (!_verify_only) {
2117       C->clear_major_progress();
2118       C->record_method_not_compilable("empty program detected during loop optimization");
2119     }
2120     return;
2121   }
2122 
2123   // Nothing to do, so get out
2124   bool stop_early = !C->has_loops() && !skip_loop_opts && !do_split_ifs && !_verify_me && !_verify_only;
2125   bool do_expensive_nodes = C->should_optimize_expensive_nodes(_igvn);
2126   if (stop_early && !do_expensive_nodes) {
2127     _igvn.optimize();           // Cleanup NeverBranches
2128     return;
2129   }
2130 
2131   // Set loop nesting depth
2132   _ltree_root->set_nest( 0 );
2133 
2134   // Split shared headers and insert loop landing pads.
2135   // Do not bother doing this on the Root loop of course.
2136   if( !_verify_me && !_verify_only && _ltree_root->_child ) {
2137     C->print_method(PHASE_BEFORE_BEAUTIFY_LOOPS, 3);
2138     if( _ltree_root->_child->beautify_loops( this ) ) {
2139       // Re-build loop tree!
2140       _ltree_root->_child = NULL;
2141       _nodes.clear();
2142       reallocate_preorders();
2143       build_loop_tree();
2144       // Check for bailout, and return
2145       if (C->failing()) {
2146         return;
2147       }
2148       // Reset loop nesting depth
2149       _ltree_root->set_nest( 0 );
2150 
2151       C->print_method(PHASE_AFTER_BEAUTIFY_LOOPS, 3);
2152     }
2153   }
2154 
2155   // Build Dominators for elision of NULL checks & loop finding.
2156   // Since nodes do not have a slot for immediate dominator, make
2157   // a persistent side array for that info indexed on node->_idx.
2158   _idom_size = C->unique();
2159   _idom      = NEW_RESOURCE_ARRAY( Node*, _idom_size );
2160   _dom_depth = NEW_RESOURCE_ARRAY( uint,  _idom_size );
2161   _dom_stk   = NULL; // Allocated on demand in recompute_dom_depth
2162   memset( _dom_depth, 0, _idom_size * sizeof(uint) );
2163 
2164   Dominators();
2165 
2166   if (!_verify_only) {
2167     // As a side effect, Dominators removed any unreachable CFG paths
2168     // into RegionNodes.  It doesn't do this test against Root, so
2169     // we do it here.
2170     for( uint i = 1; i < C->root()->req(); i++ ) {
2171       if( !_nodes[C->root()->in(i)->_idx] ) {    // Dead path into Root?
2172         _igvn.delete_input_of(C->root(), i);
2173         i--;                      // Rerun same iteration on compressed edges
2174       }
2175     }
2176 
2177     // Given dominators, try to find inner loops with calls that must
2178     // always be executed (call dominates loop tail).  These loops do
2179     // not need a separate safepoint.
2180     Node_List cisstack(a);
2181     _ltree_root->check_safepts(visited, cisstack);
2182   }
2183 
2184   // Walk the DATA nodes and place into loops.  Find earliest control
2185   // node.  For CFG nodes, the _nodes array starts out and remains
2186   // holding the associated IdealLoopTree pointer.  For DATA nodes, the
2187   // _nodes array holds the earliest legal controlling CFG node.
2188 
2189   // Allocate stack with enough space to avoid frequent realloc
2190   int stack_size = (C->live_nodes() >> 1) + 16; // (live_nodes>>1)+16 from Java2D stats
2191   Node_Stack nstack( a, stack_size );
2192 
2193   visited.Clear();
2194   Node_List worklist(a);
2195   // Don't need C->root() on worklist since
2196   // it will be processed among C->top() inputs
2197   worklist.push( C->top() );
2198   visited.set( C->top()->_idx ); // Set C->top() as visited now
2199   build_loop_early( visited, worklist, nstack );
2200 
2201   // Given early legal placement, try finding counted loops.  This placement
2202   // is good enough to discover most loop invariants.
2203   if( !_verify_me && !_verify_only )
2204     _ltree_root->counted_loop( this );
2205 
2206   // Find latest loop placement.  Find ideal loop placement.
2207   visited.Clear();
2208   init_dom_lca_tags();
2209   // Need C->root() on worklist when processing outs
2210   worklist.push( C->root() );
2211   NOT_PRODUCT( C->verify_graph_edges(); )
2212   worklist.push( C->top() );
2213   build_loop_late( visited, worklist, nstack );
2214 
2215   if (_verify_only) {
2216     // restore major progress flag
2217     for (int i = 0; i < old_progress; i++)
2218       C->set_major_progress();
2219     assert(C->unique() == unique, "verification mode made Nodes? ? ?");
2220     assert(_igvn._worklist.size() == orig_worklist_size, "shouldn't push anything");
2221     return;
2222   }
2223 
2224   // clear out the dead code after build_loop_late
2225   while (_deadlist.size()) {
2226     _igvn.remove_globally_dead_node(_deadlist.pop());
2227   }
2228 
2229   if (stop_early) {
2230     assert(do_expensive_nodes, "why are we here?");
2231     if (process_expensive_nodes()) {
2232       // If we made some progress when processing expensive nodes then
2233       // the IGVN may modify the graph in a way that will allow us to
2234       // make some more progress: we need to try processing expensive
2235       // nodes again.
2236       C->set_major_progress();
2237     }
2238     _igvn.optimize();
2239     return;
2240   }
2241 
2242   // Some parser-inserted loop predicates could never be used by loop
2243   // predication or they were moved away from loop during some optimizations.
2244   // For example, peeling. Eliminate them before next loop optimizations.
2245   eliminate_useless_predicates();
2246 
2247 #ifndef PRODUCT
2248   C->verify_graph_edges();
2249   if (_verify_me) {             // Nested verify pass?
2250     // Check to see if the verify mode is broken
2251     assert(C->unique() == unique, "non-optimize mode made Nodes? ? ?");
2252     return;
2253   }
2254   if(VerifyLoopOptimizations) verify();
2255   if(TraceLoopOpts && C->has_loops()) {
2256     _ltree_root->dump();
2257   }
2258 #endif
2259 
2260   if (skip_loop_opts) {
2261     // restore major progress flag
2262     for (int i = 0; i < old_progress; i++) {
2263       C->set_major_progress();
2264     }
2265 
2266     // Cleanup any modified bits
2267     _igvn.optimize();
2268 
2269     if (C->log() != NULL) {
2270       log_loop_tree(_ltree_root, _ltree_root, C->log());
2271     }
2272     return;
2273   }
2274 
2275   if (ReassociateInvariants) {
2276     // Reassociate invariants and prep for split_thru_phi
2277     for (LoopTreeIterator iter(_ltree_root); !iter.done(); iter.next()) {
2278       IdealLoopTree* lpt = iter.current();
2279       bool is_counted = lpt->is_counted();
2280       if (!is_counted || !lpt->is_inner()) continue;
2281 
2282       // check for vectorized loops, any reassociation of invariants was already done
2283       if (is_counted && lpt->_head->as_CountedLoop()->do_unroll_only()) continue;
2284 
2285       lpt->reassociate_invariants(this);
2286 
2287       // Because RCE opportunities can be masked by split_thru_phi,
2288       // look for RCE candidates and inhibit split_thru_phi
2289       // on just their loop-phi's for this pass of loop opts
2290       if (SplitIfBlocks && do_split_ifs) {
2291         if (lpt->policy_range_check(this)) {
2292           lpt->_rce_candidate = 1; // = true
2293         }
2294       }
2295     }
2296   }
2297 
2298   // Check for aggressive application of split-if and other transforms
2299   // that require basic-block info (like cloning through Phi's)
2300   if( SplitIfBlocks && do_split_ifs ) {
2301     visited.Clear();
2302     split_if_with_blocks( visited, nstack );
2303     NOT_PRODUCT( if( VerifyLoopOptimizations ) verify(); );
2304   }
2305 
2306   if (!C->major_progress() && do_expensive_nodes && process_expensive_nodes()) {
2307     C->set_major_progress();
2308   }
2309 
2310   // Perform loop predication before iteration splitting
2311   if (C->has_loops() && !C->major_progress() && (C->predicate_count() > 0)) {
2312     _ltree_root->_child->loop_predication(this);
2313   }
2314 
2315   if (OptimizeFill && UseLoopPredicate && C->has_loops() && !C->major_progress()) {
2316     if (do_intrinsify_fill()) {
2317       C->set_major_progress();
2318     }
2319   }
2320 
2321   // Perform iteration-splitting on inner loops.  Split iterations to avoid
2322   // range checks or one-shot null checks.
2323 
2324   // If split-if's didn't hack the graph too bad (no CFG changes)
2325   // then do loop opts.
2326   if (C->has_loops() && !C->major_progress()) {
2327     memset( worklist.adr(), 0, worklist.Size()*sizeof(Node*) );
2328     _ltree_root->_child->iteration_split( this, worklist );
2329     // No verify after peeling!  GCM has hoisted code out of the loop.
2330     // After peeling, the hoisted code could sink inside the peeled area.
2331     // The peeling code does not try to recompute the best location for
2332     // all the code before the peeled area, so the verify pass will always
2333     // complain about it.
2334   }
2335   // Do verify graph edges in any case
2336   NOT_PRODUCT( C->verify_graph_edges(); );
2337 
2338   if (!do_split_ifs) {
2339     // We saw major progress in Split-If to get here.  We forced a
2340     // pass with unrolling and not split-if, however more split-if's
2341     // might make progress.  If the unrolling didn't make progress
2342     // then the major-progress flag got cleared and we won't try
2343     // another round of Split-If.  In particular the ever-common
2344     // instance-of/check-cast pattern requires at least 2 rounds of
2345     // Split-If to clear out.
2346     C->set_major_progress();
2347   }
2348 
2349   // Repeat loop optimizations if new loops were seen
2350   if (created_loop_node()) {
2351     C->set_major_progress();
2352   }
2353 
2354   // Keep loop predicates and perform optimizations with them
2355   // until no more loop optimizations could be done.
2356   // After that switch predicates off and do more loop optimizations.
2357   if (!C->major_progress() && (C->predicate_count() > 0)) {
2358      C->cleanup_loop_predicates(_igvn);
2359      if (TraceLoopOpts) {
2360        tty->print_cr("PredicatesOff");
2361      }
2362      C->set_major_progress();
2363   }
2364 
2365   // Convert scalar to superword operations at the end of all loop opts.
2366   if (UseSuperWord && C->has_loops() && !C->major_progress()) {
2367     // SuperWord transform
2368     SuperWord sw(this);
2369     for (LoopTreeIterator iter(_ltree_root); !iter.done(); iter.next()) {
2370       IdealLoopTree* lpt = iter.current();
2371       if (lpt->is_counted()) {
2372         CountedLoopNode *cl = lpt->_head->as_CountedLoop();
2373 
2374         if (PostLoopMultiversioning && cl->is_rce_post_loop() && !cl->is_vectorized_loop()) {
2375           // Check that the rce'd post loop is encountered first, multiversion after all
2376           // major main loop optimization are concluded
2377           if (!C->major_progress()) {
2378             IdealLoopTree *lpt_next = lpt->_next;
2379             if (lpt_next && lpt_next->is_counted()) {
2380               CountedLoopNode *cl = lpt_next->_head->as_CountedLoop();
2381               has_range_checks(lpt_next);
2382               if (cl->is_post_loop() && cl->range_checks_present()) {
2383                 if (!cl->is_multiversioned()) {
2384                   if (multi_version_post_loops(lpt, lpt_next) == false) {
2385                     // Cause the rce loop to be optimized away if we fail
2386                     cl->mark_is_multiversioned();
2387                     cl->set_slp_max_unroll(0);
2388                     poison_rce_post_loop(lpt);
2389                   }
2390                 }
2391               }
2392             }
2393             sw.transform_loop(lpt, true);
2394           }
2395         } else if (cl->is_main_loop()) {
2396           sw.transform_loop(lpt, true);
2397         }
2398       }
2399     }
2400   }
2401 
2402   // Cleanup any modified bits
2403   _igvn.optimize();
2404 
2405   // disable assert until issue with split_flow_path is resolved (6742111)
2406   // assert(!_has_irreducible_loops || C->parsed_irreducible_loop() || C->is_osr_compilation(),
2407   //        "shouldn't introduce irreducible loops");
2408 
2409   if (C->log() != NULL) {
2410     log_loop_tree(_ltree_root, _ltree_root, C->log());
2411   }
2412 }
2413 
2414 #ifndef PRODUCT
2415 //------------------------------print_statistics-------------------------------
2416 int PhaseIdealLoop::_loop_invokes=0;// Count of PhaseIdealLoop invokes
2417 int PhaseIdealLoop::_loop_work=0; // Sum of PhaseIdealLoop x unique
2418 void PhaseIdealLoop::print_statistics() {
2419   tty->print_cr("PhaseIdealLoop=%d, sum _unique=%d", _loop_invokes, _loop_work);
2420 }
2421 
2422 //------------------------------verify-----------------------------------------
2423 // Build a verify-only PhaseIdealLoop, and see that it agrees with me.
2424 static int fail;                // debug only, so its multi-thread dont care
2425 void PhaseIdealLoop::verify() const {
2426   int old_progress = C->major_progress();
2427   ResourceMark rm;
2428   PhaseIdealLoop loop_verify( _igvn, this );
2429   VectorSet visited(Thread::current()->resource_area());
2430 
2431   fail = 0;
2432   verify_compare( C->root(), &loop_verify, visited );
2433   assert( fail == 0, "verify loops failed" );
2434   // Verify loop structure is the same
2435   _ltree_root->verify_tree(loop_verify._ltree_root, NULL);
2436   // Reset major-progress.  It was cleared by creating a verify version of
2437   // PhaseIdealLoop.
2438   for( int i=0; i<old_progress; i++ )
2439     C->set_major_progress();
2440 }
2441 
2442 //------------------------------verify_compare---------------------------------
2443 // Make sure me and the given PhaseIdealLoop agree on key data structures
2444 void PhaseIdealLoop::verify_compare( Node *n, const PhaseIdealLoop *loop_verify, VectorSet &visited ) const {
2445   if( !n ) return;
2446   if( visited.test_set( n->_idx ) ) return;
2447   if( !_nodes[n->_idx] ) {      // Unreachable
2448     assert( !loop_verify->_nodes[n->_idx], "both should be unreachable" );
2449     return;
2450   }
2451 
2452   uint i;
2453   for( i = 0; i < n->req(); i++ )
2454     verify_compare( n->in(i), loop_verify, visited );
2455 
2456   // Check the '_nodes' block/loop structure
2457   i = n->_idx;
2458   if( has_ctrl(n) ) {           // We have control; verify has loop or ctrl
2459     if( _nodes[i] != loop_verify->_nodes[i] &&
2460         get_ctrl_no_update(n) != loop_verify->get_ctrl_no_update(n) ) {
2461       tty->print("Mismatched control setting for: ");
2462       n->dump();
2463       if( fail++ > 10 ) return;
2464       Node *c = get_ctrl_no_update(n);
2465       tty->print("We have it as: ");
2466       if( c->in(0) ) c->dump();
2467         else tty->print_cr("N%d",c->_idx);
2468       tty->print("Verify thinks: ");
2469       if( loop_verify->has_ctrl(n) )
2470         loop_verify->get_ctrl_no_update(n)->dump();
2471       else
2472         loop_verify->get_loop_idx(n)->dump();
2473       tty->cr();
2474     }
2475   } else {                    // We have a loop
2476     IdealLoopTree *us = get_loop_idx(n);
2477     if( loop_verify->has_ctrl(n) ) {
2478       tty->print("Mismatched loop setting for: ");
2479       n->dump();
2480       if( fail++ > 10 ) return;
2481       tty->print("We have it as: ");
2482       us->dump();
2483       tty->print("Verify thinks: ");
2484       loop_verify->get_ctrl_no_update(n)->dump();
2485       tty->cr();
2486     } else if (!C->major_progress()) {
2487       // Loop selection can be messed up if we did a major progress
2488       // operation, like split-if.  Do not verify in that case.
2489       IdealLoopTree *them = loop_verify->get_loop_idx(n);
2490       if( us->_head != them->_head ||  us->_tail != them->_tail ) {
2491         tty->print("Unequals loops for: ");
2492         n->dump();
2493         if( fail++ > 10 ) return;
2494         tty->print("We have it as: ");
2495         us->dump();
2496         tty->print("Verify thinks: ");
2497         them->dump();
2498         tty->cr();
2499       }
2500     }
2501   }
2502 
2503   // Check for immediate dominators being equal
2504   if( i >= _idom_size ) {
2505     if( !n->is_CFG() ) return;
2506     tty->print("CFG Node with no idom: ");
2507     n->dump();
2508     return;
2509   }
2510   if( !n->is_CFG() ) return;
2511   if( n == C->root() ) return; // No IDOM here
2512 
2513   assert(n->_idx == i, "sanity");
2514   Node *id = idom_no_update(n);
2515   if( id != loop_verify->idom_no_update(n) ) {
2516     tty->print("Unequals idoms for: ");
2517     n->dump();
2518     if( fail++ > 10 ) return;
2519     tty->print("We have it as: ");
2520     id->dump();
2521     tty->print("Verify thinks: ");
2522     loop_verify->idom_no_update(n)->dump();
2523     tty->cr();
2524   }
2525 
2526 }
2527 
2528 //------------------------------verify_tree------------------------------------
2529 // Verify that tree structures match.  Because the CFG can change, siblings
2530 // within the loop tree can be reordered.  We attempt to deal with that by
2531 // reordering the verify's loop tree if possible.
2532 void IdealLoopTree::verify_tree(IdealLoopTree *loop, const IdealLoopTree *parent) const {
2533   assert( _parent == parent, "Badly formed loop tree" );
2534 
2535   // Siblings not in same order?  Attempt to re-order.
2536   if( _head != loop->_head ) {
2537     // Find _next pointer to update
2538     IdealLoopTree **pp = &loop->_parent->_child;
2539     while( *pp != loop )
2540       pp = &((*pp)->_next);
2541     // Find proper sibling to be next
2542     IdealLoopTree **nn = &loop->_next;
2543     while( (*nn) && (*nn)->_head != _head )
2544       nn = &((*nn)->_next);
2545 
2546     // Check for no match.
2547     if( !(*nn) ) {
2548       // Annoyingly, irreducible loops can pick different headers
2549       // after a major_progress operation, so the rest of the loop
2550       // tree cannot be matched.
2551       if (_irreducible && Compile::current()->major_progress())  return;
2552       assert( 0, "failed to match loop tree" );
2553     }
2554 
2555     // Move (*nn) to (*pp)
2556     IdealLoopTree *hit = *nn;
2557     *nn = hit->_next;
2558     hit->_next = loop;
2559     *pp = loop;
2560     loop = hit;
2561     // Now try again to verify
2562   }
2563 
2564   assert( _head  == loop->_head , "mismatched loop head" );
2565   Node *tail = _tail;           // Inline a non-updating version of
2566   while( !tail->in(0) )         // the 'tail()' call.
2567     tail = tail->in(1);
2568   assert( tail == loop->_tail, "mismatched loop tail" );
2569 
2570   // Counted loops that are guarded should be able to find their guards
2571   if( _head->is_CountedLoop() && _head->as_CountedLoop()->is_main_loop() ) {
2572     CountedLoopNode *cl = _head->as_CountedLoop();
2573     Node *init = cl->init_trip();
2574     Node *ctrl = cl->in(LoopNode::EntryControl);
2575     assert( ctrl->Opcode() == Op_IfTrue || ctrl->Opcode() == Op_IfFalse, "" );
2576     Node *iff  = ctrl->in(0);
2577     assert( iff->Opcode() == Op_If, "" );
2578     Node *bol  = iff->in(1);
2579     assert( bol->Opcode() == Op_Bool, "" );
2580     Node *cmp  = bol->in(1);
2581     assert( cmp->Opcode() == Op_CmpI, "" );
2582     Node *add  = cmp->in(1);
2583     Node *opaq;
2584     if( add->Opcode() == Op_Opaque1 ) {
2585       opaq = add;
2586     } else {
2587       assert( add->Opcode() == Op_AddI || add->Opcode() == Op_ConI , "" );
2588       assert( add == init, "" );
2589       opaq = cmp->in(2);
2590     }
2591     assert( opaq->Opcode() == Op_Opaque1, "" );
2592 
2593   }
2594 
2595   if (_child != NULL)  _child->verify_tree(loop->_child, this);
2596   if (_next  != NULL)  _next ->verify_tree(loop->_next,  parent);
2597   // Innermost loops need to verify loop bodies,
2598   // but only if no 'major_progress'
2599   int fail = 0;
2600   if (!Compile::current()->major_progress() && _child == NULL) {
2601     for( uint i = 0; i < _body.size(); i++ ) {
2602       Node *n = _body.at(i);
2603       if (n->outcnt() == 0)  continue; // Ignore dead
2604       uint j;
2605       for( j = 0; j < loop->_body.size(); j++ )
2606         if( loop->_body.at(j) == n )
2607           break;
2608       if( j == loop->_body.size() ) { // Not found in loop body
2609         // Last ditch effort to avoid assertion: Its possible that we
2610         // have some users (so outcnt not zero) but are still dead.
2611         // Try to find from root.
2612         if (Compile::current()->root()->find(n->_idx)) {
2613           fail++;
2614           tty->print("We have that verify does not: ");
2615           n->dump();
2616         }
2617       }
2618     }
2619     for( uint i2 = 0; i2 < loop->_body.size(); i2++ ) {
2620       Node *n = loop->_body.at(i2);
2621       if (n->outcnt() == 0)  continue; // Ignore dead
2622       uint j;
2623       for( j = 0; j < _body.size(); j++ )
2624         if( _body.at(j) == n )
2625           break;
2626       if( j == _body.size() ) { // Not found in loop body
2627         // Last ditch effort to avoid assertion: Its possible that we
2628         // have some users (so outcnt not zero) but are still dead.
2629         // Try to find from root.
2630         if (Compile::current()->root()->find(n->_idx)) {
2631           fail++;
2632           tty->print("Verify has that we do not: ");
2633           n->dump();
2634         }
2635       }
2636     }
2637     assert( !fail, "loop body mismatch" );
2638   }
2639 }
2640 
2641 #endif
2642 
2643 //------------------------------set_idom---------------------------------------
2644 void PhaseIdealLoop::set_idom(Node* d, Node* n, uint dom_depth) {
2645   uint idx = d->_idx;
2646   if (idx >= _idom_size) {
2647     uint newsize = _idom_size<<1;
2648     while( idx >= newsize ) {
2649       newsize <<= 1;
2650     }
2651     _idom      = REALLOC_RESOURCE_ARRAY( Node*,     _idom,_idom_size,newsize);
2652     _dom_depth = REALLOC_RESOURCE_ARRAY( uint, _dom_depth,_idom_size,newsize);
2653     memset( _dom_depth + _idom_size, 0, (newsize - _idom_size) * sizeof(uint) );
2654     _idom_size = newsize;
2655   }
2656   _idom[idx] = n;
2657   _dom_depth[idx] = dom_depth;
2658 }
2659 
2660 //------------------------------recompute_dom_depth---------------------------------------
2661 // The dominator tree is constructed with only parent pointers.
2662 // This recomputes the depth in the tree by first tagging all
2663 // nodes as "no depth yet" marker.  The next pass then runs up
2664 // the dom tree from each node marked "no depth yet", and computes
2665 // the depth on the way back down.
2666 void PhaseIdealLoop::recompute_dom_depth() {
2667   uint no_depth_marker = C->unique();
2668   uint i;
2669   // Initialize depth to "no depth yet"
2670   for (i = 0; i < _idom_size; i++) {
2671     if (_dom_depth[i] > 0 && _idom[i] != NULL) {
2672      _dom_depth[i] = no_depth_marker;
2673     }
2674   }
2675   if (_dom_stk == NULL) {
2676     uint init_size = C->live_nodes() / 100; // Guess that 1/100 is a reasonable initial size.
2677     if (init_size < 10) init_size = 10;
2678     _dom_stk = new GrowableArray<uint>(init_size);
2679   }
2680   // Compute new depth for each node.
2681   for (i = 0; i < _idom_size; i++) {
2682     uint j = i;
2683     // Run up the dom tree to find a node with a depth
2684     while (_dom_depth[j] == no_depth_marker) {
2685       _dom_stk->push(j);
2686       j = _idom[j]->_idx;
2687     }
2688     // Compute the depth on the way back down this tree branch
2689     uint dd = _dom_depth[j] + 1;
2690     while (_dom_stk->length() > 0) {
2691       uint j = _dom_stk->pop();
2692       _dom_depth[j] = dd;
2693       dd++;
2694     }
2695   }
2696 }
2697 
2698 //------------------------------sort-------------------------------------------
2699 // Insert 'loop' into the existing loop tree.  'innermost' is a leaf of the
2700 // loop tree, not the root.
2701 IdealLoopTree *PhaseIdealLoop::sort( IdealLoopTree *loop, IdealLoopTree *innermost ) {
2702   if( !innermost ) return loop; // New innermost loop
2703 
2704   int loop_preorder = get_preorder(loop->_head); // Cache pre-order number
2705   assert( loop_preorder, "not yet post-walked loop" );
2706   IdealLoopTree **pp = &innermost;      // Pointer to previous next-pointer
2707   IdealLoopTree *l = *pp;               // Do I go before or after 'l'?
2708 
2709   // Insert at start of list
2710   while( l ) {                  // Insertion sort based on pre-order
2711     if( l == loop ) return innermost; // Already on list!
2712     int l_preorder = get_preorder(l->_head); // Cache pre-order number
2713     assert( l_preorder, "not yet post-walked l" );
2714     // Check header pre-order number to figure proper nesting
2715     if( loop_preorder > l_preorder )
2716       break;                    // End of insertion
2717     // If headers tie (e.g., shared headers) check tail pre-order numbers.
2718     // Since I split shared headers, you'd think this could not happen.
2719     // BUT: I must first do the preorder numbering before I can discover I
2720     // have shared headers, so the split headers all get the same preorder
2721     // number as the RegionNode they split from.
2722     if( loop_preorder == l_preorder &&
2723         get_preorder(loop->_tail) < get_preorder(l->_tail) )
2724       break;                    // Also check for shared headers (same pre#)
2725     pp = &l->_parent;           // Chain up list
2726     l = *pp;
2727   }
2728   // Link into list
2729   // Point predecessor to me
2730   *pp = loop;
2731   // Point me to successor
2732   IdealLoopTree *p = loop->_parent;
2733   loop->_parent = l;            // Point me to successor
2734   if( p ) sort( p, innermost ); // Insert my parents into list as well
2735   return innermost;
2736 }
2737 
2738 //------------------------------build_loop_tree--------------------------------
2739 // I use a modified Vick/Tarjan algorithm.  I need pre- and a post- visit
2740 // bits.  The _nodes[] array is mapped by Node index and holds a NULL for
2741 // not-yet-pre-walked, pre-order # for pre-but-not-post-walked and holds the
2742 // tightest enclosing IdealLoopTree for post-walked.
2743 //
2744 // During my forward walk I do a short 1-layer lookahead to see if I can find
2745 // a loop backedge with that doesn't have any work on the backedge.  This
2746 // helps me construct nested loops with shared headers better.
2747 //
2748 // Once I've done the forward recursion, I do the post-work.  For each child
2749 // I check to see if there is a backedge.  Backedges define a loop!  I
2750 // insert an IdealLoopTree at the target of the backedge.
2751 //
2752 // During the post-work I also check to see if I have several children
2753 // belonging to different loops.  If so, then this Node is a decision point
2754 // where control flow can choose to change loop nests.  It is at this
2755 // decision point where I can figure out how loops are nested.  At this
2756 // time I can properly order the different loop nests from my children.
2757 // Note that there may not be any backedges at the decision point!
2758 //
2759 // Since the decision point can be far removed from the backedges, I can't
2760 // order my loops at the time I discover them.  Thus at the decision point
2761 // I need to inspect loop header pre-order numbers to properly nest my
2762 // loops.  This means I need to sort my childrens' loops by pre-order.
2763 // The sort is of size number-of-control-children, which generally limits
2764 // it to size 2 (i.e., I just choose between my 2 target loops).
2765 void PhaseIdealLoop::build_loop_tree() {
2766   // Allocate stack of size C->live_nodes()/2 to avoid frequent realloc
2767   GrowableArray <Node *> bltstack(C->live_nodes() >> 1);
2768   Node *n = C->root();
2769   bltstack.push(n);
2770   int pre_order = 1;
2771   int stack_size;
2772 
2773   while ( ( stack_size = bltstack.length() ) != 0 ) {
2774     n = bltstack.top(); // Leave node on stack
2775     if ( !is_visited(n) ) {
2776       // ---- Pre-pass Work ----
2777       // Pre-walked but not post-walked nodes need a pre_order number.
2778 
2779       set_preorder_visited( n, pre_order ); // set as visited
2780 
2781       // ---- Scan over children ----
2782       // Scan first over control projections that lead to loop headers.
2783       // This helps us find inner-to-outer loops with shared headers better.
2784 
2785       // Scan children's children for loop headers.
2786       for ( int i = n->outcnt() - 1; i >= 0; --i ) {
2787         Node* m = n->raw_out(i);       // Child
2788         if( m->is_CFG() && !is_visited(m) ) { // Only for CFG children
2789           // Scan over children's children to find loop
2790           for (DUIterator_Fast jmax, j = m->fast_outs(jmax); j < jmax; j++) {
2791             Node* l = m->fast_out(j);
2792             if( is_visited(l) &&       // Been visited?
2793                 !is_postvisited(l) &&  // But not post-visited
2794                 get_preorder(l) < pre_order ) { // And smaller pre-order
2795               // Found!  Scan the DFS down this path before doing other paths
2796               bltstack.push(m);
2797               break;
2798             }
2799           }
2800         }
2801       }
2802       pre_order++;
2803     }
2804     else if ( !is_postvisited(n) ) {
2805       // Note: build_loop_tree_impl() adds out edges on rare occasions,
2806       // such as com.sun.rsasign.am::a.
2807       // For non-recursive version, first, process current children.
2808       // On next iteration, check if additional children were added.
2809       for ( int k = n->outcnt() - 1; k >= 0; --k ) {
2810         Node* u = n->raw_out(k);
2811         if ( u->is_CFG() && !is_visited(u) ) {
2812           bltstack.push(u);
2813         }
2814       }
2815       if ( bltstack.length() == stack_size ) {
2816         // There were no additional children, post visit node now
2817         (void)bltstack.pop(); // Remove node from stack
2818         pre_order = build_loop_tree_impl( n, pre_order );
2819         // Check for bailout
2820         if (C->failing()) {
2821           return;
2822         }
2823         // Check to grow _preorders[] array for the case when
2824         // build_loop_tree_impl() adds new nodes.
2825         check_grow_preorders();
2826       }
2827     }
2828     else {
2829       (void)bltstack.pop(); // Remove post-visited node from stack
2830     }
2831   }
2832 }
2833 
2834 //------------------------------build_loop_tree_impl---------------------------
2835 int PhaseIdealLoop::build_loop_tree_impl( Node *n, int pre_order ) {
2836   // ---- Post-pass Work ----
2837   // Pre-walked but not post-walked nodes need a pre_order number.
2838 
2839   // Tightest enclosing loop for this Node
2840   IdealLoopTree *innermost = NULL;
2841 
2842   // For all children, see if any edge is a backedge.  If so, make a loop
2843   // for it.  Then find the tightest enclosing loop for the self Node.
2844   for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
2845     Node* m = n->fast_out(i);   // Child
2846     if( n == m ) continue;      // Ignore control self-cycles
2847     if( !m->is_CFG() ) continue;// Ignore non-CFG edges
2848 
2849     IdealLoopTree *l;           // Child's loop
2850     if( !is_postvisited(m) ) {  // Child visited but not post-visited?
2851       // Found a backedge
2852       assert( get_preorder(m) < pre_order, "should be backedge" );
2853       // Check for the RootNode, which is already a LoopNode and is allowed
2854       // to have multiple "backedges".
2855       if( m == C->root()) {     // Found the root?
2856         l = _ltree_root;        // Root is the outermost LoopNode
2857       } else {                  // Else found a nested loop
2858         // Insert a LoopNode to mark this loop.
2859         l = new IdealLoopTree(this, m, n);
2860       } // End of Else found a nested loop
2861       if( !has_loop(m) )        // If 'm' does not already have a loop set
2862         set_loop(m, l);         // Set loop header to loop now
2863 
2864     } else {                    // Else not a nested loop
2865       if( !_nodes[m->_idx] ) continue; // Dead code has no loop
2866       l = get_loop(m);          // Get previously determined loop
2867       // If successor is header of a loop (nest), move up-loop till it
2868       // is a member of some outer enclosing loop.  Since there are no
2869       // shared headers (I've split them already) I only need to go up
2870       // at most 1 level.
2871       while( l && l->_head == m ) // Successor heads loop?
2872         l = l->_parent;         // Move up 1 for me
2873       // If this loop is not properly parented, then this loop
2874       // has no exit path out, i.e. its an infinite loop.
2875       if( !l ) {
2876         // Make loop "reachable" from root so the CFG is reachable.  Basically
2877         // insert a bogus loop exit that is never taken.  'm', the loop head,
2878         // points to 'n', one (of possibly many) fall-in paths.  There may be
2879         // many backedges as well.
2880 
2881         // Here I set the loop to be the root loop.  I could have, after
2882         // inserting a bogus loop exit, restarted the recursion and found my
2883         // new loop exit.  This would make the infinite loop a first-class
2884         // loop and it would then get properly optimized.  What's the use of
2885         // optimizing an infinite loop?
2886         l = _ltree_root;        // Oops, found infinite loop
2887 
2888         if (!_verify_only) {
2889           // Insert the NeverBranch between 'm' and it's control user.
2890           NeverBranchNode *iff = new NeverBranchNode( m );
2891           _igvn.register_new_node_with_optimizer(iff);
2892           set_loop(iff, l);
2893           Node *if_t = new CProjNode( iff, 0 );
2894           _igvn.register_new_node_with_optimizer(if_t);
2895           set_loop(if_t, l);
2896 
2897           Node* cfg = NULL;       // Find the One True Control User of m
2898           for (DUIterator_Fast jmax, j = m->fast_outs(jmax); j < jmax; j++) {
2899             Node* x = m->fast_out(j);
2900             if (x->is_CFG() && x != m && x != iff)
2901               { cfg = x; break; }
2902           }
2903           assert(cfg != NULL, "must find the control user of m");
2904           uint k = 0;             // Probably cfg->in(0)
2905           while( cfg->in(k) != m ) k++; // But check incase cfg is a Region
2906           cfg->set_req( k, if_t ); // Now point to NeverBranch
2907           _igvn._worklist.push(cfg);
2908 
2909           // Now create the never-taken loop exit
2910           Node *if_f = new CProjNode( iff, 1 );
2911           _igvn.register_new_node_with_optimizer(if_f);
2912           set_loop(if_f, l);
2913           // Find frame ptr for Halt.  Relies on the optimizer
2914           // V-N'ing.  Easier and quicker than searching through
2915           // the program structure.
2916           Node *frame = new ParmNode( C->start(), TypeFunc::FramePtr );
2917           _igvn.register_new_node_with_optimizer(frame);
2918           // Halt & Catch Fire
2919           Node *halt = new HaltNode( if_f, frame );
2920           _igvn.register_new_node_with_optimizer(halt);
2921           set_loop(halt, l);
2922           C->root()->add_req(halt);
2923         }
2924         set_loop(C->root(), _ltree_root);
2925       }
2926     }
2927     // Weeny check for irreducible.  This child was already visited (this
2928     // IS the post-work phase).  Is this child's loop header post-visited
2929     // as well?  If so, then I found another entry into the loop.
2930     if (!_verify_only) {
2931       while( is_postvisited(l->_head) ) {
2932         // found irreducible
2933         l->_irreducible = 1; // = true
2934         l = l->_parent;
2935         _has_irreducible_loops = true;
2936         // Check for bad CFG here to prevent crash, and bailout of compile
2937         if (l == NULL) {
2938           C->record_method_not_compilable("unhandled CFG detected during loop optimization");
2939           return pre_order;
2940         }
2941       }
2942       C->set_has_irreducible_loop(_has_irreducible_loops);
2943     }
2944 
2945     // This Node might be a decision point for loops.  It is only if
2946     // it's children belong to several different loops.  The sort call
2947     // does a trivial amount of work if there is only 1 child or all
2948     // children belong to the same loop.  If however, the children
2949     // belong to different loops, the sort call will properly set the
2950     // _parent pointers to show how the loops nest.
2951     //
2952     // In any case, it returns the tightest enclosing loop.
2953     innermost = sort( l, innermost );
2954   }
2955 
2956   // Def-use info will have some dead stuff; dead stuff will have no
2957   // loop decided on.
2958 
2959   // Am I a loop header?  If so fix up my parent's child and next ptrs.
2960   if( innermost && innermost->_head == n ) {
2961     assert( get_loop(n) == innermost, "" );
2962     IdealLoopTree *p = innermost->_parent;
2963     IdealLoopTree *l = innermost;
2964     while( p && l->_head == n ) {
2965       l->_next = p->_child;     // Put self on parents 'next child'
2966       p->_child = l;            // Make self as first child of parent
2967       l = p;                    // Now walk up the parent chain
2968       p = l->_parent;
2969     }
2970   } else {
2971     // Note that it is possible for a LoopNode to reach here, if the
2972     // backedge has been made unreachable (hence the LoopNode no longer
2973     // denotes a Loop, and will eventually be removed).
2974 
2975     // Record tightest enclosing loop for self.  Mark as post-visited.
2976     set_loop(n, innermost);
2977     // Also record has_call flag early on
2978     if( innermost ) {
2979       if( n->is_Call() && !n->is_CallLeaf() && !n->is_macro() ) {
2980         // Do not count uncommon calls
2981         if( !n->is_CallStaticJava() || !n->as_CallStaticJava()->_name ) {
2982           Node *iff = n->in(0)->in(0);
2983           // No any calls for vectorized loops.
2984           if( UseSuperWord || !iff->is_If() ||
2985               (n->in(0)->Opcode() == Op_IfFalse &&
2986                (1.0 - iff->as_If()->_prob) >= 0.01) ||
2987               (iff->as_If()->_prob >= 0.01) )
2988             innermost->_has_call = 1;
2989         }
2990       } else if( n->is_Allocate() && n->as_Allocate()->_is_scalar_replaceable ) {
2991         // Disable loop optimizations if the loop has a scalar replaceable
2992         // allocation. This disabling may cause a potential performance lost
2993         // if the allocation is not eliminated for some reason.
2994         innermost->_allow_optimizations = false;
2995         innermost->_has_call = 1; // = true
2996       } else if (n->Opcode() == Op_SafePoint) {
2997         // Record all safepoints in this loop.
2998         if (innermost->_safepts == NULL) innermost->_safepts = new Node_List();
2999         innermost->_safepts->push(n);
3000       }
3001     }
3002   }
3003 
3004   // Flag as post-visited now
3005   set_postvisited(n);
3006   return pre_order;
3007 }
3008 
3009 
3010 //------------------------------build_loop_early-------------------------------
3011 // Put Data nodes into some loop nest, by setting the _nodes[]->loop mapping.
3012 // First pass computes the earliest controlling node possible.  This is the
3013 // controlling input with the deepest dominating depth.
3014 void PhaseIdealLoop::build_loop_early( VectorSet &visited, Node_List &worklist, Node_Stack &nstack ) {
3015   while (worklist.size() != 0) {
3016     // Use local variables nstack_top_n & nstack_top_i to cache values
3017     // on nstack's top.
3018     Node *nstack_top_n = worklist.pop();
3019     uint  nstack_top_i = 0;
3020 //while_nstack_nonempty:
3021     while (true) {
3022       // Get parent node and next input's index from stack's top.
3023       Node  *n = nstack_top_n;
3024       uint   i = nstack_top_i;
3025       uint cnt = n->req(); // Count of inputs
3026       if (i == 0) {        // Pre-process the node.
3027         if( has_node(n) &&            // Have either loop or control already?
3028             !has_ctrl(n) ) {          // Have loop picked out already?
3029           // During "merge_many_backedges" we fold up several nested loops
3030           // into a single loop.  This makes the members of the original
3031           // loop bodies pointing to dead loops; they need to move up
3032           // to the new UNION'd larger loop.  I set the _head field of these
3033           // dead loops to NULL and the _parent field points to the owning
3034           // loop.  Shades of UNION-FIND algorithm.
3035           IdealLoopTree *ilt;
3036           while( !(ilt = get_loop(n))->_head ) {
3037             // Normally I would use a set_loop here.  But in this one special
3038             // case, it is legal (and expected) to change what loop a Node
3039             // belongs to.
3040             _nodes.map(n->_idx, (Node*)(ilt->_parent) );
3041           }
3042           // Remove safepoints ONLY if I've already seen I don't need one.
3043           // (the old code here would yank a 2nd safepoint after seeing a
3044           // first one, even though the 1st did not dominate in the loop body
3045           // and thus could be avoided indefinitely)
3046           if( !_verify_only && !_verify_me && ilt->_has_sfpt && n->Opcode() == Op_SafePoint &&
3047               is_deleteable_safept(n)) {
3048             Node *in = n->in(TypeFunc::Control);
3049             lazy_replace(n,in);       // Pull safepoint now
3050             if (ilt->_safepts != NULL) {
3051               ilt->_safepts->yank(n);
3052             }
3053             // Carry on with the recursion "as if" we are walking
3054             // only the control input
3055             if( !visited.test_set( in->_idx ) ) {
3056               worklist.push(in);      // Visit this guy later, using worklist
3057             }
3058             // Get next node from nstack:
3059             // - skip n's inputs processing by setting i > cnt;
3060             // - we also will not call set_early_ctrl(n) since
3061             //   has_node(n) == true (see the condition above).
3062             i = cnt + 1;
3063           }
3064         }
3065       } // if (i == 0)
3066 
3067       // Visit all inputs
3068       bool done = true;       // Assume all n's inputs will be processed
3069       while (i < cnt) {
3070         Node *in = n->in(i);
3071         ++i;
3072         if (in == NULL) continue;
3073         if (in->pinned() && !in->is_CFG())
3074           set_ctrl(in, in->in(0));
3075         int is_visited = visited.test_set( in->_idx );
3076         if (!has_node(in)) {  // No controlling input yet?
3077           assert( !in->is_CFG(), "CFG Node with no controlling input?" );
3078           assert( !is_visited, "visit only once" );
3079           nstack.push(n, i);  // Save parent node and next input's index.
3080           nstack_top_n = in;  // Process current input now.
3081           nstack_top_i = 0;
3082           done = false;       // Not all n's inputs processed.
3083           break; // continue while_nstack_nonempty;
3084         } else if (!is_visited) {
3085           // This guy has a location picked out for him, but has not yet
3086           // been visited.  Happens to all CFG nodes, for instance.
3087           // Visit him using the worklist instead of recursion, to break
3088           // cycles.  Since he has a location already we do not need to
3089           // find his location before proceeding with the current Node.
3090           worklist.push(in);  // Visit this guy later, using worklist
3091         }
3092       }
3093       if (done) {
3094         // All of n's inputs have been processed, complete post-processing.
3095 
3096         // Compute earliest point this Node can go.
3097         // CFG, Phi, pinned nodes already know their controlling input.
3098         if (!has_node(n)) {
3099           // Record earliest legal location
3100           set_early_ctrl( n );
3101         }
3102         if (nstack.is_empty()) {
3103           // Finished all nodes on stack.
3104           // Process next node on the worklist.
3105           break;
3106         }
3107         // Get saved parent node and next input's index.
3108         nstack_top_n = nstack.node();
3109         nstack_top_i = nstack.index();
3110         nstack.pop();
3111       }
3112     } // while (true)
3113   }
3114 }
3115 
3116 //------------------------------dom_lca_internal--------------------------------
3117 // Pair-wise LCA
3118 Node *PhaseIdealLoop::dom_lca_internal( Node *n1, Node *n2 ) const {
3119   if( !n1 ) return n2;          // Handle NULL original LCA
3120   assert( n1->is_CFG(), "" );
3121   assert( n2->is_CFG(), "" );
3122   // find LCA of all uses
3123   uint d1 = dom_depth(n1);
3124   uint d2 = dom_depth(n2);
3125   while (n1 != n2) {
3126     if (d1 > d2) {
3127       n1 =      idom(n1);
3128       d1 = dom_depth(n1);
3129     } else if (d1 < d2) {
3130       n2 =      idom(n2);
3131       d2 = dom_depth(n2);
3132     } else {
3133       // Here d1 == d2.  Due to edits of the dominator-tree, sections
3134       // of the tree might have the same depth.  These sections have
3135       // to be searched more carefully.
3136 
3137       // Scan up all the n1's with equal depth, looking for n2.
3138       Node *t1 = idom(n1);
3139       while (dom_depth(t1) == d1) {
3140         if (t1 == n2)  return n2;
3141         t1 = idom(t1);
3142       }
3143       // Scan up all the n2's with equal depth, looking for n1.
3144       Node *t2 = idom(n2);
3145       while (dom_depth(t2) == d2) {
3146         if (t2 == n1)  return n1;
3147         t2 = idom(t2);
3148       }
3149       // Move up to a new dominator-depth value as well as up the dom-tree.
3150       n1 = t1;
3151       n2 = t2;
3152       d1 = dom_depth(n1);
3153       d2 = dom_depth(n2);
3154     }
3155   }
3156   return n1;
3157 }
3158 
3159 //------------------------------compute_idom-----------------------------------
3160 // Locally compute IDOM using dom_lca call.  Correct only if the incoming
3161 // IDOMs are correct.
3162 Node *PhaseIdealLoop::compute_idom( Node *region ) const {
3163   assert( region->is_Region(), "" );
3164   Node *LCA = NULL;
3165   for( uint i = 1; i < region->req(); i++ ) {
3166     if( region->in(i) != C->top() )
3167       LCA = dom_lca( LCA, region->in(i) );
3168   }
3169   return LCA;
3170 }
3171 
3172 bool PhaseIdealLoop::verify_dominance(Node* n, Node* use, Node* LCA, Node* early) {
3173   bool had_error = false;
3174 #ifdef ASSERT
3175   if (early != C->root()) {
3176     // Make sure that there's a dominance path from LCA to early
3177     Node* d = LCA;
3178     while (d != early) {
3179       if (d == C->root()) {
3180         dump_bad_graph("Bad graph detected in compute_lca_of_uses", n, early, LCA);
3181         tty->print_cr("*** Use %d isn't dominated by def %d ***", use->_idx, n->_idx);
3182         had_error = true;
3183         break;
3184       }
3185       d = idom(d);
3186     }
3187   }
3188 #endif
3189   return had_error;
3190 }
3191 
3192 
3193 Node* PhaseIdealLoop::compute_lca_of_uses(Node* n, Node* early, bool verify) {
3194   // Compute LCA over list of uses
3195   bool had_error = false;
3196   Node *LCA = NULL;
3197   for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax && LCA != early; i++) {
3198     Node* c = n->fast_out(i);
3199     if (_nodes[c->_idx] == NULL)
3200       continue;                 // Skip the occasional dead node
3201     if( c->is_Phi() ) {         // For Phis, we must land above on the path
3202       for( uint j=1; j<c->req(); j++ ) {// For all inputs
3203         if( c->in(j) == n ) {   // Found matching input?
3204           Node *use = c->in(0)->in(j);
3205           if (_verify_only && use->is_top()) continue;
3206           LCA = dom_lca_for_get_late_ctrl( LCA, use, n );
3207           if (verify) had_error = verify_dominance(n, use, LCA, early) || had_error;
3208         }
3209       }
3210     } else {
3211       // For CFG data-users, use is in the block just prior
3212       Node *use = has_ctrl(c) ? get_ctrl(c) : c->in(0);
3213       LCA = dom_lca_for_get_late_ctrl( LCA, use, n );
3214       if (verify) had_error = verify_dominance(n, use, LCA, early) || had_error;
3215     }
3216   }
3217   assert(!had_error, "bad dominance");
3218   return LCA;
3219 }
3220 
3221 // Check the shape of the graph at the loop entry. In some cases,
3222 // the shape of the graph does not match the shape outlined below.
3223 // That is caused by the Opaque1 node "protecting" the shape of
3224 // the graph being removed by, for example, the IGVN performed
3225 // in PhaseIdealLoop::build_and_optimize().
3226 //
3227 // After the Opaque1 node has been removed, optimizations (e.g., split-if,
3228 // loop unswitching, and IGVN, or a combination of them) can freely change
3229 // the graph's shape. As a result, the graph shape outlined below cannot
3230 // be guaranteed anymore.
3231 bool PhaseIdealLoop::is_canonical_loop_entry(CountedLoopNode* cl) {
3232   if (!cl->is_main_loop() && !cl->is_post_loop()) {
3233     return false;
3234   }
3235   Node* ctrl = cl->in(LoopNode::EntryControl);
3236   if (ctrl == NULL || (!ctrl->is_IfTrue() && !ctrl->is_IfFalse())) {
3237     return false;
3238   }
3239   Node* iffm = ctrl->in(0);
3240   if (iffm == NULL || !iffm->is_If()) {
3241     return false;
3242   }
3243   Node* bolzm = iffm->in(1);
3244   if (bolzm == NULL || !bolzm->is_Bool()) {
3245     return false;
3246   }
3247   Node* cmpzm = bolzm->in(1);
3248   if (cmpzm == NULL || !cmpzm->is_Cmp()) {
3249     return false;
3250   }
3251   // compares can get conditionally flipped
3252   bool found_opaque = false;
3253   for (uint i = 1; i < cmpzm->req(); i++) {
3254     Node* opnd = cmpzm->in(i);
3255     if (opnd && opnd->Opcode() == Op_Opaque1) {
3256       found_opaque = true;
3257       break;
3258     }
3259   }
3260   if (!found_opaque) {
3261     return false;
3262   }
3263   return true;
3264 }
3265 
3266 //------------------------------get_late_ctrl----------------------------------
3267 // Compute latest legal control.
3268 Node *PhaseIdealLoop::get_late_ctrl( Node *n, Node *early ) {
3269   assert(early != NULL, "early control should not be NULL");
3270 
3271   Node* LCA = compute_lca_of_uses(n, early);
3272 #ifdef ASSERT
3273   if (LCA == C->root() && LCA != early) {
3274     // def doesn't dominate uses so print some useful debugging output
3275     compute_lca_of_uses(n, early, true);
3276   }
3277 #endif
3278 
3279   // if this is a load, check for anti-dependent stores
3280   // We use a conservative algorithm to identify potential interfering
3281   // instructions and for rescheduling the load.  The users of the memory
3282   // input of this load are examined.  Any use which is not a load and is
3283   // dominated by early is considered a potentially interfering store.
3284   // This can produce false positives.
3285   if (n->is_Load() && LCA != early) {
3286     Node_List worklist;
3287 
3288     Node *mem = n->in(MemNode::Memory);
3289     for (DUIterator_Fast imax, i = mem->fast_outs(imax); i < imax; i++) {
3290       Node* s = mem->fast_out(i);
3291       worklist.push(s);
3292     }
3293     while(worklist.size() != 0 && LCA != early) {
3294       Node* s = worklist.pop();
3295       if (s->is_Load()) {
3296         continue;
3297       } else if (s->is_MergeMem()) {
3298         for (DUIterator_Fast imax, i = s->fast_outs(imax); i < imax; i++) {
3299           Node* s1 = s->fast_out(i);
3300           worklist.push(s1);
3301         }
3302       } else {
3303         Node *sctrl = has_ctrl(s) ? get_ctrl(s) : s->in(0);
3304         assert(sctrl != NULL || s->outcnt() == 0, "must have control");
3305         if (sctrl != NULL && !sctrl->is_top() && is_dominator(early, sctrl)) {
3306           LCA = dom_lca_for_get_late_ctrl(LCA, sctrl, n);
3307         }
3308       }
3309     }
3310   }
3311 
3312   assert(LCA == find_non_split_ctrl(LCA), "unexpected late control");
3313   return LCA;
3314 }
3315 
3316 // true if CFG node d dominates CFG node n
3317 bool PhaseIdealLoop::is_dominator(Node *d, Node *n) {
3318   if (d == n)
3319     return true;
3320   assert(d->is_CFG() && n->is_CFG(), "must have CFG nodes");
3321   uint dd = dom_depth(d);
3322   while (dom_depth(n) >= dd) {
3323     if (n == d)
3324       return true;
3325     n = idom(n);
3326   }
3327   return false;
3328 }
3329 
3330 //------------------------------dom_lca_for_get_late_ctrl_internal-------------
3331 // Pair-wise LCA with tags.
3332 // Tag each index with the node 'tag' currently being processed
3333 // before advancing up the dominator chain using idom().
3334 // Later calls that find a match to 'tag' know that this path has already
3335 // been considered in the current LCA (which is input 'n1' by convention).
3336 // Since get_late_ctrl() is only called once for each node, the tag array
3337 // does not need to be cleared between calls to get_late_ctrl().
3338 // Algorithm trades a larger constant factor for better asymptotic behavior
3339 //
3340 Node *PhaseIdealLoop::dom_lca_for_get_late_ctrl_internal( Node *n1, Node *n2, Node *tag ) {
3341   uint d1 = dom_depth(n1);
3342   uint d2 = dom_depth(n2);
3343 
3344   do {
3345     if (d1 > d2) {
3346       // current lca is deeper than n2
3347       _dom_lca_tags.map(n1->_idx, tag);
3348       n1 =      idom(n1);
3349       d1 = dom_depth(n1);
3350     } else if (d1 < d2) {
3351       // n2 is deeper than current lca
3352       Node *memo = _dom_lca_tags[n2->_idx];
3353       if( memo == tag ) {
3354         return n1;    // Return the current LCA
3355       }
3356       _dom_lca_tags.map(n2->_idx, tag);
3357       n2 =      idom(n2);
3358       d2 = dom_depth(n2);
3359     } else {
3360       // Here d1 == d2.  Due to edits of the dominator-tree, sections
3361       // of the tree might have the same depth.  These sections have
3362       // to be searched more carefully.
3363 
3364       // Scan up all the n1's with equal depth, looking for n2.
3365       _dom_lca_tags.map(n1->_idx, tag);
3366       Node *t1 = idom(n1);
3367       while (dom_depth(t1) == d1) {
3368         if (t1 == n2)  return n2;
3369         _dom_lca_tags.map(t1->_idx, tag);
3370         t1 = idom(t1);
3371       }
3372       // Scan up all the n2's with equal depth, looking for n1.
3373       _dom_lca_tags.map(n2->_idx, tag);
3374       Node *t2 = idom(n2);
3375       while (dom_depth(t2) == d2) {
3376         if (t2 == n1)  return n1;
3377         _dom_lca_tags.map(t2->_idx, tag);
3378         t2 = idom(t2);
3379       }
3380       // Move up to a new dominator-depth value as well as up the dom-tree.
3381       n1 = t1;
3382       n2 = t2;
3383       d1 = dom_depth(n1);
3384       d2 = dom_depth(n2);
3385     }
3386   } while (n1 != n2);
3387   return n1;
3388 }
3389 
3390 //------------------------------init_dom_lca_tags------------------------------
3391 // Tag could be a node's integer index, 32bits instead of 64bits in some cases
3392 // Intended use does not involve any growth for the array, so it could
3393 // be of fixed size.
3394 void PhaseIdealLoop::init_dom_lca_tags() {
3395   uint limit = C->unique() + 1;
3396   _dom_lca_tags.map( limit, NULL );
3397 #ifdef ASSERT
3398   for( uint i = 0; i < limit; ++i ) {
3399     assert(_dom_lca_tags[i] == NULL, "Must be distinct from each node pointer");
3400   }
3401 #endif // ASSERT
3402 }
3403 
3404 //------------------------------clear_dom_lca_tags------------------------------
3405 // Tag could be a node's integer index, 32bits instead of 64bits in some cases
3406 // Intended use does not involve any growth for the array, so it could
3407 // be of fixed size.
3408 void PhaseIdealLoop::clear_dom_lca_tags() {
3409   uint limit = C->unique() + 1;
3410   _dom_lca_tags.map( limit, NULL );
3411   _dom_lca_tags.clear();
3412 #ifdef ASSERT
3413   for( uint i = 0; i < limit; ++i ) {
3414     assert(_dom_lca_tags[i] == NULL, "Must be distinct from each node pointer");
3415   }
3416 #endif // ASSERT
3417 }
3418 
3419 //------------------------------build_loop_late--------------------------------
3420 // Put Data nodes into some loop nest, by setting the _nodes[]->loop mapping.
3421 // Second pass finds latest legal placement, and ideal loop placement.
3422 void PhaseIdealLoop::build_loop_late( VectorSet &visited, Node_List &worklist, Node_Stack &nstack ) {
3423   while (worklist.size() != 0) {
3424     Node *n = worklist.pop();
3425     // Only visit once
3426     if (visited.test_set(n->_idx)) continue;
3427     uint cnt = n->outcnt();
3428     uint   i = 0;
3429     while (true) {
3430       assert( _nodes[n->_idx], "no dead nodes" );
3431       // Visit all children
3432       if (i < cnt) {
3433         Node* use = n->raw_out(i);
3434         ++i;
3435         // Check for dead uses.  Aggressively prune such junk.  It might be
3436         // dead in the global sense, but still have local uses so I cannot
3437         // easily call 'remove_dead_node'.
3438         if( _nodes[use->_idx] != NULL || use->is_top() ) { // Not dead?
3439           // Due to cycles, we might not hit the same fixed point in the verify
3440           // pass as we do in the regular pass.  Instead, visit such phis as
3441           // simple uses of the loop head.
3442           if( use->in(0) && (use->is_CFG() || use->is_Phi()) ) {
3443             if( !visited.test(use->_idx) )
3444               worklist.push(use);
3445           } else if( !visited.test_set(use->_idx) ) {
3446             nstack.push(n, i); // Save parent and next use's index.
3447             n   = use;         // Process all children of current use.
3448             cnt = use->outcnt();
3449             i   = 0;
3450           }
3451         } else {
3452           // Do not visit around the backedge of loops via data edges.
3453           // push dead code onto a worklist
3454           _deadlist.push(use);
3455         }
3456       } else {
3457         // All of n's children have been processed, complete post-processing.
3458         build_loop_late_post(n);
3459         if (nstack.is_empty()) {
3460           // Finished all nodes on stack.
3461           // Process next node on the worklist.
3462           break;
3463         }
3464         // Get saved parent node and next use's index. Visit the rest of uses.
3465         n   = nstack.node();
3466         cnt = n->outcnt();
3467         i   = nstack.index();
3468         nstack.pop();
3469       }
3470     }
3471   }
3472 }
3473 
3474 //------------------------------build_loop_late_post---------------------------
3475 // Put Data nodes into some loop nest, by setting the _nodes[]->loop mapping.
3476 // Second pass finds latest legal placement, and ideal loop placement.
3477 void PhaseIdealLoop::build_loop_late_post( Node *n ) {
3478 
3479   if (n->req() == 2 && (n->Opcode() == Op_ConvI2L || n->Opcode() == Op_CastII) && !C->major_progress() && !_verify_only) {
3480     _igvn._worklist.push(n);  // Maybe we'll normalize it, if no more loops.
3481   }
3482 
3483 #ifdef ASSERT
3484   if (_verify_only && !n->is_CFG()) {
3485     // Check def-use domination.
3486     compute_lca_of_uses(n, get_ctrl(n), true /* verify */);
3487   }
3488 #endif
3489 
3490   // CFG and pinned nodes already handled
3491   if( n->in(0) ) {
3492     if( n->in(0)->is_top() ) return; // Dead?
3493 
3494     // We'd like +VerifyLoopOptimizations to not believe that Mod's/Loads
3495     // _must_ be pinned (they have to observe their control edge of course).
3496     // Unlike Stores (which modify an unallocable resource, the memory
3497     // state), Mods/Loads can float around.  So free them up.
3498     bool pinned = true;
3499     switch( n->Opcode() ) {
3500     case Op_DivI:
3501     case Op_DivF:
3502     case Op_DivD:
3503     case Op_ModI:
3504     case Op_ModF:
3505     case Op_ModD:
3506     case Op_LoadB:              // Same with Loads; they can sink
3507     case Op_LoadUB:             // during loop optimizations.
3508     case Op_LoadUS:
3509     case Op_LoadD:
3510     case Op_LoadF:
3511     case Op_LoadI:
3512     case Op_LoadKlass:
3513     case Op_LoadNKlass:
3514     case Op_LoadL:
3515     case Op_LoadS:
3516     case Op_LoadP:
3517     case Op_LoadN:
3518     case Op_LoadRange:
3519     case Op_LoadD_unaligned:
3520     case Op_LoadL_unaligned:
3521     case Op_StrComp:            // Does a bunch of load-like effects
3522     case Op_StrEquals:
3523     case Op_StrIndexOf:
3524     case Op_StrIndexOfChar:
3525     case Op_AryEq:
3526     case Op_HasNegatives:
3527       pinned = false;
3528     }
3529     if( pinned ) {
3530       IdealLoopTree *chosen_loop = get_loop(n->is_CFG() ? n : get_ctrl(n));
3531       if( !chosen_loop->_child )       // Inner loop?
3532         chosen_loop->_body.push(n); // Collect inner loops
3533       return;
3534     }
3535   } else {                      // No slot zero
3536     if( n->is_CFG() ) {         // CFG with no slot 0 is dead
3537       _nodes.map(n->_idx,0);    // No block setting, it's globally dead
3538       return;
3539     }
3540     assert(!n->is_CFG() || n->outcnt() == 0, "");
3541   }
3542 
3543   // Do I have a "safe range" I can select over?
3544   Node *early = get_ctrl(n);// Early location already computed
3545 
3546   // Compute latest point this Node can go
3547   Node *LCA = get_late_ctrl( n, early );
3548   // LCA is NULL due to uses being dead
3549   if( LCA == NULL ) {
3550 #ifdef ASSERT
3551     for (DUIterator i1 = n->outs(); n->has_out(i1); i1++) {
3552       assert( _nodes[n->out(i1)->_idx] == NULL, "all uses must also be dead");
3553     }
3554 #endif
3555     _nodes.map(n->_idx, 0);     // This node is useless
3556     _deadlist.push(n);
3557     return;
3558   }
3559   assert(LCA != NULL && !LCA->is_top(), "no dead nodes");
3560 
3561   Node *legal = LCA;            // Walk 'legal' up the IDOM chain
3562   Node *least = legal;          // Best legal position so far
3563   while( early != legal ) {     // While not at earliest legal
3564 #ifdef ASSERT
3565     if (legal->is_Start() && !early->is_Root()) {
3566       // Bad graph. Print idom path and fail.
3567       dump_bad_graph("Bad graph detected in build_loop_late", n, early, LCA);
3568       assert(false, "Bad graph detected in build_loop_late");
3569     }
3570 #endif
3571     // Find least loop nesting depth
3572     legal = idom(legal);        // Bump up the IDOM tree
3573     // Check for lower nesting depth
3574     if( get_loop(legal)->_nest < get_loop(least)->_nest )
3575       least = legal;
3576   }
3577   assert(early == legal || legal != C->root(), "bad dominance of inputs");
3578 
3579   // Try not to place code on a loop entry projection
3580   // which can inhibit range check elimination.
3581   if (least != early) {
3582     Node* ctrl_out = least->unique_ctrl_out();
3583     if (ctrl_out && ctrl_out->is_CountedLoop() &&
3584         least == ctrl_out->in(LoopNode::EntryControl)) {
3585       Node* least_dom = idom(least);
3586       if (get_loop(least_dom)->is_member(get_loop(least))) {
3587         least = least_dom;
3588       }
3589     }
3590   }
3591 
3592 #ifdef ASSERT
3593   // If verifying, verify that 'verify_me' has a legal location
3594   // and choose it as our location.
3595   if( _verify_me ) {
3596     Node *v_ctrl = _verify_me->get_ctrl_no_update(n);
3597     Node *legal = LCA;
3598     while( early != legal ) {   // While not at earliest legal
3599       if( legal == v_ctrl ) break;  // Check for prior good location
3600       legal = idom(legal)      ;// Bump up the IDOM tree
3601     }
3602     // Check for prior good location
3603     if( legal == v_ctrl ) least = legal; // Keep prior if found
3604   }
3605 #endif
3606 
3607   // Assign discovered "here or above" point
3608   least = find_non_split_ctrl(least);
3609   set_ctrl(n, least);
3610 
3611   // Collect inner loop bodies
3612   IdealLoopTree *chosen_loop = get_loop(least);
3613   if( !chosen_loop->_child )   // Inner loop?
3614     chosen_loop->_body.push(n);// Collect inner loops
3615 }
3616 
3617 #ifdef ASSERT
3618 void PhaseIdealLoop::dump_bad_graph(const char* msg, Node* n, Node* early, Node* LCA) {
3619   tty->print_cr("%s", msg);
3620   tty->print("n: "); n->dump();
3621   tty->print("early(n): "); early->dump();
3622   if (n->in(0) != NULL  && !n->in(0)->is_top() &&
3623       n->in(0) != early && !n->in(0)->is_Root()) {
3624     tty->print("n->in(0): "); n->in(0)->dump();
3625   }
3626   for (uint i = 1; i < n->req(); i++) {
3627     Node* in1 = n->in(i);
3628     if (in1 != NULL && in1 != n && !in1->is_top()) {
3629       tty->print("n->in(%d): ", i); in1->dump();
3630       Node* in1_early = get_ctrl(in1);
3631       tty->print("early(n->in(%d)): ", i); in1_early->dump();
3632       if (in1->in(0) != NULL     && !in1->in(0)->is_top() &&
3633           in1->in(0) != in1_early && !in1->in(0)->is_Root()) {
3634         tty->print("n->in(%d)->in(0): ", i); in1->in(0)->dump();
3635       }
3636       for (uint j = 1; j < in1->req(); j++) {
3637         Node* in2 = in1->in(j);
3638         if (in2 != NULL && in2 != n && in2 != in1 && !in2->is_top()) {
3639           tty->print("n->in(%d)->in(%d): ", i, j); in2->dump();
3640           Node* in2_early = get_ctrl(in2);
3641           tty->print("early(n->in(%d)->in(%d)): ", i, j); in2_early->dump();
3642           if (in2->in(0) != NULL     && !in2->in(0)->is_top() &&
3643               in2->in(0) != in2_early && !in2->in(0)->is_Root()) {
3644             tty->print("n->in(%d)->in(%d)->in(0): ", i, j); in2->in(0)->dump();
3645           }
3646         }
3647       }
3648     }
3649   }
3650   tty->cr();
3651   tty->print("LCA(n): "); LCA->dump();
3652   for (uint i = 0; i < n->outcnt(); i++) {
3653     Node* u1 = n->raw_out(i);
3654     if (u1 == n)
3655       continue;
3656     tty->print("n->out(%d): ", i); u1->dump();
3657     if (u1->is_CFG()) {
3658       for (uint j = 0; j < u1->outcnt(); j++) {
3659         Node* u2 = u1->raw_out(j);
3660         if (u2 != u1 && u2 != n && u2->is_CFG()) {
3661           tty->print("n->out(%d)->out(%d): ", i, j); u2->dump();
3662         }
3663       }
3664     } else {
3665       Node* u1_later = get_ctrl(u1);
3666       tty->print("later(n->out(%d)): ", i); u1_later->dump();
3667       if (u1->in(0) != NULL     && !u1->in(0)->is_top() &&
3668           u1->in(0) != u1_later && !u1->in(0)->is_Root()) {
3669         tty->print("n->out(%d)->in(0): ", i); u1->in(0)->dump();
3670       }
3671       for (uint j = 0; j < u1->outcnt(); j++) {
3672         Node* u2 = u1->raw_out(j);
3673         if (u2 == n || u2 == u1)
3674           continue;
3675         tty->print("n->out(%d)->out(%d): ", i, j); u2->dump();
3676         if (!u2->is_CFG()) {
3677           Node* u2_later = get_ctrl(u2);
3678           tty->print("later(n->out(%d)->out(%d)): ", i, j); u2_later->dump();
3679           if (u2->in(0) != NULL     && !u2->in(0)->is_top() &&
3680               u2->in(0) != u2_later && !u2->in(0)->is_Root()) {
3681             tty->print("n->out(%d)->in(0): ", i); u2->in(0)->dump();
3682           }
3683         }
3684       }
3685     }
3686   }
3687   tty->cr();
3688   int ct = 0;
3689   Node *dbg_legal = LCA;
3690   while(!dbg_legal->is_Start() && ct < 100) {
3691     tty->print("idom[%d] ",ct); dbg_legal->dump();
3692     ct++;
3693     dbg_legal = idom(dbg_legal);
3694   }
3695   tty->cr();
3696 }
3697 #endif
3698 
3699 #ifndef PRODUCT
3700 //------------------------------dump-------------------------------------------
3701 void PhaseIdealLoop::dump( ) const {
3702   ResourceMark rm;
3703   Arena* arena = Thread::current()->resource_area();
3704   Node_Stack stack(arena, C->live_nodes() >> 2);
3705   Node_List rpo_list;
3706   VectorSet visited(arena);
3707   visited.set(C->top()->_idx);
3708   rpo( C->root(), stack, visited, rpo_list );
3709   // Dump root loop indexed by last element in PO order
3710   dump( _ltree_root, rpo_list.size(), rpo_list );
3711 }
3712 
3713 void PhaseIdealLoop::dump( IdealLoopTree *loop, uint idx, Node_List &rpo_list ) const {
3714   loop->dump_head();
3715 
3716   // Now scan for CFG nodes in the same loop
3717   for( uint j=idx; j > 0;  j-- ) {
3718     Node *n = rpo_list[j-1];
3719     if( !_nodes[n->_idx] )      // Skip dead nodes
3720       continue;
3721     if( get_loop(n) != loop ) { // Wrong loop nest
3722       if( get_loop(n)->_head == n &&    // Found nested loop?
3723           get_loop(n)->_parent == loop )
3724         dump(get_loop(n),rpo_list.size(),rpo_list);     // Print it nested-ly
3725       continue;
3726     }
3727 
3728     // Dump controlling node
3729     for( uint x = 0; x < loop->_nest; x++ )
3730       tty->print("  ");
3731     tty->print("C");
3732     if( n == C->root() ) {
3733       n->dump();
3734     } else {
3735       Node* cached_idom   = idom_no_update(n);
3736       Node *computed_idom = n->in(0);
3737       if( n->is_Region() ) {
3738         computed_idom = compute_idom(n);
3739         // computed_idom() will return n->in(0) when idom(n) is an IfNode (or
3740         // any MultiBranch ctrl node), so apply a similar transform to
3741         // the cached idom returned from idom_no_update.
3742         cached_idom = find_non_split_ctrl(cached_idom);
3743       }
3744       tty->print(" ID:%d",computed_idom->_idx);
3745       n->dump();
3746       if( cached_idom != computed_idom ) {
3747         tty->print_cr("*** BROKEN IDOM!  Computed as: %d, cached as: %d",
3748                       computed_idom->_idx, cached_idom->_idx);
3749       }
3750     }
3751     // Dump nodes it controls
3752     for( uint k = 0; k < _nodes.Size(); k++ ) {
3753       // (k < C->unique() && get_ctrl(find(k)) == n)
3754       if (k < C->unique() && _nodes[k] == (Node*)((intptr_t)n + 1)) {
3755         Node *m = C->root()->find(k);
3756         if( m && m->outcnt() > 0 ) {
3757           if (!(has_ctrl(m) && get_ctrl_no_update(m) == n)) {
3758             tty->print_cr("*** BROKEN CTRL ACCESSOR!  _nodes[k] is %p, ctrl is %p",
3759                           _nodes[k], has_ctrl(m) ? get_ctrl_no_update(m) : NULL);
3760           }
3761           for( uint j = 0; j < loop->_nest; j++ )
3762             tty->print("  ");
3763           tty->print(" ");
3764           m->dump();
3765         }
3766       }
3767     }
3768   }
3769 }
3770 
3771 // Collect a R-P-O for the whole CFG.
3772 // Result list is in post-order (scan backwards for RPO)
3773 void PhaseIdealLoop::rpo( Node *start, Node_Stack &stk, VectorSet &visited, Node_List &rpo_list ) const {
3774   stk.push(start, 0);
3775   visited.set(start->_idx);
3776 
3777   while (stk.is_nonempty()) {
3778     Node* m   = stk.node();
3779     uint  idx = stk.index();
3780     if (idx < m->outcnt()) {
3781       stk.set_index(idx + 1);
3782       Node* n = m->raw_out(idx);
3783       if (n->is_CFG() && !visited.test_set(n->_idx)) {
3784         stk.push(n, 0);
3785       }
3786     } else {
3787       rpo_list.push(m);
3788       stk.pop();
3789     }
3790   }
3791 }
3792 #endif
3793 
3794 
3795 //=============================================================================
3796 //------------------------------LoopTreeIterator-----------------------------------
3797 
3798 // Advance to next loop tree using a preorder, left-to-right traversal.
3799 void LoopTreeIterator::next() {
3800   assert(!done(), "must not be done.");
3801   if (_curnt->_child != NULL) {
3802     _curnt = _curnt->_child;
3803   } else if (_curnt->_next != NULL) {
3804     _curnt = _curnt->_next;
3805   } else {
3806     while (_curnt != _root && _curnt->_next == NULL) {
3807       _curnt = _curnt->_parent;
3808     }
3809     if (_curnt == _root) {
3810       _curnt = NULL;
3811       assert(done(), "must be done.");
3812     } else {
3813       assert(_curnt->_next != NULL, "must be more to do");
3814       _curnt = _curnt->_next;
3815     }
3816   }
3817 }