1 /* 2 * Copyright (c) 1999, 2025, 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 "gc/shared/barrierSet.hpp" 26 #include "gc/shared/c2/barrierSetC2.hpp" 27 #include "memory/allocation.inline.hpp" 28 #include "memory/resourceArea.hpp" 29 #include "opto/addnode.hpp" 30 #include "opto/callnode.hpp" 31 #include "opto/castnode.hpp" 32 #include "opto/connode.hpp" 33 #include "opto/divnode.hpp" 34 #include "opto/loopnode.hpp" 35 #include "opto/matcher.hpp" 36 #include "opto/movenode.hpp" 37 #include "opto/mulnode.hpp" 38 #include "opto/opaquenode.hpp" 39 #include "opto/rootnode.hpp" 40 #include "opto/subnode.hpp" 41 #include "opto/subtypenode.hpp" 42 #include "opto/superword.hpp" 43 #include "opto/vectornode.hpp" 44 #include "utilities/macros.hpp" 45 46 //============================================================================= 47 //------------------------------split_thru_phi--------------------------------- 48 // Split Node 'n' through merge point if there is enough win. 49 Node* PhaseIdealLoop::split_thru_phi(Node* n, Node* region, int policy) { 50 if ((n->Opcode() == Op_ConvI2L && n->bottom_type() != TypeLong::LONG) || 51 (n->Opcode() == Op_ConvL2I && n->bottom_type() != TypeInt::INT)) { 52 // ConvI2L/ConvL2I may have type information on it which is unsafe to push up 53 // so disable this for now 54 return nullptr; 55 } 56 57 // Splitting range check CastIIs through a loop induction Phi can 58 // cause new Phis to be created that are left unrelated to the loop 59 // induction Phi and prevent optimizations (vectorization) 60 if (n->Opcode() == Op_CastII && region->is_CountedLoop() && 61 n->in(1) == region->as_CountedLoop()->phi()) { 62 return nullptr; 63 } 64 65 if (cannot_split_division(n, region)) { 66 return nullptr; 67 } 68 69 int wins = 0; 70 assert(!n->is_CFG(), ""); 71 assert(region->is_Region(), ""); 72 73 const Type* type = n->bottom_type(); 74 const TypeOopPtr* t_oop = _igvn.type(n)->isa_oopptr(); 75 Node* phi; 76 if (t_oop != nullptr && t_oop->is_known_instance_field()) { 77 int iid = t_oop->instance_id(); 78 int index = C->get_alias_index(t_oop); 79 int offset = t_oop->offset(); 80 phi = new PhiNode(region, type, nullptr, iid, index, offset); 81 } else { 82 phi = PhiNode::make_blank(region, n); 83 } 84 uint old_unique = C->unique(); 85 for (uint i = 1; i < region->req(); i++) { 86 Node* x; 87 Node* the_clone = nullptr; 88 if (region->in(i) == C->top()) { 89 x = C->top(); // Dead path? Use a dead data op 90 } else { 91 x = n->clone(); // Else clone up the data op 92 the_clone = x; // Remember for possible deletion. 93 // Alter data node to use pre-phi inputs 94 if (n->in(0) == region) 95 x->set_req( 0, region->in(i) ); 96 for (uint j = 1; j < n->req(); j++) { 97 Node* in = n->in(j); 98 if (in->is_Phi() && in->in(0) == region) 99 x->set_req(j, in->in(i)); // Use pre-Phi input for the clone 100 } 101 } 102 // Check for a 'win' on some paths 103 const Type* t = x->Value(&_igvn); 104 105 bool singleton = t->singleton(); 106 107 // A TOP singleton indicates that there are no possible values incoming 108 // along a particular edge. In most cases, this is OK, and the Phi will 109 // be eliminated later in an Ideal call. However, we can't allow this to 110 // happen if the singleton occurs on loop entry, as the elimination of 111 // the PhiNode may cause the resulting node to migrate back to a previous 112 // loop iteration. 113 if (singleton && t == Type::TOP) { 114 // Is_Loop() == false does not confirm the absence of a loop (e.g., an 115 // irreducible loop may not be indicated by an affirmative is_Loop()); 116 // therefore, the only top we can split thru a phi is on a backedge of 117 // a loop. 118 singleton &= region->is_Loop() && (i != LoopNode::EntryControl); 119 } 120 121 if (singleton) { 122 wins++; 123 x = makecon(t); 124 } else { 125 // We now call Identity to try to simplify the cloned node. 126 // Note that some Identity methods call phase->type(this). 127 // Make sure that the type array is big enough for 128 // our new node, even though we may throw the node away. 129 // (Note: This tweaking with igvn only works because x is a new node.) 130 _igvn.set_type(x, t); 131 // If x is a TypeNode, capture any more-precise type permanently into Node 132 // otherwise it will be not updated during igvn->transform since 133 // igvn->type(x) is set to x->Value() already. 134 x->raise_bottom_type(t); 135 Node* y = x->Identity(&_igvn); 136 if (y != x) { 137 wins++; 138 x = y; 139 } else { 140 y = _igvn.hash_find(x); 141 if (y == nullptr) { 142 y = similar_subtype_check(x, region->in(i)); 143 } 144 if (y) { 145 wins++; 146 x = y; 147 } else { 148 // Else x is a new node we are keeping 149 // We do not need register_new_node_with_optimizer 150 // because set_type has already been called. 151 _igvn._worklist.push(x); 152 } 153 } 154 } 155 156 phi->set_req( i, x ); 157 158 if (the_clone == nullptr) { 159 continue; 160 } 161 162 if (the_clone != x) { 163 _igvn.remove_dead_node(the_clone); 164 } else if (region->is_Loop() && i == LoopNode::LoopBackControl && 165 n->is_Load() && can_move_to_inner_loop(n, region->as_Loop(), x)) { 166 // it is not a win if 'x' moved from an outer to an inner loop 167 // this edge case can only happen for Load nodes 168 wins = 0; 169 break; 170 } 171 } 172 // Too few wins? 173 if (wins <= policy) { 174 _igvn.remove_dead_node(phi); 175 return nullptr; 176 } 177 178 // Record Phi 179 register_new_node( phi, region ); 180 181 for (uint i2 = 1; i2 < phi->req(); i2++) { 182 Node *x = phi->in(i2); 183 // If we commoned up the cloned 'x' with another existing Node, 184 // the existing Node picks up a new use. We need to make the 185 // existing Node occur higher up so it dominates its uses. 186 Node *old_ctrl; 187 IdealLoopTree *old_loop; 188 189 if (x->is_Con()) { 190 assert(get_ctrl(x) == C->root(), "constant control is not root"); 191 continue; 192 } 193 // The occasional new node 194 if (x->_idx >= old_unique) { // Found a new, unplaced node? 195 old_ctrl = nullptr; 196 old_loop = nullptr; // Not in any prior loop 197 } else { 198 old_ctrl = get_ctrl(x); 199 old_loop = get_loop(old_ctrl); // Get prior loop 200 } 201 // New late point must dominate new use 202 Node *new_ctrl = dom_lca(old_ctrl, region->in(i2)); 203 if (new_ctrl == old_ctrl) // Nothing is changed 204 continue; 205 206 IdealLoopTree *new_loop = get_loop(new_ctrl); 207 208 // Don't move x into a loop if its uses are 209 // outside of loop. Otherwise x will be cloned 210 // for each use outside of this loop. 211 IdealLoopTree *use_loop = get_loop(region); 212 if (!new_loop->is_member(use_loop) && 213 (old_loop == nullptr || !new_loop->is_member(old_loop))) { 214 // Take early control, later control will be recalculated 215 // during next iteration of loop optimizations. 216 new_ctrl = get_early_ctrl(x); 217 new_loop = get_loop(new_ctrl); 218 } 219 // Set new location 220 set_ctrl(x, new_ctrl); 221 // If changing loop bodies, see if we need to collect into new body 222 if (old_loop != new_loop) { 223 if (old_loop && !old_loop->_child) 224 old_loop->_body.yank(x); 225 if (!new_loop->_child) 226 new_loop->_body.push(x); // Collect body info 227 } 228 } 229 230 return phi; 231 } 232 233 // Test whether node 'x' can move into an inner loop relative to node 'n'. 234 // Note: The test is not exact. Returns true if 'x' COULD end up in an inner loop, 235 // BUT it can also return true and 'x' is in the outer loop 236 bool PhaseIdealLoop::can_move_to_inner_loop(Node* n, LoopNode* n_loop, Node* x) { 237 IdealLoopTree* n_loop_tree = get_loop(n_loop); 238 IdealLoopTree* x_loop_tree = get_loop(get_early_ctrl(x)); 239 // x_loop_tree should be outer or same loop as n_loop_tree 240 return !x_loop_tree->is_member(n_loop_tree); 241 } 242 243 // Subtype checks that carry profile data don't common so look for a replacement by following edges 244 Node* PhaseIdealLoop::similar_subtype_check(const Node* x, Node* r_in) { 245 if (x->is_SubTypeCheck()) { 246 Node* in1 = x->in(1); 247 for (DUIterator_Fast imax, i = in1->fast_outs(imax); i < imax; i++) { 248 Node* u = in1->fast_out(i); 249 if (u != x && u->is_SubTypeCheck() && u->in(1) == x->in(1) && u->in(2) == x->in(2)) { 250 for (DUIterator_Fast jmax, j = u->fast_outs(jmax); j < jmax; j++) { 251 Node* bol = u->fast_out(j); 252 for (DUIterator_Fast kmax, k = bol->fast_outs(kmax); k < kmax; k++) { 253 Node* iff = bol->fast_out(k); 254 // Only dominating subtype checks are interesting: otherwise we risk replacing a subtype check by another with 255 // unrelated profile 256 if (iff->is_If() && is_dominator(iff, r_in)) { 257 return u; 258 } 259 } 260 } 261 } 262 } 263 } 264 return nullptr; 265 } 266 267 // Return true if 'n' is a Div or Mod node (without zero check If node which was removed earlier) with a loop phi divisor 268 // of a trip-counted (integer or long) loop with a backedge input that could be zero (include zero in its type range). In 269 // this case, we cannot split the division to the backedge as it could freely float above the loop exit check resulting in 270 // a division by zero. This situation is possible because the type of an increment node of an iv phi (trip-counter) could 271 // include zero while the iv phi does not (see PhiNode::Value() for trip-counted loops where we improve types of iv phis). 272 // We also need to check other loop phis as they could have been created in the same split-if pass when applying 273 // PhaseIdealLoop::split_thru_phi() to split nodes through an iv phi. 274 bool PhaseIdealLoop::cannot_split_division(const Node* n, const Node* region) const { 275 const Type* zero; 276 switch (n->Opcode()) { 277 case Op_DivI: 278 case Op_ModI: 279 case Op_UDivI: 280 case Op_UModI: 281 zero = TypeInt::ZERO; 282 break; 283 case Op_DivL: 284 case Op_ModL: 285 case Op_UDivL: 286 case Op_UModL: 287 zero = TypeLong::ZERO; 288 break; 289 default: 290 return false; 291 } 292 293 if (n->in(0) != nullptr) { 294 // Cannot split through phi if Div or Mod node has a control dependency to a zero check. 295 return true; 296 } 297 298 Node* divisor = n->in(2); 299 return is_divisor_loop_phi(divisor, region) && 300 loop_phi_backedge_type_contains_zero(divisor, zero); 301 } 302 303 bool PhaseIdealLoop::is_divisor_loop_phi(const Node* divisor, const Node* loop) { 304 return loop->is_Loop() && divisor->is_Phi() && divisor->in(0) == loop; 305 } 306 307 bool PhaseIdealLoop::loop_phi_backedge_type_contains_zero(const Node* phi_divisor, const Type* zero) const { 308 return _igvn.type(phi_divisor->in(LoopNode::LoopBackControl))->filter_speculative(zero) != Type::TOP; 309 } 310 311 //------------------------------dominated_by------------------------------------ 312 // Replace the dominated test with an obvious true or false. Place it on the 313 // IGVN worklist for later cleanup. Move control-dependent data Nodes on the 314 // live path up to the dominating control. 315 void PhaseIdealLoop::dominated_by(IfProjNode* prevdom, IfNode* iff, bool flip, bool pin_array_access_nodes) { 316 if (VerifyLoopOptimizations && PrintOpto) { tty->print_cr("dominating test"); } 317 318 // prevdom is the dominating projection of the dominating test. 319 assert(iff->Opcode() == Op_If || 320 iff->Opcode() == Op_CountedLoopEnd || 321 iff->Opcode() == Op_LongCountedLoopEnd || 322 iff->Opcode() == Op_RangeCheck || 323 iff->Opcode() == Op_ParsePredicate, 324 "Check this code when new subtype is added"); 325 326 int pop = prevdom->Opcode(); 327 assert( pop == Op_IfFalse || pop == Op_IfTrue, "" ); 328 if (flip) { 329 if (pop == Op_IfTrue) 330 pop = Op_IfFalse; 331 else 332 pop = Op_IfTrue; 333 } 334 // 'con' is set to true or false to kill the dominated test. 335 Node* con = makecon(pop == Op_IfTrue ? TypeInt::ONE : TypeInt::ZERO); 336 // Hack the dominated test 337 _igvn.replace_input_of(iff, 1, con); 338 339 // If I don't have a reachable TRUE and FALSE path following the IfNode then 340 // I can assume this path reaches an infinite loop. In this case it's not 341 // important to optimize the data Nodes - either the whole compilation will 342 // be tossed or this path (and all data Nodes) will go dead. 343 if (iff->outcnt() != 2) { 344 return; 345 } 346 347 // Make control-dependent data Nodes on the live path (path that will remain 348 // once the dominated IF is removed) become control-dependent on the 349 // dominating projection. 350 Node* dp = iff->proj_out_or_null(pop == Op_IfTrue); 351 352 if (dp == nullptr) { 353 return; 354 } 355 356 rewire_safe_outputs_to_dominator(dp, prevdom, pin_array_access_nodes); 357 } 358 359 void PhaseIdealLoop::rewire_safe_outputs_to_dominator(Node* source, Node* dominator, const bool pin_array_access_nodes) { 360 IdealLoopTree* old_loop = get_loop(source); 361 362 for (DUIterator_Fast imax, i = source->fast_outs(imax); i < imax; i++) { 363 Node* out = source->fast_out(i); // Control-dependent node 364 // Do not rewire Div and Mod nodes which could have a zero divisor to avoid skipping their zero check. 365 if (out->depends_only_on_test() && _igvn.no_dependent_zero_check(out)) { 366 assert(out->in(0) == source, "must be control dependent on source"); 367 _igvn.replace_input_of(out, 0, dominator); 368 if (pin_array_access_nodes) { 369 // Because of Loop Predication, Loads and range check Cast nodes that are control dependent on this range 370 // check (that is about to be removed) now depend on multiple dominating Hoisted Check Predicates. After the 371 // removal of this range check, these control dependent nodes end up at the lowest/nearest dominating predicate 372 // in the graph. To ensure that these Loads/Casts do not float above any of the dominating checks (even when the 373 // lowest dominating check is later replaced by yet another dominating check), we need to pin them at the lowest 374 // dominating check. 375 Node* clone = out->pin_array_access_node(); 376 if (clone != nullptr) { 377 clone = _igvn.register_new_node_with_optimizer(clone, out); 378 _igvn.replace_node(out, clone); 379 out = clone; 380 } 381 } 382 set_early_ctrl(out, false); 383 IdealLoopTree* new_loop = get_loop(get_ctrl(out)); 384 if (old_loop != new_loop) { 385 if (!old_loop->_child) { 386 old_loop->_body.yank(out); 387 } 388 if (!new_loop->_child) { 389 new_loop->_body.push(out); 390 } 391 } 392 --i; 393 --imax; 394 } 395 } 396 } 397 398 //------------------------------has_local_phi_input---------------------------- 399 // Return TRUE if 'n' has Phi inputs from its local block and no other 400 // block-local inputs (all non-local-phi inputs come from earlier blocks) 401 Node *PhaseIdealLoop::has_local_phi_input( Node *n ) { 402 Node *n_ctrl = get_ctrl(n); 403 // See if some inputs come from a Phi in this block, or from before 404 // this block. 405 uint i; 406 for( i = 1; i < n->req(); i++ ) { 407 Node *phi = n->in(i); 408 if( phi->is_Phi() && phi->in(0) == n_ctrl ) 409 break; 410 } 411 if( i >= n->req() ) 412 return nullptr; // No Phi inputs; nowhere to clone thru 413 414 // Check for inputs created between 'n' and the Phi input. These 415 // must split as well; they have already been given the chance 416 // (courtesy of a post-order visit) and since they did not we must 417 // recover the 'cost' of splitting them by being very profitable 418 // when splitting 'n'. Since this is unlikely we simply give up. 419 for( i = 1; i < n->req(); i++ ) { 420 Node *m = n->in(i); 421 if( get_ctrl(m) == n_ctrl && !m->is_Phi() ) { 422 // We allow the special case of AddP's with no local inputs. 423 // This allows us to split-up address expressions. 424 if (m->is_AddP() && 425 get_ctrl(m->in(AddPNode::Base)) != n_ctrl && 426 get_ctrl(m->in(AddPNode::Address)) != n_ctrl && 427 get_ctrl(m->in(AddPNode::Offset)) != n_ctrl) { 428 // Move the AddP up to the dominating point. That's fine because control of m's inputs 429 // must dominate get_ctrl(m) == n_ctrl and we just checked that the input controls are != n_ctrl. 430 Node* c = find_non_split_ctrl(idom(n_ctrl)); 431 if (c->is_OuterStripMinedLoop()) { 432 c->as_Loop()->verify_strip_mined(1); 433 c = c->in(LoopNode::EntryControl); 434 } 435 set_ctrl_and_loop(m, c); 436 continue; 437 } 438 return nullptr; 439 } 440 assert(n->is_Phi() || m->is_Phi() || is_dominator(get_ctrl(m), n_ctrl), "m has strange control"); 441 } 442 443 return n_ctrl; 444 } 445 446 // Replace expressions like ((V+I) << 2) with (V<<2 + I<<2). 447 Node* PhaseIdealLoop::remix_address_expressions_add_left_shift(Node* n, IdealLoopTree* n_loop, Node* n_ctrl, BasicType bt) { 448 assert(bt == T_INT || bt == T_LONG, "only for integers"); 449 int n_op = n->Opcode(); 450 451 if (n_op == Op_LShift(bt)) { 452 // Scale is loop invariant 453 Node* scale = n->in(2); 454 Node* scale_ctrl = get_ctrl(scale); 455 IdealLoopTree* scale_loop = get_loop(scale_ctrl); 456 if (n_loop == scale_loop || !scale_loop->is_member(n_loop)) { 457 return nullptr; 458 } 459 const TypeInt* scale_t = scale->bottom_type()->isa_int(); 460 if (scale_t != nullptr && scale_t->is_con() && scale_t->get_con() >= 16) { 461 return nullptr; // Dont bother with byte/short masking 462 } 463 // Add must vary with loop (else shift would be loop-invariant) 464 Node* add = n->in(1); 465 Node* add_ctrl = get_ctrl(add); 466 IdealLoopTree* add_loop = get_loop(add_ctrl); 467 if (n_loop != add_loop) { 468 return nullptr; // happens w/ evil ZKM loops 469 } 470 471 // Convert I-V into I+ (0-V); same for V-I 472 if (add->Opcode() == Op_Sub(bt) && 473 _igvn.type(add->in(1)) != TypeInteger::zero(bt)) { 474 assert(add->Opcode() == Op_SubI || add->Opcode() == Op_SubL, ""); 475 Node* zero = integercon(0, bt); 476 Node* neg = SubNode::make(zero, add->in(2), bt); 477 register_new_node_with_ctrl_of(neg, add->in(2)); 478 add = AddNode::make(add->in(1), neg, bt); 479 register_new_node(add, add_ctrl); 480 } 481 if (add->Opcode() != Op_Add(bt)) return nullptr; 482 assert(add->Opcode() == Op_AddI || add->Opcode() == Op_AddL, ""); 483 // See if one add input is loop invariant 484 Node* add_var = add->in(1); 485 Node* add_var_ctrl = get_ctrl(add_var); 486 IdealLoopTree* add_var_loop = get_loop(add_var_ctrl); 487 Node* add_invar = add->in(2); 488 Node* add_invar_ctrl = get_ctrl(add_invar); 489 IdealLoopTree* add_invar_loop = get_loop(add_invar_ctrl); 490 if (add_invar_loop == n_loop) { 491 // Swap to find the invariant part 492 add_invar = add_var; 493 add_invar_ctrl = add_var_ctrl; 494 add_invar_loop = add_var_loop; 495 add_var = add->in(2); 496 } else if (add_var_loop != n_loop) { // Else neither input is loop invariant 497 return nullptr; 498 } 499 if (n_loop == add_invar_loop || !add_invar_loop->is_member(n_loop)) { 500 return nullptr; // No invariant part of the add? 501 } 502 503 // Yes! Reshape address expression! 504 Node* inv_scale = LShiftNode::make(add_invar, scale, bt); 505 Node* inv_scale_ctrl = 506 dom_depth(add_invar_ctrl) > dom_depth(scale_ctrl) ? 507 add_invar_ctrl : scale_ctrl; 508 register_new_node(inv_scale, inv_scale_ctrl); 509 Node* var_scale = LShiftNode::make(add_var, scale, bt); 510 register_new_node(var_scale, n_ctrl); 511 Node* var_add = AddNode::make(var_scale, inv_scale, bt); 512 register_new_node(var_add, n_ctrl); 513 _igvn.replace_node(n, var_add); 514 return var_add; 515 } 516 return nullptr; 517 } 518 519 //------------------------------remix_address_expressions---------------------- 520 // Rework addressing expressions to get the most loop-invariant stuff 521 // moved out. We'd like to do all associative operators, but it's especially 522 // important (common) to do address expressions. 523 Node* PhaseIdealLoop::remix_address_expressions(Node* n) { 524 if (!has_ctrl(n)) return nullptr; 525 Node* n_ctrl = get_ctrl(n); 526 IdealLoopTree* n_loop = get_loop(n_ctrl); 527 528 // See if 'n' mixes loop-varying and loop-invariant inputs and 529 // itself is loop-varying. 530 531 // Only interested in binary ops (and AddP) 532 if (n->req() < 3 || n->req() > 4) return nullptr; 533 534 Node* n1_ctrl = get_ctrl(n->in( 1)); 535 Node* n2_ctrl = get_ctrl(n->in( 2)); 536 Node* n3_ctrl = get_ctrl(n->in(n->req() == 3 ? 2 : 3)); 537 IdealLoopTree* n1_loop = get_loop(n1_ctrl); 538 IdealLoopTree* n2_loop = get_loop(n2_ctrl); 539 IdealLoopTree* n3_loop = get_loop(n3_ctrl); 540 541 // Does one of my inputs spin in a tighter loop than self? 542 if ((n_loop->is_member(n1_loop) && n_loop != n1_loop) || 543 (n_loop->is_member(n2_loop) && n_loop != n2_loop) || 544 (n_loop->is_member(n3_loop) && n_loop != n3_loop)) { 545 return nullptr; // Leave well enough alone 546 } 547 548 // Is at least one of my inputs loop-invariant? 549 if (n1_loop == n_loop && 550 n2_loop == n_loop && 551 n3_loop == n_loop) { 552 return nullptr; // No loop-invariant inputs 553 } 554 555 Node* res = remix_address_expressions_add_left_shift(n, n_loop, n_ctrl, T_INT); 556 if (res != nullptr) { 557 return res; 558 } 559 res = remix_address_expressions_add_left_shift(n, n_loop, n_ctrl, T_LONG); 560 if (res != nullptr) { 561 return res; 562 } 563 564 int n_op = n->Opcode(); 565 // Replace (I+V) with (V+I) 566 if (n_op == Op_AddI || 567 n_op == Op_AddL || 568 n_op == Op_AddF || 569 n_op == Op_AddD || 570 n_op == Op_MulI || 571 n_op == Op_MulL || 572 n_op == Op_MulF || 573 n_op == Op_MulD) { 574 if (n2_loop == n_loop) { 575 assert(n1_loop != n_loop, ""); 576 n->swap_edges(1, 2); 577 } 578 } 579 580 // Replace ((I1 +p V) +p I2) with ((I1 +p I2) +p V), 581 // but not if I2 is a constant. Skip for irreducible loops. 582 if (n_op == Op_AddP && n_loop->_head->is_Loop()) { 583 if (n2_loop == n_loop && n3_loop != n_loop) { 584 if (n->in(2)->Opcode() == Op_AddP && !n->in(3)->is_Con()) { 585 Node* n22_ctrl = get_ctrl(n->in(2)->in(2)); 586 Node* n23_ctrl = get_ctrl(n->in(2)->in(3)); 587 IdealLoopTree* n22loop = get_loop(n22_ctrl); 588 IdealLoopTree* n23_loop = get_loop(n23_ctrl); 589 if (n22loop != n_loop && n22loop->is_member(n_loop) && 590 n23_loop == n_loop) { 591 Node* add1 = new AddPNode(n->in(1), n->in(2)->in(2), n->in(3)); 592 // Stuff new AddP in the loop preheader 593 register_new_node(add1, n_loop->_head->as_Loop()->skip_strip_mined(1)->in(LoopNode::EntryControl)); 594 Node* add2 = new AddPNode(n->in(1), add1, n->in(2)->in(3)); 595 register_new_node(add2, n_ctrl); 596 _igvn.replace_node(n, add2); 597 return add2; 598 } 599 } 600 } 601 602 // Replace (I1 +p (I2 + V)) with ((I1 +p I2) +p V) 603 if (n2_loop != n_loop && n3_loop == n_loop) { 604 if (n->in(3)->Opcode() == Op_AddX) { 605 Node* V = n->in(3)->in(1); 606 Node* I = n->in(3)->in(2); 607 if (is_member(n_loop,get_ctrl(V))) { 608 } else { 609 Node *tmp = V; V = I; I = tmp; 610 } 611 if (!is_member(n_loop,get_ctrl(I))) { 612 Node* add1 = new AddPNode(n->in(1), n->in(2), I); 613 // Stuff new AddP in the loop preheader 614 register_new_node(add1, n_loop->_head->as_Loop()->skip_strip_mined(1)->in(LoopNode::EntryControl)); 615 Node* add2 = new AddPNode(n->in(1), add1, V); 616 register_new_node(add2, n_ctrl); 617 _igvn.replace_node(n, add2); 618 return add2; 619 } 620 } 621 } 622 } 623 624 return nullptr; 625 } 626 627 // Optimize ((in1[2*i] * in2[2*i]) + (in1[2*i+1] * in2[2*i+1])) 628 Node *PhaseIdealLoop::convert_add_to_muladd(Node* n) { 629 assert(n->Opcode() == Op_AddI, "sanity"); 630 Node * nn = nullptr; 631 Node * in1 = n->in(1); 632 Node * in2 = n->in(2); 633 if (in1->Opcode() == Op_MulI && in2->Opcode() == Op_MulI) { 634 IdealLoopTree* loop_n = get_loop(get_ctrl(n)); 635 if (loop_n->is_counted() && 636 loop_n->_head->as_Loop()->is_valid_counted_loop(T_INT) && 637 Matcher::match_rule_supported(Op_MulAddVS2VI) && 638 Matcher::match_rule_supported(Op_MulAddS2I)) { 639 Node* mul_in1 = in1->in(1); 640 Node* mul_in2 = in1->in(2); 641 Node* mul_in3 = in2->in(1); 642 Node* mul_in4 = in2->in(2); 643 if (mul_in1->Opcode() == Op_LoadS && 644 mul_in2->Opcode() == Op_LoadS && 645 mul_in3->Opcode() == Op_LoadS && 646 mul_in4->Opcode() == Op_LoadS) { 647 IdealLoopTree* loop1 = get_loop(get_ctrl(mul_in1)); 648 IdealLoopTree* loop2 = get_loop(get_ctrl(mul_in2)); 649 IdealLoopTree* loop3 = get_loop(get_ctrl(mul_in3)); 650 IdealLoopTree* loop4 = get_loop(get_ctrl(mul_in4)); 651 IdealLoopTree* loop5 = get_loop(get_ctrl(in1)); 652 IdealLoopTree* loop6 = get_loop(get_ctrl(in2)); 653 // All nodes should be in the same counted loop. 654 if (loop_n == loop1 && loop_n == loop2 && loop_n == loop3 && 655 loop_n == loop4 && loop_n == loop5 && loop_n == loop6) { 656 Node* adr1 = mul_in1->in(MemNode::Address); 657 Node* adr2 = mul_in2->in(MemNode::Address); 658 Node* adr3 = mul_in3->in(MemNode::Address); 659 Node* adr4 = mul_in4->in(MemNode::Address); 660 if (adr1->is_AddP() && adr2->is_AddP() && adr3->is_AddP() && adr4->is_AddP()) { 661 if ((adr1->in(AddPNode::Base) == adr3->in(AddPNode::Base)) && 662 (adr2->in(AddPNode::Base) == adr4->in(AddPNode::Base))) { 663 nn = new MulAddS2INode(mul_in1, mul_in2, mul_in3, mul_in4); 664 register_new_node_with_ctrl_of(nn, n); 665 _igvn.replace_node(n, nn); 666 return nn; 667 } else if ((adr1->in(AddPNode::Base) == adr4->in(AddPNode::Base)) && 668 (adr2->in(AddPNode::Base) == adr3->in(AddPNode::Base))) { 669 nn = new MulAddS2INode(mul_in1, mul_in2, mul_in4, mul_in3); 670 register_new_node_with_ctrl_of(nn, n); 671 _igvn.replace_node(n, nn); 672 return nn; 673 } 674 } 675 } 676 } 677 } 678 } 679 return nn; 680 } 681 682 //------------------------------conditional_move------------------------------- 683 // Attempt to replace a Phi with a conditional move. We have some pretty 684 // strict profitability requirements. All Phis at the merge point must 685 // be converted, so we can remove the control flow. We need to limit the 686 // number of c-moves to a small handful. All code that was in the side-arms 687 // of the CFG diamond is now speculatively executed. This code has to be 688 // "cheap enough". We are pretty much limited to CFG diamonds that merge 689 // 1 or 2 items with a total of 1 or 2 ops executed speculatively. 690 Node *PhaseIdealLoop::conditional_move( Node *region ) { 691 692 assert(region->is_Region(), "sanity check"); 693 if (region->req() != 3) return nullptr; 694 695 // Check for CFG diamond 696 Node *lp = region->in(1); 697 Node *rp = region->in(2); 698 if (!lp || !rp) return nullptr; 699 Node *lp_c = lp->in(0); 700 if (lp_c == nullptr || lp_c != rp->in(0) || !lp_c->is_If()) return nullptr; 701 IfNode *iff = lp_c->as_If(); 702 703 // Check for ops pinned in an arm of the diamond. 704 // Can't remove the control flow in this case 705 if (lp->outcnt() > 1) return nullptr; 706 if (rp->outcnt() > 1) return nullptr; 707 708 IdealLoopTree* r_loop = get_loop(region); 709 assert(r_loop == get_loop(iff), "sanity"); 710 // Always convert to CMOVE if all results are used only outside this loop. 711 bool used_inside_loop = (r_loop == _ltree_root); 712 713 // Check profitability 714 int cost = 0; 715 int phis = 0; 716 for (DUIterator_Fast imax, i = region->fast_outs(imax); i < imax; i++) { 717 Node *out = region->fast_out(i); 718 if (!out->is_Phi()) continue; // Ignore other control edges, etc 719 phis++; 720 PhiNode* phi = out->as_Phi(); 721 BasicType bt = phi->type()->basic_type(); 722 switch (bt) { 723 case T_DOUBLE: 724 case T_FLOAT: 725 if (C->use_cmove()) { 726 continue; //TODO: maybe we want to add some cost 727 } 728 cost += Matcher::float_cmove_cost(); // Could be very expensive 729 break; 730 case T_LONG: { 731 cost += Matcher::long_cmove_cost(); // May encodes as 2 CMOV's 732 } 733 case T_INT: // These all CMOV fine 734 case T_ADDRESS: { // (RawPtr) 735 cost++; 736 break; 737 } 738 case T_NARROWOOP: // Fall through 739 case T_OBJECT: { // Base oops are OK, but not derived oops 740 const TypeOopPtr *tp = phi->type()->make_ptr()->isa_oopptr(); 741 // Derived pointers are Bad (tm): what's the Base (for GC purposes) of a 742 // CMOVE'd derived pointer? It's a CMOVE'd derived base. Thus 743 // CMOVE'ing a derived pointer requires we also CMOVE the base. If we 744 // have a Phi for the base here that we convert to a CMOVE all is well 745 // and good. But if the base is dead, we'll not make a CMOVE. Later 746 // the allocator will have to produce a base by creating a CMOVE of the 747 // relevant bases. This puts the allocator in the business of 748 // manufacturing expensive instructions, generally a bad plan. 749 // Just Say No to Conditionally-Moved Derived Pointers. 750 if (tp && tp->offset() != 0) 751 return nullptr; 752 cost++; 753 break; 754 } 755 default: 756 return nullptr; // In particular, can't do memory or I/O 757 } 758 // Add in cost any speculative ops 759 for (uint j = 1; j < region->req(); j++) { 760 Node *proj = region->in(j); 761 Node *inp = phi->in(j); 762 if (get_ctrl(inp) == proj) { // Found local op 763 cost++; 764 // Check for a chain of dependent ops; these will all become 765 // speculative in a CMOV. 766 for (uint k = 1; k < inp->req(); k++) 767 if (get_ctrl(inp->in(k)) == proj) 768 cost += ConditionalMoveLimit; // Too much speculative goo 769 } 770 } 771 // See if the Phi is used by a Cmp or Narrow oop Decode/Encode. 772 // This will likely Split-If, a higher-payoff operation. 773 for (DUIterator_Fast kmax, k = phi->fast_outs(kmax); k < kmax; k++) { 774 Node* use = phi->fast_out(k); 775 if (use->is_Cmp() || use->is_DecodeNarrowPtr() || use->is_EncodeNarrowPtr()) 776 cost += ConditionalMoveLimit; 777 // Is there a use inside the loop? 778 // Note: check only basic types since CMoveP is pinned. 779 if (!used_inside_loop && is_java_primitive(bt)) { 780 IdealLoopTree* u_loop = get_loop(has_ctrl(use) ? get_ctrl(use) : use); 781 if (r_loop == u_loop || r_loop->is_member(u_loop)) { 782 used_inside_loop = true; 783 } 784 } 785 } 786 }//for 787 Node* bol = iff->in(1); 788 assert(!bol->is_OpaqueInitializedAssertionPredicate(), "Initialized Assertion Predicates cannot form a diamond with Halt"); 789 if (bol->is_OpaqueTemplateAssertionPredicate()) { 790 // Ignore Template Assertion Predicates with OpaqueTemplateAssertionPredicate nodes. 791 return nullptr; 792 } 793 if (bol->is_OpaqueMultiversioning()) { 794 assert(bol->as_OpaqueMultiversioning()->is_useless(), "Must be useless, i.e. fast main loop has already disappeared."); 795 // Ignore multiversion_if that just lost its loops. The OpaqueMultiversioning is marked useless, 796 // and will make the multiversion_if constant fold in the next IGVN round. 797 return nullptr; 798 } 799 if (!bol->is_Bool()) { 800 assert(false, "Expected Bool, but got %s", NodeClassNames[bol->Opcode()]); 801 return nullptr; 802 } 803 int cmp_op = bol->in(1)->Opcode(); 804 if (cmp_op == Op_SubTypeCheck) { // SubTypeCheck expansion expects an IfNode 805 return nullptr; 806 } 807 // It is expensive to generate flags from a float compare. 808 // Avoid duplicated float compare. 809 if (phis > 1 && (cmp_op == Op_CmpF || cmp_op == Op_CmpD)) return nullptr; 810 811 float infrequent_prob = PROB_UNLIKELY_MAG(3); 812 // Ignore cost and blocks frequency if CMOVE can be moved outside the loop. 813 if (used_inside_loop) { 814 if (cost >= ConditionalMoveLimit) return nullptr; // Too much goo 815 816 // BlockLayoutByFrequency optimization moves infrequent branch 817 // from hot path. No point in CMOV'ing in such case (110 is used 818 // instead of 100 to take into account not exactness of float value). 819 if (BlockLayoutByFrequency) { 820 infrequent_prob = MAX2(infrequent_prob, (float)BlockLayoutMinDiamondPercentage/110.0f); 821 } 822 } 823 // Check for highly predictable branch. No point in CMOV'ing if 824 // we are going to predict accurately all the time. 825 if (C->use_cmove() && (cmp_op == Op_CmpF || cmp_op == Op_CmpD)) { 826 //keep going 827 } else if (iff->_prob < infrequent_prob || 828 iff->_prob > (1.0f - infrequent_prob)) 829 return nullptr; 830 831 // -------------- 832 // Now replace all Phis with CMOV's 833 Node *cmov_ctrl = iff->in(0); 834 uint flip = (lp->Opcode() == Op_IfTrue); 835 Node_List wq; 836 while (1) { 837 PhiNode* phi = nullptr; 838 for (DUIterator_Fast imax, i = region->fast_outs(imax); i < imax; i++) { 839 Node *out = region->fast_out(i); 840 if (out->is_Phi()) { 841 phi = out->as_Phi(); 842 break; 843 } 844 } 845 if (phi == nullptr || _igvn.type(phi) == Type::TOP || !CMoveNode::supported(_igvn.type(phi))) { 846 break; 847 } 848 // Move speculative ops 849 wq.push(phi); 850 while (wq.size() > 0) { 851 Node *n = wq.pop(); 852 for (uint j = 1; j < n->req(); j++) { 853 Node* m = n->in(j); 854 if (m != nullptr && !is_dominator(get_ctrl(m), cmov_ctrl)) { 855 set_ctrl(m, cmov_ctrl); 856 wq.push(m); 857 } 858 } 859 } 860 Node* cmov = CMoveNode::make(iff->in(1), phi->in(1+flip), phi->in(2-flip), _igvn.type(phi)); 861 register_new_node(cmov, cmov_ctrl); 862 _igvn.replace_node(phi, cmov); 863 #ifndef PRODUCT 864 if (TraceLoopOpts) { 865 tty->print("CMOV "); 866 r_loop->dump_head(); 867 if (Verbose) { 868 bol->in(1)->dump(1); 869 cmov->dump(1); 870 } 871 } 872 DEBUG_ONLY( if (VerifyLoopOptimizations) { verify(); } ); 873 #endif 874 } 875 876 // The useless CFG diamond will fold up later; see the optimization in 877 // RegionNode::Ideal. 878 _igvn._worklist.push(region); 879 880 return iff->in(1); 881 } 882 883 static void enqueue_cfg_uses(Node* m, Unique_Node_List& wq) { 884 for (DUIterator_Fast imax, i = m->fast_outs(imax); i < imax; i++) { 885 Node* u = m->fast_out(i); 886 if (u->is_CFG()) { 887 if (u->is_NeverBranch()) { 888 u = u->as_NeverBranch()->proj_out(0); 889 enqueue_cfg_uses(u, wq); 890 } else { 891 wq.push(u); 892 } 893 } 894 } 895 } 896 897 // Try moving a store out of a loop, right before the loop 898 Node* PhaseIdealLoop::try_move_store_before_loop(Node* n, Node *n_ctrl) { 899 // Store has to be first in the loop body 900 IdealLoopTree *n_loop = get_loop(n_ctrl); 901 if (n->is_Store() && n_loop != _ltree_root && 902 n_loop->is_loop() && n_loop->_head->is_Loop() && 903 n->in(0) != nullptr) { 904 Node* address = n->in(MemNode::Address); 905 Node* value = n->in(MemNode::ValueIn); 906 Node* mem = n->in(MemNode::Memory); 907 IdealLoopTree* address_loop = get_loop(get_ctrl(address)); 908 IdealLoopTree* value_loop = get_loop(get_ctrl(value)); 909 910 // - address and value must be loop invariant 911 // - memory must be a memory Phi for the loop 912 // - Store must be the only store on this memory slice in the 913 // loop: if there's another store following this one then value 914 // written at iteration i by the second store could be overwritten 915 // at iteration i+n by the first store: it's not safe to move the 916 // first store out of the loop 917 // - nothing must observe the memory Phi: it guarantees no read 918 // before the store, we are also guaranteed the store post 919 // dominates the loop head (ignoring a possible early 920 // exit). Otherwise there would be extra Phi involved between the 921 // loop's Phi and the store. 922 // - there must be no early exit from the loop before the Store 923 // (such an exit most of the time would be an extra use of the 924 // memory Phi but sometimes is a bottom memory Phi that takes the 925 // store as input). 926 927 if (!n_loop->is_member(address_loop) && 928 !n_loop->is_member(value_loop) && 929 mem->is_Phi() && mem->in(0) == n_loop->_head && 930 mem->outcnt() == 1 && 931 mem->in(LoopNode::LoopBackControl) == n) { 932 933 assert(n_loop->_tail != nullptr, "need a tail"); 934 assert(is_dominator(n_ctrl, n_loop->_tail), "store control must not be in a branch in the loop"); 935 936 // Verify that there's no early exit of the loop before the store. 937 bool ctrl_ok = false; 938 { 939 // Follow control from loop head until n, we exit the loop or 940 // we reach the tail 941 ResourceMark rm; 942 Unique_Node_List wq; 943 wq.push(n_loop->_head); 944 945 for (uint next = 0; next < wq.size(); ++next) { 946 Node *m = wq.at(next); 947 if (m == n->in(0)) { 948 ctrl_ok = true; 949 continue; 950 } 951 assert(!has_ctrl(m), "should be CFG"); 952 if (!n_loop->is_member(get_loop(m)) || m == n_loop->_tail) { 953 ctrl_ok = false; 954 break; 955 } 956 enqueue_cfg_uses(m, wq); 957 if (wq.size() > 10) { 958 ctrl_ok = false; 959 break; 960 } 961 } 962 } 963 if (ctrl_ok) { 964 // move the Store 965 _igvn.replace_input_of(mem, LoopNode::LoopBackControl, mem); 966 _igvn.replace_input_of(n, 0, n_loop->_head->as_Loop()->skip_strip_mined()->in(LoopNode::EntryControl)); 967 _igvn.replace_input_of(n, MemNode::Memory, mem->in(LoopNode::EntryControl)); 968 // Disconnect the phi now. An empty phi can confuse other 969 // optimizations in this pass of loop opts. 970 _igvn.replace_node(mem, mem->in(LoopNode::EntryControl)); 971 n_loop->_body.yank(mem); 972 973 set_ctrl_and_loop(n, n->in(0)); 974 975 return n; 976 } 977 } 978 } 979 return nullptr; 980 } 981 982 // Try moving a store out of a loop, right after the loop 983 void PhaseIdealLoop::try_move_store_after_loop(Node* n) { 984 if (n->is_Store() && n->in(0) != nullptr) { 985 Node *n_ctrl = get_ctrl(n); 986 IdealLoopTree *n_loop = get_loop(n_ctrl); 987 // Store must be in a loop 988 if (n_loop != _ltree_root && !n_loop->_irreducible) { 989 Node* address = n->in(MemNode::Address); 990 Node* value = n->in(MemNode::ValueIn); 991 IdealLoopTree* address_loop = get_loop(get_ctrl(address)); 992 // address must be loop invariant 993 if (!n_loop->is_member(address_loop)) { 994 // Store must be last on this memory slice in the loop and 995 // nothing in the loop must observe it 996 Node* phi = nullptr; 997 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) { 998 Node* u = n->fast_out(i); 999 if (has_ctrl(u)) { // control use? 1000 IdealLoopTree *u_loop = get_loop(get_ctrl(u)); 1001 if (!n_loop->is_member(u_loop)) { 1002 continue; 1003 } 1004 if (u->is_Phi() && u->in(0) == n_loop->_head) { 1005 assert(_igvn.type(u) == Type::MEMORY, "bad phi"); 1006 // multiple phis on the same slice are possible 1007 if (phi != nullptr) { 1008 return; 1009 } 1010 phi = u; 1011 continue; 1012 } 1013 } 1014 return; 1015 } 1016 if (phi != nullptr) { 1017 // Nothing in the loop before the store (next iteration) 1018 // must observe the stored value 1019 bool mem_ok = true; 1020 { 1021 ResourceMark rm; 1022 Unique_Node_List wq; 1023 wq.push(phi); 1024 for (uint next = 0; next < wq.size() && mem_ok; ++next) { 1025 Node *m = wq.at(next); 1026 for (DUIterator_Fast imax, i = m->fast_outs(imax); i < imax && mem_ok; i++) { 1027 Node* u = m->fast_out(i); 1028 if (u->is_Store() || u->is_Phi()) { 1029 if (u != n) { 1030 wq.push(u); 1031 mem_ok = (wq.size() <= 10); 1032 } 1033 } else { 1034 mem_ok = false; 1035 break; 1036 } 1037 } 1038 } 1039 } 1040 if (mem_ok) { 1041 // Move the store out of the loop if the LCA of all 1042 // users (except for the phi) is outside the loop. 1043 Node* hook = new Node(1); 1044 hook->init_req(0, n_ctrl); // Add an input to prevent hook from being dead 1045 _igvn.rehash_node_delayed(phi); 1046 int count = phi->replace_edge(n, hook, &_igvn); 1047 assert(count > 0, "inconsistent phi"); 1048 1049 // Compute latest point this store can go 1050 Node* lca = get_late_ctrl(n, get_ctrl(n)); 1051 if (lca->is_OuterStripMinedLoop()) { 1052 lca = lca->in(LoopNode::EntryControl); 1053 } 1054 if (n_loop->is_member(get_loop(lca))) { 1055 // LCA is in the loop - bail out 1056 _igvn.replace_node(hook, n); 1057 return; 1058 } 1059 #ifdef ASSERT 1060 if (n_loop->_head->is_Loop() && n_loop->_head->as_Loop()->is_strip_mined()) { 1061 assert(n_loop->_head->Opcode() == Op_CountedLoop, "outer loop is a strip mined"); 1062 n_loop->_head->as_Loop()->verify_strip_mined(1); 1063 Node* outer = n_loop->_head->as_CountedLoop()->outer_loop(); 1064 IdealLoopTree* outer_loop = get_loop(outer); 1065 assert(n_loop->_parent == outer_loop, "broken loop tree"); 1066 assert(get_loop(lca) == outer_loop, "safepoint in outer loop consume all memory state"); 1067 } 1068 #endif 1069 lca = place_outside_loop(lca, n_loop); 1070 assert(!n_loop->is_member(get_loop(lca)), "control must not be back in the loop"); 1071 assert(get_loop(lca)->_nest < n_loop->_nest || get_loop(lca)->_head->as_Loop()->is_in_infinite_subgraph(), "must not be moved into inner loop"); 1072 1073 // Move store out of the loop 1074 _igvn.replace_node(hook, n->in(MemNode::Memory)); 1075 _igvn.replace_input_of(n, 0, lca); 1076 set_ctrl_and_loop(n, lca); 1077 1078 // Disconnect the phi now. An empty phi can confuse other 1079 // optimizations in this pass of loop opts.. 1080 if (phi->in(LoopNode::LoopBackControl) == phi) { 1081 _igvn.replace_node(phi, phi->in(LoopNode::EntryControl)); 1082 n_loop->_body.yank(phi); 1083 } 1084 } 1085 } 1086 } 1087 } 1088 } 1089 } 1090 1091 //------------------------------split_if_with_blocks_pre----------------------- 1092 // Do the real work in a non-recursive function. Data nodes want to be 1093 // cloned in the pre-order so they can feed each other nicely. 1094 Node *PhaseIdealLoop::split_if_with_blocks_pre( Node *n ) { 1095 // Cloning these guys is unlikely to win 1096 int n_op = n->Opcode(); 1097 if (n_op == Op_MergeMem) { 1098 return n; 1099 } 1100 if (n->is_Proj()) { 1101 return n; 1102 } 1103 // Do not clone-up CmpFXXX variations, as these are always 1104 // followed by a CmpI 1105 if (n->is_Cmp()) { 1106 return n; 1107 } 1108 // Attempt to use a conditional move instead of a phi/branch 1109 if (ConditionalMoveLimit > 0 && n_op == Op_Region) { 1110 Node *cmov = conditional_move( n ); 1111 if (cmov) { 1112 return cmov; 1113 } 1114 } 1115 if (n->is_CFG() || n->is_LoadStore()) { 1116 return n; 1117 } 1118 if (n->is_Opaque1()) { // Opaque nodes cannot be mod'd 1119 if (!C->major_progress()) { // If chance of no more loop opts... 1120 _igvn._worklist.push(n); // maybe we'll remove them 1121 } 1122 return n; 1123 } 1124 1125 if (n->is_Con()) { 1126 return n; // No cloning for Con nodes 1127 } 1128 1129 Node *n_ctrl = get_ctrl(n); 1130 if (!n_ctrl) { 1131 return n; // Dead node 1132 } 1133 1134 Node* res = try_move_store_before_loop(n, n_ctrl); 1135 if (res != nullptr) { 1136 return n; 1137 } 1138 1139 // Attempt to remix address expressions for loop invariants 1140 Node *m = remix_address_expressions( n ); 1141 if( m ) return m; 1142 1143 if (n_op == Op_AddI) { 1144 Node *nn = convert_add_to_muladd( n ); 1145 if ( nn ) return nn; 1146 } 1147 1148 if (n->is_ConstraintCast()) { 1149 Node* dom_cast = n->as_ConstraintCast()->dominating_cast(&_igvn, this); 1150 // ConstraintCastNode::dominating_cast() uses node control input to determine domination. 1151 // Node control inputs don't necessarily agree with loop control info (due to 1152 // transformations happened in between), thus additional dominance check is needed 1153 // to keep loop info valid. 1154 if (dom_cast != nullptr && is_dominator(get_ctrl(dom_cast), get_ctrl(n))) { 1155 _igvn.replace_node(n, dom_cast); 1156 return dom_cast; 1157 } 1158 } 1159 1160 // Determine if the Node has inputs from some local Phi. 1161 // Returns the block to clone thru. 1162 Node *n_blk = has_local_phi_input( n ); 1163 if( !n_blk ) return n; 1164 1165 // Do not clone the trip counter through on a CountedLoop 1166 // (messes up the canonical shape). 1167 if (((n_blk->is_CountedLoop() || (n_blk->is_Loop() && n_blk->as_Loop()->is_loop_nest_inner_loop())) && n->Opcode() == Op_AddI) || 1168 (n_blk->is_LongCountedLoop() && n->Opcode() == Op_AddL)) { 1169 return n; 1170 } 1171 // Pushing a shift through the iv Phi can get in the way of addressing optimizations or range check elimination 1172 if (n_blk->is_BaseCountedLoop() && n->Opcode() == Op_LShift(n_blk->as_BaseCountedLoop()->bt()) && 1173 n->in(1) == n_blk->as_BaseCountedLoop()->phi()) { 1174 return n; 1175 } 1176 1177 // Check for having no control input; not pinned. Allow 1178 // dominating control. 1179 if (n->in(0)) { 1180 Node *dom = idom(n_blk); 1181 if (dom_lca(n->in(0), dom) != n->in(0)) { 1182 return n; 1183 } 1184 } 1185 // Policy: when is it profitable. You must get more wins than 1186 // policy before it is considered profitable. Policy is usually 0, 1187 // so 1 win is considered profitable. Big merges will require big 1188 // cloning, so get a larger policy. 1189 int policy = n_blk->req() >> 2; 1190 1191 // If the loop is a candidate for range check elimination, 1192 // delay splitting through it's phi until a later loop optimization 1193 if (n_blk->is_BaseCountedLoop()) { 1194 IdealLoopTree *lp = get_loop(n_blk); 1195 if (lp && lp->_rce_candidate) { 1196 return n; 1197 } 1198 } 1199 1200 if (must_throttle_split_if()) return n; 1201 1202 // Split 'n' through the merge point if it is profitable 1203 Node *phi = split_thru_phi( n, n_blk, policy ); 1204 if (!phi) return n; 1205 1206 // Found a Phi to split thru! 1207 // Replace 'n' with the new phi 1208 _igvn.replace_node( n, phi ); 1209 // Moved a load around the loop, 'en-registering' something. 1210 if (n_blk->is_Loop() && n->is_Load() && 1211 !phi->in(LoopNode::LoopBackControl)->is_Load()) 1212 C->set_major_progress(); 1213 1214 return phi; 1215 } 1216 1217 static bool merge_point_too_heavy(Compile* C, Node* region) { 1218 // Bail out if the region and its phis have too many users. 1219 int weight = 0; 1220 for (DUIterator_Fast imax, i = region->fast_outs(imax); i < imax; i++) { 1221 weight += region->fast_out(i)->outcnt(); 1222 } 1223 int nodes_left = C->max_node_limit() - C->live_nodes(); 1224 if (weight * 8 > nodes_left) { 1225 if (PrintOpto) { 1226 tty->print_cr("*** Split-if bails out: %d nodes, region weight %d", C->unique(), weight); 1227 } 1228 return true; 1229 } else { 1230 return false; 1231 } 1232 } 1233 1234 static bool merge_point_safe(Node* region) { 1235 // 4799512: Stop split_if_with_blocks from splitting a block with a ConvI2LNode 1236 // having a PhiNode input. This sidesteps the dangerous case where the split 1237 // ConvI2LNode may become TOP if the input Value() does not 1238 // overlap the ConvI2L range, leaving a node which may not dominate its 1239 // uses. 1240 // A better fix for this problem can be found in the BugTraq entry, but 1241 // expediency for Mantis demands this hack. 1242 #ifdef _LP64 1243 for (DUIterator_Fast imax, i = region->fast_outs(imax); i < imax; i++) { 1244 Node* n = region->fast_out(i); 1245 if (n->is_Phi()) { 1246 for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++) { 1247 Node* m = n->fast_out(j); 1248 if (m->Opcode() == Op_ConvI2L) 1249 return false; 1250 if (m->is_CastII()) { 1251 return false; 1252 } 1253 } 1254 } 1255 } 1256 #endif 1257 return true; 1258 } 1259 1260 1261 //------------------------------place_outside_loop--------------------------------- 1262 // Place some computation outside of this loop on the path to the use passed as argument 1263 Node* PhaseIdealLoop::place_outside_loop(Node* useblock, IdealLoopTree* loop) const { 1264 Node* head = loop->_head; 1265 assert(!loop->is_member(get_loop(useblock)), "must be outside loop"); 1266 if (head->is_Loop() && head->as_Loop()->is_strip_mined()) { 1267 loop = loop->_parent; 1268 assert(loop->_head->is_OuterStripMinedLoop(), "malformed strip mined loop"); 1269 } 1270 1271 // Pick control right outside the loop 1272 for (;;) { 1273 Node* dom = idom(useblock); 1274 if (loop->is_member(get_loop(dom))) { 1275 break; 1276 } 1277 useblock = dom; 1278 } 1279 assert(find_non_split_ctrl(useblock) == useblock, "should be non split control"); 1280 return useblock; 1281 } 1282 1283 1284 bool PhaseIdealLoop::identical_backtoback_ifs(Node *n) { 1285 if (!n->is_If() || n->is_BaseCountedLoopEnd()) { 1286 return false; 1287 } 1288 if (!n->in(0)->is_Region()) { 1289 return false; 1290 } 1291 1292 Node* region = n->in(0); 1293 Node* dom = idom(region); 1294 if (!dom->is_If() || !n->as_If()->same_condition(dom, &_igvn)) { 1295 return false; 1296 } 1297 IfNode* dom_if = dom->as_If(); 1298 Node* proj_true = dom_if->proj_out(1); 1299 Node* proj_false = dom_if->proj_out(0); 1300 1301 for (uint i = 1; i < region->req(); i++) { 1302 if (is_dominator(proj_true, region->in(i))) { 1303 continue; 1304 } 1305 if (is_dominator(proj_false, region->in(i))) { 1306 continue; 1307 } 1308 return false; 1309 } 1310 1311 return true; 1312 } 1313 1314 1315 bool PhaseIdealLoop::can_split_if(Node* n_ctrl) { 1316 if (must_throttle_split_if()) { 1317 return false; 1318 } 1319 1320 // Do not do 'split-if' if irreducible loops are present. 1321 if (_has_irreducible_loops) { 1322 return false; 1323 } 1324 1325 if (merge_point_too_heavy(C, n_ctrl)) { 1326 return false; 1327 } 1328 1329 // Do not do 'split-if' if some paths are dead. First do dead code 1330 // elimination and then see if its still profitable. 1331 for (uint i = 1; i < n_ctrl->req(); i++) { 1332 if (n_ctrl->in(i) == C->top()) { 1333 return false; 1334 } 1335 } 1336 1337 // If trying to do a 'Split-If' at the loop head, it is only 1338 // profitable if the cmp folds up on BOTH paths. Otherwise we 1339 // risk peeling a loop forever. 1340 1341 // CNC - Disabled for now. Requires careful handling of loop 1342 // body selection for the cloned code. Also, make sure we check 1343 // for any input path not being in the same loop as n_ctrl. For 1344 // irreducible loops we cannot check for 'n_ctrl->is_Loop()' 1345 // because the alternative loop entry points won't be converted 1346 // into LoopNodes. 1347 IdealLoopTree *n_loop = get_loop(n_ctrl); 1348 for (uint j = 1; j < n_ctrl->req(); j++) { 1349 if (get_loop(n_ctrl->in(j)) != n_loop) { 1350 return false; 1351 } 1352 } 1353 1354 // Check for safety of the merge point. 1355 if (!merge_point_safe(n_ctrl)) { 1356 return false; 1357 } 1358 1359 return true; 1360 } 1361 1362 // Detect if the node is the inner strip-mined loop 1363 // Return: null if it's not the case, or the exit of outer strip-mined loop 1364 static Node* is_inner_of_stripmined_loop(const Node* out) { 1365 Node* out_le = nullptr; 1366 1367 if (out->is_CountedLoopEnd()) { 1368 const CountedLoopNode* loop = out->as_CountedLoopEnd()->loopnode(); 1369 1370 if (loop != nullptr && loop->is_strip_mined()) { 1371 out_le = loop->in(LoopNode::EntryControl)->as_OuterStripMinedLoop()->outer_loop_exit(); 1372 } 1373 } 1374 1375 return out_le; 1376 } 1377 1378 //------------------------------split_if_with_blocks_post---------------------- 1379 // Do the real work in a non-recursive function. CFG hackery wants to be 1380 // in the post-order, so it can dirty the I-DOM info and not use the dirtied 1381 // info. 1382 void PhaseIdealLoop::split_if_with_blocks_post(Node *n) { 1383 1384 // Cloning Cmp through Phi's involves the split-if transform. 1385 // FastLock is not used by an If 1386 if (n->is_Cmp() && !n->is_FastLock()) { 1387 Node *n_ctrl = get_ctrl(n); 1388 // Determine if the Node has inputs from some local Phi. 1389 // Returns the block to clone thru. 1390 Node *n_blk = has_local_phi_input(n); 1391 if (n_blk != n_ctrl) { 1392 return; 1393 } 1394 1395 if (!can_split_if(n_ctrl)) { 1396 return; 1397 } 1398 1399 if (n->outcnt() != 1) { 1400 return; // Multiple bool's from 1 compare? 1401 } 1402 Node *bol = n->unique_out(); 1403 assert(bol->is_Bool(), "expect a bool here"); 1404 if (bol->outcnt() != 1) { 1405 return;// Multiple branches from 1 compare? 1406 } 1407 Node *iff = bol->unique_out(); 1408 1409 // Check some safety conditions 1410 if (iff->is_If()) { // Classic split-if? 1411 if (iff->in(0) != n_ctrl) { 1412 return; // Compare must be in same blk as if 1413 } 1414 } else if (iff->is_CMove()) { // Trying to split-up a CMOVE 1415 // Can't split CMove with different control. 1416 if (get_ctrl(iff) != n_ctrl) { 1417 return; 1418 } 1419 if (get_ctrl(iff->in(2)) == n_ctrl || 1420 get_ctrl(iff->in(3)) == n_ctrl) { 1421 return; // Inputs not yet split-up 1422 } 1423 if (get_loop(n_ctrl) != get_loop(get_ctrl(iff))) { 1424 return; // Loop-invar test gates loop-varying CMOVE 1425 } 1426 } else { 1427 return; // some other kind of node, such as an Allocate 1428 } 1429 1430 // When is split-if profitable? Every 'win' on means some control flow 1431 // goes dead, so it's almost always a win. 1432 int policy = 0; 1433 // Split compare 'n' through the merge point if it is profitable 1434 Node *phi = split_thru_phi( n, n_ctrl, policy); 1435 if (!phi) { 1436 return; 1437 } 1438 1439 // Found a Phi to split thru! 1440 // Replace 'n' with the new phi 1441 _igvn.replace_node(n, phi); 1442 1443 // Now split the bool up thru the phi 1444 Node *bolphi = split_thru_phi(bol, n_ctrl, -1); 1445 guarantee(bolphi != nullptr, "null boolean phi node"); 1446 1447 _igvn.replace_node(bol, bolphi); 1448 assert(iff->in(1) == bolphi, ""); 1449 1450 if (bolphi->Value(&_igvn)->singleton()) { 1451 return; 1452 } 1453 1454 // Conditional-move? Must split up now 1455 if (!iff->is_If()) { 1456 Node *cmovphi = split_thru_phi(iff, n_ctrl, -1); 1457 _igvn.replace_node(iff, cmovphi); 1458 return; 1459 } 1460 1461 // Now split the IF 1462 C->print_method(PHASE_BEFORE_SPLIT_IF, 4, iff); 1463 if (TraceLoopOpts) { 1464 tty->print_cr("Split-If"); 1465 } 1466 do_split_if(iff); 1467 C->print_method(PHASE_AFTER_SPLIT_IF, 4, iff); 1468 return; 1469 } 1470 1471 // Two identical ifs back to back can be merged 1472 if (try_merge_identical_ifs(n)) { 1473 return; 1474 } 1475 1476 // Check for an IF ready to split; one that has its 1477 // condition codes input coming from a Phi at the block start. 1478 int n_op = n->Opcode(); 1479 1480 // Check for an IF being dominated by another IF same test 1481 if (n_op == Op_If || 1482 n_op == Op_RangeCheck) { 1483 Node *bol = n->in(1); 1484 uint max = bol->outcnt(); 1485 // Check for same test used more than once? 1486 if (bol->is_Bool() && (max > 1 || bol->in(1)->is_SubTypeCheck())) { 1487 // Search up IDOMs to see if this IF is dominated. 1488 Node* cmp = bol->in(1); 1489 Node *cutoff = cmp->is_SubTypeCheck() ? dom_lca(get_ctrl(cmp->in(1)), get_ctrl(cmp->in(2))) : get_ctrl(bol); 1490 1491 // Now search up IDOMs till cutoff, looking for a dominating test 1492 Node *prevdom = n; 1493 Node *dom = idom(prevdom); 1494 while (dom != cutoff) { 1495 if (dom->req() > 1 && n->as_If()->same_condition(dom, &_igvn) && prevdom->in(0) == dom && 1496 safe_for_if_replacement(dom)) { 1497 // It's invalid to move control dependent data nodes in the inner 1498 // strip-mined loop, because: 1499 // 1) break validation of LoopNode::verify_strip_mined() 1500 // 2) move code with side-effect in strip-mined loop 1501 // Move to the exit of outer strip-mined loop in that case. 1502 Node* out_le = is_inner_of_stripmined_loop(dom); 1503 if (out_le != nullptr) { 1504 prevdom = out_le; 1505 } 1506 // Replace the dominated test with an obvious true or false. 1507 // Place it on the IGVN worklist for later cleanup. 1508 C->set_major_progress(); 1509 // Split if: pin array accesses that are control dependent on a range check and moved to a regular if, 1510 // to prevent an array load from floating above its range check. There are three cases: 1511 // 1. Move from RangeCheck "a" to RangeCheck "b": don't need to pin. If we ever remove b, then we pin 1512 // all its array accesses at that point. 1513 // 2. We move from RangeCheck "a" to regular if "b": need to pin. If we ever remove b, then its array 1514 // accesses would start to float, since we don't pin at that point. 1515 // 3. If we move from regular if: don't pin. All array accesses are already assumed to be pinned. 1516 bool pin_array_access_nodes = n->Opcode() == Op_RangeCheck && 1517 prevdom->in(0)->Opcode() != Op_RangeCheck; 1518 dominated_by(prevdom->as_IfProj(), n->as_If(), false, pin_array_access_nodes); 1519 DEBUG_ONLY( if (VerifyLoopOptimizations) { verify(); } ); 1520 return; 1521 } 1522 prevdom = dom; 1523 dom = idom(prevdom); 1524 } 1525 } 1526 } 1527 1528 try_sink_out_of_loop(n); 1529 if (C->failing()) { 1530 return; 1531 } 1532 1533 try_move_store_after_loop(n); 1534 } 1535 1536 // Transform: 1537 // 1538 // if (some_condition) { 1539 // // body 1 1540 // } else { 1541 // // body 2 1542 // } 1543 // if (some_condition) { 1544 // // body 3 1545 // } else { 1546 // // body 4 1547 // } 1548 // 1549 // into: 1550 // 1551 // 1552 // if (some_condition) { 1553 // // body 1 1554 // // body 3 1555 // } else { 1556 // // body 2 1557 // // body 4 1558 // } 1559 bool PhaseIdealLoop::try_merge_identical_ifs(Node* n) { 1560 if (identical_backtoback_ifs(n) && can_split_if(n->in(0))) { 1561 Node *n_ctrl = n->in(0); 1562 IfNode* dom_if = idom(n_ctrl)->as_If(); 1563 if (n->in(1) != dom_if->in(1)) { 1564 assert(n->in(1)->in(1)->is_SubTypeCheck() && 1565 (n->in(1)->in(1)->as_SubTypeCheck()->method() != nullptr || 1566 dom_if->in(1)->in(1)->as_SubTypeCheck()->method() != nullptr), "only for subtype checks with profile data attached"); 1567 _igvn.replace_input_of(n, 1, dom_if->in(1)); 1568 } 1569 ProjNode* dom_proj_true = dom_if->proj_out(1); 1570 ProjNode* dom_proj_false = dom_if->proj_out(0); 1571 1572 // Now split the IF 1573 RegionNode* new_false_region; 1574 RegionNode* new_true_region; 1575 do_split_if(n, &new_false_region, &new_true_region); 1576 assert(new_false_region->req() == new_true_region->req(), ""); 1577 #ifdef ASSERT 1578 for (uint i = 1; i < new_false_region->req(); ++i) { 1579 assert(new_false_region->in(i)->in(0) == new_true_region->in(i)->in(0), "unexpected shape following split if"); 1580 assert(i == new_false_region->req() - 1 || new_false_region->in(i)->in(0)->in(1) == new_false_region->in(i + 1)->in(0)->in(1), "unexpected shape following split if"); 1581 } 1582 #endif 1583 assert(new_false_region->in(1)->in(0)->in(1) == dom_if->in(1), "dominating if and dominated if after split must share test"); 1584 1585 // We now have: 1586 // if (some_condition) { 1587 // // body 1 1588 // if (some_condition) { 1589 // body3: // new_true_region 1590 // // body3 1591 // } else { 1592 // goto body4; 1593 // } 1594 // } else { 1595 // // body 2 1596 // if (some_condition) { 1597 // goto body3; 1598 // } else { 1599 // body4: // new_false_region 1600 // // body4; 1601 // } 1602 // } 1603 // 1604 1605 // clone pinned nodes thru the resulting regions 1606 push_pinned_nodes_thru_region(dom_if, new_true_region); 1607 push_pinned_nodes_thru_region(dom_if, new_false_region); 1608 1609 // Optimize out the cloned ifs. Because pinned nodes were cloned, this also allows a CastPP that would be dependent 1610 // on a projection of n to have the dom_if as a control dependency. We don't want the CastPP to end up with an 1611 // unrelated control dependency. 1612 for (uint i = 1; i < new_false_region->req(); i++) { 1613 if (is_dominator(dom_proj_true, new_false_region->in(i))) { 1614 dominated_by(dom_proj_true->as_IfProj(), new_false_region->in(i)->in(0)->as_If()); 1615 } else { 1616 assert(is_dominator(dom_proj_false, new_false_region->in(i)), "bad if"); 1617 dominated_by(dom_proj_false->as_IfProj(), new_false_region->in(i)->in(0)->as_If()); 1618 } 1619 } 1620 return true; 1621 } 1622 return false; 1623 } 1624 1625 void PhaseIdealLoop::push_pinned_nodes_thru_region(IfNode* dom_if, Node* region) { 1626 for (DUIterator i = region->outs(); region->has_out(i); i++) { 1627 Node* u = region->out(i); 1628 if (!has_ctrl(u) || u->is_Phi() || !u->depends_only_on_test() || !_igvn.no_dependent_zero_check(u)) { 1629 continue; 1630 } 1631 assert(u->in(0) == region, "not a control dependent node?"); 1632 uint j = 1; 1633 for (; j < u->req(); ++j) { 1634 Node* in = u->in(j); 1635 if (!is_dominator(ctrl_or_self(in), dom_if)) { 1636 break; 1637 } 1638 } 1639 if (j == u->req()) { 1640 Node *phi = PhiNode::make_blank(region, u); 1641 for (uint k = 1; k < region->req(); ++k) { 1642 Node* clone = u->clone(); 1643 clone->set_req(0, region->in(k)); 1644 register_new_node(clone, region->in(k)); 1645 phi->init_req(k, clone); 1646 } 1647 register_new_node(phi, region); 1648 _igvn.replace_node(u, phi); 1649 --i; 1650 } 1651 } 1652 } 1653 1654 bool PhaseIdealLoop::safe_for_if_replacement(const Node* dom) const { 1655 if (!dom->is_CountedLoopEnd()) { 1656 return true; 1657 } 1658 CountedLoopEndNode* le = dom->as_CountedLoopEnd(); 1659 CountedLoopNode* cl = le->loopnode(); 1660 if (cl == nullptr) { 1661 return true; 1662 } 1663 if (!cl->is_main_loop()) { 1664 return true; 1665 } 1666 if (cl->is_canonical_loop_entry() == nullptr) { 1667 return true; 1668 } 1669 // Further unrolling is possible so loop exit condition might change 1670 return false; 1671 } 1672 1673 // See if a shared loop-varying computation has no loop-varying uses. 1674 // Happens if something is only used for JVM state in uncommon trap exits, 1675 // like various versions of induction variable+offset. Clone the 1676 // computation per usage to allow it to sink out of the loop. 1677 void PhaseIdealLoop::try_sink_out_of_loop(Node* n) { 1678 bool is_raw_to_oop_cast = n->is_ConstraintCast() && 1679 n->in(1)->bottom_type()->isa_rawptr() && 1680 !n->bottom_type()->isa_rawptr(); 1681 1682 if (has_ctrl(n) && 1683 !n->is_Phi() && 1684 !n->is_Bool() && 1685 !n->is_Proj() && 1686 !n->is_MergeMem() && 1687 !n->is_CMove() && 1688 !n->is_OpaqueNotNull() && 1689 !n->is_OpaqueInitializedAssertionPredicate() && 1690 !n->is_OpaqueTemplateAssertionPredicate() && 1691 !is_raw_to_oop_cast && // don't extend live ranges of raw oops 1692 (KillPathsReachableByDeadTypeNode || !n->is_Type()) 1693 ) { 1694 Node *n_ctrl = get_ctrl(n); 1695 IdealLoopTree *n_loop = get_loop(n_ctrl); 1696 1697 if (n->in(0) != nullptr) { 1698 IdealLoopTree* loop_ctrl = get_loop(n->in(0)); 1699 if (n_loop != loop_ctrl && n_loop->is_member(loop_ctrl)) { 1700 // n has a control input inside a loop but get_ctrl() is member of an outer loop. This could happen, for example, 1701 // for Div nodes inside a loop (control input inside loop) without a use except for an UCT (outside the loop). 1702 // Rewire control of n to right outside of the loop, regardless if its input(s) are later sunk or not. 1703 Node* maybe_pinned_n = n; 1704 Node* outside_ctrl = place_outside_loop(n_ctrl, loop_ctrl); 1705 if (n->depends_only_on_test()) { 1706 Node* pinned_clone = n->pin_array_access_node(); 1707 if (pinned_clone != nullptr) { 1708 // Pin array access nodes: if this is an array load, it's going to be dependent on a condition that's not a 1709 // range check for that access. If that condition is replaced by an identical dominating one, then an 1710 // unpinned load would risk floating above its range check. 1711 register_new_node(pinned_clone, n_ctrl); 1712 maybe_pinned_n = pinned_clone; 1713 _igvn.replace_node(n, pinned_clone); 1714 } 1715 } 1716 _igvn.replace_input_of(maybe_pinned_n, 0, outside_ctrl); 1717 } 1718 } 1719 if (n_loop != _ltree_root && n->outcnt() > 1) { 1720 // Compute early control: needed for anti-dependence analysis. It's also possible that as a result of 1721 // previous transformations in this loop opts round, the node can be hoisted now: early control will tell us. 1722 Node* early_ctrl = compute_early_ctrl(n, n_ctrl); 1723 if (n_loop->is_member(get_loop(early_ctrl)) && // check that this one can't be hoisted now 1724 ctrl_of_all_uses_out_of_loop(n, early_ctrl, n_loop)) { // All uses in outer loops! 1725 if (n->is_Store() || n->is_LoadStore()) { 1726 assert(false, "no node with a side effect"); 1727 C->record_failure("no node with a side effect"); 1728 return; 1729 } 1730 Node* outer_loop_clone = nullptr; 1731 for (DUIterator_Last jmin, j = n->last_outs(jmin); j >= jmin;) { 1732 Node* u = n->last_out(j); // Clone private computation per use 1733 _igvn.rehash_node_delayed(u); 1734 Node* x = nullptr; 1735 if (n->depends_only_on_test()) { 1736 // Pin array access nodes: if this is an array load, it's going to be dependent on a condition that's not a 1737 // range check for that access. If that condition is replaced by an identical dominating one, then an 1738 // unpinned load would risk floating above its range check. 1739 x = n->pin_array_access_node(); 1740 } 1741 if (x == nullptr) { 1742 x = n->clone(); 1743 } 1744 Node* x_ctrl = nullptr; 1745 if (u->is_Phi()) { 1746 // Replace all uses of normal nodes. Replace Phi uses 1747 // individually, so the separate Nodes can sink down 1748 // different paths. 1749 uint k = 1; 1750 while (u->in(k) != n) k++; 1751 u->set_req(k, x); 1752 // x goes next to Phi input path 1753 x_ctrl = u->in(0)->in(k); 1754 // Find control for 'x' next to use but not inside inner loops. 1755 x_ctrl = place_outside_loop(x_ctrl, n_loop); 1756 --j; 1757 } else { // Normal use 1758 if (has_ctrl(u)) { 1759 x_ctrl = get_ctrl(u); 1760 } else { 1761 x_ctrl = u->in(0); 1762 } 1763 // Find control for 'x' next to use but not inside inner loops. 1764 x_ctrl = place_outside_loop(x_ctrl, n_loop); 1765 // Replace all uses 1766 if (u->is_ConstraintCast() && _igvn.type(n)->higher_equal(u->bottom_type()) && u->in(0) == x_ctrl) { 1767 // If we're sinking a chain of data nodes, we might have inserted a cast to pin the use which is not necessary 1768 // anymore now that we're going to pin n as well 1769 _igvn.replace_node(u, x); 1770 --j; 1771 } else { 1772 int nb = u->replace_edge(n, x, &_igvn); 1773 j -= nb; 1774 } 1775 } 1776 1777 if (n->is_Load()) { 1778 // For loads, add a control edge to a CFG node outside of the loop 1779 // to force them to not combine and return back inside the loop 1780 // during GVN optimization (4641526). 1781 assert(x_ctrl == get_late_ctrl_with_anti_dep(x->as_Load(), early_ctrl, x_ctrl), "anti-dependences were already checked"); 1782 1783 IdealLoopTree* x_loop = get_loop(x_ctrl); 1784 Node* x_head = x_loop->_head; 1785 if (x_head->is_Loop() && x_head->is_OuterStripMinedLoop()) { 1786 // Do not add duplicate LoadNodes to the outer strip mined loop 1787 if (outer_loop_clone != nullptr) { 1788 _igvn.replace_node(x, outer_loop_clone); 1789 continue; 1790 } 1791 outer_loop_clone = x; 1792 } 1793 x->set_req(0, x_ctrl); 1794 } else if (n->in(0) != nullptr){ 1795 x->set_req(0, x_ctrl); 1796 } 1797 assert(dom_depth(n_ctrl) <= dom_depth(x_ctrl), "n is later than its clone"); 1798 assert(!n_loop->is_member(get_loop(x_ctrl)), "should have moved out of loop"); 1799 register_new_node(x, x_ctrl); 1800 1801 // Chain of AddP nodes: (AddP base (AddP base (AddP base ))) 1802 // All AddP nodes must keep the same base after sinking so: 1803 // 1- We don't add a CastPP here until the last one of the chain is sunk: if part of the chain is not sunk, 1804 // their bases remain the same. 1805 // (see 2- below) 1806 assert(!x->is_AddP() || !x->in(AddPNode::Address)->is_AddP() || 1807 x->in(AddPNode::Address)->in(AddPNode::Base) == x->in(AddPNode::Base) || 1808 !x->in(AddPNode::Address)->in(AddPNode::Base)->eqv_uncast(x->in(AddPNode::Base)), "unexpected AddP shape"); 1809 if (x->in(0) == nullptr && !x->is_DecodeNarrowPtr() && 1810 !(x->is_AddP() && x->in(AddPNode::Address)->is_AddP() && x->in(AddPNode::Address)->in(AddPNode::Base) == x->in(AddPNode::Base))) { 1811 assert(!x->is_Load(), "load should be pinned"); 1812 // Use a cast node to pin clone out of loop 1813 Node* cast = nullptr; 1814 for (uint k = 0; k < x->req(); k++) { 1815 Node* in = x->in(k); 1816 if (in != nullptr && n_loop->is_member(get_loop(get_ctrl(in)))) { 1817 const Type* in_t = _igvn.type(in); 1818 cast = ConstraintCastNode::make_cast_for_type(x_ctrl, in, in_t, 1819 ConstraintCastNode::UnconditionalDependency, nullptr); 1820 } 1821 if (cast != nullptr) { 1822 Node* prev = _igvn.hash_find_insert(cast); 1823 if (prev != nullptr && get_ctrl(prev) == x_ctrl) { 1824 cast->destruct(&_igvn); 1825 cast = prev; 1826 } else { 1827 register_new_node(cast, x_ctrl); 1828 } 1829 x->replace_edge(in, cast); 1830 // Chain of AddP nodes: 1831 // 2- A CastPP of the base is only added now that all AddP nodes are sunk 1832 if (x->is_AddP() && k == AddPNode::Base) { 1833 update_addp_chain_base(x, n->in(AddPNode::Base), cast); 1834 } 1835 break; 1836 } 1837 } 1838 assert(cast != nullptr, "must have added a cast to pin the node"); 1839 } 1840 } 1841 _igvn.remove_dead_node(n); 1842 } 1843 _dom_lca_tags_round = 0; 1844 } 1845 } 1846 } 1847 1848 void PhaseIdealLoop::update_addp_chain_base(Node* x, Node* old_base, Node* new_base) { 1849 ResourceMark rm; 1850 Node_List wq; 1851 wq.push(x); 1852 while (wq.size() != 0) { 1853 Node* n = wq.pop(); 1854 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) { 1855 Node* u = n->fast_out(i); 1856 if (u->is_AddP() && u->in(AddPNode::Base) == old_base) { 1857 _igvn.replace_input_of(u, AddPNode::Base, new_base); 1858 wq.push(u); 1859 } 1860 } 1861 } 1862 } 1863 1864 // Compute the early control of a node by following its inputs until we reach 1865 // nodes that are pinned. Then compute the LCA of the control of all pinned nodes. 1866 Node* PhaseIdealLoop::compute_early_ctrl(Node* n, Node* n_ctrl) { 1867 Node* early_ctrl = nullptr; 1868 ResourceMark rm; 1869 Unique_Node_List wq; 1870 wq.push(n); 1871 for (uint i = 0; i < wq.size(); i++) { 1872 Node* m = wq.at(i); 1873 Node* c = nullptr; 1874 if (m->is_CFG()) { 1875 c = m; 1876 } else if (m->pinned()) { 1877 c = m->in(0); 1878 } else { 1879 for (uint j = 0; j < m->req(); j++) { 1880 Node* in = m->in(j); 1881 if (in != nullptr) { 1882 wq.push(in); 1883 } 1884 } 1885 } 1886 if (c != nullptr) { 1887 assert(is_dominator(c, n_ctrl), "control input must dominate current control"); 1888 if (early_ctrl == nullptr || is_dominator(early_ctrl, c)) { 1889 early_ctrl = c; 1890 } 1891 } 1892 } 1893 assert(is_dominator(early_ctrl, n_ctrl), "early control must dominate current control"); 1894 return early_ctrl; 1895 } 1896 1897 bool PhaseIdealLoop::ctrl_of_all_uses_out_of_loop(const Node* n, Node* n_ctrl, IdealLoopTree* n_loop) { 1898 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) { 1899 Node* u = n->fast_out(i); 1900 if (u->is_Opaque1()) { 1901 return false; // Found loop limit, bugfix for 4677003 1902 } 1903 // We can't reuse tags in PhaseIdealLoop::dom_lca_for_get_late_ctrl_internal() so make sure calls to 1904 // get_late_ctrl_with_anti_dep() use their own tag 1905 _dom_lca_tags_round++; 1906 assert(_dom_lca_tags_round != 0, "shouldn't wrap around"); 1907 1908 if (u->is_Phi()) { 1909 for (uint j = 1; j < u->req(); ++j) { 1910 if (u->in(j) == n && !ctrl_of_use_out_of_loop(n, n_ctrl, n_loop, u->in(0)->in(j))) { 1911 return false; 1912 } 1913 } 1914 } else { 1915 Node* ctrl = has_ctrl(u) ? get_ctrl(u) : u->in(0); 1916 if (!ctrl_of_use_out_of_loop(n, n_ctrl, n_loop, ctrl)) { 1917 return false; 1918 } 1919 } 1920 } 1921 return true; 1922 } 1923 1924 bool PhaseIdealLoop::ctrl_of_use_out_of_loop(const Node* n, Node* n_ctrl, IdealLoopTree* n_loop, Node* ctrl) { 1925 if (n->is_Load()) { 1926 ctrl = get_late_ctrl_with_anti_dep(n->as_Load(), n_ctrl, ctrl); 1927 } 1928 IdealLoopTree *u_loop = get_loop(ctrl); 1929 if (u_loop == n_loop) { 1930 return false; // Found loop-varying use 1931 } 1932 if (n_loop->is_member(u_loop)) { 1933 return false; // Found use in inner loop 1934 } 1935 // Sinking a node from a pre loop to its main loop pins the node between the pre and main loops. If that node is input 1936 // to a check that's eliminated by range check elimination, it becomes input to an expression that feeds into the exit 1937 // test of the pre loop above the point in the graph where it's pinned. 1938 if (n_loop->_head->is_CountedLoop() && n_loop->_head->as_CountedLoop()->is_pre_loop()) { 1939 CountedLoopNode* pre_loop = n_loop->_head->as_CountedLoop(); 1940 if (is_dominator(pre_loop->loopexit(), ctrl)) { 1941 return false; 1942 } 1943 } 1944 return true; 1945 } 1946 1947 //------------------------------split_if_with_blocks--------------------------- 1948 // Check for aggressive application of 'split-if' optimization, 1949 // using basic block level info. 1950 void PhaseIdealLoop::split_if_with_blocks(VectorSet &visited, Node_Stack &nstack) { 1951 Node* root = C->root(); 1952 visited.set(root->_idx); // first, mark root as visited 1953 // Do pre-visit work for root 1954 Node* n = split_if_with_blocks_pre(root); 1955 uint cnt = n->outcnt(); 1956 uint i = 0; 1957 1958 while (true) { 1959 // Visit all children 1960 if (i < cnt) { 1961 Node* use = n->raw_out(i); 1962 ++i; 1963 if (use->outcnt() != 0 && !visited.test_set(use->_idx)) { 1964 // Now do pre-visit work for this use 1965 use = split_if_with_blocks_pre(use); 1966 nstack.push(n, i); // Save parent and next use's index. 1967 n = use; // Process all children of current use. 1968 cnt = use->outcnt(); 1969 i = 0; 1970 } 1971 } 1972 else { 1973 // All of n's children have been processed, complete post-processing. 1974 if (cnt != 0 && !n->is_Con()) { 1975 assert(has_node(n), "no dead nodes"); 1976 split_if_with_blocks_post(n); 1977 if (C->failing()) { 1978 return; 1979 } 1980 } 1981 if (must_throttle_split_if()) { 1982 nstack.clear(); 1983 } 1984 if (nstack.is_empty()) { 1985 // Finished all nodes on stack. 1986 break; 1987 } 1988 // Get saved parent node and next use's index. Visit the rest of uses. 1989 n = nstack.node(); 1990 cnt = n->outcnt(); 1991 i = nstack.index(); 1992 nstack.pop(); 1993 } 1994 } 1995 } 1996 1997 1998 //============================================================================= 1999 // 2000 // C L O N E A L O O P B O D Y 2001 // 2002 2003 //------------------------------clone_iff-------------------------------------- 2004 // Passed in a Phi merging (recursively) some nearly equivalent Bool/Cmps. 2005 // "Nearly" because all Nodes have been cloned from the original in the loop, 2006 // but the fall-in edges to the Cmp are different. Clone bool/Cmp pairs 2007 // through the Phi recursively, and return a Bool. 2008 Node* PhaseIdealLoop::clone_iff(PhiNode* phi) { 2009 2010 // Convert this Phi into a Phi merging Bools 2011 uint i; 2012 for (i = 1; i < phi->req(); i++) { 2013 Node* b = phi->in(i); 2014 if (b->is_Phi()) { 2015 _igvn.replace_input_of(phi, i, clone_iff(b->as_Phi())); 2016 } else { 2017 assert(b->is_Bool() || b->is_OpaqueNotNull() || b->is_OpaqueInitializedAssertionPredicate(), 2018 "bool, non-null check with OpaqueNotNull or Initialized Assertion Predicate with its Opaque node"); 2019 } 2020 } 2021 Node* n = phi->in(1); 2022 Node* sample_opaque = nullptr; 2023 Node *sample_bool = nullptr; 2024 if (n->is_OpaqueNotNull() || n->is_OpaqueInitializedAssertionPredicate()) { 2025 sample_opaque = n; 2026 sample_bool = n->in(1); 2027 assert(sample_bool->is_Bool(), "wrong type"); 2028 } else { 2029 sample_bool = n; 2030 } 2031 Node *sample_cmp = sample_bool->in(1); 2032 2033 // Make Phis to merge the Cmp's inputs. 2034 PhiNode *phi1 = new PhiNode(phi->in(0), Type::TOP); 2035 PhiNode *phi2 = new PhiNode(phi->in(0), Type::TOP); 2036 for (i = 1; i < phi->req(); i++) { 2037 Node *n1 = sample_opaque == nullptr ? phi->in(i)->in(1)->in(1) : phi->in(i)->in(1)->in(1)->in(1); 2038 Node *n2 = sample_opaque == nullptr ? phi->in(i)->in(1)->in(2) : phi->in(i)->in(1)->in(1)->in(2); 2039 phi1->set_req(i, n1); 2040 phi2->set_req(i, n2); 2041 phi1->set_type(phi1->type()->meet_speculative(n1->bottom_type())); 2042 phi2->set_type(phi2->type()->meet_speculative(n2->bottom_type())); 2043 } 2044 // See if these Phis have been made before. 2045 // Register with optimizer 2046 Node *hit1 = _igvn.hash_find_insert(phi1); 2047 if (hit1) { // Hit, toss just made Phi 2048 _igvn.remove_dead_node(phi1); // Remove new phi 2049 assert(hit1->is_Phi(), "" ); 2050 phi1 = (PhiNode*)hit1; // Use existing phi 2051 } else { // Miss 2052 _igvn.register_new_node_with_optimizer(phi1); 2053 } 2054 Node *hit2 = _igvn.hash_find_insert(phi2); 2055 if (hit2) { // Hit, toss just made Phi 2056 _igvn.remove_dead_node(phi2); // Remove new phi 2057 assert(hit2->is_Phi(), "" ); 2058 phi2 = (PhiNode*)hit2; // Use existing phi 2059 } else { // Miss 2060 _igvn.register_new_node_with_optimizer(phi2); 2061 } 2062 // Register Phis with loop/block info 2063 set_ctrl(phi1, phi->in(0)); 2064 set_ctrl(phi2, phi->in(0)); 2065 // Make a new Cmp 2066 Node *cmp = sample_cmp->clone(); 2067 cmp->set_req(1, phi1); 2068 cmp->set_req(2, phi2); 2069 _igvn.register_new_node_with_optimizer(cmp); 2070 set_ctrl(cmp, phi->in(0)); 2071 2072 // Make a new Bool 2073 Node *b = sample_bool->clone(); 2074 b->set_req(1,cmp); 2075 _igvn.register_new_node_with_optimizer(b); 2076 set_ctrl(b, phi->in(0)); 2077 2078 if (sample_opaque != nullptr) { 2079 Node* opaque = sample_opaque->clone(); 2080 opaque->set_req(1, b); 2081 _igvn.register_new_node_with_optimizer(opaque); 2082 set_ctrl(opaque, phi->in(0)); 2083 return opaque; 2084 } 2085 2086 assert(b->is_Bool(), ""); 2087 return b; 2088 } 2089 2090 //------------------------------clone_bool------------------------------------- 2091 // Passed in a Phi merging (recursively) some nearly equivalent Bool/Cmps. 2092 // "Nearly" because all Nodes have been cloned from the original in the loop, 2093 // but the fall-in edges to the Cmp are different. Clone bool/Cmp pairs 2094 // through the Phi recursively, and return a Bool. 2095 CmpNode*PhaseIdealLoop::clone_bool(PhiNode* phi) { 2096 uint i; 2097 // Convert this Phi into a Phi merging Bools 2098 for( i = 1; i < phi->req(); i++ ) { 2099 Node *b = phi->in(i); 2100 if( b->is_Phi() ) { 2101 _igvn.replace_input_of(phi, i, clone_bool(b->as_Phi())); 2102 } else { 2103 assert( b->is_Cmp() || b->is_top(), "inputs are all Cmp or TOP" ); 2104 } 2105 } 2106 2107 Node *sample_cmp = phi->in(1); 2108 2109 // Make Phis to merge the Cmp's inputs. 2110 PhiNode *phi1 = new PhiNode( phi->in(0), Type::TOP ); 2111 PhiNode *phi2 = new PhiNode( phi->in(0), Type::TOP ); 2112 for( uint j = 1; j < phi->req(); j++ ) { 2113 Node *cmp_top = phi->in(j); // Inputs are all Cmp or TOP 2114 Node *n1, *n2; 2115 if( cmp_top->is_Cmp() ) { 2116 n1 = cmp_top->in(1); 2117 n2 = cmp_top->in(2); 2118 } else { 2119 n1 = n2 = cmp_top; 2120 } 2121 phi1->set_req( j, n1 ); 2122 phi2->set_req( j, n2 ); 2123 phi1->set_type(phi1->type()->meet_speculative(n1->bottom_type())); 2124 phi2->set_type(phi2->type()->meet_speculative(n2->bottom_type())); 2125 } 2126 2127 // See if these Phis have been made before. 2128 // Register with optimizer 2129 Node *hit1 = _igvn.hash_find_insert(phi1); 2130 if( hit1 ) { // Hit, toss just made Phi 2131 _igvn.remove_dead_node(phi1); // Remove new phi 2132 assert( hit1->is_Phi(), "" ); 2133 phi1 = (PhiNode*)hit1; // Use existing phi 2134 } else { // Miss 2135 _igvn.register_new_node_with_optimizer(phi1); 2136 } 2137 Node *hit2 = _igvn.hash_find_insert(phi2); 2138 if( hit2 ) { // Hit, toss just made Phi 2139 _igvn.remove_dead_node(phi2); // Remove new phi 2140 assert( hit2->is_Phi(), "" ); 2141 phi2 = (PhiNode*)hit2; // Use existing phi 2142 } else { // Miss 2143 _igvn.register_new_node_with_optimizer(phi2); 2144 } 2145 // Register Phis with loop/block info 2146 set_ctrl(phi1, phi->in(0)); 2147 set_ctrl(phi2, phi->in(0)); 2148 // Make a new Cmp 2149 Node *cmp = sample_cmp->clone(); 2150 cmp->set_req( 1, phi1 ); 2151 cmp->set_req( 2, phi2 ); 2152 _igvn.register_new_node_with_optimizer(cmp); 2153 set_ctrl(cmp, phi->in(0)); 2154 2155 assert( cmp->is_Cmp(), "" ); 2156 return (CmpNode*)cmp; 2157 } 2158 2159 void PhaseIdealLoop::clone_loop_handle_data_uses(Node* old, Node_List &old_new, 2160 IdealLoopTree* loop, IdealLoopTree* outer_loop, 2161 Node_List*& split_if_set, Node_List*& split_bool_set, 2162 Node_List*& split_cex_set, Node_List& worklist, 2163 uint new_counter, CloneLoopMode mode) { 2164 Node* nnn = old_new[old->_idx]; 2165 // Copy uses to a worklist, so I can munge the def-use info 2166 // with impunity. 2167 for (DUIterator_Fast jmax, j = old->fast_outs(jmax); j < jmax; j++) 2168 worklist.push(old->fast_out(j)); 2169 2170 while( worklist.size() ) { 2171 Node *use = worklist.pop(); 2172 if (!has_node(use)) continue; // Ignore dead nodes 2173 if (use->in(0) == C->top()) continue; 2174 IdealLoopTree *use_loop = get_loop( has_ctrl(use) ? get_ctrl(use) : use ); 2175 // Check for data-use outside of loop - at least one of OLD or USE 2176 // must not be a CFG node. 2177 #ifdef ASSERT 2178 if (loop->_head->as_Loop()->is_strip_mined() && outer_loop->is_member(use_loop) && !loop->is_member(use_loop) && old_new[use->_idx] == nullptr) { 2179 Node* sfpt = loop->_head->as_CountedLoop()->outer_safepoint(); 2180 assert(mode != IgnoreStripMined, "incorrect cloning mode"); 2181 assert((mode == ControlAroundStripMined && use == sfpt) || !use->is_reachable_from_root(), "missed a node"); 2182 } 2183 #endif 2184 if (!loop->is_member(use_loop) && !outer_loop->is_member(use_loop) && (!old->is_CFG() || !use->is_CFG())) { 2185 2186 // If the Data use is an IF, that means we have an IF outside the 2187 // loop that is switching on a condition that is set inside the 2188 // loop. Happens if people set a loop-exit flag; then test the flag 2189 // in the loop to break the loop, then test is again outside the 2190 // loop to determine which way the loop exited. 2191 // 2192 // For several uses we need to make sure that there is no phi between, 2193 // the use and the Bool/Cmp. We therefore clone the Bool/Cmp down here 2194 // to avoid such a phi in between. 2195 // For example, it is unexpected that there is a Phi between an 2196 // AllocateArray node and its ValidLengthTest input that could cause 2197 // split if to break. 2198 assert(!use->is_OpaqueTemplateAssertionPredicate(), 2199 "should not clone a Template Assertion Predicate which should be removed once it's useless"); 2200 if (use->is_If() || use->is_CMove() || use->is_OpaqueNotNull() || use->is_OpaqueInitializedAssertionPredicate() || 2201 (use->Opcode() == Op_AllocateArray && use->in(AllocateNode::ValidLengthTest) == old)) { 2202 // Since this code is highly unlikely, we lazily build the worklist 2203 // of such Nodes to go split. 2204 if (!split_if_set) { 2205 split_if_set = new Node_List(); 2206 } 2207 split_if_set->push(use); 2208 } 2209 if (use->is_Bool()) { 2210 if (!split_bool_set) { 2211 split_bool_set = new Node_List(); 2212 } 2213 split_bool_set->push(use); 2214 } 2215 if (use->Opcode() == Op_CreateEx) { 2216 if (!split_cex_set) { 2217 split_cex_set = new Node_List(); 2218 } 2219 split_cex_set->push(use); 2220 } 2221 2222 2223 // Get "block" use is in 2224 uint idx = 0; 2225 while( use->in(idx) != old ) idx++; 2226 Node *prev = use->is_CFG() ? use : get_ctrl(use); 2227 assert(!loop->is_member(get_loop(prev)) && !outer_loop->is_member(get_loop(prev)), "" ); 2228 Node* cfg = (prev->_idx >= new_counter && prev->is_Region()) 2229 ? prev->in(2) 2230 : idom(prev); 2231 if( use->is_Phi() ) // Phi use is in prior block 2232 cfg = prev->in(idx); // NOT in block of Phi itself 2233 if (cfg->is_top()) { // Use is dead? 2234 _igvn.replace_input_of(use, idx, C->top()); 2235 continue; 2236 } 2237 2238 // If use is referenced through control edge... (idx == 0) 2239 if (mode == IgnoreStripMined && idx == 0) { 2240 LoopNode *head = loop->_head->as_Loop(); 2241 if (head->is_strip_mined() && is_dominator(head->outer_loop_exit(), prev)) { 2242 // That node is outside the inner loop, leave it outside the 2243 // outer loop as well to not confuse verification code. 2244 assert(!loop->_parent->is_member(use_loop), "should be out of the outer loop"); 2245 _igvn.replace_input_of(use, 0, head->outer_loop_exit()); 2246 continue; 2247 } 2248 } 2249 2250 while(!outer_loop->is_member(get_loop(cfg))) { 2251 prev = cfg; 2252 cfg = (cfg->_idx >= new_counter && cfg->is_Region()) ? cfg->in(2) : idom(cfg); 2253 } 2254 // If the use occurs after merging several exits from the loop, then 2255 // old value must have dominated all those exits. Since the same old 2256 // value was used on all those exits we did not need a Phi at this 2257 // merge point. NOW we do need a Phi here. Each loop exit value 2258 // is now merged with the peeled body exit; each exit gets its own 2259 // private Phi and those Phis need to be merged here. 2260 Node *phi; 2261 if( prev->is_Region() ) { 2262 if( idx == 0 ) { // Updating control edge? 2263 phi = prev; // Just use existing control 2264 } else { // Else need a new Phi 2265 phi = PhiNode::make( prev, old ); 2266 // Now recursively fix up the new uses of old! 2267 for( uint i = 1; i < prev->req(); i++ ) { 2268 worklist.push(phi); // Onto worklist once for each 'old' input 2269 } 2270 } 2271 } else { 2272 // Get new RegionNode merging old and new loop exits 2273 prev = old_new[prev->_idx]; 2274 assert( prev, "just made this in step 7" ); 2275 if( idx == 0) { // Updating control edge? 2276 phi = prev; // Just use existing control 2277 } else { // Else need a new Phi 2278 // Make a new Phi merging data values properly 2279 phi = PhiNode::make( prev, old ); 2280 phi->set_req( 1, nnn ); 2281 } 2282 } 2283 // If inserting a new Phi, check for prior hits 2284 if( idx != 0 ) { 2285 Node *hit = _igvn.hash_find_insert(phi); 2286 if( hit == nullptr ) { 2287 _igvn.register_new_node_with_optimizer(phi); // Register new phi 2288 } else { // or 2289 // Remove the new phi from the graph and use the hit 2290 _igvn.remove_dead_node(phi); 2291 phi = hit; // Use existing phi 2292 } 2293 set_ctrl(phi, prev); 2294 } 2295 // Make 'use' use the Phi instead of the old loop body exit value 2296 assert(use->in(idx) == old, "old is still input of use"); 2297 // We notify all uses of old, including use, and the indirect uses, 2298 // that may now be optimized because we have replaced old with phi. 2299 _igvn.add_users_to_worklist(old); 2300 if (idx == 0 && 2301 use->depends_only_on_test()) { 2302 Node* pinned_clone = use->pin_array_access_node(); 2303 if (pinned_clone != nullptr) { 2304 // Pin array access nodes: control is updated here to a region. If, after some transformations, only one path 2305 // into the region is left, an array load could become dependent on a condition that's not a range check for 2306 // that access. If that condition is replaced by an identical dominating one, then an unpinned load would risk 2307 // floating above its range check. 2308 pinned_clone->set_req(0, phi); 2309 register_new_node_with_ctrl_of(pinned_clone, use); 2310 _igvn.replace_node(use, pinned_clone); 2311 continue; 2312 } 2313 } 2314 _igvn.replace_input_of(use, idx, phi); 2315 if( use->_idx >= new_counter ) { // If updating new phis 2316 // Not needed for correctness, but prevents a weak assert 2317 // in AddPNode from tripping (when we end up with different 2318 // base & derived Phis that will become the same after 2319 // IGVN does CSE). 2320 Node *hit = _igvn.hash_find_insert(use); 2321 if( hit ) // Go ahead and re-hash for hits. 2322 _igvn.replace_node( use, hit ); 2323 } 2324 } 2325 } 2326 } 2327 2328 static void collect_nodes_in_outer_loop_not_reachable_from_sfpt(Node* n, const IdealLoopTree *loop, const IdealLoopTree* outer_loop, 2329 const Node_List &old_new, Unique_Node_List& wq, PhaseIdealLoop* phase, 2330 bool check_old_new) { 2331 for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++) { 2332 Node* u = n->fast_out(j); 2333 assert(check_old_new || old_new[u->_idx] == nullptr, "shouldn't have been cloned"); 2334 if (!u->is_CFG() && (!check_old_new || old_new[u->_idx] == nullptr)) { 2335 Node* c = phase->get_ctrl(u); 2336 IdealLoopTree* u_loop = phase->get_loop(c); 2337 assert(!loop->is_member(u_loop) || !loop->_body.contains(u), "can be in outer loop or out of both loops only"); 2338 if (!loop->is_member(u_loop)) { 2339 if (outer_loop->is_member(u_loop)) { 2340 wq.push(u); 2341 } else { 2342 // nodes pinned with control in the outer loop but not referenced from the safepoint must be moved out of 2343 // the outer loop too 2344 Node* u_c = u->in(0); 2345 if (u_c != nullptr) { 2346 IdealLoopTree* u_c_loop = phase->get_loop(u_c); 2347 if (outer_loop->is_member(u_c_loop) && !loop->is_member(u_c_loop)) { 2348 wq.push(u); 2349 } 2350 } 2351 } 2352 } 2353 } 2354 } 2355 } 2356 2357 void PhaseIdealLoop::clone_outer_loop(LoopNode* head, CloneLoopMode mode, IdealLoopTree *loop, 2358 IdealLoopTree* outer_loop, int dd, Node_List &old_new, 2359 Node_List& extra_data_nodes) { 2360 if (head->is_strip_mined() && mode != IgnoreStripMined) { 2361 CountedLoopNode* cl = head->as_CountedLoop(); 2362 Node* l = cl->outer_loop(); 2363 Node* tail = cl->outer_loop_tail(); 2364 IfNode* le = cl->outer_loop_end(); 2365 Node* sfpt = cl->outer_safepoint(); 2366 CountedLoopEndNode* cle = cl->loopexit(); 2367 CountedLoopNode* new_cl = old_new[cl->_idx]->as_CountedLoop(); 2368 CountedLoopEndNode* new_cle = new_cl->as_CountedLoop()->loopexit_or_null(); 2369 Node* cle_out = cle->proj_out(false); 2370 2371 Node* new_sfpt = nullptr; 2372 Node* new_cle_out = cle_out->clone(); 2373 old_new.map(cle_out->_idx, new_cle_out); 2374 if (mode == CloneIncludesStripMined) { 2375 // clone outer loop body 2376 Node* new_l = l->clone(); 2377 Node* new_tail = tail->clone(); 2378 IfNode* new_le = le->clone()->as_If(); 2379 new_sfpt = sfpt->clone(); 2380 2381 set_loop(new_l, outer_loop->_parent); 2382 set_idom(new_l, new_l->in(LoopNode::EntryControl), dd); 2383 set_loop(new_cle_out, outer_loop->_parent); 2384 set_idom(new_cle_out, new_cle, dd); 2385 set_loop(new_sfpt, outer_loop->_parent); 2386 set_idom(new_sfpt, new_cle_out, dd); 2387 set_loop(new_le, outer_loop->_parent); 2388 set_idom(new_le, new_sfpt, dd); 2389 set_loop(new_tail, outer_loop->_parent); 2390 set_idom(new_tail, new_le, dd); 2391 set_idom(new_cl, new_l, dd); 2392 2393 old_new.map(l->_idx, new_l); 2394 old_new.map(tail->_idx, new_tail); 2395 old_new.map(le->_idx, new_le); 2396 old_new.map(sfpt->_idx, new_sfpt); 2397 2398 new_l->set_req(LoopNode::LoopBackControl, new_tail); 2399 new_l->set_req(0, new_l); 2400 new_tail->set_req(0, new_le); 2401 new_le->set_req(0, new_sfpt); 2402 new_sfpt->set_req(0, new_cle_out); 2403 new_cle_out->set_req(0, new_cle); 2404 new_cl->set_req(LoopNode::EntryControl, new_l); 2405 2406 _igvn.register_new_node_with_optimizer(new_l); 2407 _igvn.register_new_node_with_optimizer(new_tail); 2408 _igvn.register_new_node_with_optimizer(new_le); 2409 } else { 2410 Node *newhead = old_new[loop->_head->_idx]; 2411 newhead->as_Loop()->clear_strip_mined(); 2412 _igvn.replace_input_of(newhead, LoopNode::EntryControl, newhead->in(LoopNode::EntryControl)->in(LoopNode::EntryControl)); 2413 set_idom(newhead, newhead->in(LoopNode::EntryControl), dd); 2414 } 2415 // Look at data node that were assigned a control in the outer 2416 // loop: they are kept in the outer loop by the safepoint so start 2417 // from the safepoint node's inputs. 2418 IdealLoopTree* outer_loop = get_loop(l); 2419 Node_Stack stack(2); 2420 stack.push(sfpt, 1); 2421 uint new_counter = C->unique(); 2422 while (stack.size() > 0) { 2423 Node* n = stack.node(); 2424 uint i = stack.index(); 2425 while (i < n->req() && 2426 (n->in(i) == nullptr || 2427 !has_ctrl(n->in(i)) || 2428 get_loop(get_ctrl(n->in(i))) != outer_loop || 2429 (old_new[n->in(i)->_idx] != nullptr && old_new[n->in(i)->_idx]->_idx >= new_counter))) { 2430 i++; 2431 } 2432 if (i < n->req()) { 2433 stack.set_index(i+1); 2434 stack.push(n->in(i), 0); 2435 } else { 2436 assert(old_new[n->_idx] == nullptr || n == sfpt || old_new[n->_idx]->_idx < new_counter, "no clone yet"); 2437 Node* m = n == sfpt ? new_sfpt : n->clone(); 2438 if (m != nullptr) { 2439 for (uint i = 0; i < n->req(); i++) { 2440 if (m->in(i) != nullptr && old_new[m->in(i)->_idx] != nullptr) { 2441 m->set_req(i, old_new[m->in(i)->_idx]); 2442 } 2443 } 2444 } else { 2445 assert(n == sfpt && mode != CloneIncludesStripMined, "where's the safepoint clone?"); 2446 } 2447 if (n != sfpt) { 2448 extra_data_nodes.push(n); 2449 _igvn.register_new_node_with_optimizer(m); 2450 assert(get_ctrl(n) == cle_out, "what other control?"); 2451 set_ctrl(m, new_cle_out); 2452 old_new.map(n->_idx, m); 2453 } 2454 stack.pop(); 2455 } 2456 } 2457 if (mode == CloneIncludesStripMined) { 2458 _igvn.register_new_node_with_optimizer(new_sfpt); 2459 _igvn.register_new_node_with_optimizer(new_cle_out); 2460 } 2461 // Some other transformation may have pessimistically assigned some 2462 // data nodes to the outer loop. Set their control so they are out 2463 // of the outer loop. 2464 ResourceMark rm; 2465 Unique_Node_List wq; 2466 for (uint i = 0; i < extra_data_nodes.size(); i++) { 2467 Node* old = extra_data_nodes.at(i); 2468 collect_nodes_in_outer_loop_not_reachable_from_sfpt(old, loop, outer_loop, old_new, wq, this, true); 2469 } 2470 2471 for (uint i = 0; i < loop->_body.size(); i++) { 2472 Node* old = loop->_body.at(i); 2473 collect_nodes_in_outer_loop_not_reachable_from_sfpt(old, loop, outer_loop, old_new, wq, this, true); 2474 } 2475 2476 Node* inner_out = sfpt->in(0); 2477 if (inner_out->outcnt() > 1) { 2478 collect_nodes_in_outer_loop_not_reachable_from_sfpt(inner_out, loop, outer_loop, old_new, wq, this, true); 2479 } 2480 2481 Node* new_ctrl = cl->outer_loop_exit(); 2482 assert(get_loop(new_ctrl) != outer_loop, "must be out of the loop nest"); 2483 for (uint i = 0; i < wq.size(); i++) { 2484 Node* n = wq.at(i); 2485 set_ctrl(n, new_ctrl); 2486 if (n->in(0) != nullptr) { 2487 _igvn.replace_input_of(n, 0, new_ctrl); 2488 } 2489 collect_nodes_in_outer_loop_not_reachable_from_sfpt(n, loop, outer_loop, old_new, wq, this, false); 2490 } 2491 } else { 2492 Node *newhead = old_new[loop->_head->_idx]; 2493 set_idom(newhead, newhead->in(LoopNode::EntryControl), dd); 2494 } 2495 } 2496 2497 //------------------------------clone_loop------------------------------------- 2498 // 2499 // C L O N E A L O O P B O D Y 2500 // 2501 // This is the basic building block of the loop optimizations. It clones an 2502 // entire loop body. It makes an old_new loop body mapping; with this mapping 2503 // you can find the new-loop equivalent to an old-loop node. All new-loop 2504 // nodes are exactly equal to their old-loop counterparts, all edges are the 2505 // same. All exits from the old-loop now have a RegionNode that merges the 2506 // equivalent new-loop path. This is true even for the normal "loop-exit" 2507 // condition. All uses of loop-invariant old-loop values now come from (one 2508 // or more) Phis that merge their new-loop equivalents. 2509 // 2510 // This operation leaves the graph in an illegal state: there are two valid 2511 // control edges coming from the loop pre-header to both loop bodies. I'll 2512 // definitely have to hack the graph after running this transform. 2513 // 2514 // From this building block I will further edit edges to perform loop peeling 2515 // or loop unrolling or iteration splitting (Range-Check-Elimination), etc. 2516 // 2517 // Parameter side_by_size_idom: 2518 // When side_by_size_idom is null, the dominator tree is constructed for 2519 // the clone loop to dominate the original. Used in construction of 2520 // pre-main-post loop sequence. 2521 // When nonnull, the clone and original are side-by-side, both are 2522 // dominated by the side_by_side_idom node. Used in construction of 2523 // unswitched loops. 2524 void PhaseIdealLoop::clone_loop( IdealLoopTree *loop, Node_List &old_new, int dd, 2525 CloneLoopMode mode, Node* side_by_side_idom) { 2526 2527 LoopNode* head = loop->_head->as_Loop(); 2528 head->verify_strip_mined(1); 2529 2530 if (C->do_vector_loop() && PrintOpto) { 2531 const char* mname = C->method()->name()->as_quoted_ascii(); 2532 if (mname != nullptr) { 2533 tty->print("PhaseIdealLoop::clone_loop: for vectorize method %s\n", mname); 2534 } 2535 } 2536 2537 CloneMap& cm = C->clone_map(); 2538 if (C->do_vector_loop()) { 2539 cm.set_clone_idx(cm.max_gen()+1); 2540 #ifndef PRODUCT 2541 if (PrintOpto) { 2542 tty->print_cr("PhaseIdealLoop::clone_loop: _clone_idx %d", cm.clone_idx()); 2543 loop->dump_head(); 2544 } 2545 #endif 2546 } 2547 2548 // Step 1: Clone the loop body. Make the old->new mapping. 2549 clone_loop_body(loop->_body, old_new, &cm); 2550 2551 IdealLoopTree* outer_loop = (head->is_strip_mined() && mode != IgnoreStripMined) ? get_loop(head->as_CountedLoop()->outer_loop()) : loop; 2552 2553 // Step 2: Fix the edges in the new body. If the old input is outside the 2554 // loop use it. If the old input is INside the loop, use the corresponding 2555 // new node instead. 2556 fix_body_edges(loop->_body, loop, old_new, dd, outer_loop->_parent, false); 2557 2558 Node_List extra_data_nodes; // data nodes in the outer strip mined loop 2559 clone_outer_loop(head, mode, loop, outer_loop, dd, old_new, extra_data_nodes); 2560 2561 // Step 3: Now fix control uses. Loop varying control uses have already 2562 // been fixed up (as part of all input edges in Step 2). Loop invariant 2563 // control uses must be either an IfFalse or an IfTrue. Make a merge 2564 // point to merge the old and new IfFalse/IfTrue nodes; make the use 2565 // refer to this. 2566 Node_List worklist; 2567 uint new_counter = C->unique(); 2568 fix_ctrl_uses(loop->_body, loop, old_new, mode, side_by_side_idom, &cm, worklist); 2569 2570 // Step 4: If loop-invariant use is not control, it must be dominated by a 2571 // loop exit IfFalse/IfTrue. Find "proper" loop exit. Make a Region 2572 // there if needed. Make a Phi there merging old and new used values. 2573 Node_List *split_if_set = nullptr; 2574 Node_List *split_bool_set = nullptr; 2575 Node_List *split_cex_set = nullptr; 2576 fix_data_uses(loop->_body, loop, mode, outer_loop, new_counter, old_new, worklist, split_if_set, split_bool_set, split_cex_set); 2577 2578 for (uint i = 0; i < extra_data_nodes.size(); i++) { 2579 Node* old = extra_data_nodes.at(i); 2580 clone_loop_handle_data_uses(old, old_new, loop, outer_loop, split_if_set, 2581 split_bool_set, split_cex_set, worklist, new_counter, 2582 mode); 2583 } 2584 2585 // Check for IFs that need splitting/cloning. Happens if an IF outside of 2586 // the loop uses a condition set in the loop. The original IF probably 2587 // takes control from one or more OLD Regions (which in turn get from NEW 2588 // Regions). In any case, there will be a set of Phis for each merge point 2589 // from the IF up to where the original BOOL def exists the loop. 2590 finish_clone_loop(split_if_set, split_bool_set, split_cex_set); 2591 2592 } 2593 2594 void PhaseIdealLoop::finish_clone_loop(Node_List* split_if_set, Node_List* split_bool_set, Node_List* split_cex_set) { 2595 if (split_if_set) { 2596 while (split_if_set->size()) { 2597 Node *iff = split_if_set->pop(); 2598 uint input = iff->Opcode() == Op_AllocateArray ? AllocateNode::ValidLengthTest : 1; 2599 if (iff->in(input)->is_Phi()) { 2600 Node *b = clone_iff(iff->in(input)->as_Phi()); 2601 _igvn.replace_input_of(iff, input, b); 2602 } 2603 } 2604 } 2605 if (split_bool_set) { 2606 while (split_bool_set->size()) { 2607 Node *b = split_bool_set->pop(); 2608 Node *phi = b->in(1); 2609 assert(phi->is_Phi(), ""); 2610 CmpNode *cmp = clone_bool((PhiNode*) phi); 2611 _igvn.replace_input_of(b, 1, cmp); 2612 } 2613 } 2614 if (split_cex_set) { 2615 while (split_cex_set->size()) { 2616 Node *b = split_cex_set->pop(); 2617 assert(b->in(0)->is_Region(), ""); 2618 assert(b->in(1)->is_Phi(), ""); 2619 assert(b->in(0)->in(0) == b->in(1)->in(0), ""); 2620 split_up(b, b->in(0), nullptr); 2621 } 2622 } 2623 } 2624 2625 void PhaseIdealLoop::fix_data_uses(Node_List& body, IdealLoopTree* loop, CloneLoopMode mode, IdealLoopTree* outer_loop, 2626 uint new_counter, Node_List &old_new, Node_List &worklist, Node_List*& split_if_set, 2627 Node_List*& split_bool_set, Node_List*& split_cex_set) { 2628 for(uint i = 0; i < body.size(); i++ ) { 2629 Node* old = body.at(i); 2630 clone_loop_handle_data_uses(old, old_new, loop, outer_loop, split_if_set, 2631 split_bool_set, split_cex_set, worklist, new_counter, 2632 mode); 2633 } 2634 } 2635 2636 void PhaseIdealLoop::fix_ctrl_uses(const Node_List& body, const IdealLoopTree* loop, Node_List &old_new, CloneLoopMode mode, 2637 Node* side_by_side_idom, CloneMap* cm, Node_List &worklist) { 2638 LoopNode* head = loop->_head->as_Loop(); 2639 for(uint i = 0; i < body.size(); i++ ) { 2640 Node* old = body.at(i); 2641 if( !old->is_CFG() ) continue; 2642 2643 // Copy uses to a worklist, so I can munge the def-use info 2644 // with impunity. 2645 for (DUIterator_Fast jmax, j = old->fast_outs(jmax); j < jmax; j++) { 2646 worklist.push(old->fast_out(j)); 2647 } 2648 2649 while (worklist.size()) { // Visit all uses 2650 Node *use = worklist.pop(); 2651 if (!has_node(use)) continue; // Ignore dead nodes 2652 IdealLoopTree *use_loop = get_loop(has_ctrl(use) ? get_ctrl(use) : use ); 2653 if (!loop->is_member(use_loop) && use->is_CFG()) { 2654 // Both OLD and USE are CFG nodes here. 2655 assert(use->is_Proj(), "" ); 2656 Node* nnn = old_new[old->_idx]; 2657 2658 Node* newuse = nullptr; 2659 if (head->is_strip_mined() && mode != IgnoreStripMined) { 2660 CountedLoopNode* cl = head->as_CountedLoop(); 2661 CountedLoopEndNode* cle = cl->loopexit(); 2662 Node* cle_out = cle->proj_out_or_null(false); 2663 if (use == cle_out) { 2664 IfNode* le = cl->outer_loop_end(); 2665 use = le->proj_out(false); 2666 use_loop = get_loop(use); 2667 if (mode == CloneIncludesStripMined) { 2668 nnn = old_new[le->_idx]; 2669 } else { 2670 newuse = old_new[cle_out->_idx]; 2671 } 2672 } 2673 } 2674 if (newuse == nullptr) { 2675 newuse = use->clone(); 2676 } 2677 2678 // Clone the loop exit control projection 2679 if (C->do_vector_loop() && cm != nullptr) { 2680 cm->verify_insert_and_clone(use, newuse, cm->clone_idx()); 2681 } 2682 newuse->set_req(0,nnn); 2683 _igvn.register_new_node_with_optimizer(newuse); 2684 set_loop(newuse, use_loop); 2685 set_idom(newuse, nnn, dom_depth(nnn) + 1 ); 2686 2687 // We need a Region to merge the exit from the peeled body and the 2688 // exit from the old loop body. 2689 RegionNode *r = new RegionNode(3); 2690 uint dd_r = MIN2(dom_depth(newuse), dom_depth(use)); 2691 assert(dd_r >= dom_depth(dom_lca(newuse, use)), "" ); 2692 2693 // The original user of 'use' uses 'r' instead. 2694 for (DUIterator_Last lmin, l = use->last_outs(lmin); l >= lmin;) { 2695 Node* useuse = use->last_out(l); 2696 _igvn.rehash_node_delayed(useuse); 2697 uint uses_found = 0; 2698 if (useuse->in(0) == use) { 2699 useuse->set_req(0, r); 2700 uses_found++; 2701 if (useuse->is_CFG()) { 2702 // This is not a dom_depth > dd_r because when new 2703 // control flow is constructed by a loop opt, a node and 2704 // its dominator can end up at the same dom_depth 2705 assert(dom_depth(useuse) >= dd_r, ""); 2706 set_idom(useuse, r, dom_depth(useuse)); 2707 } 2708 } 2709 for (uint k = 1; k < useuse->req(); k++) { 2710 if( useuse->in(k) == use ) { 2711 useuse->set_req(k, r); 2712 uses_found++; 2713 if (useuse->is_Loop() && k == LoopNode::EntryControl) { 2714 // This is not a dom_depth > dd_r because when new 2715 // control flow is constructed by a loop opt, a node 2716 // and its dominator can end up at the same dom_depth 2717 assert(dom_depth(useuse) >= dd_r , ""); 2718 set_idom(useuse, r, dom_depth(useuse)); 2719 } 2720 } 2721 } 2722 l -= uses_found; // we deleted 1 or more copies of this edge 2723 } 2724 2725 assert(use->is_Proj(), "loop exit should be projection"); 2726 // lazy_replace() below moves all nodes that are: 2727 // - control dependent on the loop exit or 2728 // - have control set to the loop exit 2729 // below the post-loop merge point. lazy_replace() takes a dead control as first input. To make it 2730 // possible to use it, the loop exit projection is cloned and becomes the new exit projection. The initial one 2731 // becomes dead and is "replaced" by the region. 2732 Node* use_clone = use->clone(); 2733 register_control(use_clone, use_loop, idom(use), dom_depth(use)); 2734 // Now finish up 'r' 2735 r->set_req(1, newuse); 2736 r->set_req(2, use_clone); 2737 _igvn.register_new_node_with_optimizer(r); 2738 set_loop(r, use_loop); 2739 set_idom(r, (side_by_side_idom == nullptr) ? newuse->in(0) : side_by_side_idom, dd_r); 2740 lazy_replace(use, r); 2741 // Map the (cloned) old use to the new merge point 2742 old_new.map(use_clone->_idx, r); 2743 } // End of if a loop-exit test 2744 } 2745 } 2746 } 2747 2748 void PhaseIdealLoop::fix_body_edges(const Node_List &body, IdealLoopTree* loop, const Node_List &old_new, int dd, 2749 IdealLoopTree* parent, bool partial) { 2750 for(uint i = 0; i < body.size(); i++ ) { 2751 Node *old = body.at(i); 2752 Node *nnn = old_new[old->_idx]; 2753 // Fix CFG/Loop controlling the new node 2754 if (has_ctrl(old)) { 2755 set_ctrl(nnn, old_new[get_ctrl(old)->_idx]); 2756 } else { 2757 set_loop(nnn, parent); 2758 if (old->outcnt() > 0) { 2759 Node* dom = idom(old); 2760 if (old_new[dom->_idx] != nullptr) { 2761 dom = old_new[dom->_idx]; 2762 set_idom(nnn, dom, dd ); 2763 } 2764 } 2765 } 2766 // Correct edges to the new node 2767 for (uint j = 0; j < nnn->req(); j++) { 2768 Node *n = nnn->in(j); 2769 if (n != nullptr) { 2770 IdealLoopTree *old_in_loop = get_loop(has_ctrl(n) ? get_ctrl(n) : n); 2771 if (loop->is_member(old_in_loop)) { 2772 if (old_new[n->_idx] != nullptr) { 2773 nnn->set_req(j, old_new[n->_idx]); 2774 } else { 2775 assert(!body.contains(n), ""); 2776 assert(partial, "node not cloned"); 2777 } 2778 } 2779 } 2780 } 2781 _igvn.hash_find_insert(nnn); 2782 } 2783 } 2784 2785 void PhaseIdealLoop::clone_loop_body(const Node_List& body, Node_List &old_new, CloneMap* cm) { 2786 for (uint i = 0; i < body.size(); i++) { 2787 Node* old = body.at(i); 2788 Node* nnn = old->clone(); 2789 old_new.map(old->_idx, nnn); 2790 if (C->do_vector_loop() && cm != nullptr) { 2791 cm->verify_insert_and_clone(old, nnn, cm->clone_idx()); 2792 } 2793 _igvn.register_new_node_with_optimizer(nnn); 2794 } 2795 } 2796 2797 2798 //---------------------- stride_of_possible_iv ------------------------------------- 2799 // Looks for an iff/bool/comp with one operand of the compare 2800 // being a cycle involving an add and a phi, 2801 // with an optional truncation (left-shift followed by a right-shift) 2802 // of the add. Returns zero if not an iv. 2803 int PhaseIdealLoop::stride_of_possible_iv(Node* iff) { 2804 Node* trunc1 = nullptr; 2805 Node* trunc2 = nullptr; 2806 const TypeInteger* ttype = nullptr; 2807 if (!iff->is_If() || iff->in(1) == nullptr || !iff->in(1)->is_Bool()) { 2808 return 0; 2809 } 2810 BoolNode* bl = iff->in(1)->as_Bool(); 2811 Node* cmp = bl->in(1); 2812 if (!cmp || (cmp->Opcode() != Op_CmpI && cmp->Opcode() != Op_CmpU)) { 2813 return 0; 2814 } 2815 // Must have an invariant operand 2816 if (is_member(get_loop(iff), get_ctrl(cmp->in(2)))) { 2817 return 0; 2818 } 2819 Node* add2 = nullptr; 2820 Node* cmp1 = cmp->in(1); 2821 if (cmp1->is_Phi()) { 2822 // (If (Bool (CmpX phi:(Phi ...(Optional-trunc(AddI phi add2))) ))) 2823 Node* phi = cmp1; 2824 for (uint i = 1; i < phi->req(); i++) { 2825 Node* in = phi->in(i); 2826 Node* add = CountedLoopNode::match_incr_with_optional_truncation(in, 2827 &trunc1, &trunc2, &ttype, T_INT); 2828 if (add && add->in(1) == phi) { 2829 add2 = add->in(2); 2830 break; 2831 } 2832 } 2833 } else { 2834 // (If (Bool (CmpX addtrunc:(Optional-trunc((AddI (Phi ...addtrunc...) add2)) ))) 2835 Node* addtrunc = cmp1; 2836 Node* add = CountedLoopNode::match_incr_with_optional_truncation(addtrunc, 2837 &trunc1, &trunc2, &ttype, T_INT); 2838 if (add && add->in(1)->is_Phi()) { 2839 Node* phi = add->in(1); 2840 for (uint i = 1; i < phi->req(); i++) { 2841 if (phi->in(i) == addtrunc) { 2842 add2 = add->in(2); 2843 break; 2844 } 2845 } 2846 } 2847 } 2848 if (add2 != nullptr) { 2849 const TypeInt* add2t = _igvn.type(add2)->is_int(); 2850 if (add2t->is_con()) { 2851 return add2t->get_con(); 2852 } 2853 } 2854 return 0; 2855 } 2856 2857 2858 //---------------------- stay_in_loop ------------------------------------- 2859 // Return the (unique) control output node that's in the loop (if it exists.) 2860 Node* PhaseIdealLoop::stay_in_loop( Node* n, IdealLoopTree *loop) { 2861 Node* unique = nullptr; 2862 if (!n) return nullptr; 2863 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) { 2864 Node* use = n->fast_out(i); 2865 if (!has_ctrl(use) && loop->is_member(get_loop(use))) { 2866 if (unique != nullptr) { 2867 return nullptr; 2868 } 2869 unique = use; 2870 } 2871 } 2872 return unique; 2873 } 2874 2875 //------------------------------ register_node ------------------------------------- 2876 // Utility to register node "n" with PhaseIdealLoop 2877 void PhaseIdealLoop::register_node(Node* n, IdealLoopTree* loop, Node* pred, uint ddepth) { 2878 _igvn.register_new_node_with_optimizer(n); 2879 loop->_body.push(n); 2880 if (n->is_CFG()) { 2881 set_loop(n, loop); 2882 set_idom(n, pred, ddepth); 2883 } else { 2884 set_ctrl(n, pred); 2885 } 2886 } 2887 2888 //------------------------------ proj_clone ------------------------------------- 2889 // Utility to create an if-projection 2890 ProjNode* PhaseIdealLoop::proj_clone(ProjNode* p, IfNode* iff) { 2891 ProjNode* c = p->clone()->as_Proj(); 2892 c->set_req(0, iff); 2893 return c; 2894 } 2895 2896 //------------------------------ short_circuit_if ------------------------------------- 2897 // Force the iff control output to be the live_proj 2898 Node* PhaseIdealLoop::short_circuit_if(IfNode* iff, ProjNode* live_proj) { 2899 guarantee(live_proj != nullptr, "null projection"); 2900 int proj_con = live_proj->_con; 2901 assert(proj_con == 0 || proj_con == 1, "false or true projection"); 2902 Node* con = intcon(proj_con); 2903 if (iff) { 2904 iff->set_req(1, con); 2905 } 2906 return con; 2907 } 2908 2909 //------------------------------ insert_if_before_proj ------------------------------------- 2910 // Insert a new if before an if projection (* - new node) 2911 // 2912 // before 2913 // if(test) 2914 // / \ 2915 // v v 2916 // other-proj proj (arg) 2917 // 2918 // after 2919 // if(test) 2920 // / \ 2921 // / v 2922 // | * proj-clone 2923 // v | 2924 // other-proj v 2925 // * new_if(relop(cmp[IU](left,right))) 2926 // / \ 2927 // v v 2928 // * new-proj proj 2929 // (returned) 2930 // 2931 ProjNode* PhaseIdealLoop::insert_if_before_proj(Node* left, bool Signed, BoolTest::mask relop, Node* right, ProjNode* proj) { 2932 IfNode* iff = proj->in(0)->as_If(); 2933 IdealLoopTree *loop = get_loop(proj); 2934 ProjNode *other_proj = iff->proj_out(!proj->is_IfTrue())->as_Proj(); 2935 uint ddepth = dom_depth(proj); 2936 2937 _igvn.rehash_node_delayed(iff); 2938 _igvn.rehash_node_delayed(proj); 2939 2940 proj->set_req(0, nullptr); // temporary disconnect 2941 ProjNode* proj2 = proj_clone(proj, iff); 2942 register_node(proj2, loop, iff, ddepth); 2943 2944 Node* cmp = Signed ? (Node*) new CmpINode(left, right) : (Node*) new CmpUNode(left, right); 2945 register_node(cmp, loop, proj2, ddepth); 2946 2947 BoolNode* bol = new BoolNode(cmp, relop); 2948 register_node(bol, loop, proj2, ddepth); 2949 2950 int opcode = iff->Opcode(); 2951 assert(opcode == Op_If || opcode == Op_RangeCheck, "unexpected opcode"); 2952 IfNode* new_if = IfNode::make_with_same_profile(iff, proj2, bol); 2953 register_node(new_if, loop, proj2, ddepth); 2954 2955 proj->set_req(0, new_if); // reattach 2956 set_idom(proj, new_if, ddepth); 2957 2958 ProjNode* new_exit = proj_clone(other_proj, new_if)->as_Proj(); 2959 guarantee(new_exit != nullptr, "null exit node"); 2960 register_node(new_exit, get_loop(other_proj), new_if, ddepth); 2961 2962 return new_exit; 2963 } 2964 2965 //------------------------------ insert_region_before_proj ------------------------------------- 2966 // Insert a region before an if projection (* - new node) 2967 // 2968 // before 2969 // if(test) 2970 // / | 2971 // v | 2972 // proj v 2973 // other-proj 2974 // 2975 // after 2976 // if(test) 2977 // / | 2978 // v | 2979 // * proj-clone v 2980 // | other-proj 2981 // v 2982 // * new-region 2983 // | 2984 // v 2985 // * dum_if 2986 // / \ 2987 // v \ 2988 // * dum-proj v 2989 // proj 2990 // 2991 RegionNode* PhaseIdealLoop::insert_region_before_proj(ProjNode* proj) { 2992 IfNode* iff = proj->in(0)->as_If(); 2993 IdealLoopTree *loop = get_loop(proj); 2994 ProjNode *other_proj = iff->proj_out(!proj->is_IfTrue())->as_Proj(); 2995 uint ddepth = dom_depth(proj); 2996 2997 _igvn.rehash_node_delayed(iff); 2998 _igvn.rehash_node_delayed(proj); 2999 3000 proj->set_req(0, nullptr); // temporary disconnect 3001 ProjNode* proj2 = proj_clone(proj, iff); 3002 register_node(proj2, loop, iff, ddepth); 3003 3004 RegionNode* reg = new RegionNode(2); 3005 reg->set_req(1, proj2); 3006 register_node(reg, loop, iff, ddepth); 3007 3008 IfNode* dum_if = new IfNode(reg, short_circuit_if(nullptr, proj), iff->_prob, iff->_fcnt); 3009 register_node(dum_if, loop, reg, ddepth); 3010 3011 proj->set_req(0, dum_if); // reattach 3012 set_idom(proj, dum_if, ddepth); 3013 3014 ProjNode* dum_proj = proj_clone(other_proj, dum_if); 3015 register_node(dum_proj, loop, dum_if, ddepth); 3016 3017 return reg; 3018 } 3019 3020 // Idea 3021 // ---- 3022 // Partial Peeling tries to rotate the loop in such a way that it can later be turned into a counted loop. Counted loops 3023 // require a signed loop exit test. When calling this method, we've only found a suitable unsigned test to partial peel 3024 // with. Therefore, we try to split off a signed loop exit test from the unsigned test such that it can be used as new 3025 // loop exit while keeping the unsigned test unchanged and preserving the same behavior as if we've used the unsigned 3026 // test alone instead: 3027 // 3028 // Before Partial Peeling: 3029 // Loop: 3030 // <peeled section> 3031 // Split off signed loop exit test 3032 // <-- CUT HERE --> 3033 // Unchanged unsigned loop exit test 3034 // <rest of unpeeled section> 3035 // goto Loop 3036 // 3037 // After Partial Peeling: 3038 // <cloned peeled section> 3039 // Cloned split off signed loop exit test 3040 // Loop: 3041 // Unchanged unsigned loop exit test 3042 // <rest of unpeeled section> 3043 // <peeled section> 3044 // Split off signed loop exit test 3045 // goto Loop 3046 // 3047 // Details 3048 // ------- 3049 // Before: 3050 // if (i <u limit) Unsigned loop exit condition 3051 // / | 3052 // v v 3053 // exit-proj stay-in-loop-proj 3054 // 3055 // Split off a signed loop exit test (i.e. with CmpI) from an unsigned loop exit test (i.e. with CmpU) and insert it 3056 // before the CmpU on the stay-in-loop path and keep both tests: 3057 // 3058 // if (i <u limit) Signed loop exit test 3059 // / | 3060 // / if (i <u limit) Unsigned loop exit test 3061 // / / | 3062 // v v v 3063 // exit-region stay-in-loop-proj 3064 // 3065 // Implementation 3066 // -------------- 3067 // We need to make sure that the new signed loop exit test is properly inserted into the graph such that the unsigned 3068 // loop exit test still dominates the same set of control nodes, the ctrl() relation from data nodes to both loop 3069 // exit tests is preserved, and their loop nesting is correct. 3070 // 3071 // To achieve that, we clone the unsigned loop exit test completely (leave it unchanged), insert the signed loop exit 3072 // test above it and kill the original unsigned loop exit test by setting it's condition to a constant 3073 // (i.e. stay-in-loop-const in graph below) such that IGVN can fold it later: 3074 // 3075 // if (stay-in-loop-const) Killed original unsigned loop exit test 3076 // / | 3077 // / v 3078 // / if (i < limit) Split off signed loop exit test 3079 // / / | 3080 // / / v 3081 // / / if (i <u limit) Cloned unsigned loop exit test 3082 // / / / | 3083 // v v v | 3084 // exit-region | 3085 // | | 3086 // dummy-if | 3087 // / | | 3088 // dead | | 3089 // v v 3090 // exit-proj stay-in-loop-proj 3091 // 3092 // Note: The dummy-if is inserted to create a region to merge the loop exits between the original to be killed unsigned 3093 // loop exit test and its exit projection while keeping the exit projection (also see insert_region_before_proj()). 3094 // 3095 // Requirements 3096 // ------------ 3097 // Note that we can only split off a signed loop exit test from the unsigned loop exit test when the behavior is exactly 3098 // the same as before with only a single unsigned test. This is only possible if certain requirements are met. 3099 // Otherwise, we need to bail out (see comments in the code below). 3100 IfNode* PhaseIdealLoop::insert_cmpi_loop_exit(IfNode* if_cmpu, IdealLoopTree* loop) { 3101 const bool Signed = true; 3102 const bool Unsigned = false; 3103 3104 BoolNode* bol = if_cmpu->in(1)->as_Bool(); 3105 if (bol->_test._test != BoolTest::lt) { 3106 return nullptr; 3107 } 3108 CmpNode* cmpu = bol->in(1)->as_Cmp(); 3109 assert(cmpu->Opcode() == Op_CmpU, "must be unsigned comparison"); 3110 3111 int stride = stride_of_possible_iv(if_cmpu); 3112 if (stride == 0) { 3113 return nullptr; 3114 } 3115 3116 Node* lp_proj = stay_in_loop(if_cmpu, loop); 3117 guarantee(lp_proj != nullptr, "null loop node"); 3118 3119 ProjNode* lp_continue = lp_proj->as_Proj(); 3120 ProjNode* lp_exit = if_cmpu->proj_out(!lp_continue->is_IfTrue())->as_Proj(); 3121 if (!lp_exit->is_IfFalse()) { 3122 // The loop exit condition is (i <u limit) ==> (i >= 0 && i < limit). 3123 // We therefore can't add a single exit condition. 3124 return nullptr; 3125 } 3126 // The unsigned loop exit condition is 3127 // !(i <u limit) 3128 // = i >=u limit 3129 // 3130 // First, we note that for any x for which 3131 // 0 <= x <= INT_MAX 3132 // we can convert x to an unsigned int and still get the same guarantee: 3133 // 0 <= (uint) x <= INT_MAX = (uint) INT_MAX 3134 // 0 <=u (uint) x <=u INT_MAX = (uint) INT_MAX (LEMMA) 3135 // 3136 // With that in mind, if 3137 // limit >= 0 (COND) 3138 // then the unsigned loop exit condition 3139 // i >=u limit (ULE) 3140 // is equivalent to 3141 // i < 0 || i >= limit (SLE-full) 3142 // because either i is negative and therefore always greater than MAX_INT when converting to unsigned 3143 // (uint) i >=u MAX_INT >= limit >= 0 3144 // or otherwise 3145 // i >= limit >= 0 3146 // holds due to (LEMMA). 3147 // 3148 // For completeness, a counterexample with limit < 0: 3149 // Assume i = -3 and limit = -2: 3150 // i < 0 3151 // -2 < 0 3152 // is true and thus also "i < 0 || i >= limit". But 3153 // i >=u limit 3154 // -3 >=u -2 3155 // is false. 3156 Node* limit = cmpu->in(2); 3157 const TypeInt* type_limit = _igvn.type(limit)->is_int(); 3158 if (type_limit->_lo < 0) { 3159 return nullptr; 3160 } 3161 3162 // We prove below that we can extract a single signed loop exit condition from (SLE-full), depending on the stride: 3163 // stride < 0: 3164 // i < 0 (SLE = SLE-negative) 3165 // stride > 0: 3166 // i >= limit (SLE = SLE-positive) 3167 // such that we have the following graph before Partial Peeling with stride > 0 (similar for stride < 0): 3168 // 3169 // Loop: 3170 // <peeled section> 3171 // i >= limit (SLE-positive) 3172 // <-- CUT HERE --> 3173 // i >=u limit (ULE) 3174 // <rest of unpeeled section> 3175 // goto Loop 3176 // 3177 // We exit the loop if: 3178 // (SLE) is true OR (ULE) is true 3179 // However, if (SLE) is true then (ULE) also needs to be true to ensure the exact same behavior. Otherwise, we wrongly 3180 // exit a loop that should not have been exited if we did not apply Partial Peeling. More formally, we need to ensure: 3181 // (SLE) IMPLIES (ULE) 3182 // This indeed holds when (COND) is given: 3183 // - stride > 0: 3184 // i >= limit // (SLE = SLE-positive) 3185 // i >= limit >= 0 // (COND) 3186 // i >=u limit >= 0 // (LEMMA) 3187 // which is the unsigned loop exit condition (ULE). 3188 // - stride < 0: 3189 // i < 0 // (SLE = SLE-negative) 3190 // (uint) i >u MAX_INT // (NEG) all negative values are greater than MAX_INT when converted to unsigned 3191 // MAX_INT >= limit >= 0 // (COND) 3192 // MAX_INT >=u limit >= 0 // (LEMMA) 3193 // and thus from (NEG) and (LEMMA): 3194 // i >=u limit 3195 // which is the unsigned loop exit condition (ULE). 3196 // 3197 // 3198 // After Partial Peeling, we have the following structure for stride > 0 (similar for stride < 0): 3199 // <cloned peeled section> 3200 // i >= limit (SLE-positive) 3201 // Loop: 3202 // i >=u limit (ULE) 3203 // <rest of unpeeled section> 3204 // <peeled section> 3205 // i >= limit (SLE-positive) 3206 // goto Loop 3207 Node* rhs_cmpi; 3208 if (stride > 0) { 3209 rhs_cmpi = limit; // For i >= limit 3210 } else { 3211 rhs_cmpi = makecon(TypeInt::ZERO); // For i < 0 3212 } 3213 // Create a new region on the exit path 3214 RegionNode* reg = insert_region_before_proj(lp_exit); 3215 guarantee(reg != nullptr, "null region node"); 3216 3217 // Clone the if-cmpu-true-false using a signed compare 3218 BoolTest::mask rel_i = stride > 0 ? bol->_test._test : BoolTest::ge; 3219 ProjNode* cmpi_exit = insert_if_before_proj(cmpu->in(1), Signed, rel_i, rhs_cmpi, lp_continue); 3220 reg->add_req(cmpi_exit); 3221 3222 // Clone the if-cmpu-true-false 3223 BoolTest::mask rel_u = bol->_test._test; 3224 ProjNode* cmpu_exit = insert_if_before_proj(cmpu->in(1), Unsigned, rel_u, cmpu->in(2), lp_continue); 3225 reg->add_req(cmpu_exit); 3226 3227 // Force original if to stay in loop. 3228 short_circuit_if(if_cmpu, lp_continue); 3229 3230 return cmpi_exit->in(0)->as_If(); 3231 } 3232 3233 //------------------------------ remove_cmpi_loop_exit ------------------------------------- 3234 // Remove a previously inserted signed compare loop exit. 3235 void PhaseIdealLoop::remove_cmpi_loop_exit(IfNode* if_cmp, IdealLoopTree *loop) { 3236 Node* lp_proj = stay_in_loop(if_cmp, loop); 3237 assert(if_cmp->in(1)->in(1)->Opcode() == Op_CmpI && 3238 stay_in_loop(lp_proj, loop)->is_If() && 3239 stay_in_loop(lp_proj, loop)->in(1)->in(1)->Opcode() == Op_CmpU, "inserted cmpi before cmpu"); 3240 Node* con = makecon(lp_proj->is_IfTrue() ? TypeInt::ONE : TypeInt::ZERO); 3241 if_cmp->set_req(1, con); 3242 } 3243 3244 //------------------------------ scheduled_nodelist ------------------------------------- 3245 // Create a post order schedule of nodes that are in the 3246 // "member" set. The list is returned in "sched". 3247 // The first node in "sched" is the loop head, followed by 3248 // nodes which have no inputs in the "member" set, and then 3249 // followed by the nodes that have an immediate input dependence 3250 // on a node in "sched". 3251 void PhaseIdealLoop::scheduled_nodelist( IdealLoopTree *loop, VectorSet& member, Node_List &sched ) { 3252 3253 assert(member.test(loop->_head->_idx), "loop head must be in member set"); 3254 VectorSet visited; 3255 Node_Stack nstack(loop->_body.size()); 3256 3257 Node* n = loop->_head; // top of stack is cached in "n" 3258 uint idx = 0; 3259 visited.set(n->_idx); 3260 3261 // Initially push all with no inputs from within member set 3262 for(uint i = 0; i < loop->_body.size(); i++ ) { 3263 Node *elt = loop->_body.at(i); 3264 if (member.test(elt->_idx)) { 3265 bool found = false; 3266 for (uint j = 0; j < elt->req(); j++) { 3267 Node* def = elt->in(j); 3268 if (def && member.test(def->_idx) && def != elt) { 3269 found = true; 3270 break; 3271 } 3272 } 3273 if (!found && elt != loop->_head) { 3274 nstack.push(n, idx); 3275 n = elt; 3276 assert(!visited.test(n->_idx), "not seen yet"); 3277 visited.set(n->_idx); 3278 } 3279 } 3280 } 3281 3282 // traverse out's that are in the member set 3283 while (true) { 3284 if (idx < n->outcnt()) { 3285 Node* use = n->raw_out(idx); 3286 idx++; 3287 if (!visited.test_set(use->_idx)) { 3288 if (member.test(use->_idx)) { 3289 nstack.push(n, idx); 3290 n = use; 3291 idx = 0; 3292 } 3293 } 3294 } else { 3295 // All outputs processed 3296 sched.push(n); 3297 if (nstack.is_empty()) break; 3298 n = nstack.node(); 3299 idx = nstack.index(); 3300 nstack.pop(); 3301 } 3302 } 3303 } 3304 3305 3306 //------------------------------ has_use_in_set ------------------------------------- 3307 // Has a use in the vector set 3308 bool PhaseIdealLoop::has_use_in_set( Node* n, VectorSet& vset ) { 3309 for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++) { 3310 Node* use = n->fast_out(j); 3311 if (vset.test(use->_idx)) { 3312 return true; 3313 } 3314 } 3315 return false; 3316 } 3317 3318 3319 //------------------------------ has_use_internal_to_set ------------------------------------- 3320 // Has use internal to the vector set (ie. not in a phi at the loop head) 3321 bool PhaseIdealLoop::has_use_internal_to_set( Node* n, VectorSet& vset, IdealLoopTree *loop ) { 3322 Node* head = loop->_head; 3323 for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++) { 3324 Node* use = n->fast_out(j); 3325 if (vset.test(use->_idx) && !(use->is_Phi() && use->in(0) == head)) { 3326 return true; 3327 } 3328 } 3329 return false; 3330 } 3331 3332 3333 //------------------------------ clone_for_use_outside_loop ------------------------------------- 3334 // clone "n" for uses that are outside of loop 3335 int PhaseIdealLoop::clone_for_use_outside_loop( IdealLoopTree *loop, Node* n, Node_List& worklist ) { 3336 int cloned = 0; 3337 assert(worklist.size() == 0, "should be empty"); 3338 for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++) { 3339 Node* use = n->fast_out(j); 3340 if( !loop->is_member(get_loop(has_ctrl(use) ? get_ctrl(use) : use)) ) { 3341 worklist.push(use); 3342 } 3343 } 3344 3345 if (C->check_node_count(worklist.size() + NodeLimitFudgeFactor, 3346 "Too many clones required in clone_for_use_outside_loop in partial peeling")) { 3347 return -1; 3348 } 3349 3350 while( worklist.size() ) { 3351 Node *use = worklist.pop(); 3352 if (!has_node(use) || use->in(0) == C->top()) continue; 3353 uint j; 3354 for (j = 0; j < use->req(); j++) { 3355 if (use->in(j) == n) break; 3356 } 3357 assert(j < use->req(), "must be there"); 3358 3359 // clone "n" and insert it between the inputs of "n" and the use outside the loop 3360 Node* n_clone = n->clone(); 3361 _igvn.replace_input_of(use, j, n_clone); 3362 cloned++; 3363 Node* use_c; 3364 if (!use->is_Phi()) { 3365 use_c = has_ctrl(use) ? get_ctrl(use) : use->in(0); 3366 } else { 3367 // Use in a phi is considered a use in the associated predecessor block 3368 use_c = use->in(0)->in(j); 3369 } 3370 set_ctrl(n_clone, use_c); 3371 assert(!loop->is_member(get_loop(use_c)), "should be outside loop"); 3372 get_loop(use_c)->_body.push(n_clone); 3373 _igvn.register_new_node_with_optimizer(n_clone); 3374 #ifndef PRODUCT 3375 if (TracePartialPeeling) { 3376 tty->print_cr("loop exit cloning old: %d new: %d newbb: %d", n->_idx, n_clone->_idx, get_ctrl(n_clone)->_idx); 3377 } 3378 #endif 3379 } 3380 return cloned; 3381 } 3382 3383 3384 //------------------------------ clone_for_special_use_inside_loop ------------------------------------- 3385 // clone "n" for special uses that are in the not_peeled region. 3386 // If these def-uses occur in separate blocks, the code generator 3387 // marks the method as not compilable. For example, if a "BoolNode" 3388 // is in a different basic block than the "IfNode" that uses it, then 3389 // the compilation is aborted in the code generator. 3390 void PhaseIdealLoop::clone_for_special_use_inside_loop( IdealLoopTree *loop, Node* n, 3391 VectorSet& not_peel, Node_List& sink_list, Node_List& worklist ) { 3392 if (n->is_Phi() || n->is_Load()) { 3393 return; 3394 } 3395 assert(worklist.size() == 0, "should be empty"); 3396 for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++) { 3397 Node* use = n->fast_out(j); 3398 if ( not_peel.test(use->_idx) && 3399 (use->is_If() || use->is_CMove() || use->is_Bool() || use->is_OpaqueInitializedAssertionPredicate()) && 3400 use->in(1) == n) { 3401 worklist.push(use); 3402 } 3403 } 3404 if (worklist.size() > 0) { 3405 // clone "n" and insert it between inputs of "n" and the use 3406 Node* n_clone = n->clone(); 3407 loop->_body.push(n_clone); 3408 _igvn.register_new_node_with_optimizer(n_clone); 3409 set_ctrl(n_clone, get_ctrl(n)); 3410 sink_list.push(n_clone); 3411 not_peel.set(n_clone->_idx); 3412 #ifndef PRODUCT 3413 if (TracePartialPeeling) { 3414 tty->print_cr("special not_peeled cloning old: %d new: %d", n->_idx, n_clone->_idx); 3415 } 3416 #endif 3417 while( worklist.size() ) { 3418 Node *use = worklist.pop(); 3419 _igvn.rehash_node_delayed(use); 3420 for (uint j = 1; j < use->req(); j++) { 3421 if (use->in(j) == n) { 3422 use->set_req(j, n_clone); 3423 } 3424 } 3425 } 3426 } 3427 } 3428 3429 3430 //------------------------------ insert_phi_for_loop ------------------------------------- 3431 // Insert phi(lp_entry_val, back_edge_val) at use->in(idx) for loop lp if phi does not already exist 3432 void PhaseIdealLoop::insert_phi_for_loop( Node* use, uint idx, Node* lp_entry_val, Node* back_edge_val, LoopNode* lp ) { 3433 Node *phi = PhiNode::make(lp, back_edge_val); 3434 phi->set_req(LoopNode::EntryControl, lp_entry_val); 3435 // Use existing phi if it already exists 3436 Node *hit = _igvn.hash_find_insert(phi); 3437 if( hit == nullptr ) { 3438 _igvn.register_new_node_with_optimizer(phi); 3439 set_ctrl(phi, lp); 3440 } else { 3441 // Remove the new phi from the graph and use the hit 3442 _igvn.remove_dead_node(phi); 3443 phi = hit; 3444 } 3445 _igvn.replace_input_of(use, idx, phi); 3446 } 3447 3448 #ifdef ASSERT 3449 //------------------------------ is_valid_loop_partition ------------------------------------- 3450 // Validate the loop partition sets: peel and not_peel 3451 bool PhaseIdealLoop::is_valid_loop_partition( IdealLoopTree *loop, VectorSet& peel, Node_List& peel_list, 3452 VectorSet& not_peel ) { 3453 uint i; 3454 // Check that peel_list entries are in the peel set 3455 for (i = 0; i < peel_list.size(); i++) { 3456 if (!peel.test(peel_list.at(i)->_idx)) { 3457 return false; 3458 } 3459 } 3460 // Check at loop members are in one of peel set or not_peel set 3461 for (i = 0; i < loop->_body.size(); i++ ) { 3462 Node *def = loop->_body.at(i); 3463 uint di = def->_idx; 3464 // Check that peel set elements are in peel_list 3465 if (peel.test(di)) { 3466 if (not_peel.test(di)) { 3467 return false; 3468 } 3469 // Must be in peel_list also 3470 bool found = false; 3471 for (uint j = 0; j < peel_list.size(); j++) { 3472 if (peel_list.at(j)->_idx == di) { 3473 found = true; 3474 break; 3475 } 3476 } 3477 if (!found) { 3478 return false; 3479 } 3480 } else if (not_peel.test(di)) { 3481 if (peel.test(di)) { 3482 return false; 3483 } 3484 } else { 3485 return false; 3486 } 3487 } 3488 return true; 3489 } 3490 3491 //------------------------------ is_valid_clone_loop_exit_use ------------------------------------- 3492 // Ensure a use outside of loop is of the right form 3493 bool PhaseIdealLoop::is_valid_clone_loop_exit_use( IdealLoopTree *loop, Node* use, uint exit_idx) { 3494 Node *use_c = has_ctrl(use) ? get_ctrl(use) : use; 3495 return (use->is_Phi() && 3496 use_c->is_Region() && use_c->req() == 3 && 3497 (use_c->in(exit_idx)->Opcode() == Op_IfTrue || 3498 use_c->in(exit_idx)->Opcode() == Op_IfFalse || 3499 use_c->in(exit_idx)->Opcode() == Op_JumpProj) && 3500 loop->is_member( get_loop( use_c->in(exit_idx)->in(0) ) ) ); 3501 } 3502 3503 //------------------------------ is_valid_clone_loop_form ------------------------------------- 3504 // Ensure that all uses outside of loop are of the right form 3505 bool PhaseIdealLoop::is_valid_clone_loop_form( IdealLoopTree *loop, Node_List& peel_list, 3506 uint orig_exit_idx, uint clone_exit_idx) { 3507 uint len = peel_list.size(); 3508 for (uint i = 0; i < len; i++) { 3509 Node *def = peel_list.at(i); 3510 3511 for (DUIterator_Fast jmax, j = def->fast_outs(jmax); j < jmax; j++) { 3512 Node *use = def->fast_out(j); 3513 Node *use_c = has_ctrl(use) ? get_ctrl(use) : use; 3514 if (!loop->is_member(get_loop(use_c))) { 3515 // use is not in the loop, check for correct structure 3516 if (use->in(0) == def) { 3517 // Okay 3518 } else if (!is_valid_clone_loop_exit_use(loop, use, orig_exit_idx)) { 3519 return false; 3520 } 3521 } 3522 } 3523 } 3524 return true; 3525 } 3526 #endif 3527 3528 //------------------------------ partial_peel ------------------------------------- 3529 // Partially peel (aka loop rotation) the top portion of a loop (called 3530 // the peel section below) by cloning it and placing one copy just before 3531 // the new loop head and the other copy at the bottom of the new loop. 3532 // 3533 // before after where it came from 3534 // 3535 // stmt1 stmt1 3536 // loop: stmt2 clone 3537 // stmt2 if condA goto exitA clone 3538 // if condA goto exitA new_loop: new 3539 // stmt3 stmt3 clone 3540 // if !condB goto loop if condB goto exitB clone 3541 // exitB: stmt2 orig 3542 // stmt4 if !condA goto new_loop orig 3543 // exitA: goto exitA 3544 // exitB: 3545 // stmt4 3546 // exitA: 3547 // 3548 // Step 1: find the cut point: an exit test on probable 3549 // induction variable. 3550 // Step 2: schedule (with cloning) operations in the peel 3551 // section that can be executed after the cut into 3552 // the section that is not peeled. This may need 3553 // to clone operations into exit blocks. For 3554 // instance, a reference to A[i] in the not-peel 3555 // section and a reference to B[i] in an exit block 3556 // may cause a left-shift of i by 2 to be placed 3557 // in the peel block. This step will clone the left 3558 // shift into the exit block and sink the left shift 3559 // from the peel to the not-peel section. 3560 // Step 3: clone the loop, retarget the control, and insert 3561 // phis for values that are live across the new loop 3562 // head. This is very dependent on the graph structure 3563 // from clone_loop. It creates region nodes for 3564 // exit control and associated phi nodes for values 3565 // flow out of the loop through that exit. The region 3566 // node is dominated by the clone's control projection. 3567 // So the clone's peel section is placed before the 3568 // new loop head, and the clone's not-peel section is 3569 // forms the top part of the new loop. The original 3570 // peel section forms the tail of the new loop. 3571 // Step 4: update the dominator tree and recompute the 3572 // dominator depth. 3573 // 3574 // orig 3575 // 3576 // stmt1 3577 // | 3578 // v 3579 // predicates 3580 // | 3581 // v 3582 // loop<----+ 3583 // | | 3584 // stmt2 | 3585 // | | 3586 // v | 3587 // ifA | 3588 // / | | 3589 // v v | 3590 // false true ^ <-- last_peel 3591 // / | | 3592 // / ===|==cut | 3593 // / stmt3 | <-- first_not_peel 3594 // / | | 3595 // | v | 3596 // v ifB | 3597 // exitA: / \ | 3598 // / \ | 3599 // v v | 3600 // false true | 3601 // / \ | 3602 // / ----+ 3603 // | 3604 // v 3605 // exitB: 3606 // stmt4 3607 // 3608 // 3609 // after clone loop 3610 // 3611 // stmt1 3612 // | 3613 // v 3614 // predicates 3615 // / \ 3616 // clone / \ orig 3617 // / \ 3618 // / \ 3619 // v v 3620 // +---->loop loop<----+ 3621 // | | | | 3622 // | stmt2 stmt2 | 3623 // | | | | 3624 // | v v | 3625 // | ifA ifA | 3626 // | | \ / | | 3627 // | v v v v | 3628 // ^ true false false true ^ <-- last_peel 3629 // | | ^ \ / | | 3630 // | cut==|== \ \ / ===|==cut | 3631 // | stmt3 \ \ / stmt3 | <-- first_not_peel 3632 // | | dom | | | | 3633 // | v \ 1v v2 v | 3634 // | ifB regionA ifB | 3635 // | / \ | / \ | 3636 // | / \ v / \ | 3637 // | v v exitA: v v | 3638 // | true false false true | 3639 // | / ^ \ / \ | 3640 // +---- \ \ / ----+ 3641 // dom \ / 3642 // \ 1v v2 3643 // regionB 3644 // | 3645 // v 3646 // exitB: 3647 // stmt4 3648 // 3649 // 3650 // after partial peel 3651 // 3652 // stmt1 3653 // | 3654 // v 3655 // predicates 3656 // / 3657 // clone / orig 3658 // / TOP 3659 // / \ 3660 // v v 3661 // TOP->loop loop----+ 3662 // | | | 3663 // stmt2 stmt2 | 3664 // | | | 3665 // v v | 3666 // ifA ifA | 3667 // | \ / | | 3668 // v v v v | 3669 // true false false true | <-- last_peel 3670 // | ^ \ / +------|---+ 3671 // +->newloop \ \ / === ==cut | | 3672 // | stmt3 \ \ / TOP | | 3673 // | | dom | | stmt3 | | <-- first_not_peel 3674 // | v \ 1v v2 v | | 3675 // | ifB regionA ifB ^ v 3676 // | / \ | / \ | | 3677 // | / \ v / \ | | 3678 // | v v exitA: v v | | 3679 // | true false false true | | 3680 // | / ^ \ / \ | | 3681 // | | \ \ / v | | 3682 // | | dom \ / TOP | | 3683 // | | \ 1v v2 | | 3684 // ^ v regionB | | 3685 // | | | | | 3686 // | | v ^ v 3687 // | | exitB: | | 3688 // | | stmt4 | | 3689 // | +------------>-----------------+ | 3690 // | | 3691 // +-----------------<---------------------+ 3692 // 3693 // 3694 // final graph 3695 // 3696 // stmt1 3697 // | 3698 // v 3699 // predicates 3700 // | 3701 // v 3702 // stmt2 clone 3703 // | 3704 // v 3705 // ........> ifA clone 3706 // : / | 3707 // dom / | 3708 // : v v 3709 // : false true 3710 // : | | 3711 // : | v 3712 // : | newloop<-----+ 3713 // : | | | 3714 // : | stmt3 clone | 3715 // : | | | 3716 // : | v | 3717 // : | ifB | 3718 // : | / \ | 3719 // : | v v | 3720 // : | false true | 3721 // : | | | | 3722 // : | v stmt2 | 3723 // : | exitB: | | 3724 // : | stmt4 v | 3725 // : | ifA orig | 3726 // : | / \ | 3727 // : | / \ | 3728 // : | v v | 3729 // : | false true | 3730 // : | / \ | 3731 // : v v -----+ 3732 // RegionA 3733 // | 3734 // v 3735 // exitA 3736 // 3737 bool PhaseIdealLoop::partial_peel( IdealLoopTree *loop, Node_List &old_new ) { 3738 3739 assert(!loop->_head->is_CountedLoop(), "Non-counted loop only"); 3740 if (!loop->_head->is_Loop()) { 3741 return false; 3742 } 3743 LoopNode *head = loop->_head->as_Loop(); 3744 3745 if (head->is_partial_peel_loop() || head->partial_peel_has_failed()) { 3746 return false; 3747 } 3748 3749 // Check for complex exit control 3750 for (uint ii = 0; ii < loop->_body.size(); ii++) { 3751 Node *n = loop->_body.at(ii); 3752 int opc = n->Opcode(); 3753 if (n->is_Call() || 3754 opc == Op_Catch || 3755 opc == Op_CatchProj || 3756 opc == Op_Jump || 3757 opc == Op_JumpProj) { 3758 #ifndef PRODUCT 3759 if (TracePartialPeeling) { 3760 tty->print_cr("\nExit control too complex: lp: %d", head->_idx); 3761 } 3762 #endif 3763 return false; 3764 } 3765 } 3766 3767 int dd = dom_depth(head); 3768 3769 // Step 1: find cut point 3770 3771 // Walk up dominators to loop head looking for first loop exit 3772 // which is executed on every path thru loop. 3773 IfNode *peel_if = nullptr; 3774 IfNode *peel_if_cmpu = nullptr; 3775 3776 Node *iff = loop->tail(); 3777 while (iff != head) { 3778 if (iff->is_If()) { 3779 Node *ctrl = get_ctrl(iff->in(1)); 3780 if (ctrl->is_top()) return false; // Dead test on live IF. 3781 // If loop-varying exit-test, check for induction variable 3782 if (loop->is_member(get_loop(ctrl)) && 3783 loop->is_loop_exit(iff) && 3784 is_possible_iv_test(iff)) { 3785 Node* cmp = iff->in(1)->in(1); 3786 if (cmp->Opcode() == Op_CmpI) { 3787 peel_if = iff->as_If(); 3788 } else { 3789 assert(cmp->Opcode() == Op_CmpU, "must be CmpI or CmpU"); 3790 peel_if_cmpu = iff->as_If(); 3791 } 3792 } 3793 } 3794 iff = idom(iff); 3795 } 3796 3797 // Prefer signed compare over unsigned compare. 3798 IfNode* new_peel_if = nullptr; 3799 if (peel_if == nullptr) { 3800 if (!PartialPeelAtUnsignedTests || peel_if_cmpu == nullptr) { 3801 return false; // No peel point found 3802 } 3803 new_peel_if = insert_cmpi_loop_exit(peel_if_cmpu, loop); 3804 if (new_peel_if == nullptr) { 3805 return false; // No peel point found 3806 } 3807 peel_if = new_peel_if; 3808 } 3809 Node* last_peel = stay_in_loop(peel_if, loop); 3810 Node* first_not_peeled = stay_in_loop(last_peel, loop); 3811 if (first_not_peeled == nullptr || first_not_peeled == head) { 3812 return false; 3813 } 3814 3815 #ifndef PRODUCT 3816 if (TraceLoopOpts) { 3817 tty->print("PartialPeel "); 3818 loop->dump_head(); 3819 } 3820 3821 if (TracePartialPeeling) { 3822 tty->print_cr("before partial peel one iteration"); 3823 Node_List wl; 3824 Node* t = head->in(2); 3825 while (true) { 3826 wl.push(t); 3827 if (t == head) break; 3828 t = idom(t); 3829 } 3830 while (wl.size() > 0) { 3831 Node* tt = wl.pop(); 3832 tt->dump(); 3833 if (tt == last_peel) tty->print_cr("-- cut --"); 3834 } 3835 } 3836 #endif 3837 3838 C->print_method(PHASE_BEFORE_PARTIAL_PEELING, 4, head); 3839 3840 VectorSet peel; 3841 VectorSet not_peel; 3842 Node_List peel_list; 3843 Node_List worklist; 3844 Node_List sink_list; 3845 3846 uint estimate = loop->est_loop_clone_sz(1); 3847 if (exceeding_node_budget(estimate)) { 3848 return false; 3849 } 3850 3851 // Set of cfg nodes to peel are those that are executable from 3852 // the head through last_peel. 3853 assert(worklist.size() == 0, "should be empty"); 3854 worklist.push(head); 3855 peel.set(head->_idx); 3856 while (worklist.size() > 0) { 3857 Node *n = worklist.pop(); 3858 if (n != last_peel) { 3859 for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++) { 3860 Node* use = n->fast_out(j); 3861 if (use->is_CFG() && 3862 loop->is_member(get_loop(use)) && 3863 !peel.test_set(use->_idx)) { 3864 worklist.push(use); 3865 } 3866 } 3867 } 3868 } 3869 3870 // Set of non-cfg nodes to peel are those that are control 3871 // dependent on the cfg nodes. 3872 for (uint i = 0; i < loop->_body.size(); i++) { 3873 Node *n = loop->_body.at(i); 3874 Node *n_c = has_ctrl(n) ? get_ctrl(n) : n; 3875 if (peel.test(n_c->_idx)) { 3876 peel.set(n->_idx); 3877 } else { 3878 not_peel.set(n->_idx); 3879 } 3880 } 3881 3882 // Step 2: move operations from the peeled section down into the 3883 // not-peeled section 3884 3885 // Get a post order schedule of nodes in the peel region 3886 // Result in right-most operand. 3887 scheduled_nodelist(loop, peel, peel_list); 3888 3889 assert(is_valid_loop_partition(loop, peel, peel_list, not_peel), "bad partition"); 3890 3891 // For future check for too many new phis 3892 uint old_phi_cnt = 0; 3893 for (DUIterator_Fast jmax, j = head->fast_outs(jmax); j < jmax; j++) { 3894 Node* use = head->fast_out(j); 3895 if (use->is_Phi()) old_phi_cnt++; 3896 } 3897 3898 #ifndef PRODUCT 3899 if (TracePartialPeeling) { 3900 tty->print_cr("\npeeled list"); 3901 } 3902 #endif 3903 3904 // Evacuate nodes in peel region into the not_peeled region if possible 3905 bool too_many_clones = false; 3906 uint new_phi_cnt = 0; 3907 uint cloned_for_outside_use = 0; 3908 for (uint i = 0; i < peel_list.size();) { 3909 Node* n = peel_list.at(i); 3910 #ifndef PRODUCT 3911 if (TracePartialPeeling) n->dump(); 3912 #endif 3913 bool incr = true; 3914 if (!n->is_CFG()) { 3915 if (has_use_in_set(n, not_peel)) { 3916 // If not used internal to the peeled region, 3917 // move "n" from peeled to not_peeled region. 3918 if (!has_use_internal_to_set(n, peel, loop)) { 3919 // if not pinned and not a load (which maybe anti-dependent on a store) 3920 // and not a CMove (Matcher expects only bool->cmove). 3921 if (n->in(0) == nullptr && !n->is_Load() && !n->is_CMove()) { 3922 int new_clones = clone_for_use_outside_loop(loop, n, worklist); 3923 if (C->failing()) return false; 3924 if (new_clones == -1) { 3925 too_many_clones = true; 3926 break; 3927 } 3928 cloned_for_outside_use += new_clones; 3929 sink_list.push(n); 3930 peel.remove(n->_idx); 3931 not_peel.set(n->_idx); 3932 peel_list.remove(i); 3933 incr = false; 3934 #ifndef PRODUCT 3935 if (TracePartialPeeling) { 3936 tty->print_cr("sink to not_peeled region: %d newbb: %d", 3937 n->_idx, get_ctrl(n)->_idx); 3938 } 3939 #endif 3940 } 3941 } else { 3942 // Otherwise check for special def-use cases that span 3943 // the peel/not_peel boundary such as bool->if 3944 clone_for_special_use_inside_loop(loop, n, not_peel, sink_list, worklist); 3945 new_phi_cnt++; 3946 } 3947 } 3948 } 3949 if (incr) i++; 3950 } 3951 3952 estimate += cloned_for_outside_use + new_phi_cnt; 3953 bool exceed_node_budget = !may_require_nodes(estimate); 3954 bool exceed_phi_limit = new_phi_cnt > old_phi_cnt + PartialPeelNewPhiDelta; 3955 3956 if (too_many_clones || exceed_node_budget || exceed_phi_limit) { 3957 #ifndef PRODUCT 3958 if (TracePartialPeeling && exceed_phi_limit) { 3959 tty->print_cr("\nToo many new phis: %d old %d new cmpi: %c", 3960 new_phi_cnt, old_phi_cnt, new_peel_if != nullptr?'T':'F'); 3961 } 3962 #endif 3963 if (new_peel_if != nullptr) { 3964 remove_cmpi_loop_exit(new_peel_if, loop); 3965 } 3966 // Inhibit more partial peeling on this loop 3967 assert(!head->is_partial_peel_loop(), "not partial peeled"); 3968 head->mark_partial_peel_failed(); 3969 if (cloned_for_outside_use > 0) { 3970 // Terminate this round of loop opts because 3971 // the graph outside this loop was changed. 3972 C->set_major_progress(); 3973 return true; 3974 } 3975 return false; 3976 } 3977 3978 // Step 3: clone loop, retarget control, and insert new phis 3979 3980 // Create new loop head for new phis and to hang 3981 // the nodes being moved (sinked) from the peel region. 3982 LoopNode* new_head = new LoopNode(last_peel, last_peel); 3983 new_head->set_unswitch_count(head->unswitch_count()); // Preserve 3984 _igvn.register_new_node_with_optimizer(new_head); 3985 assert(first_not_peeled->in(0) == last_peel, "last_peel <- first_not_peeled"); 3986 _igvn.replace_input_of(first_not_peeled, 0, new_head); 3987 set_loop(new_head, loop); 3988 loop->_body.push(new_head); 3989 not_peel.set(new_head->_idx); 3990 set_idom(new_head, last_peel, dom_depth(first_not_peeled)); 3991 set_idom(first_not_peeled, new_head, dom_depth(first_not_peeled)); 3992 3993 while (sink_list.size() > 0) { 3994 Node* n = sink_list.pop(); 3995 set_ctrl(n, new_head); 3996 } 3997 3998 assert(is_valid_loop_partition(loop, peel, peel_list, not_peel), "bad partition"); 3999 4000 clone_loop(loop, old_new, dd, IgnoreStripMined); 4001 4002 const uint clone_exit_idx = 1; 4003 const uint orig_exit_idx = 2; 4004 assert(is_valid_clone_loop_form(loop, peel_list, orig_exit_idx, clone_exit_idx), "bad clone loop"); 4005 4006 Node* head_clone = old_new[head->_idx]; 4007 LoopNode* new_head_clone = old_new[new_head->_idx]->as_Loop(); 4008 Node* orig_tail_clone = head_clone->in(2); 4009 4010 // Add phi if "def" node is in peel set and "use" is not 4011 4012 for (uint i = 0; i < peel_list.size(); i++) { 4013 Node *def = peel_list.at(i); 4014 if (!def->is_CFG()) { 4015 for (DUIterator_Fast jmax, j = def->fast_outs(jmax); j < jmax; j++) { 4016 Node *use = def->fast_out(j); 4017 if (has_node(use) && use->in(0) != C->top() && 4018 (!peel.test(use->_idx) || 4019 (use->is_Phi() && use->in(0) == head)) ) { 4020 worklist.push(use); 4021 } 4022 } 4023 while( worklist.size() ) { 4024 Node *use = worklist.pop(); 4025 for (uint j = 1; j < use->req(); j++) { 4026 Node* n = use->in(j); 4027 if (n == def) { 4028 4029 // "def" is in peel set, "use" is not in peel set 4030 // or "use" is in the entry boundary (a phi) of the peel set 4031 4032 Node* use_c = has_ctrl(use) ? get_ctrl(use) : use; 4033 4034 if ( loop->is_member(get_loop( use_c )) ) { 4035 // use is in loop 4036 if (old_new[use->_idx] != nullptr) { // null for dead code 4037 Node* use_clone = old_new[use->_idx]; 4038 _igvn.replace_input_of(use, j, C->top()); 4039 insert_phi_for_loop( use_clone, j, old_new[def->_idx], def, new_head_clone ); 4040 } 4041 } else { 4042 assert(is_valid_clone_loop_exit_use(loop, use, orig_exit_idx), "clone loop format"); 4043 // use is not in the loop, check if the live range includes the cut 4044 Node* lp_if = use_c->in(orig_exit_idx)->in(0); 4045 if (not_peel.test(lp_if->_idx)) { 4046 assert(j == orig_exit_idx, "use from original loop"); 4047 insert_phi_for_loop( use, clone_exit_idx, old_new[def->_idx], def, new_head_clone ); 4048 } 4049 } 4050 } 4051 } 4052 } 4053 } 4054 } 4055 4056 // Step 3b: retarget control 4057 4058 // Redirect control to the new loop head if a cloned node in 4059 // the not_peeled region has control that points into the peeled region. 4060 // This necessary because the cloned peeled region will be outside 4061 // the loop. 4062 // from to 4063 // cloned-peeled <---+ 4064 // new_head_clone: | <--+ 4065 // cloned-not_peeled in(0) in(0) 4066 // orig-peeled 4067 4068 for (uint i = 0; i < loop->_body.size(); i++) { 4069 Node *n = loop->_body.at(i); 4070 if (!n->is_CFG() && n->in(0) != nullptr && 4071 not_peel.test(n->_idx) && peel.test(n->in(0)->_idx)) { 4072 Node* n_clone = old_new[n->_idx]; 4073 if (n_clone->depends_only_on_test()) { 4074 // Pin array access nodes: control is updated here to the loop head. If, after some transformations, the 4075 // backedge is removed, an array load could become dependent on a condition that's not a range check for that 4076 // access. If that condition is replaced by an identical dominating one, then an unpinned load would risk 4077 // floating above its range check. 4078 Node* pinned_clone = n_clone->pin_array_access_node(); 4079 if (pinned_clone != nullptr) { 4080 register_new_node_with_ctrl_of(pinned_clone, n_clone); 4081 old_new.map(n->_idx, pinned_clone); 4082 _igvn.replace_node(n_clone, pinned_clone); 4083 n_clone = pinned_clone; 4084 } 4085 } 4086 _igvn.replace_input_of(n_clone, 0, new_head_clone); 4087 } 4088 } 4089 4090 // Backedge of the surviving new_head (the clone) is original last_peel 4091 _igvn.replace_input_of(new_head_clone, LoopNode::LoopBackControl, last_peel); 4092 4093 // Cut first node in original not_peel set 4094 _igvn.rehash_node_delayed(new_head); // Multiple edge updates: 4095 new_head->set_req(LoopNode::EntryControl, C->top()); // use rehash_node_delayed / set_req instead of 4096 new_head->set_req(LoopNode::LoopBackControl, C->top()); // multiple replace_input_of calls 4097 4098 // Copy head_clone back-branch info to original head 4099 // and remove original head's loop entry and 4100 // clone head's back-branch 4101 _igvn.rehash_node_delayed(head); // Multiple edge updates 4102 head->set_req(LoopNode::EntryControl, head_clone->in(LoopNode::LoopBackControl)); 4103 head->set_req(LoopNode::LoopBackControl, C->top()); 4104 _igvn.replace_input_of(head_clone, LoopNode::LoopBackControl, C->top()); 4105 4106 // Similarly modify the phis 4107 for (DUIterator_Fast kmax, k = head->fast_outs(kmax); k < kmax; k++) { 4108 Node* use = head->fast_out(k); 4109 if (use->is_Phi() && use->outcnt() > 0) { 4110 Node* use_clone = old_new[use->_idx]; 4111 _igvn.rehash_node_delayed(use); // Multiple edge updates 4112 use->set_req(LoopNode::EntryControl, use_clone->in(LoopNode::LoopBackControl)); 4113 use->set_req(LoopNode::LoopBackControl, C->top()); 4114 _igvn.replace_input_of(use_clone, LoopNode::LoopBackControl, C->top()); 4115 } 4116 } 4117 4118 // Step 4: update dominator tree and dominator depth 4119 4120 set_idom(head, orig_tail_clone, dd); 4121 recompute_dom_depth(); 4122 4123 // Inhibit more partial peeling on this loop 4124 new_head_clone->set_partial_peel_loop(); 4125 C->set_major_progress(); 4126 loop->record_for_igvn(); 4127 4128 #ifndef PRODUCT 4129 if (TracePartialPeeling) { 4130 tty->print_cr("\nafter partial peel one iteration"); 4131 Node_List wl; 4132 Node* t = last_peel; 4133 while (true) { 4134 wl.push(t); 4135 if (t == head_clone) break; 4136 t = idom(t); 4137 } 4138 while (wl.size() > 0) { 4139 Node* tt = wl.pop(); 4140 if (tt == head) tty->print_cr("orig head"); 4141 else if (tt == new_head_clone) tty->print_cr("new head"); 4142 else if (tt == head_clone) tty->print_cr("clone head"); 4143 tt->dump(); 4144 } 4145 } 4146 #endif 4147 4148 C->print_method(PHASE_AFTER_PARTIAL_PEELING, 4, new_head_clone); 4149 4150 return true; 4151 } 4152 4153 // Transform: 4154 // 4155 // loop<-----------------+ 4156 // | | 4157 // stmt1 stmt2 .. stmtn | 4158 // | | | | 4159 // \ | / | 4160 // v v v | 4161 // region | 4162 // | | 4163 // shared_stmt | 4164 // | | 4165 // v | 4166 // if | 4167 // / \ | 4168 // | -----------+ 4169 // v 4170 // 4171 // into: 4172 // 4173 // loop<-------------------+ 4174 // | | 4175 // v | 4176 // +->loop | 4177 // | | | 4178 // | stmt1 stmt2 .. stmtn | 4179 // | | | | | 4180 // | | \ / | 4181 // | | v v | 4182 // | | region1 | 4183 // | | | | 4184 // | shared_stmt shared_stmt | 4185 // | | | | 4186 // | v v | 4187 // | if if | 4188 // | /\ / \ | 4189 // +-- | | -------+ 4190 // \ / 4191 // v v 4192 // region2 4193 // 4194 // (region2 is shown to merge mirrored projections of the loop exit 4195 // ifs to make the diagram clearer but they really merge the same 4196 // projection) 4197 // 4198 // Conditions for this transformation to trigger: 4199 // - the path through stmt1 is frequent enough 4200 // - the inner loop will be turned into a counted loop after transformation 4201 bool PhaseIdealLoop::duplicate_loop_backedge(IdealLoopTree *loop, Node_List &old_new) { 4202 if (!DuplicateBackedge) { 4203 return false; 4204 } 4205 assert(!loop->_head->is_CountedLoop() || StressDuplicateBackedge, "Non-counted loop only"); 4206 if (!loop->_head->is_Loop()) { 4207 return false; 4208 } 4209 4210 uint estimate = loop->est_loop_clone_sz(1); 4211 if (exceeding_node_budget(estimate)) { 4212 return false; 4213 } 4214 4215 LoopNode *head = loop->_head->as_Loop(); 4216 4217 Node* region = nullptr; 4218 IfNode* exit_test = nullptr; 4219 uint inner; 4220 float f; 4221 if (StressDuplicateBackedge) { 4222 if (head->is_strip_mined()) { 4223 return false; 4224 } 4225 Node* c = head->in(LoopNode::LoopBackControl); 4226 4227 while (c != head) { 4228 if (c->is_Region()) { 4229 region = c; 4230 } 4231 c = idom(c); 4232 } 4233 4234 if (region == nullptr) { 4235 return false; 4236 } 4237 4238 inner = 1; 4239 } else { 4240 // Is the shape of the loop that of a counted loop... 4241 Node* back_control = loop_exit_control(head, loop); 4242 if (back_control == nullptr) { 4243 return false; 4244 } 4245 4246 BoolTest::mask bt = BoolTest::illegal; 4247 float cl_prob = 0; 4248 Node* incr = nullptr; 4249 Node* limit = nullptr; 4250 Node* cmp = loop_exit_test(back_control, loop, incr, limit, bt, cl_prob); 4251 if (cmp == nullptr || cmp->Opcode() != Op_CmpI) { 4252 return false; 4253 } 4254 4255 // With an extra phi for the candidate iv? 4256 // Or the region node is the loop head 4257 if (!incr->is_Phi() || incr->in(0) == head) { 4258 return false; 4259 } 4260 4261 PathFrequency pf(head, this); 4262 region = incr->in(0); 4263 4264 // Go over all paths for the extra phi's region and see if that 4265 // path is frequent enough and would match the expected iv shape 4266 // if the extra phi is removed 4267 inner = 0; 4268 for (uint i = 1; i < incr->req(); ++i) { 4269 Node* in = incr->in(i); 4270 Node* trunc1 = nullptr; 4271 Node* trunc2 = nullptr; 4272 const TypeInteger* iv_trunc_t = nullptr; 4273 Node* orig_in = in; 4274 if (!(in = CountedLoopNode::match_incr_with_optional_truncation(in, &trunc1, &trunc2, &iv_trunc_t, T_INT))) { 4275 continue; 4276 } 4277 assert(in->Opcode() == Op_AddI, "wrong increment code"); 4278 Node* xphi = nullptr; 4279 Node* stride = loop_iv_stride(in, xphi); 4280 4281 if (stride == nullptr) { 4282 continue; 4283 } 4284 4285 PhiNode* phi = loop_iv_phi(xphi, nullptr, head); 4286 if (phi == nullptr || 4287 (trunc1 == nullptr && phi->in(LoopNode::LoopBackControl) != incr) || 4288 (trunc1 != nullptr && phi->in(LoopNode::LoopBackControl) != trunc1)) { 4289 return false; 4290 } 4291 4292 f = pf.to(region->in(i)); 4293 if (f > 0.5) { 4294 inner = i; 4295 break; 4296 } 4297 } 4298 4299 if (inner == 0) { 4300 return false; 4301 } 4302 4303 exit_test = back_control->in(0)->as_If(); 4304 } 4305 4306 if (idom(region)->is_Catch()) { 4307 return false; 4308 } 4309 4310 // Collect all control nodes that need to be cloned (shared_stmt in the diagram) 4311 Unique_Node_List wq; 4312 wq.push(head->in(LoopNode::LoopBackControl)); 4313 for (uint i = 0; i < wq.size(); i++) { 4314 Node* c = wq.at(i); 4315 assert(get_loop(c) == loop, "not in the right loop?"); 4316 if (c->is_Region()) { 4317 if (c != region) { 4318 for (uint j = 1; j < c->req(); ++j) { 4319 wq.push(c->in(j)); 4320 } 4321 } 4322 } else { 4323 wq.push(c->in(0)); 4324 } 4325 assert(!is_strict_dominator(c, region), "shouldn't go above region"); 4326 } 4327 4328 Node* region_dom = idom(region); 4329 4330 // Can't do the transformation if this would cause a membar pair to 4331 // be split 4332 for (uint i = 0; i < wq.size(); i++) { 4333 Node* c = wq.at(i); 4334 if (c->is_MemBar() && (c->as_MemBar()->trailing_store() || c->as_MemBar()->trailing_load_store())) { 4335 assert(c->as_MemBar()->leading_membar()->trailing_membar() == c, "bad membar pair"); 4336 if (!wq.member(c->as_MemBar()->leading_membar())) { 4337 return false; 4338 } 4339 } 4340 } 4341 4342 // Collect data nodes that need to be clones as well 4343 int dd = dom_depth(head); 4344 4345 for (uint i = 0; i < loop->_body.size(); ++i) { 4346 Node* n = loop->_body.at(i); 4347 if (has_ctrl(n)) { 4348 Node* c = get_ctrl(n); 4349 if (wq.member(c)) { 4350 wq.push(n); 4351 } 4352 } else { 4353 set_idom(n, idom(n), dd); 4354 } 4355 } 4356 4357 // clone shared_stmt 4358 clone_loop_body(wq, old_new, nullptr); 4359 4360 Node* region_clone = old_new[region->_idx]; 4361 region_clone->set_req(inner, C->top()); 4362 set_idom(region, region->in(inner), dd); 4363 4364 // Prepare the outer loop 4365 Node* outer_head = new LoopNode(head->in(LoopNode::EntryControl), old_new[head->in(LoopNode::LoopBackControl)->_idx]); 4366 register_control(outer_head, loop->_parent, outer_head->in(LoopNode::EntryControl)); 4367 _igvn.replace_input_of(head, LoopNode::EntryControl, outer_head); 4368 set_idom(head, outer_head, dd); 4369 4370 fix_body_edges(wq, loop, old_new, dd, loop->_parent, true); 4371 4372 // Make one of the shared_stmt copies only reachable from stmt1, the 4373 // other only from stmt2..stmtn. 4374 Node* dom = nullptr; 4375 for (uint i = 1; i < region->req(); ++i) { 4376 if (i != inner) { 4377 _igvn.replace_input_of(region, i, C->top()); 4378 } 4379 Node* in = region_clone->in(i); 4380 if (in->is_top()) { 4381 continue; 4382 } 4383 if (dom == nullptr) { 4384 dom = in; 4385 } else { 4386 dom = dom_lca(dom, in); 4387 } 4388 } 4389 4390 set_idom(region_clone, dom, dd); 4391 4392 // Set up the outer loop 4393 for (uint i = 0; i < head->outcnt(); i++) { 4394 Node* u = head->raw_out(i); 4395 if (u->is_Phi()) { 4396 Node* outer_phi = u->clone(); 4397 outer_phi->set_req(0, outer_head); 4398 Node* backedge = old_new[u->in(LoopNode::LoopBackControl)->_idx]; 4399 if (backedge == nullptr) { 4400 backedge = u->in(LoopNode::LoopBackControl); 4401 } 4402 outer_phi->set_req(LoopNode::LoopBackControl, backedge); 4403 register_new_node(outer_phi, outer_head); 4404 _igvn.replace_input_of(u, LoopNode::EntryControl, outer_phi); 4405 } 4406 } 4407 4408 // create control and data nodes for out of loop uses (including region2) 4409 Node_List worklist; 4410 uint new_counter = C->unique(); 4411 fix_ctrl_uses(wq, loop, old_new, ControlAroundStripMined, outer_head, nullptr, worklist); 4412 4413 Node_List *split_if_set = nullptr; 4414 Node_List *split_bool_set = nullptr; 4415 Node_List *split_cex_set = nullptr; 4416 fix_data_uses(wq, loop, ControlAroundStripMined, loop->skip_strip_mined(), new_counter, old_new, worklist, 4417 split_if_set, split_bool_set, split_cex_set); 4418 4419 finish_clone_loop(split_if_set, split_bool_set, split_cex_set); 4420 4421 if (exit_test != nullptr) { 4422 float cnt = exit_test->_fcnt; 4423 if (cnt != COUNT_UNKNOWN) { 4424 exit_test->_fcnt = cnt * f; 4425 old_new[exit_test->_idx]->as_If()->_fcnt = cnt * (1 - f); 4426 } 4427 } 4428 4429 C->set_major_progress(); 4430 4431 return true; 4432 } 4433 4434 // AutoVectorize the loop: replace scalar ops with vector ops. 4435 PhaseIdealLoop::AutoVectorizeStatus 4436 PhaseIdealLoop::auto_vectorize(IdealLoopTree* lpt, VSharedData &vshared) { 4437 // Counted loop only 4438 if (!lpt->is_counted()) { 4439 return AutoVectorizeStatus::Impossible; 4440 } 4441 4442 // Main-loop only 4443 CountedLoopNode* cl = lpt->_head->as_CountedLoop(); 4444 if (!cl->is_main_loop()) { 4445 return AutoVectorizeStatus::Impossible; 4446 } 4447 4448 VLoop vloop(lpt, false); 4449 if (!vloop.check_preconditions()) { 4450 return AutoVectorizeStatus::TriedAndFailed; 4451 } 4452 4453 // Ensure the shared data is cleared before each use 4454 vshared.clear(); 4455 4456 const VLoopAnalyzer vloop_analyzer(vloop, vshared); 4457 if (!vloop_analyzer.success()) { 4458 return AutoVectorizeStatus::TriedAndFailed; 4459 } 4460 4461 SuperWord sw(vloop_analyzer); 4462 if (!sw.transform_loop()) { 4463 return AutoVectorizeStatus::TriedAndFailed; 4464 } 4465 4466 return AutoVectorizeStatus::Success; 4467 } 4468 4469 // Just before insert_pre_post_loops, we can multiversion the loop: 4470 // 4471 // multiversion_if 4472 // | | 4473 // fast_loop slow_loop 4474 // 4475 // In the fast_loop we can make speculative assumptions, and put the 4476 // conditions into the multiversion_if. If the conditions hold at runtime, 4477 // we enter the fast_loop, if the conditions fail, we take the slow_loop 4478 // instead which does not make any of the speculative assumptions. 4479 // 4480 // Note: we only multiversion the loop if the loop does not have any 4481 // auto vectorization check Predicate. If we have that predicate, 4482 // then we can simply add the speculative assumption checks to 4483 // that Predicate. This means we do not need to duplicate the 4484 // loop - we have a smaller graph and save compile time. Should 4485 // the conditions ever fail, then we deopt / trap at the Predicate 4486 // and recompile without that Predicate. At that point we will 4487 // multiversion the loop, so that we can still have speculative 4488 // runtime checks. 4489 // 4490 // We perform the multiversioning when the loop is still in its single 4491 // iteration form, even before we insert pre and post loops. This makes 4492 // the cloning much simpler. However, this means that both the fast 4493 // and the slow loop have to be optimized independently (adding pre 4494 // and post loops, unrolling the main loop, auto-vectorize etc.). And 4495 // we may end up not needing any speculative assumptions in the fast_loop 4496 // and then rejecting the slow_loop by constant folding the multiversion_if. 4497 // 4498 // Therefore, we "delay" the optimization of the slow_loop until we add 4499 // at least one speculative assumption for the fast_loop. If we never 4500 // add such a speculative runtime check, the OpaqueMultiversioningNode 4501 // of the multiversion_if constant folds to true after loop opts, and the 4502 // multiversion_if folds away the "delayed" slow_loop. If we add any 4503 // speculative assumption, then we notify the OpaqueMultiversioningNode 4504 // with "notify_slow_loop_that_it_can_resume_optimizations". 4505 // 4506 // Note: new runtime checks can be added to the multiversion_if with 4507 // PhaseIdealLoop::create_new_if_for_multiversion 4508 void PhaseIdealLoop::maybe_multiversion_for_auto_vectorization_runtime_checks(IdealLoopTree* lpt, Node_List& old_new) { 4509 CountedLoopNode* cl = lpt->_head->as_CountedLoop(); 4510 LoopNode* outer_loop = cl->skip_strip_mined(); 4511 Node* entry = outer_loop->in(LoopNode::EntryControl); 4512 4513 // Check we have multiversioning enabled, and are not already multiversioned. 4514 if (!LoopMultiversioning || cl->is_multiversion()) { return; } 4515 4516 // Check that we do not have a parse-predicate where we can add the runtime checks 4517 // during auto-vectorization. 4518 const Predicates predicates(entry); 4519 const PredicateBlock* predicate_block = predicates.auto_vectorization_check_block(); 4520 if (predicate_block->has_parse_predicate()) { return; } 4521 4522 // Check node budget. 4523 uint estimate = lpt->est_loop_clone_sz(2); 4524 if (!may_require_nodes(estimate)) { return; } 4525 4526 do_multiversioning(lpt, old_new); 4527 } 4528 4529 // Returns true if the Reduction node is unordered. 4530 static bool is_unordered_reduction(Node* n) { 4531 return n->is_Reduction() && !n->as_Reduction()->requires_strict_order(); 4532 } 4533 4534 // Having ReductionNodes in the loop is expensive. They need to recursively 4535 // fold together the vector values, for every vectorized loop iteration. If 4536 // we encounter the following pattern, we can vector accumulate the values 4537 // inside the loop, and only have a single UnorderedReduction after the loop. 4538 // 4539 // Note: UnorderedReduction represents a ReductionNode which does not require 4540 // calculating in strict order. 4541 // 4542 // CountedLoop init 4543 // | | 4544 // +------+ | +-----------------------+ 4545 // | | | | 4546 // PhiNode (s) | 4547 // | | 4548 // | Vector | 4549 // | | | 4550 // UnorderedReduction (first_ur) | 4551 // | | 4552 // ... Vector | 4553 // | | | 4554 // UnorderedReduction (last_ur) | 4555 // | | 4556 // +---------------------+ 4557 // 4558 // We patch the graph to look like this: 4559 // 4560 // CountedLoop identity_vector 4561 // | | 4562 // +-------+ | +---------------+ 4563 // | | | | 4564 // PhiNode (v) | 4565 // | | 4566 // | Vector | 4567 // | | | 4568 // VectorAccumulator | 4569 // | | 4570 // ... Vector | 4571 // | | | 4572 // init VectorAccumulator | 4573 // | | | | 4574 // UnorderedReduction +-----------+ 4575 // 4576 // We turned the scalar (s) Phi into a vectorized one (v). In the loop, we 4577 // use vector_accumulators, which do the same reductions, but only element 4578 // wise. This is a single operation per vector_accumulator, rather than many 4579 // for a UnorderedReduction. We can then reduce the last vector_accumulator 4580 // after the loop, and also reduce the init value into it. 4581 // 4582 // We can not do this with all reductions. Some reductions do not allow the 4583 // reordering of operations (for example float addition/multiplication require 4584 // strict order). 4585 void PhaseIdealLoop::move_unordered_reduction_out_of_loop(IdealLoopTree* loop) { 4586 assert(!C->major_progress() && loop->is_counted() && loop->is_innermost(), "sanity"); 4587 4588 // Find all Phi nodes with an unordered Reduction on backedge. 4589 CountedLoopNode* cl = loop->_head->as_CountedLoop(); 4590 for (DUIterator_Fast jmax, j = cl->fast_outs(jmax); j < jmax; j++) { 4591 Node* phi = cl->fast_out(j); 4592 // We have a phi with a single use, and an unordered Reduction on the backedge. 4593 if (!phi->is_Phi() || phi->outcnt() != 1 || !is_unordered_reduction(phi->in(2))) { 4594 continue; 4595 } 4596 4597 ReductionNode* last_ur = phi->in(2)->as_Reduction(); 4598 assert(!last_ur->requires_strict_order(), "must be"); 4599 4600 // Determine types 4601 const TypeVect* vec_t = last_ur->vect_type(); 4602 uint vector_length = vec_t->length(); 4603 BasicType bt = vec_t->element_basic_type(); 4604 4605 // Convert opcode from vector-reduction -> scalar -> normal-vector-op 4606 const int sopc = VectorNode::scalar_opcode(last_ur->Opcode(), bt); 4607 const int vopc = VectorNode::opcode(sopc, bt); 4608 if (!Matcher::match_rule_supported_vector(vopc, vector_length, bt)) { 4609 DEBUG_ONLY( last_ur->dump(); ) 4610 assert(false, "do not have normal vector op for this reduction"); 4611 continue; // not implemented -> fails 4612 } 4613 4614 // Traverse up the chain of unordered Reductions, checking that it loops back to 4615 // the phi. Check that all unordered Reductions only have a single use, except for 4616 // the last (last_ur), which only has phi as a use in the loop, and all other uses 4617 // are outside the loop. 4618 ReductionNode* current = last_ur; 4619 ReductionNode* first_ur = nullptr; 4620 while (true) { 4621 assert(!current->requires_strict_order(), "sanity"); 4622 4623 // Expect no ctrl and a vector_input from within the loop. 4624 Node* ctrl = current->in(0); 4625 Node* vector_input = current->in(2); 4626 if (ctrl != nullptr || get_ctrl(vector_input) != cl) { 4627 DEBUG_ONLY( current->dump(1); ) 4628 assert(false, "reduction has ctrl or bad vector_input"); 4629 break; // Chain traversal fails. 4630 } 4631 4632 assert(current->vect_type() != nullptr, "must have vector type"); 4633 if (current->vect_type() != last_ur->vect_type()) { 4634 // Reductions do not have the same vector type (length and element type). 4635 break; // Chain traversal fails. 4636 } 4637 4638 // Expect single use of an unordered Reduction, except for last_ur. 4639 if (current == last_ur) { 4640 // Expect all uses to be outside the loop, except phi. 4641 for (DUIterator_Fast kmax, k = current->fast_outs(kmax); k < kmax; k++) { 4642 Node* use = current->fast_out(k); 4643 if (use != phi && ctrl_or_self(use) == cl) { 4644 DEBUG_ONLY( current->dump(-1); ) 4645 assert(false, "reduction has use inside loop"); 4646 // Should not be allowed by SuperWord::mark_reductions 4647 return; // bail out of optimization 4648 } 4649 } 4650 } else { 4651 if (current->outcnt() != 1) { 4652 break; // Chain traversal fails. 4653 } 4654 } 4655 4656 // Expect another unordered Reduction or phi as the scalar input. 4657 Node* scalar_input = current->in(1); 4658 if (is_unordered_reduction(scalar_input) && 4659 scalar_input->Opcode() == current->Opcode()) { 4660 // Move up the unordered Reduction chain. 4661 current = scalar_input->as_Reduction(); 4662 assert(!current->requires_strict_order(), "must be"); 4663 } else if (scalar_input == phi) { 4664 // Chain terminates at phi. 4665 first_ur = current; 4666 current = nullptr; 4667 break; // Success. 4668 } else { 4669 // scalar_input is neither phi nor a matching reduction 4670 // Can for example be scalar reduction when we have 4671 // partial vectorization. 4672 break; // Chain traversal fails. 4673 } 4674 } 4675 if (current != nullptr) { 4676 // Chain traversal was not successful. 4677 continue; 4678 } 4679 assert(first_ur != nullptr, "must have successfully terminated chain traversal"); 4680 4681 Node* identity_scalar = ReductionNode::make_identity_con_scalar(_igvn, sopc, bt); 4682 set_root_as_ctrl(identity_scalar); 4683 VectorNode* identity_vector = VectorNode::scalar2vector(identity_scalar, vector_length, bt); 4684 register_new_node(identity_vector, C->root()); 4685 assert(vec_t == identity_vector->vect_type(), "matching vector type"); 4686 VectorNode::trace_new_vector(identity_vector, "Unordered Reduction"); 4687 4688 // Turn the scalar phi into a vector phi. 4689 _igvn.rehash_node_delayed(phi); 4690 Node* init = phi->in(1); // Remember init before replacing it. 4691 phi->set_req_X(1, identity_vector, &_igvn); 4692 phi->as_Type()->set_type(vec_t); 4693 _igvn.set_type(phi, vec_t); 4694 4695 // Traverse down the chain of unordered Reductions, and replace them with vector_accumulators. 4696 current = first_ur; 4697 while (true) { 4698 // Create vector_accumulator to replace current. 4699 Node* last_vector_accumulator = current->in(1); 4700 Node* vector_input = current->in(2); 4701 VectorNode* vector_accumulator = VectorNode::make(vopc, last_vector_accumulator, vector_input, vec_t); 4702 register_new_node(vector_accumulator, cl); 4703 _igvn.replace_node(current, vector_accumulator); 4704 VectorNode::trace_new_vector(vector_accumulator, "Unordered Reduction"); 4705 if (current == last_ur) { 4706 break; 4707 } 4708 current = vector_accumulator->unique_out()->as_Reduction(); 4709 assert(!current->requires_strict_order(), "must be"); 4710 } 4711 4712 // Create post-loop reduction. 4713 Node* last_accumulator = phi->in(2); 4714 Node* post_loop_reduction = ReductionNode::make(sopc, nullptr, init, last_accumulator, bt); 4715 4716 // Take over uses of last_accumulator that are not in the loop. 4717 for (DUIterator i = last_accumulator->outs(); last_accumulator->has_out(i); i++) { 4718 Node* use = last_accumulator->out(i); 4719 if (use != phi && use != post_loop_reduction) { 4720 assert(ctrl_or_self(use) != cl, "use must be outside loop"); 4721 use->replace_edge(last_accumulator, post_loop_reduction, &_igvn); 4722 --i; 4723 } 4724 } 4725 register_new_node(post_loop_reduction, get_late_ctrl(post_loop_reduction, cl)); 4726 VectorNode::trace_new_vector(post_loop_reduction, "Unordered Reduction"); 4727 4728 assert(last_accumulator->outcnt() == 2, "last_accumulator has 2 uses: phi and post_loop_reduction"); 4729 assert(post_loop_reduction->outcnt() > 0, "should have taken over all non loop uses of last_accumulator"); 4730 assert(phi->outcnt() == 1, "accumulator is the only use of phi"); 4731 } 4732 } 4733 4734 void DataNodeGraph::clone_data_nodes(Node* new_ctrl) { 4735 for (uint i = 0; i < _data_nodes.size(); i++) { 4736 clone(_data_nodes[i], new_ctrl); 4737 } 4738 } 4739 4740 // Clone the given node and set it up properly. Set 'new_ctrl' as ctrl. 4741 void DataNodeGraph::clone(Node* node, Node* new_ctrl) { 4742 Node* clone = node->clone(); 4743 _phase->igvn().register_new_node_with_optimizer(clone); 4744 _orig_to_new.put(node, clone); 4745 _phase->set_ctrl(clone, new_ctrl); 4746 if (node->is_CastII()) { 4747 clone->set_req(0, new_ctrl); 4748 } 4749 } 4750 4751 // Rewire the data inputs of all (unprocessed) cloned nodes, whose inputs are still pointing to the same inputs as their 4752 // corresponding orig nodes, to the newly cloned inputs to create a separate cloned graph. 4753 void DataNodeGraph::rewire_clones_to_cloned_inputs() { 4754 _orig_to_new.iterate_all([&](Node* node, Node* clone) { 4755 for (uint i = 1; i < node->req(); i++) { 4756 Node** cloned_input = _orig_to_new.get(node->in(i)); 4757 if (cloned_input != nullptr) { 4758 // Input was also cloned -> rewire clone to the cloned input. 4759 _phase->igvn().replace_input_of(clone, i, *cloned_input); 4760 } 4761 } 4762 }); 4763 } 4764 4765 // Clone all non-OpaqueLoop* nodes and apply the provided transformation strategy for OpaqueLoop* nodes. 4766 // Set 'new_ctrl' as ctrl for all cloned non-OpaqueLoop* nodes. 4767 void DataNodeGraph::clone_data_nodes_and_transform_opaque_loop_nodes( 4768 const TransformStrategyForOpaqueLoopNodes& transform_strategy, 4769 Node* new_ctrl) { 4770 for (uint i = 0; i < _data_nodes.size(); i++) { 4771 Node* data_node = _data_nodes[i]; 4772 if (data_node->is_Opaque1()) { 4773 transform_opaque_node(transform_strategy, data_node); 4774 } else { 4775 clone(data_node, new_ctrl); 4776 } 4777 } 4778 } 4779 4780 void DataNodeGraph::transform_opaque_node(const TransformStrategyForOpaqueLoopNodes& transform_strategy, Node* node) { 4781 Node* transformed_node; 4782 if (node->is_OpaqueLoopInit()) { 4783 transformed_node = transform_strategy.transform_opaque_init(node->as_OpaqueLoopInit()); 4784 } else { 4785 assert(node->is_OpaqueLoopStride(), "must be OpaqueLoopStrideNode"); 4786 transformed_node = transform_strategy.transform_opaque_stride(node->as_OpaqueLoopStride()); 4787 } 4788 // Add an orig->new mapping to correctly update the inputs of the copied graph in rewire_clones_to_cloned_inputs(). 4789 _orig_to_new.put(node, transformed_node); 4790 }