1 /*
2 * Copyright (c) 1998, 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 "ci/ciMethodData.hpp"
26 #include "compiler/compileLog.hpp"
27 #include "gc/shared/barrierSet.hpp"
28 #include "gc/shared/c2/barrierSetC2.hpp"
29 #include "libadt/vectset.hpp"
30 #include "memory/allocation.inline.hpp"
31 #include "memory/resourceArea.hpp"
32 #include "opto/addnode.hpp"
33 #include "opto/arraycopynode.hpp"
34 #include "opto/c2_globals.hpp"
35 #include "opto/callnode.hpp"
36 #include "opto/castnode.hpp"
37 #include "opto/connode.hpp"
38 #include "opto/convertnode.hpp"
39 #include "opto/divnode.hpp"
40 #include "opto/idealGraphPrinter.hpp"
41 #include "opto/loopnode.hpp"
42 #include "opto/movenode.hpp"
43 #include "opto/mulnode.hpp"
44 #include "opto/opaquenode.hpp"
45 #include "opto/opcodes.hpp"
46 #include "opto/predicates.hpp"
47 #include "opto/rootnode.hpp"
48 #include "opto/runtime.hpp"
49 #include "opto/vectorization.hpp"
50 #include "runtime/sharedRuntime.hpp"
51 #include "utilities/checkedCast.hpp"
52 #include "utilities/powerOfTwo.hpp"
53
54 //=============================================================================
55 //--------------------------is_cloop_ind_var-----------------------------------
56 // Determine if a node is a counted loop induction variable.
57 // NOTE: The method is declared in "node.hpp".
58 bool Node::is_cloop_ind_var() const {
59 return (is_Phi() &&
60 as_Phi()->region()->is_CountedLoop() &&
61 as_Phi()->region()->as_CountedLoop()->phi() == this);
62 }
63
64 //=============================================================================
65 //------------------------------dump_spec--------------------------------------
66 // Dump special per-node info
67 #ifndef PRODUCT
68 void LoopNode::dump_spec(outputStream *st) const {
69 RegionNode::dump_spec(st);
70 if (is_inner_loop()) st->print( "inner " );
71 if (is_partial_peel_loop()) st->print( "partial_peel " );
72 if (partial_peel_has_failed()) st->print( "partial_peel_failed " );
73 }
74 #endif
75
76 //------------------------------is_valid_counted_loop-------------------------
77 bool LoopNode::is_valid_counted_loop(BasicType bt) const {
78 if (is_BaseCountedLoop() && as_BaseCountedLoop()->bt() == bt) {
79 BaseCountedLoopNode* l = as_BaseCountedLoop();
80 BaseCountedLoopEndNode* le = l->loopexit_or_null();
81 if (le != nullptr &&
82 le->proj_out_or_null(1 /* true */) == l->in(LoopNode::LoopBackControl)) {
83 Node* phi = l->phi();
84 Node* exit = le->proj_out_or_null(0 /* false */);
85 if (exit != nullptr && exit->Opcode() == Op_IfFalse &&
86 phi != nullptr && phi->is_Phi() &&
87 phi->in(LoopNode::LoopBackControl) == l->incr() &&
88 le->loopnode() == l && le->stride_is_con()) {
89 return true;
90 }
91 }
92 }
93 return false;
94 }
95
96 //------------------------------get_early_ctrl---------------------------------
97 // Compute earliest legal control
98 Node *PhaseIdealLoop::get_early_ctrl( Node *n ) {
99 assert( !n->is_Phi() && !n->is_CFG(), "this code only handles data nodes" );
100 uint i;
101 Node *early;
102 if (n->in(0) && !n->is_expensive()) {
103 early = n->in(0);
104 if (!early->is_CFG()) // Might be a non-CFG multi-def
105 early = get_ctrl(early); // So treat input as a straight data input
106 i = 1;
107 } else {
108 early = get_ctrl(n->in(1));
109 i = 2;
110 }
111 uint e_d = dom_depth(early);
112 assert( early, "" );
113 for (; i < n->req(); i++) {
114 Node *cin = get_ctrl(n->in(i));
115 assert( cin, "" );
116 // Keep deepest dominator depth
117 uint c_d = dom_depth(cin);
118 if (c_d > e_d) { // Deeper guy?
119 early = cin; // Keep deepest found so far
120 e_d = c_d;
121 } else if (c_d == e_d && // Same depth?
122 early != cin) { // If not equal, must use slower algorithm
123 // If same depth but not equal, one _must_ dominate the other
124 // and we want the deeper (i.e., dominated) guy.
125 Node *n1 = early;
126 Node *n2 = cin;
127 while (1) {
128 n1 = idom(n1); // Walk up until break cycle
129 n2 = idom(n2);
130 if (n1 == cin || // Walked early up to cin
131 dom_depth(n2) < c_d)
132 break; // early is deeper; keep him
133 if (n2 == early || // Walked cin up to early
134 dom_depth(n1) < c_d) {
135 early = cin; // cin is deeper; keep him
136 break;
137 }
138 }
139 e_d = dom_depth(early); // Reset depth register cache
140 }
141 }
142
143 // Return earliest legal location
144 assert(early == find_non_split_ctrl(early), "unexpected early control");
145
146 if (n->is_expensive() && !_verify_only && !_verify_me) {
147 assert(n->in(0), "should have control input");
148 early = get_early_ctrl_for_expensive(n, early);
149 }
150
151 return early;
152 }
153
154 //------------------------------get_early_ctrl_for_expensive---------------------------------
155 // Move node up the dominator tree as high as legal while still beneficial
156 Node *PhaseIdealLoop::get_early_ctrl_for_expensive(Node *n, Node* earliest) {
157 assert(n->in(0) && n->is_expensive(), "expensive node with control input here");
158 assert(OptimizeExpensiveOps, "optimization off?");
159
160 Node* ctl = n->in(0);
161 assert(ctl->is_CFG(), "expensive input 0 must be cfg");
162 uint min_dom_depth = dom_depth(earliest);
163 #ifdef ASSERT
164 if (!is_dominator(ctl, earliest) && !is_dominator(earliest, ctl)) {
165 dump_bad_graph("Bad graph detected in get_early_ctrl_for_expensive", n, earliest, ctl);
166 assert(false, "Bad graph detected in get_early_ctrl_for_expensive");
167 }
168 #endif
169 if (dom_depth(ctl) < min_dom_depth) {
170 return earliest;
171 }
172
173 while (true) {
174 Node* next = ctl;
175 // Moving the node out of a loop on the projection of an If
176 // confuses Loop Predication. So, once we hit a loop in an If branch
177 // that doesn't branch to an UNC, we stop. The code that process
178 // expensive nodes will notice the loop and skip over it to try to
179 // move the node further up.
180 if (ctl->is_CountedLoop() && ctl->in(1) != nullptr && ctl->in(1)->in(0) != nullptr && ctl->in(1)->in(0)->is_If()) {
181 if (!ctl->in(1)->as_Proj()->is_uncommon_trap_if_pattern()) {
182 break;
183 }
184 next = idom(ctl->in(1)->in(0));
185 } else if (ctl->is_Proj()) {
186 // We only move it up along a projection if the projection is
187 // the single control projection for its parent: same code path,
188 // if it's a If with UNC or fallthrough of a call.
189 Node* parent_ctl = ctl->in(0);
190 if (parent_ctl == nullptr) {
191 break;
192 } else if (parent_ctl->is_CountedLoopEnd() && parent_ctl->as_CountedLoopEnd()->loopnode() != nullptr) {
193 next = parent_ctl->as_CountedLoopEnd()->loopnode()->init_control();
194 } else if (parent_ctl->is_If()) {
195 if (!ctl->as_Proj()->is_uncommon_trap_if_pattern()) {
196 break;
197 }
198 assert(idom(ctl) == parent_ctl, "strange");
199 next = idom(parent_ctl);
200 } else if (ctl->is_CatchProj()) {
201 if (ctl->as_Proj()->_con != CatchProjNode::fall_through_index) {
202 break;
203 }
204 assert(parent_ctl->in(0)->in(0)->is_Call(), "strange graph");
205 next = parent_ctl->in(0)->in(0)->in(0);
206 } else {
207 // Check if parent control has a single projection (this
208 // control is the only possible successor of the parent
209 // control). If so, we can try to move the node above the
210 // parent control.
211 int nb_ctl_proj = 0;
212 for (DUIterator_Fast imax, i = parent_ctl->fast_outs(imax); i < imax; i++) {
213 Node *p = parent_ctl->fast_out(i);
214 if (p->is_Proj() && p->is_CFG()) {
215 nb_ctl_proj++;
216 if (nb_ctl_proj > 1) {
217 break;
218 }
219 }
220 }
221
222 if (nb_ctl_proj > 1) {
223 break;
224 }
225 assert(parent_ctl->is_Start() || parent_ctl->is_MemBar() || parent_ctl->is_Call() ||
226 BarrierSet::barrier_set()->barrier_set_c2()->is_gc_barrier_node(parent_ctl), "unexpected node");
227 assert(idom(ctl) == parent_ctl, "strange");
228 next = idom(parent_ctl);
229 }
230 } else {
231 next = idom(ctl);
232 }
233 if (next->is_Root() || next->is_Start() || dom_depth(next) < min_dom_depth) {
234 break;
235 }
236 ctl = next;
237 }
238
239 if (ctl != n->in(0)) {
240 _igvn.replace_input_of(n, 0, ctl);
241 _igvn.hash_insert(n);
242 }
243
244 return ctl;
245 }
246
247
248 //------------------------------set_early_ctrl---------------------------------
249 // Set earliest legal control
250 void PhaseIdealLoop::set_early_ctrl(Node* n, bool update_body) {
251 Node *early = get_early_ctrl(n);
252
253 // Record earliest legal location
254 set_ctrl(n, early);
255 IdealLoopTree *loop = get_loop(early);
256 if (update_body && loop->_child == nullptr) {
257 loop->_body.push(n);
258 }
259 }
260
261 //------------------------------set_subtree_ctrl-------------------------------
262 // set missing _ctrl entries on new nodes
263 void PhaseIdealLoop::set_subtree_ctrl(Node* n, bool update_body) {
264 // Already set? Get out.
265 if (_loop_or_ctrl[n->_idx]) return;
266 // Recursively set _loop_or_ctrl array to indicate where the Node goes
267 uint i;
268 for (i = 0; i < n->req(); ++i) {
269 Node *m = n->in(i);
270 if (m && m != C->root()) {
271 set_subtree_ctrl(m, update_body);
272 }
273 }
274
275 // Fixup self
276 set_early_ctrl(n, update_body);
277 }
278
279 IdealLoopTree* PhaseIdealLoop::insert_outer_loop(IdealLoopTree* loop, LoopNode* outer_l, Node* outer_ift) {
280 IdealLoopTree* outer_ilt = new IdealLoopTree(this, outer_l, outer_ift);
281 IdealLoopTree* parent = loop->_parent;
282 IdealLoopTree* sibling = parent->_child;
283 if (sibling == loop) {
284 parent->_child = outer_ilt;
285 } else {
286 while (sibling->_next != loop) {
287 sibling = sibling->_next;
288 }
289 sibling->_next = outer_ilt;
290 }
291 outer_ilt->_next = loop->_next;
292 outer_ilt->_parent = parent;
293 outer_ilt->_child = loop;
294 outer_ilt->_nest = loop->_nest;
295 loop->_parent = outer_ilt;
296 loop->_next = nullptr;
297 loop->_nest++;
298 assert(loop->_nest <= SHRT_MAX, "sanity");
299 return outer_ilt;
300 }
301
302 // Create a skeleton strip mined outer loop: an OuterStripMinedLoop head before the inner strip mined CountedLoop, a
303 // SafePoint on exit of the inner CountedLoopEnd and an OuterStripMinedLoopEnd test that can't constant fold until loop
304 // optimizations are over. The inner strip mined loop is left as it is. Only once loop optimizations are over, do we
305 // adjust the inner loop exit condition to limit its number of iterations, set the outer loop exit condition and add
306 // Phis to the outer loop head. Some loop optimizations that operate on the inner strip mined loop need to be aware of
307 // the outer strip mined loop: loop unswitching needs to clone the outer loop as well as the inner, unrolling needs to
308 // only clone the inner loop etc. No optimizations need to change the outer strip mined loop as it is only a skeleton.
309 //
310 // Schematically:
311 //
312 // OuterStripMinedLoop -------|
313 // | |
314 // CountedLoop ----------- | |
315 // \- Phi (iv) -| | |
316 // / \ | | |
317 // CmpI AddI --| | |
318 // \ | |
319 // Bool | |
320 // \ | |
321 // CountedLoopEnd | |
322 // / \ | |
323 // IfFalse IfTrue--------| |
324 // | |
325 // SafePoint |
326 // | |
327 // OuterStripMinedLoopEnd |
328 // / \ |
329 // IfFalse IfTrue-----------|
330 // |
331 //
332 //
333 // As loop optimizations transform the inner loop, the outer strip mined loop stays mostly unchanged. The only exception
334 // is nodes referenced from the SafePoint and sunk from the inner loop: they end up in the outer strip mined loop.
335 //
336 // Not adding Phis to the outer loop head from the beginning, and only adding them after loop optimizations does not
337 // conform to C2's IR rules: any variable or memory slice that is mutated in a loop should have a Phi. The main
338 // motivation for such a design that doesn't conform to C2's IR rules is to allow existing loop optimizations to be
339 // mostly unaffected by the outer strip mined loop: the only extra step needed in most cases is to step over the
340 // OuterStripMinedLoop. The main drawback is that once loop optimizations are over, an extra step is needed to finish
341 // constructing the outer loop. This is handled by OuterStripMinedLoopNode::adjust_strip_mined_loop().
342 //
343 // Adding Phis to the outer loop is largely straightforward: there needs to be one Phi in the outer loop for every Phi
344 // in the inner loop. Things may be more complicated for sunk Store nodes: there may not be any inner loop Phi left
345 // after sinking for a particular memory slice but the outer loop needs a Phi. See
346 // OuterStripMinedLoopNode::handle_sunk_stores_when_finishing_construction()
347 IdealLoopTree* PhaseIdealLoop::create_outer_strip_mined_loop(Node* init_control,
348 IdealLoopTree* loop, float cl_prob, float le_fcnt,
349 Node*& entry_control, Node*& iffalse) {
350 Node* outer_test = intcon(0);
351 Node *orig = iffalse;
352 iffalse = iffalse->clone();
353 _igvn.register_new_node_with_optimizer(iffalse);
354 set_idom(iffalse, idom(orig), dom_depth(orig));
355
356 IfNode *outer_le = new OuterStripMinedLoopEndNode(iffalse, outer_test, cl_prob, le_fcnt);
357 Node *outer_ift = new IfTrueNode (outer_le);
358 Node* outer_iff = orig;
359 _igvn.replace_input_of(outer_iff, 0, outer_le);
360
361 LoopNode *outer_l = new OuterStripMinedLoopNode(C, init_control, outer_ift);
362 entry_control = outer_l;
363
364 IdealLoopTree* outer_ilt = insert_outer_loop(loop, outer_l, outer_ift);
365
366 set_loop(iffalse, outer_ilt);
367 // When this code runs, loop bodies have not yet been populated.
368 const bool body_populated = false;
369 register_control(outer_le, outer_ilt, iffalse, body_populated);
370 register_control(outer_ift, outer_ilt, outer_le, body_populated);
371 set_idom(outer_iff, outer_le, dom_depth(outer_le));
372 _igvn.register_new_node_with_optimizer(outer_l);
373 set_loop(outer_l, outer_ilt);
374 set_idom(outer_l, init_control, dom_depth(init_control)+1);
375
376 return outer_ilt;
377 }
378
379 void PhaseIdealLoop::insert_loop_limit_check_predicate(ParsePredicateSuccessProj* loop_limit_check_parse_proj,
380 Node* cmp_limit, Node* bol) {
381 assert(loop_limit_check_parse_proj->in(0)->is_ParsePredicate(), "must be parse predicate");
382 Node* new_predicate_proj = create_new_if_for_predicate(loop_limit_check_parse_proj, nullptr,
383 Deoptimization::Reason_loop_limit_check,
384 Op_If);
385 Node* iff = new_predicate_proj->in(0);
386 cmp_limit = _igvn.register_new_node_with_optimizer(cmp_limit);
387 bol = _igvn.register_new_node_with_optimizer(bol);
388 set_subtree_ctrl(bol, false);
389 _igvn.replace_input_of(iff, 1, bol);
390
391 #ifndef PRODUCT
392 // report that the loop predication has been actually performed
393 // for this loop
394 if (TraceLoopLimitCheck) {
395 tty->print_cr("Counted Loop Limit Check generated:");
396 DEBUG_ONLY( bol->dump(2); )
397 }
398 #endif
399 }
400
401 Node* PhaseIdealLoop::loop_exit_control(Node* x, IdealLoopTree* loop) {
402 // Counted loop head must be a good RegionNode with only 3 not null
403 // control input edges: Self, Entry, LoopBack.
404 if (x->in(LoopNode::Self) == nullptr || x->req() != 3 || loop->_irreducible) {
405 return nullptr;
406 }
407 Node *init_control = x->in(LoopNode::EntryControl);
408 Node *back_control = x->in(LoopNode::LoopBackControl);
409 if (init_control == nullptr || back_control == nullptr) { // Partially dead
410 return nullptr;
411 }
412 // Must also check for TOP when looking for a dead loop
413 if (init_control->is_top() || back_control->is_top()) {
414 return nullptr;
415 }
416
417 // Allow funny placement of Safepoint
418 if (back_control->Opcode() == Op_SafePoint) {
419 back_control = back_control->in(TypeFunc::Control);
420 }
421
422 // Controlling test for loop
423 Node *iftrue = back_control;
424 uint iftrue_op = iftrue->Opcode();
425 if (iftrue_op != Op_IfTrue &&
426 iftrue_op != Op_IfFalse) {
427 // I have a weird back-control. Probably the loop-exit test is in
428 // the middle of the loop and I am looking at some trailing control-flow
429 // merge point. To fix this I would have to partially peel the loop.
430 return nullptr; // Obscure back-control
431 }
432
433 // Get boolean guarding loop-back test
434 Node *iff = iftrue->in(0);
435 if (get_loop(iff) != loop || !iff->in(1)->is_Bool()) {
436 return nullptr;
437 }
438 return iftrue;
439 }
440
441 Node* PhaseIdealLoop::loop_exit_test(Node* back_control, IdealLoopTree* loop, Node*& incr, Node*& limit, BoolTest::mask& bt, float& cl_prob) {
442 Node* iftrue = back_control;
443 uint iftrue_op = iftrue->Opcode();
444 Node* iff = iftrue->in(0);
445 BoolNode* test = iff->in(1)->as_Bool();
446 bt = test->_test._test;
447 cl_prob = iff->as_If()->_prob;
448 if (iftrue_op == Op_IfFalse) {
449 bt = BoolTest(bt).negate();
450 cl_prob = 1.0 - cl_prob;
451 }
452 // Get backedge compare
453 Node* cmp = test->in(1);
454 if (!cmp->is_Cmp()) {
455 return nullptr;
456 }
457
458 // Find the trip-counter increment & limit. Limit must be loop invariant.
459 incr = cmp->in(1);
460 limit = cmp->in(2);
461
462 // ---------
463 // need 'loop()' test to tell if limit is loop invariant
464 // ---------
465
466 if (!ctrl_is_member(loop, incr)) { // Swapped trip counter and limit?
467 Node* tmp = incr; // Then reverse order into the CmpI
468 incr = limit;
469 limit = tmp;
470 bt = BoolTest(bt).commute(); // And commute the exit test
471 }
472 if (ctrl_is_member(loop, limit)) { // Limit must be loop-invariant
473 return nullptr;
474 }
475 if (!ctrl_is_member(loop, incr)) { // Trip counter must be loop-variant
476 return nullptr;
477 }
478 return cmp;
479 }
480
481 Node* PhaseIdealLoop::loop_iv_incr(Node* incr, Node* x, IdealLoopTree* loop, Node*& phi_incr) {
482 if (incr->is_Phi()) {
483 if (incr->as_Phi()->region() != x || incr->req() != 3) {
484 return nullptr; // Not simple trip counter expression
485 }
486 phi_incr = incr;
487 incr = phi_incr->in(LoopNode::LoopBackControl); // Assume incr is on backedge of Phi
488 if (!ctrl_is_member(loop, incr)) { // Trip counter must be loop-variant
489 return nullptr;
490 }
491 }
492 return incr;
493 }
494
495 Node* PhaseIdealLoop::loop_iv_stride(Node* incr, Node*& xphi) {
496 assert(incr->Opcode() == Op_AddI || incr->Opcode() == Op_AddL, "caller resp.");
497 // Get merge point
498 xphi = incr->in(1);
499 Node *stride = incr->in(2);
500 if (!stride->is_Con()) { // Oops, swap these
501 if (!xphi->is_Con()) { // Is the other guy a constant?
502 return nullptr; // Nope, unknown stride, bail out
503 }
504 Node *tmp = xphi; // 'incr' is commutative, so ok to swap
505 xphi = stride;
506 stride = tmp;
507 }
508 return stride;
509 }
510
511 PhiNode* PhaseIdealLoop::loop_iv_phi(Node* xphi, Node* phi_incr, Node* x) {
512 if (!xphi->is_Phi()) {
513 return nullptr; // Too much math on the trip counter
514 }
515 if (phi_incr != nullptr && phi_incr != xphi) {
516 return nullptr;
517 }
518 PhiNode *phi = xphi->as_Phi();
519
520 // Phi must be of loop header; backedge must wrap to increment
521 if (phi->region() != x) {
522 return nullptr;
523 }
524 return phi;
525 }
526
527 static int check_stride_overflow(jlong final_correction, const TypeInteger* limit_t, BasicType bt) {
528 if (final_correction > 0) {
529 if (limit_t->lo_as_long() > (max_signed_integer(bt) - final_correction)) {
530 return -1;
531 }
532 if (limit_t->hi_as_long() > (max_signed_integer(bt) - final_correction)) {
533 return 1;
534 }
535 } else {
536 if (limit_t->hi_as_long() < (min_signed_integer(bt) - final_correction)) {
537 return -1;
538 }
539 if (limit_t->lo_as_long() < (min_signed_integer(bt) - final_correction)) {
540 return 1;
541 }
542 }
543 return 0;
544 }
545
546 static bool condition_stride_ok(BoolTest::mask bt, jlong stride_con) {
547 // If the condition is inverted and we will be rolling
548 // through MININT to MAXINT, then bail out.
549 if (bt == BoolTest::eq || // Bail out, but this loop trips at most twice!
550 // Odd stride
551 (bt == BoolTest::ne && stride_con != 1 && stride_con != -1) ||
552 // Count down loop rolls through MAXINT
553 ((bt == BoolTest::le || bt == BoolTest::lt) && stride_con < 0) ||
554 // Count up loop rolls through MININT
555 ((bt == BoolTest::ge || bt == BoolTest::gt) && stride_con > 0)) {
556 return false; // Bail out
557 }
558 return true;
559 }
560
561 Node* PhaseIdealLoop::loop_nest_replace_iv(Node* iv_to_replace, Node* inner_iv, Node* outer_phi, Node* inner_head,
562 BasicType bt) {
563 Node* iv_as_long;
564 if (bt == T_LONG) {
565 iv_as_long = new ConvI2LNode(inner_iv, TypeLong::INT);
566 register_new_node(iv_as_long, inner_head);
567 } else {
568 iv_as_long = inner_iv;
569 }
570 Node* iv_replacement = AddNode::make(outer_phi, iv_as_long, bt);
571 register_new_node(iv_replacement, inner_head);
572 for (DUIterator_Last imin, i = iv_to_replace->last_outs(imin); i >= imin;) {
573 Node* u = iv_to_replace->last_out(i);
574 #ifdef ASSERT
575 if (!is_dominator(inner_head, ctrl_or_self(u))) {
576 assert(u->is_Phi(), "should be a Phi");
577 for (uint j = 1; j < u->req(); j++) {
578 if (u->in(j) == iv_to_replace) {
579 assert(is_dominator(inner_head, u->in(0)->in(j)), "iv use above loop?");
580 }
581 }
582 }
583 #endif
584 _igvn.rehash_node_delayed(u);
585 int nb = u->replace_edge(iv_to_replace, iv_replacement, &_igvn);
586 i -= nb;
587 }
588 return iv_replacement;
589 }
590
591 // Add a Parse Predicate with an uncommon trap on the failing/false path. Normal control will continue on the true path.
592 void PhaseIdealLoop::add_parse_predicate(Deoptimization::DeoptReason reason, Node* inner_head, IdealLoopTree* loop,
593 SafePointNode* sfpt) {
594 if (!C->too_many_traps(reason)) {
595 ParsePredicateNode* parse_predicate = new ParsePredicateNode(inner_head->in(LoopNode::EntryControl), reason, &_igvn);
596 register_control(parse_predicate, loop, inner_head->in(LoopNode::EntryControl));
597 Node* if_false = new IfFalseNode(parse_predicate);
598 register_control(if_false, _ltree_root, parse_predicate);
599 Node* if_true = new IfTrueNode(parse_predicate);
600 register_control(if_true, loop, parse_predicate);
601
602 int trap_request = Deoptimization::make_trap_request(reason, Deoptimization::Action_maybe_recompile);
603 address call_addr = OptoRuntime::uncommon_trap_blob()->entry_point();
604 const TypePtr* no_memory_effects = nullptr;
605 CallNode* unc = new CallStaticJavaNode(OptoRuntime::uncommon_trap_Type(), call_addr, "uncommon_trap",
606 no_memory_effects);
607
608 Node* mem = nullptr;
609 Node* i_o = nullptr;
610 if (sfpt->is_Call()) {
611 mem = sfpt->proj_out(TypeFunc::Memory);
612 i_o = sfpt->proj_out(TypeFunc::I_O);
613 } else {
614 mem = sfpt->memory();
615 i_o = sfpt->i_o();
616 }
617
618 Node *frame = new ParmNode(C->start(), TypeFunc::FramePtr);
619 register_new_node(frame, C->start());
620 Node *ret = new ParmNode(C->start(), TypeFunc::ReturnAdr);
621 register_new_node(ret, C->start());
622
623 unc->init_req(TypeFunc::Control, if_false);
624 unc->init_req(TypeFunc::I_O, i_o);
625 unc->init_req(TypeFunc::Memory, mem); // may gc ptrs
626 unc->init_req(TypeFunc::FramePtr, frame);
627 unc->init_req(TypeFunc::ReturnAdr, ret);
628 unc->init_req(TypeFunc::Parms+0, _igvn.intcon(trap_request));
629 unc->set_cnt(PROB_UNLIKELY_MAG(4));
630 unc->copy_call_debug_info(&_igvn, sfpt);
631
632 for (uint i = TypeFunc::Parms; i < unc->req(); i++) {
633 set_subtree_ctrl(unc->in(i), false);
634 }
635 register_control(unc, _ltree_root, if_false);
636
637 Node* ctrl = new ProjNode(unc, TypeFunc::Control);
638 register_control(ctrl, _ltree_root, unc);
639 Node* halt = new HaltNode(ctrl, frame, "uncommon trap returned which should never happen" PRODUCT_ONLY(COMMA /*reachable*/false));
640 register_control(halt, _ltree_root, ctrl);
641 _igvn.add_input_to(C->root(), halt);
642
643 _igvn.replace_input_of(inner_head, LoopNode::EntryControl, if_true);
644 set_idom(inner_head, if_true, dom_depth(inner_head));
645 }
646 }
647
648 // Find a safepoint node that dominates the back edge. We need a
649 // SafePointNode so we can use its jvm state to create empty
650 // predicates.
651 static bool no_side_effect_since_safepoint(Compile* C, Node* x, Node* mem, MergeMemNode* mm, PhaseIdealLoop* phase) {
652 SafePointNode* safepoint = nullptr;
653 for (DUIterator_Fast imax, i = x->fast_outs(imax); i < imax; i++) {
654 Node* u = x->fast_out(i);
655 if (u->is_memory_phi()) {
656 Node* m = u->in(LoopNode::LoopBackControl);
657 if (u->adr_type() == TypePtr::BOTTOM) {
658 if (m->is_MergeMem() && mem->is_MergeMem()) {
659 if (m != mem DEBUG_ONLY(|| true)) {
660 // MergeMemStream can modify m, for example to adjust the length to mem.
661 // This is unfortunate, and probably unnecessary. But as it is, we need
662 // to add m to the igvn worklist, else we may have a modified node that
663 // is not on the igvn worklist.
664 phase->igvn()._worklist.push(m);
665 for (MergeMemStream mms(m->as_MergeMem(), mem->as_MergeMem()); mms.next_non_empty2(); ) {
666 if (!mms.is_empty()) {
667 if (mms.memory() != mms.memory2()) {
668 return false;
669 }
670 #ifdef ASSERT
671 if (mms.alias_idx() != Compile::AliasIdxBot) {
672 mm->set_memory_at(mms.alias_idx(), mem->as_MergeMem()->base_memory());
673 }
674 #endif
675 }
676 }
677 }
678 } else if (mem->is_MergeMem()) {
679 if (m != mem->as_MergeMem()->base_memory()) {
680 return false;
681 }
682 } else {
683 return false;
684 }
685 } else {
686 if (mem->is_MergeMem()) {
687 if (m != mem->as_MergeMem()->memory_at(C->get_alias_index(u->adr_type()))) {
688 return false;
689 }
690 #ifdef ASSERT
691 mm->set_memory_at(C->get_alias_index(u->adr_type()), mem->as_MergeMem()->base_memory());
692 #endif
693 } else {
694 if (m != mem) {
695 return false;
696 }
697 }
698 }
699 }
700 }
701 return true;
702 }
703
704 SafePointNode* PhaseIdealLoop::find_safepoint(Node* back_control, Node* x, IdealLoopTree* loop) {
705 IfNode* exit_test = back_control->in(0)->as_If();
706 SafePointNode* safepoint = nullptr;
707 if (exit_test->in(0)->is_SafePoint() && exit_test->in(0)->outcnt() == 1) {
708 safepoint = exit_test->in(0)->as_SafePoint();
709 } else {
710 Node* c = back_control;
711 while (c != x && c->Opcode() != Op_SafePoint) {
712 c = idom(c);
713 }
714
715 if (c->Opcode() == Op_SafePoint) {
716 safepoint = c->as_SafePoint();
717 }
718
719 if (safepoint == nullptr) {
720 return nullptr;
721 }
722
723 Node* mem = safepoint->in(TypeFunc::Memory);
724
725 // We can only use that safepoint if there's no side effect between the backedge and the safepoint.
726
727 // mm is the memory state at the safepoint (when it's a MergeMem)
728 // no_side_effect_since_safepoint() goes over the memory state at the backedge. It resets the mm input for each
729 // component of the memory state it encounters so it points to the base memory. Once no_side_effect_since_safepoint()
730 // is done, if no side effect after the safepoint was found, mm should transform to the base memory: the states at
731 // the backedge and safepoint are the same so all components of the memory state at the safepoint should have been
732 // reset.
733 MergeMemNode* mm = nullptr;
734 #ifdef ASSERT
735 if (mem->is_MergeMem()) {
736 mm = mem->clone()->as_MergeMem();
737 _igvn._worklist.push(mm);
738 for (MergeMemStream mms(mem->as_MergeMem()); mms.next_non_empty(); ) {
739 // Loop invariant memory state won't be reset by no_side_effect_since_safepoint(). Do it here.
740 // Escape Analysis can add state to mm that it doesn't add to the backedge memory Phis, breaking verification
741 // code that relies on mm. Clear that extra state here.
742 if (mms.alias_idx() != Compile::AliasIdxBot &&
743 (loop != get_loop(ctrl_or_self(mms.memory())) ||
744 (mms.adr_type()->isa_oop_ptr() && mms.adr_type()->is_known_instance()))) {
745 mm->set_memory_at(mms.alias_idx(), mem->as_MergeMem()->base_memory());
746 }
747 }
748 }
749 #endif
750 if (!no_side_effect_since_safepoint(C, x, mem, mm, this)) {
751 safepoint = nullptr;
752 } else {
753 assert(mm == nullptr|| _igvn.transform(mm) == mem->as_MergeMem()->base_memory(), "all memory state should have been processed");
754 }
755 #ifdef ASSERT
756 if (mm != nullptr) {
757 _igvn.remove_dead_node(mm);
758 }
759 #endif
760 }
761 return safepoint;
762 }
763
764 // If the loop has the shape of a counted loop but with a long
765 // induction variable, transform the loop in a loop nest: an inner
766 // loop that iterates for at most max int iterations with an integer
767 // induction variable and an outer loop that iterates over the full
768 // range of long values from the initial loop in (at most) max int
769 // steps. That is:
770 //
771 // x: for (long phi = init; phi < limit; phi += stride) {
772 // // phi := Phi(L, init, incr)
773 // // incr := AddL(phi, longcon(stride))
774 // long incr = phi + stride;
775 // ... use phi and incr ...
776 // }
777 //
778 // OR:
779 //
780 // x: for (long phi = init; (phi += stride) < limit; ) {
781 // // phi := Phi(L, AddL(init, stride), incr)
782 // // incr := AddL(phi, longcon(stride))
783 // long incr = phi + stride;
784 // ... use phi and (phi + stride) ...
785 // }
786 //
787 // ==transform=>
788 //
789 // const ulong inner_iters_limit = INT_MAX - stride - 1; //near 0x7FFFFFF0
790 // assert(stride <= inner_iters_limit); // else abort transform
791 // assert((extralong)limit + stride <= LONG_MAX); // else deopt
792 // outer_head: for (long outer_phi = init;;) {
793 // // outer_phi := Phi(outer_head, init, AddL(outer_phi, I2L(inner_phi)))
794 // ulong inner_iters_max = (ulong) MAX(0, ((extralong)limit + stride - outer_phi));
795 // long inner_iters_actual = MIN(inner_iters_limit, inner_iters_max);
796 // assert(inner_iters_actual == (int)inner_iters_actual);
797 // int inner_phi, inner_incr;
798 // x: for (inner_phi = 0;; inner_phi = inner_incr) {
799 // // inner_phi := Phi(x, intcon(0), inner_incr)
800 // // inner_incr := AddI(inner_phi, intcon(stride))
801 // inner_incr = inner_phi + stride;
802 // if (inner_incr < inner_iters_actual) {
803 // ... use phi=>(outer_phi+inner_phi) ...
804 // continue;
805 // }
806 // else break;
807 // }
808 // if ((outer_phi+inner_phi) < limit) //OR (outer_phi+inner_incr) < limit
809 // continue;
810 // else break;
811 // }
812 //
813 // The same logic is used to transform an int counted loop that contains long range checks into a loop nest of 2 int
814 // loops with long range checks transformed to int range checks in the inner loop.
815 bool PhaseIdealLoop::create_loop_nest(IdealLoopTree* loop, Node_List &old_new) {
816 Node* x = loop->_head;
817 // Only for inner loops
818 if (loop->_child != nullptr || !x->is_BaseCountedLoop() || x->as_Loop()->is_loop_nest_outer_loop()) {
819 return false;
820 }
821
822 if (x->is_CountedLoop() && !x->as_CountedLoop()->is_main_loop() && !x->as_CountedLoop()->is_normal_loop()) {
823 return false;
824 }
825
826 BaseCountedLoopNode* head = x->as_BaseCountedLoop();
827 BasicType bt = x->as_BaseCountedLoop()->bt();
828
829 check_counted_loop_shape(loop, x, bt);
830
831 #ifndef PRODUCT
832 if (bt == T_LONG) {
833 AtomicAccess::inc(&_long_loop_candidates);
834 }
835 #endif
836
837 jlong stride_con_long = head->stride_con();
838 assert(stride_con_long != 0, "missed some peephole opt");
839 // We can't iterate for more than max int at a time.
840 if (stride_con_long != (jint)stride_con_long || stride_con_long == min_jint) {
841 assert(bt == T_LONG, "only for long loops");
842 return false;
843 }
844 jint stride_con = checked_cast<jint>(stride_con_long);
845 // The number of iterations for the integer count loop: guarantee no
846 // overflow: max_jint - stride_con max. -1 so there's no need for a
847 // loop limit check if the exit test is <= or >=.
848 int iters_limit = max_jint - ABS(stride_con) - 1;
849 #ifdef ASSERT
850 if (bt == T_LONG && StressLongCountedLoop > 0) {
851 iters_limit = iters_limit / StressLongCountedLoop;
852 }
853 #endif
854 // At least 2 iterations so counted loop construction doesn't fail
855 if (iters_limit/ABS(stride_con) < 2) {
856 return false;
857 }
858
859 assert(iters_limit > 0, "can't be negative");
860
861 PhiNode* phi = head->phi()->as_Phi();
862
863 Node* back_control = head->in(LoopNode::LoopBackControl);
864
865 // data nodes on back branch not supported
866 if (back_control->outcnt() > 1) {
867 return false;
868 }
869
870 Node* limit = head->limit();
871 // We'll need to use the loop limit before the inner loop is entered
872 if (!is_dominator(get_ctrl(limit), x)) {
873 return false;
874 }
875
876 IfNode* exit_test = head->loopexit();
877
878 assert(back_control->Opcode() == Op_IfTrue, "wrong projection for back edge");
879
880 Node_List range_checks;
881 iters_limit = extract_long_range_checks(loop, stride_con, iters_limit, phi, range_checks);
882
883 if (bt == T_INT) {
884 // The only purpose of creating a loop nest is to handle long range checks. If there are none, do not proceed further.
885 if (range_checks.size() == 0) {
886 return false;
887 }
888 }
889
890 // Take what we know about the number of iterations of the long counted loop into account when computing the limit of
891 // the inner loop.
892 Node* init = head->init_trip();
893 const TypeInteger* lo = _igvn.type(init)->is_integer(bt);
894 const TypeInteger* hi = _igvn.type(limit)->is_integer(bt);
895 if (stride_con < 0) {
896 swap(lo, hi);
897 }
898 if (hi->hi_as_long() <= lo->lo_as_long()) {
899 // not a loop after all
900 return false;
901 }
902
903 if (range_checks.size() > 0) {
904 // This transformation requires peeling one iteration. Also, if it has range checks and they are eliminated by Loop
905 // Predication, then 2 Hoisted Check Predicates are added for one range check. Finally, transforming a long range
906 // check requires extra logic to be executed before the loop is entered and for the outer loop. As a result, the
907 // transformations can't pay off for a small number of iterations: roughly, if the loop runs for 3 iterations, it's
908 // going to execute as many range checks once transformed with range checks eliminated (1 peeled iteration with
909 // range checks + 2 predicates per range checks) as it would have not transformed. It also has to pay for the extra
910 // logic on loop entry and for the outer loop.
911 loop->compute_trip_count(this, bt);
912 if (head->is_CountedLoop() && head->as_CountedLoop()->has_exact_trip_count()) {
913 if (head->as_CountedLoop()->trip_count() <= 3) {
914 return false;
915 }
916 } else {
917 loop->compute_profile_trip_cnt(this);
918 if (!head->is_profile_trip_failed() && head->profile_trip_cnt() <= 3) {
919 return false;
920 }
921 }
922 }
923
924 if (try_make_short_running_loop(loop, stride_con, range_checks, iters_limit)) {
925 C->set_major_progress();
926 return true;
927 }
928
929 julong orig_iters = (julong)hi->hi_as_long() - lo->lo_as_long();
930 iters_limit = checked_cast<int>(MIN2((julong)iters_limit, orig_iters));
931
932 // We need a safepoint to insert Parse Predicates for the inner loop.
933 SafePointNode* safepoint;
934 if (bt == T_INT && head->as_CountedLoop()->is_strip_mined()) {
935 // Loop is strip mined: use the safepoint of the outer strip mined loop
936 OuterStripMinedLoopNode* outer_loop = head->as_CountedLoop()->outer_loop();
937 assert(outer_loop != nullptr, "no outer loop");
938 safepoint = outer_loop->outer_safepoint();
939 outer_loop->transform_to_counted_loop(&_igvn, this);
940 exit_test = head->loopexit();
941 } else {
942 safepoint = find_safepoint(back_control, x, loop);
943 }
944
945 Node* exit_branch = exit_test->proj_out(false);
946 Node* entry_control = head->in(LoopNode::EntryControl);
947
948 // Clone the control flow of the loop to build an outer loop
949 Node* outer_back_branch = back_control->clone();
950 Node* outer_exit_test = new IfNode(exit_test->in(0), exit_test->in(1), exit_test->_prob, exit_test->_fcnt);
951 Node* inner_exit_branch = exit_branch->clone();
952
953 LoopNode* outer_head = new LoopNode(entry_control, outer_back_branch);
954 IdealLoopTree* outer_ilt = insert_outer_loop(loop, outer_head, outer_back_branch);
955
956 const bool body_populated = true;
957 register_control(outer_head, outer_ilt, entry_control, body_populated);
958
959 _igvn.register_new_node_with_optimizer(inner_exit_branch);
960 set_loop(inner_exit_branch, outer_ilt);
961 set_idom(inner_exit_branch, exit_test, dom_depth(exit_branch));
962
963 outer_exit_test->set_req(0, inner_exit_branch);
964 register_control(outer_exit_test, outer_ilt, inner_exit_branch, body_populated);
965
966 _igvn.replace_input_of(exit_branch, 0, outer_exit_test);
967 set_idom(exit_branch, outer_exit_test, dom_depth(exit_branch));
968
969 outer_back_branch->set_req(0, outer_exit_test);
970 register_control(outer_back_branch, outer_ilt, outer_exit_test, body_populated);
971
972 _igvn.replace_input_of(x, LoopNode::EntryControl, outer_head);
973 set_idom(x, outer_head, dom_depth(x));
974
975 // add an iv phi to the outer loop and use it to compute the inner
976 // loop iteration limit
977 Node* outer_phi = phi->clone();
978 outer_phi->set_req(0, outer_head);
979 register_new_node(outer_phi, outer_head);
980
981 Node* inner_iters_max = nullptr;
982 if (stride_con > 0) {
983 inner_iters_max = MaxNode::max_diff_with_zero(limit, outer_phi, TypeInteger::bottom(bt), _igvn);
984 } else {
985 inner_iters_max = MaxNode::max_diff_with_zero(outer_phi, limit, TypeInteger::bottom(bt), _igvn);
986 }
987
988 Node* inner_iters_limit = _igvn.integercon(iters_limit, bt);
989 // inner_iters_max may not fit in a signed integer (iterating from
990 // Long.MIN_VALUE to Long.MAX_VALUE for instance). Use an unsigned
991 // min.
992 const TypeInteger* inner_iters_actual_range = TypeInteger::make(0, iters_limit, Type::WidenMin, bt);
993 Node* inner_iters_actual = MaxNode::unsigned_min(inner_iters_max, inner_iters_limit, inner_iters_actual_range, _igvn);
994
995 Node* inner_iters_actual_int;
996 if (bt == T_LONG) {
997 inner_iters_actual_int = new ConvL2INode(inner_iters_actual);
998 _igvn.register_new_node_with_optimizer(inner_iters_actual_int);
999 // When the inner loop is transformed to a counted loop, a loop limit check is not expected to be needed because
1000 // the loop limit is less or equal to max_jint - stride - 1 (if stride is positive but a similar argument exists for
1001 // a negative stride). We add a CastII here to guarantee that, when the counted loop is created in a subsequent loop
1002 // opts pass, an accurate range of values for the limits is found.
1003 const TypeInt* inner_iters_actual_int_range = TypeInt::make(0, iters_limit, Type::WidenMin);
1004 inner_iters_actual_int = new CastIINode(outer_head, inner_iters_actual_int, inner_iters_actual_int_range, ConstraintCastNode::DependencyType::NonFloatingNonNarrowing);
1005 _igvn.register_new_node_with_optimizer(inner_iters_actual_int);
1006 } else {
1007 inner_iters_actual_int = inner_iters_actual;
1008 }
1009
1010 Node* int_zero = intcon(0);
1011 if (stride_con < 0) {
1012 inner_iters_actual_int = new SubINode(int_zero, inner_iters_actual_int);
1013 _igvn.register_new_node_with_optimizer(inner_iters_actual_int);
1014 }
1015
1016 // Clone the iv data nodes as an integer iv
1017 Node* int_stride = intcon(stride_con);
1018 Node* inner_phi = new PhiNode(x->in(0), TypeInt::INT);
1019 Node* inner_incr = new AddINode(inner_phi, int_stride);
1020 Node* inner_cmp = nullptr;
1021 inner_cmp = new CmpINode(inner_incr, inner_iters_actual_int);
1022 Node* inner_bol = new BoolNode(inner_cmp, exit_test->in(1)->as_Bool()->_test._test);
1023 inner_phi->set_req(LoopNode::EntryControl, int_zero);
1024 inner_phi->set_req(LoopNode::LoopBackControl, inner_incr);
1025 register_new_node(inner_phi, x);
1026 register_new_node(inner_incr, x);
1027 register_new_node(inner_cmp, x);
1028 register_new_node(inner_bol, x);
1029
1030 _igvn.replace_input_of(exit_test, 1, inner_bol);
1031
1032 // Clone inner loop phis to outer loop
1033 for (uint i = 0; i < head->outcnt(); i++) {
1034 Node* u = head->raw_out(i);
1035 if (u->is_Phi() && u != inner_phi && u != phi) {
1036 assert(u->in(0) == head, "inconsistent");
1037 Node* clone = u->clone();
1038 clone->set_req(0, outer_head);
1039 register_new_node(clone, outer_head);
1040 _igvn.replace_input_of(u, LoopNode::EntryControl, clone);
1041 }
1042 }
1043
1044 // Replace inner loop long iv phi as inner loop int iv phi + outer
1045 // loop iv phi
1046 Node* iv_add = loop_nest_replace_iv(phi, inner_phi, outer_phi, head, bt);
1047
1048 set_subtree_ctrl(inner_iters_actual_int, body_populated);
1049
1050 LoopNode* inner_head = create_inner_head(loop, head, exit_test);
1051
1052 // Summary of steps from initial loop to loop nest:
1053 //
1054 // == old IR nodes =>
1055 //
1056 // entry_control: {...}
1057 // x:
1058 // for (long phi = init;;) {
1059 // // phi := Phi(x, init, incr)
1060 // // incr := AddL(phi, longcon(stride))
1061 // exit_test:
1062 // if (phi < limit)
1063 // back_control: fallthrough;
1064 // else
1065 // exit_branch: break;
1066 // long incr = phi + stride;
1067 // ... use phi and incr ...
1068 // phi = incr;
1069 // }
1070 //
1071 // == new IR nodes (just before final peel) =>
1072 //
1073 // entry_control: {...}
1074 // long adjusted_limit = limit + stride; //because phi_incr != nullptr
1075 // assert(!limit_check_required || (extralong)limit + stride == adjusted_limit); // else deopt
1076 // ulong inner_iters_limit = max_jint - ABS(stride) - 1; //near 0x7FFFFFF0
1077 // outer_head:
1078 // for (long outer_phi = init;;) {
1079 // // outer_phi := phi->clone(), in(0):=outer_head, => Phi(outer_head, init, incr)
1080 // // REPLACE phi => AddL(outer_phi, I2L(inner_phi))
1081 // // REPLACE incr => AddL(outer_phi, I2L(inner_incr))
1082 // // SO THAT outer_phi := Phi(outer_head, init, AddL(outer_phi, I2L(inner_incr)))
1083 // ulong inner_iters_max = (ulong) MAX(0, ((extralong)adjusted_limit - outer_phi) * SGN(stride));
1084 // int inner_iters_actual_int = (int) MIN(inner_iters_limit, inner_iters_max) * SGN(stride);
1085 // inner_head: x: //in(1) := outer_head
1086 // int inner_phi;
1087 // for (inner_phi = 0;;) {
1088 // // inner_phi := Phi(x, intcon(0), inner_phi + stride)
1089 // int inner_incr = inner_phi + stride;
1090 // bool inner_bol = (inner_incr < inner_iters_actual_int);
1091 // exit_test: //exit_test->in(1) := inner_bol;
1092 // if (inner_bol) // WAS (phi < limit)
1093 // back_control: fallthrough;
1094 // else
1095 // inner_exit_branch: break; //exit_branch->clone()
1096 // ... use phi=>(outer_phi+inner_phi) ...
1097 // inner_phi = inner_phi + stride; // inner_incr
1098 // }
1099 // outer_exit_test: //exit_test->clone(), in(0):=inner_exit_branch
1100 // if ((outer_phi+inner_phi) < limit) // WAS (phi < limit)
1101 // outer_back_branch: fallthrough; //back_control->clone(), in(0):=outer_exit_test
1102 // else
1103 // exit_branch: break; //in(0) := outer_exit_test
1104 // }
1105
1106 if (bt == T_INT) {
1107 outer_phi = new ConvI2LNode(outer_phi);
1108 register_new_node(outer_phi, outer_head);
1109 }
1110
1111 transform_long_range_checks(stride_con, range_checks, outer_phi, inner_iters_actual_int,
1112 inner_phi, iv_add, inner_head);
1113 // Peel one iteration of the loop and use the safepoint at the end
1114 // of the peeled iteration to insert Parse Predicates. If no well
1115 // positioned safepoint peel to guarantee a safepoint in the outer
1116 // loop.
1117 if (safepoint != nullptr || !loop->_has_call) {
1118 old_new.clear();
1119 do_peeling(loop, old_new);
1120 } else {
1121 C->set_major_progress();
1122 }
1123
1124 if (safepoint != nullptr) {
1125 SafePointNode* cloned_sfpt = old_new[safepoint->_idx]->as_SafePoint();
1126
1127 if (ShortRunningLongLoop) {
1128 add_parse_predicate(Deoptimization::Reason_short_running_long_loop, inner_head, outer_ilt, cloned_sfpt);
1129 }
1130 if (UseLoopPredicate) {
1131 add_parse_predicate(Deoptimization::Reason_predicate, inner_head, outer_ilt, cloned_sfpt);
1132 if (UseProfiledLoopPredicate) {
1133 add_parse_predicate(Deoptimization::Reason_profile_predicate, inner_head, outer_ilt, cloned_sfpt);
1134 }
1135 }
1136
1137 if (UseAutoVectorizationPredicate) {
1138 // We only want to use the auto-vectorization check as a trap once per bci. And
1139 // PhaseIdealLoop::add_parse_predicate only checks trap limits per method, so
1140 // we do a custom check here.
1141 if (!C->too_many_traps(cloned_sfpt->jvms()->method(), cloned_sfpt->jvms()->bci(), Deoptimization::Reason_auto_vectorization_check)) {
1142 add_parse_predicate(Deoptimization::Reason_auto_vectorization_check, inner_head, outer_ilt, cloned_sfpt);
1143 }
1144 }
1145
1146 add_parse_predicate(Deoptimization::Reason_loop_limit_check, inner_head, outer_ilt, cloned_sfpt);
1147 }
1148
1149 #ifndef PRODUCT
1150 if (bt == T_LONG) {
1151 AtomicAccess::inc(&_long_loop_nests);
1152 }
1153 #endif
1154
1155 inner_head->mark_loop_nest_inner_loop();
1156 outer_head->mark_loop_nest_outer_loop();
1157
1158 return true;
1159 }
1160
1161 // Make a copy of Parse/Template Assertion predicates below existing predicates at the loop passed as argument
1162 class CloneShortLoopPredicateVisitor : public PredicateVisitor {
1163 ClonePredicateToTargetLoop _clone_predicate_to_loop;
1164 PhaseIdealLoop* const _phase;
1165 Node* const _new_init;
1166
1167 public:
1168 CloneShortLoopPredicateVisitor(LoopNode* target_loop_head,
1169 Node* new_init,
1170 const NodeInSingleLoopBody &node_in_loop_body,
1171 PhaseIdealLoop* phase)
1172 : _clone_predicate_to_loop(target_loop_head, node_in_loop_body, phase),
1173 _phase(phase),
1174 _new_init(new_init) {
1175 }
1176 NONCOPYABLE(CloneShortLoopPredicateVisitor);
1177
1178 using PredicateVisitor::visit;
1179
1180 void visit(const ParsePredicate& parse_predicate) override {
1181 _clone_predicate_to_loop.clone_parse_predicate(parse_predicate, true);
1182 parse_predicate.kill(_phase->igvn());
1183 }
1184
1185 void visit(const TemplateAssertionPredicate& template_assertion_predicate) override {
1186 _clone_predicate_to_loop.clone_template_assertion_predicate_and_replace_init(template_assertion_predicate, _new_init);
1187 template_assertion_predicate.kill(_phase->igvn());
1188 }
1189 };
1190
1191 // For an int counted loop, try_make_short_running_loop() transforms the loop from:
1192 // for (int = start; i < stop; i+= stride) { ... }
1193 // to
1194 // for (int = 0; i < stop - start; i+= stride) { ... }
1195 // Template Assertion Predicates added so far were with an init value of start. They need to be updated with the new
1196 // init value of 0 (otherwise when a template assertion predicate is turned into an initialized assertion predicate, it
1197 // performs an incorrect check):
1198 // zero
1199 // init |
1200 // | ===> OpaqueLoopInit init
1201 // OpaqueLoopInit \ /
1202 // AddI
1203 //
1204 Node* PhaseIdealLoop::new_assertion_predicate_opaque_init(Node* entry_control, Node* init, Node* int_zero) {
1205 OpaqueLoopInitNode* new_opaque_init = new OpaqueLoopInitNode(C, int_zero);
1206 register_new_node(new_opaque_init, entry_control);
1207 Node* new_init = new AddINode(new_opaque_init, init);
1208 register_new_node(new_init, entry_control);
1209 return new_init;
1210 }
1211
1212 // If the loop is either statically known to run for a small enough number of iterations or if profile data indicates
1213 // that, we don't want an outer loop because the overhead of having an outer loop whose backedge is never taken, has a
1214 // measurable cost. Furthermore, creating the loop nest usually causes one iteration of the loop to be peeled so
1215 // predicates can be set up. If the loop is short running, then it's an extra iteration that's run with range checks
1216 // (compared to an int counted loop with int range checks).
1217 //
1218 // In the short running case, turn the loop into a regular loop again and transform the long range checks:
1219 // - LongCountedLoop: Create LoopNode but keep the loop limit type with a CastLL node to avoid that we later try to
1220 // create a Loop Limit Check when turning the LoopNode into a CountedLoopNode.
1221 // - CountedLoop: Can be reused.
1222 bool PhaseIdealLoop::try_make_short_running_loop(IdealLoopTree* loop, jint stride_con, const Node_List &range_checks,
1223 const uint iters_limit) {
1224 if (!ShortRunningLongLoop) {
1225 return false;
1226 }
1227 BaseCountedLoopNode* head = loop->_head->as_BaseCountedLoop();
1228 BasicType bt = head->bt();
1229 Node* entry_control = head->skip_strip_mined()->in(LoopNode::EntryControl);
1230
1231 loop->compute_trip_count(this, bt);
1232 // Loop must run for no more than iter_limits as it guarantees no overflow of scale * iv in long range checks (see
1233 // comment above PhaseIdealLoop::transform_long_range_checks()).
1234 // iters_limit / ABS(stride_con) is the largest trip count for which we know it's correct to not create a loop nest:
1235 // it's always beneficial to have a single loop rather than a loop nest, so we try to apply this transformation as
1236 // often as possible.
1237 bool known_short_running_loop = head->trip_count() <= iters_limit / ABS(stride_con);
1238 bool profile_short_running_loop = false;
1239 if (!known_short_running_loop) {
1240 loop->compute_profile_trip_cnt(this);
1241 if (StressShortRunningLongLoop) {
1242 profile_short_running_loop = true;
1243 } else {
1244 profile_short_running_loop = !head->is_profile_trip_failed() && head->profile_trip_cnt() <= iters_limit / ABS(stride_con);
1245 }
1246 }
1247
1248 if (!known_short_running_loop && !profile_short_running_loop) {
1249 return false;
1250 }
1251
1252 Node* limit = head->limit();
1253 Node* init = head->init_trip();
1254
1255 Node* new_limit;
1256 if (stride_con > 0) {
1257 new_limit = SubNode::make(limit, init, bt);
1258 } else {
1259 new_limit = SubNode::make(init, limit, bt);
1260 }
1261 register_new_node(new_limit, entry_control);
1262
1263 Node* int_zero = intcon(0);
1264 PhiNode* phi = head->phi()->as_Phi();
1265 if (profile_short_running_loop) {
1266 // Add a Short Running Long Loop Predicate. It's the first predicate in the predicate chain before entering a loop
1267 // because a cast that's control dependent on the Short Running Long Loop Predicate is added to narrow the limit and
1268 // future predicates may be dependent on the new limit (so have to be between the loop and Short Running Long Loop
1269 // Predicate). The current limit could, itself, be dependent on an existing predicate. Clone parse and template
1270 // assertion predicates below existing predicates to get proper ordering of predicates when walking from the loop
1271 // up: future predicates, Short Running Long Loop Predicate, existing predicates.
1272 //
1273 // Existing Hoisted
1274 // Check Predicates
1275 // |
1276 // New Short Running Long
1277 // Loop Predicate
1278 // |
1279 // Cloned Parse Predicates and
1280 // Template Assertion Predicates
1281 // (future predicates added here)
1282 // |
1283 // Loop
1284 const Predicates predicates_before_cloning(entry_control);
1285 const PredicateBlock* short_running_long_loop_predicate_block = predicates_before_cloning.short_running_long_loop_predicate_block();
1286 if (!short_running_long_loop_predicate_block->has_parse_predicate()) { // already trapped
1287 return false;
1288 }
1289 Node* new_init = new_assertion_predicate_opaque_init(entry_control, init, int_zero);
1290
1291 PredicateIterator predicate_iterator(entry_control);
1292 NodeInSingleLoopBody node_in_short_loop_body(this, loop);
1293 CloneShortLoopPredicateVisitor clone_short_loop_predicates_visitor(head, new_init, node_in_short_loop_body, this);
1294 predicate_iterator.for_each(clone_short_loop_predicates_visitor);
1295
1296 entry_control = head->skip_strip_mined()->in(LoopNode::EntryControl);
1297
1298 const Predicates predicates_after_cloning(entry_control);
1299
1300 ParsePredicateSuccessProj* short_running_loop_predicate_proj = predicates_after_cloning.
1301 short_running_long_loop_predicate_block()->
1302 parse_predicate_success_proj();
1303 assert(short_running_loop_predicate_proj->in(0)->is_ParsePredicate(), "must be parse predicate");
1304
1305 const jlong iters_limit_long = iters_limit;
1306 Node* cmp_limit = CmpNode::make(new_limit, _igvn.integercon(iters_limit_long, bt), bt);
1307 Node* bol = new BoolNode(cmp_limit, BoolTest::le);
1308 Node* new_predicate_proj = create_new_if_for_predicate(short_running_loop_predicate_proj,
1309 nullptr,
1310 Deoptimization::Reason_short_running_long_loop,
1311 Op_If);
1312 Node* iff = new_predicate_proj->in(0);
1313 _igvn.replace_input_of(iff, 1, bol);
1314 register_new_node(cmp_limit, iff->in(0));
1315 register_new_node(bol, iff->in(0));
1316 new_limit = ConstraintCastNode::make_cast_for_basic_type(new_predicate_proj, new_limit,
1317 TypeInteger::make(1, iters_limit_long, Type::WidenMin, bt),
1318 ConstraintCastNode::DependencyType::NonFloatingNonNarrowing, bt);
1319 register_new_node(new_limit, new_predicate_proj);
1320
1321 #ifndef PRODUCT
1322 if (TraceLoopLimitCheck) {
1323 tty->print_cr("Short Long Loop Check Predicate generated:");
1324 DEBUG_ONLY(bol->dump(2);)
1325 }
1326 #endif
1327 entry_control = head->skip_strip_mined()->in(LoopNode::EntryControl);
1328 } else if (bt == T_LONG) {
1329 // We're turning a long counted loop into a regular loop that will be converted into an int counted loop. That loop
1330 // won't need loop limit check predicates (iters_limit guarantees that). Add a cast to make sure that, whatever
1331 // transformation happens by the time the counted loop is created (in a subsequent pass of loop opts), C2 knows
1332 // enough about the loop's limit that it doesn't try to add loop limit check predicates.
1333 const Predicates predicates(entry_control);
1334 const TypeLong* new_limit_t = new_limit->Value(&_igvn)->is_long();
1335 new_limit = ConstraintCastNode::make_cast_for_basic_type(predicates.entry(), new_limit,
1336 TypeLong::make(0, new_limit_t->_hi, new_limit_t->_widen),
1337 ConstraintCastNode::DependencyType::NonFloatingNonNarrowing, bt);
1338 register_new_node(new_limit, predicates.entry());
1339 } else {
1340 assert(bt == T_INT && known_short_running_loop, "only CountedLoop statically known to be short running");
1341 PredicateIterator predicate_iterator(entry_control);
1342 Node* new_init = new_assertion_predicate_opaque_init(entry_control, init, int_zero);
1343 UpdateInitForTemplateAssertionPredicates update_init_for_template_assertion_predicates(new_init, this);
1344 predicate_iterator.for_each(update_init_for_template_assertion_predicates);
1345 }
1346 IfNode* exit_test = head->loopexit();
1347
1348 if (bt == T_LONG) {
1349 // The loop is short running so new_limit fits into an int: either we determined that statically or added a guard
1350 new_limit = new ConvL2INode(new_limit);
1351 register_new_node(new_limit, entry_control);
1352 }
1353
1354 if (stride_con < 0) {
1355 new_limit = new SubINode(int_zero, new_limit);
1356 register_new_node(new_limit, entry_control);
1357 }
1358
1359 // Clone the iv data nodes as an integer iv
1360 Node* int_stride = intcon(stride_con);
1361 Node* inner_phi = new PhiNode(head, TypeInt::INT);
1362 Node* inner_incr = new AddINode(inner_phi, int_stride);
1363 Node* inner_cmp = new CmpINode(inner_incr, new_limit);
1364 Node* inner_bol = new BoolNode(inner_cmp, exit_test->in(1)->as_Bool()->_test._test);
1365 inner_phi->set_req(LoopNode::EntryControl, int_zero);
1366 inner_phi->set_req(LoopNode::LoopBackControl, inner_incr);
1367 register_new_node(inner_phi, head);
1368 register_new_node(inner_incr, head);
1369 register_new_node(inner_cmp, head);
1370 register_new_node(inner_bol, head);
1371
1372 _igvn.replace_input_of(exit_test, 1, inner_bol);
1373
1374 // Replace inner loop long iv phi as inner loop int iv phi + outer
1375 // loop iv phi
1376 Node* iv_add = loop_nest_replace_iv(phi, inner_phi, init, head, bt);
1377
1378 LoopNode* inner_head = head;
1379 if (bt == T_LONG) {
1380 // Turn the loop back to a counted loop
1381 inner_head = create_inner_head(loop, head, exit_test);
1382 } else {
1383 // Use existing counted loop
1384 revert_to_normal_loop(head);
1385 }
1386
1387 if (bt == T_INT) {
1388 init = new ConvI2LNode(init);
1389 register_new_node(init, entry_control);
1390 }
1391
1392 transform_long_range_checks(stride_con, range_checks, init, new_limit,
1393 inner_phi, iv_add, inner_head);
1394
1395 inner_head->mark_loop_nest_inner_loop();
1396
1397 return true;
1398 }
1399
1400 int PhaseIdealLoop::extract_long_range_checks(const IdealLoopTree* loop, jint stride_con, int iters_limit, PhiNode* phi,
1401 Node_List& range_checks) {
1402 const jlong min_iters = 2;
1403 jlong reduced_iters_limit = iters_limit;
1404 jlong original_iters_limit = iters_limit;
1405 for (uint i = 0; i < loop->_body.size(); i++) {
1406 Node* c = loop->_body.at(i);
1407 if (c->is_IfProj() && c->in(0)->is_RangeCheck()) {
1408 IfProjNode* if_proj = c->as_IfProj();
1409 CallStaticJavaNode* call = if_proj->is_uncommon_trap_if_pattern();
1410 if (call != nullptr) {
1411 Node* range = nullptr;
1412 Node* offset = nullptr;
1413 jlong scale = 0;
1414 if (loop->is_range_check_if(if_proj, this, T_LONG, phi, range, offset, scale) &&
1415 loop->is_invariant(range) && loop->is_invariant(offset) &&
1416 scale != min_jlong &&
1417 original_iters_limit / ABS(scale) >= min_iters * ABS(stride_con)) {
1418 assert(scale == (jint)scale, "scale should be an int");
1419 reduced_iters_limit = MIN2(reduced_iters_limit, original_iters_limit/ABS(scale));
1420 range_checks.push(c);
1421 }
1422 }
1423 }
1424 }
1425
1426 return checked_cast<int>(reduced_iters_limit);
1427 }
1428
1429 // One execution of the inner loop covers a sub-range of the entire iteration range of the loop: [A,Z), aka [A=init,
1430 // Z=limit). If the loop has at least one trip (which is the case here), the iteration variable i always takes A as its
1431 // first value, followed by A+S (S is the stride), next A+2S, etc. The limit is exclusive, so that the final value B of
1432 // i is never Z. It will be B=Z-1 if S=1, or B=Z+1 if S=-1.
1433
1434 // If |S|>1 the formula for the last value B would require a floor operation, specifically B=floor((Z-sgn(S)-A)/S)*S+A,
1435 // which is B=Z-sgn(S)U for some U in [1,|S|]. So when S>0, i ranges as i:[A,Z) or i:[A,B=Z-U], or else (in reverse)
1436 // as i:(Z,A] or i:[B=Z+U,A]. It will become important to reason about this inclusive range [A,B] or [B,A].
1437
1438 // Within the loop there may be many range checks. Each such range check (R.C.) is of the form 0 <= i*K+L < R, where K
1439 // is a scale factor applied to the loop iteration variable i, and L is some offset; K, L, and R are loop-invariant.
1440 // Because R is never negative (see below), this check can always be simplified to an unsigned check i*K+L <u R.
1441
1442 // When a long loop over a 64-bit variable i (outer_iv) is decomposed into a series of shorter sub-loops over a 32-bit
1443 // variable j (inner_iv), j ranges over a shorter interval j:[0,B_2] or [0,Z_2) (assuming S > 0), where the limit is
1444 // chosen to prevent various cases of 32-bit overflow (including multiplications j*K below). In the sub-loop the
1445 // logical value i is offset from j by a 64-bit constant C, so i ranges in i:C+[0,Z_2).
1446
1447 // For S<0, j ranges (in reverse!) through j:[-|B_2|,0] or (-|Z_2|,0]. For either sign of S, we can say i=j+C and j
1448 // ranges through 32-bit ranges [A_2,B_2] or [B_2,A_2] (A_2=0 of course).
1449
1450 // The disjoint union of all the C+[A_2,B_2] ranges from the sub-loops must be identical to the whole range [A,B].
1451 // Assuming S>0, the first C must be A itself, and the next C value is the previous C+B_2, plus S. If |S|=1, the next
1452 // C value is also the previous C+Z_2. In each sub-loop, j counts from j=A_2=0 and i counts from C+0 and exits at
1453 // j=B_2 (i=C+B_2), just before it gets to i=C+Z_2. Both i and j count up (from C and 0) if S>0; otherwise they count
1454 // down (from C and 0 again).
1455
1456 // Returning to range checks, we see that each i*K+L <u R expands to (C+j)*K+L <u R, or j*K+Q <u R, where Q=(C*K+L).
1457 // (Recall that K and L and R are loop-invariant scale, offset and range values for a particular R.C.) This is still a
1458 // 64-bit comparison, so the range check elimination logic will not apply to it. (The R.C.E. transforms operate only on
1459 // 32-bit indexes and comparisons, because they use 64-bit temporary values to avoid overflow; see
1460 // PhaseIdealLoop::add_constraint.)
1461
1462 // We must transform this comparison so that it gets the same answer, but by means of a 32-bit R.C. (using j not i) of
1463 // the form j*K+L_2 <u32 R_2. Note that L_2 and R_2 must be loop-invariant, but only with respect to the sub-loop. Thus, the
1464 // problem reduces to computing values for L_2 and R_2 (for each R.C. in the loop) in the loop header for the sub-loop.
1465 // Then the standard R.C.E. transforms can take those as inputs and further compute the necessary minimum and maximum
1466 // values for the 32-bit counter j within which the range checks can be eliminated.
1467
1468 // So, given j*K+Q <u R, we need to find some j*K+L_2 <u32 R_2, where L_2 and R_2 fit in 32 bits, and the 32-bit operations do
1469 // not overflow. We also need to cover the cases where i*K+L (= j*K+Q) overflows to a 64-bit negative, since that is
1470 // allowed as an input to the R.C., as long as the R.C. as a whole fails.
1471
1472 // If 32-bit multiplication j*K might overflow, we adjust the sub-loop limit Z_2 closer to zero to reduce j's range.
1473
1474 // For each R.C. j*K+Q <u32 R, the range of mathematical values of j*K+Q in the sub-loop is [Q_min, Q_max], where
1475 // Q_min=Q and Q_max=B_2*K+Q (if S>0 and K>0), Q_min=A_2*K+Q and Q_max=Q (if S<0 and K>0),
1476 // Q_min=B_2*K+Q and Q_max=Q if (S>0 and K<0), Q_min=Q and Q_max=A_2*K+Q (if S<0 and K<0)
1477
1478 // Note that the first R.C. value is always Q=(S*K>0 ? Q_min : Q_max). Also Q_{min,max} = Q + {min,max}(A_2*K,B_2*K).
1479 // If S*K>0 then, as the loop iterations progress, each R.C. value i*K+L = j*K+Q goes up from Q=Q_min towards Q_max.
1480 // If S*K<0 then j*K+Q starts at Q=Q_max and goes down towards Q_min.
1481
1482 // Case A: Some Negatives (but no overflow).
1483 // Number line:
1484 // |s64_min . . . 0 . . . s64_max|
1485 // | . Q_min..Q_max . 0 . . . . | s64 negative
1486 // | . . . . R=0 R< R< R< R< | (against R values)
1487 // | . . . Q_min..0..Q_max . . . | small mixed
1488 // | . . . . R R R< R< R< | (against R values)
1489 //
1490 // R values which are out of range (>Q_max+1) are reduced to max(0,Q_max+1). They are marked on the number line as R<.
1491 //
1492 // So, if Q_min <s64 0, then use this test:
1493 // j*K + s32_trunc(Q_min) <u32 clamp(R, 0, Q_max+1) if S*K>0 (R.C.E. steps upward)
1494 // j*K + s32_trunc(Q_max) <u32 clamp(R, 0, Q_max+1) if S*K<0 (R.C.E. steps downward)
1495 // Both formulas reduce to adding j*K to the 32-bit truncated value of the first R.C. expression value, Q:
1496 // j*K + s32_trunc(Q) <u32 clamp(R, 0, Q_max+1) for all S,K
1497
1498 // If the 32-bit truncation loses information, no harm is done, since certainly the clamp also will return R_2=zero.
1499
1500 // Case B: No Negatives.
1501 // Number line:
1502 // |s64_min . . . 0 . . . s64_max|
1503 // | . . . . 0 Q_min..Q_max . . | small positive
1504 // | . . . . R> R R R< R< | (against R values)
1505 // | . . . . 0 . Q_min..Q_max . | s64 positive
1506 // | . . . . R> R> R R R< | (against R values)
1507 //
1508 // R values which are out of range (<Q_min or >Q_max+1) are reduced as marked: R> up to Q_min, R< down to Q_max+1.
1509 // Then the whole comparison is shifted left by Q_min, so it can take place at zero, which is a nice 32-bit value.
1510 //
1511 // So, if both Q_min, Q_max+1 >=s64 0, then use this test:
1512 // j*K + 0 <u32 clamp(R, Q_min, Q_max+1) - Q_min if S*K>0
1513 // More generally:
1514 // j*K + Q - Q_min <u32 clamp(R, Q_min, Q_max+1) - Q_min for all S,K
1515
1516 // Case C: Overflow in the 64-bit domain
1517 // Number line:
1518 // |..Q_max-2^64 . . 0 . . . Q_min..| s64 overflow
1519 // | . . . . R> R> R> R> R | (against R values)
1520 //
1521 // In this case, Q_min >s64 Q_max+1, even though the mathematical values of Q_min and Q_max+1 are correctly ordered.
1522 // The formulas from the previous case can be used, except that the bad upper bound Q_max is replaced by max_jlong.
1523 // (In fact, we could use any replacement bound from R to max_jlong inclusive, as the input to the clamp function.)
1524 //
1525 // So if Q_min >=s64 0 but Q_max+1 <s64 0, use this test:
1526 // j*K + 0 <u32 clamp(R, Q_min, max_jlong) - Q_min if S*K>0
1527 // More generally:
1528 // j*K + Q - Q_min <u32 clamp(R, Q_min, max_jlong) - Q_min for all S,K
1529 //
1530 // Dropping the bad bound means only Q_min is used to reduce the range of R:
1531 // j*K + Q - Q_min <u32 max(Q_min, R) - Q_min for all S,K
1532 //
1533 // Here the clamp function is a 64-bit min/max that reduces the dynamic range of its R operand to the required [L,H]:
1534 // clamp(X, L, H) := max(L, min(X, H))
1535 // When degenerately L > H, it returns L not H.
1536 //
1537 // All of the formulas above can be merged into a single one:
1538 // L_clamp = Q_min < 0 ? 0 : Q_min --whether and how far to left-shift
1539 // H_clamp = Q_max+1 < Q_min ? max_jlong : Q_max+1
1540 // = Q_max+1 < 0 && Q_min >= 0 ? max_jlong : Q_max+1
1541 // Q_first = Q = (S*K>0 ? Q_min : Q_max) = (C*K+L)
1542 // R_clamp = clamp(R, L_clamp, H_clamp) --reduced dynamic range
1543 // replacement R.C.:
1544 // j*K + Q_first - L_clamp <u32 R_clamp - L_clamp
1545 // or equivalently:
1546 // j*K + L_2 <u32 R_2
1547 // where
1548 // L_2 = Q_first - L_clamp
1549 // R_2 = R_clamp - L_clamp
1550 //
1551 // Note on why R is never negative:
1552 //
1553 // Various details of this transformation would break badly if R could be negative, so this transformation only
1554 // operates after obtaining hard evidence that R<0 is impossible. For example, if R comes from a LoadRange node, we
1555 // know R cannot be negative. For explicit checks (of both int and long) a proof is constructed in
1556 // inline_preconditions_checkIndex, which triggers an uncommon trap if R<0, then wraps R in a ConstraintCastNode with a
1557 // non-negative type. Later on, when IdealLoopTree::is_range_check_if looks for an optimizable R.C., it checks that
1558 // the type of that R node is non-negative. Any "wild" R node that could be negative is not treated as an optimizable
1559 // R.C., but R values from a.length and inside checkIndex are good to go.
1560 //
1561 void PhaseIdealLoop::transform_long_range_checks(int stride_con, const Node_List &range_checks, Node* outer_phi,
1562 Node* inner_iters_actual_int, Node* inner_phi,
1563 Node* iv_add, LoopNode* inner_head) {
1564 Node* long_zero = longcon(0);
1565 Node* int_zero = intcon(0);
1566 Node* long_one = longcon(1);
1567 Node* int_stride = intcon(checked_cast<int>(stride_con));
1568
1569 for (uint i = 0; i < range_checks.size(); i++) {
1570 ProjNode* proj = range_checks.at(i)->as_Proj();
1571 RangeCheckNode* rc = proj->in(0)->as_RangeCheck();
1572 jlong scale = 0;
1573 Node* offset = nullptr;
1574 Node* rc_bol = rc->in(1);
1575 Node* rc_cmp = rc_bol->in(1);
1576 if (rc_cmp->Opcode() == Op_CmpU) {
1577 // could be shared and have already been taken care of
1578 continue;
1579 }
1580 bool short_scale = false;
1581 bool ok = is_scaled_iv_plus_offset(rc_cmp->in(1), iv_add, T_LONG, &scale, &offset, &short_scale);
1582 assert(ok, "inconsistent: was tested before");
1583 Node* range = rc_cmp->in(2);
1584 Node* c = rc->in(0);
1585 Node* entry_control = inner_head->in(LoopNode::EntryControl);
1586
1587 Node* R = range;
1588 Node* K = longcon(scale);
1589
1590 Node* L = offset;
1591
1592 if (short_scale) {
1593 // This converts:
1594 // (int)i*K + L <u64 R
1595 // with K an int into:
1596 // i*(long)K + L <u64 unsigned_min((long)max_jint + L + 1, R)
1597 // to protect against an overflow of (int)i*K
1598 //
1599 // Because if (int)i*K overflows, there are K,L where:
1600 // (int)i*K + L <u64 R is false because (int)i*K+L overflows to a negative which becomes a huge u64 value.
1601 // But if i*(long)K + L is >u64 (long)max_jint and still is <u64 R, then
1602 // i*(long)K + L <u64 R is true.
1603 //
1604 // As a consequence simply converting i*K + L <u64 R to i*(long)K + L <u64 R could cause incorrect execution.
1605 //
1606 // It's always true that:
1607 // (int)i*K <u64 (long)max_jint + 1
1608 // which implies (int)i*K + L <u64 (long)max_jint + 1 + L
1609 // As a consequence:
1610 // i*(long)K + L <u64 unsigned_min((long)max_jint + L + 1, R)
1611 // is always false in case of overflow of i*K
1612 //
1613 // Note, there are also K,L where i*K overflows and
1614 // i*K + L <u64 R is true, but
1615 // i*(long)K + L <u64 unsigned_min((long)max_jint + L + 1, R) is false
1616 // So this transformation could cause spurious deoptimizations and failed range check elimination
1617 // (but not incorrect execution) for unlikely corner cases with overflow.
1618 // If this causes problems in practice, we could maybe direct execution to a post-loop, instead of deoptimizing.
1619 Node* max_jint_plus_one_long = longcon((jlong)max_jint + 1);
1620 Node* max_range = new AddLNode(max_jint_plus_one_long, L);
1621 register_new_node(max_range, entry_control);
1622 R = MaxNode::unsigned_min(R, max_range, TypeLong::POS, _igvn);
1623 set_subtree_ctrl(R, true);
1624 }
1625
1626 Node* C = outer_phi;
1627
1628 // Start with 64-bit values:
1629 // i*K + L <u64 R
1630 // (C+j)*K + L <u64 R
1631 // j*K + Q <u64 R where Q = Q_first = C*K+L
1632 Node* Q_first = new MulLNode(C, K);
1633 register_new_node(Q_first, entry_control);
1634 Q_first = new AddLNode(Q_first, L);
1635 register_new_node(Q_first, entry_control);
1636
1637 // Compute endpoints of the range of values j*K + Q.
1638 // Q_min = (j=0)*K + Q; Q_max = (j=B_2)*K + Q
1639 Node* Q_min = Q_first;
1640
1641 // Compute the exact ending value B_2 (which is really A_2 if S < 0)
1642 Node* B_2 = new LoopLimitNode(this->C, int_zero, inner_iters_actual_int, int_stride);
1643 register_new_node(B_2, entry_control);
1644 B_2 = new SubINode(B_2, int_stride);
1645 register_new_node(B_2, entry_control);
1646 B_2 = new ConvI2LNode(B_2);
1647 register_new_node(B_2, entry_control);
1648
1649 Node* Q_max = new MulLNode(B_2, K);
1650 register_new_node(Q_max, entry_control);
1651 Q_max = new AddLNode(Q_max, Q_first);
1652 register_new_node(Q_max, entry_control);
1653
1654 if (scale * stride_con < 0) {
1655 swap(Q_min, Q_max);
1656 }
1657 // Now, mathematically, Q_max > Q_min, and they are close enough so that (Q_max-Q_min) fits in 32 bits.
1658
1659 // L_clamp = Q_min < 0 ? 0 : Q_min
1660 Node* Q_min_cmp = new CmpLNode(Q_min, long_zero);
1661 register_new_node(Q_min_cmp, entry_control);
1662 Node* Q_min_bool = new BoolNode(Q_min_cmp, BoolTest::lt);
1663 register_new_node(Q_min_bool, entry_control);
1664 Node* L_clamp = new CMoveLNode(Q_min_bool, Q_min, long_zero, TypeLong::LONG);
1665 register_new_node(L_clamp, entry_control);
1666 // (This could also be coded bitwise as L_clamp = Q_min & ~(Q_min>>63).)
1667
1668 Node* Q_max_plus_one = new AddLNode(Q_max, long_one);
1669 register_new_node(Q_max_plus_one, entry_control);
1670
1671 // H_clamp = Q_max+1 < Q_min ? max_jlong : Q_max+1
1672 // (Because Q_min and Q_max are close, the overflow check could also be encoded as Q_max+1 < 0 & Q_min >= 0.)
1673 Node* max_jlong_long = longcon(max_jlong);
1674 Node* Q_max_cmp = new CmpLNode(Q_max_plus_one, Q_min);
1675 register_new_node(Q_max_cmp, entry_control);
1676 Node* Q_max_bool = new BoolNode(Q_max_cmp, BoolTest::lt);
1677 register_new_node(Q_max_bool, entry_control);
1678 Node* H_clamp = new CMoveLNode(Q_max_bool, Q_max_plus_one, max_jlong_long, TypeLong::LONG);
1679 register_new_node(H_clamp, entry_control);
1680 // (This could also be coded bitwise as H_clamp = ((Q_max+1)<<1 | M)>>>1 where M = (Q_max+1)>>63 & ~Q_min>>63.)
1681
1682 // R_2 = clamp(R, L_clamp, H_clamp) - L_clamp
1683 // that is: R_2 = clamp(R, L_clamp=0, H_clamp=Q_max) if Q_min < 0
1684 // or else: R_2 = clamp(R, L_clamp, H_clamp) - Q_min if Q_min >= 0
1685 // and also: R_2 = clamp(R, L_clamp, Q_max+1) - L_clamp if Q_min < Q_max+1 (no overflow)
1686 // or else: R_2 = clamp(R, L_clamp, *no limit*)- L_clamp if Q_max+1 < Q_min (overflow)
1687 Node* R_2 = clamp(R, L_clamp, H_clamp);
1688 R_2 = new SubLNode(R_2, L_clamp);
1689 register_new_node(R_2, entry_control);
1690 R_2 = new ConvL2INode(R_2, TypeInt::POS);
1691 register_new_node(R_2, entry_control);
1692
1693 // L_2 = Q_first - L_clamp
1694 // We are subtracting L_clamp from both sides of the <u32 comparison.
1695 // If S*K>0, then Q_first == 0 and the R.C. expression at -L_clamp and steps upward to Q_max-L_clamp.
1696 // If S*K<0, then Q_first != 0 and the R.C. expression starts high and steps downward to Q_min-L_clamp.
1697 Node* L_2 = new SubLNode(Q_first, L_clamp);
1698 register_new_node(L_2, entry_control);
1699 L_2 = new ConvL2INode(L_2, TypeInt::INT);
1700 register_new_node(L_2, entry_control);
1701
1702 // Transform the range check using the computed values L_2/R_2
1703 // from: i*K + L <u64 R
1704 // to: j*K + L_2 <u32 R_2
1705 // that is:
1706 // (j*K + Q_first) - L_clamp <u32 clamp(R, L_clamp, H_clamp) - L_clamp
1707 K = intcon(checked_cast<int>(scale));
1708 Node* scaled_iv = new MulINode(inner_phi, K);
1709 register_new_node(scaled_iv, c);
1710 Node* scaled_iv_plus_offset = new AddINode(scaled_iv, L_2);
1711 register_new_node(scaled_iv_plus_offset, c);
1712
1713 Node* new_rc_cmp = new CmpUNode(scaled_iv_plus_offset, R_2);
1714 register_new_node(new_rc_cmp, c);
1715
1716 _igvn.replace_input_of(rc_bol, 1, new_rc_cmp);
1717 }
1718 }
1719
1720 Node* PhaseIdealLoop::clamp(Node* R, Node* L, Node* H) {
1721 Node* min = MaxNode::signed_min(R, H, TypeLong::LONG, _igvn);
1722 set_subtree_ctrl(min, true);
1723 Node* max = MaxNode::signed_max(L, min, TypeLong::LONG, _igvn);
1724 set_subtree_ctrl(max, true);
1725 return max;
1726 }
1727
1728 LoopNode* PhaseIdealLoop::create_inner_head(IdealLoopTree* loop, BaseCountedLoopNode* head,
1729 IfNode* exit_test) {
1730 LoopNode* new_inner_head = new LoopNode(head->in(1), head->in(2));
1731 IfNode* new_inner_exit = new IfNode(exit_test->in(0), exit_test->in(1), exit_test->_prob, exit_test->_fcnt);
1732 _igvn.register_new_node_with_optimizer(new_inner_head);
1733 _igvn.register_new_node_with_optimizer(new_inner_exit);
1734 loop->_body.push(new_inner_head);
1735 loop->_body.push(new_inner_exit);
1736 loop->_body.yank(head);
1737 loop->_body.yank(exit_test);
1738 set_loop(new_inner_head, loop);
1739 set_loop(new_inner_exit, loop);
1740 set_idom(new_inner_head, idom(head), dom_depth(head));
1741 set_idom(new_inner_exit, idom(exit_test), dom_depth(exit_test));
1742 replace_node_and_forward_ctrl(head, new_inner_head);
1743 replace_node_and_forward_ctrl(exit_test, new_inner_exit);
1744 loop->_head = new_inner_head;
1745 return new_inner_head;
1746 }
1747
1748 #ifdef ASSERT
1749 void PhaseIdealLoop::check_counted_loop_shape(IdealLoopTree* loop, Node* x, BasicType bt) {
1750 Node* back_control = loop_exit_control(x, loop);
1751 assert(back_control != nullptr, "no back control");
1752
1753 BoolTest::mask mask = BoolTest::illegal;
1754 float cl_prob = 0;
1755 Node* incr = nullptr;
1756 Node* limit = nullptr;
1757
1758 Node* cmp = loop_exit_test(back_control, loop, incr, limit, mask, cl_prob);
1759 assert(cmp != nullptr && cmp->Opcode() == Op_Cmp(bt), "no exit test");
1760
1761 Node* phi_incr = nullptr;
1762 incr = loop_iv_incr(incr, x, loop, phi_incr);
1763 assert(incr != nullptr && incr->Opcode() == Op_Add(bt), "no incr");
1764
1765 Node* xphi = nullptr;
1766 Node* stride = loop_iv_stride(incr, xphi);
1767
1768 assert(stride != nullptr, "no stride");
1769
1770 PhiNode* phi = loop_iv_phi(xphi, phi_incr, x);
1771
1772 assert(phi != nullptr && phi->in(LoopNode::LoopBackControl) == incr, "No phi");
1773
1774 jlong stride_con = stride->get_integer_as_long(bt);
1775
1776 assert(condition_stride_ok(mask, stride_con), "illegal condition");
1777
1778 assert(mask != BoolTest::ne, "unexpected condition");
1779 assert(phi_incr == nullptr, "bad loop shape");
1780 assert(cmp->in(1) == incr, "bad exit test shape");
1781
1782 // Safepoint on backedge not supported
1783 assert(x->in(LoopNode::LoopBackControl)->Opcode() != Op_SafePoint, "no safepoint on backedge");
1784 }
1785 #endif
1786
1787 #ifdef ASSERT
1788 // convert an int counted loop to a long counted to stress handling of
1789 // long counted loops
1790 bool PhaseIdealLoop::convert_to_long_loop(Node* cmp, Node* phi, IdealLoopTree* loop) {
1791 Unique_Node_List iv_nodes;
1792 Node_List old_new;
1793 iv_nodes.push(cmp);
1794 bool failed = false;
1795
1796 for (uint i = 0; i < iv_nodes.size() && !failed; i++) {
1797 Node* n = iv_nodes.at(i);
1798 switch(n->Opcode()) {
1799 case Op_Phi: {
1800 Node* clone = new PhiNode(n->in(0), TypeLong::LONG);
1801 old_new.map(n->_idx, clone);
1802 break;
1803 }
1804 case Op_CmpI: {
1805 Node* clone = new CmpLNode(nullptr, nullptr);
1806 old_new.map(n->_idx, clone);
1807 break;
1808 }
1809 case Op_AddI: {
1810 Node* clone = new AddLNode(nullptr, nullptr);
1811 old_new.map(n->_idx, clone);
1812 break;
1813 }
1814 case Op_CastII: {
1815 failed = true;
1816 break;
1817 }
1818 default:
1819 DEBUG_ONLY(n->dump());
1820 fatal("unexpected");
1821 }
1822
1823 for (uint i = 1; i < n->req(); i++) {
1824 Node* in = n->in(i);
1825 if (in == nullptr) {
1826 continue;
1827 }
1828 if (ctrl_is_member(loop, in)) {
1829 iv_nodes.push(in);
1830 }
1831 }
1832 }
1833
1834 if (failed) {
1835 for (uint i = 0; i < iv_nodes.size(); i++) {
1836 Node* n = iv_nodes.at(i);
1837 Node* clone = old_new[n->_idx];
1838 if (clone != nullptr) {
1839 _igvn.remove_dead_node(clone);
1840 }
1841 }
1842 return false;
1843 }
1844
1845 for (uint i = 0; i < iv_nodes.size(); i++) {
1846 Node* n = iv_nodes.at(i);
1847 Node* clone = old_new[n->_idx];
1848 for (uint i = 1; i < n->req(); i++) {
1849 Node* in = n->in(i);
1850 if (in == nullptr) {
1851 continue;
1852 }
1853 Node* in_clone = old_new[in->_idx];
1854 if (in_clone == nullptr) {
1855 assert(_igvn.type(in)->isa_int(), "");
1856 in_clone = new ConvI2LNode(in);
1857 _igvn.register_new_node_with_optimizer(in_clone);
1858 set_subtree_ctrl(in_clone, false);
1859 }
1860 if (in_clone->in(0) == nullptr) {
1861 in_clone->set_req(0, C->top());
1862 clone->set_req(i, in_clone);
1863 in_clone->set_req(0, nullptr);
1864 } else {
1865 clone->set_req(i, in_clone);
1866 }
1867 }
1868 _igvn.register_new_node_with_optimizer(clone);
1869 }
1870 set_ctrl(old_new[phi->_idx], phi->in(0));
1871
1872 for (uint i = 0; i < iv_nodes.size(); i++) {
1873 Node* n = iv_nodes.at(i);
1874 Node* clone = old_new[n->_idx];
1875 set_subtree_ctrl(clone, false);
1876 Node* m = n->Opcode() == Op_CmpI ? clone : nullptr;
1877 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
1878 Node* u = n->fast_out(i);
1879 if (iv_nodes.member(u)) {
1880 continue;
1881 }
1882 if (m == nullptr) {
1883 m = new ConvL2INode(clone);
1884 _igvn.register_new_node_with_optimizer(m);
1885 set_subtree_ctrl(m, false);
1886 }
1887 _igvn.rehash_node_delayed(u);
1888 int nb = u->replace_edge(n, m, &_igvn);
1889 --i, imax -= nb;
1890 }
1891 }
1892 return true;
1893 }
1894 #endif
1895
1896 //------------------------------is_counted_loop--------------------------------
1897 bool PhaseIdealLoop::is_counted_loop(Node* x, IdealLoopTree*&loop, BasicType iv_bt) {
1898 PhaseGVN *gvn = &_igvn;
1899
1900 Node* back_control = loop_exit_control(x, loop);
1901 if (back_control == nullptr) {
1902 return false;
1903 }
1904
1905 BoolTest::mask bt = BoolTest::illegal;
1906 float cl_prob = 0;
1907 Node* incr = nullptr;
1908 Node* limit = nullptr;
1909 Node* cmp = loop_exit_test(back_control, loop, incr, limit, bt, cl_prob);
1910 if (cmp == nullptr || cmp->Opcode() != Op_Cmp(iv_bt)) {
1911 return false; // Avoid pointer & float & 64-bit compares
1912 }
1913
1914 // Trip-counter increment must be commutative & associative.
1915 if (incr->Opcode() == Op_Cast(iv_bt)) {
1916 incr = incr->in(1);
1917 }
1918
1919 Node* phi_incr = nullptr;
1920 incr = loop_iv_incr(incr, x, loop, phi_incr);
1921 if (incr == nullptr) {
1922 return false;
1923 }
1924
1925 Node* trunc1 = nullptr;
1926 Node* trunc2 = nullptr;
1927 const TypeInteger* iv_trunc_t = nullptr;
1928 Node* orig_incr = incr;
1929 if (!(incr = CountedLoopNode::match_incr_with_optional_truncation(incr, &trunc1, &trunc2, &iv_trunc_t, iv_bt))) {
1930 return false; // Funny increment opcode
1931 }
1932 assert(incr->Opcode() == Op_Add(iv_bt), "wrong increment code");
1933
1934 Node* xphi = nullptr;
1935 Node* stride = loop_iv_stride(incr, xphi);
1936
1937 if (stride == nullptr) {
1938 return false;
1939 }
1940
1941 // Iteratively uncast the loop induction variable
1942 // until no more CastII/CastLL nodes are found.
1943 while (xphi->Opcode() == Op_Cast(iv_bt)) {
1944 xphi = xphi->in(1);
1945 }
1946
1947 // Stride must be constant
1948 jlong stride_con = stride->get_integer_as_long(iv_bt);
1949 assert(stride_con != 0, "missed some peephole opt");
1950
1951 PhiNode* phi = loop_iv_phi(xphi, phi_incr, x);
1952
1953 if (phi == nullptr ||
1954 (trunc1 == nullptr && phi->in(LoopNode::LoopBackControl) != incr) ||
1955 (trunc1 != nullptr && phi->in(LoopNode::LoopBackControl) != trunc1)) {
1956 return false;
1957 }
1958
1959 Node* iftrue = back_control;
1960 uint iftrue_op = iftrue->Opcode();
1961 Node* iff = iftrue->in(0);
1962 BoolNode* test = iff->in(1)->as_Bool();
1963
1964 const TypeInteger* limit_t = gvn->type(limit)->is_integer(iv_bt);
1965 if (trunc1 != nullptr) {
1966 // When there is a truncation, we must be sure that after the truncation
1967 // the trip counter will end up higher than the limit, otherwise we are looking
1968 // at an endless loop. Can happen with range checks.
1969
1970 // Example:
1971 // int i = 0;
1972 // while (true)
1973 // sum + = array[i];
1974 // i++;
1975 // i = i && 0x7fff;
1976 // }
1977 //
1978 // If the array is shorter than 0x8000 this exits through a AIOOB
1979 // - Counted loop transformation is ok
1980 // If the array is longer then this is an endless loop
1981 // - No transformation can be done.
1982
1983 const TypeInteger* incr_t = gvn->type(orig_incr)->is_integer(iv_bt);
1984 if (limit_t->hi_as_long() > incr_t->hi_as_long()) {
1985 // if the limit can have a higher value than the increment (before the phi)
1986 return false;
1987 }
1988 }
1989
1990 Node *init_trip = phi->in(LoopNode::EntryControl);
1991
1992 // If iv trunc type is smaller than int, check for possible wrap.
1993 if (!TypeInteger::bottom(iv_bt)->higher_equal(iv_trunc_t)) {
1994 assert(trunc1 != nullptr, "must have found some truncation");
1995
1996 // Get a better type for the phi (filtered thru if's)
1997 const TypeInteger* phi_ft = filtered_type(phi);
1998
1999 // Can iv take on a value that will wrap?
2000 //
2001 // Ensure iv's limit is not within "stride" of the wrap value.
2002 //
2003 // Example for "short" type
2004 // Truncation ensures value is in the range -32768..32767 (iv_trunc_t)
2005 // If the stride is +10, then the last value of the induction
2006 // variable before the increment (phi_ft->_hi) must be
2007 // <= 32767 - 10 and (phi_ft->_lo) must be >= -32768 to
2008 // ensure no truncation occurs after the increment.
2009
2010 if (stride_con > 0) {
2011 if (iv_trunc_t->hi_as_long() - phi_ft->hi_as_long() < stride_con ||
2012 iv_trunc_t->lo_as_long() > phi_ft->lo_as_long()) {
2013 return false; // truncation may occur
2014 }
2015 } else if (stride_con < 0) {
2016 if (iv_trunc_t->lo_as_long() - phi_ft->lo_as_long() > stride_con ||
2017 iv_trunc_t->hi_as_long() < phi_ft->hi_as_long()) {
2018 return false; // truncation may occur
2019 }
2020 }
2021 // No possibility of wrap so truncation can be discarded
2022 // Promote iv type to Int
2023 } else {
2024 assert(trunc1 == nullptr && trunc2 == nullptr, "no truncation for int");
2025 }
2026
2027 if (!condition_stride_ok(bt, stride_con)) {
2028 return false;
2029 }
2030
2031 const TypeInteger* init_t = gvn->type(init_trip)->is_integer(iv_bt);
2032
2033 if (stride_con > 0) {
2034 if (init_t->lo_as_long() > max_signed_integer(iv_bt) - stride_con) {
2035 return false; // cyclic loop
2036 }
2037 } else {
2038 if (init_t->hi_as_long() < min_signed_integer(iv_bt) - stride_con) {
2039 return false; // cyclic loop
2040 }
2041 }
2042
2043 if (phi_incr != nullptr && bt != BoolTest::ne) {
2044 // check if there is a possibility of IV overflowing after the first increment
2045 if (stride_con > 0) {
2046 if (init_t->hi_as_long() > max_signed_integer(iv_bt) - stride_con) {
2047 return false;
2048 }
2049 } else {
2050 if (init_t->lo_as_long() < min_signed_integer(iv_bt) - stride_con) {
2051 return false;
2052 }
2053 }
2054 }
2055
2056 // =================================================
2057 // ---- SUCCESS! Found A Trip-Counted Loop! -----
2058 //
2059
2060 if (x->Opcode() == Op_Region) {
2061 // x has not yet been transformed to Loop or LongCountedLoop.
2062 // This should only happen if we are inside an infinite loop.
2063 // It happens like this:
2064 // build_loop_tree -> do not attach infinite loop and nested loops
2065 // beautify_loops -> does not transform the infinite and nested loops to LoopNode, because not attached yet
2066 // build_loop_tree -> find and attach infinite and nested loops
2067 // counted_loop -> nested Regions are not yet transformed to LoopNodes, we land here
2068 assert(x->as_Region()->is_in_infinite_subgraph(),
2069 "x can only be a Region and not Loop if inside infinite loop");
2070 // Come back later when Region is transformed to LoopNode
2071 return false;
2072 }
2073
2074 assert(x->Opcode() == Op_Loop || x->Opcode() == Op_LongCountedLoop, "regular loops only");
2075 C->print_method(PHASE_BEFORE_CLOOPS, 3, x);
2076
2077 // ===================================================
2078 // We can only convert this loop to a counted loop if we can guarantee that the iv phi will never overflow at runtime.
2079 // This is an implicit assumption taken by some loop optimizations. We therefore must ensure this property at all cost.
2080 // At this point, we've already excluded some trivial cases where an overflow could have been proven statically.
2081 // But even though we cannot prove that an overflow will *not* happen, we still want to speculatively convert this loop
2082 // to a counted loop. This can be achieved by adding additional iv phi overflow checks before the loop. If they fail,
2083 // we trap and resume execution before the loop without having executed any iteration of the loop, yet.
2084 //
2085 // These additional iv phi overflow checks can be inserted as Loop Limit Check Predicates above the Loop Limit Check
2086 // Parse Predicate which captures a JVM state just before the entry of the loop. If there is no such Parse Predicate,
2087 // we cannot generate a Loop Limit Check Predicate and thus cannot speculatively convert the loop to a counted loop.
2088 //
2089 // In the following, we only focus on int loops with stride > 0 to keep things simple. The argumentation and proof
2090 // for stride < 0 is analogously. For long loops, we would replace max_int with max_long.
2091 //
2092 //
2093 // The loop to be converted does not always need to have the often used shape:
2094 //
2095 // i = init
2096 // i = init loop:
2097 // do { ...
2098 // // ... equivalent i+=stride
2099 // i+=stride <==> if (i < limit)
2100 // } while (i < limit); goto loop
2101 // exit:
2102 // ...
2103 //
2104 // where the loop exit check uses the post-incremented iv phi and a '<'-operator.
2105 //
2106 // We could also have '<='-operator (or '>='-operator for negative strides) or use the pre-incremented iv phi value
2107 // in the loop exit check:
2108 //
2109 // i = init
2110 // loop:
2111 // ...
2112 // if (i <= limit)
2113 // i+=stride
2114 // goto loop
2115 // exit:
2116 // ...
2117 //
2118 // Let's define the following terms:
2119 // - iv_pre_i: The pre-incremented iv phi before the i-th iteration.
2120 // - iv_post_i: The post-incremented iv phi after the i-th iteration.
2121 //
2122 // The iv_pre_i and iv_post_i have the following relation:
2123 // iv_pre_i + stride = iv_post_i
2124 //
2125 // When converting a loop to a counted loop, we want to have a canonicalized loop exit check of the form:
2126 // iv_post_i < adjusted_limit
2127 //
2128 // If that is not the case, we need to canonicalize the loop exit check by using different values for adjusted_limit:
2129 // (LE1) iv_post_i < limit: Already canonicalized. We can directly use limit as adjusted_limit.
2130 // -> adjusted_limit = limit.
2131 // (LE2) iv_post_i <= limit:
2132 // iv_post_i < limit + 1
2133 // -> adjusted limit = limit + 1
2134 // (LE3) iv_pre_i < limit:
2135 // iv_pre_i + stride < limit + stride
2136 // iv_post_i < limit + stride
2137 // -> adjusted_limit = limit + stride
2138 // (LE4) iv_pre_i <= limit:
2139 // iv_pre_i < limit + 1
2140 // iv_pre_i + stride < limit + stride + 1
2141 // iv_post_i < limit + stride + 1
2142 // -> adjusted_limit = limit + stride + 1
2143 //
2144 // Note that:
2145 // (AL) limit <= adjusted_limit.
2146 //
2147 // The following loop invariant has to hold for counted loops with n iterations (i.e. loop exit check true after n-th
2148 // loop iteration) and a canonicalized loop exit check to guarantee that no iv_post_i over- or underflows:
2149 // (INV) For i = 1..n, min_int <= iv_post_i <= max_int
2150 //
2151 // To prove (INV), we require the following two conditions/assumptions:
2152 // (i): adjusted_limit - 1 + stride <= max_int
2153 // (ii): init < limit
2154 //
2155 // If we can prove (INV), we know that there can be no over- or underflow of any iv phi value. We prove (INV) by
2156 // induction by assuming (i) and (ii).
2157 //
2158 // Proof by Induction
2159 // ------------------
2160 // > Base case (i = 1): We show that (INV) holds after the first iteration:
2161 // min_int <= iv_post_1 = init + stride <= max_int
2162 // Proof:
2163 // First, we note that (ii) implies
2164 // (iii) init <= limit - 1
2165 // max_int >= adjusted_limit - 1 + stride [using (i)]
2166 // >= limit - 1 + stride [using (AL)]
2167 // >= init + stride [using (iii)]
2168 // >= min_int [using stride > 0, no underflow]
2169 // Thus, no overflow happens after the first iteration and (INV) holds for i = 1.
2170 //
2171 // Note that to prove the base case we need (i) and (ii).
2172 //
2173 // > Induction Hypothesis (i = j, j > 1): Assume that (INV) holds after the j-th iteration:
2174 // min_int <= iv_post_j <= max_int
2175 // > Step case (i = j + 1): We show that (INV) also holds after the j+1-th iteration:
2176 // min_int <= iv_post_{j+1} = iv_post_j + stride <= max_int
2177 // Proof:
2178 // If iv_post_j >= adjusted_limit:
2179 // We exit the loop after the j-th iteration, and we don't execute the j+1-th iteration anymore. Thus, there is
2180 // also no iv_{j+1}. Since (INV) holds for iv_j, there is nothing left to prove.
2181 // If iv_post_j < adjusted_limit:
2182 // First, we note that:
2183 // (iv) iv_post_j <= adjusted_limit - 1
2184 // max_int >= adjusted_limit - 1 + stride [using (i)]
2185 // >= iv_post_j + stride [using (iv)]
2186 // >= min_int [using stride > 0, no underflow]
2187 //
2188 // Note that to prove the step case we only need (i).
2189 //
2190 // Thus, by assuming (i) and (ii), we proved (INV).
2191 //
2192 //
2193 // It is therefore enough to add the following two Loop Limit Check Predicates to check assumptions (i) and (ii):
2194 //
2195 // (1) Loop Limit Check Predicate for (i):
2196 // Using (i): adjusted_limit - 1 + stride <= max_int
2197 //
2198 // This condition is now restated to use limit instead of adjusted_limit:
2199 //
2200 // To prevent an overflow of adjusted_limit -1 + stride itself, we rewrite this check to
2201 // max_int - stride + 1 >= adjusted_limit
2202 // We can merge the two constants into
2203 // canonicalized_correction = stride - 1
2204 // which gives us
2205 // max_int - canonicalized_correction >= adjusted_limit
2206 //
2207 // To directly use limit instead of adjusted_limit in the predicate condition, we split adjusted_limit into:
2208 // adjusted_limit = limit + limit_correction
2209 // Since stride > 0 and limit_correction <= stride + 1, we can restate this with no over- or underflow into:
2210 // max_int - canonicalized_correction - limit_correction >= limit
2211 // Since canonicalized_correction and limit_correction are both constants, we can replace them with a new constant:
2212 // (v) final_correction = canonicalized_correction + limit_correction
2213 //
2214 // which gives us:
2215 //
2216 // Final predicate condition:
2217 // max_int - final_correction >= limit
2218 //
2219 // However, we need to be careful that (v) does not over- or underflow.
2220 // We know that:
2221 // canonicalized_correction = stride - 1
2222 // and
2223 // limit_correction <= stride + 1
2224 // and thus
2225 // canonicalized_correction + limit_correction <= 2 * stride
2226 // To prevent an over- or underflow of (v), we must ensure that
2227 // 2 * stride <= max_int
2228 // which can safely be checked without over- or underflow with
2229 // (vi) stride != min_int AND abs(stride) <= max_int / 2
2230 //
2231 // We could try to further optimize the cases where (vi) does not hold but given that such large strides are
2232 // very uncommon and the loop would only run for a very few iterations anyway, we simply bail out if (vi) fails.
2233 //
2234 // (2) Loop Limit Check Predicate for (ii):
2235 // Using (ii): init < limit
2236 //
2237 // This Loop Limit Check Predicate is not required if we can prove at compile time that either:
2238 // (2.1) type(init) < type(limit)
2239 // In this case, we know:
2240 // all possible values of init < all possible values of limit
2241 // and we can skip the predicate.
2242 //
2243 // (2.2) init < limit is already checked before (i.e. found as a dominating check)
2244 // In this case, we do not need to re-check the condition and can skip the predicate.
2245 // This is often found for while- and for-loops which have the following shape:
2246 //
2247 // if (init < limit) { // Dominating test. Do not need the Loop Limit Check Predicate below.
2248 // i = init;
2249 // if (init >= limit) { trap(); } // Here we would insert the Loop Limit Check Predicate
2250 // do {
2251 // i += stride;
2252 // } while (i < limit);
2253 // }
2254 //
2255 // (2.3) init + stride <= max_int
2256 // In this case, there is no overflow of the iv phi after the first loop iteration.
2257 // In the proof of the base case above we showed that init + stride <= max_int by using assumption (ii):
2258 // init < limit
2259 // In the proof of the step case above, we did not need (ii) anymore. Therefore, if we already know at
2260 // compile time that init + stride <= max_int then we have trivially proven the base case and that
2261 // there is no overflow of the iv phi after the first iteration. In this case, we don't need to check (ii)
2262 // again and can skip the predicate.
2263
2264 // Check (vi) and bail out if the stride is too big.
2265 if (stride_con == min_signed_integer(iv_bt) || (ABS(stride_con) > max_signed_integer(iv_bt) / 2)) {
2266 return false;
2267 }
2268
2269 // Accounting for (LE3) and (LE4) where we use pre-incremented phis in the loop exit check.
2270 const jlong limit_correction_for_pre_iv_exit_check = (phi_incr != nullptr) ? stride_con : 0;
2271
2272 // Accounting for (LE2) and (LE4) where we use <= or >= in the loop exit check.
2273 const bool includes_limit = (bt == BoolTest::le || bt == BoolTest::ge);
2274 const jlong limit_correction_for_le_ge_exit_check = (includes_limit ? (stride_con > 0 ? 1 : -1) : 0);
2275
2276 const jlong limit_correction = limit_correction_for_pre_iv_exit_check + limit_correction_for_le_ge_exit_check;
2277 const jlong canonicalized_correction = stride_con + (stride_con > 0 ? -1 : 1);
2278 const jlong final_correction = canonicalized_correction + limit_correction;
2279
2280 int sov = check_stride_overflow(final_correction, limit_t, iv_bt);
2281 Node* init_control = x->in(LoopNode::EntryControl);
2282
2283 // If sov==0, limit's type always satisfies the condition, for
2284 // example, when it is an array length.
2285 if (sov != 0) {
2286 if (sov < 0) {
2287 return false; // Bailout: integer overflow is certain.
2288 }
2289 // (1) Loop Limit Check Predicate is required because we could not statically prove that
2290 // limit + final_correction = adjusted_limit - 1 + stride <= max_int
2291 assert(!x->as_Loop()->is_loop_nest_inner_loop(), "loop was transformed");
2292 const Predicates predicates(init_control);
2293 const PredicateBlock* loop_limit_check_predicate_block = predicates.loop_limit_check_predicate_block();
2294 if (!loop_limit_check_predicate_block->has_parse_predicate()) {
2295 // The Loop Limit Check Parse Predicate is not generated if this method trapped here before.
2296 #ifdef ASSERT
2297 if (TraceLoopLimitCheck) {
2298 tty->print("Missing Loop Limit Check Parse Predicate:");
2299 loop->dump_head();
2300 x->dump(1);
2301 }
2302 #endif
2303 return false;
2304 }
2305
2306 ParsePredicateNode* loop_limit_check_parse_predicate = loop_limit_check_predicate_block->parse_predicate();
2307 if (!is_dominator(get_ctrl(limit), loop_limit_check_parse_predicate->in(0))) {
2308 return false;
2309 }
2310
2311 Node* cmp_limit;
2312 Node* bol;
2313
2314 if (stride_con > 0) {
2315 cmp_limit = CmpNode::make(limit, _igvn.integercon(max_signed_integer(iv_bt) - final_correction, iv_bt), iv_bt);
2316 bol = new BoolNode(cmp_limit, BoolTest::le);
2317 } else {
2318 cmp_limit = CmpNode::make(limit, _igvn.integercon(min_signed_integer(iv_bt) - final_correction, iv_bt), iv_bt);
2319 bol = new BoolNode(cmp_limit, BoolTest::ge);
2320 }
2321
2322 insert_loop_limit_check_predicate(init_control->as_IfTrue(), cmp_limit, bol);
2323 }
2324
2325 // (2.3)
2326 const bool init_plus_stride_could_overflow =
2327 (stride_con > 0 && init_t->hi_as_long() > max_signed_integer(iv_bt) - stride_con) ||
2328 (stride_con < 0 && init_t->lo_as_long() < min_signed_integer(iv_bt) - stride_con);
2329 // (2.1)
2330 const bool init_gte_limit = (stride_con > 0 && init_t->hi_as_long() >= limit_t->lo_as_long()) ||
2331 (stride_con < 0 && init_t->lo_as_long() <= limit_t->hi_as_long());
2332
2333 if (init_gte_limit && // (2.1)
2334 ((bt == BoolTest::ne || init_plus_stride_could_overflow) && // (2.3)
2335 !has_dominating_loop_limit_check(init_trip, limit, stride_con, iv_bt, init_control))) { // (2.2)
2336 // (2) Iteration Loop Limit Check Predicate is required because neither (2.1), (2.2), nor (2.3) holds.
2337 // We use the following condition:
2338 // - stride > 0: init < limit
2339 // - stride < 0: init > limit
2340 //
2341 // This predicate is always required if we have a non-equal-operator in the loop exit check (where stride = 1 is
2342 // a requirement). We transform the loop exit check by using a less-than-operator. By doing so, we must always
2343 // check that init < limit. Otherwise, we could have a different number of iterations at runtime.
2344
2345 const Predicates predicates(init_control);
2346 const PredicateBlock* loop_limit_check_predicate_block = predicates.loop_limit_check_predicate_block();
2347 if (!loop_limit_check_predicate_block->has_parse_predicate()) {
2348 // The Loop Limit Check Parse Predicate is not generated if this method trapped here before.
2349 #ifdef ASSERT
2350 if (TraceLoopLimitCheck) {
2351 tty->print("Missing Loop Limit Check Parse Predicate:");
2352 loop->dump_head();
2353 x->dump(1);
2354 }
2355 #endif
2356 return false;
2357 }
2358
2359 ParsePredicateNode* loop_limit_check_parse_predicate = loop_limit_check_predicate_block->parse_predicate();
2360 Node* parse_predicate_entry = loop_limit_check_parse_predicate->in(0);
2361 if (!is_dominator(get_ctrl(limit), parse_predicate_entry) ||
2362 !is_dominator(get_ctrl(init_trip), parse_predicate_entry)) {
2363 return false;
2364 }
2365
2366 Node* cmp_limit;
2367 Node* bol;
2368
2369 if (stride_con > 0) {
2370 cmp_limit = CmpNode::make(init_trip, limit, iv_bt);
2371 bol = new BoolNode(cmp_limit, BoolTest::lt);
2372 } else {
2373 cmp_limit = CmpNode::make(init_trip, limit, iv_bt);
2374 bol = new BoolNode(cmp_limit, BoolTest::gt);
2375 }
2376
2377 insert_loop_limit_check_predicate(init_control->as_IfTrue(), cmp_limit, bol);
2378 }
2379
2380 if (bt == BoolTest::ne) {
2381 // Now we need to canonicalize the loop condition if it is 'ne'.
2382 assert(stride_con == 1 || stride_con == -1, "simple increment only - checked before");
2383 if (stride_con > 0) {
2384 // 'ne' can be replaced with 'lt' only when init < limit. This is ensured by the inserted predicate above.
2385 bt = BoolTest::lt;
2386 } else {
2387 assert(stride_con < 0, "must be");
2388 // 'ne' can be replaced with 'gt' only when init > limit. This is ensured by the inserted predicate above.
2389 bt = BoolTest::gt;
2390 }
2391 }
2392
2393 Node* sfpt = nullptr;
2394 if (loop->_child == nullptr) {
2395 sfpt = find_safepoint(back_control, x, loop);
2396 } else {
2397 sfpt = iff->in(0);
2398 if (sfpt->Opcode() != Op_SafePoint) {
2399 sfpt = nullptr;
2400 }
2401 }
2402
2403 if (x->in(LoopNode::LoopBackControl)->Opcode() == Op_SafePoint) {
2404 Node* backedge_sfpt = x->in(LoopNode::LoopBackControl);
2405 if (((iv_bt == T_INT && LoopStripMiningIter != 0) ||
2406 iv_bt == T_LONG) &&
2407 sfpt == nullptr) {
2408 // Leaving the safepoint on the backedge and creating a
2409 // CountedLoop will confuse optimizations. We can't move the
2410 // safepoint around because its jvm state wouldn't match a new
2411 // location. Give up on that loop.
2412 return false;
2413 }
2414 if (is_deleteable_safept(backedge_sfpt)) {
2415 replace_node_and_forward_ctrl(backedge_sfpt, iftrue);
2416 if (loop->_safepts != nullptr) {
2417 loop->_safepts->yank(backedge_sfpt);
2418 }
2419 loop->_tail = iftrue;
2420 }
2421 }
2422
2423
2424 #ifdef ASSERT
2425 if (iv_bt == T_INT &&
2426 !x->as_Loop()->is_loop_nest_inner_loop() &&
2427 StressLongCountedLoop > 0 &&
2428 trunc1 == nullptr &&
2429 convert_to_long_loop(cmp, phi, loop)) {
2430 return false;
2431 }
2432 #endif
2433
2434 Node* adjusted_limit = limit;
2435 if (phi_incr != nullptr) {
2436 // If compare points directly to the phi we need to adjust
2437 // the compare so that it points to the incr. Limit have
2438 // to be adjusted to keep trip count the same and we
2439 // should avoid int overflow.
2440 //
2441 // i = init; do {} while(i++ < limit);
2442 // is converted to
2443 // i = init; do {} while(++i < limit+1);
2444 //
2445 adjusted_limit = gvn->transform(AddNode::make(limit, stride, iv_bt));
2446 }
2447
2448 if (includes_limit) {
2449 // The limit check guaranties that 'limit <= (max_jint - stride)' so
2450 // we can convert 'i <= limit' to 'i < limit+1' since stride != 0.
2451 //
2452 Node* one = (stride_con > 0) ? gvn->integercon( 1, iv_bt) : gvn->integercon(-1, iv_bt);
2453 adjusted_limit = gvn->transform(AddNode::make(adjusted_limit, one, iv_bt));
2454 if (bt == BoolTest::le)
2455 bt = BoolTest::lt;
2456 else if (bt == BoolTest::ge)
2457 bt = BoolTest::gt;
2458 else
2459 ShouldNotReachHere();
2460 }
2461 set_subtree_ctrl(adjusted_limit, false);
2462
2463 // Build a canonical trip test.
2464 // Clone code, as old values may be in use.
2465 incr = incr->clone();
2466 incr->set_req(1,phi);
2467 incr->set_req(2,stride);
2468 incr = _igvn.register_new_node_with_optimizer(incr);
2469 set_early_ctrl(incr, false);
2470 _igvn.rehash_node_delayed(phi);
2471 phi->set_req_X( LoopNode::LoopBackControl, incr, &_igvn );
2472
2473 // If phi type is more restrictive than Int, raise to
2474 // Int to prevent (almost) infinite recursion in igvn
2475 // which can only handle integer types for constants or minint..maxint.
2476 if (!TypeInteger::bottom(iv_bt)->higher_equal(phi->bottom_type())) {
2477 Node* nphi = PhiNode::make(phi->in(0), phi->in(LoopNode::EntryControl), TypeInteger::bottom(iv_bt));
2478 nphi->set_req(LoopNode::LoopBackControl, phi->in(LoopNode::LoopBackControl));
2479 nphi = _igvn.register_new_node_with_optimizer(nphi);
2480 set_ctrl(nphi, get_ctrl(phi));
2481 _igvn.replace_node(phi, nphi);
2482 phi = nphi->as_Phi();
2483 }
2484 cmp = cmp->clone();
2485 cmp->set_req(1,incr);
2486 cmp->set_req(2, adjusted_limit);
2487 cmp = _igvn.register_new_node_with_optimizer(cmp);
2488 set_ctrl(cmp, iff->in(0));
2489
2490 test = test->clone()->as_Bool();
2491 (*(BoolTest*)&test->_test)._test = bt;
2492 test->set_req(1,cmp);
2493 _igvn.register_new_node_with_optimizer(test);
2494 set_ctrl(test, iff->in(0));
2495
2496 // Replace the old IfNode with a new LoopEndNode
2497 Node *lex = _igvn.register_new_node_with_optimizer(BaseCountedLoopEndNode::make(iff->in(0), test, cl_prob, iff->as_If()->_fcnt, iv_bt));
2498 IfNode *le = lex->as_If();
2499 uint dd = dom_depth(iff);
2500 set_idom(le, le->in(0), dd); // Update dominance for loop exit
2501 set_loop(le, loop);
2502
2503 // Get the loop-exit control
2504 Node *iffalse = iff->as_If()->proj_out(!(iftrue_op == Op_IfTrue));
2505
2506 // Need to swap loop-exit and loop-back control?
2507 if (iftrue_op == Op_IfFalse) {
2508 Node *ift2=_igvn.register_new_node_with_optimizer(new IfTrueNode (le));
2509 Node *iff2=_igvn.register_new_node_with_optimizer(new IfFalseNode(le));
2510
2511 loop->_tail = back_control = ift2;
2512 set_loop(ift2, loop);
2513 set_loop(iff2, get_loop(iffalse));
2514
2515 // Lazy update of 'get_ctrl' mechanism.
2516 replace_node_and_forward_ctrl(iffalse, iff2);
2517 replace_node_and_forward_ctrl(iftrue, ift2);
2518
2519 // Swap names
2520 iffalse = iff2;
2521 iftrue = ift2;
2522 } else {
2523 _igvn.rehash_node_delayed(iffalse);
2524 _igvn.rehash_node_delayed(iftrue);
2525 iffalse->set_req_X( 0, le, &_igvn );
2526 iftrue ->set_req_X( 0, le, &_igvn );
2527 }
2528
2529 set_idom(iftrue, le, dd+1);
2530 set_idom(iffalse, le, dd+1);
2531 assert(iff->outcnt() == 0, "should be dead now");
2532 replace_node_and_forward_ctrl(iff, le); // fix 'get_ctrl'
2533
2534 Node* entry_control = init_control;
2535 bool strip_mine_loop = iv_bt == T_INT &&
2536 loop->_child == nullptr &&
2537 sfpt != nullptr &&
2538 !loop->_has_call &&
2539 is_deleteable_safept(sfpt);
2540 IdealLoopTree* outer_ilt = nullptr;
2541 if (strip_mine_loop) {
2542 outer_ilt = create_outer_strip_mined_loop(init_control, loop, cl_prob, le->_fcnt,
2543 entry_control, iffalse);
2544 }
2545
2546 // Now setup a new CountedLoopNode to replace the existing LoopNode
2547 BaseCountedLoopNode *l = BaseCountedLoopNode::make(entry_control, back_control, iv_bt);
2548 l->set_unswitch_count(x->as_Loop()->unswitch_count()); // Preserve
2549 // The following assert is approximately true, and defines the intention
2550 // of can_be_counted_loop. It fails, however, because phase->type
2551 // is not yet initialized for this loop and its parts.
2552 //assert(l->can_be_counted_loop(this), "sanity");
2553 _igvn.register_new_node_with_optimizer(l);
2554 set_loop(l, loop);
2555 loop->_head = l;
2556 // Fix all data nodes placed at the old loop head.
2557 // Uses the lazy-update mechanism of 'get_ctrl'.
2558 replace_node_and_forward_ctrl(x, l);
2559 set_idom(l, entry_control, dom_depth(entry_control) + 1);
2560
2561 if (iv_bt == T_INT && (LoopStripMiningIter == 0 || strip_mine_loop)) {
2562 // Check for immediately preceding SafePoint and remove
2563 if (sfpt != nullptr && (strip_mine_loop || is_deleteable_safept(sfpt))) {
2564 if (strip_mine_loop) {
2565 Node* outer_le = outer_ilt->_tail->in(0);
2566 Node* sfpt_clone = sfpt->clone();
2567 sfpt_clone->set_req(0, iffalse);
2568 outer_le->set_req(0, sfpt_clone);
2569
2570 Node* polladdr = sfpt_clone->in(TypeFunc::Parms);
2571 if (polladdr != nullptr && polladdr->is_Load()) {
2572 // Polling load should be pinned outside inner loop.
2573 Node* new_polladdr = polladdr->clone();
2574 new_polladdr->set_req(0, iffalse);
2575 _igvn.register_new_node_with_optimizer(new_polladdr, polladdr);
2576 set_ctrl(new_polladdr, iffalse);
2577 sfpt_clone->set_req(TypeFunc::Parms, new_polladdr);
2578 }
2579 // When this code runs, loop bodies have not yet been populated.
2580 const bool body_populated = false;
2581 register_control(sfpt_clone, outer_ilt, iffalse, body_populated);
2582 set_idom(outer_le, sfpt_clone, dom_depth(sfpt_clone));
2583 }
2584 replace_node_and_forward_ctrl(sfpt, sfpt->in(TypeFunc::Control));
2585 if (loop->_safepts != nullptr) {
2586 loop->_safepts->yank(sfpt);
2587 }
2588 }
2589 }
2590
2591 #ifdef ASSERT
2592 assert(l->is_valid_counted_loop(iv_bt), "counted loop shape is messed up");
2593 assert(l == loop->_head && l->phi() == phi && l->loopexit_or_null() == lex, "" );
2594 #endif
2595 #ifndef PRODUCT
2596 if (TraceLoopOpts) {
2597 tty->print("Counted ");
2598 loop->dump_head();
2599 }
2600 #endif
2601
2602 C->print_method(PHASE_AFTER_CLOOPS, 3, l);
2603
2604 // Capture bounds of the loop in the induction variable Phi before
2605 // subsequent transformation (iteration splitting) obscures the
2606 // bounds
2607 l->phi()->as_Phi()->set_type(l->phi()->Value(&_igvn));
2608
2609 if (strip_mine_loop) {
2610 l->mark_strip_mined();
2611 l->verify_strip_mined(1);
2612 outer_ilt->_head->as_Loop()->verify_strip_mined(1);
2613 loop = outer_ilt;
2614 }
2615
2616 #ifndef PRODUCT
2617 if (x->as_Loop()->is_loop_nest_inner_loop() && iv_bt == T_LONG) {
2618 AtomicAccess::inc(&_long_loop_counted_loops);
2619 }
2620 #endif
2621 if (iv_bt == T_LONG && x->as_Loop()->is_loop_nest_outer_loop()) {
2622 l->mark_loop_nest_outer_loop();
2623 }
2624
2625 return true;
2626 }
2627
2628 // Check if there is a dominating loop limit check of the form 'init < limit' starting at the loop entry.
2629 // If there is one, then we do not need to create an additional Loop Limit Check Predicate.
2630 bool PhaseIdealLoop::has_dominating_loop_limit_check(Node* init_trip, Node* limit, const jlong stride_con,
2631 const BasicType iv_bt, Node* loop_entry) {
2632 // Eagerly call transform() on the Cmp and Bool node to common them up if possible. This is required in order to
2633 // successfully find a dominated test with the If node below.
2634 Node* cmp_limit;
2635 Node* bol;
2636 if (stride_con > 0) {
2637 cmp_limit = _igvn.transform(CmpNode::make(init_trip, limit, iv_bt));
2638 bol = _igvn.transform(new BoolNode(cmp_limit, BoolTest::lt));
2639 } else {
2640 cmp_limit = _igvn.transform(CmpNode::make(init_trip, limit, iv_bt));
2641 bol = _igvn.transform(new BoolNode(cmp_limit, BoolTest::gt));
2642 }
2643
2644 // Check if there is already a dominating init < limit check. If so, we do not need a Loop Limit Check Predicate.
2645 IfNode* iff = new IfNode(loop_entry, bol, PROB_MIN, COUNT_UNKNOWN);
2646 // Also add fake IfProj nodes in order to call transform() on the newly created IfNode.
2647 IfFalseNode* if_false = new IfFalseNode(iff);
2648 IfTrueNode* if_true = new IfTrueNode(iff);
2649 Node* dominated_iff = _igvn.transform(iff);
2650 // ConI node? Found dominating test (IfNode::dominated_by() returns a ConI node).
2651 const bool found_dominating_test = dominated_iff != nullptr && dominated_iff->is_ConI();
2652
2653 // Kill the If with its projections again in the next IGVN round by cutting it off from the graph.
2654 _igvn.replace_input_of(iff, 0, C->top());
2655 _igvn.replace_input_of(iff, 1, C->top());
2656 return found_dominating_test;
2657 }
2658
2659 //----------------------exact_limit-------------------------------------------
2660 Node* PhaseIdealLoop::exact_limit( IdealLoopTree *loop ) {
2661 assert(loop->_head->is_CountedLoop(), "");
2662 CountedLoopNode *cl = loop->_head->as_CountedLoop();
2663 assert(cl->is_valid_counted_loop(T_INT), "");
2664
2665 if (cl->stride_con() == 1 ||
2666 cl->stride_con() == -1 ||
2667 cl->limit()->Opcode() == Op_LoopLimit) {
2668 // Old code has exact limit (it could be incorrect in case of int overflow).
2669 // Loop limit is exact with stride == 1. And loop may already have exact limit.
2670 return cl->limit();
2671 }
2672 Node *limit = nullptr;
2673 #ifdef ASSERT
2674 BoolTest::mask bt = cl->loopexit()->test_trip();
2675 assert(bt == BoolTest::lt || bt == BoolTest::gt, "canonical test is expected");
2676 #endif
2677 if (cl->has_exact_trip_count()) {
2678 // Simple case: loop has constant boundaries.
2679 // Use jlongs to avoid integer overflow.
2680 int stride_con = cl->stride_con();
2681 jlong init_con = cl->init_trip()->get_int();
2682 jlong limit_con = cl->limit()->get_int();
2683 julong trip_cnt = cl->trip_count();
2684 jlong final_con = init_con + trip_cnt*stride_con;
2685 int final_int = (int)final_con;
2686 // The final value should be in integer range since the loop
2687 // is counted and the limit was checked for overflow.
2688 assert(final_con == (jlong)final_int, "final value should be integer");
2689 limit = _igvn.intcon(final_int);
2690 } else {
2691 // Create new LoopLimit node to get exact limit (final iv value).
2692 limit = new LoopLimitNode(C, cl->init_trip(), cl->limit(), cl->stride());
2693 register_new_node(limit, cl->in(LoopNode::EntryControl));
2694 }
2695 assert(limit != nullptr, "sanity");
2696 return limit;
2697 }
2698
2699 //------------------------------Ideal------------------------------------------
2700 // Return a node which is more "ideal" than the current node.
2701 // Attempt to convert into a counted-loop.
2702 Node *LoopNode::Ideal(PhaseGVN *phase, bool can_reshape) {
2703 if (!can_be_counted_loop(phase) && !is_OuterStripMinedLoop()) {
2704 phase->C->set_major_progress();
2705 }
2706 return RegionNode::Ideal(phase, can_reshape);
2707 }
2708
2709 #ifdef ASSERT
2710 void LoopNode::verify_strip_mined(int expect_skeleton) const {
2711 const OuterStripMinedLoopNode* outer = nullptr;
2712 const CountedLoopNode* inner = nullptr;
2713 if (is_strip_mined()) {
2714 if (!is_valid_counted_loop(T_INT)) {
2715 return; // Skip malformed counted loop
2716 }
2717 assert(is_CountedLoop(), "no Loop should be marked strip mined");
2718 inner = as_CountedLoop();
2719 outer = inner->in(LoopNode::EntryControl)->as_OuterStripMinedLoop();
2720 } else if (is_OuterStripMinedLoop()) {
2721 outer = this->as_OuterStripMinedLoop();
2722 inner = outer->unique_ctrl_out()->as_CountedLoop();
2723 assert(inner->is_valid_counted_loop(T_INT) && inner->is_strip_mined(), "OuterStripMinedLoop should have been removed");
2724 assert(!is_strip_mined(), "outer loop shouldn't be marked strip mined");
2725 }
2726 if (inner != nullptr || outer != nullptr) {
2727 assert(inner != nullptr && outer != nullptr, "missing loop in strip mined nest");
2728 Node* outer_tail = outer->in(LoopNode::LoopBackControl);
2729 Node* outer_le = outer_tail->in(0);
2730 assert(outer_le->Opcode() == Op_OuterStripMinedLoopEnd, "tail of outer loop should be an If");
2731 Node* sfpt = outer_le->in(0);
2732 assert(sfpt->Opcode() == Op_SafePoint, "where's the safepoint?");
2733 Node* inner_out = sfpt->in(0);
2734 CountedLoopEndNode* cle = inner_out->in(0)->as_CountedLoopEnd();
2735 assert(cle == inner->loopexit_or_null(), "mismatch");
2736 bool has_skeleton = outer_le->in(1)->bottom_type()->singleton() && outer_le->in(1)->bottom_type()->is_int()->get_con() == 0;
2737 if (has_skeleton) {
2738 assert(expect_skeleton == 1 || expect_skeleton == -1, "unexpected skeleton node");
2739 assert(outer->outcnt() == 2, "only control nodes");
2740 } else {
2741 assert(expect_skeleton == 0 || expect_skeleton == -1, "no skeleton node?");
2742 uint phis = 0;
2743 uint be_loads = 0;
2744 Node* be = inner->in(LoopNode::LoopBackControl);
2745 for (DUIterator_Fast imax, i = inner->fast_outs(imax); i < imax; i++) {
2746 Node* u = inner->fast_out(i);
2747 if (u->is_Phi()) {
2748 phis++;
2749 for (DUIterator_Fast jmax, j = be->fast_outs(jmax); j < jmax; j++) {
2750 Node* n = be->fast_out(j);
2751 if (n->is_Load()) {
2752 assert(n->in(0) == be || n->find_prec_edge(be) > 0, "should be on the backedge");
2753 do {
2754 n = n->raw_out(0);
2755 } while (!n->is_Phi());
2756 if (n == u) {
2757 be_loads++;
2758 break;
2759 }
2760 }
2761 }
2762 }
2763 }
2764 assert(be_loads <= phis, "wrong number phis that depends on a pinned load");
2765 for (DUIterator_Fast imax, i = outer->fast_outs(imax); i < imax; i++) {
2766 Node* u = outer->fast_out(i);
2767 assert(u == outer || u == inner || u->is_Phi(), "nothing between inner and outer loop");
2768 }
2769 uint stores = 0;
2770 for (DUIterator_Fast imax, i = inner_out->fast_outs(imax); i < imax; i++) {
2771 Node* u = inner_out->fast_out(i);
2772 if (u->is_Store()) {
2773 stores++;
2774 }
2775 }
2776 // Late optimization of loads on backedge can cause Phi of outer loop to be eliminated but Phi of inner loop is
2777 // not guaranteed to be optimized out.
2778 assert(outer->outcnt() >= phis + 2 - be_loads && outer->outcnt() <= phis + 2 + stores + 1, "only phis");
2779 }
2780 assert(sfpt->outcnt() == 1, "no data node");
2781 assert(outer_tail->outcnt() == 1 || !has_skeleton, "no data node");
2782 }
2783 }
2784 #endif
2785
2786 //=============================================================================
2787 //------------------------------Ideal------------------------------------------
2788 // Return a node which is more "ideal" than the current node.
2789 // Attempt to convert into a counted-loop.
2790 Node *CountedLoopNode::Ideal(PhaseGVN *phase, bool can_reshape) {
2791 return RegionNode::Ideal(phase, can_reshape);
2792 }
2793
2794 //------------------------------dump_spec--------------------------------------
2795 // Dump special per-node info
2796 #ifndef PRODUCT
2797 void CountedLoopNode::dump_spec(outputStream *st) const {
2798 LoopNode::dump_spec(st);
2799 if (stride_is_con()) {
2800 st->print("stride: %d ",stride_con());
2801 }
2802 if (is_pre_loop ()) st->print("pre of N%d" , _main_idx);
2803 if (is_main_loop()) st->print("main of N%d", _idx);
2804 if (is_post_loop()) st->print("post of N%d", _main_idx);
2805 if (is_strip_mined()) st->print(" strip mined");
2806 if (is_multiversion_fast_loop()) { st->print(" multiversion_fast"); }
2807 if (is_multiversion_slow_loop()) { st->print(" multiversion_slow"); }
2808 if (is_multiversion_delayed_slow_loop()) { st->print(" multiversion_delayed_slow"); }
2809 }
2810 #endif
2811
2812 //=============================================================================
2813 jlong BaseCountedLoopEndNode::stride_con() const {
2814 return stride()->bottom_type()->is_integer(bt())->get_con_as_long(bt());
2815 }
2816
2817
2818 BaseCountedLoopEndNode* BaseCountedLoopEndNode::make(Node* control, Node* test, float prob, float cnt, BasicType bt) {
2819 if (bt == T_INT) {
2820 return new CountedLoopEndNode(control, test, prob, cnt);
2821 }
2822 assert(bt == T_LONG, "unsupported");
2823 return new LongCountedLoopEndNode(control, test, prob, cnt);
2824 }
2825
2826 //=============================================================================
2827 //------------------------------Value-----------------------------------------
2828 const Type* LoopLimitNode::Value(PhaseGVN* phase) const {
2829 const Type* init_t = phase->type(in(Init));
2830 const Type* limit_t = phase->type(in(Limit));
2831 const Type* stride_t = phase->type(in(Stride));
2832 // Either input is TOP ==> the result is TOP
2833 if (init_t == Type::TOP) return Type::TOP;
2834 if (limit_t == Type::TOP) return Type::TOP;
2835 if (stride_t == Type::TOP) return Type::TOP;
2836
2837 int stride_con = stride_t->is_int()->get_con();
2838 if (stride_con == 1)
2839 return bottom_type(); // Identity
2840
2841 if (init_t->is_int()->is_con() && limit_t->is_int()->is_con()) {
2842 // Use jlongs to avoid integer overflow.
2843 jlong init_con = init_t->is_int()->get_con();
2844 jlong limit_con = limit_t->is_int()->get_con();
2845 int stride_m = stride_con - (stride_con > 0 ? 1 : -1);
2846 jlong trip_count = (limit_con - init_con + stride_m)/stride_con;
2847 jlong final_con = init_con + stride_con*trip_count;
2848 int final_int = (int)final_con;
2849 // The final value should be in integer range in almost all cases,
2850 // since the loop is counted and the limit was checked for overflow.
2851 // There some exceptions, for example:
2852 // - During CCP, there might be a temporary overflow from PhiNodes, see JDK-8309266.
2853 // - During PhaseIdealLoop::split_thru_phi, the LoopLimitNode floats possibly far above
2854 // the loop and its predicates, and we might get constants on one side of the phi that
2855 // would lead to overflows. Such a code path would never lead us to enter the loop
2856 // because of the loop limit overflow check that happens after the LoopLimitNode
2857 // computation with overflow, but before we enter the loop, see JDK-8335747.
2858 if (final_con == (jlong)final_int) {
2859 return TypeInt::make(final_int);
2860 } else {
2861 return bottom_type();
2862 }
2863 }
2864
2865 return bottom_type(); // TypeInt::INT
2866 }
2867
2868 //------------------------------Ideal------------------------------------------
2869 // Return a node which is more "ideal" than the current node.
2870 Node *LoopLimitNode::Ideal(PhaseGVN *phase, bool can_reshape) {
2871 if (phase->type(in(Init)) == Type::TOP ||
2872 phase->type(in(Limit)) == Type::TOP ||
2873 phase->type(in(Stride)) == Type::TOP)
2874 return nullptr; // Dead
2875
2876 int stride_con = phase->type(in(Stride))->is_int()->get_con();
2877 if (stride_con == 1)
2878 return nullptr; // Identity
2879
2880 // Delay following optimizations until all loop optimizations
2881 // done to keep Ideal graph simple.
2882 if (!can_reshape || !phase->C->post_loop_opts_phase()) {
2883 phase->C->record_for_post_loop_opts_igvn(this);
2884 return nullptr;
2885 }
2886
2887 const TypeInt* init_t = phase->type(in(Init) )->is_int();
2888 const TypeInt* limit_t = phase->type(in(Limit))->is_int();
2889 jlong stride_p;
2890 jlong lim, ini;
2891 julong max;
2892 if (stride_con > 0) {
2893 stride_p = stride_con;
2894 lim = limit_t->_hi;
2895 ini = init_t->_lo;
2896 max = (julong)max_jint;
2897 } else {
2898 stride_p = -(jlong)stride_con;
2899 lim = init_t->_hi;
2900 ini = limit_t->_lo;
2901 max = (julong)(juint)min_jint; // double cast to get 0x0000000080000000, not 0xffffffff80000000
2902 }
2903 julong range = lim - ini + stride_p;
2904 if (range <= max) {
2905 // Convert to integer expression if it is not overflow.
2906 Node* stride_m = phase->intcon(stride_con - (stride_con > 0 ? 1 : -1));
2907 Node *range = phase->transform(new SubINode(in(Limit), in(Init)));
2908 Node *bias = phase->transform(new AddINode(range, stride_m));
2909 Node *trip = phase->transform(new DivINode(nullptr, bias, in(Stride)));
2910 Node *span = phase->transform(new MulINode(trip, in(Stride)));
2911 return new AddINode(span, in(Init)); // exact limit
2912 }
2913
2914 if (is_power_of_2(stride_p) || // divisor is 2^n
2915 !Matcher::has_match_rule(Op_LoopLimit)) { // or no specialized Mach node?
2916 // Convert to long expression to avoid integer overflow
2917 // and let igvn optimizer convert this division.
2918 //
2919 Node* init = phase->transform( new ConvI2LNode(in(Init)));
2920 Node* limit = phase->transform( new ConvI2LNode(in(Limit)));
2921 Node* stride = phase->longcon(stride_con);
2922 Node* stride_m = phase->longcon(stride_con - (stride_con > 0 ? 1 : -1));
2923
2924 Node *range = phase->transform(new SubLNode(limit, init));
2925 Node *bias = phase->transform(new AddLNode(range, stride_m));
2926 Node *span;
2927 if (stride_con > 0 && is_power_of_2(stride_p)) {
2928 // bias >= 0 if stride >0, so if stride is 2^n we can use &(-stride)
2929 // and avoid generating rounding for division. Zero trip guard should
2930 // guarantee that init < limit but sometimes the guard is missing and
2931 // we can get situation when init > limit. Note, for the empty loop
2932 // optimization zero trip guard is generated explicitly which leaves
2933 // only RCE predicate where exact limit is used and the predicate
2934 // will simply fail forcing recompilation.
2935 Node* neg_stride = phase->longcon(-stride_con);
2936 span = phase->transform(new AndLNode(bias, neg_stride));
2937 } else {
2938 Node *trip = phase->transform(new DivLNode(nullptr, bias, stride));
2939 span = phase->transform(new MulLNode(trip, stride));
2940 }
2941 // Convert back to int
2942 Node *span_int = phase->transform(new ConvL2INode(span));
2943 return new AddINode(span_int, in(Init)); // exact limit
2944 }
2945
2946 return nullptr; // No progress
2947 }
2948
2949 //------------------------------Identity---------------------------------------
2950 // If stride == 1 return limit node.
2951 Node* LoopLimitNode::Identity(PhaseGVN* phase) {
2952 int stride_con = phase->type(in(Stride))->is_int()->get_con();
2953 if (stride_con == 1 || stride_con == -1)
2954 return in(Limit);
2955 return this;
2956 }
2957
2958 //=============================================================================
2959 //----------------------match_incr_with_optional_truncation--------------------
2960 // Match increment with optional truncation:
2961 // CHAR: (i+1)&0x7fff, BYTE: ((i+1)<<8)>>8, or SHORT: ((i+1)<<16)>>16
2962 // Return null for failure. Success returns the increment node.
2963 Node* CountedLoopNode::match_incr_with_optional_truncation(Node* expr, Node** trunc1, Node** trunc2,
2964 const TypeInteger** trunc_type,
2965 BasicType bt) {
2966 // Quick cutouts:
2967 if (expr == nullptr || expr->req() != 3) return nullptr;
2968
2969 Node *t1 = nullptr;
2970 Node *t2 = nullptr;
2971 Node* n1 = expr;
2972 int n1op = n1->Opcode();
2973 const TypeInteger* trunc_t = TypeInteger::bottom(bt);
2974
2975 if (bt == T_INT) {
2976 // Try to strip (n1 & M) or (n1 << N >> N) from n1.
2977 if (n1op == Op_AndI &&
2978 n1->in(2)->is_Con() &&
2979 n1->in(2)->bottom_type()->is_int()->get_con() == 0x7fff) {
2980 // %%% This check should match any mask of 2**K-1.
2981 t1 = n1;
2982 n1 = t1->in(1);
2983 n1op = n1->Opcode();
2984 trunc_t = TypeInt::CHAR;
2985 } else if (n1op == Op_RShiftI &&
2986 n1->in(1) != nullptr &&
2987 n1->in(1)->Opcode() == Op_LShiftI &&
2988 n1->in(2) == n1->in(1)->in(2) &&
2989 n1->in(2)->is_Con()) {
2990 jint shift = n1->in(2)->bottom_type()->is_int()->get_con();
2991 // %%% This check should match any shift in [1..31].
2992 if (shift == 16 || shift == 8) {
2993 t1 = n1;
2994 t2 = t1->in(1);
2995 n1 = t2->in(1);
2996 n1op = n1->Opcode();
2997 if (shift == 16) {
2998 trunc_t = TypeInt::SHORT;
2999 } else if (shift == 8) {
3000 trunc_t = TypeInt::BYTE;
3001 }
3002 }
3003 }
3004 }
3005
3006 // If (maybe after stripping) it is an AddI, we won:
3007 if (n1op == Op_Add(bt)) {
3008 *trunc1 = t1;
3009 *trunc2 = t2;
3010 *trunc_type = trunc_t;
3011 return n1;
3012 }
3013
3014 // failed
3015 return nullptr;
3016 }
3017
3018 IfNode* CountedLoopNode::find_multiversion_if_from_multiversion_fast_main_loop() {
3019 assert(is_main_loop() && is_multiversion_fast_loop(), "must be multiversion fast main loop");
3020 CountedLoopEndNode* pre_end = find_pre_loop_end();
3021 if (pre_end == nullptr) { return nullptr; }
3022 Node* pre_entry = pre_end->loopnode()->in(LoopNode::EntryControl);
3023 const Predicates predicates(pre_entry);
3024 IfTrueNode* before_predicates = predicates.entry()->isa_IfTrue();
3025 if (before_predicates != nullptr &&
3026 before_predicates->in(0)->in(1)->is_OpaqueMultiversioning()) {
3027 return before_predicates->in(0)->as_If();
3028 }
3029 return nullptr;
3030 }
3031
3032 LoopNode* CountedLoopNode::skip_strip_mined(int expect_skeleton) {
3033 if (is_strip_mined() && in(EntryControl) != nullptr && in(EntryControl)->is_OuterStripMinedLoop()) {
3034 verify_strip_mined(expect_skeleton);
3035 return in(EntryControl)->as_Loop();
3036 }
3037 return this;
3038 }
3039
3040 OuterStripMinedLoopNode* CountedLoopNode::outer_loop() const {
3041 assert(is_strip_mined(), "not a strip mined loop");
3042 Node* c = in(EntryControl);
3043 if (c == nullptr || c->is_top() || !c->is_OuterStripMinedLoop()) {
3044 return nullptr;
3045 }
3046 return c->as_OuterStripMinedLoop();
3047 }
3048
3049 IfTrueNode* OuterStripMinedLoopNode::outer_loop_tail() const {
3050 Node* c = in(LoopBackControl);
3051 if (c == nullptr || c->is_top()) {
3052 return nullptr;
3053 }
3054 return c->as_IfTrue();
3055 }
3056
3057 IfTrueNode* CountedLoopNode::outer_loop_tail() const {
3058 LoopNode* l = outer_loop();
3059 if (l == nullptr) {
3060 return nullptr;
3061 }
3062 return l->outer_loop_tail();
3063 }
3064
3065 OuterStripMinedLoopEndNode* OuterStripMinedLoopNode::outer_loop_end() const {
3066 IfTrueNode* proj = outer_loop_tail();
3067 if (proj == nullptr) {
3068 return nullptr;
3069 }
3070 Node* c = proj->in(0);
3071 if (c == nullptr || c->is_top() || c->outcnt() != 2) {
3072 return nullptr;
3073 }
3074 return c->as_OuterStripMinedLoopEnd();
3075 }
3076
3077 OuterStripMinedLoopEndNode* CountedLoopNode::outer_loop_end() const {
3078 LoopNode* l = outer_loop();
3079 if (l == nullptr) {
3080 return nullptr;
3081 }
3082 return l->outer_loop_end();
3083 }
3084
3085 IfFalseNode* OuterStripMinedLoopNode::outer_loop_exit() const {
3086 IfNode* le = outer_loop_end();
3087 if (le == nullptr) {
3088 return nullptr;
3089 }
3090 Node* c = le->proj_out_or_null(false);
3091 if (c == nullptr) {
3092 return nullptr;
3093 }
3094 return c->as_IfFalse();
3095 }
3096
3097 IfFalseNode* CountedLoopNode::outer_loop_exit() const {
3098 LoopNode* l = outer_loop();
3099 if (l == nullptr) {
3100 return nullptr;
3101 }
3102 return l->outer_loop_exit();
3103 }
3104
3105 SafePointNode* OuterStripMinedLoopNode::outer_safepoint() const {
3106 IfNode* le = outer_loop_end();
3107 if (le == nullptr) {
3108 return nullptr;
3109 }
3110 Node* c = le->in(0);
3111 if (c == nullptr || c->is_top()) {
3112 return nullptr;
3113 }
3114 assert(c->Opcode() == Op_SafePoint, "broken outer loop");
3115 return c->as_SafePoint();
3116 }
3117
3118 SafePointNode* CountedLoopNode::outer_safepoint() const {
3119 LoopNode* l = outer_loop();
3120 if (l == nullptr) {
3121 return nullptr;
3122 }
3123 return l->outer_safepoint();
3124 }
3125
3126 Node* CountedLoopNode::skip_assertion_predicates_with_halt() {
3127 Node* ctrl = in(LoopNode::EntryControl);
3128 if (ctrl == nullptr) {
3129 // Dying loop.
3130 return nullptr;
3131 }
3132 if (is_main_loop()) {
3133 ctrl = skip_strip_mined()->in(LoopNode::EntryControl);
3134 }
3135 if (is_main_loop() || is_post_loop()) {
3136 AssertionPredicates assertion_predicates(ctrl);
3137 return assertion_predicates.entry();
3138 }
3139 return ctrl;
3140 }
3141
3142
3143 int CountedLoopNode::stride_con() const {
3144 CountedLoopEndNode* cle = loopexit_or_null();
3145 return cle != nullptr ? cle->stride_con() : 0;
3146 }
3147
3148 BaseCountedLoopNode* BaseCountedLoopNode::make(Node* entry, Node* backedge, BasicType bt) {
3149 if (bt == T_INT) {
3150 return new CountedLoopNode(entry, backedge);
3151 }
3152 assert(bt == T_LONG, "unsupported");
3153 return new LongCountedLoopNode(entry, backedge);
3154 }
3155
3156 void OuterStripMinedLoopNode::fix_sunk_stores_when_back_to_counted_loop(PhaseIterGVN* igvn,
3157 PhaseIdealLoop* iloop) const {
3158 CountedLoopNode* inner_cl = inner_counted_loop();
3159 IfFalseNode* cle_out = inner_loop_exit();
3160
3161 if (cle_out->outcnt() > 1) {
3162 // Look for chains of stores that were sunk
3163 // out of the inner loop and are in the outer loop
3164 for (DUIterator_Fast imax, i = cle_out->fast_outs(imax); i < imax; i++) {
3165 Node* u = cle_out->fast_out(i);
3166 if (u->is_Store()) {
3167 int alias_idx = igvn->C->get_alias_index(u->adr_type());
3168 Node* first = u;
3169 for (;;) {
3170 Node* next = first->in(MemNode::Memory);
3171 if (!next->is_Store() || next->in(0) != cle_out) {
3172 break;
3173 }
3174 assert(igvn->C->get_alias_index(next->adr_type()) == alias_idx, "");
3175 first = next;
3176 }
3177 Node* last = u;
3178 for (;;) {
3179 Node* next = nullptr;
3180 for (DUIterator_Fast jmax, j = last->fast_outs(jmax); j < jmax; j++) {
3181 Node* uu = last->fast_out(j);
3182 if (uu->is_Store() && uu->in(0) == cle_out) {
3183 assert(next == nullptr, "only one in the outer loop");
3184 next = uu;
3185 assert(igvn->C->get_alias_index(next->adr_type()) == alias_idx, "");
3186 }
3187 }
3188 if (next == nullptr) {
3189 break;
3190 }
3191 last = next;
3192 }
3193 Node* phi = nullptr;
3194 for (DUIterator_Fast jmax, j = inner_cl->fast_outs(jmax); j < jmax; j++) {
3195 Node* uu = inner_cl->fast_out(j);
3196 if (uu->is_Phi()) {
3197 Node* be = uu->in(LoopNode::LoopBackControl);
3198 if (be->is_Store() && be->in(0) == inner_cl->in(LoopNode::LoopBackControl)) {
3199 assert(igvn->C->get_alias_index(uu->adr_type()) != alias_idx && igvn->C->get_alias_index(uu->adr_type()) != Compile::AliasIdxBot, "unexpected store");
3200 }
3201 if (be == last || be == first->in(MemNode::Memory)) {
3202 assert(igvn->C->get_alias_index(uu->adr_type()) == alias_idx || igvn->C->get_alias_index(uu->adr_type()) == Compile::AliasIdxBot, "unexpected alias");
3203 assert(phi == nullptr, "only one phi");
3204 phi = uu;
3205 }
3206 }
3207 }
3208 #ifdef ASSERT
3209 for (DUIterator_Fast jmax, j = inner_cl->fast_outs(jmax); j < jmax; j++) {
3210 Node* uu = inner_cl->fast_out(j);
3211 if (uu->is_memory_phi()) {
3212 if (uu->adr_type() == igvn->C->get_adr_type(igvn->C->get_alias_index(u->adr_type()))) {
3213 assert(phi == uu, "what's that phi?");
3214 } else if (uu->adr_type() == TypePtr::BOTTOM) {
3215 Node* n = uu->in(LoopNode::LoopBackControl);
3216 uint limit = igvn->C->live_nodes();
3217 uint i = 0;
3218 while (n != uu) {
3219 i++;
3220 assert(i < limit, "infinite loop");
3221 if (n->is_Proj()) {
3222 n = n->in(0);
3223 } else if (n->is_SafePoint() || n->is_MemBar()) {
3224 n = n->in(TypeFunc::Memory);
3225 } else if (n->is_Phi()) {
3226 n = n->in(1);
3227 } else if (n->is_MergeMem()) {
3228 n = n->as_MergeMem()->memory_at(igvn->C->get_alias_index(u->adr_type()));
3229 } else if (n->is_Store() || n->is_LoadStore() || n->is_ClearArray()) {
3230 n = n->in(MemNode::Memory);
3231 } else {
3232 n->dump();
3233 ShouldNotReachHere();
3234 }
3235 }
3236 }
3237 }
3238 }
3239 #endif
3240 if (phi == nullptr) {
3241 // If an entire chains was sunk, the
3242 // inner loop has no phi for that memory
3243 // slice, create one for the outer loop
3244 phi = PhiNode::make(inner_cl, first->in(MemNode::Memory), Type::MEMORY,
3245 igvn->C->get_adr_type(igvn->C->get_alias_index(u->adr_type())));
3246 phi->set_req(LoopNode::LoopBackControl, last);
3247 phi = register_new_node(phi, inner_cl, igvn, iloop);
3248 igvn->replace_input_of(first, MemNode::Memory, phi);
3249 } else {
3250 // Or fix the outer loop fix to include
3251 // that chain of stores.
3252 Node* be = phi->in(LoopNode::LoopBackControl);
3253 assert(!(be->is_Store() && be->in(0) == inner_cl->in(LoopNode::LoopBackControl)), "store on the backedge + sunk stores: unsupported");
3254 if (be == first->in(MemNode::Memory)) {
3255 if (be == phi->in(LoopNode::LoopBackControl)) {
3256 igvn->replace_input_of(phi, LoopNode::LoopBackControl, last);
3257 } else {
3258 igvn->replace_input_of(be, MemNode::Memory, last);
3259 }
3260 } else {
3261 #ifdef ASSERT
3262 if (be == phi->in(LoopNode::LoopBackControl)) {
3263 assert(phi->in(LoopNode::LoopBackControl) == last, "");
3264 } else {
3265 assert(be->in(MemNode::Memory) == last, "");
3266 }
3267 #endif
3268 }
3269 }
3270 }
3271 }
3272 }
3273 }
3274
3275 // The outer strip mined loop is initially only partially constructed. In particular Phis are omitted.
3276 // See comment above: PhaseIdealLoop::create_outer_strip_mined_loop()
3277 // We're now in the process of finishing the construction of the outer loop. For each Phi in the inner loop, a Phi in
3278 // the outer loop was just now created. However, Sunk Stores cause an extra challenge:
3279 // 1) If all Stores in the inner loop were sunk for a particular memory slice, there's no Phi left for that memory slice
3280 // in the inner loop anymore, and hence we did not yet add a Phi for the outer loop. So an extra Phi must now be
3281 // added for each chain of sunk Stores for a particular memory slice.
3282 // 2) If some Stores were sunk and some left in the inner loop, a Phi was already created in the outer loop but
3283 // its backedge input wasn't wired correctly to the last Store of the chain: the backedge input was set to the
3284 // backedge of the inner loop Phi instead, but it needs to be the last Store of the chain in the outer loop. We now
3285 // have to fix that too.
3286 void OuterStripMinedLoopNode::handle_sunk_stores_when_finishing_construction(PhaseIterGVN* igvn) {
3287 IfFalseNode* cle_exit_proj = inner_loop_exit();
3288
3289 // Find Sunk stores: Sunk stores are pinned on the loop exit projection of the inner loop. Indeed, because Sunk Stores
3290 // modify the memory state captured by the SafePoint in the outer strip mined loop, they must be above it. The
3291 // SafePoint's control input is the loop exit projection. It's also the only control out of the inner loop above the
3292 // SafePoint.
3293 #ifdef ASSERT
3294 int stores_in_outer_loop_cnt = 0;
3295 for (DUIterator_Fast imax, i = cle_exit_proj->fast_outs(imax); i < imax; i++) {
3296 Node* u = cle_exit_proj->fast_out(i);
3297 if (u->is_Store()) {
3298 stores_in_outer_loop_cnt++;
3299 }
3300 }
3301 #endif
3302
3303 // Sunk stores are reachable from the memory state of the outer loop safepoint
3304 SafePointNode* safepoint = outer_safepoint();
3305 MergeMemNode* mm = safepoint->in(TypeFunc::Memory)->isa_MergeMem();
3306 if (mm == nullptr) {
3307 // There is no MergeMem, which should only happen if there was no memory node
3308 // sunk out of the loop.
3309 assert(stores_in_outer_loop_cnt == 0, "inconsistent");
3310 return;
3311 }
3312 DEBUG_ONLY(int stores_in_outer_loop_cnt2 = 0);
3313 for (MergeMemStream mms(mm); mms.next_non_empty();) {
3314 Node* mem = mms.memory();
3315 // Traverse up the chain of stores to find the first store pinned
3316 // at the loop exit projection.
3317 Node* last = mem;
3318 Node* first = nullptr;
3319 while (mem->is_Store() && mem->in(0) == cle_exit_proj) {
3320 DEBUG_ONLY(stores_in_outer_loop_cnt2++);
3321 first = mem;
3322 mem = mem->in(MemNode::Memory);
3323 }
3324 if (first != nullptr) {
3325 // Found a chain of Stores that were sunk
3326 // Do we already have a memory Phi for that slice on the outer loop? If that is the case, that Phi was created
3327 // by cloning an inner loop Phi. The inner loop Phi should have mem, the memory state of the first Store out of
3328 // the inner loop, as input on the backedge. So does the outer loop Phi given it's a clone.
3329 Node* phi = nullptr;
3330 for (DUIterator_Fast imax, i = mem->fast_outs(imax); i < imax; i++) {
3331 Node* u = mem->fast_out(i);
3332 if (u->is_Phi() && u->in(0) == this && u->in(LoopBackControl) == mem) {
3333 assert(phi == nullptr, "there should be only one");
3334 phi = u;
3335 PRODUCT_ONLY(break);
3336 }
3337 }
3338 if (phi == nullptr) {
3339 // No outer loop Phi? create one
3340 phi = PhiNode::make(this, last);
3341 phi->set_req(EntryControl, mem);
3342 phi = igvn->transform(phi);
3343 igvn->replace_input_of(first, MemNode::Memory, phi);
3344 } else {
3345 // Fix memory state along the backedge: it should be the last sunk Store of the chain
3346 igvn->replace_input_of(phi, LoopBackControl, last);
3347 }
3348 }
3349 }
3350 assert(stores_in_outer_loop_cnt == stores_in_outer_loop_cnt2, "inconsistent");
3351 }
3352
3353 void OuterStripMinedLoopNode::adjust_strip_mined_loop(PhaseIterGVN* igvn) {
3354 verify_strip_mined(1);
3355 // Look for the outer & inner strip mined loop, reduce number of
3356 // iterations of the inner loop, set exit condition of outer loop,
3357 // construct required phi nodes for outer loop.
3358 CountedLoopNode* inner_cl = inner_counted_loop();
3359 assert(inner_cl->is_strip_mined(), "inner loop should be strip mined");
3360 if (LoopStripMiningIter == 0) {
3361 remove_outer_loop_and_safepoint(igvn);
3362 return;
3363 }
3364 if (LoopStripMiningIter == 1) {
3365 transform_to_counted_loop(igvn, nullptr);
3366 return;
3367 }
3368 Node* inner_iv_phi = inner_cl->phi();
3369 if (inner_iv_phi == nullptr) {
3370 IfNode* outer_le = outer_loop_end();
3371 Node* iff = igvn->transform(new IfNode(outer_le->in(0), outer_le->in(1), outer_le->_prob, outer_le->_fcnt));
3372 igvn->replace_node(outer_le, iff);
3373 inner_cl->clear_strip_mined();
3374 return;
3375 }
3376 CountedLoopEndNode* inner_cle = inner_counted_loop_end();
3377
3378 int stride = inner_cl->stride_con();
3379 // For a min int stride, LoopStripMiningIter * stride overflows the int range for all values of LoopStripMiningIter
3380 // except 0 or 1. Those values are handled early on in this method and causes the method to return. So for a min int
3381 // stride, the method is guaranteed to return at the next check below.
3382 jlong scaled_iters_long = ((jlong)LoopStripMiningIter) * ABS((jlong)stride);
3383 int scaled_iters = (int)scaled_iters_long;
3384 if ((jlong)scaled_iters != scaled_iters_long) {
3385 // Remove outer loop and safepoint (too few iterations)
3386 remove_outer_loop_and_safepoint(igvn);
3387 return;
3388 }
3389 jlong short_scaled_iters = LoopStripMiningIterShortLoop * ABS(stride);
3390 const TypeInt* inner_iv_t = igvn->type(inner_iv_phi)->is_int();
3391 jlong iter_estimate = (jlong)inner_iv_t->_hi - (jlong)inner_iv_t->_lo;
3392 assert(iter_estimate > 0, "broken");
3393 if (iter_estimate <= short_scaled_iters) {
3394 // Remove outer loop and safepoint: loop executes less than LoopStripMiningIterShortLoop
3395 remove_outer_loop_and_safepoint(igvn);
3396 return;
3397 }
3398 if (iter_estimate <= scaled_iters_long) {
3399 // We would only go through one iteration of
3400 // the outer loop: drop the outer loop but
3401 // keep the safepoint so we don't run for
3402 // too long without a safepoint
3403 IfNode* outer_le = outer_loop_end();
3404 Node* iff = igvn->transform(new IfNode(outer_le->in(0), outer_le->in(1), outer_le->_prob, outer_le->_fcnt));
3405 igvn->replace_node(outer_le, iff);
3406 inner_cl->clear_strip_mined();
3407 return;
3408 }
3409
3410 Node* cle_tail = inner_cle->proj_out(true);
3411 ResourceMark rm;
3412 Node_List old_new;
3413 if (cle_tail->outcnt() > 1) {
3414 // Look for nodes on backedge of inner loop and clone them
3415 Unique_Node_List backedge_nodes;
3416 for (DUIterator_Fast imax, i = cle_tail->fast_outs(imax); i < imax; i++) {
3417 Node* u = cle_tail->fast_out(i);
3418 if (u != inner_cl) {
3419 assert(!u->is_CFG(), "control flow on the backedge?");
3420 backedge_nodes.push(u);
3421 }
3422 }
3423 uint last = igvn->C->unique();
3424 for (uint next = 0; next < backedge_nodes.size(); next++) {
3425 Node* n = backedge_nodes.at(next);
3426 old_new.map(n->_idx, n->clone());
3427 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
3428 Node* u = n->fast_out(i);
3429 assert(!u->is_CFG(), "broken");
3430 if (u->_idx >= last) {
3431 continue;
3432 }
3433 if (!u->is_Phi()) {
3434 backedge_nodes.push(u);
3435 } else {
3436 assert(u->in(0) == inner_cl, "strange phi on the backedge");
3437 }
3438 }
3439 }
3440 // Put the clones on the outer loop backedge
3441 Node* le_tail = outer_loop_tail();
3442 for (uint next = 0; next < backedge_nodes.size(); next++) {
3443 Node *n = old_new[backedge_nodes.at(next)->_idx];
3444 for (uint i = 1; i < n->req(); i++) {
3445 if (n->in(i) != nullptr && old_new[n->in(i)->_idx] != nullptr) {
3446 n->set_req(i, old_new[n->in(i)->_idx]);
3447 }
3448 }
3449 if (n->in(0) != nullptr && n->in(0) == cle_tail) {
3450 n->set_req(0, le_tail);
3451 }
3452 igvn->register_new_node_with_optimizer(n);
3453 }
3454 }
3455
3456 Node* iv_phi = nullptr;
3457 // Make a clone of each phi in the inner loop for the outer loop
3458 // When Stores were Sunk, after this step, a Phi may still be missing or its backedge incorrectly wired. See
3459 // handle_sunk_stores_when_finishing_construction()
3460 for (uint i = 0; i < inner_cl->outcnt(); i++) {
3461 Node* u = inner_cl->raw_out(i);
3462 if (u->is_Phi()) {
3463 assert(u->in(0) == inner_cl, "inconsistent");
3464 Node* phi = u->clone();
3465 phi->set_req(0, this);
3466 Node* be = old_new[phi->in(LoopNode::LoopBackControl)->_idx];
3467 if (be != nullptr) {
3468 phi->set_req(LoopNode::LoopBackControl, be);
3469 }
3470 phi = igvn->transform(phi);
3471 igvn->replace_input_of(u, LoopNode::EntryControl, phi);
3472 if (u == inner_iv_phi) {
3473 iv_phi = phi;
3474 }
3475 }
3476 }
3477
3478 handle_sunk_stores_when_finishing_construction(igvn);
3479
3480 if (iv_phi != nullptr) {
3481 // Now adjust the inner loop's exit condition
3482 Node* limit = inner_cl->limit();
3483 // If limit < init for stride > 0 (or limit > init for stride < 0),
3484 // the loop body is run only once. Given limit - init (init - limit resp.)
3485 // would be negative, the unsigned comparison below would cause
3486 // the loop body to be run for LoopStripMiningIter.
3487 Node* max = nullptr;
3488 if (stride > 0) {
3489 max = MaxNode::max_diff_with_zero(limit, iv_phi, TypeInt::INT, *igvn);
3490 } else {
3491 max = MaxNode::max_diff_with_zero(iv_phi, limit, TypeInt::INT, *igvn);
3492 }
3493 // sub is positive and can be larger than the max signed int
3494 // value. Use an unsigned min.
3495 Node* const_iters = igvn->intcon(scaled_iters);
3496 Node* min = MaxNode::unsigned_min(max, const_iters, TypeInt::make(0, scaled_iters, Type::WidenMin), *igvn);
3497 // min is the number of iterations for the next inner loop execution:
3498 // unsigned_min(max(limit - iv_phi, 0), scaled_iters) if stride > 0
3499 // unsigned_min(max(iv_phi - limit, 0), scaled_iters) if stride < 0
3500
3501 Node* new_limit = nullptr;
3502 if (stride > 0) {
3503 new_limit = igvn->transform(new AddINode(min, iv_phi));
3504 } else {
3505 new_limit = igvn->transform(new SubINode(iv_phi, min));
3506 }
3507 Node* inner_cmp = inner_cle->cmp_node();
3508 Node* inner_bol = inner_cle->in(CountedLoopEndNode::TestValue);
3509 Node* outer_bol = inner_bol;
3510 // cmp node for inner loop may be shared
3511 inner_cmp = inner_cmp->clone();
3512 inner_cmp->set_req(2, new_limit);
3513 inner_bol = inner_bol->clone();
3514 inner_bol->set_req(1, igvn->transform(inner_cmp));
3515 igvn->replace_input_of(inner_cle, CountedLoopEndNode::TestValue, igvn->transform(inner_bol));
3516 // Set the outer loop's exit condition too
3517 igvn->replace_input_of(outer_loop_end(), 1, outer_bol);
3518 } else {
3519 assert(false, "should be able to adjust outer loop");
3520 IfNode* outer_le = outer_loop_end();
3521 Node* iff = igvn->transform(new IfNode(outer_le->in(0), outer_le->in(1), outer_le->_prob, outer_le->_fcnt));
3522 igvn->replace_node(outer_le, iff);
3523 inner_cl->clear_strip_mined();
3524 }
3525 }
3526
3527 void OuterStripMinedLoopNode::transform_to_counted_loop(PhaseIterGVN* igvn, PhaseIdealLoop* iloop) {
3528 CountedLoopNode* inner_cl = unique_ctrl_out()->as_CountedLoop();
3529 CountedLoopEndNode* cle = inner_cl->loopexit();
3530 Node* inner_test = cle->in(1);
3531 IfNode* outer_le = outer_loop_end();
3532 CountedLoopEndNode* inner_cle = inner_cl->loopexit();
3533 Node* safepoint = outer_safepoint();
3534
3535 fix_sunk_stores_when_back_to_counted_loop(igvn, iloop);
3536
3537 // make counted loop exit test always fail
3538 ConINode* zero = igvn->intcon(0);
3539 if (iloop != nullptr) {
3540 iloop->set_root_as_ctrl(zero);
3541 }
3542 igvn->replace_input_of(cle, 1, zero);
3543 // replace outer loop end with CountedLoopEndNode with formers' CLE's exit test
3544 Node* new_end = new CountedLoopEndNode(outer_le->in(0), inner_test, cle->_prob, cle->_fcnt);
3545 register_control(new_end, inner_cl, outer_le->in(0), igvn, iloop);
3546 if (iloop == nullptr) {
3547 igvn->replace_node(outer_le, new_end);
3548 } else {
3549 iloop->replace_node_and_forward_ctrl(outer_le, new_end);
3550 }
3551 // the backedge of the inner loop must be rewired to the new loop end
3552 Node* backedge = cle->proj_out(true);
3553 igvn->replace_input_of(backedge, 0, new_end);
3554 if (iloop != nullptr) {
3555 iloop->set_idom(backedge, new_end, iloop->dom_depth(new_end) + 1);
3556 }
3557 // make the outer loop go away
3558 igvn->replace_input_of(in(LoopBackControl), 0, igvn->C->top());
3559 igvn->replace_input_of(this, LoopBackControl, igvn->C->top());
3560 inner_cl->clear_strip_mined();
3561 if (iloop != nullptr) {
3562 Unique_Node_List wq;
3563 wq.push(safepoint);
3564
3565 IdealLoopTree* outer_loop_ilt = iloop->get_loop(this);
3566 IdealLoopTree* loop = iloop->get_loop(inner_cl);
3567
3568 for (uint i = 0; i < wq.size(); i++) {
3569 Node* n = wq.at(i);
3570 for (uint j = 0; j < n->req(); ++j) {
3571 Node* in = n->in(j);
3572 if (in == nullptr || in->is_CFG()) {
3573 continue;
3574 }
3575 if (iloop->get_loop(iloop->get_ctrl(in)) != outer_loop_ilt) {
3576 continue;
3577 }
3578 wq.push(in);
3579 }
3580 assert(!loop->_body.contains(n), "Shouldn't append node to body twice");
3581 loop->_body.push(n);
3582 }
3583 iloop->set_loop(safepoint, loop);
3584 loop->_body.push(safepoint);
3585 iloop->set_loop(safepoint->in(0), loop);
3586 loop->_body.push(safepoint->in(0));
3587 outer_loop_ilt->_tail = igvn->C->top();
3588 }
3589 }
3590
3591 void OuterStripMinedLoopNode::remove_outer_loop_and_safepoint(PhaseIterGVN* igvn) const {
3592 CountedLoopNode* inner_cl = unique_ctrl_out()->as_CountedLoop();
3593 Node* outer_sfpt = outer_safepoint();
3594 Node* outer_out = outer_loop_exit();
3595 igvn->replace_node(outer_out, outer_sfpt->in(0));
3596 igvn->replace_input_of(outer_sfpt, 0, igvn->C->top());
3597 inner_cl->clear_strip_mined();
3598 }
3599
3600 Node* OuterStripMinedLoopNode::register_new_node(Node* node, LoopNode* ctrl, PhaseIterGVN* igvn, PhaseIdealLoop* iloop) {
3601 if (iloop == nullptr) {
3602 return igvn->transform(node);
3603 }
3604 iloop->register_new_node(node, ctrl);
3605 return node;
3606 }
3607
3608 Node* OuterStripMinedLoopNode::register_control(Node* node, Node* loop, Node* idom, PhaseIterGVN* igvn,
3609 PhaseIdealLoop* iloop) {
3610 if (iloop == nullptr) {
3611 return igvn->transform(node);
3612 }
3613 iloop->register_control(node, iloop->get_loop(loop), idom);
3614 return node;
3615 }
3616
3617 const Type* OuterStripMinedLoopEndNode::Value(PhaseGVN* phase) const {
3618 if (!in(0)) return Type::TOP;
3619 if (phase->type(in(0)) == Type::TOP)
3620 return Type::TOP;
3621
3622 // Until expansion, the loop end condition is not set so this should not constant fold.
3623 if (is_expanded(phase)) {
3624 return IfNode::Value(phase);
3625 }
3626
3627 return TypeTuple::IFBOTH;
3628 }
3629
3630 bool OuterStripMinedLoopEndNode::is_expanded(PhaseGVN *phase) const {
3631 // The outer strip mined loop head only has Phi uses after expansion
3632 if (phase->is_IterGVN()) {
3633 Node* backedge = proj_out_or_null(true);
3634 if (backedge != nullptr) {
3635 Node* head = backedge->unique_ctrl_out_or_null();
3636 if (head != nullptr && head->is_OuterStripMinedLoop()) {
3637 if (head->find_out_with(Op_Phi) != nullptr) {
3638 return true;
3639 }
3640 }
3641 }
3642 }
3643 return false;
3644 }
3645
3646 Node *OuterStripMinedLoopEndNode::Ideal(PhaseGVN *phase, bool can_reshape) {
3647 if (remove_dead_region(phase, can_reshape)) return this;
3648
3649 return nullptr;
3650 }
3651
3652 //------------------------------filtered_type--------------------------------
3653 // Return a type based on condition control flow
3654 // A successful return will be a type that is restricted due
3655 // to a series of dominating if-tests, such as:
3656 // if (i < 10) {
3657 // if (i > 0) {
3658 // here: "i" type is [1..10)
3659 // }
3660 // }
3661 // or a control flow merge
3662 // if (i < 10) {
3663 // do {
3664 // phi( , ) -- at top of loop type is [min_int..10)
3665 // i = ?
3666 // } while ( i < 10)
3667 //
3668 const TypeInt* PhaseIdealLoop::filtered_type( Node *n, Node* n_ctrl) {
3669 assert(n && n->bottom_type()->is_int(), "must be int");
3670 const TypeInt* filtered_t = nullptr;
3671 if (!n->is_Phi()) {
3672 assert(n_ctrl != nullptr || n_ctrl == C->top(), "valid control");
3673 filtered_t = filtered_type_from_dominators(n, n_ctrl);
3674
3675 } else {
3676 Node* phi = n->as_Phi();
3677 Node* region = phi->in(0);
3678 assert(n_ctrl == nullptr || n_ctrl == region, "ctrl parameter must be region");
3679 if (region && region != C->top()) {
3680 for (uint i = 1; i < phi->req(); i++) {
3681 Node* val = phi->in(i);
3682 Node* use_c = region->in(i);
3683 const TypeInt* val_t = filtered_type_from_dominators(val, use_c);
3684 if (val_t != nullptr) {
3685 if (filtered_t == nullptr) {
3686 filtered_t = val_t;
3687 } else {
3688 filtered_t = filtered_t->meet(val_t)->is_int();
3689 }
3690 }
3691 }
3692 }
3693 }
3694 const TypeInt* n_t = _igvn.type(n)->is_int();
3695 if (filtered_t != nullptr) {
3696 n_t = n_t->join(filtered_t)->is_int();
3697 }
3698 return n_t;
3699 }
3700
3701
3702 //------------------------------filtered_type_from_dominators--------------------------------
3703 // Return a possibly more restrictive type for val based on condition control flow of dominators
3704 const TypeInt* PhaseIdealLoop::filtered_type_from_dominators( Node* val, Node *use_ctrl) {
3705 if (val->is_Con()) {
3706 return val->bottom_type()->is_int();
3707 }
3708 uint if_limit = 10; // Max number of dominating if's visited
3709 const TypeInt* rtn_t = nullptr;
3710
3711 if (use_ctrl && use_ctrl != C->top()) {
3712 Node* val_ctrl = get_ctrl(val);
3713 uint val_dom_depth = dom_depth(val_ctrl);
3714 Node* pred = use_ctrl;
3715 uint if_cnt = 0;
3716 while (if_cnt < if_limit) {
3717 if ((pred->Opcode() == Op_IfTrue || pred->Opcode() == Op_IfFalse)) {
3718 if_cnt++;
3719 const TypeInt* if_t = IfNode::filtered_int_type(&_igvn, val, pred);
3720 if (if_t != nullptr) {
3721 if (rtn_t == nullptr) {
3722 rtn_t = if_t;
3723 } else {
3724 rtn_t = rtn_t->join(if_t)->is_int();
3725 }
3726 }
3727 }
3728 pred = idom(pred);
3729 if (pred == nullptr || pred == C->top()) {
3730 break;
3731 }
3732 // Stop if going beyond definition block of val
3733 if (dom_depth(pred) < val_dom_depth) {
3734 break;
3735 }
3736 }
3737 }
3738 return rtn_t;
3739 }
3740
3741
3742 //------------------------------dump_spec--------------------------------------
3743 // Dump special per-node info
3744 #ifndef PRODUCT
3745 void CountedLoopEndNode::dump_spec(outputStream *st) const {
3746 if( in(TestValue) != nullptr && in(TestValue)->is_Bool() ) {
3747 BoolTest bt( test_trip()); // Added this for g++.
3748
3749 st->print("[");
3750 bt.dump_on(st);
3751 st->print("]");
3752 }
3753 st->print(" ");
3754 IfNode::dump_spec(st);
3755 }
3756 #endif
3757
3758 //=============================================================================
3759 //------------------------------is_member--------------------------------------
3760 // Is 'l' a member of 'this'?
3761 bool IdealLoopTree::is_member(const IdealLoopTree *l) const {
3762 while( l->_nest > _nest ) l = l->_parent;
3763 return l == this;
3764 }
3765
3766 //------------------------------set_nest---------------------------------------
3767 // Set loop tree nesting depth. Accumulate _has_call bits.
3768 int IdealLoopTree::set_nest( uint depth ) {
3769 assert(depth <= SHRT_MAX, "sanity");
3770 _nest = depth;
3771 int bits = _has_call;
3772 if( _child ) bits |= _child->set_nest(depth+1);
3773 if( bits ) _has_call = 1;
3774 if( _next ) bits |= _next ->set_nest(depth );
3775 return bits;
3776 }
3777
3778 //------------------------------split_fall_in----------------------------------
3779 // Split out multiple fall-in edges from the loop header. Move them to a
3780 // private RegionNode before the loop. This becomes the loop landing pad.
3781 void IdealLoopTree::split_fall_in( PhaseIdealLoop *phase, int fall_in_cnt ) {
3782 PhaseIterGVN &igvn = phase->_igvn;
3783 uint i;
3784
3785 // Make a new RegionNode to be the landing pad.
3786 RegionNode* landing_pad = new RegionNode(fall_in_cnt + 1);
3787 phase->set_loop(landing_pad,_parent);
3788 // If _head was irreducible loop entry, landing_pad may now be too
3789 landing_pad->set_loop_status(_head->as_Region()->loop_status());
3790 // Gather all the fall-in control paths into the landing pad
3791 uint icnt = fall_in_cnt;
3792 uint oreq = _head->req();
3793 for( i = oreq-1; i>0; i-- )
3794 if( !phase->is_member( this, _head->in(i) ) )
3795 landing_pad->set_req(icnt--,_head->in(i));
3796
3797 // Peel off PhiNode edges as well
3798 for (DUIterator_Fast jmax, j = _head->fast_outs(jmax); j < jmax; j++) {
3799 Node *oj = _head->fast_out(j);
3800 if( oj->is_Phi() ) {
3801 PhiNode* old_phi = oj->as_Phi();
3802 assert( old_phi->region() == _head, "" );
3803 igvn.hash_delete(old_phi); // Yank from hash before hacking edges
3804 Node *p = PhiNode::make_blank(landing_pad, old_phi);
3805 uint icnt = fall_in_cnt;
3806 for( i = oreq-1; i>0; i-- ) {
3807 if( !phase->is_member( this, _head->in(i) ) ) {
3808 p->init_req(icnt--, old_phi->in(i));
3809 // Go ahead and clean out old edges from old phi
3810 old_phi->del_req(i);
3811 }
3812 }
3813 // Search for CSE's here, because ZKM.jar does a lot of
3814 // loop hackery and we need to be a little incremental
3815 // with the CSE to avoid O(N^2) node blow-up.
3816 Node *p2 = igvn.hash_find_insert(p); // Look for a CSE
3817 if( p2 ) { // Found CSE
3818 p->destruct(&igvn); // Recover useless new node
3819 p = p2; // Use old node
3820 } else {
3821 igvn.register_new_node_with_optimizer(p, old_phi);
3822 }
3823 // Make old Phi refer to new Phi.
3824 old_phi->add_req(p);
3825 // Check for the special case of making the old phi useless and
3826 // disappear it. In JavaGrande I have a case where this useless
3827 // Phi is the loop limit and prevents recognizing a CountedLoop
3828 // which in turn prevents removing an empty loop.
3829 Node *id_old_phi = old_phi->Identity(&igvn);
3830 if( id_old_phi != old_phi ) { // Found a simple identity?
3831 // Note that I cannot call 'replace_node' here, because
3832 // that will yank the edge from old_phi to the Region and
3833 // I'm mid-iteration over the Region's uses.
3834 for (DUIterator_Last imin, i = old_phi->last_outs(imin); i >= imin; ) {
3835 Node* use = old_phi->last_out(i);
3836 igvn.rehash_node_delayed(use);
3837 uint uses_found = 0;
3838 for (uint j = 0; j < use->len(); j++) {
3839 if (use->in(j) == old_phi) {
3840 if (j < use->req()) use->set_req (j, id_old_phi);
3841 else use->set_prec(j, id_old_phi);
3842 uses_found++;
3843 }
3844 }
3845 i -= uses_found; // we deleted 1 or more copies of this edge
3846 }
3847 }
3848 igvn._worklist.push(old_phi);
3849 }
3850 }
3851 // Finally clean out the fall-in edges from the RegionNode
3852 for( i = oreq-1; i>0; i-- ) {
3853 if( !phase->is_member( this, _head->in(i) ) ) {
3854 _head->del_req(i);
3855 }
3856 }
3857 igvn.rehash_node_delayed(_head);
3858 // Transform landing pad
3859 igvn.register_new_node_with_optimizer(landing_pad, _head);
3860 // Insert landing pad into the header
3861 _head->add_req(landing_pad);
3862 }
3863
3864 //------------------------------split_outer_loop-------------------------------
3865 // Split out the outermost loop from this shared header.
3866 void IdealLoopTree::split_outer_loop( PhaseIdealLoop *phase ) {
3867 PhaseIterGVN &igvn = phase->_igvn;
3868
3869 // Find index of outermost loop; it should also be my tail.
3870 uint outer_idx = 1;
3871 while( _head->in(outer_idx) != _tail ) outer_idx++;
3872
3873 // Make a LoopNode for the outermost loop.
3874 Node *ctl = _head->in(LoopNode::EntryControl);
3875 Node *outer = new LoopNode( ctl, _head->in(outer_idx) );
3876 outer = igvn.register_new_node_with_optimizer(outer, _head);
3877 phase->set_created_loop_node();
3878
3879 // Outermost loop falls into '_head' loop
3880 _head->set_req(LoopNode::EntryControl, outer);
3881 _head->del_req(outer_idx);
3882 // Split all the Phis up between '_head' loop and 'outer' loop.
3883 for (DUIterator_Fast jmax, j = _head->fast_outs(jmax); j < jmax; j++) {
3884 Node *out = _head->fast_out(j);
3885 if( out->is_Phi() ) {
3886 PhiNode *old_phi = out->as_Phi();
3887 assert( old_phi->region() == _head, "" );
3888 Node *phi = PhiNode::make_blank(outer, old_phi);
3889 phi->init_req(LoopNode::EntryControl, old_phi->in(LoopNode::EntryControl));
3890 phi->init_req(LoopNode::LoopBackControl, old_phi->in(outer_idx));
3891 phi = igvn.register_new_node_with_optimizer(phi, old_phi);
3892 // Make old Phi point to new Phi on the fall-in path
3893 igvn.replace_input_of(old_phi, LoopNode::EntryControl, phi);
3894 old_phi->del_req(outer_idx);
3895 }
3896 }
3897
3898 // Use the new loop head instead of the old shared one
3899 _head = outer;
3900 phase->set_loop(_head, this);
3901 }
3902
3903 //------------------------------fix_parent-------------------------------------
3904 static void fix_parent( IdealLoopTree *loop, IdealLoopTree *parent ) {
3905 loop->_parent = parent;
3906 if( loop->_child ) fix_parent( loop->_child, loop );
3907 if( loop->_next ) fix_parent( loop->_next , parent );
3908 }
3909
3910 //------------------------------estimate_path_freq-----------------------------
3911 static float estimate_path_freq( Node *n ) {
3912 // Try to extract some path frequency info
3913 IfNode *iff;
3914 for( int i = 0; i < 50; i++ ) { // Skip through a bunch of uncommon tests
3915 uint nop = n->Opcode();
3916 if( nop == Op_SafePoint ) { // Skip any safepoint
3917 n = n->in(0);
3918 continue;
3919 }
3920 if( nop == Op_CatchProj ) { // Get count from a prior call
3921 // Assume call does not always throw exceptions: means the call-site
3922 // count is also the frequency of the fall-through path.
3923 assert( n->is_CatchProj(), "" );
3924 if( ((CatchProjNode*)n)->_con != CatchProjNode::fall_through_index )
3925 return 0.0f; // Assume call exception path is rare
3926 Node *call = n->in(0)->in(0)->in(0);
3927 assert( call->is_Call(), "expect a call here" );
3928 const JVMState *jvms = ((CallNode*)call)->jvms();
3929 ciMethodData* methodData = jvms->method()->method_data();
3930 if (!methodData->is_mature()) return 0.0f; // No call-site data
3931 ciProfileData* data = methodData->bci_to_data(jvms->bci());
3932 if ((data == nullptr) || !data->is_CounterData()) {
3933 // no call profile available, try call's control input
3934 n = n->in(0);
3935 continue;
3936 }
3937 return data->as_CounterData()->count()/FreqCountInvocations;
3938 }
3939 // See if there's a gating IF test
3940 Node *n_c = n->in(0);
3941 if( !n_c->is_If() ) break; // No estimate available
3942 iff = n_c->as_If();
3943 if( iff->_fcnt != COUNT_UNKNOWN ) // Have a valid count?
3944 // Compute how much count comes on this path
3945 return ((nop == Op_IfTrue) ? iff->_prob : 1.0f - iff->_prob) * iff->_fcnt;
3946 // Have no count info. Skip dull uncommon-trap like branches.
3947 if( (nop == Op_IfTrue && iff->_prob < PROB_LIKELY_MAG(5)) ||
3948 (nop == Op_IfFalse && iff->_prob > PROB_UNLIKELY_MAG(5)) )
3949 break;
3950 // Skip through never-taken branch; look for a real loop exit.
3951 n = iff->in(0);
3952 }
3953 return 0.0f; // No estimate available
3954 }
3955
3956 //------------------------------merge_many_backedges---------------------------
3957 // Merge all the backedges from the shared header into a private Region.
3958 // Feed that region as the one backedge to this loop.
3959 void IdealLoopTree::merge_many_backedges( PhaseIdealLoop *phase ) {
3960 uint i;
3961
3962 // Scan for the top 2 hottest backedges
3963 float hotcnt = 0.0f;
3964 float warmcnt = 0.0f;
3965 uint hot_idx = 0;
3966 // Loop starts at 2 because slot 1 is the fall-in path
3967 for( i = 2; i < _head->req(); i++ ) {
3968 float cnt = estimate_path_freq(_head->in(i));
3969 if( cnt > hotcnt ) { // Grab hottest path
3970 warmcnt = hotcnt;
3971 hotcnt = cnt;
3972 hot_idx = i;
3973 } else if( cnt > warmcnt ) { // And 2nd hottest path
3974 warmcnt = cnt;
3975 }
3976 }
3977
3978 // See if the hottest backedge is worthy of being an inner loop
3979 // by being much hotter than the next hottest backedge.
3980 if( hotcnt <= 0.0001 ||
3981 hotcnt < 2.0*warmcnt ) hot_idx = 0;// No hot backedge
3982
3983 // Peel out the backedges into a private merge point; peel
3984 // them all except optionally hot_idx.
3985 PhaseIterGVN &igvn = phase->_igvn;
3986
3987 Node *hot_tail = nullptr;
3988 // Make a Region for the merge point
3989 Node *r = new RegionNode(1);
3990 for( i = 2; i < _head->req(); i++ ) {
3991 if( i != hot_idx )
3992 r->add_req( _head->in(i) );
3993 else hot_tail = _head->in(i);
3994 }
3995 igvn.register_new_node_with_optimizer(r, _head);
3996 // Plug region into end of loop _head, followed by hot_tail
3997 while( _head->req() > 3 ) _head->del_req( _head->req()-1 );
3998 igvn.replace_input_of(_head, 2, r);
3999 if( hot_idx ) _head->add_req(hot_tail);
4000
4001 // Split all the Phis up between '_head' loop and the Region 'r'
4002 for (DUIterator_Fast jmax, j = _head->fast_outs(jmax); j < jmax; j++) {
4003 Node *out = _head->fast_out(j);
4004 if( out->is_Phi() ) {
4005 PhiNode* n = out->as_Phi();
4006 igvn.hash_delete(n); // Delete from hash before hacking edges
4007 Node *hot_phi = nullptr;
4008 Node *phi = new PhiNode(r, n->type(), n->adr_type());
4009 // Check all inputs for the ones to peel out
4010 uint j = 1;
4011 for( uint i = 2; i < n->req(); i++ ) {
4012 if( i != hot_idx )
4013 phi->set_req( j++, n->in(i) );
4014 else hot_phi = n->in(i);
4015 }
4016 // Register the phi but do not transform until whole place transforms
4017 igvn.register_new_node_with_optimizer(phi, n);
4018 // Add the merge phi to the old Phi
4019 while( n->req() > 3 ) n->del_req( n->req()-1 );
4020 igvn.replace_input_of(n, 2, phi);
4021 if( hot_idx ) n->add_req(hot_phi);
4022 }
4023 }
4024
4025
4026 // Insert a new IdealLoopTree inserted below me. Turn it into a clone
4027 // of self loop tree. Turn self into a loop headed by _head and with
4028 // tail being the new merge point.
4029 IdealLoopTree *ilt = new IdealLoopTree( phase, _head, _tail );
4030 phase->set_loop(_tail,ilt); // Adjust tail
4031 _tail = r; // Self's tail is new merge point
4032 phase->set_loop(r,this);
4033 ilt->_child = _child; // New guy has my children
4034 _child = ilt; // Self has new guy as only child
4035 ilt->_parent = this; // new guy has self for parent
4036 ilt->_nest = _nest; // Same nesting depth (for now)
4037
4038 // Starting with 'ilt', look for child loop trees using the same shared
4039 // header. Flatten these out; they will no longer be loops in the end.
4040 IdealLoopTree **pilt = &_child;
4041 while( ilt ) {
4042 if( ilt->_head == _head ) {
4043 uint i;
4044 for( i = 2; i < _head->req(); i++ )
4045 if( _head->in(i) == ilt->_tail )
4046 break; // Still a loop
4047 if( i == _head->req() ) { // No longer a loop
4048 // Flatten ilt. Hang ilt's "_next" list from the end of
4049 // ilt's '_child' list. Move the ilt's _child up to replace ilt.
4050 IdealLoopTree **cp = &ilt->_child;
4051 while( *cp ) cp = &(*cp)->_next; // Find end of child list
4052 *cp = ilt->_next; // Hang next list at end of child list
4053 *pilt = ilt->_child; // Move child up to replace ilt
4054 ilt->_head = nullptr; // Flag as a loop UNIONED into parent
4055 ilt = ilt->_child; // Repeat using new ilt
4056 continue; // do not advance over ilt->_child
4057 }
4058 assert( ilt->_tail == hot_tail, "expected to only find the hot inner loop here" );
4059 phase->set_loop(_head,ilt);
4060 }
4061 pilt = &ilt->_child; // Advance to next
4062 ilt = *pilt;
4063 }
4064
4065 if( _child ) fix_parent( _child, this );
4066 }
4067
4068 //------------------------------beautify_loops---------------------------------
4069 // Split shared headers and insert loop landing pads.
4070 // Insert a LoopNode to replace the RegionNode.
4071 // Return TRUE if loop tree is structurally changed.
4072 bool IdealLoopTree::beautify_loops( PhaseIdealLoop *phase ) {
4073 bool result = false;
4074 // Cache parts in locals for easy
4075 PhaseIterGVN &igvn = phase->_igvn;
4076
4077 igvn.hash_delete(_head); // Yank from hash before hacking edges
4078
4079 // Check for multiple fall-in paths. Peel off a landing pad if need be.
4080 int fall_in_cnt = 0;
4081 for( uint i = 1; i < _head->req(); i++ )
4082 if( !phase->is_member( this, _head->in(i) ) )
4083 fall_in_cnt++;
4084 assert( fall_in_cnt, "at least 1 fall-in path" );
4085 if( fall_in_cnt > 1 ) // Need a loop landing pad to merge fall-ins
4086 split_fall_in( phase, fall_in_cnt );
4087
4088 // Swap inputs to the _head and all Phis to move the fall-in edge to
4089 // the left.
4090 fall_in_cnt = 1;
4091 while( phase->is_member( this, _head->in(fall_in_cnt) ) )
4092 fall_in_cnt++;
4093 if( fall_in_cnt > 1 ) {
4094 // Since I am just swapping inputs I do not need to update def-use info
4095 Node *tmp = _head->in(1);
4096 igvn.rehash_node_delayed(_head);
4097 _head->set_req( 1, _head->in(fall_in_cnt) );
4098 _head->set_req( fall_in_cnt, tmp );
4099 // Swap also all Phis
4100 for (DUIterator_Fast imax, i = _head->fast_outs(imax); i < imax; i++) {
4101 Node* phi = _head->fast_out(i);
4102 if( phi->is_Phi() ) {
4103 igvn.rehash_node_delayed(phi); // Yank from hash before hacking edges
4104 tmp = phi->in(1);
4105 phi->set_req( 1, phi->in(fall_in_cnt) );
4106 phi->set_req( fall_in_cnt, tmp );
4107 }
4108 }
4109 }
4110 assert( !phase->is_member( this, _head->in(1) ), "left edge is fall-in" );
4111 assert( phase->is_member( this, _head->in(2) ), "right edge is loop" );
4112
4113 // If I am a shared header (multiple backedges), peel off the many
4114 // backedges into a private merge point and use the merge point as
4115 // the one true backedge.
4116 if (_head->req() > 3) {
4117 // Merge the many backedges into a single backedge but leave
4118 // the hottest backedge as separate edge for the following peel.
4119 if (!_irreducible) {
4120 merge_many_backedges( phase );
4121 }
4122
4123 // When recursively beautify my children, split_fall_in can change
4124 // loop tree structure when I am an irreducible loop. Then the head
4125 // of my children has a req() not bigger than 3. Here we need to set
4126 // result to true to catch that case in order to tell the caller to
4127 // rebuild loop tree. See issue JDK-8244407 for details.
4128 result = true;
4129 }
4130
4131 // If I have one hot backedge, peel off myself loop.
4132 // I better be the outermost loop.
4133 if (_head->req() > 3 && !_irreducible) {
4134 split_outer_loop( phase );
4135 result = true;
4136
4137 } else if (!_head->is_Loop() && !_irreducible) {
4138 // Make a new LoopNode to replace the old loop head
4139 Node *l = new LoopNode( _head->in(1), _head->in(2) );
4140 l = igvn.register_new_node_with_optimizer(l, _head);
4141 phase->set_created_loop_node();
4142 // Go ahead and replace _head
4143 phase->_igvn.replace_node( _head, l );
4144 _head = l;
4145 phase->set_loop(_head, this);
4146 }
4147
4148 // Now recursively beautify nested loops
4149 if( _child ) result |= _child->beautify_loops( phase );
4150 if( _next ) result |= _next ->beautify_loops( phase );
4151 return result;
4152 }
4153
4154 //------------------------------allpaths_check_safepts----------------------------
4155 // Allpaths backwards scan. Starting at the head, traversing all backedges, and the body. Terminating each path at first
4156 // safepoint encountered. Helper for check_safepts.
4157 void IdealLoopTree::allpaths_check_safepts(VectorSet &visited, Node_List &stack) {
4158 assert(stack.size() == 0, "empty stack");
4159 stack.push(_head);
4160 visited.clear();
4161 visited.set(_head->_idx);
4162 while (stack.size() > 0) {
4163 Node* n = stack.pop();
4164 if (n->is_Call() && n->as_Call()->guaranteed_safepoint()) {
4165 // Terminate this path
4166 } else if (n->Opcode() == Op_SafePoint) {
4167 if (_phase->get_loop(n) != this) {
4168 if (_required_safept == nullptr) _required_safept = new Node_List();
4169 // save the first we run into on that path: closest to the tail if the head has a single backedge
4170 _required_safept->push(n);
4171 }
4172 // Terminate this path
4173 } else {
4174 uint start = n->is_Region() ? 1 : 0;
4175 uint end = n->is_Region() && (!n->is_Loop() || n == _head) ? n->req() : start + 1;
4176 for (uint i = start; i < end; i++) {
4177 Node* in = n->in(i);
4178 assert(in->is_CFG(), "must be");
4179 if (!visited.test_set(in->_idx) && is_member(_phase->get_loop(in))) {
4180 stack.push(in);
4181 }
4182 }
4183 }
4184 }
4185 }
4186
4187 //------------------------------check_safepts----------------------------
4188 // Given dominators, try to find loops with calls that must always be
4189 // executed (call dominates loop tail). These loops do not need non-call
4190 // safepoints (ncsfpt).
4191 //
4192 // A complication is that a safepoint in a inner loop may be needed
4193 // by an outer loop. In the following, the inner loop sees it has a
4194 // call (block 3) on every path from the head (block 2) to the
4195 // backedge (arc 3->2). So it deletes the ncsfpt (non-call safepoint)
4196 // in block 2, _but_ this leaves the outer loop without a safepoint.
4197 //
4198 // entry 0
4199 // |
4200 // v
4201 // outer 1,2,4 +-> 1
4202 // | \
4203 // | v
4204 // inner 2,3 | 2 <---+ ncsfpt in 2
4205 // | / \ |
4206 // | v v |
4207 // | 4 3 | call in 3
4208 // |_/ \ \_|
4209 // |
4210 // v
4211 // exit 5
4212 //
4213 // This method maintains a list (_required_safept) of ncsfpts that must
4214 // be protected for each loop. It only marks ncsfpts for prevervation,
4215 // and does not actually delete any of them.
4216 //
4217 // If some other method needs to delete a ncsfpt later, it will make sure
4218 // the ncsfpt is not in the list of all outer loops of the current loop.
4219 // See `PhaseIdealLoop::is_deleteable_safept`.
4220 //
4221 // The insights into the problem:
4222 // A) Counted loops are okay (i.e. do not need to preserve ncsfpts),
4223 // they will be handled in `IdealLoopTree::counted_loop`
4224 // B) Innermost loops are okay because there's no inner loops that can
4225 // delete their ncsfpts. Only outer loops need to mark safepoints for
4226 // protection, because only loops further in can accidentally delete
4227 // their ncsfpts
4228 // C) If an outer loop has a call that's guaranteed to execute (on the
4229 // idom-path), then that loop is okay. Because the call will always
4230 // perform a safepoint poll, regardless of what safepoints are deleted
4231 // from its inner loops
4232 // D) Similarly, if an outer loop has a ncsfpt on the idom-path that isn't
4233 // inside any nested loop, then that loop is okay
4234 // E) Otherwise, if an outer loop's ncsfpt on the idom-path is nested in
4235 // an inner loop, we need to prevent the inner loop from deleting it
4236 //
4237 // There are two analyses:
4238 // 1) The first, and cheaper one, scans the loop body from
4239 // tail to head following the idom (immediate dominator)
4240 // chain, looking for the cases (C,D,E) above.
4241 // Since inner loops are scanned before outer loops, there is summary
4242 // information about inner loops. Inner loops can be skipped over
4243 // when the tail of an inner loop is encountered.
4244 //
4245 // 2) The second, invoked if the first fails to find a call or ncsfpt on
4246 // the idom path (which is rare), scans all predecessor control paths
4247 // from the tail to the head, terminating a path when a call or sfpt
4248 // is encountered, to find the ncsfpt's that are closest to the tail.
4249 //
4250 void IdealLoopTree::check_safepts(VectorSet &visited, Node_List &stack) {
4251 // Bottom up traversal
4252 IdealLoopTree* ch = _child;
4253 if (_child) _child->check_safepts(visited, stack);
4254 if (_next) _next ->check_safepts(visited, stack);
4255
4256 if (!_head->is_CountedLoop() && !_has_sfpt && _parent != nullptr) {
4257 bool has_call = false; // call on dom-path
4258 bool has_local_ncsfpt = false; // ncsfpt on dom-path at this loop depth
4259 Node* nonlocal_ncsfpt = nullptr; // ncsfpt on dom-path at a deeper depth
4260 if (!_irreducible) {
4261 // Scan the dom-path nodes from tail to head
4262 for (Node* n = tail(); n != _head; n = _phase->idom(n)) {
4263 if (n->is_Call() && n->as_Call()->guaranteed_safepoint()) {
4264 has_call = true;
4265 _has_sfpt = 1; // Then no need for a safept!
4266 break;
4267 } else if (n->Opcode() == Op_SafePoint) {
4268 if (_phase->get_loop(n) == this) {
4269 // We found a local ncsfpt.
4270 // Continue searching for a call that is guaranteed to be a safepoint.
4271 has_local_ncsfpt = true;
4272 } else if (nonlocal_ncsfpt == nullptr) {
4273 nonlocal_ncsfpt = n; // save the one closest to the tail
4274 }
4275 } else {
4276 IdealLoopTree* nlpt = _phase->get_loop(n);
4277 if (this != nlpt) {
4278 // If at an inner loop tail, see if the inner loop has already
4279 // recorded seeing a call on the dom-path (and stop.) If not,
4280 // jump to the head of the inner loop.
4281 assert(is_member(nlpt), "nested loop");
4282 Node* tail = nlpt->_tail;
4283 if (tail->in(0)->is_If()) tail = tail->in(0);
4284 if (n == tail) {
4285 // If inner loop has call on dom-path, so does outer loop
4286 if (nlpt->_has_sfpt) {
4287 has_call = true;
4288 _has_sfpt = 1;
4289 break;
4290 }
4291 // Skip to head of inner loop
4292 assert(_phase->is_dominator(_head, nlpt->_head), "inner head dominated by outer head");
4293 n = nlpt->_head;
4294 if (_head == n) {
4295 // this and nlpt (inner loop) have the same loop head. This should not happen because
4296 // during beautify_loops we call merge_many_backedges. However, infinite loops may not
4297 // have been attached to the loop-tree during build_loop_tree before beautify_loops,
4298 // but then attached in the build_loop_tree afterwards, and so still have unmerged
4299 // backedges. Check if we are indeed in an infinite subgraph, and terminate the scan,
4300 // since we have reached the loop head of this.
4301 assert(_head->as_Region()->is_in_infinite_subgraph(),
4302 "only expect unmerged backedges in infinite loops");
4303 break;
4304 }
4305 }
4306 }
4307 }
4308 }
4309 }
4310 // Record safept's that this loop needs preserved when an
4311 // inner loop attempts to delete it's safepoints.
4312 if (_child != nullptr && !has_call && !has_local_ncsfpt) {
4313 if (nonlocal_ncsfpt != nullptr) {
4314 if (_required_safept == nullptr) _required_safept = new Node_List();
4315 _required_safept->push(nonlocal_ncsfpt);
4316 } else {
4317 // Failed to find a suitable safept on the dom-path. Now use
4318 // an all paths walk from tail to head, looking for safepoints to preserve.
4319 allpaths_check_safepts(visited, stack);
4320 }
4321 }
4322 }
4323 }
4324
4325 //---------------------------is_deleteable_safept----------------------------
4326 // Is safept not required by an outer loop?
4327 bool PhaseIdealLoop::is_deleteable_safept(Node* sfpt) {
4328 assert(sfpt->Opcode() == Op_SafePoint, "");
4329 IdealLoopTree* lp = get_loop(sfpt)->_parent;
4330 while (lp != nullptr) {
4331 Node_List* sfpts = lp->_required_safept;
4332 if (sfpts != nullptr) {
4333 for (uint i = 0; i < sfpts->size(); i++) {
4334 if (sfpt == sfpts->at(i))
4335 return false;
4336 }
4337 }
4338 lp = lp->_parent;
4339 }
4340 return true;
4341 }
4342
4343 //---------------------------replace_parallel_iv-------------------------------
4344 // Replace parallel induction variable (parallel to trip counter)
4345 // This optimization looks for patterns similar to:
4346 //
4347 // int a = init2;
4348 // for (int iv = init; iv < limit; iv += stride_con) {
4349 // a += stride_con2;
4350 // }
4351 //
4352 // and transforms it to:
4353 //
4354 // int iv2 = init2
4355 // int iv = init
4356 // loop:
4357 // if (iv >= limit) goto exit
4358 // iv += stride_con
4359 // iv2 = init2 + (iv - init) * (stride_con2 / stride_con)
4360 // goto loop
4361 // exit:
4362 // ...
4363 //
4364 // Such transformation introduces more optimization opportunities. In this
4365 // particular example, the loop can be eliminated entirely given that
4366 // `stride_con2 / stride_con` is exact (i.e., no remainder). Checks are in
4367 // place to only perform this optimization if such a division is exact. This
4368 // example will be transformed into its semantic equivalence:
4369 //
4370 // int iv2 = (iv * stride_con2 / stride_con) + (init2 - (init * stride_con2 / stride_con))
4371 //
4372 // which corresponds to the structure of transformed subgraph.
4373 //
4374 // However, if there is a mismatch between types of the loop and the parallel
4375 // induction variable (e.g., a long-typed IV in an int-typed loop), type
4376 // conversions are required:
4377 //
4378 // long iv2 = ((long) iv * stride_con2 / stride_con) + (init2 - ((long) init * stride_con2 / stride_con))
4379 //
4380 void PhaseIdealLoop::replace_parallel_iv(IdealLoopTree *loop) {
4381 assert(loop->_head->is_CountedLoop(), "");
4382 CountedLoopNode *cl = loop->_head->as_CountedLoop();
4383 if (!cl->is_valid_counted_loop(T_INT)) {
4384 return; // skip malformed counted loop
4385 }
4386 Node *incr = cl->incr();
4387 if (incr == nullptr) {
4388 return; // Dead loop?
4389 }
4390 Node *init = cl->init_trip();
4391 Node *phi = cl->phi();
4392 jlong stride_con = cl->stride_con();
4393
4394 // Visit all children, looking for Phis
4395 for (DUIterator i = cl->outs(); cl->has_out(i); i++) {
4396 Node *out = cl->out(i);
4397 // Look for other phis (secondary IVs). Skip dead ones
4398 if (!out->is_Phi() || out == phi || !has_node(out)) {
4399 continue;
4400 }
4401
4402 PhiNode* phi2 = out->as_Phi();
4403 Node* incr2 = phi2->in(LoopNode::LoopBackControl);
4404 // Look for induction variables of the form: X += constant
4405 if (phi2->region() != loop->_head ||
4406 incr2->req() != 3 ||
4407 incr2->in(1)->uncast() != phi2 ||
4408 incr2 == incr ||
4409 (incr2->Opcode() != Op_AddI && incr2->Opcode() != Op_AddL) ||
4410 !incr2->in(2)->is_Con()) {
4411 continue;
4412 }
4413
4414 if (incr2->in(1)->is_ConstraintCast() &&
4415 !(incr2->in(1)->in(0)->is_IfProj() && incr2->in(1)->in(0)->in(0)->is_RangeCheck())) {
4416 // Skip AddI->CastII->Phi case if CastII is not controlled by local RangeCheck
4417 continue;
4418 }
4419 // Check for parallel induction variable (parallel to trip counter)
4420 // via an affine function. In particular, count-down loops with
4421 // count-up array indices are common. We only RCE references off
4422 // the trip-counter, so we need to convert all these to trip-counter
4423 // expressions.
4424 Node* init2 = phi2->in(LoopNode::EntryControl);
4425
4426 // Determine the basic type of the stride constant (and the iv being incremented).
4427 BasicType stride_con2_bt = incr2->Opcode() == Op_AddI ? T_INT : T_LONG;
4428 jlong stride_con2 = incr2->in(2)->get_integer_as_long(stride_con2_bt);
4429
4430 // The ratio of the two strides cannot be represented as an int
4431 // if stride_con2 is min_jint (or min_jlong, respectively) and
4432 // stride_con is -1.
4433 if (stride_con2 == min_signed_integer(stride_con2_bt) && stride_con == -1) {
4434 continue;
4435 }
4436
4437 // The general case here gets a little tricky. We want to find the
4438 // GCD of all possible parallel IV's and make a new IV using this
4439 // GCD for the loop. Then all possible IVs are simple multiples of
4440 // the GCD. In practice, this will cover very few extra loops.
4441 // Instead we require 'stride_con2' to be a multiple of 'stride_con',
4442 // where +/-1 is the common case, but other integer multiples are
4443 // also easy to handle.
4444 jlong ratio_con = stride_con2 / stride_con;
4445
4446 if ((ratio_con * stride_con) != stride_con2) { // Check for exact (no remainder)
4447 continue;
4448 }
4449
4450 #ifndef PRODUCT
4451 if (TraceLoopOpts) {
4452 tty->print("Parallel IV: %d ", phi2->_idx);
4453 loop->dump_head();
4454 }
4455 #endif
4456
4457 // Convert to using the trip counter. The parallel induction
4458 // variable differs from the trip counter by a loop-invariant
4459 // amount, the difference between their respective initial values.
4460 // It is scaled by the 'ratio_con'.
4461 Node* ratio = integercon(ratio_con, stride_con2_bt);
4462
4463 Node* init_converted = insert_convert_node_if_needed(stride_con2_bt, init);
4464 Node* phi_converted = insert_convert_node_if_needed(stride_con2_bt, phi);
4465
4466 Node* ratio_init = MulNode::make(init_converted, ratio, stride_con2_bt);
4467 _igvn.register_new_node_with_optimizer(ratio_init, init_converted);
4468 set_early_ctrl(ratio_init, false);
4469
4470 Node* diff = SubNode::make(init2, ratio_init, stride_con2_bt);
4471 _igvn.register_new_node_with_optimizer(diff, init2);
4472 set_early_ctrl(diff, false);
4473
4474 Node* ratio_idx = MulNode::make(phi_converted, ratio, stride_con2_bt);
4475 _igvn.register_new_node_with_optimizer(ratio_idx, phi_converted);
4476 set_ctrl(ratio_idx, cl);
4477
4478 Node* add = AddNode::make(ratio_idx, diff, stride_con2_bt);
4479 _igvn.register_new_node_with_optimizer(add);
4480 set_ctrl(add, cl);
4481
4482 _igvn.replace_node( phi2, add );
4483 // Sometimes an induction variable is unused
4484 if (add->outcnt() == 0) {
4485 _igvn.remove_dead_node(add);
4486 }
4487 --i; // deleted this phi; rescan starting with next position
4488 }
4489 }
4490
4491 Node* PhaseIdealLoop::insert_convert_node_if_needed(BasicType target, Node* input) {
4492 BasicType source = _igvn.type(input)->basic_type();
4493 if (source == target) {
4494 return input;
4495 }
4496
4497 Node* converted = ConvertNode::create_convert(source, target, input);
4498 _igvn.register_new_node_with_optimizer(converted, input);
4499 set_early_ctrl(converted, false);
4500
4501 return converted;
4502 }
4503
4504 void IdealLoopTree::remove_safepoints(PhaseIdealLoop* phase, bool keep_one) {
4505 Node* keep = nullptr;
4506 if (keep_one) {
4507 // Look for a safepoint on the idom-path.
4508 for (Node* i = tail(); i != _head; i = phase->idom(i)) {
4509 if (i->Opcode() == Op_SafePoint && phase->get_loop(i) == this) {
4510 keep = i;
4511 break; // Found one
4512 }
4513 }
4514 }
4515
4516 // Don't remove any safepoints if it is requested to keep a single safepoint and
4517 // no safepoint was found on idom-path. It is not safe to remove any safepoint
4518 // in this case since there's no safepoint dominating all paths in the loop body.
4519 bool prune = !keep_one || keep != nullptr;
4520
4521 // Delete other safepoints in this loop.
4522 Node_List* sfpts = _safepts;
4523 if (prune && sfpts != nullptr) {
4524 assert(keep == nullptr || keep->Opcode() == Op_SafePoint, "not safepoint");
4525 for (uint i = 0; i < sfpts->size(); i++) {
4526 Node* n = sfpts->at(i);
4527 assert(phase->get_loop(n) == this, "");
4528 if (n != keep && phase->is_deleteable_safept(n)) {
4529 phase->replace_node_and_forward_ctrl(n, n->in(TypeFunc::Control));
4530 }
4531 }
4532 }
4533 }
4534
4535 //------------------------------counted_loop-----------------------------------
4536 // Convert to counted loops where possible
4537 void IdealLoopTree::counted_loop( PhaseIdealLoop *phase ) {
4538
4539 // For grins, set the inner-loop flag here
4540 if (!_child) {
4541 if (_head->is_Loop()) _head->as_Loop()->set_inner_loop();
4542 }
4543
4544 IdealLoopTree* loop = this;
4545 if (_head->is_CountedLoop() ||
4546 phase->is_counted_loop(_head, loop, T_INT)) {
4547
4548 if (LoopStripMiningIter == 0 || _head->as_CountedLoop()->is_strip_mined()) {
4549 // Indicate we do not need a safepoint here
4550 _has_sfpt = 1;
4551 }
4552
4553 // Remove safepoints
4554 bool keep_one_sfpt = !(_has_call || _has_sfpt);
4555 remove_safepoints(phase, keep_one_sfpt);
4556
4557 // Look for induction variables
4558 phase->replace_parallel_iv(this);
4559 } else if (_head->is_LongCountedLoop() ||
4560 phase->is_counted_loop(_head, loop, T_LONG)) {
4561 remove_safepoints(phase, true);
4562 } else {
4563 assert(!_head->is_Loop() || !_head->as_Loop()->is_loop_nest_inner_loop(), "transformation to counted loop should not fail");
4564 if (_parent != nullptr && !_irreducible) {
4565 // Not a counted loop. Keep one safepoint.
4566 bool keep_one_sfpt = true;
4567 remove_safepoints(phase, keep_one_sfpt);
4568 }
4569 }
4570
4571 // Recursively
4572 assert(loop->_child != this || (loop->_head->as_Loop()->is_OuterStripMinedLoop() && _head->as_CountedLoop()->is_strip_mined()), "what kind of loop was added?");
4573 assert(loop->_child != this || (loop->_child->_child == nullptr && loop->_child->_next == nullptr), "would miss some loops");
4574 if (loop->_child && loop->_child != this) loop->_child->counted_loop(phase);
4575 if (loop->_next) loop->_next ->counted_loop(phase);
4576 }
4577
4578
4579 // The Estimated Loop Clone Size:
4580 // CloneFactor * (~112% * BodySize + BC) + CC + FanOutTerm,
4581 // where BC and CC are totally ad-hoc/magic "body" and "clone" constants,
4582 // respectively, used to ensure that the node usage estimates made are on the
4583 // safe side, for the most part. The FanOutTerm is an attempt to estimate the
4584 // possible additional/excessive nodes generated due to data and control flow
4585 // merging, for edges reaching outside the loop.
4586 uint IdealLoopTree::est_loop_clone_sz(uint factor) const {
4587
4588 precond(0 < factor && factor < 16);
4589
4590 uint const bc = 13;
4591 uint const cc = 17;
4592 uint const sz = _body.size() + (_body.size() + 7) / 2;
4593 uint estimate = factor * (sz + bc) + cc;
4594
4595 assert((estimate - cc) / factor == sz + bc, "overflow");
4596
4597 return estimate + est_loop_flow_merge_sz();
4598 }
4599
4600 // The Estimated Loop (full-) Unroll Size:
4601 // UnrollFactor * (~106% * BodySize) + CC + FanOutTerm,
4602 // where CC is a (totally) ad-hoc/magic "clone" constant, used to ensure that
4603 // node usage estimates made are on the safe side, for the most part. This is
4604 // a "light" version of the loop clone size calculation (above), based on the
4605 // assumption that most of the loop-construct overhead will be unraveled when
4606 // (fully) unrolled. Defined for unroll factors larger or equal to one (>=1),
4607 // including an overflow check and returning UINT_MAX in case of an overflow.
4608 uint IdealLoopTree::est_loop_unroll_sz(uint factor) const {
4609
4610 precond(factor > 0);
4611
4612 // Take into account that after unroll conjoined heads and tails will fold.
4613 uint const b0 = _body.size() - EMPTY_LOOP_SIZE;
4614 uint const cc = 7;
4615 uint const sz = b0 + (b0 + 15) / 16;
4616 uint estimate = factor * sz + cc;
4617
4618 if ((estimate - cc) / factor != sz) {
4619 return UINT_MAX;
4620 }
4621
4622 return estimate + est_loop_flow_merge_sz();
4623 }
4624
4625 // Estimate the growth effect (in nodes) of merging control and data flow when
4626 // cloning a loop body, based on the amount of control and data flow reaching
4627 // outside of the (current) loop body.
4628 uint IdealLoopTree::est_loop_flow_merge_sz() const {
4629
4630 uint ctrl_edge_out_cnt = 0;
4631 uint data_edge_out_cnt = 0;
4632
4633 for (uint i = 0; i < _body.size(); i++) {
4634 Node* node = _body.at(i);
4635 uint outcnt = node->outcnt();
4636
4637 for (uint k = 0; k < outcnt; k++) {
4638 Node* out = node->raw_out(k);
4639 if (out == nullptr) continue;
4640 if (out->is_CFG()) {
4641 if (!is_member(_phase->get_loop(out))) {
4642 ctrl_edge_out_cnt++;
4643 }
4644 } else if (_phase->has_ctrl(out)) {
4645 Node* ctrl = _phase->get_ctrl(out);
4646 assert(ctrl != nullptr, "must be");
4647 assert(ctrl->is_CFG(), "must be");
4648 if (!is_member(_phase->get_loop(ctrl))) {
4649 data_edge_out_cnt++;
4650 }
4651 }
4652 }
4653 }
4654 // Use data and control count (x2.0) in estimate iff both are > 0. This is
4655 // a rather pessimistic estimate for the most part, in particular for some
4656 // complex loops, but still not enough to capture all loops.
4657 if (ctrl_edge_out_cnt > 0 && data_edge_out_cnt > 0) {
4658 return 2 * (ctrl_edge_out_cnt + data_edge_out_cnt);
4659 }
4660 return 0;
4661 }
4662
4663 #ifndef PRODUCT
4664 //------------------------------dump_head--------------------------------------
4665 // Dump 1 liner for loop header info
4666 void IdealLoopTree::dump_head() {
4667 tty->sp(2 * _nest);
4668 tty->print("Loop: N%d/N%d ", _head->_idx, _tail->_idx);
4669 if (_irreducible) tty->print(" IRREDUCIBLE");
4670 Node* entry = _head->is_Loop() ? _head->as_Loop()->skip_strip_mined(-1)->in(LoopNode::EntryControl)
4671 : _head->in(LoopNode::EntryControl);
4672 const Predicates predicates(entry);
4673 if (predicates.loop_limit_check_predicate_block()->is_non_empty()) {
4674 tty->print(" limit_check");
4675 }
4676 if (predicates.short_running_long_loop_predicate_block()->is_non_empty()) {
4677 tty->print(" short_running");
4678 }
4679 if (UseLoopPredicate) {
4680 if (UseProfiledLoopPredicate && predicates.profiled_loop_predicate_block()->is_non_empty()) {
4681 tty->print(" profile_predicated");
4682 }
4683 if (predicates.loop_predicate_block()->is_non_empty()) {
4684 tty->print(" predicated");
4685 }
4686 }
4687 if (UseAutoVectorizationPredicate && predicates.auto_vectorization_check_block()->is_non_empty()) {
4688 tty->print(" auto_vectorization_check_predicate");
4689 }
4690 if (_head->is_CountedLoop()) {
4691 CountedLoopNode *cl = _head->as_CountedLoop();
4692 tty->print(" counted");
4693
4694 Node* init_n = cl->init_trip();
4695 if (init_n != nullptr && init_n->is_Con())
4696 tty->print(" [%d,", cl->init_trip()->get_int());
4697 else
4698 tty->print(" [int,");
4699 Node* limit_n = cl->limit();
4700 if (limit_n != nullptr && limit_n->is_Con())
4701 tty->print("%d),", cl->limit()->get_int());
4702 else
4703 tty->print("int),");
4704 int stride_con = cl->stride_con();
4705 if (stride_con > 0) tty->print("+");
4706 tty->print("%d", stride_con);
4707
4708 tty->print(" (%0.f iters) ", cl->profile_trip_cnt());
4709
4710 if (cl->is_pre_loop ()) tty->print(" pre" );
4711 if (cl->is_main_loop()) tty->print(" main");
4712 if (cl->is_post_loop()) tty->print(" post");
4713 if (cl->is_vectorized_loop()) tty->print(" vector");
4714 if (range_checks_present()) tty->print(" rc ");
4715 if (cl->is_multiversion_fast_loop()) { tty->print(" multiversion_fast"); }
4716 if (cl->is_multiversion_slow_loop()) { tty->print(" multiversion_slow"); }
4717 if (cl->is_multiversion_delayed_slow_loop()) { tty->print(" multiversion_delayed_slow"); }
4718 }
4719 if (_has_call) tty->print(" has_call");
4720 if (_has_sfpt) tty->print(" has_sfpt");
4721 if (_rce_candidate) tty->print(" rce");
4722 if (_safepts != nullptr && _safepts->size() > 0) {
4723 tty->print(" sfpts={"); _safepts->dump_simple(); tty->print(" }");
4724 }
4725 if (_required_safept != nullptr && _required_safept->size() > 0) {
4726 tty->print(" req={"); _required_safept->dump_simple(); tty->print(" }");
4727 }
4728 if (Verbose) {
4729 tty->print(" body={"); _body.dump_simple(); tty->print(" }");
4730 }
4731 if (_head->is_Loop() && _head->as_Loop()->is_strip_mined()) {
4732 tty->print(" strip_mined");
4733 }
4734 tty->cr();
4735 }
4736
4737 //------------------------------dump-------------------------------------------
4738 // Dump loops by loop tree
4739 void IdealLoopTree::dump() {
4740 dump_head();
4741 if (_child) _child->dump();
4742 if (_next) _next ->dump();
4743 }
4744
4745 #endif
4746
4747 static void log_loop_tree_helper(IdealLoopTree* root, IdealLoopTree* loop, CompileLog* log) {
4748 if (loop == root) {
4749 if (loop->_child != nullptr) {
4750 log->begin_head("loop_tree");
4751 log->end_head();
4752 log_loop_tree_helper(root, loop->_child, log);
4753 log->tail("loop_tree");
4754 assert(loop->_next == nullptr, "what?");
4755 }
4756 } else if (loop != nullptr) {
4757 Node* head = loop->_head;
4758 log->begin_head("loop");
4759 log->print(" idx='%d' ", head->_idx);
4760 if (loop->_irreducible) log->print("irreducible='1' ");
4761 if (head->is_Loop()) {
4762 if (head->as_Loop()->is_inner_loop()) log->print("inner_loop='1' ");
4763 if (head->as_Loop()->is_partial_peel_loop()) log->print("partial_peel_loop='1' ");
4764 } else if (head->is_CountedLoop()) {
4765 CountedLoopNode* cl = head->as_CountedLoop();
4766 if (cl->is_pre_loop()) log->print("pre_loop='%d' ", cl->main_idx());
4767 if (cl->is_main_loop()) log->print("main_loop='%d' ", cl->_idx);
4768 if (cl->is_post_loop()) log->print("post_loop='%d' ", cl->main_idx());
4769 }
4770 log->end_head();
4771 log_loop_tree_helper(root, loop->_child, log);
4772 log->tail("loop");
4773 log_loop_tree_helper(root, loop->_next, log);
4774 }
4775 }
4776
4777 void PhaseIdealLoop::log_loop_tree() {
4778 if (C->log() != nullptr) {
4779 log_loop_tree_helper(_ltree_root, _ltree_root, C->log());
4780 }
4781 }
4782
4783 // Eliminate all Parse and Template Assertion Predicates that are not associated with a loop anymore. The eliminated
4784 // predicates will be removed during the next round of IGVN.
4785 void PhaseIdealLoop::eliminate_useless_predicates() const {
4786 if (C->parse_predicate_count() == 0 && C->template_assertion_predicate_count() == 0) {
4787 return; // No predicates left.
4788 }
4789
4790 EliminateUselessPredicates eliminate_useless_predicates(_igvn, _ltree_root);
4791 eliminate_useless_predicates.eliminate();
4792 }
4793
4794 // If a post or main loop is removed due to an assert predicate, the opaque that guards the loop is not needed anymore
4795 void PhaseIdealLoop::eliminate_useless_zero_trip_guard() {
4796 if (_zero_trip_guard_opaque_nodes.size() == 0) {
4797 return;
4798 }
4799 Unique_Node_List useful_zero_trip_guard_opaques_nodes;
4800 for (LoopTreeIterator iter(_ltree_root); !iter.done(); iter.next()) {
4801 IdealLoopTree* lpt = iter.current();
4802 if (lpt->_child == nullptr && lpt->is_counted()) {
4803 CountedLoopNode* head = lpt->_head->as_CountedLoop();
4804 Node* opaque = head->is_canonical_loop_entry();
4805 if (opaque != nullptr) {
4806 useful_zero_trip_guard_opaques_nodes.push(opaque);
4807 #ifdef ASSERT
4808 // See PhaseIdealLoop::do_unroll
4809 // This property is required in do_unroll, but it may not hold after cloning a loop.
4810 // In such a case, we bail out from unrolling, and rely on IGVN to clean up the graph.
4811 // We are here before loop cloning (before iteration_split), so if this property
4812 // does not hold, it must come from the previous round of loop optimizations, meaning
4813 // that IGVN failed to clean it: we will catch that here.
4814 // On the other hand, if this assert passes, a bailout in do_unroll means that
4815 // this property was broken in the current round of loop optimization (between here
4816 // and do_unroll), so we give a chance to IGVN to make the property true again.
4817 if (head->is_main_loop()) {
4818 assert(opaque->outcnt() == 1, "opaque node should not be shared");
4819 assert(opaque->in(1) == head->limit(), "After IGVN cleanup, input of opaque node must be the limit.");
4820 }
4821 if (head->is_post_loop()) {
4822 assert(opaque->outcnt() == 1, "opaque node should not be shared");
4823 }
4824 #endif
4825 }
4826 }
4827 }
4828 for (uint i = 0; i < _zero_trip_guard_opaque_nodes.size(); ++i) {
4829 OpaqueZeroTripGuardNode* opaque = ((OpaqueZeroTripGuardNode*)_zero_trip_guard_opaque_nodes.at(i));
4830 DEBUG_ONLY(CountedLoopNode* guarded_loop = opaque->guarded_loop());
4831 if (!useful_zero_trip_guard_opaques_nodes.member(opaque)) {
4832 IfNode* iff = opaque->if_node();
4833 IdealLoopTree* loop = get_loop(iff);
4834 while (loop != _ltree_root && loop != nullptr) {
4835 loop = loop->_parent;
4836 }
4837 if (loop == nullptr) {
4838 // unreachable from _ltree_root: zero trip guard is in a newly discovered infinite loop.
4839 // We can't tell if the opaque node is useful or not
4840 assert(guarded_loop == nullptr || guarded_loop->is_in_infinite_subgraph(), "");
4841 } else {
4842 assert(guarded_loop == nullptr, "");
4843 this->_igvn.replace_node(opaque, opaque->in(1));
4844 }
4845 } else {
4846 assert(guarded_loop != nullptr, "");
4847 }
4848 }
4849 }
4850
4851 void PhaseIdealLoop::eliminate_useless_multiversion_if() {
4852 if (_multiversion_opaque_nodes.size() == 0) {
4853 return;
4854 }
4855
4856 ResourceMark rm;
4857 Unique_Node_List useful_multiversioning_opaque_nodes;
4858
4859 // The OpaqueMultiversioning is only used from the fast main loop in AutoVectorization, to add
4860 // speculative runtime-checks to the multiversion_if. Thus, a OpaqueMultiversioning is only
4861 // useful if it can be found from a fast main loop. If it can not be found from a fast main loop,
4862 // then we cannot ever use that multiversion_if to add more speculative runtime-checks, and hence
4863 // it is useless. If it is still in delayed mode, i.e. has not yet had any runtime-checks added,
4864 // then we can let it constant fold towards the fast loop.
4865 for (LoopTreeIterator iter(_ltree_root); !iter.done(); iter.next()) {
4866 IdealLoopTree* lpt = iter.current();
4867 if (lpt->_child == nullptr && lpt->is_counted()) {
4868 CountedLoopNode* head = lpt->_head->as_CountedLoop();
4869 if (head->is_main_loop() && head->is_multiversion_fast_loop()) {
4870 // There are fast_loop pre/main/post loops, but the finding traversal starts at the main
4871 // loop, and traverses via the fast pre loop to the multiversion_if.
4872 IfNode* multiversion_if = head->find_multiversion_if_from_multiversion_fast_main_loop();
4873 if (multiversion_if != nullptr) {
4874 useful_multiversioning_opaque_nodes.push(multiversion_if->in(1)->as_OpaqueMultiversioning());
4875 } else {
4876 // We could not find the multiversion_if, and would never find it again. Remove the
4877 // multiversion marking for consistency.
4878 head->set_no_multiversion();
4879 }
4880 }
4881 }
4882 }
4883
4884 for (uint i = 0; i < _multiversion_opaque_nodes.size(); i++) {
4885 OpaqueMultiversioningNode* opaque = _multiversion_opaque_nodes.at(i)->as_OpaqueMultiversioning();
4886 if (!useful_multiversioning_opaque_nodes.member(opaque)) {
4887 if (opaque->is_delayed_slow_loop()) {
4888 // We cannot hack the node directly, otherwise the slow_loop will complain that it cannot
4889 // find the multiversioning opaque node. Instead, we mark the opaque node as useless, and
4890 // it can be constant folded during IGVN.
4891 opaque->mark_useless(_igvn);
4892 }
4893 }
4894 }
4895 }
4896
4897 //------------------------process_expensive_nodes-----------------------------
4898 // Expensive nodes have their control input set to prevent the GVN
4899 // from commoning them and as a result forcing the resulting node to
4900 // be in a more frequent path. Use CFG information here, to change the
4901 // control inputs so that some expensive nodes can be commoned while
4902 // not executed more frequently.
4903 bool PhaseIdealLoop::process_expensive_nodes() {
4904 assert(OptimizeExpensiveOps, "optimization off?");
4905
4906 // Sort nodes to bring similar nodes together
4907 C->sort_expensive_nodes();
4908
4909 bool progress = false;
4910
4911 for (int i = 0; i < C->expensive_count(); ) {
4912 Node* n = C->expensive_node(i);
4913 int start = i;
4914 // Find nodes similar to n
4915 i++;
4916 for (; i < C->expensive_count() && Compile::cmp_expensive_nodes(n, C->expensive_node(i)) == 0; i++);
4917 int end = i;
4918 // And compare them two by two
4919 for (int j = start; j < end; j++) {
4920 Node* n1 = C->expensive_node(j);
4921 if (is_node_unreachable(n1)) {
4922 continue;
4923 }
4924 for (int k = j+1; k < end; k++) {
4925 Node* n2 = C->expensive_node(k);
4926 if (is_node_unreachable(n2)) {
4927 continue;
4928 }
4929
4930 assert(n1 != n2, "should be pair of nodes");
4931
4932 Node* c1 = n1->in(0);
4933 Node* c2 = n2->in(0);
4934
4935 Node* parent_c1 = c1;
4936 Node* parent_c2 = c2;
4937
4938 // The call to get_early_ctrl_for_expensive() moves the
4939 // expensive nodes up but stops at loops that are in a if
4940 // branch. See whether we can exit the loop and move above the
4941 // If.
4942 if (c1->is_Loop()) {
4943 parent_c1 = c1->in(1);
4944 }
4945 if (c2->is_Loop()) {
4946 parent_c2 = c2->in(1);
4947 }
4948
4949 if (parent_c1 == parent_c2) {
4950 _igvn._worklist.push(n1);
4951 _igvn._worklist.push(n2);
4952 continue;
4953 }
4954
4955 // Look for identical expensive node up the dominator chain.
4956 if (is_dominator(c1, c2)) {
4957 c2 = c1;
4958 } else if (is_dominator(c2, c1)) {
4959 c1 = c2;
4960 } else if (parent_c1->is_Proj() && parent_c1->in(0)->is_If() &&
4961 parent_c2->is_Proj() && parent_c1->in(0) == parent_c2->in(0)) {
4962 // Both branches have the same expensive node so move it up
4963 // before the if.
4964 c1 = c2 = idom(parent_c1->in(0));
4965 }
4966 // Do the actual moves
4967 if (n1->in(0) != c1) {
4968 _igvn.replace_input_of(n1, 0, c1);
4969 progress = true;
4970 }
4971 if (n2->in(0) != c2) {
4972 _igvn.replace_input_of(n2, 0, c2);
4973 progress = true;
4974 }
4975 }
4976 }
4977 }
4978
4979 return progress;
4980 }
4981
4982 //=============================================================================
4983 //----------------------------build_and_optimize-------------------------------
4984 // Create a PhaseLoop. Build the ideal Loop tree. Map each Ideal Node to
4985 // its corresponding LoopNode. If 'optimize' is true, do some loop cleanups.
4986 void PhaseIdealLoop::build_and_optimize() {
4987 assert(!C->post_loop_opts_phase(), "no loop opts allowed");
4988
4989 bool do_split_ifs = (_mode == LoopOptsDefault);
4990 bool skip_loop_opts = (_mode == LoopOptsNone);
4991 bool do_max_unroll = (_mode == LoopOptsMaxUnroll);
4992
4993
4994 bool old_progress = C->major_progress();
4995 uint orig_worklist_size = _igvn._worklist.size();
4996
4997 // Reset major-progress flag for the driver's heuristics
4998 C->clear_major_progress();
4999
5000 #ifndef PRODUCT
5001 // Capture for later assert
5002 uint unique = C->unique();
5003 _loop_invokes++;
5004 _loop_work += unique;
5005 #endif
5006
5007 // True if the method has at least 1 irreducible loop
5008 _has_irreducible_loops = false;
5009
5010 _created_loop_node = false;
5011
5012 VectorSet visited;
5013 // Pre-grow the mapping from Nodes to IdealLoopTrees.
5014 _loop_or_ctrl.map(C->unique(), nullptr);
5015 memset(_loop_or_ctrl.adr(), 0, wordSize * C->unique());
5016
5017 // Pre-build the top-level outermost loop tree entry
5018 _ltree_root = new IdealLoopTree( this, C->root(), C->root() );
5019 // Do not need a safepoint at the top level
5020 _ltree_root->_has_sfpt = 1;
5021
5022 // Initialize Dominators.
5023 // Checked in clone_loop_predicate() during beautify_loops().
5024 _idom_size = 0;
5025 _idom = nullptr;
5026 _dom_depth = nullptr;
5027 _dom_stk = nullptr;
5028
5029 // Empty pre-order array
5030 allocate_preorders();
5031
5032 // Build a loop tree on the fly. Build a mapping from CFG nodes to
5033 // IdealLoopTree entries. Data nodes are NOT walked.
5034 build_loop_tree();
5035 // Check for bailout, and return
5036 if (C->failing()) {
5037 return;
5038 }
5039
5040 // Verify that the has_loops() flag set at parse time is consistent with the just built loop tree. When the back edge
5041 // is an exception edge, parsing doesn't set has_loops().
5042 assert(_ltree_root->_child == nullptr || C->has_loops() || C->has_exception_backedge(), "parsing found no loops but there are some");
5043 // No loops after all
5044 if( !_ltree_root->_child && !_verify_only ) C->set_has_loops(false);
5045
5046 // There should always be an outer loop containing the Root and Return nodes.
5047 // If not, we have a degenerate empty program. Bail out in this case.
5048 if (!has_node(C->root())) {
5049 if (!_verify_only) {
5050 C->clear_major_progress();
5051 assert(false, "empty program detected during loop optimization");
5052 C->record_method_not_compilable("empty program detected during loop optimization");
5053 }
5054 return;
5055 }
5056
5057 // Nothing to do, so get out
5058 bool stop_early = !C->has_loops() && !skip_loop_opts && !do_split_ifs && !do_max_unroll && !_verify_me &&
5059 !_verify_only;
5060 bool do_expensive_nodes = C->should_optimize_expensive_nodes(_igvn);
5061 if (stop_early && !do_expensive_nodes) {
5062 return;
5063 }
5064
5065 // Set loop nesting depth
5066 _ltree_root->set_nest( 0 );
5067
5068 // Split shared headers and insert loop landing pads.
5069 // Do not bother doing this on the Root loop of course.
5070 if( !_verify_me && !_verify_only && _ltree_root->_child ) {
5071 C->print_method(PHASE_BEFORE_BEAUTIFY_LOOPS, 3);
5072 if( _ltree_root->_child->beautify_loops( this ) ) {
5073 // Re-build loop tree!
5074 _ltree_root->_child = nullptr;
5075 _loop_or_ctrl.clear();
5076 reallocate_preorders();
5077 build_loop_tree();
5078 // Check for bailout, and return
5079 if (C->failing()) {
5080 return;
5081 }
5082 // Reset loop nesting depth
5083 _ltree_root->set_nest( 0 );
5084
5085 C->print_method(PHASE_AFTER_BEAUTIFY_LOOPS, 3);
5086 }
5087 }
5088
5089 // Build Dominators for elision of null checks & loop finding.
5090 // Since nodes do not have a slot for immediate dominator, make
5091 // a persistent side array for that info indexed on node->_idx.
5092 _idom_size = C->unique();
5093 _idom = NEW_RESOURCE_ARRAY( Node*, _idom_size );
5094 _dom_depth = NEW_RESOURCE_ARRAY( uint, _idom_size );
5095 _dom_stk = nullptr; // Allocated on demand in recompute_dom_depth
5096 memset( _dom_depth, 0, _idom_size * sizeof(uint) );
5097
5098 Dominators();
5099
5100 if (!_verify_only) {
5101 // As a side effect, Dominators removed any unreachable CFG paths
5102 // into RegionNodes. It doesn't do this test against Root, so
5103 // we do it here.
5104 for( uint i = 1; i < C->root()->req(); i++ ) {
5105 if (!_loop_or_ctrl[C->root()->in(i)->_idx]) { // Dead path into Root?
5106 _igvn.delete_input_of(C->root(), i);
5107 i--; // Rerun same iteration on compressed edges
5108 }
5109 }
5110
5111 // Given dominators, try to find inner loops with calls that must
5112 // always be executed (call dominates loop tail). These loops do
5113 // not need a separate safepoint.
5114 Node_List cisstack;
5115 _ltree_root->check_safepts(visited, cisstack);
5116 }
5117
5118 // Walk the DATA nodes and place into loops. Find earliest control
5119 // node. For CFG nodes, the _loop_or_ctrl array starts out and remains
5120 // holding the associated IdealLoopTree pointer. For DATA nodes, the
5121 // _loop_or_ctrl array holds the earliest legal controlling CFG node.
5122
5123 // Allocate stack with enough space to avoid frequent realloc
5124 int stack_size = (C->live_nodes() >> 1) + 16; // (live_nodes>>1)+16 from Java2D stats
5125 Node_Stack nstack(stack_size);
5126
5127 visited.clear();
5128 Node_List worklist;
5129 // Don't need C->root() on worklist since
5130 // it will be processed among C->top() inputs
5131 worklist.push(C->top());
5132 visited.set(C->top()->_idx); // Set C->top() as visited now
5133 build_loop_early( visited, worklist, nstack );
5134
5135 // Given early legal placement, try finding counted loops. This placement
5136 // is good enough to discover most loop invariants.
5137 if (!_verify_me && !_verify_only) {
5138 _ltree_root->counted_loop( this );
5139 }
5140
5141 // Find latest loop placement. Find ideal loop placement.
5142 visited.clear();
5143 init_dom_lca_tags();
5144 // Need C->root() on worklist when processing outs
5145 worklist.push(C->root());
5146 NOT_PRODUCT( C->verify_graph_edges(); )
5147 worklist.push(C->top());
5148 build_loop_late( visited, worklist, nstack );
5149 if (C->failing()) { return; }
5150
5151 if (_verify_only) {
5152 C->restore_major_progress(old_progress);
5153 assert(C->unique() == unique, "verification _mode made Nodes? ? ?");
5154 assert(_igvn._worklist.size() == orig_worklist_size, "shouldn't push anything");
5155 return;
5156 }
5157
5158 // clear out the dead code after build_loop_late
5159 while (_deadlist.size()) {
5160 _igvn.remove_globally_dead_node(_deadlist.pop());
5161 }
5162
5163 eliminate_useless_zero_trip_guard();
5164 eliminate_useless_multiversion_if();
5165
5166 if (stop_early) {
5167 assert(do_expensive_nodes, "why are we here?");
5168 if (process_expensive_nodes()) {
5169 // If we made some progress when processing expensive nodes then
5170 // the IGVN may modify the graph in a way that will allow us to
5171 // make some more progress: we need to try processing expensive
5172 // nodes again.
5173 C->set_major_progress();
5174 }
5175 return;
5176 }
5177
5178 // Some parser-inserted loop predicates could never be used by loop
5179 // predication or they were moved away from loop during some optimizations.
5180 // For example, peeling. Eliminate them before next loop optimizations.
5181 eliminate_useless_predicates();
5182
5183 #ifndef PRODUCT
5184 C->verify_graph_edges();
5185 if (_verify_me) { // Nested verify pass?
5186 // Check to see if the verify _mode is broken
5187 assert(C->unique() == unique, "non-optimize _mode made Nodes? ? ?");
5188 return;
5189 }
5190 DEBUG_ONLY( if (VerifyLoopOptimizations) { verify(); } );
5191 if (TraceLoopOpts && C->has_loops()) {
5192 _ltree_root->dump();
5193 }
5194 #endif
5195
5196 if (skip_loop_opts) {
5197 C->restore_major_progress(old_progress);
5198 return;
5199 }
5200
5201 if (do_max_unroll) {
5202 for (LoopTreeIterator iter(_ltree_root); !iter.done(); iter.next()) {
5203 IdealLoopTree* lpt = iter.current();
5204 if (lpt->is_innermost() && lpt->_allow_optimizations && !lpt->_has_call && lpt->is_counted()) {
5205 lpt->compute_trip_count(this, T_INT);
5206 if (!lpt->do_one_iteration_loop(this) &&
5207 !lpt->do_remove_empty_loop(this)) {
5208 AutoNodeBudget node_budget(this);
5209 if (lpt->_head->as_CountedLoop()->is_normal_loop() &&
5210 lpt->policy_maximally_unroll(this)) {
5211 memset( worklist.adr(), 0, worklist.max()*sizeof(Node*) );
5212 do_maximally_unroll(lpt, worklist);
5213 }
5214 }
5215 }
5216 }
5217
5218 C->restore_major_progress(old_progress);
5219 return;
5220 }
5221
5222 if (ReassociateInvariants && !C->major_progress()) {
5223 // Reassociate invariants and prep for split_thru_phi
5224 for (LoopTreeIterator iter(_ltree_root); !iter.done(); iter.next()) {
5225 IdealLoopTree* lpt = iter.current();
5226 if (!lpt->is_loop()) {
5227 continue;
5228 }
5229 Node* head = lpt->_head;
5230 if (!lpt->is_innermost()) continue;
5231
5232 // check for vectorized loops, any reassociation of invariants was already done
5233 if (head->is_CountedLoop() && head->as_CountedLoop()->is_unroll_only()) {
5234 continue;
5235 } else {
5236 AutoNodeBudget node_budget(this);
5237 lpt->reassociate_invariants(this);
5238 }
5239 // Because RCE opportunities can be masked by split_thru_phi,
5240 // look for RCE candidates and inhibit split_thru_phi
5241 // on just their loop-phi's for this pass of loop opts
5242 if (SplitIfBlocks && do_split_ifs &&
5243 head->is_BaseCountedLoop() &&
5244 head->as_BaseCountedLoop()->is_valid_counted_loop(head->as_BaseCountedLoop()->bt()) &&
5245 (lpt->policy_range_check(this, true, T_LONG) ||
5246 (head->is_CountedLoop() && lpt->policy_range_check(this, true, T_INT)))) {
5247 lpt->_rce_candidate = 1; // = true
5248 }
5249 }
5250 }
5251
5252 // Check for aggressive application of split-if and other transforms
5253 // that require basic-block info (like cloning through Phi's)
5254 if (!C->major_progress() && SplitIfBlocks && do_split_ifs) {
5255 visited.clear();
5256 split_if_with_blocks(visited, nstack);
5257 if (C->failing()) {
5258 return;
5259 }
5260 DEBUG_ONLY( if (VerifyLoopOptimizations) { verify(); } );
5261 }
5262
5263 if (!C->major_progress() && do_expensive_nodes && process_expensive_nodes()) {
5264 C->set_major_progress();
5265 }
5266
5267 // Perform loop predication before iteration splitting
5268 if (UseLoopPredicate && C->has_loops() && !C->major_progress() && (C->parse_predicate_count() > 0)) {
5269 _ltree_root->_child->loop_predication(this);
5270 }
5271
5272 if (OptimizeFill && UseLoopPredicate && C->has_loops() && !C->major_progress()) {
5273 if (do_intrinsify_fill()) {
5274 C->set_major_progress();
5275 }
5276 }
5277
5278 // Perform iteration-splitting on inner loops. Split iterations to avoid
5279 // range checks or one-shot null checks.
5280
5281 // If split-if's didn't hack the graph too bad (no CFG changes)
5282 // then do loop opts.
5283 if (C->has_loops() && !C->major_progress()) {
5284 memset( worklist.adr(), 0, worklist.max()*sizeof(Node*) );
5285 _ltree_root->_child->iteration_split( this, worklist );
5286 // No verify after peeling! GCM has hoisted code out of the loop.
5287 // After peeling, the hoisted code could sink inside the peeled area.
5288 // The peeling code does not try to recompute the best location for
5289 // all the code before the peeled area, so the verify pass will always
5290 // complain about it.
5291 }
5292
5293 // Check for bailout, and return
5294 if (C->failing()) {
5295 return;
5296 }
5297
5298 // Do verify graph edges in any case
5299 NOT_PRODUCT( C->verify_graph_edges(); );
5300
5301 if (!do_split_ifs) {
5302 // We saw major progress in Split-If to get here. We forced a
5303 // pass with unrolling and not split-if, however more split-if's
5304 // might make progress. If the unrolling didn't make progress
5305 // then the major-progress flag got cleared and we won't try
5306 // another round of Split-If. In particular the ever-common
5307 // instance-of/check-cast pattern requires at least 2 rounds of
5308 // Split-If to clear out.
5309 C->set_major_progress();
5310 }
5311
5312 // Repeat loop optimizations if new loops were seen
5313 if (created_loop_node()) {
5314 C->set_major_progress();
5315 }
5316
5317 // Auto-vectorize main-loop
5318 if (C->do_superword() && C->has_loops() && !C->major_progress()) {
5319 Compile::TracePhase tp(_t_autoVectorize);
5320
5321 // Shared data structures for all AutoVectorizations, to reduce allocations
5322 // of large arrays.
5323 VSharedData vshared;
5324 for (LoopTreeIterator iter(_ltree_root); !iter.done(); iter.next()) {
5325 IdealLoopTree* lpt = iter.current();
5326 AutoVectorizeStatus status = auto_vectorize(lpt, vshared);
5327
5328 if (status == AutoVectorizeStatus::TriedAndFailed) {
5329 // We tried vectorization, but failed. From now on only unroll the loop.
5330 CountedLoopNode* cl = lpt->_head->as_CountedLoop();
5331 if (cl->has_passed_slp()) {
5332 C->set_major_progress();
5333 cl->set_notpassed_slp();
5334 cl->mark_do_unroll_only();
5335 }
5336 }
5337 }
5338 }
5339
5340 // Keep loop predicates and perform optimizations with them
5341 // until no more loop optimizations could be done.
5342 // After that switch predicates off and do more loop optimizations.
5343 if (!C->major_progress() && (C->parse_predicate_count() > 0)) {
5344 C->mark_parse_predicate_nodes_useless(_igvn);
5345 assert(C->parse_predicate_count() == 0, "should be zero now");
5346 if (TraceLoopOpts) {
5347 tty->print_cr("PredicatesOff");
5348 }
5349 C->set_major_progress();
5350 }
5351 }
5352
5353 #ifndef PRODUCT
5354 //------------------------------print_statistics-------------------------------
5355 int PhaseIdealLoop::_loop_invokes=0;// Count of PhaseIdealLoop invokes
5356 int PhaseIdealLoop::_loop_work=0; // Sum of PhaseIdealLoop x unique
5357 volatile int PhaseIdealLoop::_long_loop_candidates=0; // Number of long loops seen
5358 volatile int PhaseIdealLoop::_long_loop_nests=0; // Number of long loops successfully transformed to a nest
5359 volatile int PhaseIdealLoop::_long_loop_counted_loops=0; // Number of long loops successfully transformed to a counted loop
5360 void PhaseIdealLoop::print_statistics() {
5361 tty->print_cr("PhaseIdealLoop=%d, sum _unique=%d, long loops=%d/%d/%d", _loop_invokes, _loop_work, _long_loop_counted_loops, _long_loop_nests, _long_loop_candidates);
5362 }
5363 #endif
5364
5365 #ifdef ASSERT
5366 // Build a verify-only PhaseIdealLoop, and see that it agrees with "this".
5367 void PhaseIdealLoop::verify() const {
5368 ResourceMark rm;
5369 bool old_progress = C->major_progress();
5370 bool success = true;
5371
5372 PhaseIdealLoop phase_verify(_igvn, this);
5373 if (C->failing_internal()) {
5374 return;
5375 }
5376
5377 // Verify ctrl and idom of every node.
5378 success &= verify_idom_and_nodes(C->root(), &phase_verify);
5379
5380 // Verify loop-tree.
5381 success &= _ltree_root->verify_tree(phase_verify._ltree_root);
5382
5383 assert(success, "VerifyLoopOptimizations failed");
5384
5385 // Major progress was cleared by creating a verify version of PhaseIdealLoop.
5386 C->restore_major_progress(old_progress);
5387 }
5388
5389 // Perform a BFS starting at n, through all inputs.
5390 // Call verify_idom and verify_node on all nodes of BFS traversal.
5391 bool PhaseIdealLoop::verify_idom_and_nodes(Node* root, const PhaseIdealLoop* phase_verify) const {
5392 Unique_Node_List worklist;
5393 worklist.push(root);
5394 bool success = true;
5395 for (uint i = 0; i < worklist.size(); i++) {
5396 Node* n = worklist.at(i);
5397 // process node
5398 success &= verify_idom(n, phase_verify);
5399 success &= verify_loop_ctrl(n, phase_verify);
5400 // visit inputs
5401 for (uint j = 0; j < n->req(); j++) {
5402 if (n->in(j) != nullptr) {
5403 worklist.push(n->in(j));
5404 }
5405 }
5406 }
5407 return success;
5408 }
5409
5410 // Verify dominator structure (IDOM).
5411 bool PhaseIdealLoop::verify_idom(Node* n, const PhaseIdealLoop* phase_verify) const {
5412 // Verify IDOM for all CFG nodes (except root).
5413 if (!n->is_CFG() || n->is_Root()) {
5414 return true; // pass
5415 }
5416
5417 if (n->_idx >= _idom_size) {
5418 tty->print("CFG Node with no idom: ");
5419 n->dump();
5420 return false; // fail
5421 }
5422
5423 Node* id = idom_no_update(n);
5424 Node* id_verify = phase_verify->idom_no_update(n);
5425 if (id != id_verify) {
5426 tty->print("Mismatching idom for node: ");
5427 n->dump();
5428 tty->print(" We have idom: ");
5429 id->dump();
5430 tty->print(" Verify has idom: ");
5431 id_verify->dump();
5432 tty->cr();
5433 return false; // fail
5434 }
5435 return true; // pass
5436 }
5437
5438 // Verify "_loop_or_ctrl": control and loop membership.
5439 // (0) _loop_or_ctrl[i] == nullptr -> node not reachable.
5440 // (1) has_ctrl -> check lowest bit. 1 -> data node. 0 -> ctrl node.
5441 // (2) has_ctrl true: get_ctrl_no_update returns ctrl of data node.
5442 // (3) has_ctrl false: get_loop_idx returns IdealLoopTree for ctrl node.
5443 bool PhaseIdealLoop::verify_loop_ctrl(Node* n, const PhaseIdealLoop* phase_verify) const {
5444 const uint i = n->_idx;
5445 // The loop-tree was built from def to use (top-down).
5446 // The verification happens from use to def (bottom-up).
5447 // We may thus find nodes during verification that are not in the loop-tree.
5448 if (_loop_or_ctrl[i] == nullptr || phase_verify->_loop_or_ctrl[i] == nullptr) {
5449 if (_loop_or_ctrl[i] != nullptr || phase_verify->_loop_or_ctrl[i] != nullptr) {
5450 tty->print_cr("Was reachable in only one. this %d, verify %d.",
5451 _loop_or_ctrl[i] != nullptr, phase_verify->_loop_or_ctrl[i] != nullptr);
5452 n->dump();
5453 return false; // fail
5454 }
5455 // Not reachable for both.
5456 return true; // pass
5457 }
5458
5459 if (n->is_CFG() == has_ctrl(n)) {
5460 tty->print_cr("Exactly one should be true: %d for is_CFG, %d for has_ctrl.", n->is_CFG(), has_ctrl(n));
5461 n->dump();
5462 return false; // fail
5463 }
5464
5465 if (has_ctrl(n) != phase_verify->has_ctrl(n)) {
5466 tty->print_cr("Mismatch has_ctrl: %d for this, %d for verify.", has_ctrl(n), phase_verify->has_ctrl(n));
5467 n->dump();
5468 return false; // fail
5469 } else if (has_ctrl(n)) {
5470 assert(phase_verify->has_ctrl(n), "sanity");
5471 // n is a data node.
5472 // Verify that its ctrl is the same.
5473
5474 // Broken part of VerifyLoopOptimizations (A)
5475 // Reason:
5476 // BUG, wrong control set for example in
5477 // PhaseIdealLoop::split_if_with_blocks
5478 // at "set_ctrl(x, new_ctrl);"
5479 /*
5480 if( _loop_or_ctrl[i] != loop_verify->_loop_or_ctrl[i] &&
5481 get_ctrl_no_update(n) != loop_verify->get_ctrl_no_update(n) ) {
5482 tty->print("Mismatched control setting for: ");
5483 n->dump();
5484 if( fail++ > 10 ) return;
5485 Node *c = get_ctrl_no_update(n);
5486 tty->print("We have it as: ");
5487 if( c->in(0) ) c->dump();
5488 else tty->print_cr("N%d",c->_idx);
5489 tty->print("Verify thinks: ");
5490 if( loop_verify->has_ctrl(n) )
5491 loop_verify->get_ctrl_no_update(n)->dump();
5492 else
5493 loop_verify->get_loop_idx(n)->dump();
5494 tty->cr();
5495 }
5496 */
5497 return true; // pass
5498 } else {
5499 assert(!phase_verify->has_ctrl(n), "sanity");
5500 // n is a ctrl node.
5501 // Verify that not has_ctrl, and that get_loop_idx is the same.
5502
5503 // Broken part of VerifyLoopOptimizations (B)
5504 // Reason:
5505 // NeverBranch node for example is added to loop outside its scope.
5506 // Once we run build_loop_tree again, it is added to the correct loop.
5507 /*
5508 if (!C->major_progress()) {
5509 // Loop selection can be messed up if we did a major progress
5510 // operation, like split-if. Do not verify in that case.
5511 IdealLoopTree *us = get_loop_idx(n);
5512 IdealLoopTree *them = loop_verify->get_loop_idx(n);
5513 if( us->_head != them->_head || us->_tail != them->_tail ) {
5514 tty->print("Unequals loops for: ");
5515 n->dump();
5516 if( fail++ > 10 ) return;
5517 tty->print("We have it as: ");
5518 us->dump();
5519 tty->print("Verify thinks: ");
5520 them->dump();
5521 tty->cr();
5522 }
5523 }
5524 */
5525 return true; // pass
5526 }
5527 }
5528
5529 static int compare_tree(IdealLoopTree* const& a, IdealLoopTree* const& b) {
5530 assert(a != nullptr && b != nullptr, "must be");
5531 return a->_head->_idx - b->_head->_idx;
5532 }
5533
5534 GrowableArray<IdealLoopTree*> IdealLoopTree::collect_sorted_children() const {
5535 GrowableArray<IdealLoopTree*> children;
5536 IdealLoopTree* child = _child;
5537 while (child != nullptr) {
5538 assert(child->_parent == this, "all must be children of this");
5539 children.insert_sorted<compare_tree>(child);
5540 child = child->_next;
5541 }
5542 return children;
5543 }
5544
5545 // Verify that tree structures match. Because the CFG can change, siblings
5546 // within the loop tree can be reordered. We attempt to deal with that by
5547 // reordering the verify's loop tree if possible.
5548 bool IdealLoopTree::verify_tree(IdealLoopTree* loop_verify) const {
5549 assert(_head == loop_verify->_head, "mismatched loop head");
5550 assert(this->_parent != nullptr || this->_next == nullptr, "is_root_loop implies has_no_sibling");
5551
5552 // Collect the children
5553 GrowableArray<IdealLoopTree*> children = collect_sorted_children();
5554 GrowableArray<IdealLoopTree*> children_verify = loop_verify->collect_sorted_children();
5555
5556 bool success = true;
5557
5558 // Compare the two children lists
5559 for (int i = 0, j = 0; i < children.length() || j < children_verify.length(); ) {
5560 IdealLoopTree* child = nullptr;
5561 IdealLoopTree* child_verify = nullptr;
5562 // Read from both lists, if possible.
5563 if (i < children.length()) {
5564 child = children.at(i);
5565 }
5566 if (j < children_verify.length()) {
5567 child_verify = children_verify.at(j);
5568 }
5569 assert(child != nullptr || child_verify != nullptr, "must find at least one");
5570 if (child != nullptr && child_verify != nullptr && child->_head != child_verify->_head) {
5571 // We found two non-equal children. Select the smaller one.
5572 if (child->_head->_idx < child_verify->_head->_idx) {
5573 child_verify = nullptr;
5574 } else {
5575 child = nullptr;
5576 }
5577 }
5578 // Process the two children, or potentially log the failure if we only found one.
5579 if (child_verify == nullptr) {
5580 if (child->_irreducible && Compile::current()->major_progress()) {
5581 // Irreducible loops can pick a different header (one of its entries).
5582 } else {
5583 tty->print_cr("We have a loop that verify does not have");
5584 child->dump();
5585 success = false;
5586 }
5587 i++; // step for this
5588 } else if (child == nullptr) {
5589 if (child_verify->_irreducible && Compile::current()->major_progress()) {
5590 // Irreducible loops can pick a different header (one of its entries).
5591 } else if (child_verify->_head->as_Region()->is_in_infinite_subgraph()) {
5592 // Infinite loops do not get attached to the loop-tree on their first visit.
5593 // "this" runs before "loop_verify". It is thus possible that we find the
5594 // infinite loop only for "child_verify". Only finding it with "child" would
5595 // mean that we lost it, which is not ok.
5596 } else {
5597 tty->print_cr("Verify has a loop that we do not have");
5598 child_verify->dump();
5599 success = false;
5600 }
5601 j++; // step for verify
5602 } else {
5603 assert(child->_head == child_verify->_head, "We have both and they are equal");
5604 success &= child->verify_tree(child_verify); // Recursion
5605 i++; // step for this
5606 j++; // step for verify
5607 }
5608 }
5609
5610 // Broken part of VerifyLoopOptimizations (D)
5611 // Reason:
5612 // split_if has to update the _tail, if it is modified. But that is done by
5613 // checking to what loop the iff belongs to. That info can be wrong, and then
5614 // we do not update the _tail correctly.
5615 /*
5616 Node *tail = _tail; // Inline a non-updating version of
5617 while( !tail->in(0) ) // the 'tail()' call.
5618 tail = tail->in(1);
5619 assert( tail == loop->_tail, "mismatched loop tail" );
5620 */
5621
5622 if (_head->is_CountedLoop()) {
5623 CountedLoopNode *cl = _head->as_CountedLoop();
5624
5625 Node* ctrl = cl->init_control();
5626 Node* back = cl->back_control();
5627 assert(ctrl != nullptr && ctrl->is_CFG(), "sane loop in-ctrl");
5628 assert(back != nullptr && back->is_CFG(), "sane loop backedge");
5629 cl->loopexit(); // assert implied
5630 }
5631
5632 // Broken part of VerifyLoopOptimizations (E)
5633 // Reason:
5634 // PhaseIdealLoop::split_thru_region creates new nodes for loop that are not added
5635 // to the loop body. Or maybe they are not added to the correct loop.
5636 // at "Node* x = n->clone();"
5637 /*
5638 // Innermost loops need to verify loop bodies,
5639 // but only if no 'major_progress'
5640 int fail = 0;
5641 if (!Compile::current()->major_progress() && _child == nullptr) {
5642 for( uint i = 0; i < _body.size(); i++ ) {
5643 Node *n = _body.at(i);
5644 if (n->outcnt() == 0) continue; // Ignore dead
5645 uint j;
5646 for( j = 0; j < loop->_body.size(); j++ )
5647 if( loop->_body.at(j) == n )
5648 break;
5649 if( j == loop->_body.size() ) { // Not found in loop body
5650 // Last ditch effort to avoid assertion: Its possible that we
5651 // have some users (so outcnt not zero) but are still dead.
5652 // Try to find from root.
5653 if (Compile::current()->root()->find(n->_idx)) {
5654 fail++;
5655 tty->print("We have that verify does not: ");
5656 n->dump();
5657 }
5658 }
5659 }
5660 for( uint i2 = 0; i2 < loop->_body.size(); i2++ ) {
5661 Node *n = loop->_body.at(i2);
5662 if (n->outcnt() == 0) continue; // Ignore dead
5663 uint j;
5664 for( j = 0; j < _body.size(); j++ )
5665 if( _body.at(j) == n )
5666 break;
5667 if( j == _body.size() ) { // Not found in loop body
5668 // Last ditch effort to avoid assertion: Its possible that we
5669 // have some users (so outcnt not zero) but are still dead.
5670 // Try to find from root.
5671 if (Compile::current()->root()->find(n->_idx)) {
5672 fail++;
5673 tty->print("Verify has that we do not: ");
5674 n->dump();
5675 }
5676 }
5677 }
5678 assert( !fail, "loop body mismatch" );
5679 }
5680 */
5681 return success;
5682 }
5683 #endif
5684
5685 //------------------------------set_idom---------------------------------------
5686 void PhaseIdealLoop::set_idom(Node* d, Node* n, uint dom_depth) {
5687 _nesting.check(); // Check if a potential reallocation in the resource arena is safe
5688 uint idx = d->_idx;
5689 if (idx >= _idom_size) {
5690 uint newsize = next_power_of_2(idx);
5691 _idom = REALLOC_RESOURCE_ARRAY( Node*, _idom,_idom_size,newsize);
5692 _dom_depth = REALLOC_RESOURCE_ARRAY( uint, _dom_depth,_idom_size,newsize);
5693 memset( _dom_depth + _idom_size, 0, (newsize - _idom_size) * sizeof(uint) );
5694 _idom_size = newsize;
5695 }
5696 _idom[idx] = n;
5697 _dom_depth[idx] = dom_depth;
5698 }
5699
5700 //------------------------------recompute_dom_depth---------------------------------------
5701 // The dominator tree is constructed with only parent pointers.
5702 // This recomputes the depth in the tree by first tagging all
5703 // nodes as "no depth yet" marker. The next pass then runs up
5704 // the dom tree from each node marked "no depth yet", and computes
5705 // the depth on the way back down.
5706 void PhaseIdealLoop::recompute_dom_depth() {
5707 uint no_depth_marker = C->unique();
5708 uint i;
5709 // Initialize depth to "no depth yet" and realize all lazy updates
5710 for (i = 0; i < _idom_size; i++) {
5711 // Only indices with a _dom_depth has a Node* or null (otherwise uninitialized).
5712 if (_dom_depth[i] > 0 && _idom[i] != nullptr) {
5713 _dom_depth[i] = no_depth_marker;
5714
5715 // heal _idom if it has a fwd mapping in _loop_or_ctrl
5716 if (_idom[i]->in(0) == nullptr) {
5717 idom(i);
5718 }
5719 }
5720 }
5721 if (_dom_stk == nullptr) {
5722 uint init_size = C->live_nodes() / 100; // Guess that 1/100 is a reasonable initial size.
5723 if (init_size < 10) init_size = 10;
5724 _dom_stk = new GrowableArray<uint>(init_size);
5725 }
5726 // Compute new depth for each node.
5727 for (i = 0; i < _idom_size; i++) {
5728 uint j = i;
5729 // Run up the dom tree to find a node with a depth
5730 while (_dom_depth[j] == no_depth_marker) {
5731 _dom_stk->push(j);
5732 j = _idom[j]->_idx;
5733 }
5734 // Compute the depth on the way back down this tree branch
5735 uint dd = _dom_depth[j] + 1;
5736 while (_dom_stk->length() > 0) {
5737 uint j = _dom_stk->pop();
5738 _dom_depth[j] = dd;
5739 dd++;
5740 }
5741 }
5742 }
5743
5744 //------------------------------sort-------------------------------------------
5745 // Insert 'loop' into the existing loop tree. 'innermost' is a leaf of the
5746 // loop tree, not the root.
5747 IdealLoopTree *PhaseIdealLoop::sort( IdealLoopTree *loop, IdealLoopTree *innermost ) {
5748 if( !innermost ) return loop; // New innermost loop
5749
5750 int loop_preorder = get_preorder(loop->_head); // Cache pre-order number
5751 assert( loop_preorder, "not yet post-walked loop" );
5752 IdealLoopTree **pp = &innermost; // Pointer to previous next-pointer
5753 IdealLoopTree *l = *pp; // Do I go before or after 'l'?
5754
5755 // Insert at start of list
5756 while( l ) { // Insertion sort based on pre-order
5757 if( l == loop ) return innermost; // Already on list!
5758 int l_preorder = get_preorder(l->_head); // Cache pre-order number
5759 assert( l_preorder, "not yet post-walked l" );
5760 // Check header pre-order number to figure proper nesting
5761 if( loop_preorder > l_preorder )
5762 break; // End of insertion
5763 // If headers tie (e.g., shared headers) check tail pre-order numbers.
5764 // Since I split shared headers, you'd think this could not happen.
5765 // BUT: I must first do the preorder numbering before I can discover I
5766 // have shared headers, so the split headers all get the same preorder
5767 // number as the RegionNode they split from.
5768 if( loop_preorder == l_preorder &&
5769 get_preorder(loop->_tail) < get_preorder(l->_tail) )
5770 break; // Also check for shared headers (same pre#)
5771 pp = &l->_parent; // Chain up list
5772 l = *pp;
5773 }
5774 // Link into list
5775 // Point predecessor to me
5776 *pp = loop;
5777 // Point me to successor
5778 IdealLoopTree *p = loop->_parent;
5779 loop->_parent = l; // Point me to successor
5780 if( p ) sort( p, innermost ); // Insert my parents into list as well
5781 return innermost;
5782 }
5783
5784 //------------------------------build_loop_tree--------------------------------
5785 // I use a modified Vick/Tarjan algorithm. I need pre- and a post- visit
5786 // bits. The _loop_or_ctrl[] array is mapped by Node index and holds a null for
5787 // not-yet-pre-walked, pre-order # for pre-but-not-post-walked and holds the
5788 // tightest enclosing IdealLoopTree for post-walked.
5789 //
5790 // During my forward walk I do a short 1-layer lookahead to see if I can find
5791 // a loop backedge with that doesn't have any work on the backedge. This
5792 // helps me construct nested loops with shared headers better.
5793 //
5794 // Once I've done the forward recursion, I do the post-work. For each child
5795 // I check to see if there is a backedge. Backedges define a loop! I
5796 // insert an IdealLoopTree at the target of the backedge.
5797 //
5798 // During the post-work I also check to see if I have several children
5799 // belonging to different loops. If so, then this Node is a decision point
5800 // where control flow can choose to change loop nests. It is at this
5801 // decision point where I can figure out how loops are nested. At this
5802 // time I can properly order the different loop nests from my children.
5803 // Note that there may not be any backedges at the decision point!
5804 //
5805 // Since the decision point can be far removed from the backedges, I can't
5806 // order my loops at the time I discover them. Thus at the decision point
5807 // I need to inspect loop header pre-order numbers to properly nest my
5808 // loops. This means I need to sort my childrens' loops by pre-order.
5809 // The sort is of size number-of-control-children, which generally limits
5810 // it to size 2 (i.e., I just choose between my 2 target loops).
5811 void PhaseIdealLoop::build_loop_tree() {
5812 // Allocate stack of size C->live_nodes()/2 to avoid frequent realloc
5813 GrowableArray <Node *> bltstack(C->live_nodes() >> 1);
5814 Node *n = C->root();
5815 bltstack.push(n);
5816 int pre_order = 1;
5817 int stack_size;
5818
5819 while ( ( stack_size = bltstack.length() ) != 0 ) {
5820 n = bltstack.top(); // Leave node on stack
5821 if ( !is_visited(n) ) {
5822 // ---- Pre-pass Work ----
5823 // Pre-walked but not post-walked nodes need a pre_order number.
5824
5825 set_preorder_visited( n, pre_order ); // set as visited
5826
5827 // ---- Scan over children ----
5828 // Scan first over control projections that lead to loop headers.
5829 // This helps us find inner-to-outer loops with shared headers better.
5830
5831 // Scan children's children for loop headers.
5832 for ( int i = n->outcnt() - 1; i >= 0; --i ) {
5833 Node* m = n->raw_out(i); // Child
5834 if( m->is_CFG() && !is_visited(m) ) { // Only for CFG children
5835 // Scan over children's children to find loop
5836 for (DUIterator_Fast jmax, j = m->fast_outs(jmax); j < jmax; j++) {
5837 Node* l = m->fast_out(j);
5838 if( is_visited(l) && // Been visited?
5839 !is_postvisited(l) && // But not post-visited
5840 get_preorder(l) < pre_order ) { // And smaller pre-order
5841 // Found! Scan the DFS down this path before doing other paths
5842 bltstack.push(m);
5843 break;
5844 }
5845 }
5846 }
5847 }
5848 pre_order++;
5849 }
5850 else if ( !is_postvisited(n) ) {
5851 // Note: build_loop_tree_impl() adds out edges on rare occasions,
5852 // such as com.sun.rsasign.am::a.
5853 // For non-recursive version, first, process current children.
5854 // On next iteration, check if additional children were added.
5855 for ( int k = n->outcnt() - 1; k >= 0; --k ) {
5856 Node* u = n->raw_out(k);
5857 if ( u->is_CFG() && !is_visited(u) ) {
5858 bltstack.push(u);
5859 }
5860 }
5861 if ( bltstack.length() == stack_size ) {
5862 // There were no additional children, post visit node now
5863 (void)bltstack.pop(); // Remove node from stack
5864 pre_order = build_loop_tree_impl(n, pre_order);
5865 // Check for bailout
5866 if (C->failing()) {
5867 return;
5868 }
5869 // Check to grow _preorders[] array for the case when
5870 // build_loop_tree_impl() adds new nodes.
5871 check_grow_preorders();
5872 }
5873 }
5874 else {
5875 (void)bltstack.pop(); // Remove post-visited node from stack
5876 }
5877 }
5878 DEBUG_ONLY(verify_regions_in_irreducible_loops();)
5879 }
5880
5881 //------------------------------build_loop_tree_impl---------------------------
5882 int PhaseIdealLoop::build_loop_tree_impl(Node* n, int pre_order) {
5883 // ---- Post-pass Work ----
5884 // Pre-walked but not post-walked nodes need a pre_order number.
5885
5886 // Tightest enclosing loop for this Node
5887 IdealLoopTree *innermost = nullptr;
5888
5889 // For all children, see if any edge is a backedge. If so, make a loop
5890 // for it. Then find the tightest enclosing loop for the self Node.
5891 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
5892 Node* m = n->fast_out(i); // Child
5893 if (n == m) continue; // Ignore control self-cycles
5894 if (!m->is_CFG()) continue;// Ignore non-CFG edges
5895
5896 IdealLoopTree *l; // Child's loop
5897 if (!is_postvisited(m)) { // Child visited but not post-visited?
5898 // Found a backedge
5899 assert(get_preorder(m) < pre_order, "should be backedge");
5900 // Check for the RootNode, which is already a LoopNode and is allowed
5901 // to have multiple "backedges".
5902 if (m == C->root()) { // Found the root?
5903 l = _ltree_root; // Root is the outermost LoopNode
5904 } else { // Else found a nested loop
5905 // Insert a LoopNode to mark this loop.
5906 l = new IdealLoopTree(this, m, n);
5907 } // End of Else found a nested loop
5908 if (!has_loop(m)) { // If 'm' does not already have a loop set
5909 set_loop(m, l); // Set loop header to loop now
5910 }
5911 } else { // Else not a nested loop
5912 if (!_loop_or_ctrl[m->_idx]) continue; // Dead code has no loop
5913 IdealLoopTree* m_loop = get_loop(m);
5914 l = m_loop; // Get previously determined loop
5915 // If successor is header of a loop (nest), move up-loop till it
5916 // is a member of some outer enclosing loop. Since there are no
5917 // shared headers (I've split them already) I only need to go up
5918 // at most 1 level.
5919 while (l && l->_head == m) { // Successor heads loop?
5920 l = l->_parent; // Move up 1 for me
5921 }
5922 // If this loop is not properly parented, then this loop
5923 // has no exit path out, i.e. its an infinite loop.
5924 if (!l) {
5925 // Make loop "reachable" from root so the CFG is reachable. Basically
5926 // insert a bogus loop exit that is never taken. 'm', the loop head,
5927 // points to 'n', one (of possibly many) fall-in paths. There may be
5928 // many backedges as well.
5929
5930 if (!_verify_only) {
5931 // Insert the NeverBranch between 'm' and it's control user.
5932 NeverBranchNode *iff = new NeverBranchNode( m );
5933 _igvn.register_new_node_with_optimizer(iff);
5934 set_loop(iff, m_loop);
5935 Node *if_t = new CProjNode( iff, 0 );
5936 _igvn.register_new_node_with_optimizer(if_t);
5937 set_loop(if_t, m_loop);
5938
5939 Node* cfg = nullptr; // Find the One True Control User of m
5940 for (DUIterator_Fast jmax, j = m->fast_outs(jmax); j < jmax; j++) {
5941 Node* x = m->fast_out(j);
5942 if (x->is_CFG() && x != m && x != iff)
5943 { cfg = x; break; }
5944 }
5945 assert(cfg != nullptr, "must find the control user of m");
5946 uint k = 0; // Probably cfg->in(0)
5947 while( cfg->in(k) != m ) k++; // But check in case cfg is a Region
5948 _igvn.replace_input_of(cfg, k, if_t); // Now point to NeverBranch
5949
5950 // Now create the never-taken loop exit
5951 Node *if_f = new CProjNode( iff, 1 );
5952 _igvn.register_new_node_with_optimizer(if_f);
5953 set_loop(if_f, _ltree_root);
5954 // Find frame ptr for Halt. Relies on the optimizer
5955 // V-N'ing. Easier and quicker than searching through
5956 // the program structure.
5957 Node *frame = new ParmNode( C->start(), TypeFunc::FramePtr );
5958 _igvn.register_new_node_with_optimizer(frame);
5959 // Halt & Catch Fire
5960 Node* halt = new HaltNode(if_f, frame, "never-taken loop exit reached");
5961 _igvn.register_new_node_with_optimizer(halt);
5962 set_loop(halt, _ltree_root);
5963 _igvn.add_input_to(C->root(), halt);
5964 }
5965 set_loop(C->root(), _ltree_root);
5966 // move to outer most loop with same header
5967 l = m_loop;
5968 while (true) {
5969 IdealLoopTree* next = l->_parent;
5970 if (next == nullptr || next->_head != m) {
5971 break;
5972 }
5973 l = next;
5974 }
5975 // properly insert infinite loop in loop tree
5976 sort(_ltree_root, l);
5977 // fix child link from parent
5978 IdealLoopTree* p = l->_parent;
5979 l->_next = p->_child;
5980 p->_child = l;
5981 // code below needs enclosing loop
5982 l = l->_parent;
5983 }
5984 }
5985 if (is_postvisited(l->_head)) {
5986 // We are currently visiting l, but its head has already been post-visited.
5987 // l is irreducible: we just found a second entry m.
5988 _has_irreducible_loops = true;
5989 RegionNode* secondary_entry = m->as_Region();
5990
5991 if (!secondary_entry->can_be_irreducible_entry()) {
5992 assert(!VerifyNoNewIrreducibleLoops, "A new irreducible loop was created after parsing.");
5993 C->record_method_not_compilable("A new irreducible loop was created after parsing.");
5994 return pre_order;
5995 }
5996
5997 // Walk up the loop-tree, mark all loops that are already post-visited as irreducible
5998 // Since m is a secondary entry to them all.
5999 while( is_postvisited(l->_head) ) {
6000 l->_irreducible = 1; // = true
6001 RegionNode* head = l->_head->as_Region();
6002 if (!head->can_be_irreducible_entry()) {
6003 assert(!VerifyNoNewIrreducibleLoops, "A new irreducible loop was created after parsing.");
6004 C->record_method_not_compilable("A new irreducible loop was created after parsing.");
6005 return pre_order;
6006 }
6007 l = l->_parent;
6008 // Check for bad CFG here to prevent crash, and bailout of compile
6009 if (l == nullptr) {
6010 #ifndef PRODUCT
6011 if (TraceLoopOpts) {
6012 tty->print_cr("bailout: unhandled CFG: infinite irreducible loop");
6013 m->dump();
6014 }
6015 #endif
6016 // This is a rare case that we do not want to handle in C2.
6017 C->record_method_not_compilable("unhandled CFG detected during loop optimization");
6018 return pre_order;
6019 }
6020 }
6021 }
6022 if (!_verify_only) {
6023 C->set_has_irreducible_loop(_has_irreducible_loops);
6024 }
6025
6026 // This Node might be a decision point for loops. It is only if
6027 // it's children belong to several different loops. The sort call
6028 // does a trivial amount of work if there is only 1 child or all
6029 // children belong to the same loop. If however, the children
6030 // belong to different loops, the sort call will properly set the
6031 // _parent pointers to show how the loops nest.
6032 //
6033 // In any case, it returns the tightest enclosing loop.
6034 innermost = sort( l, innermost );
6035 }
6036
6037 // Def-use info will have some dead stuff; dead stuff will have no
6038 // loop decided on.
6039
6040 // Am I a loop header? If so fix up my parent's child and next ptrs.
6041 if( innermost && innermost->_head == n ) {
6042 assert( get_loop(n) == innermost, "" );
6043 IdealLoopTree *p = innermost->_parent;
6044 IdealLoopTree *l = innermost;
6045 while (p && l->_head == n) {
6046 l->_next = p->_child; // Put self on parents 'next child'
6047 p->_child = l; // Make self as first child of parent
6048 l = p; // Now walk up the parent chain
6049 p = l->_parent;
6050 }
6051 } else {
6052 // Note that it is possible for a LoopNode to reach here, if the
6053 // backedge has been made unreachable (hence the LoopNode no longer
6054 // denotes a Loop, and will eventually be removed).
6055
6056 // Record tightest enclosing loop for self. Mark as post-visited.
6057 set_loop(n, innermost);
6058 // Also record has_call flag early on
6059 if (innermost) {
6060 if( n->is_Call() && !n->is_CallLeaf() && !n->is_macro() ) {
6061 // Do not count uncommon calls
6062 if( !n->is_CallStaticJava() || !n->as_CallStaticJava()->_name ) {
6063 Node *iff = n->in(0)->in(0);
6064 // No any calls for vectorized loops.
6065 if (C->do_superword() ||
6066 !iff->is_If() ||
6067 (n->in(0)->Opcode() == Op_IfFalse && (1.0 - iff->as_If()->_prob) >= 0.01) ||
6068 iff->as_If()->_prob >= 0.01) {
6069 innermost->_has_call = 1;
6070 }
6071 }
6072 } else if( n->is_Allocate() && n->as_Allocate()->_is_scalar_replaceable ) {
6073 // Disable loop optimizations if the loop has a scalar replaceable
6074 // allocation. This disabling may cause a potential performance lost
6075 // if the allocation is not eliminated for some reason.
6076 innermost->_allow_optimizations = false;
6077 innermost->_has_call = 1; // = true
6078 } else if (n->Opcode() == Op_SafePoint) {
6079 // Record all safepoints in this loop.
6080 if (innermost->_safepts == nullptr) innermost->_safepts = new Node_List();
6081 innermost->_safepts->push(n);
6082 }
6083 }
6084 }
6085
6086 // Flag as post-visited now
6087 set_postvisited(n);
6088 return pre_order;
6089 }
6090
6091 #ifdef ASSERT
6092 //--------------------------verify_regions_in_irreducible_loops----------------
6093 // Iterate down from Root through CFG, verify for every region:
6094 // if it is in an irreducible loop it must be marked as such
6095 void PhaseIdealLoop::verify_regions_in_irreducible_loops() {
6096 ResourceMark rm;
6097 if (!_has_irreducible_loops) {
6098 // last build_loop_tree has not found any irreducible loops
6099 // hence no region has to be marked is_in_irreduible_loop
6100 return;
6101 }
6102
6103 RootNode* root = C->root();
6104 Unique_Node_List worklist; // visit all nodes once
6105 worklist.push(root);
6106 bool failure = false;
6107 for (uint i = 0; i < worklist.size(); i++) {
6108 Node* n = worklist.at(i);
6109 if (n->is_Region()) {
6110 RegionNode* region = n->as_Region();
6111 if (is_in_irreducible_loop(region) &&
6112 region->loop_status() == RegionNode::LoopStatus::Reducible) {
6113 failure = true;
6114 tty->print("irreducible! ");
6115 region->dump();
6116 }
6117 }
6118 for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++) {
6119 Node* use = n->fast_out(j);
6120 if (use->is_CFG()) {
6121 worklist.push(use); // push if was not pushed before
6122 }
6123 }
6124 }
6125 assert(!failure, "region in irreducible loop was marked as reducible");
6126 }
6127
6128 //---------------------------is_in_irreducible_loop-------------------------
6129 // Analogous to ciTypeFlow::Block::is_in_irreducible_loop
6130 bool PhaseIdealLoop::is_in_irreducible_loop(RegionNode* region) {
6131 if (!_has_irreducible_loops) {
6132 return false; // no irreducible loop in graph
6133 }
6134 IdealLoopTree* l = get_loop(region); // l: innermost loop that contains region
6135 do {
6136 if (l->_irreducible) {
6137 return true; // found it
6138 }
6139 if (l == _ltree_root) {
6140 return false; // reached root, terimnate
6141 }
6142 l = l->_parent;
6143 } while (l != nullptr);
6144 assert(region->is_in_infinite_subgraph(), "must be in infinite subgraph");
6145 // We have "l->_parent == nullptr", which happens only for infinite loops,
6146 // where no parent is attached to the loop. We did not find any irreducible
6147 // loop from this block out to lp. Thus lp only has one entry, and no exit
6148 // (it is infinite and reducible). We can always rewrite an infinite loop
6149 // that is nested inside other loops:
6150 // while(condition) { infinite_loop; }
6151 // with an equivalent program where the infinite loop is an outermost loop
6152 // that is not nested in any loop:
6153 // while(condition) { break; } infinite_loop;
6154 // Thus, we can understand lp as an outermost loop, and can terminate and
6155 // conclude: this block is in no irreducible loop.
6156 return false;
6157 }
6158 #endif
6159
6160 //------------------------------build_loop_early-------------------------------
6161 // Put Data nodes into some loop nest, by setting the _loop_or_ctrl[]->loop mapping.
6162 // First pass computes the earliest controlling node possible. This is the
6163 // controlling input with the deepest dominating depth.
6164 void PhaseIdealLoop::build_loop_early( VectorSet &visited, Node_List &worklist, Node_Stack &nstack ) {
6165 while (worklist.size() != 0) {
6166 // Use local variables nstack_top_n & nstack_top_i to cache values
6167 // on nstack's top.
6168 Node *nstack_top_n = worklist.pop();
6169 uint nstack_top_i = 0;
6170 //while_nstack_nonempty:
6171 while (true) {
6172 // Get parent node and next input's index from stack's top.
6173 Node *n = nstack_top_n;
6174 uint i = nstack_top_i;
6175 uint cnt = n->req(); // Count of inputs
6176 if (i == 0) { // Pre-process the node.
6177 if( has_node(n) && // Have either loop or control already?
6178 !has_ctrl(n) ) { // Have loop picked out already?
6179 // During "merge_many_backedges" we fold up several nested loops
6180 // into a single loop. This makes the members of the original
6181 // loop bodies pointing to dead loops; they need to move up
6182 // to the new UNION'd larger loop. I set the _head field of these
6183 // dead loops to null and the _parent field points to the owning
6184 // loop. Shades of UNION-FIND algorithm.
6185 IdealLoopTree *ilt;
6186 while( !(ilt = get_loop(n))->_head ) {
6187 // Normally I would use a set_loop here. But in this one special
6188 // case, it is legal (and expected) to change what loop a Node
6189 // belongs to.
6190 _loop_or_ctrl.map(n->_idx, (Node*)(ilt->_parent));
6191 }
6192 // Remove safepoints ONLY if I've already seen I don't need one.
6193 // (the old code here would yank a 2nd safepoint after seeing a
6194 // first one, even though the 1st did not dominate in the loop body
6195 // and thus could be avoided indefinitely)
6196 if( !_verify_only && !_verify_me && ilt->_has_sfpt && n->Opcode() == Op_SafePoint &&
6197 is_deleteable_safept(n)) {
6198 Node *in = n->in(TypeFunc::Control);
6199 replace_node_and_forward_ctrl(n, in); // Pull safepoint now
6200 if (ilt->_safepts != nullptr) {
6201 ilt->_safepts->yank(n);
6202 }
6203 // Carry on with the recursion "as if" we are walking
6204 // only the control input
6205 if( !visited.test_set( in->_idx ) ) {
6206 worklist.push(in); // Visit this guy later, using worklist
6207 }
6208 // Get next node from nstack:
6209 // - skip n's inputs processing by setting i > cnt;
6210 // - we also will not call set_early_ctrl(n) since
6211 // has_node(n) == true (see the condition above).
6212 i = cnt + 1;
6213 }
6214 }
6215 } // if (i == 0)
6216
6217 // Visit all inputs
6218 bool done = true; // Assume all n's inputs will be processed
6219 while (i < cnt) {
6220 Node *in = n->in(i);
6221 ++i;
6222 if (in == nullptr) continue;
6223 if (in->pinned() && !in->is_CFG())
6224 set_ctrl(in, in->in(0));
6225 int is_visited = visited.test_set( in->_idx );
6226 if (!has_node(in)) { // No controlling input yet?
6227 assert( !in->is_CFG(), "CFG Node with no controlling input?" );
6228 assert( !is_visited, "visit only once" );
6229 nstack.push(n, i); // Save parent node and next input's index.
6230 nstack_top_n = in; // Process current input now.
6231 nstack_top_i = 0;
6232 done = false; // Not all n's inputs processed.
6233 break; // continue while_nstack_nonempty;
6234 } else if (!is_visited) {
6235 // This guy has a location picked out for him, but has not yet
6236 // been visited. Happens to all CFG nodes, for instance.
6237 // Visit him using the worklist instead of recursion, to break
6238 // cycles. Since he has a location already we do not need to
6239 // find his location before proceeding with the current Node.
6240 worklist.push(in); // Visit this guy later, using worklist
6241 }
6242 }
6243 if (done) {
6244 // All of n's inputs have been processed, complete post-processing.
6245
6246 // Compute earliest point this Node can go.
6247 // CFG, Phi, pinned nodes already know their controlling input.
6248 if (!has_node(n)) {
6249 // Record earliest legal location
6250 set_early_ctrl(n, false);
6251 }
6252 if (nstack.is_empty()) {
6253 // Finished all nodes on stack.
6254 // Process next node on the worklist.
6255 break;
6256 }
6257 // Get saved parent node and next input's index.
6258 nstack_top_n = nstack.node();
6259 nstack_top_i = nstack.index();
6260 nstack.pop();
6261 }
6262 } // while (true)
6263 }
6264 }
6265
6266 //------------------------------dom_lca_internal--------------------------------
6267 // Pair-wise LCA
6268 Node *PhaseIdealLoop::dom_lca_internal( Node *n1, Node *n2 ) const {
6269 if( !n1 ) return n2; // Handle null original LCA
6270 assert( n1->is_CFG(), "" );
6271 assert( n2->is_CFG(), "" );
6272 // find LCA of all uses
6273 uint d1 = dom_depth(n1);
6274 uint d2 = dom_depth(n2);
6275 while (n1 != n2) {
6276 if (d1 > d2) {
6277 n1 = idom(n1);
6278 d1 = dom_depth(n1);
6279 } else if (d1 < d2) {
6280 n2 = idom(n2);
6281 d2 = dom_depth(n2);
6282 } else {
6283 // Here d1 == d2. Due to edits of the dominator-tree, sections
6284 // of the tree might have the same depth. These sections have
6285 // to be searched more carefully.
6286
6287 // Scan up all the n1's with equal depth, looking for n2.
6288 Node *t1 = idom(n1);
6289 while (dom_depth(t1) == d1) {
6290 if (t1 == n2) return n2;
6291 t1 = idom(t1);
6292 }
6293 // Scan up all the n2's with equal depth, looking for n1.
6294 Node *t2 = idom(n2);
6295 while (dom_depth(t2) == d2) {
6296 if (t2 == n1) return n1;
6297 t2 = idom(t2);
6298 }
6299 // Move up to a new dominator-depth value as well as up the dom-tree.
6300 n1 = t1;
6301 n2 = t2;
6302 d1 = dom_depth(n1);
6303 d2 = dom_depth(n2);
6304 }
6305 }
6306 return n1;
6307 }
6308
6309 //------------------------------compute_idom-----------------------------------
6310 // Locally compute IDOM using dom_lca call. Correct only if the incoming
6311 // IDOMs are correct.
6312 Node *PhaseIdealLoop::compute_idom( Node *region ) const {
6313 assert( region->is_Region(), "" );
6314 Node *LCA = nullptr;
6315 for( uint i = 1; i < region->req(); i++ ) {
6316 if( region->in(i) != C->top() )
6317 LCA = dom_lca( LCA, region->in(i) );
6318 }
6319 return LCA;
6320 }
6321
6322 bool PhaseIdealLoop::verify_dominance(Node* n, Node* use, Node* LCA, Node* early) {
6323 bool had_error = false;
6324 #ifdef ASSERT
6325 if (early != C->root()) {
6326 // Make sure that there's a dominance path from LCA to early
6327 Node* d = LCA;
6328 while (d != early) {
6329 if (d == C->root()) {
6330 dump_bad_graph("Bad graph detected in compute_lca_of_uses", n, early, LCA);
6331 tty->print_cr("*** Use %d isn't dominated by def %d ***", use->_idx, n->_idx);
6332 had_error = true;
6333 break;
6334 }
6335 d = idom(d);
6336 }
6337 }
6338 #endif
6339 return had_error;
6340 }
6341
6342
6343 Node* PhaseIdealLoop::compute_lca_of_uses(Node* n, Node* early, bool verify) {
6344 // Compute LCA over list of uses
6345 bool had_error = false;
6346 Node *LCA = nullptr;
6347 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax && LCA != early; i++) {
6348 Node* c = n->fast_out(i);
6349 if (_loop_or_ctrl[c->_idx] == nullptr)
6350 continue; // Skip the occasional dead node
6351 if( c->is_Phi() ) { // For Phis, we must land above on the path
6352 for( uint j=1; j<c->req(); j++ ) {// For all inputs
6353 if( c->in(j) == n ) { // Found matching input?
6354 Node *use = c->in(0)->in(j);
6355 if (_verify_only && use->is_top()) continue;
6356 LCA = dom_lca_for_get_late_ctrl( LCA, use, n );
6357 if (verify) had_error = verify_dominance(n, use, LCA, early) || had_error;
6358 }
6359 }
6360 } else {
6361 // For CFG data-users, use is in the block just prior
6362 Node *use = has_ctrl(c) ? get_ctrl(c) : c->in(0);
6363 LCA = dom_lca_for_get_late_ctrl( LCA, use, n );
6364 if (verify) had_error = verify_dominance(n, use, LCA, early) || had_error;
6365 }
6366 }
6367 assert(!had_error, "bad dominance");
6368 return LCA;
6369 }
6370
6371 // Check the shape of the graph at the loop entry. In some cases,
6372 // the shape of the graph does not match the shape outlined below.
6373 // That is caused by the Opaque1 node "protecting" the shape of
6374 // the graph being removed by, for example, the IGVN performed
6375 // in PhaseIdealLoop::build_and_optimize().
6376 //
6377 // After the Opaque1 node has been removed, optimizations (e.g., split-if,
6378 // loop unswitching, and IGVN, or a combination of them) can freely change
6379 // the graph's shape. As a result, the graph shape outlined below cannot
6380 // be guaranteed anymore.
6381 Node* CountedLoopNode::is_canonical_loop_entry() {
6382 if (!is_main_loop() && !is_post_loop()) {
6383 return nullptr;
6384 }
6385 Node* ctrl = skip_assertion_predicates_with_halt();
6386
6387 if (ctrl == nullptr || (!ctrl->is_IfTrue() && !ctrl->is_IfFalse())) {
6388 return nullptr;
6389 }
6390 Node* iffm = ctrl->in(0);
6391 if (iffm == nullptr || iffm->Opcode() != Op_If) {
6392 return nullptr;
6393 }
6394 Node* bolzm = iffm->in(1);
6395 if (bolzm == nullptr || !bolzm->is_Bool()) {
6396 return nullptr;
6397 }
6398 Node* cmpzm = bolzm->in(1);
6399 if (cmpzm == nullptr || !cmpzm->is_Cmp()) {
6400 return nullptr;
6401 }
6402
6403 uint input = is_main_loop() ? 2 : 1;
6404 if (input >= cmpzm->req() || cmpzm->in(input) == nullptr) {
6405 return nullptr;
6406 }
6407 bool res = cmpzm->in(input)->Opcode() == Op_OpaqueZeroTripGuard;
6408 #ifdef ASSERT
6409 bool found_opaque = false;
6410 for (uint i = 1; i < cmpzm->req(); i++) {
6411 Node* opnd = cmpzm->in(i);
6412 if (opnd && opnd->is_Opaque1()) {
6413 found_opaque = true;
6414 break;
6415 }
6416 }
6417 assert(found_opaque == res, "wrong pattern");
6418 #endif
6419 return res ? cmpzm->in(input) : nullptr;
6420 }
6421
6422 // Find pre loop end from main loop. Returns nullptr if none.
6423 CountedLoopEndNode* CountedLoopNode::find_pre_loop_end() {
6424 assert(is_main_loop(), "Can only find pre-loop from main-loop");
6425 // The loop cannot be optimized if the graph shape at the loop entry is
6426 // inappropriate.
6427 if (is_canonical_loop_entry() == nullptr) {
6428 return nullptr;
6429 }
6430
6431 Node* p_f = skip_assertion_predicates_with_halt()->in(0)->in(0);
6432 if (!p_f->is_IfFalse() || !p_f->in(0)->is_CountedLoopEnd()) {
6433 return nullptr;
6434 }
6435 CountedLoopEndNode* pre_end = p_f->in(0)->as_CountedLoopEnd();
6436 CountedLoopNode* loop_node = pre_end->loopnode();
6437 if (loop_node == nullptr || !loop_node->is_pre_loop()) {
6438 return nullptr;
6439 }
6440 return pre_end;
6441 }
6442
6443 Node* CountedLoopNode::uncasted_init_trip(bool uncast) {
6444 Node* init = init_trip();
6445 if (uncast && init->is_CastII()) {
6446 // skip over the cast added by PhaseIdealLoop::cast_incr_before_loop() when pre/post/main loops are created because
6447 // it can get in the way of type propagation. For instance, the index tested by an Assertion Predicate, if the cast
6448 // is not skipped over, could be (1):
6449 // (AddI (CastII (AddI pre_loop_iv -2) int) 1)
6450 // while without the cast, it is (2):
6451 // (AddI (AddI pre_loop_iv -2) 1)
6452 // which is be transformed to (3):
6453 // (AddI pre_loop_iv -1)
6454 // The compiler may be able to constant fold the Assertion Predicate condition for (3) but not (1)
6455 assert(init->as_CastII()->carry_dependency() && skip_assertion_predicates_with_halt() == init->in(0), "casted iv phi from pre loop expected");
6456 init = init->in(1);
6457 }
6458 return init;
6459 }
6460
6461 //------------------------------get_late_ctrl----------------------------------
6462 // Compute latest legal control.
6463 Node *PhaseIdealLoop::get_late_ctrl( Node *n, Node *early ) {
6464 assert(early != nullptr, "early control should not be null");
6465
6466 Node* LCA = compute_lca_of_uses(n, early);
6467 #ifdef ASSERT
6468 if (LCA == C->root() && LCA != early) {
6469 // def doesn't dominate uses so print some useful debugging output
6470 compute_lca_of_uses(n, early, true);
6471 }
6472 #endif
6473
6474 if (n->is_Load() && LCA != early) {
6475 LCA = get_late_ctrl_with_anti_dep(n->as_Load(), early, LCA);
6476 }
6477
6478 assert(LCA == find_non_split_ctrl(LCA), "unexpected late control");
6479 return LCA;
6480 }
6481
6482 // if this is a load, check for anti-dependent stores
6483 // We use a conservative algorithm to identify potential interfering
6484 // instructions and for rescheduling the load. The users of the memory
6485 // input of this load are examined. Any use which is not a load and is
6486 // dominated by early is considered a potentially interfering store.
6487 // This can produce false positives.
6488 Node* PhaseIdealLoop::get_late_ctrl_with_anti_dep(LoadNode* n, Node* early, Node* LCA) {
6489 int load_alias_idx = C->get_alias_index(n->adr_type());
6490 if (C->alias_type(load_alias_idx)->is_rewritable()) {
6491 Unique_Node_List worklist;
6492
6493 Node* mem = n->in(MemNode::Memory);
6494 for (DUIterator_Fast imax, i = mem->fast_outs(imax); i < imax; i++) {
6495 Node* s = mem->fast_out(i);
6496 worklist.push(s);
6497 }
6498 for (uint i = 0; i < worklist.size() && LCA != early; i++) {
6499 Node* s = worklist.at(i);
6500 if (s->is_Load() || s->Opcode() == Op_SafePoint ||
6501 (s->is_CallStaticJava() && s->as_CallStaticJava()->uncommon_trap_request() != 0) ||
6502 s->is_Phi()) {
6503 continue;
6504 } else if (s->is_MergeMem()) {
6505 for (DUIterator_Fast imax, i = s->fast_outs(imax); i < imax; i++) {
6506 Node* s1 = s->fast_out(i);
6507 worklist.push(s1);
6508 }
6509 } else {
6510 Node* sctrl = has_ctrl(s) ? get_ctrl(s) : s->in(0);
6511 assert(sctrl != nullptr || !s->is_reachable_from_root(), "must have control");
6512 if (sctrl != nullptr && !sctrl->is_top() && is_dominator(early, sctrl)) {
6513 const TypePtr* adr_type = s->adr_type();
6514 if (s->is_ArrayCopy()) {
6515 // Copy to known instance needs destination type to test for aliasing
6516 const TypePtr* dest_type = s->as_ArrayCopy()->_dest_type;
6517 if (dest_type != TypeOopPtr::BOTTOM) {
6518 adr_type = dest_type;
6519 }
6520 }
6521 if (C->can_alias(adr_type, load_alias_idx)) {
6522 LCA = dom_lca_for_get_late_ctrl(LCA, sctrl, n);
6523 } else if (s->is_CFG() && s->is_Multi()) {
6524 // Look for the memory use of s (that is the use of its memory projection)
6525 for (DUIterator_Fast imax, i = s->fast_outs(imax); i < imax; i++) {
6526 Node* s1 = s->fast_out(i);
6527 assert(s1->is_Proj(), "projection expected");
6528 if (_igvn.type(s1) == Type::MEMORY) {
6529 for (DUIterator_Fast jmax, j = s1->fast_outs(jmax); j < jmax; j++) {
6530 Node* s2 = s1->fast_out(j);
6531 worklist.push(s2);
6532 }
6533 }
6534 }
6535 }
6536 }
6537 }
6538 }
6539 // For Phis only consider Region's inputs that were reached by following the memory edges
6540 if (LCA != early) {
6541 for (uint i = 0; i < worklist.size(); i++) {
6542 Node* s = worklist.at(i);
6543 if (s->is_Phi() && C->can_alias(s->adr_type(), load_alias_idx)) {
6544 Node* r = s->in(0);
6545 for (uint j = 1; j < s->req(); j++) {
6546 Node* in = s->in(j);
6547 Node* r_in = r->in(j);
6548 // We can't reach any node from a Phi because we don't enqueue Phi's uses above
6549 if (((worklist.member(in) && !in->is_Phi()) || in == mem) && is_dominator(early, r_in)) {
6550 LCA = dom_lca_for_get_late_ctrl(LCA, r_in, n);
6551 }
6552 }
6553 }
6554 }
6555 }
6556 }
6557 return LCA;
6558 }
6559
6560 // Is CFG node 'dominator' dominating node 'n'?
6561 bool PhaseIdealLoop::is_dominator(Node* dominator, Node* n) {
6562 if (dominator == n) {
6563 return true;
6564 }
6565 assert(dominator->is_CFG() && n->is_CFG(), "must have CFG nodes");
6566 uint dd = dom_depth(dominator);
6567 while (dom_depth(n) >= dd) {
6568 if (n == dominator) {
6569 return true;
6570 }
6571 n = idom(n);
6572 }
6573 return false;
6574 }
6575
6576 // Is CFG node 'dominator' strictly dominating node 'n'?
6577 bool PhaseIdealLoop::is_strict_dominator(Node* dominator, Node* n) {
6578 return dominator != n && is_dominator(dominator, n);
6579 }
6580
6581 //------------------------------dom_lca_for_get_late_ctrl_internal-------------
6582 // Pair-wise LCA with tags.
6583 // Tag each index with the node 'tag' currently being processed
6584 // before advancing up the dominator chain using idom().
6585 // Later calls that find a match to 'tag' know that this path has already
6586 // been considered in the current LCA (which is input 'n1' by convention).
6587 // Since get_late_ctrl() is only called once for each node, the tag array
6588 // does not need to be cleared between calls to get_late_ctrl().
6589 // Algorithm trades a larger constant factor for better asymptotic behavior
6590 //
6591 Node *PhaseIdealLoop::dom_lca_for_get_late_ctrl_internal(Node *n1, Node *n2, Node *tag_node) {
6592 uint d1 = dom_depth(n1);
6593 uint d2 = dom_depth(n2);
6594 jlong tag = tag_node->_idx | (((jlong)_dom_lca_tags_round) << 32);
6595
6596 do {
6597 if (d1 > d2) {
6598 // current lca is deeper than n2
6599 _dom_lca_tags.at_put_grow(n1->_idx, tag);
6600 n1 = idom(n1);
6601 d1 = dom_depth(n1);
6602 } else if (d1 < d2) {
6603 // n2 is deeper than current lca
6604 jlong memo = _dom_lca_tags.at_grow(n2->_idx, 0);
6605 if (memo == tag) {
6606 return n1; // Return the current LCA
6607 }
6608 _dom_lca_tags.at_put_grow(n2->_idx, tag);
6609 n2 = idom(n2);
6610 d2 = dom_depth(n2);
6611 } else {
6612 // Here d1 == d2. Due to edits of the dominator-tree, sections
6613 // of the tree might have the same depth. These sections have
6614 // to be searched more carefully.
6615
6616 // Scan up all the n1's with equal depth, looking for n2.
6617 _dom_lca_tags.at_put_grow(n1->_idx, tag);
6618 Node *t1 = idom(n1);
6619 while (dom_depth(t1) == d1) {
6620 if (t1 == n2) return n2;
6621 _dom_lca_tags.at_put_grow(t1->_idx, tag);
6622 t1 = idom(t1);
6623 }
6624 // Scan up all the n2's with equal depth, looking for n1.
6625 _dom_lca_tags.at_put_grow(n2->_idx, tag);
6626 Node *t2 = idom(n2);
6627 while (dom_depth(t2) == d2) {
6628 if (t2 == n1) return n1;
6629 _dom_lca_tags.at_put_grow(t2->_idx, tag);
6630 t2 = idom(t2);
6631 }
6632 // Move up to a new dominator-depth value as well as up the dom-tree.
6633 n1 = t1;
6634 n2 = t2;
6635 d1 = dom_depth(n1);
6636 d2 = dom_depth(n2);
6637 }
6638 } while (n1 != n2);
6639 return n1;
6640 }
6641
6642 //------------------------------init_dom_lca_tags------------------------------
6643 // Tag could be a node's integer index, 32bits instead of 64bits in some cases
6644 // Intended use does not involve any growth for the array, so it could
6645 // be of fixed size.
6646 void PhaseIdealLoop::init_dom_lca_tags() {
6647 uint limit = C->unique() + 1;
6648 _dom_lca_tags.at_grow(limit, 0);
6649 _dom_lca_tags_round = 0;
6650 #ifdef ASSERT
6651 for (uint i = 0; i < limit; ++i) {
6652 assert(_dom_lca_tags.at(i) == 0, "Must be distinct from each node pointer");
6653 }
6654 #endif // ASSERT
6655 }
6656
6657 //------------------------------build_loop_late--------------------------------
6658 // Put Data nodes into some loop nest, by setting the _loop_or_ctrl[]->loop mapping.
6659 // Second pass finds latest legal placement, and ideal loop placement.
6660 void PhaseIdealLoop::build_loop_late( VectorSet &visited, Node_List &worklist, Node_Stack &nstack ) {
6661 while (worklist.size() != 0) {
6662 Node *n = worklist.pop();
6663 // Only visit once
6664 if (visited.test_set(n->_idx)) continue;
6665 uint cnt = n->outcnt();
6666 uint i = 0;
6667 while (true) {
6668 assert(_loop_or_ctrl[n->_idx], "no dead nodes");
6669 // Visit all children
6670 if (i < cnt) {
6671 Node* use = n->raw_out(i);
6672 ++i;
6673 // Check for dead uses. Aggressively prune such junk. It might be
6674 // dead in the global sense, but still have local uses so I cannot
6675 // easily call 'remove_dead_node'.
6676 if (_loop_or_ctrl[use->_idx] != nullptr || use->is_top()) { // Not dead?
6677 // Due to cycles, we might not hit the same fixed point in the verify
6678 // pass as we do in the regular pass. Instead, visit such phis as
6679 // simple uses of the loop head.
6680 if( use->in(0) && (use->is_CFG() || use->is_Phi()) ) {
6681 if( !visited.test(use->_idx) )
6682 worklist.push(use);
6683 } else if( !visited.test_set(use->_idx) ) {
6684 nstack.push(n, i); // Save parent and next use's index.
6685 n = use; // Process all children of current use.
6686 cnt = use->outcnt();
6687 i = 0;
6688 }
6689 } else {
6690 // Do not visit around the backedge of loops via data edges.
6691 // push dead code onto a worklist
6692 _deadlist.push(use);
6693 }
6694 } else {
6695 // All of n's children have been processed, complete post-processing.
6696 build_loop_late_post(n);
6697 if (C->failing()) { return; }
6698 if (nstack.is_empty()) {
6699 // Finished all nodes on stack.
6700 // Process next node on the worklist.
6701 break;
6702 }
6703 // Get saved parent node and next use's index. Visit the rest of uses.
6704 n = nstack.node();
6705 cnt = n->outcnt();
6706 i = nstack.index();
6707 nstack.pop();
6708 }
6709 }
6710 }
6711 }
6712
6713 // Verify that no data node is scheduled in the outer loop of a strip
6714 // mined loop.
6715 void PhaseIdealLoop::verify_strip_mined_scheduling(Node *n, Node* least) {
6716 #ifdef ASSERT
6717 if (get_loop(least)->_nest == 0) {
6718 return;
6719 }
6720 IdealLoopTree* loop = get_loop(least);
6721 Node* head = loop->_head;
6722 if (head->is_OuterStripMinedLoop() &&
6723 // Verification can't be applied to fully built strip mined loops
6724 head->as_Loop()->outer_loop_end()->in(1)->find_int_con(-1) == 0) {
6725 Node* sfpt = head->as_Loop()->outer_safepoint();
6726 ResourceMark rm;
6727 Unique_Node_List wq;
6728 wq.push(sfpt);
6729 for (uint i = 0; i < wq.size(); i++) {
6730 Node *m = wq.at(i);
6731 for (uint i = 1; i < m->req(); i++) {
6732 Node* nn = m->in(i);
6733 if (nn == n) {
6734 return;
6735 }
6736 if (nn != nullptr && has_ctrl(nn) && get_loop(get_ctrl(nn)) == loop) {
6737 wq.push(nn);
6738 }
6739 }
6740 }
6741 ShouldNotReachHere();
6742 }
6743 #endif
6744 }
6745
6746
6747 //------------------------------build_loop_late_post---------------------------
6748 // Put Data nodes into some loop nest, by setting the _loop_or_ctrl[]->loop mapping.
6749 // Second pass finds latest legal placement, and ideal loop placement.
6750 void PhaseIdealLoop::build_loop_late_post(Node *n) {
6751 build_loop_late_post_work(n, true);
6752 }
6753
6754 // Class to visit all predicates in a predicate chain to find out which are dominated by a given node. Keeps track of
6755 // the entry to the earliest predicate that is still dominated by the given dominator. This class is used when trying to
6756 // legally skip all predicates when figuring out the latest placement such that a node does not interfere with Loop
6757 // Predication or creating a Loop Limit Check Predicate later.
6758 class DominatedPredicates : public UnifiedPredicateVisitor {
6759 Node* const _dominator;
6760 Node* _earliest_dominated_predicate_entry;
6761 bool _should_continue;
6762 PhaseIdealLoop* const _phase;
6763
6764 public:
6765 DominatedPredicates(Node* dominator, Node* start_node, PhaseIdealLoop* phase)
6766 : _dominator(dominator),
6767 _earliest_dominated_predicate_entry(start_node),
6768 _should_continue(true),
6769 _phase(phase) {}
6770 NONCOPYABLE(DominatedPredicates);
6771
6772 bool should_continue() const override {
6773 return _should_continue;
6774 }
6775
6776 // Returns the entry to the earliest predicate that is still dominated by the given dominator (all could be dominated).
6777 Node* earliest_dominated_predicate_entry() const {
6778 return _earliest_dominated_predicate_entry;
6779 }
6780
6781 void visit_predicate(const Predicate& predicate) override {
6782 Node* entry = predicate.entry();
6783 if (_phase->is_strict_dominator(entry, _dominator)) {
6784 _should_continue = false;
6785 } else {
6786 _earliest_dominated_predicate_entry = entry;
6787 }
6788 }
6789 };
6790
6791 void PhaseIdealLoop::build_loop_late_post_work(Node *n, bool pinned) {
6792
6793 if (n->req() == 2 && (n->Opcode() == Op_ConvI2L || n->Opcode() == Op_CastII) && !C->major_progress() && !_verify_only) {
6794 _igvn._worklist.push(n); // Maybe we'll normalize it, if no more loops.
6795 }
6796
6797 #ifdef ASSERT
6798 if (_verify_only && !n->is_CFG()) {
6799 // Check def-use domination.
6800 // We would like to expose this check in product but it appears to be expensive.
6801 compute_lca_of_uses(n, get_ctrl(n), true /* verify */);
6802 }
6803 #endif
6804
6805 // CFG and pinned nodes already handled
6806 if( n->in(0) ) {
6807 if( n->in(0)->is_top() ) return; // Dead?
6808
6809 // We'd like +VerifyLoopOptimizations to not believe that Mod's/Loads
6810 // _must_ be pinned (they have to observe their control edge of course).
6811 // Unlike Stores (which modify an unallocable resource, the memory
6812 // state), Mods/Loads can float around. So free them up.
6813 switch( n->Opcode() ) {
6814 case Op_DivI:
6815 case Op_DivF:
6816 case Op_DivD:
6817 case Op_ModI:
6818 case Op_LoadB: // Same with Loads; they can sink
6819 case Op_LoadUB: // during loop optimizations.
6820 case Op_LoadUS:
6821 case Op_LoadD:
6822 case Op_LoadF:
6823 case Op_LoadI:
6824 case Op_LoadKlass:
6825 case Op_LoadNKlass:
6826 case Op_LoadL:
6827 case Op_LoadS:
6828 case Op_LoadP:
6829 case Op_LoadN:
6830 case Op_LoadRange:
6831 case Op_LoadD_unaligned:
6832 case Op_LoadL_unaligned:
6833 case Op_StrComp: // Does a bunch of load-like effects
6834 case Op_StrEquals:
6835 case Op_StrIndexOf:
6836 case Op_StrIndexOfChar:
6837 case Op_AryEq:
6838 case Op_VectorizedHashCode:
6839 case Op_CountPositives:
6840 pinned = false;
6841 }
6842 if (n->is_CMove() || n->is_ConstraintCast()) {
6843 pinned = false;
6844 }
6845 if( pinned ) {
6846 IdealLoopTree *chosen_loop = get_loop(n->is_CFG() ? n : get_ctrl(n));
6847 if( !chosen_loop->_child ) // Inner loop?
6848 chosen_loop->_body.push(n); // Collect inner loops
6849 return;
6850 }
6851 } else { // No slot zero
6852 if( n->is_CFG() ) { // CFG with no slot 0 is dead
6853 _loop_or_ctrl.map(n->_idx,nullptr); // No block setting, it's globally dead
6854 return;
6855 }
6856 assert(!n->is_CFG() || n->outcnt() == 0, "");
6857 }
6858
6859 // Do I have a "safe range" I can select over?
6860 Node *early = get_ctrl(n);// Early location already computed
6861
6862 // Compute latest point this Node can go
6863 Node *LCA = get_late_ctrl( n, early );
6864 // LCA is null due to uses being dead
6865 if( LCA == nullptr ) {
6866 #ifdef ASSERT
6867 for (DUIterator i1 = n->outs(); n->has_out(i1); i1++) {
6868 assert(_loop_or_ctrl[n->out(i1)->_idx] == nullptr, "all uses must also be dead");
6869 }
6870 #endif
6871 _loop_or_ctrl.map(n->_idx, nullptr); // This node is useless
6872 _deadlist.push(n);
6873 return;
6874 }
6875 assert(LCA != nullptr && !LCA->is_top(), "no dead nodes");
6876
6877 Node *legal = LCA; // Walk 'legal' up the IDOM chain
6878 Node *least = legal; // Best legal position so far
6879 while( early != legal ) { // While not at earliest legal
6880 if (legal->is_Start() && !early->is_Root()) {
6881 #ifdef ASSERT
6882 // Bad graph. Print idom path and fail.
6883 dump_bad_graph("Bad graph detected in build_loop_late", n, early, LCA);
6884 assert(false, "Bad graph detected in build_loop_late");
6885 #endif
6886 C->record_method_not_compilable("Bad graph detected in build_loop_late");
6887 return;
6888 }
6889 // Find least loop nesting depth
6890 legal = idom(legal); // Bump up the IDOM tree
6891 // Check for lower nesting depth
6892 if( get_loop(legal)->_nest < get_loop(least)->_nest )
6893 least = legal;
6894 }
6895 assert(early == legal || legal != C->root(), "bad dominance of inputs");
6896
6897 if (least != early) {
6898 // Move the node above predicates as far up as possible so a
6899 // following pass of Loop Predication doesn't hoist a predicate
6900 // that depends on it above that node.
6901 const PredicateIterator predicate_iterator(least);
6902 DominatedPredicates dominated_predicates(early, least, this);
6903 predicate_iterator.for_each(dominated_predicates);
6904 least = dominated_predicates.earliest_dominated_predicate_entry();
6905 }
6906 // Try not to place code on a loop entry projection
6907 // which can inhibit range check elimination.
6908 if (least != early) {
6909 Node* ctrl_out = least->unique_ctrl_out_or_null();
6910 if (ctrl_out != nullptr && ctrl_out->is_Loop() &&
6911 least == ctrl_out->in(LoopNode::EntryControl) &&
6912 (ctrl_out->is_CountedLoop() || ctrl_out->is_OuterStripMinedLoop())) {
6913 Node* least_dom = idom(least);
6914 if (get_loop(least_dom)->is_member(get_loop(least))) {
6915 least = least_dom;
6916 }
6917 }
6918 }
6919 // Don't extend live ranges of raw oops
6920 if (least != early && n->is_ConstraintCast() && n->in(1)->bottom_type()->isa_rawptr() &&
6921 !n->bottom_type()->isa_rawptr()) {
6922 least = early;
6923 }
6924
6925 #ifdef ASSERT
6926 // Broken part of VerifyLoopOptimizations (F)
6927 // Reason:
6928 // _verify_me->get_ctrl_no_update(n) seems to return wrong result
6929 /*
6930 // If verifying, verify that 'verify_me' has a legal location
6931 // and choose it as our location.
6932 if( _verify_me ) {
6933 Node *v_ctrl = _verify_me->get_ctrl_no_update(n);
6934 Node *legal = LCA;
6935 while( early != legal ) { // While not at earliest legal
6936 if( legal == v_ctrl ) break; // Check for prior good location
6937 legal = idom(legal) ;// Bump up the IDOM tree
6938 }
6939 // Check for prior good location
6940 if( legal == v_ctrl ) least = legal; // Keep prior if found
6941 }
6942 */
6943 #endif
6944
6945 // Assign discovered "here or above" point
6946 least = find_non_split_ctrl(least);
6947 verify_strip_mined_scheduling(n, least);
6948 set_ctrl(n, least);
6949
6950 // Collect inner loop bodies
6951 IdealLoopTree *chosen_loop = get_loop(least);
6952 if( !chosen_loop->_child ) // Inner loop?
6953 chosen_loop->_body.push(n);// Collect inner loops
6954
6955 if (!_verify_only && n->Opcode() == Op_OpaqueZeroTripGuard) {
6956 _zero_trip_guard_opaque_nodes.push(n);
6957 }
6958
6959 if (!_verify_only && n->Opcode() == Op_OpaqueMultiversioning) {
6960 _multiversion_opaque_nodes.push(n);
6961 }
6962 }
6963
6964 #ifdef ASSERT
6965 void PhaseIdealLoop::dump_bad_graph(const char* msg, Node* n, Node* early, Node* LCA) {
6966 tty->print_cr("%s", msg);
6967 tty->print("n: "); n->dump();
6968 tty->print("early(n): "); early->dump();
6969 if (n->in(0) != nullptr && !n->in(0)->is_top() &&
6970 n->in(0) != early && !n->in(0)->is_Root()) {
6971 tty->print("n->in(0): "); n->in(0)->dump();
6972 }
6973 for (uint i = 1; i < n->req(); i++) {
6974 Node* in1 = n->in(i);
6975 if (in1 != nullptr && in1 != n && !in1->is_top()) {
6976 tty->print("n->in(%d): ", i); in1->dump();
6977 Node* in1_early = get_ctrl(in1);
6978 tty->print("early(n->in(%d)): ", i); in1_early->dump();
6979 if (in1->in(0) != nullptr && !in1->in(0)->is_top() &&
6980 in1->in(0) != in1_early && !in1->in(0)->is_Root()) {
6981 tty->print("n->in(%d)->in(0): ", i); in1->in(0)->dump();
6982 }
6983 for (uint j = 1; j < in1->req(); j++) {
6984 Node* in2 = in1->in(j);
6985 if (in2 != nullptr && in2 != n && in2 != in1 && !in2->is_top()) {
6986 tty->print("n->in(%d)->in(%d): ", i, j); in2->dump();
6987 Node* in2_early = get_ctrl(in2);
6988 tty->print("early(n->in(%d)->in(%d)): ", i, j); in2_early->dump();
6989 if (in2->in(0) != nullptr && !in2->in(0)->is_top() &&
6990 in2->in(0) != in2_early && !in2->in(0)->is_Root()) {
6991 tty->print("n->in(%d)->in(%d)->in(0): ", i, j); in2->in(0)->dump();
6992 }
6993 }
6994 }
6995 }
6996 }
6997 tty->cr();
6998 tty->print("LCA(n): "); LCA->dump();
6999 for (uint i = 0; i < n->outcnt(); i++) {
7000 Node* u1 = n->raw_out(i);
7001 if (u1 == n)
7002 continue;
7003 tty->print("n->out(%d): ", i); u1->dump();
7004 if (u1->is_CFG()) {
7005 for (uint j = 0; j < u1->outcnt(); j++) {
7006 Node* u2 = u1->raw_out(j);
7007 if (u2 != u1 && u2 != n && u2->is_CFG()) {
7008 tty->print("n->out(%d)->out(%d): ", i, j); u2->dump();
7009 }
7010 }
7011 } else {
7012 Node* u1_later = get_ctrl(u1);
7013 tty->print("later(n->out(%d)): ", i); u1_later->dump();
7014 if (u1->in(0) != nullptr && !u1->in(0)->is_top() &&
7015 u1->in(0) != u1_later && !u1->in(0)->is_Root()) {
7016 tty->print("n->out(%d)->in(0): ", i); u1->in(0)->dump();
7017 }
7018 for (uint j = 0; j < u1->outcnt(); j++) {
7019 Node* u2 = u1->raw_out(j);
7020 if (u2 == n || u2 == u1)
7021 continue;
7022 tty->print("n->out(%d)->out(%d): ", i, j); u2->dump();
7023 if (!u2->is_CFG()) {
7024 Node* u2_later = get_ctrl(u2);
7025 tty->print("later(n->out(%d)->out(%d)): ", i, j); u2_later->dump();
7026 if (u2->in(0) != nullptr && !u2->in(0)->is_top() &&
7027 u2->in(0) != u2_later && !u2->in(0)->is_Root()) {
7028 tty->print("n->out(%d)->in(0): ", i); u2->in(0)->dump();
7029 }
7030 }
7031 }
7032 }
7033 }
7034 dump_idoms(early, LCA);
7035 tty->cr();
7036 }
7037
7038 // Class to compute the real LCA given an early node and a wrong LCA in a bad graph.
7039 class RealLCA {
7040 const PhaseIdealLoop* _phase;
7041 Node* _early;
7042 Node* _wrong_lca;
7043 uint _early_index;
7044 int _wrong_lca_index;
7045
7046 // Given idom chains of early and wrong LCA: Walk through idoms starting at StartNode and find the first node which
7047 // is different: Return the previously visited node which must be the real LCA.
7048 // The node lists also contain _early and _wrong_lca, respectively.
7049 Node* find_real_lca(Unique_Node_List& early_with_idoms, Unique_Node_List& wrong_lca_with_idoms) {
7050 int early_index = early_with_idoms.size() - 1;
7051 int wrong_lca_index = wrong_lca_with_idoms.size() - 1;
7052 bool found_difference = false;
7053 do {
7054 if (early_with_idoms[early_index] != wrong_lca_with_idoms[wrong_lca_index]) {
7055 // First time early and wrong LCA idoms differ. Real LCA must be at the previous index.
7056 found_difference = true;
7057 break;
7058 }
7059 early_index--;
7060 wrong_lca_index--;
7061 } while (wrong_lca_index >= 0);
7062
7063 assert(early_index >= 0, "must always find an LCA - cannot be early");
7064 _early_index = early_index;
7065 _wrong_lca_index = wrong_lca_index;
7066 Node* real_lca = early_with_idoms[_early_index + 1]; // Plus one to skip _early.
7067 assert(found_difference || real_lca == _wrong_lca, "wrong LCA dominates early and is therefore the real LCA");
7068 return real_lca;
7069 }
7070
7071 void dump(Node* real_lca) {
7072 tty->cr();
7073 tty->print_cr("idoms of early \"%d %s\":", _early->_idx, _early->Name());
7074 _phase->dump_idom(_early, _early_index + 1);
7075
7076 tty->cr();
7077 tty->print_cr("idoms of (wrong) LCA \"%d %s\":", _wrong_lca->_idx, _wrong_lca->Name());
7078 _phase->dump_idom(_wrong_lca, _wrong_lca_index + 1);
7079
7080 tty->cr();
7081 tty->print("Real LCA of early \"%d %s\" (idom[%d]) and wrong LCA \"%d %s\"",
7082 _early->_idx, _early->Name(), _early_index, _wrong_lca->_idx, _wrong_lca->Name());
7083 if (_wrong_lca_index >= 0) {
7084 tty->print(" (idom[%d])", _wrong_lca_index);
7085 }
7086 tty->print_cr(":");
7087 real_lca->dump();
7088 }
7089
7090 public:
7091 RealLCA(const PhaseIdealLoop* phase, Node* early, Node* wrong_lca)
7092 : _phase(phase), _early(early), _wrong_lca(wrong_lca), _early_index(0), _wrong_lca_index(0) {
7093 assert(!wrong_lca->is_Start(), "StartNode is always a common dominator");
7094 }
7095
7096 void compute_and_dump() {
7097 ResourceMark rm;
7098 Unique_Node_List early_with_idoms;
7099 Unique_Node_List wrong_lca_with_idoms;
7100 early_with_idoms.push(_early);
7101 wrong_lca_with_idoms.push(_wrong_lca);
7102 _phase->get_idoms(_early, 10000, early_with_idoms);
7103 _phase->get_idoms(_wrong_lca, 10000, wrong_lca_with_idoms);
7104 Node* real_lca = find_real_lca(early_with_idoms, wrong_lca_with_idoms);
7105 dump(real_lca);
7106 }
7107 };
7108
7109 // Dump the idom chain of early, of the wrong LCA and dump the real LCA of early and wrong LCA.
7110 void PhaseIdealLoop::dump_idoms(Node* early, Node* wrong_lca) {
7111 assert(!is_dominator(early, wrong_lca), "sanity check that early does not dominate wrong lca");
7112 assert(!has_ctrl(early) && !has_ctrl(wrong_lca), "sanity check, no data nodes");
7113
7114 RealLCA real_lca(this, early, wrong_lca);
7115 real_lca.compute_and_dump();
7116 }
7117 #endif // ASSERT
7118
7119 #ifndef PRODUCT
7120 //------------------------------dump-------------------------------------------
7121 void PhaseIdealLoop::dump() const {
7122 ResourceMark rm;
7123 Node_Stack stack(C->live_nodes() >> 2);
7124 Node_List rpo_list;
7125 VectorSet visited;
7126 visited.set(C->top()->_idx);
7127 rpo(C->root(), stack, visited, rpo_list);
7128 // Dump root loop indexed by last element in PO order
7129 dump(_ltree_root, rpo_list.size(), rpo_list);
7130 }
7131
7132 void PhaseIdealLoop::dump(IdealLoopTree* loop, uint idx, Node_List &rpo_list) const {
7133 loop->dump_head();
7134
7135 // Now scan for CFG nodes in the same loop
7136 for (uint j = idx; j > 0; j--) {
7137 Node* n = rpo_list[j-1];
7138 if (!_loop_or_ctrl[n->_idx]) // Skip dead nodes
7139 continue;
7140
7141 if (get_loop(n) != loop) { // Wrong loop nest
7142 if (get_loop(n)->_head == n && // Found nested loop?
7143 get_loop(n)->_parent == loop)
7144 dump(get_loop(n), rpo_list.size(), rpo_list); // Print it nested-ly
7145 continue;
7146 }
7147
7148 // Dump controlling node
7149 tty->sp(2 * loop->_nest);
7150 tty->print("C");
7151 if (n == C->root()) {
7152 n->dump();
7153 } else {
7154 Node* cached_idom = idom_no_update(n);
7155 Node* computed_idom = n->in(0);
7156 if (n->is_Region()) {
7157 computed_idom = compute_idom(n);
7158 // computed_idom() will return n->in(0) when idom(n) is an IfNode (or
7159 // any MultiBranch ctrl node), so apply a similar transform to
7160 // the cached idom returned from idom_no_update.
7161 cached_idom = find_non_split_ctrl(cached_idom);
7162 }
7163 tty->print(" ID:%d", computed_idom->_idx);
7164 n->dump();
7165 if (cached_idom != computed_idom) {
7166 tty->print_cr("*** BROKEN IDOM! Computed as: %d, cached as: %d",
7167 computed_idom->_idx, cached_idom->_idx);
7168 }
7169 }
7170 // Dump nodes it controls
7171 for (uint k = 0; k < _loop_or_ctrl.max(); k++) {
7172 // (k < C->unique() && get_ctrl(find(k)) == n)
7173 if (k < C->unique() && _loop_or_ctrl[k] == (Node*)((intptr_t)n + 1)) {
7174 Node* m = C->root()->find(k);
7175 if (m && m->outcnt() > 0) {
7176 if (!(has_ctrl(m) && get_ctrl_no_update(m) == n)) {
7177 tty->print_cr("*** BROKEN CTRL ACCESSOR! _loop_or_ctrl[k] is %p, ctrl is %p",
7178 _loop_or_ctrl[k], has_ctrl(m) ? get_ctrl_no_update(m) : nullptr);
7179 }
7180 tty->sp(2 * loop->_nest + 1);
7181 m->dump();
7182 }
7183 }
7184 }
7185 }
7186 }
7187
7188 void PhaseIdealLoop::dump_idom(Node* n, const uint count) const {
7189 if (has_ctrl(n)) {
7190 tty->print_cr("No idom for data nodes");
7191 } else {
7192 ResourceMark rm;
7193 Unique_Node_List idoms;
7194 get_idoms(n, count, idoms);
7195 dump_idoms_in_reverse(n, idoms);
7196 }
7197 }
7198
7199 void PhaseIdealLoop::get_idoms(Node* n, const uint count, Unique_Node_List& idoms) const {
7200 Node* next = n;
7201 for (uint i = 0; !next->is_Start() && i < count; i++) {
7202 next = idom(next);
7203 assert(!idoms.member(next), "duplicated idom is not possible");
7204 idoms.push(next);
7205 }
7206 }
7207
7208 void PhaseIdealLoop::dump_idoms_in_reverse(const Node* n, const Node_List& idom_list) const {
7209 Node* next;
7210 uint padding = 3;
7211 uint node_index_padding_width = (C->unique() == 0 ? 0 : static_cast<int>(log10(static_cast<double>(C->unique())))) + 1;
7212 for (int i = idom_list.size() - 1; i >= 0; i--) {
7213 if (i == 9 || i == 99) {
7214 padding++;
7215 }
7216 next = idom_list[i];
7217 tty->print_cr("idom[%d]:%*c%*d %s", i, padding, ' ', node_index_padding_width, next->_idx, next->Name());
7218 }
7219 tty->print_cr("n: %*c%*d %s", padding, ' ', node_index_padding_width, n->_idx, n->Name());
7220 }
7221 #endif // NOT PRODUCT
7222
7223 // Collect a R-P-O for the whole CFG.
7224 // Result list is in post-order (scan backwards for RPO)
7225 void PhaseIdealLoop::rpo(Node* start, Node_Stack &stk, VectorSet &visited, Node_List &rpo_list) const {
7226 stk.push(start, 0);
7227 visited.set(start->_idx);
7228
7229 while (stk.is_nonempty()) {
7230 Node* m = stk.node();
7231 uint idx = stk.index();
7232 if (idx < m->outcnt()) {
7233 stk.set_index(idx + 1);
7234 Node* n = m->raw_out(idx);
7235 if (n->is_CFG() && !visited.test_set(n->_idx)) {
7236 stk.push(n, 0);
7237 }
7238 } else {
7239 rpo_list.push(m);
7240 stk.pop();
7241 }
7242 }
7243 }
7244
7245 ConINode* PhaseIdealLoop::intcon(jint i) {
7246 ConINode* node = _igvn.intcon(i);
7247 set_root_as_ctrl(node);
7248 return node;
7249 }
7250
7251 ConLNode* PhaseIdealLoop::longcon(jlong i) {
7252 ConLNode* node = _igvn.longcon(i);
7253 set_root_as_ctrl(node);
7254 return node;
7255 }
7256
7257 ConNode* PhaseIdealLoop::makecon(const Type* t) {
7258 ConNode* node = _igvn.makecon(t);
7259 set_root_as_ctrl(node);
7260 return node;
7261 }
7262
7263 ConNode* PhaseIdealLoop::integercon(jlong l, BasicType bt) {
7264 ConNode* node = _igvn.integercon(l, bt);
7265 set_root_as_ctrl(node);
7266 return node;
7267 }
7268
7269 ConNode* PhaseIdealLoop::zerocon(BasicType bt) {
7270 ConNode* node = _igvn.zerocon(bt);
7271 set_root_as_ctrl(node);
7272 return node;
7273 }
7274
7275
7276 //=============================================================================
7277 //------------------------------LoopTreeIterator-------------------------------
7278
7279 // Advance to next loop tree using a preorder, left-to-right traversal.
7280 void LoopTreeIterator::next() {
7281 assert(!done(), "must not be done.");
7282 if (_curnt->_child != nullptr) {
7283 _curnt = _curnt->_child;
7284 } else if (_curnt->_next != nullptr) {
7285 _curnt = _curnt->_next;
7286 } else {
7287 while (_curnt != _root && _curnt->_next == nullptr) {
7288 _curnt = _curnt->_parent;
7289 }
7290 if (_curnt == _root) {
7291 _curnt = nullptr;
7292 assert(done(), "must be done.");
7293 } else {
7294 assert(_curnt->_next != nullptr, "must be more to do");
7295 _curnt = _curnt->_next;
7296 }
7297 }
7298 }