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