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