loopTransform.cpp revision 5776:de6a9e811145
1/*
2 * Copyright (c) 2000, 2013, 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/connode.hpp"
31#include "opto/divnode.hpp"
32#include "opto/loopnode.hpp"
33#include "opto/mulnode.hpp"
34#include "opto/rootnode.hpp"
35#include "opto/runtime.hpp"
36#include "opto/subnode.hpp"
37
38//------------------------------is_loop_exit-----------------------------------
39// Given an IfNode, return the loop-exiting projection or NULL if both
40// arms remain in the loop.
41Node *IdealLoopTree::is_loop_exit(Node *iff) const {
42  if( iff->outcnt() != 2 ) return NULL; // Ignore partially dead tests
43  PhaseIdealLoop *phase = _phase;
44  // Test is an IfNode, has 2 projections.  If BOTH are in the loop
45  // we need loop unswitching instead of peeling.
46  if( !is_member(phase->get_loop( iff->raw_out(0) )) )
47    return iff->raw_out(0);
48  if( !is_member(phase->get_loop( iff->raw_out(1) )) )
49    return iff->raw_out(1);
50  return NULL;
51}
52
53
54//=============================================================================
55
56
57//------------------------------record_for_igvn----------------------------
58// Put loop body on igvn work list
59void IdealLoopTree::record_for_igvn() {
60  for( uint i = 0; i < _body.size(); i++ ) {
61    Node *n = _body.at(i);
62    _phase->_igvn._worklist.push(n);
63  }
64}
65
66//------------------------------compute_exact_trip_count-----------------------
67// Compute loop exact trip count if possible. Do not recalculate trip count for
68// split loops (pre-main-post) which have their limits and inits behind Opaque node.
69void IdealLoopTree::compute_exact_trip_count( PhaseIdealLoop *phase ) {
70  if (!_head->as_Loop()->is_valid_counted_loop()) {
71    return;
72  }
73  CountedLoopNode* cl = _head->as_CountedLoop();
74  // Trip count may become nonexact for iteration split loops since
75  // RCE modifies limits. Note, _trip_count value is not reset since
76  // it is used to limit unrolling of main loop.
77  cl->set_nonexact_trip_count();
78
79  // Loop's test should be part of loop.
80  if (!phase->is_member(this, phase->get_ctrl(cl->loopexit()->in(CountedLoopEndNode::TestValue))))
81    return; // Infinite loop
82
83#ifdef ASSERT
84  BoolTest::mask bt = cl->loopexit()->test_trip();
85  assert(bt == BoolTest::lt || bt == BoolTest::gt ||
86         bt == BoolTest::ne, "canonical test is expected");
87#endif
88
89  Node* init_n = cl->init_trip();
90  Node* limit_n = cl->limit();
91  if (init_n  != NULL &&  init_n->is_Con() &&
92      limit_n != NULL && limit_n->is_Con()) {
93    // Use longs to avoid integer overflow.
94    int stride_con  = cl->stride_con();
95    jlong init_con   = cl->init_trip()->get_int();
96    jlong limit_con  = cl->limit()->get_int();
97    int stride_m    = stride_con - (stride_con > 0 ? 1 : -1);
98    jlong trip_count = (limit_con - init_con + stride_m)/stride_con;
99    if (trip_count > 0 && (julong)trip_count < (julong)max_juint) {
100      // Set exact trip count.
101      cl->set_exact_trip_count((uint)trip_count);
102    }
103  }
104}
105
106//------------------------------compute_profile_trip_cnt----------------------------
107// Compute loop trip count from profile data as
108//    (backedge_count + loop_exit_count) / loop_exit_count
109void IdealLoopTree::compute_profile_trip_cnt( PhaseIdealLoop *phase ) {
110  if (!_head->is_CountedLoop()) {
111    return;
112  }
113  CountedLoopNode* head = _head->as_CountedLoop();
114  if (head->profile_trip_cnt() != COUNT_UNKNOWN) {
115    return; // Already computed
116  }
117  float trip_cnt = (float)max_jint; // default is big
118
119  Node* back = head->in(LoopNode::LoopBackControl);
120  while (back != head) {
121    if ((back->Opcode() == Op_IfTrue || back->Opcode() == Op_IfFalse) &&
122        back->in(0) &&
123        back->in(0)->is_If() &&
124        back->in(0)->as_If()->_fcnt != COUNT_UNKNOWN &&
125        back->in(0)->as_If()->_prob != PROB_UNKNOWN) {
126      break;
127    }
128    back = phase->idom(back);
129  }
130  if (back != head) {
131    assert((back->Opcode() == Op_IfTrue || back->Opcode() == Op_IfFalse) &&
132           back->in(0), "if-projection exists");
133    IfNode* back_if = back->in(0)->as_If();
134    float loop_back_cnt = back_if->_fcnt * back_if->_prob;
135
136    // Now compute a loop exit count
137    float loop_exit_cnt = 0.0f;
138    for( uint i = 0; i < _body.size(); i++ ) {
139      Node *n = _body[i];
140      if( n->is_If() ) {
141        IfNode *iff = n->as_If();
142        if( iff->_fcnt != COUNT_UNKNOWN && iff->_prob != PROB_UNKNOWN ) {
143          Node *exit = is_loop_exit(iff);
144          if( exit ) {
145            float exit_prob = iff->_prob;
146            if (exit->Opcode() == Op_IfFalse) exit_prob = 1.0 - exit_prob;
147            if (exit_prob > PROB_MIN) {
148              float exit_cnt = iff->_fcnt * exit_prob;
149              loop_exit_cnt += exit_cnt;
150            }
151          }
152        }
153      }
154    }
155    if (loop_exit_cnt > 0.0f) {
156      trip_cnt = (loop_back_cnt + loop_exit_cnt) / loop_exit_cnt;
157    } else {
158      // No exit count so use
159      trip_cnt = loop_back_cnt;
160    }
161  }
162#ifndef PRODUCT
163  if (TraceProfileTripCount) {
164    tty->print_cr("compute_profile_trip_cnt  lp: %d cnt: %f\n", head->_idx, trip_cnt);
165  }
166#endif
167  head->set_profile_trip_cnt(trip_cnt);
168}
169
170//---------------------is_invariant_addition-----------------------------
171// Return nonzero index of invariant operand for an Add or Sub
172// of (nonconstant) invariant and variant values. Helper for reassociate_invariants.
173int IdealLoopTree::is_invariant_addition(Node* n, PhaseIdealLoop *phase) {
174  int op = n->Opcode();
175  if (op == Op_AddI || op == Op_SubI) {
176    bool in1_invar = this->is_invariant(n->in(1));
177    bool in2_invar = this->is_invariant(n->in(2));
178    if (in1_invar && !in2_invar) return 1;
179    if (!in1_invar && in2_invar) return 2;
180  }
181  return 0;
182}
183
184//---------------------reassociate_add_sub-----------------------------
185// Reassociate invariant add and subtract expressions:
186//
187// inv1 + (x + inv2)  =>  ( inv1 + inv2) + x
188// (x + inv2) + inv1  =>  ( inv1 + inv2) + x
189// inv1 + (x - inv2)  =>  ( inv1 - inv2) + x
190// inv1 - (inv2 - x)  =>  ( inv1 - inv2) + x
191// (x + inv2) - inv1  =>  (-inv1 + inv2) + x
192// (x - inv2) + inv1  =>  ( inv1 - inv2) + x
193// (x - inv2) - inv1  =>  (-inv1 - inv2) + x
194// inv1 + (inv2 - x)  =>  ( inv1 + inv2) - x
195// inv1 - (x - inv2)  =>  ( inv1 + inv2) - x
196// (inv2 - x) + inv1  =>  ( inv1 + inv2) - x
197// (inv2 - x) - inv1  =>  (-inv1 + inv2) - x
198// inv1 - (x + inv2)  =>  ( inv1 - inv2) - x
199//
200Node* IdealLoopTree::reassociate_add_sub(Node* n1, PhaseIdealLoop *phase) {
201  if (!n1->is_Add() && !n1->is_Sub() || n1->outcnt() == 0) return NULL;
202  if (is_invariant(n1)) return NULL;
203  int inv1_idx = is_invariant_addition(n1, phase);
204  if (!inv1_idx) return NULL;
205  // Don't mess with add of constant (igvn moves them to expression tree root.)
206  if (n1->is_Add() && n1->in(2)->is_Con()) return NULL;
207  Node* inv1 = n1->in(inv1_idx);
208  Node* n2 = n1->in(3 - inv1_idx);
209  int inv2_idx = is_invariant_addition(n2, phase);
210  if (!inv2_idx) return NULL;
211  Node* x    = n2->in(3 - inv2_idx);
212  Node* inv2 = n2->in(inv2_idx);
213
214  bool neg_x    = n2->is_Sub() && inv2_idx == 1;
215  bool neg_inv2 = n2->is_Sub() && inv2_idx == 2;
216  bool neg_inv1 = n1->is_Sub() && inv1_idx == 2;
217  if (n1->is_Sub() && inv1_idx == 1) {
218    neg_x    = !neg_x;
219    neg_inv2 = !neg_inv2;
220  }
221  Node* inv1_c = phase->get_ctrl(inv1);
222  Node* inv2_c = phase->get_ctrl(inv2);
223  Node* n_inv1;
224  if (neg_inv1) {
225    Node *zero = phase->_igvn.intcon(0);
226    phase->set_ctrl(zero, phase->C->root());
227    n_inv1 = new (phase->C) SubINode(zero, inv1);
228    phase->register_new_node(n_inv1, inv1_c);
229  } else {
230    n_inv1 = inv1;
231  }
232  Node* inv;
233  if (neg_inv2) {
234    inv = new (phase->C) SubINode(n_inv1, inv2);
235  } else {
236    inv = new (phase->C) AddINode(n_inv1, inv2);
237  }
238  phase->register_new_node(inv, phase->get_early_ctrl(inv));
239
240  Node* addx;
241  if (neg_x) {
242    addx = new (phase->C) SubINode(inv, x);
243  } else {
244    addx = new (phase->C) AddINode(x, inv);
245  }
246  phase->register_new_node(addx, phase->get_ctrl(x));
247  phase->_igvn.replace_node(n1, addx);
248  assert(phase->get_loop(phase->get_ctrl(n1)) == this, "");
249  _body.yank(n1);
250  return addx;
251}
252
253//---------------------reassociate_invariants-----------------------------
254// Reassociate invariant expressions:
255void IdealLoopTree::reassociate_invariants(PhaseIdealLoop *phase) {
256  for (int i = _body.size() - 1; i >= 0; i--) {
257    Node *n = _body.at(i);
258    for (int j = 0; j < 5; j++) {
259      Node* nn = reassociate_add_sub(n, phase);
260      if (nn == NULL) break;
261      n = nn; // again
262    };
263  }
264}
265
266//------------------------------policy_peeling---------------------------------
267// Return TRUE or FALSE if the loop should be peeled or not.  Peel if we can
268// make some loop-invariant test (usually a null-check) happen before the loop.
269bool IdealLoopTree::policy_peeling( PhaseIdealLoop *phase ) const {
270  Node *test = ((IdealLoopTree*)this)->tail();
271  int  body_size = ((IdealLoopTree*)this)->_body.size();
272  int  live_node_count = phase->C->live_nodes();
273  // Peeling does loop cloning which can result in O(N^2) node construction
274  if( body_size > 255 /* Prevent overflow for large body_size */
275      || (body_size * body_size + live_node_count > MaxNodeLimit) ) {
276    return false;           // too large to safely clone
277  }
278  while( test != _head ) {      // Scan till run off top of loop
279    if( test->is_If() ) {       // Test?
280      Node *ctrl = phase->get_ctrl(test->in(1));
281      if (ctrl->is_top())
282        return false;           // Found dead test on live IF?  No peeling!
283      // Standard IF only has one input value to check for loop invariance
284      assert( test->Opcode() == Op_If || test->Opcode() == Op_CountedLoopEnd, "Check this code when new subtype is added");
285      // Condition is not a member of this loop?
286      if( !is_member(phase->get_loop(ctrl)) &&
287          is_loop_exit(test) )
288        return true;            // Found reason to peel!
289    }
290    // Walk up dominators to loop _head looking for test which is
291    // executed on every path thru loop.
292    test = phase->idom(test);
293  }
294  return false;
295}
296
297//------------------------------peeled_dom_test_elim---------------------------
298// If we got the effect of peeling, either by actually peeling or by making
299// a pre-loop which must execute at least once, we can remove all
300// loop-invariant dominated tests in the main body.
301void PhaseIdealLoop::peeled_dom_test_elim( IdealLoopTree *loop, Node_List &old_new ) {
302  bool progress = true;
303  while( progress ) {
304    progress = false;           // Reset for next iteration
305    Node *prev = loop->_head->in(LoopNode::LoopBackControl);//loop->tail();
306    Node *test = prev->in(0);
307    while( test != loop->_head ) { // Scan till run off top of loop
308
309      int p_op = prev->Opcode();
310      if( (p_op == Op_IfFalse || p_op == Op_IfTrue) &&
311          test->is_If() &&      // Test?
312          !test->in(1)->is_Con() && // And not already obvious?
313          // Condition is not a member of this loop?
314          !loop->is_member(get_loop(get_ctrl(test->in(1))))){
315        // Walk loop body looking for instances of this test
316        for( uint i = 0; i < loop->_body.size(); i++ ) {
317          Node *n = loop->_body.at(i);
318          if( n->is_If() && n->in(1) == test->in(1) /*&& n != loop->tail()->in(0)*/ ) {
319            // IfNode was dominated by version in peeled loop body
320            progress = true;
321            dominated_by( old_new[prev->_idx], n );
322          }
323        }
324      }
325      prev = test;
326      test = idom(test);
327    } // End of scan tests in loop
328
329  } // End of while( progress )
330}
331
332//------------------------------do_peeling-------------------------------------
333// Peel the first iteration of the given loop.
334// Step 1: Clone the loop body.  The clone becomes the peeled iteration.
335//         The pre-loop illegally has 2 control users (old & new loops).
336// Step 2: Make the old-loop fall-in edges point to the peeled iteration.
337//         Do this by making the old-loop fall-in edges act as if they came
338//         around the loopback from the prior iteration (follow the old-loop
339//         backedges) and then map to the new peeled iteration.  This leaves
340//         the pre-loop with only 1 user (the new peeled iteration), but the
341//         peeled-loop backedge has 2 users.
342// Step 3: Cut the backedge on the clone (so its not a loop) and remove the
343//         extra backedge user.
344//
345//                   orig
346//
347//                  stmt1
348//                    |
349//                    v
350//              loop predicate
351//                    |
352//                    v
353//                   loop<----+
354//                     |      |
355//                   stmt2    |
356//                     |      |
357//                     v      |
358//                    if      ^
359//                   / \      |
360//                  /   \     |
361//                 v     v    |
362//               false true   |
363//               /       \    |
364//              /         ----+
365//             |
366//             v
367//           exit
368//
369//
370//            after clone loop
371//
372//                   stmt1
373//                     |
374//                     v
375//               loop predicate
376//                 /       \
377//        clone   /         \   orig
378//               /           \
379//              /             \
380//             v               v
381//   +---->loop clone          loop<----+
382//   |      |                    |      |
383//   |    stmt2 clone          stmt2    |
384//   |      |                    |      |
385//   |      v                    v      |
386//   ^      if clone            If      ^
387//   |      / \                / \      |
388//   |     /   \              /   \     |
389//   |    v     v            v     v    |
390//   |    true  false      false true   |
391//   |    /         \      /       \    |
392//   +----           \    /         ----+
393//                    \  /
394//                    1v v2
395//                  region
396//                     |
397//                     v
398//                   exit
399//
400//
401//         after peel and predicate move
402//
403//                   stmt1
404//                    /
405//                   /
406//        clone     /            orig
407//                 /
408//                /              +----------+
409//               /               |          |
410//              /          loop predicate   |
411//             /                 |          |
412//            v                  v          |
413//   TOP-->loop clone          loop<----+   |
414//          |                    |      |   |
415//        stmt2 clone          stmt2    |   |
416//          |                    |      |   ^
417//          v                    v      |   |
418//          if clone            If      ^   |
419//          / \                / \      |   |
420//         /   \              /   \     |   |
421//        v     v            v     v    |   |
422//      true   false      false  true   |   |
423//        |         \      /       \    |   |
424//        |          \    /         ----+   ^
425//        |           \  /                  |
426//        |           1v v2                 |
427//        v         region                  |
428//        |            |                    |
429//        |            v                    |
430//        |          exit                   |
431//        |                                 |
432//        +--------------->-----------------+
433//
434//
435//              final graph
436//
437//                  stmt1
438//                    |
439//                    v
440//                  stmt2 clone
441//                    |
442//                    v
443//                   if clone
444//                  / |
445//                 /  |
446//                v   v
447//            false  true
448//             |      |
449//             |      v
450//             | loop predicate
451//             |      |
452//             |      v
453//             |     loop<----+
454//             |      |       |
455//             |    stmt2     |
456//             |      |       |
457//             |      v       |
458//             v      if      ^
459//             |     /  \     |
460//             |    /    \    |
461//             |   v     v    |
462//             | false  true  |
463//             |  |        \  |
464//             v  v         --+
465//            region
466//              |
467//              v
468//             exit
469//
470void PhaseIdealLoop::do_peeling( IdealLoopTree *loop, Node_List &old_new ) {
471
472  C->set_major_progress();
473  // Peeling a 'main' loop in a pre/main/post situation obfuscates the
474  // 'pre' loop from the main and the 'pre' can no longer have it's
475  // iterations adjusted.  Therefore, we need to declare this loop as
476  // no longer a 'main' loop; it will need new pre and post loops before
477  // we can do further RCE.
478#ifndef PRODUCT
479  if (TraceLoopOpts) {
480    tty->print("Peel         ");
481    loop->dump_head();
482  }
483#endif
484  Node* head = loop->_head;
485  bool counted_loop = head->is_CountedLoop();
486  if (counted_loop) {
487    CountedLoopNode *cl = head->as_CountedLoop();
488    assert(cl->trip_count() > 0, "peeling a fully unrolled loop");
489    cl->set_trip_count(cl->trip_count() - 1);
490    if (cl->is_main_loop()) {
491      cl->set_normal_loop();
492#ifndef PRODUCT
493      if (PrintOpto && VerifyLoopOptimizations) {
494        tty->print("Peeling a 'main' loop; resetting to 'normal' ");
495        loop->dump_head();
496      }
497#endif
498    }
499  }
500  Node* entry = head->in(LoopNode::EntryControl);
501
502  // Step 1: Clone the loop body.  The clone becomes the peeled iteration.
503  //         The pre-loop illegally has 2 control users (old & new loops).
504  clone_loop( loop, old_new, dom_depth(head) );
505
506  // Step 2: Make the old-loop fall-in edges point to the peeled iteration.
507  //         Do this by making the old-loop fall-in edges act as if they came
508  //         around the loopback from the prior iteration (follow the old-loop
509  //         backedges) and then map to the new peeled iteration.  This leaves
510  //         the pre-loop with only 1 user (the new peeled iteration), but the
511  //         peeled-loop backedge has 2 users.
512  Node* new_entry = old_new[head->in(LoopNode::LoopBackControl)->_idx];
513  _igvn.hash_delete(head);
514  head->set_req(LoopNode::EntryControl, new_entry);
515  for (DUIterator_Fast jmax, j = head->fast_outs(jmax); j < jmax; j++) {
516    Node* old = head->fast_out(j);
517    if (old->in(0) == loop->_head && old->req() == 3 && old->is_Phi()) {
518      Node* new_exit_value = old_new[old->in(LoopNode::LoopBackControl)->_idx];
519      if (!new_exit_value )     // Backedge value is ALSO loop invariant?
520        // Then loop body backedge value remains the same.
521        new_exit_value = old->in(LoopNode::LoopBackControl);
522      _igvn.hash_delete(old);
523      old->set_req(LoopNode::EntryControl, new_exit_value);
524    }
525  }
526
527
528  // Step 3: Cut the backedge on the clone (so its not a loop) and remove the
529  //         extra backedge user.
530  Node* new_head = old_new[head->_idx];
531  _igvn.hash_delete(new_head);
532  new_head->set_req(LoopNode::LoopBackControl, C->top());
533  for (DUIterator_Fast j2max, j2 = new_head->fast_outs(j2max); j2 < j2max; j2++) {
534    Node* use = new_head->fast_out(j2);
535    if (use->in(0) == new_head && use->req() == 3 && use->is_Phi()) {
536      _igvn.hash_delete(use);
537      use->set_req(LoopNode::LoopBackControl, C->top());
538    }
539  }
540
541
542  // Step 4: Correct dom-depth info.  Set to loop-head depth.
543  int dd = dom_depth(head);
544  set_idom(head, head->in(1), dd);
545  for (uint j3 = 0; j3 < loop->_body.size(); j3++) {
546    Node *old = loop->_body.at(j3);
547    Node *nnn = old_new[old->_idx];
548    if (!has_ctrl(nnn))
549      set_idom(nnn, idom(nnn), dd-1);
550  }
551
552  // Now force out all loop-invariant dominating tests.  The optimizer
553  // finds some, but we _know_ they are all useless.
554  peeled_dom_test_elim(loop,old_new);
555
556  loop->record_for_igvn();
557}
558
559#define EMPTY_LOOP_SIZE 7 // number of nodes in an empty loop
560
561//------------------------------policy_maximally_unroll------------------------
562// Calculate exact loop trip count and return true if loop can be maximally
563// unrolled.
564bool IdealLoopTree::policy_maximally_unroll( PhaseIdealLoop *phase ) const {
565  CountedLoopNode *cl = _head->as_CountedLoop();
566  assert(cl->is_normal_loop(), "");
567  if (!cl->is_valid_counted_loop())
568    return false; // Malformed counted loop
569
570  if (!cl->has_exact_trip_count()) {
571    // Trip count is not exact.
572    return false;
573  }
574
575  uint trip_count = cl->trip_count();
576  // Note, max_juint is used to indicate unknown trip count.
577  assert(trip_count > 1, "one iteration loop should be optimized out already");
578  assert(trip_count < max_juint, "exact trip_count should be less than max_uint.");
579
580  // Real policy: if we maximally unroll, does it get too big?
581  // Allow the unrolled mess to get larger than standard loop
582  // size.  After all, it will no longer be a loop.
583  uint body_size    = _body.size();
584  uint unroll_limit = (uint)LoopUnrollLimit * 4;
585  assert( (intx)unroll_limit == LoopUnrollLimit * 4, "LoopUnrollLimit must fit in 32bits");
586  if (trip_count > unroll_limit || body_size > unroll_limit) {
587    return false;
588  }
589
590  // Fully unroll a loop with few iterations regardless next
591  // conditions since following loop optimizations will split
592  // such loop anyway (pre-main-post).
593  if (trip_count <= 3)
594    return true;
595
596  // Take into account that after unroll conjoined heads and tails will fold,
597  // otherwise policy_unroll() may allow more unrolling than max unrolling.
598  uint new_body_size = EMPTY_LOOP_SIZE + (body_size - EMPTY_LOOP_SIZE) * trip_count;
599  uint tst_body_size = (new_body_size - EMPTY_LOOP_SIZE) / trip_count + EMPTY_LOOP_SIZE;
600  if (body_size != tst_body_size) // Check for int overflow
601    return false;
602  if (new_body_size > unroll_limit ||
603      // Unrolling can result in a large amount of node construction
604      new_body_size >= MaxNodeLimit - (uint) phase->C->live_nodes()) {
605    return false;
606  }
607
608  // Do not unroll a loop with String intrinsics code.
609  // String intrinsics are large and have loops.
610  for (uint k = 0; k < _body.size(); k++) {
611    Node* n = _body.at(k);
612    switch (n->Opcode()) {
613      case Op_StrComp:
614      case Op_StrEquals:
615      case Op_StrIndexOf:
616      case Op_EncodeISOArray:
617      case Op_AryEq: {
618        return false;
619      }
620    } // switch
621  }
622
623  return true; // Do maximally unroll
624}
625
626
627//------------------------------policy_unroll----------------------------------
628// Return TRUE or FALSE if the loop should be unrolled or not.  Unroll if
629// the loop is a CountedLoop and the body is small enough.
630bool IdealLoopTree::policy_unroll( PhaseIdealLoop *phase ) const {
631
632  CountedLoopNode *cl = _head->as_CountedLoop();
633  assert(cl->is_normal_loop() || cl->is_main_loop(), "");
634
635  if (!cl->is_valid_counted_loop())
636    return false; // Malformed counted loop
637
638  // Protect against over-unrolling.
639  // After split at least one iteration will be executed in pre-loop.
640  if (cl->trip_count() <= (uint)(cl->is_normal_loop() ? 2 : 1)) return false;
641
642  int future_unroll_ct = cl->unrolled_count() * 2;
643  if (future_unroll_ct > LoopMaxUnroll) return false;
644
645  // Check for initial stride being a small enough constant
646  if (abs(cl->stride_con()) > (1<<2)*future_unroll_ct) return false;
647
648  // Don't unroll if the next round of unrolling would push us
649  // over the expected trip count of the loop.  One is subtracted
650  // from the expected trip count because the pre-loop normally
651  // executes 1 iteration.
652  if (UnrollLimitForProfileCheck > 0 &&
653      cl->profile_trip_cnt() != COUNT_UNKNOWN &&
654      future_unroll_ct        > UnrollLimitForProfileCheck &&
655      (float)future_unroll_ct > cl->profile_trip_cnt() - 1.0) {
656    return false;
657  }
658
659  // When unroll count is greater than LoopUnrollMin, don't unroll if:
660  //   the residual iterations are more than 10% of the trip count
661  //   and rounds of "unroll,optimize" are not making significant progress
662  //   Progress defined as current size less than 20% larger than previous size.
663  if (UseSuperWord && cl->node_count_before_unroll() > 0 &&
664      future_unroll_ct > LoopUnrollMin &&
665      (future_unroll_ct - 1) * 10.0 > cl->profile_trip_cnt() &&
666      1.2 * cl->node_count_before_unroll() < (double)_body.size()) {
667    return false;
668  }
669
670  Node *init_n = cl->init_trip();
671  Node *limit_n = cl->limit();
672  int stride_con = cl->stride_con();
673  // Non-constant bounds.
674  // Protect against over-unrolling when init or/and limit are not constant
675  // (so that trip_count's init value is maxint) but iv range is known.
676  if (init_n   == NULL || !init_n->is_Con()  ||
677      limit_n  == NULL || !limit_n->is_Con()) {
678    Node* phi = cl->phi();
679    if (phi != NULL) {
680      assert(phi->is_Phi() && phi->in(0) == _head, "Counted loop should have iv phi.");
681      const TypeInt* iv_type = phase->_igvn.type(phi)->is_int();
682      int next_stride = stride_con * 2; // stride after this unroll
683      if (next_stride > 0) {
684        if (iv_type->_lo + next_stride <= iv_type->_lo || // overflow
685            iv_type->_lo + next_stride >  iv_type->_hi) {
686          return false;  // over-unrolling
687        }
688      } else if (next_stride < 0) {
689        if (iv_type->_hi + next_stride >= iv_type->_hi || // overflow
690            iv_type->_hi + next_stride <  iv_type->_lo) {
691          return false;  // over-unrolling
692        }
693      }
694    }
695  }
696
697  // After unroll limit will be adjusted: new_limit = limit-stride.
698  // Bailout if adjustment overflow.
699  const TypeInt* limit_type = phase->_igvn.type(limit_n)->is_int();
700  if (stride_con > 0 && ((limit_type->_hi - stride_con) >= limit_type->_hi) ||
701      stride_con < 0 && ((limit_type->_lo - stride_con) <= limit_type->_lo))
702    return false;  // overflow
703
704  // Adjust body_size to determine if we unroll or not
705  uint body_size = _body.size();
706  // Key test to unroll loop in CRC32 java code
707  int xors_in_loop = 0;
708  // Also count ModL, DivL and MulL which expand mightly
709  for (uint k = 0; k < _body.size(); k++) {
710    Node* n = _body.at(k);
711    switch (n->Opcode()) {
712      case Op_XorI: xors_in_loop++; break; // CRC32 java code
713      case Op_ModL: body_size += 30; break;
714      case Op_DivL: body_size += 30; break;
715      case Op_MulL: body_size += 10; break;
716      case Op_FlagsProj:
717        // Can't handle unrolling of loops containing
718        // nodes that generate a FlagsProj at the moment
719        return false;
720      case Op_StrComp:
721      case Op_StrEquals:
722      case Op_StrIndexOf:
723      case Op_EncodeISOArray:
724      case Op_AryEq: {
725        // Do not unroll a loop with String intrinsics code.
726        // String intrinsics are large and have loops.
727        return false;
728      }
729    } // switch
730  }
731
732  // Check for being too big
733  if (body_size > (uint)LoopUnrollLimit) {
734    if (xors_in_loop >= 4 && body_size < (uint)LoopUnrollLimit*4) return true;
735    // Normal case: loop too big
736    return false;
737  }
738
739  // Unroll once!  (Each trip will soon do double iterations)
740  return true;
741}
742
743//------------------------------policy_align-----------------------------------
744// Return TRUE or FALSE if the loop should be cache-line aligned.  Gather the
745// expression that does the alignment.  Note that only one array base can be
746// aligned in a loop (unless the VM guarantees mutual alignment).  Note that
747// if we vectorize short memory ops into longer memory ops, we may want to
748// increase alignment.
749bool IdealLoopTree::policy_align( PhaseIdealLoop *phase ) const {
750  return false;
751}
752
753//------------------------------policy_range_check-----------------------------
754// Return TRUE or FALSE if the loop should be range-check-eliminated.
755// Actually we do iteration-splitting, a more powerful form of RCE.
756bool IdealLoopTree::policy_range_check( PhaseIdealLoop *phase ) const {
757  if (!RangeCheckElimination) return false;
758
759  CountedLoopNode *cl = _head->as_CountedLoop();
760  // If we unrolled with no intention of doing RCE and we later
761  // changed our minds, we got no pre-loop.  Either we need to
762  // make a new pre-loop, or we gotta disallow RCE.
763  if (cl->is_main_no_pre_loop()) return false; // Disallowed for now.
764  Node *trip_counter = cl->phi();
765
766  // Check loop body for tests of trip-counter plus loop-invariant vs
767  // loop-invariant.
768  for (uint i = 0; i < _body.size(); i++) {
769    Node *iff = _body[i];
770    if (iff->Opcode() == Op_If) { // Test?
771
772      // Comparing trip+off vs limit
773      Node *bol = iff->in(1);
774      if (bol->req() != 2) continue; // dead constant test
775      if (!bol->is_Bool()) {
776        assert(UseLoopPredicate && bol->Opcode() == Op_Conv2B, "predicate check only");
777        continue;
778      }
779      if (bol->as_Bool()->_test._test == BoolTest::ne)
780        continue; // not RC
781
782      Node *cmp = bol->in(1);
783      if (cmp->is_FlagsProj()) {
784        continue;
785      }
786
787      Node *rc_exp = cmp->in(1);
788      Node *limit = cmp->in(2);
789
790      Node *limit_c = phase->get_ctrl(limit);
791      if( limit_c == phase->C->top() )
792        return false;           // Found dead test on live IF?  No RCE!
793      if( is_member(phase->get_loop(limit_c) ) ) {
794        // Compare might have operands swapped; commute them
795        rc_exp = cmp->in(2);
796        limit  = cmp->in(1);
797        limit_c = phase->get_ctrl(limit);
798        if( is_member(phase->get_loop(limit_c) ) )
799          continue;             // Both inputs are loop varying; cannot RCE
800      }
801
802      if (!phase->is_scaled_iv_plus_offset(rc_exp, trip_counter, NULL, NULL)) {
803        continue;
804      }
805      // Yeah!  Found a test like 'trip+off vs limit'
806      // Test is an IfNode, has 2 projections.  If BOTH are in the loop
807      // we need loop unswitching instead of iteration splitting.
808      if( is_loop_exit(iff) )
809        return true;            // Found reason to split iterations
810    } // End of is IF
811  }
812
813  return false;
814}
815
816//------------------------------policy_peel_only-------------------------------
817// Return TRUE or FALSE if the loop should NEVER be RCE'd or aligned.  Useful
818// for unrolling loops with NO array accesses.
819bool IdealLoopTree::policy_peel_only( PhaseIdealLoop *phase ) const {
820
821  for( uint i = 0; i < _body.size(); i++ )
822    if( _body[i]->is_Mem() )
823      return false;
824
825  // No memory accesses at all!
826  return true;
827}
828
829//------------------------------clone_up_backedge_goo--------------------------
830// If Node n lives in the back_ctrl block and cannot float, we clone a private
831// version of n in preheader_ctrl block and return that, otherwise return n.
832Node *PhaseIdealLoop::clone_up_backedge_goo( Node *back_ctrl, Node *preheader_ctrl, Node *n, VectorSet &visited, Node_Stack &clones ) {
833  if( get_ctrl(n) != back_ctrl ) return n;
834
835  // Only visit once
836  if (visited.test_set(n->_idx)) {
837    Node *x = clones.find(n->_idx);
838    if (x != NULL)
839      return x;
840    return n;
841  }
842
843  Node *x = NULL;               // If required, a clone of 'n'
844  // Check for 'n' being pinned in the backedge.
845  if( n->in(0) && n->in(0) == back_ctrl ) {
846    assert(clones.find(n->_idx) == NULL, "dead loop");
847    x = n->clone();             // Clone a copy of 'n' to preheader
848    clones.push(x, n->_idx);
849    x->set_req( 0, preheader_ctrl ); // Fix x's control input to preheader
850  }
851
852  // Recursive fixup any other input edges into x.
853  // If there are no changes we can just return 'n', otherwise
854  // we need to clone a private copy and change it.
855  for( uint i = 1; i < n->req(); i++ ) {
856    Node *g = clone_up_backedge_goo( back_ctrl, preheader_ctrl, n->in(i), visited, clones );
857    if( g != n->in(i) ) {
858      if( !x ) {
859        assert(clones.find(n->_idx) == NULL, "dead loop");
860        x = n->clone();
861        clones.push(x, n->_idx);
862      }
863      x->set_req(i, g);
864    }
865  }
866  if( x ) {                     // x can legally float to pre-header location
867    register_new_node( x, preheader_ctrl );
868    return x;
869  } else {                      // raise n to cover LCA of uses
870    set_ctrl( n, find_non_split_ctrl(back_ctrl->in(0)) );
871  }
872  return n;
873}
874
875//------------------------------insert_pre_post_loops--------------------------
876// Insert pre and post loops.  If peel_only is set, the pre-loop can not have
877// more iterations added.  It acts as a 'peel' only, no lower-bound RCE, no
878// alignment.  Useful to unroll loops that do no array accesses.
879void PhaseIdealLoop::insert_pre_post_loops( IdealLoopTree *loop, Node_List &old_new, bool peel_only ) {
880
881#ifndef PRODUCT
882  if (TraceLoopOpts) {
883    if (peel_only)
884      tty->print("PeelMainPost ");
885    else
886      tty->print("PreMainPost  ");
887    loop->dump_head();
888  }
889#endif
890  C->set_major_progress();
891
892  // Find common pieces of the loop being guarded with pre & post loops
893  CountedLoopNode *main_head = loop->_head->as_CountedLoop();
894  assert( main_head->is_normal_loop(), "" );
895  CountedLoopEndNode *main_end = main_head->loopexit();
896  guarantee(main_end != NULL, "no loop exit node");
897  assert( main_end->outcnt() == 2, "1 true, 1 false path only" );
898  uint dd_main_head = dom_depth(main_head);
899  uint max = main_head->outcnt();
900
901  Node *pre_header= main_head->in(LoopNode::EntryControl);
902  Node *init      = main_head->init_trip();
903  Node *incr      = main_end ->incr();
904  Node *limit     = main_end ->limit();
905  Node *stride    = main_end ->stride();
906  Node *cmp       = main_end ->cmp_node();
907  BoolTest::mask b_test = main_end->test_trip();
908
909  // Need only 1 user of 'bol' because I will be hacking the loop bounds.
910  Node *bol = main_end->in(CountedLoopEndNode::TestValue);
911  if( bol->outcnt() != 1 ) {
912    bol = bol->clone();
913    register_new_node(bol,main_end->in(CountedLoopEndNode::TestControl));
914    _igvn.hash_delete(main_end);
915    main_end->set_req(CountedLoopEndNode::TestValue, bol);
916  }
917  // Need only 1 user of 'cmp' because I will be hacking the loop bounds.
918  if( cmp->outcnt() != 1 ) {
919    cmp = cmp->clone();
920    register_new_node(cmp,main_end->in(CountedLoopEndNode::TestControl));
921    _igvn.hash_delete(bol);
922    bol->set_req(1, cmp);
923  }
924
925  //------------------------------
926  // Step A: Create Post-Loop.
927  Node* main_exit = main_end->proj_out(false);
928  assert( main_exit->Opcode() == Op_IfFalse, "" );
929  int dd_main_exit = dom_depth(main_exit);
930
931  // Step A1: Clone the loop body.  The clone becomes the post-loop.  The main
932  // loop pre-header illegally has 2 control users (old & new loops).
933  clone_loop( loop, old_new, dd_main_exit );
934  assert( old_new[main_end ->_idx]->Opcode() == Op_CountedLoopEnd, "" );
935  CountedLoopNode *post_head = old_new[main_head->_idx]->as_CountedLoop();
936  post_head->set_post_loop(main_head);
937
938  // Reduce the post-loop trip count.
939  CountedLoopEndNode* post_end = old_new[main_end ->_idx]->as_CountedLoopEnd();
940  post_end->_prob = PROB_FAIR;
941
942  // Build the main-loop normal exit.
943  IfFalseNode *new_main_exit = new (C) IfFalseNode(main_end);
944  _igvn.register_new_node_with_optimizer( new_main_exit );
945  set_idom(new_main_exit, main_end, dd_main_exit );
946  set_loop(new_main_exit, loop->_parent);
947
948  // Step A2: Build a zero-trip guard for the post-loop.  After leaving the
949  // main-loop, the post-loop may not execute at all.  We 'opaque' the incr
950  // (the main-loop trip-counter exit value) because we will be changing
951  // the exit value (via unrolling) so we cannot constant-fold away the zero
952  // trip guard until all unrolling is done.
953  Node *zer_opaq = new (C) Opaque1Node(C, incr);
954  Node *zer_cmp  = new (C) CmpINode( zer_opaq, limit );
955  Node *zer_bol  = new (C) BoolNode( zer_cmp, b_test );
956  register_new_node( zer_opaq, new_main_exit );
957  register_new_node( zer_cmp , new_main_exit );
958  register_new_node( zer_bol , new_main_exit );
959
960  // Build the IfNode
961  IfNode *zer_iff = new (C) IfNode( new_main_exit, zer_bol, PROB_FAIR, COUNT_UNKNOWN );
962  _igvn.register_new_node_with_optimizer( zer_iff );
963  set_idom(zer_iff, new_main_exit, dd_main_exit);
964  set_loop(zer_iff, loop->_parent);
965
966  // Plug in the false-path, taken if we need to skip post-loop
967  _igvn.replace_input_of(main_exit, 0, zer_iff);
968  set_idom(main_exit, zer_iff, dd_main_exit);
969  set_idom(main_exit->unique_out(), zer_iff, dd_main_exit);
970  // Make the true-path, must enter the post loop
971  Node *zer_taken = new (C) IfTrueNode( zer_iff );
972  _igvn.register_new_node_with_optimizer( zer_taken );
973  set_idom(zer_taken, zer_iff, dd_main_exit);
974  set_loop(zer_taken, loop->_parent);
975  // Plug in the true path
976  _igvn.hash_delete( post_head );
977  post_head->set_req(LoopNode::EntryControl, zer_taken);
978  set_idom(post_head, zer_taken, dd_main_exit);
979
980  Arena *a = Thread::current()->resource_area();
981  VectorSet visited(a);
982  Node_Stack clones(a, main_head->back_control()->outcnt());
983  // Step A3: Make the fall-in values to the post-loop come from the
984  // fall-out values of the main-loop.
985  for (DUIterator_Fast imax, i = main_head->fast_outs(imax); i < imax; i++) {
986    Node* main_phi = main_head->fast_out(i);
987    if( main_phi->is_Phi() && main_phi->in(0) == main_head && main_phi->outcnt() >0 ) {
988      Node *post_phi = old_new[main_phi->_idx];
989      Node *fallmain  = clone_up_backedge_goo(main_head->back_control(),
990                                              post_head->init_control(),
991                                              main_phi->in(LoopNode::LoopBackControl),
992                                              visited, clones);
993      _igvn.hash_delete(post_phi);
994      post_phi->set_req( LoopNode::EntryControl, fallmain );
995    }
996  }
997
998  // Update local caches for next stanza
999  main_exit = new_main_exit;
1000
1001
1002  //------------------------------
1003  // Step B: Create Pre-Loop.
1004
1005  // Step B1: Clone the loop body.  The clone becomes the pre-loop.  The main
1006  // loop pre-header illegally has 2 control users (old & new loops).
1007  clone_loop( loop, old_new, dd_main_head );
1008  CountedLoopNode*    pre_head = old_new[main_head->_idx]->as_CountedLoop();
1009  CountedLoopEndNode* pre_end  = old_new[main_end ->_idx]->as_CountedLoopEnd();
1010  pre_head->set_pre_loop(main_head);
1011  Node *pre_incr = old_new[incr->_idx];
1012
1013  // Reduce the pre-loop trip count.
1014  pre_end->_prob = PROB_FAIR;
1015
1016  // Find the pre-loop normal exit.
1017  Node* pre_exit = pre_end->proj_out(false);
1018  assert( pre_exit->Opcode() == Op_IfFalse, "" );
1019  IfFalseNode *new_pre_exit = new (C) IfFalseNode(pre_end);
1020  _igvn.register_new_node_with_optimizer( new_pre_exit );
1021  set_idom(new_pre_exit, pre_end, dd_main_head);
1022  set_loop(new_pre_exit, loop->_parent);
1023
1024  // Step B2: Build a zero-trip guard for the main-loop.  After leaving the
1025  // pre-loop, the main-loop may not execute at all.  Later in life this
1026  // zero-trip guard will become the minimum-trip guard when we unroll
1027  // the main-loop.
1028  Node *min_opaq = new (C) Opaque1Node(C, limit);
1029  Node *min_cmp  = new (C) CmpINode( pre_incr, min_opaq );
1030  Node *min_bol  = new (C) BoolNode( min_cmp, b_test );
1031  register_new_node( min_opaq, new_pre_exit );
1032  register_new_node( min_cmp , new_pre_exit );
1033  register_new_node( min_bol , new_pre_exit );
1034
1035  // Build the IfNode (assume the main-loop is executed always).
1036  IfNode *min_iff = new (C) IfNode( new_pre_exit, min_bol, PROB_ALWAYS, COUNT_UNKNOWN );
1037  _igvn.register_new_node_with_optimizer( min_iff );
1038  set_idom(min_iff, new_pre_exit, dd_main_head);
1039  set_loop(min_iff, loop->_parent);
1040
1041  // Plug in the false-path, taken if we need to skip main-loop
1042  _igvn.hash_delete( pre_exit );
1043  pre_exit->set_req(0, min_iff);
1044  set_idom(pre_exit, min_iff, dd_main_head);
1045  set_idom(pre_exit->unique_out(), min_iff, dd_main_head);
1046  // Make the true-path, must enter the main loop
1047  Node *min_taken = new (C) IfTrueNode( min_iff );
1048  _igvn.register_new_node_with_optimizer( min_taken );
1049  set_idom(min_taken, min_iff, dd_main_head);
1050  set_loop(min_taken, loop->_parent);
1051  // Plug in the true path
1052  _igvn.hash_delete( main_head );
1053  main_head->set_req(LoopNode::EntryControl, min_taken);
1054  set_idom(main_head, min_taken, dd_main_head);
1055
1056  visited.Clear();
1057  clones.clear();
1058  // Step B3: Make the fall-in values to the main-loop come from the
1059  // fall-out values of the pre-loop.
1060  for (DUIterator_Fast i2max, i2 = main_head->fast_outs(i2max); i2 < i2max; i2++) {
1061    Node* main_phi = main_head->fast_out(i2);
1062    if( main_phi->is_Phi() && main_phi->in(0) == main_head && main_phi->outcnt() > 0 ) {
1063      Node *pre_phi = old_new[main_phi->_idx];
1064      Node *fallpre  = clone_up_backedge_goo(pre_head->back_control(),
1065                                             main_head->init_control(),
1066                                             pre_phi->in(LoopNode::LoopBackControl),
1067                                             visited, clones);
1068      _igvn.hash_delete(main_phi);
1069      main_phi->set_req( LoopNode::EntryControl, fallpre );
1070    }
1071  }
1072
1073  // Step B4: Shorten the pre-loop to run only 1 iteration (for now).
1074  // RCE and alignment may change this later.
1075  Node *cmp_end = pre_end->cmp_node();
1076  assert( cmp_end->in(2) == limit, "" );
1077  Node *pre_limit = new (C) AddINode( init, stride );
1078
1079  // Save the original loop limit in this Opaque1 node for
1080  // use by range check elimination.
1081  Node *pre_opaq  = new (C) Opaque1Node(C, pre_limit, limit);
1082
1083  register_new_node( pre_limit, pre_head->in(0) );
1084  register_new_node( pre_opaq , pre_head->in(0) );
1085
1086  // Since no other users of pre-loop compare, I can hack limit directly
1087  assert( cmp_end->outcnt() == 1, "no other users" );
1088  _igvn.hash_delete(cmp_end);
1089  cmp_end->set_req(2, peel_only ? pre_limit : pre_opaq);
1090
1091  // Special case for not-equal loop bounds:
1092  // Change pre loop test, main loop test, and the
1093  // main loop guard test to use lt or gt depending on stride
1094  // direction:
1095  // positive stride use <
1096  // negative stride use >
1097  //
1098  // not-equal test is kept for post loop to handle case
1099  // when init > limit when stride > 0 (and reverse).
1100
1101  if (pre_end->in(CountedLoopEndNode::TestValue)->as_Bool()->_test._test == BoolTest::ne) {
1102
1103    BoolTest::mask new_test = (main_end->stride_con() > 0) ? BoolTest::lt : BoolTest::gt;
1104    // Modify pre loop end condition
1105    Node* pre_bol = pre_end->in(CountedLoopEndNode::TestValue)->as_Bool();
1106    BoolNode* new_bol0 = new (C) BoolNode(pre_bol->in(1), new_test);
1107    register_new_node( new_bol0, pre_head->in(0) );
1108    _igvn.hash_delete(pre_end);
1109    pre_end->set_req(CountedLoopEndNode::TestValue, new_bol0);
1110    // Modify main loop guard condition
1111    assert(min_iff->in(CountedLoopEndNode::TestValue) == min_bol, "guard okay");
1112    BoolNode* new_bol1 = new (C) BoolNode(min_bol->in(1), new_test);
1113    register_new_node( new_bol1, new_pre_exit );
1114    _igvn.hash_delete(min_iff);
1115    min_iff->set_req(CountedLoopEndNode::TestValue, new_bol1);
1116    // Modify main loop end condition
1117    BoolNode* main_bol = main_end->in(CountedLoopEndNode::TestValue)->as_Bool();
1118    BoolNode* new_bol2 = new (C) BoolNode(main_bol->in(1), new_test);
1119    register_new_node( new_bol2, main_end->in(CountedLoopEndNode::TestControl) );
1120    _igvn.hash_delete(main_end);
1121    main_end->set_req(CountedLoopEndNode::TestValue, new_bol2);
1122  }
1123
1124  // Flag main loop
1125  main_head->set_main_loop();
1126  if( peel_only ) main_head->set_main_no_pre_loop();
1127
1128  // Subtract a trip count for the pre-loop.
1129  main_head->set_trip_count(main_head->trip_count() - 1);
1130
1131  // It's difficult to be precise about the trip-counts
1132  // for the pre/post loops.  They are usually very short,
1133  // so guess that 4 trips is a reasonable value.
1134  post_head->set_profile_trip_cnt(4.0);
1135  pre_head->set_profile_trip_cnt(4.0);
1136
1137  // Now force out all loop-invariant dominating tests.  The optimizer
1138  // finds some, but we _know_ they are all useless.
1139  peeled_dom_test_elim(loop,old_new);
1140}
1141
1142//------------------------------is_invariant-----------------------------
1143// Return true if n is invariant
1144bool IdealLoopTree::is_invariant(Node* n) const {
1145  Node *n_c = _phase->has_ctrl(n) ? _phase->get_ctrl(n) : n;
1146  if (n_c->is_top()) return false;
1147  return !is_member(_phase->get_loop(n_c));
1148}
1149
1150
1151//------------------------------do_unroll--------------------------------------
1152// Unroll the loop body one step - make each trip do 2 iterations.
1153void PhaseIdealLoop::do_unroll( IdealLoopTree *loop, Node_List &old_new, bool adjust_min_trip ) {
1154  assert(LoopUnrollLimit, "");
1155  CountedLoopNode *loop_head = loop->_head->as_CountedLoop();
1156  CountedLoopEndNode *loop_end = loop_head->loopexit();
1157  assert(loop_end, "");
1158#ifndef PRODUCT
1159  if (PrintOpto && VerifyLoopOptimizations) {
1160    tty->print("Unrolling ");
1161    loop->dump_head();
1162  } else if (TraceLoopOpts) {
1163    if (loop_head->trip_count() < (uint)LoopUnrollLimit) {
1164      tty->print("Unroll %d(%2d) ", loop_head->unrolled_count()*2, loop_head->trip_count());
1165    } else {
1166      tty->print("Unroll %d     ", loop_head->unrolled_count()*2);
1167    }
1168    loop->dump_head();
1169  }
1170#endif
1171
1172  // Remember loop node count before unrolling to detect
1173  // if rounds of unroll,optimize are making progress
1174  loop_head->set_node_count_before_unroll(loop->_body.size());
1175
1176  Node *ctrl  = loop_head->in(LoopNode::EntryControl);
1177  Node *limit = loop_head->limit();
1178  Node *init  = loop_head->init_trip();
1179  Node *stride = loop_head->stride();
1180
1181  Node *opaq = NULL;
1182  if (adjust_min_trip) {       // If not maximally unrolling, need adjustment
1183    // Search for zero-trip guard.
1184    assert( loop_head->is_main_loop(), "" );
1185    assert( ctrl->Opcode() == Op_IfTrue || ctrl->Opcode() == Op_IfFalse, "" );
1186    Node *iff = ctrl->in(0);
1187    assert( iff->Opcode() == Op_If, "" );
1188    Node *bol = iff->in(1);
1189    assert( bol->Opcode() == Op_Bool, "" );
1190    Node *cmp = bol->in(1);
1191    assert( cmp->Opcode() == Op_CmpI, "" );
1192    opaq = cmp->in(2);
1193    // Occasionally it's possible for a zero-trip guard Opaque1 node to be
1194    // optimized away and then another round of loop opts attempted.
1195    // We can not optimize this particular loop in that case.
1196    if (opaq->Opcode() != Op_Opaque1)
1197      return; // Cannot find zero-trip guard!  Bail out!
1198    // Zero-trip test uses an 'opaque' node which is not shared.
1199    assert(opaq->outcnt() == 1 && opaq->in(1) == limit, "");
1200  }
1201
1202  C->set_major_progress();
1203
1204  Node* new_limit = NULL;
1205  if (UnrollLimitCheck) {
1206    int stride_con = stride->get_int();
1207    int stride_p = (stride_con > 0) ? stride_con : -stride_con;
1208    uint old_trip_count = loop_head->trip_count();
1209    // Verify that unroll policy result is still valid.
1210    assert(old_trip_count > 1 &&
1211           (!adjust_min_trip || stride_p <= (1<<3)*loop_head->unrolled_count()), "sanity");
1212
1213    // Adjust loop limit to keep valid iterations number after unroll.
1214    // Use (limit - stride) instead of (((limit - init)/stride) & (-2))*stride
1215    // which may overflow.
1216    if (!adjust_min_trip) {
1217      assert(old_trip_count > 1 && (old_trip_count & 1) == 0,
1218             "odd trip count for maximally unroll");
1219      // Don't need to adjust limit for maximally unroll since trip count is even.
1220    } else if (loop_head->has_exact_trip_count() && init->is_Con()) {
1221      // Loop's limit is constant. Loop's init could be constant when pre-loop
1222      // become peeled iteration.
1223      jlong init_con = init->get_int();
1224      // We can keep old loop limit if iterations count stays the same:
1225      //   old_trip_count == new_trip_count * 2
1226      // Note: since old_trip_count >= 2 then new_trip_count >= 1
1227      // so we also don't need to adjust zero trip test.
1228      jlong limit_con  = limit->get_int();
1229      // (stride_con*2) not overflow since stride_con <= 8.
1230      int new_stride_con = stride_con * 2;
1231      int stride_m    = new_stride_con - (stride_con > 0 ? 1 : -1);
1232      jlong trip_count = (limit_con - init_con + stride_m)/new_stride_con;
1233      // New trip count should satisfy next conditions.
1234      assert(trip_count > 0 && (julong)trip_count < (julong)max_juint/2, "sanity");
1235      uint new_trip_count = (uint)trip_count;
1236      adjust_min_trip = (old_trip_count != new_trip_count*2);
1237    }
1238
1239    if (adjust_min_trip) {
1240      // Step 2: Adjust the trip limit if it is called for.
1241      // The adjustment amount is -stride. Need to make sure if the
1242      // adjustment underflows or overflows, then the main loop is skipped.
1243      Node* cmp = loop_end->cmp_node();
1244      assert(cmp->in(2) == limit, "sanity");
1245      assert(opaq != NULL && opaq->in(1) == limit, "sanity");
1246
1247      // Verify that policy_unroll result is still valid.
1248      const TypeInt* limit_type = _igvn.type(limit)->is_int();
1249      assert(stride_con > 0 && ((limit_type->_hi - stride_con) < limit_type->_hi) ||
1250             stride_con < 0 && ((limit_type->_lo - stride_con) > limit_type->_lo), "sanity");
1251
1252      if (limit->is_Con()) {
1253        // The check in policy_unroll and the assert above guarantee
1254        // no underflow if limit is constant.
1255        new_limit = _igvn.intcon(limit->get_int() - stride_con);
1256        set_ctrl(new_limit, C->root());
1257      } else {
1258        // Limit is not constant.
1259        if (loop_head->unrolled_count() == 1) { // only for first unroll
1260          // Separate limit by Opaque node in case it is an incremented
1261          // variable from previous loop to avoid using pre-incremented
1262          // value which could increase register pressure.
1263          // Otherwise reorg_offsets() optimization will create a separate
1264          // Opaque node for each use of trip-counter and as result
1265          // zero trip guard limit will be different from loop limit.
1266          assert(has_ctrl(opaq), "should have it");
1267          Node* opaq_ctrl = get_ctrl(opaq);
1268          limit = new (C) Opaque2Node( C, limit );
1269          register_new_node( limit, opaq_ctrl );
1270        }
1271        if (stride_con > 0 && ((limit_type->_lo - stride_con) < limit_type->_lo) ||
1272                   stride_con < 0 && ((limit_type->_hi - stride_con) > limit_type->_hi)) {
1273          // No underflow.
1274          new_limit = new (C) SubINode(limit, stride);
1275        } else {
1276          // (limit - stride) may underflow.
1277          // Clamp the adjustment value with MININT or MAXINT:
1278          //
1279          //   new_limit = limit-stride
1280          //   if (stride > 0)
1281          //     new_limit = (limit < new_limit) ? MININT : new_limit;
1282          //   else
1283          //     new_limit = (limit > new_limit) ? MAXINT : new_limit;
1284          //
1285          BoolTest::mask bt = loop_end->test_trip();
1286          assert(bt == BoolTest::lt || bt == BoolTest::gt, "canonical test is expected");
1287          Node* adj_max = _igvn.intcon((stride_con > 0) ? min_jint : max_jint);
1288          set_ctrl(adj_max, C->root());
1289          Node* old_limit = NULL;
1290          Node* adj_limit = NULL;
1291          Node* bol = limit->is_CMove() ? limit->in(CMoveNode::Condition) : NULL;
1292          if (loop_head->unrolled_count() > 1 &&
1293              limit->is_CMove() && limit->Opcode() == Op_CMoveI &&
1294              limit->in(CMoveNode::IfTrue) == adj_max &&
1295              bol->as_Bool()->_test._test == bt &&
1296              bol->in(1)->Opcode() == Op_CmpI &&
1297              bol->in(1)->in(2) == limit->in(CMoveNode::IfFalse)) {
1298            // Loop was unrolled before.
1299            // Optimize the limit to avoid nested CMove:
1300            // use original limit as old limit.
1301            old_limit = bol->in(1)->in(1);
1302            // Adjust previous adjusted limit.
1303            adj_limit = limit->in(CMoveNode::IfFalse);
1304            adj_limit = new (C) SubINode(adj_limit, stride);
1305          } else {
1306            old_limit = limit;
1307            adj_limit = new (C) SubINode(limit, stride);
1308          }
1309          assert(old_limit != NULL && adj_limit != NULL, "");
1310          register_new_node( adj_limit, ctrl ); // adjust amount
1311          Node* adj_cmp = new (C) CmpINode(old_limit, adj_limit);
1312          register_new_node( adj_cmp, ctrl );
1313          Node* adj_bool = new (C) BoolNode(adj_cmp, bt);
1314          register_new_node( adj_bool, ctrl );
1315          new_limit = new (C) CMoveINode(adj_bool, adj_limit, adj_max, TypeInt::INT);
1316        }
1317        register_new_node(new_limit, ctrl);
1318      }
1319      assert(new_limit != NULL, "");
1320      // Replace in loop test.
1321      assert(loop_end->in(1)->in(1) == cmp, "sanity");
1322      if (cmp->outcnt() == 1 && loop_end->in(1)->outcnt() == 1) {
1323        // Don't need to create new test since only one user.
1324        _igvn.hash_delete(cmp);
1325        cmp->set_req(2, new_limit);
1326      } else {
1327        // Create new test since it is shared.
1328        Node* ctrl2 = loop_end->in(0);
1329        Node* cmp2  = cmp->clone();
1330        cmp2->set_req(2, new_limit);
1331        register_new_node(cmp2, ctrl2);
1332        Node* bol2 = loop_end->in(1)->clone();
1333        bol2->set_req(1, cmp2);
1334        register_new_node(bol2, ctrl2);
1335        _igvn.hash_delete(loop_end);
1336        loop_end->set_req(1, bol2);
1337      }
1338      // Step 3: Find the min-trip test guaranteed before a 'main' loop.
1339      // Make it a 1-trip test (means at least 2 trips).
1340
1341      // Guard test uses an 'opaque' node which is not shared.  Hence I
1342      // can edit it's inputs directly.  Hammer in the new limit for the
1343      // minimum-trip guard.
1344      assert(opaq->outcnt() == 1, "");
1345      _igvn.hash_delete(opaq);
1346      opaq->set_req(1, new_limit);
1347    }
1348
1349    // Adjust max trip count. The trip count is intentionally rounded
1350    // down here (e.g. 15-> 7-> 3-> 1) because if we unwittingly over-unroll,
1351    // the main, unrolled, part of the loop will never execute as it is protected
1352    // by the min-trip test.  See bug 4834191 for a case where we over-unrolled
1353    // and later determined that part of the unrolled loop was dead.
1354    loop_head->set_trip_count(old_trip_count / 2);
1355
1356    // Double the count of original iterations in the unrolled loop body.
1357    loop_head->double_unrolled_count();
1358
1359  } else { // LoopLimitCheck
1360
1361    // Adjust max trip count. The trip count is intentionally rounded
1362    // down here (e.g. 15-> 7-> 3-> 1) because if we unwittingly over-unroll,
1363    // the main, unrolled, part of the loop will never execute as it is protected
1364    // by the min-trip test.  See bug 4834191 for a case where we over-unrolled
1365    // and later determined that part of the unrolled loop was dead.
1366    loop_head->set_trip_count(loop_head->trip_count() / 2);
1367
1368    // Double the count of original iterations in the unrolled loop body.
1369    loop_head->double_unrolled_count();
1370
1371    // -----------
1372    // Step 2: Cut back the trip counter for an unroll amount of 2.
1373    // Loop will normally trip (limit - init)/stride_con.  Since it's a
1374    // CountedLoop this is exact (stride divides limit-init exactly).
1375    // We are going to double the loop body, so we want to knock off any
1376    // odd iteration: (trip_cnt & ~1).  Then back compute a new limit.
1377    Node *span = new (C) SubINode( limit, init );
1378    register_new_node( span, ctrl );
1379    Node *trip = new (C) DivINode( 0, span, stride );
1380    register_new_node( trip, ctrl );
1381    Node *mtwo = _igvn.intcon(-2);
1382    set_ctrl(mtwo, C->root());
1383    Node *rond = new (C) AndINode( trip, mtwo );
1384    register_new_node( rond, ctrl );
1385    Node *spn2 = new (C) MulINode( rond, stride );
1386    register_new_node( spn2, ctrl );
1387    new_limit = new (C) AddINode( spn2, init );
1388    register_new_node( new_limit, ctrl );
1389
1390    // Hammer in the new limit
1391    Node *ctrl2 = loop_end->in(0);
1392    Node *cmp2 = new (C) CmpINode( loop_head->incr(), new_limit );
1393    register_new_node( cmp2, ctrl2 );
1394    Node *bol2 = new (C) BoolNode( cmp2, loop_end->test_trip() );
1395    register_new_node( bol2, ctrl2 );
1396    _igvn.hash_delete(loop_end);
1397    loop_end->set_req(CountedLoopEndNode::TestValue, bol2);
1398
1399    // Step 3: Find the min-trip test guaranteed before a 'main' loop.
1400    // Make it a 1-trip test (means at least 2 trips).
1401    if( adjust_min_trip ) {
1402      assert( new_limit != NULL, "" );
1403      // Guard test uses an 'opaque' node which is not shared.  Hence I
1404      // can edit it's inputs directly.  Hammer in the new limit for the
1405      // minimum-trip guard.
1406      assert( opaq->outcnt() == 1, "" );
1407      _igvn.hash_delete(opaq);
1408      opaq->set_req(1, new_limit);
1409    }
1410  } // LoopLimitCheck
1411
1412  // ---------
1413  // Step 4: Clone the loop body.  Move it inside the loop.  This loop body
1414  // represents the odd iterations; since the loop trips an even number of
1415  // times its backedge is never taken.  Kill the backedge.
1416  uint dd = dom_depth(loop_head);
1417  clone_loop( loop, old_new, dd );
1418
1419  // Make backedges of the clone equal to backedges of the original.
1420  // Make the fall-in from the original come from the fall-out of the clone.
1421  for (DUIterator_Fast jmax, j = loop_head->fast_outs(jmax); j < jmax; j++) {
1422    Node* phi = loop_head->fast_out(j);
1423    if( phi->is_Phi() && phi->in(0) == loop_head && phi->outcnt() > 0 ) {
1424      Node *newphi = old_new[phi->_idx];
1425      _igvn.hash_delete( phi );
1426      _igvn.hash_delete( newphi );
1427
1428      phi   ->set_req(LoopNode::   EntryControl, newphi->in(LoopNode::LoopBackControl));
1429      newphi->set_req(LoopNode::LoopBackControl, phi   ->in(LoopNode::LoopBackControl));
1430      phi   ->set_req(LoopNode::LoopBackControl, C->top());
1431    }
1432  }
1433  Node *clone_head = old_new[loop_head->_idx];
1434  _igvn.hash_delete( clone_head );
1435  loop_head ->set_req(LoopNode::   EntryControl, clone_head->in(LoopNode::LoopBackControl));
1436  clone_head->set_req(LoopNode::LoopBackControl, loop_head ->in(LoopNode::LoopBackControl));
1437  loop_head ->set_req(LoopNode::LoopBackControl, C->top());
1438  loop->_head = clone_head;     // New loop header
1439
1440  set_idom(loop_head,  loop_head ->in(LoopNode::EntryControl), dd);
1441  set_idom(clone_head, clone_head->in(LoopNode::EntryControl), dd);
1442
1443  // Kill the clone's backedge
1444  Node *newcle = old_new[loop_end->_idx];
1445  _igvn.hash_delete( newcle );
1446  Node *one = _igvn.intcon(1);
1447  set_ctrl(one, C->root());
1448  newcle->set_req(1, one);
1449  // Force clone into same loop body
1450  uint max = loop->_body.size();
1451  for( uint k = 0; k < max; k++ ) {
1452    Node *old = loop->_body.at(k);
1453    Node *nnn = old_new[old->_idx];
1454    loop->_body.push(nnn);
1455    if (!has_ctrl(old))
1456      set_loop(nnn, loop);
1457  }
1458
1459  loop->record_for_igvn();
1460}
1461
1462//------------------------------do_maximally_unroll----------------------------
1463
1464void PhaseIdealLoop::do_maximally_unroll( IdealLoopTree *loop, Node_List &old_new ) {
1465  CountedLoopNode *cl = loop->_head->as_CountedLoop();
1466  assert(cl->has_exact_trip_count(), "trip count is not exact");
1467  assert(cl->trip_count() > 0, "");
1468#ifndef PRODUCT
1469  if (TraceLoopOpts) {
1470    tty->print("MaxUnroll  %d ", cl->trip_count());
1471    loop->dump_head();
1472  }
1473#endif
1474
1475  // If loop is tripping an odd number of times, peel odd iteration
1476  if ((cl->trip_count() & 1) == 1) {
1477    do_peeling(loop, old_new);
1478  }
1479
1480  // Now its tripping an even number of times remaining.  Double loop body.
1481  // Do not adjust pre-guards; they are not needed and do not exist.
1482  if (cl->trip_count() > 0) {
1483    assert((cl->trip_count() & 1) == 0, "missed peeling");
1484    do_unroll(loop, old_new, false);
1485  }
1486}
1487
1488//------------------------------dominates_backedge---------------------------------
1489// Returns true if ctrl is executed on every complete iteration
1490bool IdealLoopTree::dominates_backedge(Node* ctrl) {
1491  assert(ctrl->is_CFG(), "must be control");
1492  Node* backedge = _head->as_Loop()->in(LoopNode::LoopBackControl);
1493  return _phase->dom_lca_internal(ctrl, backedge) == ctrl;
1494}
1495
1496//------------------------------adjust_limit-----------------------------------
1497// Helper function for add_constraint().
1498Node* PhaseIdealLoop::adjust_limit(int stride_con, Node * scale, Node *offset, Node *rc_limit, Node *loop_limit, Node *pre_ctrl) {
1499  // Compute "I :: (limit-offset)/scale"
1500  Node *con = new (C) SubINode(rc_limit, offset);
1501  register_new_node(con, pre_ctrl);
1502  Node *X = new (C) DivINode(0, con, scale);
1503  register_new_node(X, pre_ctrl);
1504
1505  // Adjust loop limit
1506  loop_limit = (stride_con > 0)
1507               ? (Node*)(new (C) MinINode(loop_limit, X))
1508               : (Node*)(new (C) MaxINode(loop_limit, X));
1509  register_new_node(loop_limit, pre_ctrl);
1510  return loop_limit;
1511}
1512
1513//------------------------------add_constraint---------------------------------
1514// Constrain the main loop iterations so the conditions:
1515//    low_limit <= scale_con * I + offset  <  upper_limit
1516// always holds true.  That is, either increase the number of iterations in
1517// the pre-loop or the post-loop until the condition holds true in the main
1518// loop.  Stride, scale, offset and limit are all loop invariant.  Further,
1519// stride and scale are constants (offset and limit often are).
1520void PhaseIdealLoop::add_constraint( int stride_con, int scale_con, Node *offset, Node *low_limit, Node *upper_limit, Node *pre_ctrl, Node **pre_limit, Node **main_limit ) {
1521  // For positive stride, the pre-loop limit always uses a MAX function
1522  // and the main loop a MIN function.  For negative stride these are
1523  // reversed.
1524
1525  // Also for positive stride*scale the affine function is increasing, so the
1526  // pre-loop must check for underflow and the post-loop for overflow.
1527  // Negative stride*scale reverses this; pre-loop checks for overflow and
1528  // post-loop for underflow.
1529
1530  Node *scale = _igvn.intcon(scale_con);
1531  set_ctrl(scale, C->root());
1532
1533  if ((stride_con^scale_con) >= 0) { // Use XOR to avoid overflow
1534    // The overflow limit: scale*I+offset < upper_limit
1535    // For main-loop compute
1536    //   ( if (scale > 0) /* and stride > 0 */
1537    //       I < (upper_limit-offset)/scale
1538    //     else /* scale < 0 and stride < 0 */
1539    //       I > (upper_limit-offset)/scale
1540    //   )
1541    //
1542    // (upper_limit-offset) may overflow or underflow.
1543    // But it is fine since main loop will either have
1544    // less iterations or will be skipped in such case.
1545    *main_limit = adjust_limit(stride_con, scale, offset, upper_limit, *main_limit, pre_ctrl);
1546
1547    // The underflow limit: low_limit <= scale*I+offset.
1548    // For pre-loop compute
1549    //   NOT(scale*I+offset >= low_limit)
1550    //   scale*I+offset < low_limit
1551    //   ( if (scale > 0) /* and stride > 0 */
1552    //       I < (low_limit-offset)/scale
1553    //     else /* scale < 0 and stride < 0 */
1554    //       I > (low_limit-offset)/scale
1555    //   )
1556
1557    if (low_limit->get_int() == -max_jint) {
1558      if (!RangeLimitCheck) return;
1559      // We need this guard when scale*pre_limit+offset >= limit
1560      // due to underflow. So we need execute pre-loop until
1561      // scale*I+offset >= min_int. But (min_int-offset) will
1562      // underflow when offset > 0 and X will be > original_limit
1563      // when stride > 0. To avoid it we replace positive offset with 0.
1564      //
1565      // Also (min_int+1 == -max_int) is used instead of min_int here
1566      // to avoid problem with scale == -1 (min_int/(-1) == min_int).
1567      Node* shift = _igvn.intcon(31);
1568      set_ctrl(shift, C->root());
1569      Node* sign = new (C) RShiftINode(offset, shift);
1570      register_new_node(sign, pre_ctrl);
1571      offset = new (C) AndINode(offset, sign);
1572      register_new_node(offset, pre_ctrl);
1573    } else {
1574      assert(low_limit->get_int() == 0, "wrong low limit for range check");
1575      // The only problem we have here when offset == min_int
1576      // since (0-min_int) == min_int. It may be fine for stride > 0
1577      // but for stride < 0 X will be < original_limit. To avoid it
1578      // max(pre_limit, original_limit) is used in do_range_check().
1579    }
1580    // Pass (-stride) to indicate pre_loop_cond = NOT(main_loop_cond);
1581    *pre_limit = adjust_limit((-stride_con), scale, offset, low_limit, *pre_limit, pre_ctrl);
1582
1583  } else { // stride_con*scale_con < 0
1584    // For negative stride*scale pre-loop checks for overflow and
1585    // post-loop for underflow.
1586    //
1587    // The overflow limit: scale*I+offset < upper_limit
1588    // For pre-loop compute
1589    //   NOT(scale*I+offset < upper_limit)
1590    //   scale*I+offset >= upper_limit
1591    //   scale*I+offset+1 > upper_limit
1592    //   ( if (scale < 0) /* and stride > 0 */
1593    //       I < (upper_limit-(offset+1))/scale
1594    //     else /* scale > 0 and stride < 0 */
1595    //       I > (upper_limit-(offset+1))/scale
1596    //   )
1597    //
1598    // (upper_limit-offset-1) may underflow or overflow.
1599    // To avoid it min(pre_limit, original_limit) is used
1600    // in do_range_check() for stride > 0 and max() for < 0.
1601    Node *one  = _igvn.intcon(1);
1602    set_ctrl(one, C->root());
1603
1604    Node *plus_one = new (C) AddINode(offset, one);
1605    register_new_node( plus_one, pre_ctrl );
1606    // Pass (-stride) to indicate pre_loop_cond = NOT(main_loop_cond);
1607    *pre_limit = adjust_limit((-stride_con), scale, plus_one, upper_limit, *pre_limit, pre_ctrl);
1608
1609    if (low_limit->get_int() == -max_jint) {
1610      if (!RangeLimitCheck) return;
1611      // We need this guard when scale*main_limit+offset >= limit
1612      // due to underflow. So we need execute main-loop while
1613      // scale*I+offset+1 > min_int. But (min_int-offset-1) will
1614      // underflow when (offset+1) > 0 and X will be < main_limit
1615      // when scale < 0 (and stride > 0). To avoid it we replace
1616      // positive (offset+1) with 0.
1617      //
1618      // Also (min_int+1 == -max_int) is used instead of min_int here
1619      // to avoid problem with scale == -1 (min_int/(-1) == min_int).
1620      Node* shift = _igvn.intcon(31);
1621      set_ctrl(shift, C->root());
1622      Node* sign = new (C) RShiftINode(plus_one, shift);
1623      register_new_node(sign, pre_ctrl);
1624      plus_one = new (C) AndINode(plus_one, sign);
1625      register_new_node(plus_one, pre_ctrl);
1626    } else {
1627      assert(low_limit->get_int() == 0, "wrong low limit for range check");
1628      // The only problem we have here when offset == max_int
1629      // since (max_int+1) == min_int and (0-min_int) == min_int.
1630      // But it is fine since main loop will either have
1631      // less iterations or will be skipped in such case.
1632    }
1633    // The underflow limit: low_limit <= scale*I+offset.
1634    // For main-loop compute
1635    //   scale*I+offset+1 > low_limit
1636    //   ( if (scale < 0) /* and stride > 0 */
1637    //       I < (low_limit-(offset+1))/scale
1638    //     else /* scale > 0 and stride < 0 */
1639    //       I > (low_limit-(offset+1))/scale
1640    //   )
1641
1642    *main_limit = adjust_limit(stride_con, scale, plus_one, low_limit, *main_limit, pre_ctrl);
1643  }
1644}
1645
1646
1647//------------------------------is_scaled_iv---------------------------------
1648// Return true if exp is a constant times an induction var
1649bool PhaseIdealLoop::is_scaled_iv(Node* exp, Node* iv, int* p_scale) {
1650  if (exp == iv) {
1651    if (p_scale != NULL) {
1652      *p_scale = 1;
1653    }
1654    return true;
1655  }
1656  int opc = exp->Opcode();
1657  if (opc == Op_MulI) {
1658    if (exp->in(1) == iv && exp->in(2)->is_Con()) {
1659      if (p_scale != NULL) {
1660        *p_scale = exp->in(2)->get_int();
1661      }
1662      return true;
1663    }
1664    if (exp->in(2) == iv && exp->in(1)->is_Con()) {
1665      if (p_scale != NULL) {
1666        *p_scale = exp->in(1)->get_int();
1667      }
1668      return true;
1669    }
1670  } else if (opc == Op_LShiftI) {
1671    if (exp->in(1) == iv && exp->in(2)->is_Con()) {
1672      if (p_scale != NULL) {
1673        *p_scale = 1 << exp->in(2)->get_int();
1674      }
1675      return true;
1676    }
1677  }
1678  return false;
1679}
1680
1681//-----------------------------is_scaled_iv_plus_offset------------------------------
1682// Return true if exp is a simple induction variable expression: k1*iv + (invar + k2)
1683bool PhaseIdealLoop::is_scaled_iv_plus_offset(Node* exp, Node* iv, int* p_scale, Node** p_offset, int depth) {
1684  if (is_scaled_iv(exp, iv, p_scale)) {
1685    if (p_offset != NULL) {
1686      Node *zero = _igvn.intcon(0);
1687      set_ctrl(zero, C->root());
1688      *p_offset = zero;
1689    }
1690    return true;
1691  }
1692  int opc = exp->Opcode();
1693  if (opc == Op_AddI) {
1694    if (is_scaled_iv(exp->in(1), iv, p_scale)) {
1695      if (p_offset != NULL) {
1696        *p_offset = exp->in(2);
1697      }
1698      return true;
1699    }
1700    if (exp->in(2)->is_Con()) {
1701      Node* offset2 = NULL;
1702      if (depth < 2 &&
1703          is_scaled_iv_plus_offset(exp->in(1), iv, p_scale,
1704                                   p_offset != NULL ? &offset2 : NULL, depth+1)) {
1705        if (p_offset != NULL) {
1706          Node *ctrl_off2 = get_ctrl(offset2);
1707          Node* offset = new (C) AddINode(offset2, exp->in(2));
1708          register_new_node(offset, ctrl_off2);
1709          *p_offset = offset;
1710        }
1711        return true;
1712      }
1713    }
1714  } else if (opc == Op_SubI) {
1715    if (is_scaled_iv(exp->in(1), iv, p_scale)) {
1716      if (p_offset != NULL) {
1717        Node *zero = _igvn.intcon(0);
1718        set_ctrl(zero, C->root());
1719        Node *ctrl_off = get_ctrl(exp->in(2));
1720        Node* offset = new (C) SubINode(zero, exp->in(2));
1721        register_new_node(offset, ctrl_off);
1722        *p_offset = offset;
1723      }
1724      return true;
1725    }
1726    if (is_scaled_iv(exp->in(2), iv, p_scale)) {
1727      if (p_offset != NULL) {
1728        *p_scale *= -1;
1729        *p_offset = exp->in(1);
1730      }
1731      return true;
1732    }
1733  }
1734  return false;
1735}
1736
1737//------------------------------do_range_check---------------------------------
1738// Eliminate range-checks and other trip-counter vs loop-invariant tests.
1739void PhaseIdealLoop::do_range_check( IdealLoopTree *loop, Node_List &old_new ) {
1740#ifndef PRODUCT
1741  if (PrintOpto && VerifyLoopOptimizations) {
1742    tty->print("Range Check Elimination ");
1743    loop->dump_head();
1744  } else if (TraceLoopOpts) {
1745    tty->print("RangeCheck   ");
1746    loop->dump_head();
1747  }
1748#endif
1749  assert(RangeCheckElimination, "");
1750  CountedLoopNode *cl = loop->_head->as_CountedLoop();
1751  assert(cl->is_main_loop(), "");
1752
1753  // protect against stride not being a constant
1754  if (!cl->stride_is_con())
1755    return;
1756
1757  // Find the trip counter; we are iteration splitting based on it
1758  Node *trip_counter = cl->phi();
1759  // Find the main loop limit; we will trim it's iterations
1760  // to not ever trip end tests
1761  Node *main_limit = cl->limit();
1762
1763  // Need to find the main-loop zero-trip guard
1764  Node *ctrl  = cl->in(LoopNode::EntryControl);
1765  assert(ctrl->Opcode() == Op_IfTrue || ctrl->Opcode() == Op_IfFalse, "");
1766  Node *iffm = ctrl->in(0);
1767  assert(iffm->Opcode() == Op_If, "");
1768  Node *bolzm = iffm->in(1);
1769  assert(bolzm->Opcode() == Op_Bool, "");
1770  Node *cmpzm = bolzm->in(1);
1771  assert(cmpzm->is_Cmp(), "");
1772  Node *opqzm = cmpzm->in(2);
1773  // Can not optimize a loop if zero-trip Opaque1 node is optimized
1774  // away and then another round of loop opts attempted.
1775  if (opqzm->Opcode() != Op_Opaque1)
1776    return;
1777  assert(opqzm->in(1) == main_limit, "do not understand situation");
1778
1779  // Find the pre-loop limit; we will expand it's iterations to
1780  // not ever trip low tests.
1781  Node *p_f = iffm->in(0);
1782  assert(p_f->Opcode() == Op_IfFalse, "");
1783  CountedLoopEndNode *pre_end = p_f->in(0)->as_CountedLoopEnd();
1784  assert(pre_end->loopnode()->is_pre_loop(), "");
1785  Node *pre_opaq1 = pre_end->limit();
1786  // Occasionally it's possible for a pre-loop Opaque1 node to be
1787  // optimized away and then another round of loop opts attempted.
1788  // We can not optimize this particular loop in that case.
1789  if (pre_opaq1->Opcode() != Op_Opaque1)
1790    return;
1791  Opaque1Node *pre_opaq = (Opaque1Node*)pre_opaq1;
1792  Node *pre_limit = pre_opaq->in(1);
1793
1794  // Where do we put new limit calculations
1795  Node *pre_ctrl = pre_end->loopnode()->in(LoopNode::EntryControl);
1796
1797  // Ensure the original loop limit is available from the
1798  // pre-loop Opaque1 node.
1799  Node *orig_limit = pre_opaq->original_loop_limit();
1800  if (orig_limit == NULL || _igvn.type(orig_limit) == Type::TOP)
1801    return;
1802
1803  // Must know if its a count-up or count-down loop
1804
1805  int stride_con = cl->stride_con();
1806  Node *zero = _igvn.intcon(0);
1807  Node *one  = _igvn.intcon(1);
1808  // Use symmetrical int range [-max_jint,max_jint]
1809  Node *mini = _igvn.intcon(-max_jint);
1810  set_ctrl(zero, C->root());
1811  set_ctrl(one,  C->root());
1812  set_ctrl(mini, C->root());
1813
1814  // Range checks that do not dominate the loop backedge (ie.
1815  // conditionally executed) can lengthen the pre loop limit beyond
1816  // the original loop limit. To prevent this, the pre limit is
1817  // (for stride > 0) MINed with the original loop limit (MAXed
1818  // stride < 0) when some range_check (rc) is conditionally
1819  // executed.
1820  bool conditional_rc = false;
1821
1822  // Check loop body for tests of trip-counter plus loop-invariant vs
1823  // loop-invariant.
1824  for( uint i = 0; i < loop->_body.size(); i++ ) {
1825    Node *iff = loop->_body[i];
1826    if( iff->Opcode() == Op_If ) { // Test?
1827
1828      // Test is an IfNode, has 2 projections.  If BOTH are in the loop
1829      // we need loop unswitching instead of iteration splitting.
1830      Node *exit = loop->is_loop_exit(iff);
1831      if( !exit ) continue;
1832      int flip = (exit->Opcode() == Op_IfTrue) ? 1 : 0;
1833
1834      // Get boolean condition to test
1835      Node *i1 = iff->in(1);
1836      if( !i1->is_Bool() ) continue;
1837      BoolNode *bol = i1->as_Bool();
1838      BoolTest b_test = bol->_test;
1839      // Flip sense of test if exit condition is flipped
1840      if( flip )
1841        b_test = b_test.negate();
1842
1843      // Get compare
1844      Node *cmp = bol->in(1);
1845
1846      // Look for trip_counter + offset vs limit
1847      Node *rc_exp = cmp->in(1);
1848      Node *limit  = cmp->in(2);
1849      jint scale_con= 1;        // Assume trip counter not scaled
1850
1851      Node *limit_c = get_ctrl(limit);
1852      if( loop->is_member(get_loop(limit_c) ) ) {
1853        // Compare might have operands swapped; commute them
1854        b_test = b_test.commute();
1855        rc_exp = cmp->in(2);
1856        limit  = cmp->in(1);
1857        limit_c = get_ctrl(limit);
1858        if( loop->is_member(get_loop(limit_c) ) )
1859          continue;             // Both inputs are loop varying; cannot RCE
1860      }
1861      // Here we know 'limit' is loop invariant
1862
1863      // 'limit' maybe pinned below the zero trip test (probably from a
1864      // previous round of rce), in which case, it can't be used in the
1865      // zero trip test expression which must occur before the zero test's if.
1866      if( limit_c == ctrl ) {
1867        continue;  // Don't rce this check but continue looking for other candidates.
1868      }
1869
1870      // Check for scaled induction variable plus an offset
1871      Node *offset = NULL;
1872
1873      if (!is_scaled_iv_plus_offset(rc_exp, trip_counter, &scale_con, &offset)) {
1874        continue;
1875      }
1876
1877      Node *offset_c = get_ctrl(offset);
1878      if( loop->is_member( get_loop(offset_c) ) )
1879        continue;               // Offset is not really loop invariant
1880      // Here we know 'offset' is loop invariant.
1881
1882      // As above for the 'limit', the 'offset' maybe pinned below the
1883      // zero trip test.
1884      if( offset_c == ctrl ) {
1885        continue; // Don't rce this check but continue looking for other candidates.
1886      }
1887#ifdef ASSERT
1888      if (TraceRangeLimitCheck) {
1889        tty->print_cr("RC bool node%s", flip ? " flipped:" : ":");
1890        bol->dump(2);
1891      }
1892#endif
1893      // At this point we have the expression as:
1894      //   scale_con * trip_counter + offset :: limit
1895      // where scale_con, offset and limit are loop invariant.  Trip_counter
1896      // monotonically increases by stride_con, a constant.  Both (or either)
1897      // stride_con and scale_con can be negative which will flip about the
1898      // sense of the test.
1899
1900      // Adjust pre and main loop limits to guard the correct iteration set
1901      if( cmp->Opcode() == Op_CmpU ) {// Unsigned compare is really 2 tests
1902        if( b_test._test == BoolTest::lt ) { // Range checks always use lt
1903          // The underflow and overflow limits: 0 <= scale*I+offset < limit
1904          add_constraint( stride_con, scale_con, offset, zero, limit, pre_ctrl, &pre_limit, &main_limit );
1905          if (!conditional_rc) {
1906            // (0-offset)/scale could be outside of loop iterations range.
1907            conditional_rc = !loop->dominates_backedge(iff) || RangeLimitCheck;
1908          }
1909        } else {
1910#ifndef PRODUCT
1911          if( PrintOpto )
1912            tty->print_cr("missed RCE opportunity");
1913#endif
1914          continue;             // In release mode, ignore it
1915        }
1916      } else {                  // Otherwise work on normal compares
1917        switch( b_test._test ) {
1918        case BoolTest::gt:
1919          // Fall into GE case
1920        case BoolTest::ge:
1921          // Convert (I*scale+offset) >= Limit to (I*(-scale)+(-offset)) <= -Limit
1922          scale_con = -scale_con;
1923          offset = new (C) SubINode( zero, offset );
1924          register_new_node( offset, pre_ctrl );
1925          limit  = new (C) SubINode( zero, limit  );
1926          register_new_node( limit, pre_ctrl );
1927          // Fall into LE case
1928        case BoolTest::le:
1929          if (b_test._test != BoolTest::gt) {
1930            // Convert X <= Y to X < Y+1
1931            limit = new (C) AddINode( limit, one );
1932            register_new_node( limit, pre_ctrl );
1933          }
1934          // Fall into LT case
1935        case BoolTest::lt:
1936          // The underflow and overflow limits: MIN_INT <= scale*I+offset < limit
1937          // Note: (MIN_INT+1 == -MAX_INT) is used instead of MIN_INT here
1938          // to avoid problem with scale == -1: MIN_INT/(-1) == MIN_INT.
1939          add_constraint( stride_con, scale_con, offset, mini, limit, pre_ctrl, &pre_limit, &main_limit );
1940          if (!conditional_rc) {
1941            // ((MIN_INT+1)-offset)/scale could be outside of loop iterations range.
1942            // Note: negative offset is replaced with 0 but (MIN_INT+1)/scale could
1943            // still be outside of loop range.
1944            conditional_rc = !loop->dominates_backedge(iff) || RangeLimitCheck;
1945          }
1946          break;
1947        default:
1948#ifndef PRODUCT
1949          if( PrintOpto )
1950            tty->print_cr("missed RCE opportunity");
1951#endif
1952          continue;             // Unhandled case
1953        }
1954      }
1955
1956      // Kill the eliminated test
1957      C->set_major_progress();
1958      Node *kill_con = _igvn.intcon( 1-flip );
1959      set_ctrl(kill_con, C->root());
1960      _igvn.replace_input_of(iff, 1, kill_con);
1961      // Find surviving projection
1962      assert(iff->is_If(), "");
1963      ProjNode* dp = ((IfNode*)iff)->proj_out(1-flip);
1964      // Find loads off the surviving projection; remove their control edge
1965      for (DUIterator_Fast imax, i = dp->fast_outs(imax); i < imax; i++) {
1966        Node* cd = dp->fast_out(i); // Control-dependent node
1967        if (cd->is_Load() && cd->depends_only_on_test()) {   // Loads can now float around in the loop
1968          // Allow the load to float around in the loop, or before it
1969          // but NOT before the pre-loop.
1970          _igvn.replace_input_of(cd, 0, ctrl); // ctrl, not NULL
1971          --i;
1972          --imax;
1973        }
1974      }
1975
1976    } // End of is IF
1977
1978  }
1979
1980  // Update loop limits
1981  if (conditional_rc) {
1982    pre_limit = (stride_con > 0) ? (Node*)new (C) MinINode(pre_limit, orig_limit)
1983                                 : (Node*)new (C) MaxINode(pre_limit, orig_limit);
1984    register_new_node(pre_limit, pre_ctrl);
1985  }
1986  _igvn.hash_delete(pre_opaq);
1987  pre_opaq->set_req(1, pre_limit);
1988
1989  // Note:: we are making the main loop limit no longer precise;
1990  // need to round up based on stride.
1991  cl->set_nonexact_trip_count();
1992  if (!LoopLimitCheck && stride_con != 1 && stride_con != -1) { // Cutout for common case
1993    // "Standard" round-up logic:  ([main_limit-init+(y-1)]/y)*y+init
1994    // Hopefully, compiler will optimize for powers of 2.
1995    Node *ctrl = get_ctrl(main_limit);
1996    Node *stride = cl->stride();
1997    Node *init = cl->init_trip();
1998    Node *span = new (C) SubINode(main_limit,init);
1999    register_new_node(span,ctrl);
2000    Node *rndup = _igvn.intcon(stride_con + ((stride_con>0)?-1:1));
2001    Node *add = new (C) AddINode(span,rndup);
2002    register_new_node(add,ctrl);
2003    Node *div = new (C) DivINode(0,add,stride);
2004    register_new_node(div,ctrl);
2005    Node *mul = new (C) MulINode(div,stride);
2006    register_new_node(mul,ctrl);
2007    Node *newlim = new (C) AddINode(mul,init);
2008    register_new_node(newlim,ctrl);
2009    main_limit = newlim;
2010  }
2011
2012  Node *main_cle = cl->loopexit();
2013  Node *main_bol = main_cle->in(1);
2014  // Hacking loop bounds; need private copies of exit test
2015  if( main_bol->outcnt() > 1 ) {// BoolNode shared?
2016    _igvn.hash_delete(main_cle);
2017    main_bol = main_bol->clone();// Clone a private BoolNode
2018    register_new_node( main_bol, main_cle->in(0) );
2019    main_cle->set_req(1,main_bol);
2020  }
2021  Node *main_cmp = main_bol->in(1);
2022  if( main_cmp->outcnt() > 1 ) { // CmpNode shared?
2023    _igvn.hash_delete(main_bol);
2024    main_cmp = main_cmp->clone();// Clone a private CmpNode
2025    register_new_node( main_cmp, main_cle->in(0) );
2026    main_bol->set_req(1,main_cmp);
2027  }
2028  // Hack the now-private loop bounds
2029  _igvn.replace_input_of(main_cmp, 2, main_limit);
2030  // The OpaqueNode is unshared by design
2031  assert( opqzm->outcnt() == 1, "cannot hack shared node" );
2032  _igvn.replace_input_of(opqzm, 1, main_limit);
2033}
2034
2035//------------------------------DCE_loop_body----------------------------------
2036// Remove simplistic dead code from loop body
2037void IdealLoopTree::DCE_loop_body() {
2038  for( uint i = 0; i < _body.size(); i++ )
2039    if( _body.at(i)->outcnt() == 0 )
2040      _body.map( i--, _body.pop() );
2041}
2042
2043
2044//------------------------------adjust_loop_exit_prob--------------------------
2045// Look for loop-exit tests with the 50/50 (or worse) guesses from the parsing stage.
2046// Replace with a 1-in-10 exit guess.
2047void IdealLoopTree::adjust_loop_exit_prob( PhaseIdealLoop *phase ) {
2048  Node *test = tail();
2049  while( test != _head ) {
2050    uint top = test->Opcode();
2051    if( top == Op_IfTrue || top == Op_IfFalse ) {
2052      int test_con = ((ProjNode*)test)->_con;
2053      assert(top == (uint)(test_con? Op_IfTrue: Op_IfFalse), "sanity");
2054      IfNode *iff = test->in(0)->as_If();
2055      if( iff->outcnt() == 2 ) {        // Ignore dead tests
2056        Node *bol = iff->in(1);
2057        if( bol && bol->req() > 1 && bol->in(1) &&
2058            ((bol->in(1)->Opcode() == Op_StorePConditional ) ||
2059             (bol->in(1)->Opcode() == Op_StoreIConditional ) ||
2060             (bol->in(1)->Opcode() == Op_StoreLConditional ) ||
2061             (bol->in(1)->Opcode() == Op_CompareAndSwapI ) ||
2062             (bol->in(1)->Opcode() == Op_CompareAndSwapL ) ||
2063             (bol->in(1)->Opcode() == Op_CompareAndSwapP ) ||
2064             (bol->in(1)->Opcode() == Op_CompareAndSwapN )))
2065          return;               // Allocation loops RARELY take backedge
2066        // Find the OTHER exit path from the IF
2067        Node* ex = iff->proj_out(1-test_con);
2068        float p = iff->_prob;
2069        if( !phase->is_member( this, ex ) && iff->_fcnt == COUNT_UNKNOWN ) {
2070          if( top == Op_IfTrue ) {
2071            if( p < (PROB_FAIR + PROB_UNLIKELY_MAG(3))) {
2072              iff->_prob = PROB_STATIC_FREQUENT;
2073            }
2074          } else {
2075            if( p > (PROB_FAIR - PROB_UNLIKELY_MAG(3))) {
2076              iff->_prob = PROB_STATIC_INFREQUENT;
2077            }
2078          }
2079        }
2080      }
2081    }
2082    test = phase->idom(test);
2083  }
2084}
2085
2086
2087//------------------------------policy_do_remove_empty_loop--------------------
2088// Micro-benchmark spamming.  Policy is to always remove empty loops.
2089// The 'DO' part is to replace the trip counter with the value it will
2090// have on the last iteration.  This will break the loop.
2091bool IdealLoopTree::policy_do_remove_empty_loop( PhaseIdealLoop *phase ) {
2092  // Minimum size must be empty loop
2093  if (_body.size() > EMPTY_LOOP_SIZE)
2094    return false;
2095
2096  if (!_head->is_CountedLoop())
2097    return false;     // Dead loop
2098  CountedLoopNode *cl = _head->as_CountedLoop();
2099  if (!cl->is_valid_counted_loop())
2100    return false; // Malformed loop
2101  if (!phase->is_member(this, phase->get_ctrl(cl->loopexit()->in(CountedLoopEndNode::TestValue))))
2102    return false;             // Infinite loop
2103
2104#ifdef ASSERT
2105  // Ensure only one phi which is the iv.
2106  Node* iv = NULL;
2107  for (DUIterator_Fast imax, i = cl->fast_outs(imax); i < imax; i++) {
2108    Node* n = cl->fast_out(i);
2109    if (n->Opcode() == Op_Phi) {
2110      assert(iv == NULL, "Too many phis" );
2111      iv = n;
2112    }
2113  }
2114  assert(iv == cl->phi(), "Wrong phi" );
2115#endif
2116
2117  // main and post loops have explicitly created zero trip guard
2118  bool needs_guard = !cl->is_main_loop() && !cl->is_post_loop();
2119  if (needs_guard) {
2120    // Skip guard if values not overlap.
2121    const TypeInt* init_t = phase->_igvn.type(cl->init_trip())->is_int();
2122    const TypeInt* limit_t = phase->_igvn.type(cl->limit())->is_int();
2123    int  stride_con = cl->stride_con();
2124    if (stride_con > 0) {
2125      needs_guard = (init_t->_hi >= limit_t->_lo);
2126    } else {
2127      needs_guard = (init_t->_lo <= limit_t->_hi);
2128    }
2129  }
2130  if (needs_guard) {
2131    // Check for an obvious zero trip guard.
2132    Node* inctrl = PhaseIdealLoop::skip_loop_predicates(cl->in(LoopNode::EntryControl));
2133    if (inctrl->Opcode() == Op_IfTrue) {
2134      // The test should look like just the backedge of a CountedLoop
2135      Node* iff = inctrl->in(0);
2136      if (iff->is_If()) {
2137        Node* bol = iff->in(1);
2138        if (bol->is_Bool() && bol->as_Bool()->_test._test == cl->loopexit()->test_trip()) {
2139          Node* cmp = bol->in(1);
2140          if (cmp->is_Cmp() && cmp->in(1) == cl->init_trip() && cmp->in(2) == cl->limit()) {
2141            needs_guard = false;
2142          }
2143        }
2144      }
2145    }
2146  }
2147
2148#ifndef PRODUCT
2149  if (PrintOpto) {
2150    tty->print("Removing empty loop with%s zero trip guard", needs_guard ? "out" : "");
2151    this->dump_head();
2152  } else if (TraceLoopOpts) {
2153    tty->print("Empty with%s zero trip guard   ", needs_guard ? "out" : "");
2154    this->dump_head();
2155  }
2156#endif
2157
2158  if (needs_guard) {
2159    // Peel the loop to ensure there's a zero trip guard
2160    Node_List old_new;
2161    phase->do_peeling(this, old_new);
2162  }
2163
2164  // Replace the phi at loop head with the final value of the last
2165  // iteration.  Then the CountedLoopEnd will collapse (backedge never
2166  // taken) and all loop-invariant uses of the exit values will be correct.
2167  Node *phi = cl->phi();
2168  Node *exact_limit = phase->exact_limit(this);
2169  if (exact_limit != cl->limit()) {
2170    // We also need to replace the original limit to collapse loop exit.
2171    Node* cmp = cl->loopexit()->cmp_node();
2172    assert(cl->limit() == cmp->in(2), "sanity");
2173    phase->_igvn._worklist.push(cmp->in(2)); // put limit on worklist
2174    phase->_igvn.replace_input_of(cmp, 2, exact_limit); // put cmp on worklist
2175  }
2176  // Note: the final value after increment should not overflow since
2177  // counted loop has limit check predicate.
2178  Node *final = new (phase->C) SubINode( exact_limit, cl->stride() );
2179  phase->register_new_node(final,cl->in(LoopNode::EntryControl));
2180  phase->_igvn.replace_node(phi,final);
2181  phase->C->set_major_progress();
2182  return true;
2183}
2184
2185//------------------------------policy_do_one_iteration_loop-------------------
2186// Convert one iteration loop into normal code.
2187bool IdealLoopTree::policy_do_one_iteration_loop( PhaseIdealLoop *phase ) {
2188  if (!_head->as_Loop()->is_valid_counted_loop())
2189    return false; // Only for counted loop
2190
2191  CountedLoopNode *cl = _head->as_CountedLoop();
2192  if (!cl->has_exact_trip_count() || cl->trip_count() != 1) {
2193    return false;
2194  }
2195
2196#ifndef PRODUCT
2197  if(TraceLoopOpts) {
2198    tty->print("OneIteration ");
2199    this->dump_head();
2200  }
2201#endif
2202
2203  Node *init_n = cl->init_trip();
2204#ifdef ASSERT
2205  // Loop boundaries should be constant since trip count is exact.
2206  assert(init_n->get_int() + cl->stride_con() >= cl->limit()->get_int(), "should be one iteration");
2207#endif
2208  // Replace the phi at loop head with the value of the init_trip.
2209  // Then the CountedLoopEnd will collapse (backedge will not be taken)
2210  // and all loop-invariant uses of the exit values will be correct.
2211  phase->_igvn.replace_node(cl->phi(), cl->init_trip());
2212  phase->C->set_major_progress();
2213  return true;
2214}
2215
2216//=============================================================================
2217//------------------------------iteration_split_impl---------------------------
2218bool IdealLoopTree::iteration_split_impl( PhaseIdealLoop *phase, Node_List &old_new ) {
2219  // Compute exact loop trip count if possible.
2220  compute_exact_trip_count(phase);
2221
2222  // Convert one iteration loop into normal code.
2223  if (policy_do_one_iteration_loop(phase))
2224    return true;
2225
2226  // Check and remove empty loops (spam micro-benchmarks)
2227  if (policy_do_remove_empty_loop(phase))
2228    return true;  // Here we removed an empty loop
2229
2230  bool should_peel = policy_peeling(phase); // Should we peel?
2231
2232  bool should_unswitch = policy_unswitching(phase);
2233
2234  // Non-counted loops may be peeled; exactly 1 iteration is peeled.
2235  // This removes loop-invariant tests (usually null checks).
2236  if (!_head->is_CountedLoop()) { // Non-counted loop
2237    if (PartialPeelLoop && phase->partial_peel(this, old_new)) {
2238      // Partial peel succeeded so terminate this round of loop opts
2239      return false;
2240    }
2241    if (should_peel) {            // Should we peel?
2242#ifndef PRODUCT
2243      if (PrintOpto) tty->print_cr("should_peel");
2244#endif
2245      phase->do_peeling(this,old_new);
2246    } else if (should_unswitch) {
2247      phase->do_unswitching(this, old_new);
2248    }
2249    return true;
2250  }
2251  CountedLoopNode *cl = _head->as_CountedLoop();
2252
2253  if (!cl->is_valid_counted_loop()) return true; // Ignore various kinds of broken loops
2254
2255  // Do nothing special to pre- and post- loops
2256  if (cl->is_pre_loop() || cl->is_post_loop()) return true;
2257
2258  // Compute loop trip count from profile data
2259  compute_profile_trip_cnt(phase);
2260
2261  // Before attempting fancy unrolling, RCE or alignment, see if we want
2262  // to completely unroll this loop or do loop unswitching.
2263  if (cl->is_normal_loop()) {
2264    if (should_unswitch) {
2265      phase->do_unswitching(this, old_new);
2266      return true;
2267    }
2268    bool should_maximally_unroll =  policy_maximally_unroll(phase);
2269    if (should_maximally_unroll) {
2270      // Here we did some unrolling and peeling.  Eventually we will
2271      // completely unroll this loop and it will no longer be a loop.
2272      phase->do_maximally_unroll(this,old_new);
2273      return true;
2274    }
2275  }
2276
2277  // Skip next optimizations if running low on nodes. Note that
2278  // policy_unswitching and policy_maximally_unroll have this check.
2279  uint nodes_left = MaxNodeLimit - (uint) phase->C->live_nodes();
2280  if ((2 * _body.size()) > nodes_left) {
2281    return true;
2282  }
2283
2284  // Counted loops may be peeled, may need some iterations run up
2285  // front for RCE, and may want to align loop refs to a cache
2286  // line.  Thus we clone a full loop up front whose trip count is
2287  // at least 1 (if peeling), but may be several more.
2288
2289  // The main loop will start cache-line aligned with at least 1
2290  // iteration of the unrolled body (zero-trip test required) and
2291  // will have some range checks removed.
2292
2293  // A post-loop will finish any odd iterations (leftover after
2294  // unrolling), plus any needed for RCE purposes.
2295
2296  bool should_unroll = policy_unroll(phase);
2297
2298  bool should_rce = policy_range_check(phase);
2299
2300  bool should_align = policy_align(phase);
2301
2302  // If not RCE'ing (iteration splitting) or Aligning, then we do not
2303  // need a pre-loop.  We may still need to peel an initial iteration but
2304  // we will not be needing an unknown number of pre-iterations.
2305  //
2306  // Basically, if may_rce_align reports FALSE first time through,
2307  // we will not be able to later do RCE or Aligning on this loop.
2308  bool may_rce_align = !policy_peel_only(phase) || should_rce || should_align;
2309
2310  // If we have any of these conditions (RCE, alignment, unrolling) met, then
2311  // we switch to the pre-/main-/post-loop model.  This model also covers
2312  // peeling.
2313  if (should_rce || should_align || should_unroll) {
2314    if (cl->is_normal_loop())  // Convert to 'pre/main/post' loops
2315      phase->insert_pre_post_loops(this,old_new, !may_rce_align);
2316
2317    // Adjust the pre- and main-loop limits to let the pre and post loops run
2318    // with full checks, but the main-loop with no checks.  Remove said
2319    // checks from the main body.
2320    if (should_rce)
2321      phase->do_range_check(this,old_new);
2322
2323    // Double loop body for unrolling.  Adjust the minimum-trip test (will do
2324    // twice as many iterations as before) and the main body limit (only do
2325    // an even number of trips).  If we are peeling, we might enable some RCE
2326    // and we'd rather unroll the post-RCE'd loop SO... do not unroll if
2327    // peeling.
2328    if (should_unroll && !should_peel)
2329      phase->do_unroll(this,old_new, true);
2330
2331    // Adjust the pre-loop limits to align the main body
2332    // iterations.
2333    if (should_align)
2334      Unimplemented();
2335
2336  } else {                      // Else we have an unchanged counted loop
2337    if (should_peel)           // Might want to peel but do nothing else
2338      phase->do_peeling(this,old_new);
2339  }
2340  return true;
2341}
2342
2343
2344//=============================================================================
2345//------------------------------iteration_split--------------------------------
2346bool IdealLoopTree::iteration_split( PhaseIdealLoop *phase, Node_List &old_new ) {
2347  // Recursively iteration split nested loops
2348  if (_child && !_child->iteration_split(phase, old_new))
2349    return false;
2350
2351  // Clean out prior deadwood
2352  DCE_loop_body();
2353
2354
2355  // Look for loop-exit tests with my 50/50 guesses from the Parsing stage.
2356  // Replace with a 1-in-10 exit guess.
2357  if (_parent /*not the root loop*/ &&
2358      !_irreducible &&
2359      // Also ignore the occasional dead backedge
2360      !tail()->is_top()) {
2361    adjust_loop_exit_prob(phase);
2362  }
2363
2364  // Gate unrolling, RCE and peeling efforts.
2365  if (!_child &&                // If not an inner loop, do not split
2366      !_irreducible &&
2367      _allow_optimizations &&
2368      !tail()->is_top()) {     // Also ignore the occasional dead backedge
2369    if (!_has_call) {
2370        if (!iteration_split_impl(phase, old_new)) {
2371          return false;
2372        }
2373    } else if (policy_unswitching(phase)) {
2374      phase->do_unswitching(this, old_new);
2375    }
2376  }
2377
2378  // Minor offset re-organization to remove loop-fallout uses of
2379  // trip counter when there was no major reshaping.
2380  phase->reorg_offsets(this);
2381
2382  if (_next && !_next->iteration_split(phase, old_new))
2383    return false;
2384  return true;
2385}
2386
2387
2388//=============================================================================
2389// Process all the loops in the loop tree and replace any fill
2390// patterns with an intrisc version.
2391bool PhaseIdealLoop::do_intrinsify_fill() {
2392  bool changed = false;
2393  for (LoopTreeIterator iter(_ltree_root); !iter.done(); iter.next()) {
2394    IdealLoopTree* lpt = iter.current();
2395    changed |= intrinsify_fill(lpt);
2396  }
2397  return changed;
2398}
2399
2400
2401// Examine an inner loop looking for a a single store of an invariant
2402// value in a unit stride loop,
2403bool PhaseIdealLoop::match_fill_loop(IdealLoopTree* lpt, Node*& store, Node*& store_value,
2404                                     Node*& shift, Node*& con) {
2405  const char* msg = NULL;
2406  Node* msg_node = NULL;
2407
2408  store_value = NULL;
2409  con = NULL;
2410  shift = NULL;
2411
2412  // Process the loop looking for stores.  If there are multiple
2413  // stores or extra control flow give at this point.
2414  CountedLoopNode* head = lpt->_head->as_CountedLoop();
2415  for (uint i = 0; msg == NULL && i < lpt->_body.size(); i++) {
2416    Node* n = lpt->_body.at(i);
2417    if (n->outcnt() == 0) continue; // Ignore dead
2418    if (n->is_Store()) {
2419      if (store != NULL) {
2420        msg = "multiple stores";
2421        break;
2422      }
2423      int opc = n->Opcode();
2424      if (opc == Op_StoreP || opc == Op_StoreN || opc == Op_StoreNKlass || opc == Op_StoreCM) {
2425        msg = "oop fills not handled";
2426        break;
2427      }
2428      Node* value = n->in(MemNode::ValueIn);
2429      if (!lpt->is_invariant(value)) {
2430        msg  = "variant store value";
2431      } else if (!_igvn.type(n->in(MemNode::Address))->isa_aryptr()) {
2432        msg = "not array address";
2433      }
2434      store = n;
2435      store_value = value;
2436    } else if (n->is_If() && n != head->loopexit()) {
2437      msg = "extra control flow";
2438      msg_node = n;
2439    }
2440  }
2441
2442  if (store == NULL) {
2443    // No store in loop
2444    return false;
2445  }
2446
2447  if (msg == NULL && head->stride_con() != 1) {
2448    // could handle negative strides too
2449    if (head->stride_con() < 0) {
2450      msg = "negative stride";
2451    } else {
2452      msg = "non-unit stride";
2453    }
2454  }
2455
2456  if (msg == NULL && !store->in(MemNode::Address)->is_AddP()) {
2457    msg = "can't handle store address";
2458    msg_node = store->in(MemNode::Address);
2459  }
2460
2461  if (msg == NULL &&
2462      (!store->in(MemNode::Memory)->is_Phi() ||
2463       store->in(MemNode::Memory)->in(LoopNode::LoopBackControl) != store)) {
2464    msg = "store memory isn't proper phi";
2465    msg_node = store->in(MemNode::Memory);
2466  }
2467
2468  // Make sure there is an appropriate fill routine
2469  BasicType t = store->as_Mem()->memory_type();
2470  const char* fill_name;
2471  if (msg == NULL &&
2472      StubRoutines::select_fill_function(t, false, fill_name) == NULL) {
2473    msg = "unsupported store";
2474    msg_node = store;
2475  }
2476
2477  if (msg != NULL) {
2478#ifndef PRODUCT
2479    if (TraceOptimizeFill) {
2480      tty->print_cr("not fill intrinsic candidate: %s", msg);
2481      if (msg_node != NULL) msg_node->dump();
2482    }
2483#endif
2484    return false;
2485  }
2486
2487  // Make sure the address expression can be handled.  It should be
2488  // head->phi * elsize + con.  head->phi might have a ConvI2L.
2489  Node* elements[4];
2490  Node* conv = NULL;
2491  bool found_index = false;
2492  int count = store->in(MemNode::Address)->as_AddP()->unpack_offsets(elements, ARRAY_SIZE(elements));
2493  for (int e = 0; e < count; e++) {
2494    Node* n = elements[e];
2495    if (n->is_Con() && con == NULL) {
2496      con = n;
2497    } else if (n->Opcode() == Op_LShiftX && shift == NULL) {
2498      Node* value = n->in(1);
2499#ifdef _LP64
2500      if (value->Opcode() == Op_ConvI2L) {
2501        conv = value;
2502        value = value->in(1);
2503      }
2504#endif
2505      if (value != head->phi()) {
2506        msg = "unhandled shift in address";
2507      } else {
2508        if (type2aelembytes(store->as_Mem()->memory_type(), true) != (1 << n->in(2)->get_int())) {
2509          msg = "scale doesn't match";
2510        } else {
2511          found_index = true;
2512          shift = n;
2513        }
2514      }
2515    } else if (n->Opcode() == Op_ConvI2L && conv == NULL) {
2516      if (n->in(1) == head->phi()) {
2517        found_index = true;
2518        conv = n;
2519      } else {
2520        msg = "unhandled input to ConvI2L";
2521      }
2522    } else if (n == head->phi()) {
2523      // no shift, check below for allowed cases
2524      found_index = true;
2525    } else {
2526      msg = "unhandled node in address";
2527      msg_node = n;
2528    }
2529  }
2530
2531  if (count == -1) {
2532    msg = "malformed address expression";
2533    msg_node = store;
2534  }
2535
2536  if (!found_index) {
2537    msg = "missing use of index";
2538  }
2539
2540  // byte sized items won't have a shift
2541  if (msg == NULL && shift == NULL && t != T_BYTE && t != T_BOOLEAN) {
2542    msg = "can't find shift";
2543    msg_node = store;
2544  }
2545
2546  if (msg != NULL) {
2547#ifndef PRODUCT
2548    if (TraceOptimizeFill) {
2549      tty->print_cr("not fill intrinsic: %s", msg);
2550      if (msg_node != NULL) msg_node->dump();
2551    }
2552#endif
2553    return false;
2554  }
2555
2556  // No make sure all the other nodes in the loop can be handled
2557  VectorSet ok(Thread::current()->resource_area());
2558
2559  // store related values are ok
2560  ok.set(store->_idx);
2561  ok.set(store->in(MemNode::Memory)->_idx);
2562
2563  CountedLoopEndNode* loop_exit = head->loopexit();
2564  guarantee(loop_exit != NULL, "no loop exit node");
2565
2566  // Loop structure is ok
2567  ok.set(head->_idx);
2568  ok.set(loop_exit->_idx);
2569  ok.set(head->phi()->_idx);
2570  ok.set(head->incr()->_idx);
2571  ok.set(loop_exit->cmp_node()->_idx);
2572  ok.set(loop_exit->in(1)->_idx);
2573
2574  // Address elements are ok
2575  if (con)   ok.set(con->_idx);
2576  if (shift) ok.set(shift->_idx);
2577  if (conv)  ok.set(conv->_idx);
2578
2579  for (uint i = 0; msg == NULL && i < lpt->_body.size(); i++) {
2580    Node* n = lpt->_body.at(i);
2581    if (n->outcnt() == 0) continue; // Ignore dead
2582    if (ok.test(n->_idx)) continue;
2583    // Backedge projection is ok
2584    if (n->is_IfTrue() && n->in(0) == loop_exit) continue;
2585    if (!n->is_AddP()) {
2586      msg = "unhandled node";
2587      msg_node = n;
2588      break;
2589    }
2590  }
2591
2592  // Make sure no unexpected values are used outside the loop
2593  for (uint i = 0; msg == NULL && i < lpt->_body.size(); i++) {
2594    Node* n = lpt->_body.at(i);
2595    // These values can be replaced with other nodes if they are used
2596    // outside the loop.
2597    if (n == store || n == loop_exit || n == head->incr() || n == store->in(MemNode::Memory)) continue;
2598    for (SimpleDUIterator iter(n); iter.has_next(); iter.next()) {
2599      Node* use = iter.get();
2600      if (!lpt->_body.contains(use)) {
2601        msg = "node is used outside loop";
2602        // lpt->_body.dump();
2603        msg_node = n;
2604        break;
2605      }
2606    }
2607  }
2608
2609#ifdef ASSERT
2610  if (TraceOptimizeFill) {
2611    if (msg != NULL) {
2612      tty->print_cr("no fill intrinsic: %s", msg);
2613      if (msg_node != NULL) msg_node->dump();
2614    } else {
2615      tty->print_cr("fill intrinsic for:");
2616    }
2617    store->dump();
2618    if (Verbose) {
2619      lpt->_body.dump();
2620    }
2621  }
2622#endif
2623
2624  return msg == NULL;
2625}
2626
2627
2628
2629bool PhaseIdealLoop::intrinsify_fill(IdealLoopTree* lpt) {
2630  // Only for counted inner loops
2631  if (!lpt->is_counted() || !lpt->is_inner()) {
2632    return false;
2633  }
2634
2635  // Must have constant stride
2636  CountedLoopNode* head = lpt->_head->as_CountedLoop();
2637  if (!head->is_valid_counted_loop() || !head->is_normal_loop()) {
2638    return false;
2639  }
2640
2641  // Check that the body only contains a store of a loop invariant
2642  // value that is indexed by the loop phi.
2643  Node* store = NULL;
2644  Node* store_value = NULL;
2645  Node* shift = NULL;
2646  Node* offset = NULL;
2647  if (!match_fill_loop(lpt, store, store_value, shift, offset)) {
2648    return false;
2649  }
2650
2651#ifndef PRODUCT
2652  if (TraceLoopOpts) {
2653    tty->print("ArrayFill    ");
2654    lpt->dump_head();
2655  }
2656#endif
2657
2658  // Now replace the whole loop body by a call to a fill routine that
2659  // covers the same region as the loop.
2660  Node* base = store->in(MemNode::Address)->as_AddP()->in(AddPNode::Base);
2661
2662  // Build an expression for the beginning of the copy region
2663  Node* index = head->init_trip();
2664#ifdef _LP64
2665  index = new (C) ConvI2LNode(index);
2666  _igvn.register_new_node_with_optimizer(index);
2667#endif
2668  if (shift != NULL) {
2669    // byte arrays don't require a shift but others do.
2670    index = new (C) LShiftXNode(index, shift->in(2));
2671    _igvn.register_new_node_with_optimizer(index);
2672  }
2673  index = new (C) AddPNode(base, base, index);
2674  _igvn.register_new_node_with_optimizer(index);
2675  Node* from = new (C) AddPNode(base, index, offset);
2676  _igvn.register_new_node_with_optimizer(from);
2677  // Compute the number of elements to copy
2678  Node* len = new (C) SubINode(head->limit(), head->init_trip());
2679  _igvn.register_new_node_with_optimizer(len);
2680
2681  BasicType t = store->as_Mem()->memory_type();
2682  bool aligned = false;
2683  if (offset != NULL && head->init_trip()->is_Con()) {
2684    int element_size = type2aelembytes(t);
2685    aligned = (offset->find_intptr_t_type()->get_con() + head->init_trip()->get_int() * element_size) % HeapWordSize == 0;
2686  }
2687
2688  // Build a call to the fill routine
2689  const char* fill_name;
2690  address fill = StubRoutines::select_fill_function(t, aligned, fill_name);
2691  assert(fill != NULL, "what?");
2692
2693  // Convert float/double to int/long for fill routines
2694  if (t == T_FLOAT) {
2695    store_value = new (C) MoveF2INode(store_value);
2696    _igvn.register_new_node_with_optimizer(store_value);
2697  } else if (t == T_DOUBLE) {
2698    store_value = new (C) MoveD2LNode(store_value);
2699    _igvn.register_new_node_with_optimizer(store_value);
2700  }
2701
2702  Node* mem_phi = store->in(MemNode::Memory);
2703  Node* result_ctrl;
2704  Node* result_mem;
2705  const TypeFunc* call_type = OptoRuntime::array_fill_Type();
2706  CallLeafNode *call = new (C) CallLeafNoFPNode(call_type, fill,
2707                                                fill_name, TypeAryPtr::get_array_body_type(t));
2708  call->init_req(TypeFunc::Parms+0, from);
2709  call->init_req(TypeFunc::Parms+1, store_value);
2710#ifdef _LP64
2711  len = new (C) ConvI2LNode(len);
2712  _igvn.register_new_node_with_optimizer(len);
2713#endif
2714  call->init_req(TypeFunc::Parms+2, len);
2715#ifdef _LP64
2716  call->init_req(TypeFunc::Parms+3, C->top());
2717#endif
2718  call->init_req( TypeFunc::Control, head->init_control());
2719  call->init_req( TypeFunc::I_O    , C->top() )        ;   // does no i/o
2720  call->init_req( TypeFunc::Memory ,  mem_phi->in(LoopNode::EntryControl) );
2721  call->init_req( TypeFunc::ReturnAdr, C->start()->proj_out(TypeFunc::ReturnAdr) );
2722  call->init_req( TypeFunc::FramePtr, C->start()->proj_out(TypeFunc::FramePtr) );
2723  _igvn.register_new_node_with_optimizer(call);
2724  result_ctrl = new (C) ProjNode(call,TypeFunc::Control);
2725  _igvn.register_new_node_with_optimizer(result_ctrl);
2726  result_mem = new (C) ProjNode(call,TypeFunc::Memory);
2727  _igvn.register_new_node_with_optimizer(result_mem);
2728
2729/* Disable following optimization until proper fix (add missing checks).
2730
2731  // If this fill is tightly coupled to an allocation and overwrites
2732  // the whole body, allow it to take over the zeroing.
2733  AllocateNode* alloc = AllocateNode::Ideal_allocation(base, this);
2734  if (alloc != NULL && alloc->is_AllocateArray()) {
2735    Node* length = alloc->as_AllocateArray()->Ideal_length();
2736    if (head->limit() == length &&
2737        head->init_trip() == _igvn.intcon(0)) {
2738      if (TraceOptimizeFill) {
2739        tty->print_cr("Eliminated zeroing in allocation");
2740      }
2741      alloc->maybe_set_complete(&_igvn);
2742    } else {
2743#ifdef ASSERT
2744      if (TraceOptimizeFill) {
2745        tty->print_cr("filling array but bounds don't match");
2746        alloc->dump();
2747        head->init_trip()->dump();
2748        head->limit()->dump();
2749        length->dump();
2750      }
2751#endif
2752    }
2753  }
2754*/
2755
2756  // Redirect the old control and memory edges that are outside the loop.
2757  Node* exit = head->loopexit()->proj_out(0);
2758  // Sometimes the memory phi of the head is used as the outgoing
2759  // state of the loop.  It's safe in this case to replace it with the
2760  // result_mem.
2761  _igvn.replace_node(store->in(MemNode::Memory), result_mem);
2762  _igvn.replace_node(exit, result_ctrl);
2763  _igvn.replace_node(store, result_mem);
2764  // Any uses the increment outside of the loop become the loop limit.
2765  _igvn.replace_node(head->incr(), head->limit());
2766
2767  // Disconnect the head from the loop.
2768  for (uint i = 0; i < lpt->_body.size(); i++) {
2769    Node* n = lpt->_body.at(i);
2770    _igvn.replace_node(n, C->top());
2771  }
2772
2773  return true;
2774}
2775