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