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