1 /* 2 * Copyright (c) 1998, 2024, 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 "gc/shared/barrierSet.hpp" 29 #include "gc/shared/c2/barrierSetC2.hpp" 30 #include "libadt/vectset.hpp" 31 #include "memory/allocation.inline.hpp" 32 #include "memory/resourceArea.hpp" 33 #include "opto/addnode.hpp" 34 #include "opto/arraycopynode.hpp" 35 #include "opto/callnode.hpp" 36 #include "opto/castnode.hpp" 37 #include "opto/connode.hpp" 38 #include "opto/convertnode.hpp" 39 #include "opto/divnode.hpp" 40 #include "opto/idealGraphPrinter.hpp" 41 #include "opto/loopnode.hpp" 42 #include "opto/movenode.hpp" 43 #include "opto/mulnode.hpp" 44 #include "opto/opaquenode.hpp" 45 #include "opto/predicates.hpp" 46 #include "opto/rootnode.hpp" 47 #include "opto/runtime.hpp" 48 #include "opto/vectorization.hpp" 49 #include "runtime/sharedRuntime.hpp" 50 #include "utilities/checkedCast.hpp" 51 #include "utilities/powerOfTwo.hpp" 52 53 //============================================================================= 54 //--------------------------is_cloop_ind_var----------------------------------- 55 // Determine if a node is a counted loop induction variable. 56 // NOTE: The method is declared in "node.hpp". 57 bool Node::is_cloop_ind_var() const { 58 return (is_Phi() && 59 as_Phi()->region()->is_CountedLoop() && 60 as_Phi()->region()->as_CountedLoop()->phi() == this); 61 } 62 63 //============================================================================= 64 //------------------------------dump_spec-------------------------------------- 65 // Dump special per-node info 66 #ifndef PRODUCT 67 void LoopNode::dump_spec(outputStream *st) const { 68 RegionNode::dump_spec(st); 69 if (is_inner_loop()) st->print( "inner " ); 70 if (is_partial_peel_loop()) st->print( "partial_peel " ); 71 if (partial_peel_has_failed()) st->print( "partial_peel_failed " ); 72 } 73 #endif 74 75 //------------------------------is_valid_counted_loop------------------------- 76 bool LoopNode::is_valid_counted_loop(BasicType bt) const { 77 if (is_BaseCountedLoop() && as_BaseCountedLoop()->bt() == bt) { 78 BaseCountedLoopNode* l = as_BaseCountedLoop(); 79 BaseCountedLoopEndNode* le = l->loopexit_or_null(); 80 if (le != nullptr && 81 le->proj_out_or_null(1 /* true */) == l->in(LoopNode::LoopBackControl)) { 82 Node* phi = l->phi(); 83 Node* exit = le->proj_out_or_null(0 /* false */); 84 if (exit != nullptr && exit->Opcode() == Op_IfFalse && 85 phi != nullptr && phi->is_Phi() && 86 phi->in(LoopNode::LoopBackControl) == l->incr() && 87 le->loopnode() == l && le->stride_is_con()) { 88 return true; 89 } 90 } 91 } 92 return false; 93 } 94 95 //------------------------------get_early_ctrl--------------------------------- 96 // Compute earliest legal control 97 Node *PhaseIdealLoop::get_early_ctrl( Node *n ) { 98 assert( !n->is_Phi() && !n->is_CFG(), "this code only handles data nodes" ); 99 uint i; 100 Node *early; 101 if (n->in(0) && !n->is_expensive()) { 102 early = n->in(0); 103 if (!early->is_CFG()) // Might be a non-CFG multi-def 104 early = get_ctrl(early); // So treat input as a straight data input 105 i = 1; 106 } else { 107 early = get_ctrl(n->in(1)); 108 i = 2; 109 } 110 uint e_d = dom_depth(early); 111 assert( early, "" ); 112 for (; i < n->req(); i++) { 113 Node *cin = get_ctrl(n->in(i)); 114 assert( cin, "" ); 115 // Keep deepest dominator depth 116 uint c_d = dom_depth(cin); 117 if (c_d > e_d) { // Deeper guy? 118 early = cin; // Keep deepest found so far 119 e_d = c_d; 120 } else if (c_d == e_d && // Same depth? 121 early != cin) { // If not equal, must use slower algorithm 122 // If same depth but not equal, one _must_ dominate the other 123 // and we want the deeper (i.e., dominated) guy. 124 Node *n1 = early; 125 Node *n2 = cin; 126 while (1) { 127 n1 = idom(n1); // Walk up until break cycle 128 n2 = idom(n2); 129 if (n1 == cin || // Walked early up to cin 130 dom_depth(n2) < c_d) 131 break; // early is deeper; keep him 132 if (n2 == early || // Walked cin up to early 133 dom_depth(n1) < c_d) { 134 early = cin; // cin is deeper; keep him 135 break; 136 } 137 } 138 e_d = dom_depth(early); // Reset depth register cache 139 } 140 } 141 142 // Return earliest legal location 143 assert(early == find_non_split_ctrl(early), "unexpected early control"); 144 145 if (n->is_expensive() && !_verify_only && !_verify_me) { 146 assert(n->in(0), "should have control input"); 147 early = get_early_ctrl_for_expensive(n, early); 148 } 149 150 return early; 151 } 152 153 //------------------------------get_early_ctrl_for_expensive--------------------------------- 154 // Move node up the dominator tree as high as legal while still beneficial 155 Node *PhaseIdealLoop::get_early_ctrl_for_expensive(Node *n, Node* earliest) { 156 assert(n->in(0) && n->is_expensive(), "expensive node with control input here"); 157 assert(OptimizeExpensiveOps, "optimization off?"); 158 159 Node* ctl = n->in(0); 160 assert(ctl->is_CFG(), "expensive input 0 must be cfg"); 161 uint min_dom_depth = dom_depth(earliest); 162 #ifdef ASSERT 163 if (!is_dominator(ctl, earliest) && !is_dominator(earliest, ctl)) { 164 dump_bad_graph("Bad graph detected in get_early_ctrl_for_expensive", n, earliest, ctl); 165 assert(false, "Bad graph detected in get_early_ctrl_for_expensive"); 166 } 167 #endif 168 if (dom_depth(ctl) < min_dom_depth) { 169 return earliest; 170 } 171 172 while (true) { 173 Node* next = ctl; 174 // Moving the node out of a loop on the projection of an If 175 // confuses Loop Predication. So, once we hit a loop in an If branch 176 // that doesn't branch to an UNC, we stop. The code that process 177 // expensive nodes will notice the loop and skip over it to try to 178 // move the node further up. 179 if (ctl->is_CountedLoop() && ctl->in(1) != nullptr && ctl->in(1)->in(0) != nullptr && ctl->in(1)->in(0)->is_If()) { 180 if (!ctl->in(1)->as_Proj()->is_uncommon_trap_if_pattern()) { 181 break; 182 } 183 next = idom(ctl->in(1)->in(0)); 184 } else if (ctl->is_Proj()) { 185 // We only move it up along a projection if the projection is 186 // the single control projection for its parent: same code path, 187 // if it's a If with UNC or fallthrough of a call. 188 Node* parent_ctl = ctl->in(0); 189 if (parent_ctl == nullptr) { 190 break; 191 } else if (parent_ctl->is_CountedLoopEnd() && parent_ctl->as_CountedLoopEnd()->loopnode() != nullptr) { 192 next = parent_ctl->as_CountedLoopEnd()->loopnode()->init_control(); 193 } else if (parent_ctl->is_If()) { 194 if (!ctl->as_Proj()->is_uncommon_trap_if_pattern()) { 195 break; 196 } 197 assert(idom(ctl) == parent_ctl, "strange"); 198 next = idom(parent_ctl); 199 } else if (ctl->is_CatchProj()) { 200 if (ctl->as_Proj()->_con != CatchProjNode::fall_through_index) { 201 break; 202 } 203 assert(parent_ctl->in(0)->in(0)->is_Call(), "strange graph"); 204 next = parent_ctl->in(0)->in(0)->in(0); 205 } else { 206 // Check if parent control has a single projection (this 207 // control is the only possible successor of the parent 208 // control). If so, we can try to move the node above the 209 // parent control. 210 int nb_ctl_proj = 0; 211 for (DUIterator_Fast imax, i = parent_ctl->fast_outs(imax); i < imax; i++) { 212 Node *p = parent_ctl->fast_out(i); 213 if (p->is_Proj() && p->is_CFG()) { 214 nb_ctl_proj++; 215 if (nb_ctl_proj > 1) { 216 break; 217 } 218 } 219 } 220 221 if (nb_ctl_proj > 1) { 222 break; 223 } 224 assert(parent_ctl->is_Start() || parent_ctl->is_MemBar() || parent_ctl->is_Call() || 225 BarrierSet::barrier_set()->barrier_set_c2()->is_gc_barrier_node(parent_ctl), "unexpected node"); 226 assert(idom(ctl) == parent_ctl, "strange"); 227 next = idom(parent_ctl); 228 } 229 } else { 230 next = idom(ctl); 231 } 232 if (next->is_Root() || next->is_Start() || dom_depth(next) < min_dom_depth) { 233 break; 234 } 235 ctl = next; 236 } 237 238 if (ctl != n->in(0)) { 239 _igvn.replace_input_of(n, 0, ctl); 240 _igvn.hash_insert(n); 241 } 242 243 return ctl; 244 } 245 246 247 //------------------------------set_early_ctrl--------------------------------- 248 // Set earliest legal control 249 void PhaseIdealLoop::set_early_ctrl(Node* n, bool update_body) { 250 Node *early = get_early_ctrl(n); 251 252 // Record earliest legal location 253 set_ctrl(n, early); 254 IdealLoopTree *loop = get_loop(early); 255 if (update_body && loop->_child == nullptr) { 256 loop->_body.push(n); 257 } 258 } 259 260 //------------------------------set_subtree_ctrl------------------------------- 261 // set missing _ctrl entries on new nodes 262 void PhaseIdealLoop::set_subtree_ctrl(Node* n, bool update_body) { 263 // Already set? Get out. 264 if (_loop_or_ctrl[n->_idx]) return; 265 // Recursively set _loop_or_ctrl array to indicate where the Node goes 266 uint i; 267 for (i = 0; i < n->req(); ++i) { 268 Node *m = n->in(i); 269 if (m && m != C->root()) { 270 set_subtree_ctrl(m, update_body); 271 } 272 } 273 274 // Fixup self 275 set_early_ctrl(n, update_body); 276 } 277 278 IdealLoopTree* PhaseIdealLoop::insert_outer_loop(IdealLoopTree* loop, LoopNode* outer_l, Node* outer_ift) { 279 IdealLoopTree* outer_ilt = new IdealLoopTree(this, outer_l, outer_ift); 280 IdealLoopTree* parent = loop->_parent; 281 IdealLoopTree* sibling = parent->_child; 282 if (sibling == loop) { 283 parent->_child = outer_ilt; 284 } else { 285 while (sibling->_next != loop) { 286 sibling = sibling->_next; 287 } 288 sibling->_next = outer_ilt; 289 } 290 outer_ilt->_next = loop->_next; 291 outer_ilt->_parent = parent; 292 outer_ilt->_child = loop; 293 outer_ilt->_nest = loop->_nest; 294 loop->_parent = outer_ilt; 295 loop->_next = nullptr; 296 loop->_nest++; 297 assert(loop->_nest <= SHRT_MAX, "sanity"); 298 return outer_ilt; 299 } 300 301 // Create a skeleton strip mined outer loop: a Loop head before the 302 // inner strip mined loop, a safepoint and an exit condition guarded 303 // by an opaque node after the inner strip mined loop with a backedge 304 // to the loop head. The inner strip mined loop is left as it is. Only 305 // once loop optimizations are over, do we adjust the inner loop exit 306 // condition to limit its number of iterations, set the outer loop 307 // exit condition and add Phis to the outer loop head. Some loop 308 // optimizations that operate on the inner strip mined loop need to be 309 // aware of the outer strip mined loop: loop unswitching needs to 310 // clone the outer loop as well as the inner, unrolling needs to only 311 // clone the inner loop etc. No optimizations need to change the outer 312 // strip mined loop as it is only a skeleton. 313 IdealLoopTree* PhaseIdealLoop::create_outer_strip_mined_loop(BoolNode *test, Node *cmp, Node *init_control, 314 IdealLoopTree* loop, float cl_prob, float le_fcnt, 315 Node*& entry_control, Node*& iffalse) { 316 Node* outer_test = _igvn.intcon(0); 317 set_ctrl(outer_test, C->root()); 318 Node *orig = iffalse; 319 iffalse = iffalse->clone(); 320 _igvn.register_new_node_with_optimizer(iffalse); 321 set_idom(iffalse, idom(orig), dom_depth(orig)); 322 323 IfNode *outer_le = new OuterStripMinedLoopEndNode(iffalse, outer_test, cl_prob, le_fcnt); 324 Node *outer_ift = new IfTrueNode (outer_le); 325 Node* outer_iff = orig; 326 _igvn.replace_input_of(outer_iff, 0, outer_le); 327 328 LoopNode *outer_l = new OuterStripMinedLoopNode(C, init_control, outer_ift); 329 entry_control = outer_l; 330 331 IdealLoopTree* outer_ilt = insert_outer_loop(loop, outer_l, outer_ift); 332 333 set_loop(iffalse, outer_ilt); 334 // When this code runs, loop bodies have not yet been populated. 335 const bool body_populated = false; 336 register_control(outer_le, outer_ilt, iffalse, body_populated); 337 register_control(outer_ift, outer_ilt, outer_le, body_populated); 338 set_idom(outer_iff, outer_le, dom_depth(outer_le)); 339 _igvn.register_new_node_with_optimizer(outer_l); 340 set_loop(outer_l, outer_ilt); 341 set_idom(outer_l, init_control, dom_depth(init_control)+1); 342 343 return outer_ilt; 344 } 345 346 void PhaseIdealLoop::insert_loop_limit_check_predicate(ParsePredicateSuccessProj* loop_limit_check_parse_proj, 347 Node* cmp_limit, Node* bol) { 348 assert(loop_limit_check_parse_proj->in(0)->is_ParsePredicate(), "must be parse predicate"); 349 Node* new_predicate_proj = create_new_if_for_predicate(loop_limit_check_parse_proj, nullptr, 350 Deoptimization::Reason_loop_limit_check, 351 Op_If); 352 Node* iff = new_predicate_proj->in(0); 353 cmp_limit = _igvn.register_new_node_with_optimizer(cmp_limit); 354 bol = _igvn.register_new_node_with_optimizer(bol); 355 set_subtree_ctrl(bol, false); 356 _igvn.replace_input_of(iff, 1, bol); 357 358 #ifndef PRODUCT 359 // report that the loop predication has been actually performed 360 // for this loop 361 if (TraceLoopLimitCheck) { 362 tty->print_cr("Counted Loop Limit Check generated:"); 363 debug_only( bol->dump(2); ) 364 } 365 #endif 366 } 367 368 Node* PhaseIdealLoop::loop_exit_control(Node* x, IdealLoopTree* loop) { 369 // Counted loop head must be a good RegionNode with only 3 not null 370 // control input edges: Self, Entry, LoopBack. 371 if (x->in(LoopNode::Self) == nullptr || x->req() != 3 || loop->_irreducible) { 372 return nullptr; 373 } 374 Node *init_control = x->in(LoopNode::EntryControl); 375 Node *back_control = x->in(LoopNode::LoopBackControl); 376 if (init_control == nullptr || back_control == nullptr) { // Partially dead 377 return nullptr; 378 } 379 // Must also check for TOP when looking for a dead loop 380 if (init_control->is_top() || back_control->is_top()) { 381 return nullptr; 382 } 383 384 // Allow funny placement of Safepoint 385 if (back_control->Opcode() == Op_SafePoint) { 386 back_control = back_control->in(TypeFunc::Control); 387 } 388 389 // Controlling test for loop 390 Node *iftrue = back_control; 391 uint iftrue_op = iftrue->Opcode(); 392 if (iftrue_op != Op_IfTrue && 393 iftrue_op != Op_IfFalse) { 394 // I have a weird back-control. Probably the loop-exit test is in 395 // the middle of the loop and I am looking at some trailing control-flow 396 // merge point. To fix this I would have to partially peel the loop. 397 return nullptr; // Obscure back-control 398 } 399 400 // Get boolean guarding loop-back test 401 Node *iff = iftrue->in(0); 402 if (get_loop(iff) != loop || !iff->in(1)->is_Bool()) { 403 return nullptr; 404 } 405 return iftrue; 406 } 407 408 Node* PhaseIdealLoop::loop_exit_test(Node* back_control, IdealLoopTree* loop, Node*& incr, Node*& limit, BoolTest::mask& bt, float& cl_prob) { 409 Node* iftrue = back_control; 410 uint iftrue_op = iftrue->Opcode(); 411 Node* iff = iftrue->in(0); 412 BoolNode* test = iff->in(1)->as_Bool(); 413 bt = test->_test._test; 414 cl_prob = iff->as_If()->_prob; 415 if (iftrue_op == Op_IfFalse) { 416 bt = BoolTest(bt).negate(); 417 cl_prob = 1.0 - cl_prob; 418 } 419 // Get backedge compare 420 Node* cmp = test->in(1); 421 if (!cmp->is_Cmp()) { 422 return nullptr; 423 } 424 425 // Find the trip-counter increment & limit. Limit must be loop invariant. 426 incr = cmp->in(1); 427 limit = cmp->in(2); 428 429 // --------- 430 // need 'loop()' test to tell if limit is loop invariant 431 // --------- 432 433 if (!is_member(loop, get_ctrl(incr))) { // Swapped trip counter and limit? 434 Node* tmp = incr; // Then reverse order into the CmpI 435 incr = limit; 436 limit = tmp; 437 bt = BoolTest(bt).commute(); // And commute the exit test 438 } 439 if (is_member(loop, get_ctrl(limit))) { // Limit must be loop-invariant 440 return nullptr; 441 } 442 if (!is_member(loop, get_ctrl(incr))) { // Trip counter must be loop-variant 443 return nullptr; 444 } 445 return cmp; 446 } 447 448 Node* PhaseIdealLoop::loop_iv_incr(Node* incr, Node* x, IdealLoopTree* loop, Node*& phi_incr) { 449 if (incr->is_Phi()) { 450 if (incr->as_Phi()->region() != x || incr->req() != 3) { 451 return nullptr; // Not simple trip counter expression 452 } 453 phi_incr = incr; 454 incr = phi_incr->in(LoopNode::LoopBackControl); // Assume incr is on backedge of Phi 455 if (!is_member(loop, get_ctrl(incr))) { // Trip counter must be loop-variant 456 return nullptr; 457 } 458 } 459 return incr; 460 } 461 462 Node* PhaseIdealLoop::loop_iv_stride(Node* incr, IdealLoopTree* loop, Node*& xphi) { 463 assert(incr->Opcode() == Op_AddI || incr->Opcode() == Op_AddL, "caller resp."); 464 // Get merge point 465 xphi = incr->in(1); 466 Node *stride = incr->in(2); 467 if (!stride->is_Con()) { // Oops, swap these 468 if (!xphi->is_Con()) { // Is the other guy a constant? 469 return nullptr; // Nope, unknown stride, bail out 470 } 471 Node *tmp = xphi; // 'incr' is commutative, so ok to swap 472 xphi = stride; 473 stride = tmp; 474 } 475 return stride; 476 } 477 478 PhiNode* PhaseIdealLoop::loop_iv_phi(Node* xphi, Node* phi_incr, Node* x, IdealLoopTree* loop) { 479 if (!xphi->is_Phi()) { 480 return nullptr; // Too much math on the trip counter 481 } 482 if (phi_incr != nullptr && phi_incr != xphi) { 483 return nullptr; 484 } 485 PhiNode *phi = xphi->as_Phi(); 486 487 // Phi must be of loop header; backedge must wrap to increment 488 if (phi->region() != x) { 489 return nullptr; 490 } 491 return phi; 492 } 493 494 static int check_stride_overflow(jlong final_correction, const TypeInteger* limit_t, BasicType bt) { 495 if (final_correction > 0) { 496 if (limit_t->lo_as_long() > (max_signed_integer(bt) - final_correction)) { 497 return -1; 498 } 499 if (limit_t->hi_as_long() > (max_signed_integer(bt) - final_correction)) { 500 return 1; 501 } 502 } else { 503 if (limit_t->hi_as_long() < (min_signed_integer(bt) - final_correction)) { 504 return -1; 505 } 506 if (limit_t->lo_as_long() < (min_signed_integer(bt) - final_correction)) { 507 return 1; 508 } 509 } 510 return 0; 511 } 512 513 static bool condition_stride_ok(BoolTest::mask bt, jlong stride_con) { 514 // If the condition is inverted and we will be rolling 515 // through MININT to MAXINT, then bail out. 516 if (bt == BoolTest::eq || // Bail out, but this loop trips at most twice! 517 // Odd stride 518 (bt == BoolTest::ne && stride_con != 1 && stride_con != -1) || 519 // Count down loop rolls through MAXINT 520 ((bt == BoolTest::le || bt == BoolTest::lt) && stride_con < 0) || 521 // Count up loop rolls through MININT 522 ((bt == BoolTest::ge || bt == BoolTest::gt) && stride_con > 0)) { 523 return false; // Bail out 524 } 525 return true; 526 } 527 528 Node* PhaseIdealLoop::loop_nest_replace_iv(Node* iv_to_replace, Node* inner_iv, Node* outer_phi, Node* inner_head, 529 BasicType bt) { 530 Node* iv_as_long; 531 if (bt == T_LONG) { 532 iv_as_long = new ConvI2LNode(inner_iv, TypeLong::INT); 533 register_new_node(iv_as_long, inner_head); 534 } else { 535 iv_as_long = inner_iv; 536 } 537 Node* iv_replacement = AddNode::make(outer_phi, iv_as_long, bt); 538 register_new_node(iv_replacement, inner_head); 539 for (DUIterator_Last imin, i = iv_to_replace->last_outs(imin); i >= imin;) { 540 Node* u = iv_to_replace->last_out(i); 541 #ifdef ASSERT 542 if (!is_dominator(inner_head, ctrl_or_self(u))) { 543 assert(u->is_Phi(), "should be a Phi"); 544 for (uint j = 1; j < u->req(); j++) { 545 if (u->in(j) == iv_to_replace) { 546 assert(is_dominator(inner_head, u->in(0)->in(j)), "iv use above loop?"); 547 } 548 } 549 } 550 #endif 551 _igvn.rehash_node_delayed(u); 552 int nb = u->replace_edge(iv_to_replace, iv_replacement, &_igvn); 553 i -= nb; 554 } 555 return iv_replacement; 556 } 557 558 // Add a Parse Predicate with an uncommon trap on the failing/false path. Normal control will continue on the true path. 559 void PhaseIdealLoop::add_parse_predicate(Deoptimization::DeoptReason reason, Node* inner_head, IdealLoopTree* loop, 560 SafePointNode* sfpt) { 561 if (!C->too_many_traps(reason)) { 562 ParsePredicateNode* parse_predicate = new ParsePredicateNode(inner_head->in(LoopNode::EntryControl), reason, &_igvn); 563 register_control(parse_predicate, loop, inner_head->in(LoopNode::EntryControl)); 564 Node* if_false = new IfFalseNode(parse_predicate); 565 register_control(if_false, _ltree_root, parse_predicate); 566 Node* if_true = new IfTrueNode(parse_predicate); 567 register_control(if_true, loop, parse_predicate); 568 569 int trap_request = Deoptimization::make_trap_request(reason, Deoptimization::Action_maybe_recompile); 570 address call_addr = OptoRuntime::uncommon_trap_blob()->entry_point(); 571 const TypePtr* no_memory_effects = nullptr; 572 JVMState* jvms = sfpt->jvms(); 573 CallNode* unc = new CallStaticJavaNode(OptoRuntime::uncommon_trap_Type(), call_addr, "uncommon_trap", 574 no_memory_effects); 575 576 Node* mem = nullptr; 577 Node* i_o = nullptr; 578 if (sfpt->is_Call()) { 579 mem = sfpt->proj_out(TypeFunc::Memory); 580 i_o = sfpt->proj_out(TypeFunc::I_O); 581 } else { 582 mem = sfpt->memory(); 583 i_o = sfpt->i_o(); 584 } 585 586 Node *frame = new ParmNode(C->start(), TypeFunc::FramePtr); 587 register_new_node(frame, C->start()); 588 Node *ret = new ParmNode(C->start(), TypeFunc::ReturnAdr); 589 register_new_node(ret, C->start()); 590 591 unc->init_req(TypeFunc::Control, if_false); 592 unc->init_req(TypeFunc::I_O, i_o); 593 unc->init_req(TypeFunc::Memory, mem); // may gc ptrs 594 unc->init_req(TypeFunc::FramePtr, frame); 595 unc->init_req(TypeFunc::ReturnAdr, ret); 596 unc->init_req(TypeFunc::Parms+0, _igvn.intcon(trap_request)); 597 unc->set_cnt(PROB_UNLIKELY_MAG(4)); 598 unc->copy_call_debug_info(&_igvn, sfpt); 599 600 for (uint i = TypeFunc::Parms; i < unc->req(); i++) { 601 set_subtree_ctrl(unc->in(i), false); 602 } 603 register_control(unc, _ltree_root, if_false); 604 605 Node* ctrl = new ProjNode(unc, TypeFunc::Control); 606 register_control(ctrl, _ltree_root, unc); 607 Node* halt = new HaltNode(ctrl, frame, "uncommon trap returned which should never happen" PRODUCT_ONLY(COMMA /*reachable*/false)); 608 register_control(halt, _ltree_root, ctrl); 609 _igvn.add_input_to(C->root(), halt); 610 611 _igvn.replace_input_of(inner_head, LoopNode::EntryControl, if_true); 612 set_idom(inner_head, if_true, dom_depth(inner_head)); 613 } 614 } 615 616 // Find a safepoint node that dominates the back edge. We need a 617 // SafePointNode so we can use its jvm state to create empty 618 // predicates. 619 static bool no_side_effect_since_safepoint(Compile* C, Node* x, Node* mem, MergeMemNode* mm, PhaseIdealLoop* phase) { 620 SafePointNode* safepoint = nullptr; 621 for (DUIterator_Fast imax, i = x->fast_outs(imax); i < imax; i++) { 622 Node* u = x->fast_out(i); 623 if (u->is_memory_phi()) { 624 Node* m = u->in(LoopNode::LoopBackControl); 625 if (u->adr_type() == TypePtr::BOTTOM) { 626 if (m->is_MergeMem() && mem->is_MergeMem()) { 627 if (m != mem DEBUG_ONLY(|| true)) { 628 // MergeMemStream can modify m, for example to adjust the length to mem. 629 // This is unfortunate, and probably unnecessary. But as it is, we need 630 // to add m to the igvn worklist, else we may have a modified node that 631 // is not on the igvn worklist. 632 phase->igvn()._worklist.push(m); 633 for (MergeMemStream mms(m->as_MergeMem(), mem->as_MergeMem()); mms.next_non_empty2(); ) { 634 if (!mms.is_empty()) { 635 if (mms.memory() != mms.memory2()) { 636 return false; 637 } 638 #ifdef ASSERT 639 if (mms.alias_idx() != Compile::AliasIdxBot) { 640 mm->set_memory_at(mms.alias_idx(), mem->as_MergeMem()->base_memory()); 641 } 642 #endif 643 } 644 } 645 } 646 } else if (mem->is_MergeMem()) { 647 if (m != mem->as_MergeMem()->base_memory()) { 648 return false; 649 } 650 } else { 651 return false; 652 } 653 } else { 654 if (mem->is_MergeMem()) { 655 if (m != mem->as_MergeMem()->memory_at(C->get_alias_index(u->adr_type()))) { 656 return false; 657 } 658 #ifdef ASSERT 659 mm->set_memory_at(C->get_alias_index(u->adr_type()), mem->as_MergeMem()->base_memory()); 660 #endif 661 } else { 662 if (m != mem) { 663 return false; 664 } 665 } 666 } 667 } 668 } 669 return true; 670 } 671 672 SafePointNode* PhaseIdealLoop::find_safepoint(Node* back_control, Node* x, IdealLoopTree* loop) { 673 IfNode* exit_test = back_control->in(0)->as_If(); 674 SafePointNode* safepoint = nullptr; 675 if (exit_test->in(0)->is_SafePoint() && exit_test->in(0)->outcnt() == 1) { 676 safepoint = exit_test->in(0)->as_SafePoint(); 677 } else { 678 Node* c = back_control; 679 while (c != x && c->Opcode() != Op_SafePoint) { 680 c = idom(c); 681 } 682 683 if (c->Opcode() == Op_SafePoint) { 684 safepoint = c->as_SafePoint(); 685 } 686 687 if (safepoint == nullptr) { 688 return nullptr; 689 } 690 691 Node* mem = safepoint->in(TypeFunc::Memory); 692 693 // We can only use that safepoint if there's no side effect between the backedge and the safepoint. 694 695 // mm is the memory state at the safepoint (when it's a MergeMem) 696 // no_side_effect_since_safepoint() goes over the memory state at the backedge. It resets the mm input for each 697 // component of the memory state it encounters so it points to the base memory. Once no_side_effect_since_safepoint() 698 // is done, if no side effect after the safepoint was found, mm should transform to the base memory: the states at 699 // the backedge and safepoint are the same so all components of the memory state at the safepoint should have been 700 // reset. 701 MergeMemNode* mm = nullptr; 702 #ifdef ASSERT 703 if (mem->is_MergeMem()) { 704 mm = mem->clone()->as_MergeMem(); 705 _igvn._worklist.push(mm); 706 for (MergeMemStream mms(mem->as_MergeMem()); mms.next_non_empty(); ) { 707 // Loop invariant memory state won't be reset by no_side_effect_since_safepoint(). Do it here. 708 // Escape Analysis can add state to mm that it doesn't add to the backedge memory Phis, breaking verification 709 // code that relies on mm. Clear that extra state here. 710 if (mms.alias_idx() != Compile::AliasIdxBot && 711 (loop != get_loop(ctrl_or_self(mms.memory())) || 712 (mms.adr_type()->isa_oop_ptr() && mms.adr_type()->is_known_instance()))) { 713 mm->set_memory_at(mms.alias_idx(), mem->as_MergeMem()->base_memory()); 714 } 715 } 716 } 717 #endif 718 if (!no_side_effect_since_safepoint(C, x, mem, mm, this)) { 719 safepoint = nullptr; 720 } else { 721 assert(mm == nullptr|| _igvn.transform(mm) == mem->as_MergeMem()->base_memory(), "all memory state should have been processed"); 722 } 723 #ifdef ASSERT 724 if (mm != nullptr) { 725 _igvn.remove_dead_node(mm); 726 } 727 #endif 728 } 729 return safepoint; 730 } 731 732 // If the loop has the shape of a counted loop but with a long 733 // induction variable, transform the loop in a loop nest: an inner 734 // loop that iterates for at most max int iterations with an integer 735 // induction variable and an outer loop that iterates over the full 736 // range of long values from the initial loop in (at most) max int 737 // steps. That is: 738 // 739 // x: for (long phi = init; phi < limit; phi += stride) { 740 // // phi := Phi(L, init, incr) 741 // // incr := AddL(phi, longcon(stride)) 742 // long incr = phi + stride; 743 // ... use phi and incr ... 744 // } 745 // 746 // OR: 747 // 748 // x: for (long phi = init; (phi += stride) < limit; ) { 749 // // phi := Phi(L, AddL(init, stride), incr) 750 // // incr := AddL(phi, longcon(stride)) 751 // long incr = phi + stride; 752 // ... use phi and (phi + stride) ... 753 // } 754 // 755 // ==transform=> 756 // 757 // const ulong inner_iters_limit = INT_MAX - stride - 1; //near 0x7FFFFFF0 758 // assert(stride <= inner_iters_limit); // else abort transform 759 // assert((extralong)limit + stride <= LONG_MAX); // else deopt 760 // outer_head: for (long outer_phi = init;;) { 761 // // outer_phi := Phi(outer_head, init, AddL(outer_phi, I2L(inner_phi))) 762 // ulong inner_iters_max = (ulong) MAX(0, ((extralong)limit + stride - outer_phi)); 763 // long inner_iters_actual = MIN(inner_iters_limit, inner_iters_max); 764 // assert(inner_iters_actual == (int)inner_iters_actual); 765 // int inner_phi, inner_incr; 766 // x: for (inner_phi = 0;; inner_phi = inner_incr) { 767 // // inner_phi := Phi(x, intcon(0), inner_incr) 768 // // inner_incr := AddI(inner_phi, intcon(stride)) 769 // inner_incr = inner_phi + stride; 770 // if (inner_incr < inner_iters_actual) { 771 // ... use phi=>(outer_phi+inner_phi) ... 772 // continue; 773 // } 774 // else break; 775 // } 776 // if ((outer_phi+inner_phi) < limit) //OR (outer_phi+inner_incr) < limit 777 // continue; 778 // else break; 779 // } 780 // 781 // The same logic is used to transform an int counted loop that contains long range checks into a loop nest of 2 int 782 // loops with long range checks transformed to int range checks in the inner loop. 783 bool PhaseIdealLoop::create_loop_nest(IdealLoopTree* loop, Node_List &old_new) { 784 Node* x = loop->_head; 785 // Only for inner loops 786 if (loop->_child != nullptr || !x->is_BaseCountedLoop() || x->as_Loop()->is_loop_nest_outer_loop()) { 787 return false; 788 } 789 790 if (x->is_CountedLoop() && !x->as_CountedLoop()->is_main_loop() && !x->as_CountedLoop()->is_normal_loop()) { 791 return false; 792 } 793 794 BaseCountedLoopNode* head = x->as_BaseCountedLoop(); 795 BasicType bt = x->as_BaseCountedLoop()->bt(); 796 797 check_counted_loop_shape(loop, x, bt); 798 799 #ifndef PRODUCT 800 if (bt == T_LONG) { 801 Atomic::inc(&_long_loop_candidates); 802 } 803 #endif 804 805 jlong stride_con_long = head->stride_con(); 806 assert(stride_con_long != 0, "missed some peephole opt"); 807 // We can't iterate for more than max int at a time. 808 if (stride_con_long != (jint)stride_con_long || stride_con_long == min_jint) { 809 assert(bt == T_LONG, "only for long loops"); 810 return false; 811 } 812 jint stride_con = checked_cast<jint>(stride_con_long); 813 // The number of iterations for the integer count loop: guarantee no 814 // overflow: max_jint - stride_con max. -1 so there's no need for a 815 // loop limit check if the exit test is <= or >=. 816 int iters_limit = max_jint - ABS(stride_con) - 1; 817 #ifdef ASSERT 818 if (bt == T_LONG && StressLongCountedLoop > 0) { 819 iters_limit = iters_limit / StressLongCountedLoop; 820 } 821 #endif 822 // At least 2 iterations so counted loop construction doesn't fail 823 if (iters_limit/ABS(stride_con) < 2) { 824 return false; 825 } 826 827 PhiNode* phi = head->phi()->as_Phi(); 828 Node* incr = head->incr(); 829 830 Node* back_control = head->in(LoopNode::LoopBackControl); 831 832 // data nodes on back branch not supported 833 if (back_control->outcnt() > 1) { 834 return false; 835 } 836 837 Node* limit = head->limit(); 838 // We'll need to use the loop limit before the inner loop is entered 839 if (!is_dominator(get_ctrl(limit), x)) { 840 return false; 841 } 842 843 IfNode* exit_test = head->loopexit(); 844 845 assert(back_control->Opcode() == Op_IfTrue, "wrong projection for back edge"); 846 847 Node_List range_checks; 848 iters_limit = extract_long_range_checks(loop, stride_con, iters_limit, phi, range_checks); 849 850 if (bt == T_INT) { 851 // The only purpose of creating a loop nest is to handle long range checks. If there are none, do not proceed further. 852 if (range_checks.size() == 0) { 853 return false; 854 } 855 } 856 857 // Take what we know about the number of iterations of the long counted loop into account when computing the limit of 858 // the inner loop. 859 const Node* init = head->init_trip(); 860 const TypeInteger* lo = _igvn.type(init)->is_integer(bt); 861 const TypeInteger* hi = _igvn.type(limit)->is_integer(bt); 862 if (stride_con < 0) { 863 swap(lo, hi); 864 } 865 if (hi->hi_as_long() <= lo->lo_as_long()) { 866 // not a loop after all 867 return false; 868 } 869 870 if (range_checks.size() > 0) { 871 // This transformation requires peeling one iteration. Also, if it has range checks and they are eliminated by Loop 872 // Predication, then 2 Hoisted Check Predicates are added for one range check. Finally, transforming a long range 873 // check requires extra logic to be executed before the loop is entered and for the outer loop. As a result, the 874 // transformations can't pay off for a small number of iterations: roughly, if the loop runs for 3 iterations, it's 875 // going to execute as many range checks once transformed with range checks eliminated (1 peeled iteration with 876 // range checks + 2 predicates per range checks) as it would have not transformed. It also has to pay for the extra 877 // logic on loop entry and for the outer loop. 878 loop->compute_trip_count(this); 879 if (head->is_CountedLoop() && head->as_CountedLoop()->has_exact_trip_count()) { 880 if (head->as_CountedLoop()->trip_count() <= 3) { 881 return false; 882 } 883 } else { 884 loop->compute_profile_trip_cnt(this); 885 if (!head->is_profile_trip_failed() && head->profile_trip_cnt() <= 3) { 886 return false; 887 } 888 } 889 } 890 891 julong orig_iters = (julong)hi->hi_as_long() - lo->lo_as_long(); 892 iters_limit = checked_cast<int>(MIN2((julong)iters_limit, orig_iters)); 893 894 // We need a safepoint to insert Parse Predicates for the inner loop. 895 SafePointNode* safepoint; 896 if (bt == T_INT && head->as_CountedLoop()->is_strip_mined()) { 897 // Loop is strip mined: use the safepoint of the outer strip mined loop 898 OuterStripMinedLoopNode* outer_loop = head->as_CountedLoop()->outer_loop(); 899 assert(outer_loop != nullptr, "no outer loop"); 900 safepoint = outer_loop->outer_safepoint(); 901 outer_loop->transform_to_counted_loop(&_igvn, this); 902 exit_test = head->loopexit(); 903 } else { 904 safepoint = find_safepoint(back_control, x, loop); 905 } 906 907 Node* exit_branch = exit_test->proj_out(false); 908 Node* entry_control = head->in(LoopNode::EntryControl); 909 910 // Clone the control flow of the loop to build an outer loop 911 Node* outer_back_branch = back_control->clone(); 912 Node* outer_exit_test = new IfNode(exit_test->in(0), exit_test->in(1), exit_test->_prob, exit_test->_fcnt); 913 Node* inner_exit_branch = exit_branch->clone(); 914 915 LoopNode* outer_head = new LoopNode(entry_control, outer_back_branch); 916 IdealLoopTree* outer_ilt = insert_outer_loop(loop, outer_head, outer_back_branch); 917 918 const bool body_populated = true; 919 register_control(outer_head, outer_ilt, entry_control, body_populated); 920 921 _igvn.register_new_node_with_optimizer(inner_exit_branch); 922 set_loop(inner_exit_branch, outer_ilt); 923 set_idom(inner_exit_branch, exit_test, dom_depth(exit_branch)); 924 925 outer_exit_test->set_req(0, inner_exit_branch); 926 register_control(outer_exit_test, outer_ilt, inner_exit_branch, body_populated); 927 928 _igvn.replace_input_of(exit_branch, 0, outer_exit_test); 929 set_idom(exit_branch, outer_exit_test, dom_depth(exit_branch)); 930 931 outer_back_branch->set_req(0, outer_exit_test); 932 register_control(outer_back_branch, outer_ilt, outer_exit_test, body_populated); 933 934 _igvn.replace_input_of(x, LoopNode::EntryControl, outer_head); 935 set_idom(x, outer_head, dom_depth(x)); 936 937 // add an iv phi to the outer loop and use it to compute the inner 938 // loop iteration limit 939 Node* outer_phi = phi->clone(); 940 outer_phi->set_req(0, outer_head); 941 register_new_node(outer_phi, outer_head); 942 943 Node* inner_iters_max = nullptr; 944 if (stride_con > 0) { 945 inner_iters_max = MaxNode::max_diff_with_zero(limit, outer_phi, TypeInteger::bottom(bt), _igvn); 946 } else { 947 inner_iters_max = MaxNode::max_diff_with_zero(outer_phi, limit, TypeInteger::bottom(bt), _igvn); 948 } 949 950 Node* inner_iters_limit = _igvn.integercon(iters_limit, bt); 951 // inner_iters_max may not fit in a signed integer (iterating from 952 // Long.MIN_VALUE to Long.MAX_VALUE for instance). Use an unsigned 953 // min. 954 const TypeInteger* inner_iters_actual_range = TypeInteger::make(0, iters_limit, Type::WidenMin, bt); 955 Node* inner_iters_actual = MaxNode::unsigned_min(inner_iters_max, inner_iters_limit, inner_iters_actual_range, _igvn); 956 957 Node* inner_iters_actual_int; 958 if (bt == T_LONG) { 959 inner_iters_actual_int = new ConvL2INode(inner_iters_actual); 960 _igvn.register_new_node_with_optimizer(inner_iters_actual_int); 961 // When the inner loop is transformed to a counted loop, a loop limit check is not expected to be needed because 962 // the loop limit is less or equal to max_jint - stride - 1 (if stride is positive but a similar argument exists for 963 // a negative stride). We add a CastII here to guarantee that, when the counted loop is created in a subsequent loop 964 // opts pass, an accurate range of values for the limits is found. 965 const TypeInt* inner_iters_actual_int_range = TypeInt::make(0, iters_limit, Type::WidenMin); 966 inner_iters_actual_int = new CastIINode(outer_head, inner_iters_actual_int, inner_iters_actual_int_range, ConstraintCastNode::UnconditionalDependency); 967 _igvn.register_new_node_with_optimizer(inner_iters_actual_int); 968 } else { 969 inner_iters_actual_int = inner_iters_actual; 970 } 971 972 Node* int_zero = _igvn.intcon(0); 973 set_ctrl(int_zero, C->root()); 974 if (stride_con < 0) { 975 inner_iters_actual_int = new SubINode(int_zero, inner_iters_actual_int); 976 _igvn.register_new_node_with_optimizer(inner_iters_actual_int); 977 } 978 979 // Clone the iv data nodes as an integer iv 980 Node* int_stride = _igvn.intcon(stride_con); 981 set_ctrl(int_stride, C->root()); 982 Node* inner_phi = new PhiNode(x->in(0), TypeInt::INT); 983 Node* inner_incr = new AddINode(inner_phi, int_stride); 984 Node* inner_cmp = nullptr; 985 inner_cmp = new CmpINode(inner_incr, inner_iters_actual_int); 986 Node* inner_bol = new BoolNode(inner_cmp, exit_test->in(1)->as_Bool()->_test._test); 987 inner_phi->set_req(LoopNode::EntryControl, int_zero); 988 inner_phi->set_req(LoopNode::LoopBackControl, inner_incr); 989 register_new_node(inner_phi, x); 990 register_new_node(inner_incr, x); 991 register_new_node(inner_cmp, x); 992 register_new_node(inner_bol, x); 993 994 _igvn.replace_input_of(exit_test, 1, inner_bol); 995 996 // Clone inner loop phis to outer loop 997 for (uint i = 0; i < head->outcnt(); i++) { 998 Node* u = head->raw_out(i); 999 if (u->is_Phi() && u != inner_phi && u != phi) { 1000 assert(u->in(0) == head, "inconsistent"); 1001 Node* clone = u->clone(); 1002 clone->set_req(0, outer_head); 1003 register_new_node(clone, outer_head); 1004 _igvn.replace_input_of(u, LoopNode::EntryControl, clone); 1005 } 1006 } 1007 1008 // Replace inner loop long iv phi as inner loop int iv phi + outer 1009 // loop iv phi 1010 Node* iv_add = loop_nest_replace_iv(phi, inner_phi, outer_phi, head, bt); 1011 1012 set_subtree_ctrl(inner_iters_actual_int, body_populated); 1013 1014 LoopNode* inner_head = create_inner_head(loop, head, exit_test); 1015 1016 // Summary of steps from initial loop to loop nest: 1017 // 1018 // == old IR nodes => 1019 // 1020 // entry_control: {...} 1021 // x: 1022 // for (long phi = init;;) { 1023 // // phi := Phi(x, init, incr) 1024 // // incr := AddL(phi, longcon(stride)) 1025 // exit_test: 1026 // if (phi < limit) 1027 // back_control: fallthrough; 1028 // else 1029 // exit_branch: break; 1030 // long incr = phi + stride; 1031 // ... use phi and incr ... 1032 // phi = incr; 1033 // } 1034 // 1035 // == new IR nodes (just before final peel) => 1036 // 1037 // entry_control: {...} 1038 // long adjusted_limit = limit + stride; //because phi_incr != nullptr 1039 // assert(!limit_check_required || (extralong)limit + stride == adjusted_limit); // else deopt 1040 // ulong inner_iters_limit = max_jint - ABS(stride) - 1; //near 0x7FFFFFF0 1041 // outer_head: 1042 // for (long outer_phi = init;;) { 1043 // // outer_phi := phi->clone(), in(0):=outer_head, => Phi(outer_head, init, incr) 1044 // // REPLACE phi => AddL(outer_phi, I2L(inner_phi)) 1045 // // REPLACE incr => AddL(outer_phi, I2L(inner_incr)) 1046 // // SO THAT outer_phi := Phi(outer_head, init, AddL(outer_phi, I2L(inner_incr))) 1047 // ulong inner_iters_max = (ulong) MAX(0, ((extralong)adjusted_limit - outer_phi) * SGN(stride)); 1048 // int inner_iters_actual_int = (int) MIN(inner_iters_limit, inner_iters_max) * SGN(stride); 1049 // inner_head: x: //in(1) := outer_head 1050 // int inner_phi; 1051 // for (inner_phi = 0;;) { 1052 // // inner_phi := Phi(x, intcon(0), inner_phi + stride) 1053 // int inner_incr = inner_phi + stride; 1054 // bool inner_bol = (inner_incr < inner_iters_actual_int); 1055 // exit_test: //exit_test->in(1) := inner_bol; 1056 // if (inner_bol) // WAS (phi < limit) 1057 // back_control: fallthrough; 1058 // else 1059 // inner_exit_branch: break; //exit_branch->clone() 1060 // ... use phi=>(outer_phi+inner_phi) ... 1061 // inner_phi = inner_phi + stride; // inner_incr 1062 // } 1063 // outer_exit_test: //exit_test->clone(), in(0):=inner_exit_branch 1064 // if ((outer_phi+inner_phi) < limit) // WAS (phi < limit) 1065 // outer_back_branch: fallthrough; //back_control->clone(), in(0):=outer_exit_test 1066 // else 1067 // exit_branch: break; //in(0) := outer_exit_test 1068 // } 1069 1070 if (bt == T_INT) { 1071 outer_phi = new ConvI2LNode(outer_phi); 1072 register_new_node(outer_phi, outer_head); 1073 } 1074 1075 transform_long_range_checks(stride_con, range_checks, outer_phi, inner_iters_actual_int, 1076 inner_phi, iv_add, inner_head); 1077 // Peel one iteration of the loop and use the safepoint at the end 1078 // of the peeled iteration to insert Parse Predicates. If no well 1079 // positioned safepoint peel to guarantee a safepoint in the outer 1080 // loop. 1081 if (safepoint != nullptr || !loop->_has_call) { 1082 old_new.clear(); 1083 do_peeling(loop, old_new); 1084 } else { 1085 C->set_major_progress(); 1086 } 1087 1088 if (safepoint != nullptr) { 1089 SafePointNode* cloned_sfpt = old_new[safepoint->_idx]->as_SafePoint(); 1090 1091 if (UseLoopPredicate) { 1092 add_parse_predicate(Deoptimization::Reason_predicate, inner_head, outer_ilt, cloned_sfpt); 1093 } 1094 if (UseProfiledLoopPredicate) { 1095 add_parse_predicate(Deoptimization::Reason_profile_predicate, inner_head, outer_ilt, cloned_sfpt); 1096 } 1097 add_parse_predicate(Deoptimization::Reason_loop_limit_check, inner_head, outer_ilt, cloned_sfpt); 1098 } 1099 1100 #ifndef PRODUCT 1101 if (bt == T_LONG) { 1102 Atomic::inc(&_long_loop_nests); 1103 } 1104 #endif 1105 1106 inner_head->mark_loop_nest_inner_loop(); 1107 outer_head->mark_loop_nest_outer_loop(); 1108 1109 return true; 1110 } 1111 1112 int PhaseIdealLoop::extract_long_range_checks(const IdealLoopTree* loop, jint stride_con, int iters_limit, PhiNode* phi, 1113 Node_List& range_checks) { 1114 const jlong min_iters = 2; 1115 jlong reduced_iters_limit = iters_limit; 1116 jlong original_iters_limit = iters_limit; 1117 for (uint i = 0; i < loop->_body.size(); i++) { 1118 Node* c = loop->_body.at(i); 1119 if (c->is_IfProj() && c->in(0)->is_RangeCheck()) { 1120 IfProjNode* if_proj = c->as_IfProj(); 1121 CallStaticJavaNode* call = if_proj->is_uncommon_trap_if_pattern(); 1122 if (call != nullptr) { 1123 Node* range = nullptr; 1124 Node* offset = nullptr; 1125 jlong scale = 0; 1126 if (loop->is_range_check_if(if_proj, this, T_LONG, phi, range, offset, scale) && 1127 loop->is_invariant(range) && loop->is_invariant(offset) && 1128 scale != min_jlong && 1129 original_iters_limit / ABS(scale) >= min_iters * ABS(stride_con)) { 1130 assert(scale == (jint)scale, "scale should be an int"); 1131 reduced_iters_limit = MIN2(reduced_iters_limit, original_iters_limit/ABS(scale)); 1132 range_checks.push(c); 1133 } 1134 } 1135 } 1136 } 1137 1138 return checked_cast<int>(reduced_iters_limit); 1139 } 1140 1141 // One execution of the inner loop covers a sub-range of the entire iteration range of the loop: [A,Z), aka [A=init, 1142 // Z=limit). If the loop has at least one trip (which is the case here), the iteration variable i always takes A as its 1143 // first value, followed by A+S (S is the stride), next A+2S, etc. The limit is exclusive, so that the final value B of 1144 // i is never Z. It will be B=Z-1 if S=1, or B=Z+1 if S=-1. 1145 1146 // If |S|>1 the formula for the last value B would require a floor operation, specifically B=floor((Z-sgn(S)-A)/S)*S+A, 1147 // which is B=Z-sgn(S)U for some U in [1,|S|]. So when S>0, i ranges as i:[A,Z) or i:[A,B=Z-U], or else (in reverse) 1148 // as i:(Z,A] or i:[B=Z+U,A]. It will become important to reason about this inclusive range [A,B] or [B,A]. 1149 1150 // Within the loop there may be many range checks. Each such range check (R.C.) is of the form 0 <= i*K+L < R, where K 1151 // is a scale factor applied to the loop iteration variable i, and L is some offset; K, L, and R are loop-invariant. 1152 // Because R is never negative (see below), this check can always be simplified to an unsigned check i*K+L <u R. 1153 1154 // When a long loop over a 64-bit variable i (outer_iv) is decomposed into a series of shorter sub-loops over a 32-bit 1155 // variable j (inner_iv), j ranges over a shorter interval j:[0,B_2] or [0,Z_2) (assuming S > 0), where the limit is 1156 // chosen to prevent various cases of 32-bit overflow (including multiplications j*K below). In the sub-loop the 1157 // logical value i is offset from j by a 64-bit constant C, so i ranges in i:C+[0,Z_2). 1158 1159 // For S<0, j ranges (in reverse!) through j:[-|B_2|,0] or (-|Z_2|,0]. For either sign of S, we can say i=j+C and j 1160 // ranges through 32-bit ranges [A_2,B_2] or [B_2,A_2] (A_2=0 of course). 1161 1162 // The disjoint union of all the C+[A_2,B_2] ranges from the sub-loops must be identical to the whole range [A,B]. 1163 // Assuming S>0, the first C must be A itself, and the next C value is the previous C+B_2, plus S. If |S|=1, the next 1164 // C value is also the previous C+Z_2. In each sub-loop, j counts from j=A_2=0 and i counts from C+0 and exits at 1165 // j=B_2 (i=C+B_2), just before it gets to i=C+Z_2. Both i and j count up (from C and 0) if S>0; otherwise they count 1166 // down (from C and 0 again). 1167 1168 // Returning to range checks, we see that each i*K+L <u R expands to (C+j)*K+L <u R, or j*K+Q <u R, where Q=(C*K+L). 1169 // (Recall that K and L and R are loop-invariant scale, offset and range values for a particular R.C.) This is still a 1170 // 64-bit comparison, so the range check elimination logic will not apply to it. (The R.C.E. transforms operate only on 1171 // 32-bit indexes and comparisons, because they use 64-bit temporary values to avoid overflow; see 1172 // PhaseIdealLoop::add_constraint.) 1173 1174 // We must transform this comparison so that it gets the same answer, but by means of a 32-bit R.C. (using j not i) of 1175 // the form j*K+L_2 <u32 R_2. Note that L_2 and R_2 must be loop-invariant, but only with respect to the sub-loop. Thus, the 1176 // problem reduces to computing values for L_2 and R_2 (for each R.C. in the loop) in the loop header for the sub-loop. 1177 // Then the standard R.C.E. transforms can take those as inputs and further compute the necessary minimum and maximum 1178 // values for the 32-bit counter j within which the range checks can be eliminated. 1179 1180 // So, given j*K+Q <u R, we need to find some j*K+L_2 <u32 R_2, where L_2 and R_2 fit in 32 bits, and the 32-bit operations do 1181 // not overflow. We also need to cover the cases where i*K+L (= j*K+Q) overflows to a 64-bit negative, since that is 1182 // allowed as an input to the R.C., as long as the R.C. as a whole fails. 1183 1184 // If 32-bit multiplication j*K might overflow, we adjust the sub-loop limit Z_2 closer to zero to reduce j's range. 1185 1186 // For each R.C. j*K+Q <u32 R, the range of mathematical values of j*K+Q in the sub-loop is [Q_min, Q_max], where 1187 // Q_min=Q and Q_max=B_2*K+Q (if S>0 and K>0), Q_min=A_2*K+Q and Q_max=Q (if S<0 and K>0), 1188 // Q_min=B_2*K+Q and Q_max=Q if (S>0 and K<0), Q_min=Q and Q_max=A_2*K+Q (if S<0 and K<0) 1189 1190 // Note that the first R.C. value is always Q=(S*K>0 ? Q_min : Q_max). Also Q_{min,max} = Q + {min,max}(A_2*K,B_2*K). 1191 // If S*K>0 then, as the loop iterations progress, each R.C. value i*K+L = j*K+Q goes up from Q=Q_min towards Q_max. 1192 // If S*K<0 then j*K+Q starts at Q=Q_max and goes down towards Q_min. 1193 1194 // Case A: Some Negatives (but no overflow). 1195 // Number line: 1196 // |s64_min . . . 0 . . . s64_max| 1197 // | . Q_min..Q_max . 0 . . . . | s64 negative 1198 // | . . . . R=0 R< R< R< R< | (against R values) 1199 // | . . . Q_min..0..Q_max . . . | small mixed 1200 // | . . . . R R R< R< R< | (against R values) 1201 // 1202 // R values which are out of range (>Q_max+1) are reduced to max(0,Q_max+1). They are marked on the number line as R<. 1203 // 1204 // So, if Q_min <s64 0, then use this test: 1205 // j*K + s32_trunc(Q_min) <u32 clamp(R, 0, Q_max+1) if S*K>0 (R.C.E. steps upward) 1206 // j*K + s32_trunc(Q_max) <u32 clamp(R, 0, Q_max+1) if S*K<0 (R.C.E. steps downward) 1207 // Both formulas reduce to adding j*K to the 32-bit truncated value of the first R.C. expression value, Q: 1208 // j*K + s32_trunc(Q) <u32 clamp(R, 0, Q_max+1) for all S,K 1209 1210 // If the 32-bit truncation loses information, no harm is done, since certainly the clamp also will return R_2=zero. 1211 1212 // Case B: No Negatives. 1213 // Number line: 1214 // |s64_min . . . 0 . . . s64_max| 1215 // | . . . . 0 Q_min..Q_max . . | small positive 1216 // | . . . . R> R R R< R< | (against R values) 1217 // | . . . . 0 . Q_min..Q_max . | s64 positive 1218 // | . . . . R> R> R R R< | (against R values) 1219 // 1220 // R values which are out of range (<Q_min or >Q_max+1) are reduced as marked: R> up to Q_min, R< down to Q_max+1. 1221 // Then the whole comparison is shifted left by Q_min, so it can take place at zero, which is a nice 32-bit value. 1222 // 1223 // So, if both Q_min, Q_max+1 >=s64 0, then use this test: 1224 // j*K + 0 <u32 clamp(R, Q_min, Q_max+1) - Q_min if S*K>0 1225 // More generally: 1226 // j*K + Q - Q_min <u32 clamp(R, Q_min, Q_max+1) - Q_min for all S,K 1227 1228 // Case C: Overflow in the 64-bit domain 1229 // Number line: 1230 // |..Q_max-2^64 . . 0 . . . Q_min..| s64 overflow 1231 // | . . . . R> R> R> R> R | (against R values) 1232 // 1233 // In this case, Q_min >s64 Q_max+1, even though the mathematical values of Q_min and Q_max+1 are correctly ordered. 1234 // The formulas from the previous case can be used, except that the bad upper bound Q_max is replaced by max_jlong. 1235 // (In fact, we could use any replacement bound from R to max_jlong inclusive, as the input to the clamp function.) 1236 // 1237 // So if Q_min >=s64 0 but Q_max+1 <s64 0, use this test: 1238 // j*K + 0 <u32 clamp(R, Q_min, max_jlong) - Q_min if S*K>0 1239 // More generally: 1240 // j*K + Q - Q_min <u32 clamp(R, Q_min, max_jlong) - Q_min for all S,K 1241 // 1242 // Dropping the bad bound means only Q_min is used to reduce the range of R: 1243 // j*K + Q - Q_min <u32 max(Q_min, R) - Q_min for all S,K 1244 // 1245 // Here the clamp function is a 64-bit min/max that reduces the dynamic range of its R operand to the required [L,H]: 1246 // clamp(X, L, H) := max(L, min(X, H)) 1247 // When degenerately L > H, it returns L not H. 1248 // 1249 // All of the formulas above can be merged into a single one: 1250 // L_clamp = Q_min < 0 ? 0 : Q_min --whether and how far to left-shift 1251 // H_clamp = Q_max+1 < Q_min ? max_jlong : Q_max+1 1252 // = Q_max+1 < 0 && Q_min >= 0 ? max_jlong : Q_max+1 1253 // Q_first = Q = (S*K>0 ? Q_min : Q_max) = (C*K+L) 1254 // R_clamp = clamp(R, L_clamp, H_clamp) --reduced dynamic range 1255 // replacement R.C.: 1256 // j*K + Q_first - L_clamp <u32 R_clamp - L_clamp 1257 // or equivalently: 1258 // j*K + L_2 <u32 R_2 1259 // where 1260 // L_2 = Q_first - L_clamp 1261 // R_2 = R_clamp - L_clamp 1262 // 1263 // Note on why R is never negative: 1264 // 1265 // Various details of this transformation would break badly if R could be negative, so this transformation only 1266 // operates after obtaining hard evidence that R<0 is impossible. For example, if R comes from a LoadRange node, we 1267 // know R cannot be negative. For explicit checks (of both int and long) a proof is constructed in 1268 // inline_preconditions_checkIndex, which triggers an uncommon trap if R<0, then wraps R in a ConstraintCastNode with a 1269 // non-negative type. Later on, when IdealLoopTree::is_range_check_if looks for an optimizable R.C., it checks that 1270 // the type of that R node is non-negative. Any "wild" R node that could be negative is not treated as an optimizable 1271 // R.C., but R values from a.length and inside checkIndex are good to go. 1272 // 1273 void PhaseIdealLoop::transform_long_range_checks(int stride_con, const Node_List &range_checks, Node* outer_phi, 1274 Node* inner_iters_actual_int, Node* inner_phi, 1275 Node* iv_add, LoopNode* inner_head) { 1276 Node* long_zero = _igvn.longcon(0); 1277 set_ctrl(long_zero, C->root()); 1278 Node* int_zero = _igvn.intcon(0); 1279 set_ctrl(int_zero, this->C->root()); 1280 Node* long_one = _igvn.longcon(1); 1281 set_ctrl(long_one, this->C->root()); 1282 Node* int_stride = _igvn.intcon(checked_cast<int>(stride_con)); 1283 set_ctrl(int_stride, this->C->root()); 1284 1285 for (uint i = 0; i < range_checks.size(); i++) { 1286 ProjNode* proj = range_checks.at(i)->as_Proj(); 1287 ProjNode* unc_proj = proj->other_if_proj(); 1288 RangeCheckNode* rc = proj->in(0)->as_RangeCheck(); 1289 jlong scale = 0; 1290 Node* offset = nullptr; 1291 Node* rc_bol = rc->in(1); 1292 Node* rc_cmp = rc_bol->in(1); 1293 if (rc_cmp->Opcode() == Op_CmpU) { 1294 // could be shared and have already been taken care of 1295 continue; 1296 } 1297 bool short_scale = false; 1298 bool ok = is_scaled_iv_plus_offset(rc_cmp->in(1), iv_add, T_LONG, &scale, &offset, &short_scale); 1299 assert(ok, "inconsistent: was tested before"); 1300 Node* range = rc_cmp->in(2); 1301 Node* c = rc->in(0); 1302 Node* entry_control = inner_head->in(LoopNode::EntryControl); 1303 1304 Node* R = range; 1305 Node* K = _igvn.longcon(scale); 1306 set_ctrl(K, this->C->root()); 1307 1308 Node* L = offset; 1309 1310 if (short_scale) { 1311 // This converts: 1312 // (int)i*K + L <u64 R 1313 // with K an int into: 1314 // i*(long)K + L <u64 unsigned_min((long)max_jint + L + 1, R) 1315 // to protect against an overflow of (int)i*K 1316 // 1317 // Because if (int)i*K overflows, there are K,L where: 1318 // (int)i*K + L <u64 R is false because (int)i*K+L overflows to a negative which becomes a huge u64 value. 1319 // But if i*(long)K + L is >u64 (long)max_jint and still is <u64 R, then 1320 // i*(long)K + L <u64 R is true. 1321 // 1322 // As a consequence simply converting i*K + L <u64 R to i*(long)K + L <u64 R could cause incorrect execution. 1323 // 1324 // It's always true that: 1325 // (int)i*K <u64 (long)max_jint + 1 1326 // which implies (int)i*K + L <u64 (long)max_jint + 1 + L 1327 // As a consequence: 1328 // i*(long)K + L <u64 unsigned_min((long)max_jint + L + 1, R) 1329 // is always false in case of overflow of i*K 1330 // 1331 // Note, there are also K,L where i*K overflows and 1332 // i*K + L <u64 R is true, but 1333 // i*(long)K + L <u64 unsigned_min((long)max_jint + L + 1, R) is false 1334 // So this transformation could cause spurious deoptimizations and failed range check elimination 1335 // (but not incorrect execution) for unlikely corner cases with overflow. 1336 // If this causes problems in practice, we could maybe direct execution to a post-loop, instead of deoptimizing. 1337 Node* max_jint_plus_one_long = _igvn.longcon((jlong)max_jint + 1); 1338 set_ctrl(max_jint_plus_one_long, C->root()); 1339 Node* max_range = new AddLNode(max_jint_plus_one_long, L); 1340 register_new_node(max_range, entry_control); 1341 R = MaxNode::unsigned_min(R, max_range, TypeLong::POS, _igvn); 1342 set_subtree_ctrl(R, true); 1343 } 1344 1345 Node* C = outer_phi; 1346 1347 // Start with 64-bit values: 1348 // i*K + L <u64 R 1349 // (C+j)*K + L <u64 R 1350 // j*K + Q <u64 R where Q = Q_first = C*K+L 1351 Node* Q_first = new MulLNode(C, K); 1352 register_new_node(Q_first, entry_control); 1353 Q_first = new AddLNode(Q_first, L); 1354 register_new_node(Q_first, entry_control); 1355 1356 // Compute endpoints of the range of values j*K + Q. 1357 // Q_min = (j=0)*K + Q; Q_max = (j=B_2)*K + Q 1358 Node* Q_min = Q_first; 1359 1360 // Compute the exact ending value B_2 (which is really A_2 if S < 0) 1361 Node* B_2 = new LoopLimitNode(this->C, int_zero, inner_iters_actual_int, int_stride); 1362 register_new_node(B_2, entry_control); 1363 B_2 = new SubINode(B_2, int_stride); 1364 register_new_node(B_2, entry_control); 1365 B_2 = new ConvI2LNode(B_2); 1366 register_new_node(B_2, entry_control); 1367 1368 Node* Q_max = new MulLNode(B_2, K); 1369 register_new_node(Q_max, entry_control); 1370 Q_max = new AddLNode(Q_max, Q_first); 1371 register_new_node(Q_max, entry_control); 1372 1373 if (scale * stride_con < 0) { 1374 swap(Q_min, Q_max); 1375 } 1376 // Now, mathematically, Q_max > Q_min, and they are close enough so that (Q_max-Q_min) fits in 32 bits. 1377 1378 // L_clamp = Q_min < 0 ? 0 : Q_min 1379 Node* Q_min_cmp = new CmpLNode(Q_min, long_zero); 1380 register_new_node(Q_min_cmp, entry_control); 1381 Node* Q_min_bool = new BoolNode(Q_min_cmp, BoolTest::lt); 1382 register_new_node(Q_min_bool, entry_control); 1383 Node* L_clamp = new CMoveLNode(Q_min_bool, Q_min, long_zero, TypeLong::LONG); 1384 register_new_node(L_clamp, entry_control); 1385 // (This could also be coded bitwise as L_clamp = Q_min & ~(Q_min>>63).) 1386 1387 Node* Q_max_plus_one = new AddLNode(Q_max, long_one); 1388 register_new_node(Q_max_plus_one, entry_control); 1389 1390 // H_clamp = Q_max+1 < Q_min ? max_jlong : Q_max+1 1391 // (Because Q_min and Q_max are close, the overflow check could also be encoded as Q_max+1 < 0 & Q_min >= 0.) 1392 Node* max_jlong_long = _igvn.longcon(max_jlong); 1393 set_ctrl(max_jlong_long, this->C->root()); 1394 Node* Q_max_cmp = new CmpLNode(Q_max_plus_one, Q_min); 1395 register_new_node(Q_max_cmp, entry_control); 1396 Node* Q_max_bool = new BoolNode(Q_max_cmp, BoolTest::lt); 1397 register_new_node(Q_max_bool, entry_control); 1398 Node* H_clamp = new CMoveLNode(Q_max_bool, Q_max_plus_one, max_jlong_long, TypeLong::LONG); 1399 register_new_node(H_clamp, entry_control); 1400 // (This could also be coded bitwise as H_clamp = ((Q_max+1)<<1 | M)>>>1 where M = (Q_max+1)>>63 & ~Q_min>>63.) 1401 1402 // R_2 = clamp(R, L_clamp, H_clamp) - L_clamp 1403 // that is: R_2 = clamp(R, L_clamp=0, H_clamp=Q_max) if Q_min < 0 1404 // or else: R_2 = clamp(R, L_clamp, H_clamp) - Q_min if Q_min >= 0 1405 // and also: R_2 = clamp(R, L_clamp, Q_max+1) - L_clamp if Q_min < Q_max+1 (no overflow) 1406 // or else: R_2 = clamp(R, L_clamp, *no limit*)- L_clamp if Q_max+1 < Q_min (overflow) 1407 Node* R_2 = clamp(R, L_clamp, H_clamp); 1408 R_2 = new SubLNode(R_2, L_clamp); 1409 register_new_node(R_2, entry_control); 1410 R_2 = new ConvL2INode(R_2, TypeInt::POS); 1411 register_new_node(R_2, entry_control); 1412 1413 // L_2 = Q_first - L_clamp 1414 // We are subtracting L_clamp from both sides of the <u32 comparison. 1415 // If S*K>0, then Q_first == 0 and the R.C. expression at -L_clamp and steps upward to Q_max-L_clamp. 1416 // If S*K<0, then Q_first != 0 and the R.C. expression starts high and steps downward to Q_min-L_clamp. 1417 Node* L_2 = new SubLNode(Q_first, L_clamp); 1418 register_new_node(L_2, entry_control); 1419 L_2 = new ConvL2INode(L_2, TypeInt::INT); 1420 register_new_node(L_2, entry_control); 1421 1422 // Transform the range check using the computed values L_2/R_2 1423 // from: i*K + L <u64 R 1424 // to: j*K + L_2 <u32 R_2 1425 // that is: 1426 // (j*K + Q_first) - L_clamp <u32 clamp(R, L_clamp, H_clamp) - L_clamp 1427 K = _igvn.intcon(checked_cast<int>(scale)); 1428 set_ctrl(K, this->C->root()); 1429 Node* scaled_iv = new MulINode(inner_phi, K); 1430 register_new_node(scaled_iv, c); 1431 Node* scaled_iv_plus_offset = new AddINode(scaled_iv, L_2); 1432 register_new_node(scaled_iv_plus_offset, c); 1433 1434 Node* new_rc_cmp = new CmpUNode(scaled_iv_plus_offset, R_2); 1435 register_new_node(new_rc_cmp, c); 1436 1437 _igvn.replace_input_of(rc_bol, 1, new_rc_cmp); 1438 } 1439 } 1440 1441 Node* PhaseIdealLoop::clamp(Node* R, Node* L, Node* H) { 1442 Node* min = MaxNode::signed_min(R, H, TypeLong::LONG, _igvn); 1443 set_subtree_ctrl(min, true); 1444 Node* max = MaxNode::signed_max(L, min, TypeLong::LONG, _igvn); 1445 set_subtree_ctrl(max, true); 1446 return max; 1447 } 1448 1449 LoopNode* PhaseIdealLoop::create_inner_head(IdealLoopTree* loop, BaseCountedLoopNode* head, 1450 IfNode* exit_test) { 1451 LoopNode* new_inner_head = new LoopNode(head->in(1), head->in(2)); 1452 IfNode* new_inner_exit = new IfNode(exit_test->in(0), exit_test->in(1), exit_test->_prob, exit_test->_fcnt); 1453 _igvn.register_new_node_with_optimizer(new_inner_head); 1454 _igvn.register_new_node_with_optimizer(new_inner_exit); 1455 loop->_body.push(new_inner_head); 1456 loop->_body.push(new_inner_exit); 1457 loop->_body.yank(head); 1458 loop->_body.yank(exit_test); 1459 set_loop(new_inner_head, loop); 1460 set_loop(new_inner_exit, loop); 1461 set_idom(new_inner_head, idom(head), dom_depth(head)); 1462 set_idom(new_inner_exit, idom(exit_test), dom_depth(exit_test)); 1463 lazy_replace(head, new_inner_head); 1464 lazy_replace(exit_test, new_inner_exit); 1465 loop->_head = new_inner_head; 1466 return new_inner_head; 1467 } 1468 1469 #ifdef ASSERT 1470 void PhaseIdealLoop::check_counted_loop_shape(IdealLoopTree* loop, Node* x, BasicType bt) { 1471 Node* back_control = loop_exit_control(x, loop); 1472 assert(back_control != nullptr, "no back control"); 1473 1474 BoolTest::mask mask = BoolTest::illegal; 1475 float cl_prob = 0; 1476 Node* incr = nullptr; 1477 Node* limit = nullptr; 1478 1479 Node* cmp = loop_exit_test(back_control, loop, incr, limit, mask, cl_prob); 1480 assert(cmp != nullptr && cmp->Opcode() == Op_Cmp(bt), "no exit test"); 1481 1482 Node* phi_incr = nullptr; 1483 incr = loop_iv_incr(incr, x, loop, phi_incr); 1484 assert(incr != nullptr && incr->Opcode() == Op_Add(bt), "no incr"); 1485 1486 Node* xphi = nullptr; 1487 Node* stride = loop_iv_stride(incr, loop, xphi); 1488 1489 assert(stride != nullptr, "no stride"); 1490 1491 PhiNode* phi = loop_iv_phi(xphi, phi_incr, x, loop); 1492 1493 assert(phi != nullptr && phi->in(LoopNode::LoopBackControl) == incr, "No phi"); 1494 1495 jlong stride_con = stride->get_integer_as_long(bt); 1496 1497 assert(condition_stride_ok(mask, stride_con), "illegal condition"); 1498 1499 assert(mask != BoolTest::ne, "unexpected condition"); 1500 assert(phi_incr == nullptr, "bad loop shape"); 1501 assert(cmp->in(1) == incr, "bad exit test shape"); 1502 1503 // Safepoint on backedge not supported 1504 assert(x->in(LoopNode::LoopBackControl)->Opcode() != Op_SafePoint, "no safepoint on backedge"); 1505 } 1506 #endif 1507 1508 #ifdef ASSERT 1509 // convert an int counted loop to a long counted to stress handling of 1510 // long counted loops 1511 bool PhaseIdealLoop::convert_to_long_loop(Node* cmp, Node* phi, IdealLoopTree* loop) { 1512 Unique_Node_List iv_nodes; 1513 Node_List old_new; 1514 iv_nodes.push(cmp); 1515 bool failed = false; 1516 1517 for (uint i = 0; i < iv_nodes.size() && !failed; i++) { 1518 Node* n = iv_nodes.at(i); 1519 switch(n->Opcode()) { 1520 case Op_Phi: { 1521 Node* clone = new PhiNode(n->in(0), TypeLong::LONG); 1522 old_new.map(n->_idx, clone); 1523 break; 1524 } 1525 case Op_CmpI: { 1526 Node* clone = new CmpLNode(nullptr, nullptr); 1527 old_new.map(n->_idx, clone); 1528 break; 1529 } 1530 case Op_AddI: { 1531 Node* clone = new AddLNode(nullptr, nullptr); 1532 old_new.map(n->_idx, clone); 1533 break; 1534 } 1535 case Op_CastII: { 1536 failed = true; 1537 break; 1538 } 1539 default: 1540 DEBUG_ONLY(n->dump()); 1541 fatal("unexpected"); 1542 } 1543 1544 for (uint i = 1; i < n->req(); i++) { 1545 Node* in = n->in(i); 1546 if (in == nullptr) { 1547 continue; 1548 } 1549 if (loop->is_member(get_loop(get_ctrl(in)))) { 1550 iv_nodes.push(in); 1551 } 1552 } 1553 } 1554 1555 if (failed) { 1556 for (uint i = 0; i < iv_nodes.size(); i++) { 1557 Node* n = iv_nodes.at(i); 1558 Node* clone = old_new[n->_idx]; 1559 if (clone != nullptr) { 1560 _igvn.remove_dead_node(clone); 1561 } 1562 } 1563 return false; 1564 } 1565 1566 for (uint i = 0; i < iv_nodes.size(); i++) { 1567 Node* n = iv_nodes.at(i); 1568 Node* clone = old_new[n->_idx]; 1569 for (uint i = 1; i < n->req(); i++) { 1570 Node* in = n->in(i); 1571 if (in == nullptr) { 1572 continue; 1573 } 1574 Node* in_clone = old_new[in->_idx]; 1575 if (in_clone == nullptr) { 1576 assert(_igvn.type(in)->isa_int(), ""); 1577 in_clone = new ConvI2LNode(in); 1578 _igvn.register_new_node_with_optimizer(in_clone); 1579 set_subtree_ctrl(in_clone, false); 1580 } 1581 if (in_clone->in(0) == nullptr) { 1582 in_clone->set_req(0, C->top()); 1583 clone->set_req(i, in_clone); 1584 in_clone->set_req(0, nullptr); 1585 } else { 1586 clone->set_req(i, in_clone); 1587 } 1588 } 1589 _igvn.register_new_node_with_optimizer(clone); 1590 } 1591 set_ctrl(old_new[phi->_idx], phi->in(0)); 1592 1593 for (uint i = 0; i < iv_nodes.size(); i++) { 1594 Node* n = iv_nodes.at(i); 1595 Node* clone = old_new[n->_idx]; 1596 set_subtree_ctrl(clone, false); 1597 Node* m = n->Opcode() == Op_CmpI ? clone : nullptr; 1598 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) { 1599 Node* u = n->fast_out(i); 1600 if (iv_nodes.member(u)) { 1601 continue; 1602 } 1603 if (m == nullptr) { 1604 m = new ConvL2INode(clone); 1605 _igvn.register_new_node_with_optimizer(m); 1606 set_subtree_ctrl(m, false); 1607 } 1608 _igvn.rehash_node_delayed(u); 1609 int nb = u->replace_edge(n, m, &_igvn); 1610 --i, imax -= nb; 1611 } 1612 } 1613 return true; 1614 } 1615 #endif 1616 1617 //------------------------------is_counted_loop-------------------------------- 1618 bool PhaseIdealLoop::is_counted_loop(Node* x, IdealLoopTree*&loop, BasicType iv_bt) { 1619 PhaseGVN *gvn = &_igvn; 1620 1621 Node* back_control = loop_exit_control(x, loop); 1622 if (back_control == nullptr) { 1623 return false; 1624 } 1625 1626 BoolTest::mask bt = BoolTest::illegal; 1627 float cl_prob = 0; 1628 Node* incr = nullptr; 1629 Node* limit = nullptr; 1630 Node* cmp = loop_exit_test(back_control, loop, incr, limit, bt, cl_prob); 1631 if (cmp == nullptr || cmp->Opcode() != Op_Cmp(iv_bt)) { 1632 return false; // Avoid pointer & float & 64-bit compares 1633 } 1634 1635 // Trip-counter increment must be commutative & associative. 1636 if (incr->Opcode() == Op_Cast(iv_bt)) { 1637 incr = incr->in(1); 1638 } 1639 1640 Node* phi_incr = nullptr; 1641 incr = loop_iv_incr(incr, x, loop, phi_incr); 1642 if (incr == nullptr) { 1643 return false; 1644 } 1645 1646 Node* trunc1 = nullptr; 1647 Node* trunc2 = nullptr; 1648 const TypeInteger* iv_trunc_t = nullptr; 1649 Node* orig_incr = incr; 1650 if (!(incr = CountedLoopNode::match_incr_with_optional_truncation(incr, &trunc1, &trunc2, &iv_trunc_t, iv_bt))) { 1651 return false; // Funny increment opcode 1652 } 1653 assert(incr->Opcode() == Op_Add(iv_bt), "wrong increment code"); 1654 1655 Node* xphi = nullptr; 1656 Node* stride = loop_iv_stride(incr, loop, xphi); 1657 1658 if (stride == nullptr) { 1659 return false; 1660 } 1661 1662 if (xphi->Opcode() == Op_Cast(iv_bt)) { 1663 xphi = xphi->in(1); 1664 } 1665 1666 // Stride must be constant 1667 jlong stride_con = stride->get_integer_as_long(iv_bt); 1668 assert(stride_con != 0, "missed some peephole opt"); 1669 1670 PhiNode* phi = loop_iv_phi(xphi, phi_incr, x, loop); 1671 1672 if (phi == nullptr || 1673 (trunc1 == nullptr && phi->in(LoopNode::LoopBackControl) != incr) || 1674 (trunc1 != nullptr && phi->in(LoopNode::LoopBackControl) != trunc1)) { 1675 return false; 1676 } 1677 1678 Node* iftrue = back_control; 1679 uint iftrue_op = iftrue->Opcode(); 1680 Node* iff = iftrue->in(0); 1681 BoolNode* test = iff->in(1)->as_Bool(); 1682 1683 const TypeInteger* limit_t = gvn->type(limit)->is_integer(iv_bt); 1684 if (trunc1 != nullptr) { 1685 // When there is a truncation, we must be sure that after the truncation 1686 // the trip counter will end up higher than the limit, otherwise we are looking 1687 // at an endless loop. Can happen with range checks. 1688 1689 // Example: 1690 // int i = 0; 1691 // while (true) 1692 // sum + = array[i]; 1693 // i++; 1694 // i = i && 0x7fff; 1695 // } 1696 // 1697 // If the array is shorter than 0x8000 this exits through a AIOOB 1698 // - Counted loop transformation is ok 1699 // If the array is longer then this is an endless loop 1700 // - No transformation can be done. 1701 1702 const TypeInteger* incr_t = gvn->type(orig_incr)->is_integer(iv_bt); 1703 if (limit_t->hi_as_long() > incr_t->hi_as_long()) { 1704 // if the limit can have a higher value than the increment (before the phi) 1705 return false; 1706 } 1707 } 1708 1709 Node *init_trip = phi->in(LoopNode::EntryControl); 1710 1711 // If iv trunc type is smaller than int, check for possible wrap. 1712 if (!TypeInteger::bottom(iv_bt)->higher_equal(iv_trunc_t)) { 1713 assert(trunc1 != nullptr, "must have found some truncation"); 1714 1715 // Get a better type for the phi (filtered thru if's) 1716 const TypeInteger* phi_ft = filtered_type(phi); 1717 1718 // Can iv take on a value that will wrap? 1719 // 1720 // Ensure iv's limit is not within "stride" of the wrap value. 1721 // 1722 // Example for "short" type 1723 // Truncation ensures value is in the range -32768..32767 (iv_trunc_t) 1724 // If the stride is +10, then the last value of the induction 1725 // variable before the increment (phi_ft->_hi) must be 1726 // <= 32767 - 10 and (phi_ft->_lo) must be >= -32768 to 1727 // ensure no truncation occurs after the increment. 1728 1729 if (stride_con > 0) { 1730 if (iv_trunc_t->hi_as_long() - phi_ft->hi_as_long() < stride_con || 1731 iv_trunc_t->lo_as_long() > phi_ft->lo_as_long()) { 1732 return false; // truncation may occur 1733 } 1734 } else if (stride_con < 0) { 1735 if (iv_trunc_t->lo_as_long() - phi_ft->lo_as_long() > stride_con || 1736 iv_trunc_t->hi_as_long() < phi_ft->hi_as_long()) { 1737 return false; // truncation may occur 1738 } 1739 } 1740 // No possibility of wrap so truncation can be discarded 1741 // Promote iv type to Int 1742 } else { 1743 assert(trunc1 == nullptr && trunc2 == nullptr, "no truncation for int"); 1744 } 1745 1746 if (!condition_stride_ok(bt, stride_con)) { 1747 return false; 1748 } 1749 1750 const TypeInteger* init_t = gvn->type(init_trip)->is_integer(iv_bt); 1751 1752 if (stride_con > 0) { 1753 if (init_t->lo_as_long() > max_signed_integer(iv_bt) - stride_con) { 1754 return false; // cyclic loop 1755 } 1756 } else { 1757 if (init_t->hi_as_long() < min_signed_integer(iv_bt) - stride_con) { 1758 return false; // cyclic loop 1759 } 1760 } 1761 1762 if (phi_incr != nullptr && bt != BoolTest::ne) { 1763 // check if there is a possibility of IV overflowing after the first increment 1764 if (stride_con > 0) { 1765 if (init_t->hi_as_long() > max_signed_integer(iv_bt) - stride_con) { 1766 return false; 1767 } 1768 } else { 1769 if (init_t->lo_as_long() < min_signed_integer(iv_bt) - stride_con) { 1770 return false; 1771 } 1772 } 1773 } 1774 1775 // ================================================= 1776 // ---- SUCCESS! Found A Trip-Counted Loop! ----- 1777 // 1778 1779 if (x->Opcode() == Op_Region) { 1780 // x has not yet been transformed to Loop or LongCountedLoop. 1781 // This should only happen if we are inside an infinite loop. 1782 // It happens like this: 1783 // build_loop_tree -> do not attach infinite loop and nested loops 1784 // beautify_loops -> does not transform the infinite and nested loops to LoopNode, because not attached yet 1785 // build_loop_tree -> find and attach infinite and nested loops 1786 // counted_loop -> nested Regions are not yet transformed to LoopNodes, we land here 1787 assert(x->as_Region()->is_in_infinite_subgraph(), 1788 "x can only be a Region and not Loop if inside infinite loop"); 1789 // Come back later when Region is transformed to LoopNode 1790 return false; 1791 } 1792 1793 assert(x->Opcode() == Op_Loop || x->Opcode() == Op_LongCountedLoop, "regular loops only"); 1794 C->print_method(PHASE_BEFORE_CLOOPS, 3, x); 1795 1796 // =================================================== 1797 // We can only convert this loop to a counted loop if we can guarantee that the iv phi will never overflow at runtime. 1798 // This is an implicit assumption taken by some loop optimizations. We therefore must ensure this property at all cost. 1799 // At this point, we've already excluded some trivial cases where an overflow could have been proven statically. 1800 // But even though we cannot prove that an overflow will *not* happen, we still want to speculatively convert this loop 1801 // to a counted loop. This can be achieved by adding additional iv phi overflow checks before the loop. If they fail, 1802 // we trap and resume execution before the loop without having executed any iteration of the loop, yet. 1803 // 1804 // These additional iv phi overflow checks can be inserted as Loop Limit Check Predicates above the Loop Limit Check 1805 // Parse Predicate which captures a JVM state just before the entry of the loop. If there is no such Parse Predicate, 1806 // we cannot generate a Loop Limit Check Predicate and thus cannot speculatively convert the loop to a counted loop. 1807 // 1808 // In the following, we only focus on int loops with stride > 0 to keep things simple. The argumentation and proof 1809 // for stride < 0 is analogously. For long loops, we would replace max_int with max_long. 1810 // 1811 // 1812 // The loop to be converted does not always need to have the often used shape: 1813 // 1814 // i = init 1815 // i = init loop: 1816 // do { ... 1817 // // ... equivalent i+=stride 1818 // i+=stride <==> if (i < limit) 1819 // } while (i < limit); goto loop 1820 // exit: 1821 // ... 1822 // 1823 // where the loop exit check uses the post-incremented iv phi and a '<'-operator. 1824 // 1825 // We could also have '<='-operator (or '>='-operator for negative strides) or use the pre-incremented iv phi value 1826 // in the loop exit check: 1827 // 1828 // i = init 1829 // loop: 1830 // ... 1831 // if (i <= limit) 1832 // i+=stride 1833 // goto loop 1834 // exit: 1835 // ... 1836 // 1837 // Let's define the following terms: 1838 // - iv_pre_i: The pre-incremented iv phi before the i-th iteration. 1839 // - iv_post_i: The post-incremented iv phi after the i-th iteration. 1840 // 1841 // The iv_pre_i and iv_post_i have the following relation: 1842 // iv_pre_i + stride = iv_post_i 1843 // 1844 // When converting a loop to a counted loop, we want to have a canonicalized loop exit check of the form: 1845 // iv_post_i < adjusted_limit 1846 // 1847 // If that is not the case, we need to canonicalize the loop exit check by using different values for adjusted_limit: 1848 // (LE1) iv_post_i < limit: Already canonicalized. We can directly use limit as adjusted_limit. 1849 // -> adjusted_limit = limit. 1850 // (LE2) iv_post_i <= limit: 1851 // iv_post_i < limit + 1 1852 // -> adjusted limit = limit + 1 1853 // (LE3) iv_pre_i < limit: 1854 // iv_pre_i + stride < limit + stride 1855 // iv_post_i < limit + stride 1856 // -> adjusted_limit = limit + stride 1857 // (LE4) iv_pre_i <= limit: 1858 // iv_pre_i < limit + 1 1859 // iv_pre_i + stride < limit + stride + 1 1860 // iv_post_i < limit + stride + 1 1861 // -> adjusted_limit = limit + stride + 1 1862 // 1863 // Note that: 1864 // (AL) limit <= adjusted_limit. 1865 // 1866 // The following loop invariant has to hold for counted loops with n iterations (i.e. loop exit check true after n-th 1867 // loop iteration) and a canonicalized loop exit check to guarantee that no iv_post_i over- or underflows: 1868 // (INV) For i = 1..n, min_int <= iv_post_i <= max_int 1869 // 1870 // To prove (INV), we require the following two conditions/assumptions: 1871 // (i): adjusted_limit - 1 + stride <= max_int 1872 // (ii): init < limit 1873 // 1874 // If we can prove (INV), we know that there can be no over- or underflow of any iv phi value. We prove (INV) by 1875 // induction by assuming (i) and (ii). 1876 // 1877 // Proof by Induction 1878 // ------------------ 1879 // > Base case (i = 1): We show that (INV) holds after the first iteration: 1880 // min_int <= iv_post_1 = init + stride <= max_int 1881 // Proof: 1882 // First, we note that (ii) implies 1883 // (iii) init <= limit - 1 1884 // max_int >= adjusted_limit - 1 + stride [using (i)] 1885 // >= limit - 1 + stride [using (AL)] 1886 // >= init + stride [using (iii)] 1887 // >= min_int [using stride > 0, no underflow] 1888 // Thus, no overflow happens after the first iteration and (INV) holds for i = 1. 1889 // 1890 // Note that to prove the base case we need (i) and (ii). 1891 // 1892 // > Induction Hypothesis (i = j, j > 1): Assume that (INV) holds after the j-th iteration: 1893 // min_int <= iv_post_j <= max_int 1894 // > Step case (i = j + 1): We show that (INV) also holds after the j+1-th iteration: 1895 // min_int <= iv_post_{j+1} = iv_post_j + stride <= max_int 1896 // Proof: 1897 // If iv_post_j >= adjusted_limit: 1898 // We exit the loop after the j-th iteration, and we don't execute the j+1-th iteration anymore. Thus, there is 1899 // also no iv_{j+1}. Since (INV) holds for iv_j, there is nothing left to prove. 1900 // If iv_post_j < adjusted_limit: 1901 // First, we note that: 1902 // (iv) iv_post_j <= adjusted_limit - 1 1903 // max_int >= adjusted_limit - 1 + stride [using (i)] 1904 // >= iv_post_j + stride [using (iv)] 1905 // >= min_int [using stride > 0, no underflow] 1906 // 1907 // Note that to prove the step case we only need (i). 1908 // 1909 // Thus, by assuming (i) and (ii), we proved (INV). 1910 // 1911 // 1912 // It is therefore enough to add the following two Loop Limit Check Predicates to check assumptions (i) and (ii): 1913 // 1914 // (1) Loop Limit Check Predicate for (i): 1915 // Using (i): adjusted_limit - 1 + stride <= max_int 1916 // 1917 // This condition is now restated to use limit instead of adjusted_limit: 1918 // 1919 // To prevent an overflow of adjusted_limit -1 + stride itself, we rewrite this check to 1920 // max_int - stride + 1 >= adjusted_limit 1921 // We can merge the two constants into 1922 // canonicalized_correction = stride - 1 1923 // which gives us 1924 // max_int - canonicalized_correction >= adjusted_limit 1925 // 1926 // To directly use limit instead of adjusted_limit in the predicate condition, we split adjusted_limit into: 1927 // adjusted_limit = limit + limit_correction 1928 // Since stride > 0 and limit_correction <= stride + 1, we can restate this with no over- or underflow into: 1929 // max_int - canonicalized_correction - limit_correction >= limit 1930 // Since canonicalized_correction and limit_correction are both constants, we can replace them with a new constant: 1931 // (v) final_correction = canonicalized_correction + limit_correction 1932 // 1933 // which gives us: 1934 // 1935 // Final predicate condition: 1936 // max_int - final_correction >= limit 1937 // 1938 // However, we need to be careful that (v) does not over- or underflow. 1939 // We know that: 1940 // canonicalized_correction = stride - 1 1941 // and 1942 // limit_correction <= stride + 1 1943 // and thus 1944 // canonicalized_correction + limit_correction <= 2 * stride 1945 // To prevent an over- or underflow of (v), we must ensure that 1946 // 2 * stride <= max_int 1947 // which can safely be checked without over- or underflow with 1948 // (vi) stride != min_int AND abs(stride) <= max_int / 2 1949 // 1950 // We could try to further optimize the cases where (vi) does not hold but given that such large strides are 1951 // very uncommon and the loop would only run for a very few iterations anyway, we simply bail out if (vi) fails. 1952 // 1953 // (2) Loop Limit Check Predicate for (ii): 1954 // Using (ii): init < limit 1955 // 1956 // This Loop Limit Check Predicate is not required if we can prove at compile time that either: 1957 // (2.1) type(init) < type(limit) 1958 // In this case, we know: 1959 // all possible values of init < all possible values of limit 1960 // and we can skip the predicate. 1961 // 1962 // (2.2) init < limit is already checked before (i.e. found as a dominating check) 1963 // In this case, we do not need to re-check the condition and can skip the predicate. 1964 // This is often found for while- and for-loops which have the following shape: 1965 // 1966 // if (init < limit) { // Dominating test. Do not need the Loop Limit Check Predicate below. 1967 // i = init; 1968 // if (init >= limit) { trap(); } // Here we would insert the Loop Limit Check Predicate 1969 // do { 1970 // i += stride; 1971 // } while (i < limit); 1972 // } 1973 // 1974 // (2.3) init + stride <= max_int 1975 // In this case, there is no overflow of the iv phi after the first loop iteration. 1976 // In the proof of the base case above we showed that init + stride <= max_int by using assumption (ii): 1977 // init < limit 1978 // In the proof of the step case above, we did not need (ii) anymore. Therefore, if we already know at 1979 // compile time that init + stride <= max_int then we have trivially proven the base case and that 1980 // there is no overflow of the iv phi after the first iteration. In this case, we don't need to check (ii) 1981 // again and can skip the predicate. 1982 1983 // Check (vi) and bail out if the stride is too big. 1984 if (stride_con == min_signed_integer(iv_bt) || (ABS(stride_con) > max_signed_integer(iv_bt) / 2)) { 1985 return false; 1986 } 1987 1988 // Accounting for (LE3) and (LE4) where we use pre-incremented phis in the loop exit check. 1989 const jlong limit_correction_for_pre_iv_exit_check = (phi_incr != nullptr) ? stride_con : 0; 1990 1991 // Accounting for (LE2) and (LE4) where we use <= or >= in the loop exit check. 1992 const bool includes_limit = (bt == BoolTest::le || bt == BoolTest::ge); 1993 const jlong limit_correction_for_le_ge_exit_check = (includes_limit ? (stride_con > 0 ? 1 : -1) : 0); 1994 1995 const jlong limit_correction = limit_correction_for_pre_iv_exit_check + limit_correction_for_le_ge_exit_check; 1996 const jlong canonicalized_correction = stride_con + (stride_con > 0 ? -1 : 1); 1997 const jlong final_correction = canonicalized_correction + limit_correction; 1998 1999 int sov = check_stride_overflow(final_correction, limit_t, iv_bt); 2000 Node* init_control = x->in(LoopNode::EntryControl); 2001 2002 // If sov==0, limit's type always satisfies the condition, for 2003 // example, when it is an array length. 2004 if (sov != 0) { 2005 if (sov < 0) { 2006 return false; // Bailout: integer overflow is certain. 2007 } 2008 // (1) Loop Limit Check Predicate is required because we could not statically prove that 2009 // limit + final_correction = adjusted_limit - 1 + stride <= max_int 2010 assert(!x->as_Loop()->is_loop_nest_inner_loop(), "loop was transformed"); 2011 const Predicates predicates(init_control); 2012 const PredicateBlock* loop_limit_check_predicate_block = predicates.loop_limit_check_predicate_block(); 2013 if (!loop_limit_check_predicate_block->has_parse_predicate()) { 2014 // The Loop Limit Check Parse Predicate is not generated if this method trapped here before. 2015 #ifdef ASSERT 2016 if (TraceLoopLimitCheck) { 2017 tty->print("Missing Loop Limit Check Parse Predicate:"); 2018 loop->dump_head(); 2019 x->dump(1); 2020 } 2021 #endif 2022 return false; 2023 } 2024 2025 ParsePredicateNode* loop_limit_check_parse_predicate = loop_limit_check_predicate_block->parse_predicate(); 2026 if (!is_dominator(get_ctrl(limit), loop_limit_check_parse_predicate->in(0))) { 2027 return false; 2028 } 2029 2030 Node* cmp_limit; 2031 Node* bol; 2032 2033 if (stride_con > 0) { 2034 cmp_limit = CmpNode::make(limit, _igvn.integercon(max_signed_integer(iv_bt) - final_correction, iv_bt), iv_bt); 2035 bol = new BoolNode(cmp_limit, BoolTest::le); 2036 } else { 2037 cmp_limit = CmpNode::make(limit, _igvn.integercon(min_signed_integer(iv_bt) - final_correction, iv_bt), iv_bt); 2038 bol = new BoolNode(cmp_limit, BoolTest::ge); 2039 } 2040 2041 insert_loop_limit_check_predicate(init_control->as_IfTrue(), cmp_limit, bol); 2042 } 2043 2044 // (2.3) 2045 const bool init_plus_stride_could_overflow = 2046 (stride_con > 0 && init_t->hi_as_long() > max_signed_integer(iv_bt) - stride_con) || 2047 (stride_con < 0 && init_t->lo_as_long() < min_signed_integer(iv_bt) - stride_con); 2048 // (2.1) 2049 const bool init_gte_limit = (stride_con > 0 && init_t->hi_as_long() >= limit_t->lo_as_long()) || 2050 (stride_con < 0 && init_t->lo_as_long() <= limit_t->hi_as_long()); 2051 2052 if (init_gte_limit && // (2.1) 2053 ((bt == BoolTest::ne || init_plus_stride_could_overflow) && // (2.3) 2054 !has_dominating_loop_limit_check(init_trip, limit, stride_con, iv_bt, init_control))) { // (2.2) 2055 // (2) Iteration Loop Limit Check Predicate is required because neither (2.1), (2.2), nor (2.3) holds. 2056 // We use the following condition: 2057 // - stride > 0: init < limit 2058 // - stride < 0: init > limit 2059 // 2060 // This predicate is always required if we have a non-equal-operator in the loop exit check (where stride = 1 is 2061 // a requirement). We transform the loop exit check by using a less-than-operator. By doing so, we must always 2062 // check that init < limit. Otherwise, we could have a different number of iterations at runtime. 2063 2064 const Predicates predicates(init_control); 2065 const PredicateBlock* loop_limit_check_predicate_block = predicates.loop_limit_check_predicate_block(); 2066 if (!loop_limit_check_predicate_block->has_parse_predicate()) { 2067 // The Loop Limit Check Parse Predicate is not generated if this method trapped here before. 2068 #ifdef ASSERT 2069 if (TraceLoopLimitCheck) { 2070 tty->print("Missing Loop Limit Check Parse Predicate:"); 2071 loop->dump_head(); 2072 x->dump(1); 2073 } 2074 #endif 2075 return false; 2076 } 2077 2078 ParsePredicateNode* loop_limit_check_parse_predicate = loop_limit_check_predicate_block->parse_predicate(); 2079 Node* parse_predicate_entry = loop_limit_check_parse_predicate->in(0); 2080 if (!is_dominator(get_ctrl(limit), parse_predicate_entry) || 2081 !is_dominator(get_ctrl(init_trip), parse_predicate_entry)) { 2082 return false; 2083 } 2084 2085 Node* cmp_limit; 2086 Node* bol; 2087 2088 if (stride_con > 0) { 2089 cmp_limit = CmpNode::make(init_trip, limit, iv_bt); 2090 bol = new BoolNode(cmp_limit, BoolTest::lt); 2091 } else { 2092 cmp_limit = CmpNode::make(init_trip, limit, iv_bt); 2093 bol = new BoolNode(cmp_limit, BoolTest::gt); 2094 } 2095 2096 insert_loop_limit_check_predicate(init_control->as_IfTrue(), cmp_limit, bol); 2097 } 2098 2099 if (bt == BoolTest::ne) { 2100 // Now we need to canonicalize the loop condition if it is 'ne'. 2101 assert(stride_con == 1 || stride_con == -1, "simple increment only - checked before"); 2102 if (stride_con > 0) { 2103 // 'ne' can be replaced with 'lt' only when init < limit. This is ensured by the inserted predicate above. 2104 bt = BoolTest::lt; 2105 } else { 2106 assert(stride_con < 0, "must be"); 2107 // 'ne' can be replaced with 'gt' only when init > limit. This is ensured by the inserted predicate above. 2108 bt = BoolTest::gt; 2109 } 2110 } 2111 2112 Node* sfpt = nullptr; 2113 if (loop->_child == nullptr) { 2114 sfpt = find_safepoint(back_control, x, loop); 2115 } else { 2116 sfpt = iff->in(0); 2117 if (sfpt->Opcode() != Op_SafePoint) { 2118 sfpt = nullptr; 2119 } 2120 } 2121 2122 if (x->in(LoopNode::LoopBackControl)->Opcode() == Op_SafePoint) { 2123 Node* backedge_sfpt = x->in(LoopNode::LoopBackControl); 2124 if (((iv_bt == T_INT && LoopStripMiningIter != 0) || 2125 iv_bt == T_LONG) && 2126 sfpt == nullptr) { 2127 // Leaving the safepoint on the backedge and creating a 2128 // CountedLoop will confuse optimizations. We can't move the 2129 // safepoint around because its jvm state wouldn't match a new 2130 // location. Give up on that loop. 2131 return false; 2132 } 2133 if (is_deleteable_safept(backedge_sfpt)) { 2134 lazy_replace(backedge_sfpt, iftrue); 2135 if (loop->_safepts != nullptr) { 2136 loop->_safepts->yank(backedge_sfpt); 2137 } 2138 loop->_tail = iftrue; 2139 } 2140 } 2141 2142 2143 #ifdef ASSERT 2144 if (iv_bt == T_INT && 2145 !x->as_Loop()->is_loop_nest_inner_loop() && 2146 StressLongCountedLoop > 0 && 2147 trunc1 == nullptr && 2148 convert_to_long_loop(cmp, phi, loop)) { 2149 return false; 2150 } 2151 #endif 2152 2153 Node* adjusted_limit = limit; 2154 if (phi_incr != nullptr) { 2155 // If compare points directly to the phi we need to adjust 2156 // the compare so that it points to the incr. Limit have 2157 // to be adjusted to keep trip count the same and we 2158 // should avoid int overflow. 2159 // 2160 // i = init; do {} while(i++ < limit); 2161 // is converted to 2162 // i = init; do {} while(++i < limit+1); 2163 // 2164 adjusted_limit = gvn->transform(AddNode::make(limit, stride, iv_bt)); 2165 } 2166 2167 if (includes_limit) { 2168 // The limit check guaranties that 'limit <= (max_jint - stride)' so 2169 // we can convert 'i <= limit' to 'i < limit+1' since stride != 0. 2170 // 2171 Node* one = (stride_con > 0) ? gvn->integercon( 1, iv_bt) : gvn->integercon(-1, iv_bt); 2172 adjusted_limit = gvn->transform(AddNode::make(adjusted_limit, one, iv_bt)); 2173 if (bt == BoolTest::le) 2174 bt = BoolTest::lt; 2175 else if (bt == BoolTest::ge) 2176 bt = BoolTest::gt; 2177 else 2178 ShouldNotReachHere(); 2179 } 2180 set_subtree_ctrl(adjusted_limit, false); 2181 2182 // Build a canonical trip test. 2183 // Clone code, as old values may be in use. 2184 incr = incr->clone(); 2185 incr->set_req(1,phi); 2186 incr->set_req(2,stride); 2187 incr = _igvn.register_new_node_with_optimizer(incr); 2188 set_early_ctrl(incr, false); 2189 _igvn.rehash_node_delayed(phi); 2190 phi->set_req_X( LoopNode::LoopBackControl, incr, &_igvn ); 2191 2192 // If phi type is more restrictive than Int, raise to 2193 // Int to prevent (almost) infinite recursion in igvn 2194 // which can only handle integer types for constants or minint..maxint. 2195 if (!TypeInteger::bottom(iv_bt)->higher_equal(phi->bottom_type())) { 2196 Node* nphi = PhiNode::make(phi->in(0), phi->in(LoopNode::EntryControl), TypeInteger::bottom(iv_bt)); 2197 nphi->set_req(LoopNode::LoopBackControl, phi->in(LoopNode::LoopBackControl)); 2198 nphi = _igvn.register_new_node_with_optimizer(nphi); 2199 set_ctrl(nphi, get_ctrl(phi)); 2200 _igvn.replace_node(phi, nphi); 2201 phi = nphi->as_Phi(); 2202 } 2203 cmp = cmp->clone(); 2204 cmp->set_req(1,incr); 2205 cmp->set_req(2, adjusted_limit); 2206 cmp = _igvn.register_new_node_with_optimizer(cmp); 2207 set_ctrl(cmp, iff->in(0)); 2208 2209 test = test->clone()->as_Bool(); 2210 (*(BoolTest*)&test->_test)._test = bt; 2211 test->set_req(1,cmp); 2212 _igvn.register_new_node_with_optimizer(test); 2213 set_ctrl(test, iff->in(0)); 2214 2215 // Replace the old IfNode with a new LoopEndNode 2216 Node *lex = _igvn.register_new_node_with_optimizer(BaseCountedLoopEndNode::make(iff->in(0), test, cl_prob, iff->as_If()->_fcnt, iv_bt)); 2217 IfNode *le = lex->as_If(); 2218 uint dd = dom_depth(iff); 2219 set_idom(le, le->in(0), dd); // Update dominance for loop exit 2220 set_loop(le, loop); 2221 2222 // Get the loop-exit control 2223 Node *iffalse = iff->as_If()->proj_out(!(iftrue_op == Op_IfTrue)); 2224 2225 // Need to swap loop-exit and loop-back control? 2226 if (iftrue_op == Op_IfFalse) { 2227 Node *ift2=_igvn.register_new_node_with_optimizer(new IfTrueNode (le)); 2228 Node *iff2=_igvn.register_new_node_with_optimizer(new IfFalseNode(le)); 2229 2230 loop->_tail = back_control = ift2; 2231 set_loop(ift2, loop); 2232 set_loop(iff2, get_loop(iffalse)); 2233 2234 // Lazy update of 'get_ctrl' mechanism. 2235 lazy_replace(iffalse, iff2); 2236 lazy_replace(iftrue, ift2); 2237 2238 // Swap names 2239 iffalse = iff2; 2240 iftrue = ift2; 2241 } else { 2242 _igvn.rehash_node_delayed(iffalse); 2243 _igvn.rehash_node_delayed(iftrue); 2244 iffalse->set_req_X( 0, le, &_igvn ); 2245 iftrue ->set_req_X( 0, le, &_igvn ); 2246 } 2247 2248 set_idom(iftrue, le, dd+1); 2249 set_idom(iffalse, le, dd+1); 2250 assert(iff->outcnt() == 0, "should be dead now"); 2251 lazy_replace( iff, le ); // fix 'get_ctrl' 2252 2253 Node* entry_control = init_control; 2254 bool strip_mine_loop = iv_bt == T_INT && 2255 loop->_child == nullptr && 2256 sfpt != nullptr && 2257 !loop->_has_call && 2258 is_deleteable_safept(sfpt); 2259 IdealLoopTree* outer_ilt = nullptr; 2260 if (strip_mine_loop) { 2261 outer_ilt = create_outer_strip_mined_loop(test, cmp, init_control, loop, 2262 cl_prob, le->_fcnt, entry_control, 2263 iffalse); 2264 } 2265 2266 // Now setup a new CountedLoopNode to replace the existing LoopNode 2267 BaseCountedLoopNode *l = BaseCountedLoopNode::make(entry_control, back_control, iv_bt); 2268 l->set_unswitch_count(x->as_Loop()->unswitch_count()); // Preserve 2269 // The following assert is approximately true, and defines the intention 2270 // of can_be_counted_loop. It fails, however, because phase->type 2271 // is not yet initialized for this loop and its parts. 2272 //assert(l->can_be_counted_loop(this), "sanity"); 2273 _igvn.register_new_node_with_optimizer(l); 2274 set_loop(l, loop); 2275 loop->_head = l; 2276 // Fix all data nodes placed at the old loop head. 2277 // Uses the lazy-update mechanism of 'get_ctrl'. 2278 lazy_replace( x, l ); 2279 set_idom(l, entry_control, dom_depth(entry_control) + 1); 2280 2281 if (iv_bt == T_INT && (LoopStripMiningIter == 0 || strip_mine_loop)) { 2282 // Check for immediately preceding SafePoint and remove 2283 if (sfpt != nullptr && (strip_mine_loop || is_deleteable_safept(sfpt))) { 2284 if (strip_mine_loop) { 2285 Node* outer_le = outer_ilt->_tail->in(0); 2286 Node* sfpt_clone = sfpt->clone(); 2287 sfpt_clone->set_req(0, iffalse); 2288 outer_le->set_req(0, sfpt_clone); 2289 2290 Node* polladdr = sfpt_clone->in(TypeFunc::Parms); 2291 if (polladdr != nullptr && polladdr->is_Load()) { 2292 // Polling load should be pinned outside inner loop. 2293 Node* new_polladdr = polladdr->clone(); 2294 new_polladdr->set_req(0, iffalse); 2295 _igvn.register_new_node_with_optimizer(new_polladdr, polladdr); 2296 set_ctrl(new_polladdr, iffalse); 2297 sfpt_clone->set_req(TypeFunc::Parms, new_polladdr); 2298 } 2299 // When this code runs, loop bodies have not yet been populated. 2300 const bool body_populated = false; 2301 register_control(sfpt_clone, outer_ilt, iffalse, body_populated); 2302 set_idom(outer_le, sfpt_clone, dom_depth(sfpt_clone)); 2303 } 2304 lazy_replace(sfpt, sfpt->in(TypeFunc::Control)); 2305 if (loop->_safepts != nullptr) { 2306 loop->_safepts->yank(sfpt); 2307 } 2308 } 2309 } 2310 2311 #ifdef ASSERT 2312 assert(l->is_valid_counted_loop(iv_bt), "counted loop shape is messed up"); 2313 assert(l == loop->_head && l->phi() == phi && l->loopexit_or_null() == lex, "" ); 2314 #endif 2315 #ifndef PRODUCT 2316 if (TraceLoopOpts) { 2317 tty->print("Counted "); 2318 loop->dump_head(); 2319 } 2320 #endif 2321 2322 C->print_method(PHASE_AFTER_CLOOPS, 3, l); 2323 2324 // Capture bounds of the loop in the induction variable Phi before 2325 // subsequent transformation (iteration splitting) obscures the 2326 // bounds 2327 l->phi()->as_Phi()->set_type(l->phi()->Value(&_igvn)); 2328 2329 if (strip_mine_loop) { 2330 l->mark_strip_mined(); 2331 l->verify_strip_mined(1); 2332 outer_ilt->_head->as_Loop()->verify_strip_mined(1); 2333 loop = outer_ilt; 2334 } 2335 2336 #ifndef PRODUCT 2337 if (x->as_Loop()->is_loop_nest_inner_loop() && iv_bt == T_LONG) { 2338 Atomic::inc(&_long_loop_counted_loops); 2339 } 2340 #endif 2341 if (iv_bt == T_LONG && x->as_Loop()->is_loop_nest_outer_loop()) { 2342 l->mark_loop_nest_outer_loop(); 2343 } 2344 2345 return true; 2346 } 2347 2348 // Check if there is a dominating loop limit check of the form 'init < limit' starting at the loop entry. 2349 // If there is one, then we do not need to create an additional Loop Limit Check Predicate. 2350 bool PhaseIdealLoop::has_dominating_loop_limit_check(Node* init_trip, Node* limit, const jlong stride_con, 2351 const BasicType iv_bt, Node* loop_entry) { 2352 // Eagerly call transform() on the Cmp and Bool node to common them up if possible. This is required in order to 2353 // successfully find a dominated test with the If node below. 2354 Node* cmp_limit; 2355 Node* bol; 2356 if (stride_con > 0) { 2357 cmp_limit = _igvn.transform(CmpNode::make(init_trip, limit, iv_bt)); 2358 bol = _igvn.transform(new BoolNode(cmp_limit, BoolTest::lt)); 2359 } else { 2360 cmp_limit = _igvn.transform(CmpNode::make(init_trip, limit, iv_bt)); 2361 bol = _igvn.transform(new BoolNode(cmp_limit, BoolTest::gt)); 2362 } 2363 2364 // Check if there is already a dominating init < limit check. If so, we do not need a Loop Limit Check Predicate. 2365 IfNode* iff = new IfNode(loop_entry, bol, PROB_MIN, COUNT_UNKNOWN); 2366 // Also add fake IfProj nodes in order to call transform() on the newly created IfNode. 2367 IfFalseNode* if_false = new IfFalseNode(iff); 2368 IfTrueNode* if_true = new IfTrueNode(iff); 2369 Node* dominated_iff = _igvn.transform(iff); 2370 // ConI node? Found dominating test (IfNode::dominated_by() returns a ConI node). 2371 const bool found_dominating_test = dominated_iff != nullptr && dominated_iff->is_ConI(); 2372 2373 // Kill the If with its projections again in the next IGVN round by cutting it off from the graph. 2374 _igvn.replace_input_of(iff, 0, C->top()); 2375 _igvn.replace_input_of(iff, 1, C->top()); 2376 return found_dominating_test; 2377 } 2378 2379 //----------------------exact_limit------------------------------------------- 2380 Node* PhaseIdealLoop::exact_limit( IdealLoopTree *loop ) { 2381 assert(loop->_head->is_CountedLoop(), ""); 2382 CountedLoopNode *cl = loop->_head->as_CountedLoop(); 2383 assert(cl->is_valid_counted_loop(T_INT), ""); 2384 2385 if (cl->stride_con() == 1 || 2386 cl->stride_con() == -1 || 2387 cl->limit()->Opcode() == Op_LoopLimit) { 2388 // Old code has exact limit (it could be incorrect in case of int overflow). 2389 // Loop limit is exact with stride == 1. And loop may already have exact limit. 2390 return cl->limit(); 2391 } 2392 Node *limit = nullptr; 2393 #ifdef ASSERT 2394 BoolTest::mask bt = cl->loopexit()->test_trip(); 2395 assert(bt == BoolTest::lt || bt == BoolTest::gt, "canonical test is expected"); 2396 #endif 2397 if (cl->has_exact_trip_count()) { 2398 // Simple case: loop has constant boundaries. 2399 // Use jlongs to avoid integer overflow. 2400 int stride_con = cl->stride_con(); 2401 jlong init_con = cl->init_trip()->get_int(); 2402 jlong limit_con = cl->limit()->get_int(); 2403 julong trip_cnt = cl->trip_count(); 2404 jlong final_con = init_con + trip_cnt*stride_con; 2405 int final_int = (int)final_con; 2406 // The final value should be in integer range since the loop 2407 // is counted and the limit was checked for overflow. 2408 assert(final_con == (jlong)final_int, "final value should be integer"); 2409 limit = _igvn.intcon(final_int); 2410 } else { 2411 // Create new LoopLimit node to get exact limit (final iv value). 2412 limit = new LoopLimitNode(C, cl->init_trip(), cl->limit(), cl->stride()); 2413 register_new_node(limit, cl->in(LoopNode::EntryControl)); 2414 } 2415 assert(limit != nullptr, "sanity"); 2416 return limit; 2417 } 2418 2419 //------------------------------Ideal------------------------------------------ 2420 // Return a node which is more "ideal" than the current node. 2421 // Attempt to convert into a counted-loop. 2422 Node *LoopNode::Ideal(PhaseGVN *phase, bool can_reshape) { 2423 if (!can_be_counted_loop(phase) && !is_OuterStripMinedLoop()) { 2424 phase->C->set_major_progress(); 2425 } 2426 return RegionNode::Ideal(phase, can_reshape); 2427 } 2428 2429 #ifdef ASSERT 2430 void LoopNode::verify_strip_mined(int expect_skeleton) const { 2431 const OuterStripMinedLoopNode* outer = nullptr; 2432 const CountedLoopNode* inner = nullptr; 2433 if (is_strip_mined()) { 2434 if (!is_valid_counted_loop(T_INT)) { 2435 return; // Skip malformed counted loop 2436 } 2437 assert(is_CountedLoop(), "no Loop should be marked strip mined"); 2438 inner = as_CountedLoop(); 2439 outer = inner->in(LoopNode::EntryControl)->as_OuterStripMinedLoop(); 2440 } else if (is_OuterStripMinedLoop()) { 2441 outer = this->as_OuterStripMinedLoop(); 2442 inner = outer->unique_ctrl_out()->as_CountedLoop(); 2443 assert(inner->is_valid_counted_loop(T_INT) && inner->is_strip_mined(), "OuterStripMinedLoop should have been removed"); 2444 assert(!is_strip_mined(), "outer loop shouldn't be marked strip mined"); 2445 } 2446 if (inner != nullptr || outer != nullptr) { 2447 assert(inner != nullptr && outer != nullptr, "missing loop in strip mined nest"); 2448 Node* outer_tail = outer->in(LoopNode::LoopBackControl); 2449 Node* outer_le = outer_tail->in(0); 2450 assert(outer_le->Opcode() == Op_OuterStripMinedLoopEnd, "tail of outer loop should be an If"); 2451 Node* sfpt = outer_le->in(0); 2452 assert(sfpt->Opcode() == Op_SafePoint, "where's the safepoint?"); 2453 Node* inner_out = sfpt->in(0); 2454 CountedLoopEndNode* cle = inner_out->in(0)->as_CountedLoopEnd(); 2455 assert(cle == inner->loopexit_or_null(), "mismatch"); 2456 bool has_skeleton = outer_le->in(1)->bottom_type()->singleton() && outer_le->in(1)->bottom_type()->is_int()->get_con() == 0; 2457 if (has_skeleton) { 2458 assert(expect_skeleton == 1 || expect_skeleton == -1, "unexpected skeleton node"); 2459 assert(outer->outcnt() == 2, "only control nodes"); 2460 } else { 2461 assert(expect_skeleton == 0 || expect_skeleton == -1, "no skeleton node?"); 2462 uint phis = 0; 2463 uint be_loads = 0; 2464 Node* be = inner->in(LoopNode::LoopBackControl); 2465 for (DUIterator_Fast imax, i = inner->fast_outs(imax); i < imax; i++) { 2466 Node* u = inner->fast_out(i); 2467 if (u->is_Phi()) { 2468 phis++; 2469 for (DUIterator_Fast jmax, j = be->fast_outs(jmax); j < jmax; j++) { 2470 Node* n = be->fast_out(j); 2471 if (n->is_Load()) { 2472 assert(n->in(0) == be || n->find_prec_edge(be) > 0, "should be on the backedge"); 2473 do { 2474 n = n->raw_out(0); 2475 } while (!n->is_Phi()); 2476 if (n == u) { 2477 be_loads++; 2478 break; 2479 } 2480 } 2481 } 2482 } 2483 } 2484 assert(be_loads <= phis, "wrong number phis that depends on a pinned load"); 2485 for (DUIterator_Fast imax, i = outer->fast_outs(imax); i < imax; i++) { 2486 Node* u = outer->fast_out(i); 2487 assert(u == outer || u == inner || u->is_Phi(), "nothing between inner and outer loop"); 2488 } 2489 uint stores = 0; 2490 for (DUIterator_Fast imax, i = inner_out->fast_outs(imax); i < imax; i++) { 2491 Node* u = inner_out->fast_out(i); 2492 if (u->is_Store()) { 2493 stores++; 2494 } 2495 } 2496 // Late optimization of loads on backedge can cause Phi of outer loop to be eliminated but Phi of inner loop is 2497 // not guaranteed to be optimized out. 2498 assert(outer->outcnt() >= phis + 2 - be_loads && outer->outcnt() <= phis + 2 + stores + 1, "only phis"); 2499 } 2500 assert(sfpt->outcnt() == 1, "no data node"); 2501 assert(outer_tail->outcnt() == 1 || !has_skeleton, "no data node"); 2502 } 2503 } 2504 #endif 2505 2506 //============================================================================= 2507 //------------------------------Ideal------------------------------------------ 2508 // Return a node which is more "ideal" than the current node. 2509 // Attempt to convert into a counted-loop. 2510 Node *CountedLoopNode::Ideal(PhaseGVN *phase, bool can_reshape) { 2511 return RegionNode::Ideal(phase, can_reshape); 2512 } 2513 2514 //------------------------------dump_spec-------------------------------------- 2515 // Dump special per-node info 2516 #ifndef PRODUCT 2517 void CountedLoopNode::dump_spec(outputStream *st) const { 2518 LoopNode::dump_spec(st); 2519 if (stride_is_con()) { 2520 st->print("stride: %d ",stride_con()); 2521 } 2522 if (is_pre_loop ()) st->print("pre of N%d" , _main_idx); 2523 if (is_main_loop()) st->print("main of N%d", _idx); 2524 if (is_post_loop()) st->print("post of N%d", _main_idx); 2525 if (is_strip_mined()) st->print(" strip mined"); 2526 } 2527 #endif 2528 2529 //============================================================================= 2530 jlong BaseCountedLoopEndNode::stride_con() const { 2531 return stride()->bottom_type()->is_integer(bt())->get_con_as_long(bt()); 2532 } 2533 2534 2535 BaseCountedLoopEndNode* BaseCountedLoopEndNode::make(Node* control, Node* test, float prob, float cnt, BasicType bt) { 2536 if (bt == T_INT) { 2537 return new CountedLoopEndNode(control, test, prob, cnt); 2538 } 2539 assert(bt == T_LONG, "unsupported"); 2540 return new LongCountedLoopEndNode(control, test, prob, cnt); 2541 } 2542 2543 //============================================================================= 2544 //------------------------------Value----------------------------------------- 2545 const Type* LoopLimitNode::Value(PhaseGVN* phase) const { 2546 const Type* init_t = phase->type(in(Init)); 2547 const Type* limit_t = phase->type(in(Limit)); 2548 const Type* stride_t = phase->type(in(Stride)); 2549 // Either input is TOP ==> the result is TOP 2550 if (init_t == Type::TOP) return Type::TOP; 2551 if (limit_t == Type::TOP) return Type::TOP; 2552 if (stride_t == Type::TOP) return Type::TOP; 2553 2554 int stride_con = stride_t->is_int()->get_con(); 2555 if (stride_con == 1) 2556 return bottom_type(); // Identity 2557 2558 if (init_t->is_int()->is_con() && limit_t->is_int()->is_con()) { 2559 // Use jlongs to avoid integer overflow. 2560 jlong init_con = init_t->is_int()->get_con(); 2561 jlong limit_con = limit_t->is_int()->get_con(); 2562 int stride_m = stride_con - (stride_con > 0 ? 1 : -1); 2563 jlong trip_count = (limit_con - init_con + stride_m)/stride_con; 2564 jlong final_con = init_con + stride_con*trip_count; 2565 int final_int = (int)final_con; 2566 // The final value should be in integer range since the loop 2567 // is counted and the limit was checked for overflow. 2568 // Assert checks for overflow only if all input nodes are ConINodes, as during CCP 2569 // there might be a temporary overflow from PhiNodes see JDK-8309266 2570 assert((in(Init)->is_ConI() && in(Limit)->is_ConI() && in(Stride)->is_ConI()) ? final_con == (jlong)final_int : true, "final value should be integer"); 2571 if (final_con == (jlong)final_int) { 2572 return TypeInt::make(final_int); 2573 } else { 2574 return bottom_type(); 2575 } 2576 } 2577 2578 return bottom_type(); // TypeInt::INT 2579 } 2580 2581 //------------------------------Ideal------------------------------------------ 2582 // Return a node which is more "ideal" than the current node. 2583 Node *LoopLimitNode::Ideal(PhaseGVN *phase, bool can_reshape) { 2584 if (phase->type(in(Init)) == Type::TOP || 2585 phase->type(in(Limit)) == Type::TOP || 2586 phase->type(in(Stride)) == Type::TOP) 2587 return nullptr; // Dead 2588 2589 int stride_con = phase->type(in(Stride))->is_int()->get_con(); 2590 if (stride_con == 1) 2591 return nullptr; // Identity 2592 2593 if (in(Init)->is_Con() && in(Limit)->is_Con()) 2594 return nullptr; // Value 2595 2596 // Delay following optimizations until all loop optimizations 2597 // done to keep Ideal graph simple. 2598 if (!can_reshape || !phase->C->post_loop_opts_phase()) { 2599 return nullptr; 2600 } 2601 2602 const TypeInt* init_t = phase->type(in(Init) )->is_int(); 2603 const TypeInt* limit_t = phase->type(in(Limit))->is_int(); 2604 jlong stride_p; 2605 jlong lim, ini; 2606 julong max; 2607 if (stride_con > 0) { 2608 stride_p = stride_con; 2609 lim = limit_t->_hi; 2610 ini = init_t->_lo; 2611 max = (julong)max_jint; 2612 } else { 2613 stride_p = -(jlong)stride_con; 2614 lim = init_t->_hi; 2615 ini = limit_t->_lo; 2616 max = (julong)(juint)min_jint; // double cast to get 0x0000000080000000, not 0xffffffff80000000 2617 } 2618 julong range = lim - ini + stride_p; 2619 if (range <= max) { 2620 // Convert to integer expression if it is not overflow. 2621 Node* stride_m = phase->intcon(stride_con - (stride_con > 0 ? 1 : -1)); 2622 Node *range = phase->transform(new SubINode(in(Limit), in(Init))); 2623 Node *bias = phase->transform(new AddINode(range, stride_m)); 2624 Node *trip = phase->transform(new DivINode(nullptr, bias, in(Stride))); 2625 Node *span = phase->transform(new MulINode(trip, in(Stride))); 2626 return new AddINode(span, in(Init)); // exact limit 2627 } 2628 2629 if (is_power_of_2(stride_p) || // divisor is 2^n 2630 !Matcher::has_match_rule(Op_LoopLimit)) { // or no specialized Mach node? 2631 // Convert to long expression to avoid integer overflow 2632 // and let igvn optimizer convert this division. 2633 // 2634 Node* init = phase->transform( new ConvI2LNode(in(Init))); 2635 Node* limit = phase->transform( new ConvI2LNode(in(Limit))); 2636 Node* stride = phase->longcon(stride_con); 2637 Node* stride_m = phase->longcon(stride_con - (stride_con > 0 ? 1 : -1)); 2638 2639 Node *range = phase->transform(new SubLNode(limit, init)); 2640 Node *bias = phase->transform(new AddLNode(range, stride_m)); 2641 Node *span; 2642 if (stride_con > 0 && is_power_of_2(stride_p)) { 2643 // bias >= 0 if stride >0, so if stride is 2^n we can use &(-stride) 2644 // and avoid generating rounding for division. Zero trip guard should 2645 // guarantee that init < limit but sometimes the guard is missing and 2646 // we can get situation when init > limit. Note, for the empty loop 2647 // optimization zero trip guard is generated explicitly which leaves 2648 // only RCE predicate where exact limit is used and the predicate 2649 // will simply fail forcing recompilation. 2650 Node* neg_stride = phase->longcon(-stride_con); 2651 span = phase->transform(new AndLNode(bias, neg_stride)); 2652 } else { 2653 Node *trip = phase->transform(new DivLNode(nullptr, bias, stride)); 2654 span = phase->transform(new MulLNode(trip, stride)); 2655 } 2656 // Convert back to int 2657 Node *span_int = phase->transform(new ConvL2INode(span)); 2658 return new AddINode(span_int, in(Init)); // exact limit 2659 } 2660 2661 return nullptr; // No progress 2662 } 2663 2664 //------------------------------Identity--------------------------------------- 2665 // If stride == 1 return limit node. 2666 Node* LoopLimitNode::Identity(PhaseGVN* phase) { 2667 int stride_con = phase->type(in(Stride))->is_int()->get_con(); 2668 if (stride_con == 1 || stride_con == -1) 2669 return in(Limit); 2670 return this; 2671 } 2672 2673 //============================================================================= 2674 //----------------------match_incr_with_optional_truncation-------------------- 2675 // Match increment with optional truncation: 2676 // CHAR: (i+1)&0x7fff, BYTE: ((i+1)<<8)>>8, or SHORT: ((i+1)<<16)>>16 2677 // Return null for failure. Success returns the increment node. 2678 Node* CountedLoopNode::match_incr_with_optional_truncation(Node* expr, Node** trunc1, Node** trunc2, 2679 const TypeInteger** trunc_type, 2680 BasicType bt) { 2681 // Quick cutouts: 2682 if (expr == nullptr || expr->req() != 3) return nullptr; 2683 2684 Node *t1 = nullptr; 2685 Node *t2 = nullptr; 2686 Node* n1 = expr; 2687 int n1op = n1->Opcode(); 2688 const TypeInteger* trunc_t = TypeInteger::bottom(bt); 2689 2690 if (bt == T_INT) { 2691 // Try to strip (n1 & M) or (n1 << N >> N) from n1. 2692 if (n1op == Op_AndI && 2693 n1->in(2)->is_Con() && 2694 n1->in(2)->bottom_type()->is_int()->get_con() == 0x7fff) { 2695 // %%% This check should match any mask of 2**K-1. 2696 t1 = n1; 2697 n1 = t1->in(1); 2698 n1op = n1->Opcode(); 2699 trunc_t = TypeInt::CHAR; 2700 } else if (n1op == Op_RShiftI && 2701 n1->in(1) != nullptr && 2702 n1->in(1)->Opcode() == Op_LShiftI && 2703 n1->in(2) == n1->in(1)->in(2) && 2704 n1->in(2)->is_Con()) { 2705 jint shift = n1->in(2)->bottom_type()->is_int()->get_con(); 2706 // %%% This check should match any shift in [1..31]. 2707 if (shift == 16 || shift == 8) { 2708 t1 = n1; 2709 t2 = t1->in(1); 2710 n1 = t2->in(1); 2711 n1op = n1->Opcode(); 2712 if (shift == 16) { 2713 trunc_t = TypeInt::SHORT; 2714 } else if (shift == 8) { 2715 trunc_t = TypeInt::BYTE; 2716 } 2717 } 2718 } 2719 } 2720 2721 // If (maybe after stripping) it is an AddI, we won: 2722 if (n1op == Op_Add(bt)) { 2723 *trunc1 = t1; 2724 *trunc2 = t2; 2725 *trunc_type = trunc_t; 2726 return n1; 2727 } 2728 2729 // failed 2730 return nullptr; 2731 } 2732 2733 LoopNode* CountedLoopNode::skip_strip_mined(int expect_skeleton) { 2734 if (is_strip_mined() && in(EntryControl) != nullptr && in(EntryControl)->is_OuterStripMinedLoop()) { 2735 verify_strip_mined(expect_skeleton); 2736 return in(EntryControl)->as_Loop(); 2737 } 2738 return this; 2739 } 2740 2741 OuterStripMinedLoopNode* CountedLoopNode::outer_loop() const { 2742 assert(is_strip_mined(), "not a strip mined loop"); 2743 Node* c = in(EntryControl); 2744 if (c == nullptr || c->is_top() || !c->is_OuterStripMinedLoop()) { 2745 return nullptr; 2746 } 2747 return c->as_OuterStripMinedLoop(); 2748 } 2749 2750 IfTrueNode* OuterStripMinedLoopNode::outer_loop_tail() const { 2751 Node* c = in(LoopBackControl); 2752 if (c == nullptr || c->is_top()) { 2753 return nullptr; 2754 } 2755 return c->as_IfTrue(); 2756 } 2757 2758 IfTrueNode* CountedLoopNode::outer_loop_tail() const { 2759 LoopNode* l = outer_loop(); 2760 if (l == nullptr) { 2761 return nullptr; 2762 } 2763 return l->outer_loop_tail(); 2764 } 2765 2766 OuterStripMinedLoopEndNode* OuterStripMinedLoopNode::outer_loop_end() const { 2767 IfTrueNode* proj = outer_loop_tail(); 2768 if (proj == nullptr) { 2769 return nullptr; 2770 } 2771 Node* c = proj->in(0); 2772 if (c == nullptr || c->is_top() || c->outcnt() != 2) { 2773 return nullptr; 2774 } 2775 return c->as_OuterStripMinedLoopEnd(); 2776 } 2777 2778 OuterStripMinedLoopEndNode* CountedLoopNode::outer_loop_end() const { 2779 LoopNode* l = outer_loop(); 2780 if (l == nullptr) { 2781 return nullptr; 2782 } 2783 return l->outer_loop_end(); 2784 } 2785 2786 IfFalseNode* OuterStripMinedLoopNode::outer_loop_exit() const { 2787 IfNode* le = outer_loop_end(); 2788 if (le == nullptr) { 2789 return nullptr; 2790 } 2791 Node* c = le->proj_out_or_null(false); 2792 if (c == nullptr) { 2793 return nullptr; 2794 } 2795 return c->as_IfFalse(); 2796 } 2797 2798 IfFalseNode* CountedLoopNode::outer_loop_exit() const { 2799 LoopNode* l = outer_loop(); 2800 if (l == nullptr) { 2801 return nullptr; 2802 } 2803 return l->outer_loop_exit(); 2804 } 2805 2806 SafePointNode* OuterStripMinedLoopNode::outer_safepoint() const { 2807 IfNode* le = outer_loop_end(); 2808 if (le == nullptr) { 2809 return nullptr; 2810 } 2811 Node* c = le->in(0); 2812 if (c == nullptr || c->is_top()) { 2813 return nullptr; 2814 } 2815 assert(c->Opcode() == Op_SafePoint, "broken outer loop"); 2816 return c->as_SafePoint(); 2817 } 2818 2819 SafePointNode* CountedLoopNode::outer_safepoint() const { 2820 LoopNode* l = outer_loop(); 2821 if (l == nullptr) { 2822 return nullptr; 2823 } 2824 return l->outer_safepoint(); 2825 } 2826 2827 Node* CountedLoopNode::skip_assertion_predicates_with_halt() { 2828 Node* ctrl = in(LoopNode::EntryControl); 2829 if (ctrl == nullptr) { 2830 // Dying loop. 2831 return nullptr; 2832 } 2833 if (is_main_loop()) { 2834 ctrl = skip_strip_mined()->in(LoopNode::EntryControl); 2835 } 2836 if (is_main_loop() || is_post_loop()) { 2837 AssertionPredicates assertion_predicates(ctrl); 2838 return assertion_predicates.entry(); 2839 } 2840 return ctrl; 2841 } 2842 2843 2844 int CountedLoopNode::stride_con() const { 2845 CountedLoopEndNode* cle = loopexit_or_null(); 2846 return cle != nullptr ? cle->stride_con() : 0; 2847 } 2848 2849 BaseCountedLoopNode* BaseCountedLoopNode::make(Node* entry, Node* backedge, BasicType bt) { 2850 if (bt == T_INT) { 2851 return new CountedLoopNode(entry, backedge); 2852 } 2853 assert(bt == T_LONG, "unsupported"); 2854 return new LongCountedLoopNode(entry, backedge); 2855 } 2856 2857 void OuterStripMinedLoopNode::fix_sunk_stores(CountedLoopEndNode* inner_cle, LoopNode* inner_cl, PhaseIterGVN* igvn, 2858 PhaseIdealLoop* iloop) { 2859 Node* cle_out = inner_cle->proj_out(false); 2860 Node* cle_tail = inner_cle->proj_out(true); 2861 if (cle_out->outcnt() > 1) { 2862 // Look for chains of stores that were sunk 2863 // out of the inner loop and are in the outer loop 2864 for (DUIterator_Fast imax, i = cle_out->fast_outs(imax); i < imax; i++) { 2865 Node* u = cle_out->fast_out(i); 2866 if (u->is_Store()) { 2867 int alias_idx = igvn->C->get_alias_index(u->adr_type()); 2868 Node* first = u; 2869 for (;;) { 2870 Node* next = first->in(MemNode::Memory); 2871 if (!next->is_Store() || next->in(0) != cle_out) { 2872 break; 2873 } 2874 assert(igvn->C->get_alias_index(next->adr_type()) == alias_idx, ""); 2875 first = next; 2876 } 2877 Node* last = u; 2878 for (;;) { 2879 Node* next = nullptr; 2880 for (DUIterator_Fast jmax, j = last->fast_outs(jmax); j < jmax; j++) { 2881 Node* uu = last->fast_out(j); 2882 if (uu->is_Store() && uu->in(0) == cle_out) { 2883 assert(next == nullptr, "only one in the outer loop"); 2884 next = uu; 2885 assert(igvn->C->get_alias_index(next->adr_type()) == alias_idx, ""); 2886 } 2887 } 2888 if (next == nullptr) { 2889 break; 2890 } 2891 last = next; 2892 } 2893 Node* phi = nullptr; 2894 for (DUIterator_Fast jmax, j = inner_cl->fast_outs(jmax); j < jmax; j++) { 2895 Node* uu = inner_cl->fast_out(j); 2896 if (uu->is_Phi()) { 2897 Node* be = uu->in(LoopNode::LoopBackControl); 2898 if (be->is_Store() && be->in(0) == inner_cl->in(LoopNode::LoopBackControl)) { 2899 assert(igvn->C->get_alias_index(uu->adr_type()) != alias_idx && igvn->C->get_alias_index(uu->adr_type()) != Compile::AliasIdxBot, "unexpected store"); 2900 } 2901 if (be == last || be == first->in(MemNode::Memory)) { 2902 assert(igvn->C->get_alias_index(uu->adr_type()) == alias_idx || igvn->C->get_alias_index(uu->adr_type()) == Compile::AliasIdxBot, "unexpected alias"); 2903 assert(phi == nullptr, "only one phi"); 2904 phi = uu; 2905 } 2906 } 2907 } 2908 #ifdef ASSERT 2909 for (DUIterator_Fast jmax, j = inner_cl->fast_outs(jmax); j < jmax; j++) { 2910 Node* uu = inner_cl->fast_out(j); 2911 if (uu->is_memory_phi()) { 2912 if (uu->adr_type() == igvn->C->get_adr_type(igvn->C->get_alias_index(u->adr_type()))) { 2913 assert(phi == uu, "what's that phi?"); 2914 } else if (uu->adr_type() == TypePtr::BOTTOM) { 2915 Node* n = uu->in(LoopNode::LoopBackControl); 2916 uint limit = igvn->C->live_nodes(); 2917 uint i = 0; 2918 while (n != uu) { 2919 i++; 2920 assert(i < limit, "infinite loop"); 2921 if (n->is_Proj()) { 2922 n = n->in(0); 2923 } else if (n->is_SafePoint() || n->is_MemBar()) { 2924 n = n->in(TypeFunc::Memory); 2925 } else if (n->is_Phi()) { 2926 n = n->in(1); 2927 } else if (n->is_MergeMem()) { 2928 n = n->as_MergeMem()->memory_at(igvn->C->get_alias_index(u->adr_type())); 2929 } else if (n->is_Store() || n->is_LoadStore() || n->is_ClearArray()) { 2930 n = n->in(MemNode::Memory); 2931 } else { 2932 n->dump(); 2933 ShouldNotReachHere(); 2934 } 2935 } 2936 } 2937 } 2938 } 2939 #endif 2940 if (phi == nullptr) { 2941 // If an entire chains was sunk, the 2942 // inner loop has no phi for that memory 2943 // slice, create one for the outer loop 2944 phi = PhiNode::make(inner_cl, first->in(MemNode::Memory), Type::MEMORY, 2945 igvn->C->get_adr_type(igvn->C->get_alias_index(u->adr_type()))); 2946 phi->set_req(LoopNode::LoopBackControl, last); 2947 phi = register_new_node(phi, inner_cl, igvn, iloop); 2948 igvn->replace_input_of(first, MemNode::Memory, phi); 2949 } else { 2950 // Or fix the outer loop fix to include 2951 // that chain of stores. 2952 Node* be = phi->in(LoopNode::LoopBackControl); 2953 assert(!(be->is_Store() && be->in(0) == inner_cl->in(LoopNode::LoopBackControl)), "store on the backedge + sunk stores: unsupported"); 2954 if (be == first->in(MemNode::Memory)) { 2955 if (be == phi->in(LoopNode::LoopBackControl)) { 2956 igvn->replace_input_of(phi, LoopNode::LoopBackControl, last); 2957 } else { 2958 igvn->replace_input_of(be, MemNode::Memory, last); 2959 } 2960 } else { 2961 #ifdef ASSERT 2962 if (be == phi->in(LoopNode::LoopBackControl)) { 2963 assert(phi->in(LoopNode::LoopBackControl) == last, ""); 2964 } else { 2965 assert(be->in(MemNode::Memory) == last, ""); 2966 } 2967 #endif 2968 } 2969 } 2970 } 2971 } 2972 } 2973 } 2974 2975 void OuterStripMinedLoopNode::adjust_strip_mined_loop(PhaseIterGVN* igvn) { 2976 // Look for the outer & inner strip mined loop, reduce number of 2977 // iterations of the inner loop, set exit condition of outer loop, 2978 // construct required phi nodes for outer loop. 2979 CountedLoopNode* inner_cl = unique_ctrl_out()->as_CountedLoop(); 2980 assert(inner_cl->is_strip_mined(), "inner loop should be strip mined"); 2981 if (LoopStripMiningIter == 0) { 2982 remove_outer_loop_and_safepoint(igvn); 2983 return; 2984 } 2985 if (LoopStripMiningIter == 1) { 2986 transform_to_counted_loop(igvn, nullptr); 2987 return; 2988 } 2989 Node* inner_iv_phi = inner_cl->phi(); 2990 if (inner_iv_phi == nullptr) { 2991 IfNode* outer_le = outer_loop_end(); 2992 Node* iff = igvn->transform(new IfNode(outer_le->in(0), outer_le->in(1), outer_le->_prob, outer_le->_fcnt)); 2993 igvn->replace_node(outer_le, iff); 2994 inner_cl->clear_strip_mined(); 2995 return; 2996 } 2997 CountedLoopEndNode* inner_cle = inner_cl->loopexit(); 2998 2999 int stride = inner_cl->stride_con(); 3000 // For a min int stride, LoopStripMiningIter * stride overflows the int range for all values of LoopStripMiningIter 3001 // except 0 or 1. Those values are handled early on in this method and causes the method to return. So for a min int 3002 // stride, the method is guaranteed to return at the next check below. 3003 jlong scaled_iters_long = ((jlong)LoopStripMiningIter) * ABS((jlong)stride); 3004 int scaled_iters = (int)scaled_iters_long; 3005 if ((jlong)scaled_iters != scaled_iters_long) { 3006 // Remove outer loop and safepoint (too few iterations) 3007 remove_outer_loop_and_safepoint(igvn); 3008 return; 3009 } 3010 jlong short_scaled_iters = LoopStripMiningIterShortLoop * ABS(stride); 3011 const TypeInt* inner_iv_t = igvn->type(inner_iv_phi)->is_int(); 3012 jlong iter_estimate = (jlong)inner_iv_t->_hi - (jlong)inner_iv_t->_lo; 3013 assert(iter_estimate > 0, "broken"); 3014 if (iter_estimate <= short_scaled_iters) { 3015 // Remove outer loop and safepoint: loop executes less than LoopStripMiningIterShortLoop 3016 remove_outer_loop_and_safepoint(igvn); 3017 return; 3018 } 3019 if (iter_estimate <= scaled_iters_long) { 3020 // We would only go through one iteration of 3021 // the outer loop: drop the outer loop but 3022 // keep the safepoint so we don't run for 3023 // too long without a safepoint 3024 IfNode* outer_le = outer_loop_end(); 3025 Node* iff = igvn->transform(new IfNode(outer_le->in(0), outer_le->in(1), outer_le->_prob, outer_le->_fcnt)); 3026 igvn->replace_node(outer_le, iff); 3027 inner_cl->clear_strip_mined(); 3028 return; 3029 } 3030 3031 Node* cle_tail = inner_cle->proj_out(true); 3032 ResourceMark rm; 3033 Node_List old_new; 3034 if (cle_tail->outcnt() > 1) { 3035 // Look for nodes on backedge of inner loop and clone them 3036 Unique_Node_List backedge_nodes; 3037 for (DUIterator_Fast imax, i = cle_tail->fast_outs(imax); i < imax; i++) { 3038 Node* u = cle_tail->fast_out(i); 3039 if (u != inner_cl) { 3040 assert(!u->is_CFG(), "control flow on the backedge?"); 3041 backedge_nodes.push(u); 3042 } 3043 } 3044 uint last = igvn->C->unique(); 3045 for (uint next = 0; next < backedge_nodes.size(); next++) { 3046 Node* n = backedge_nodes.at(next); 3047 old_new.map(n->_idx, n->clone()); 3048 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) { 3049 Node* u = n->fast_out(i); 3050 assert(!u->is_CFG(), "broken"); 3051 if (u->_idx >= last) { 3052 continue; 3053 } 3054 if (!u->is_Phi()) { 3055 backedge_nodes.push(u); 3056 } else { 3057 assert(u->in(0) == inner_cl, "strange phi on the backedge"); 3058 } 3059 } 3060 } 3061 // Put the clones on the outer loop backedge 3062 Node* le_tail = outer_loop_tail(); 3063 for (uint next = 0; next < backedge_nodes.size(); next++) { 3064 Node *n = old_new[backedge_nodes.at(next)->_idx]; 3065 for (uint i = 1; i < n->req(); i++) { 3066 if (n->in(i) != nullptr && old_new[n->in(i)->_idx] != nullptr) { 3067 n->set_req(i, old_new[n->in(i)->_idx]); 3068 } 3069 } 3070 if (n->in(0) != nullptr && n->in(0) == cle_tail) { 3071 n->set_req(0, le_tail); 3072 } 3073 igvn->register_new_node_with_optimizer(n); 3074 } 3075 } 3076 3077 Node* iv_phi = nullptr; 3078 // Make a clone of each phi in the inner loop 3079 // for the outer loop 3080 for (uint i = 0; i < inner_cl->outcnt(); i++) { 3081 Node* u = inner_cl->raw_out(i); 3082 if (u->is_Phi()) { 3083 assert(u->in(0) == inner_cl, "inconsistent"); 3084 Node* phi = u->clone(); 3085 phi->set_req(0, this); 3086 Node* be = old_new[phi->in(LoopNode::LoopBackControl)->_idx]; 3087 if (be != nullptr) { 3088 phi->set_req(LoopNode::LoopBackControl, be); 3089 } 3090 phi = igvn->transform(phi); 3091 igvn->replace_input_of(u, LoopNode::EntryControl, phi); 3092 if (u == inner_iv_phi) { 3093 iv_phi = phi; 3094 } 3095 } 3096 } 3097 3098 if (iv_phi != nullptr) { 3099 // Now adjust the inner loop's exit condition 3100 Node* limit = inner_cl->limit(); 3101 // If limit < init for stride > 0 (or limit > init for stride < 0), 3102 // the loop body is run only once. Given limit - init (init - limit resp.) 3103 // would be negative, the unsigned comparison below would cause 3104 // the loop body to be run for LoopStripMiningIter. 3105 Node* max = nullptr; 3106 if (stride > 0) { 3107 max = MaxNode::max_diff_with_zero(limit, iv_phi, TypeInt::INT, *igvn); 3108 } else { 3109 max = MaxNode::max_diff_with_zero(iv_phi, limit, TypeInt::INT, *igvn); 3110 } 3111 // sub is positive and can be larger than the max signed int 3112 // value. Use an unsigned min. 3113 Node* const_iters = igvn->intcon(scaled_iters); 3114 Node* min = MaxNode::unsigned_min(max, const_iters, TypeInt::make(0, scaled_iters, Type::WidenMin), *igvn); 3115 // min is the number of iterations for the next inner loop execution: 3116 // unsigned_min(max(limit - iv_phi, 0), scaled_iters) if stride > 0 3117 // unsigned_min(max(iv_phi - limit, 0), scaled_iters) if stride < 0 3118 3119 Node* new_limit = nullptr; 3120 if (stride > 0) { 3121 new_limit = igvn->transform(new AddINode(min, iv_phi)); 3122 } else { 3123 new_limit = igvn->transform(new SubINode(iv_phi, min)); 3124 } 3125 Node* inner_cmp = inner_cle->cmp_node(); 3126 Node* inner_bol = inner_cle->in(CountedLoopEndNode::TestValue); 3127 Node* outer_bol = inner_bol; 3128 // cmp node for inner loop may be shared 3129 inner_cmp = inner_cmp->clone(); 3130 inner_cmp->set_req(2, new_limit); 3131 inner_bol = inner_bol->clone(); 3132 inner_bol->set_req(1, igvn->transform(inner_cmp)); 3133 igvn->replace_input_of(inner_cle, CountedLoopEndNode::TestValue, igvn->transform(inner_bol)); 3134 // Set the outer loop's exit condition too 3135 igvn->replace_input_of(outer_loop_end(), 1, outer_bol); 3136 } else { 3137 assert(false, "should be able to adjust outer loop"); 3138 IfNode* outer_le = outer_loop_end(); 3139 Node* iff = igvn->transform(new IfNode(outer_le->in(0), outer_le->in(1), outer_le->_prob, outer_le->_fcnt)); 3140 igvn->replace_node(outer_le, iff); 3141 inner_cl->clear_strip_mined(); 3142 } 3143 } 3144 3145 void OuterStripMinedLoopNode::transform_to_counted_loop(PhaseIterGVN* igvn, PhaseIdealLoop* iloop) { 3146 CountedLoopNode* inner_cl = unique_ctrl_out()->as_CountedLoop(); 3147 CountedLoopEndNode* cle = inner_cl->loopexit(); 3148 Node* inner_test = cle->in(1); 3149 IfNode* outer_le = outer_loop_end(); 3150 CountedLoopEndNode* inner_cle = inner_cl->loopexit(); 3151 Node* safepoint = outer_safepoint(); 3152 3153 fix_sunk_stores(inner_cle, inner_cl, igvn, iloop); 3154 3155 // make counted loop exit test always fail 3156 ConINode* zero = igvn->intcon(0); 3157 if (iloop != nullptr) { 3158 iloop->set_ctrl(zero, igvn->C->root()); 3159 } 3160 igvn->replace_input_of(cle, 1, zero); 3161 // replace outer loop end with CountedLoopEndNode with formers' CLE's exit test 3162 Node* new_end = new CountedLoopEndNode(outer_le->in(0), inner_test, cle->_prob, cle->_fcnt); 3163 register_control(new_end, inner_cl, outer_le->in(0), igvn, iloop); 3164 if (iloop == nullptr) { 3165 igvn->replace_node(outer_le, new_end); 3166 } else { 3167 iloop->lazy_replace(outer_le, new_end); 3168 } 3169 // the backedge of the inner loop must be rewired to the new loop end 3170 Node* backedge = cle->proj_out(true); 3171 igvn->replace_input_of(backedge, 0, new_end); 3172 if (iloop != nullptr) { 3173 iloop->set_idom(backedge, new_end, iloop->dom_depth(new_end) + 1); 3174 } 3175 // make the outer loop go away 3176 igvn->replace_input_of(in(LoopBackControl), 0, igvn->C->top()); 3177 igvn->replace_input_of(this, LoopBackControl, igvn->C->top()); 3178 inner_cl->clear_strip_mined(); 3179 if (iloop != nullptr) { 3180 Unique_Node_List wq; 3181 wq.push(safepoint); 3182 3183 IdealLoopTree* outer_loop_ilt = iloop->get_loop(this); 3184 IdealLoopTree* loop = iloop->get_loop(inner_cl); 3185 3186 for (uint i = 0; i < wq.size(); i++) { 3187 Node* n = wq.at(i); 3188 for (uint j = 0; j < n->req(); ++j) { 3189 Node* in = n->in(j); 3190 if (in == nullptr || in->is_CFG()) { 3191 continue; 3192 } 3193 if (iloop->get_loop(iloop->get_ctrl(in)) != outer_loop_ilt) { 3194 continue; 3195 } 3196 assert(!loop->_body.contains(in), ""); 3197 loop->_body.push(in); 3198 wq.push(in); 3199 } 3200 } 3201 iloop->set_loop(safepoint, loop); 3202 loop->_body.push(safepoint); 3203 iloop->set_loop(safepoint->in(0), loop); 3204 loop->_body.push(safepoint->in(0)); 3205 outer_loop_ilt->_tail = igvn->C->top(); 3206 } 3207 } 3208 3209 void OuterStripMinedLoopNode::remove_outer_loop_and_safepoint(PhaseIterGVN* igvn) const { 3210 CountedLoopNode* inner_cl = unique_ctrl_out()->as_CountedLoop(); 3211 Node* outer_sfpt = outer_safepoint(); 3212 Node* outer_out = outer_loop_exit(); 3213 igvn->replace_node(outer_out, outer_sfpt->in(0)); 3214 igvn->replace_input_of(outer_sfpt, 0, igvn->C->top()); 3215 inner_cl->clear_strip_mined(); 3216 } 3217 3218 Node* OuterStripMinedLoopNode::register_new_node(Node* node, LoopNode* ctrl, PhaseIterGVN* igvn, PhaseIdealLoop* iloop) { 3219 if (iloop == nullptr) { 3220 return igvn->transform(node); 3221 } 3222 iloop->register_new_node(node, ctrl); 3223 return node; 3224 } 3225 3226 Node* OuterStripMinedLoopNode::register_control(Node* node, Node* loop, Node* idom, PhaseIterGVN* igvn, 3227 PhaseIdealLoop* iloop) { 3228 if (iloop == nullptr) { 3229 return igvn->transform(node); 3230 } 3231 iloop->register_control(node, iloop->get_loop(loop), idom); 3232 return node; 3233 } 3234 3235 const Type* OuterStripMinedLoopEndNode::Value(PhaseGVN* phase) const { 3236 if (!in(0)) return Type::TOP; 3237 if (phase->type(in(0)) == Type::TOP) 3238 return Type::TOP; 3239 3240 // Until expansion, the loop end condition is not set so this should not constant fold. 3241 if (is_expanded(phase)) { 3242 return IfNode::Value(phase); 3243 } 3244 3245 return TypeTuple::IFBOTH; 3246 } 3247 3248 bool OuterStripMinedLoopEndNode::is_expanded(PhaseGVN *phase) const { 3249 // The outer strip mined loop head only has Phi uses after expansion 3250 if (phase->is_IterGVN()) { 3251 Node* backedge = proj_out_or_null(true); 3252 if (backedge != nullptr) { 3253 Node* head = backedge->unique_ctrl_out_or_null(); 3254 if (head != nullptr && head->is_OuterStripMinedLoop()) { 3255 if (head->find_out_with(Op_Phi) != nullptr) { 3256 return true; 3257 } 3258 } 3259 } 3260 } 3261 return false; 3262 } 3263 3264 Node *OuterStripMinedLoopEndNode::Ideal(PhaseGVN *phase, bool can_reshape) { 3265 if (remove_dead_region(phase, can_reshape)) return this; 3266 3267 return nullptr; 3268 } 3269 3270 //------------------------------filtered_type-------------------------------- 3271 // Return a type based on condition control flow 3272 // A successful return will be a type that is restricted due 3273 // to a series of dominating if-tests, such as: 3274 // if (i < 10) { 3275 // if (i > 0) { 3276 // here: "i" type is [1..10) 3277 // } 3278 // } 3279 // or a control flow merge 3280 // if (i < 10) { 3281 // do { 3282 // phi( , ) -- at top of loop type is [min_int..10) 3283 // i = ? 3284 // } while ( i < 10) 3285 // 3286 const TypeInt* PhaseIdealLoop::filtered_type( Node *n, Node* n_ctrl) { 3287 assert(n && n->bottom_type()->is_int(), "must be int"); 3288 const TypeInt* filtered_t = nullptr; 3289 if (!n->is_Phi()) { 3290 assert(n_ctrl != nullptr || n_ctrl == C->top(), "valid control"); 3291 filtered_t = filtered_type_from_dominators(n, n_ctrl); 3292 3293 } else { 3294 Node* phi = n->as_Phi(); 3295 Node* region = phi->in(0); 3296 assert(n_ctrl == nullptr || n_ctrl == region, "ctrl parameter must be region"); 3297 if (region && region != C->top()) { 3298 for (uint i = 1; i < phi->req(); i++) { 3299 Node* val = phi->in(i); 3300 Node* use_c = region->in(i); 3301 const TypeInt* val_t = filtered_type_from_dominators(val, use_c); 3302 if (val_t != nullptr) { 3303 if (filtered_t == nullptr) { 3304 filtered_t = val_t; 3305 } else { 3306 filtered_t = filtered_t->meet(val_t)->is_int(); 3307 } 3308 } 3309 } 3310 } 3311 } 3312 const TypeInt* n_t = _igvn.type(n)->is_int(); 3313 if (filtered_t != nullptr) { 3314 n_t = n_t->join(filtered_t)->is_int(); 3315 } 3316 return n_t; 3317 } 3318 3319 3320 //------------------------------filtered_type_from_dominators-------------------------------- 3321 // Return a possibly more restrictive type for val based on condition control flow of dominators 3322 const TypeInt* PhaseIdealLoop::filtered_type_from_dominators( Node* val, Node *use_ctrl) { 3323 if (val->is_Con()) { 3324 return val->bottom_type()->is_int(); 3325 } 3326 uint if_limit = 10; // Max number of dominating if's visited 3327 const TypeInt* rtn_t = nullptr; 3328 3329 if (use_ctrl && use_ctrl != C->top()) { 3330 Node* val_ctrl = get_ctrl(val); 3331 uint val_dom_depth = dom_depth(val_ctrl); 3332 Node* pred = use_ctrl; 3333 uint if_cnt = 0; 3334 while (if_cnt < if_limit) { 3335 if ((pred->Opcode() == Op_IfTrue || pred->Opcode() == Op_IfFalse)) { 3336 if_cnt++; 3337 const TypeInt* if_t = IfNode::filtered_int_type(&_igvn, val, pred); 3338 if (if_t != nullptr) { 3339 if (rtn_t == nullptr) { 3340 rtn_t = if_t; 3341 } else { 3342 rtn_t = rtn_t->join(if_t)->is_int(); 3343 } 3344 } 3345 } 3346 pred = idom(pred); 3347 if (pred == nullptr || pred == C->top()) { 3348 break; 3349 } 3350 // Stop if going beyond definition block of val 3351 if (dom_depth(pred) < val_dom_depth) { 3352 break; 3353 } 3354 } 3355 } 3356 return rtn_t; 3357 } 3358 3359 3360 //------------------------------dump_spec-------------------------------------- 3361 // Dump special per-node info 3362 #ifndef PRODUCT 3363 void CountedLoopEndNode::dump_spec(outputStream *st) const { 3364 if( in(TestValue) != nullptr && in(TestValue)->is_Bool() ) { 3365 BoolTest bt( test_trip()); // Added this for g++. 3366 3367 st->print("["); 3368 bt.dump_on(st); 3369 st->print("]"); 3370 } 3371 st->print(" "); 3372 IfNode::dump_spec(st); 3373 } 3374 #endif 3375 3376 //============================================================================= 3377 //------------------------------is_member-------------------------------------- 3378 // Is 'l' a member of 'this'? 3379 bool IdealLoopTree::is_member(const IdealLoopTree *l) const { 3380 while( l->_nest > _nest ) l = l->_parent; 3381 return l == this; 3382 } 3383 3384 //------------------------------set_nest--------------------------------------- 3385 // Set loop tree nesting depth. Accumulate _has_call bits. 3386 int IdealLoopTree::set_nest( uint depth ) { 3387 assert(depth <= SHRT_MAX, "sanity"); 3388 _nest = depth; 3389 int bits = _has_call; 3390 if( _child ) bits |= _child->set_nest(depth+1); 3391 if( bits ) _has_call = 1; 3392 if( _next ) bits |= _next ->set_nest(depth ); 3393 return bits; 3394 } 3395 3396 //------------------------------split_fall_in---------------------------------- 3397 // Split out multiple fall-in edges from the loop header. Move them to a 3398 // private RegionNode before the loop. This becomes the loop landing pad. 3399 void IdealLoopTree::split_fall_in( PhaseIdealLoop *phase, int fall_in_cnt ) { 3400 PhaseIterGVN &igvn = phase->_igvn; 3401 uint i; 3402 3403 // Make a new RegionNode to be the landing pad. 3404 RegionNode* landing_pad = new RegionNode(fall_in_cnt + 1); 3405 phase->set_loop(landing_pad,_parent); 3406 // If _head was irreducible loop entry, landing_pad may now be too 3407 landing_pad->set_loop_status(_head->as_Region()->loop_status()); 3408 // Gather all the fall-in control paths into the landing pad 3409 uint icnt = fall_in_cnt; 3410 uint oreq = _head->req(); 3411 for( i = oreq-1; i>0; i-- ) 3412 if( !phase->is_member( this, _head->in(i) ) ) 3413 landing_pad->set_req(icnt--,_head->in(i)); 3414 3415 // Peel off PhiNode edges as well 3416 for (DUIterator_Fast jmax, j = _head->fast_outs(jmax); j < jmax; j++) { 3417 Node *oj = _head->fast_out(j); 3418 if( oj->is_Phi() ) { 3419 PhiNode* old_phi = oj->as_Phi(); 3420 assert( old_phi->region() == _head, "" ); 3421 igvn.hash_delete(old_phi); // Yank from hash before hacking edges 3422 Node *p = PhiNode::make_blank(landing_pad, old_phi); 3423 uint icnt = fall_in_cnt; 3424 for( i = oreq-1; i>0; i-- ) { 3425 if( !phase->is_member( this, _head->in(i) ) ) { 3426 p->init_req(icnt--, old_phi->in(i)); 3427 // Go ahead and clean out old edges from old phi 3428 old_phi->del_req(i); 3429 } 3430 } 3431 // Search for CSE's here, because ZKM.jar does a lot of 3432 // loop hackery and we need to be a little incremental 3433 // with the CSE to avoid O(N^2) node blow-up. 3434 Node *p2 = igvn.hash_find_insert(p); // Look for a CSE 3435 if( p2 ) { // Found CSE 3436 p->destruct(&igvn); // Recover useless new node 3437 p = p2; // Use old node 3438 } else { 3439 igvn.register_new_node_with_optimizer(p, old_phi); 3440 } 3441 // Make old Phi refer to new Phi. 3442 old_phi->add_req(p); 3443 // Check for the special case of making the old phi useless and 3444 // disappear it. In JavaGrande I have a case where this useless 3445 // Phi is the loop limit and prevents recognizing a CountedLoop 3446 // which in turn prevents removing an empty loop. 3447 Node *id_old_phi = old_phi->Identity(&igvn); 3448 if( id_old_phi != old_phi ) { // Found a simple identity? 3449 // Note that I cannot call 'replace_node' here, because 3450 // that will yank the edge from old_phi to the Region and 3451 // I'm mid-iteration over the Region's uses. 3452 for (DUIterator_Last imin, i = old_phi->last_outs(imin); i >= imin; ) { 3453 Node* use = old_phi->last_out(i); 3454 igvn.rehash_node_delayed(use); 3455 uint uses_found = 0; 3456 for (uint j = 0; j < use->len(); j++) { 3457 if (use->in(j) == old_phi) { 3458 if (j < use->req()) use->set_req (j, id_old_phi); 3459 else use->set_prec(j, id_old_phi); 3460 uses_found++; 3461 } 3462 } 3463 i -= uses_found; // we deleted 1 or more copies of this edge 3464 } 3465 } 3466 igvn._worklist.push(old_phi); 3467 } 3468 } 3469 // Finally clean out the fall-in edges from the RegionNode 3470 for( i = oreq-1; i>0; i-- ) { 3471 if( !phase->is_member( this, _head->in(i) ) ) { 3472 _head->del_req(i); 3473 } 3474 } 3475 igvn.rehash_node_delayed(_head); 3476 // Transform landing pad 3477 igvn.register_new_node_with_optimizer(landing_pad, _head); 3478 // Insert landing pad into the header 3479 _head->add_req(landing_pad); 3480 } 3481 3482 //------------------------------split_outer_loop------------------------------- 3483 // Split out the outermost loop from this shared header. 3484 void IdealLoopTree::split_outer_loop( PhaseIdealLoop *phase ) { 3485 PhaseIterGVN &igvn = phase->_igvn; 3486 3487 // Find index of outermost loop; it should also be my tail. 3488 uint outer_idx = 1; 3489 while( _head->in(outer_idx) != _tail ) outer_idx++; 3490 3491 // Make a LoopNode for the outermost loop. 3492 Node *ctl = _head->in(LoopNode::EntryControl); 3493 Node *outer = new LoopNode( ctl, _head->in(outer_idx) ); 3494 outer = igvn.register_new_node_with_optimizer(outer, _head); 3495 phase->set_created_loop_node(); 3496 3497 // Outermost loop falls into '_head' loop 3498 _head->set_req(LoopNode::EntryControl, outer); 3499 _head->del_req(outer_idx); 3500 // Split all the Phis up between '_head' loop and 'outer' loop. 3501 for (DUIterator_Fast jmax, j = _head->fast_outs(jmax); j < jmax; j++) { 3502 Node *out = _head->fast_out(j); 3503 if( out->is_Phi() ) { 3504 PhiNode *old_phi = out->as_Phi(); 3505 assert( old_phi->region() == _head, "" ); 3506 Node *phi = PhiNode::make_blank(outer, old_phi); 3507 phi->init_req(LoopNode::EntryControl, old_phi->in(LoopNode::EntryControl)); 3508 phi->init_req(LoopNode::LoopBackControl, old_phi->in(outer_idx)); 3509 phi = igvn.register_new_node_with_optimizer(phi, old_phi); 3510 // Make old Phi point to new Phi on the fall-in path 3511 igvn.replace_input_of(old_phi, LoopNode::EntryControl, phi); 3512 old_phi->del_req(outer_idx); 3513 } 3514 } 3515 3516 // Use the new loop head instead of the old shared one 3517 _head = outer; 3518 phase->set_loop(_head, this); 3519 } 3520 3521 //------------------------------fix_parent------------------------------------- 3522 static void fix_parent( IdealLoopTree *loop, IdealLoopTree *parent ) { 3523 loop->_parent = parent; 3524 if( loop->_child ) fix_parent( loop->_child, loop ); 3525 if( loop->_next ) fix_parent( loop->_next , parent ); 3526 } 3527 3528 //------------------------------estimate_path_freq----------------------------- 3529 static float estimate_path_freq( Node *n ) { 3530 // Try to extract some path frequency info 3531 IfNode *iff; 3532 for( int i = 0; i < 50; i++ ) { // Skip through a bunch of uncommon tests 3533 uint nop = n->Opcode(); 3534 if( nop == Op_SafePoint ) { // Skip any safepoint 3535 n = n->in(0); 3536 continue; 3537 } 3538 if( nop == Op_CatchProj ) { // Get count from a prior call 3539 // Assume call does not always throw exceptions: means the call-site 3540 // count is also the frequency of the fall-through path. 3541 assert( n->is_CatchProj(), "" ); 3542 if( ((CatchProjNode*)n)->_con != CatchProjNode::fall_through_index ) 3543 return 0.0f; // Assume call exception path is rare 3544 Node *call = n->in(0)->in(0)->in(0); 3545 assert( call->is_Call(), "expect a call here" ); 3546 const JVMState *jvms = ((CallNode*)call)->jvms(); 3547 ciMethodData* methodData = jvms->method()->method_data(); 3548 if (!methodData->is_mature()) return 0.0f; // No call-site data 3549 ciProfileData* data = methodData->bci_to_data(jvms->bci()); 3550 if ((data == nullptr) || !data->is_CounterData()) { 3551 // no call profile available, try call's control input 3552 n = n->in(0); 3553 continue; 3554 } 3555 return data->as_CounterData()->count()/FreqCountInvocations; 3556 } 3557 // See if there's a gating IF test 3558 Node *n_c = n->in(0); 3559 if( !n_c->is_If() ) break; // No estimate available 3560 iff = n_c->as_If(); 3561 if( iff->_fcnt != COUNT_UNKNOWN ) // Have a valid count? 3562 // Compute how much count comes on this path 3563 return ((nop == Op_IfTrue) ? iff->_prob : 1.0f - iff->_prob) * iff->_fcnt; 3564 // Have no count info. Skip dull uncommon-trap like branches. 3565 if( (nop == Op_IfTrue && iff->_prob < PROB_LIKELY_MAG(5)) || 3566 (nop == Op_IfFalse && iff->_prob > PROB_UNLIKELY_MAG(5)) ) 3567 break; 3568 // Skip through never-taken branch; look for a real loop exit. 3569 n = iff->in(0); 3570 } 3571 return 0.0f; // No estimate available 3572 } 3573 3574 //------------------------------merge_many_backedges--------------------------- 3575 // Merge all the backedges from the shared header into a private Region. 3576 // Feed that region as the one backedge to this loop. 3577 void IdealLoopTree::merge_many_backedges( PhaseIdealLoop *phase ) { 3578 uint i; 3579 3580 // Scan for the top 2 hottest backedges 3581 float hotcnt = 0.0f; 3582 float warmcnt = 0.0f; 3583 uint hot_idx = 0; 3584 // Loop starts at 2 because slot 1 is the fall-in path 3585 for( i = 2; i < _head->req(); i++ ) { 3586 float cnt = estimate_path_freq(_head->in(i)); 3587 if( cnt > hotcnt ) { // Grab hottest path 3588 warmcnt = hotcnt; 3589 hotcnt = cnt; 3590 hot_idx = i; 3591 } else if( cnt > warmcnt ) { // And 2nd hottest path 3592 warmcnt = cnt; 3593 } 3594 } 3595 3596 // See if the hottest backedge is worthy of being an inner loop 3597 // by being much hotter than the next hottest backedge. 3598 if( hotcnt <= 0.0001 || 3599 hotcnt < 2.0*warmcnt ) hot_idx = 0;// No hot backedge 3600 3601 // Peel out the backedges into a private merge point; peel 3602 // them all except optionally hot_idx. 3603 PhaseIterGVN &igvn = phase->_igvn; 3604 3605 Node *hot_tail = nullptr; 3606 // Make a Region for the merge point 3607 Node *r = new RegionNode(1); 3608 for( i = 2; i < _head->req(); i++ ) { 3609 if( i != hot_idx ) 3610 r->add_req( _head->in(i) ); 3611 else hot_tail = _head->in(i); 3612 } 3613 igvn.register_new_node_with_optimizer(r, _head); 3614 // Plug region into end of loop _head, followed by hot_tail 3615 while( _head->req() > 3 ) _head->del_req( _head->req()-1 ); 3616 igvn.replace_input_of(_head, 2, r); 3617 if( hot_idx ) _head->add_req(hot_tail); 3618 3619 // Split all the Phis up between '_head' loop and the Region 'r' 3620 for (DUIterator_Fast jmax, j = _head->fast_outs(jmax); j < jmax; j++) { 3621 Node *out = _head->fast_out(j); 3622 if( out->is_Phi() ) { 3623 PhiNode* n = out->as_Phi(); 3624 igvn.hash_delete(n); // Delete from hash before hacking edges 3625 Node *hot_phi = nullptr; 3626 Node *phi = new PhiNode(r, n->type(), n->adr_type()); 3627 // Check all inputs for the ones to peel out 3628 uint j = 1; 3629 for( uint i = 2; i < n->req(); i++ ) { 3630 if( i != hot_idx ) 3631 phi->set_req( j++, n->in(i) ); 3632 else hot_phi = n->in(i); 3633 } 3634 // Register the phi but do not transform until whole place transforms 3635 igvn.register_new_node_with_optimizer(phi, n); 3636 // Add the merge phi to the old Phi 3637 while( n->req() > 3 ) n->del_req( n->req()-1 ); 3638 igvn.replace_input_of(n, 2, phi); 3639 if( hot_idx ) n->add_req(hot_phi); 3640 } 3641 } 3642 3643 3644 // Insert a new IdealLoopTree inserted below me. Turn it into a clone 3645 // of self loop tree. Turn self into a loop headed by _head and with 3646 // tail being the new merge point. 3647 IdealLoopTree *ilt = new IdealLoopTree( phase, _head, _tail ); 3648 phase->set_loop(_tail,ilt); // Adjust tail 3649 _tail = r; // Self's tail is new merge point 3650 phase->set_loop(r,this); 3651 ilt->_child = _child; // New guy has my children 3652 _child = ilt; // Self has new guy as only child 3653 ilt->_parent = this; // new guy has self for parent 3654 ilt->_nest = _nest; // Same nesting depth (for now) 3655 3656 // Starting with 'ilt', look for child loop trees using the same shared 3657 // header. Flatten these out; they will no longer be loops in the end. 3658 IdealLoopTree **pilt = &_child; 3659 while( ilt ) { 3660 if( ilt->_head == _head ) { 3661 uint i; 3662 for( i = 2; i < _head->req(); i++ ) 3663 if( _head->in(i) == ilt->_tail ) 3664 break; // Still a loop 3665 if( i == _head->req() ) { // No longer a loop 3666 // Flatten ilt. Hang ilt's "_next" list from the end of 3667 // ilt's '_child' list. Move the ilt's _child up to replace ilt. 3668 IdealLoopTree **cp = &ilt->_child; 3669 while( *cp ) cp = &(*cp)->_next; // Find end of child list 3670 *cp = ilt->_next; // Hang next list at end of child list 3671 *pilt = ilt->_child; // Move child up to replace ilt 3672 ilt->_head = nullptr; // Flag as a loop UNIONED into parent 3673 ilt = ilt->_child; // Repeat using new ilt 3674 continue; // do not advance over ilt->_child 3675 } 3676 assert( ilt->_tail == hot_tail, "expected to only find the hot inner loop here" ); 3677 phase->set_loop(_head,ilt); 3678 } 3679 pilt = &ilt->_child; // Advance to next 3680 ilt = *pilt; 3681 } 3682 3683 if( _child ) fix_parent( _child, this ); 3684 } 3685 3686 //------------------------------beautify_loops--------------------------------- 3687 // Split shared headers and insert loop landing pads. 3688 // Insert a LoopNode to replace the RegionNode. 3689 // Return TRUE if loop tree is structurally changed. 3690 bool IdealLoopTree::beautify_loops( PhaseIdealLoop *phase ) { 3691 bool result = false; 3692 // Cache parts in locals for easy 3693 PhaseIterGVN &igvn = phase->_igvn; 3694 3695 igvn.hash_delete(_head); // Yank from hash before hacking edges 3696 3697 // Check for multiple fall-in paths. Peel off a landing pad if need be. 3698 int fall_in_cnt = 0; 3699 for( uint i = 1; i < _head->req(); i++ ) 3700 if( !phase->is_member( this, _head->in(i) ) ) 3701 fall_in_cnt++; 3702 assert( fall_in_cnt, "at least 1 fall-in path" ); 3703 if( fall_in_cnt > 1 ) // Need a loop landing pad to merge fall-ins 3704 split_fall_in( phase, fall_in_cnt ); 3705 3706 // Swap inputs to the _head and all Phis to move the fall-in edge to 3707 // the left. 3708 fall_in_cnt = 1; 3709 while( phase->is_member( this, _head->in(fall_in_cnt) ) ) 3710 fall_in_cnt++; 3711 if( fall_in_cnt > 1 ) { 3712 // Since I am just swapping inputs I do not need to update def-use info 3713 Node *tmp = _head->in(1); 3714 igvn.rehash_node_delayed(_head); 3715 _head->set_req( 1, _head->in(fall_in_cnt) ); 3716 _head->set_req( fall_in_cnt, tmp ); 3717 // Swap also all Phis 3718 for (DUIterator_Fast imax, i = _head->fast_outs(imax); i < imax; i++) { 3719 Node* phi = _head->fast_out(i); 3720 if( phi->is_Phi() ) { 3721 igvn.rehash_node_delayed(phi); // Yank from hash before hacking edges 3722 tmp = phi->in(1); 3723 phi->set_req( 1, phi->in(fall_in_cnt) ); 3724 phi->set_req( fall_in_cnt, tmp ); 3725 } 3726 } 3727 } 3728 assert( !phase->is_member( this, _head->in(1) ), "left edge is fall-in" ); 3729 assert( phase->is_member( this, _head->in(2) ), "right edge is loop" ); 3730 3731 // If I am a shared header (multiple backedges), peel off the many 3732 // backedges into a private merge point and use the merge point as 3733 // the one true backedge. 3734 if (_head->req() > 3) { 3735 // Merge the many backedges into a single backedge but leave 3736 // the hottest backedge as separate edge for the following peel. 3737 if (!_irreducible) { 3738 merge_many_backedges( phase ); 3739 } 3740 3741 // When recursively beautify my children, split_fall_in can change 3742 // loop tree structure when I am an irreducible loop. Then the head 3743 // of my children has a req() not bigger than 3. Here we need to set 3744 // result to true to catch that case in order to tell the caller to 3745 // rebuild loop tree. See issue JDK-8244407 for details. 3746 result = true; 3747 } 3748 3749 // If I have one hot backedge, peel off myself loop. 3750 // I better be the outermost loop. 3751 if (_head->req() > 3 && !_irreducible) { 3752 split_outer_loop( phase ); 3753 result = true; 3754 3755 } else if (!_head->is_Loop() && !_irreducible) { 3756 // Make a new LoopNode to replace the old loop head 3757 Node *l = new LoopNode( _head->in(1), _head->in(2) ); 3758 l = igvn.register_new_node_with_optimizer(l, _head); 3759 phase->set_created_loop_node(); 3760 // Go ahead and replace _head 3761 phase->_igvn.replace_node( _head, l ); 3762 _head = l; 3763 phase->set_loop(_head, this); 3764 } 3765 3766 // Now recursively beautify nested loops 3767 if( _child ) result |= _child->beautify_loops( phase ); 3768 if( _next ) result |= _next ->beautify_loops( phase ); 3769 return result; 3770 } 3771 3772 //------------------------------allpaths_check_safepts---------------------------- 3773 // Allpaths backwards scan. Starting at the head, traversing all backedges, and the body. Terminating each path at first 3774 // safepoint encountered. Helper for check_safepts. 3775 void IdealLoopTree::allpaths_check_safepts(VectorSet &visited, Node_List &stack) { 3776 assert(stack.size() == 0, "empty stack"); 3777 stack.push(_head); 3778 visited.clear(); 3779 visited.set(_head->_idx); 3780 while (stack.size() > 0) { 3781 Node* n = stack.pop(); 3782 if (n->is_Call() && n->as_Call()->guaranteed_safepoint()) { 3783 // Terminate this path 3784 } else if (n->Opcode() == Op_SafePoint) { 3785 if (_phase->get_loop(n) != this) { 3786 if (_required_safept == nullptr) _required_safept = new Node_List(); 3787 // save the first we run into on that path: closest to the tail if the head has a single backedge 3788 _required_safept->push(n); 3789 } 3790 // Terminate this path 3791 } else { 3792 uint start = n->is_Region() ? 1 : 0; 3793 uint end = n->is_Region() && (!n->is_Loop() || n == _head) ? n->req() : start + 1; 3794 for (uint i = start; i < end; i++) { 3795 Node* in = n->in(i); 3796 assert(in->is_CFG(), "must be"); 3797 if (!visited.test_set(in->_idx) && is_member(_phase->get_loop(in))) { 3798 stack.push(in); 3799 } 3800 } 3801 } 3802 } 3803 } 3804 3805 //------------------------------check_safepts---------------------------- 3806 // Given dominators, try to find loops with calls that must always be 3807 // executed (call dominates loop tail). These loops do not need non-call 3808 // safepoints (ncsfpt). 3809 // 3810 // A complication is that a safepoint in a inner loop may be needed 3811 // by an outer loop. In the following, the inner loop sees it has a 3812 // call (block 3) on every path from the head (block 2) to the 3813 // backedge (arc 3->2). So it deletes the ncsfpt (non-call safepoint) 3814 // in block 2, _but_ this leaves the outer loop without a safepoint. 3815 // 3816 // entry 0 3817 // | 3818 // v 3819 // outer 1,2 +->1 3820 // | | 3821 // | v 3822 // | 2<---+ ncsfpt in 2 3823 // |_/|\ | 3824 // | v | 3825 // inner 2,3 / 3 | call in 3 3826 // / | | 3827 // v +--+ 3828 // exit 4 3829 // 3830 // 3831 // This method creates a list (_required_safept) of ncsfpt nodes that must 3832 // be protected is created for each loop. When a ncsfpt maybe deleted, it 3833 // is first looked for in the lists for the outer loops of the current loop. 3834 // 3835 // The insights into the problem: 3836 // A) counted loops are okay 3837 // B) innermost loops are okay (only an inner loop can delete 3838 // a ncsfpt needed by an outer loop) 3839 // C) a loop is immune from an inner loop deleting a safepoint 3840 // if the loop has a call on the idom-path 3841 // D) a loop is also immune if it has a ncsfpt (non-call safepoint) on the 3842 // idom-path that is not in a nested loop 3843 // E) otherwise, an ncsfpt on the idom-path that is nested in an inner 3844 // loop needs to be prevented from deletion by an inner loop 3845 // 3846 // There are two analyses: 3847 // 1) The first, and cheaper one, scans the loop body from 3848 // tail to head following the idom (immediate dominator) 3849 // chain, looking for the cases (C,D,E) above. 3850 // Since inner loops are scanned before outer loops, there is summary 3851 // information about inner loops. Inner loops can be skipped over 3852 // when the tail of an inner loop is encountered. 3853 // 3854 // 2) The second, invoked if the first fails to find a call or ncsfpt on 3855 // the idom path (which is rare), scans all predecessor control paths 3856 // from the tail to the head, terminating a path when a call or sfpt 3857 // is encountered, to find the ncsfpt's that are closest to the tail. 3858 // 3859 void IdealLoopTree::check_safepts(VectorSet &visited, Node_List &stack) { 3860 // Bottom up traversal 3861 IdealLoopTree* ch = _child; 3862 if (_child) _child->check_safepts(visited, stack); 3863 if (_next) _next ->check_safepts(visited, stack); 3864 3865 if (!_head->is_CountedLoop() && !_has_sfpt && _parent != nullptr) { 3866 bool has_call = false; // call on dom-path 3867 bool has_local_ncsfpt = false; // ncsfpt on dom-path at this loop depth 3868 Node* nonlocal_ncsfpt = nullptr; // ncsfpt on dom-path at a deeper depth 3869 if (!_irreducible) { 3870 // Scan the dom-path nodes from tail to head 3871 for (Node* n = tail(); n != _head; n = _phase->idom(n)) { 3872 if (n->is_Call() && n->as_Call()->guaranteed_safepoint()) { 3873 has_call = true; 3874 _has_sfpt = 1; // Then no need for a safept! 3875 break; 3876 } else if (n->Opcode() == Op_SafePoint) { 3877 if (_phase->get_loop(n) == this) { 3878 has_local_ncsfpt = true; 3879 break; 3880 } 3881 if (nonlocal_ncsfpt == nullptr) { 3882 nonlocal_ncsfpt = n; // save the one closest to the tail 3883 } 3884 } else { 3885 IdealLoopTree* nlpt = _phase->get_loop(n); 3886 if (this != nlpt) { 3887 // If at an inner loop tail, see if the inner loop has already 3888 // recorded seeing a call on the dom-path (and stop.) If not, 3889 // jump to the head of the inner loop. 3890 assert(is_member(nlpt), "nested loop"); 3891 Node* tail = nlpt->_tail; 3892 if (tail->in(0)->is_If()) tail = tail->in(0); 3893 if (n == tail) { 3894 // If inner loop has call on dom-path, so does outer loop 3895 if (nlpt->_has_sfpt) { 3896 has_call = true; 3897 _has_sfpt = 1; 3898 break; 3899 } 3900 // Skip to head of inner loop 3901 assert(_phase->is_dominator(_head, nlpt->_head), "inner head dominated by outer head"); 3902 n = nlpt->_head; 3903 if (_head == n) { 3904 // this and nlpt (inner loop) have the same loop head. This should not happen because 3905 // during beautify_loops we call merge_many_backedges. However, infinite loops may not 3906 // have been attached to the loop-tree during build_loop_tree before beautify_loops, 3907 // but then attached in the build_loop_tree afterwards, and so still have unmerged 3908 // backedges. Check if we are indeed in an infinite subgraph, and terminate the scan, 3909 // since we have reached the loop head of this. 3910 assert(_head->as_Region()->is_in_infinite_subgraph(), 3911 "only expect unmerged backedges in infinite loops"); 3912 break; 3913 } 3914 } 3915 } 3916 } 3917 } 3918 } 3919 // Record safept's that this loop needs preserved when an 3920 // inner loop attempts to delete it's safepoints. 3921 if (_child != nullptr && !has_call && !has_local_ncsfpt) { 3922 if (nonlocal_ncsfpt != nullptr) { 3923 if (_required_safept == nullptr) _required_safept = new Node_List(); 3924 _required_safept->push(nonlocal_ncsfpt); 3925 } else { 3926 // Failed to find a suitable safept on the dom-path. Now use 3927 // an all paths walk from tail to head, looking for safepoints to preserve. 3928 allpaths_check_safepts(visited, stack); 3929 } 3930 } 3931 } 3932 } 3933 3934 //---------------------------is_deleteable_safept---------------------------- 3935 // Is safept not required by an outer loop? 3936 bool PhaseIdealLoop::is_deleteable_safept(Node* sfpt) { 3937 assert(sfpt->Opcode() == Op_SafePoint, ""); 3938 IdealLoopTree* lp = get_loop(sfpt)->_parent; 3939 while (lp != nullptr) { 3940 Node_List* sfpts = lp->_required_safept; 3941 if (sfpts != nullptr) { 3942 for (uint i = 0; i < sfpts->size(); i++) { 3943 if (sfpt == sfpts->at(i)) 3944 return false; 3945 } 3946 } 3947 lp = lp->_parent; 3948 } 3949 return true; 3950 } 3951 3952 //---------------------------replace_parallel_iv------------------------------- 3953 // Replace parallel induction variable (parallel to trip counter) 3954 // This optimization looks for patterns similar to: 3955 // 3956 // int a = init2; 3957 // for (int iv = init; iv < limit; iv += stride_con) { 3958 // a += stride_con2; 3959 // } 3960 // 3961 // and transforms it to: 3962 // 3963 // int iv2 = init2 3964 // int iv = init 3965 // loop: 3966 // if (iv >= limit) goto exit 3967 // iv += stride_con 3968 // iv2 = init2 + (iv - init) * (stride_con2 / stride_con) 3969 // goto loop 3970 // exit: 3971 // ... 3972 // 3973 // Such transformation introduces more optimization opportunities. In this 3974 // particular example, the loop can be eliminated entirely given that 3975 // `stride_con2 / stride_con` is exact (i.e., no remainder). Checks are in 3976 // place to only perform this optimization if such a division is exact. This 3977 // example will be transformed into its semantic equivalence: 3978 // 3979 // int iv2 = (iv * stride_con2 / stride_con) + (init2 - (init * stride_con2 / stride_con)) 3980 // 3981 // which corresponds to the structure of transformed subgraph. 3982 // 3983 // However, if there is a mismatch between types of the loop and the parallel 3984 // induction variable (e.g., a long-typed IV in an int-typed loop), type 3985 // conversions are required: 3986 // 3987 // long iv2 = ((long) iv * stride_con2 / stride_con) + (init2 - ((long) init * stride_con2 / stride_con)) 3988 // 3989 void PhaseIdealLoop::replace_parallel_iv(IdealLoopTree *loop) { 3990 assert(loop->_head->is_CountedLoop(), ""); 3991 CountedLoopNode *cl = loop->_head->as_CountedLoop(); 3992 if (!cl->is_valid_counted_loop(T_INT)) { 3993 return; // skip malformed counted loop 3994 } 3995 Node *incr = cl->incr(); 3996 if (incr == nullptr) { 3997 return; // Dead loop? 3998 } 3999 Node *init = cl->init_trip(); 4000 Node *phi = cl->phi(); 4001 jlong stride_con = cl->stride_con(); 4002 4003 // Visit all children, looking for Phis 4004 for (DUIterator i = cl->outs(); cl->has_out(i); i++) { 4005 Node *out = cl->out(i); 4006 // Look for other phis (secondary IVs). Skip dead ones 4007 if (!out->is_Phi() || out == phi || !has_node(out)) { 4008 continue; 4009 } 4010 4011 PhiNode* phi2 = out->as_Phi(); 4012 Node* incr2 = phi2->in(LoopNode::LoopBackControl); 4013 // Look for induction variables of the form: X += constant 4014 if (phi2->region() != loop->_head || 4015 incr2->req() != 3 || 4016 incr2->in(1)->uncast() != phi2 || 4017 incr2 == incr || 4018 (incr2->Opcode() != Op_AddI && incr2->Opcode() != Op_AddL) || 4019 !incr2->in(2)->is_Con()) { 4020 continue; 4021 } 4022 4023 if (incr2->in(1)->is_ConstraintCast() && 4024 !(incr2->in(1)->in(0)->is_IfProj() && incr2->in(1)->in(0)->in(0)->is_RangeCheck())) { 4025 // Skip AddI->CastII->Phi case if CastII is not controlled by local RangeCheck 4026 continue; 4027 } 4028 // Check for parallel induction variable (parallel to trip counter) 4029 // via an affine function. In particular, count-down loops with 4030 // count-up array indices are common. We only RCE references off 4031 // the trip-counter, so we need to convert all these to trip-counter 4032 // expressions. 4033 Node* init2 = phi2->in(LoopNode::EntryControl); 4034 4035 // Determine the basic type of the stride constant (and the iv being incremented). 4036 BasicType stride_con2_bt = incr2->Opcode() == Op_AddI ? T_INT : T_LONG; 4037 jlong stride_con2 = incr2->in(2)->get_integer_as_long(stride_con2_bt); 4038 4039 // The ratio of the two strides cannot be represented as an int 4040 // if stride_con2 is min_jint (or min_jlong, respectively) and 4041 // stride_con is -1. 4042 if (stride_con2 == min_signed_integer(stride_con2_bt) && stride_con == -1) { 4043 continue; 4044 } 4045 4046 // The general case here gets a little tricky. We want to find the 4047 // GCD of all possible parallel IV's and make a new IV using this 4048 // GCD for the loop. Then all possible IVs are simple multiples of 4049 // the GCD. In practice, this will cover very few extra loops. 4050 // Instead we require 'stride_con2' to be a multiple of 'stride_con', 4051 // where +/-1 is the common case, but other integer multiples are 4052 // also easy to handle. 4053 jlong ratio_con = stride_con2 / stride_con; 4054 4055 if ((ratio_con * stride_con) != stride_con2) { // Check for exact (no remainder) 4056 continue; 4057 } 4058 4059 #ifndef PRODUCT 4060 if (TraceLoopOpts) { 4061 tty->print("Parallel IV: %d ", phi2->_idx); 4062 loop->dump_head(); 4063 } 4064 #endif 4065 4066 // Convert to using the trip counter. The parallel induction 4067 // variable differs from the trip counter by a loop-invariant 4068 // amount, the difference between their respective initial values. 4069 // It is scaled by the 'ratio_con'. 4070 Node* ratio = _igvn.integercon(ratio_con, stride_con2_bt); 4071 set_ctrl(ratio, C->root()); 4072 4073 Node* init_converted = insert_convert_node_if_needed(stride_con2_bt, init); 4074 Node* phi_converted = insert_convert_node_if_needed(stride_con2_bt, phi); 4075 4076 Node* ratio_init = MulNode::make(init_converted, ratio, stride_con2_bt); 4077 _igvn.register_new_node_with_optimizer(ratio_init, init_converted); 4078 set_early_ctrl(ratio_init, false); 4079 4080 Node* diff = SubNode::make(init2, ratio_init, stride_con2_bt); 4081 _igvn.register_new_node_with_optimizer(diff, init2); 4082 set_early_ctrl(diff, false); 4083 4084 Node* ratio_idx = MulNode::make(phi_converted, ratio, stride_con2_bt); 4085 _igvn.register_new_node_with_optimizer(ratio_idx, phi_converted); 4086 set_ctrl(ratio_idx, cl); 4087 4088 Node* add = AddNode::make(ratio_idx, diff, stride_con2_bt); 4089 _igvn.register_new_node_with_optimizer(add); 4090 set_ctrl(add, cl); 4091 4092 _igvn.replace_node( phi2, add ); 4093 // Sometimes an induction variable is unused 4094 if (add->outcnt() == 0) { 4095 _igvn.remove_dead_node(add); 4096 } 4097 --i; // deleted this phi; rescan starting with next position 4098 } 4099 } 4100 4101 Node* PhaseIdealLoop::insert_convert_node_if_needed(BasicType target, Node* input) { 4102 BasicType source = _igvn.type(input)->basic_type(); 4103 if (source == target) { 4104 return input; 4105 } 4106 4107 Node* converted = ConvertNode::create_convert(source, target, input); 4108 _igvn.register_new_node_with_optimizer(converted, input); 4109 set_early_ctrl(converted, false); 4110 4111 return converted; 4112 } 4113 4114 void IdealLoopTree::remove_safepoints(PhaseIdealLoop* phase, bool keep_one) { 4115 Node* keep = nullptr; 4116 if (keep_one) { 4117 // Look for a safepoint on the idom-path. 4118 for (Node* i = tail(); i != _head; i = phase->idom(i)) { 4119 if (i->Opcode() == Op_SafePoint && phase->get_loop(i) == this) { 4120 keep = i; 4121 break; // Found one 4122 } 4123 } 4124 } 4125 4126 // Don't remove any safepoints if it is requested to keep a single safepoint and 4127 // no safepoint was found on idom-path. It is not safe to remove any safepoint 4128 // in this case since there's no safepoint dominating all paths in the loop body. 4129 bool prune = !keep_one || keep != nullptr; 4130 4131 // Delete other safepoints in this loop. 4132 Node_List* sfpts = _safepts; 4133 if (prune && sfpts != nullptr) { 4134 assert(keep == nullptr || keep->Opcode() == Op_SafePoint, "not safepoint"); 4135 for (uint i = 0; i < sfpts->size(); i++) { 4136 Node* n = sfpts->at(i); 4137 assert(phase->get_loop(n) == this, ""); 4138 if (n != keep && phase->is_deleteable_safept(n)) { 4139 phase->lazy_replace(n, n->in(TypeFunc::Control)); 4140 } 4141 } 4142 } 4143 } 4144 4145 //------------------------------counted_loop----------------------------------- 4146 // Convert to counted loops where possible 4147 void IdealLoopTree::counted_loop( PhaseIdealLoop *phase ) { 4148 4149 // For grins, set the inner-loop flag here 4150 if (!_child) { 4151 if (_head->is_Loop()) _head->as_Loop()->set_inner_loop(); 4152 } 4153 4154 IdealLoopTree* loop = this; 4155 if (_head->is_CountedLoop() || 4156 phase->is_counted_loop(_head, loop, T_INT)) { 4157 4158 if (LoopStripMiningIter == 0 || _head->as_CountedLoop()->is_strip_mined()) { 4159 // Indicate we do not need a safepoint here 4160 _has_sfpt = 1; 4161 } 4162 4163 // Remove safepoints 4164 bool keep_one_sfpt = !(_has_call || _has_sfpt); 4165 remove_safepoints(phase, keep_one_sfpt); 4166 4167 // Look for induction variables 4168 phase->replace_parallel_iv(this); 4169 } else if (_head->is_LongCountedLoop() || 4170 phase->is_counted_loop(_head, loop, T_LONG)) { 4171 remove_safepoints(phase, true); 4172 } else { 4173 assert(!_head->is_Loop() || !_head->as_Loop()->is_loop_nest_inner_loop(), "transformation to counted loop should not fail"); 4174 if (_parent != nullptr && !_irreducible) { 4175 // Not a counted loop. Keep one safepoint. 4176 bool keep_one_sfpt = true; 4177 remove_safepoints(phase, keep_one_sfpt); 4178 } 4179 } 4180 4181 // Recursively 4182 assert(loop->_child != this || (loop->_head->as_Loop()->is_OuterStripMinedLoop() && _head->as_CountedLoop()->is_strip_mined()), "what kind of loop was added?"); 4183 assert(loop->_child != this || (loop->_child->_child == nullptr && loop->_child->_next == nullptr), "would miss some loops"); 4184 if (loop->_child && loop->_child != this) loop->_child->counted_loop(phase); 4185 if (loop->_next) loop->_next ->counted_loop(phase); 4186 } 4187 4188 4189 // The Estimated Loop Clone Size: 4190 // CloneFactor * (~112% * BodySize + BC) + CC + FanOutTerm, 4191 // where BC and CC are totally ad-hoc/magic "body" and "clone" constants, 4192 // respectively, used to ensure that the node usage estimates made are on the 4193 // safe side, for the most part. The FanOutTerm is an attempt to estimate the 4194 // possible additional/excessive nodes generated due to data and control flow 4195 // merging, for edges reaching outside the loop. 4196 uint IdealLoopTree::est_loop_clone_sz(uint factor) const { 4197 4198 precond(0 < factor && factor < 16); 4199 4200 uint const bc = 13; 4201 uint const cc = 17; 4202 uint const sz = _body.size() + (_body.size() + 7) / 2; 4203 uint estimate = factor * (sz + bc) + cc; 4204 4205 assert((estimate - cc) / factor == sz + bc, "overflow"); 4206 4207 return estimate + est_loop_flow_merge_sz(); 4208 } 4209 4210 // The Estimated Loop (full-) Unroll Size: 4211 // UnrollFactor * (~106% * BodySize) + CC + FanOutTerm, 4212 // where CC is a (totally) ad-hoc/magic "clone" constant, used to ensure that 4213 // node usage estimates made are on the safe side, for the most part. This is 4214 // a "light" version of the loop clone size calculation (above), based on the 4215 // assumption that most of the loop-construct overhead will be unraveled when 4216 // (fully) unrolled. Defined for unroll factors larger or equal to one (>=1), 4217 // including an overflow check and returning UINT_MAX in case of an overflow. 4218 uint IdealLoopTree::est_loop_unroll_sz(uint factor) const { 4219 4220 precond(factor > 0); 4221 4222 // Take into account that after unroll conjoined heads and tails will fold. 4223 uint const b0 = _body.size() - EMPTY_LOOP_SIZE; 4224 uint const cc = 7; 4225 uint const sz = b0 + (b0 + 15) / 16; 4226 uint estimate = factor * sz + cc; 4227 4228 if ((estimate - cc) / factor != sz) { 4229 return UINT_MAX; 4230 } 4231 4232 return estimate + est_loop_flow_merge_sz(); 4233 } 4234 4235 // Estimate the growth effect (in nodes) of merging control and data flow when 4236 // cloning a loop body, based on the amount of control and data flow reaching 4237 // outside of the (current) loop body. 4238 uint IdealLoopTree::est_loop_flow_merge_sz() const { 4239 4240 uint ctrl_edge_out_cnt = 0; 4241 uint data_edge_out_cnt = 0; 4242 4243 for (uint i = 0; i < _body.size(); i++) { 4244 Node* node = _body.at(i); 4245 uint outcnt = node->outcnt(); 4246 4247 for (uint k = 0; k < outcnt; k++) { 4248 Node* out = node->raw_out(k); 4249 if (out == nullptr) continue; 4250 if (out->is_CFG()) { 4251 if (!is_member(_phase->get_loop(out))) { 4252 ctrl_edge_out_cnt++; 4253 } 4254 } else if (_phase->has_ctrl(out)) { 4255 Node* ctrl = _phase->get_ctrl(out); 4256 assert(ctrl != nullptr, "must be"); 4257 assert(ctrl->is_CFG(), "must be"); 4258 if (!is_member(_phase->get_loop(ctrl))) { 4259 data_edge_out_cnt++; 4260 } 4261 } 4262 } 4263 } 4264 // Use data and control count (x2.0) in estimate iff both are > 0. This is 4265 // a rather pessimistic estimate for the most part, in particular for some 4266 // complex loops, but still not enough to capture all loops. 4267 if (ctrl_edge_out_cnt > 0 && data_edge_out_cnt > 0) { 4268 return 2 * (ctrl_edge_out_cnt + data_edge_out_cnt); 4269 } 4270 return 0; 4271 } 4272 4273 #ifndef PRODUCT 4274 //------------------------------dump_head-------------------------------------- 4275 // Dump 1 liner for loop header info 4276 void IdealLoopTree::dump_head() { 4277 tty->sp(2 * _nest); 4278 tty->print("Loop: N%d/N%d ", _head->_idx, _tail->_idx); 4279 if (_irreducible) tty->print(" IRREDUCIBLE"); 4280 Node* entry = _head->is_Loop() ? _head->as_Loop()->skip_strip_mined(-1)->in(LoopNode::EntryControl) 4281 : _head->in(LoopNode::EntryControl); 4282 const Predicates predicates(entry); 4283 if (predicates.loop_limit_check_predicate_block()->is_non_empty()) { 4284 tty->print(" limit_check"); 4285 } 4286 if (UseProfiledLoopPredicate && predicates.profiled_loop_predicate_block()->is_non_empty()) { 4287 tty->print(" profile_predicated"); 4288 } 4289 if (UseLoopPredicate && predicates.loop_predicate_block()->is_non_empty()) { 4290 tty->print(" predicated"); 4291 } 4292 if (_head->is_CountedLoop()) { 4293 CountedLoopNode *cl = _head->as_CountedLoop(); 4294 tty->print(" counted"); 4295 4296 Node* init_n = cl->init_trip(); 4297 if (init_n != nullptr && init_n->is_Con()) 4298 tty->print(" [%d,", cl->init_trip()->get_int()); 4299 else 4300 tty->print(" [int,"); 4301 Node* limit_n = cl->limit(); 4302 if (limit_n != nullptr && limit_n->is_Con()) 4303 tty->print("%d),", cl->limit()->get_int()); 4304 else 4305 tty->print("int),"); 4306 int stride_con = cl->stride_con(); 4307 if (stride_con > 0) tty->print("+"); 4308 tty->print("%d", stride_con); 4309 4310 tty->print(" (%0.f iters) ", cl->profile_trip_cnt()); 4311 4312 if (cl->is_pre_loop ()) tty->print(" pre" ); 4313 if (cl->is_main_loop()) tty->print(" main"); 4314 if (cl->is_post_loop()) tty->print(" post"); 4315 if (cl->is_vectorized_loop()) tty->print(" vector"); 4316 if (range_checks_present()) tty->print(" rc "); 4317 } 4318 if (_has_call) tty->print(" has_call"); 4319 if (_has_sfpt) tty->print(" has_sfpt"); 4320 if (_rce_candidate) tty->print(" rce"); 4321 if (_safepts != nullptr && _safepts->size() > 0) { 4322 tty->print(" sfpts={"); _safepts->dump_simple(); tty->print(" }"); 4323 } 4324 if (_required_safept != nullptr && _required_safept->size() > 0) { 4325 tty->print(" req={"); _required_safept->dump_simple(); tty->print(" }"); 4326 } 4327 if (Verbose) { 4328 tty->print(" body={"); _body.dump_simple(); tty->print(" }"); 4329 } 4330 if (_head->is_Loop() && _head->as_Loop()->is_strip_mined()) { 4331 tty->print(" strip_mined"); 4332 } 4333 tty->cr(); 4334 } 4335 4336 //------------------------------dump------------------------------------------- 4337 // Dump loops by loop tree 4338 void IdealLoopTree::dump() { 4339 dump_head(); 4340 if (_child) _child->dump(); 4341 if (_next) _next ->dump(); 4342 } 4343 4344 #endif 4345 4346 static void log_loop_tree_helper(IdealLoopTree* root, IdealLoopTree* loop, CompileLog* log) { 4347 if (loop == root) { 4348 if (loop->_child != nullptr) { 4349 log->begin_head("loop_tree"); 4350 log->end_head(); 4351 log_loop_tree_helper(root, loop->_child, log); 4352 log->tail("loop_tree"); 4353 assert(loop->_next == nullptr, "what?"); 4354 } 4355 } else if (loop != nullptr) { 4356 Node* head = loop->_head; 4357 log->begin_head("loop"); 4358 log->print(" idx='%d' ", head->_idx); 4359 if (loop->_irreducible) log->print("irreducible='1' "); 4360 if (head->is_Loop()) { 4361 if (head->as_Loop()->is_inner_loop()) log->print("inner_loop='1' "); 4362 if (head->as_Loop()->is_partial_peel_loop()) log->print("partial_peel_loop='1' "); 4363 } else if (head->is_CountedLoop()) { 4364 CountedLoopNode* cl = head->as_CountedLoop(); 4365 if (cl->is_pre_loop()) log->print("pre_loop='%d' ", cl->main_idx()); 4366 if (cl->is_main_loop()) log->print("main_loop='%d' ", cl->_idx); 4367 if (cl->is_post_loop()) log->print("post_loop='%d' ", cl->main_idx()); 4368 } 4369 log->end_head(); 4370 log_loop_tree_helper(root, loop->_child, log); 4371 log->tail("loop"); 4372 log_loop_tree_helper(root, loop->_next, log); 4373 } 4374 } 4375 4376 void PhaseIdealLoop::log_loop_tree() { 4377 if (C->log() != nullptr) { 4378 log_loop_tree_helper(_ltree_root, _ltree_root, C->log()); 4379 } 4380 } 4381 4382 // Eliminate all Parse and Template Assertion Predicates that are not associated with a loop anymore. The eliminated 4383 // predicates will be removed during the next round of IGVN. 4384 void PhaseIdealLoop::eliminate_useless_predicates() { 4385 if (C->parse_predicate_count() == 0 && C->template_assertion_predicate_count() == 0) { 4386 return; // No predicates left. 4387 } 4388 4389 eliminate_useless_parse_predicates(); 4390 eliminate_useless_template_assertion_predicates(); 4391 } 4392 4393 // Eliminate all Parse Predicates that do not belong to a loop anymore by marking them useless. These will be removed 4394 // during the next round of IGVN. 4395 void PhaseIdealLoop::eliminate_useless_parse_predicates() { 4396 mark_all_parse_predicates_useless(); 4397 if (C->has_loops()) { 4398 mark_loop_associated_parse_predicates_useful(); 4399 } 4400 add_useless_parse_predicates_to_igvn_worklist(); 4401 } 4402 4403 void PhaseIdealLoop::mark_all_parse_predicates_useless() const { 4404 for (int i = 0; i < C->parse_predicate_count(); i++) { 4405 C->parse_predicate(i)->mark_useless(); 4406 } 4407 } 4408 4409 void PhaseIdealLoop::mark_loop_associated_parse_predicates_useful() { 4410 for (LoopTreeIterator iterator(_ltree_root); !iterator.done(); iterator.next()) { 4411 IdealLoopTree* loop = iterator.current(); 4412 if (loop->can_apply_loop_predication()) { 4413 mark_useful_parse_predicates_for_loop(loop); 4414 } 4415 } 4416 } 4417 4418 // This visitor marks all visited Parse Predicates useful. 4419 class ParsePredicateUsefulMarker : public PredicateVisitor { 4420 public: 4421 using PredicateVisitor::visit; 4422 4423 void visit(const ParsePredicate& parse_predicate) override { 4424 parse_predicate.head()->mark_useful(); 4425 } 4426 }; 4427 4428 void PhaseIdealLoop::mark_useful_parse_predicates_for_loop(IdealLoopTree* loop) { 4429 Node* entry = loop->_head->as_Loop()->skip_strip_mined()->in(LoopNode::EntryControl); 4430 const PredicateIterator predicate_iterator(entry); 4431 ParsePredicateUsefulMarker useful_marker; 4432 predicate_iterator.for_each(useful_marker); 4433 } 4434 4435 void PhaseIdealLoop::add_useless_parse_predicates_to_igvn_worklist() { 4436 for (int i = 0; i < C->parse_predicate_count(); i++) { 4437 ParsePredicateNode* parse_predicate_node = C->parse_predicate(i); 4438 if (parse_predicate_node->is_useless()) { 4439 _igvn._worklist.push(parse_predicate_node); 4440 } 4441 } 4442 } 4443 4444 4445 // Eliminate all Template Assertion Predicates that do not belong to their originally associated loop anymore by 4446 // replacing the OpaqueTemplateAssertionPredicate node of the If node with true. These nodes will be removed during the 4447 // next round of IGVN. 4448 void PhaseIdealLoop::eliminate_useless_template_assertion_predicates() { 4449 Unique_Node_List useful_predicates; 4450 if (C->has_loops()) { 4451 collect_useful_template_assertion_predicates(useful_predicates); 4452 } 4453 eliminate_useless_template_assertion_predicates(useful_predicates); 4454 } 4455 4456 void PhaseIdealLoop::collect_useful_template_assertion_predicates(Unique_Node_List& useful_predicates) { 4457 for (LoopTreeIterator iterator(_ltree_root); !iterator.done(); iterator.next()) { 4458 IdealLoopTree* loop = iterator.current(); 4459 if (loop->can_apply_loop_predication()) { 4460 collect_useful_template_assertion_predicates_for_loop(loop, useful_predicates); 4461 } 4462 } 4463 } 4464 4465 void PhaseIdealLoop::collect_useful_template_assertion_predicates_for_loop(IdealLoopTree* loop, 4466 Unique_Node_List &useful_predicates) { 4467 Node* entry = loop->_head->as_Loop()->skip_strip_mined()->in(LoopNode::EntryControl); 4468 const Predicates predicates(entry); 4469 if (UseProfiledLoopPredicate) { 4470 const PredicateBlock* profiled_loop_predicate_block = predicates.profiled_loop_predicate_block(); 4471 if (profiled_loop_predicate_block->has_parse_predicate()) { 4472 ParsePredicateSuccessProj* parse_predicate_proj = profiled_loop_predicate_block->parse_predicate_success_proj(); 4473 get_template_assertion_predicates(parse_predicate_proj, useful_predicates, true); 4474 } 4475 } 4476 4477 if (UseLoopPredicate) { 4478 const PredicateBlock* loop_predicate_block = predicates.loop_predicate_block(); 4479 if (loop_predicate_block->has_parse_predicate()) { 4480 ParsePredicateSuccessProj* parse_predicate_proj = loop_predicate_block->parse_predicate_success_proj(); 4481 get_template_assertion_predicates(parse_predicate_proj, useful_predicates, true); 4482 } 4483 } 4484 } 4485 4486 void PhaseIdealLoop::eliminate_useless_template_assertion_predicates(Unique_Node_List& useful_predicates) { 4487 for (int i = C->template_assertion_predicate_count(); i > 0; i--) { 4488 OpaqueTemplateAssertionPredicateNode* opaque_node = 4489 C->template_assertion_predicate_opaq_node(i - 1)->as_OpaqueTemplateAssertionPredicate(); 4490 if (!useful_predicates.member(opaque_node)) { // not in the useful list 4491 ConINode* one = _igvn.intcon(1); 4492 set_ctrl(one, C->root()); 4493 _igvn.replace_node(opaque_node, one); 4494 } 4495 } 4496 } 4497 4498 // If a post or main loop is removed due to an assert predicate, the opaque that guards the loop is not needed anymore 4499 void PhaseIdealLoop::eliminate_useless_zero_trip_guard() { 4500 if (_zero_trip_guard_opaque_nodes.size() == 0) { 4501 return; 4502 } 4503 Unique_Node_List useful_zero_trip_guard_opaques_nodes; 4504 for (LoopTreeIterator iter(_ltree_root); !iter.done(); iter.next()) { 4505 IdealLoopTree* lpt = iter.current(); 4506 if (lpt->_child == nullptr && lpt->is_counted()) { 4507 CountedLoopNode* head = lpt->_head->as_CountedLoop(); 4508 Node* opaque = head->is_canonical_loop_entry(); 4509 if (opaque != nullptr) { 4510 useful_zero_trip_guard_opaques_nodes.push(opaque); 4511 } 4512 } 4513 } 4514 for (uint i = 0; i < _zero_trip_guard_opaque_nodes.size(); ++i) { 4515 OpaqueZeroTripGuardNode* opaque = ((OpaqueZeroTripGuardNode*)_zero_trip_guard_opaque_nodes.at(i)); 4516 DEBUG_ONLY(CountedLoopNode* guarded_loop = opaque->guarded_loop()); 4517 if (!useful_zero_trip_guard_opaques_nodes.member(opaque)) { 4518 IfNode* iff = opaque->if_node(); 4519 IdealLoopTree* loop = get_loop(iff); 4520 while (loop != _ltree_root && loop != nullptr) { 4521 loop = loop->_parent; 4522 } 4523 if (loop == nullptr) { 4524 // unreachable from _ltree_root: zero trip guard is in a newly discovered infinite loop. 4525 // We can't tell if the opaque node is useful or not 4526 assert(guarded_loop == nullptr || guarded_loop->is_in_infinite_subgraph(), ""); 4527 } else { 4528 assert(guarded_loop == nullptr, ""); 4529 this->_igvn.replace_node(opaque, opaque->in(1)); 4530 } 4531 } else { 4532 assert(guarded_loop != nullptr, ""); 4533 } 4534 } 4535 } 4536 4537 //------------------------process_expensive_nodes----------------------------- 4538 // Expensive nodes have their control input set to prevent the GVN 4539 // from commoning them and as a result forcing the resulting node to 4540 // be in a more frequent path. Use CFG information here, to change the 4541 // control inputs so that some expensive nodes can be commoned while 4542 // not executed more frequently. 4543 bool PhaseIdealLoop::process_expensive_nodes() { 4544 assert(OptimizeExpensiveOps, "optimization off?"); 4545 4546 // Sort nodes to bring similar nodes together 4547 C->sort_expensive_nodes(); 4548 4549 bool progress = false; 4550 4551 for (int i = 0; i < C->expensive_count(); ) { 4552 Node* n = C->expensive_node(i); 4553 int start = i; 4554 // Find nodes similar to n 4555 i++; 4556 for (; i < C->expensive_count() && Compile::cmp_expensive_nodes(n, C->expensive_node(i)) == 0; i++); 4557 int end = i; 4558 // And compare them two by two 4559 for (int j = start; j < end; j++) { 4560 Node* n1 = C->expensive_node(j); 4561 if (is_node_unreachable(n1)) { 4562 continue; 4563 } 4564 for (int k = j+1; k < end; k++) { 4565 Node* n2 = C->expensive_node(k); 4566 if (is_node_unreachable(n2)) { 4567 continue; 4568 } 4569 4570 assert(n1 != n2, "should be pair of nodes"); 4571 4572 Node* c1 = n1->in(0); 4573 Node* c2 = n2->in(0); 4574 4575 Node* parent_c1 = c1; 4576 Node* parent_c2 = c2; 4577 4578 // The call to get_early_ctrl_for_expensive() moves the 4579 // expensive nodes up but stops at loops that are in a if 4580 // branch. See whether we can exit the loop and move above the 4581 // If. 4582 if (c1->is_Loop()) { 4583 parent_c1 = c1->in(1); 4584 } 4585 if (c2->is_Loop()) { 4586 parent_c2 = c2->in(1); 4587 } 4588 4589 if (parent_c1 == parent_c2) { 4590 _igvn._worklist.push(n1); 4591 _igvn._worklist.push(n2); 4592 continue; 4593 } 4594 4595 // Look for identical expensive node up the dominator chain. 4596 if (is_dominator(c1, c2)) { 4597 c2 = c1; 4598 } else if (is_dominator(c2, c1)) { 4599 c1 = c2; 4600 } else if (parent_c1->is_Proj() && parent_c1->in(0)->is_If() && 4601 parent_c2->is_Proj() && parent_c1->in(0) == parent_c2->in(0)) { 4602 // Both branches have the same expensive node so move it up 4603 // before the if. 4604 c1 = c2 = idom(parent_c1->in(0)); 4605 } 4606 // Do the actual moves 4607 if (n1->in(0) != c1) { 4608 _igvn.replace_input_of(n1, 0, c1); 4609 progress = true; 4610 } 4611 if (n2->in(0) != c2) { 4612 _igvn.replace_input_of(n2, 0, c2); 4613 progress = true; 4614 } 4615 } 4616 } 4617 } 4618 4619 return progress; 4620 } 4621 4622 //============================================================================= 4623 //----------------------------build_and_optimize------------------------------- 4624 // Create a PhaseLoop. Build the ideal Loop tree. Map each Ideal Node to 4625 // its corresponding LoopNode. If 'optimize' is true, do some loop cleanups. 4626 void PhaseIdealLoop::build_and_optimize() { 4627 assert(!C->post_loop_opts_phase(), "no loop opts allowed"); 4628 4629 bool do_split_ifs = (_mode == LoopOptsDefault); 4630 bool skip_loop_opts = (_mode == LoopOptsNone); 4631 bool do_max_unroll = (_mode == LoopOptsMaxUnroll); 4632 4633 4634 int old_progress = C->major_progress(); 4635 uint orig_worklist_size = _igvn._worklist.size(); 4636 4637 // Reset major-progress flag for the driver's heuristics 4638 C->clear_major_progress(); 4639 4640 #ifndef PRODUCT 4641 // Capture for later assert 4642 uint unique = C->unique(); 4643 _loop_invokes++; 4644 _loop_work += unique; 4645 #endif 4646 4647 // True if the method has at least 1 irreducible loop 4648 _has_irreducible_loops = false; 4649 4650 _created_loop_node = false; 4651 4652 VectorSet visited; 4653 // Pre-grow the mapping from Nodes to IdealLoopTrees. 4654 _loop_or_ctrl.map(C->unique(), nullptr); 4655 memset(_loop_or_ctrl.adr(), 0, wordSize * C->unique()); 4656 4657 // Pre-build the top-level outermost loop tree entry 4658 _ltree_root = new IdealLoopTree( this, C->root(), C->root() ); 4659 // Do not need a safepoint at the top level 4660 _ltree_root->_has_sfpt = 1; 4661 4662 // Initialize Dominators. 4663 // Checked in clone_loop_predicate() during beautify_loops(). 4664 _idom_size = 0; 4665 _idom = nullptr; 4666 _dom_depth = nullptr; 4667 _dom_stk = nullptr; 4668 4669 // Empty pre-order array 4670 allocate_preorders(); 4671 4672 // Build a loop tree on the fly. Build a mapping from CFG nodes to 4673 // IdealLoopTree entries. Data nodes are NOT walked. 4674 build_loop_tree(); 4675 // Check for bailout, and return 4676 if (C->failing()) { 4677 return; 4678 } 4679 4680 // Verify that the has_loops() flag set at parse time is consistent with the just built loop tree. When the back edge 4681 // is an exception edge, parsing doesn't set has_loops(). 4682 assert(_ltree_root->_child == nullptr || C->has_loops() || C->has_exception_backedge(), "parsing found no loops but there are some"); 4683 // No loops after all 4684 if( !_ltree_root->_child && !_verify_only ) C->set_has_loops(false); 4685 4686 // There should always be an outer loop containing the Root and Return nodes. 4687 // If not, we have a degenerate empty program. Bail out in this case. 4688 if (!has_node(C->root())) { 4689 if (!_verify_only) { 4690 C->clear_major_progress(); 4691 assert(false, "empty program detected during loop optimization"); 4692 C->record_method_not_compilable("empty program detected during loop optimization"); 4693 } 4694 return; 4695 } 4696 4697 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2(); 4698 // Nothing to do, so get out 4699 bool stop_early = !C->has_loops() && !skip_loop_opts && !do_split_ifs && !do_max_unroll && !_verify_me && 4700 !_verify_only && !bs->is_gc_specific_loop_opts_pass(_mode); 4701 bool do_expensive_nodes = C->should_optimize_expensive_nodes(_igvn); 4702 bool strip_mined_loops_expanded = bs->strip_mined_loops_expanded(_mode); 4703 if (stop_early && !do_expensive_nodes) { 4704 return; 4705 } 4706 4707 // Set loop nesting depth 4708 _ltree_root->set_nest( 0 ); 4709 4710 // Split shared headers and insert loop landing pads. 4711 // Do not bother doing this on the Root loop of course. 4712 if( !_verify_me && !_verify_only && _ltree_root->_child ) { 4713 C->print_method(PHASE_BEFORE_BEAUTIFY_LOOPS, 3); 4714 if( _ltree_root->_child->beautify_loops( this ) ) { 4715 // Re-build loop tree! 4716 _ltree_root->_child = nullptr; 4717 _loop_or_ctrl.clear(); 4718 reallocate_preorders(); 4719 build_loop_tree(); 4720 // Check for bailout, and return 4721 if (C->failing()) { 4722 return; 4723 } 4724 // Reset loop nesting depth 4725 _ltree_root->set_nest( 0 ); 4726 4727 C->print_method(PHASE_AFTER_BEAUTIFY_LOOPS, 3); 4728 } 4729 } 4730 4731 // Build Dominators for elision of null checks & loop finding. 4732 // Since nodes do not have a slot for immediate dominator, make 4733 // a persistent side array for that info indexed on node->_idx. 4734 _idom_size = C->unique(); 4735 _idom = NEW_RESOURCE_ARRAY( Node*, _idom_size ); 4736 _dom_depth = NEW_RESOURCE_ARRAY( uint, _idom_size ); 4737 _dom_stk = nullptr; // Allocated on demand in recompute_dom_depth 4738 memset( _dom_depth, 0, _idom_size * sizeof(uint) ); 4739 4740 Dominators(); 4741 4742 if (!_verify_only) { 4743 // As a side effect, Dominators removed any unreachable CFG paths 4744 // into RegionNodes. It doesn't do this test against Root, so 4745 // we do it here. 4746 for( uint i = 1; i < C->root()->req(); i++ ) { 4747 if (!_loop_or_ctrl[C->root()->in(i)->_idx]) { // Dead path into Root? 4748 _igvn.delete_input_of(C->root(), i); 4749 i--; // Rerun same iteration on compressed edges 4750 } 4751 } 4752 4753 // Given dominators, try to find inner loops with calls that must 4754 // always be executed (call dominates loop tail). These loops do 4755 // not need a separate safepoint. 4756 Node_List cisstack; 4757 _ltree_root->check_safepts(visited, cisstack); 4758 } 4759 4760 // Walk the DATA nodes and place into loops. Find earliest control 4761 // node. For CFG nodes, the _loop_or_ctrl array starts out and remains 4762 // holding the associated IdealLoopTree pointer. For DATA nodes, the 4763 // _loop_or_ctrl array holds the earliest legal controlling CFG node. 4764 4765 // Allocate stack with enough space to avoid frequent realloc 4766 int stack_size = (C->live_nodes() >> 1) + 16; // (live_nodes>>1)+16 from Java2D stats 4767 Node_Stack nstack(stack_size); 4768 4769 visited.clear(); 4770 Node_List worklist; 4771 // Don't need C->root() on worklist since 4772 // it will be processed among C->top() inputs 4773 worklist.push(C->top()); 4774 visited.set(C->top()->_idx); // Set C->top() as visited now 4775 build_loop_early( visited, worklist, nstack ); 4776 4777 // Given early legal placement, try finding counted loops. This placement 4778 // is good enough to discover most loop invariants. 4779 if (!_verify_me && !_verify_only && !strip_mined_loops_expanded) { 4780 _ltree_root->counted_loop( this ); 4781 } 4782 4783 // Find latest loop placement. Find ideal loop placement. 4784 visited.clear(); 4785 init_dom_lca_tags(); 4786 // Need C->root() on worklist when processing outs 4787 worklist.push(C->root()); 4788 NOT_PRODUCT( C->verify_graph_edges(); ) 4789 worklist.push(C->top()); 4790 build_loop_late( visited, worklist, nstack ); 4791 if (C->failing()) { return; } 4792 4793 if (_verify_only) { 4794 C->restore_major_progress(old_progress); 4795 assert(C->unique() == unique, "verification _mode made Nodes? ? ?"); 4796 assert(_igvn._worklist.size() == orig_worklist_size, "shouldn't push anything"); 4797 return; 4798 } 4799 4800 // clear out the dead code after build_loop_late 4801 while (_deadlist.size()) { 4802 _igvn.remove_globally_dead_node(_deadlist.pop()); 4803 } 4804 4805 eliminate_useless_zero_trip_guard(); 4806 4807 if (stop_early) { 4808 assert(do_expensive_nodes, "why are we here?"); 4809 if (process_expensive_nodes()) { 4810 // If we made some progress when processing expensive nodes then 4811 // the IGVN may modify the graph in a way that will allow us to 4812 // make some more progress: we need to try processing expensive 4813 // nodes again. 4814 C->set_major_progress(); 4815 } 4816 return; 4817 } 4818 4819 // Some parser-inserted loop predicates could never be used by loop 4820 // predication or they were moved away from loop during some optimizations. 4821 // For example, peeling. Eliminate them before next loop optimizations. 4822 eliminate_useless_predicates(); 4823 4824 #ifndef PRODUCT 4825 C->verify_graph_edges(); 4826 if (_verify_me) { // Nested verify pass? 4827 // Check to see if the verify _mode is broken 4828 assert(C->unique() == unique, "non-optimize _mode made Nodes? ? ?"); 4829 return; 4830 } 4831 DEBUG_ONLY( if (VerifyLoopOptimizations) { verify(); } ); 4832 if (TraceLoopOpts && C->has_loops()) { 4833 _ltree_root->dump(); 4834 } 4835 #endif 4836 4837 if (skip_loop_opts) { 4838 C->restore_major_progress(old_progress); 4839 return; 4840 } 4841 4842 if (do_max_unroll) { 4843 for (LoopTreeIterator iter(_ltree_root); !iter.done(); iter.next()) { 4844 IdealLoopTree* lpt = iter.current(); 4845 if (lpt->is_innermost() && lpt->_allow_optimizations && !lpt->_has_call && lpt->is_counted()) { 4846 lpt->compute_trip_count(this); 4847 if (!lpt->do_one_iteration_loop(this) && 4848 !lpt->do_remove_empty_loop(this)) { 4849 AutoNodeBudget node_budget(this); 4850 if (lpt->_head->as_CountedLoop()->is_normal_loop() && 4851 lpt->policy_maximally_unroll(this)) { 4852 memset( worklist.adr(), 0, worklist.max()*sizeof(Node*) ); 4853 do_maximally_unroll(lpt, worklist); 4854 } 4855 } 4856 } 4857 } 4858 4859 C->restore_major_progress(old_progress); 4860 return; 4861 } 4862 4863 if (bs->optimize_loops(this, _mode, visited, nstack, worklist)) { 4864 return; 4865 } 4866 4867 if (ReassociateInvariants && !C->major_progress()) { 4868 // Reassociate invariants and prep for split_thru_phi 4869 for (LoopTreeIterator iter(_ltree_root); !iter.done(); iter.next()) { 4870 IdealLoopTree* lpt = iter.current(); 4871 if (!lpt->is_loop()) { 4872 continue; 4873 } 4874 Node* head = lpt->_head; 4875 if (!head->is_BaseCountedLoop() || !lpt->is_innermost()) continue; 4876 4877 // check for vectorized loops, any reassociation of invariants was already done 4878 if (head->is_CountedLoop()) { 4879 if (head->as_CountedLoop()->is_unroll_only()) { 4880 continue; 4881 } else { 4882 AutoNodeBudget node_budget(this); 4883 lpt->reassociate_invariants(this); 4884 } 4885 } 4886 // Because RCE opportunities can be masked by split_thru_phi, 4887 // look for RCE candidates and inhibit split_thru_phi 4888 // on just their loop-phi's for this pass of loop opts 4889 if (SplitIfBlocks && do_split_ifs && 4890 head->as_BaseCountedLoop()->is_valid_counted_loop(head->as_BaseCountedLoop()->bt()) && 4891 (lpt->policy_range_check(this, true, T_LONG) || 4892 (head->is_CountedLoop() && lpt->policy_range_check(this, true, T_INT)))) { 4893 lpt->_rce_candidate = 1; // = true 4894 } 4895 } 4896 } 4897 4898 // Check for aggressive application of split-if and other transforms 4899 // that require basic-block info (like cloning through Phi's) 4900 if (!C->major_progress() && SplitIfBlocks && do_split_ifs) { 4901 visited.clear(); 4902 split_if_with_blocks( visited, nstack); 4903 DEBUG_ONLY( if (VerifyLoopOptimizations) { verify(); } ); 4904 } 4905 4906 if (!C->major_progress() && do_expensive_nodes && process_expensive_nodes()) { 4907 C->set_major_progress(); 4908 } 4909 4910 // Perform loop predication before iteration splitting 4911 if (UseLoopPredicate && C->has_loops() && !C->major_progress() && (C->parse_predicate_count() > 0)) { 4912 _ltree_root->_child->loop_predication(this); 4913 } 4914 4915 if (OptimizeFill && UseLoopPredicate && C->has_loops() && !C->major_progress()) { 4916 if (do_intrinsify_fill()) { 4917 C->set_major_progress(); 4918 } 4919 } 4920 4921 // Perform iteration-splitting on inner loops. Split iterations to avoid 4922 // range checks or one-shot null checks. 4923 4924 // If split-if's didn't hack the graph too bad (no CFG changes) 4925 // then do loop opts. 4926 if (C->has_loops() && !C->major_progress()) { 4927 memset( worklist.adr(), 0, worklist.max()*sizeof(Node*) ); 4928 _ltree_root->_child->iteration_split( this, worklist ); 4929 // No verify after peeling! GCM has hoisted code out of the loop. 4930 // After peeling, the hoisted code could sink inside the peeled area. 4931 // The peeling code does not try to recompute the best location for 4932 // all the code before the peeled area, so the verify pass will always 4933 // complain about it. 4934 } 4935 4936 // Check for bailout, and return 4937 if (C->failing()) { 4938 return; 4939 } 4940 4941 // Do verify graph edges in any case 4942 NOT_PRODUCT( C->verify_graph_edges(); ); 4943 4944 if (!do_split_ifs) { 4945 // We saw major progress in Split-If to get here. We forced a 4946 // pass with unrolling and not split-if, however more split-if's 4947 // might make progress. If the unrolling didn't make progress 4948 // then the major-progress flag got cleared and we won't try 4949 // another round of Split-If. In particular the ever-common 4950 // instance-of/check-cast pattern requires at least 2 rounds of 4951 // Split-If to clear out. 4952 C->set_major_progress(); 4953 } 4954 4955 // Repeat loop optimizations if new loops were seen 4956 if (created_loop_node()) { 4957 C->set_major_progress(); 4958 } 4959 4960 // Keep loop predicates and perform optimizations with them 4961 // until no more loop optimizations could be done. 4962 // After that switch predicates off and do more loop optimizations. 4963 if (!C->major_progress() && (C->parse_predicate_count() > 0)) { 4964 C->mark_parse_predicate_nodes_useless(_igvn); 4965 assert(C->parse_predicate_count() == 0, "should be zero now"); 4966 if (TraceLoopOpts) { 4967 tty->print_cr("PredicatesOff"); 4968 } 4969 C->set_major_progress(); 4970 } 4971 4972 // Auto-vectorize main-loop 4973 if (C->do_superword() && C->has_loops() && !C->major_progress()) { 4974 Compile::TracePhase tp(_t_autoVectorize); 4975 4976 // Shared data structures for all AutoVectorizations, to reduce allocations 4977 // of large arrays. 4978 VSharedData vshared; 4979 for (LoopTreeIterator iter(_ltree_root); !iter.done(); iter.next()) { 4980 IdealLoopTree* lpt = iter.current(); 4981 AutoVectorizeStatus status = auto_vectorize(lpt, vshared); 4982 4983 if (status == AutoVectorizeStatus::TriedAndFailed) { 4984 // We tried vectorization, but failed. From now on only unroll the loop. 4985 CountedLoopNode* cl = lpt->_head->as_CountedLoop(); 4986 if (cl->has_passed_slp()) { 4987 C->set_major_progress(); 4988 cl->set_notpassed_slp(); 4989 cl->mark_do_unroll_only(); 4990 } 4991 } 4992 } 4993 } 4994 4995 // Move UnorderedReduction out of counted loop. Can be introduced by AutoVectorization. 4996 if (C->has_loops() && !C->major_progress()) { 4997 for (LoopTreeIterator iter(_ltree_root); !iter.done(); iter.next()) { 4998 IdealLoopTree* lpt = iter.current(); 4999 if (lpt->is_counted() && lpt->is_innermost()) { 5000 move_unordered_reduction_out_of_loop(lpt); 5001 } 5002 } 5003 } 5004 } 5005 5006 #ifndef PRODUCT 5007 //------------------------------print_statistics------------------------------- 5008 int PhaseIdealLoop::_loop_invokes=0;// Count of PhaseIdealLoop invokes 5009 int PhaseIdealLoop::_loop_work=0; // Sum of PhaseIdealLoop x unique 5010 volatile int PhaseIdealLoop::_long_loop_candidates=0; // Number of long loops seen 5011 volatile int PhaseIdealLoop::_long_loop_nests=0; // Number of long loops successfully transformed to a nest 5012 volatile int PhaseIdealLoop::_long_loop_counted_loops=0; // Number of long loops successfully transformed to a counted loop 5013 void PhaseIdealLoop::print_statistics() { 5014 tty->print_cr("PhaseIdealLoop=%d, sum _unique=%d, long loops=%d/%d/%d", _loop_invokes, _loop_work, _long_loop_counted_loops, _long_loop_nests, _long_loop_candidates); 5015 } 5016 #endif 5017 5018 #ifdef ASSERT 5019 // Build a verify-only PhaseIdealLoop, and see that it agrees with "this". 5020 void PhaseIdealLoop::verify() const { 5021 ResourceMark rm; 5022 int old_progress = C->major_progress(); 5023 bool success = true; 5024 5025 PhaseIdealLoop phase_verify(_igvn, this); 5026 if (C->failing_internal()) { 5027 return; 5028 } 5029 5030 // Verify ctrl and idom of every node. 5031 success &= verify_idom_and_nodes(C->root(), &phase_verify); 5032 5033 // Verify loop-tree. 5034 success &= _ltree_root->verify_tree(phase_verify._ltree_root); 5035 5036 assert(success, "VerifyLoopOptimizations failed"); 5037 5038 // Major progress was cleared by creating a verify version of PhaseIdealLoop. 5039 C->restore_major_progress(old_progress); 5040 } 5041 5042 // Perform a BFS starting at n, through all inputs. 5043 // Call verify_idom and verify_node on all nodes of BFS traversal. 5044 bool PhaseIdealLoop::verify_idom_and_nodes(Node* root, const PhaseIdealLoop* phase_verify) const { 5045 Unique_Node_List worklist; 5046 worklist.push(root); 5047 bool success = true; 5048 for (uint i = 0; i < worklist.size(); i++) { 5049 Node* n = worklist.at(i); 5050 // process node 5051 success &= verify_idom(n, phase_verify); 5052 success &= verify_loop_ctrl(n, phase_verify); 5053 // visit inputs 5054 for (uint j = 0; j < n->req(); j++) { 5055 if (n->in(j) != nullptr) { 5056 worklist.push(n->in(j)); 5057 } 5058 } 5059 } 5060 return success; 5061 } 5062 5063 // Verify dominator structure (IDOM). 5064 bool PhaseIdealLoop::verify_idom(Node* n, const PhaseIdealLoop* phase_verify) const { 5065 // Verify IDOM for all CFG nodes (except root). 5066 if (!n->is_CFG() || n->is_Root()) { 5067 return true; // pass 5068 } 5069 5070 if (n->_idx >= _idom_size) { 5071 tty->print("CFG Node with no idom: "); 5072 n->dump(); 5073 return false; // fail 5074 } 5075 5076 Node* id = idom_no_update(n); 5077 Node* id_verify = phase_verify->idom_no_update(n); 5078 if (id != id_verify) { 5079 tty->print("Mismatching idom for node: "); 5080 n->dump(); 5081 tty->print(" We have idom: "); 5082 id->dump(); 5083 tty->print(" Verify has idom: "); 5084 id_verify->dump(); 5085 tty->cr(); 5086 return false; // fail 5087 } 5088 return true; // pass 5089 } 5090 5091 // Verify "_loop_or_ctrl": control and loop membership. 5092 // (0) _loop_or_ctrl[i] == nullptr -> node not reachable. 5093 // (1) has_ctrl -> check lowest bit. 1 -> data node. 0 -> ctrl node. 5094 // (2) has_ctrl true: get_ctrl_no_update returns ctrl of data node. 5095 // (3) has_ctrl false: get_loop_idx returns IdealLoopTree for ctrl node. 5096 bool PhaseIdealLoop::verify_loop_ctrl(Node* n, const PhaseIdealLoop* phase_verify) const { 5097 const uint i = n->_idx; 5098 // The loop-tree was built from def to use (top-down). 5099 // The verification happens from use to def (bottom-up). 5100 // We may thus find nodes during verification that are not in the loop-tree. 5101 if (_loop_or_ctrl[i] == nullptr || phase_verify->_loop_or_ctrl[i] == nullptr) { 5102 if (_loop_or_ctrl[i] != nullptr || phase_verify->_loop_or_ctrl[i] != nullptr) { 5103 tty->print_cr("Was reachable in only one. this %d, verify %d.", 5104 _loop_or_ctrl[i] != nullptr, phase_verify->_loop_or_ctrl[i] != nullptr); 5105 n->dump(); 5106 return false; // fail 5107 } 5108 // Not reachable for both. 5109 return true; // pass 5110 } 5111 5112 if (n->is_CFG() == has_ctrl(n)) { 5113 tty->print_cr("Exactly one should be true: %d for is_CFG, %d for has_ctrl.", n->is_CFG(), has_ctrl(n)); 5114 n->dump(); 5115 return false; // fail 5116 } 5117 5118 if (has_ctrl(n) != phase_verify->has_ctrl(n)) { 5119 tty->print_cr("Mismatch has_ctrl: %d for this, %d for verify.", has_ctrl(n), phase_verify->has_ctrl(n)); 5120 n->dump(); 5121 return false; // fail 5122 } else if (has_ctrl(n)) { 5123 assert(phase_verify->has_ctrl(n), "sanity"); 5124 // n is a data node. 5125 // Verify that its ctrl is the same. 5126 5127 // Broken part of VerifyLoopOptimizations (A) 5128 // Reason: 5129 // BUG, wrong control set for example in 5130 // PhaseIdealLoop::split_if_with_blocks 5131 // at "set_ctrl(x, new_ctrl);" 5132 /* 5133 if( _loop_or_ctrl[i] != loop_verify->_loop_or_ctrl[i] && 5134 get_ctrl_no_update(n) != loop_verify->get_ctrl_no_update(n) ) { 5135 tty->print("Mismatched control setting for: "); 5136 n->dump(); 5137 if( fail++ > 10 ) return; 5138 Node *c = get_ctrl_no_update(n); 5139 tty->print("We have it as: "); 5140 if( c->in(0) ) c->dump(); 5141 else tty->print_cr("N%d",c->_idx); 5142 tty->print("Verify thinks: "); 5143 if( loop_verify->has_ctrl(n) ) 5144 loop_verify->get_ctrl_no_update(n)->dump(); 5145 else 5146 loop_verify->get_loop_idx(n)->dump(); 5147 tty->cr(); 5148 } 5149 */ 5150 return true; // pass 5151 } else { 5152 assert(!phase_verify->has_ctrl(n), "sanity"); 5153 // n is a ctrl node. 5154 // Verify that not has_ctrl, and that get_loop_idx is the same. 5155 5156 // Broken part of VerifyLoopOptimizations (B) 5157 // Reason: 5158 // NeverBranch node for example is added to loop outside its scope. 5159 // Once we run build_loop_tree again, it is added to the correct loop. 5160 /* 5161 if (!C->major_progress()) { 5162 // Loop selection can be messed up if we did a major progress 5163 // operation, like split-if. Do not verify in that case. 5164 IdealLoopTree *us = get_loop_idx(n); 5165 IdealLoopTree *them = loop_verify->get_loop_idx(n); 5166 if( us->_head != them->_head || us->_tail != them->_tail ) { 5167 tty->print("Unequals loops for: "); 5168 n->dump(); 5169 if( fail++ > 10 ) return; 5170 tty->print("We have it as: "); 5171 us->dump(); 5172 tty->print("Verify thinks: "); 5173 them->dump(); 5174 tty->cr(); 5175 } 5176 } 5177 */ 5178 return true; // pass 5179 } 5180 } 5181 5182 static int compare_tree(IdealLoopTree* const& a, IdealLoopTree* const& b) { 5183 assert(a != nullptr && b != nullptr, "must be"); 5184 return a->_head->_idx - b->_head->_idx; 5185 } 5186 5187 GrowableArray<IdealLoopTree*> IdealLoopTree::collect_sorted_children() const { 5188 GrowableArray<IdealLoopTree*> children; 5189 IdealLoopTree* child = _child; 5190 while (child != nullptr) { 5191 assert(child->_parent == this, "all must be children of this"); 5192 children.insert_sorted<compare_tree>(child); 5193 child = child->_next; 5194 } 5195 return children; 5196 } 5197 5198 // Verify that tree structures match. Because the CFG can change, siblings 5199 // within the loop tree can be reordered. We attempt to deal with that by 5200 // reordering the verify's loop tree if possible. 5201 bool IdealLoopTree::verify_tree(IdealLoopTree* loop_verify) const { 5202 assert(_head == loop_verify->_head, "mismatched loop head"); 5203 assert(this->_parent != nullptr || this->_next == nullptr, "is_root_loop implies has_no_sibling"); 5204 5205 // Collect the children 5206 GrowableArray<IdealLoopTree*> children = collect_sorted_children(); 5207 GrowableArray<IdealLoopTree*> children_verify = loop_verify->collect_sorted_children(); 5208 5209 bool success = true; 5210 5211 // Compare the two children lists 5212 for (int i = 0, j = 0; i < children.length() || j < children_verify.length(); ) { 5213 IdealLoopTree* child = nullptr; 5214 IdealLoopTree* child_verify = nullptr; 5215 // Read from both lists, if possible. 5216 if (i < children.length()) { 5217 child = children.at(i); 5218 } 5219 if (j < children_verify.length()) { 5220 child_verify = children_verify.at(j); 5221 } 5222 assert(child != nullptr || child_verify != nullptr, "must find at least one"); 5223 if (child != nullptr && child_verify != nullptr && child->_head != child_verify->_head) { 5224 // We found two non-equal children. Select the smaller one. 5225 if (child->_head->_idx < child_verify->_head->_idx) { 5226 child_verify = nullptr; 5227 } else { 5228 child = nullptr; 5229 } 5230 } 5231 // Process the two children, or potentially log the failure if we only found one. 5232 if (child_verify == nullptr) { 5233 if (child->_irreducible && Compile::current()->major_progress()) { 5234 // Irreducible loops can pick a different header (one of its entries). 5235 } else { 5236 tty->print_cr("We have a loop that verify does not have"); 5237 child->dump(); 5238 success = false; 5239 } 5240 i++; // step for this 5241 } else if (child == nullptr) { 5242 if (child_verify->_irreducible && Compile::current()->major_progress()) { 5243 // Irreducible loops can pick a different header (one of its entries). 5244 } else if (child_verify->_head->as_Region()->is_in_infinite_subgraph()) { 5245 // Infinite loops do not get attached to the loop-tree on their first visit. 5246 // "this" runs before "loop_verify". It is thus possible that we find the 5247 // infinite loop only for "child_verify". Only finding it with "child" would 5248 // mean that we lost it, which is not ok. 5249 } else { 5250 tty->print_cr("Verify has a loop that we do not have"); 5251 child_verify->dump(); 5252 success = false; 5253 } 5254 j++; // step for verify 5255 } else { 5256 assert(child->_head == child_verify->_head, "We have both and they are equal"); 5257 success &= child->verify_tree(child_verify); // Recursion 5258 i++; // step for this 5259 j++; // step for verify 5260 } 5261 } 5262 5263 // Broken part of VerifyLoopOptimizations (D) 5264 // Reason: 5265 // split_if has to update the _tail, if it is modified. But that is done by 5266 // checking to what loop the iff belongs to. That info can be wrong, and then 5267 // we do not update the _tail correctly. 5268 /* 5269 Node *tail = _tail; // Inline a non-updating version of 5270 while( !tail->in(0) ) // the 'tail()' call. 5271 tail = tail->in(1); 5272 assert( tail == loop->_tail, "mismatched loop tail" ); 5273 */ 5274 5275 if (_head->is_CountedLoop()) { 5276 CountedLoopNode *cl = _head->as_CountedLoop(); 5277 5278 Node* ctrl = cl->init_control(); 5279 Node* back = cl->back_control(); 5280 assert(ctrl != nullptr && ctrl->is_CFG(), "sane loop in-ctrl"); 5281 assert(back != nullptr && back->is_CFG(), "sane loop backedge"); 5282 cl->loopexit(); // assert implied 5283 } 5284 5285 // Broken part of VerifyLoopOptimizations (E) 5286 // Reason: 5287 // PhaseIdealLoop::split_thru_region creates new nodes for loop that are not added 5288 // to the loop body. Or maybe they are not added to the correct loop. 5289 // at "Node* x = n->clone();" 5290 /* 5291 // Innermost loops need to verify loop bodies, 5292 // but only if no 'major_progress' 5293 int fail = 0; 5294 if (!Compile::current()->major_progress() && _child == nullptr) { 5295 for( uint i = 0; i < _body.size(); i++ ) { 5296 Node *n = _body.at(i); 5297 if (n->outcnt() == 0) continue; // Ignore dead 5298 uint j; 5299 for( j = 0; j < loop->_body.size(); j++ ) 5300 if( loop->_body.at(j) == n ) 5301 break; 5302 if( j == loop->_body.size() ) { // Not found in loop body 5303 // Last ditch effort to avoid assertion: Its possible that we 5304 // have some users (so outcnt not zero) but are still dead. 5305 // Try to find from root. 5306 if (Compile::current()->root()->find(n->_idx)) { 5307 fail++; 5308 tty->print("We have that verify does not: "); 5309 n->dump(); 5310 } 5311 } 5312 } 5313 for( uint i2 = 0; i2 < loop->_body.size(); i2++ ) { 5314 Node *n = loop->_body.at(i2); 5315 if (n->outcnt() == 0) continue; // Ignore dead 5316 uint j; 5317 for( j = 0; j < _body.size(); j++ ) 5318 if( _body.at(j) == n ) 5319 break; 5320 if( j == _body.size() ) { // Not found in loop body 5321 // Last ditch effort to avoid assertion: Its possible that we 5322 // have some users (so outcnt not zero) but are still dead. 5323 // Try to find from root. 5324 if (Compile::current()->root()->find(n->_idx)) { 5325 fail++; 5326 tty->print("Verify has that we do not: "); 5327 n->dump(); 5328 } 5329 } 5330 } 5331 assert( !fail, "loop body mismatch" ); 5332 } 5333 */ 5334 return success; 5335 } 5336 #endif 5337 5338 //------------------------------set_idom--------------------------------------- 5339 void PhaseIdealLoop::set_idom(Node* d, Node* n, uint dom_depth) { 5340 _nesting.check(); // Check if a potential reallocation in the resource arena is safe 5341 uint idx = d->_idx; 5342 if (idx >= _idom_size) { 5343 uint newsize = next_power_of_2(idx); 5344 _idom = REALLOC_RESOURCE_ARRAY( Node*, _idom,_idom_size,newsize); 5345 _dom_depth = REALLOC_RESOURCE_ARRAY( uint, _dom_depth,_idom_size,newsize); 5346 memset( _dom_depth + _idom_size, 0, (newsize - _idom_size) * sizeof(uint) ); 5347 _idom_size = newsize; 5348 } 5349 _idom[idx] = n; 5350 _dom_depth[idx] = dom_depth; 5351 } 5352 5353 //------------------------------recompute_dom_depth--------------------------------------- 5354 // The dominator tree is constructed with only parent pointers. 5355 // This recomputes the depth in the tree by first tagging all 5356 // nodes as "no depth yet" marker. The next pass then runs up 5357 // the dom tree from each node marked "no depth yet", and computes 5358 // the depth on the way back down. 5359 void PhaseIdealLoop::recompute_dom_depth() { 5360 uint no_depth_marker = C->unique(); 5361 uint i; 5362 // Initialize depth to "no depth yet" and realize all lazy updates 5363 for (i = 0; i < _idom_size; i++) { 5364 // Only indices with a _dom_depth has a Node* or null (otherwise uninitialized). 5365 if (_dom_depth[i] > 0 && _idom[i] != nullptr) { 5366 _dom_depth[i] = no_depth_marker; 5367 5368 // heal _idom if it has a fwd mapping in _loop_or_ctrl 5369 if (_idom[i]->in(0) == nullptr) { 5370 idom(i); 5371 } 5372 } 5373 } 5374 if (_dom_stk == nullptr) { 5375 uint init_size = C->live_nodes() / 100; // Guess that 1/100 is a reasonable initial size. 5376 if (init_size < 10) init_size = 10; 5377 _dom_stk = new GrowableArray<uint>(init_size); 5378 } 5379 // Compute new depth for each node. 5380 for (i = 0; i < _idom_size; i++) { 5381 uint j = i; 5382 // Run up the dom tree to find a node with a depth 5383 while (_dom_depth[j] == no_depth_marker) { 5384 _dom_stk->push(j); 5385 j = _idom[j]->_idx; 5386 } 5387 // Compute the depth on the way back down this tree branch 5388 uint dd = _dom_depth[j] + 1; 5389 while (_dom_stk->length() > 0) { 5390 uint j = _dom_stk->pop(); 5391 _dom_depth[j] = dd; 5392 dd++; 5393 } 5394 } 5395 } 5396 5397 //------------------------------sort------------------------------------------- 5398 // Insert 'loop' into the existing loop tree. 'innermost' is a leaf of the 5399 // loop tree, not the root. 5400 IdealLoopTree *PhaseIdealLoop::sort( IdealLoopTree *loop, IdealLoopTree *innermost ) { 5401 if( !innermost ) return loop; // New innermost loop 5402 5403 int loop_preorder = get_preorder(loop->_head); // Cache pre-order number 5404 assert( loop_preorder, "not yet post-walked loop" ); 5405 IdealLoopTree **pp = &innermost; // Pointer to previous next-pointer 5406 IdealLoopTree *l = *pp; // Do I go before or after 'l'? 5407 5408 // Insert at start of list 5409 while( l ) { // Insertion sort based on pre-order 5410 if( l == loop ) return innermost; // Already on list! 5411 int l_preorder = get_preorder(l->_head); // Cache pre-order number 5412 assert( l_preorder, "not yet post-walked l" ); 5413 // Check header pre-order number to figure proper nesting 5414 if( loop_preorder > l_preorder ) 5415 break; // End of insertion 5416 // If headers tie (e.g., shared headers) check tail pre-order numbers. 5417 // Since I split shared headers, you'd think this could not happen. 5418 // BUT: I must first do the preorder numbering before I can discover I 5419 // have shared headers, so the split headers all get the same preorder 5420 // number as the RegionNode they split from. 5421 if( loop_preorder == l_preorder && 5422 get_preorder(loop->_tail) < get_preorder(l->_tail) ) 5423 break; // Also check for shared headers (same pre#) 5424 pp = &l->_parent; // Chain up list 5425 l = *pp; 5426 } 5427 // Link into list 5428 // Point predecessor to me 5429 *pp = loop; 5430 // Point me to successor 5431 IdealLoopTree *p = loop->_parent; 5432 loop->_parent = l; // Point me to successor 5433 if( p ) sort( p, innermost ); // Insert my parents into list as well 5434 return innermost; 5435 } 5436 5437 //------------------------------build_loop_tree-------------------------------- 5438 // I use a modified Vick/Tarjan algorithm. I need pre- and a post- visit 5439 // bits. The _loop_or_ctrl[] array is mapped by Node index and holds a null for 5440 // not-yet-pre-walked, pre-order # for pre-but-not-post-walked and holds the 5441 // tightest enclosing IdealLoopTree for post-walked. 5442 // 5443 // During my forward walk I do a short 1-layer lookahead to see if I can find 5444 // a loop backedge with that doesn't have any work on the backedge. This 5445 // helps me construct nested loops with shared headers better. 5446 // 5447 // Once I've done the forward recursion, I do the post-work. For each child 5448 // I check to see if there is a backedge. Backedges define a loop! I 5449 // insert an IdealLoopTree at the target of the backedge. 5450 // 5451 // During the post-work I also check to see if I have several children 5452 // belonging to different loops. If so, then this Node is a decision point 5453 // where control flow can choose to change loop nests. It is at this 5454 // decision point where I can figure out how loops are nested. At this 5455 // time I can properly order the different loop nests from my children. 5456 // Note that there may not be any backedges at the decision point! 5457 // 5458 // Since the decision point can be far removed from the backedges, I can't 5459 // order my loops at the time I discover them. Thus at the decision point 5460 // I need to inspect loop header pre-order numbers to properly nest my 5461 // loops. This means I need to sort my childrens' loops by pre-order. 5462 // The sort is of size number-of-control-children, which generally limits 5463 // it to size 2 (i.e., I just choose between my 2 target loops). 5464 void PhaseIdealLoop::build_loop_tree() { 5465 // Allocate stack of size C->live_nodes()/2 to avoid frequent realloc 5466 GrowableArray <Node *> bltstack(C->live_nodes() >> 1); 5467 Node *n = C->root(); 5468 bltstack.push(n); 5469 int pre_order = 1; 5470 int stack_size; 5471 5472 while ( ( stack_size = bltstack.length() ) != 0 ) { 5473 n = bltstack.top(); // Leave node on stack 5474 if ( !is_visited(n) ) { 5475 // ---- Pre-pass Work ---- 5476 // Pre-walked but not post-walked nodes need a pre_order number. 5477 5478 set_preorder_visited( n, pre_order ); // set as visited 5479 5480 // ---- Scan over children ---- 5481 // Scan first over control projections that lead to loop headers. 5482 // This helps us find inner-to-outer loops with shared headers better. 5483 5484 // Scan children's children for loop headers. 5485 for ( int i = n->outcnt() - 1; i >= 0; --i ) { 5486 Node* m = n->raw_out(i); // Child 5487 if( m->is_CFG() && !is_visited(m) ) { // Only for CFG children 5488 // Scan over children's children to find loop 5489 for (DUIterator_Fast jmax, j = m->fast_outs(jmax); j < jmax; j++) { 5490 Node* l = m->fast_out(j); 5491 if( is_visited(l) && // Been visited? 5492 !is_postvisited(l) && // But not post-visited 5493 get_preorder(l) < pre_order ) { // And smaller pre-order 5494 // Found! Scan the DFS down this path before doing other paths 5495 bltstack.push(m); 5496 break; 5497 } 5498 } 5499 } 5500 } 5501 pre_order++; 5502 } 5503 else if ( !is_postvisited(n) ) { 5504 // Note: build_loop_tree_impl() adds out edges on rare occasions, 5505 // such as com.sun.rsasign.am::a. 5506 // For non-recursive version, first, process current children. 5507 // On next iteration, check if additional children were added. 5508 for ( int k = n->outcnt() - 1; k >= 0; --k ) { 5509 Node* u = n->raw_out(k); 5510 if ( u->is_CFG() && !is_visited(u) ) { 5511 bltstack.push(u); 5512 } 5513 } 5514 if ( bltstack.length() == stack_size ) { 5515 // There were no additional children, post visit node now 5516 (void)bltstack.pop(); // Remove node from stack 5517 pre_order = build_loop_tree_impl(n, pre_order); 5518 // Check for bailout 5519 if (C->failing()) { 5520 return; 5521 } 5522 // Check to grow _preorders[] array for the case when 5523 // build_loop_tree_impl() adds new nodes. 5524 check_grow_preorders(); 5525 } 5526 } 5527 else { 5528 (void)bltstack.pop(); // Remove post-visited node from stack 5529 } 5530 } 5531 DEBUG_ONLY(verify_regions_in_irreducible_loops();) 5532 } 5533 5534 //------------------------------build_loop_tree_impl--------------------------- 5535 int PhaseIdealLoop::build_loop_tree_impl(Node* n, int pre_order) { 5536 // ---- Post-pass Work ---- 5537 // Pre-walked but not post-walked nodes need a pre_order number. 5538 5539 // Tightest enclosing loop for this Node 5540 IdealLoopTree *innermost = nullptr; 5541 5542 // For all children, see if any edge is a backedge. If so, make a loop 5543 // for it. Then find the tightest enclosing loop for the self Node. 5544 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) { 5545 Node* m = n->fast_out(i); // Child 5546 if (n == m) continue; // Ignore control self-cycles 5547 if (!m->is_CFG()) continue;// Ignore non-CFG edges 5548 5549 IdealLoopTree *l; // Child's loop 5550 if (!is_postvisited(m)) { // Child visited but not post-visited? 5551 // Found a backedge 5552 assert(get_preorder(m) < pre_order, "should be backedge"); 5553 // Check for the RootNode, which is already a LoopNode and is allowed 5554 // to have multiple "backedges". 5555 if (m == C->root()) { // Found the root? 5556 l = _ltree_root; // Root is the outermost LoopNode 5557 } else { // Else found a nested loop 5558 // Insert a LoopNode to mark this loop. 5559 l = new IdealLoopTree(this, m, n); 5560 } // End of Else found a nested loop 5561 if (!has_loop(m)) { // If 'm' does not already have a loop set 5562 set_loop(m, l); // Set loop header to loop now 5563 } 5564 } else { // Else not a nested loop 5565 if (!_loop_or_ctrl[m->_idx]) continue; // Dead code has no loop 5566 IdealLoopTree* m_loop = get_loop(m); 5567 l = m_loop; // Get previously determined loop 5568 // If successor is header of a loop (nest), move up-loop till it 5569 // is a member of some outer enclosing loop. Since there are no 5570 // shared headers (I've split them already) I only need to go up 5571 // at most 1 level. 5572 while (l && l->_head == m) { // Successor heads loop? 5573 l = l->_parent; // Move up 1 for me 5574 } 5575 // If this loop is not properly parented, then this loop 5576 // has no exit path out, i.e. its an infinite loop. 5577 if (!l) { 5578 // Make loop "reachable" from root so the CFG is reachable. Basically 5579 // insert a bogus loop exit that is never taken. 'm', the loop head, 5580 // points to 'n', one (of possibly many) fall-in paths. There may be 5581 // many backedges as well. 5582 5583 if (!_verify_only) { 5584 // Insert the NeverBranch between 'm' and it's control user. 5585 NeverBranchNode *iff = new NeverBranchNode( m ); 5586 _igvn.register_new_node_with_optimizer(iff); 5587 set_loop(iff, m_loop); 5588 Node *if_t = new CProjNode( iff, 0 ); 5589 _igvn.register_new_node_with_optimizer(if_t); 5590 set_loop(if_t, m_loop); 5591 5592 Node* cfg = nullptr; // Find the One True Control User of m 5593 for (DUIterator_Fast jmax, j = m->fast_outs(jmax); j < jmax; j++) { 5594 Node* x = m->fast_out(j); 5595 if (x->is_CFG() && x != m && x != iff) 5596 { cfg = x; break; } 5597 } 5598 assert(cfg != nullptr, "must find the control user of m"); 5599 uint k = 0; // Probably cfg->in(0) 5600 while( cfg->in(k) != m ) k++; // But check in case cfg is a Region 5601 _igvn.replace_input_of(cfg, k, if_t); // Now point to NeverBranch 5602 5603 // Now create the never-taken loop exit 5604 Node *if_f = new CProjNode( iff, 1 ); 5605 _igvn.register_new_node_with_optimizer(if_f); 5606 set_loop(if_f, _ltree_root); 5607 // Find frame ptr for Halt. Relies on the optimizer 5608 // V-N'ing. Easier and quicker than searching through 5609 // the program structure. 5610 Node *frame = new ParmNode( C->start(), TypeFunc::FramePtr ); 5611 _igvn.register_new_node_with_optimizer(frame); 5612 // Halt & Catch Fire 5613 Node* halt = new HaltNode(if_f, frame, "never-taken loop exit reached"); 5614 _igvn.register_new_node_with_optimizer(halt); 5615 set_loop(halt, _ltree_root); 5616 _igvn.add_input_to(C->root(), halt); 5617 } 5618 set_loop(C->root(), _ltree_root); 5619 // move to outer most loop with same header 5620 l = m_loop; 5621 while (true) { 5622 IdealLoopTree* next = l->_parent; 5623 if (next == nullptr || next->_head != m) { 5624 break; 5625 } 5626 l = next; 5627 } 5628 // properly insert infinite loop in loop tree 5629 sort(_ltree_root, l); 5630 // fix child link from parent 5631 IdealLoopTree* p = l->_parent; 5632 l->_next = p->_child; 5633 p->_child = l; 5634 // code below needs enclosing loop 5635 l = l->_parent; 5636 } 5637 } 5638 if (is_postvisited(l->_head)) { 5639 // We are currently visiting l, but its head has already been post-visited. 5640 // l is irreducible: we just found a second entry m. 5641 _has_irreducible_loops = true; 5642 RegionNode* secondary_entry = m->as_Region(); 5643 DEBUG_ONLY(secondary_entry->verify_can_be_irreducible_entry();) 5644 5645 // Walk up the loop-tree, mark all loops that are already post-visited as irreducible 5646 // Since m is a secondary entry to them all. 5647 while( is_postvisited(l->_head) ) { 5648 l->_irreducible = 1; // = true 5649 RegionNode* head = l->_head->as_Region(); 5650 DEBUG_ONLY(head->verify_can_be_irreducible_entry();) 5651 l = l->_parent; 5652 // Check for bad CFG here to prevent crash, and bailout of compile 5653 if (l == nullptr) { 5654 #ifndef PRODUCT 5655 if (TraceLoopOpts) { 5656 tty->print_cr("bailout: unhandled CFG: infinite irreducible loop"); 5657 m->dump(); 5658 } 5659 #endif 5660 // This is a rare case that we do not want to handle in C2. 5661 C->record_method_not_compilable("unhandled CFG detected during loop optimization"); 5662 return pre_order; 5663 } 5664 } 5665 } 5666 if (!_verify_only) { 5667 C->set_has_irreducible_loop(_has_irreducible_loops); 5668 } 5669 5670 // This Node might be a decision point for loops. It is only if 5671 // it's children belong to several different loops. The sort call 5672 // does a trivial amount of work if there is only 1 child or all 5673 // children belong to the same loop. If however, the children 5674 // belong to different loops, the sort call will properly set the 5675 // _parent pointers to show how the loops nest. 5676 // 5677 // In any case, it returns the tightest enclosing loop. 5678 innermost = sort( l, innermost ); 5679 } 5680 5681 // Def-use info will have some dead stuff; dead stuff will have no 5682 // loop decided on. 5683 5684 // Am I a loop header? If so fix up my parent's child and next ptrs. 5685 if( innermost && innermost->_head == n ) { 5686 assert( get_loop(n) == innermost, "" ); 5687 IdealLoopTree *p = innermost->_parent; 5688 IdealLoopTree *l = innermost; 5689 while (p && l->_head == n) { 5690 l->_next = p->_child; // Put self on parents 'next child' 5691 p->_child = l; // Make self as first child of parent 5692 l = p; // Now walk up the parent chain 5693 p = l->_parent; 5694 } 5695 } else { 5696 // Note that it is possible for a LoopNode to reach here, if the 5697 // backedge has been made unreachable (hence the LoopNode no longer 5698 // denotes a Loop, and will eventually be removed). 5699 5700 // Record tightest enclosing loop for self. Mark as post-visited. 5701 set_loop(n, innermost); 5702 // Also record has_call flag early on 5703 if (innermost) { 5704 if( n->is_Call() && !n->is_CallLeaf() && !n->is_macro() ) { 5705 // Do not count uncommon calls 5706 if( !n->is_CallStaticJava() || !n->as_CallStaticJava()->_name ) { 5707 Node *iff = n->in(0)->in(0); 5708 // No any calls for vectorized loops. 5709 if (C->do_superword() || 5710 !iff->is_If() || 5711 (n->in(0)->Opcode() == Op_IfFalse && (1.0 - iff->as_If()->_prob) >= 0.01) || 5712 iff->as_If()->_prob >= 0.01) { 5713 innermost->_has_call = 1; 5714 } 5715 } 5716 } else if( n->is_Allocate() && n->as_Allocate()->_is_scalar_replaceable ) { 5717 // Disable loop optimizations if the loop has a scalar replaceable 5718 // allocation. This disabling may cause a potential performance lost 5719 // if the allocation is not eliminated for some reason. 5720 innermost->_allow_optimizations = false; 5721 innermost->_has_call = 1; // = true 5722 } else if (n->Opcode() == Op_SafePoint) { 5723 // Record all safepoints in this loop. 5724 if (innermost->_safepts == nullptr) innermost->_safepts = new Node_List(); 5725 innermost->_safepts->push(n); 5726 } 5727 } 5728 } 5729 5730 // Flag as post-visited now 5731 set_postvisited(n); 5732 return pre_order; 5733 } 5734 5735 #ifdef ASSERT 5736 //--------------------------verify_regions_in_irreducible_loops---------------- 5737 // Iterate down from Root through CFG, verify for every region: 5738 // if it is in an irreducible loop it must be marked as such 5739 void PhaseIdealLoop::verify_regions_in_irreducible_loops() { 5740 ResourceMark rm; 5741 if (!_has_irreducible_loops) { 5742 // last build_loop_tree has not found any irreducible loops 5743 // hence no region has to be marked is_in_irreduible_loop 5744 return; 5745 } 5746 5747 RootNode* root = C->root(); 5748 Unique_Node_List worklist; // visit all nodes once 5749 worklist.push(root); 5750 bool failure = false; 5751 for (uint i = 0; i < worklist.size(); i++) { 5752 Node* n = worklist.at(i); 5753 if (n->is_Region()) { 5754 RegionNode* region = n->as_Region(); 5755 if (is_in_irreducible_loop(region) && 5756 region->loop_status() == RegionNode::LoopStatus::Reducible) { 5757 failure = true; 5758 tty->print("irreducible! "); 5759 region->dump(); 5760 } 5761 } 5762 for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++) { 5763 Node* use = n->fast_out(j); 5764 if (use->is_CFG()) { 5765 worklist.push(use); // push if was not pushed before 5766 } 5767 } 5768 } 5769 assert(!failure, "region in irreducible loop was marked as reducible"); 5770 } 5771 5772 //---------------------------is_in_irreducible_loop------------------------- 5773 // Analogous to ciTypeFlow::Block::is_in_irreducible_loop 5774 bool PhaseIdealLoop::is_in_irreducible_loop(RegionNode* region) { 5775 if (!_has_irreducible_loops) { 5776 return false; // no irreducible loop in graph 5777 } 5778 IdealLoopTree* l = get_loop(region); // l: innermost loop that contains region 5779 do { 5780 if (l->_irreducible) { 5781 return true; // found it 5782 } 5783 if (l == _ltree_root) { 5784 return false; // reached root, terimnate 5785 } 5786 l = l->_parent; 5787 } while (l != nullptr); 5788 assert(region->is_in_infinite_subgraph(), "must be in infinite subgraph"); 5789 // We have "l->_parent == nullptr", which happens only for infinite loops, 5790 // where no parent is attached to the loop. We did not find any irreducible 5791 // loop from this block out to lp. Thus lp only has one entry, and no exit 5792 // (it is infinite and reducible). We can always rewrite an infinite loop 5793 // that is nested inside other loops: 5794 // while(condition) { infinite_loop; } 5795 // with an equivalent program where the infinite loop is an outermost loop 5796 // that is not nested in any loop: 5797 // while(condition) { break; } infinite_loop; 5798 // Thus, we can understand lp as an outermost loop, and can terminate and 5799 // conclude: this block is in no irreducible loop. 5800 return false; 5801 } 5802 #endif 5803 5804 //------------------------------build_loop_early------------------------------- 5805 // Put Data nodes into some loop nest, by setting the _loop_or_ctrl[]->loop mapping. 5806 // First pass computes the earliest controlling node possible. This is the 5807 // controlling input with the deepest dominating depth. 5808 void PhaseIdealLoop::build_loop_early( VectorSet &visited, Node_List &worklist, Node_Stack &nstack ) { 5809 while (worklist.size() != 0) { 5810 // Use local variables nstack_top_n & nstack_top_i to cache values 5811 // on nstack's top. 5812 Node *nstack_top_n = worklist.pop(); 5813 uint nstack_top_i = 0; 5814 //while_nstack_nonempty: 5815 while (true) { 5816 // Get parent node and next input's index from stack's top. 5817 Node *n = nstack_top_n; 5818 uint i = nstack_top_i; 5819 uint cnt = n->req(); // Count of inputs 5820 if (i == 0) { // Pre-process the node. 5821 if( has_node(n) && // Have either loop or control already? 5822 !has_ctrl(n) ) { // Have loop picked out already? 5823 // During "merge_many_backedges" we fold up several nested loops 5824 // into a single loop. This makes the members of the original 5825 // loop bodies pointing to dead loops; they need to move up 5826 // to the new UNION'd larger loop. I set the _head field of these 5827 // dead loops to null and the _parent field points to the owning 5828 // loop. Shades of UNION-FIND algorithm. 5829 IdealLoopTree *ilt; 5830 while( !(ilt = get_loop(n))->_head ) { 5831 // Normally I would use a set_loop here. But in this one special 5832 // case, it is legal (and expected) to change what loop a Node 5833 // belongs to. 5834 _loop_or_ctrl.map(n->_idx, (Node*)(ilt->_parent)); 5835 } 5836 // Remove safepoints ONLY if I've already seen I don't need one. 5837 // (the old code here would yank a 2nd safepoint after seeing a 5838 // first one, even though the 1st did not dominate in the loop body 5839 // and thus could be avoided indefinitely) 5840 if( !_verify_only && !_verify_me && ilt->_has_sfpt && n->Opcode() == Op_SafePoint && 5841 is_deleteable_safept(n)) { 5842 Node *in = n->in(TypeFunc::Control); 5843 lazy_replace(n,in); // Pull safepoint now 5844 if (ilt->_safepts != nullptr) { 5845 ilt->_safepts->yank(n); 5846 } 5847 // Carry on with the recursion "as if" we are walking 5848 // only the control input 5849 if( !visited.test_set( in->_idx ) ) { 5850 worklist.push(in); // Visit this guy later, using worklist 5851 } 5852 // Get next node from nstack: 5853 // - skip n's inputs processing by setting i > cnt; 5854 // - we also will not call set_early_ctrl(n) since 5855 // has_node(n) == true (see the condition above). 5856 i = cnt + 1; 5857 } 5858 } 5859 } // if (i == 0) 5860 5861 // Visit all inputs 5862 bool done = true; // Assume all n's inputs will be processed 5863 while (i < cnt) { 5864 Node *in = n->in(i); 5865 ++i; 5866 if (in == nullptr) continue; 5867 if (in->pinned() && !in->is_CFG()) 5868 set_ctrl(in, in->in(0)); 5869 int is_visited = visited.test_set( in->_idx ); 5870 if (!has_node(in)) { // No controlling input yet? 5871 assert( !in->is_CFG(), "CFG Node with no controlling input?" ); 5872 assert( !is_visited, "visit only once" ); 5873 nstack.push(n, i); // Save parent node and next input's index. 5874 nstack_top_n = in; // Process current input now. 5875 nstack_top_i = 0; 5876 done = false; // Not all n's inputs processed. 5877 break; // continue while_nstack_nonempty; 5878 } else if (!is_visited) { 5879 // This guy has a location picked out for him, but has not yet 5880 // been visited. Happens to all CFG nodes, for instance. 5881 // Visit him using the worklist instead of recursion, to break 5882 // cycles. Since he has a location already we do not need to 5883 // find his location before proceeding with the current Node. 5884 worklist.push(in); // Visit this guy later, using worklist 5885 } 5886 } 5887 if (done) { 5888 // All of n's inputs have been processed, complete post-processing. 5889 5890 // Compute earliest point this Node can go. 5891 // CFG, Phi, pinned nodes already know their controlling input. 5892 if (!has_node(n)) { 5893 // Record earliest legal location 5894 set_early_ctrl(n, false); 5895 } 5896 if (nstack.is_empty()) { 5897 // Finished all nodes on stack. 5898 // Process next node on the worklist. 5899 break; 5900 } 5901 // Get saved parent node and next input's index. 5902 nstack_top_n = nstack.node(); 5903 nstack_top_i = nstack.index(); 5904 nstack.pop(); 5905 } 5906 } // while (true) 5907 } 5908 } 5909 5910 //------------------------------dom_lca_internal-------------------------------- 5911 // Pair-wise LCA 5912 Node *PhaseIdealLoop::dom_lca_internal( Node *n1, Node *n2 ) const { 5913 if( !n1 ) return n2; // Handle null original LCA 5914 assert( n1->is_CFG(), "" ); 5915 assert( n2->is_CFG(), "" ); 5916 // find LCA of all uses 5917 uint d1 = dom_depth(n1); 5918 uint d2 = dom_depth(n2); 5919 while (n1 != n2) { 5920 if (d1 > d2) { 5921 n1 = idom(n1); 5922 d1 = dom_depth(n1); 5923 } else if (d1 < d2) { 5924 n2 = idom(n2); 5925 d2 = dom_depth(n2); 5926 } else { 5927 // Here d1 == d2. Due to edits of the dominator-tree, sections 5928 // of the tree might have the same depth. These sections have 5929 // to be searched more carefully. 5930 5931 // Scan up all the n1's with equal depth, looking for n2. 5932 Node *t1 = idom(n1); 5933 while (dom_depth(t1) == d1) { 5934 if (t1 == n2) return n2; 5935 t1 = idom(t1); 5936 } 5937 // Scan up all the n2's with equal depth, looking for n1. 5938 Node *t2 = idom(n2); 5939 while (dom_depth(t2) == d2) { 5940 if (t2 == n1) return n1; 5941 t2 = idom(t2); 5942 } 5943 // Move up to a new dominator-depth value as well as up the dom-tree. 5944 n1 = t1; 5945 n2 = t2; 5946 d1 = dom_depth(n1); 5947 d2 = dom_depth(n2); 5948 } 5949 } 5950 return n1; 5951 } 5952 5953 //------------------------------compute_idom----------------------------------- 5954 // Locally compute IDOM using dom_lca call. Correct only if the incoming 5955 // IDOMs are correct. 5956 Node *PhaseIdealLoop::compute_idom( Node *region ) const { 5957 assert( region->is_Region(), "" ); 5958 Node *LCA = nullptr; 5959 for( uint i = 1; i < region->req(); i++ ) { 5960 if( region->in(i) != C->top() ) 5961 LCA = dom_lca( LCA, region->in(i) ); 5962 } 5963 return LCA; 5964 } 5965 5966 bool PhaseIdealLoop::verify_dominance(Node* n, Node* use, Node* LCA, Node* early) { 5967 bool had_error = false; 5968 #ifdef ASSERT 5969 if (early != C->root()) { 5970 // Make sure that there's a dominance path from LCA to early 5971 Node* d = LCA; 5972 while (d != early) { 5973 if (d == C->root()) { 5974 dump_bad_graph("Bad graph detected in compute_lca_of_uses", n, early, LCA); 5975 tty->print_cr("*** Use %d isn't dominated by def %d ***", use->_idx, n->_idx); 5976 had_error = true; 5977 break; 5978 } 5979 d = idom(d); 5980 } 5981 } 5982 #endif 5983 return had_error; 5984 } 5985 5986 5987 Node* PhaseIdealLoop::compute_lca_of_uses(Node* n, Node* early, bool verify) { 5988 // Compute LCA over list of uses 5989 bool had_error = false; 5990 Node *LCA = nullptr; 5991 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax && LCA != early; i++) { 5992 Node* c = n->fast_out(i); 5993 if (_loop_or_ctrl[c->_idx] == nullptr) 5994 continue; // Skip the occasional dead node 5995 if( c->is_Phi() ) { // For Phis, we must land above on the path 5996 for( uint j=1; j<c->req(); j++ ) {// For all inputs 5997 if( c->in(j) == n ) { // Found matching input? 5998 Node *use = c->in(0)->in(j); 5999 if (_verify_only && use->is_top()) continue; 6000 LCA = dom_lca_for_get_late_ctrl( LCA, use, n ); 6001 if (verify) had_error = verify_dominance(n, use, LCA, early) || had_error; 6002 } 6003 } 6004 } else { 6005 // For CFG data-users, use is in the block just prior 6006 Node *use = has_ctrl(c) ? get_ctrl(c) : c->in(0); 6007 LCA = dom_lca_for_get_late_ctrl( LCA, use, n ); 6008 if (verify) had_error = verify_dominance(n, use, LCA, early) || had_error; 6009 } 6010 } 6011 assert(!had_error, "bad dominance"); 6012 return LCA; 6013 } 6014 6015 // Check the shape of the graph at the loop entry. In some cases, 6016 // the shape of the graph does not match the shape outlined below. 6017 // That is caused by the Opaque1 node "protecting" the shape of 6018 // the graph being removed by, for example, the IGVN performed 6019 // in PhaseIdealLoop::build_and_optimize(). 6020 // 6021 // After the Opaque1 node has been removed, optimizations (e.g., split-if, 6022 // loop unswitching, and IGVN, or a combination of them) can freely change 6023 // the graph's shape. As a result, the graph shape outlined below cannot 6024 // be guaranteed anymore. 6025 Node* CountedLoopNode::is_canonical_loop_entry() { 6026 if (!is_main_loop() && !is_post_loop()) { 6027 return nullptr; 6028 } 6029 Node* ctrl = skip_assertion_predicates_with_halt(); 6030 6031 if (ctrl == nullptr || (!ctrl->is_IfTrue() && !ctrl->is_IfFalse())) { 6032 return nullptr; 6033 } 6034 Node* iffm = ctrl->in(0); 6035 if (iffm == nullptr || iffm->Opcode() != Op_If) { 6036 return nullptr; 6037 } 6038 Node* bolzm = iffm->in(1); 6039 if (bolzm == nullptr || !bolzm->is_Bool()) { 6040 return nullptr; 6041 } 6042 Node* cmpzm = bolzm->in(1); 6043 if (cmpzm == nullptr || !cmpzm->is_Cmp()) { 6044 return nullptr; 6045 } 6046 6047 uint input = is_main_loop() ? 2 : 1; 6048 if (input >= cmpzm->req() || cmpzm->in(input) == nullptr) { 6049 return nullptr; 6050 } 6051 bool res = cmpzm->in(input)->Opcode() == Op_OpaqueZeroTripGuard; 6052 #ifdef ASSERT 6053 bool found_opaque = false; 6054 for (uint i = 1; i < cmpzm->req(); i++) { 6055 Node* opnd = cmpzm->in(i); 6056 if (opnd && opnd->is_Opaque1()) { 6057 found_opaque = true; 6058 break; 6059 } 6060 } 6061 assert(found_opaque == res, "wrong pattern"); 6062 #endif 6063 return res ? cmpzm->in(input) : nullptr; 6064 } 6065 6066 // Find pre loop end from main loop. Returns nullptr if none. 6067 CountedLoopEndNode* CountedLoopNode::find_pre_loop_end() { 6068 assert(is_main_loop(), "Can only find pre-loop from main-loop"); 6069 // The loop cannot be optimized if the graph shape at the loop entry is 6070 // inappropriate. 6071 if (is_canonical_loop_entry() == nullptr) { 6072 return nullptr; 6073 } 6074 6075 Node* p_f = skip_assertion_predicates_with_halt()->in(0)->in(0); 6076 if (!p_f->is_IfFalse() || !p_f->in(0)->is_CountedLoopEnd()) { 6077 return nullptr; 6078 } 6079 CountedLoopEndNode* pre_end = p_f->in(0)->as_CountedLoopEnd(); 6080 CountedLoopNode* loop_node = pre_end->loopnode(); 6081 if (loop_node == nullptr || !loop_node->is_pre_loop()) { 6082 return nullptr; 6083 } 6084 return pre_end; 6085 } 6086 6087 //------------------------------get_late_ctrl---------------------------------- 6088 // Compute latest legal control. 6089 Node *PhaseIdealLoop::get_late_ctrl( Node *n, Node *early ) { 6090 assert(early != nullptr, "early control should not be null"); 6091 6092 Node* LCA = compute_lca_of_uses(n, early); 6093 #ifdef ASSERT 6094 if (LCA == C->root() && LCA != early) { 6095 // def doesn't dominate uses so print some useful debugging output 6096 compute_lca_of_uses(n, early, true); 6097 } 6098 #endif 6099 6100 if (n->is_Load() && LCA != early) { 6101 LCA = get_late_ctrl_with_anti_dep(n->as_Load(), early, LCA); 6102 } 6103 6104 assert(LCA == find_non_split_ctrl(LCA), "unexpected late control"); 6105 return LCA; 6106 } 6107 6108 // if this is a load, check for anti-dependent stores 6109 // We use a conservative algorithm to identify potential interfering 6110 // instructions and for rescheduling the load. The users of the memory 6111 // input of this load are examined. Any use which is not a load and is 6112 // dominated by early is considered a potentially interfering store. 6113 // This can produce false positives. 6114 Node* PhaseIdealLoop::get_late_ctrl_with_anti_dep(LoadNode* n, Node* early, Node* LCA) { 6115 int load_alias_idx = C->get_alias_index(n->adr_type()); 6116 if (C->alias_type(load_alias_idx)->is_rewritable()) { 6117 Unique_Node_List worklist; 6118 6119 Node* mem = n->in(MemNode::Memory); 6120 for (DUIterator_Fast imax, i = mem->fast_outs(imax); i < imax; i++) { 6121 Node* s = mem->fast_out(i); 6122 worklist.push(s); 6123 } 6124 for (uint i = 0; i < worklist.size() && LCA != early; i++) { 6125 Node* s = worklist.at(i); 6126 if (s->is_Load() || s->Opcode() == Op_SafePoint || 6127 (s->is_CallStaticJava() && s->as_CallStaticJava()->uncommon_trap_request() != 0) || 6128 s->is_Phi()) { 6129 continue; 6130 } else if (s->is_MergeMem()) { 6131 for (DUIterator_Fast imax, i = s->fast_outs(imax); i < imax; i++) { 6132 Node* s1 = s->fast_out(i); 6133 worklist.push(s1); 6134 } 6135 } else { 6136 Node* sctrl = has_ctrl(s) ? get_ctrl(s) : s->in(0); 6137 assert(sctrl != nullptr || !s->is_reachable_from_root(), "must have control"); 6138 if (sctrl != nullptr && !sctrl->is_top() && is_dominator(early, sctrl)) { 6139 const TypePtr* adr_type = s->adr_type(); 6140 if (s->is_ArrayCopy()) { 6141 // Copy to known instance needs destination type to test for aliasing 6142 const TypePtr* dest_type = s->as_ArrayCopy()->_dest_type; 6143 if (dest_type != TypeOopPtr::BOTTOM) { 6144 adr_type = dest_type; 6145 } 6146 } 6147 if (C->can_alias(adr_type, load_alias_idx)) { 6148 LCA = dom_lca_for_get_late_ctrl(LCA, sctrl, n); 6149 } else if (s->is_CFG() && s->is_Multi()) { 6150 // Look for the memory use of s (that is the use of its memory projection) 6151 for (DUIterator_Fast imax, i = s->fast_outs(imax); i < imax; i++) { 6152 Node* s1 = s->fast_out(i); 6153 assert(s1->is_Proj(), "projection expected"); 6154 if (_igvn.type(s1) == Type::MEMORY) { 6155 for (DUIterator_Fast jmax, j = s1->fast_outs(jmax); j < jmax; j++) { 6156 Node* s2 = s1->fast_out(j); 6157 worklist.push(s2); 6158 } 6159 } 6160 } 6161 } 6162 } 6163 } 6164 } 6165 // For Phis only consider Region's inputs that were reached by following the memory edges 6166 if (LCA != early) { 6167 for (uint i = 0; i < worklist.size(); i++) { 6168 Node* s = worklist.at(i); 6169 if (s->is_Phi() && C->can_alias(s->adr_type(), load_alias_idx)) { 6170 Node* r = s->in(0); 6171 for (uint j = 1; j < s->req(); j++) { 6172 Node* in = s->in(j); 6173 Node* r_in = r->in(j); 6174 // We can't reach any node from a Phi because we don't enqueue Phi's uses above 6175 if (((worklist.member(in) && !in->is_Phi()) || in == mem) && is_dominator(early, r_in)) { 6176 LCA = dom_lca_for_get_late_ctrl(LCA, r_in, n); 6177 } 6178 } 6179 } 6180 } 6181 } 6182 } 6183 return LCA; 6184 } 6185 6186 // Is CFG node 'dominator' dominating node 'n'? 6187 bool PhaseIdealLoop::is_dominator(Node* dominator, Node* n) { 6188 if (dominator == n) { 6189 return true; 6190 } 6191 assert(dominator->is_CFG() && n->is_CFG(), "must have CFG nodes"); 6192 uint dd = dom_depth(dominator); 6193 while (dom_depth(n) >= dd) { 6194 if (n == dominator) { 6195 return true; 6196 } 6197 n = idom(n); 6198 } 6199 return false; 6200 } 6201 6202 // Is CFG node 'dominator' strictly dominating node 'n'? 6203 bool PhaseIdealLoop::is_strict_dominator(Node* dominator, Node* n) { 6204 return dominator != n && is_dominator(dominator, n); 6205 } 6206 6207 //------------------------------dom_lca_for_get_late_ctrl_internal------------- 6208 // Pair-wise LCA with tags. 6209 // Tag each index with the node 'tag' currently being processed 6210 // before advancing up the dominator chain using idom(). 6211 // Later calls that find a match to 'tag' know that this path has already 6212 // been considered in the current LCA (which is input 'n1' by convention). 6213 // Since get_late_ctrl() is only called once for each node, the tag array 6214 // does not need to be cleared between calls to get_late_ctrl(). 6215 // Algorithm trades a larger constant factor for better asymptotic behavior 6216 // 6217 Node *PhaseIdealLoop::dom_lca_for_get_late_ctrl_internal(Node *n1, Node *n2, Node *tag_node) { 6218 uint d1 = dom_depth(n1); 6219 uint d2 = dom_depth(n2); 6220 jlong tag = tag_node->_idx | (((jlong)_dom_lca_tags_round) << 32); 6221 6222 do { 6223 if (d1 > d2) { 6224 // current lca is deeper than n2 6225 _dom_lca_tags.at_put_grow(n1->_idx, tag); 6226 n1 = idom(n1); 6227 d1 = dom_depth(n1); 6228 } else if (d1 < d2) { 6229 // n2 is deeper than current lca 6230 jlong memo = _dom_lca_tags.at_grow(n2->_idx, 0); 6231 if (memo == tag) { 6232 return n1; // Return the current LCA 6233 } 6234 _dom_lca_tags.at_put_grow(n2->_idx, tag); 6235 n2 = idom(n2); 6236 d2 = dom_depth(n2); 6237 } else { 6238 // Here d1 == d2. Due to edits of the dominator-tree, sections 6239 // of the tree might have the same depth. These sections have 6240 // to be searched more carefully. 6241 6242 // Scan up all the n1's with equal depth, looking for n2. 6243 _dom_lca_tags.at_put_grow(n1->_idx, tag); 6244 Node *t1 = idom(n1); 6245 while (dom_depth(t1) == d1) { 6246 if (t1 == n2) return n2; 6247 _dom_lca_tags.at_put_grow(t1->_idx, tag); 6248 t1 = idom(t1); 6249 } 6250 // Scan up all the n2's with equal depth, looking for n1. 6251 _dom_lca_tags.at_put_grow(n2->_idx, tag); 6252 Node *t2 = idom(n2); 6253 while (dom_depth(t2) == d2) { 6254 if (t2 == n1) return n1; 6255 _dom_lca_tags.at_put_grow(t2->_idx, tag); 6256 t2 = idom(t2); 6257 } 6258 // Move up to a new dominator-depth value as well as up the dom-tree. 6259 n1 = t1; 6260 n2 = t2; 6261 d1 = dom_depth(n1); 6262 d2 = dom_depth(n2); 6263 } 6264 } while (n1 != n2); 6265 return n1; 6266 } 6267 6268 //------------------------------init_dom_lca_tags------------------------------ 6269 // Tag could be a node's integer index, 32bits instead of 64bits in some cases 6270 // Intended use does not involve any growth for the array, so it could 6271 // be of fixed size. 6272 void PhaseIdealLoop::init_dom_lca_tags() { 6273 uint limit = C->unique() + 1; 6274 _dom_lca_tags.at_grow(limit, 0); 6275 _dom_lca_tags_round = 0; 6276 #ifdef ASSERT 6277 for (uint i = 0; i < limit; ++i) { 6278 assert(_dom_lca_tags.at(i) == 0, "Must be distinct from each node pointer"); 6279 } 6280 #endif // ASSERT 6281 } 6282 6283 //------------------------------build_loop_late-------------------------------- 6284 // Put Data nodes into some loop nest, by setting the _loop_or_ctrl[]->loop mapping. 6285 // Second pass finds latest legal placement, and ideal loop placement. 6286 void PhaseIdealLoop::build_loop_late( VectorSet &visited, Node_List &worklist, Node_Stack &nstack ) { 6287 while (worklist.size() != 0) { 6288 Node *n = worklist.pop(); 6289 // Only visit once 6290 if (visited.test_set(n->_idx)) continue; 6291 uint cnt = n->outcnt(); 6292 uint i = 0; 6293 while (true) { 6294 assert(_loop_or_ctrl[n->_idx], "no dead nodes"); 6295 // Visit all children 6296 if (i < cnt) { 6297 Node* use = n->raw_out(i); 6298 ++i; 6299 // Check for dead uses. Aggressively prune such junk. It might be 6300 // dead in the global sense, but still have local uses so I cannot 6301 // easily call 'remove_dead_node'. 6302 if (_loop_or_ctrl[use->_idx] != nullptr || use->is_top()) { // Not dead? 6303 // Due to cycles, we might not hit the same fixed point in the verify 6304 // pass as we do in the regular pass. Instead, visit such phis as 6305 // simple uses of the loop head. 6306 if( use->in(0) && (use->is_CFG() || use->is_Phi()) ) { 6307 if( !visited.test(use->_idx) ) 6308 worklist.push(use); 6309 } else if( !visited.test_set(use->_idx) ) { 6310 nstack.push(n, i); // Save parent and next use's index. 6311 n = use; // Process all children of current use. 6312 cnt = use->outcnt(); 6313 i = 0; 6314 } 6315 } else { 6316 // Do not visit around the backedge of loops via data edges. 6317 // push dead code onto a worklist 6318 _deadlist.push(use); 6319 } 6320 } else { 6321 // All of n's children have been processed, complete post-processing. 6322 build_loop_late_post(n); 6323 if (C->failing()) { return; } 6324 if (nstack.is_empty()) { 6325 // Finished all nodes on stack. 6326 // Process next node on the worklist. 6327 break; 6328 } 6329 // Get saved parent node and next use's index. Visit the rest of uses. 6330 n = nstack.node(); 6331 cnt = n->outcnt(); 6332 i = nstack.index(); 6333 nstack.pop(); 6334 } 6335 } 6336 } 6337 } 6338 6339 // Verify that no data node is scheduled in the outer loop of a strip 6340 // mined loop. 6341 void PhaseIdealLoop::verify_strip_mined_scheduling(Node *n, Node* least) { 6342 #ifdef ASSERT 6343 if (get_loop(least)->_nest == 0) { 6344 return; 6345 } 6346 IdealLoopTree* loop = get_loop(least); 6347 Node* head = loop->_head; 6348 if (head->is_OuterStripMinedLoop() && 6349 // Verification can't be applied to fully built strip mined loops 6350 head->as_Loop()->outer_loop_end()->in(1)->find_int_con(-1) == 0) { 6351 Node* sfpt = head->as_Loop()->outer_safepoint(); 6352 ResourceMark rm; 6353 Unique_Node_List wq; 6354 wq.push(sfpt); 6355 for (uint i = 0; i < wq.size(); i++) { 6356 Node *m = wq.at(i); 6357 for (uint i = 1; i < m->req(); i++) { 6358 Node* nn = m->in(i); 6359 if (nn == n) { 6360 return; 6361 } 6362 if (nn != nullptr && has_ctrl(nn) && get_loop(get_ctrl(nn)) == loop) { 6363 wq.push(nn); 6364 } 6365 } 6366 } 6367 ShouldNotReachHere(); 6368 } 6369 #endif 6370 } 6371 6372 6373 //------------------------------build_loop_late_post--------------------------- 6374 // Put Data nodes into some loop nest, by setting the _loop_or_ctrl[]->loop mapping. 6375 // Second pass finds latest legal placement, and ideal loop placement. 6376 void PhaseIdealLoop::build_loop_late_post(Node *n) { 6377 build_loop_late_post_work(n, true); 6378 } 6379 6380 // Class to visit all predicates in a predicate chain to find out which are dominated by a given node. Keeps track of 6381 // the entry to the earliest predicate that is still dominated by the given dominator. This class is used when trying to 6382 // legally skip all predicates when figuring out the latest placement such that a node does not interfere with Loop 6383 // Predication or creating a Loop Limit Check Predicate later. 6384 class DominatedPredicates : public UnifiedPredicateVisitor { 6385 Node* const _dominator; 6386 Node* _earliest_dominated_predicate_entry; 6387 bool _should_continue; 6388 PhaseIdealLoop* const _phase; 6389 6390 public: 6391 DominatedPredicates(Node* dominator, Node* start_node, PhaseIdealLoop* phase) 6392 : _dominator(dominator), 6393 _earliest_dominated_predicate_entry(start_node), 6394 _should_continue(true), 6395 _phase(phase) {} 6396 NONCOPYABLE(DominatedPredicates); 6397 6398 bool should_continue() const override { 6399 return _should_continue; 6400 } 6401 6402 // Returns the entry to the earliest predicate that is still dominated by the given dominator (all could be dominated). 6403 Node* earliest_dominated_predicate_entry() const { 6404 return _earliest_dominated_predicate_entry; 6405 } 6406 6407 void visit_predicate(const Predicate& predicate) override { 6408 Node* entry = predicate.entry(); 6409 if (_phase->is_strict_dominator(entry, _dominator)) { 6410 _should_continue = false; 6411 } else { 6412 _earliest_dominated_predicate_entry = entry; 6413 } 6414 } 6415 }; 6416 6417 void PhaseIdealLoop::build_loop_late_post_work(Node *n, bool pinned) { 6418 6419 if (n->req() == 2 && (n->Opcode() == Op_ConvI2L || n->Opcode() == Op_CastII) && !C->major_progress() && !_verify_only) { 6420 _igvn._worklist.push(n); // Maybe we'll normalize it, if no more loops. 6421 } 6422 6423 #ifdef ASSERT 6424 if (_verify_only && !n->is_CFG()) { 6425 // Check def-use domination. 6426 compute_lca_of_uses(n, get_ctrl(n), true /* verify */); 6427 } 6428 #endif 6429 6430 // CFG and pinned nodes already handled 6431 if( n->in(0) ) { 6432 if( n->in(0)->is_top() ) return; // Dead? 6433 6434 // We'd like +VerifyLoopOptimizations to not believe that Mod's/Loads 6435 // _must_ be pinned (they have to observe their control edge of course). 6436 // Unlike Stores (which modify an unallocable resource, the memory 6437 // state), Mods/Loads can float around. So free them up. 6438 switch( n->Opcode() ) { 6439 case Op_DivI: 6440 case Op_DivF: 6441 case Op_DivD: 6442 case Op_ModI: 6443 case Op_ModF: 6444 case Op_ModD: 6445 case Op_LoadB: // Same with Loads; they can sink 6446 case Op_LoadUB: // during loop optimizations. 6447 case Op_LoadUS: 6448 case Op_LoadD: 6449 case Op_LoadF: 6450 case Op_LoadI: 6451 case Op_LoadKlass: 6452 case Op_LoadNKlass: 6453 case Op_LoadL: 6454 case Op_LoadS: 6455 case Op_LoadP: 6456 case Op_LoadN: 6457 case Op_LoadRange: 6458 case Op_LoadD_unaligned: 6459 case Op_LoadL_unaligned: 6460 case Op_StrComp: // Does a bunch of load-like effects 6461 case Op_StrEquals: 6462 case Op_StrIndexOf: 6463 case Op_StrIndexOfChar: 6464 case Op_AryEq: 6465 case Op_VectorizedHashCode: 6466 case Op_CountPositives: 6467 pinned = false; 6468 } 6469 if (n->is_CMove() || n->is_ConstraintCast()) { 6470 pinned = false; 6471 } 6472 if( pinned ) { 6473 IdealLoopTree *chosen_loop = get_loop(n->is_CFG() ? n : get_ctrl(n)); 6474 if( !chosen_loop->_child ) // Inner loop? 6475 chosen_loop->_body.push(n); // Collect inner loops 6476 return; 6477 } 6478 } else { // No slot zero 6479 if( n->is_CFG() ) { // CFG with no slot 0 is dead 6480 _loop_or_ctrl.map(n->_idx,nullptr); // No block setting, it's globally dead 6481 return; 6482 } 6483 assert(!n->is_CFG() || n->outcnt() == 0, ""); 6484 } 6485 6486 // Do I have a "safe range" I can select over? 6487 Node *early = get_ctrl(n);// Early location already computed 6488 6489 // Compute latest point this Node can go 6490 Node *LCA = get_late_ctrl( n, early ); 6491 // LCA is null due to uses being dead 6492 if( LCA == nullptr ) { 6493 #ifdef ASSERT 6494 for (DUIterator i1 = n->outs(); n->has_out(i1); i1++) { 6495 assert(_loop_or_ctrl[n->out(i1)->_idx] == nullptr, "all uses must also be dead"); 6496 } 6497 #endif 6498 _loop_or_ctrl.map(n->_idx, nullptr); // This node is useless 6499 _deadlist.push(n); 6500 return; 6501 } 6502 assert(LCA != nullptr && !LCA->is_top(), "no dead nodes"); 6503 6504 Node *legal = LCA; // Walk 'legal' up the IDOM chain 6505 Node *least = legal; // Best legal position so far 6506 while( early != legal ) { // While not at earliest legal 6507 if (legal->is_Start() && !early->is_Root()) { 6508 #ifdef ASSERT 6509 // Bad graph. Print idom path and fail. 6510 dump_bad_graph("Bad graph detected in build_loop_late", n, early, LCA); 6511 assert(false, "Bad graph detected in build_loop_late"); 6512 #endif 6513 C->record_method_not_compilable("Bad graph detected in build_loop_late"); 6514 return; 6515 } 6516 // Find least loop nesting depth 6517 legal = idom(legal); // Bump up the IDOM tree 6518 // Check for lower nesting depth 6519 if( get_loop(legal)->_nest < get_loop(least)->_nest ) 6520 least = legal; 6521 } 6522 assert(early == legal || legal != C->root(), "bad dominance of inputs"); 6523 6524 if (least != early) { 6525 // Move the node above predicates as far up as possible so a 6526 // following pass of Loop Predication doesn't hoist a predicate 6527 // that depends on it above that node. 6528 const PredicateIterator predicate_iterator(least); 6529 DominatedPredicates dominated_predicates(early, least, this); 6530 predicate_iterator.for_each(dominated_predicates); 6531 least = dominated_predicates.earliest_dominated_predicate_entry(); 6532 } 6533 // Try not to place code on a loop entry projection 6534 // which can inhibit range check elimination. 6535 if (least != early && !BarrierSet::barrier_set()->barrier_set_c2()->is_gc_specific_loop_opts_pass(_mode)) { 6536 Node* ctrl_out = least->unique_ctrl_out_or_null(); 6537 if (ctrl_out != nullptr && ctrl_out->is_Loop() && 6538 least == ctrl_out->in(LoopNode::EntryControl) && 6539 (ctrl_out->is_CountedLoop() || ctrl_out->is_OuterStripMinedLoop())) { 6540 Node* least_dom = idom(least); 6541 if (get_loop(least_dom)->is_member(get_loop(least))) { 6542 least = least_dom; 6543 } 6544 } 6545 } 6546 // Don't extend live ranges of raw oops 6547 if (least != early && n->is_ConstraintCast() && n->in(1)->bottom_type()->isa_rawptr() && 6548 !n->bottom_type()->isa_rawptr()) { 6549 least = early; 6550 } 6551 6552 #ifdef ASSERT 6553 // Broken part of VerifyLoopOptimizations (F) 6554 // Reason: 6555 // _verify_me->get_ctrl_no_update(n) seems to return wrong result 6556 /* 6557 // If verifying, verify that 'verify_me' has a legal location 6558 // and choose it as our location. 6559 if( _verify_me ) { 6560 Node *v_ctrl = _verify_me->get_ctrl_no_update(n); 6561 Node *legal = LCA; 6562 while( early != legal ) { // While not at earliest legal 6563 if( legal == v_ctrl ) break; // Check for prior good location 6564 legal = idom(legal) ;// Bump up the IDOM tree 6565 } 6566 // Check for prior good location 6567 if( legal == v_ctrl ) least = legal; // Keep prior if found 6568 } 6569 */ 6570 #endif 6571 6572 // Assign discovered "here or above" point 6573 least = find_non_split_ctrl(least); 6574 verify_strip_mined_scheduling(n, least); 6575 set_ctrl(n, least); 6576 6577 // Collect inner loop bodies 6578 IdealLoopTree *chosen_loop = get_loop(least); 6579 if( !chosen_loop->_child ) // Inner loop? 6580 chosen_loop->_body.push(n);// Collect inner loops 6581 6582 if (!_verify_only && n->Opcode() == Op_OpaqueZeroTripGuard) { 6583 _zero_trip_guard_opaque_nodes.push(n); 6584 } 6585 6586 } 6587 6588 #ifdef ASSERT 6589 void PhaseIdealLoop::dump_bad_graph(const char* msg, Node* n, Node* early, Node* LCA) { 6590 tty->print_cr("%s", msg); 6591 tty->print("n: "); n->dump(); 6592 tty->print("early(n): "); early->dump(); 6593 if (n->in(0) != nullptr && !n->in(0)->is_top() && 6594 n->in(0) != early && !n->in(0)->is_Root()) { 6595 tty->print("n->in(0): "); n->in(0)->dump(); 6596 } 6597 for (uint i = 1; i < n->req(); i++) { 6598 Node* in1 = n->in(i); 6599 if (in1 != nullptr && in1 != n && !in1->is_top()) { 6600 tty->print("n->in(%d): ", i); in1->dump(); 6601 Node* in1_early = get_ctrl(in1); 6602 tty->print("early(n->in(%d)): ", i); in1_early->dump(); 6603 if (in1->in(0) != nullptr && !in1->in(0)->is_top() && 6604 in1->in(0) != in1_early && !in1->in(0)->is_Root()) { 6605 tty->print("n->in(%d)->in(0): ", i); in1->in(0)->dump(); 6606 } 6607 for (uint j = 1; j < in1->req(); j++) { 6608 Node* in2 = in1->in(j); 6609 if (in2 != nullptr && in2 != n && in2 != in1 && !in2->is_top()) { 6610 tty->print("n->in(%d)->in(%d): ", i, j); in2->dump(); 6611 Node* in2_early = get_ctrl(in2); 6612 tty->print("early(n->in(%d)->in(%d)): ", i, j); in2_early->dump(); 6613 if (in2->in(0) != nullptr && !in2->in(0)->is_top() && 6614 in2->in(0) != in2_early && !in2->in(0)->is_Root()) { 6615 tty->print("n->in(%d)->in(%d)->in(0): ", i, j); in2->in(0)->dump(); 6616 } 6617 } 6618 } 6619 } 6620 } 6621 tty->cr(); 6622 tty->print("LCA(n): "); LCA->dump(); 6623 for (uint i = 0; i < n->outcnt(); i++) { 6624 Node* u1 = n->raw_out(i); 6625 if (u1 == n) 6626 continue; 6627 tty->print("n->out(%d): ", i); u1->dump(); 6628 if (u1->is_CFG()) { 6629 for (uint j = 0; j < u1->outcnt(); j++) { 6630 Node* u2 = u1->raw_out(j); 6631 if (u2 != u1 && u2 != n && u2->is_CFG()) { 6632 tty->print("n->out(%d)->out(%d): ", i, j); u2->dump(); 6633 } 6634 } 6635 } else { 6636 Node* u1_later = get_ctrl(u1); 6637 tty->print("later(n->out(%d)): ", i); u1_later->dump(); 6638 if (u1->in(0) != nullptr && !u1->in(0)->is_top() && 6639 u1->in(0) != u1_later && !u1->in(0)->is_Root()) { 6640 tty->print("n->out(%d)->in(0): ", i); u1->in(0)->dump(); 6641 } 6642 for (uint j = 0; j < u1->outcnt(); j++) { 6643 Node* u2 = u1->raw_out(j); 6644 if (u2 == n || u2 == u1) 6645 continue; 6646 tty->print("n->out(%d)->out(%d): ", i, j); u2->dump(); 6647 if (!u2->is_CFG()) { 6648 Node* u2_later = get_ctrl(u2); 6649 tty->print("later(n->out(%d)->out(%d)): ", i, j); u2_later->dump(); 6650 if (u2->in(0) != nullptr && !u2->in(0)->is_top() && 6651 u2->in(0) != u2_later && !u2->in(0)->is_Root()) { 6652 tty->print("n->out(%d)->in(0): ", i); u2->in(0)->dump(); 6653 } 6654 } 6655 } 6656 } 6657 } 6658 dump_idoms(early, LCA); 6659 tty->cr(); 6660 } 6661 6662 // Class to compute the real LCA given an early node and a wrong LCA in a bad graph. 6663 class RealLCA { 6664 const PhaseIdealLoop* _phase; 6665 Node* _early; 6666 Node* _wrong_lca; 6667 uint _early_index; 6668 int _wrong_lca_index; 6669 6670 // Given idom chains of early and wrong LCA: Walk through idoms starting at StartNode and find the first node which 6671 // is different: Return the previously visited node which must be the real LCA. 6672 // The node lists also contain _early and _wrong_lca, respectively. 6673 Node* find_real_lca(Unique_Node_List& early_with_idoms, Unique_Node_List& wrong_lca_with_idoms) { 6674 int early_index = early_with_idoms.size() - 1; 6675 int wrong_lca_index = wrong_lca_with_idoms.size() - 1; 6676 bool found_difference = false; 6677 do { 6678 if (early_with_idoms[early_index] != wrong_lca_with_idoms[wrong_lca_index]) { 6679 // First time early and wrong LCA idoms differ. Real LCA must be at the previous index. 6680 found_difference = true; 6681 break; 6682 } 6683 early_index--; 6684 wrong_lca_index--; 6685 } while (wrong_lca_index >= 0); 6686 6687 assert(early_index >= 0, "must always find an LCA - cannot be early"); 6688 _early_index = early_index; 6689 _wrong_lca_index = wrong_lca_index; 6690 Node* real_lca = early_with_idoms[_early_index + 1]; // Plus one to skip _early. 6691 assert(found_difference || real_lca == _wrong_lca, "wrong LCA dominates early and is therefore the real LCA"); 6692 return real_lca; 6693 } 6694 6695 void dump(Node* real_lca) { 6696 tty->cr(); 6697 tty->print_cr("idoms of early \"%d %s\":", _early->_idx, _early->Name()); 6698 _phase->dump_idom(_early, _early_index + 1); 6699 6700 tty->cr(); 6701 tty->print_cr("idoms of (wrong) LCA \"%d %s\":", _wrong_lca->_idx, _wrong_lca->Name()); 6702 _phase->dump_idom(_wrong_lca, _wrong_lca_index + 1); 6703 6704 tty->cr(); 6705 tty->print("Real LCA of early \"%d %s\" (idom[%d]) and wrong LCA \"%d %s\"", 6706 _early->_idx, _early->Name(), _early_index, _wrong_lca->_idx, _wrong_lca->Name()); 6707 if (_wrong_lca_index >= 0) { 6708 tty->print(" (idom[%d])", _wrong_lca_index); 6709 } 6710 tty->print_cr(":"); 6711 real_lca->dump(); 6712 } 6713 6714 public: 6715 RealLCA(const PhaseIdealLoop* phase, Node* early, Node* wrong_lca) 6716 : _phase(phase), _early(early), _wrong_lca(wrong_lca), _early_index(0), _wrong_lca_index(0) { 6717 assert(!wrong_lca->is_Start(), "StartNode is always a common dominator"); 6718 } 6719 6720 void compute_and_dump() { 6721 ResourceMark rm; 6722 Unique_Node_List early_with_idoms; 6723 Unique_Node_List wrong_lca_with_idoms; 6724 early_with_idoms.push(_early); 6725 wrong_lca_with_idoms.push(_wrong_lca); 6726 _phase->get_idoms(_early, 10000, early_with_idoms); 6727 _phase->get_idoms(_wrong_lca, 10000, wrong_lca_with_idoms); 6728 Node* real_lca = find_real_lca(early_with_idoms, wrong_lca_with_idoms); 6729 dump(real_lca); 6730 } 6731 }; 6732 6733 // Dump the idom chain of early, of the wrong LCA and dump the real LCA of early and wrong LCA. 6734 void PhaseIdealLoop::dump_idoms(Node* early, Node* wrong_lca) { 6735 assert(!is_dominator(early, wrong_lca), "sanity check that early does not dominate wrong lca"); 6736 assert(!has_ctrl(early) && !has_ctrl(wrong_lca), "sanity check, no data nodes"); 6737 6738 RealLCA real_lca(this, early, wrong_lca); 6739 real_lca.compute_and_dump(); 6740 } 6741 #endif // ASSERT 6742 6743 #ifndef PRODUCT 6744 //------------------------------dump------------------------------------------- 6745 void PhaseIdealLoop::dump() const { 6746 ResourceMark rm; 6747 Node_Stack stack(C->live_nodes() >> 2); 6748 Node_List rpo_list; 6749 VectorSet visited; 6750 visited.set(C->top()->_idx); 6751 rpo(C->root(), stack, visited, rpo_list); 6752 // Dump root loop indexed by last element in PO order 6753 dump(_ltree_root, rpo_list.size(), rpo_list); 6754 } 6755 6756 void PhaseIdealLoop::dump(IdealLoopTree* loop, uint idx, Node_List &rpo_list) const { 6757 loop->dump_head(); 6758 6759 // Now scan for CFG nodes in the same loop 6760 for (uint j = idx; j > 0; j--) { 6761 Node* n = rpo_list[j-1]; 6762 if (!_loop_or_ctrl[n->_idx]) // Skip dead nodes 6763 continue; 6764 6765 if (get_loop(n) != loop) { // Wrong loop nest 6766 if (get_loop(n)->_head == n && // Found nested loop? 6767 get_loop(n)->_parent == loop) 6768 dump(get_loop(n), rpo_list.size(), rpo_list); // Print it nested-ly 6769 continue; 6770 } 6771 6772 // Dump controlling node 6773 tty->sp(2 * loop->_nest); 6774 tty->print("C"); 6775 if (n == C->root()) { 6776 n->dump(); 6777 } else { 6778 Node* cached_idom = idom_no_update(n); 6779 Node* computed_idom = n->in(0); 6780 if (n->is_Region()) { 6781 computed_idom = compute_idom(n); 6782 // computed_idom() will return n->in(0) when idom(n) is an IfNode (or 6783 // any MultiBranch ctrl node), so apply a similar transform to 6784 // the cached idom returned from idom_no_update. 6785 cached_idom = find_non_split_ctrl(cached_idom); 6786 } 6787 tty->print(" ID:%d", computed_idom->_idx); 6788 n->dump(); 6789 if (cached_idom != computed_idom) { 6790 tty->print_cr("*** BROKEN IDOM! Computed as: %d, cached as: %d", 6791 computed_idom->_idx, cached_idom->_idx); 6792 } 6793 } 6794 // Dump nodes it controls 6795 for (uint k = 0; k < _loop_or_ctrl.max(); k++) { 6796 // (k < C->unique() && get_ctrl(find(k)) == n) 6797 if (k < C->unique() && _loop_or_ctrl[k] == (Node*)((intptr_t)n + 1)) { 6798 Node* m = C->root()->find(k); 6799 if (m && m->outcnt() > 0) { 6800 if (!(has_ctrl(m) && get_ctrl_no_update(m) == n)) { 6801 tty->print_cr("*** BROKEN CTRL ACCESSOR! _loop_or_ctrl[k] is %p, ctrl is %p", 6802 _loop_or_ctrl[k], has_ctrl(m) ? get_ctrl_no_update(m) : nullptr); 6803 } 6804 tty->sp(2 * loop->_nest + 1); 6805 m->dump(); 6806 } 6807 } 6808 } 6809 } 6810 } 6811 6812 void PhaseIdealLoop::dump_idom(Node* n, const uint count) const { 6813 if (has_ctrl(n)) { 6814 tty->print_cr("No idom for data nodes"); 6815 } else { 6816 ResourceMark rm; 6817 Unique_Node_List idoms; 6818 get_idoms(n, count, idoms); 6819 dump_idoms_in_reverse(n, idoms); 6820 } 6821 } 6822 6823 void PhaseIdealLoop::get_idoms(Node* n, const uint count, Unique_Node_List& idoms) const { 6824 Node* next = n; 6825 for (uint i = 0; !next->is_Start() && i < count; i++) { 6826 next = idom(next); 6827 assert(!idoms.member(next), "duplicated idom is not possible"); 6828 idoms.push(next); 6829 } 6830 } 6831 6832 void PhaseIdealLoop::dump_idoms_in_reverse(const Node* n, const Node_List& idom_list) const { 6833 Node* next; 6834 uint padding = 3; 6835 uint node_index_padding_width = static_cast<int>(log10(static_cast<double>(C->unique()))) + 1; 6836 for (int i = idom_list.size() - 1; i >= 0; i--) { 6837 if (i == 9 || i == 99) { 6838 padding++; 6839 } 6840 next = idom_list[i]; 6841 tty->print_cr("idom[%d]:%*c%*d %s", i, padding, ' ', node_index_padding_width, next->_idx, next->Name()); 6842 } 6843 tty->print_cr("n: %*c%*d %s", padding, ' ', node_index_padding_width, n->_idx, n->Name()); 6844 } 6845 #endif // NOT PRODUCT 6846 6847 // Collect a R-P-O for the whole CFG. 6848 // Result list is in post-order (scan backwards for RPO) 6849 void PhaseIdealLoop::rpo(Node* start, Node_Stack &stk, VectorSet &visited, Node_List &rpo_list) const { 6850 stk.push(start, 0); 6851 visited.set(start->_idx); 6852 6853 while (stk.is_nonempty()) { 6854 Node* m = stk.node(); 6855 uint idx = stk.index(); 6856 if (idx < m->outcnt()) { 6857 stk.set_index(idx + 1); 6858 Node* n = m->raw_out(idx); 6859 if (n->is_CFG() && !visited.test_set(n->_idx)) { 6860 stk.push(n, 0); 6861 } 6862 } else { 6863 rpo_list.push(m); 6864 stk.pop(); 6865 } 6866 } 6867 } 6868 6869 6870 //============================================================================= 6871 //------------------------------LoopTreeIterator------------------------------- 6872 6873 // Advance to next loop tree using a preorder, left-to-right traversal. 6874 void LoopTreeIterator::next() { 6875 assert(!done(), "must not be done."); 6876 if (_curnt->_child != nullptr) { 6877 _curnt = _curnt->_child; 6878 } else if (_curnt->_next != nullptr) { 6879 _curnt = _curnt->_next; 6880 } else { 6881 while (_curnt != _root && _curnt->_next == nullptr) { 6882 _curnt = _curnt->_parent; 6883 } 6884 if (_curnt == _root) { 6885 _curnt = nullptr; 6886 assert(done(), "must be done."); 6887 } else { 6888 assert(_curnt->_next != nullptr, "must be more to do"); 6889 _curnt = _curnt->_next; 6890 } 6891 } 6892 }