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