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