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