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