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