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