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