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