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