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