1 /*
2 * Copyright (c) 1998, 2020, 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 "precompiled.hpp"
26 #include "ci/ciMethodData.hpp"
27 #include "compiler/compileLog.hpp"
28 #include "gc/shared/barrierSet.hpp"
29 #include "gc/shared/c2/barrierSetC2.hpp"
30 #include "libadt/vectset.hpp"
31 #include "memory/allocation.inline.hpp"
32 #include "memory/resourceArea.hpp"
33 #include "opto/addnode.hpp"
34 #include "opto/arraycopynode.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/rootnode.hpp"
46 #include "opto/runtime.hpp"
47 #include "opto/superword.hpp"
48 #include "runtime/sharedRuntime.hpp"
49 #include "utilities/powerOfTwo.hpp"
50
51 //=============================================================================
52 //--------------------------is_cloop_ind_var-----------------------------------
53 // Determine if a node is a counted loop induction variable.
54 // NOTE: The method is declared in "node.hpp".
is_cloop_ind_var() const55 bool Node::is_cloop_ind_var() const {
56 return (is_Phi() &&
57 as_Phi()->region()->is_CountedLoop() &&
58 as_Phi()->region()->as_CountedLoop()->phi() == this);
59 }
60
61 //=============================================================================
62 //------------------------------dump_spec--------------------------------------
63 // Dump special per-node info
64 #ifndef PRODUCT
dump_spec(outputStream * st) const65 void LoopNode::dump_spec(outputStream *st) const {
66 if (is_inner_loop()) st->print( "inner " );
67 if (is_partial_peel_loop()) st->print( "partial_peel " );
68 if (partial_peel_has_failed()) st->print( "partial_peel_failed " );
69 }
70 #endif
71
72 //------------------------------is_valid_counted_loop-------------------------
is_valid_counted_loop(BasicType bt) const73 bool LoopNode::is_valid_counted_loop(BasicType bt) const {
74 if (is_BaseCountedLoop() && operates_on(bt, false)) {
75 BaseCountedLoopNode* l = as_BaseCountedLoop();
76 BaseCountedLoopEndNode* le = l->loopexit_or_null();
77 if (le != NULL &&
78 le->proj_out_or_null(1 /* true */) == l->in(LoopNode::LoopBackControl)) {
79 Node* phi = l->phi();
80 Node* exit = le->proj_out_or_null(0 /* false */);
81 if (exit != NULL && exit->Opcode() == Op_IfFalse &&
82 phi != NULL && phi->is_Phi() &&
83 phi->in(LoopNode::LoopBackControl) == l->incr() &&
84 le->loopnode() == l && le->stride_is_con()) {
85 return true;
86 }
87 }
88 }
89 return false;
90 }
91
92 //------------------------------get_early_ctrl---------------------------------
93 // Compute earliest legal control
get_early_ctrl(Node * n)94 Node *PhaseIdealLoop::get_early_ctrl( Node *n ) {
95 assert( !n->is_Phi() && !n->is_CFG(), "this code only handles data nodes" );
96 uint i;
97 Node *early;
98 if (n->in(0) && !n->is_expensive()) {
99 early = n->in(0);
100 if (!early->is_CFG()) // Might be a non-CFG multi-def
101 early = get_ctrl(early); // So treat input as a straight data input
102 i = 1;
103 } else {
104 early = get_ctrl(n->in(1));
105 i = 2;
106 }
107 uint e_d = dom_depth(early);
108 assert( early, "" );
109 for (; i < n->req(); i++) {
110 Node *cin = get_ctrl(n->in(i));
111 assert( cin, "" );
112 // Keep deepest dominator depth
113 uint c_d = dom_depth(cin);
114 if (c_d > e_d) { // Deeper guy?
115 early = cin; // Keep deepest found so far
116 e_d = c_d;
117 } else if (c_d == e_d && // Same depth?
118 early != cin) { // If not equal, must use slower algorithm
119 // If same depth but not equal, one _must_ dominate the other
120 // and we want the deeper (i.e., dominated) guy.
121 Node *n1 = early;
122 Node *n2 = cin;
123 while (1) {
124 n1 = idom(n1); // Walk up until break cycle
125 n2 = idom(n2);
126 if (n1 == cin || // Walked early up to cin
127 dom_depth(n2) < c_d)
128 break; // early is deeper; keep him
129 if (n2 == early || // Walked cin up to early
130 dom_depth(n1) < c_d) {
131 early = cin; // cin is deeper; keep him
132 break;
133 }
134 }
135 e_d = dom_depth(early); // Reset depth register cache
136 }
137 }
138
139 // Return earliest legal location
140 assert(early == find_non_split_ctrl(early), "unexpected early control");
141
142 if (n->is_expensive() && !_verify_only && !_verify_me) {
143 assert(n->in(0), "should have control input");
144 early = get_early_ctrl_for_expensive(n, early);
145 }
146
147 return early;
148 }
149
150 //------------------------------get_early_ctrl_for_expensive---------------------------------
151 // Move node up the dominator tree as high as legal while still beneficial
get_early_ctrl_for_expensive(Node * n,Node * earliest)152 Node *PhaseIdealLoop::get_early_ctrl_for_expensive(Node *n, Node* earliest) {
153 assert(n->in(0) && n->is_expensive(), "expensive node with control input here");
154 assert(OptimizeExpensiveOps, "optimization off?");
155
156 Node* ctl = n->in(0);
157 assert(ctl->is_CFG(), "expensive input 0 must be cfg");
158 uint min_dom_depth = dom_depth(earliest);
159 #ifdef ASSERT
160 if (!is_dominator(ctl, earliest) && !is_dominator(earliest, ctl)) {
161 dump_bad_graph("Bad graph detected in get_early_ctrl_for_expensive", n, earliest, ctl);
162 assert(false, "Bad graph detected in get_early_ctrl_for_expensive");
163 }
164 #endif
165 if (dom_depth(ctl) < min_dom_depth) {
166 return earliest;
167 }
168
169 while (1) {
170 Node *next = ctl;
171 // Moving the node out of a loop on the projection of a If
172 // confuses loop predication. So once we hit a Loop in a If branch
173 // that doesn't branch to an UNC, we stop. The code that process
174 // expensive nodes will notice the loop and skip over it to try to
175 // move the node further up.
176 if (ctl->is_CountedLoop() && ctl->in(1) != NULL && ctl->in(1)->in(0) != NULL && ctl->in(1)->in(0)->is_If()) {
177 if (!ctl->in(1)->as_Proj()->is_uncommon_trap_if_pattern(Deoptimization::Reason_none)) {
178 break;
179 }
180 next = idom(ctl->in(1)->in(0));
181 } else if (ctl->is_Proj()) {
182 // We only move it up along a projection if the projection is
183 // the single control projection for its parent: same code path,
184 // if it's a If with UNC or fallthrough of a call.
185 Node* parent_ctl = ctl->in(0);
186 if (parent_ctl == NULL) {
187 break;
188 } else if (parent_ctl->is_CountedLoopEnd() && parent_ctl->as_CountedLoopEnd()->loopnode() != NULL) {
189 next = parent_ctl->as_CountedLoopEnd()->loopnode()->init_control();
190 } else if (parent_ctl->is_If()) {
191 if (!ctl->as_Proj()->is_uncommon_trap_if_pattern(Deoptimization::Reason_none)) {
192 break;
193 }
194 assert(idom(ctl) == parent_ctl, "strange");
195 next = idom(parent_ctl);
196 } else if (ctl->is_CatchProj()) {
197 if (ctl->as_Proj()->_con != CatchProjNode::fall_through_index) {
198 break;
199 }
200 assert(parent_ctl->in(0)->in(0)->is_Call(), "strange graph");
201 next = parent_ctl->in(0)->in(0)->in(0);
202 } else {
203 // Check if parent control has a single projection (this
204 // control is the only possible successor of the parent
205 // control). If so, we can try to move the node above the
206 // parent control.
207 int nb_ctl_proj = 0;
208 for (DUIterator_Fast imax, i = parent_ctl->fast_outs(imax); i < imax; i++) {
209 Node *p = parent_ctl->fast_out(i);
210 if (p->is_Proj() && p->is_CFG()) {
211 nb_ctl_proj++;
212 if (nb_ctl_proj > 1) {
213 break;
214 }
215 }
216 }
217
218 if (nb_ctl_proj > 1) {
219 break;
220 }
221 assert(parent_ctl->is_Start() || parent_ctl->is_MemBar() || parent_ctl->is_Call() ||
222 BarrierSet::barrier_set()->barrier_set_c2()->is_gc_barrier_node(parent_ctl), "unexpected node");
223 assert(idom(ctl) == parent_ctl, "strange");
224 next = idom(parent_ctl);
225 }
226 } else {
227 next = idom(ctl);
228 }
229 if (next->is_Root() || next->is_Start() || dom_depth(next) < min_dom_depth) {
230 break;
231 }
232 ctl = next;
233 }
234
235 if (ctl != n->in(0)) {
236 _igvn.replace_input_of(n, 0, ctl);
237 _igvn.hash_insert(n);
238 }
239
240 return ctl;
241 }
242
243
244 //------------------------------set_early_ctrl---------------------------------
245 // Set earliest legal control
set_early_ctrl(Node * n,bool update_body)246 void PhaseIdealLoop::set_early_ctrl(Node* n, bool update_body) {
247 Node *early = get_early_ctrl(n);
248
249 // Record earliest legal location
250 set_ctrl(n, early);
251 IdealLoopTree *loop = get_loop(early);
252 if (update_body && loop->_child == NULL) {
253 loop->_body.push(n);
254 }
255 }
256
257 //------------------------------set_subtree_ctrl-------------------------------
258 // set missing _ctrl entries on new nodes
set_subtree_ctrl(Node * n,bool update_body)259 void PhaseIdealLoop::set_subtree_ctrl(Node* n, bool update_body) {
260 // Already set? Get out.
261 if (_nodes[n->_idx]) return;
262 // Recursively set _nodes array to indicate where the Node goes
263 uint i;
264 for (i = 0; i < n->req(); ++i) {
265 Node *m = n->in(i);
266 if (m && m != C->root()) {
267 set_subtree_ctrl(m, update_body);
268 }
269 }
270
271 // Fixup self
272 set_early_ctrl(n, update_body);
273 }
274
insert_outer_loop(IdealLoopTree * loop,LoopNode * outer_l,Node * outer_ift)275 IdealLoopTree* PhaseIdealLoop::insert_outer_loop(IdealLoopTree* loop, LoopNode* outer_l, Node* outer_ift) {
276 IdealLoopTree* outer_ilt = new IdealLoopTree(this, outer_l, outer_ift);
277 IdealLoopTree* parent = loop->_parent;
278 IdealLoopTree* sibling = parent->_child;
279 if (sibling == loop) {
280 parent->_child = outer_ilt;
281 } else {
282 while (sibling->_next != loop) {
283 sibling = sibling->_next;
284 }
285 sibling->_next = outer_ilt;
286 }
287 outer_ilt->_next = loop->_next;
288 outer_ilt->_parent = parent;
289 outer_ilt->_child = loop;
290 outer_ilt->_nest = loop->_nest;
291 loop->_parent = outer_ilt;
292 loop->_next = NULL;
293 loop->_nest++;
294 assert(loop->_nest <= SHRT_MAX, "sanity");
295 return outer_ilt;
296 }
297
298 // Create a skeleton strip mined outer loop: a Loop head before the
299 // inner strip mined loop, a safepoint and an exit condition guarded
300 // by an opaque node after the inner strip mined loop with a backedge
301 // to the loop head. The inner strip mined loop is left as it is. Only
302 // once loop optimizations are over, do we adjust the inner loop exit
303 // condition to limit its number of iterations, set the outer loop
304 // exit condition and add Phis to the outer loop head. Some loop
305 // optimizations that operate on the inner strip mined loop need to be
306 // aware of the outer strip mined loop: loop unswitching needs to
307 // clone the outer loop as well as the inner, unrolling needs to only
308 // clone the inner loop etc. No optimizations need to change the outer
309 // strip mined loop as it is only a skeleton.
create_outer_strip_mined_loop(BoolNode * test,Node * cmp,Node * init_control,IdealLoopTree * loop,float cl_prob,float le_fcnt,Node * & entry_control,Node * & iffalse)310 IdealLoopTree* PhaseIdealLoop::create_outer_strip_mined_loop(BoolNode *test, Node *cmp, Node *init_control,
311 IdealLoopTree* loop, float cl_prob, float le_fcnt,
312 Node*& entry_control, Node*& iffalse) {
313 Node* outer_test = _igvn.intcon(0);
314 set_ctrl(outer_test, C->root());
315 Node *orig = iffalse;
316 iffalse = iffalse->clone();
317 _igvn.register_new_node_with_optimizer(iffalse);
318 set_idom(iffalse, idom(orig), dom_depth(orig));
319
320 IfNode *outer_le = new OuterStripMinedLoopEndNode(iffalse, outer_test, cl_prob, le_fcnt);
321 Node *outer_ift = new IfTrueNode (outer_le);
322 Node* outer_iff = orig;
323 _igvn.replace_input_of(outer_iff, 0, outer_le);
324
325 LoopNode *outer_l = new OuterStripMinedLoopNode(C, init_control, outer_ift);
326 entry_control = outer_l;
327
328 IdealLoopTree* outer_ilt = insert_outer_loop(loop, outer_l, outer_ift);
329
330 set_loop(iffalse, outer_ilt);
331 // When this code runs, loop bodies have not yet been populated.
332 const bool body_populated = false;
333 register_control(outer_le, outer_ilt, iffalse, body_populated);
334 register_control(outer_ift, outer_ilt, outer_le, body_populated);
335 set_idom(outer_iff, outer_le, dom_depth(outer_le));
336 _igvn.register_new_node_with_optimizer(outer_l);
337 set_loop(outer_l, outer_ilt);
338 set_idom(outer_l, init_control, dom_depth(init_control)+1);
339
340 return outer_ilt;
341 }
342
insert_loop_limit_check(ProjNode * limit_check_proj,Node * cmp_limit,Node * bol)343 void PhaseIdealLoop::insert_loop_limit_check(ProjNode* limit_check_proj, Node* cmp_limit, Node* bol) {
344 Node* new_predicate_proj = create_new_if_for_predicate(limit_check_proj, NULL,
345 Deoptimization::Reason_loop_limit_check,
346 Op_If);
347 Node* iff = new_predicate_proj->in(0);
348 assert(iff->Opcode() == Op_If, "bad graph shape");
349 Node* conv = iff->in(1);
350 assert(conv->Opcode() == Op_Conv2B, "bad graph shape");
351 Node* opaq = conv->in(1);
352 assert(opaq->Opcode() == Op_Opaque1, "bad graph shape");
353 cmp_limit = _igvn.register_new_node_with_optimizer(cmp_limit);
354 bol = _igvn.register_new_node_with_optimizer(bol);
355 set_subtree_ctrl(bol, false);
356 _igvn.replace_input_of(iff, 1, bol);
357
358 #ifndef PRODUCT
359 // report that the loop predication has been actually performed
360 // for this loop
361 if (TraceLoopLimitCheck) {
362 tty->print_cr("Counted Loop Limit Check generated:");
363 debug_only( bol->dump(2); )
364 }
365 #endif
366 }
367
loop_exit_control(Node * x,IdealLoopTree * loop)368 Node* PhaseIdealLoop::loop_exit_control(Node* x, IdealLoopTree* loop) {
369 // Counted loop head must be a good RegionNode with only 3 not NULL
370 // control input edges: Self, Entry, LoopBack.
371 if (x->in(LoopNode::Self) == NULL || x->req() != 3 || loop->_irreducible) {
372 return NULL;
373 }
374 Node *init_control = x->in(LoopNode::EntryControl);
375 Node *back_control = x->in(LoopNode::LoopBackControl);
376 if (init_control == NULL || back_control == NULL) { // Partially dead
377 return NULL;
378 }
379 // Must also check for TOP when looking for a dead loop
380 if (init_control->is_top() || back_control->is_top()) {
381 return NULL;
382 }
383
384 // Allow funny placement of Safepoint
385 if (back_control->Opcode() == Op_SafePoint) {
386 back_control = back_control->in(TypeFunc::Control);
387 }
388
389 // Controlling test for loop
390 Node *iftrue = back_control;
391 uint iftrue_op = iftrue->Opcode();
392 if (iftrue_op != Op_IfTrue &&
393 iftrue_op != Op_IfFalse) {
394 // I have a weird back-control. Probably the loop-exit test is in
395 // the middle of the loop and I am looking at some trailing control-flow
396 // merge point. To fix this I would have to partially peel the loop.
397 return NULL; // Obscure back-control
398 }
399
400 // Get boolean guarding loop-back test
401 Node *iff = iftrue->in(0);
402 if (get_loop(iff) != loop || !iff->in(1)->is_Bool()) {
403 return NULL;
404 }
405 return iftrue;
406 }
407
loop_exit_test(Node * back_control,IdealLoopTree * loop,Node * & incr,Node * & limit,BoolTest::mask & bt,float & cl_prob)408 Node* PhaseIdealLoop::loop_exit_test(Node* back_control, IdealLoopTree* loop, Node*& incr, Node*& limit, BoolTest::mask& bt, float& cl_prob) {
409 Node* iftrue = back_control;
410 uint iftrue_op = iftrue->Opcode();
411 Node* iff = iftrue->in(0);
412 BoolNode* test = iff->in(1)->as_Bool();
413 bt = test->_test._test;
414 cl_prob = iff->as_If()->_prob;
415 if (iftrue_op == Op_IfFalse) {
416 bt = BoolTest(bt).negate();
417 cl_prob = 1.0 - cl_prob;
418 }
419 // Get backedge compare
420 Node* cmp = test->in(1);
421 if (!cmp->is_Cmp()) {
422 return NULL;
423 }
424
425 // Find the trip-counter increment & limit. Limit must be loop invariant.
426 incr = cmp->in(1);
427 limit = cmp->in(2);
428
429 // ---------
430 // need 'loop()' test to tell if limit is loop invariant
431 // ---------
432
433 if (!is_member(loop, get_ctrl(incr))) { // Swapped trip counter and limit?
434 Node* tmp = incr; // Then reverse order into the CmpI
435 incr = limit;
436 limit = tmp;
437 bt = BoolTest(bt).commute(); // And commute the exit test
438 }
439 if (is_member(loop, get_ctrl(limit))) { // Limit must be loop-invariant
440 return NULL;
441 }
442 if (!is_member(loop, get_ctrl(incr))) { // Trip counter must be loop-variant
443 return NULL;
444 }
445 return cmp;
446 }
447
loop_iv_incr(Node * incr,Node * x,IdealLoopTree * loop,Node * & phi_incr)448 Node* PhaseIdealLoop::loop_iv_incr(Node* incr, Node* x, IdealLoopTree* loop, Node*& phi_incr) {
449 if (incr->is_Phi()) {
450 if (incr->as_Phi()->region() != x || incr->req() != 3) {
451 return NULL; // Not simple trip counter expression
452 }
453 phi_incr = incr;
454 incr = phi_incr->in(LoopNode::LoopBackControl); // Assume incr is on backedge of Phi
455 if (!is_member(loop, get_ctrl(incr))) { // Trip counter must be loop-variant
456 return NULL;
457 }
458 }
459 return incr;
460 }
461
loop_iv_stride(Node * incr,IdealLoopTree * loop,Node * & xphi)462 Node* PhaseIdealLoop::loop_iv_stride(Node* incr, IdealLoopTree* loop, Node*& xphi) {
463 assert(incr->Opcode() == Op_AddI || incr->Opcode() == Op_AddL, "caller resp.");
464 // Get merge point
465 xphi = incr->in(1);
466 Node *stride = incr->in(2);
467 if (!stride->is_Con()) { // Oops, swap these
468 if (!xphi->is_Con()) { // Is the other guy a constant?
469 return NULL; // Nope, unknown stride, bail out
470 }
471 Node *tmp = xphi; // 'incr' is commutative, so ok to swap
472 xphi = stride;
473 stride = tmp;
474 }
475 return stride;
476 }
477
loop_iv_phi(Node * xphi,Node * phi_incr,Node * x,IdealLoopTree * loop)478 PhiNode* PhaseIdealLoop::loop_iv_phi(Node* xphi, Node* phi_incr, Node* x, IdealLoopTree* loop) {
479 if (!xphi->is_Phi()) {
480 return NULL; // Too much math on the trip counter
481 }
482 if (phi_incr != NULL && phi_incr != xphi) {
483 return NULL;
484 }
485 PhiNode *phi = xphi->as_Phi();
486
487 // Phi must be of loop header; backedge must wrap to increment
488 if (phi->region() != x) {
489 return NULL;
490 }
491 return phi;
492 }
493
check_stride_overflow(jlong stride_con,const TypeInteger * limit_t,BasicType bt)494 static int check_stride_overflow(jlong stride_con, const TypeInteger* limit_t, BasicType bt) {
495 if (stride_con > 0) {
496 if (limit_t->lo_as_long() > (max_signed_integer(bt) - stride_con)) {
497 return -1;
498 }
499 if (limit_t->hi_as_long() > (max_signed_integer(bt) - stride_con)) {
500 return 1;
501 }
502 } else {
503 if (limit_t->hi_as_long() < (min_signed_integer(bt) - stride_con)) {
504 return -1;
505 }
506 if (limit_t->lo_as_long() < (min_signed_integer(bt) - stride_con)) {
507 return 1;
508 }
509 }
510 return 0;
511 }
512
condition_stride_ok(BoolTest::mask bt,jlong stride_con)513 static bool condition_stride_ok(BoolTest::mask bt, jlong stride_con) {
514 // If the condition is inverted and we will be rolling
515 // through MININT to MAXINT, then bail out.
516 if (bt == BoolTest::eq || // Bail out, but this loop trips at most twice!
517 // Odd stride
518 (bt == BoolTest::ne && stride_con != 1 && stride_con != -1) ||
519 // Count down loop rolls through MAXINT
520 ((bt == BoolTest::le || bt == BoolTest::lt) && stride_con < 0) ||
521 // Count up loop rolls through MININT
522 ((bt == BoolTest::ge || bt == BoolTest::gt) && stride_con > 0)) {
523 return false; // Bail out
524 }
525 return true;
526 }
527
long_loop_replace_long_iv(Node * iv_to_replace,Node * inner_iv,Node * outer_phi,Node * inner_head)528 void PhaseIdealLoop::long_loop_replace_long_iv(Node* iv_to_replace, Node* inner_iv, Node* outer_phi, Node* inner_head) {
529 Node* iv_as_long = new ConvI2LNode(inner_iv, TypeLong::INT);
530 register_new_node(iv_as_long, inner_head);
531 Node* iv_replacement = new AddLNode(outer_phi, iv_as_long);
532 register_new_node(iv_replacement, inner_head);
533 for (DUIterator_Last imin, i = iv_to_replace->last_outs(imin); i >= imin;) {
534 Node* u = iv_to_replace->last_out(i);
535 #ifdef ASSERT
536 if (!is_dominator(inner_head, ctrl_or_self(u))) {
537 assert(u->is_Phi(), "should be a Phi");
538 for (uint j = 1; j < u->req(); j++) {
539 if (u->in(j) == iv_to_replace) {
540 assert(is_dominator(inner_head, u->in(0)->in(j)), "iv use above loop?");
541 }
542 }
543 }
544 #endif
545 _igvn.rehash_node_delayed(u);
546 int nb = u->replace_edge(iv_to_replace, iv_replacement);
547 i -= nb;
548 }
549 }
550
add_empty_predicate(Deoptimization::DeoptReason reason,Node * inner_head,IdealLoopTree * loop,SafePointNode * sfpt)551 void PhaseIdealLoop::add_empty_predicate(Deoptimization::DeoptReason reason, Node* inner_head, IdealLoopTree* loop, SafePointNode* sfpt) {
552 if (!C->too_many_traps(reason)) {
553 Node *cont = _igvn.intcon(1);
554 Node* opq = new Opaque1Node(C, cont);
555 _igvn.register_new_node_with_optimizer(opq);
556 Node *bol = new Conv2BNode(opq);
557 _igvn.register_new_node_with_optimizer(bol);
558 set_subtree_ctrl(bol, false);
559 IfNode* iff = new IfNode(inner_head->in(LoopNode::EntryControl), bol, PROB_MAX, COUNT_UNKNOWN);
560 register_control(iff, loop, inner_head->in(LoopNode::EntryControl));
561 Node* iffalse = new IfFalseNode(iff);
562 register_control(iffalse, _ltree_root, iff);
563 Node* iftrue = new IfTrueNode(iff);
564 register_control(iftrue, loop, iff);
565 C->add_predicate_opaq(opq);
566
567 int trap_request = Deoptimization::make_trap_request(reason, Deoptimization::Action_maybe_recompile);
568 address call_addr = SharedRuntime::uncommon_trap_blob()->entry_point();
569 const TypePtr* no_memory_effects = NULL;
570 JVMState* jvms = sfpt->jvms();
571 CallNode* unc = new CallStaticJavaNode(OptoRuntime::uncommon_trap_Type(), call_addr, "uncommon_trap",
572 jvms->bci(), no_memory_effects);
573
574 Node* mem = NULL;
575 Node* i_o = NULL;
576 if (sfpt->is_Call()) {
577 mem = sfpt->proj_out(TypeFunc::Memory);
578 i_o = sfpt->proj_out(TypeFunc::I_O);
579 } else {
580 mem = sfpt->memory();
581 i_o = sfpt->i_o();
582 }
583
584 Node *frame = new ParmNode(C->start(), TypeFunc::FramePtr);
585 register_new_node(frame, C->start());
586 Node *ret = new ParmNode(C->start(), TypeFunc::ReturnAdr);
587 register_new_node(ret, C->start());
588
589 unc->init_req(TypeFunc::Control, iffalse);
590 unc->init_req(TypeFunc::I_O, i_o);
591 unc->init_req(TypeFunc::Memory, mem); // may gc ptrs
592 unc->init_req(TypeFunc::FramePtr, frame);
593 unc->init_req(TypeFunc::ReturnAdr, ret);
594 unc->init_req(TypeFunc::Parms+0, _igvn.intcon(trap_request));
595 unc->set_cnt(PROB_UNLIKELY_MAG(4));
596 unc->copy_call_debug_info(&_igvn, sfpt);
597
598 for (uint i = TypeFunc::Parms; i < unc->req(); i++) {
599 set_subtree_ctrl(unc->in(i), false);
600 }
601 register_control(unc, _ltree_root, iffalse);
602
603 Node* ctrl = new ProjNode(unc, TypeFunc::Control);
604 register_control(ctrl, _ltree_root, unc);
605 Node* halt = new HaltNode(ctrl, frame, "uncommon trap returned which should never happen" PRODUCT_ONLY(COMMA /*reachable*/false));
606 register_control(halt, _ltree_root, ctrl);
607 C->root()->add_req(halt);
608
609 _igvn.replace_input_of(inner_head, LoopNode::EntryControl, iftrue);
610 set_idom(inner_head, iftrue, dom_depth(inner_head));
611 }
612 }
613
614 // Find a safepoint node that dominates the back edge. We need a
615 // SafePointNode so we can use its jvm state to create empty
616 // predicates.
no_side_effect_since_safepoint(Compile * C,Node * x,Node * mem,MergeMemNode * mm)617 static bool no_side_effect_since_safepoint(Compile* C, Node* x, Node* mem, MergeMemNode* mm) {
618 SafePointNode* safepoint = NULL;
619 for (DUIterator_Fast imax, i = x->fast_outs(imax); i < imax; i++) {
620 Node* u = x->fast_out(i);
621 if (u->is_Phi() && u->bottom_type() == Type::MEMORY) {
622 Node* m = u->in(LoopNode::LoopBackControl);
623 if (u->adr_type() == TypePtr::BOTTOM) {
624 if (m->is_MergeMem() && mem->is_MergeMem()) {
625 if (m != mem DEBUG_ONLY(|| true)) {
626 for (MergeMemStream mms(m->as_MergeMem(), mem->as_MergeMem()); mms.next_non_empty2(); ) {
627 if (!mms.is_empty()) {
628 if (mms.memory() != mms.memory2()) {
629 return false;
630 }
631 #ifdef ASSERT
632 if (mms.alias_idx() != Compile::AliasIdxBot) {
633 mm->set_memory_at(mms.alias_idx(), mem->as_MergeMem()->base_memory());
634 }
635 #endif
636 }
637 }
638 }
639 } else if (mem->is_MergeMem()) {
640 if (m != mem->as_MergeMem()->base_memory()) {
641 return false;
642 }
643 } else {
644 return false;
645 }
646 } else {
647 if (mem->is_MergeMem()) {
648 if (m != mem->as_MergeMem()->memory_at(C->get_alias_index(u->adr_type()))) {
649 return false;
650 }
651 #ifdef ASSERT
652 mm->set_memory_at(C->get_alias_index(u->adr_type()), mem->as_MergeMem()->base_memory());
653 #endif
654 } else {
655 if (m != mem) {
656 return false;
657 }
658 }
659 }
660 }
661 }
662 return true;
663 }
664
find_safepoint(Node * back_control,Node * x,IdealLoopTree * loop)665 SafePointNode* PhaseIdealLoop::find_safepoint(Node* back_control, Node* x, IdealLoopTree* loop) {
666 IfNode* exit_test = back_control->in(0)->as_If();
667 SafePointNode* safepoint = NULL;
668 if (exit_test->in(0)->is_SafePoint() && exit_test->in(0)->outcnt() == 1) {
669 safepoint = exit_test->in(0)->as_SafePoint();
670 } else {
671 Node* c = back_control;
672 while (c != x && c->Opcode() != Op_SafePoint) {
673 c = idom(c);
674 }
675
676 if (c->Opcode() == Op_SafePoint) {
677 safepoint = c->as_SafePoint();
678 }
679
680 if (safepoint == NULL) {
681 return NULL;
682 }
683
684 Node* mem = safepoint->in(TypeFunc::Memory);
685
686 // We can only use that safepoint if there's not side effect
687 // between the backedge and the safepoint.
688
689 // mm is used for book keeping
690 MergeMemNode* mm = NULL;
691 #ifdef ASSERT
692 if (mem->is_MergeMem()) {
693 mm = mem->clone()->as_MergeMem();
694 _igvn._worklist.push(mm);
695 for (MergeMemStream mms(mem->as_MergeMem()); mms.next_non_empty(); ) {
696 if (mms.alias_idx() != Compile::AliasIdxBot && loop != get_loop(ctrl_or_self(mms.memory()))) {
697 mm->set_memory_at(mms.alias_idx(), mem->as_MergeMem()->base_memory());
698 }
699 }
700 }
701 #endif
702 if (!no_side_effect_since_safepoint(C, x, mem, mm)) {
703 safepoint = NULL;
704 } else {
705 assert(mm == NULL|| _igvn.transform(mm) == mem->as_MergeMem()->base_memory(), "all memory state should have been processed");
706 }
707 #ifdef ASSERT
708 if (mm != NULL) {
709 _igvn.remove_dead_node(mm);
710 }
711 #endif
712 }
713 return safepoint;
714 }
715
716 // If the loop has the shape of a counted loop but with a long
717 // induction variable, transform the loop in a loop nest: an inner
718 // loop that iterates for at most max int iterations with an integer
719 // induction variable and an outer loop that iterates over the full
720 // range of long values from the initial loop in (at most) max int
721 // steps. That is:
722 //
723 // x: for (long phi = init; phi < limit; phi += stride) {
724 // // phi := Phi(L, init, incr)
725 // // incr := AddL(phi, longcon(stride))
726 // long incr = phi + stride;
727 // ... use phi and incr ...
728 // }
729 //
730 // OR:
731 //
732 // x: for (long phi = init; (phi += stride) < limit; ) {
733 // // phi := Phi(L, AddL(init, stride), incr)
734 // // incr := AddL(phi, longcon(stride))
735 // long incr = phi + stride;
736 // ... use phi and (phi + stride) ...
737 // }
738 //
739 // ==transform=>
740 //
741 // const ulong inner_iters_limit = INT_MAX - stride - 1; //near 0x7FFFFFF0
742 // assert(stride <= inner_iters_limit); // else abort transform
743 // assert((extralong)limit + stride <= LONG_MAX); // else deopt
744 // outer_head: for (long outer_phi = init;;) {
745 // // outer_phi := Phi(outer_head, init, AddL(outer_phi, I2L(inner_phi)))
746 // ulong inner_iters_max = (ulong) MAX(0, ((extralong)limit + stride - outer_phi));
747 // long inner_iters_actual = MIN(inner_iters_limit, inner_iters_max);
748 // assert(inner_iters_actual == (int)inner_iters_actual);
749 // int inner_phi, inner_incr;
750 // x: for (inner_phi = 0;; inner_phi = inner_incr) {
751 // // inner_phi := Phi(x, intcon(0), inner_incr)
752 // // inner_incr := AddI(inner_phi, intcon(stride))
753 // inner_incr = inner_phi + stride;
754 // if (inner_incr < inner_iters_actual) {
755 // ... use phi=>(outer_phi+inner_phi) and incr=>(outer_phi+inner_incr) ...
756 // continue;
757 // }
758 // else break;
759 // }
760 // if ((outer_phi+inner_phi) < limit) //OR (outer_phi+inner_incr) < limit
761 // continue;
762 // else break;
763 // }
transform_long_counted_loop(IdealLoopTree * loop,Node_List & old_new)764 bool PhaseIdealLoop::transform_long_counted_loop(IdealLoopTree* loop, Node_List &old_new) {
765 Node* x = loop->_head;
766 // Only for inner loops
767 if (loop->_child != NULL || !x->is_LongCountedLoop()) {
768 return false;
769 }
770
771 check_long_counted_loop(loop, x);
772
773 LongCountedLoopNode* head = x->as_LongCountedLoop();
774
775 #ifndef PRODUCT
776 Atomic::inc(&_long_loop_candidates);
777 #endif
778
779 jlong stride_con = head->stride_con();
780 assert(stride_con != 0, "missed some peephole opt");
781 // We can't iterate for more than max int at a time.
782 if (stride_con != (jint)stride_con) {
783 return false;
784 }
785 // The number of iterations for the integer count loop: guarantee no
786 // overflow: max_jint - stride_con max. -1 so there's no need for a
787 // loop limit check if the exit test is <= or >=.
788 int iters_limit = max_jint - ABS(stride_con) - 1;
789 #ifdef ASSERT
790 if (StressLongCountedLoop > 0) {
791 iters_limit = iters_limit / StressLongCountedLoop;
792 }
793 #endif
794 // At least 2 iterations so counted loop construction doesn't fail
795 if (iters_limit/ABS(stride_con) < 2) {
796 return false;
797 }
798
799 PhiNode* phi = head->phi()->as_Phi();
800 Node* incr = head->incr();
801
802 Node* back_control = head->in(LoopNode::LoopBackControl);
803
804 // data nodes on back branch not supported
805 if (back_control->outcnt() > 1) {
806 return false;
807 }
808
809 Node* limit = head->limit();
810 // We'll need to use the loop limit before the inner loop is entered
811 if (!is_dominator(get_ctrl(limit), x)) {
812 return false;
813 }
814
815 const TypeLong* phi_t = _igvn.type(phi)->is_long();
816 assert(phi_t->_hi >= phi_t->_lo, "dead phi?");
817 iters_limit = (int)MIN2((julong)iters_limit, (julong)(phi_t->_hi - phi_t->_lo));
818
819 LongCountedLoopEndNode* exit_test = head->loopexit();
820 BoolTest::mask bt = exit_test->test_trip();
821
822 // We need a safepoint to insert empty predicates for the inner loop.
823 SafePointNode* safepoint = find_safepoint(back_control, x, loop);
824
825 assert(back_control->Opcode() == Op_IfTrue, "wrong projection for back edge");
826 Node* exit_branch = exit_test->proj_out(false);
827 Node* entry_control = x->in(LoopNode::EntryControl);
828 Node* cmp = exit_test->cmp_node();
829
830 // Clone the control flow of the loop to build an outer loop
831 Node* outer_back_branch = back_control->clone();
832 Node* outer_exit_test = new IfNode(exit_test->in(0), exit_test->in(1), exit_test->_prob, exit_test->_fcnt);
833 Node* inner_exit_branch = exit_branch->clone();
834
835 Node* outer_head = new LoopNode(entry_control, outer_back_branch);
836 IdealLoopTree* outer_ilt = insert_outer_loop(loop, outer_head->as_Loop(), outer_back_branch);
837
838 const bool body_populated = true;
839 register_control(outer_head, outer_ilt, entry_control, body_populated);
840
841 _igvn.register_new_node_with_optimizer(inner_exit_branch);
842 set_loop(inner_exit_branch, outer_ilt);
843 set_idom(inner_exit_branch, exit_test, dom_depth(exit_branch));
844
845 outer_exit_test->set_req(0, inner_exit_branch);
846 register_control(outer_exit_test, outer_ilt, inner_exit_branch, body_populated);
847
848 _igvn.replace_input_of(exit_branch, 0, outer_exit_test);
849 set_idom(exit_branch, outer_exit_test, dom_depth(exit_branch));
850
851 outer_back_branch->set_req(0, outer_exit_test);
852 register_control(outer_back_branch, outer_ilt, outer_exit_test, body_populated);
853
854 _igvn.replace_input_of(x, LoopNode::EntryControl, outer_head);
855 set_idom(x, outer_head, dom_depth(x));
856
857 // add an iv phi to the outer loop and use it to compute the inner
858 // loop iteration limit
859 Node* outer_phi = phi->clone();
860 outer_phi->set_req(0, outer_head);
861 register_new_node(outer_phi, outer_head);
862
863 Node* inner_iters_max = NULL;
864 if (stride_con > 0) {
865 inner_iters_max = MaxNode::max_diff_with_zero(limit, outer_phi, TypeLong::LONG, _igvn);
866 } else {
867 inner_iters_max = MaxNode::max_diff_with_zero(outer_phi, limit, TypeLong::LONG, _igvn);
868 }
869
870 Node* inner_iters_limit = _igvn.longcon(iters_limit);
871 // inner_iters_max may not fit in a signed integer (iterating from
872 // Long.MIN_VALUE to Long.MAX_VALUE for instance). Use an unsigned
873 // min.
874 Node* inner_iters_actual = MaxNode::unsigned_min(inner_iters_max, inner_iters_limit, TypeLong::make(0, iters_limit, Type::WidenMin), _igvn);
875
876 Node* inner_iters_actual_int = new ConvL2INode(inner_iters_actual);
877 _igvn.register_new_node_with_optimizer(inner_iters_actual_int);
878
879 Node* zero = _igvn.intcon(0);
880 set_ctrl(zero, C->root());
881 if (stride_con < 0) {
882 inner_iters_actual_int = new SubINode(zero, inner_iters_actual_int);
883 _igvn.register_new_node_with_optimizer(inner_iters_actual_int);
884 }
885
886 // Clone the iv data nodes as an integer iv
887 Node* int_stride = _igvn.intcon((int)stride_con);
888 set_ctrl(int_stride, C->root());
889 Node* inner_phi = new PhiNode(x->in(0), TypeInt::INT);
890 Node* inner_incr = new AddINode(inner_phi, int_stride);
891 Node* inner_cmp = NULL;
892 inner_cmp = new CmpINode(inner_incr, inner_iters_actual_int);
893 Node* inner_bol = new BoolNode(inner_cmp, exit_test->in(1)->as_Bool()->_test._test);
894 inner_phi->set_req(LoopNode::EntryControl, zero);
895 inner_phi->set_req(LoopNode::LoopBackControl, inner_incr);
896 register_new_node(inner_phi, x);
897 register_new_node(inner_incr, x);
898 register_new_node(inner_cmp, x);
899 register_new_node(inner_bol, x);
900
901 _igvn.replace_input_of(exit_test, 1, inner_bol);
902
903 // Clone inner loop phis to outer loop
904 for (uint i = 0; i < head->outcnt(); i++) {
905 Node* u = head->raw_out(i);
906 if (u->is_Phi() && u != inner_phi && u != phi) {
907 assert(u->in(0) == head, "inconsistent");
908 Node* clone = u->clone();
909 clone->set_req(0, outer_head);
910 register_new_node(clone, outer_head);
911 _igvn.replace_input_of(u, LoopNode::EntryControl, clone);
912 }
913 }
914
915 // Replace inner loop long iv phi as inner loop int iv phi + outer
916 // loop iv phi
917 long_loop_replace_long_iv(phi, inner_phi, outer_phi, head);
918
919 // Replace inner loop long iv incr with inner loop int incr + outer
920 // loop iv phi
921 long_loop_replace_long_iv(incr, inner_incr, outer_phi, head);
922
923 set_subtree_ctrl(inner_iters_actual_int, body_populated);
924
925 LoopNode* inner_head = create_inner_head(loop, head, exit_test);
926
927 // Summary of steps from inital loop to loop nest:
928 //
929 // == old IR nodes =>
930 //
931 // entry_control: {...}
932 // x:
933 // for (long phi = init;;) {
934 // // phi := Phi(x, init, incr)
935 // // incr := AddL(phi, longcon(stride))
936 // exit_test:
937 // if (phi < limit)
938 // back_control: fallthrough;
939 // else
940 // exit_branch: break;
941 // long incr = phi + stride;
942 // ... use phi and incr ...
943 // phi = incr;
944 // }
945 //
946 // == new IR nodes (just before final peel) =>
947 //
948 // entry_control: {...}
949 // long adjusted_limit = limit + stride; //because phi_incr != NULL
950 // assert(!limit_check_required || (extralong)limit + stride == adjusted_limit); // else deopt
951 // ulong inner_iters_limit = max_jint - ABS(stride) - 1; //near 0x7FFFFFF0
952 // outer_head:
953 // for (long outer_phi = init;;) {
954 // // outer_phi := phi->clone(), in(0):=outer_head, => Phi(outer_head, init, incr)
955 // // REPLACE phi => AddL(outer_phi, I2L(inner_phi))
956 // // REPLACE incr => AddL(outer_phi, I2L(inner_incr))
957 // // SO THAT outer_phi := Phi(outer_head, init, AddL(outer_phi, I2L(inner_incr)))
958 // ulong inner_iters_max = (ulong) MAX(0, ((extralong)adjusted_limit - outer_phi) * SGN(stride));
959 // int inner_iters_actual_int = (int) MIN(inner_iters_limit, inner_iters_max) * SGN(stride);
960 // inner_head: x: //in(1) := outer_head
961 // int inner_phi;
962 // for (inner_phi = 0;;) {
963 // // inner_phi := Phi(x, intcon(0), inner_phi + stride)
964 // int inner_incr = inner_phi + stride;
965 // bool inner_bol = (inner_incr < inner_iters_actual_int);
966 // exit_test: //exit_test->in(1) := inner_bol;
967 // if (inner_bol) // WAS (phi < limit)
968 // back_control: fallthrough;
969 // else
970 // inner_exit_branch: break; //exit_branch->clone()
971 // ... use phi=>(outer_phi+inner_phi) and incr=>(outer_phi+inner_incr) ...
972 // inner_phi = inner_phi + stride; // inner_incr
973 // }
974 // outer_exit_test: //exit_test->clone(), in(0):=inner_exit_branch
975 // if ((outer_phi+inner_phi) < limit) // WAS (phi < limit)
976 // outer_back_branch: fallthrough; //back_control->clone(), in(0):=outer_exit_test
977 // else
978 // exit_branch: break; //in(0) := outer_exit_test
979 // }
980
981 // Peel one iteration of the loop and use the safepoint at the end
982 // of the peeled iteration to insert empty predicates. If no well
983 // positioned safepoint peel to guarantee a safepoint in the outer
984 // loop.
985 if (safepoint != NULL || !loop->_has_call) {
986 old_new.clear();
987 do_peeling(loop, old_new);
988 } else {
989 C->set_major_progress();
990 }
991
992 if (safepoint != NULL) {
993 SafePointNode* cloned_sfpt = old_new[safepoint->_idx]->as_SafePoint();
994
995 if (UseLoopPredicate) {
996 add_empty_predicate(Deoptimization::Reason_predicate, inner_head, outer_ilt, cloned_sfpt);
997 }
998 if (UseProfiledLoopPredicate) {
999 add_empty_predicate(Deoptimization::Reason_profile_predicate, inner_head, outer_ilt, cloned_sfpt);
1000 }
1001 add_empty_predicate(Deoptimization::Reason_loop_limit_check, inner_head, outer_ilt, cloned_sfpt);
1002 }
1003
1004 #ifndef PRODUCT
1005 Atomic::inc(&_long_loop_nests);
1006 #endif
1007
1008 inner_head->mark_transformed_long_loop();
1009
1010 return true;
1011 }
1012
create_inner_head(IdealLoopTree * loop,LongCountedLoopNode * head,LongCountedLoopEndNode * exit_test)1013 LoopNode* PhaseIdealLoop::create_inner_head(IdealLoopTree* loop, LongCountedLoopNode* head,
1014 LongCountedLoopEndNode* exit_test) {
1015 LoopNode* new_inner_head = new LoopNode(head->in(1), head->in(2));
1016 IfNode* new_inner_exit = new IfNode(exit_test->in(0), exit_test->in(1), exit_test->_prob, exit_test->_fcnt);
1017 _igvn.register_new_node_with_optimizer(new_inner_head);
1018 _igvn.register_new_node_with_optimizer(new_inner_exit);
1019 loop->_body.push(new_inner_head);
1020 loop->_body.push(new_inner_exit);
1021 loop->_body.yank(head);
1022 loop->_body.yank(exit_test);
1023 set_loop(new_inner_head, loop);
1024 set_loop(new_inner_exit, loop);
1025 set_idom(new_inner_head, idom(head), dom_depth(head));
1026 set_idom(new_inner_exit, idom(exit_test), dom_depth(exit_test));
1027 lazy_replace(head, new_inner_head);
1028 lazy_replace(exit_test, new_inner_exit);
1029 loop->_head = new_inner_head;
1030 return new_inner_head;
1031 }
1032
1033 #ifdef ASSERT
check_long_counted_loop(IdealLoopTree * loop,Node * x)1034 void PhaseIdealLoop::check_long_counted_loop(IdealLoopTree* loop, Node* x) {
1035 Node* back_control = loop_exit_control(x, loop);
1036 assert(back_control != NULL, "no back control");
1037
1038 BoolTest::mask bt = BoolTest::illegal;
1039 float cl_prob = 0;
1040 Node* incr = NULL;
1041 Node* limit = NULL;
1042
1043 Node* cmp = loop_exit_test(back_control, loop, incr, limit, bt, cl_prob);
1044 assert(cmp != NULL && cmp->Opcode() == Op_CmpL, "no exit test");
1045
1046 Node* phi_incr = NULL;
1047 incr = loop_iv_incr(incr, x, loop, phi_incr);
1048 assert(incr != NULL && incr->Opcode() == Op_AddL, "no incr");
1049
1050 Node* xphi = NULL;
1051 Node* stride = loop_iv_stride(incr, loop, xphi);
1052
1053 assert(stride != NULL, "no stride");
1054
1055 PhiNode* phi = loop_iv_phi(xphi, phi_incr, x, loop);
1056
1057 assert(phi != NULL && phi->in(LoopNode::LoopBackControl) == incr, "No phi");
1058
1059 jlong stride_con = stride->get_long();
1060
1061 assert(condition_stride_ok(bt, stride_con), "illegal condition");
1062
1063 assert(bt != BoolTest::ne, "unexpected condition");
1064 assert(phi_incr == NULL, "bad loop shape");
1065 assert(cmp->in(1) == incr, "bad exit test shape");
1066
1067 // Safepoint on backedge not supported
1068 assert(x->in(LoopNode::LoopBackControl)->Opcode() != Op_SafePoint, "no safepoint on backedge");
1069 }
1070 #endif
1071
1072 #ifdef ASSERT
1073 // convert an int counted loop to a long counted to stress handling of
1074 // long counted loops
convert_to_long_loop(Node * cmp,Node * phi,IdealLoopTree * loop)1075 bool PhaseIdealLoop::convert_to_long_loop(Node* cmp, Node* phi, IdealLoopTree* loop) {
1076 Unique_Node_List iv_nodes;
1077 Node_List old_new;
1078 iv_nodes.push(cmp);
1079 bool failed = false;
1080
1081 for (uint i = 0; i < iv_nodes.size() && !failed; i++) {
1082 Node* n = iv_nodes.at(i);
1083 switch(n->Opcode()) {
1084 case Op_Phi: {
1085 Node* clone = new PhiNode(n->in(0), TypeLong::LONG);
1086 old_new.map(n->_idx, clone);
1087 break;
1088 }
1089 case Op_CmpI: {
1090 Node* clone = new CmpLNode(NULL, NULL);
1091 old_new.map(n->_idx, clone);
1092 break;
1093 }
1094 case Op_AddI: {
1095 Node* clone = new AddLNode(NULL, NULL);
1096 old_new.map(n->_idx, clone);
1097 break;
1098 }
1099 case Op_CastII: {
1100 failed = true;
1101 break;
1102 }
1103 default:
1104 DEBUG_ONLY(n->dump());
1105 fatal("unexpected");
1106 }
1107
1108 for (uint i = 1; i < n->req(); i++) {
1109 Node* in = n->in(i);
1110 if (in == NULL) {
1111 continue;
1112 }
1113 if (loop->is_member(get_loop(get_ctrl(in)))) {
1114 iv_nodes.push(in);
1115 }
1116 }
1117 }
1118
1119 if (failed) {
1120 for (uint i = 0; i < iv_nodes.size(); i++) {
1121 Node* n = iv_nodes.at(i);
1122 Node* clone = old_new[n->_idx];
1123 if (clone != NULL) {
1124 _igvn.remove_dead_node(clone);
1125 }
1126 }
1127 return false;
1128 }
1129
1130 for (uint i = 0; i < iv_nodes.size(); i++) {
1131 Node* n = iv_nodes.at(i);
1132 Node* clone = old_new[n->_idx];
1133 for (uint i = 1; i < n->req(); i++) {
1134 Node* in = n->in(i);
1135 if (in == NULL) {
1136 continue;
1137 }
1138 Node* in_clone = old_new[in->_idx];
1139 if (in_clone == NULL) {
1140 assert(_igvn.type(in)->isa_int(), "");
1141 in_clone = new ConvI2LNode(in);
1142 _igvn.register_new_node_with_optimizer(in_clone);
1143 set_subtree_ctrl(in_clone, false);
1144 }
1145 if (in_clone->in(0) == NULL) {
1146 in_clone->set_req(0, C->top());
1147 clone->set_req(i, in_clone);
1148 in_clone->set_req(0, NULL);
1149 } else {
1150 clone->set_req(i, in_clone);
1151 }
1152 }
1153 _igvn.register_new_node_with_optimizer(clone);
1154 }
1155 set_ctrl(old_new[phi->_idx], phi->in(0));
1156
1157 for (uint i = 0; i < iv_nodes.size(); i++) {
1158 Node* n = iv_nodes.at(i);
1159 Node* clone = old_new[n->_idx];
1160 set_subtree_ctrl(clone, false);
1161 Node* m = n->Opcode() == Op_CmpI ? clone : NULL;
1162 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
1163 Node* u = n->fast_out(i);
1164 if (iv_nodes.member(u)) {
1165 continue;
1166 }
1167 if (m == NULL) {
1168 m = new ConvL2INode(clone);
1169 _igvn.register_new_node_with_optimizer(m);
1170 set_subtree_ctrl(m, false);
1171 }
1172 _igvn.rehash_node_delayed(u);
1173 int nb = u->replace_edge(n, m);
1174 --i, imax -= nb;
1175 }
1176 }
1177 return true;
1178 }
1179 #endif
1180
1181 //------------------------------is_counted_loop--------------------------------
is_counted_loop(Node * x,IdealLoopTree * & loop,BasicType iv_bt)1182 bool PhaseIdealLoop::is_counted_loop(Node* x, IdealLoopTree*&loop, BasicType iv_bt) {
1183 PhaseGVN *gvn = &_igvn;
1184
1185 Node* back_control = loop_exit_control(x, loop);
1186 if (back_control == NULL) {
1187 return false;
1188 }
1189
1190 BoolTest::mask bt = BoolTest::illegal;
1191 float cl_prob = 0;
1192 Node* incr = NULL;
1193 Node* limit = NULL;
1194 Node* cmp = loop_exit_test(back_control, loop, incr, limit, bt, cl_prob);
1195 if (cmp == NULL || !(cmp->is_Cmp() && cmp->operates_on(iv_bt, true))) {
1196 return false; // Avoid pointer & float & 64-bit compares
1197 }
1198
1199 // Trip-counter increment must be commutative & associative.
1200 if (incr->is_ConstraintCast() && incr->operates_on(iv_bt, false)) {
1201 incr = incr->in(1);
1202 }
1203
1204 Node* phi_incr = NULL;
1205 incr = loop_iv_incr(incr, x, loop, phi_incr);
1206 if (incr == NULL) {
1207 return false;
1208 }
1209
1210 Node* trunc1 = NULL;
1211 Node* trunc2 = NULL;
1212 const TypeInteger* iv_trunc_t = NULL;
1213 Node* orig_incr = incr;
1214 if (!(incr = CountedLoopNode::match_incr_with_optional_truncation(incr, &trunc1, &trunc2, &iv_trunc_t, iv_bt))) {
1215 return false; // Funny increment opcode
1216 }
1217 assert(incr->is_Add() && incr->operates_on(iv_bt, false), "wrong increment code");
1218
1219 Node* xphi = NULL;
1220 Node* stride = loop_iv_stride(incr, loop, xphi);
1221
1222 if (stride == NULL) {
1223 return false;
1224 }
1225
1226 if (xphi->is_ConstraintCast() && xphi->operates_on(iv_bt, false)) {
1227 xphi = xphi->in(1);
1228 }
1229
1230 // Stride must be constant
1231 jlong stride_con = stride->get_integer_as_long(iv_bt);
1232 assert(stride_con != 0, "missed some peephole opt");
1233
1234 PhiNode* phi = loop_iv_phi(xphi, phi_incr, x, loop);
1235
1236 if (phi == NULL ||
1237 (trunc1 == NULL && phi->in(LoopNode::LoopBackControl) != incr) ||
1238 (trunc1 != NULL && phi->in(LoopNode::LoopBackControl) != trunc1)) {
1239 return false;
1240 }
1241
1242 if (x->in(LoopNode::LoopBackControl)->Opcode() == Op_SafePoint &&
1243 ((iv_bt == T_INT && LoopStripMiningIter != 0) ||
1244 iv_bt == T_LONG)) {
1245 // Leaving the safepoint on the backedge and creating a
1246 // CountedLoop will confuse optimizations. We can't move the
1247 // safepoint around because its jvm state wouldn't match a new
1248 // location. Give up on that loop.
1249 return false;
1250 }
1251
1252 Node* iftrue = back_control;
1253 uint iftrue_op = iftrue->Opcode();
1254 Node* iff = iftrue->in(0);
1255 BoolNode* test = iff->in(1)->as_Bool();
1256
1257 const TypeInteger* limit_t = gvn->type(limit)->is_integer(iv_bt);
1258 if (trunc1 != NULL) {
1259 // When there is a truncation, we must be sure that after the truncation
1260 // the trip counter will end up higher than the limit, otherwise we are looking
1261 // at an endless loop. Can happen with range checks.
1262
1263 // Example:
1264 // int i = 0;
1265 // while (true)
1266 // sum + = array[i];
1267 // i++;
1268 // i = i && 0x7fff;
1269 // }
1270 //
1271 // If the array is shorter than 0x8000 this exits through a AIOOB
1272 // - Counted loop transformation is ok
1273 // If the array is longer then this is an endless loop
1274 // - No transformation can be done.
1275
1276 const TypeInteger* incr_t = gvn->type(orig_incr)->is_integer(iv_bt);
1277 if (limit_t->hi_as_long() > incr_t->hi_as_long()) {
1278 // if the limit can have a higher value than the increment (before the phi)
1279 return false;
1280 }
1281 }
1282
1283 Node *init_trip = phi->in(LoopNode::EntryControl);
1284
1285 // If iv trunc type is smaller than int, check for possible wrap.
1286 if (!TypeInteger::bottom(iv_bt)->higher_equal(iv_trunc_t)) {
1287 assert(trunc1 != NULL, "must have found some truncation");
1288
1289 // Get a better type for the phi (filtered thru if's)
1290 const TypeInteger* phi_ft = filtered_type(phi);
1291
1292 // Can iv take on a value that will wrap?
1293 //
1294 // Ensure iv's limit is not within "stride" of the wrap value.
1295 //
1296 // Example for "short" type
1297 // Truncation ensures value is in the range -32768..32767 (iv_trunc_t)
1298 // If the stride is +10, then the last value of the induction
1299 // variable before the increment (phi_ft->_hi) must be
1300 // <= 32767 - 10 and (phi_ft->_lo) must be >= -32768 to
1301 // ensure no truncation occurs after the increment.
1302
1303 if (stride_con > 0) {
1304 if (iv_trunc_t->hi_as_long() - phi_ft->hi_as_long() < stride_con ||
1305 iv_trunc_t->lo_as_long() > phi_ft->lo_as_long()) {
1306 return false; // truncation may occur
1307 }
1308 } else if (stride_con < 0) {
1309 if (iv_trunc_t->lo_as_long() - phi_ft->lo_as_long() > stride_con ||
1310 iv_trunc_t->hi_as_long() < phi_ft->hi_as_long()) {
1311 return false; // truncation may occur
1312 }
1313 }
1314 // No possibility of wrap so truncation can be discarded
1315 // Promote iv type to Int
1316 } else {
1317 assert(trunc1 == NULL && trunc2 == NULL, "no truncation for int");
1318 }
1319
1320 if (!condition_stride_ok(bt, stride_con)) {
1321 return false;
1322 }
1323
1324 const TypeInteger* init_t = gvn->type(init_trip)->is_integer(iv_bt);
1325
1326 if (stride_con > 0) {
1327 if (init_t->lo_as_long() > max_signed_integer(iv_bt) - stride_con) {
1328 return false; // cyclic loop
1329 }
1330 } else {
1331 if (init_t->hi_as_long() < min_signed_integer(iv_bt) - stride_con) {
1332 return false; // cyclic loop
1333 }
1334 }
1335
1336 if (phi_incr != NULL && bt != BoolTest::ne) {
1337 // check if there is a possiblity of IV overflowing after the first increment
1338 if (stride_con > 0) {
1339 if (init_t->hi_as_long() > max_signed_integer(iv_bt) - stride_con) {
1340 return false;
1341 }
1342 } else {
1343 if (init_t->lo_as_long() < min_signed_integer(iv_bt) - stride_con) {
1344 return false;
1345 }
1346 }
1347 }
1348
1349 // =================================================
1350 // ---- SUCCESS! Found A Trip-Counted Loop! -----
1351 //
1352 assert(x->Opcode() == Op_Loop || x->Opcode() == Op_LongCountedLoop, "regular loops only");
1353 C->print_method(PHASE_BEFORE_CLOOPS, 3);
1354
1355 // ===================================================
1356 // Generate loop limit check to avoid integer overflow
1357 // in cases like next (cyclic loops):
1358 //
1359 // for (i=0; i <= max_jint; i++) {}
1360 // for (i=0; i < max_jint; i+=2) {}
1361 //
1362 //
1363 // Limit check predicate depends on the loop test:
1364 //
1365 // for(;i != limit; i++) --> limit <= (max_jint)
1366 // for(;i < limit; i+=stride) --> limit <= (max_jint - stride + 1)
1367 // for(;i <= limit; i+=stride) --> limit <= (max_jint - stride )
1368 //
1369
1370 // Check if limit is excluded to do more precise int overflow check.
1371 bool incl_limit = (bt == BoolTest::le || bt == BoolTest::ge);
1372 jlong stride_m = stride_con - (incl_limit ? 0 : (stride_con > 0 ? 1 : -1));
1373
1374 // If compare points directly to the phi we need to adjust
1375 // the compare so that it points to the incr. Limit have
1376 // to be adjusted to keep trip count the same and the
1377 // adjusted limit should be checked for int overflow.
1378 Node* adjusted_limit = limit;
1379 if (phi_incr != NULL) {
1380 stride_m += stride_con;
1381 }
1382
1383 Node *init_control = x->in(LoopNode::EntryControl);
1384
1385 int sov = check_stride_overflow(stride_m, limit_t, iv_bt);
1386 // If sov==0, limit's type always satisfies the condition, for
1387 // example, when it is an array length.
1388 if (sov != 0) {
1389 if (sov < 0) {
1390 return false; // Bailout: integer overflow is certain.
1391 }
1392 assert(!x->as_Loop()->is_transformed_long_loop(), "long loop was transformed");
1393 // Generate loop's limit check.
1394 // Loop limit check predicate should be near the loop.
1395 ProjNode *limit_check_proj = find_predicate_insertion_point(init_control, Deoptimization::Reason_loop_limit_check);
1396 if (!limit_check_proj) {
1397 // The limit check predicate is not generated if this method trapped here before.
1398 #ifdef ASSERT
1399 if (TraceLoopLimitCheck) {
1400 tty->print("missing loop limit check:");
1401 loop->dump_head();
1402 x->dump(1);
1403 }
1404 #endif
1405 return false;
1406 }
1407
1408 IfNode* check_iff = limit_check_proj->in(0)->as_If();
1409
1410 if (!is_dominator(get_ctrl(limit), check_iff->in(0))) {
1411 return false;
1412 }
1413
1414 Node* cmp_limit;
1415 Node* bol;
1416
1417 if (stride_con > 0) {
1418 cmp_limit = CmpNode::make(limit, _igvn.integercon(max_jint - stride_m, iv_bt), iv_bt);
1419 bol = new BoolNode(cmp_limit, BoolTest::le);
1420 } else {
1421 cmp_limit = CmpNode::make(limit, _igvn.integercon(min_jint - stride_m, iv_bt), iv_bt);
1422 bol = new BoolNode(cmp_limit, BoolTest::ge);
1423 }
1424
1425 insert_loop_limit_check(limit_check_proj, cmp_limit, bol);
1426 }
1427
1428 // Now we need to canonicalize loop condition.
1429 if (bt == BoolTest::ne) {
1430 assert(stride_con == 1 || stride_con == -1, "simple increment only");
1431 if (stride_con > 0 && init_t->hi_as_long() < limit_t->lo_as_long()) {
1432 // 'ne' can be replaced with 'lt' only when init < limit.
1433 bt = BoolTest::lt;
1434 } else if (stride_con < 0 && init_t->lo_as_long() > limit_t->hi_as_long()) {
1435 // 'ne' can be replaced with 'gt' only when init > limit.
1436 bt = BoolTest::gt;
1437 } else {
1438 ProjNode *limit_check_proj = find_predicate_insertion_point(init_control, Deoptimization::Reason_loop_limit_check);
1439 if (!limit_check_proj) {
1440 // The limit check predicate is not generated if this method trapped here before.
1441 #ifdef ASSERT
1442 if (TraceLoopLimitCheck) {
1443 tty->print("missing loop limit check:");
1444 loop->dump_head();
1445 x->dump(1);
1446 }
1447 #endif
1448 return false;
1449 }
1450 IfNode* check_iff = limit_check_proj->in(0)->as_If();
1451
1452 if (!is_dominator(get_ctrl(limit), check_iff->in(0)) ||
1453 !is_dominator(get_ctrl(init_trip), check_iff->in(0))) {
1454 return false;
1455 }
1456
1457 Node* cmp_limit;
1458 Node* bol;
1459
1460 if (stride_con > 0) {
1461 cmp_limit = CmpNode::make(init_trip, limit, iv_bt);
1462 bol = new BoolNode(cmp_limit, BoolTest::lt);
1463 } else {
1464 cmp_limit = CmpNode::make(init_trip, limit, iv_bt);
1465 bol = new BoolNode(cmp_limit, BoolTest::gt);
1466 }
1467
1468 insert_loop_limit_check(limit_check_proj, cmp_limit, bol);
1469
1470 if (stride_con > 0) {
1471 // 'ne' can be replaced with 'lt' only when init < limit.
1472 bt = BoolTest::lt;
1473 } else if (stride_con < 0) {
1474 // 'ne' can be replaced with 'gt' only when init > limit.
1475 bt = BoolTest::gt;
1476 }
1477 }
1478 }
1479
1480 #ifdef ASSERT
1481 if (iv_bt == T_INT &&
1482 !x->as_Loop()->is_transformed_long_loop() &&
1483 StressLongCountedLoop > 0 &&
1484 trunc1 == NULL &&
1485 convert_to_long_loop(cmp, phi, loop)) {
1486 return false;
1487 }
1488 #endif
1489
1490 if (phi_incr != NULL) {
1491 // If compare points directly to the phi we need to adjust
1492 // the compare so that it points to the incr. Limit have
1493 // to be adjusted to keep trip count the same and we
1494 // should avoid int overflow.
1495 //
1496 // i = init; do {} while(i++ < limit);
1497 // is converted to
1498 // i = init; do {} while(++i < limit+1);
1499 //
1500 adjusted_limit = gvn->transform(AddNode::make(limit, stride, iv_bt));
1501 }
1502
1503 if (incl_limit) {
1504 // The limit check guaranties that 'limit <= (max_jint - stride)' so
1505 // we can convert 'i <= limit' to 'i < limit+1' since stride != 0.
1506 //
1507 Node* one = (stride_con > 0) ? gvn->integercon( 1, iv_bt) : gvn->integercon(-1, iv_bt);
1508 adjusted_limit = gvn->transform(AddNode::make(adjusted_limit, one, iv_bt));
1509 if (bt == BoolTest::le)
1510 bt = BoolTest::lt;
1511 else if (bt == BoolTest::ge)
1512 bt = BoolTest::gt;
1513 else
1514 ShouldNotReachHere();
1515 }
1516 set_subtree_ctrl(adjusted_limit, false);
1517
1518 if (iv_bt == T_INT && LoopStripMiningIter == 0) {
1519 // Check for SafePoint on backedge and remove
1520 Node *sfpt = x->in(LoopNode::LoopBackControl);
1521 if (sfpt->Opcode() == Op_SafePoint && is_deleteable_safept(sfpt)) {
1522 lazy_replace( sfpt, iftrue );
1523 if (loop->_safepts != NULL) {
1524 loop->_safepts->yank(sfpt);
1525 }
1526 loop->_tail = iftrue;
1527 }
1528 }
1529
1530 // Build a canonical trip test.
1531 // Clone code, as old values may be in use.
1532 incr = incr->clone();
1533 incr->set_req(1,phi);
1534 incr->set_req(2,stride);
1535 incr = _igvn.register_new_node_with_optimizer(incr);
1536 set_early_ctrl(incr, false);
1537 _igvn.rehash_node_delayed(phi);
1538 phi->set_req_X( LoopNode::LoopBackControl, incr, &_igvn );
1539
1540 // If phi type is more restrictive than Int, raise to
1541 // Int to prevent (almost) infinite recursion in igvn
1542 // which can only handle integer types for constants or minint..maxint.
1543 if (!TypeInteger::bottom(iv_bt)->higher_equal(phi->bottom_type())) {
1544 Node* nphi = PhiNode::make(phi->in(0), phi->in(LoopNode::EntryControl), TypeInteger::bottom(iv_bt));
1545 nphi->set_req(LoopNode::LoopBackControl, phi->in(LoopNode::LoopBackControl));
1546 nphi = _igvn.register_new_node_with_optimizer(nphi);
1547 set_ctrl(nphi, get_ctrl(phi));
1548 _igvn.replace_node(phi, nphi);
1549 phi = nphi->as_Phi();
1550 }
1551 cmp = cmp->clone();
1552 cmp->set_req(1,incr);
1553 cmp->set_req(2, adjusted_limit);
1554 cmp = _igvn.register_new_node_with_optimizer(cmp);
1555 set_ctrl(cmp, iff->in(0));
1556
1557 test = test->clone()->as_Bool();
1558 (*(BoolTest*)&test->_test)._test = bt;
1559 test->set_req(1,cmp);
1560 _igvn.register_new_node_with_optimizer(test);
1561 set_ctrl(test, iff->in(0));
1562
1563 // Replace the old IfNode with a new LoopEndNode
1564 Node *lex = _igvn.register_new_node_with_optimizer(BaseCountedLoopEndNode::make(iff->in(0), test, cl_prob, iff->as_If()->_fcnt, iv_bt));
1565 IfNode *le = lex->as_If();
1566 uint dd = dom_depth(iff);
1567 set_idom(le, le->in(0), dd); // Update dominance for loop exit
1568 set_loop(le, loop);
1569
1570 // Get the loop-exit control
1571 Node *iffalse = iff->as_If()->proj_out(!(iftrue_op == Op_IfTrue));
1572
1573 // Need to swap loop-exit and loop-back control?
1574 if (iftrue_op == Op_IfFalse) {
1575 Node *ift2=_igvn.register_new_node_with_optimizer(new IfTrueNode (le));
1576 Node *iff2=_igvn.register_new_node_with_optimizer(new IfFalseNode(le));
1577
1578 loop->_tail = back_control = ift2;
1579 set_loop(ift2, loop);
1580 set_loop(iff2, get_loop(iffalse));
1581
1582 // Lazy update of 'get_ctrl' mechanism.
1583 lazy_replace(iffalse, iff2);
1584 lazy_replace(iftrue, ift2);
1585
1586 // Swap names
1587 iffalse = iff2;
1588 iftrue = ift2;
1589 } else {
1590 _igvn.rehash_node_delayed(iffalse);
1591 _igvn.rehash_node_delayed(iftrue);
1592 iffalse->set_req_X( 0, le, &_igvn );
1593 iftrue ->set_req_X( 0, le, &_igvn );
1594 }
1595
1596 set_idom(iftrue, le, dd+1);
1597 set_idom(iffalse, le, dd+1);
1598 assert(iff->outcnt() == 0, "should be dead now");
1599 lazy_replace( iff, le ); // fix 'get_ctrl'
1600
1601 Node *sfpt2 = le->in(0);
1602
1603 Node* entry_control = init_control;
1604 bool strip_mine_loop = iv_bt == T_INT &&
1605 LoopStripMiningIter > 1 &&
1606 loop->_child == NULL &&
1607 sfpt2->Opcode() == Op_SafePoint &&
1608 !loop->_has_call;
1609 IdealLoopTree* outer_ilt = NULL;
1610 if (strip_mine_loop) {
1611 outer_ilt = create_outer_strip_mined_loop(test, cmp, init_control, loop,
1612 cl_prob, le->_fcnt, entry_control,
1613 iffalse);
1614 }
1615
1616 // Now setup a new CountedLoopNode to replace the existing LoopNode
1617 BaseCountedLoopNode *l = BaseCountedLoopNode::make(entry_control, back_control, iv_bt);
1618 l->set_unswitch_count(x->as_Loop()->unswitch_count()); // Preserve
1619 // The following assert is approximately true, and defines the intention
1620 // of can_be_counted_loop. It fails, however, because phase->type
1621 // is not yet initialized for this loop and its parts.
1622 //assert(l->can_be_counted_loop(this), "sanity");
1623 _igvn.register_new_node_with_optimizer(l);
1624 set_loop(l, loop);
1625 loop->_head = l;
1626 // Fix all data nodes placed at the old loop head.
1627 // Uses the lazy-update mechanism of 'get_ctrl'.
1628 lazy_replace( x, l );
1629 set_idom(l, entry_control, dom_depth(entry_control) + 1);
1630
1631 if (iv_bt == T_INT && (LoopStripMiningIter == 0 || strip_mine_loop)) {
1632 // Check for immediately preceding SafePoint and remove
1633 if (sfpt2->Opcode() == Op_SafePoint && (LoopStripMiningIter != 0 || is_deleteable_safept(sfpt2))) {
1634 if (strip_mine_loop) {
1635 Node* outer_le = outer_ilt->_tail->in(0);
1636 Node* sfpt = sfpt2->clone();
1637 sfpt->set_req(0, iffalse);
1638 outer_le->set_req(0, sfpt);
1639 // When this code runs, loop bodies have not yet been populated.
1640 const bool body_populated = false;
1641 register_control(sfpt, outer_ilt, iffalse, body_populated);
1642 set_idom(outer_le, sfpt, dom_depth(sfpt));
1643 }
1644 lazy_replace( sfpt2, sfpt2->in(TypeFunc::Control));
1645 if (loop->_safepts != NULL) {
1646 loop->_safepts->yank(sfpt2);
1647 }
1648 }
1649 }
1650
1651 #ifdef ASSERT
1652 assert(l->is_valid_counted_loop(iv_bt), "counted loop shape is messed up");
1653 assert(l == loop->_head && l->phi() == phi && l->loopexit_or_null() == lex, "" );
1654 #endif
1655 #ifndef PRODUCT
1656 if (TraceLoopOpts) {
1657 tty->print("Counted ");
1658 loop->dump_head();
1659 }
1660 #endif
1661
1662 C->print_method(PHASE_AFTER_CLOOPS, 3);
1663
1664 // Capture bounds of the loop in the induction variable Phi before
1665 // subsequent transformation (iteration splitting) obscures the
1666 // bounds
1667 l->phi()->as_Phi()->set_type(l->phi()->Value(&_igvn));
1668
1669 if (strip_mine_loop) {
1670 l->mark_strip_mined();
1671 l->verify_strip_mined(1);
1672 outer_ilt->_head->as_Loop()->verify_strip_mined(1);
1673 loop = outer_ilt;
1674 }
1675
1676 #ifndef PRODUCT
1677 if (x->as_Loop()->is_transformed_long_loop()) {
1678 Atomic::inc(&_long_loop_counted_loops);
1679 }
1680 #endif
1681
1682 return true;
1683 }
1684
1685 //----------------------exact_limit-------------------------------------------
exact_limit(IdealLoopTree * loop)1686 Node* PhaseIdealLoop::exact_limit( IdealLoopTree *loop ) {
1687 assert(loop->_head->is_CountedLoop(), "");
1688 CountedLoopNode *cl = loop->_head->as_CountedLoop();
1689 assert(cl->is_valid_counted_loop(T_INT), "");
1690
1691 if (ABS(cl->stride_con()) == 1 ||
1692 cl->limit()->Opcode() == Op_LoopLimit) {
1693 // Old code has exact limit (it could be incorrect in case of int overflow).
1694 // Loop limit is exact with stride == 1. And loop may already have exact limit.
1695 return cl->limit();
1696 }
1697 Node *limit = NULL;
1698 #ifdef ASSERT
1699 BoolTest::mask bt = cl->loopexit()->test_trip();
1700 assert(bt == BoolTest::lt || bt == BoolTest::gt, "canonical test is expected");
1701 #endif
1702 if (cl->has_exact_trip_count()) {
1703 // Simple case: loop has constant boundaries.
1704 // Use jlongs to avoid integer overflow.
1705 int stride_con = cl->stride_con();
1706 jlong init_con = cl->init_trip()->get_int();
1707 jlong limit_con = cl->limit()->get_int();
1708 julong trip_cnt = cl->trip_count();
1709 jlong final_con = init_con + trip_cnt*stride_con;
1710 int final_int = (int)final_con;
1711 // The final value should be in integer range since the loop
1712 // is counted and the limit was checked for overflow.
1713 assert(final_con == (jlong)final_int, "final value should be integer");
1714 limit = _igvn.intcon(final_int);
1715 } else {
1716 // Create new LoopLimit node to get exact limit (final iv value).
1717 limit = new LoopLimitNode(C, cl->init_trip(), cl->limit(), cl->stride());
1718 register_new_node(limit, cl->in(LoopNode::EntryControl));
1719 }
1720 assert(limit != NULL, "sanity");
1721 return limit;
1722 }
1723
1724 //------------------------------Ideal------------------------------------------
1725 // Return a node which is more "ideal" than the current node.
1726 // Attempt to convert into a counted-loop.
Ideal(PhaseGVN * phase,bool can_reshape)1727 Node *LoopNode::Ideal(PhaseGVN *phase, bool can_reshape) {
1728 if (!can_be_counted_loop(phase) && !is_OuterStripMinedLoop()) {
1729 phase->C->set_major_progress();
1730 }
1731 return RegionNode::Ideal(phase, can_reshape);
1732 }
1733
1734 #ifdef ASSERT
verify_strip_mined(int expect_skeleton) const1735 void LoopNode::verify_strip_mined(int expect_skeleton) const {
1736 const OuterStripMinedLoopNode* outer = NULL;
1737 const CountedLoopNode* inner = NULL;
1738 if (is_strip_mined()) {
1739 if (!is_valid_counted_loop(T_INT)) {
1740 return; // Skip malformed counted loop
1741 }
1742 assert(is_CountedLoop(), "no Loop should be marked strip mined");
1743 inner = as_CountedLoop();
1744 outer = inner->in(LoopNode::EntryControl)->as_OuterStripMinedLoop();
1745 } else if (is_OuterStripMinedLoop()) {
1746 outer = this->as_OuterStripMinedLoop();
1747 inner = outer->unique_ctrl_out()->as_CountedLoop();
1748 assert(inner->is_valid_counted_loop(T_INT) && inner->is_strip_mined(), "OuterStripMinedLoop should have been removed");
1749 assert(!is_strip_mined(), "outer loop shouldn't be marked strip mined");
1750 }
1751 if (inner != NULL || outer != NULL) {
1752 assert(inner != NULL && outer != NULL, "missing loop in strip mined nest");
1753 Node* outer_tail = outer->in(LoopNode::LoopBackControl);
1754 Node* outer_le = outer_tail->in(0);
1755 assert(outer_le->Opcode() == Op_OuterStripMinedLoopEnd, "tail of outer loop should be an If");
1756 Node* sfpt = outer_le->in(0);
1757 assert(sfpt->Opcode() == Op_SafePoint, "where's the safepoint?");
1758 Node* inner_out = sfpt->in(0);
1759 if (inner_out->outcnt() != 1) {
1760 ResourceMark rm;
1761 Unique_Node_List wq;
1762
1763 for (DUIterator_Fast imax, i = inner_out->fast_outs(imax); i < imax; i++) {
1764 Node* u = inner_out->fast_out(i);
1765 if (u == sfpt) {
1766 continue;
1767 }
1768 wq.clear();
1769 wq.push(u);
1770 bool found_sfpt = false;
1771 for (uint next = 0; next < wq.size() && !found_sfpt; next++) {
1772 Node* n = wq.at(next);
1773 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax && !found_sfpt; i++) {
1774 Node* u = n->fast_out(i);
1775 if (u == sfpt) {
1776 found_sfpt = true;
1777 }
1778 if (!u->is_CFG()) {
1779 wq.push(u);
1780 }
1781 }
1782 }
1783 assert(found_sfpt, "no node in loop that's not input to safepoint");
1784 }
1785 }
1786
1787 CountedLoopEndNode* cle = inner_out->in(0)->as_CountedLoopEnd();
1788 assert(cle == inner->loopexit_or_null(), "mismatch");
1789 bool has_skeleton = outer_le->in(1)->bottom_type()->singleton() && outer_le->in(1)->bottom_type()->is_int()->get_con() == 0;
1790 if (has_skeleton) {
1791 assert(expect_skeleton == 1 || expect_skeleton == -1, "unexpected skeleton node");
1792 assert(outer->outcnt() == 2, "only control nodes");
1793 } else {
1794 assert(expect_skeleton == 0 || expect_skeleton == -1, "no skeleton node?");
1795 uint phis = 0;
1796 uint be_loads = 0;
1797 Node* be = inner->in(LoopNode::LoopBackControl);
1798 for (DUIterator_Fast imax, i = inner->fast_outs(imax); i < imax; i++) {
1799 Node* u = inner->fast_out(i);
1800 if (u->is_Phi()) {
1801 phis++;
1802 for (DUIterator_Fast jmax, j = be->fast_outs(jmax); j < jmax; j++) {
1803 Node* n = be->fast_out(j);
1804 if (n->is_Load()) {
1805 assert(n->in(0) == be, "should be on the backedge");
1806 do {
1807 n = n->raw_out(0);
1808 } while (!n->is_Phi());
1809 if (n == u) {
1810 be_loads++;
1811 break;
1812 }
1813 }
1814 }
1815 }
1816 }
1817 assert(be_loads <= phis, "wrong number phis that depends on a pinned load");
1818 for (DUIterator_Fast imax, i = outer->fast_outs(imax); i < imax; i++) {
1819 Node* u = outer->fast_out(i);
1820 assert(u == outer || u == inner || u->is_Phi(), "nothing between inner and outer loop");
1821 }
1822 uint stores = 0;
1823 for (DUIterator_Fast imax, i = inner_out->fast_outs(imax); i < imax; i++) {
1824 Node* u = inner_out->fast_out(i);
1825 if (u->is_Store()) {
1826 stores++;
1827 }
1828 }
1829 // Late optimization of loads on backedge can cause Phi of outer loop to be eliminated but Phi of inner loop is
1830 // not guaranteed to be optimized out.
1831 assert(outer->outcnt() >= phis + 2 - be_loads && outer->outcnt() <= phis + 2 + stores + 1, "only phis");
1832 }
1833 assert(sfpt->outcnt() == 1, "no data node");
1834 assert(outer_tail->outcnt() == 1 || !has_skeleton, "no data node");
1835 }
1836 }
1837 #endif
1838
1839 //=============================================================================
1840 //------------------------------Ideal------------------------------------------
1841 // Return a node which is more "ideal" than the current node.
1842 // Attempt to convert into a counted-loop.
Ideal(PhaseGVN * phase,bool can_reshape)1843 Node *CountedLoopNode::Ideal(PhaseGVN *phase, bool can_reshape) {
1844 return RegionNode::Ideal(phase, can_reshape);
1845 }
1846
1847 //------------------------------dump_spec--------------------------------------
1848 // Dump special per-node info
1849 #ifndef PRODUCT
dump_spec(outputStream * st) const1850 void CountedLoopNode::dump_spec(outputStream *st) const {
1851 LoopNode::dump_spec(st);
1852 if (stride_is_con()) {
1853 st->print("stride: %d ",stride_con());
1854 }
1855 if (is_pre_loop ()) st->print("pre of N%d" , _main_idx);
1856 if (is_main_loop()) st->print("main of N%d", _idx);
1857 if (is_post_loop()) st->print("post of N%d", _main_idx);
1858 if (is_strip_mined()) st->print(" strip mined");
1859 }
1860 #endif
1861
1862 //=============================================================================
stride_con() const1863 jlong BaseCountedLoopEndNode::stride_con() const {
1864 return stride()->bottom_type()->is_integer(bt())->get_con_as_long(bt());
1865 }
1866
1867
make(Node * control,Node * test,float prob,float cnt,BasicType bt)1868 BaseCountedLoopEndNode* BaseCountedLoopEndNode::make(Node* control, Node* test, float prob, float cnt, BasicType bt) {
1869 if (bt == T_INT) {
1870 return new CountedLoopEndNode(control, test, prob, cnt);
1871 }
1872 assert(bt == T_LONG, "unsupported");
1873 return new LongCountedLoopEndNode(control, test, prob, cnt);
1874 }
1875
1876 //=============================================================================
1877 //------------------------------Value-----------------------------------------
Value(PhaseGVN * phase) const1878 const Type* LoopLimitNode::Value(PhaseGVN* phase) const {
1879 const Type* init_t = phase->type(in(Init));
1880 const Type* limit_t = phase->type(in(Limit));
1881 const Type* stride_t = phase->type(in(Stride));
1882 // Either input is TOP ==> the result is TOP
1883 if (init_t == Type::TOP) return Type::TOP;
1884 if (limit_t == Type::TOP) return Type::TOP;
1885 if (stride_t == Type::TOP) return Type::TOP;
1886
1887 int stride_con = stride_t->is_int()->get_con();
1888 if (stride_con == 1)
1889 return NULL; // Identity
1890
1891 if (init_t->is_int()->is_con() && limit_t->is_int()->is_con()) {
1892 // Use jlongs to avoid integer overflow.
1893 jlong init_con = init_t->is_int()->get_con();
1894 jlong limit_con = limit_t->is_int()->get_con();
1895 int stride_m = stride_con - (stride_con > 0 ? 1 : -1);
1896 jlong trip_count = (limit_con - init_con + stride_m)/stride_con;
1897 jlong final_con = init_con + stride_con*trip_count;
1898 int final_int = (int)final_con;
1899 // The final value should be in integer range since the loop
1900 // is counted and the limit was checked for overflow.
1901 assert(final_con == (jlong)final_int, "final value should be integer");
1902 return TypeInt::make(final_int);
1903 }
1904
1905 return bottom_type(); // TypeInt::INT
1906 }
1907
1908 //------------------------------Ideal------------------------------------------
1909 // Return a node which is more "ideal" than the current node.
Ideal(PhaseGVN * phase,bool can_reshape)1910 Node *LoopLimitNode::Ideal(PhaseGVN *phase, bool can_reshape) {
1911 if (phase->type(in(Init)) == Type::TOP ||
1912 phase->type(in(Limit)) == Type::TOP ||
1913 phase->type(in(Stride)) == Type::TOP)
1914 return NULL; // Dead
1915
1916 int stride_con = phase->type(in(Stride))->is_int()->get_con();
1917 if (stride_con == 1)
1918 return NULL; // Identity
1919
1920 if (in(Init)->is_Con() && in(Limit)->is_Con())
1921 return NULL; // Value
1922
1923 // Delay following optimizations until all loop optimizations
1924 // done to keep Ideal graph simple.
1925 if (!can_reshape || !phase->C->post_loop_opts_phase()) {
1926 return NULL;
1927 }
1928
1929 const TypeInt* init_t = phase->type(in(Init) )->is_int();
1930 const TypeInt* limit_t = phase->type(in(Limit))->is_int();
1931 int stride_p;
1932 jlong lim, ini;
1933 julong max;
1934 if (stride_con > 0) {
1935 stride_p = stride_con;
1936 lim = limit_t->_hi;
1937 ini = init_t->_lo;
1938 max = (julong)max_jint;
1939 } else {
1940 stride_p = -stride_con;
1941 lim = init_t->_hi;
1942 ini = limit_t->_lo;
1943 max = (julong)min_jint;
1944 }
1945 julong range = lim - ini + stride_p;
1946 if (range <= max) {
1947 // Convert to integer expression if it is not overflow.
1948 Node* stride_m = phase->intcon(stride_con - (stride_con > 0 ? 1 : -1));
1949 Node *range = phase->transform(new SubINode(in(Limit), in(Init)));
1950 Node *bias = phase->transform(new AddINode(range, stride_m));
1951 Node *trip = phase->transform(new DivINode(0, bias, in(Stride)));
1952 Node *span = phase->transform(new MulINode(trip, in(Stride)));
1953 return new AddINode(span, in(Init)); // exact limit
1954 }
1955
1956 if (is_power_of_2(stride_p) || // divisor is 2^n
1957 !Matcher::has_match_rule(Op_LoopLimit)) { // or no specialized Mach node?
1958 // Convert to long expression to avoid integer overflow
1959 // and let igvn optimizer convert this division.
1960 //
1961 Node* init = phase->transform( new ConvI2LNode(in(Init)));
1962 Node* limit = phase->transform( new ConvI2LNode(in(Limit)));
1963 Node* stride = phase->longcon(stride_con);
1964 Node* stride_m = phase->longcon(stride_con - (stride_con > 0 ? 1 : -1));
1965
1966 Node *range = phase->transform(new SubLNode(limit, init));
1967 Node *bias = phase->transform(new AddLNode(range, stride_m));
1968 Node *span;
1969 if (stride_con > 0 && is_power_of_2(stride_p)) {
1970 // bias >= 0 if stride >0, so if stride is 2^n we can use &(-stride)
1971 // and avoid generating rounding for division. Zero trip guard should
1972 // guarantee that init < limit but sometimes the guard is missing and
1973 // we can get situation when init > limit. Note, for the empty loop
1974 // optimization zero trip guard is generated explicitly which leaves
1975 // only RCE predicate where exact limit is used and the predicate
1976 // will simply fail forcing recompilation.
1977 Node* neg_stride = phase->longcon(-stride_con);
1978 span = phase->transform(new AndLNode(bias, neg_stride));
1979 } else {
1980 Node *trip = phase->transform(new DivLNode(0, bias, stride));
1981 span = phase->transform(new MulLNode(trip, stride));
1982 }
1983 // Convert back to int
1984 Node *span_int = phase->transform(new ConvL2INode(span));
1985 return new AddINode(span_int, in(Init)); // exact limit
1986 }
1987
1988 return NULL; // No progress
1989 }
1990
1991 //------------------------------Identity---------------------------------------
1992 // If stride == 1 return limit node.
Identity(PhaseGVN * phase)1993 Node* LoopLimitNode::Identity(PhaseGVN* phase) {
1994 int stride_con = phase->type(in(Stride))->is_int()->get_con();
1995 if (stride_con == 1 || stride_con == -1)
1996 return in(Limit);
1997 return this;
1998 }
1999
2000 //=============================================================================
2001 //----------------------match_incr_with_optional_truncation--------------------
2002 // Match increment with optional truncation:
2003 // CHAR: (i+1)&0x7fff, BYTE: ((i+1)<<8)>>8, or SHORT: ((i+1)<<16)>>16
2004 // Return NULL for failure. Success returns the increment node.
match_incr_with_optional_truncation(Node * expr,Node ** trunc1,Node ** trunc2,const TypeInteger ** trunc_type,BasicType bt)2005 Node* CountedLoopNode::match_incr_with_optional_truncation(Node* expr, Node** trunc1, Node** trunc2,
2006 const TypeInteger** trunc_type,
2007 BasicType bt) {
2008 // Quick cutouts:
2009 if (expr == NULL || expr->req() != 3) return NULL;
2010
2011 Node *t1 = NULL;
2012 Node *t2 = NULL;
2013 Node* n1 = expr;
2014 int n1op = n1->Opcode();
2015 const TypeInteger* trunc_t = TypeInteger::bottom(bt);
2016
2017 if (bt == T_INT) {
2018 // Try to strip (n1 & M) or (n1 << N >> N) from n1.
2019 if (n1op == Op_AndI &&
2020 n1->in(2)->is_Con() &&
2021 n1->in(2)->bottom_type()->is_int()->get_con() == 0x7fff) {
2022 // %%% This check should match any mask of 2**K-1.
2023 t1 = n1;
2024 n1 = t1->in(1);
2025 n1op = n1->Opcode();
2026 trunc_t = TypeInt::CHAR;
2027 } else if (n1op == Op_RShiftI &&
2028 n1->in(1) != NULL &&
2029 n1->in(1)->Opcode() == Op_LShiftI &&
2030 n1->in(2) == n1->in(1)->in(2) &&
2031 n1->in(2)->is_Con()) {
2032 jint shift = n1->in(2)->bottom_type()->is_int()->get_con();
2033 // %%% This check should match any shift in [1..31].
2034 if (shift == 16 || shift == 8) {
2035 t1 = n1;
2036 t2 = t1->in(1);
2037 n1 = t2->in(1);
2038 n1op = n1->Opcode();
2039 if (shift == 16) {
2040 trunc_t = TypeInt::SHORT;
2041 } else if (shift == 8) {
2042 trunc_t = TypeInt::BYTE;
2043 }
2044 }
2045 }
2046 }
2047
2048 // If (maybe after stripping) it is an AddI, we won:
2049 if (n1->is_Add() && n1->operates_on(bt, true)) {
2050 *trunc1 = t1;
2051 *trunc2 = t2;
2052 *trunc_type = trunc_t;
2053 return n1;
2054 }
2055
2056 // failed
2057 return NULL;
2058 }
2059
skip_strip_mined(int expect_skeleton)2060 LoopNode* CountedLoopNode::skip_strip_mined(int expect_skeleton) {
2061 if (is_strip_mined() && is_valid_counted_loop(T_INT)) {
2062 verify_strip_mined(expect_skeleton);
2063 return in(EntryControl)->as_Loop();
2064 }
2065 return this;
2066 }
2067
outer_loop() const2068 OuterStripMinedLoopNode* CountedLoopNode::outer_loop() const {
2069 assert(is_strip_mined(), "not a strip mined loop");
2070 Node* c = in(EntryControl);
2071 if (c == NULL || c->is_top() || !c->is_OuterStripMinedLoop()) {
2072 return NULL;
2073 }
2074 return c->as_OuterStripMinedLoop();
2075 }
2076
outer_loop_tail() const2077 IfTrueNode* OuterStripMinedLoopNode::outer_loop_tail() const {
2078 Node* c = in(LoopBackControl);
2079 if (c == NULL || c->is_top()) {
2080 return NULL;
2081 }
2082 return c->as_IfTrue();
2083 }
2084
outer_loop_tail() const2085 IfTrueNode* CountedLoopNode::outer_loop_tail() const {
2086 LoopNode* l = outer_loop();
2087 if (l == NULL) {
2088 return NULL;
2089 }
2090 return l->outer_loop_tail();
2091 }
2092
outer_loop_end() const2093 OuterStripMinedLoopEndNode* OuterStripMinedLoopNode::outer_loop_end() const {
2094 IfTrueNode* proj = outer_loop_tail();
2095 if (proj == NULL) {
2096 return NULL;
2097 }
2098 Node* c = proj->in(0);
2099 if (c == NULL || c->is_top() || c->outcnt() != 2) {
2100 return NULL;
2101 }
2102 return c->as_OuterStripMinedLoopEnd();
2103 }
2104
outer_loop_end() const2105 OuterStripMinedLoopEndNode* CountedLoopNode::outer_loop_end() const {
2106 LoopNode* l = outer_loop();
2107 if (l == NULL) {
2108 return NULL;
2109 }
2110 return l->outer_loop_end();
2111 }
2112
outer_loop_exit() const2113 IfFalseNode* OuterStripMinedLoopNode::outer_loop_exit() const {
2114 IfNode* le = outer_loop_end();
2115 if (le == NULL) {
2116 return NULL;
2117 }
2118 Node* c = le->proj_out_or_null(false);
2119 if (c == NULL) {
2120 return NULL;
2121 }
2122 return c->as_IfFalse();
2123 }
2124
outer_loop_exit() const2125 IfFalseNode* CountedLoopNode::outer_loop_exit() const {
2126 LoopNode* l = outer_loop();
2127 if (l == NULL) {
2128 return NULL;
2129 }
2130 return l->outer_loop_exit();
2131 }
2132
outer_safepoint() const2133 SafePointNode* OuterStripMinedLoopNode::outer_safepoint() const {
2134 IfNode* le = outer_loop_end();
2135 if (le == NULL) {
2136 return NULL;
2137 }
2138 Node* c = le->in(0);
2139 if (c == NULL || c->is_top()) {
2140 return NULL;
2141 }
2142 assert(c->Opcode() == Op_SafePoint, "broken outer loop");
2143 return c->as_SafePoint();
2144 }
2145
outer_safepoint() const2146 SafePointNode* CountedLoopNode::outer_safepoint() const {
2147 LoopNode* l = outer_loop();
2148 if (l == NULL) {
2149 return NULL;
2150 }
2151 return l->outer_safepoint();
2152 }
2153
skip_predicates_from_entry(Node * ctrl)2154 Node* CountedLoopNode::skip_predicates_from_entry(Node* ctrl) {
2155 while (ctrl != NULL && ctrl->is_Proj() && ctrl->in(0)->is_If() &&
2156 ctrl->in(0)->as_If()->proj_out(1-ctrl->as_Proj()->_con)->outcnt() == 1 &&
2157 ctrl->in(0)->as_If()->proj_out(1-ctrl->as_Proj()->_con)->unique_out()->Opcode() == Op_Halt) {
2158 ctrl = ctrl->in(0)->in(0);
2159 }
2160
2161 return ctrl;
2162 }
2163
skip_predicates()2164 Node* CountedLoopNode::skip_predicates() {
2165 if (is_main_loop()) {
2166 Node* ctrl = skip_strip_mined()->in(LoopNode::EntryControl);
2167
2168 return skip_predicates_from_entry(ctrl);
2169 }
2170 return in(LoopNode::EntryControl);
2171 }
2172
2173
stride_con() const2174 int CountedLoopNode::stride_con() const {
2175 CountedLoopEndNode* cle = loopexit_or_null();
2176 return cle != NULL ? cle->stride_con() : 0;
2177 }
2178
stride_con() const2179 jlong LongCountedLoopNode::stride_con() const {
2180 LongCountedLoopEndNode* cle = loopexit_or_null();
2181 return cle != NULL ? cle->stride_con() : 0;
2182 }
2183
make(Node * entry,Node * backedge,BasicType bt)2184 BaseCountedLoopNode* BaseCountedLoopNode::make(Node* entry, Node* backedge, BasicType bt) {
2185 if (bt == T_INT) {
2186 return new CountedLoopNode(entry, backedge);
2187 }
2188 assert(bt == T_LONG, "unsupported");
2189 return new LongCountedLoopNode(entry, backedge);
2190 }
2191
2192
adjust_strip_mined_loop(PhaseIterGVN * igvn)2193 void OuterStripMinedLoopNode::adjust_strip_mined_loop(PhaseIterGVN* igvn) {
2194 // Look for the outer & inner strip mined loop, reduce number of
2195 // iterations of the inner loop, set exit condition of outer loop,
2196 // construct required phi nodes for outer loop.
2197 CountedLoopNode* inner_cl = unique_ctrl_out()->as_CountedLoop();
2198 assert(inner_cl->is_strip_mined(), "inner loop should be strip mined");
2199 Node* inner_iv_phi = inner_cl->phi();
2200 if (inner_iv_phi == NULL) {
2201 IfNode* outer_le = outer_loop_end();
2202 Node* iff = igvn->transform(new IfNode(outer_le->in(0), outer_le->in(1), outer_le->_prob, outer_le->_fcnt));
2203 igvn->replace_node(outer_le, iff);
2204 inner_cl->clear_strip_mined();
2205 return;
2206 }
2207 CountedLoopEndNode* inner_cle = inner_cl->loopexit();
2208
2209 int stride = inner_cl->stride_con();
2210 jlong scaled_iters_long = ((jlong)LoopStripMiningIter) * ABS(stride);
2211 int scaled_iters = (int)scaled_iters_long;
2212 int short_scaled_iters = LoopStripMiningIterShortLoop* ABS(stride);
2213 const TypeInt* inner_iv_t = igvn->type(inner_iv_phi)->is_int();
2214 jlong iter_estimate = (jlong)inner_iv_t->_hi - (jlong)inner_iv_t->_lo;
2215 assert(iter_estimate > 0, "broken");
2216 if ((jlong)scaled_iters != scaled_iters_long || iter_estimate <= short_scaled_iters) {
2217 // Remove outer loop and safepoint (too few iterations)
2218 Node* outer_sfpt = outer_safepoint();
2219 Node* outer_out = outer_loop_exit();
2220 igvn->replace_node(outer_out, outer_sfpt->in(0));
2221 igvn->replace_input_of(outer_sfpt, 0, igvn->C->top());
2222 inner_cl->clear_strip_mined();
2223 return;
2224 }
2225 if (iter_estimate <= scaled_iters_long) {
2226 // We would only go through one iteration of
2227 // the outer loop: drop the outer loop but
2228 // keep the safepoint so we don't run for
2229 // too long without a safepoint
2230 IfNode* outer_le = outer_loop_end();
2231 Node* iff = igvn->transform(new IfNode(outer_le->in(0), outer_le->in(1), outer_le->_prob, outer_le->_fcnt));
2232 igvn->replace_node(outer_le, iff);
2233 inner_cl->clear_strip_mined();
2234 return;
2235 }
2236
2237 Node* cle_tail = inner_cle->proj_out(true);
2238 ResourceMark rm;
2239 Node_List old_new;
2240 if (cle_tail->outcnt() > 1) {
2241 // Look for nodes on backedge of inner loop and clone them
2242 Unique_Node_List backedge_nodes;
2243 for (DUIterator_Fast imax, i = cle_tail->fast_outs(imax); i < imax; i++) {
2244 Node* u = cle_tail->fast_out(i);
2245 if (u != inner_cl) {
2246 assert(!u->is_CFG(), "control flow on the backedge?");
2247 backedge_nodes.push(u);
2248 }
2249 }
2250 uint last = igvn->C->unique();
2251 for (uint next = 0; next < backedge_nodes.size(); next++) {
2252 Node* n = backedge_nodes.at(next);
2253 old_new.map(n->_idx, n->clone());
2254 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
2255 Node* u = n->fast_out(i);
2256 assert(!u->is_CFG(), "broken");
2257 if (u->_idx >= last) {
2258 continue;
2259 }
2260 if (!u->is_Phi()) {
2261 backedge_nodes.push(u);
2262 } else {
2263 assert(u->in(0) == inner_cl, "strange phi on the backedge");
2264 }
2265 }
2266 }
2267 // Put the clones on the outer loop backedge
2268 Node* le_tail = outer_loop_tail();
2269 for (uint next = 0; next < backedge_nodes.size(); next++) {
2270 Node *n = old_new[backedge_nodes.at(next)->_idx];
2271 for (uint i = 1; i < n->req(); i++) {
2272 if (n->in(i) != NULL && old_new[n->in(i)->_idx] != NULL) {
2273 n->set_req(i, old_new[n->in(i)->_idx]);
2274 }
2275 }
2276 if (n->in(0) != NULL && n->in(0) == cle_tail) {
2277 n->set_req(0, le_tail);
2278 }
2279 igvn->register_new_node_with_optimizer(n);
2280 }
2281 }
2282
2283 Node* iv_phi = NULL;
2284 // Make a clone of each phi in the inner loop
2285 // for the outer loop
2286 for (uint i = 0; i < inner_cl->outcnt(); i++) {
2287 Node* u = inner_cl->raw_out(i);
2288 if (u->is_Phi()) {
2289 assert(u->in(0) == inner_cl, "inconsistent");
2290 Node* phi = u->clone();
2291 phi->set_req(0, this);
2292 Node* be = old_new[phi->in(LoopNode::LoopBackControl)->_idx];
2293 if (be != NULL) {
2294 phi->set_req(LoopNode::LoopBackControl, be);
2295 }
2296 phi = igvn->transform(phi);
2297 igvn->replace_input_of(u, LoopNode::EntryControl, phi);
2298 if (u == inner_iv_phi) {
2299 iv_phi = phi;
2300 }
2301 }
2302 }
2303 Node* cle_out = inner_cle->proj_out(false);
2304 if (cle_out->outcnt() > 1) {
2305 // Look for chains of stores that were sunk
2306 // out of the inner loop and are in the outer loop
2307 for (DUIterator_Fast imax, i = cle_out->fast_outs(imax); i < imax; i++) {
2308 Node* u = cle_out->fast_out(i);
2309 if (u->is_Store()) {
2310 Node* first = u;
2311 for(;;) {
2312 Node* next = first->in(MemNode::Memory);
2313 if (!next->is_Store() || next->in(0) != cle_out) {
2314 break;
2315 }
2316 first = next;
2317 }
2318 Node* last = u;
2319 for(;;) {
2320 Node* next = NULL;
2321 for (DUIterator_Fast jmax, j = last->fast_outs(jmax); j < jmax; j++) {
2322 Node* uu = last->fast_out(j);
2323 if (uu->is_Store() && uu->in(0) == cle_out) {
2324 assert(next == NULL, "only one in the outer loop");
2325 next = uu;
2326 }
2327 }
2328 if (next == NULL) {
2329 break;
2330 }
2331 last = next;
2332 }
2333 Node* phi = NULL;
2334 for (DUIterator_Fast jmax, j = fast_outs(jmax); j < jmax; j++) {
2335 Node* uu = fast_out(j);
2336 if (uu->is_Phi()) {
2337 Node* be = uu->in(LoopNode::LoopBackControl);
2338 if (be->is_Store() && old_new[be->_idx] != NULL) {
2339 assert(false, "store on the backedge + sunk stores: unsupported");
2340 // drop outer loop
2341 IfNode* outer_le = outer_loop_end();
2342 Node* iff = igvn->transform(new IfNode(outer_le->in(0), outer_le->in(1), outer_le->_prob, outer_le->_fcnt));
2343 igvn->replace_node(outer_le, iff);
2344 inner_cl->clear_strip_mined();
2345 return;
2346 }
2347 if (be == last || be == first->in(MemNode::Memory)) {
2348 assert(phi == NULL, "only one phi");
2349 phi = uu;
2350 }
2351 }
2352 }
2353 #ifdef ASSERT
2354 for (DUIterator_Fast jmax, j = fast_outs(jmax); j < jmax; j++) {
2355 Node* uu = fast_out(j);
2356 if (uu->is_Phi() && uu->bottom_type() == Type::MEMORY) {
2357 if (uu->adr_type() == igvn->C->get_adr_type(igvn->C->get_alias_index(u->adr_type()))) {
2358 assert(phi == uu, "what's that phi?");
2359 } else if (uu->adr_type() == TypePtr::BOTTOM) {
2360 Node* n = uu->in(LoopNode::LoopBackControl);
2361 uint limit = igvn->C->live_nodes();
2362 uint i = 0;
2363 while (n != uu) {
2364 i++;
2365 assert(i < limit, "infinite loop");
2366 if (n->is_Proj()) {
2367 n = n->in(0);
2368 } else if (n->is_SafePoint() || n->is_MemBar()) {
2369 n = n->in(TypeFunc::Memory);
2370 } else if (n->is_Phi()) {
2371 n = n->in(1);
2372 } else if (n->is_MergeMem()) {
2373 n = n->as_MergeMem()->memory_at(igvn->C->get_alias_index(u->adr_type()));
2374 } else if (n->is_Store() || n->is_LoadStore() || n->is_ClearArray()) {
2375 n = n->in(MemNode::Memory);
2376 } else {
2377 n->dump();
2378 ShouldNotReachHere();
2379 }
2380 }
2381 }
2382 }
2383 }
2384 #endif
2385 if (phi == NULL) {
2386 // If the an entire chains was sunk, the
2387 // inner loop has no phi for that memory
2388 // slice, create one for the outer loop
2389 phi = PhiNode::make(this, first->in(MemNode::Memory), Type::MEMORY,
2390 igvn->C->get_adr_type(igvn->C->get_alias_index(u->adr_type())));
2391 phi->set_req(LoopNode::LoopBackControl, last);
2392 phi = igvn->transform(phi);
2393 igvn->replace_input_of(first, MemNode::Memory, phi);
2394 } else {
2395 // Or fix the outer loop fix to include
2396 // that chain of stores.
2397 Node* be = phi->in(LoopNode::LoopBackControl);
2398 assert(!(be->is_Store() && old_new[be->_idx] != NULL), "store on the backedge + sunk stores: unsupported");
2399 if (be == first->in(MemNode::Memory)) {
2400 if (be == phi->in(LoopNode::LoopBackControl)) {
2401 igvn->replace_input_of(phi, LoopNode::LoopBackControl, last);
2402 } else {
2403 igvn->replace_input_of(be, MemNode::Memory, last);
2404 }
2405 } else {
2406 #ifdef ASSERT
2407 if (be == phi->in(LoopNode::LoopBackControl)) {
2408 assert(phi->in(LoopNode::LoopBackControl) == last, "");
2409 } else {
2410 assert(be->in(MemNode::Memory) == last, "");
2411 }
2412 #endif
2413 }
2414 }
2415 }
2416 }
2417 }
2418
2419 if (iv_phi != NULL) {
2420 // Now adjust the inner loop's exit condition
2421 Node* limit = inner_cl->limit();
2422 // If limit < init for stride > 0 (or limit > init for stride < 0),
2423 // the loop body is run only once. Given limit - init (init - limit resp.)
2424 // would be negative, the unsigned comparison below would cause
2425 // the loop body to be run for LoopStripMiningIter.
2426 Node* max = NULL;
2427 if (stride > 0) {
2428 max = MaxNode::max_diff_with_zero(limit, iv_phi, TypeInt::INT, *igvn);
2429 } else {
2430 max = MaxNode::max_diff_with_zero(iv_phi, limit, TypeInt::INT, *igvn);
2431 }
2432 // sub is positive and can be larger than the max signed int
2433 // value. Use an unsigned min.
2434 Node* const_iters = igvn->intcon(scaled_iters);
2435 Node* min = MaxNode::unsigned_min(max, const_iters, TypeInt::make(0, scaled_iters, Type::WidenMin), *igvn);
2436 // min is the number of iterations for the next inner loop execution:
2437 // unsigned_min(max(limit - iv_phi, 0), scaled_iters) if stride > 0
2438 // unsigned_min(max(iv_phi - limit, 0), scaled_iters) if stride < 0
2439
2440 Node* new_limit = NULL;
2441 if (stride > 0) {
2442 new_limit = igvn->transform(new AddINode(min, iv_phi));
2443 } else {
2444 new_limit = igvn->transform(new SubINode(iv_phi, min));
2445 }
2446 Node* inner_cmp = inner_cle->cmp_node();
2447 Node* inner_bol = inner_cle->in(CountedLoopEndNode::TestValue);
2448 Node* outer_bol = inner_bol;
2449 // cmp node for inner loop may be shared
2450 inner_cmp = inner_cmp->clone();
2451 inner_cmp->set_req(2, new_limit);
2452 inner_bol = inner_bol->clone();
2453 inner_bol->set_req(1, igvn->transform(inner_cmp));
2454 igvn->replace_input_of(inner_cle, CountedLoopEndNode::TestValue, igvn->transform(inner_bol));
2455 // Set the outer loop's exit condition too
2456 igvn->replace_input_of(outer_loop_end(), 1, outer_bol);
2457 } else {
2458 assert(false, "should be able to adjust outer loop");
2459 IfNode* outer_le = outer_loop_end();
2460 Node* iff = igvn->transform(new IfNode(outer_le->in(0), outer_le->in(1), outer_le->_prob, outer_le->_fcnt));
2461 igvn->replace_node(outer_le, iff);
2462 inner_cl->clear_strip_mined();
2463 }
2464 }
2465
Value(PhaseGVN * phase) const2466 const Type* OuterStripMinedLoopEndNode::Value(PhaseGVN* phase) const {
2467 if (!in(0)) return Type::TOP;
2468 if (phase->type(in(0)) == Type::TOP)
2469 return Type::TOP;
2470
2471 // Until expansion, the loop end condition is not set so this should not constant fold.
2472 if (is_expanded(phase)) {
2473 return IfNode::Value(phase);
2474 }
2475
2476 return TypeTuple::IFBOTH;
2477 }
2478
is_expanded(PhaseGVN * phase) const2479 bool OuterStripMinedLoopEndNode::is_expanded(PhaseGVN *phase) const {
2480 // The outer strip mined loop head only has Phi uses after expansion
2481 if (phase->is_IterGVN()) {
2482 Node* backedge = proj_out_or_null(true);
2483 if (backedge != NULL) {
2484 Node* head = backedge->unique_ctrl_out();
2485 if (head != NULL && head->is_OuterStripMinedLoop()) {
2486 if (head->find_out_with(Op_Phi) != NULL) {
2487 return true;
2488 }
2489 }
2490 }
2491 }
2492 return false;
2493 }
2494
Ideal(PhaseGVN * phase,bool can_reshape)2495 Node *OuterStripMinedLoopEndNode::Ideal(PhaseGVN *phase, bool can_reshape) {
2496 if (remove_dead_region(phase, can_reshape)) return this;
2497
2498 return NULL;
2499 }
2500
2501 //------------------------------filtered_type--------------------------------
2502 // Return a type based on condition control flow
2503 // A successful return will be a type that is restricted due
2504 // to a series of dominating if-tests, such as:
2505 // if (i < 10) {
2506 // if (i > 0) {
2507 // here: "i" type is [1..10)
2508 // }
2509 // }
2510 // or a control flow merge
2511 // if (i < 10) {
2512 // do {
2513 // phi( , ) -- at top of loop type is [min_int..10)
2514 // i = ?
2515 // } while ( i < 10)
2516 //
filtered_type(Node * n,Node * n_ctrl)2517 const TypeInt* PhaseIdealLoop::filtered_type( Node *n, Node* n_ctrl) {
2518 assert(n && n->bottom_type()->is_int(), "must be int");
2519 const TypeInt* filtered_t = NULL;
2520 if (!n->is_Phi()) {
2521 assert(n_ctrl != NULL || n_ctrl == C->top(), "valid control");
2522 filtered_t = filtered_type_from_dominators(n, n_ctrl);
2523
2524 } else {
2525 Node* phi = n->as_Phi();
2526 Node* region = phi->in(0);
2527 assert(n_ctrl == NULL || n_ctrl == region, "ctrl parameter must be region");
2528 if (region && region != C->top()) {
2529 for (uint i = 1; i < phi->req(); i++) {
2530 Node* val = phi->in(i);
2531 Node* use_c = region->in(i);
2532 const TypeInt* val_t = filtered_type_from_dominators(val, use_c);
2533 if (val_t != NULL) {
2534 if (filtered_t == NULL) {
2535 filtered_t = val_t;
2536 } else {
2537 filtered_t = filtered_t->meet(val_t)->is_int();
2538 }
2539 }
2540 }
2541 }
2542 }
2543 const TypeInt* n_t = _igvn.type(n)->is_int();
2544 if (filtered_t != NULL) {
2545 n_t = n_t->join(filtered_t)->is_int();
2546 }
2547 return n_t;
2548 }
2549
2550
2551 //------------------------------filtered_type_from_dominators--------------------------------
2552 // Return a possibly more restrictive type for val based on condition control flow of dominators
filtered_type_from_dominators(Node * val,Node * use_ctrl)2553 const TypeInt* PhaseIdealLoop::filtered_type_from_dominators( Node* val, Node *use_ctrl) {
2554 if (val->is_Con()) {
2555 return val->bottom_type()->is_int();
2556 }
2557 uint if_limit = 10; // Max number of dominating if's visited
2558 const TypeInt* rtn_t = NULL;
2559
2560 if (use_ctrl && use_ctrl != C->top()) {
2561 Node* val_ctrl = get_ctrl(val);
2562 uint val_dom_depth = dom_depth(val_ctrl);
2563 Node* pred = use_ctrl;
2564 uint if_cnt = 0;
2565 while (if_cnt < if_limit) {
2566 if ((pred->Opcode() == Op_IfTrue || pred->Opcode() == Op_IfFalse)) {
2567 if_cnt++;
2568 const TypeInt* if_t = IfNode::filtered_int_type(&_igvn, val, pred);
2569 if (if_t != NULL) {
2570 if (rtn_t == NULL) {
2571 rtn_t = if_t;
2572 } else {
2573 rtn_t = rtn_t->join(if_t)->is_int();
2574 }
2575 }
2576 }
2577 pred = idom(pred);
2578 if (pred == NULL || pred == C->top()) {
2579 break;
2580 }
2581 // Stop if going beyond definition block of val
2582 if (dom_depth(pred) < val_dom_depth) {
2583 break;
2584 }
2585 }
2586 }
2587 return rtn_t;
2588 }
2589
2590
2591 //------------------------------dump_spec--------------------------------------
2592 // Dump special per-node info
2593 #ifndef PRODUCT
dump_spec(outputStream * st) const2594 void CountedLoopEndNode::dump_spec(outputStream *st) const {
2595 if( in(TestValue) != NULL && in(TestValue)->is_Bool() ) {
2596 BoolTest bt( test_trip()); // Added this for g++.
2597
2598 st->print("[");
2599 bt.dump_on(st);
2600 st->print("]");
2601 }
2602 st->print(" ");
2603 IfNode::dump_spec(st);
2604 }
2605 #endif
2606
2607 //=============================================================================
2608 //------------------------------is_member--------------------------------------
2609 // Is 'l' a member of 'this'?
is_member(const IdealLoopTree * l) const2610 bool IdealLoopTree::is_member(const IdealLoopTree *l) const {
2611 while( l->_nest > _nest ) l = l->_parent;
2612 return l == this;
2613 }
2614
2615 //------------------------------set_nest---------------------------------------
2616 // Set loop tree nesting depth. Accumulate _has_call bits.
set_nest(uint depth)2617 int IdealLoopTree::set_nest( uint depth ) {
2618 assert(depth <= SHRT_MAX, "sanity");
2619 _nest = depth;
2620 int bits = _has_call;
2621 if( _child ) bits |= _child->set_nest(depth+1);
2622 if( bits ) _has_call = 1;
2623 if( _next ) bits |= _next ->set_nest(depth );
2624 return bits;
2625 }
2626
2627 //------------------------------split_fall_in----------------------------------
2628 // Split out multiple fall-in edges from the loop header. Move them to a
2629 // private RegionNode before the loop. This becomes the loop landing pad.
split_fall_in(PhaseIdealLoop * phase,int fall_in_cnt)2630 void IdealLoopTree::split_fall_in( PhaseIdealLoop *phase, int fall_in_cnt ) {
2631 PhaseIterGVN &igvn = phase->_igvn;
2632 uint i;
2633
2634 // Make a new RegionNode to be the landing pad.
2635 Node *landing_pad = new RegionNode( fall_in_cnt+1 );
2636 phase->set_loop(landing_pad,_parent);
2637 // Gather all the fall-in control paths into the landing pad
2638 uint icnt = fall_in_cnt;
2639 uint oreq = _head->req();
2640 for( i = oreq-1; i>0; i-- )
2641 if( !phase->is_member( this, _head->in(i) ) )
2642 landing_pad->set_req(icnt--,_head->in(i));
2643
2644 // Peel off PhiNode edges as well
2645 for (DUIterator_Fast jmax, j = _head->fast_outs(jmax); j < jmax; j++) {
2646 Node *oj = _head->fast_out(j);
2647 if( oj->is_Phi() ) {
2648 PhiNode* old_phi = oj->as_Phi();
2649 assert( old_phi->region() == _head, "" );
2650 igvn.hash_delete(old_phi); // Yank from hash before hacking edges
2651 Node *p = PhiNode::make_blank(landing_pad, old_phi);
2652 uint icnt = fall_in_cnt;
2653 for( i = oreq-1; i>0; i-- ) {
2654 if( !phase->is_member( this, _head->in(i) ) ) {
2655 p->init_req(icnt--, old_phi->in(i));
2656 // Go ahead and clean out old edges from old phi
2657 old_phi->del_req(i);
2658 }
2659 }
2660 // Search for CSE's here, because ZKM.jar does a lot of
2661 // loop hackery and we need to be a little incremental
2662 // with the CSE to avoid O(N^2) node blow-up.
2663 Node *p2 = igvn.hash_find_insert(p); // Look for a CSE
2664 if( p2 ) { // Found CSE
2665 p->destruct(&igvn); // Recover useless new node
2666 p = p2; // Use old node
2667 } else {
2668 igvn.register_new_node_with_optimizer(p, old_phi);
2669 }
2670 // Make old Phi refer to new Phi.
2671 old_phi->add_req(p);
2672 // Check for the special case of making the old phi useless and
2673 // disappear it. In JavaGrande I have a case where this useless
2674 // Phi is the loop limit and prevents recognizing a CountedLoop
2675 // which in turn prevents removing an empty loop.
2676 Node *id_old_phi = old_phi->Identity(&igvn);
2677 if( id_old_phi != old_phi ) { // Found a simple identity?
2678 // Note that I cannot call 'replace_node' here, because
2679 // that will yank the edge from old_phi to the Region and
2680 // I'm mid-iteration over the Region's uses.
2681 for (DUIterator_Last imin, i = old_phi->last_outs(imin); i >= imin; ) {
2682 Node* use = old_phi->last_out(i);
2683 igvn.rehash_node_delayed(use);
2684 uint uses_found = 0;
2685 for (uint j = 0; j < use->len(); j++) {
2686 if (use->in(j) == old_phi) {
2687 if (j < use->req()) use->set_req (j, id_old_phi);
2688 else use->set_prec(j, id_old_phi);
2689 uses_found++;
2690 }
2691 }
2692 i -= uses_found; // we deleted 1 or more copies of this edge
2693 }
2694 }
2695 igvn._worklist.push(old_phi);
2696 }
2697 }
2698 // Finally clean out the fall-in edges from the RegionNode
2699 for( i = oreq-1; i>0; i-- ) {
2700 if( !phase->is_member( this, _head->in(i) ) ) {
2701 _head->del_req(i);
2702 }
2703 }
2704 igvn.rehash_node_delayed(_head);
2705 // Transform landing pad
2706 igvn.register_new_node_with_optimizer(landing_pad, _head);
2707 // Insert landing pad into the header
2708 _head->add_req(landing_pad);
2709 }
2710
2711 //------------------------------split_outer_loop-------------------------------
2712 // Split out the outermost loop from this shared header.
split_outer_loop(PhaseIdealLoop * phase)2713 void IdealLoopTree::split_outer_loop( PhaseIdealLoop *phase ) {
2714 PhaseIterGVN &igvn = phase->_igvn;
2715
2716 // Find index of outermost loop; it should also be my tail.
2717 uint outer_idx = 1;
2718 while( _head->in(outer_idx) != _tail ) outer_idx++;
2719
2720 // Make a LoopNode for the outermost loop.
2721 Node *ctl = _head->in(LoopNode::EntryControl);
2722 Node *outer = new LoopNode( ctl, _head->in(outer_idx) );
2723 outer = igvn.register_new_node_with_optimizer(outer, _head);
2724 phase->set_created_loop_node();
2725
2726 // Outermost loop falls into '_head' loop
2727 _head->set_req(LoopNode::EntryControl, outer);
2728 _head->del_req(outer_idx);
2729 // Split all the Phis up between '_head' loop and 'outer' loop.
2730 for (DUIterator_Fast jmax, j = _head->fast_outs(jmax); j < jmax; j++) {
2731 Node *out = _head->fast_out(j);
2732 if( out->is_Phi() ) {
2733 PhiNode *old_phi = out->as_Phi();
2734 assert( old_phi->region() == _head, "" );
2735 Node *phi = PhiNode::make_blank(outer, old_phi);
2736 phi->init_req(LoopNode::EntryControl, old_phi->in(LoopNode::EntryControl));
2737 phi->init_req(LoopNode::LoopBackControl, old_phi->in(outer_idx));
2738 phi = igvn.register_new_node_with_optimizer(phi, old_phi);
2739 // Make old Phi point to new Phi on the fall-in path
2740 igvn.replace_input_of(old_phi, LoopNode::EntryControl, phi);
2741 old_phi->del_req(outer_idx);
2742 }
2743 }
2744
2745 // Use the new loop head instead of the old shared one
2746 _head = outer;
2747 phase->set_loop(_head, this);
2748 }
2749
2750 //------------------------------fix_parent-------------------------------------
fix_parent(IdealLoopTree * loop,IdealLoopTree * parent)2751 static void fix_parent( IdealLoopTree *loop, IdealLoopTree *parent ) {
2752 loop->_parent = parent;
2753 if( loop->_child ) fix_parent( loop->_child, loop );
2754 if( loop->_next ) fix_parent( loop->_next , parent );
2755 }
2756
2757 //------------------------------estimate_path_freq-----------------------------
estimate_path_freq(Node * n)2758 static float estimate_path_freq( Node *n ) {
2759 // Try to extract some path frequency info
2760 IfNode *iff;
2761 for( int i = 0; i < 50; i++ ) { // Skip through a bunch of uncommon tests
2762 uint nop = n->Opcode();
2763 if( nop == Op_SafePoint ) { // Skip any safepoint
2764 n = n->in(0);
2765 continue;
2766 }
2767 if( nop == Op_CatchProj ) { // Get count from a prior call
2768 // Assume call does not always throw exceptions: means the call-site
2769 // count is also the frequency of the fall-through path.
2770 assert( n->is_CatchProj(), "" );
2771 if( ((CatchProjNode*)n)->_con != CatchProjNode::fall_through_index )
2772 return 0.0f; // Assume call exception path is rare
2773 Node *call = n->in(0)->in(0)->in(0);
2774 assert( call->is_Call(), "expect a call here" );
2775 const JVMState *jvms = ((CallNode*)call)->jvms();
2776 ciMethodData* methodData = jvms->method()->method_data();
2777 if (!methodData->is_mature()) return 0.0f; // No call-site data
2778 ciProfileData* data = methodData->bci_to_data(jvms->bci());
2779 if ((data == NULL) || !data->is_CounterData()) {
2780 // no call profile available, try call's control input
2781 n = n->in(0);
2782 continue;
2783 }
2784 return data->as_CounterData()->count()/FreqCountInvocations;
2785 }
2786 // See if there's a gating IF test
2787 Node *n_c = n->in(0);
2788 if( !n_c->is_If() ) break; // No estimate available
2789 iff = n_c->as_If();
2790 if( iff->_fcnt != COUNT_UNKNOWN ) // Have a valid count?
2791 // Compute how much count comes on this path
2792 return ((nop == Op_IfTrue) ? iff->_prob : 1.0f - iff->_prob) * iff->_fcnt;
2793 // Have no count info. Skip dull uncommon-trap like branches.
2794 if( (nop == Op_IfTrue && iff->_prob < PROB_LIKELY_MAG(5)) ||
2795 (nop == Op_IfFalse && iff->_prob > PROB_UNLIKELY_MAG(5)) )
2796 break;
2797 // Skip through never-taken branch; look for a real loop exit.
2798 n = iff->in(0);
2799 }
2800 return 0.0f; // No estimate available
2801 }
2802
2803 //------------------------------merge_many_backedges---------------------------
2804 // Merge all the backedges from the shared header into a private Region.
2805 // Feed that region as the one backedge to this loop.
merge_many_backedges(PhaseIdealLoop * phase)2806 void IdealLoopTree::merge_many_backedges( PhaseIdealLoop *phase ) {
2807 uint i;
2808
2809 // Scan for the top 2 hottest backedges
2810 float hotcnt = 0.0f;
2811 float warmcnt = 0.0f;
2812 uint hot_idx = 0;
2813 // Loop starts at 2 because slot 1 is the fall-in path
2814 for( i = 2; i < _head->req(); i++ ) {
2815 float cnt = estimate_path_freq(_head->in(i));
2816 if( cnt > hotcnt ) { // Grab hottest path
2817 warmcnt = hotcnt;
2818 hotcnt = cnt;
2819 hot_idx = i;
2820 } else if( cnt > warmcnt ) { // And 2nd hottest path
2821 warmcnt = cnt;
2822 }
2823 }
2824
2825 // See if the hottest backedge is worthy of being an inner loop
2826 // by being much hotter than the next hottest backedge.
2827 if( hotcnt <= 0.0001 ||
2828 hotcnt < 2.0*warmcnt ) hot_idx = 0;// No hot backedge
2829
2830 // Peel out the backedges into a private merge point; peel
2831 // them all except optionally hot_idx.
2832 PhaseIterGVN &igvn = phase->_igvn;
2833
2834 Node *hot_tail = NULL;
2835 // Make a Region for the merge point
2836 Node *r = new RegionNode(1);
2837 for( i = 2; i < _head->req(); i++ ) {
2838 if( i != hot_idx )
2839 r->add_req( _head->in(i) );
2840 else hot_tail = _head->in(i);
2841 }
2842 igvn.register_new_node_with_optimizer(r, _head);
2843 // Plug region into end of loop _head, followed by hot_tail
2844 while( _head->req() > 3 ) _head->del_req( _head->req()-1 );
2845 igvn.replace_input_of(_head, 2, r);
2846 if( hot_idx ) _head->add_req(hot_tail);
2847
2848 // Split all the Phis up between '_head' loop and the Region 'r'
2849 for (DUIterator_Fast jmax, j = _head->fast_outs(jmax); j < jmax; j++) {
2850 Node *out = _head->fast_out(j);
2851 if( out->is_Phi() ) {
2852 PhiNode* n = out->as_Phi();
2853 igvn.hash_delete(n); // Delete from hash before hacking edges
2854 Node *hot_phi = NULL;
2855 Node *phi = new PhiNode(r, n->type(), n->adr_type());
2856 // Check all inputs for the ones to peel out
2857 uint j = 1;
2858 for( uint i = 2; i < n->req(); i++ ) {
2859 if( i != hot_idx )
2860 phi->set_req( j++, n->in(i) );
2861 else hot_phi = n->in(i);
2862 }
2863 // Register the phi but do not transform until whole place transforms
2864 igvn.register_new_node_with_optimizer(phi, n);
2865 // Add the merge phi to the old Phi
2866 while( n->req() > 3 ) n->del_req( n->req()-1 );
2867 igvn.replace_input_of(n, 2, phi);
2868 if( hot_idx ) n->add_req(hot_phi);
2869 }
2870 }
2871
2872
2873 // Insert a new IdealLoopTree inserted below me. Turn it into a clone
2874 // of self loop tree. Turn self into a loop headed by _head and with
2875 // tail being the new merge point.
2876 IdealLoopTree *ilt = new IdealLoopTree( phase, _head, _tail );
2877 phase->set_loop(_tail,ilt); // Adjust tail
2878 _tail = r; // Self's tail is new merge point
2879 phase->set_loop(r,this);
2880 ilt->_child = _child; // New guy has my children
2881 _child = ilt; // Self has new guy as only child
2882 ilt->_parent = this; // new guy has self for parent
2883 ilt->_nest = _nest; // Same nesting depth (for now)
2884
2885 // Starting with 'ilt', look for child loop trees using the same shared
2886 // header. Flatten these out; they will no longer be loops in the end.
2887 IdealLoopTree **pilt = &_child;
2888 while( ilt ) {
2889 if( ilt->_head == _head ) {
2890 uint i;
2891 for( i = 2; i < _head->req(); i++ )
2892 if( _head->in(i) == ilt->_tail )
2893 break; // Still a loop
2894 if( i == _head->req() ) { // No longer a loop
2895 // Flatten ilt. Hang ilt's "_next" list from the end of
2896 // ilt's '_child' list. Move the ilt's _child up to replace ilt.
2897 IdealLoopTree **cp = &ilt->_child;
2898 while( *cp ) cp = &(*cp)->_next; // Find end of child list
2899 *cp = ilt->_next; // Hang next list at end of child list
2900 *pilt = ilt->_child; // Move child up to replace ilt
2901 ilt->_head = NULL; // Flag as a loop UNIONED into parent
2902 ilt = ilt->_child; // Repeat using new ilt
2903 continue; // do not advance over ilt->_child
2904 }
2905 assert( ilt->_tail == hot_tail, "expected to only find the hot inner loop here" );
2906 phase->set_loop(_head,ilt);
2907 }
2908 pilt = &ilt->_child; // Advance to next
2909 ilt = *pilt;
2910 }
2911
2912 if( _child ) fix_parent( _child, this );
2913 }
2914
2915 //------------------------------beautify_loops---------------------------------
2916 // Split shared headers and insert loop landing pads.
2917 // Insert a LoopNode to replace the RegionNode.
2918 // Return TRUE if loop tree is structurally changed.
beautify_loops(PhaseIdealLoop * phase)2919 bool IdealLoopTree::beautify_loops( PhaseIdealLoop *phase ) {
2920 bool result = false;
2921 // Cache parts in locals for easy
2922 PhaseIterGVN &igvn = phase->_igvn;
2923
2924 igvn.hash_delete(_head); // Yank from hash before hacking edges
2925
2926 // Check for multiple fall-in paths. Peel off a landing pad if need be.
2927 int fall_in_cnt = 0;
2928 for( uint i = 1; i < _head->req(); i++ )
2929 if( !phase->is_member( this, _head->in(i) ) )
2930 fall_in_cnt++;
2931 assert( fall_in_cnt, "at least 1 fall-in path" );
2932 if( fall_in_cnt > 1 ) // Need a loop landing pad to merge fall-ins
2933 split_fall_in( phase, fall_in_cnt );
2934
2935 // Swap inputs to the _head and all Phis to move the fall-in edge to
2936 // the left.
2937 fall_in_cnt = 1;
2938 while( phase->is_member( this, _head->in(fall_in_cnt) ) )
2939 fall_in_cnt++;
2940 if( fall_in_cnt > 1 ) {
2941 // Since I am just swapping inputs I do not need to update def-use info
2942 Node *tmp = _head->in(1);
2943 igvn.rehash_node_delayed(_head);
2944 _head->set_req( 1, _head->in(fall_in_cnt) );
2945 _head->set_req( fall_in_cnt, tmp );
2946 // Swap also all Phis
2947 for (DUIterator_Fast imax, i = _head->fast_outs(imax); i < imax; i++) {
2948 Node* phi = _head->fast_out(i);
2949 if( phi->is_Phi() ) {
2950 igvn.rehash_node_delayed(phi); // Yank from hash before hacking edges
2951 tmp = phi->in(1);
2952 phi->set_req( 1, phi->in(fall_in_cnt) );
2953 phi->set_req( fall_in_cnt, tmp );
2954 }
2955 }
2956 }
2957 assert( !phase->is_member( this, _head->in(1) ), "left edge is fall-in" );
2958 assert( phase->is_member( this, _head->in(2) ), "right edge is loop" );
2959
2960 // If I am a shared header (multiple backedges), peel off the many
2961 // backedges into a private merge point and use the merge point as
2962 // the one true backedge.
2963 if (_head->req() > 3) {
2964 // Merge the many backedges into a single backedge but leave
2965 // the hottest backedge as separate edge for the following peel.
2966 if (!_irreducible) {
2967 merge_many_backedges( phase );
2968 }
2969
2970 // When recursively beautify my children, split_fall_in can change
2971 // loop tree structure when I am an irreducible loop. Then the head
2972 // of my children has a req() not bigger than 3. Here we need to set
2973 // result to true to catch that case in order to tell the caller to
2974 // rebuild loop tree. See issue JDK-8244407 for details.
2975 result = true;
2976 }
2977
2978 // If I have one hot backedge, peel off myself loop.
2979 // I better be the outermost loop.
2980 if (_head->req() > 3 && !_irreducible) {
2981 split_outer_loop( phase );
2982 result = true;
2983
2984 } else if (!_head->is_Loop() && !_irreducible) {
2985 // Make a new LoopNode to replace the old loop head
2986 Node *l = new LoopNode( _head->in(1), _head->in(2) );
2987 l = igvn.register_new_node_with_optimizer(l, _head);
2988 phase->set_created_loop_node();
2989 // Go ahead and replace _head
2990 phase->_igvn.replace_node( _head, l );
2991 _head = l;
2992 phase->set_loop(_head, this);
2993 }
2994
2995 // Now recursively beautify nested loops
2996 if( _child ) result |= _child->beautify_loops( phase );
2997 if( _next ) result |= _next ->beautify_loops( phase );
2998 return result;
2999 }
3000
3001 //------------------------------allpaths_check_safepts----------------------------
3002 // Allpaths backwards scan from loop tail, terminating each path at first safepoint
3003 // encountered. Helper for check_safepts.
allpaths_check_safepts(VectorSet & visited,Node_List & stack)3004 void IdealLoopTree::allpaths_check_safepts(VectorSet &visited, Node_List &stack) {
3005 assert(stack.size() == 0, "empty stack");
3006 stack.push(_tail);
3007 visited.clear();
3008 visited.set(_tail->_idx);
3009 while (stack.size() > 0) {
3010 Node* n = stack.pop();
3011 if (n->is_Call() && n->as_Call()->guaranteed_safepoint()) {
3012 // Terminate this path
3013 } else if (n->Opcode() == Op_SafePoint) {
3014 if (_phase->get_loop(n) != this) {
3015 if (_required_safept == NULL) _required_safept = new Node_List();
3016 _required_safept->push(n); // save the one closest to the tail
3017 }
3018 // Terminate this path
3019 } else {
3020 uint start = n->is_Region() ? 1 : 0;
3021 uint end = n->is_Region() && !n->is_Loop() ? n->req() : start + 1;
3022 for (uint i = start; i < end; i++) {
3023 Node* in = n->in(i);
3024 assert(in->is_CFG(), "must be");
3025 if (!visited.test_set(in->_idx) && is_member(_phase->get_loop(in))) {
3026 stack.push(in);
3027 }
3028 }
3029 }
3030 }
3031 }
3032
3033 //------------------------------check_safepts----------------------------
3034 // Given dominators, try to find loops with calls that must always be
3035 // executed (call dominates loop tail). These loops do not need non-call
3036 // safepoints (ncsfpt).
3037 //
3038 // A complication is that a safepoint in a inner loop may be needed
3039 // by an outer loop. In the following, the inner loop sees it has a
3040 // call (block 3) on every path from the head (block 2) to the
3041 // backedge (arc 3->2). So it deletes the ncsfpt (non-call safepoint)
3042 // in block 2, _but_ this leaves the outer loop without a safepoint.
3043 //
3044 // entry 0
3045 // |
3046 // v
3047 // outer 1,2 +->1
3048 // | |
3049 // | v
3050 // | 2<---+ ncsfpt in 2
3051 // |_/|\ |
3052 // | v |
3053 // inner 2,3 / 3 | call in 3
3054 // / | |
3055 // v +--+
3056 // exit 4
3057 //
3058 //
3059 // This method creates a list (_required_safept) of ncsfpt nodes that must
3060 // be protected is created for each loop. When a ncsfpt maybe deleted, it
3061 // is first looked for in the lists for the outer loops of the current loop.
3062 //
3063 // The insights into the problem:
3064 // A) counted loops are okay
3065 // B) innermost loops are okay (only an inner loop can delete
3066 // a ncsfpt needed by an outer loop)
3067 // C) a loop is immune from an inner loop deleting a safepoint
3068 // if the loop has a call on the idom-path
3069 // D) a loop is also immune if it has a ncsfpt (non-call safepoint) on the
3070 // idom-path that is not in a nested loop
3071 // E) otherwise, an ncsfpt on the idom-path that is nested in an inner
3072 // loop needs to be prevented from deletion by an inner loop
3073 //
3074 // There are two analyses:
3075 // 1) The first, and cheaper one, scans the loop body from
3076 // tail to head following the idom (immediate dominator)
3077 // chain, looking for the cases (C,D,E) above.
3078 // Since inner loops are scanned before outer loops, there is summary
3079 // information about inner loops. Inner loops can be skipped over
3080 // when the tail of an inner loop is encountered.
3081 //
3082 // 2) The second, invoked if the first fails to find a call or ncsfpt on
3083 // the idom path (which is rare), scans all predecessor control paths
3084 // from the tail to the head, terminating a path when a call or sfpt
3085 // is encountered, to find the ncsfpt's that are closest to the tail.
3086 //
check_safepts(VectorSet & visited,Node_List & stack)3087 void IdealLoopTree::check_safepts(VectorSet &visited, Node_List &stack) {
3088 // Bottom up traversal
3089 IdealLoopTree* ch = _child;
3090 if (_child) _child->check_safepts(visited, stack);
3091 if (_next) _next ->check_safepts(visited, stack);
3092
3093 if (!_head->is_CountedLoop() && !_has_sfpt && _parent != NULL && !_irreducible) {
3094 bool has_call = false; // call on dom-path
3095 bool has_local_ncsfpt = false; // ncsfpt on dom-path at this loop depth
3096 Node* nonlocal_ncsfpt = NULL; // ncsfpt on dom-path at a deeper depth
3097 // Scan the dom-path nodes from tail to head
3098 for (Node* n = tail(); n != _head; n = _phase->idom(n)) {
3099 if (n->is_Call() && n->as_Call()->guaranteed_safepoint()) {
3100 has_call = true;
3101 _has_sfpt = 1; // Then no need for a safept!
3102 break;
3103 } else if (n->Opcode() == Op_SafePoint) {
3104 if (_phase->get_loop(n) == this) {
3105 has_local_ncsfpt = true;
3106 break;
3107 }
3108 if (nonlocal_ncsfpt == NULL) {
3109 nonlocal_ncsfpt = n; // save the one closest to the tail
3110 }
3111 } else {
3112 IdealLoopTree* nlpt = _phase->get_loop(n);
3113 if (this != nlpt) {
3114 // If at an inner loop tail, see if the inner loop has already
3115 // recorded seeing a call on the dom-path (and stop.) If not,
3116 // jump to the head of the inner loop.
3117 assert(is_member(nlpt), "nested loop");
3118 Node* tail = nlpt->_tail;
3119 if (tail->in(0)->is_If()) tail = tail->in(0);
3120 if (n == tail) {
3121 // If inner loop has call on dom-path, so does outer loop
3122 if (nlpt->_has_sfpt) {
3123 has_call = true;
3124 _has_sfpt = 1;
3125 break;
3126 }
3127 // Skip to head of inner loop
3128 assert(_phase->is_dominator(_head, nlpt->_head), "inner head dominated by outer head");
3129 n = nlpt->_head;
3130 }
3131 }
3132 }
3133 }
3134 // Record safept's that this loop needs preserved when an
3135 // inner loop attempts to delete it's safepoints.
3136 if (_child != NULL && !has_call && !has_local_ncsfpt) {
3137 if (nonlocal_ncsfpt != NULL) {
3138 if (_required_safept == NULL) _required_safept = new Node_List();
3139 _required_safept->push(nonlocal_ncsfpt);
3140 } else {
3141 // Failed to find a suitable safept on the dom-path. Now use
3142 // an all paths walk from tail to head, looking for safepoints to preserve.
3143 allpaths_check_safepts(visited, stack);
3144 }
3145 }
3146 }
3147 }
3148
3149 //---------------------------is_deleteable_safept----------------------------
3150 // Is safept not required by an outer loop?
is_deleteable_safept(Node * sfpt)3151 bool PhaseIdealLoop::is_deleteable_safept(Node* sfpt) {
3152 assert(sfpt->Opcode() == Op_SafePoint, "");
3153 IdealLoopTree* lp = get_loop(sfpt)->_parent;
3154 while (lp != NULL) {
3155 Node_List* sfpts = lp->_required_safept;
3156 if (sfpts != NULL) {
3157 for (uint i = 0; i < sfpts->size(); i++) {
3158 if (sfpt == sfpts->at(i))
3159 return false;
3160 }
3161 }
3162 lp = lp->_parent;
3163 }
3164 return true;
3165 }
3166
3167 //---------------------------replace_parallel_iv-------------------------------
3168 // Replace parallel induction variable (parallel to trip counter)
replace_parallel_iv(IdealLoopTree * loop)3169 void PhaseIdealLoop::replace_parallel_iv(IdealLoopTree *loop) {
3170 assert(loop->_head->is_CountedLoop(), "");
3171 CountedLoopNode *cl = loop->_head->as_CountedLoop();
3172 if (!cl->is_valid_counted_loop(T_INT))
3173 return; // skip malformed counted loop
3174 Node *incr = cl->incr();
3175 if (incr == NULL)
3176 return; // Dead loop?
3177 Node *init = cl->init_trip();
3178 Node *phi = cl->phi();
3179 int stride_con = cl->stride_con();
3180
3181 // Visit all children, looking for Phis
3182 for (DUIterator i = cl->outs(); cl->has_out(i); i++) {
3183 Node *out = cl->out(i);
3184 // Look for other phis (secondary IVs). Skip dead ones
3185 if (!out->is_Phi() || out == phi || !has_node(out))
3186 continue;
3187 PhiNode* phi2 = out->as_Phi();
3188 Node *incr2 = phi2->in( LoopNode::LoopBackControl );
3189 // Look for induction variables of the form: X += constant
3190 if (phi2->region() != loop->_head ||
3191 incr2->req() != 3 ||
3192 incr2->in(1) != phi2 ||
3193 incr2 == incr ||
3194 incr2->Opcode() != Op_AddI ||
3195 !incr2->in(2)->is_Con())
3196 continue;
3197
3198 // Check for parallel induction variable (parallel to trip counter)
3199 // via an affine function. In particular, count-down loops with
3200 // count-up array indices are common. We only RCE references off
3201 // the trip-counter, so we need to convert all these to trip-counter
3202 // expressions.
3203 Node *init2 = phi2->in( LoopNode::EntryControl );
3204 int stride_con2 = incr2->in(2)->get_int();
3205
3206 // The ratio of the two strides cannot be represented as an int
3207 // if stride_con2 is min_int and stride_con is -1.
3208 if (stride_con2 == min_jint && stride_con == -1) {
3209 continue;
3210 }
3211
3212 // The general case here gets a little tricky. We want to find the
3213 // GCD of all possible parallel IV's and make a new IV using this
3214 // GCD for the loop. Then all possible IVs are simple multiples of
3215 // the GCD. In practice, this will cover very few extra loops.
3216 // Instead we require 'stride_con2' to be a multiple of 'stride_con',
3217 // where +/-1 is the common case, but other integer multiples are
3218 // also easy to handle.
3219 int ratio_con = stride_con2/stride_con;
3220
3221 if ((ratio_con * stride_con) == stride_con2) { // Check for exact
3222 #ifndef PRODUCT
3223 if (TraceLoopOpts) {
3224 tty->print("Parallel IV: %d ", phi2->_idx);
3225 loop->dump_head();
3226 }
3227 #endif
3228 // Convert to using the trip counter. The parallel induction
3229 // variable differs from the trip counter by a loop-invariant
3230 // amount, the difference between their respective initial values.
3231 // It is scaled by the 'ratio_con'.
3232 Node* ratio = _igvn.intcon(ratio_con);
3233 set_ctrl(ratio, C->root());
3234 Node* ratio_init = new MulINode(init, ratio);
3235 _igvn.register_new_node_with_optimizer(ratio_init, init);
3236 set_early_ctrl(ratio_init, false);
3237 Node* diff = new SubINode(init2, ratio_init);
3238 _igvn.register_new_node_with_optimizer(diff, init2);
3239 set_early_ctrl(diff, false);
3240 Node* ratio_idx = new MulINode(phi, ratio);
3241 _igvn.register_new_node_with_optimizer(ratio_idx, phi);
3242 set_ctrl(ratio_idx, cl);
3243 Node* add = new AddINode(ratio_idx, diff);
3244 _igvn.register_new_node_with_optimizer(add);
3245 set_ctrl(add, cl);
3246 _igvn.replace_node( phi2, add );
3247 // Sometimes an induction variable is unused
3248 if (add->outcnt() == 0) {
3249 _igvn.remove_dead_node(add);
3250 }
3251 --i; // deleted this phi; rescan starting with next position
3252 continue;
3253 }
3254 }
3255 }
3256
remove_safepoints(PhaseIdealLoop * phase,bool keep_one)3257 void IdealLoopTree::remove_safepoints(PhaseIdealLoop* phase, bool keep_one) {
3258 Node* keep = NULL;
3259 if (keep_one) {
3260 // Look for a safepoint on the idom-path.
3261 for (Node* i = tail(); i != _head; i = phase->idom(i)) {
3262 if (i->Opcode() == Op_SafePoint && phase->get_loop(i) == this) {
3263 keep = i;
3264 break; // Found one
3265 }
3266 }
3267 }
3268
3269 // Don't remove any safepoints if it is requested to keep a single safepoint and
3270 // no safepoint was found on idom-path. It is not safe to remove any safepoint
3271 // in this case since there's no safepoint dominating all paths in the loop body.
3272 bool prune = !keep_one || keep != NULL;
3273
3274 // Delete other safepoints in this loop.
3275 Node_List* sfpts = _safepts;
3276 if (prune && sfpts != NULL) {
3277 assert(keep == NULL || keep->Opcode() == Op_SafePoint, "not safepoint");
3278 for (uint i = 0; i < sfpts->size(); i++) {
3279 Node* n = sfpts->at(i);
3280 assert(phase->get_loop(n) == this, "");
3281 if (n != keep && phase->is_deleteable_safept(n)) {
3282 phase->lazy_replace(n, n->in(TypeFunc::Control));
3283 }
3284 }
3285 }
3286 }
3287
3288 //------------------------------counted_loop-----------------------------------
3289 // Convert to counted loops where possible
counted_loop(PhaseIdealLoop * phase)3290 void IdealLoopTree::counted_loop( PhaseIdealLoop *phase ) {
3291
3292 // For grins, set the inner-loop flag here
3293 if (!_child) {
3294 if (_head->is_Loop()) _head->as_Loop()->set_inner_loop();
3295 }
3296
3297 IdealLoopTree* loop = this;
3298 if (_head->is_CountedLoop() ||
3299 phase->is_counted_loop(_head, loop, T_INT)) {
3300
3301 if (LoopStripMiningIter == 0 || (LoopStripMiningIter > 1 && _child == NULL)) {
3302 // Indicate we do not need a safepoint here
3303 _has_sfpt = 1;
3304 }
3305
3306 // Remove safepoints
3307 bool keep_one_sfpt = !(_has_call || _has_sfpt);
3308 remove_safepoints(phase, keep_one_sfpt);
3309
3310 // Look for induction variables
3311 phase->replace_parallel_iv(this);
3312 } else if (_head->is_LongCountedLoop() ||
3313 phase->is_counted_loop(_head, loop, T_LONG)) {
3314 remove_safepoints(phase, true);
3315 } else {
3316 assert(!_head->is_Loop() || !_head->as_Loop()->is_transformed_long_loop(), "transformation to counted loop should not fail");
3317 if (_parent != NULL && !_irreducible) {
3318 // Not a counted loop. Keep one safepoint.
3319 bool keep_one_sfpt = true;
3320 remove_safepoints(phase, keep_one_sfpt);
3321 }
3322 }
3323
3324 // Recursively
3325 assert(loop->_child != this || (loop->_head->as_Loop()->is_OuterStripMinedLoop() && _head->as_CountedLoop()->is_strip_mined()), "what kind of loop was added?");
3326 assert(loop->_child != this || (loop->_child->_child == NULL && loop->_child->_next == NULL), "would miss some loops");
3327 if (loop->_child && loop->_child != this) loop->_child->counted_loop(phase);
3328 if (loop->_next) loop->_next ->counted_loop(phase);
3329 }
3330
3331
3332 // The Estimated Loop Clone Size:
3333 // CloneFactor * (~112% * BodySize + BC) + CC + FanOutTerm,
3334 // where BC and CC are totally ad-hoc/magic "body" and "clone" constants,
3335 // respectively, used to ensure that the node usage estimates made are on the
3336 // safe side, for the most part. The FanOutTerm is an attempt to estimate the
3337 // possible additional/excessive nodes generated due to data and control flow
3338 // merging, for edges reaching outside the loop.
est_loop_clone_sz(uint factor) const3339 uint IdealLoopTree::est_loop_clone_sz(uint factor) const {
3340
3341 precond(0 < factor && factor < 16);
3342
3343 uint const bc = 13;
3344 uint const cc = 17;
3345 uint const sz = _body.size() + (_body.size() + 7) / 2;
3346 uint estimate = factor * (sz + bc) + cc;
3347
3348 assert((estimate - cc) / factor == sz + bc, "overflow");
3349
3350 return estimate + est_loop_flow_merge_sz();
3351 }
3352
3353 // The Estimated Loop (full-) Unroll Size:
3354 // UnrollFactor * (~106% * BodySize) + CC + FanOutTerm,
3355 // where CC is a (totally) ad-hoc/magic "clone" constant, used to ensure that
3356 // node usage estimates made are on the safe side, for the most part. This is
3357 // a "light" version of the loop clone size calculation (above), based on the
3358 // assumption that most of the loop-construct overhead will be unraveled when
3359 // (fully) unrolled. Defined for unroll factors larger or equal to one (>=1),
3360 // including an overflow check and returning UINT_MAX in case of an overflow.
est_loop_unroll_sz(uint factor) const3361 uint IdealLoopTree::est_loop_unroll_sz(uint factor) const {
3362
3363 precond(factor > 0);
3364
3365 // Take into account that after unroll conjoined heads and tails will fold.
3366 uint const b0 = _body.size() - EMPTY_LOOP_SIZE;
3367 uint const cc = 7;
3368 uint const sz = b0 + (b0 + 15) / 16;
3369 uint estimate = factor * sz + cc;
3370
3371 if ((estimate - cc) / factor != sz) {
3372 return UINT_MAX;
3373 }
3374
3375 return estimate + est_loop_flow_merge_sz();
3376 }
3377
3378 // Estimate the growth effect (in nodes) of merging control and data flow when
3379 // cloning a loop body, based on the amount of control and data flow reaching
3380 // outside of the (current) loop body.
est_loop_flow_merge_sz() const3381 uint IdealLoopTree::est_loop_flow_merge_sz() const {
3382
3383 uint ctrl_edge_out_cnt = 0;
3384 uint data_edge_out_cnt = 0;
3385
3386 for (uint i = 0; i < _body.size(); i++) {
3387 Node* node = _body.at(i);
3388 uint outcnt = node->outcnt();
3389
3390 for (uint k = 0; k < outcnt; k++) {
3391 Node* out = node->raw_out(k);
3392 if (out == NULL) continue;
3393 if (out->is_CFG()) {
3394 if (!is_member(_phase->get_loop(out))) {
3395 ctrl_edge_out_cnt++;
3396 }
3397 } else if (_phase->has_ctrl(out)) {
3398 Node* ctrl = _phase->get_ctrl(out);
3399 assert(ctrl != NULL, "must be");
3400 assert(ctrl->is_CFG(), "must be");
3401 if (!is_member(_phase->get_loop(ctrl))) {
3402 data_edge_out_cnt++;
3403 }
3404 }
3405 }
3406 }
3407 // Use data and control count (x2.0) in estimate iff both are > 0. This is
3408 // a rather pessimistic estimate for the most part, in particular for some
3409 // complex loops, but still not enough to capture all loops.
3410 if (ctrl_edge_out_cnt > 0 && data_edge_out_cnt > 0) {
3411 return 2 * (ctrl_edge_out_cnt + data_edge_out_cnt);
3412 }
3413 return 0;
3414 }
3415
3416 #ifndef PRODUCT
3417 //------------------------------dump_head--------------------------------------
3418 // Dump 1 liner for loop header info
dump_head() const3419 void IdealLoopTree::dump_head() const {
3420 tty->sp(2 * _nest);
3421 tty->print("Loop: N%d/N%d ", _head->_idx, _tail->_idx);
3422 if (_irreducible) tty->print(" IRREDUCIBLE");
3423 Node* entry = _head->is_Loop() ? _head->as_Loop()->skip_strip_mined(-1)->in(LoopNode::EntryControl) : _head->in(LoopNode::EntryControl);
3424 Node* predicate = PhaseIdealLoop::find_predicate_insertion_point(entry, Deoptimization::Reason_loop_limit_check);
3425 if (predicate != NULL ) {
3426 tty->print(" limit_check");
3427 entry = PhaseIdealLoop::skip_loop_predicates(entry);
3428 }
3429 if (UseProfiledLoopPredicate) {
3430 predicate = PhaseIdealLoop::find_predicate_insertion_point(entry, Deoptimization::Reason_profile_predicate);
3431 if (predicate != NULL) {
3432 tty->print(" profile_predicated");
3433 entry = PhaseIdealLoop::skip_loop_predicates(entry);
3434 }
3435 }
3436 if (UseLoopPredicate) {
3437 predicate = PhaseIdealLoop::find_predicate_insertion_point(entry, Deoptimization::Reason_predicate);
3438 if (predicate != NULL) {
3439 tty->print(" predicated");
3440 }
3441 }
3442 if (_head->is_CountedLoop()) {
3443 CountedLoopNode *cl = _head->as_CountedLoop();
3444 tty->print(" counted");
3445
3446 Node* init_n = cl->init_trip();
3447 if (init_n != NULL && init_n->is_Con())
3448 tty->print(" [%d,", cl->init_trip()->get_int());
3449 else
3450 tty->print(" [int,");
3451 Node* limit_n = cl->limit();
3452 if (limit_n != NULL && limit_n->is_Con())
3453 tty->print("%d),", cl->limit()->get_int());
3454 else
3455 tty->print("int),");
3456 int stride_con = cl->stride_con();
3457 if (stride_con > 0) tty->print("+");
3458 tty->print("%d", stride_con);
3459
3460 tty->print(" (%0.f iters) ", cl->profile_trip_cnt());
3461
3462 if (cl->is_pre_loop ()) tty->print(" pre" );
3463 if (cl->is_main_loop()) tty->print(" main");
3464 if (cl->is_post_loop()) tty->print(" post");
3465 if (cl->is_vectorized_loop()) tty->print(" vector");
3466 if (cl->range_checks_present()) tty->print(" rc ");
3467 if (cl->is_multiversioned()) tty->print(" multi ");
3468 }
3469 if (_has_call) tty->print(" has_call");
3470 if (_has_sfpt) tty->print(" has_sfpt");
3471 if (_rce_candidate) tty->print(" rce");
3472 if (_safepts != NULL && _safepts->size() > 0) {
3473 tty->print(" sfpts={"); _safepts->dump_simple(); tty->print(" }");
3474 }
3475 if (_required_safept != NULL && _required_safept->size() > 0) {
3476 tty->print(" req={"); _required_safept->dump_simple(); tty->print(" }");
3477 }
3478 if (Verbose) {
3479 tty->print(" body={"); _body.dump_simple(); tty->print(" }");
3480 }
3481 if (_head->is_Loop() && _head->as_Loop()->is_strip_mined()) {
3482 tty->print(" strip_mined");
3483 }
3484 tty->cr();
3485 }
3486
3487 //------------------------------dump-------------------------------------------
3488 // Dump loops by loop tree
dump() const3489 void IdealLoopTree::dump() const {
3490 dump_head();
3491 if (_child) _child->dump();
3492 if (_next) _next ->dump();
3493 }
3494
3495 #endif
3496
log_loop_tree_helper(IdealLoopTree * root,IdealLoopTree * loop,CompileLog * log)3497 static void log_loop_tree_helper(IdealLoopTree* root, IdealLoopTree* loop, CompileLog* log) {
3498 if (loop == root) {
3499 if (loop->_child != NULL) {
3500 log->begin_head("loop_tree");
3501 log->end_head();
3502 log_loop_tree_helper(root, loop->_child, log);
3503 log->tail("loop_tree");
3504 assert(loop->_next == NULL, "what?");
3505 }
3506 } else if (loop != NULL) {
3507 Node* head = loop->_head;
3508 log->begin_head("loop");
3509 log->print(" idx='%d' ", head->_idx);
3510 if (loop->_irreducible) log->print("irreducible='1' ");
3511 if (head->is_Loop()) {
3512 if (head->as_Loop()->is_inner_loop()) log->print("inner_loop='1' ");
3513 if (head->as_Loop()->is_partial_peel_loop()) log->print("partial_peel_loop='1' ");
3514 } else if (head->is_CountedLoop()) {
3515 CountedLoopNode* cl = head->as_CountedLoop();
3516 if (cl->is_pre_loop()) log->print("pre_loop='%d' ", cl->main_idx());
3517 if (cl->is_main_loop()) log->print("main_loop='%d' ", cl->_idx);
3518 if (cl->is_post_loop()) log->print("post_loop='%d' ", cl->main_idx());
3519 }
3520 log->end_head();
3521 log_loop_tree_helper(root, loop->_child, log);
3522 log->tail("loop");
3523 log_loop_tree_helper(root, loop->_next, log);
3524 }
3525 }
3526
log_loop_tree()3527 void PhaseIdealLoop::log_loop_tree() {
3528 if (C->log() != NULL) {
3529 log_loop_tree_helper(_ltree_root, _ltree_root, C->log());
3530 }
3531 }
3532
3533 //---------------------collect_potentially_useful_predicates-----------------------
3534 // Helper function to collect potentially useful predicates to prevent them from
3535 // being eliminated by PhaseIdealLoop::eliminate_useless_predicates
collect_potentially_useful_predicates(IdealLoopTree * loop,Unique_Node_List & useful_predicates)3536 void PhaseIdealLoop::collect_potentially_useful_predicates(
3537 IdealLoopTree * loop, Unique_Node_List &useful_predicates) {
3538 if (loop->_child) { // child
3539 collect_potentially_useful_predicates(loop->_child, useful_predicates);
3540 }
3541
3542 // self (only loops that we can apply loop predication may use their predicates)
3543 if (loop->_head->is_Loop() &&
3544 !loop->_irreducible &&
3545 !loop->tail()->is_top()) {
3546 LoopNode* lpn = loop->_head->as_Loop();
3547 Node* entry = lpn->in(LoopNode::EntryControl);
3548 Node* predicate_proj = find_predicate(entry); // loop_limit_check first
3549 if (predicate_proj != NULL) { // right pattern that can be used by loop predication
3550 assert(entry->in(0)->in(1)->in(1)->Opcode() == Op_Opaque1, "must be");
3551 useful_predicates.push(entry->in(0)->in(1)->in(1)); // good one
3552 entry = skip_loop_predicates(entry);
3553 }
3554 if (UseProfiledLoopPredicate) {
3555 predicate_proj = find_predicate(entry); // Predicate
3556 if (predicate_proj != NULL) {
3557 useful_predicates.push(entry->in(0)->in(1)->in(1)); // good one
3558 entry = skip_loop_predicates(entry);
3559 }
3560 }
3561 predicate_proj = find_predicate(entry); // Predicate
3562 if (predicate_proj != NULL) {
3563 useful_predicates.push(entry->in(0)->in(1)->in(1)); // good one
3564 }
3565 }
3566
3567 if (loop->_next) { // sibling
3568 collect_potentially_useful_predicates(loop->_next, useful_predicates);
3569 }
3570 }
3571
3572 //------------------------eliminate_useless_predicates-----------------------------
3573 // Eliminate all inserted predicates if they could not be used by loop predication.
3574 // Note: it will also eliminates loop limits check predicate since it also uses
3575 // Opaque1 node (see Parse::add_predicate()).
eliminate_useless_predicates()3576 void PhaseIdealLoop::eliminate_useless_predicates() {
3577 if (C->predicate_count() == 0)
3578 return; // no predicate left
3579
3580 Unique_Node_List useful_predicates; // to store useful predicates
3581 if (C->has_loops()) {
3582 collect_potentially_useful_predicates(_ltree_root->_child, useful_predicates);
3583 }
3584
3585 for (int i = C->predicate_count(); i > 0; i--) {
3586 Node * n = C->predicate_opaque1_node(i-1);
3587 assert(n->Opcode() == Op_Opaque1, "must be");
3588 if (!useful_predicates.member(n)) { // not in the useful list
3589 _igvn.replace_node(n, n->in(1));
3590 }
3591 }
3592 }
3593
3594 //------------------------process_expensive_nodes-----------------------------
3595 // Expensive nodes have their control input set to prevent the GVN
3596 // from commoning them and as a result forcing the resulting node to
3597 // be in a more frequent path. Use CFG information here, to change the
3598 // control inputs so that some expensive nodes can be commoned while
3599 // not executed more frequently.
process_expensive_nodes()3600 bool PhaseIdealLoop::process_expensive_nodes() {
3601 assert(OptimizeExpensiveOps, "optimization off?");
3602
3603 // Sort nodes to bring similar nodes together
3604 C->sort_expensive_nodes();
3605
3606 bool progress = false;
3607
3608 for (int i = 0; i < C->expensive_count(); ) {
3609 Node* n = C->expensive_node(i);
3610 int start = i;
3611 // Find nodes similar to n
3612 i++;
3613 for (; i < C->expensive_count() && Compile::cmp_expensive_nodes(n, C->expensive_node(i)) == 0; i++);
3614 int end = i;
3615 // And compare them two by two
3616 for (int j = start; j < end; j++) {
3617 Node* n1 = C->expensive_node(j);
3618 if (is_node_unreachable(n1)) {
3619 continue;
3620 }
3621 for (int k = j+1; k < end; k++) {
3622 Node* n2 = C->expensive_node(k);
3623 if (is_node_unreachable(n2)) {
3624 continue;
3625 }
3626
3627 assert(n1 != n2, "should be pair of nodes");
3628
3629 Node* c1 = n1->in(0);
3630 Node* c2 = n2->in(0);
3631
3632 Node* parent_c1 = c1;
3633 Node* parent_c2 = c2;
3634
3635 // The call to get_early_ctrl_for_expensive() moves the
3636 // expensive nodes up but stops at loops that are in a if
3637 // branch. See whether we can exit the loop and move above the
3638 // If.
3639 if (c1->is_Loop()) {
3640 parent_c1 = c1->in(1);
3641 }
3642 if (c2->is_Loop()) {
3643 parent_c2 = c2->in(1);
3644 }
3645
3646 if (parent_c1 == parent_c2) {
3647 _igvn._worklist.push(n1);
3648 _igvn._worklist.push(n2);
3649 continue;
3650 }
3651
3652 // Look for identical expensive node up the dominator chain.
3653 if (is_dominator(c1, c2)) {
3654 c2 = c1;
3655 } else if (is_dominator(c2, c1)) {
3656 c1 = c2;
3657 } else if (parent_c1->is_Proj() && parent_c1->in(0)->is_If() &&
3658 parent_c2->is_Proj() && parent_c1->in(0) == parent_c2->in(0)) {
3659 // Both branches have the same expensive node so move it up
3660 // before the if.
3661 c1 = c2 = idom(parent_c1->in(0));
3662 }
3663 // Do the actual moves
3664 if (n1->in(0) != c1) {
3665 _igvn.hash_delete(n1);
3666 n1->set_req(0, c1);
3667 _igvn.hash_insert(n1);
3668 _igvn._worklist.push(n1);
3669 progress = true;
3670 }
3671 if (n2->in(0) != c2) {
3672 _igvn.hash_delete(n2);
3673 n2->set_req(0, c2);
3674 _igvn.hash_insert(n2);
3675 _igvn._worklist.push(n2);
3676 progress = true;
3677 }
3678 }
3679 }
3680 }
3681
3682 return progress;
3683 }
3684
3685 #ifdef ASSERT
only_has_infinite_loops()3686 bool PhaseIdealLoop::only_has_infinite_loops() {
3687 for (IdealLoopTree* l = _ltree_root->_child; l != NULL; l = l->_next) {
3688 uint i = 1;
3689 for (; i < C->root()->req(); i++) {
3690 Node* in = C->root()->in(i);
3691 if (in != NULL &&
3692 in->Opcode() == Op_Halt &&
3693 in->in(0)->is_Proj() &&
3694 in->in(0)->in(0)->Opcode() == Op_NeverBranch &&
3695 in->in(0)->in(0)->in(0) == l->_head) {
3696 break;
3697 }
3698 }
3699 if (i == C->root()->req()) {
3700 return false;
3701 }
3702 }
3703
3704 return true;
3705 }
3706 #endif
3707
3708
3709 //=============================================================================
3710 //----------------------------build_and_optimize-------------------------------
3711 // Create a PhaseLoop. Build the ideal Loop tree. Map each Ideal Node to
3712 // its corresponding LoopNode. If 'optimize' is true, do some loop cleanups.
build_and_optimize(LoopOptsMode mode)3713 void PhaseIdealLoop::build_and_optimize(LoopOptsMode mode) {
3714 assert(!C->post_loop_opts_phase(), "no loop opts allowed");
3715
3716 bool do_split_ifs = (mode == LoopOptsDefault);
3717 bool skip_loop_opts = (mode == LoopOptsNone);
3718
3719 int old_progress = C->major_progress();
3720 uint orig_worklist_size = _igvn._worklist.size();
3721
3722 // Reset major-progress flag for the driver's heuristics
3723 C->clear_major_progress();
3724
3725 #ifndef PRODUCT
3726 // Capture for later assert
3727 uint unique = C->unique();
3728 _loop_invokes++;
3729 _loop_work += unique;
3730 #endif
3731
3732 // True if the method has at least 1 irreducible loop
3733 _has_irreducible_loops = false;
3734
3735 _created_loop_node = false;
3736
3737 VectorSet visited;
3738 // Pre-grow the mapping from Nodes to IdealLoopTrees.
3739 _nodes.map(C->unique(), NULL);
3740 memset(_nodes.adr(), 0, wordSize * C->unique());
3741
3742 // Pre-build the top-level outermost loop tree entry
3743 _ltree_root = new IdealLoopTree( this, C->root(), C->root() );
3744 // Do not need a safepoint at the top level
3745 _ltree_root->_has_sfpt = 1;
3746
3747 // Initialize Dominators.
3748 // Checked in clone_loop_predicate() during beautify_loops().
3749 _idom_size = 0;
3750 _idom = NULL;
3751 _dom_depth = NULL;
3752 _dom_stk = NULL;
3753
3754 // Empty pre-order array
3755 allocate_preorders();
3756
3757 // Build a loop tree on the fly. Build a mapping from CFG nodes to
3758 // IdealLoopTree entries. Data nodes are NOT walked.
3759 build_loop_tree();
3760 // Check for bailout, and return
3761 if (C->failing()) {
3762 return;
3763 }
3764
3765 // Verify that the has_loops() flag set at parse time is consistent
3766 // with the just built loop tree. With infinite loops, it could be
3767 // that one pass of loop opts only finds infinite loops, clears the
3768 // has_loops() flag but adds NeverBranch nodes so the next loop opts
3769 // verification pass finds a non empty loop tree. When the back edge
3770 // is an exception edge, parsing doesn't set has_loops().
3771 assert(_ltree_root->_child == NULL || C->has_loops() || only_has_infinite_loops() || C->has_exception_backedge(), "parsing found no loops but there are some");
3772 // No loops after all
3773 if( !_ltree_root->_child && !_verify_only ) C->set_has_loops(false);
3774
3775 // There should always be an outer loop containing the Root and Return nodes.
3776 // If not, we have a degenerate empty program. Bail out in this case.
3777 if (!has_node(C->root())) {
3778 if (!_verify_only) {
3779 C->clear_major_progress();
3780 C->record_method_not_compilable("empty program detected during loop optimization");
3781 }
3782 return;
3783 }
3784
3785 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
3786 // Nothing to do, so get out
3787 bool stop_early = !C->has_loops() && !skip_loop_opts && !do_split_ifs && !_verify_me && !_verify_only &&
3788 !bs->is_gc_specific_loop_opts_pass(mode);
3789 bool do_expensive_nodes = C->should_optimize_expensive_nodes(_igvn);
3790 bool strip_mined_loops_expanded = bs->strip_mined_loops_expanded(mode);
3791 if (stop_early && !do_expensive_nodes) {
3792 return;
3793 }
3794
3795 // Set loop nesting depth
3796 _ltree_root->set_nest( 0 );
3797
3798 // Split shared headers and insert loop landing pads.
3799 // Do not bother doing this on the Root loop of course.
3800 if( !_verify_me && !_verify_only && _ltree_root->_child ) {
3801 C->print_method(PHASE_BEFORE_BEAUTIFY_LOOPS, 3);
3802 if( _ltree_root->_child->beautify_loops( this ) ) {
3803 // Re-build loop tree!
3804 _ltree_root->_child = NULL;
3805 _nodes.clear();
3806 reallocate_preorders();
3807 build_loop_tree();
3808 // Check for bailout, and return
3809 if (C->failing()) {
3810 return;
3811 }
3812 // Reset loop nesting depth
3813 _ltree_root->set_nest( 0 );
3814
3815 C->print_method(PHASE_AFTER_BEAUTIFY_LOOPS, 3);
3816 }
3817 }
3818
3819 // Build Dominators for elision of NULL checks & loop finding.
3820 // Since nodes do not have a slot for immediate dominator, make
3821 // a persistent side array for that info indexed on node->_idx.
3822 _idom_size = C->unique();
3823 _idom = NEW_RESOURCE_ARRAY( Node*, _idom_size );
3824 _dom_depth = NEW_RESOURCE_ARRAY( uint, _idom_size );
3825 _dom_stk = NULL; // Allocated on demand in recompute_dom_depth
3826 memset( _dom_depth, 0, _idom_size * sizeof(uint) );
3827
3828 Dominators();
3829
3830 if (!_verify_only) {
3831 // As a side effect, Dominators removed any unreachable CFG paths
3832 // into RegionNodes. It doesn't do this test against Root, so
3833 // we do it here.
3834 for( uint i = 1; i < C->root()->req(); i++ ) {
3835 if( !_nodes[C->root()->in(i)->_idx] ) { // Dead path into Root?
3836 _igvn.delete_input_of(C->root(), i);
3837 i--; // Rerun same iteration on compressed edges
3838 }
3839 }
3840
3841 // Given dominators, try to find inner loops with calls that must
3842 // always be executed (call dominates loop tail). These loops do
3843 // not need a separate safepoint.
3844 Node_List cisstack;
3845 _ltree_root->check_safepts(visited, cisstack);
3846 }
3847
3848 // Walk the DATA nodes and place into loops. Find earliest control
3849 // node. For CFG nodes, the _nodes array starts out and remains
3850 // holding the associated IdealLoopTree pointer. For DATA nodes, the
3851 // _nodes array holds the earliest legal controlling CFG node.
3852
3853 // Allocate stack with enough space to avoid frequent realloc
3854 int stack_size = (C->live_nodes() >> 1) + 16; // (live_nodes>>1)+16 from Java2D stats
3855 Node_Stack nstack(stack_size);
3856
3857 visited.clear();
3858 Node_List worklist;
3859 // Don't need C->root() on worklist since
3860 // it will be processed among C->top() inputs
3861 worklist.push(C->top());
3862 visited.set(C->top()->_idx); // Set C->top() as visited now
3863 build_loop_early( visited, worklist, nstack );
3864
3865 // Given early legal placement, try finding counted loops. This placement
3866 // is good enough to discover most loop invariants.
3867 if (!_verify_me && !_verify_only && !strip_mined_loops_expanded) {
3868 _ltree_root->counted_loop( this );
3869 }
3870
3871 // Find latest loop placement. Find ideal loop placement.
3872 visited.clear();
3873 init_dom_lca_tags();
3874 // Need C->root() on worklist when processing outs
3875 worklist.push(C->root());
3876 NOT_PRODUCT( C->verify_graph_edges(); )
3877 worklist.push(C->top());
3878 build_loop_late( visited, worklist, nstack );
3879
3880 if (_verify_only) {
3881 C->restore_major_progress(old_progress);
3882 assert(C->unique() == unique, "verification mode made Nodes? ? ?");
3883 assert(_igvn._worklist.size() == orig_worklist_size, "shouldn't push anything");
3884 return;
3885 }
3886
3887 // clear out the dead code after build_loop_late
3888 while (_deadlist.size()) {
3889 _igvn.remove_globally_dead_node(_deadlist.pop());
3890 }
3891
3892 if (stop_early) {
3893 assert(do_expensive_nodes, "why are we here?");
3894 if (process_expensive_nodes()) {
3895 // If we made some progress when processing expensive nodes then
3896 // the IGVN may modify the graph in a way that will allow us to
3897 // make some more progress: we need to try processing expensive
3898 // nodes again.
3899 C->set_major_progress();
3900 }
3901 return;
3902 }
3903
3904 // Some parser-inserted loop predicates could never be used by loop
3905 // predication or they were moved away from loop during some optimizations.
3906 // For example, peeling. Eliminate them before next loop optimizations.
3907 eliminate_useless_predicates();
3908
3909 #ifndef PRODUCT
3910 C->verify_graph_edges();
3911 if (_verify_me) { // Nested verify pass?
3912 // Check to see if the verify mode is broken
3913 assert(C->unique() == unique, "non-optimize mode made Nodes? ? ?");
3914 return;
3915 }
3916 if (VerifyLoopOptimizations) verify();
3917 if (TraceLoopOpts && C->has_loops()) {
3918 _ltree_root->dump();
3919 }
3920 #endif
3921
3922 if (skip_loop_opts) {
3923 C->restore_major_progress(old_progress);
3924 return;
3925 }
3926
3927 if (mode == LoopOptsMaxUnroll) {
3928 for (LoopTreeIterator iter(_ltree_root); !iter.done(); iter.next()) {
3929 IdealLoopTree* lpt = iter.current();
3930 if (lpt->is_innermost() && lpt->_allow_optimizations && !lpt->_has_call && lpt->is_counted()) {
3931 lpt->compute_trip_count(this);
3932 if (!lpt->do_one_iteration_loop(this) &&
3933 !lpt->do_remove_empty_loop(this)) {
3934 AutoNodeBudget node_budget(this);
3935 if (lpt->_head->as_CountedLoop()->is_normal_loop() &&
3936 lpt->policy_maximally_unroll(this)) {
3937 memset( worklist.adr(), 0, worklist.Size()*sizeof(Node*) );
3938 do_maximally_unroll(lpt, worklist);
3939 }
3940 }
3941 }
3942 }
3943
3944 C->restore_major_progress(old_progress);
3945 return;
3946 }
3947
3948 if (bs->optimize_loops(this, mode, visited, nstack, worklist)) {
3949 return;
3950 }
3951
3952 if (ReassociateInvariants && !C->major_progress()) {
3953 // Reassociate invariants and prep for split_thru_phi
3954 for (LoopTreeIterator iter(_ltree_root); !iter.done(); iter.next()) {
3955 IdealLoopTree* lpt = iter.current();
3956 bool is_counted = lpt->is_counted();
3957 if (!is_counted || !lpt->is_innermost()) continue;
3958
3959 // check for vectorized loops, any reassociation of invariants was already done
3960 if (is_counted && lpt->_head->as_CountedLoop()->is_unroll_only()) {
3961 continue;
3962 } else {
3963 AutoNodeBudget node_budget(this);
3964 lpt->reassociate_invariants(this);
3965 }
3966 // Because RCE opportunities can be masked by split_thru_phi,
3967 // look for RCE candidates and inhibit split_thru_phi
3968 // on just their loop-phi's for this pass of loop opts
3969 if (SplitIfBlocks && do_split_ifs) {
3970 AutoNodeBudget node_budget(this, AutoNodeBudget::NO_BUDGET_CHECK);
3971 if (lpt->policy_range_check(this)) {
3972 lpt->_rce_candidate = 1; // = true
3973 }
3974 }
3975 }
3976 }
3977
3978 // Check for aggressive application of split-if and other transforms
3979 // that require basic-block info (like cloning through Phi's)
3980 if (!C->major_progress() && SplitIfBlocks && do_split_ifs) {
3981 visited.clear();
3982 split_if_with_blocks( visited, nstack);
3983 NOT_PRODUCT( if( VerifyLoopOptimizations ) verify(); );
3984 }
3985
3986 if (!C->major_progress() && do_expensive_nodes && process_expensive_nodes()) {
3987 C->set_major_progress();
3988 }
3989
3990 // Perform loop predication before iteration splitting
3991 if (C->has_loops() && !C->major_progress() && (C->predicate_count() > 0)) {
3992 _ltree_root->_child->loop_predication(this);
3993 }
3994
3995 if (OptimizeFill && UseLoopPredicate && C->has_loops() && !C->major_progress()) {
3996 if (do_intrinsify_fill()) {
3997 C->set_major_progress();
3998 }
3999 }
4000
4001 // Perform iteration-splitting on inner loops. Split iterations to avoid
4002 // range checks or one-shot null checks.
4003
4004 // If split-if's didn't hack the graph too bad (no CFG changes)
4005 // then do loop opts.
4006 if (C->has_loops() && !C->major_progress()) {
4007 memset( worklist.adr(), 0, worklist.Size()*sizeof(Node*) );
4008 _ltree_root->_child->iteration_split( this, worklist );
4009 // No verify after peeling! GCM has hoisted code out of the loop.
4010 // After peeling, the hoisted code could sink inside the peeled area.
4011 // The peeling code does not try to recompute the best location for
4012 // all the code before the peeled area, so the verify pass will always
4013 // complain about it.
4014 }
4015 // Do verify graph edges in any case
4016 NOT_PRODUCT( C->verify_graph_edges(); );
4017
4018 if (C->has_loops() && !C->major_progress()) {
4019 for (LoopTreeIterator iter(_ltree_root); !iter.done(); iter.next()) {
4020 IdealLoopTree *lpt = iter.current();
4021 transform_long_counted_loop(lpt, worklist);
4022 }
4023 }
4024
4025 if (!do_split_ifs) {
4026 // We saw major progress in Split-If to get here. We forced a
4027 // pass with unrolling and not split-if, however more split-if's
4028 // might make progress. If the unrolling didn't make progress
4029 // then the major-progress flag got cleared and we won't try
4030 // another round of Split-If. In particular the ever-common
4031 // instance-of/check-cast pattern requires at least 2 rounds of
4032 // Split-If to clear out.
4033 C->set_major_progress();
4034 }
4035
4036 // Repeat loop optimizations if new loops were seen
4037 if (created_loop_node()) {
4038 C->set_major_progress();
4039 }
4040
4041 // Keep loop predicates and perform optimizations with them
4042 // until no more loop optimizations could be done.
4043 // After that switch predicates off and do more loop optimizations.
4044 if (!C->major_progress() && (C->predicate_count() > 0)) {
4045 C->cleanup_loop_predicates(_igvn);
4046 if (TraceLoopOpts) {
4047 tty->print_cr("PredicatesOff");
4048 }
4049 C->set_major_progress();
4050 }
4051
4052 // Convert scalar to superword operations at the end of all loop opts.
4053 if (UseSuperWord && C->has_loops() && !C->major_progress()) {
4054 // SuperWord transform
4055 SuperWord sw(this);
4056 for (LoopTreeIterator iter(_ltree_root); !iter.done(); iter.next()) {
4057 IdealLoopTree* lpt = iter.current();
4058 if (lpt->is_counted()) {
4059 CountedLoopNode *cl = lpt->_head->as_CountedLoop();
4060
4061 if (PostLoopMultiversioning && cl->is_rce_post_loop() && !cl->is_vectorized_loop()) {
4062 // Check that the rce'd post loop is encountered first, multiversion after all
4063 // major main loop optimization are concluded
4064 if (!C->major_progress()) {
4065 IdealLoopTree *lpt_next = lpt->_next;
4066 if (lpt_next && lpt_next->is_counted()) {
4067 CountedLoopNode *cl = lpt_next->_head->as_CountedLoop();
4068 has_range_checks(lpt_next);
4069 if (cl->is_post_loop() && cl->range_checks_present()) {
4070 if (!cl->is_multiversioned()) {
4071 if (multi_version_post_loops(lpt, lpt_next) == false) {
4072 // Cause the rce loop to be optimized away if we fail
4073 cl->mark_is_multiversioned();
4074 cl->set_slp_max_unroll(0);
4075 poison_rce_post_loop(lpt);
4076 }
4077 }
4078 }
4079 }
4080 sw.transform_loop(lpt, true);
4081 }
4082 } else if (cl->is_main_loop()) {
4083 sw.transform_loop(lpt, true);
4084 }
4085 }
4086 }
4087 }
4088
4089 // disable assert until issue with split_flow_path is resolved (6742111)
4090 // assert(!_has_irreducible_loops || C->parsed_irreducible_loop() || C->is_osr_compilation(),
4091 // "shouldn't introduce irreducible loops");
4092 }
4093
4094 #ifndef PRODUCT
4095 //------------------------------print_statistics-------------------------------
4096 int PhaseIdealLoop::_loop_invokes=0;// Count of PhaseIdealLoop invokes
4097 int PhaseIdealLoop::_loop_work=0; // Sum of PhaseIdealLoop x unique
4098 volatile int PhaseIdealLoop::_long_loop_candidates=0; // Number of long loops seen
4099 volatile int PhaseIdealLoop::_long_loop_nests=0; // Number of long loops successfully transformed to a nest
4100 volatile int PhaseIdealLoop::_long_loop_counted_loops=0; // Number of long loops successfully transformed to a counted loop
print_statistics()4101 void PhaseIdealLoop::print_statistics() {
4102 tty->print_cr("PhaseIdealLoop=%d, sum _unique=%d, long loops=%d/%d/%d", _loop_invokes, _loop_work, _long_loop_counted_loops, _long_loop_nests, _long_loop_candidates);
4103 }
4104
4105 //------------------------------verify-----------------------------------------
4106 // Build a verify-only PhaseIdealLoop, and see that it agrees with me.
4107 static int fail; // debug only, so its multi-thread dont care
verify() const4108 void PhaseIdealLoop::verify() const {
4109 int old_progress = C->major_progress();
4110 ResourceMark rm;
4111 PhaseIdealLoop loop_verify(_igvn, this);
4112 VectorSet visited;
4113
4114 fail = 0;
4115 verify_compare(C->root(), &loop_verify, visited);
4116 assert(fail == 0, "verify loops failed");
4117 // Verify loop structure is the same
4118 _ltree_root->verify_tree(loop_verify._ltree_root, NULL);
4119 // Reset major-progress. It was cleared by creating a verify version of
4120 // PhaseIdealLoop.
4121 C->restore_major_progress(old_progress);
4122 }
4123
4124 //------------------------------verify_compare---------------------------------
4125 // Make sure me and the given PhaseIdealLoop agree on key data structures
verify_compare(Node * n,const PhaseIdealLoop * loop_verify,VectorSet & visited) const4126 void PhaseIdealLoop::verify_compare( Node *n, const PhaseIdealLoop *loop_verify, VectorSet &visited ) const {
4127 if( !n ) return;
4128 if( visited.test_set( n->_idx ) ) return;
4129 if( !_nodes[n->_idx] ) { // Unreachable
4130 assert( !loop_verify->_nodes[n->_idx], "both should be unreachable" );
4131 return;
4132 }
4133
4134 uint i;
4135 for( i = 0; i < n->req(); i++ )
4136 verify_compare( n->in(i), loop_verify, visited );
4137
4138 // Check the '_nodes' block/loop structure
4139 i = n->_idx;
4140 if( has_ctrl(n) ) { // We have control; verify has loop or ctrl
4141 if( _nodes[i] != loop_verify->_nodes[i] &&
4142 get_ctrl_no_update(n) != loop_verify->get_ctrl_no_update(n) ) {
4143 tty->print("Mismatched control setting for: ");
4144 n->dump();
4145 if( fail++ > 10 ) return;
4146 Node *c = get_ctrl_no_update(n);
4147 tty->print("We have it as: ");
4148 if( c->in(0) ) c->dump();
4149 else tty->print_cr("N%d",c->_idx);
4150 tty->print("Verify thinks: ");
4151 if( loop_verify->has_ctrl(n) )
4152 loop_verify->get_ctrl_no_update(n)->dump();
4153 else
4154 loop_verify->get_loop_idx(n)->dump();
4155 tty->cr();
4156 }
4157 } else { // We have a loop
4158 IdealLoopTree *us = get_loop_idx(n);
4159 if( loop_verify->has_ctrl(n) ) {
4160 tty->print("Mismatched loop setting for: ");
4161 n->dump();
4162 if( fail++ > 10 ) return;
4163 tty->print("We have it as: ");
4164 us->dump();
4165 tty->print("Verify thinks: ");
4166 loop_verify->get_ctrl_no_update(n)->dump();
4167 tty->cr();
4168 } else if (!C->major_progress()) {
4169 // Loop selection can be messed up if we did a major progress
4170 // operation, like split-if. Do not verify in that case.
4171 IdealLoopTree *them = loop_verify->get_loop_idx(n);
4172 if( us->_head != them->_head || us->_tail != them->_tail ) {
4173 tty->print("Unequals loops for: ");
4174 n->dump();
4175 if( fail++ > 10 ) return;
4176 tty->print("We have it as: ");
4177 us->dump();
4178 tty->print("Verify thinks: ");
4179 them->dump();
4180 tty->cr();
4181 }
4182 }
4183 }
4184
4185 // Check for immediate dominators being equal
4186 if( i >= _idom_size ) {
4187 if( !n->is_CFG() ) return;
4188 tty->print("CFG Node with no idom: ");
4189 n->dump();
4190 return;
4191 }
4192 if( !n->is_CFG() ) return;
4193 if( n == C->root() ) return; // No IDOM here
4194
4195 assert(n->_idx == i, "sanity");
4196 Node *id = idom_no_update(n);
4197 if( id != loop_verify->idom_no_update(n) ) {
4198 tty->print("Unequals idoms for: ");
4199 n->dump();
4200 if( fail++ > 10 ) return;
4201 tty->print("We have it as: ");
4202 id->dump();
4203 tty->print("Verify thinks: ");
4204 loop_verify->idom_no_update(n)->dump();
4205 tty->cr();
4206 }
4207
4208 }
4209
4210 //------------------------------verify_tree------------------------------------
4211 // Verify that tree structures match. Because the CFG can change, siblings
4212 // within the loop tree can be reordered. We attempt to deal with that by
4213 // reordering the verify's loop tree if possible.
verify_tree(IdealLoopTree * loop,const IdealLoopTree * parent) const4214 void IdealLoopTree::verify_tree(IdealLoopTree *loop, const IdealLoopTree *parent) const {
4215 assert( _parent == parent, "Badly formed loop tree" );
4216
4217 // Siblings not in same order? Attempt to re-order.
4218 if( _head != loop->_head ) {
4219 // Find _next pointer to update
4220 IdealLoopTree **pp = &loop->_parent->_child;
4221 while( *pp != loop )
4222 pp = &((*pp)->_next);
4223 // Find proper sibling to be next
4224 IdealLoopTree **nn = &loop->_next;
4225 while( (*nn) && (*nn)->_head != _head )
4226 nn = &((*nn)->_next);
4227
4228 // Check for no match.
4229 if( !(*nn) ) {
4230 // Annoyingly, irreducible loops can pick different headers
4231 // after a major_progress operation, so the rest of the loop
4232 // tree cannot be matched.
4233 if (_irreducible && Compile::current()->major_progress()) return;
4234 assert( 0, "failed to match loop tree" );
4235 }
4236
4237 // Move (*nn) to (*pp)
4238 IdealLoopTree *hit = *nn;
4239 *nn = hit->_next;
4240 hit->_next = loop;
4241 *pp = loop;
4242 loop = hit;
4243 // Now try again to verify
4244 }
4245
4246 assert( _head == loop->_head , "mismatched loop head" );
4247 Node *tail = _tail; // Inline a non-updating version of
4248 while( !tail->in(0) ) // the 'tail()' call.
4249 tail = tail->in(1);
4250 assert( tail == loop->_tail, "mismatched loop tail" );
4251
4252 // Counted loops that are guarded should be able to find their guards
4253 if( _head->is_CountedLoop() && _head->as_CountedLoop()->is_main_loop() ) {
4254 CountedLoopNode *cl = _head->as_CountedLoop();
4255 Node *init = cl->init_trip();
4256 Node *ctrl = cl->in(LoopNode::EntryControl);
4257 assert( ctrl->Opcode() == Op_IfTrue || ctrl->Opcode() == Op_IfFalse, "" );
4258 Node *iff = ctrl->in(0);
4259 assert( iff->Opcode() == Op_If, "" );
4260 Node *bol = iff->in(1);
4261 assert( bol->Opcode() == Op_Bool, "" );
4262 Node *cmp = bol->in(1);
4263 assert( cmp->Opcode() == Op_CmpI, "" );
4264 Node *add = cmp->in(1);
4265 Node *opaq;
4266 if( add->Opcode() == Op_Opaque1 ) {
4267 opaq = add;
4268 } else {
4269 assert( add->Opcode() == Op_AddI || add->Opcode() == Op_ConI , "" );
4270 assert( add == init, "" );
4271 opaq = cmp->in(2);
4272 }
4273 assert( opaq->Opcode() == Op_Opaque1, "" );
4274
4275 }
4276
4277 if (_child != NULL) _child->verify_tree(loop->_child, this);
4278 if (_next != NULL) _next ->verify_tree(loop->_next, parent);
4279 // Innermost loops need to verify loop bodies,
4280 // but only if no 'major_progress'
4281 int fail = 0;
4282 if (!Compile::current()->major_progress() && _child == NULL) {
4283 for( uint i = 0; i < _body.size(); i++ ) {
4284 Node *n = _body.at(i);
4285 if (n->outcnt() == 0) continue; // Ignore dead
4286 uint j;
4287 for( j = 0; j < loop->_body.size(); j++ )
4288 if( loop->_body.at(j) == n )
4289 break;
4290 if( j == loop->_body.size() ) { // Not found in loop body
4291 // Last ditch effort to avoid assertion: Its possible that we
4292 // have some users (so outcnt not zero) but are still dead.
4293 // Try to find from root.
4294 if (Compile::current()->root()->find(n->_idx)) {
4295 fail++;
4296 tty->print("We have that verify does not: ");
4297 n->dump();
4298 }
4299 }
4300 }
4301 for( uint i2 = 0; i2 < loop->_body.size(); i2++ ) {
4302 Node *n = loop->_body.at(i2);
4303 if (n->outcnt() == 0) continue; // Ignore dead
4304 uint j;
4305 for( j = 0; j < _body.size(); j++ )
4306 if( _body.at(j) == n )
4307 break;
4308 if( j == _body.size() ) { // Not found in loop body
4309 // Last ditch effort to avoid assertion: Its possible that we
4310 // have some users (so outcnt not zero) but are still dead.
4311 // Try to find from root.
4312 if (Compile::current()->root()->find(n->_idx)) {
4313 fail++;
4314 tty->print("Verify has that we do not: ");
4315 n->dump();
4316 }
4317 }
4318 }
4319 assert( !fail, "loop body mismatch" );
4320 }
4321 }
4322
4323 #endif
4324
4325 //------------------------------set_idom---------------------------------------
set_idom(Node * d,Node * n,uint dom_depth)4326 void PhaseIdealLoop::set_idom(Node* d, Node* n, uint dom_depth) {
4327 uint idx = d->_idx;
4328 if (idx >= _idom_size) {
4329 uint newsize = next_power_of_2(idx);
4330 _idom = REALLOC_RESOURCE_ARRAY( Node*, _idom,_idom_size,newsize);
4331 _dom_depth = REALLOC_RESOURCE_ARRAY( uint, _dom_depth,_idom_size,newsize);
4332 memset( _dom_depth + _idom_size, 0, (newsize - _idom_size) * sizeof(uint) );
4333 _idom_size = newsize;
4334 }
4335 _idom[idx] = n;
4336 _dom_depth[idx] = dom_depth;
4337 }
4338
4339 //------------------------------recompute_dom_depth---------------------------------------
4340 // The dominator tree is constructed with only parent pointers.
4341 // This recomputes the depth in the tree by first tagging all
4342 // nodes as "no depth yet" marker. The next pass then runs up
4343 // the dom tree from each node marked "no depth yet", and computes
4344 // the depth on the way back down.
recompute_dom_depth()4345 void PhaseIdealLoop::recompute_dom_depth() {
4346 uint no_depth_marker = C->unique();
4347 uint i;
4348 // Initialize depth to "no depth yet" and realize all lazy updates
4349 for (i = 0; i < _idom_size; i++) {
4350 // Only indices with a _dom_depth has a Node* or NULL (otherwise uninitalized).
4351 if (_dom_depth[i] > 0 && _idom[i] != NULL) {
4352 _dom_depth[i] = no_depth_marker;
4353
4354 // heal _idom if it has a fwd mapping in _nodes
4355 if (_idom[i]->in(0) == NULL) {
4356 idom(i);
4357 }
4358 }
4359 }
4360 if (_dom_stk == NULL) {
4361 uint init_size = C->live_nodes() / 100; // Guess that 1/100 is a reasonable initial size.
4362 if (init_size < 10) init_size = 10;
4363 _dom_stk = new GrowableArray<uint>(init_size);
4364 }
4365 // Compute new depth for each node.
4366 for (i = 0; i < _idom_size; i++) {
4367 uint j = i;
4368 // Run up the dom tree to find a node with a depth
4369 while (_dom_depth[j] == no_depth_marker) {
4370 _dom_stk->push(j);
4371 j = _idom[j]->_idx;
4372 }
4373 // Compute the depth on the way back down this tree branch
4374 uint dd = _dom_depth[j] + 1;
4375 while (_dom_stk->length() > 0) {
4376 uint j = _dom_stk->pop();
4377 _dom_depth[j] = dd;
4378 dd++;
4379 }
4380 }
4381 }
4382
4383 //------------------------------sort-------------------------------------------
4384 // Insert 'loop' into the existing loop tree. 'innermost' is a leaf of the
4385 // loop tree, not the root.
sort(IdealLoopTree * loop,IdealLoopTree * innermost)4386 IdealLoopTree *PhaseIdealLoop::sort( IdealLoopTree *loop, IdealLoopTree *innermost ) {
4387 if( !innermost ) return loop; // New innermost loop
4388
4389 int loop_preorder = get_preorder(loop->_head); // Cache pre-order number
4390 assert( loop_preorder, "not yet post-walked loop" );
4391 IdealLoopTree **pp = &innermost; // Pointer to previous next-pointer
4392 IdealLoopTree *l = *pp; // Do I go before or after 'l'?
4393
4394 // Insert at start of list
4395 while( l ) { // Insertion sort based on pre-order
4396 if( l == loop ) return innermost; // Already on list!
4397 int l_preorder = get_preorder(l->_head); // Cache pre-order number
4398 assert( l_preorder, "not yet post-walked l" );
4399 // Check header pre-order number to figure proper nesting
4400 if( loop_preorder > l_preorder )
4401 break; // End of insertion
4402 // If headers tie (e.g., shared headers) check tail pre-order numbers.
4403 // Since I split shared headers, you'd think this could not happen.
4404 // BUT: I must first do the preorder numbering before I can discover I
4405 // have shared headers, so the split headers all get the same preorder
4406 // number as the RegionNode they split from.
4407 if( loop_preorder == l_preorder &&
4408 get_preorder(loop->_tail) < get_preorder(l->_tail) )
4409 break; // Also check for shared headers (same pre#)
4410 pp = &l->_parent; // Chain up list
4411 l = *pp;
4412 }
4413 // Link into list
4414 // Point predecessor to me
4415 *pp = loop;
4416 // Point me to successor
4417 IdealLoopTree *p = loop->_parent;
4418 loop->_parent = l; // Point me to successor
4419 if( p ) sort( p, innermost ); // Insert my parents into list as well
4420 return innermost;
4421 }
4422
4423 //------------------------------build_loop_tree--------------------------------
4424 // I use a modified Vick/Tarjan algorithm. I need pre- and a post- visit
4425 // bits. The _nodes[] array is mapped by Node index and holds a NULL for
4426 // not-yet-pre-walked, pre-order # for pre-but-not-post-walked and holds the
4427 // tightest enclosing IdealLoopTree for post-walked.
4428 //
4429 // During my forward walk I do a short 1-layer lookahead to see if I can find
4430 // a loop backedge with that doesn't have any work on the backedge. This
4431 // helps me construct nested loops with shared headers better.
4432 //
4433 // Once I've done the forward recursion, I do the post-work. For each child
4434 // I check to see if there is a backedge. Backedges define a loop! I
4435 // insert an IdealLoopTree at the target of the backedge.
4436 //
4437 // During the post-work I also check to see if I have several children
4438 // belonging to different loops. If so, then this Node is a decision point
4439 // where control flow can choose to change loop nests. It is at this
4440 // decision point where I can figure out how loops are nested. At this
4441 // time I can properly order the different loop nests from my children.
4442 // Note that there may not be any backedges at the decision point!
4443 //
4444 // Since the decision point can be far removed from the backedges, I can't
4445 // order my loops at the time I discover them. Thus at the decision point
4446 // I need to inspect loop header pre-order numbers to properly nest my
4447 // loops. This means I need to sort my childrens' loops by pre-order.
4448 // The sort is of size number-of-control-children, which generally limits
4449 // it to size 2 (i.e., I just choose between my 2 target loops).
build_loop_tree()4450 void PhaseIdealLoop::build_loop_tree() {
4451 // Allocate stack of size C->live_nodes()/2 to avoid frequent realloc
4452 GrowableArray <Node *> bltstack(C->live_nodes() >> 1);
4453 Node *n = C->root();
4454 bltstack.push(n);
4455 int pre_order = 1;
4456 int stack_size;
4457
4458 while ( ( stack_size = bltstack.length() ) != 0 ) {
4459 n = bltstack.top(); // Leave node on stack
4460 if ( !is_visited(n) ) {
4461 // ---- Pre-pass Work ----
4462 // Pre-walked but not post-walked nodes need a pre_order number.
4463
4464 set_preorder_visited( n, pre_order ); // set as visited
4465
4466 // ---- Scan over children ----
4467 // Scan first over control projections that lead to loop headers.
4468 // This helps us find inner-to-outer loops with shared headers better.
4469
4470 // Scan children's children for loop headers.
4471 for ( int i = n->outcnt() - 1; i >= 0; --i ) {
4472 Node* m = n->raw_out(i); // Child
4473 if( m->is_CFG() && !is_visited(m) ) { // Only for CFG children
4474 // Scan over children's children to find loop
4475 for (DUIterator_Fast jmax, j = m->fast_outs(jmax); j < jmax; j++) {
4476 Node* l = m->fast_out(j);
4477 if( is_visited(l) && // Been visited?
4478 !is_postvisited(l) && // But not post-visited
4479 get_preorder(l) < pre_order ) { // And smaller pre-order
4480 // Found! Scan the DFS down this path before doing other paths
4481 bltstack.push(m);
4482 break;
4483 }
4484 }
4485 }
4486 }
4487 pre_order++;
4488 }
4489 else if ( !is_postvisited(n) ) {
4490 // Note: build_loop_tree_impl() adds out edges on rare occasions,
4491 // such as com.sun.rsasign.am::a.
4492 // For non-recursive version, first, process current children.
4493 // On next iteration, check if additional children were added.
4494 for ( int k = n->outcnt() - 1; k >= 0; --k ) {
4495 Node* u = n->raw_out(k);
4496 if ( u->is_CFG() && !is_visited(u) ) {
4497 bltstack.push(u);
4498 }
4499 }
4500 if ( bltstack.length() == stack_size ) {
4501 // There were no additional children, post visit node now
4502 (void)bltstack.pop(); // Remove node from stack
4503 pre_order = build_loop_tree_impl( n, pre_order );
4504 // Check for bailout
4505 if (C->failing()) {
4506 return;
4507 }
4508 // Check to grow _preorders[] array for the case when
4509 // build_loop_tree_impl() adds new nodes.
4510 check_grow_preorders();
4511 }
4512 }
4513 else {
4514 (void)bltstack.pop(); // Remove post-visited node from stack
4515 }
4516 }
4517 }
4518
4519 //------------------------------build_loop_tree_impl---------------------------
build_loop_tree_impl(Node * n,int pre_order)4520 int PhaseIdealLoop::build_loop_tree_impl( Node *n, int pre_order ) {
4521 // ---- Post-pass Work ----
4522 // Pre-walked but not post-walked nodes need a pre_order number.
4523
4524 // Tightest enclosing loop for this Node
4525 IdealLoopTree *innermost = NULL;
4526
4527 // For all children, see if any edge is a backedge. If so, make a loop
4528 // for it. Then find the tightest enclosing loop for the self Node.
4529 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
4530 Node* m = n->fast_out(i); // Child
4531 if( n == m ) continue; // Ignore control self-cycles
4532 if( !m->is_CFG() ) continue;// Ignore non-CFG edges
4533
4534 IdealLoopTree *l; // Child's loop
4535 if( !is_postvisited(m) ) { // Child visited but not post-visited?
4536 // Found a backedge
4537 assert( get_preorder(m) < pre_order, "should be backedge" );
4538 // Check for the RootNode, which is already a LoopNode and is allowed
4539 // to have multiple "backedges".
4540 if( m == C->root()) { // Found the root?
4541 l = _ltree_root; // Root is the outermost LoopNode
4542 } else { // Else found a nested loop
4543 // Insert a LoopNode to mark this loop.
4544 l = new IdealLoopTree(this, m, n);
4545 } // End of Else found a nested loop
4546 if( !has_loop(m) ) // If 'm' does not already have a loop set
4547 set_loop(m, l); // Set loop header to loop now
4548
4549 } else { // Else not a nested loop
4550 if( !_nodes[m->_idx] ) continue; // Dead code has no loop
4551 l = get_loop(m); // Get previously determined loop
4552 // If successor is header of a loop (nest), move up-loop till it
4553 // is a member of some outer enclosing loop. Since there are no
4554 // shared headers (I've split them already) I only need to go up
4555 // at most 1 level.
4556 while( l && l->_head == m ) // Successor heads loop?
4557 l = l->_parent; // Move up 1 for me
4558 // If this loop is not properly parented, then this loop
4559 // has no exit path out, i.e. its an infinite loop.
4560 if( !l ) {
4561 // Make loop "reachable" from root so the CFG is reachable. Basically
4562 // insert a bogus loop exit that is never taken. 'm', the loop head,
4563 // points to 'n', one (of possibly many) fall-in paths. There may be
4564 // many backedges as well.
4565
4566 // Here I set the loop to be the root loop. I could have, after
4567 // inserting a bogus loop exit, restarted the recursion and found my
4568 // new loop exit. This would make the infinite loop a first-class
4569 // loop and it would then get properly optimized. What's the use of
4570 // optimizing an infinite loop?
4571 l = _ltree_root; // Oops, found infinite loop
4572
4573 if (!_verify_only) {
4574 // Insert the NeverBranch between 'm' and it's control user.
4575 NeverBranchNode *iff = new NeverBranchNode( m );
4576 _igvn.register_new_node_with_optimizer(iff);
4577 set_loop(iff, l);
4578 Node *if_t = new CProjNode( iff, 0 );
4579 _igvn.register_new_node_with_optimizer(if_t);
4580 set_loop(if_t, l);
4581
4582 Node* cfg = NULL; // Find the One True Control User of m
4583 for (DUIterator_Fast jmax, j = m->fast_outs(jmax); j < jmax; j++) {
4584 Node* x = m->fast_out(j);
4585 if (x->is_CFG() && x != m && x != iff)
4586 { cfg = x; break; }
4587 }
4588 assert(cfg != NULL, "must find the control user of m");
4589 uint k = 0; // Probably cfg->in(0)
4590 while( cfg->in(k) != m ) k++; // But check incase cfg is a Region
4591 cfg->set_req( k, if_t ); // Now point to NeverBranch
4592 _igvn._worklist.push(cfg);
4593
4594 // Now create the never-taken loop exit
4595 Node *if_f = new CProjNode( iff, 1 );
4596 _igvn.register_new_node_with_optimizer(if_f);
4597 set_loop(if_f, l);
4598 // Find frame ptr for Halt. Relies on the optimizer
4599 // V-N'ing. Easier and quicker than searching through
4600 // the program structure.
4601 Node *frame = new ParmNode( C->start(), TypeFunc::FramePtr );
4602 _igvn.register_new_node_with_optimizer(frame);
4603 // Halt & Catch Fire
4604 Node* halt = new HaltNode(if_f, frame, "never-taken loop exit reached");
4605 _igvn.register_new_node_with_optimizer(halt);
4606 set_loop(halt, l);
4607 C->root()->add_req(halt);
4608 }
4609 set_loop(C->root(), _ltree_root);
4610 }
4611 }
4612 // Weeny check for irreducible. This child was already visited (this
4613 // IS the post-work phase). Is this child's loop header post-visited
4614 // as well? If so, then I found another entry into the loop.
4615 if (!_verify_only) {
4616 while( is_postvisited(l->_head) ) {
4617 // found irreducible
4618 l->_irreducible = 1; // = true
4619 l = l->_parent;
4620 _has_irreducible_loops = true;
4621 // Check for bad CFG here to prevent crash, and bailout of compile
4622 if (l == NULL) {
4623 C->record_method_not_compilable("unhandled CFG detected during loop optimization");
4624 return pre_order;
4625 }
4626 }
4627 C->set_has_irreducible_loop(_has_irreducible_loops);
4628 }
4629
4630 // This Node might be a decision point for loops. It is only if
4631 // it's children belong to several different loops. The sort call
4632 // does a trivial amount of work if there is only 1 child or all
4633 // children belong to the same loop. If however, the children
4634 // belong to different loops, the sort call will properly set the
4635 // _parent pointers to show how the loops nest.
4636 //
4637 // In any case, it returns the tightest enclosing loop.
4638 innermost = sort( l, innermost );
4639 }
4640
4641 // Def-use info will have some dead stuff; dead stuff will have no
4642 // loop decided on.
4643
4644 // Am I a loop header? If so fix up my parent's child and next ptrs.
4645 if( innermost && innermost->_head == n ) {
4646 assert( get_loop(n) == innermost, "" );
4647 IdealLoopTree *p = innermost->_parent;
4648 IdealLoopTree *l = innermost;
4649 while( p && l->_head == n ) {
4650 l->_next = p->_child; // Put self on parents 'next child'
4651 p->_child = l; // Make self as first child of parent
4652 l = p; // Now walk up the parent chain
4653 p = l->_parent;
4654 }
4655 } else {
4656 // Note that it is possible for a LoopNode to reach here, if the
4657 // backedge has been made unreachable (hence the LoopNode no longer
4658 // denotes a Loop, and will eventually be removed).
4659
4660 // Record tightest enclosing loop for self. Mark as post-visited.
4661 set_loop(n, innermost);
4662 // Also record has_call flag early on
4663 if( innermost ) {
4664 if( n->is_Call() && !n->is_CallLeaf() && !n->is_macro() ) {
4665 // Do not count uncommon calls
4666 if( !n->is_CallStaticJava() || !n->as_CallStaticJava()->_name ) {
4667 Node *iff = n->in(0)->in(0);
4668 // No any calls for vectorized loops.
4669 if( UseSuperWord || !iff->is_If() ||
4670 (n->in(0)->Opcode() == Op_IfFalse &&
4671 (1.0 - iff->as_If()->_prob) >= 0.01) ||
4672 (iff->as_If()->_prob >= 0.01) )
4673 innermost->_has_call = 1;
4674 }
4675 } else if( n->is_Allocate() && n->as_Allocate()->_is_scalar_replaceable ) {
4676 // Disable loop optimizations if the loop has a scalar replaceable
4677 // allocation. This disabling may cause a potential performance lost
4678 // if the allocation is not eliminated for some reason.
4679 innermost->_allow_optimizations = false;
4680 innermost->_has_call = 1; // = true
4681 } else if (n->Opcode() == Op_SafePoint) {
4682 // Record all safepoints in this loop.
4683 if (innermost->_safepts == NULL) innermost->_safepts = new Node_List();
4684 innermost->_safepts->push(n);
4685 }
4686 }
4687 }
4688
4689 // Flag as post-visited now
4690 set_postvisited(n);
4691 return pre_order;
4692 }
4693
4694
4695 //------------------------------build_loop_early-------------------------------
4696 // Put Data nodes into some loop nest, by setting the _nodes[]->loop mapping.
4697 // First pass computes the earliest controlling node possible. This is the
4698 // controlling input with the deepest dominating depth.
build_loop_early(VectorSet & visited,Node_List & worklist,Node_Stack & nstack)4699 void PhaseIdealLoop::build_loop_early( VectorSet &visited, Node_List &worklist, Node_Stack &nstack ) {
4700 while (worklist.size() != 0) {
4701 // Use local variables nstack_top_n & nstack_top_i to cache values
4702 // on nstack's top.
4703 Node *nstack_top_n = worklist.pop();
4704 uint nstack_top_i = 0;
4705 //while_nstack_nonempty:
4706 while (true) {
4707 // Get parent node and next input's index from stack's top.
4708 Node *n = nstack_top_n;
4709 uint i = nstack_top_i;
4710 uint cnt = n->req(); // Count of inputs
4711 if (i == 0) { // Pre-process the node.
4712 if( has_node(n) && // Have either loop or control already?
4713 !has_ctrl(n) ) { // Have loop picked out already?
4714 // During "merge_many_backedges" we fold up several nested loops
4715 // into a single loop. This makes the members of the original
4716 // loop bodies pointing to dead loops; they need to move up
4717 // to the new UNION'd larger loop. I set the _head field of these
4718 // dead loops to NULL and the _parent field points to the owning
4719 // loop. Shades of UNION-FIND algorithm.
4720 IdealLoopTree *ilt;
4721 while( !(ilt = get_loop(n))->_head ) {
4722 // Normally I would use a set_loop here. But in this one special
4723 // case, it is legal (and expected) to change what loop a Node
4724 // belongs to.
4725 _nodes.map(n->_idx, (Node*)(ilt->_parent) );
4726 }
4727 // Remove safepoints ONLY if I've already seen I don't need one.
4728 // (the old code here would yank a 2nd safepoint after seeing a
4729 // first one, even though the 1st did not dominate in the loop body
4730 // and thus could be avoided indefinitely)
4731 if( !_verify_only && !_verify_me && ilt->_has_sfpt && n->Opcode() == Op_SafePoint &&
4732 is_deleteable_safept(n)) {
4733 Node *in = n->in(TypeFunc::Control);
4734 lazy_replace(n,in); // Pull safepoint now
4735 if (ilt->_safepts != NULL) {
4736 ilt->_safepts->yank(n);
4737 }
4738 // Carry on with the recursion "as if" we are walking
4739 // only the control input
4740 if( !visited.test_set( in->_idx ) ) {
4741 worklist.push(in); // Visit this guy later, using worklist
4742 }
4743 // Get next node from nstack:
4744 // - skip n's inputs processing by setting i > cnt;
4745 // - we also will not call set_early_ctrl(n) since
4746 // has_node(n) == true (see the condition above).
4747 i = cnt + 1;
4748 }
4749 }
4750 } // if (i == 0)
4751
4752 // Visit all inputs
4753 bool done = true; // Assume all n's inputs will be processed
4754 while (i < cnt) {
4755 Node *in = n->in(i);
4756 ++i;
4757 if (in == NULL) continue;
4758 if (in->pinned() && !in->is_CFG())
4759 set_ctrl(in, in->in(0));
4760 int is_visited = visited.test_set( in->_idx );
4761 if (!has_node(in)) { // No controlling input yet?
4762 assert( !in->is_CFG(), "CFG Node with no controlling input?" );
4763 assert( !is_visited, "visit only once" );
4764 nstack.push(n, i); // Save parent node and next input's index.
4765 nstack_top_n = in; // Process current input now.
4766 nstack_top_i = 0;
4767 done = false; // Not all n's inputs processed.
4768 break; // continue while_nstack_nonempty;
4769 } else if (!is_visited) {
4770 // This guy has a location picked out for him, but has not yet
4771 // been visited. Happens to all CFG nodes, for instance.
4772 // Visit him using the worklist instead of recursion, to break
4773 // cycles. Since he has a location already we do not need to
4774 // find his location before proceeding with the current Node.
4775 worklist.push(in); // Visit this guy later, using worklist
4776 }
4777 }
4778 if (done) {
4779 // All of n's inputs have been processed, complete post-processing.
4780
4781 // Compute earliest point this Node can go.
4782 // CFG, Phi, pinned nodes already know their controlling input.
4783 if (!has_node(n)) {
4784 // Record earliest legal location
4785 set_early_ctrl(n, false);
4786 }
4787 if (nstack.is_empty()) {
4788 // Finished all nodes on stack.
4789 // Process next node on the worklist.
4790 break;
4791 }
4792 // Get saved parent node and next input's index.
4793 nstack_top_n = nstack.node();
4794 nstack_top_i = nstack.index();
4795 nstack.pop();
4796 }
4797 } // while (true)
4798 }
4799 }
4800
4801 //------------------------------dom_lca_internal--------------------------------
4802 // Pair-wise LCA
dom_lca_internal(Node * n1,Node * n2) const4803 Node *PhaseIdealLoop::dom_lca_internal( Node *n1, Node *n2 ) const {
4804 if( !n1 ) return n2; // Handle NULL original LCA
4805 assert( n1->is_CFG(), "" );
4806 assert( n2->is_CFG(), "" );
4807 // find LCA of all uses
4808 uint d1 = dom_depth(n1);
4809 uint d2 = dom_depth(n2);
4810 while (n1 != n2) {
4811 if (d1 > d2) {
4812 n1 = idom(n1);
4813 d1 = dom_depth(n1);
4814 } else if (d1 < d2) {
4815 n2 = idom(n2);
4816 d2 = dom_depth(n2);
4817 } else {
4818 // Here d1 == d2. Due to edits of the dominator-tree, sections
4819 // of the tree might have the same depth. These sections have
4820 // to be searched more carefully.
4821
4822 // Scan up all the n1's with equal depth, looking for n2.
4823 Node *t1 = idom(n1);
4824 while (dom_depth(t1) == d1) {
4825 if (t1 == n2) return n2;
4826 t1 = idom(t1);
4827 }
4828 // Scan up all the n2's with equal depth, looking for n1.
4829 Node *t2 = idom(n2);
4830 while (dom_depth(t2) == d2) {
4831 if (t2 == n1) return n1;
4832 t2 = idom(t2);
4833 }
4834 // Move up to a new dominator-depth value as well as up the dom-tree.
4835 n1 = t1;
4836 n2 = t2;
4837 d1 = dom_depth(n1);
4838 d2 = dom_depth(n2);
4839 }
4840 }
4841 return n1;
4842 }
4843
4844 //------------------------------compute_idom-----------------------------------
4845 // Locally compute IDOM using dom_lca call. Correct only if the incoming
4846 // IDOMs are correct.
compute_idom(Node * region) const4847 Node *PhaseIdealLoop::compute_idom( Node *region ) const {
4848 assert( region->is_Region(), "" );
4849 Node *LCA = NULL;
4850 for( uint i = 1; i < region->req(); i++ ) {
4851 if( region->in(i) != C->top() )
4852 LCA = dom_lca( LCA, region->in(i) );
4853 }
4854 return LCA;
4855 }
4856
verify_dominance(Node * n,Node * use,Node * LCA,Node * early)4857 bool PhaseIdealLoop::verify_dominance(Node* n, Node* use, Node* LCA, Node* early) {
4858 bool had_error = false;
4859 #ifdef ASSERT
4860 if (early != C->root()) {
4861 // Make sure that there's a dominance path from LCA to early
4862 Node* d = LCA;
4863 while (d != early) {
4864 if (d == C->root()) {
4865 dump_bad_graph("Bad graph detected in compute_lca_of_uses", n, early, LCA);
4866 tty->print_cr("*** Use %d isn't dominated by def %d ***", use->_idx, n->_idx);
4867 had_error = true;
4868 break;
4869 }
4870 d = idom(d);
4871 }
4872 }
4873 #endif
4874 return had_error;
4875 }
4876
4877
compute_lca_of_uses(Node * n,Node * early,bool verify)4878 Node* PhaseIdealLoop::compute_lca_of_uses(Node* n, Node* early, bool verify) {
4879 // Compute LCA over list of uses
4880 bool had_error = false;
4881 Node *LCA = NULL;
4882 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax && LCA != early; i++) {
4883 Node* c = n->fast_out(i);
4884 if (_nodes[c->_idx] == NULL)
4885 continue; // Skip the occasional dead node
4886 if( c->is_Phi() ) { // For Phis, we must land above on the path
4887 for( uint j=1; j<c->req(); j++ ) {// For all inputs
4888 if( c->in(j) == n ) { // Found matching input?
4889 Node *use = c->in(0)->in(j);
4890 if (_verify_only && use->is_top()) continue;
4891 LCA = dom_lca_for_get_late_ctrl( LCA, use, n );
4892 if (verify) had_error = verify_dominance(n, use, LCA, early) || had_error;
4893 }
4894 }
4895 } else {
4896 // For CFG data-users, use is in the block just prior
4897 Node *use = has_ctrl(c) ? get_ctrl(c) : c->in(0);
4898 LCA = dom_lca_for_get_late_ctrl( LCA, use, n );
4899 if (verify) had_error = verify_dominance(n, use, LCA, early) || had_error;
4900 }
4901 }
4902 assert(!had_error, "bad dominance");
4903 return LCA;
4904 }
4905
4906 // Check the shape of the graph at the loop entry. In some cases,
4907 // the shape of the graph does not match the shape outlined below.
4908 // That is caused by the Opaque1 node "protecting" the shape of
4909 // the graph being removed by, for example, the IGVN performed
4910 // in PhaseIdealLoop::build_and_optimize().
4911 //
4912 // After the Opaque1 node has been removed, optimizations (e.g., split-if,
4913 // loop unswitching, and IGVN, or a combination of them) can freely change
4914 // the graph's shape. As a result, the graph shape outlined below cannot
4915 // be guaranteed anymore.
is_canonical_loop_entry(CountedLoopNode * cl)4916 bool PhaseIdealLoop::is_canonical_loop_entry(CountedLoopNode* cl) {
4917 if (!cl->is_main_loop() && !cl->is_post_loop()) {
4918 return false;
4919 }
4920 Node* ctrl = cl->skip_predicates();
4921
4922 if (ctrl == NULL || (!ctrl->is_IfTrue() && !ctrl->is_IfFalse())) {
4923 return false;
4924 }
4925 Node* iffm = ctrl->in(0);
4926 if (iffm == NULL || !iffm->is_If()) {
4927 return false;
4928 }
4929 Node* bolzm = iffm->in(1);
4930 if (bolzm == NULL || !bolzm->is_Bool()) {
4931 return false;
4932 }
4933 Node* cmpzm = bolzm->in(1);
4934 if (cmpzm == NULL || !cmpzm->is_Cmp()) {
4935 return false;
4936 }
4937 // compares can get conditionally flipped
4938 bool found_opaque = false;
4939 for (uint i = 1; i < cmpzm->req(); i++) {
4940 Node* opnd = cmpzm->in(i);
4941 if (opnd && opnd->Opcode() == Op_Opaque1) {
4942 found_opaque = true;
4943 break;
4944 }
4945 }
4946 if (!found_opaque) {
4947 return false;
4948 }
4949 return true;
4950 }
4951
4952 //------------------------------get_late_ctrl----------------------------------
4953 // Compute latest legal control.
get_late_ctrl(Node * n,Node * early)4954 Node *PhaseIdealLoop::get_late_ctrl( Node *n, Node *early ) {
4955 assert(early != NULL, "early control should not be NULL");
4956
4957 Node* LCA = compute_lca_of_uses(n, early);
4958 #ifdef ASSERT
4959 if (LCA == C->root() && LCA != early) {
4960 // def doesn't dominate uses so print some useful debugging output
4961 compute_lca_of_uses(n, early, true);
4962 }
4963 #endif
4964
4965 // if this is a load, check for anti-dependent stores
4966 // We use a conservative algorithm to identify potential interfering
4967 // instructions and for rescheduling the load. The users of the memory
4968 // input of this load are examined. Any use which is not a load and is
4969 // dominated by early is considered a potentially interfering store.
4970 // This can produce false positives.
4971 if (n->is_Load() && LCA != early) {
4972 int load_alias_idx = C->get_alias_index(n->adr_type());
4973 if (C->alias_type(load_alias_idx)->is_rewritable()) {
4974 Unique_Node_List worklist;
4975
4976 Node* mem = n->in(MemNode::Memory);
4977 for (DUIterator_Fast imax, i = mem->fast_outs(imax); i < imax; i++) {
4978 Node* s = mem->fast_out(i);
4979 worklist.push(s);
4980 }
4981 for (uint i = 0; i < worklist.size() && LCA != early; i++) {
4982 Node* s = worklist.at(i);
4983 if (s->is_Load() || s->Opcode() == Op_SafePoint ||
4984 (s->is_CallStaticJava() && s->as_CallStaticJava()->uncommon_trap_request() != 0) ||
4985 s->is_Phi()) {
4986 continue;
4987 } else if (s->is_MergeMem()) {
4988 for (DUIterator_Fast imax, i = s->fast_outs(imax); i < imax; i++) {
4989 Node* s1 = s->fast_out(i);
4990 worklist.push(s1);
4991 }
4992 } else {
4993 Node* sctrl = has_ctrl(s) ? get_ctrl(s) : s->in(0);
4994 assert(sctrl != NULL || !s->is_reachable_from_root(), "must have control");
4995 if (sctrl != NULL && !sctrl->is_top() && is_dominator(early, sctrl)) {
4996 const TypePtr* adr_type = s->adr_type();
4997 if (s->is_ArrayCopy()) {
4998 // Copy to known instance needs destination type to test for aliasing
4999 const TypePtr* dest_type = s->as_ArrayCopy()->_dest_type;
5000 if (dest_type != TypeOopPtr::BOTTOM) {
5001 adr_type = dest_type;
5002 }
5003 }
5004 if (C->can_alias(adr_type, load_alias_idx)) {
5005 LCA = dom_lca_for_get_late_ctrl(LCA, sctrl, n);
5006 } else if (s->is_CFG()) {
5007 for (DUIterator_Fast imax, i = s->fast_outs(imax); i < imax; i++) {
5008 Node* s1 = s->fast_out(i);
5009 if (_igvn.type(s1) == Type::MEMORY) {
5010 worklist.push(s1);
5011 }
5012 }
5013 }
5014 }
5015 }
5016 }
5017 // For Phis only consider Region's inputs that were reached by following the memory edges
5018 if (LCA != early) {
5019 for (uint i = 0; i < worklist.size(); i++) {
5020 Node* s = worklist.at(i);
5021 if (s->is_Phi() && C->can_alias(s->adr_type(), load_alias_idx)) {
5022 Node* r = s->in(0);
5023 for (uint j = 1; j < s->req(); j++) {
5024 Node* in = s->in(j);
5025 Node* r_in = r->in(j);
5026 if ((worklist.member(in) || in == mem) && is_dominator(early, r_in)) {
5027 LCA = dom_lca_for_get_late_ctrl(LCA, r_in, n);
5028 }
5029 }
5030 }
5031 }
5032 }
5033 }
5034 }
5035
5036 assert(LCA == find_non_split_ctrl(LCA), "unexpected late control");
5037 return LCA;
5038 }
5039
5040 // true if CFG node d dominates CFG node n
is_dominator(Node * d,Node * n)5041 bool PhaseIdealLoop::is_dominator(Node *d, Node *n) {
5042 if (d == n)
5043 return true;
5044 assert(d->is_CFG() && n->is_CFG(), "must have CFG nodes");
5045 uint dd = dom_depth(d);
5046 while (dom_depth(n) >= dd) {
5047 if (n == d)
5048 return true;
5049 n = idom(n);
5050 }
5051 return false;
5052 }
5053
5054 //------------------------------dom_lca_for_get_late_ctrl_internal-------------
5055 // Pair-wise LCA with tags.
5056 // Tag each index with the node 'tag' currently being processed
5057 // before advancing up the dominator chain using idom().
5058 // Later calls that find a match to 'tag' know that this path has already
5059 // been considered in the current LCA (which is input 'n1' by convention).
5060 // Since get_late_ctrl() is only called once for each node, the tag array
5061 // does not need to be cleared between calls to get_late_ctrl().
5062 // Algorithm trades a larger constant factor for better asymptotic behavior
5063 //
dom_lca_for_get_late_ctrl_internal(Node * n1,Node * n2,Node * tag)5064 Node *PhaseIdealLoop::dom_lca_for_get_late_ctrl_internal( Node *n1, Node *n2, Node *tag ) {
5065 uint d1 = dom_depth(n1);
5066 uint d2 = dom_depth(n2);
5067
5068 do {
5069 if (d1 > d2) {
5070 // current lca is deeper than n2
5071 _dom_lca_tags.map(n1->_idx, tag);
5072 n1 = idom(n1);
5073 d1 = dom_depth(n1);
5074 } else if (d1 < d2) {
5075 // n2 is deeper than current lca
5076 Node *memo = _dom_lca_tags[n2->_idx];
5077 if( memo == tag ) {
5078 return n1; // Return the current LCA
5079 }
5080 _dom_lca_tags.map(n2->_idx, tag);
5081 n2 = idom(n2);
5082 d2 = dom_depth(n2);
5083 } else {
5084 // Here d1 == d2. Due to edits of the dominator-tree, sections
5085 // of the tree might have the same depth. These sections have
5086 // to be searched more carefully.
5087
5088 // Scan up all the n1's with equal depth, looking for n2.
5089 _dom_lca_tags.map(n1->_idx, tag);
5090 Node *t1 = idom(n1);
5091 while (dom_depth(t1) == d1) {
5092 if (t1 == n2) return n2;
5093 _dom_lca_tags.map(t1->_idx, tag);
5094 t1 = idom(t1);
5095 }
5096 // Scan up all the n2's with equal depth, looking for n1.
5097 _dom_lca_tags.map(n2->_idx, tag);
5098 Node *t2 = idom(n2);
5099 while (dom_depth(t2) == d2) {
5100 if (t2 == n1) return n1;
5101 _dom_lca_tags.map(t2->_idx, tag);
5102 t2 = idom(t2);
5103 }
5104 // Move up to a new dominator-depth value as well as up the dom-tree.
5105 n1 = t1;
5106 n2 = t2;
5107 d1 = dom_depth(n1);
5108 d2 = dom_depth(n2);
5109 }
5110 } while (n1 != n2);
5111 return n1;
5112 }
5113
5114 //------------------------------init_dom_lca_tags------------------------------
5115 // Tag could be a node's integer index, 32bits instead of 64bits in some cases
5116 // Intended use does not involve any growth for the array, so it could
5117 // be of fixed size.
init_dom_lca_tags()5118 void PhaseIdealLoop::init_dom_lca_tags() {
5119 uint limit = C->unique() + 1;
5120 _dom_lca_tags.map( limit, NULL );
5121 #ifdef ASSERT
5122 for( uint i = 0; i < limit; ++i ) {
5123 assert(_dom_lca_tags[i] == NULL, "Must be distinct from each node pointer");
5124 }
5125 #endif // ASSERT
5126 }
5127
5128 //------------------------------clear_dom_lca_tags------------------------------
5129 // Tag could be a node's integer index, 32bits instead of 64bits in some cases
5130 // Intended use does not involve any growth for the array, so it could
5131 // be of fixed size.
clear_dom_lca_tags()5132 void PhaseIdealLoop::clear_dom_lca_tags() {
5133 uint limit = C->unique() + 1;
5134 _dom_lca_tags.map( limit, NULL );
5135 _dom_lca_tags.clear();
5136 #ifdef ASSERT
5137 for( uint i = 0; i < limit; ++i ) {
5138 assert(_dom_lca_tags[i] == NULL, "Must be distinct from each node pointer");
5139 }
5140 #endif // ASSERT
5141 }
5142
5143 //------------------------------build_loop_late--------------------------------
5144 // Put Data nodes into some loop nest, by setting the _nodes[]->loop mapping.
5145 // Second pass finds latest legal placement, and ideal loop placement.
build_loop_late(VectorSet & visited,Node_List & worklist,Node_Stack & nstack)5146 void PhaseIdealLoop::build_loop_late( VectorSet &visited, Node_List &worklist, Node_Stack &nstack ) {
5147 while (worklist.size() != 0) {
5148 Node *n = worklist.pop();
5149 // Only visit once
5150 if (visited.test_set(n->_idx)) continue;
5151 uint cnt = n->outcnt();
5152 uint i = 0;
5153 while (true) {
5154 assert( _nodes[n->_idx], "no dead nodes" );
5155 // Visit all children
5156 if (i < cnt) {
5157 Node* use = n->raw_out(i);
5158 ++i;
5159 // Check for dead uses. Aggressively prune such junk. It might be
5160 // dead in the global sense, but still have local uses so I cannot
5161 // easily call 'remove_dead_node'.
5162 if( _nodes[use->_idx] != NULL || use->is_top() ) { // Not dead?
5163 // Due to cycles, we might not hit the same fixed point in the verify
5164 // pass as we do in the regular pass. Instead, visit such phis as
5165 // simple uses of the loop head.
5166 if( use->in(0) && (use->is_CFG() || use->is_Phi()) ) {
5167 if( !visited.test(use->_idx) )
5168 worklist.push(use);
5169 } else if( !visited.test_set(use->_idx) ) {
5170 nstack.push(n, i); // Save parent and next use's index.
5171 n = use; // Process all children of current use.
5172 cnt = use->outcnt();
5173 i = 0;
5174 }
5175 } else {
5176 // Do not visit around the backedge of loops via data edges.
5177 // push dead code onto a worklist
5178 _deadlist.push(use);
5179 }
5180 } else {
5181 // All of n's children have been processed, complete post-processing.
5182 build_loop_late_post(n);
5183 if (nstack.is_empty()) {
5184 // Finished all nodes on stack.
5185 // Process next node on the worklist.
5186 break;
5187 }
5188 // Get saved parent node and next use's index. Visit the rest of uses.
5189 n = nstack.node();
5190 cnt = n->outcnt();
5191 i = nstack.index();
5192 nstack.pop();
5193 }
5194 }
5195 }
5196 }
5197
5198 // Verify that no data node is scheduled in the outer loop of a strip
5199 // mined loop.
verify_strip_mined_scheduling(Node * n,Node * least)5200 void PhaseIdealLoop::verify_strip_mined_scheduling(Node *n, Node* least) {
5201 #ifdef ASSERT
5202 if (get_loop(least)->_nest == 0) {
5203 return;
5204 }
5205 IdealLoopTree* loop = get_loop(least);
5206 Node* head = loop->_head;
5207 if (head->is_OuterStripMinedLoop() &&
5208 // Verification can't be applied to fully built strip mined loops
5209 head->as_Loop()->outer_loop_end()->in(1)->find_int_con(-1) == 0) {
5210 Node* sfpt = head->as_Loop()->outer_safepoint();
5211 ResourceMark rm;
5212 Unique_Node_List wq;
5213 wq.push(sfpt);
5214 for (uint i = 0; i < wq.size(); i++) {
5215 Node *m = wq.at(i);
5216 for (uint i = 1; i < m->req(); i++) {
5217 Node* nn = m->in(i);
5218 if (nn == n) {
5219 return;
5220 }
5221 if (nn != NULL && has_ctrl(nn) && get_loop(get_ctrl(nn)) == loop) {
5222 wq.push(nn);
5223 }
5224 }
5225 }
5226 ShouldNotReachHere();
5227 }
5228 #endif
5229 }
5230
5231
5232 //------------------------------build_loop_late_post---------------------------
5233 // Put Data nodes into some loop nest, by setting the _nodes[]->loop mapping.
5234 // Second pass finds latest legal placement, and ideal loop placement.
build_loop_late_post(Node * n)5235 void PhaseIdealLoop::build_loop_late_post(Node *n) {
5236 build_loop_late_post_work(n, true);
5237 }
5238
build_loop_late_post_work(Node * n,bool pinned)5239 void PhaseIdealLoop::build_loop_late_post_work(Node *n, bool pinned) {
5240
5241 if (n->req() == 2 && (n->Opcode() == Op_ConvI2L || n->Opcode() == Op_CastII) && !C->major_progress() && !_verify_only) {
5242 _igvn._worklist.push(n); // Maybe we'll normalize it, if no more loops.
5243 }
5244
5245 #ifdef ASSERT
5246 if (_verify_only && !n->is_CFG()) {
5247 // Check def-use domination.
5248 compute_lca_of_uses(n, get_ctrl(n), true /* verify */);
5249 }
5250 #endif
5251
5252 // CFG and pinned nodes already handled
5253 if( n->in(0) ) {
5254 if( n->in(0)->is_top() ) return; // Dead?
5255
5256 // We'd like +VerifyLoopOptimizations to not believe that Mod's/Loads
5257 // _must_ be pinned (they have to observe their control edge of course).
5258 // Unlike Stores (which modify an unallocable resource, the memory
5259 // state), Mods/Loads can float around. So free them up.
5260 switch( n->Opcode() ) {
5261 case Op_DivI:
5262 case Op_DivF:
5263 case Op_DivD:
5264 case Op_ModI:
5265 case Op_ModF:
5266 case Op_ModD:
5267 case Op_LoadB: // Same with Loads; they can sink
5268 case Op_LoadUB: // during loop optimizations.
5269 case Op_LoadUS:
5270 case Op_LoadD:
5271 case Op_LoadF:
5272 case Op_LoadI:
5273 case Op_LoadKlass:
5274 case Op_LoadNKlass:
5275 case Op_LoadL:
5276 case Op_LoadS:
5277 case Op_LoadP:
5278 case Op_LoadN:
5279 case Op_LoadRange:
5280 case Op_LoadD_unaligned:
5281 case Op_LoadL_unaligned:
5282 case Op_StrComp: // Does a bunch of load-like effects
5283 case Op_StrEquals:
5284 case Op_StrIndexOf:
5285 case Op_StrIndexOfChar:
5286 case Op_AryEq:
5287 case Op_HasNegatives:
5288 pinned = false;
5289 }
5290 if (n->is_CMove()) {
5291 pinned = false;
5292 }
5293 if( pinned ) {
5294 IdealLoopTree *chosen_loop = get_loop(n->is_CFG() ? n : get_ctrl(n));
5295 if( !chosen_loop->_child ) // Inner loop?
5296 chosen_loop->_body.push(n); // Collect inner loops
5297 return;
5298 }
5299 } else { // No slot zero
5300 if( n->is_CFG() ) { // CFG with no slot 0 is dead
5301 _nodes.map(n->_idx,0); // No block setting, it's globally dead
5302 return;
5303 }
5304 assert(!n->is_CFG() || n->outcnt() == 0, "");
5305 }
5306
5307 // Do I have a "safe range" I can select over?
5308 Node *early = get_ctrl(n);// Early location already computed
5309
5310 // Compute latest point this Node can go
5311 Node *LCA = get_late_ctrl( n, early );
5312 // LCA is NULL due to uses being dead
5313 if( LCA == NULL ) {
5314 #ifdef ASSERT
5315 for (DUIterator i1 = n->outs(); n->has_out(i1); i1++) {
5316 assert( _nodes[n->out(i1)->_idx] == NULL, "all uses must also be dead");
5317 }
5318 #endif
5319 _nodes.map(n->_idx, 0); // This node is useless
5320 _deadlist.push(n);
5321 return;
5322 }
5323 assert(LCA != NULL && !LCA->is_top(), "no dead nodes");
5324
5325 Node *legal = LCA; // Walk 'legal' up the IDOM chain
5326 Node *least = legal; // Best legal position so far
5327 while( early != legal ) { // While not at earliest legal
5328 #ifdef ASSERT
5329 if (legal->is_Start() && !early->is_Root()) {
5330 // Bad graph. Print idom path and fail.
5331 dump_bad_graph("Bad graph detected in build_loop_late", n, early, LCA);
5332 assert(false, "Bad graph detected in build_loop_late");
5333 }
5334 #endif
5335 // Find least loop nesting depth
5336 legal = idom(legal); // Bump up the IDOM tree
5337 // Check for lower nesting depth
5338 if( get_loop(legal)->_nest < get_loop(least)->_nest )
5339 least = legal;
5340 }
5341 assert(early == legal || legal != C->root(), "bad dominance of inputs");
5342
5343 // Try not to place code on a loop entry projection
5344 // which can inhibit range check elimination.
5345 if (least != early) {
5346 Node* ctrl_out = least->unique_ctrl_out();
5347 if (ctrl_out && ctrl_out->is_Loop() &&
5348 least == ctrl_out->in(LoopNode::EntryControl)) {
5349 // Move the node above predicates as far up as possible so a
5350 // following pass of loop predication doesn't hoist a predicate
5351 // that depends on it above that node.
5352 Node* new_ctrl = least;
5353 for (;;) {
5354 if (!new_ctrl->is_Proj()) {
5355 break;
5356 }
5357 CallStaticJavaNode* call = new_ctrl->as_Proj()->is_uncommon_trap_if_pattern(Deoptimization::Reason_none);
5358 if (call == NULL) {
5359 break;
5360 }
5361 int req = call->uncommon_trap_request();
5362 Deoptimization::DeoptReason trap_reason = Deoptimization::trap_request_reason(req);
5363 if (trap_reason != Deoptimization::Reason_loop_limit_check &&
5364 trap_reason != Deoptimization::Reason_predicate &&
5365 trap_reason != Deoptimization::Reason_profile_predicate) {
5366 break;
5367 }
5368 Node* c = new_ctrl->in(0)->in(0);
5369 if (is_dominator(c, early) && c != early) {
5370 break;
5371 }
5372 new_ctrl = c;
5373 }
5374 least = new_ctrl;
5375 }
5376 }
5377
5378 #ifdef ASSERT
5379 // If verifying, verify that 'verify_me' has a legal location
5380 // and choose it as our location.
5381 if( _verify_me ) {
5382 Node *v_ctrl = _verify_me->get_ctrl_no_update(n);
5383 Node *legal = LCA;
5384 while( early != legal ) { // While not at earliest legal
5385 if( legal == v_ctrl ) break; // Check for prior good location
5386 legal = idom(legal) ;// Bump up the IDOM tree
5387 }
5388 // Check for prior good location
5389 if( legal == v_ctrl ) least = legal; // Keep prior if found
5390 }
5391 #endif
5392
5393 // Assign discovered "here or above" point
5394 least = find_non_split_ctrl(least);
5395 verify_strip_mined_scheduling(n, least);
5396 set_ctrl(n, least);
5397
5398 // Collect inner loop bodies
5399 IdealLoopTree *chosen_loop = get_loop(least);
5400 if( !chosen_loop->_child ) // Inner loop?
5401 chosen_loop->_body.push(n);// Collect inner loops
5402 }
5403
5404 #ifdef ASSERT
dump_bad_graph(const char * msg,Node * n,Node * early,Node * LCA)5405 void PhaseIdealLoop::dump_bad_graph(const char* msg, Node* n, Node* early, Node* LCA) {
5406 tty->print_cr("%s", msg);
5407 tty->print("n: "); n->dump();
5408 tty->print("early(n): "); early->dump();
5409 if (n->in(0) != NULL && !n->in(0)->is_top() &&
5410 n->in(0) != early && !n->in(0)->is_Root()) {
5411 tty->print("n->in(0): "); n->in(0)->dump();
5412 }
5413 for (uint i = 1; i < n->req(); i++) {
5414 Node* in1 = n->in(i);
5415 if (in1 != NULL && in1 != n && !in1->is_top()) {
5416 tty->print("n->in(%d): ", i); in1->dump();
5417 Node* in1_early = get_ctrl(in1);
5418 tty->print("early(n->in(%d)): ", i); in1_early->dump();
5419 if (in1->in(0) != NULL && !in1->in(0)->is_top() &&
5420 in1->in(0) != in1_early && !in1->in(0)->is_Root()) {
5421 tty->print("n->in(%d)->in(0): ", i); in1->in(0)->dump();
5422 }
5423 for (uint j = 1; j < in1->req(); j++) {
5424 Node* in2 = in1->in(j);
5425 if (in2 != NULL && in2 != n && in2 != in1 && !in2->is_top()) {
5426 tty->print("n->in(%d)->in(%d): ", i, j); in2->dump();
5427 Node* in2_early = get_ctrl(in2);
5428 tty->print("early(n->in(%d)->in(%d)): ", i, j); in2_early->dump();
5429 if (in2->in(0) != NULL && !in2->in(0)->is_top() &&
5430 in2->in(0) != in2_early && !in2->in(0)->is_Root()) {
5431 tty->print("n->in(%d)->in(%d)->in(0): ", i, j); in2->in(0)->dump();
5432 }
5433 }
5434 }
5435 }
5436 }
5437 tty->cr();
5438 tty->print("LCA(n): "); LCA->dump();
5439 for (uint i = 0; i < n->outcnt(); i++) {
5440 Node* u1 = n->raw_out(i);
5441 if (u1 == n)
5442 continue;
5443 tty->print("n->out(%d): ", i); u1->dump();
5444 if (u1->is_CFG()) {
5445 for (uint j = 0; j < u1->outcnt(); j++) {
5446 Node* u2 = u1->raw_out(j);
5447 if (u2 != u1 && u2 != n && u2->is_CFG()) {
5448 tty->print("n->out(%d)->out(%d): ", i, j); u2->dump();
5449 }
5450 }
5451 } else {
5452 Node* u1_later = get_ctrl(u1);
5453 tty->print("later(n->out(%d)): ", i); u1_later->dump();
5454 if (u1->in(0) != NULL && !u1->in(0)->is_top() &&
5455 u1->in(0) != u1_later && !u1->in(0)->is_Root()) {
5456 tty->print("n->out(%d)->in(0): ", i); u1->in(0)->dump();
5457 }
5458 for (uint j = 0; j < u1->outcnt(); j++) {
5459 Node* u2 = u1->raw_out(j);
5460 if (u2 == n || u2 == u1)
5461 continue;
5462 tty->print("n->out(%d)->out(%d): ", i, j); u2->dump();
5463 if (!u2->is_CFG()) {
5464 Node* u2_later = get_ctrl(u2);
5465 tty->print("later(n->out(%d)->out(%d)): ", i, j); u2_later->dump();
5466 if (u2->in(0) != NULL && !u2->in(0)->is_top() &&
5467 u2->in(0) != u2_later && !u2->in(0)->is_Root()) {
5468 tty->print("n->out(%d)->in(0): ", i); u2->in(0)->dump();
5469 }
5470 }
5471 }
5472 }
5473 }
5474 tty->cr();
5475 tty->print_cr("idoms of early %d:", early->_idx);
5476 dump_idom(early);
5477 tty->cr();
5478 tty->print_cr("idoms of (wrong) LCA %d:", LCA->_idx);
5479 dump_idom(LCA);
5480 tty->cr();
5481 dump_real_LCA(early, LCA);
5482 tty->cr();
5483 }
5484
5485 // Find the real LCA of early and the wrongly assumed LCA.
dump_real_LCA(Node * early,Node * wrong_lca)5486 void PhaseIdealLoop::dump_real_LCA(Node* early, Node* wrong_lca) {
5487 assert(!is_dominator(early, wrong_lca) && !is_dominator(early, wrong_lca),
5488 "sanity check that one node does not dominate the other");
5489 assert(!has_ctrl(early) && !has_ctrl(wrong_lca), "sanity check, no data nodes");
5490
5491 ResourceMark rm;
5492 Node_List nodes_seen;
5493 Node* real_LCA = NULL;
5494 Node* n1 = wrong_lca;
5495 Node* n2 = early;
5496 uint count_1 = 0;
5497 uint count_2 = 0;
5498 // Add early and wrong_lca to simplify calculation of idom indices
5499 nodes_seen.push(n1);
5500 nodes_seen.push(n2);
5501
5502 // Walk the idom chain up from early and wrong_lca and stop when they intersect.
5503 while (!n1->is_Start() && !n2->is_Start()) {
5504 n1 = idom(n1);
5505 n2 = idom(n2);
5506 if (n1 == n2) {
5507 // Both idom chains intersect at the same index
5508 real_LCA = n1;
5509 count_1 = nodes_seen.size() / 2;
5510 count_2 = count_1;
5511 break;
5512 }
5513 if (check_idom_chains_intersection(n1, count_1, count_2, &nodes_seen)) {
5514 real_LCA = n1;
5515 break;
5516 }
5517 if (check_idom_chains_intersection(n2, count_2, count_1, &nodes_seen)) {
5518 real_LCA = n2;
5519 break;
5520 }
5521 nodes_seen.push(n1);
5522 nodes_seen.push(n2);
5523 }
5524
5525 assert(real_LCA != NULL, "must always find an LCA");
5526 tty->print_cr("Real LCA of early %d (idom[%d]) and (wrong) LCA %d (idom[%d]):", early->_idx, count_2, wrong_lca->_idx, count_1);
5527 real_LCA->dump();
5528 }
5529
5530 // Check if n is already on nodes_seen (i.e. idom chains of early and wrong_lca intersect at n). Determine the idom index of n
5531 // on both idom chains and return them in idom_idx_new and idom_idx_other, respectively.
check_idom_chains_intersection(const Node * n,uint & idom_idx_new,uint & idom_idx_other,const Node_List * nodes_seen) const5532 bool PhaseIdealLoop::check_idom_chains_intersection(const Node* n, uint& idom_idx_new, uint& idom_idx_other, const Node_List* nodes_seen) const {
5533 if (nodes_seen->contains(n)) {
5534 // The idom chain has just discovered n.
5535 // Divide by 2 because nodes_seen contains the same amount of nodes from both chains.
5536 idom_idx_new = nodes_seen->size() / 2;
5537
5538 // The other chain already contained n. Search the index.
5539 for (uint i = 0; i < nodes_seen->size(); i++) {
5540 if (nodes_seen->at(i) == n) {
5541 // Divide by 2 because nodes_seen contains the same amount of nodes from both chains.
5542 idom_idx_other = i / 2;
5543 }
5544 }
5545 return true;
5546 }
5547 return false;
5548 }
5549 #endif // ASSERT
5550
5551 #ifndef PRODUCT
5552 //------------------------------dump-------------------------------------------
dump() const5553 void PhaseIdealLoop::dump() const {
5554 ResourceMark rm;
5555 Node_Stack stack(C->live_nodes() >> 2);
5556 Node_List rpo_list;
5557 VectorSet visited;
5558 visited.set(C->top()->_idx);
5559 rpo(C->root(), stack, visited, rpo_list);
5560 // Dump root loop indexed by last element in PO order
5561 dump(_ltree_root, rpo_list.size(), rpo_list);
5562 }
5563
dump(IdealLoopTree * loop,uint idx,Node_List & rpo_list) const5564 void PhaseIdealLoop::dump(IdealLoopTree* loop, uint idx, Node_List &rpo_list) const {
5565 loop->dump_head();
5566
5567 // Now scan for CFG nodes in the same loop
5568 for (uint j = idx; j > 0; j--) {
5569 Node* n = rpo_list[j-1];
5570 if (!_nodes[n->_idx]) // Skip dead nodes
5571 continue;
5572
5573 if (get_loop(n) != loop) { // Wrong loop nest
5574 if (get_loop(n)->_head == n && // Found nested loop?
5575 get_loop(n)->_parent == loop)
5576 dump(get_loop(n), rpo_list.size(), rpo_list); // Print it nested-ly
5577 continue;
5578 }
5579
5580 // Dump controlling node
5581 tty->sp(2 * loop->_nest);
5582 tty->print("C");
5583 if (n == C->root()) {
5584 n->dump();
5585 } else {
5586 Node* cached_idom = idom_no_update(n);
5587 Node* computed_idom = n->in(0);
5588 if (n->is_Region()) {
5589 computed_idom = compute_idom(n);
5590 // computed_idom() will return n->in(0) when idom(n) is an IfNode (or
5591 // any MultiBranch ctrl node), so apply a similar transform to
5592 // the cached idom returned from idom_no_update.
5593 cached_idom = find_non_split_ctrl(cached_idom);
5594 }
5595 tty->print(" ID:%d", computed_idom->_idx);
5596 n->dump();
5597 if (cached_idom != computed_idom) {
5598 tty->print_cr("*** BROKEN IDOM! Computed as: %d, cached as: %d",
5599 computed_idom->_idx, cached_idom->_idx);
5600 }
5601 }
5602 // Dump nodes it controls
5603 for (uint k = 0; k < _nodes.Size(); k++) {
5604 // (k < C->unique() && get_ctrl(find(k)) == n)
5605 if (k < C->unique() && _nodes[k] == (Node*)((intptr_t)n + 1)) {
5606 Node* m = C->root()->find(k);
5607 if (m && m->outcnt() > 0) {
5608 if (!(has_ctrl(m) && get_ctrl_no_update(m) == n)) {
5609 tty->print_cr("*** BROKEN CTRL ACCESSOR! _nodes[k] is %p, ctrl is %p",
5610 _nodes[k], has_ctrl(m) ? get_ctrl_no_update(m) : NULL);
5611 }
5612 tty->sp(2 * loop->_nest + 1);
5613 m->dump();
5614 }
5615 }
5616 }
5617 }
5618 }
5619
dump_idom(Node * n) const5620 void PhaseIdealLoop::dump_idom(Node* n) const {
5621 if (has_ctrl(n)) {
5622 tty->print_cr("No idom for data nodes");
5623 } else {
5624 for (int i = 0; i < 100 && !n->is_Start(); i++) {
5625 tty->print("idom[%d] ", i);
5626 n->dump();
5627 n = idom(n);
5628 }
5629 }
5630 }
5631 #endif // NOT PRODUCT
5632
5633 // Collect a R-P-O for the whole CFG.
5634 // Result list is in post-order (scan backwards for RPO)
rpo(Node * start,Node_Stack & stk,VectorSet & visited,Node_List & rpo_list) const5635 void PhaseIdealLoop::rpo(Node* start, Node_Stack &stk, VectorSet &visited, Node_List &rpo_list) const {
5636 stk.push(start, 0);
5637 visited.set(start->_idx);
5638
5639 while (stk.is_nonempty()) {
5640 Node* m = stk.node();
5641 uint idx = stk.index();
5642 if (idx < m->outcnt()) {
5643 stk.set_index(idx + 1);
5644 Node* n = m->raw_out(idx);
5645 if (n->is_CFG() && !visited.test_set(n->_idx)) {
5646 stk.push(n, 0);
5647 }
5648 } else {
5649 rpo_list.push(m);
5650 stk.pop();
5651 }
5652 }
5653 }
5654
5655
5656 //=============================================================================
5657 //------------------------------LoopTreeIterator-------------------------------
5658
5659 // Advance to next loop tree using a preorder, left-to-right traversal.
next()5660 void LoopTreeIterator::next() {
5661 assert(!done(), "must not be done.");
5662 if (_curnt->_child != NULL) {
5663 _curnt = _curnt->_child;
5664 } else if (_curnt->_next != NULL) {
5665 _curnt = _curnt->_next;
5666 } else {
5667 while (_curnt != _root && _curnt->_next == NULL) {
5668 _curnt = _curnt->_parent;
5669 }
5670 if (_curnt == _root) {
5671 _curnt = NULL;
5672 assert(done(), "must be done.");
5673 } else {
5674 assert(_curnt->_next != NULL, "must be more to do");
5675 _curnt = _curnt->_next;
5676 }
5677 }
5678 }
5679