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