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