1 /*
2  * Copyright (c) 2000, 2021, 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 "compiler/compileLog.hpp"
27 #include "memory/allocation.inline.hpp"
28 #include "opto/addnode.hpp"
29 #include "opto/callnode.hpp"
30 #include "opto/castnode.hpp"
31 #include "opto/connode.hpp"
32 #include "opto/convertnode.hpp"
33 #include "opto/divnode.hpp"
34 #include "opto/loopnode.hpp"
35 #include "opto/mulnode.hpp"
36 #include "opto/movenode.hpp"
37 #include "opto/opaquenode.hpp"
38 #include "opto/rootnode.hpp"
39 #include "opto/runtime.hpp"
40 #include "opto/subnode.hpp"
41 #include "opto/superword.hpp"
42 #include "opto/vectornode.hpp"
43 #include "runtime/globals_extension.hpp"
44 
45 //------------------------------is_loop_exit-----------------------------------
46 // Given an IfNode, return the loop-exiting projection or NULL if both
47 // arms remain in the loop.
is_loop_exit(Node * iff) const48 Node *IdealLoopTree::is_loop_exit(Node *iff) const {
49   if (iff->outcnt() != 2) return NULL;  // Ignore partially dead tests
50   PhaseIdealLoop *phase = _phase;
51   // Test is an IfNode, has 2 projections.  If BOTH are in the loop
52   // we need loop unswitching instead of peeling.
53   if (!is_member(phase->get_loop(iff->raw_out(0))))
54     return iff->raw_out(0);
55   if (!is_member(phase->get_loop(iff->raw_out(1))))
56     return iff->raw_out(1);
57   return NULL;
58 }
59 
60 
61 //=============================================================================
62 
63 
64 //------------------------------record_for_igvn----------------------------
65 // Put loop body on igvn work list
record_for_igvn()66 void IdealLoopTree::record_for_igvn() {
67   for (uint i = 0; i < _body.size(); i++) {
68     Node *n = _body.at(i);
69     _phase->_igvn._worklist.push(n);
70   }
71   // put body of outer strip mined loop on igvn work list as well
72   if (_head->is_CountedLoop() && _head->as_Loop()->is_strip_mined()) {
73     CountedLoopNode* l = _head->as_CountedLoop();
74     Node* outer_loop = l->outer_loop();
75     assert(outer_loop != NULL, "missing piece of strip mined loop");
76     _phase->_igvn._worklist.push(outer_loop);
77     Node* outer_loop_tail = l->outer_loop_tail();
78     assert(outer_loop_tail != NULL, "missing piece of strip mined loop");
79     _phase->_igvn._worklist.push(outer_loop_tail);
80     Node* outer_loop_end = l->outer_loop_end();
81     assert(outer_loop_end != NULL, "missing piece of strip mined loop");
82     _phase->_igvn._worklist.push(outer_loop_end);
83     Node* outer_safepoint = l->outer_safepoint();
84     assert(outer_safepoint != NULL, "missing piece of strip mined loop");
85     _phase->_igvn._worklist.push(outer_safepoint);
86     Node* cle_out = _head->as_CountedLoop()->loopexit()->proj_out(false);
87     assert(cle_out != NULL, "missing piece of strip mined loop");
88     _phase->_igvn._worklist.push(cle_out);
89   }
90 }
91 
92 //------------------------------compute_exact_trip_count-----------------------
93 // Compute loop trip count if possible. Do not recalculate trip count for
94 // split loops (pre-main-post) which have their limits and inits behind Opaque node.
compute_trip_count(PhaseIdealLoop * phase)95 void IdealLoopTree::compute_trip_count(PhaseIdealLoop* phase) {
96   if (!_head->as_Loop()->is_valid_counted_loop(T_INT)) {
97     return;
98   }
99   CountedLoopNode* cl = _head->as_CountedLoop();
100   // Trip count may become nonexact for iteration split loops since
101   // RCE modifies limits. Note, _trip_count value is not reset since
102   // it is used to limit unrolling of main loop.
103   cl->set_nonexact_trip_count();
104 
105   // Loop's test should be part of loop.
106   if (!phase->is_member(this, phase->get_ctrl(cl->loopexit()->in(CountedLoopEndNode::TestValue))))
107     return; // Infinite loop
108 
109 #ifdef ASSERT
110   BoolTest::mask bt = cl->loopexit()->test_trip();
111   assert(bt == BoolTest::lt || bt == BoolTest::gt ||
112          bt == BoolTest::ne, "canonical test is expected");
113 #endif
114 
115   Node* init_n = cl->init_trip();
116   Node* limit_n = cl->limit();
117   if (init_n != NULL && limit_n != NULL) {
118     // Use longs to avoid integer overflow.
119     int stride_con = cl->stride_con();
120     const TypeInt* init_type = phase->_igvn.type(init_n)->is_int();
121     const TypeInt* limit_type = phase->_igvn.type(limit_n)->is_int();
122     jlong init_con = (stride_con > 0) ? init_type->_lo : init_type->_hi;
123     jlong limit_con = (stride_con > 0) ? limit_type->_hi : limit_type->_lo;
124     int stride_m = stride_con - (stride_con > 0 ? 1 : -1);
125     jlong trip_count = (limit_con - init_con + stride_m)/stride_con;
126     if (trip_count > 0 && (julong)trip_count < (julong)max_juint) {
127       if (init_n->is_Con() && limit_n->is_Con()) {
128         // Set exact trip count.
129         cl->set_exact_trip_count((uint)trip_count);
130       } else if (cl->unrolled_count() == 1) {
131         // Set maximum trip count before unrolling.
132         cl->set_trip_count((uint)trip_count);
133       }
134     }
135   }
136 }
137 
138 //------------------------------compute_profile_trip_cnt----------------------------
139 // Compute loop trip count from profile data as
140 //    (backedge_count + loop_exit_count) / loop_exit_count
141 
compute_profile_trip_cnt_helper(Node * n)142 float IdealLoopTree::compute_profile_trip_cnt_helper(Node* n) {
143   if (n->is_If()) {
144     IfNode *iff = n->as_If();
145     if (iff->_fcnt != COUNT_UNKNOWN && iff->_prob != PROB_UNKNOWN) {
146       Node *exit = is_loop_exit(iff);
147       if (exit) {
148         float exit_prob = iff->_prob;
149         if (exit->Opcode() == Op_IfFalse) {
150           exit_prob = 1.0 - exit_prob;
151         }
152         if (exit_prob > PROB_MIN) {
153           float exit_cnt = iff->_fcnt * exit_prob;
154           return exit_cnt;
155         }
156       }
157     }
158   }
159   if (n->is_Jump()) {
160     JumpNode *jmp = n->as_Jump();
161     if (jmp->_fcnt != COUNT_UNKNOWN) {
162       float* probs = jmp->_probs;
163       float exit_prob = 0;
164       PhaseIdealLoop *phase = _phase;
165       for (DUIterator_Fast imax, i = jmp->fast_outs(imax); i < imax; i++) {
166         JumpProjNode* u = jmp->fast_out(i)->as_JumpProj();
167         if (!is_member(_phase->get_loop(u))) {
168           exit_prob += probs[u->_con];
169         }
170       }
171       return exit_prob * jmp->_fcnt;
172     }
173   }
174   return 0;
175 }
176 
compute_profile_trip_cnt(PhaseIdealLoop * phase)177 void IdealLoopTree::compute_profile_trip_cnt(PhaseIdealLoop *phase) {
178   if (!_head->is_Loop()) {
179     return;
180   }
181   LoopNode* head = _head->as_Loop();
182   if (head->profile_trip_cnt() != COUNT_UNKNOWN) {
183     return; // Already computed
184   }
185   float trip_cnt = (float)max_jint; // default is big
186 
187   Node* back = head->in(LoopNode::LoopBackControl);
188   while (back != head) {
189     if ((back->Opcode() == Op_IfTrue || back->Opcode() == Op_IfFalse) &&
190         back->in(0) &&
191         back->in(0)->is_If() &&
192         back->in(0)->as_If()->_fcnt != COUNT_UNKNOWN &&
193         back->in(0)->as_If()->_prob != PROB_UNKNOWN &&
194         (back->Opcode() == Op_IfTrue ? 1-back->in(0)->as_If()->_prob : back->in(0)->as_If()->_prob) > PROB_MIN) {
195       break;
196     }
197     back = phase->idom(back);
198   }
199   if (back != head) {
200     assert((back->Opcode() == Op_IfTrue || back->Opcode() == Op_IfFalse) &&
201            back->in(0), "if-projection exists");
202     IfNode* back_if = back->in(0)->as_If();
203     float loop_back_cnt = back_if->_fcnt * (back->Opcode() == Op_IfTrue ? back_if->_prob : (1 - back_if->_prob));
204 
205     // Now compute a loop exit count
206     float loop_exit_cnt = 0.0f;
207     if (_child == NULL) {
208       for (uint i = 0; i < _body.size(); i++) {
209         Node *n = _body[i];
210         loop_exit_cnt += compute_profile_trip_cnt_helper(n);
211       }
212     } else {
213       ResourceMark rm;
214       Unique_Node_List wq;
215       wq.push(back);
216       for (uint i = 0; i < wq.size(); i++) {
217         Node *n = wq.at(i);
218         assert(n->is_CFG(), "only control nodes");
219         if (n != head) {
220           if (n->is_Region()) {
221             for (uint j = 1; j < n->req(); j++) {
222               wq.push(n->in(j));
223             }
224           } else {
225             loop_exit_cnt += compute_profile_trip_cnt_helper(n);
226             wq.push(n->in(0));
227           }
228         }
229       }
230 
231     }
232     if (loop_exit_cnt > 0.0f) {
233       trip_cnt = (loop_back_cnt + loop_exit_cnt) / loop_exit_cnt;
234     } else {
235       // No exit count so use
236       trip_cnt = loop_back_cnt;
237     }
238   } else {
239     head->mark_profile_trip_failed();
240   }
241 #ifndef PRODUCT
242   if (TraceProfileTripCount) {
243     tty->print_cr("compute_profile_trip_cnt  lp: %d cnt: %f\n", head->_idx, trip_cnt);
244   }
245 #endif
246   head->set_profile_trip_cnt(trip_cnt);
247 }
248 
249 //---------------------find_invariant-----------------------------
250 // Return nonzero index of invariant operand for an associative
251 // binary operation of (nonconstant) invariant and variant values.
252 // Helper for reassociate_invariants.
find_invariant(Node * n,PhaseIdealLoop * phase)253 int IdealLoopTree::find_invariant(Node* n, PhaseIdealLoop *phase) {
254   bool in1_invar = this->is_invariant(n->in(1));
255   bool in2_invar = this->is_invariant(n->in(2));
256   if (in1_invar && !in2_invar) return 1;
257   if (!in1_invar && in2_invar) return 2;
258   return 0;
259 }
260 
261 //---------------------is_associative-----------------------------
262 // Return TRUE if "n" is an associative binary node. If "base" is
263 // not NULL, "n" must be re-associative with it.
is_associative(Node * n,Node * base)264 bool IdealLoopTree::is_associative(Node* n, Node* base) {
265   int op = n->Opcode();
266   if (base != NULL) {
267     assert(is_associative(base), "Base node should be associative");
268     int base_op = base->Opcode();
269     if (base_op == Op_AddI || base_op == Op_SubI) {
270       return op == Op_AddI || op == Op_SubI;
271     }
272     if (base_op == Op_AddL || base_op == Op_SubL) {
273       return op == Op_AddL || op == Op_SubL;
274     }
275     return op == base_op;
276   } else {
277     // Integer "add/sub/mul/and/or/xor" operations are associative.
278     return op == Op_AddI || op == Op_AddL
279         || op == Op_SubI || op == Op_SubL
280         || op == Op_MulI || op == Op_MulL
281         || op == Op_AndI || op == Op_AndL
282         || op == Op_OrI  || op == Op_OrL
283         || op == Op_XorI || op == Op_XorL;
284   }
285 }
286 
287 //---------------------reassociate_add_sub------------------------
288 // Reassociate invariant add and subtract expressions:
289 //
290 // inv1 + (x + inv2)  =>  ( inv1 + inv2) + x
291 // (x + inv2) + inv1  =>  ( inv1 + inv2) + x
292 // inv1 + (x - inv2)  =>  ( inv1 - inv2) + x
293 // inv1 - (inv2 - x)  =>  ( inv1 - inv2) + x
294 // (x + inv2) - inv1  =>  (-inv1 + inv2) + x
295 // (x - inv2) + inv1  =>  ( inv1 - inv2) + x
296 // (x - inv2) - inv1  =>  (-inv1 - inv2) + x
297 // inv1 + (inv2 - x)  =>  ( inv1 + inv2) - x
298 // inv1 - (x - inv2)  =>  ( inv1 + inv2) - x
299 // (inv2 - x) + inv1  =>  ( inv1 + inv2) - x
300 // (inv2 - x) - inv1  =>  (-inv1 + inv2) - x
301 // inv1 - (x + inv2)  =>  ( inv1 - inv2) - x
302 //
reassociate_add_sub(Node * n1,int inv1_idx,int inv2_idx,PhaseIdealLoop * phase)303 Node* IdealLoopTree::reassociate_add_sub(Node* n1, int inv1_idx, int inv2_idx, PhaseIdealLoop *phase) {
304   assert(n1->is_Add() || n1->is_Sub(), "Target node should be add or subtract");
305   Node* n2   = n1->in(3 - inv1_idx);
306   Node* inv1 = n1->in(inv1_idx);
307   Node* inv2 = n2->in(inv2_idx);
308   Node* x    = n2->in(3 - inv2_idx);
309 
310   bool neg_x    = n2->is_Sub() && inv2_idx == 1;
311   bool neg_inv2 = n2->is_Sub() && inv2_idx == 2;
312   bool neg_inv1 = n1->is_Sub() && inv1_idx == 2;
313   if (n1->is_Sub() && inv1_idx == 1) {
314     neg_x    = !neg_x;
315     neg_inv2 = !neg_inv2;
316   }
317 
318   bool is_int = n1->bottom_type()->isa_int() != NULL;
319   Node* inv1_c = phase->get_ctrl(inv1);
320   Node* n_inv1;
321   if (neg_inv1) {
322     Node* zero;
323     if (is_int) {
324       zero = phase->_igvn.intcon(0);
325       n_inv1 = new SubINode(zero, inv1);
326     } else {
327       zero = phase->_igvn.longcon(0L);
328       n_inv1 = new SubLNode(zero, inv1);
329     }
330     phase->set_ctrl(zero, phase->C->root());
331     phase->register_new_node(n_inv1, inv1_c);
332   } else {
333     n_inv1 = inv1;
334   }
335 
336   Node* inv;
337   if (is_int) {
338     if (neg_inv2) {
339       inv = new SubINode(n_inv1, inv2);
340     } else {
341       inv = new AddINode(n_inv1, inv2);
342     }
343     phase->register_new_node(inv, phase->get_early_ctrl(inv));
344     if (neg_x) {
345       return new SubINode(inv, x);
346     } else {
347       return new AddINode(x, inv);
348     }
349   } else {
350     if (neg_inv2) {
351       inv = new SubLNode(n_inv1, inv2);
352     } else {
353       inv = new AddLNode(n_inv1, inv2);
354     }
355     phase->register_new_node(inv, phase->get_early_ctrl(inv));
356     if (neg_x) {
357       return new SubLNode(inv, x);
358     } else {
359       return new AddLNode(x, inv);
360     }
361   }
362 }
363 
364 //---------------------reassociate-----------------------------
365 // Reassociate invariant binary expressions with add/sub/mul/
366 // and/or/xor operators.
367 // For add/sub expressions: see "reassociate_add_sub"
368 //
369 // For mul/and/or/xor expressions:
370 //
371 // inv1 op (x op inv2) => (inv1 op inv2) op x
372 //
reassociate(Node * n1,PhaseIdealLoop * phase)373 Node* IdealLoopTree::reassociate(Node* n1, PhaseIdealLoop *phase) {
374   if (!is_associative(n1) || n1->outcnt() == 0) return NULL;
375   if (is_invariant(n1)) return NULL;
376   // Don't mess with add of constant (igvn moves them to expression tree root.)
377   if (n1->is_Add() && n1->in(2)->is_Con()) return NULL;
378 
379   int inv1_idx = find_invariant(n1, phase);
380   if (!inv1_idx) return NULL;
381   Node* n2 = n1->in(3 - inv1_idx);
382   if (!is_associative(n2, n1)) return NULL;
383   int inv2_idx = find_invariant(n2, phase);
384   if (!inv2_idx) return NULL;
385 
386   if (!phase->may_require_nodes(10, 10)) return NULL;
387 
388   Node* result = NULL;
389   switch (n1->Opcode()) {
390     case Op_AddI:
391     case Op_AddL:
392     case Op_SubI:
393     case Op_SubL:
394       result = reassociate_add_sub(n1, inv1_idx, inv2_idx, phase);
395       break;
396     case Op_MulI:
397     case Op_MulL:
398     case Op_AndI:
399     case Op_AndL:
400     case Op_OrI:
401     case Op_OrL:
402     case Op_XorI:
403     case Op_XorL: {
404       Node* inv1 = n1->in(inv1_idx);
405       Node* inv2 = n2->in(inv2_idx);
406       Node* x    = n2->in(3 - inv2_idx);
407       Node* inv  = n2->clone_with_data_edge(inv1, inv2);
408       phase->register_new_node(inv, phase->get_early_ctrl(inv));
409       result = n1->clone_with_data_edge(x, inv);
410       break;
411     }
412     default:
413       ShouldNotReachHere();
414   }
415 
416   assert(result != NULL, "");
417   phase->register_new_node(result, phase->get_ctrl(n1));
418   phase->_igvn.replace_node(n1, result);
419   assert(phase->get_loop(phase->get_ctrl(n1)) == this, "");
420   _body.yank(n1);
421   return result;
422 }
423 
424 //---------------------reassociate_invariants-----------------------------
425 // Reassociate invariant expressions:
reassociate_invariants(PhaseIdealLoop * phase)426 void IdealLoopTree::reassociate_invariants(PhaseIdealLoop *phase) {
427   for (int i = _body.size() - 1; i >= 0; i--) {
428     Node *n = _body.at(i);
429     for (int j = 0; j < 5; j++) {
430       Node* nn = reassociate(n, phase);
431       if (nn == NULL) break;
432       n = nn; // again
433     }
434   }
435 }
436 
437 //------------------------------policy_peeling---------------------------------
438 // Return TRUE if the loop should be peeled, otherwise return FALSE. Peeling
439 // is applicable if we can make a loop-invariant test (usually a null-check)
440 // execute before we enter the loop. When TRUE, the estimated node budget is
441 // also requested.
policy_peeling(PhaseIdealLoop * phase)442 bool IdealLoopTree::policy_peeling(PhaseIdealLoop *phase) {
443   uint estimate = estimate_peeling(phase);
444 
445   return estimate == 0 ? false : phase->may_require_nodes(estimate);
446 }
447 
448 // Perform actual policy and size estimate for the loop peeling transform, and
449 // return the estimated loop size if peeling is applicable, otherwise return
450 // zero. No node budget is allocated.
estimate_peeling(PhaseIdealLoop * phase)451 uint IdealLoopTree::estimate_peeling(PhaseIdealLoop *phase) {
452 
453   // If nodes are depleted, some transform has miscalculated its needs.
454   assert(!phase->exceeding_node_budget(), "sanity");
455 
456   // Peeling does loop cloning which can result in O(N^2) node construction.
457   if (_body.size() > 255) {
458     return 0;   // Suppress too large body size.
459   }
460   // Optimistic estimate that approximates loop body complexity via data and
461   // control flow fan-out (instead of using the more pessimistic: BodySize^2).
462   uint estimate = est_loop_clone_sz(2);
463 
464   if (phase->exceeding_node_budget(estimate)) {
465     return 0;   // Too large to safely clone.
466   }
467 
468   // Check for vectorized loops, any peeling done was already applied.
469   if (_head->is_CountedLoop()) {
470     CountedLoopNode* cl = _head->as_CountedLoop();
471     if (cl->is_unroll_only() || cl->trip_count() == 1) {
472       return 0;
473     }
474   }
475 
476   Node* test = tail();
477 
478   while (test != _head) {   // Scan till run off top of loop
479     if (test->is_If()) {    // Test?
480       Node *ctrl = phase->get_ctrl(test->in(1));
481       if (ctrl->is_top()) {
482         return 0;           // Found dead test on live IF?  No peeling!
483       }
484       // Standard IF only has one input value to check for loop invariance.
485       assert(test->Opcode() == Op_If ||
486              test->Opcode() == Op_CountedLoopEnd ||
487              test->Opcode() == Op_LongCountedLoopEnd ||
488              test->Opcode() == Op_RangeCheck,
489              "Check this code when new subtype is added");
490       // Condition is not a member of this loop?
491       if (!is_member(phase->get_loop(ctrl)) && is_loop_exit(test)) {
492         return estimate;    // Found reason to peel!
493       }
494     }
495     // Walk up dominators to loop _head looking for test which is executed on
496     // every path through the loop.
497     test = phase->idom(test);
498   }
499   return 0;
500 }
501 
502 //------------------------------peeled_dom_test_elim---------------------------
503 // If we got the effect of peeling, either by actually peeling or by making
504 // a pre-loop which must execute at least once, we can remove all
505 // loop-invariant dominated tests in the main body.
peeled_dom_test_elim(IdealLoopTree * loop,Node_List & old_new)506 void PhaseIdealLoop::peeled_dom_test_elim(IdealLoopTree *loop, Node_List &old_new) {
507   bool progress = true;
508   while (progress) {
509     progress = false;           // Reset for next iteration
510     Node *prev = loop->_head->in(LoopNode::LoopBackControl);//loop->tail();
511     Node *test = prev->in(0);
512     while (test != loop->_head) { // Scan till run off top of loop
513 
514       int p_op = prev->Opcode();
515       if ((p_op == Op_IfFalse || p_op == Op_IfTrue) &&
516           test->is_If() &&      // Test?
517           !test->in(1)->is_Con() && // And not already obvious?
518           // Condition is not a member of this loop?
519           !loop->is_member(get_loop(get_ctrl(test->in(1))))){
520         // Walk loop body looking for instances of this test
521         for (uint i = 0; i < loop->_body.size(); i++) {
522           Node *n = loop->_body.at(i);
523           if (n->is_If() && n->in(1) == test->in(1) /*&& n != loop->tail()->in(0)*/) {
524             // IfNode was dominated by version in peeled loop body
525             progress = true;
526             dominated_by(old_new[prev->_idx], n);
527           }
528         }
529       }
530       prev = test;
531       test = idom(test);
532     } // End of scan tests in loop
533 
534   } // End of while (progress)
535 }
536 
537 //------------------------------do_peeling-------------------------------------
538 // Peel the first iteration of the given loop.
539 // Step 1: Clone the loop body.  The clone becomes the peeled iteration.
540 //         The pre-loop illegally has 2 control users (old & new loops).
541 // Step 2: Make the old-loop fall-in edges point to the peeled iteration.
542 //         Do this by making the old-loop fall-in edges act as if they came
543 //         around the loopback from the prior iteration (follow the old-loop
544 //         backedges) and then map to the new peeled iteration.  This leaves
545 //         the pre-loop with only 1 user (the new peeled iteration), but the
546 //         peeled-loop backedge has 2 users.
547 // Step 3: Cut the backedge on the clone (so its not a loop) and remove the
548 //         extra backedge user.
549 //
550 //                   orig
551 //
552 //                  stmt1
553 //                    |
554 //                    v
555 //              loop predicate
556 //                    |
557 //                    v
558 //                   loop<----+
559 //                     |      |
560 //                   stmt2    |
561 //                     |      |
562 //                     v      |
563 //                    if      ^
564 //                   / \      |
565 //                  /   \     |
566 //                 v     v    |
567 //               false true   |
568 //               /       \    |
569 //              /         ----+
570 //             |
571 //             v
572 //           exit
573 //
574 //
575 //            after clone loop
576 //
577 //                   stmt1
578 //                     |
579 //                     v
580 //               loop predicate
581 //                 /       \
582 //        clone   /         \   orig
583 //               /           \
584 //              /             \
585 //             v               v
586 //   +---->loop clone          loop<----+
587 //   |      |                    |      |
588 //   |    stmt2 clone          stmt2    |
589 //   |      |                    |      |
590 //   |      v                    v      |
591 //   ^      if clone            If      ^
592 //   |      / \                / \      |
593 //   |     /   \              /   \     |
594 //   |    v     v            v     v    |
595 //   |    true  false      false true   |
596 //   |    /         \      /       \    |
597 //   +----           \    /         ----+
598 //                    \  /
599 //                    1v v2
600 //                  region
601 //                     |
602 //                     v
603 //                   exit
604 //
605 //
606 //         after peel and predicate move
607 //
608 //                   stmt1
609 //                    /
610 //                   /
611 //        clone     /            orig
612 //                 /
613 //                /              +----------+
614 //               /               |          |
615 //              /          loop predicate   |
616 //             /                 |          |
617 //            v                  v          |
618 //   TOP-->loop clone          loop<----+   |
619 //          |                    |      |   |
620 //        stmt2 clone          stmt2    |   |
621 //          |                    |      |   ^
622 //          v                    v      |   |
623 //          if clone            If      ^   |
624 //          / \                / \      |   |
625 //         /   \              /   \     |   |
626 //        v     v            v     v    |   |
627 //      true   false      false  true   |   |
628 //        |         \      /       \    |   |
629 //        |          \    /         ----+   ^
630 //        |           \  /                  |
631 //        |           1v v2                 |
632 //        v         region                  |
633 //        |            |                    |
634 //        |            v                    |
635 //        |          exit                   |
636 //        |                                 |
637 //        +--------------->-----------------+
638 //
639 //
640 //              final graph
641 //
642 //                  stmt1
643 //                    |
644 //                    v
645 //                  stmt2 clone
646 //                    |
647 //                    v
648 //                   if clone
649 //                  / |
650 //                 /  |
651 //                v   v
652 //            false  true
653 //             |      |
654 //             |      v
655 //             | loop predicate
656 //             |      |
657 //             |      v
658 //             |     loop<----+
659 //             |      |       |
660 //             |    stmt2     |
661 //             |      |       |
662 //             |      v       |
663 //             v      if      ^
664 //             |     /  \     |
665 //             |    /    \    |
666 //             |   v     v    |
667 //             | false  true  |
668 //             |  |        \  |
669 //             v  v         --+
670 //            region
671 //              |
672 //              v
673 //             exit
674 //
do_peeling(IdealLoopTree * loop,Node_List & old_new)675 void PhaseIdealLoop::do_peeling(IdealLoopTree *loop, Node_List &old_new) {
676 
677   C->set_major_progress();
678   // Peeling a 'main' loop in a pre/main/post situation obfuscates the
679   // 'pre' loop from the main and the 'pre' can no longer have its
680   // iterations adjusted.  Therefore, we need to declare this loop as
681   // no longer a 'main' loop; it will need new pre and post loops before
682   // we can do further RCE.
683 #ifndef PRODUCT
684   if (TraceLoopOpts) {
685     tty->print("Peel         ");
686     loop->dump_head();
687   }
688 #endif
689   LoopNode* head = loop->_head->as_Loop();
690   bool counted_loop = head->is_CountedLoop();
691   if (counted_loop) {
692     CountedLoopNode *cl = head->as_CountedLoop();
693     assert(cl->trip_count() > 0, "peeling a fully unrolled loop");
694     cl->set_trip_count(cl->trip_count() - 1);
695     if (cl->is_main_loop()) {
696       cl->set_normal_loop();
697 #ifndef PRODUCT
698       if (PrintOpto && VerifyLoopOptimizations) {
699         tty->print("Peeling a 'main' loop; resetting to 'normal' ");
700         loop->dump_head();
701       }
702 #endif
703     }
704   }
705   Node* entry = head->in(LoopNode::EntryControl);
706 
707   // Step 1: Clone the loop body.  The clone becomes the peeled iteration.
708   //         The pre-loop illegally has 2 control users (old & new loops).
709   clone_loop(loop, old_new, dom_depth(head->skip_strip_mined()), ControlAroundStripMined);
710 
711   // Step 2: Make the old-loop fall-in edges point to the peeled iteration.
712   //         Do this by making the old-loop fall-in edges act as if they came
713   //         around the loopback from the prior iteration (follow the old-loop
714   //         backedges) and then map to the new peeled iteration.  This leaves
715   //         the pre-loop with only 1 user (the new peeled iteration), but the
716   //         peeled-loop backedge has 2 users.
717   Node* new_entry = old_new[head->in(LoopNode::LoopBackControl)->_idx];
718   _igvn.hash_delete(head->skip_strip_mined());
719   head->skip_strip_mined()->set_req(LoopNode::EntryControl, new_entry);
720   for (DUIterator_Fast jmax, j = head->fast_outs(jmax); j < jmax; j++) {
721     Node* old = head->fast_out(j);
722     if (old->in(0) == loop->_head && old->req() == 3 && old->is_Phi()) {
723       Node* new_exit_value = old_new[old->in(LoopNode::LoopBackControl)->_idx];
724       if (!new_exit_value)     // Backedge value is ALSO loop invariant?
725         // Then loop body backedge value remains the same.
726         new_exit_value = old->in(LoopNode::LoopBackControl);
727       _igvn.hash_delete(old);
728       old->set_req(LoopNode::EntryControl, new_exit_value);
729     }
730   }
731 
732 
733   // Step 3: Cut the backedge on the clone (so its not a loop) and remove the
734   //         extra backedge user.
735   Node* new_head = old_new[head->_idx];
736   _igvn.hash_delete(new_head);
737   new_head->set_req(LoopNode::LoopBackControl, C->top());
738   for (DUIterator_Fast j2max, j2 = new_head->fast_outs(j2max); j2 < j2max; j2++) {
739     Node* use = new_head->fast_out(j2);
740     if (use->in(0) == new_head && use->req() == 3 && use->is_Phi()) {
741       _igvn.hash_delete(use);
742       use->set_req(LoopNode::LoopBackControl, C->top());
743     }
744   }
745 
746   // Step 4: Correct dom-depth info.  Set to loop-head depth.
747 
748   int dd = dom_depth(head->skip_strip_mined());
749   set_idom(head->skip_strip_mined(), head->skip_strip_mined()->in(LoopNode::EntryControl), dd);
750   for (uint j3 = 0; j3 < loop->_body.size(); j3++) {
751     Node *old = loop->_body.at(j3);
752     Node *nnn = old_new[old->_idx];
753     if (!has_ctrl(nnn)) {
754       set_idom(nnn, idom(nnn), dd-1);
755     }
756   }
757 
758   // Now force out all loop-invariant dominating tests.  The optimizer
759   // finds some, but we _know_ they are all useless.
760   peeled_dom_test_elim(loop,old_new);
761 
762   loop->record_for_igvn();
763 }
764 
765 //------------------------------policy_maximally_unroll------------------------
766 // Calculate the exact  loop trip-count and return TRUE if loop can be fully,
767 // i.e. maximally, unrolled, otherwise return FALSE. When TRUE, the estimated
768 // node budget is also requested.
policy_maximally_unroll(PhaseIdealLoop * phase) const769 bool IdealLoopTree::policy_maximally_unroll(PhaseIdealLoop* phase) const {
770   CountedLoopNode* cl = _head->as_CountedLoop();
771   assert(cl->is_normal_loop(), "");
772   if (!cl->is_valid_counted_loop(T_INT)) {
773     return false;   // Malformed counted loop.
774   }
775   if (!cl->has_exact_trip_count()) {
776     return false;   // Trip count is not exact.
777   }
778 
779   uint trip_count = cl->trip_count();
780   // Note, max_juint is used to indicate unknown trip count.
781   assert(trip_count > 1, "one iteration loop should be optimized out already");
782   assert(trip_count < max_juint, "exact trip_count should be less than max_juint.");
783 
784   // If nodes are depleted, some transform has miscalculated its needs.
785   assert(!phase->exceeding_node_budget(), "sanity");
786 
787   // Allow the unrolled body to get larger than the standard loop size limit.
788   uint unroll_limit = (uint)LoopUnrollLimit * 4;
789   assert((intx)unroll_limit == LoopUnrollLimit * 4, "LoopUnrollLimit must fit in 32bits");
790   if (trip_count > unroll_limit || _body.size() > unroll_limit) {
791     return false;
792   }
793 
794   uint new_body_size = est_loop_unroll_sz(trip_count);
795 
796   if (new_body_size == UINT_MAX) { // Check for bad estimate (overflow).
797     return false;
798   }
799 
800   // Fully unroll a loop with few iterations, regardless of other conditions,
801   // since the following (general) loop optimizations will split such loop in
802   // any case (into pre-main-post).
803   if (trip_count <= 3) {
804     return phase->may_require_nodes(new_body_size);
805   }
806 
807   // Reject if unrolling will result in too much node construction.
808   if (new_body_size > unroll_limit || phase->exceeding_node_budget(new_body_size)) {
809     return false;
810   }
811 
812   // Do not unroll a loop with String intrinsics code.
813   // String intrinsics are large and have loops.
814   for (uint k = 0; k < _body.size(); k++) {
815     Node* n = _body.at(k);
816     switch (n->Opcode()) {
817       case Op_StrComp:
818       case Op_StrEquals:
819       case Op_StrIndexOf:
820       case Op_StrIndexOfChar:
821       case Op_EncodeISOArray:
822       case Op_AryEq:
823       case Op_HasNegatives: {
824         return false;
825       }
826 #if INCLUDE_RTM_OPT
827       case Op_FastLock:
828       case Op_FastUnlock: {
829         // Don't unroll RTM locking code because it is large.
830         if (UseRTMLocking) {
831           return false;
832         }
833       }
834 #endif
835     } // switch
836   }
837 
838   return phase->may_require_nodes(new_body_size);
839 }
840 
841 
842 //------------------------------policy_unroll----------------------------------
843 // Return TRUE or FALSE if the loop should be unrolled or not. Apply unroll if
844 // the loop is  a counted loop and  the loop body is small  enough. When TRUE,
845 // the estimated node budget is also requested.
policy_unroll(PhaseIdealLoop * phase)846 bool IdealLoopTree::policy_unroll(PhaseIdealLoop *phase) {
847 
848   CountedLoopNode *cl = _head->as_CountedLoop();
849   assert(cl->is_normal_loop() || cl->is_main_loop(), "");
850 
851   if (!cl->is_valid_counted_loop(T_INT)) {
852     return false; // Malformed counted loop
853   }
854 
855   // If nodes are depleted, some transform has miscalculated its needs.
856   assert(!phase->exceeding_node_budget(), "sanity");
857 
858   // Protect against over-unrolling.
859   // After split at least one iteration will be executed in pre-loop.
860   if (cl->trip_count() <= (cl->is_normal_loop() ? 2u : 1u)) {
861     return false;
862   }
863   _local_loop_unroll_limit  = LoopUnrollLimit;
864   _local_loop_unroll_factor = 4;
865   int future_unroll_cnt = cl->unrolled_count() * 2;
866   if (!cl->is_vectorized_loop()) {
867     if (future_unroll_cnt > LoopMaxUnroll) return false;
868   } else {
869     // obey user constraints on vector mapped loops with additional unrolling applied
870     int unroll_constraint = (cl->slp_max_unroll()) ? cl->slp_max_unroll() : 1;
871     if ((future_unroll_cnt / unroll_constraint) > LoopMaxUnroll) return false;
872   }
873 
874   // Check for initial stride being a small enough constant
875   if (abs(cl->stride_con()) > (1<<2)*future_unroll_cnt) return false;
876 
877   // Don't unroll if the next round of unrolling would push us
878   // over the expected trip count of the loop.  One is subtracted
879   // from the expected trip count because the pre-loop normally
880   // executes 1 iteration.
881   if (UnrollLimitForProfileCheck > 0 &&
882       cl->profile_trip_cnt() != COUNT_UNKNOWN &&
883       future_unroll_cnt        > UnrollLimitForProfileCheck &&
884       (float)future_unroll_cnt > cl->profile_trip_cnt() - 1.0) {
885     return false;
886   }
887 
888   // When unroll count is greater than LoopUnrollMin, don't unroll if:
889   //   the residual iterations are more than 10% of the trip count
890   //   and rounds of "unroll,optimize" are not making significant progress
891   //   Progress defined as current size less than 20% larger than previous size.
892   if (UseSuperWord && cl->node_count_before_unroll() > 0 &&
893       future_unroll_cnt > LoopUnrollMin &&
894       (future_unroll_cnt - 1) * (100 / LoopPercentProfileLimit) > cl->profile_trip_cnt() &&
895       1.2 * cl->node_count_before_unroll() < (double)_body.size()) {
896     return false;
897   }
898 
899   Node *init_n = cl->init_trip();
900   Node *limit_n = cl->limit();
901   int stride_con = cl->stride_con();
902   if (limit_n == NULL) return false; // We will dereference it below.
903 
904   // Non-constant bounds.
905   // Protect against over-unrolling when init or/and limit are not constant
906   // (so that trip_count's init value is maxint) but iv range is known.
907   if (init_n == NULL || !init_n->is_Con() || !limit_n->is_Con()) {
908     Node* phi = cl->phi();
909     if (phi != NULL) {
910       assert(phi->is_Phi() && phi->in(0) == _head, "Counted loop should have iv phi.");
911       const TypeInt* iv_type = phase->_igvn.type(phi)->is_int();
912       int next_stride = stride_con * 2; // stride after this unroll
913       if (next_stride > 0) {
914         if (iv_type->_lo > max_jint - next_stride || // overflow
915             iv_type->_lo + next_stride >  iv_type->_hi) {
916           return false;  // over-unrolling
917         }
918       } else if (next_stride < 0) {
919         if (iv_type->_hi < min_jint - next_stride || // overflow
920             iv_type->_hi + next_stride <  iv_type->_lo) {
921           return false;  // over-unrolling
922         }
923       }
924     }
925   }
926 
927   // After unroll limit will be adjusted: new_limit = limit-stride.
928   // Bailout if adjustment overflow.
929   const TypeInt* limit_type = phase->_igvn.type(limit_n)->is_int();
930   if ((stride_con > 0 && ((min_jint + stride_con) > limit_type->_hi)) ||
931       (stride_con < 0 && ((max_jint + stride_con) < limit_type->_lo)))
932     return false;  // overflow
933 
934   // Adjust body_size to determine if we unroll or not
935   uint body_size = _body.size();
936   // Key test to unroll loop in CRC32 java code
937   int xors_in_loop = 0;
938   // Also count ModL, DivL and MulL which expand mightly
939   for (uint k = 0; k < _body.size(); k++) {
940     Node* n = _body.at(k);
941     switch (n->Opcode()) {
942       case Op_XorI: xors_in_loop++; break; // CRC32 java code
943       case Op_ModL: body_size += 30; break;
944       case Op_DivL: body_size += 30; break;
945       case Op_MulL: body_size += 10; break;
946       case Op_StrComp:
947       case Op_StrEquals:
948       case Op_StrIndexOf:
949       case Op_StrIndexOfChar:
950       case Op_EncodeISOArray:
951       case Op_AryEq:
952       case Op_HasNegatives: {
953         // Do not unroll a loop with String intrinsics code.
954         // String intrinsics are large and have loops.
955         return false;
956       }
957 #if INCLUDE_RTM_OPT
958       case Op_FastLock:
959       case Op_FastUnlock: {
960         // Don't unroll RTM locking code because it is large.
961         if (UseRTMLocking) {
962           return false;
963         }
964       }
965 #endif
966     } // switch
967   }
968 
969   if (UseSuperWord) {
970     if (!cl->is_reduction_loop()) {
971       phase->mark_reductions(this);
972     }
973 
974     // Only attempt slp analysis when user controls do not prohibit it
975     if (LoopMaxUnroll > _local_loop_unroll_factor) {
976       // Once policy_slp_analysis succeeds, mark the loop with the
977       // maximal unroll factor so that we minimize analysis passes
978       if (future_unroll_cnt >= _local_loop_unroll_factor) {
979         policy_unroll_slp_analysis(cl, phase, future_unroll_cnt);
980       }
981     }
982   }
983 
984   int slp_max_unroll_factor = cl->slp_max_unroll();
985   if ((LoopMaxUnroll < slp_max_unroll_factor) && FLAG_IS_DEFAULT(LoopMaxUnroll) && UseSubwordForMaxVector) {
986     LoopMaxUnroll = slp_max_unroll_factor;
987   }
988 
989   uint estimate = est_loop_clone_sz(2);
990 
991   if (cl->has_passed_slp()) {
992     if (slp_max_unroll_factor >= future_unroll_cnt) {
993       return phase->may_require_nodes(estimate);
994     }
995     return false; // Loop too big.
996   }
997 
998   // Check for being too big
999   if (body_size > (uint)_local_loop_unroll_limit) {
1000     if ((cl->is_subword_loop() || xors_in_loop >= 4) && body_size < 4u * LoopUnrollLimit) {
1001       return phase->may_require_nodes(estimate);
1002     }
1003     return false; // Loop too big.
1004   }
1005 
1006   if (cl->is_unroll_only()) {
1007     if (TraceSuperWordLoopUnrollAnalysis) {
1008       tty->print_cr("policy_unroll passed vector loop(vlen=%d, factor=%d)\n",
1009                     slp_max_unroll_factor, future_unroll_cnt);
1010     }
1011   }
1012 
1013   // Unroll once!  (Each trip will soon do double iterations)
1014   return phase->may_require_nodes(estimate);
1015 }
1016 
policy_unroll_slp_analysis(CountedLoopNode * cl,PhaseIdealLoop * phase,int future_unroll_cnt)1017 void IdealLoopTree::policy_unroll_slp_analysis(CountedLoopNode *cl, PhaseIdealLoop *phase, int future_unroll_cnt) {
1018 
1019   // If nodes are depleted, some transform has miscalculated its needs.
1020   assert(!phase->exceeding_node_budget(), "sanity");
1021 
1022   // Enable this functionality target by target as needed
1023   if (SuperWordLoopUnrollAnalysis) {
1024     if (!cl->was_slp_analyzed()) {
1025       SuperWord sw(phase);
1026       sw.transform_loop(this, false);
1027 
1028       // If the loop is slp canonical analyze it
1029       if (sw.early_return() == false) {
1030         sw.unrolling_analysis(_local_loop_unroll_factor);
1031       }
1032     }
1033 
1034     if (cl->has_passed_slp()) {
1035       int slp_max_unroll_factor = cl->slp_max_unroll();
1036       if (slp_max_unroll_factor >= future_unroll_cnt) {
1037         int new_limit = cl->node_count_before_unroll() * slp_max_unroll_factor;
1038         if (new_limit > LoopUnrollLimit) {
1039           if (TraceSuperWordLoopUnrollAnalysis) {
1040             tty->print_cr("slp analysis unroll=%d, default limit=%d\n", new_limit, _local_loop_unroll_limit);
1041           }
1042           _local_loop_unroll_limit = new_limit;
1043         }
1044       }
1045     }
1046   }
1047 }
1048 
1049 //------------------------------policy_range_check-----------------------------
1050 // Return TRUE or FALSE if the loop should be range-check-eliminated or not.
1051 // When TRUE, the estimated node budget is also requested.
1052 //
1053 // We will actually perform iteration-splitting, a more powerful form of RCE.
policy_range_check(PhaseIdealLoop * phase) const1054 bool IdealLoopTree::policy_range_check(PhaseIdealLoop *phase) const {
1055   if (!RangeCheckElimination) return false;
1056 
1057   // If nodes are depleted, some transform has miscalculated its needs.
1058   assert(!phase->exceeding_node_budget(), "sanity");
1059 
1060   CountedLoopNode *cl = _head->as_CountedLoop();
1061   // If we unrolled  with no intention of doing RCE and we  later changed our
1062   // minds, we got no pre-loop.  Either we need to make a new pre-loop, or we
1063   // have to disallow RCE.
1064   if (cl->is_main_no_pre_loop()) return false; // Disallowed for now.
1065   Node *trip_counter = cl->phi();
1066 
1067   // check for vectorized loops, some opts are no longer needed
1068   // RCE needs pre/main/post loops. Don't apply it on a single iteration loop.
1069   if (cl->is_unroll_only() || (cl->is_normal_loop() && cl->trip_count() == 1)) return false;
1070 
1071   // Check loop body for tests of trip-counter plus loop-invariant vs
1072   // loop-invariant.
1073   for (uint i = 0; i < _body.size(); i++) {
1074     Node *iff = _body[i];
1075     if (iff->Opcode() == Op_If ||
1076         iff->Opcode() == Op_RangeCheck) { // Test?
1077 
1078       // Comparing trip+off vs limit
1079       Node *bol = iff->in(1);
1080       if (bol->req() != 2) {
1081         continue; // dead constant test
1082       }
1083       if (!bol->is_Bool()) {
1084         assert(bol->Opcode() == Op_Conv2B, "predicate check only");
1085         continue;
1086       }
1087       if (bol->as_Bool()->_test._test == BoolTest::ne) {
1088         continue; // not RC
1089       }
1090       Node *cmp = bol->in(1);
1091       Node *rc_exp = cmp->in(1);
1092       Node *limit = cmp->in(2);
1093 
1094       Node *limit_c = phase->get_ctrl(limit);
1095       if (limit_c == phase->C->top()) {
1096         return false;           // Found dead test on live IF?  No RCE!
1097       }
1098       if (is_member(phase->get_loop(limit_c))) {
1099         // Compare might have operands swapped; commute them
1100         rc_exp = cmp->in(2);
1101         limit  = cmp->in(1);
1102         limit_c = phase->get_ctrl(limit);
1103         if (is_member(phase->get_loop(limit_c))) {
1104           continue;             // Both inputs are loop varying; cannot RCE
1105         }
1106       }
1107 
1108       if (!phase->is_scaled_iv_plus_offset(rc_exp, trip_counter, NULL, NULL)) {
1109         continue;
1110       }
1111       // Found a test like 'trip+off vs limit'. Test is an IfNode, has two (2)
1112       // projections. If BOTH are in the loop we need loop unswitching instead
1113       // of iteration splitting.
1114       if (is_loop_exit(iff)) {
1115         // Found valid reason to split iterations (if there is room).
1116         // NOTE: Usually a gross overestimate.
1117         return phase->may_require_nodes(est_loop_clone_sz(2));
1118       }
1119     } // End of is IF
1120   }
1121 
1122   return false;
1123 }
1124 
1125 //------------------------------policy_peel_only-------------------------------
1126 // Return TRUE or FALSE if the loop should NEVER be RCE'd or aligned.  Useful
1127 // for unrolling loops with NO array accesses.
policy_peel_only(PhaseIdealLoop * phase) const1128 bool IdealLoopTree::policy_peel_only(PhaseIdealLoop *phase) const {
1129 
1130   // If nodes are depleted, some transform has miscalculated its needs.
1131   assert(!phase->exceeding_node_budget(), "sanity");
1132 
1133   // check for vectorized loops, any peeling done was already applied
1134   if (_head->is_CountedLoop() && _head->as_CountedLoop()->is_unroll_only()) {
1135     return false;
1136   }
1137 
1138   for (uint i = 0; i < _body.size(); i++) {
1139     if (_body[i]->is_Mem()) {
1140       return false;
1141     }
1142   }
1143   // No memory accesses at all!
1144   return true;
1145 }
1146 
1147 //------------------------------clone_up_backedge_goo--------------------------
1148 // If Node n lives in the back_ctrl block and cannot float, we clone a private
1149 // version of n in preheader_ctrl block and return that, otherwise return n.
clone_up_backedge_goo(Node * back_ctrl,Node * preheader_ctrl,Node * n,VectorSet & visited,Node_Stack & clones)1150 Node *PhaseIdealLoop::clone_up_backedge_goo(Node *back_ctrl, Node *preheader_ctrl, Node *n, VectorSet &visited, Node_Stack &clones) {
1151   if (get_ctrl(n) != back_ctrl) return n;
1152 
1153   // Only visit once
1154   if (visited.test_set(n->_idx)) {
1155     Node *x = clones.find(n->_idx);
1156     return (x != NULL) ? x : n;
1157   }
1158 
1159   Node *x = NULL;               // If required, a clone of 'n'
1160   // Check for 'n' being pinned in the backedge.
1161   if (n->in(0) && n->in(0) == back_ctrl) {
1162     assert(clones.find(n->_idx) == NULL, "dead loop");
1163     x = n->clone();             // Clone a copy of 'n' to preheader
1164     clones.push(x, n->_idx);
1165     x->set_req(0, preheader_ctrl); // Fix x's control input to preheader
1166   }
1167 
1168   // Recursive fixup any other input edges into x.
1169   // If there are no changes we can just return 'n', otherwise
1170   // we need to clone a private copy and change it.
1171   for (uint i = 1; i < n->req(); i++) {
1172     Node *g = clone_up_backedge_goo(back_ctrl, preheader_ctrl, n->in(i), visited, clones);
1173     if (g != n->in(i)) {
1174       if (!x) {
1175         assert(clones.find(n->_idx) == NULL, "dead loop");
1176         x = n->clone();
1177         clones.push(x, n->_idx);
1178       }
1179       x->set_req(i, g);
1180     }
1181   }
1182   if (x) {                     // x can legally float to pre-header location
1183     register_new_node(x, preheader_ctrl);
1184     return x;
1185   } else {                      // raise n to cover LCA of uses
1186     set_ctrl(n, find_non_split_ctrl(back_ctrl->in(0)));
1187   }
1188   return n;
1189 }
1190 
cast_incr_before_loop(Node * incr,Node * ctrl,Node * loop)1191 Node* PhaseIdealLoop::cast_incr_before_loop(Node* incr, Node* ctrl, Node* loop) {
1192   Node* castii = new CastIINode(incr, TypeInt::INT, true);
1193   castii->set_req(0, ctrl);
1194   register_new_node(castii, ctrl);
1195   for (DUIterator_Fast imax, i = incr->fast_outs(imax); i < imax; i++) {
1196     Node* n = incr->fast_out(i);
1197     if (n->is_Phi() && n->in(0) == loop) {
1198       int nrep = n->replace_edge(incr, castii);
1199       return castii;
1200     }
1201   }
1202   return NULL;
1203 }
1204 
1205 #ifdef ASSERT
ensure_zero_trip_guard_proj(Node * node,bool is_main_loop)1206 void PhaseIdealLoop::ensure_zero_trip_guard_proj(Node* node, bool is_main_loop) {
1207   assert(node->is_IfProj(), "must be the zero trip guard If node");
1208   Node* zer_bol = node->in(0)->in(1);
1209   assert(zer_bol != NULL && zer_bol->is_Bool(), "must be Bool");
1210   Node* zer_cmp = zer_bol->in(1);
1211   assert(zer_cmp != NULL && zer_cmp->Opcode() == Op_CmpI, "must be CmpI");
1212   // For the main loop, the opaque node is the second input to zer_cmp, for the post loop it's the first input node
1213   Node* zer_opaq = zer_cmp->in(is_main_loop ? 2 : 1);
1214   assert(zer_opaq != NULL && zer_opaq->Opcode() == Op_Opaque1, "must be Opaque1");
1215 }
1216 #endif
1217 
1218 // Make a copy of the skeleton range check predicates before the main
1219 // loop and set the initial value of loop as input. After unrolling,
1220 // the range of values for the induction variable in the main loop can
1221 // fall outside the allowed range of values by the array access (main
1222 // loop is never executed). When that happens, range check
1223 // CastII/ConvI2L nodes cause some data paths to die. For consistency,
1224 // the control paths must die too but the range checks were removed by
1225 // predication. The range checks that we add here guarantee that they do.
copy_skeleton_predicates_to_main_loop_helper(Node * predicate,Node * init,Node * stride,IdealLoopTree * outer_loop,LoopNode * outer_main_head,uint dd_main_head,const uint idx_before_pre_post,const uint idx_after_post_before_pre,Node * zero_trip_guard_proj_main,Node * zero_trip_guard_proj_post,const Node_List & old_new)1226 void PhaseIdealLoop::copy_skeleton_predicates_to_main_loop_helper(Node* predicate, Node* init, Node* stride,
1227                                                  IdealLoopTree* outer_loop, LoopNode* outer_main_head,
1228                                                  uint dd_main_head, const uint idx_before_pre_post,
1229                                                  const uint idx_after_post_before_pre, Node* zero_trip_guard_proj_main,
1230                                                  Node* zero_trip_guard_proj_post, const Node_List &old_new) {
1231   if (predicate != NULL) {
1232 #ifdef ASSERT
1233     ensure_zero_trip_guard_proj(zero_trip_guard_proj_main, true);
1234     ensure_zero_trip_guard_proj(zero_trip_guard_proj_post, false);
1235 #endif
1236     IfNode* iff = predicate->in(0)->as_If();
1237     ProjNode* uncommon_proj = iff->proj_out(1 - predicate->as_Proj()->_con);
1238     Node* rgn = uncommon_proj->unique_ctrl_out();
1239     assert(rgn->is_Region() || rgn->is_Call(), "must be a region or call uct");
1240     assert(iff->in(1)->in(1)->Opcode() == Op_Opaque1, "unexpected predicate shape");
1241     predicate = iff->in(0);
1242     Node* current_proj = outer_main_head->in(LoopNode::EntryControl);
1243     Node* prev_proj = current_proj;
1244     Node* opaque_init = new OpaqueLoopInitNode(C, init);
1245     register_new_node(opaque_init, outer_main_head->in(LoopNode::EntryControl));
1246     Node* opaque_stride = new OpaqueLoopStrideNode(C, stride);
1247     register_new_node(opaque_stride, outer_main_head->in(LoopNode::EntryControl));
1248 
1249     while (predicate != NULL && predicate->is_Proj() && predicate->in(0)->is_If()) {
1250       iff = predicate->in(0)->as_If();
1251       uncommon_proj = iff->proj_out(1 - predicate->as_Proj()->_con);
1252       if (uncommon_proj->unique_ctrl_out() != rgn)
1253         break;
1254       if (iff->in(1)->Opcode() == Op_Opaque4) {
1255         assert(skeleton_predicate_has_opaque(iff), "unexpected");
1256         // Clone the skeleton predicate twice and initialize one with the initial
1257         // value of the loop induction variable. Leave the other predicate
1258         // to be initialized when increasing the stride during loop unrolling.
1259         prev_proj = clone_skeleton_predicate_for_main_loop(iff, opaque_init, NULL, predicate, uncommon_proj, current_proj, outer_loop, prev_proj);
1260         assert(skeleton_predicate_has_opaque(prev_proj->in(0)->as_If()), "");
1261 
1262         prev_proj = clone_skeleton_predicate_for_main_loop(iff, init, stride, predicate, uncommon_proj, current_proj, outer_loop, prev_proj);
1263         assert(!skeleton_predicate_has_opaque(prev_proj->in(0)->as_If()), "");
1264 
1265         // Rewire any control inputs from the cloned skeleton predicates down to the main and post loop for data nodes that are part of the
1266         // main loop (and were cloned to the pre and post loop).
1267         for (DUIterator i = predicate->outs(); predicate->has_out(i); i++) {
1268           Node* loop_node = predicate->out(i);
1269           Node* pre_loop_node = old_new[loop_node->_idx];
1270           // Change the control if 'loop_node' is part of the main loop. If there is an old->new mapping and the index of
1271           // 'pre_loop_node' is greater than idx_before_pre_post, then we know that 'loop_node' was cloned and is part of
1272           // the main loop (and 'pre_loop_node' is part of the pre loop).
1273           if (!loop_node->is_CFG() && (pre_loop_node != NULL && pre_loop_node->_idx > idx_after_post_before_pre)) {
1274             // 'loop_node' is a data node and part of the main loop. Rewire the control to the projection of the zero-trip guard if node
1275             // of the main loop that is immediately preceding the cloned predicates.
1276             _igvn.replace_input_of(loop_node, 0, zero_trip_guard_proj_main);
1277             --i;
1278           } else if (loop_node->_idx > idx_before_pre_post && loop_node->_idx < idx_after_post_before_pre) {
1279             // 'loop_node' is a data node and part of the post loop. Rewire the control to the projection of the zero-trip guard if node
1280             // of the post loop that is immediately preceding the post loop header node (there are no cloned predicates for the post loop).
1281             assert(pre_loop_node == NULL, "a node belonging to the post loop should not have an old_new mapping at this stage");
1282             _igvn.replace_input_of(loop_node, 0, zero_trip_guard_proj_post);
1283             --i;
1284           }
1285         }
1286 
1287         // Remove the skeleton predicate from the pre-loop
1288         _igvn.replace_input_of(iff, 1, _igvn.intcon(1));
1289       }
1290       predicate = predicate->in(0)->in(0);
1291     }
1292     _igvn.replace_input_of(outer_main_head, LoopNode::EntryControl, prev_proj);
1293     set_idom(outer_main_head, prev_proj, dd_main_head);
1294   }
1295 }
1296 
skeleton_follow_inputs(Node * n,int op)1297 static bool skeleton_follow_inputs(Node* n, int op) {
1298   return (n->is_Bool() ||
1299           n->is_Cmp() ||
1300           op == Op_AndL ||
1301           op == Op_OrL ||
1302           op == Op_RShiftL ||
1303           op == Op_LShiftL ||
1304           op == Op_AddL ||
1305           op == Op_AddI ||
1306           op == Op_MulL ||
1307           op == Op_MulI ||
1308           op == Op_SubL ||
1309           op == Op_SubI ||
1310           op == Op_ConvI2L);
1311 }
1312 
skeleton_predicate_has_opaque(IfNode * iff)1313 bool PhaseIdealLoop::skeleton_predicate_has_opaque(IfNode* iff) {
1314   ResourceMark rm;
1315   Unique_Node_List wq;
1316   wq.push(iff->in(1)->in(1));
1317   for (uint i = 0; i < wq.size(); i++) {
1318     Node* n = wq.at(i);
1319     int op = n->Opcode();
1320     if (skeleton_follow_inputs(n, op)) {
1321       for (uint j = 1; j < n->req(); j++) {
1322         Node* m = n->in(j);
1323         if (m != NULL) {
1324           wq.push(m);
1325         }
1326       }
1327       continue;
1328     }
1329     if (n->is_Opaque1()) {
1330       return true;
1331     }
1332   }
1333   return false;
1334 }
1335 
1336 // Clone the skeleton predicate bool for a main or unswitched loop:
1337 // Main loop: Set new_init and new_stride nodes as new inputs.
1338 // Unswitched loop: new_init and new_stride are both NULL. Clone OpaqueLoopInit and OpaqueLoopStride instead.
clone_skeleton_predicate_bool(Node * iff,Node * new_init,Node * new_stride,Node * predicate,Node * uncommon_proj,Node * control,IdealLoopTree * outer_loop)1339 Node* PhaseIdealLoop::clone_skeleton_predicate_bool(Node* iff, Node* new_init, Node* new_stride, Node* predicate, Node* uncommon_proj,
1340                                                     Node* control, IdealLoopTree* outer_loop) {
1341   Node_Stack to_clone(2);
1342   to_clone.push(iff->in(1), 1);
1343   uint current = C->unique();
1344   Node* result = NULL;
1345   bool is_unswitched_loop = new_init == NULL && new_stride == NULL;
1346   assert(new_init != NULL || is_unswitched_loop, "new_init must be set when new_stride is non-null");
1347   // Look for the opaque node to replace with the new value
1348   // and clone everything in between. We keep the Opaque4 node
1349   // so the duplicated predicates are eliminated once loop
1350   // opts are over: they are here only to keep the IR graph
1351   // consistent.
1352   do {
1353     Node* n = to_clone.node();
1354     uint i = to_clone.index();
1355     Node* m = n->in(i);
1356     int op = m->Opcode();
1357     if (skeleton_follow_inputs(m, op)) {
1358       to_clone.push(m, 1);
1359       continue;
1360     }
1361     if (m->is_Opaque1()) {
1362       if (n->_idx < current) {
1363         n = n->clone();
1364         register_new_node(n, control);
1365       }
1366       if (op == Op_OpaqueLoopInit) {
1367         if (is_unswitched_loop && m->_idx < current && new_init == NULL) {
1368           new_init = m->clone();
1369           register_new_node(new_init, control);
1370         }
1371         n->set_req(i, new_init);
1372       } else {
1373         assert(op == Op_OpaqueLoopStride, "unexpected opaque node");
1374         if (is_unswitched_loop && m->_idx < current && new_stride == NULL) {
1375           new_stride = m->clone();
1376           register_new_node(new_stride, control);
1377         }
1378         if (new_stride != NULL) {
1379           n->set_req(i, new_stride);
1380         }
1381       }
1382       to_clone.set_node(n);
1383     }
1384     while (true) {
1385       Node* cur = to_clone.node();
1386       uint j = to_clone.index();
1387       if (j+1 < cur->req()) {
1388         to_clone.set_index(j+1);
1389         break;
1390       }
1391       to_clone.pop();
1392       if (to_clone.size() == 0) {
1393         result = cur;
1394         break;
1395       }
1396       Node* next = to_clone.node();
1397       j = to_clone.index();
1398       if (next->in(j) != cur) {
1399         assert(cur->_idx >= current || next->in(j)->Opcode() == Op_Opaque1, "new node or Opaque1 being replaced");
1400         if (next->_idx < current) {
1401           next = next->clone();
1402           register_new_node(next, control);
1403           to_clone.set_node(next);
1404         }
1405         next->set_req(j, cur);
1406       }
1407     }
1408   } while (result == NULL);
1409   assert(result->_idx >= current, "new node expected");
1410   assert(!is_unswitched_loop || new_init != NULL, "new_init must always be found and cloned");
1411   return result;
1412 }
1413 
1414 // Clone a skeleton predicate for the main loop. new_init and new_stride are set as new inputs. Since the predicates cannot fail at runtime,
1415 // Halt nodes are inserted instead of uncommon traps.
clone_skeleton_predicate_for_main_loop(Node * iff,Node * new_init,Node * new_stride,Node * predicate,Node * uncommon_proj,Node * control,IdealLoopTree * outer_loop,Node * input_proj)1416 Node* PhaseIdealLoop::clone_skeleton_predicate_for_main_loop(Node* iff, Node* new_init, Node* new_stride, Node* predicate, Node* uncommon_proj,
1417                                                              Node* control, IdealLoopTree* outer_loop, Node* input_proj) {
1418   Node* result = clone_skeleton_predicate_bool(iff, new_init, new_stride, predicate, uncommon_proj, control, outer_loop);
1419   Node* proj = predicate->clone();
1420   Node* other_proj = uncommon_proj->clone();
1421   Node* new_iff = iff->clone();
1422   new_iff->set_req(1, result);
1423   proj->set_req(0, new_iff);
1424   other_proj->set_req(0, new_iff);
1425   Node* frame = new ParmNode(C->start(), TypeFunc::FramePtr);
1426   register_new_node(frame, C->start());
1427   // It's impossible for the predicate to fail at runtime. Use an Halt node.
1428   Node* halt = new HaltNode(other_proj, frame, "duplicated predicate failed which is impossible");
1429   C->root()->add_req(halt);
1430   new_iff->set_req(0, input_proj);
1431 
1432   register_control(new_iff, outer_loop->_parent, input_proj);
1433   register_control(proj, outer_loop->_parent, new_iff);
1434   register_control(other_proj, _ltree_root, new_iff);
1435   register_control(halt, _ltree_root, other_proj);
1436   return proj;
1437 }
1438 
copy_skeleton_predicates_to_main_loop(CountedLoopNode * pre_head,Node * init,Node * stride,IdealLoopTree * outer_loop,LoopNode * outer_main_head,uint dd_main_head,const uint idx_before_pre_post,const uint idx_after_post_before_pre,Node * zero_trip_guard_proj_main,Node * zero_trip_guard_proj_post,const Node_List & old_new)1439 void PhaseIdealLoop::copy_skeleton_predicates_to_main_loop(CountedLoopNode* pre_head, Node* init, Node* stride,
1440                                           IdealLoopTree* outer_loop, LoopNode* outer_main_head,
1441                                           uint dd_main_head, const uint idx_before_pre_post,
1442                                           const uint idx_after_post_before_pre, Node* zero_trip_guard_proj_main,
1443                                           Node* zero_trip_guard_proj_post, const Node_List &old_new) {
1444   if (UseLoopPredicate) {
1445     Node* entry = pre_head->in(LoopNode::EntryControl);
1446     Node* predicate = NULL;
1447     predicate = find_predicate_insertion_point(entry, Deoptimization::Reason_loop_limit_check);
1448     if (predicate != NULL) {
1449       entry = skip_loop_predicates(entry);
1450     }
1451     Node* profile_predicate = NULL;
1452     if (UseProfiledLoopPredicate) {
1453       profile_predicate = find_predicate_insertion_point(entry, Deoptimization::Reason_profile_predicate);
1454       if (profile_predicate != NULL) {
1455         entry = skip_loop_predicates(entry);
1456       }
1457     }
1458     predicate = find_predicate_insertion_point(entry, Deoptimization::Reason_predicate);
1459     copy_skeleton_predicates_to_main_loop_helper(predicate, init, stride, outer_loop, outer_main_head, dd_main_head,
1460                                                  idx_before_pre_post, idx_after_post_before_pre, zero_trip_guard_proj_main,
1461                                                  zero_trip_guard_proj_post, old_new);
1462     copy_skeleton_predicates_to_main_loop_helper(profile_predicate, init, stride, outer_loop, outer_main_head, dd_main_head,
1463                                                  idx_before_pre_post, idx_after_post_before_pre, zero_trip_guard_proj_main,
1464                                                  zero_trip_guard_proj_post, old_new);
1465   }
1466 }
1467 
1468 //------------------------------insert_pre_post_loops--------------------------
1469 // Insert pre and post loops.  If peel_only is set, the pre-loop can not have
1470 // more iterations added.  It acts as a 'peel' only, no lower-bound RCE, no
1471 // alignment.  Useful to unroll loops that do no array accesses.
insert_pre_post_loops(IdealLoopTree * loop,Node_List & old_new,bool peel_only)1472 void PhaseIdealLoop::insert_pre_post_loops(IdealLoopTree *loop, Node_List &old_new, bool peel_only) {
1473 
1474 #ifndef PRODUCT
1475   if (TraceLoopOpts) {
1476     if (peel_only)
1477       tty->print("PeelMainPost ");
1478     else
1479       tty->print("PreMainPost  ");
1480     loop->dump_head();
1481   }
1482 #endif
1483   C->set_major_progress();
1484 
1485   // Find common pieces of the loop being guarded with pre & post loops
1486   CountedLoopNode *main_head = loop->_head->as_CountedLoop();
1487   assert(main_head->is_normal_loop(), "");
1488   CountedLoopEndNode *main_end = main_head->loopexit();
1489   assert(main_end->outcnt() == 2, "1 true, 1 false path only");
1490 
1491   Node *pre_header= main_head->in(LoopNode::EntryControl);
1492   Node *init      = main_head->init_trip();
1493   Node *incr      = main_end ->incr();
1494   Node *limit     = main_end ->limit();
1495   Node *stride    = main_end ->stride();
1496   Node *cmp       = main_end ->cmp_node();
1497   BoolTest::mask b_test = main_end->test_trip();
1498 
1499   // Need only 1 user of 'bol' because I will be hacking the loop bounds.
1500   Node *bol = main_end->in(CountedLoopEndNode::TestValue);
1501   if (bol->outcnt() != 1) {
1502     bol = bol->clone();
1503     register_new_node(bol,main_end->in(CountedLoopEndNode::TestControl));
1504     _igvn.replace_input_of(main_end, CountedLoopEndNode::TestValue, bol);
1505   }
1506   // Need only 1 user of 'cmp' because I will be hacking the loop bounds.
1507   if (cmp->outcnt() != 1) {
1508     cmp = cmp->clone();
1509     register_new_node(cmp,main_end->in(CountedLoopEndNode::TestControl));
1510     _igvn.replace_input_of(bol, 1, cmp);
1511   }
1512 
1513   // Add the post loop
1514   const uint idx_before_pre_post = Compile::current()->unique();
1515   CountedLoopNode *post_head = NULL;
1516   Node *main_exit = insert_post_loop(loop, old_new, main_head, main_end, incr, limit, post_head);
1517   const uint idx_after_post_before_pre = Compile::current()->unique();
1518 
1519   //------------------------------
1520   // Step B: Create Pre-Loop.
1521 
1522   // Step B1: Clone the loop body.  The clone becomes the pre-loop.  The main
1523   // loop pre-header illegally has 2 control users (old & new loops).
1524   LoopNode* outer_main_head = main_head;
1525   IdealLoopTree* outer_loop = loop;
1526   if (main_head->is_strip_mined()) {
1527     main_head->verify_strip_mined(1);
1528     outer_main_head = main_head->outer_loop();
1529     outer_loop = loop->_parent;
1530     assert(outer_loop->_head == outer_main_head, "broken loop tree");
1531   }
1532   uint dd_main_head = dom_depth(outer_main_head);
1533   clone_loop(loop, old_new, dd_main_head, ControlAroundStripMined);
1534   CountedLoopNode*    pre_head = old_new[main_head->_idx]->as_CountedLoop();
1535   CountedLoopEndNode* pre_end  = old_new[main_end ->_idx]->as_CountedLoopEnd();
1536   pre_head->set_pre_loop(main_head);
1537   Node *pre_incr = old_new[incr->_idx];
1538 
1539   // Reduce the pre-loop trip count.
1540   pre_end->_prob = PROB_FAIR;
1541 
1542   // Find the pre-loop normal exit.
1543   Node* pre_exit = pre_end->proj_out(false);
1544   assert(pre_exit->Opcode() == Op_IfFalse, "");
1545   IfFalseNode *new_pre_exit = new IfFalseNode(pre_end);
1546   _igvn.register_new_node_with_optimizer(new_pre_exit);
1547   set_idom(new_pre_exit, pre_end, dd_main_head);
1548   set_loop(new_pre_exit, outer_loop->_parent);
1549 
1550   // Step B2: Build a zero-trip guard for the main-loop.  After leaving the
1551   // pre-loop, the main-loop may not execute at all.  Later in life this
1552   // zero-trip guard will become the minimum-trip guard when we unroll
1553   // the main-loop.
1554   Node *min_opaq = new Opaque1Node(C, limit);
1555   Node *min_cmp  = new CmpINode(pre_incr, min_opaq);
1556   Node *min_bol  = new BoolNode(min_cmp, b_test);
1557   register_new_node(min_opaq, new_pre_exit);
1558   register_new_node(min_cmp , new_pre_exit);
1559   register_new_node(min_bol , new_pre_exit);
1560 
1561   // Build the IfNode (assume the main-loop is executed always).
1562   IfNode *min_iff = new IfNode(new_pre_exit, min_bol, PROB_ALWAYS, COUNT_UNKNOWN);
1563   _igvn.register_new_node_with_optimizer(min_iff);
1564   set_idom(min_iff, new_pre_exit, dd_main_head);
1565   set_loop(min_iff, outer_loop->_parent);
1566 
1567   // Plug in the false-path, taken if we need to skip main-loop
1568   _igvn.hash_delete(pre_exit);
1569   pre_exit->set_req(0, min_iff);
1570   set_idom(pre_exit, min_iff, dd_main_head);
1571   set_idom(pre_exit->unique_ctrl_out(), min_iff, dd_main_head);
1572   // Make the true-path, must enter the main loop
1573   Node *min_taken = new IfTrueNode(min_iff);
1574   _igvn.register_new_node_with_optimizer(min_taken);
1575   set_idom(min_taken, min_iff, dd_main_head);
1576   set_loop(min_taken, outer_loop->_parent);
1577   // Plug in the true path
1578   _igvn.hash_delete(outer_main_head);
1579   outer_main_head->set_req(LoopNode::EntryControl, min_taken);
1580   set_idom(outer_main_head, min_taken, dd_main_head);
1581 
1582   VectorSet visited;
1583   Node_Stack clones(main_head->back_control()->outcnt());
1584   // Step B3: Make the fall-in values to the main-loop come from the
1585   // fall-out values of the pre-loop.
1586   for (DUIterator i2 = main_head->outs(); main_head->has_out(i2); i2++) {
1587     Node* main_phi = main_head->out(i2);
1588     if (main_phi->is_Phi() && main_phi->in(0) == main_head && main_phi->outcnt() > 0) {
1589       Node* pre_phi = old_new[main_phi->_idx];
1590       Node* fallpre = clone_up_backedge_goo(pre_head->back_control(),
1591                                             main_head->skip_strip_mined()->in(LoopNode::EntryControl),
1592                                             pre_phi->in(LoopNode::LoopBackControl),
1593                                             visited, clones);
1594       _igvn.hash_delete(main_phi);
1595       main_phi->set_req(LoopNode::EntryControl, fallpre);
1596     }
1597   }
1598 
1599   // Nodes inside the loop may be control dependent on a predicate
1600   // that was moved before the preloop. If the back branch of the main
1601   // or post loops becomes dead, those nodes won't be dependent on the
1602   // test that guards that loop nest anymore which could lead to an
1603   // incorrect array access because it executes independently of the
1604   // test that was guarding the loop nest. We add a special CastII on
1605   // the if branch that enters the loop, between the input induction
1606   // variable value and the induction variable Phi to preserve correct
1607   // dependencies.
1608 
1609   // CastII for the main loop:
1610   Node* castii = cast_incr_before_loop(pre_incr, min_taken, main_head);
1611   assert(castii != NULL, "no castII inserted");
1612   assert(post_head->in(1)->is_IfProj(), "must be zero-trip guard If node projection of the post loop");
1613   copy_skeleton_predicates_to_main_loop(pre_head, castii, stride, outer_loop, outer_main_head, dd_main_head,
1614                                         idx_before_pre_post, idx_after_post_before_pre, min_taken, post_head->in(1), old_new);
1615 
1616   // Step B4: Shorten the pre-loop to run only 1 iteration (for now).
1617   // RCE and alignment may change this later.
1618   Node *cmp_end = pre_end->cmp_node();
1619   assert(cmp_end->in(2) == limit, "");
1620   Node *pre_limit = new AddINode(init, stride);
1621 
1622   // Save the original loop limit in this Opaque1 node for
1623   // use by range check elimination.
1624   Node *pre_opaq  = new Opaque1Node(C, pre_limit, limit);
1625 
1626   register_new_node(pre_limit, pre_head->in(0));
1627   register_new_node(pre_opaq , pre_head->in(0));
1628 
1629   // Since no other users of pre-loop compare, I can hack limit directly
1630   assert(cmp_end->outcnt() == 1, "no other users");
1631   _igvn.hash_delete(cmp_end);
1632   cmp_end->set_req(2, peel_only ? pre_limit : pre_opaq);
1633 
1634   // Special case for not-equal loop bounds:
1635   // Change pre loop test, main loop test, and the
1636   // main loop guard test to use lt or gt depending on stride
1637   // direction:
1638   // positive stride use <
1639   // negative stride use >
1640   //
1641   // not-equal test is kept for post loop to handle case
1642   // when init > limit when stride > 0 (and reverse).
1643 
1644   if (pre_end->in(CountedLoopEndNode::TestValue)->as_Bool()->_test._test == BoolTest::ne) {
1645 
1646     BoolTest::mask new_test = (main_end->stride_con() > 0) ? BoolTest::lt : BoolTest::gt;
1647     // Modify pre loop end condition
1648     Node* pre_bol = pre_end->in(CountedLoopEndNode::TestValue)->as_Bool();
1649     BoolNode* new_bol0 = new BoolNode(pre_bol->in(1), new_test);
1650     register_new_node(new_bol0, pre_head->in(0));
1651     _igvn.replace_input_of(pre_end, CountedLoopEndNode::TestValue, new_bol0);
1652     // Modify main loop guard condition
1653     assert(min_iff->in(CountedLoopEndNode::TestValue) == min_bol, "guard okay");
1654     BoolNode* new_bol1 = new BoolNode(min_bol->in(1), new_test);
1655     register_new_node(new_bol1, new_pre_exit);
1656     _igvn.hash_delete(min_iff);
1657     min_iff->set_req(CountedLoopEndNode::TestValue, new_bol1);
1658     // Modify main loop end condition
1659     BoolNode* main_bol = main_end->in(CountedLoopEndNode::TestValue)->as_Bool();
1660     BoolNode* new_bol2 = new BoolNode(main_bol->in(1), new_test);
1661     register_new_node(new_bol2, main_end->in(CountedLoopEndNode::TestControl));
1662     _igvn.replace_input_of(main_end, CountedLoopEndNode::TestValue, new_bol2);
1663   }
1664 
1665   // Flag main loop
1666   main_head->set_main_loop();
1667   if (peel_only) {
1668     main_head->set_main_no_pre_loop();
1669   }
1670 
1671   // Subtract a trip count for the pre-loop.
1672   main_head->set_trip_count(main_head->trip_count() - 1);
1673 
1674   // It's difficult to be precise about the trip-counts
1675   // for the pre/post loops.  They are usually very short,
1676   // so guess that 4 trips is a reasonable value.
1677   post_head->set_profile_trip_cnt(4.0);
1678   pre_head->set_profile_trip_cnt(4.0);
1679 
1680   // Now force out all loop-invariant dominating tests.  The optimizer
1681   // finds some, but we _know_ they are all useless.
1682   peeled_dom_test_elim(loop,old_new);
1683   loop->record_for_igvn();
1684 }
1685 
1686 //------------------------------insert_vector_post_loop------------------------
1687 // Insert a copy of the atomic unrolled vectorized main loop as a post loop,
1688 // unroll_policy has  already informed  us that more  unrolling is  about to
1689 // happen  to the  main  loop.  The  resultant  post loop  will  serve as  a
1690 // vectorized drain loop.
insert_vector_post_loop(IdealLoopTree * loop,Node_List & old_new)1691 void PhaseIdealLoop::insert_vector_post_loop(IdealLoopTree *loop, Node_List &old_new) {
1692   if (!loop->_head->is_CountedLoop()) return;
1693 
1694   CountedLoopNode *cl = loop->_head->as_CountedLoop();
1695 
1696   // only process vectorized main loops
1697   if (!cl->is_vectorized_loop() || !cl->is_main_loop()) return;
1698 
1699   int slp_max_unroll_factor = cl->slp_max_unroll();
1700   int cur_unroll = cl->unrolled_count();
1701 
1702   if (slp_max_unroll_factor == 0) return;
1703 
1704   // only process atomic unroll vector loops (not super unrolled after vectorization)
1705   if (cur_unroll != slp_max_unroll_factor) return;
1706 
1707   // we only ever process this one time
1708   if (cl->has_atomic_post_loop()) return;
1709 
1710   if (!may_require_nodes(loop->est_loop_clone_sz(2))) {
1711     return;
1712   }
1713 
1714 #ifndef PRODUCT
1715   if (TraceLoopOpts) {
1716     tty->print("PostVector  ");
1717     loop->dump_head();
1718   }
1719 #endif
1720   C->set_major_progress();
1721 
1722   // Find common pieces of the loop being guarded with pre & post loops
1723   CountedLoopNode *main_head = loop->_head->as_CountedLoop();
1724   CountedLoopEndNode *main_end = main_head->loopexit();
1725   // diagnostic to show loop end is not properly formed
1726   assert(main_end->outcnt() == 2, "1 true, 1 false path only");
1727 
1728   // mark this loop as processed
1729   main_head->mark_has_atomic_post_loop();
1730 
1731   Node *incr = main_end->incr();
1732   Node *limit = main_end->limit();
1733 
1734   // In this case we throw away the result as we are not using it to connect anything else.
1735   CountedLoopNode *post_head = NULL;
1736   insert_post_loop(loop, old_new, main_head, main_end, incr, limit, post_head);
1737 
1738   // It's difficult to be precise about the trip-counts
1739   // for post loops.  They are usually very short,
1740   // so guess that unit vector trips is a reasonable value.
1741   post_head->set_profile_trip_cnt(cur_unroll);
1742 
1743   // Now force out all loop-invariant dominating tests.  The optimizer
1744   // finds some, but we _know_ they are all useless.
1745   peeled_dom_test_elim(loop, old_new);
1746   loop->record_for_igvn();
1747 }
1748 
1749 
1750 //-------------------------insert_scalar_rced_post_loop------------------------
1751 // Insert a copy of the rce'd main loop as a post loop,
1752 // We have not unrolled the main loop, so this is the right time to inject this.
1753 // Later we will examine the partner of this post loop pair which still has range checks
1754 // to see inject code which tests at runtime if the range checks are applicable.
insert_scalar_rced_post_loop(IdealLoopTree * loop,Node_List & old_new)1755 void PhaseIdealLoop::insert_scalar_rced_post_loop(IdealLoopTree *loop, Node_List &old_new) {
1756   if (!loop->_head->is_CountedLoop()) return;
1757 
1758   CountedLoopNode *cl = loop->_head->as_CountedLoop();
1759 
1760   // only process RCE'd main loops
1761   if (!cl->is_main_loop() || cl->range_checks_present()) return;
1762 
1763 #ifndef PRODUCT
1764   if (TraceLoopOpts) {
1765     tty->print("PostScalarRce  ");
1766     loop->dump_head();
1767   }
1768 #endif
1769   C->set_major_progress();
1770 
1771   // Find common pieces of the loop being guarded with pre & post loops
1772   CountedLoopNode *main_head = loop->_head->as_CountedLoop();
1773   CountedLoopEndNode *main_end = main_head->loopexit();
1774   // diagnostic to show loop end is not properly formed
1775   assert(main_end->outcnt() == 2, "1 true, 1 false path only");
1776 
1777   Node *incr = main_end->incr();
1778   Node *limit = main_end->limit();
1779 
1780   // In this case we throw away the result as we are not using it to connect anything else.
1781   CountedLoopNode *post_head = NULL;
1782   insert_post_loop(loop, old_new, main_head, main_end, incr, limit, post_head);
1783 
1784   // It's difficult to be precise about the trip-counts
1785   // for post loops.  They are usually very short,
1786   // so guess that unit vector trips is a reasonable value.
1787   post_head->set_profile_trip_cnt(4.0);
1788   post_head->set_is_rce_post_loop();
1789 
1790   // Now force out all loop-invariant dominating tests.  The optimizer
1791   // finds some, but we _know_ they are all useless.
1792   peeled_dom_test_elim(loop, old_new);
1793   loop->record_for_igvn();
1794 }
1795 
1796 
1797 //------------------------------insert_post_loop-------------------------------
1798 // Insert post loops.  Add a post loop to the given loop passed.
insert_post_loop(IdealLoopTree * loop,Node_List & old_new,CountedLoopNode * main_head,CountedLoopEndNode * main_end,Node * incr,Node * limit,CountedLoopNode * & post_head)1799 Node *PhaseIdealLoop::insert_post_loop(IdealLoopTree *loop, Node_List &old_new,
1800                                        CountedLoopNode *main_head, CountedLoopEndNode *main_end,
1801                                        Node *incr, Node *limit, CountedLoopNode *&post_head) {
1802   IfNode* outer_main_end = main_end;
1803   IdealLoopTree* outer_loop = loop;
1804   if (main_head->is_strip_mined()) {
1805     main_head->verify_strip_mined(1);
1806     outer_main_end = main_head->outer_loop_end();
1807     outer_loop = loop->_parent;
1808     assert(outer_loop->_head == main_head->in(LoopNode::EntryControl), "broken loop tree");
1809   }
1810 
1811   //------------------------------
1812   // Step A: Create a new post-Loop.
1813   Node* main_exit = outer_main_end->proj_out(false);
1814   assert(main_exit->Opcode() == Op_IfFalse, "");
1815   int dd_main_exit = dom_depth(main_exit);
1816 
1817   // Step A1: Clone the loop body of main. The clone becomes the post-loop.
1818   // The main loop pre-header illegally has 2 control users (old & new loops).
1819   clone_loop(loop, old_new, dd_main_exit, ControlAroundStripMined);
1820   assert(old_new[main_end->_idx]->Opcode() == Op_CountedLoopEnd, "");
1821   post_head = old_new[main_head->_idx]->as_CountedLoop();
1822   post_head->set_normal_loop();
1823   post_head->set_post_loop(main_head);
1824 
1825   // Reduce the post-loop trip count.
1826   CountedLoopEndNode* post_end = old_new[main_end->_idx]->as_CountedLoopEnd();
1827   post_end->_prob = PROB_FAIR;
1828 
1829   // Build the main-loop normal exit.
1830   IfFalseNode *new_main_exit = new IfFalseNode(outer_main_end);
1831   _igvn.register_new_node_with_optimizer(new_main_exit);
1832   set_idom(new_main_exit, outer_main_end, dd_main_exit);
1833   set_loop(new_main_exit, outer_loop->_parent);
1834 
1835   // Step A2: Build a zero-trip guard for the post-loop.  After leaving the
1836   // main-loop, the post-loop may not execute at all.  We 'opaque' the incr
1837   // (the previous loop trip-counter exit value) because we will be changing
1838   // the exit value (via additional unrolling) so we cannot constant-fold away the zero
1839   // trip guard until all unrolling is done.
1840   Node *zer_opaq = new Opaque1Node(C, incr);
1841   Node *zer_cmp = new CmpINode(zer_opaq, limit);
1842   Node *zer_bol = new BoolNode(zer_cmp, main_end->test_trip());
1843   register_new_node(zer_opaq, new_main_exit);
1844   register_new_node(zer_cmp, new_main_exit);
1845   register_new_node(zer_bol, new_main_exit);
1846 
1847   // Build the IfNode
1848   IfNode *zer_iff = new IfNode(new_main_exit, zer_bol, PROB_FAIR, COUNT_UNKNOWN);
1849   _igvn.register_new_node_with_optimizer(zer_iff);
1850   set_idom(zer_iff, new_main_exit, dd_main_exit);
1851   set_loop(zer_iff, outer_loop->_parent);
1852 
1853   // Plug in the false-path, taken if we need to skip this post-loop
1854   _igvn.replace_input_of(main_exit, 0, zer_iff);
1855   set_idom(main_exit, zer_iff, dd_main_exit);
1856   set_idom(main_exit->unique_out(), zer_iff, dd_main_exit);
1857   // Make the true-path, must enter this post loop
1858   Node *zer_taken = new IfTrueNode(zer_iff);
1859   _igvn.register_new_node_with_optimizer(zer_taken);
1860   set_idom(zer_taken, zer_iff, dd_main_exit);
1861   set_loop(zer_taken, outer_loop->_parent);
1862   // Plug in the true path
1863   _igvn.hash_delete(post_head);
1864   post_head->set_req(LoopNode::EntryControl, zer_taken);
1865   set_idom(post_head, zer_taken, dd_main_exit);
1866 
1867   VectorSet visited;
1868   Node_Stack clones(main_head->back_control()->outcnt());
1869   // Step A3: Make the fall-in values to the post-loop come from the
1870   // fall-out values of the main-loop.
1871   for (DUIterator i = main_head->outs(); main_head->has_out(i); i++) {
1872     Node* main_phi = main_head->out(i);
1873     if (main_phi->is_Phi() && main_phi->in(0) == main_head && main_phi->outcnt() > 0) {
1874       Node* cur_phi = old_new[main_phi->_idx];
1875       Node* fallnew = clone_up_backedge_goo(main_head->back_control(),
1876                                             post_head->init_control(),
1877                                             main_phi->in(LoopNode::LoopBackControl),
1878                                             visited, clones);
1879       _igvn.hash_delete(cur_phi);
1880       cur_phi->set_req(LoopNode::EntryControl, fallnew);
1881     }
1882   }
1883 
1884   // CastII for the new post loop:
1885   Node* castii = cast_incr_before_loop(zer_opaq->in(1), zer_taken, post_head);
1886   assert(castii != NULL, "no castII inserted");
1887 
1888   return new_main_exit;
1889 }
1890 
1891 //------------------------------is_invariant-----------------------------
1892 // Return true if n is invariant
is_invariant(Node * n) const1893 bool IdealLoopTree::is_invariant(Node* n) const {
1894   Node *n_c = _phase->has_ctrl(n) ? _phase->get_ctrl(n) : n;
1895   if (n_c->is_top()) return false;
1896   return !is_member(_phase->get_loop(n_c));
1897 }
1898 
update_main_loop_skeleton_predicates(Node * ctrl,CountedLoopNode * loop_head,Node * init,int stride_con)1899 void PhaseIdealLoop::update_main_loop_skeleton_predicates(Node* ctrl, CountedLoopNode* loop_head, Node* init, int stride_con) {
1900   // Search for skeleton predicates and update them according to the new stride
1901   Node* entry = ctrl;
1902   Node* prev_proj = ctrl;
1903   LoopNode* outer_loop_head = loop_head->skip_strip_mined();
1904   IdealLoopTree* outer_loop = get_loop(outer_loop_head);
1905 
1906   // Compute the value of the loop induction variable at the end of the
1907   // first iteration of the unrolled loop: init + new_stride_con - init_inc
1908   int new_stride_con = stride_con * 2;
1909   Node* max_value = _igvn.intcon(new_stride_con);
1910   set_ctrl(max_value, C->root());
1911 
1912   while (entry != NULL && entry->is_Proj() && entry->in(0)->is_If()) {
1913     IfNode* iff = entry->in(0)->as_If();
1914     ProjNode* proj = iff->proj_out(1 - entry->as_Proj()->_con);
1915     if (proj->unique_ctrl_out()->Opcode() != Op_Halt) {
1916       break;
1917     }
1918     if (iff->in(1)->Opcode() == Op_Opaque4) {
1919       // Look for predicate with an Opaque1 node that can be used as a template
1920       if (!skeleton_predicate_has_opaque(iff)) {
1921         // No Opaque1 node? It's either the check for the first value
1922         // of the first iteration or the check for the last value of
1923         // the first iteration of an unrolled loop. We can't
1924         // tell. Kill it in any case.
1925         _igvn.replace_input_of(iff, 1, iff->in(1)->in(2));
1926       } else {
1927         // Add back predicates updated for the new stride.
1928         prev_proj = clone_skeleton_predicate_for_main_loop(iff, init, max_value, entry, proj, ctrl, outer_loop, prev_proj);
1929         assert(!skeleton_predicate_has_opaque(prev_proj->in(0)->as_If()), "unexpected");
1930       }
1931     }
1932     entry = entry->in(0)->in(0);
1933   }
1934   if (prev_proj != ctrl) {
1935     _igvn.replace_input_of(outer_loop_head, LoopNode::EntryControl, prev_proj);
1936     set_idom(outer_loop_head, prev_proj, dom_depth(outer_loop_head));
1937   }
1938 }
1939 
1940 //------------------------------do_unroll--------------------------------------
1941 // Unroll the loop body one step - make each trip do 2 iterations.
do_unroll(IdealLoopTree * loop,Node_List & old_new,bool adjust_min_trip)1942 void PhaseIdealLoop::do_unroll(IdealLoopTree *loop, Node_List &old_new, bool adjust_min_trip) {
1943   assert(LoopUnrollLimit, "");
1944   CountedLoopNode *loop_head = loop->_head->as_CountedLoop();
1945   CountedLoopEndNode *loop_end = loop_head->loopexit();
1946 #ifndef PRODUCT
1947   if (PrintOpto && VerifyLoopOptimizations) {
1948     tty->print("Unrolling ");
1949     loop->dump_head();
1950   } else if (TraceLoopOpts) {
1951     if (loop_head->trip_count() < (uint)LoopUnrollLimit) {
1952       tty->print("Unroll %d(%2d) ", loop_head->unrolled_count()*2, loop_head->trip_count());
1953     } else {
1954       tty->print("Unroll %d     ", loop_head->unrolled_count()*2);
1955     }
1956     loop->dump_head();
1957   }
1958 
1959   if (C->do_vector_loop() && (PrintOpto && (VerifyLoopOptimizations || TraceLoopOpts))) {
1960     Node_Stack stack(C->live_nodes() >> 2);
1961     Node_List rpo_list;
1962     VectorSet visited;
1963     visited.set(loop_head->_idx);
1964     rpo(loop_head, stack, visited, rpo_list);
1965     dump(loop, rpo_list.size(), rpo_list);
1966   }
1967 #endif
1968 
1969   // Remember loop node count before unrolling to detect
1970   // if rounds of unroll,optimize are making progress
1971   loop_head->set_node_count_before_unroll(loop->_body.size());
1972 
1973   Node *ctrl  = loop_head->skip_strip_mined()->in(LoopNode::EntryControl);
1974   Node *limit = loop_head->limit();
1975   Node *init  = loop_head->init_trip();
1976   Node *stride = loop_head->stride();
1977 
1978   Node *opaq = NULL;
1979   if (adjust_min_trip) {       // If not maximally unrolling, need adjustment
1980     // Search for zero-trip guard.
1981 
1982     // Check the shape of the graph at the loop entry. If an inappropriate
1983     // graph shape is encountered, the compiler bails out loop unrolling;
1984     // compilation of the method will still succeed.
1985     if (!is_canonical_loop_entry(loop_head)) {
1986       return;
1987     }
1988     opaq = loop_head->skip_predicates()->in(0)->in(1)->in(1)->in(2);
1989     // Zero-trip test uses an 'opaque' node which is not shared.
1990     assert(opaq->outcnt() == 1 && opaq->in(1) == limit, "");
1991   }
1992 
1993   C->set_major_progress();
1994 
1995   Node* new_limit = NULL;
1996   int stride_con = stride->get_int();
1997   int stride_p = (stride_con > 0) ? stride_con : -stride_con;
1998   uint old_trip_count = loop_head->trip_count();
1999   // Verify that unroll policy result is still valid.
2000   assert(old_trip_count > 1 &&
2001       (!adjust_min_trip || stride_p <= (1<<3)*loop_head->unrolled_count()), "sanity");
2002 
2003   update_main_loop_skeleton_predicates(ctrl, loop_head, init, stride_con);
2004 
2005   // Adjust loop limit to keep valid iterations number after unroll.
2006   // Use (limit - stride) instead of (((limit - init)/stride) & (-2))*stride
2007   // which may overflow.
2008   if (!adjust_min_trip) {
2009     assert(old_trip_count > 1 && (old_trip_count & 1) == 0,
2010         "odd trip count for maximally unroll");
2011     // Don't need to adjust limit for maximally unroll since trip count is even.
2012   } else if (loop_head->has_exact_trip_count() && init->is_Con()) {
2013     // Loop's limit is constant. Loop's init could be constant when pre-loop
2014     // become peeled iteration.
2015     jlong init_con = init->get_int();
2016     // We can keep old loop limit if iterations count stays the same:
2017     //   old_trip_count == new_trip_count * 2
2018     // Note: since old_trip_count >= 2 then new_trip_count >= 1
2019     // so we also don't need to adjust zero trip test.
2020     jlong limit_con  = limit->get_int();
2021     // (stride_con*2) not overflow since stride_con <= 8.
2022     int new_stride_con = stride_con * 2;
2023     int stride_m    = new_stride_con - (stride_con > 0 ? 1 : -1);
2024     jlong trip_count = (limit_con - init_con + stride_m)/new_stride_con;
2025     // New trip count should satisfy next conditions.
2026     assert(trip_count > 0 && (julong)trip_count < (julong)max_juint/2, "sanity");
2027     uint new_trip_count = (uint)trip_count;
2028     adjust_min_trip = (old_trip_count != new_trip_count*2);
2029   }
2030 
2031   if (adjust_min_trip) {
2032     // Step 2: Adjust the trip limit if it is called for.
2033     // The adjustment amount is -stride. Need to make sure if the
2034     // adjustment underflows or overflows, then the main loop is skipped.
2035     Node* cmp = loop_end->cmp_node();
2036     assert(cmp->in(2) == limit, "sanity");
2037     assert(opaq != NULL && opaq->in(1) == limit, "sanity");
2038 
2039     // Verify that policy_unroll result is still valid.
2040     const TypeInt* limit_type = _igvn.type(limit)->is_int();
2041     assert(stride_con > 0 && ((limit_type->_hi - stride_con) < limit_type->_hi) ||
2042            stride_con < 0 && ((limit_type->_lo - stride_con) > limit_type->_lo),
2043            "sanity");
2044 
2045     if (limit->is_Con()) {
2046       // The check in policy_unroll and the assert above guarantee
2047       // no underflow if limit is constant.
2048       new_limit = _igvn.intcon(limit->get_int() - stride_con);
2049       set_ctrl(new_limit, C->root());
2050     } else {
2051       // Limit is not constant.
2052       if (loop_head->unrolled_count() == 1) { // only for first unroll
2053         // Separate limit by Opaque node in case it is an incremented
2054         // variable from previous loop to avoid using pre-incremented
2055         // value which could increase register pressure.
2056         // Otherwise reorg_offsets() optimization will create a separate
2057         // Opaque node for each use of trip-counter and as result
2058         // zero trip guard limit will be different from loop limit.
2059         assert(has_ctrl(opaq), "should have it");
2060         Node* opaq_ctrl = get_ctrl(opaq);
2061         limit = new Opaque2Node(C, limit);
2062         register_new_node(limit, opaq_ctrl);
2063       }
2064       if ((stride_con > 0 && (java_subtract(limit_type->_lo, stride_con) < limit_type->_lo)) ||
2065           (stride_con < 0 && (java_subtract(limit_type->_hi, stride_con) > limit_type->_hi))) {
2066         // No underflow.
2067         new_limit = new SubINode(limit, stride);
2068       } else {
2069         // (limit - stride) may underflow.
2070         // Clamp the adjustment value with MININT or MAXINT:
2071         //
2072         //   new_limit = limit-stride
2073         //   if (stride > 0)
2074         //     new_limit = (limit < new_limit) ? MININT : new_limit;
2075         //   else
2076         //     new_limit = (limit > new_limit) ? MAXINT : new_limit;
2077         //
2078         BoolTest::mask bt = loop_end->test_trip();
2079         assert(bt == BoolTest::lt || bt == BoolTest::gt, "canonical test is expected");
2080         Node* adj_max = _igvn.intcon((stride_con > 0) ? min_jint : max_jint);
2081         set_ctrl(adj_max, C->root());
2082         Node* old_limit = NULL;
2083         Node* adj_limit = NULL;
2084         Node* bol = limit->is_CMove() ? limit->in(CMoveNode::Condition) : NULL;
2085         if (loop_head->unrolled_count() > 1 &&
2086             limit->is_CMove() && limit->Opcode() == Op_CMoveI &&
2087             limit->in(CMoveNode::IfTrue) == adj_max &&
2088             bol->as_Bool()->_test._test == bt &&
2089             bol->in(1)->Opcode() == Op_CmpI &&
2090             bol->in(1)->in(2) == limit->in(CMoveNode::IfFalse)) {
2091           // Loop was unrolled before.
2092           // Optimize the limit to avoid nested CMove:
2093           // use original limit as old limit.
2094           old_limit = bol->in(1)->in(1);
2095           // Adjust previous adjusted limit.
2096           adj_limit = limit->in(CMoveNode::IfFalse);
2097           adj_limit = new SubINode(adj_limit, stride);
2098         } else {
2099           old_limit = limit;
2100           adj_limit = new SubINode(limit, stride);
2101         }
2102         assert(old_limit != NULL && adj_limit != NULL, "");
2103         register_new_node(adj_limit, ctrl); // adjust amount
2104         Node* adj_cmp = new CmpINode(old_limit, adj_limit);
2105         register_new_node(adj_cmp, ctrl);
2106         Node* adj_bool = new BoolNode(adj_cmp, bt);
2107         register_new_node(adj_bool, ctrl);
2108         new_limit = new CMoveINode(adj_bool, adj_limit, adj_max, TypeInt::INT);
2109       }
2110       register_new_node(new_limit, ctrl);
2111     }
2112 
2113     assert(new_limit != NULL, "");
2114     // Replace in loop test.
2115     assert(loop_end->in(1)->in(1) == cmp, "sanity");
2116     if (cmp->outcnt() == 1 && loop_end->in(1)->outcnt() == 1) {
2117       // Don't need to create new test since only one user.
2118       _igvn.hash_delete(cmp);
2119       cmp->set_req(2, new_limit);
2120     } else {
2121       // Create new test since it is shared.
2122       Node* ctrl2 = loop_end->in(0);
2123       Node* cmp2  = cmp->clone();
2124       cmp2->set_req(2, new_limit);
2125       register_new_node(cmp2, ctrl2);
2126       Node* bol2 = loop_end->in(1)->clone();
2127       bol2->set_req(1, cmp2);
2128       register_new_node(bol2, ctrl2);
2129       _igvn.replace_input_of(loop_end, 1, bol2);
2130     }
2131     // Step 3: Find the min-trip test guaranteed before a 'main' loop.
2132     // Make it a 1-trip test (means at least 2 trips).
2133 
2134     // Guard test uses an 'opaque' node which is not shared.  Hence I
2135     // can edit it's inputs directly.  Hammer in the new limit for the
2136     // minimum-trip guard.
2137     assert(opaq->outcnt() == 1, "");
2138     _igvn.replace_input_of(opaq, 1, new_limit);
2139   }
2140 
2141   // Adjust max trip count. The trip count is intentionally rounded
2142   // down here (e.g. 15-> 7-> 3-> 1) because if we unwittingly over-unroll,
2143   // the main, unrolled, part of the loop will never execute as it is protected
2144   // by the min-trip test.  See bug 4834191 for a case where we over-unrolled
2145   // and later determined that part of the unrolled loop was dead.
2146   loop_head->set_trip_count(old_trip_count / 2);
2147 
2148   // Double the count of original iterations in the unrolled loop body.
2149   loop_head->double_unrolled_count();
2150 
2151   // ---------
2152   // Step 4: Clone the loop body.  Move it inside the loop.  This loop body
2153   // represents the odd iterations; since the loop trips an even number of
2154   // times its backedge is never taken.  Kill the backedge.
2155   uint dd = dom_depth(loop_head);
2156   clone_loop(loop, old_new, dd, IgnoreStripMined);
2157 
2158   // Make backedges of the clone equal to backedges of the original.
2159   // Make the fall-in from the original come from the fall-out of the clone.
2160   for (DUIterator_Fast jmax, j = loop_head->fast_outs(jmax); j < jmax; j++) {
2161     Node* phi = loop_head->fast_out(j);
2162     if (phi->is_Phi() && phi->in(0) == loop_head && phi->outcnt() > 0) {
2163       Node *newphi = old_new[phi->_idx];
2164       _igvn.hash_delete(phi);
2165       _igvn.hash_delete(newphi);
2166 
2167       phi   ->set_req(LoopNode::   EntryControl, newphi->in(LoopNode::LoopBackControl));
2168       newphi->set_req(LoopNode::LoopBackControl, phi   ->in(LoopNode::LoopBackControl));
2169       phi   ->set_req(LoopNode::LoopBackControl, C->top());
2170     }
2171   }
2172   Node *clone_head = old_new[loop_head->_idx];
2173   _igvn.hash_delete(clone_head);
2174   loop_head ->set_req(LoopNode::   EntryControl, clone_head->in(LoopNode::LoopBackControl));
2175   clone_head->set_req(LoopNode::LoopBackControl, loop_head ->in(LoopNode::LoopBackControl));
2176   loop_head ->set_req(LoopNode::LoopBackControl, C->top());
2177   loop->_head = clone_head;     // New loop header
2178 
2179   set_idom(loop_head,  loop_head ->in(LoopNode::EntryControl), dd);
2180   set_idom(clone_head, clone_head->in(LoopNode::EntryControl), dd);
2181 
2182   // Kill the clone's backedge
2183   Node *newcle = old_new[loop_end->_idx];
2184   _igvn.hash_delete(newcle);
2185   Node *one = _igvn.intcon(1);
2186   set_ctrl(one, C->root());
2187   newcle->set_req(1, one);
2188   // Force clone into same loop body
2189   uint max = loop->_body.size();
2190   for (uint k = 0; k < max; k++) {
2191     Node *old = loop->_body.at(k);
2192     Node *nnn = old_new[old->_idx];
2193     loop->_body.push(nnn);
2194     if (!has_ctrl(old)) {
2195       set_loop(nnn, loop);
2196     }
2197   }
2198 
2199   loop->record_for_igvn();
2200   loop_head->clear_strip_mined();
2201 
2202 #ifndef PRODUCT
2203   if (C->do_vector_loop() && (PrintOpto && (VerifyLoopOptimizations || TraceLoopOpts))) {
2204     tty->print("\nnew loop after unroll\n");       loop->dump_head();
2205     for (uint i = 0; i < loop->_body.size(); i++) {
2206       loop->_body.at(i)->dump();
2207     }
2208     if (C->clone_map().is_debug()) {
2209       tty->print("\nCloneMap\n");
2210       Dict* dict = C->clone_map().dict();
2211       DictI i(dict);
2212       tty->print_cr("Dict@%p[%d] = ", dict, dict->Size());
2213       for (int ii = 0; i.test(); ++i, ++ii) {
2214         NodeCloneInfo cl((uint64_t)dict->operator[]((void*)i._key));
2215         tty->print("%d->%d:%d,", (int)(intptr_t)i._key, cl.idx(), cl.gen());
2216         if (ii % 10 == 9) {
2217           tty->print_cr(" ");
2218         }
2219       }
2220       tty->print_cr(" ");
2221     }
2222   }
2223 #endif
2224 }
2225 
2226 //------------------------------do_maximally_unroll----------------------------
2227 
do_maximally_unroll(IdealLoopTree * loop,Node_List & old_new)2228 void PhaseIdealLoop::do_maximally_unroll(IdealLoopTree *loop, Node_List &old_new) {
2229   CountedLoopNode *cl = loop->_head->as_CountedLoop();
2230   assert(cl->has_exact_trip_count(), "trip count is not exact");
2231   assert(cl->trip_count() > 0, "");
2232 #ifndef PRODUCT
2233   if (TraceLoopOpts) {
2234     tty->print("MaxUnroll  %d ", cl->trip_count());
2235     loop->dump_head();
2236   }
2237 #endif
2238 
2239   // If loop is tripping an odd number of times, peel odd iteration
2240   if ((cl->trip_count() & 1) == 1) {
2241     do_peeling(loop, old_new);
2242   }
2243 
2244   // Now its tripping an even number of times remaining.  Double loop body.
2245   // Do not adjust pre-guards; they are not needed and do not exist.
2246   if (cl->trip_count() > 0) {
2247     assert((cl->trip_count() & 1) == 0, "missed peeling");
2248     do_unroll(loop, old_new, false);
2249   }
2250 }
2251 
mark_reductions(IdealLoopTree * loop)2252 void PhaseIdealLoop::mark_reductions(IdealLoopTree *loop) {
2253   if (SuperWordReductions == false) return;
2254 
2255   CountedLoopNode* loop_head = loop->_head->as_CountedLoop();
2256   if (loop_head->unrolled_count() > 1) {
2257     return;
2258   }
2259 
2260   Node* trip_phi = loop_head->phi();
2261   for (DUIterator_Fast imax, i = loop_head->fast_outs(imax); i < imax; i++) {
2262     Node* phi = loop_head->fast_out(i);
2263     if (phi->is_Phi() && phi->outcnt() > 0 && phi != trip_phi) {
2264       // For definitions which are loop inclusive and not tripcounts.
2265       Node* def_node = phi->in(LoopNode::LoopBackControl);
2266 
2267       if (def_node != NULL) {
2268         Node* n_ctrl = get_ctrl(def_node);
2269         if (n_ctrl != NULL && loop->is_member(get_loop(n_ctrl))) {
2270           // Now test it to see if it fits the standard pattern for a reduction operator.
2271           int opc = def_node->Opcode();
2272           if (opc != ReductionNode::opcode(opc, def_node->bottom_type()->basic_type())
2273               || opc == Op_MinD || opc == Op_MinF || opc == Op_MaxD || opc == Op_MaxF) {
2274             if (!def_node->is_reduction()) { // Not marked yet
2275               // To be a reduction, the arithmetic node must have the phi as input and provide a def to it
2276               bool ok = false;
2277               for (unsigned j = 1; j < def_node->req(); j++) {
2278                 Node* in = def_node->in(j);
2279                 if (in == phi) {
2280                   ok = true;
2281                   break;
2282                 }
2283               }
2284 
2285               // do nothing if we did not match the initial criteria
2286               if (ok == false) {
2287                 continue;
2288               }
2289 
2290               // The result of the reduction must not be used in the loop
2291               for (DUIterator_Fast imax, i = def_node->fast_outs(imax); i < imax && ok; i++) {
2292                 Node* u = def_node->fast_out(i);
2293                 if (!loop->is_member(get_loop(ctrl_or_self(u)))) {
2294                   continue;
2295                 }
2296                 if (u == phi) {
2297                   continue;
2298                 }
2299                 ok = false;
2300               }
2301 
2302               // iff the uses conform
2303               if (ok) {
2304                 def_node->add_flag(Node::Flag_is_reduction);
2305                 loop_head->mark_has_reductions();
2306               }
2307             }
2308           }
2309         }
2310       }
2311     }
2312   }
2313 }
2314 
2315 //------------------------------adjust_limit-----------------------------------
2316 // Helper function that computes new loop limit as (rc_limit-offset)/scale
adjust_limit(bool is_positive_stride,Node * scale,Node * offset,Node * rc_limit,Node * old_limit,Node * pre_ctrl,bool round)2317 Node* PhaseIdealLoop::adjust_limit(bool is_positive_stride, Node* scale, Node* offset, Node* rc_limit, Node* old_limit, Node* pre_ctrl, bool round) {
2318   Node* sub = new SubLNode(rc_limit, offset);
2319   register_new_node(sub, pre_ctrl);
2320   Node* limit = new DivLNode(NULL, sub, scale);
2321   register_new_node(limit, pre_ctrl);
2322 
2323   // When the absolute value of scale is greater than one, the division
2324   // may round limit down/up, so add/sub one to/from the limit.
2325   if (round) {
2326     limit = new AddLNode(limit, _igvn.longcon(is_positive_stride ? -1 : 1));
2327     register_new_node(limit, pre_ctrl);
2328   }
2329 
2330   // Clamp the limit to handle integer under-/overflows.
2331   // When reducing the limit, clamp to [min_jint, old_limit]:
2332   //   MIN(old_limit, MAX(limit, min_jint))
2333   // When increasing the limit, clamp to [old_limit, max_jint]:
2334   //   MAX(old_limit, MIN(limit, max_jint))
2335   Node* cmp = new CmpLNode(limit, _igvn.longcon(is_positive_stride ? min_jint : max_jint));
2336   register_new_node(cmp, pre_ctrl);
2337   Node* bol = new BoolNode(cmp, is_positive_stride ? BoolTest::lt : BoolTest::gt);
2338   register_new_node(bol, pre_ctrl);
2339   limit = new ConvL2INode(limit);
2340   register_new_node(limit, pre_ctrl);
2341   limit = new CMoveINode(bol, limit, _igvn.intcon(is_positive_stride ? min_jint : max_jint), TypeInt::INT);
2342   register_new_node(limit, pre_ctrl);
2343 
2344   limit = is_positive_stride ? (Node*)(new MinINode(old_limit, limit))
2345                              : (Node*)(new MaxINode(old_limit, limit));
2346   register_new_node(limit, pre_ctrl);
2347   return limit;
2348 }
2349 
2350 //------------------------------add_constraint---------------------------------
2351 // Constrain the main loop iterations so the conditions:
2352 //    low_limit <= scale_con*I + offset < upper_limit
2353 // always hold true. That is, either increase the number of iterations in the
2354 // pre-loop or reduce the number of iterations in the main-loop until the condition
2355 // holds true in the main-loop. Stride, scale, offset and limit are all loop
2356 // invariant. Further, stride and scale are constants (offset and limit often are).
add_constraint(jlong stride_con,jlong scale_con,Node * offset,Node * low_limit,Node * upper_limit,Node * pre_ctrl,Node ** pre_limit,Node ** main_limit)2357 void PhaseIdealLoop::add_constraint(jlong stride_con, jlong scale_con, Node* offset, Node* low_limit, Node* upper_limit, Node* pre_ctrl, Node** pre_limit, Node** main_limit) {
2358   assert(_igvn.type(offset)->isa_long() != NULL && _igvn.type(low_limit)->isa_long() != NULL &&
2359          _igvn.type(upper_limit)->isa_long() != NULL, "arguments should be long values");
2360 
2361   // For a positive stride, we need to reduce the main-loop limit and
2362   // increase the pre-loop limit. This is reversed for a negative stride.
2363   bool is_positive_stride = (stride_con > 0);
2364 
2365   // If the absolute scale value is greater one, division in 'adjust_limit' may require
2366   // rounding. Make sure the ABS method correctly handles min_jint.
2367   // Only do this for the pre-loop, one less iteration of the main loop doesn't hurt.
2368   bool round = ABS(scale_con) > 1;
2369 
2370   Node* scale = _igvn.longcon(scale_con);
2371   set_ctrl(scale, C->root());
2372 
2373   if ((stride_con^scale_con) >= 0) { // Use XOR to avoid overflow
2374     // Positive stride*scale: the affine function is increasing,
2375     // the pre-loop checks for underflow and the post-loop for overflow.
2376 
2377     // The overflow limit: scale*I+offset < upper_limit
2378     // For the main-loop limit compute:
2379     //   ( if (scale > 0) /* and stride > 0 */
2380     //       I < (upper_limit-offset)/scale
2381     //     else /* scale < 0 and stride < 0 */
2382     //       I > (upper_limit-offset)/scale
2383     //   )
2384     *main_limit = adjust_limit(is_positive_stride, scale, offset, upper_limit, *main_limit, pre_ctrl, false);
2385 
2386     // The underflow limit: low_limit <= scale*I+offset
2387     // For the pre-loop limit compute:
2388     //   NOT(scale*I+offset >= low_limit)
2389     //   scale*I+offset < low_limit
2390     //   ( if (scale > 0) /* and stride > 0 */
2391     //       I < (low_limit-offset)/scale
2392     //     else /* scale < 0 and stride < 0 */
2393     //       I > (low_limit-offset)/scale
2394     //   )
2395     *pre_limit = adjust_limit(!is_positive_stride, scale, offset, low_limit, *pre_limit, pre_ctrl, round);
2396   } else {
2397     // Negative stride*scale: the affine function is decreasing,
2398     // the pre-loop checks for overflow and the post-loop for underflow.
2399 
2400     // The overflow limit: scale*I+offset < upper_limit
2401     // For the pre-loop limit compute:
2402     //   NOT(scale*I+offset < upper_limit)
2403     //   scale*I+offset >= upper_limit
2404     //   scale*I+offset+1 > upper_limit
2405     //   ( if (scale < 0) /* and stride > 0 */
2406     //       I < (upper_limit-(offset+1))/scale
2407     //     else /* scale > 0 and stride < 0 */
2408     //       I > (upper_limit-(offset+1))/scale
2409     //   )
2410     Node* one = _igvn.longcon(1);
2411     set_ctrl(one, C->root());
2412     Node* plus_one = new AddLNode(offset, one);
2413     register_new_node(plus_one, pre_ctrl);
2414     *pre_limit = adjust_limit(!is_positive_stride, scale, plus_one, upper_limit, *pre_limit, pre_ctrl, round);
2415 
2416     // The underflow limit: low_limit <= scale*I+offset
2417     // For the main-loop limit compute:
2418     //   scale*I+offset+1 > low_limit
2419     //   ( if (scale < 0) /* and stride > 0 */
2420     //       I < (low_limit-(offset+1))/scale
2421     //     else /* scale > 0 and stride < 0 */
2422     //       I > (low_limit-(offset+1))/scale
2423     //   )
2424     *main_limit = adjust_limit(is_positive_stride, scale, plus_one, low_limit, *main_limit, pre_ctrl, false);
2425   }
2426 }
2427 
2428 //------------------------------is_scaled_iv---------------------------------
2429 // Return true if exp is a constant times an induction var
is_scaled_iv(Node * exp,Node * iv,int * p_scale)2430 bool PhaseIdealLoop::is_scaled_iv(Node* exp, Node* iv, int* p_scale) {
2431   exp = exp->uncast();
2432   if (exp == iv) {
2433     if (p_scale != NULL) {
2434       *p_scale = 1;
2435     }
2436     return true;
2437   }
2438   int opc = exp->Opcode();
2439   if (opc == Op_MulI) {
2440     if (exp->in(1)->uncast() == iv && exp->in(2)->is_Con()) {
2441       if (p_scale != NULL) {
2442         *p_scale = exp->in(2)->get_int();
2443       }
2444       return true;
2445     }
2446     if (exp->in(2)->uncast() == iv && exp->in(1)->is_Con()) {
2447       if (p_scale != NULL) {
2448         *p_scale = exp->in(1)->get_int();
2449       }
2450       return true;
2451     }
2452   } else if (opc == Op_LShiftI) {
2453     if (exp->in(1)->uncast() == iv && exp->in(2)->is_Con()) {
2454       if (p_scale != NULL) {
2455         *p_scale = 1 << exp->in(2)->get_int();
2456       }
2457       return true;
2458     }
2459   }
2460   return false;
2461 }
2462 
2463 //-----------------------------is_scaled_iv_plus_offset------------------------------
2464 // Return true if exp is a simple induction variable expression: k1*iv + (invar + k2)
is_scaled_iv_plus_offset(Node * exp,Node * iv,int * p_scale,Node ** p_offset,int depth)2465 bool PhaseIdealLoop::is_scaled_iv_plus_offset(Node* exp, Node* iv, int* p_scale, Node** p_offset, int depth) {
2466   if (is_scaled_iv(exp, iv, p_scale)) {
2467     if (p_offset != NULL) {
2468       Node *zero = _igvn.intcon(0);
2469       set_ctrl(zero, C->root());
2470       *p_offset = zero;
2471     }
2472     return true;
2473   }
2474   exp = exp->uncast();
2475   int opc = exp->Opcode();
2476   if (opc == Op_AddI) {
2477     if (is_scaled_iv(exp->in(1), iv, p_scale)) {
2478       if (p_offset != NULL) {
2479         *p_offset = exp->in(2);
2480       }
2481       return true;
2482     }
2483     if (is_scaled_iv(exp->in(2), iv, p_scale)) {
2484       if (p_offset != NULL) {
2485         *p_offset = exp->in(1);
2486       }
2487       return true;
2488     }
2489     if (exp->in(2)->is_Con()) {
2490       Node* offset2 = NULL;
2491       if (depth < 2 &&
2492           is_scaled_iv_plus_offset(exp->in(1), iv, p_scale,
2493                                    p_offset != NULL ? &offset2 : NULL, depth+1)) {
2494         if (p_offset != NULL) {
2495           Node *ctrl_off2 = get_ctrl(offset2);
2496           Node* offset = new AddINode(offset2, exp->in(2));
2497           register_new_node(offset, ctrl_off2);
2498           *p_offset = offset;
2499         }
2500         return true;
2501       }
2502     }
2503   } else if (opc == Op_SubI) {
2504     if (is_scaled_iv(exp->in(1), iv, p_scale)) {
2505       if (p_offset != NULL) {
2506         Node *zero = _igvn.intcon(0);
2507         set_ctrl(zero, C->root());
2508         Node *ctrl_off = get_ctrl(exp->in(2));
2509         Node* offset = new SubINode(zero, exp->in(2));
2510         register_new_node(offset, ctrl_off);
2511         *p_offset = offset;
2512       }
2513       return true;
2514     }
2515     if (is_scaled_iv(exp->in(2), iv, p_scale)) {
2516       if (p_offset != NULL) {
2517         *p_scale *= -1;
2518         *p_offset = exp->in(1);
2519       }
2520       return true;
2521     }
2522   }
2523   return false;
2524 }
2525 
2526 // Same as PhaseIdealLoop::duplicate_predicates() but for range checks
2527 // eliminated by iteration splitting.
add_range_check_predicate(IdealLoopTree * loop,CountedLoopNode * cl,Node * predicate_proj,int scale_con,Node * offset,Node * limit,jint stride_con,Node * value)2528 Node* PhaseIdealLoop::add_range_check_predicate(IdealLoopTree* loop, CountedLoopNode* cl,
2529                                                 Node* predicate_proj, int scale_con, Node* offset,
2530                                                 Node* limit, jint stride_con, Node* value) {
2531   bool overflow = false;
2532   BoolNode* bol = rc_predicate(loop, predicate_proj, scale_con, offset, value, NULL, stride_con, limit, (stride_con > 0) != (scale_con > 0), overflow);
2533   Node* opaque_bol = new Opaque4Node(C, bol, _igvn.intcon(1));
2534   register_new_node(opaque_bol, predicate_proj);
2535   IfNode* new_iff = NULL;
2536   if (overflow) {
2537     new_iff = new IfNode(predicate_proj, opaque_bol, PROB_MAX, COUNT_UNKNOWN);
2538   } else {
2539     new_iff = new RangeCheckNode(predicate_proj, opaque_bol, PROB_MAX, COUNT_UNKNOWN);
2540   }
2541   register_control(new_iff, loop->_parent, predicate_proj);
2542   Node* iffalse = new IfFalseNode(new_iff);
2543   register_control(iffalse, _ltree_root, new_iff);
2544   ProjNode* iftrue = new IfTrueNode(new_iff);
2545   register_control(iftrue, loop->_parent, new_iff);
2546   Node *frame = new ParmNode(C->start(), TypeFunc::FramePtr);
2547   register_new_node(frame, C->start());
2548   Node* halt = new HaltNode(iffalse, frame, "range check predicate failed which is impossible");
2549   register_control(halt, _ltree_root, iffalse);
2550   C->root()->add_req(halt);
2551   return iftrue;
2552 }
2553 
2554 //------------------------------do_range_check---------------------------------
2555 // Eliminate range-checks and other trip-counter vs loop-invariant tests.
do_range_check(IdealLoopTree * loop,Node_List & old_new)2556 int PhaseIdealLoop::do_range_check(IdealLoopTree *loop, Node_List &old_new) {
2557 #ifndef PRODUCT
2558   if (PrintOpto && VerifyLoopOptimizations) {
2559     tty->print("Range Check Elimination ");
2560     loop->dump_head();
2561   } else if (TraceLoopOpts) {
2562     tty->print("RangeCheck   ");
2563     loop->dump_head();
2564   }
2565 #endif
2566 
2567   assert(RangeCheckElimination, "");
2568   CountedLoopNode *cl = loop->_head->as_CountedLoop();
2569   // If we fail before trying to eliminate range checks, set multiversion state
2570   int closed_range_checks = 1;
2571 
2572   // protect against stride not being a constant
2573   if (!cl->stride_is_con()) {
2574     return closed_range_checks;
2575   }
2576   // Find the trip counter; we are iteration splitting based on it
2577   Node *trip_counter = cl->phi();
2578   // Find the main loop limit; we will trim it's iterations
2579   // to not ever trip end tests
2580   Node *main_limit = cl->limit();
2581 
2582   // Check graph shape. Cannot optimize a loop if zero-trip
2583   // Opaque1 node is optimized away and then another round
2584   // of loop opts attempted.
2585   if (!is_canonical_loop_entry(cl)) {
2586     return closed_range_checks;
2587   }
2588 
2589   // Need to find the main-loop zero-trip guard
2590   Node *ctrl = cl->skip_predicates();
2591   Node *iffm = ctrl->in(0);
2592   Node *opqzm = iffm->in(1)->in(1)->in(2);
2593   assert(opqzm->in(1) == main_limit, "do not understand situation");
2594 
2595   // Find the pre-loop limit; we will expand its iterations to
2596   // not ever trip low tests.
2597   Node *p_f = iffm->in(0);
2598   // pre loop may have been optimized out
2599   if (p_f->Opcode() != Op_IfFalse) {
2600     return closed_range_checks;
2601   }
2602   CountedLoopEndNode *pre_end = p_f->in(0)->as_CountedLoopEnd();
2603   assert(pre_end->loopnode()->is_pre_loop(), "");
2604   Node *pre_opaq1 = pre_end->limit();
2605   // Occasionally it's possible for a pre-loop Opaque1 node to be
2606   // optimized away and then another round of loop opts attempted.
2607   // We can not optimize this particular loop in that case.
2608   if (pre_opaq1->Opcode() != Op_Opaque1) {
2609     return closed_range_checks;
2610   }
2611   Opaque1Node *pre_opaq = (Opaque1Node*)pre_opaq1;
2612   Node *pre_limit = pre_opaq->in(1);
2613 
2614   // Where do we put new limit calculations
2615   Node *pre_ctrl = pre_end->loopnode()->in(LoopNode::EntryControl);
2616 
2617   // Ensure the original loop limit is available from the
2618   // pre-loop Opaque1 node.
2619   Node *orig_limit = pre_opaq->original_loop_limit();
2620   if (orig_limit == NULL || _igvn.type(orig_limit) == Type::TOP) {
2621     return closed_range_checks;
2622   }
2623   // Must know if its a count-up or count-down loop
2624 
2625   int stride_con = cl->stride_con();
2626   Node* zero = _igvn.longcon(0);
2627   Node* one  = _igvn.longcon(1);
2628   // Use symmetrical int range [-max_jint,max_jint]
2629   Node* mini = _igvn.longcon(-max_jint);
2630   set_ctrl(zero, C->root());
2631   set_ctrl(one,  C->root());
2632   set_ctrl(mini, C->root());
2633 
2634   // Count number of range checks and reduce by load range limits, if zero,
2635   // the loop is in canonical form to multiversion.
2636   closed_range_checks = 0;
2637 
2638   Node* predicate_proj = cl->skip_strip_mined()->in(LoopNode::EntryControl);
2639   assert(predicate_proj->is_Proj() && predicate_proj->in(0)->is_If(), "if projection only");
2640 
2641   // Check loop body for tests of trip-counter plus loop-invariant vs loop-variant.
2642   for (uint i = 0; i < loop->_body.size(); i++) {
2643     Node *iff = loop->_body[i];
2644     if (iff->Opcode() == Op_If ||
2645         iff->Opcode() == Op_RangeCheck) { // Test?
2646       // Test is an IfNode, has 2 projections.  If BOTH are in the loop
2647       // we need loop unswitching instead of iteration splitting.
2648       closed_range_checks++;
2649       Node *exit = loop->is_loop_exit(iff);
2650       if (!exit) continue;
2651       int flip = (exit->Opcode() == Op_IfTrue) ? 1 : 0;
2652 
2653       // Get boolean condition to test
2654       Node *i1 = iff->in(1);
2655       if (!i1->is_Bool()) continue;
2656       BoolNode *bol = i1->as_Bool();
2657       BoolTest b_test = bol->_test;
2658       // Flip sense of test if exit condition is flipped
2659       if (flip) {
2660         b_test = b_test.negate();
2661       }
2662       // Get compare
2663       Node *cmp = bol->in(1);
2664 
2665       // Look for trip_counter + offset vs limit
2666       Node *rc_exp = cmp->in(1);
2667       Node *limit  = cmp->in(2);
2668       int scale_con= 1;        // Assume trip counter not scaled
2669 
2670       Node *limit_c = get_ctrl(limit);
2671       if (loop->is_member(get_loop(limit_c))) {
2672         // Compare might have operands swapped; commute them
2673         b_test = b_test.commute();
2674         rc_exp = cmp->in(2);
2675         limit  = cmp->in(1);
2676         limit_c = get_ctrl(limit);
2677         if (loop->is_member(get_loop(limit_c))) {
2678           continue;             // Both inputs are loop varying; cannot RCE
2679         }
2680       }
2681       // Here we know 'limit' is loop invariant
2682 
2683       // 'limit' maybe pinned below the zero trip test (probably from a
2684       // previous round of rce), in which case, it can't be used in the
2685       // zero trip test expression which must occur before the zero test's if.
2686       if (is_dominator(ctrl, limit_c)) {
2687         continue;  // Don't rce this check but continue looking for other candidates.
2688       }
2689 
2690       // Check for scaled induction variable plus an offset
2691       Node *offset = NULL;
2692 
2693       if (!is_scaled_iv_plus_offset(rc_exp, trip_counter, &scale_con, &offset)) {
2694         continue;
2695       }
2696 
2697       Node *offset_c = get_ctrl(offset);
2698       if (loop->is_member(get_loop(offset_c))) {
2699         continue;               // Offset is not really loop invariant
2700       }
2701       // Here we know 'offset' is loop invariant.
2702 
2703       // As above for the 'limit', the 'offset' maybe pinned below the
2704       // zero trip test.
2705       if (is_dominator(ctrl, offset_c)) {
2706         continue; // Don't rce this check but continue looking for other candidates.
2707       }
2708 #ifdef ASSERT
2709       if (TraceRangeLimitCheck) {
2710         tty->print_cr("RC bool node%s", flip ? " flipped:" : ":");
2711         bol->dump(2);
2712       }
2713 #endif
2714       // At this point we have the expression as:
2715       //   scale_con * trip_counter + offset :: limit
2716       // where scale_con, offset and limit are loop invariant.  Trip_counter
2717       // monotonically increases by stride_con, a constant.  Both (or either)
2718       // stride_con and scale_con can be negative which will flip about the
2719       // sense of the test.
2720 
2721       // Perform the limit computations in jlong to avoid overflow
2722       jlong lscale_con = scale_con;
2723       Node* int_offset = offset;
2724       offset = new ConvI2LNode(offset);
2725       register_new_node(offset, pre_ctrl);
2726       Node* int_limit = limit;
2727       limit = new ConvI2LNode(limit);
2728       register_new_node(limit, pre_ctrl);
2729 
2730       // Adjust pre and main loop limits to guard the correct iteration set
2731       if (cmp->Opcode() == Op_CmpU) { // Unsigned compare is really 2 tests
2732         if (b_test._test == BoolTest::lt) { // Range checks always use lt
2733           // The underflow and overflow limits: 0 <= scale*I+offset < limit
2734           add_constraint(stride_con, lscale_con, offset, zero, limit, pre_ctrl, &pre_limit, &main_limit);
2735           Node* init = cl->init_trip();
2736           Node* opaque_init = new OpaqueLoopInitNode(C, init);
2737           register_new_node(opaque_init, predicate_proj);
2738 
2739           // predicate on first value of first iteration
2740           predicate_proj = add_range_check_predicate(loop, cl, predicate_proj, scale_con, int_offset, int_limit, stride_con, init);
2741           assert(!skeleton_predicate_has_opaque(predicate_proj->in(0)->as_If()), "unexpected");
2742 
2743           // template predicate so it can be updated on next unrolling
2744           predicate_proj = add_range_check_predicate(loop, cl, predicate_proj, scale_con, int_offset, int_limit, stride_con, opaque_init);
2745           assert(skeleton_predicate_has_opaque(predicate_proj->in(0)->as_If()), "unexpected");
2746 
2747           Node* opaque_stride = new OpaqueLoopStrideNode(C, cl->stride());
2748           register_new_node(opaque_stride, predicate_proj);
2749           Node* max_value = new SubINode(opaque_stride, cl->stride());
2750           register_new_node(max_value, predicate_proj);
2751           max_value = new AddINode(opaque_init, max_value);
2752           register_new_node(max_value, predicate_proj);
2753           predicate_proj = add_range_check_predicate(loop, cl, predicate_proj, scale_con, int_offset, int_limit, stride_con, max_value);
2754           assert(skeleton_predicate_has_opaque(predicate_proj->in(0)->as_If()), "unexpected");
2755 
2756         } else {
2757           if (PrintOpto) {
2758             tty->print_cr("missed RCE opportunity");
2759           }
2760           continue;             // In release mode, ignore it
2761         }
2762       } else {                  // Otherwise work on normal compares
2763         switch(b_test._test) {
2764         case BoolTest::gt:
2765           // Fall into GE case
2766         case BoolTest::ge:
2767           // Convert (I*scale+offset) >= Limit to (I*(-scale)+(-offset)) <= -Limit
2768           lscale_con = -lscale_con;
2769           offset = new SubLNode(zero, offset);
2770           register_new_node(offset, pre_ctrl);
2771           limit  = new SubLNode(zero, limit);
2772           register_new_node(limit, pre_ctrl);
2773           // Fall into LE case
2774         case BoolTest::le:
2775           if (b_test._test != BoolTest::gt) {
2776             // Convert X <= Y to X < Y+1
2777             limit = new AddLNode(limit, one);
2778             register_new_node(limit, pre_ctrl);
2779           }
2780           // Fall into LT case
2781         case BoolTest::lt:
2782           // The underflow and overflow limits: MIN_INT <= scale*I+offset < limit
2783           // Note: (MIN_INT+1 == -MAX_INT) is used instead of MIN_INT here
2784           // to avoid problem with scale == -1: MIN_INT/(-1) == MIN_INT.
2785           add_constraint(stride_con, lscale_con, offset, mini, limit, pre_ctrl, &pre_limit, &main_limit);
2786           break;
2787         default:
2788           if (PrintOpto) {
2789             tty->print_cr("missed RCE opportunity");
2790           }
2791           continue;             // Unhandled case
2792         }
2793       }
2794 
2795       // Kill the eliminated test
2796       C->set_major_progress();
2797       Node *kill_con = _igvn.intcon(1-flip);
2798       set_ctrl(kill_con, C->root());
2799       _igvn.replace_input_of(iff, 1, kill_con);
2800       // Find surviving projection
2801       assert(iff->is_If(), "");
2802       ProjNode* dp = ((IfNode*)iff)->proj_out(1-flip);
2803       // Find loads off the surviving projection; remove their control edge
2804       for (DUIterator_Fast imax, i = dp->fast_outs(imax); i < imax; i++) {
2805         Node* cd = dp->fast_out(i); // Control-dependent node
2806         if (cd->is_Load() && cd->depends_only_on_test()) {   // Loads can now float around in the loop
2807           // Allow the load to float around in the loop, or before it
2808           // but NOT before the pre-loop.
2809           _igvn.replace_input_of(cd, 0, ctrl); // ctrl, not NULL
2810           --i;
2811           --imax;
2812         }
2813       }
2814       if (int_limit->Opcode() == Op_LoadRange) {
2815         closed_range_checks--;
2816       }
2817     } // End of is IF
2818   }
2819   if (predicate_proj != cl->skip_strip_mined()->in(LoopNode::EntryControl)) {
2820     _igvn.replace_input_of(cl->skip_strip_mined(), LoopNode::EntryControl, predicate_proj);
2821     set_idom(cl->skip_strip_mined(), predicate_proj, dom_depth(cl->skip_strip_mined()));
2822   }
2823 
2824   // Update loop limits
2825   if (pre_limit != orig_limit) {
2826     // Computed pre-loop limit can be outside of loop iterations range.
2827     pre_limit = (stride_con > 0) ? (Node*)new MinINode(pre_limit, orig_limit)
2828                                  : (Node*)new MaxINode(pre_limit, orig_limit);
2829     register_new_node(pre_limit, pre_ctrl);
2830   }
2831   _igvn.replace_input_of(pre_opaq, 1, pre_limit);
2832 
2833   // Note:: we are making the main loop limit no longer precise;
2834   // need to round up based on stride.
2835   cl->set_nonexact_trip_count();
2836   Node *main_cle = cl->loopexit();
2837   Node *main_bol = main_cle->in(1);
2838   // Hacking loop bounds; need private copies of exit test
2839   if (main_bol->outcnt() > 1) {     // BoolNode shared?
2840     main_bol = main_bol->clone();   // Clone a private BoolNode
2841     register_new_node(main_bol, main_cle->in(0));
2842     _igvn.replace_input_of(main_cle, 1, main_bol);
2843   }
2844   Node *main_cmp = main_bol->in(1);
2845   if (main_cmp->outcnt() > 1) {     // CmpNode shared?
2846     main_cmp = main_cmp->clone();   // Clone a private CmpNode
2847     register_new_node(main_cmp, main_cle->in(0));
2848     _igvn.replace_input_of(main_bol, 1, main_cmp);
2849   }
2850   // Hack the now-private loop bounds
2851   _igvn.replace_input_of(main_cmp, 2, main_limit);
2852   // The OpaqueNode is unshared by design
2853   assert(opqzm->outcnt() == 1, "cannot hack shared node");
2854   _igvn.replace_input_of(opqzm, 1, main_limit);
2855 
2856   return closed_range_checks;
2857 }
2858 
2859 //------------------------------has_range_checks-------------------------------
2860 // Check to see if RCE cleaned the current loop of range-checks.
has_range_checks(IdealLoopTree * loop)2861 void PhaseIdealLoop::has_range_checks(IdealLoopTree *loop) {
2862   assert(RangeCheckElimination, "");
2863 
2864   // skip if not a counted loop
2865   if (!loop->is_counted()) return;
2866 
2867   CountedLoopNode *cl = loop->_head->as_CountedLoop();
2868 
2869   // skip this loop if it is already checked
2870   if (cl->has_been_range_checked()) return;
2871 
2872   // Now check for existence of range checks
2873   for (uint i = 0; i < loop->_body.size(); i++) {
2874     Node *iff = loop->_body[i];
2875     int iff_opc = iff->Opcode();
2876     if (iff_opc == Op_If || iff_opc == Op_RangeCheck) {
2877       cl->mark_has_range_checks();
2878       break;
2879     }
2880   }
2881   cl->set_has_been_range_checked();
2882 }
2883 
2884 //-------------------------multi_version_post_loops----------------------------
2885 // Check the range checks that remain, if simple, use the bounds to guard
2886 // which version to a post loop we execute, one with range checks or one without
multi_version_post_loops(IdealLoopTree * rce_loop,IdealLoopTree * legacy_loop)2887 bool PhaseIdealLoop::multi_version_post_loops(IdealLoopTree *rce_loop, IdealLoopTree *legacy_loop) {
2888   bool multi_version_succeeded = false;
2889   assert(RangeCheckElimination, "");
2890   CountedLoopNode *legacy_cl = legacy_loop->_head->as_CountedLoop();
2891   assert(legacy_cl->is_post_loop(), "");
2892 
2893   // Check for existence of range checks using the unique instance to make a guard with
2894   Unique_Node_List worklist;
2895   for (uint i = 0; i < legacy_loop->_body.size(); i++) {
2896     Node *iff = legacy_loop->_body[i];
2897     int iff_opc = iff->Opcode();
2898     if (iff_opc == Op_If || iff_opc == Op_RangeCheck) {
2899       worklist.push(iff);
2900     }
2901   }
2902 
2903   // Find RCE'd post loop so that we can stage its guard.
2904   if (!is_canonical_loop_entry(legacy_cl)) return multi_version_succeeded;
2905   Node* ctrl = legacy_cl->in(LoopNode::EntryControl);
2906   Node* iffm = ctrl->in(0);
2907 
2908   // Now we test that both the post loops are connected
2909   Node* post_loop_region = iffm->in(0);
2910   if (post_loop_region == NULL) return multi_version_succeeded;
2911   if (!post_loop_region->is_Region()) return multi_version_succeeded;
2912   Node* covering_region = post_loop_region->in(RegionNode::Control+1);
2913   if (covering_region == NULL) return multi_version_succeeded;
2914   if (!covering_region->is_Region()) return multi_version_succeeded;
2915   Node* p_f = covering_region->in(RegionNode::Control);
2916   if (p_f == NULL) return multi_version_succeeded;
2917   if (!p_f->is_IfFalse()) return multi_version_succeeded;
2918   if (!p_f->in(0)->is_CountedLoopEnd()) return multi_version_succeeded;
2919   CountedLoopEndNode* rce_loop_end = p_f->in(0)->as_CountedLoopEnd();
2920   if (rce_loop_end == NULL) return multi_version_succeeded;
2921   CountedLoopNode* rce_cl = rce_loop_end->loopnode();
2922   if (rce_cl == NULL || !rce_cl->is_post_loop()) return multi_version_succeeded;
2923   CountedLoopNode *known_rce_cl = rce_loop->_head->as_CountedLoop();
2924   if (rce_cl != known_rce_cl) return multi_version_succeeded;
2925 
2926   // Then we fetch the cover entry test
2927   ctrl = rce_cl->in(LoopNode::EntryControl);
2928   if (!ctrl->is_IfTrue() && !ctrl->is_IfFalse()) return multi_version_succeeded;
2929 
2930 #ifndef PRODUCT
2931   if (TraceLoopOpts) {
2932     tty->print("PostMultiVersion\n");
2933     rce_loop->dump_head();
2934     legacy_loop->dump_head();
2935   }
2936 #endif
2937 
2938   // Now fetch the limit we want to compare against
2939   Node *limit = rce_cl->limit();
2940   bool first_time = true;
2941 
2942   // If we got this far, we identified the post loop which has been RCE'd and
2943   // we have a work list.  Now we will try to transform the if guard to cause
2944   // the loop pair to be multi version executed with the determination left to runtime
2945   // or the optimizer if full information is known about the given arrays at compile time.
2946   Node *last_min = NULL;
2947   multi_version_succeeded = true;
2948   while (worklist.size()) {
2949     Node* rc_iffm = worklist.pop();
2950     if (rc_iffm->is_If()) {
2951       Node *rc_bolzm = rc_iffm->in(1);
2952       if (rc_bolzm->is_Bool()) {
2953         Node *rc_cmpzm = rc_bolzm->in(1);
2954         if (rc_cmpzm->is_Cmp()) {
2955           Node *rc_left = rc_cmpzm->in(2);
2956           if (rc_left->Opcode() != Op_LoadRange) {
2957             multi_version_succeeded = false;
2958             break;
2959           }
2960           if (first_time) {
2961             last_min = rc_left;
2962             first_time = false;
2963           } else {
2964             Node *cur_min = new MinINode(last_min, rc_left);
2965             last_min = cur_min;
2966             _igvn.register_new_node_with_optimizer(last_min);
2967           }
2968         }
2969       }
2970     }
2971   }
2972 
2973   // All we have to do is update the limit of the rce loop
2974   // with the min of our expression and the current limit.
2975   // We will use this expression to replace the current limit.
2976   if (last_min && multi_version_succeeded) {
2977     Node *cur_min = new MinINode(last_min, limit);
2978     _igvn.register_new_node_with_optimizer(cur_min);
2979     Node *cmp_node = rce_loop_end->cmp_node();
2980     _igvn.replace_input_of(cmp_node, 2, cur_min);
2981     set_ctrl(cur_min, ctrl);
2982     set_loop(cur_min, rce_loop->_parent);
2983 
2984     legacy_cl->mark_is_multiversioned();
2985     rce_cl->mark_is_multiversioned();
2986     multi_version_succeeded = true;
2987 
2988     C->set_major_progress();
2989   }
2990 
2991   return multi_version_succeeded;
2992 }
2993 
2994 //-------------------------poison_rce_post_loop--------------------------------
2995 // Causes the rce'd post loop to be optimized away if multiversioning fails
poison_rce_post_loop(IdealLoopTree * rce_loop)2996 void PhaseIdealLoop::poison_rce_post_loop(IdealLoopTree *rce_loop) {
2997   CountedLoopNode *rce_cl = rce_loop->_head->as_CountedLoop();
2998   Node* ctrl = rce_cl->in(LoopNode::EntryControl);
2999   if (ctrl->is_IfTrue() || ctrl->is_IfFalse()) {
3000     Node* iffm = ctrl->in(0);
3001     if (iffm->is_If()) {
3002       Node* cur_bool = iffm->in(1);
3003       if (cur_bool->is_Bool()) {
3004         Node* cur_cmp = cur_bool->in(1);
3005         if (cur_cmp->is_Cmp()) {
3006           BoolTest::mask new_test = BoolTest::gt;
3007           BoolNode *new_bool = new BoolNode(cur_cmp, new_test);
3008           _igvn.replace_node(cur_bool, new_bool);
3009           _igvn._worklist.push(new_bool);
3010           Node* left_op = cur_cmp->in(1);
3011           _igvn.replace_input_of(cur_cmp, 2, left_op);
3012           C->set_major_progress();
3013         }
3014       }
3015     }
3016   }
3017 }
3018 
3019 //------------------------------DCE_loop_body----------------------------------
3020 // Remove simplistic dead code from loop body
DCE_loop_body()3021 void IdealLoopTree::DCE_loop_body() {
3022   for (uint i = 0; i < _body.size(); i++) {
3023     if (_body.at(i)->outcnt() == 0) {
3024       _body.map(i, _body.pop());
3025       i--; // Ensure we revisit the updated index.
3026     }
3027   }
3028 }
3029 
3030 
3031 //------------------------------adjust_loop_exit_prob--------------------------
3032 // Look for loop-exit tests with the 50/50 (or worse) guesses from the parsing stage.
3033 // Replace with a 1-in-10 exit guess.
adjust_loop_exit_prob(PhaseIdealLoop * phase)3034 void IdealLoopTree::adjust_loop_exit_prob(PhaseIdealLoop *phase) {
3035   Node *test = tail();
3036   while (test != _head) {
3037     uint top = test->Opcode();
3038     if (top == Op_IfTrue || top == Op_IfFalse) {
3039       int test_con = ((ProjNode*)test)->_con;
3040       assert(top == (uint)(test_con? Op_IfTrue: Op_IfFalse), "sanity");
3041       IfNode *iff = test->in(0)->as_If();
3042       if (iff->outcnt() == 2) {         // Ignore dead tests
3043         Node *bol = iff->in(1);
3044         if (bol && bol->req() > 1 && bol->in(1) &&
3045             ((bol->in(1)->Opcode() == Op_StorePConditional) ||
3046              (bol->in(1)->Opcode() == Op_StoreIConditional) ||
3047              (bol->in(1)->Opcode() == Op_StoreLConditional) ||
3048              (bol->in(1)->Opcode() == Op_CompareAndExchangeB) ||
3049              (bol->in(1)->Opcode() == Op_CompareAndExchangeS) ||
3050              (bol->in(1)->Opcode() == Op_CompareAndExchangeI) ||
3051              (bol->in(1)->Opcode() == Op_CompareAndExchangeL) ||
3052              (bol->in(1)->Opcode() == Op_CompareAndExchangeP) ||
3053              (bol->in(1)->Opcode() == Op_CompareAndExchangeN) ||
3054              (bol->in(1)->Opcode() == Op_WeakCompareAndSwapB) ||
3055              (bol->in(1)->Opcode() == Op_WeakCompareAndSwapS) ||
3056              (bol->in(1)->Opcode() == Op_WeakCompareAndSwapI) ||
3057              (bol->in(1)->Opcode() == Op_WeakCompareAndSwapL) ||
3058              (bol->in(1)->Opcode() == Op_WeakCompareAndSwapP) ||
3059              (bol->in(1)->Opcode() == Op_WeakCompareAndSwapN) ||
3060              (bol->in(1)->Opcode() == Op_CompareAndSwapB) ||
3061              (bol->in(1)->Opcode() == Op_CompareAndSwapS) ||
3062              (bol->in(1)->Opcode() == Op_CompareAndSwapI) ||
3063              (bol->in(1)->Opcode() == Op_CompareAndSwapL) ||
3064              (bol->in(1)->Opcode() == Op_CompareAndSwapP) ||
3065              (bol->in(1)->Opcode() == Op_CompareAndSwapN) ||
3066              (bol->in(1)->Opcode() == Op_ShenandoahCompareAndExchangeP) ||
3067              (bol->in(1)->Opcode() == Op_ShenandoahCompareAndExchangeN) ||
3068              (bol->in(1)->Opcode() == Op_ShenandoahWeakCompareAndSwapP) ||
3069              (bol->in(1)->Opcode() == Op_ShenandoahWeakCompareAndSwapN) ||
3070              (bol->in(1)->Opcode() == Op_ShenandoahCompareAndSwapP) ||
3071              (bol->in(1)->Opcode() == Op_ShenandoahCompareAndSwapN)))
3072           return;               // Allocation loops RARELY take backedge
3073         // Find the OTHER exit path from the IF
3074         Node* ex = iff->proj_out(1-test_con);
3075         float p = iff->_prob;
3076         if (!phase->is_member(this, ex) && iff->_fcnt == COUNT_UNKNOWN) {
3077           if (top == Op_IfTrue) {
3078             if (p < (PROB_FAIR + PROB_UNLIKELY_MAG(3))) {
3079               iff->_prob = PROB_STATIC_FREQUENT;
3080             }
3081           } else {
3082             if (p > (PROB_FAIR - PROB_UNLIKELY_MAG(3))) {
3083               iff->_prob = PROB_STATIC_INFREQUENT;
3084             }
3085           }
3086         }
3087       }
3088     }
3089     test = phase->idom(test);
3090   }
3091 }
3092 
3093 #ifdef ASSERT
locate_pre_from_main(CountedLoopNode * main_loop)3094 static CountedLoopNode* locate_pre_from_main(CountedLoopNode* main_loop) {
3095   assert(!main_loop->is_main_no_pre_loop(), "Does not have a pre loop");
3096   Node* ctrl = main_loop->skip_predicates();
3097   assert(ctrl->Opcode() == Op_IfTrue || ctrl->Opcode() == Op_IfFalse, "");
3098   Node* iffm = ctrl->in(0);
3099   assert(iffm->Opcode() == Op_If, "");
3100   Node* p_f = iffm->in(0);
3101   assert(p_f->Opcode() == Op_IfFalse, "");
3102   CountedLoopNode* pre_loop = p_f->in(0)->as_CountedLoopEnd()->loopnode();
3103   assert(pre_loop->is_pre_loop(), "No pre loop found");
3104   return pre_loop;
3105 }
3106 #endif
3107 
3108 // Remove the main and post loops and make the pre loop execute all
3109 // iterations. Useful when the pre loop is found empty.
remove_main_post_loops(CountedLoopNode * cl,PhaseIdealLoop * phase)3110 void IdealLoopTree::remove_main_post_loops(CountedLoopNode *cl, PhaseIdealLoop *phase) {
3111   CountedLoopEndNode* pre_end = cl->loopexit();
3112   Node* pre_cmp = pre_end->cmp_node();
3113   if (pre_cmp->in(2)->Opcode() != Op_Opaque1) {
3114     // Only safe to remove the main loop if the compiler optimized it
3115     // out based on an unknown number of iterations
3116     return;
3117   }
3118 
3119   // Can we find the main loop?
3120   if (_next == NULL) {
3121     return;
3122   }
3123 
3124   Node* next_head = _next->_head;
3125   if (!next_head->is_CountedLoop()) {
3126     return;
3127   }
3128 
3129   CountedLoopNode* main_head = next_head->as_CountedLoop();
3130   if (!main_head->is_main_loop() || main_head->is_main_no_pre_loop()) {
3131     return;
3132   }
3133 
3134   assert(locate_pre_from_main(main_head) == cl, "bad main loop");
3135   Node* main_iff = main_head->skip_predicates()->in(0);
3136 
3137   // Remove the Opaque1Node of the pre loop and make it execute all iterations
3138   phase->_igvn.replace_input_of(pre_cmp, 2, pre_cmp->in(2)->in(2));
3139   // Remove the Opaque1Node of the main loop so it can be optimized out
3140   Node* main_cmp = main_iff->in(1)->in(1);
3141   assert(main_cmp->in(2)->Opcode() == Op_Opaque1, "main loop has no opaque node?");
3142   phase->_igvn.replace_input_of(main_cmp, 2, main_cmp->in(2)->in(1));
3143 }
3144 
3145 //------------------------------do_remove_empty_loop---------------------------
3146 // We always attempt remove empty loops.   The approach is to replace the trip
3147 // counter with the value it will have on the last iteration.  This will break
3148 // the loop.
do_remove_empty_loop(PhaseIdealLoop * phase)3149 bool IdealLoopTree::do_remove_empty_loop(PhaseIdealLoop *phase) {
3150   // Minimum size must be empty loop
3151   if (_body.size() > EMPTY_LOOP_SIZE) {
3152     return false;
3153   }
3154   if (!_head->is_CountedLoop()) {
3155     return false;   // Dead loop
3156   }
3157   CountedLoopNode *cl = _head->as_CountedLoop();
3158   if (!cl->is_valid_counted_loop(T_INT)) {
3159     return false;   // Malformed loop
3160   }
3161   if (!phase->is_member(this, phase->get_ctrl(cl->loopexit()->in(CountedLoopEndNode::TestValue)))) {
3162     return false;   // Infinite loop
3163   }
3164   if (cl->is_pre_loop()) {
3165     // If the loop we are removing is a pre-loop then the main and post loop
3166     // can be removed as well.
3167     remove_main_post_loops(cl, phase);
3168   }
3169 
3170 #ifdef ASSERT
3171   // Ensure only one phi which is the iv.
3172   Node* iv = NULL;
3173   for (DUIterator_Fast imax, i = cl->fast_outs(imax); i < imax; i++) {
3174     Node* n = cl->fast_out(i);
3175     if (n->Opcode() == Op_Phi) {
3176       assert(iv == NULL, "Too many phis");
3177       iv = n;
3178     }
3179   }
3180   assert(iv == cl->phi(), "Wrong phi");
3181 #endif
3182 
3183   // main and post loops have explicitly created zero trip guard
3184   bool needs_guard = !cl->is_main_loop() && !cl->is_post_loop();
3185   if (needs_guard) {
3186     // Skip guard if values not overlap.
3187     const TypeInt* init_t = phase->_igvn.type(cl->init_trip())->is_int();
3188     const TypeInt* limit_t = phase->_igvn.type(cl->limit())->is_int();
3189     int  stride_con = cl->stride_con();
3190     if (stride_con > 0) {
3191       needs_guard = (init_t->_hi >= limit_t->_lo);
3192     } else {
3193       needs_guard = (init_t->_lo <= limit_t->_hi);
3194     }
3195   }
3196   if (needs_guard) {
3197     // Check for an obvious zero trip guard.
3198     Node* inctrl = PhaseIdealLoop::skip_all_loop_predicates(cl->skip_predicates());
3199     if (inctrl->Opcode() == Op_IfTrue || inctrl->Opcode() == Op_IfFalse) {
3200       bool maybe_swapped = (inctrl->Opcode() == Op_IfFalse);
3201       // The test should look like just the backedge of a CountedLoop
3202       Node* iff = inctrl->in(0);
3203       if (iff->is_If()) {
3204         Node* bol = iff->in(1);
3205         if (bol->is_Bool()) {
3206           BoolTest test = bol->as_Bool()->_test;
3207           if (maybe_swapped) {
3208             test._test = test.commute();
3209             test._test = test.negate();
3210           }
3211           if (test._test == cl->loopexit()->test_trip()) {
3212             Node* cmp = bol->in(1);
3213             int init_idx = maybe_swapped ? 2 : 1;
3214             int limit_idx = maybe_swapped ? 1 : 2;
3215             if (cmp->is_Cmp() && cmp->in(init_idx) == cl->init_trip() && cmp->in(limit_idx) == cl->limit()) {
3216               needs_guard = false;
3217             }
3218           }
3219         }
3220       }
3221     }
3222   }
3223 
3224 #ifndef PRODUCT
3225   if (PrintOpto) {
3226     tty->print("Removing empty loop with%s zero trip guard", needs_guard ? "out" : "");
3227     this->dump_head();
3228   } else if (TraceLoopOpts) {
3229     tty->print("Empty with%s zero trip guard   ", needs_guard ? "out" : "");
3230     this->dump_head();
3231   }
3232 #endif
3233 
3234   if (needs_guard) {
3235     // Peel the loop to ensure there's a zero trip guard
3236     Node_List old_new;
3237     phase->do_peeling(this, old_new);
3238   }
3239 
3240   // Replace the phi at loop head with the final value of the last
3241   // iteration.  Then the CountedLoopEnd will collapse (backedge never
3242   // taken) and all loop-invariant uses of the exit values will be correct.
3243   Node *phi = cl->phi();
3244   Node *exact_limit = phase->exact_limit(this);
3245   if (exact_limit != cl->limit()) {
3246     // We also need to replace the original limit to collapse loop exit.
3247     Node* cmp = cl->loopexit()->cmp_node();
3248     assert(cl->limit() == cmp->in(2), "sanity");
3249     // Duplicate cmp node if it has other users
3250     if (cmp->outcnt() > 1) {
3251       cmp = cmp->clone();
3252       cmp = phase->_igvn.register_new_node_with_optimizer(cmp);
3253       BoolNode *bol = cl->loopexit()->in(CountedLoopEndNode::TestValue)->as_Bool();
3254       phase->_igvn.replace_input_of(bol, 1, cmp); // put bol on worklist
3255     }
3256     phase->_igvn._worklist.push(cmp->in(2)); // put limit on worklist
3257     phase->_igvn.replace_input_of(cmp, 2, exact_limit); // put cmp on worklist
3258   }
3259   // Note: the final value after increment should not overflow since
3260   // counted loop has limit check predicate.
3261   Node *final = new SubINode(exact_limit, cl->stride());
3262   phase->register_new_node(final,cl->in(LoopNode::EntryControl));
3263   phase->_igvn.replace_node(phi,final);
3264   phase->C->set_major_progress();
3265   return true;
3266 }
3267 
3268 //------------------------------do_one_iteration_loop--------------------------
3269 // Convert one iteration loop into normal code.
do_one_iteration_loop(PhaseIdealLoop * phase)3270 bool IdealLoopTree::do_one_iteration_loop(PhaseIdealLoop *phase) {
3271   if (!_head->as_Loop()->is_valid_counted_loop(T_INT)) {
3272     return false; // Only for counted loop
3273   }
3274   CountedLoopNode *cl = _head->as_CountedLoop();
3275   if (!cl->has_exact_trip_count() || cl->trip_count() != 1) {
3276     return false;
3277   }
3278 
3279 #ifndef PRODUCT
3280   if (TraceLoopOpts) {
3281     tty->print("OneIteration ");
3282     this->dump_head();
3283   }
3284 #endif
3285 
3286   Node *init_n = cl->init_trip();
3287   // Loop boundaries should be constant since trip count is exact.
3288   assert((cl->stride_con() > 0 && init_n->get_int() + cl->stride_con() >= cl->limit()->get_int()) ||
3289          (cl->stride_con() < 0 && init_n->get_int() + cl->stride_con() <= cl->limit()->get_int()), "should be one iteration");
3290   // Replace the phi at loop head with the value of the init_trip.
3291   // Then the CountedLoopEnd will collapse (backedge will not be taken)
3292   // and all loop-invariant uses of the exit values will be correct.
3293   phase->_igvn.replace_node(cl->phi(), cl->init_trip());
3294   phase->C->set_major_progress();
3295   return true;
3296 }
3297 
3298 //=============================================================================
3299 //------------------------------iteration_split_impl---------------------------
iteration_split_impl(PhaseIdealLoop * phase,Node_List & old_new)3300 bool IdealLoopTree::iteration_split_impl(PhaseIdealLoop *phase, Node_List &old_new) {
3301   // Compute loop trip count if possible.
3302   compute_trip_count(phase);
3303 
3304   // Convert one iteration loop into normal code.
3305   if (do_one_iteration_loop(phase)) {
3306     return true;
3307   }
3308   // Check and remove empty loops (spam micro-benchmarks)
3309   if (do_remove_empty_loop(phase)) {
3310     return true;  // Here we removed an empty loop
3311   }
3312 
3313   AutoNodeBudget node_budget(phase);
3314 
3315   // Non-counted loops may be peeled; exactly 1 iteration is peeled.
3316   // This removes loop-invariant tests (usually null checks).
3317   if (!_head->is_CountedLoop()) { // Non-counted loop
3318     if (PartialPeelLoop && phase->partial_peel(this, old_new)) {
3319       // Partial peel succeeded so terminate this round of loop opts
3320       return false;
3321     }
3322     if (policy_peeling(phase)) {    // Should we peel?
3323       if (PrintOpto) { tty->print_cr("should_peel"); }
3324       phase->do_peeling(this, old_new);
3325     } else if (policy_unswitching(phase)) {
3326       phase->do_unswitching(this, old_new);
3327     }
3328     return true;
3329   }
3330   CountedLoopNode *cl = _head->as_CountedLoop();
3331 
3332   if (!cl->is_valid_counted_loop(T_INT)) return true; // Ignore various kinds of broken loops
3333 
3334   // Do nothing special to pre- and post- loops
3335   if (cl->is_pre_loop() || cl->is_post_loop()) return true;
3336 
3337   // Compute loop trip count from profile data
3338   compute_profile_trip_cnt(phase);
3339 
3340   // Before attempting fancy unrolling, RCE or alignment, see if we want
3341   // to completely unroll this loop or do loop unswitching.
3342   if (cl->is_normal_loop()) {
3343     if (policy_unswitching(phase)) {
3344       phase->do_unswitching(this, old_new);
3345       return true;
3346     }
3347     if (policy_maximally_unroll(phase)) {
3348       // Here we did some unrolling and peeling.  Eventually we will
3349       // completely unroll this loop and it will no longer be a loop.
3350       phase->do_maximally_unroll(this, old_new);
3351       return true;
3352     }
3353   }
3354 
3355   uint est_peeling = estimate_peeling(phase);
3356   bool should_peel = 0 < est_peeling;
3357 
3358   // Counted loops may be peeled, or may need some iterations run up
3359   // front for RCE. Thus we clone a full loop up front whose trip count is
3360   // at least 1 (if peeling), but may be several more.
3361 
3362   // The main loop will start cache-line aligned with at least 1
3363   // iteration of the unrolled body (zero-trip test required) and
3364   // will have some range checks removed.
3365 
3366   // A post-loop will finish any odd iterations (leftover after
3367   // unrolling), plus any needed for RCE purposes.
3368 
3369   bool should_unroll = policy_unroll(phase);
3370   bool should_rce    = policy_range_check(phase);
3371 
3372   // If not RCE'ing (iteration splitting), then we do not need a pre-loop.
3373   // We may still need to peel an initial iteration but we will not
3374   // be needing an unknown number of pre-iterations.
3375   //
3376   // Basically, if peel_only reports TRUE first time through, we will not
3377   // be able to later do RCE on this loop.
3378   bool peel_only = policy_peel_only(phase) && !should_rce;
3379 
3380   // If we have any of these conditions (RCE, unrolling) met, then
3381   // we switch to the pre-/main-/post-loop model.  This model also covers
3382   // peeling.
3383   if (should_rce || should_unroll) {
3384     if (cl->is_normal_loop()) { // Convert to 'pre/main/post' loops
3385       uint estimate = est_loop_clone_sz(3);
3386       if (!phase->may_require_nodes(estimate)) {
3387         return false;
3388       }
3389       phase->insert_pre_post_loops(this, old_new, peel_only);
3390     }
3391     // Adjust the pre- and main-loop limits to let the pre and  post loops run
3392     // with full checks, but the main-loop with no checks.  Remove said checks
3393     // from the main body.
3394     if (should_rce) {
3395       if (phase->do_range_check(this, old_new) != 0) {
3396         cl->mark_has_range_checks();
3397       }
3398     } else if (PostLoopMultiversioning) {
3399       phase->has_range_checks(this);
3400     }
3401 
3402     if (should_unroll && !should_peel && PostLoopMultiversioning) {
3403       // Try to setup multiversioning on main loops before they are unrolled
3404       if (cl->is_main_loop() && (cl->unrolled_count() == 1)) {
3405         phase->insert_scalar_rced_post_loop(this, old_new);
3406       }
3407     }
3408 
3409     // Double loop body for unrolling.  Adjust the minimum-trip test (will do
3410     // twice as many iterations as before) and the main body limit (only do
3411     // an even number of trips).  If we are peeling, we might enable some RCE
3412     // and we'd rather unroll the post-RCE'd loop SO... do not unroll if
3413     // peeling.
3414     if (should_unroll && !should_peel) {
3415       if (SuperWordLoopUnrollAnalysis) {
3416         phase->insert_vector_post_loop(this, old_new);
3417       }
3418       phase->do_unroll(this, old_new, true);
3419     }
3420   } else {                      // Else we have an unchanged counted loop
3421     if (should_peel) {          // Might want to peel but do nothing else
3422       if (phase->may_require_nodes(est_peeling)) {
3423         phase->do_peeling(this, old_new);
3424       }
3425     }
3426   }
3427   return true;
3428 }
3429 
3430 
3431 //=============================================================================
3432 //------------------------------iteration_split--------------------------------
iteration_split(PhaseIdealLoop * phase,Node_List & old_new)3433 bool IdealLoopTree::iteration_split(PhaseIdealLoop* phase, Node_List &old_new) {
3434   // Recursively iteration split nested loops
3435   if (_child && !_child->iteration_split(phase, old_new)) {
3436     return false;
3437   }
3438 
3439   // Clean out prior deadwood
3440   DCE_loop_body();
3441 
3442   // Look for loop-exit tests with my 50/50 guesses from the Parsing stage.
3443   // Replace with a 1-in-10 exit guess.
3444   if (!is_root() && is_loop()) {
3445     adjust_loop_exit_prob(phase);
3446   }
3447 
3448   // Unrolling, RCE and peeling efforts, iff innermost loop.
3449   if (_allow_optimizations && is_innermost()) {
3450     if (!_has_call) {
3451       if (!iteration_split_impl(phase, old_new)) {
3452         return false;
3453       }
3454     } else {
3455       AutoNodeBudget node_budget(phase);
3456       if (policy_unswitching(phase)) {
3457         phase->do_unswitching(this, old_new);
3458       }
3459     }
3460   }
3461 
3462   // Minor offset re-organization to remove loop-fallout uses of
3463   // trip counter when there was no major reshaping.
3464   phase->reorg_offsets(this);
3465 
3466   if (_next && !_next->iteration_split(phase, old_new)) {
3467     return false;
3468   }
3469   return true;
3470 }
3471 
3472 
3473 //=============================================================================
3474 // Process all the loops in the loop tree and replace any fill
3475 // patterns with an intrinsic version.
do_intrinsify_fill()3476 bool PhaseIdealLoop::do_intrinsify_fill() {
3477   bool changed = false;
3478   for (LoopTreeIterator iter(_ltree_root); !iter.done(); iter.next()) {
3479     IdealLoopTree* lpt = iter.current();
3480     changed |= intrinsify_fill(lpt);
3481   }
3482   return changed;
3483 }
3484 
3485 
3486 // Examine an inner loop looking for a a single store of an invariant
3487 // value in a unit stride loop,
match_fill_loop(IdealLoopTree * lpt,Node * & store,Node * & store_value,Node * & shift,Node * & con)3488 bool PhaseIdealLoop::match_fill_loop(IdealLoopTree* lpt, Node*& store, Node*& store_value,
3489                                      Node*& shift, Node*& con) {
3490   const char* msg = NULL;
3491   Node* msg_node = NULL;
3492 
3493   store_value = NULL;
3494   con = NULL;
3495   shift = NULL;
3496 
3497   // Process the loop looking for stores.  If there are multiple
3498   // stores or extra control flow give at this point.
3499   CountedLoopNode* head = lpt->_head->as_CountedLoop();
3500   for (uint i = 0; msg == NULL && i < lpt->_body.size(); i++) {
3501     Node* n = lpt->_body.at(i);
3502     if (n->outcnt() == 0) continue; // Ignore dead
3503     if (n->is_Store()) {
3504       if (store != NULL) {
3505         msg = "multiple stores";
3506         break;
3507       }
3508       int opc = n->Opcode();
3509       if (opc == Op_StoreP || opc == Op_StoreN || opc == Op_StoreNKlass || opc == Op_StoreCM) {
3510         msg = "oop fills not handled";
3511         break;
3512       }
3513       Node* value = n->in(MemNode::ValueIn);
3514       if (!lpt->is_invariant(value)) {
3515         msg  = "variant store value";
3516       } else if (!_igvn.type(n->in(MemNode::Address))->isa_aryptr()) {
3517         msg = "not array address";
3518       }
3519       store = n;
3520       store_value = value;
3521     } else if (n->is_If() && n != head->loopexit_or_null()) {
3522       msg = "extra control flow";
3523       msg_node = n;
3524     }
3525   }
3526 
3527   if (store == NULL) {
3528     // No store in loop
3529     return false;
3530   }
3531 
3532   if (msg == NULL && head->stride_con() != 1) {
3533     // could handle negative strides too
3534     if (head->stride_con() < 0) {
3535       msg = "negative stride";
3536     } else {
3537       msg = "non-unit stride";
3538     }
3539   }
3540 
3541   if (msg == NULL && !store->in(MemNode::Address)->is_AddP()) {
3542     msg = "can't handle store address";
3543     msg_node = store->in(MemNode::Address);
3544   }
3545 
3546   if (msg == NULL &&
3547       (!store->in(MemNode::Memory)->is_Phi() ||
3548        store->in(MemNode::Memory)->in(LoopNode::LoopBackControl) != store)) {
3549     msg = "store memory isn't proper phi";
3550     msg_node = store->in(MemNode::Memory);
3551   }
3552 
3553   // Make sure there is an appropriate fill routine
3554   BasicType t = store->as_Mem()->memory_type();
3555   const char* fill_name;
3556   if (msg == NULL &&
3557       StubRoutines::select_fill_function(t, false, fill_name) == NULL) {
3558     msg = "unsupported store";
3559     msg_node = store;
3560   }
3561 
3562   if (msg != NULL) {
3563 #ifndef PRODUCT
3564     if (TraceOptimizeFill) {
3565       tty->print_cr("not fill intrinsic candidate: %s", msg);
3566       if (msg_node != NULL) msg_node->dump();
3567     }
3568 #endif
3569     return false;
3570   }
3571 
3572   // Make sure the address expression can be handled.  It should be
3573   // head->phi * elsize + con.  head->phi might have a ConvI2L(CastII()).
3574   Node* elements[4];
3575   Node* cast = NULL;
3576   Node* conv = NULL;
3577   bool found_index = false;
3578   int count = store->in(MemNode::Address)->as_AddP()->unpack_offsets(elements, ARRAY_SIZE(elements));
3579   for (int e = 0; e < count; e++) {
3580     Node* n = elements[e];
3581     if (n->is_Con() && con == NULL) {
3582       con = n;
3583     } else if (n->Opcode() == Op_LShiftX && shift == NULL) {
3584       Node* value = n->in(1);
3585 #ifdef _LP64
3586       if (value->Opcode() == Op_ConvI2L) {
3587         conv = value;
3588         value = value->in(1);
3589       }
3590       if (value->Opcode() == Op_CastII &&
3591           value->as_CastII()->has_range_check()) {
3592         // Skip range check dependent CastII nodes
3593         cast = value;
3594         value = value->in(1);
3595       }
3596 #endif
3597       if (value != head->phi()) {
3598         msg = "unhandled shift in address";
3599       } else {
3600         if (type2aelembytes(store->as_Mem()->memory_type(), true) != (1 << n->in(2)->get_int())) {
3601           msg = "scale doesn't match";
3602         } else {
3603           found_index = true;
3604           shift = n;
3605         }
3606       }
3607     } else if (n->Opcode() == Op_ConvI2L && conv == NULL) {
3608       conv = n;
3609       n = n->in(1);
3610       if (n->Opcode() == Op_CastII &&
3611           n->as_CastII()->has_range_check()) {
3612         // Skip range check dependent CastII nodes
3613         cast = n;
3614         n = n->in(1);
3615       }
3616       if (n == head->phi()) {
3617         found_index = true;
3618       } else {
3619         msg = "unhandled input to ConvI2L";
3620       }
3621     } else if (n == head->phi()) {
3622       // no shift, check below for allowed cases
3623       found_index = true;
3624     } else {
3625       msg = "unhandled node in address";
3626       msg_node = n;
3627     }
3628   }
3629 
3630   if (count == -1) {
3631     msg = "malformed address expression";
3632     msg_node = store;
3633   }
3634 
3635   if (!found_index) {
3636     msg = "missing use of index";
3637   }
3638 
3639   // byte sized items won't have a shift
3640   if (msg == NULL && shift == NULL && t != T_BYTE && t != T_BOOLEAN) {
3641     msg = "can't find shift";
3642     msg_node = store;
3643   }
3644 
3645   if (msg != NULL) {
3646 #ifndef PRODUCT
3647     if (TraceOptimizeFill) {
3648       tty->print_cr("not fill intrinsic: %s", msg);
3649       if (msg_node != NULL) msg_node->dump();
3650     }
3651 #endif
3652     return false;
3653   }
3654 
3655   // No make sure all the other nodes in the loop can be handled
3656   VectorSet ok;
3657 
3658   // store related values are ok
3659   ok.set(store->_idx);
3660   ok.set(store->in(MemNode::Memory)->_idx);
3661 
3662   CountedLoopEndNode* loop_exit = head->loopexit();
3663 
3664   // Loop structure is ok
3665   ok.set(head->_idx);
3666   ok.set(loop_exit->_idx);
3667   ok.set(head->phi()->_idx);
3668   ok.set(head->incr()->_idx);
3669   ok.set(loop_exit->cmp_node()->_idx);
3670   ok.set(loop_exit->in(1)->_idx);
3671 
3672   // Address elements are ok
3673   if (con)   ok.set(con->_idx);
3674   if (shift) ok.set(shift->_idx);
3675   if (cast)  ok.set(cast->_idx);
3676   if (conv)  ok.set(conv->_idx);
3677 
3678   for (uint i = 0; msg == NULL && i < lpt->_body.size(); i++) {
3679     Node* n = lpt->_body.at(i);
3680     if (n->outcnt() == 0) continue; // Ignore dead
3681     if (ok.test(n->_idx)) continue;
3682     // Backedge projection is ok
3683     if (n->is_IfTrue() && n->in(0) == loop_exit) continue;
3684     if (!n->is_AddP()) {
3685       msg = "unhandled node";
3686       msg_node = n;
3687       break;
3688     }
3689   }
3690 
3691   // Make sure no unexpected values are used outside the loop
3692   for (uint i = 0; msg == NULL && i < lpt->_body.size(); i++) {
3693     Node* n = lpt->_body.at(i);
3694     // These values can be replaced with other nodes if they are used
3695     // outside the loop.
3696     if (n == store || n == loop_exit || n == head->incr() || n == store->in(MemNode::Memory)) continue;
3697     for (SimpleDUIterator iter(n); iter.has_next(); iter.next()) {
3698       Node* use = iter.get();
3699       if (!lpt->_body.contains(use)) {
3700         if (n->is_CountedLoop() && n->as_CountedLoop()->is_strip_mined()) {
3701           // In strip-mined counted loops, the CountedLoopNode may be
3702           // used by the address polling node of the outer safepoint.
3703           // Skip this use because it's safe.
3704 #ifdef ASSERT
3705           Node* sfpt = n->as_CountedLoop()->outer_safepoint();
3706           Node* polladr = sfpt->in(TypeFunc::Parms+0);
3707           assert(use == polladr, "the use should be a safepoint polling");
3708 #endif
3709           continue;
3710         } else {
3711           msg = "node is used outside loop";
3712           msg_node = n;
3713           break;
3714         }
3715       }
3716     }
3717   }
3718 
3719 #ifdef ASSERT
3720   if (TraceOptimizeFill) {
3721     if (msg != NULL) {
3722       tty->print_cr("no fill intrinsic: %s", msg);
3723       if (msg_node != NULL) msg_node->dump();
3724     } else {
3725       tty->print_cr("fill intrinsic for:");
3726     }
3727     store->dump();
3728     if (Verbose) {
3729       lpt->_body.dump();
3730     }
3731   }
3732 #endif
3733 
3734   return msg == NULL;
3735 }
3736 
3737 
3738 
intrinsify_fill(IdealLoopTree * lpt)3739 bool PhaseIdealLoop::intrinsify_fill(IdealLoopTree* lpt) {
3740   // Only for counted inner loops
3741   if (!lpt->is_counted() || !lpt->is_innermost()) {
3742     return false;
3743   }
3744 
3745   // Must have constant stride
3746   CountedLoopNode* head = lpt->_head->as_CountedLoop();
3747   if (!head->is_valid_counted_loop(T_INT) || !head->is_normal_loop()) {
3748     return false;
3749   }
3750 
3751   head->verify_strip_mined(1);
3752 
3753   // Check that the body only contains a store of a loop invariant
3754   // value that is indexed by the loop phi.
3755   Node* store = NULL;
3756   Node* store_value = NULL;
3757   Node* shift = NULL;
3758   Node* offset = NULL;
3759   if (!match_fill_loop(lpt, store, store_value, shift, offset)) {
3760     return false;
3761   }
3762 
3763   Node* exit = head->loopexit()->proj_out_or_null(0);
3764   if (exit == NULL) {
3765     return false;
3766   }
3767 
3768 #ifndef PRODUCT
3769   if (TraceLoopOpts) {
3770     tty->print("ArrayFill    ");
3771     lpt->dump_head();
3772   }
3773 #endif
3774 
3775   // Now replace the whole loop body by a call to a fill routine that
3776   // covers the same region as the loop.
3777   Node* base = store->in(MemNode::Address)->as_AddP()->in(AddPNode::Base);
3778 
3779   // Build an expression for the beginning of the copy region
3780   Node* index = head->init_trip();
3781 #ifdef _LP64
3782   index = new ConvI2LNode(index);
3783   _igvn.register_new_node_with_optimizer(index);
3784 #endif
3785   if (shift != NULL) {
3786     // byte arrays don't require a shift but others do.
3787     index = new LShiftXNode(index, shift->in(2));
3788     _igvn.register_new_node_with_optimizer(index);
3789   }
3790   index = new AddPNode(base, base, index);
3791   _igvn.register_new_node_with_optimizer(index);
3792   Node* from = new AddPNode(base, index, offset);
3793   _igvn.register_new_node_with_optimizer(from);
3794   // Compute the number of elements to copy
3795   Node* len = new SubINode(head->limit(), head->init_trip());
3796   _igvn.register_new_node_with_optimizer(len);
3797 
3798   BasicType t = store->as_Mem()->memory_type();
3799   bool aligned = false;
3800   if (offset != NULL && head->init_trip()->is_Con()) {
3801     int element_size = type2aelembytes(t);
3802     aligned = (offset->find_intptr_t_type()->get_con() + head->init_trip()->get_int() * element_size) % HeapWordSize == 0;
3803   }
3804 
3805   // Build a call to the fill routine
3806   const char* fill_name;
3807   address fill = StubRoutines::select_fill_function(t, aligned, fill_name);
3808   assert(fill != NULL, "what?");
3809 
3810   // Convert float/double to int/long for fill routines
3811   if (t == T_FLOAT) {
3812     store_value = new MoveF2INode(store_value);
3813     _igvn.register_new_node_with_optimizer(store_value);
3814   } else if (t == T_DOUBLE) {
3815     store_value = new MoveD2LNode(store_value);
3816     _igvn.register_new_node_with_optimizer(store_value);
3817   }
3818 
3819   Node* mem_phi = store->in(MemNode::Memory);
3820   Node* result_ctrl;
3821   Node* result_mem;
3822   const TypeFunc* call_type = OptoRuntime::array_fill_Type();
3823   CallLeafNode *call = new CallLeafNoFPNode(call_type, fill,
3824                                             fill_name, TypeAryPtr::get_array_body_type(t));
3825   uint cnt = 0;
3826   call->init_req(TypeFunc::Parms + cnt++, from);
3827   call->init_req(TypeFunc::Parms + cnt++, store_value);
3828 #ifdef _LP64
3829   len = new ConvI2LNode(len);
3830   _igvn.register_new_node_with_optimizer(len);
3831 #endif
3832   call->init_req(TypeFunc::Parms + cnt++, len);
3833 #ifdef _LP64
3834   call->init_req(TypeFunc::Parms + cnt++, C->top());
3835 #endif
3836   call->init_req(TypeFunc::Control,   head->init_control());
3837   call->init_req(TypeFunc::I_O,       C->top());       // Does no I/O.
3838   call->init_req(TypeFunc::Memory,    mem_phi->in(LoopNode::EntryControl));
3839   call->init_req(TypeFunc::ReturnAdr, C->start()->proj_out_or_null(TypeFunc::ReturnAdr));
3840   call->init_req(TypeFunc::FramePtr,  C->start()->proj_out_or_null(TypeFunc::FramePtr));
3841   _igvn.register_new_node_with_optimizer(call);
3842   result_ctrl = new ProjNode(call,TypeFunc::Control);
3843   _igvn.register_new_node_with_optimizer(result_ctrl);
3844   result_mem = new ProjNode(call,TypeFunc::Memory);
3845   _igvn.register_new_node_with_optimizer(result_mem);
3846 
3847 /* Disable following optimization until proper fix (add missing checks).
3848 
3849   // If this fill is tightly coupled to an allocation and overwrites
3850   // the whole body, allow it to take over the zeroing.
3851   AllocateNode* alloc = AllocateNode::Ideal_allocation(base, this);
3852   if (alloc != NULL && alloc->is_AllocateArray()) {
3853     Node* length = alloc->as_AllocateArray()->Ideal_length();
3854     if (head->limit() == length &&
3855         head->init_trip() == _igvn.intcon(0)) {
3856       if (TraceOptimizeFill) {
3857         tty->print_cr("Eliminated zeroing in allocation");
3858       }
3859       alloc->maybe_set_complete(&_igvn);
3860     } else {
3861 #ifdef ASSERT
3862       if (TraceOptimizeFill) {
3863         tty->print_cr("filling array but bounds don't match");
3864         alloc->dump();
3865         head->init_trip()->dump();
3866         head->limit()->dump();
3867         length->dump();
3868       }
3869 #endif
3870     }
3871   }
3872 */
3873 
3874   if (head->is_strip_mined()) {
3875     // Inner strip mined loop goes away so get rid of outer strip
3876     // mined loop
3877     Node* outer_sfpt = head->outer_safepoint();
3878     Node* in = outer_sfpt->in(0);
3879     Node* outer_out = head->outer_loop_exit();
3880     lazy_replace(outer_out, in);
3881     _igvn.replace_input_of(outer_sfpt, 0, C->top());
3882   }
3883 
3884   // Redirect the old control and memory edges that are outside the loop.
3885   // Sometimes the memory phi of the head is used as the outgoing
3886   // state of the loop.  It's safe in this case to replace it with the
3887   // result_mem.
3888   _igvn.replace_node(store->in(MemNode::Memory), result_mem);
3889   lazy_replace(exit, result_ctrl);
3890   _igvn.replace_node(store, result_mem);
3891   // Any uses the increment outside of the loop become the loop limit.
3892   _igvn.replace_node(head->incr(), head->limit());
3893 
3894   // Disconnect the head from the loop.
3895   for (uint i = 0; i < lpt->_body.size(); i++) {
3896     Node* n = lpt->_body.at(i);
3897     _igvn.replace_node(n, C->top());
3898   }
3899 
3900   return true;
3901 }
3902