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     Node* cle_out = _head->as_CountedLoop()->loopexit()->proj_out(false);
  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->is_member(this, phase->get_ctrl(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           !loop->is_member(get_loop(get_ctrl(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::UnconditionalDependency);
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 *pre_header= main_head->in(LoopNode::EntryControl);
1415   Node *init      = main_head->init_trip();
1416   Node *incr      = main_end ->incr();
1417   Node *limit     = main_end ->limit();
1418   Node *stride    = main_end ->stride();
1419   Node *cmp       = main_end ->cmp_node();
1420   BoolTest::mask b_test = main_end->test_trip();
1421 
1422   // Need only 1 user of 'bol' because I will be hacking the loop bounds.
1423   Node *bol = main_end->in(CountedLoopEndNode::TestValue);
1424   if (bol->outcnt() != 1) {
1425     bol = bol->clone();
1426     register_new_node(bol,main_end->in(CountedLoopEndNode::TestControl));
1427     _igvn.replace_input_of(main_end, CountedLoopEndNode::TestValue, bol);
1428   }
1429   // Need only 1 user of 'cmp' because I will be hacking the loop bounds.
1430   if (cmp->outcnt() != 1) {
1431     cmp = cmp->clone();
1432     register_new_node(cmp,main_end->in(CountedLoopEndNode::TestControl));
1433     _igvn.replace_input_of(bol, 1, cmp);
1434   }
1435 
1436   // Add the post loop
1437   CountedLoopNode *post_head = nullptr;
1438   Node* post_incr = incr;
1439   Node* main_exit = insert_post_loop(loop, old_new, main_head, main_end, post_incr, limit, post_head);
1440   C->print_method(PHASE_AFTER_POST_LOOP, 4, post_head);
1441 
1442   //------------------------------
1443   // Step B: Create Pre-Loop.
1444 
1445   // Step B1: Clone the loop body.  The clone becomes the pre-loop.  The main
1446   // loop pre-header illegally has 2 control users (old & new loops).
1447   LoopNode* outer_main_head = main_head;
1448   IdealLoopTree* outer_loop = loop;
1449   if (main_head->is_strip_mined()) {
1450     main_head->verify_strip_mined(1);
1451     outer_main_head = main_head->outer_loop();
1452     outer_loop = loop->_parent;
1453     assert(outer_loop->_head == outer_main_head, "broken loop tree");
1454   }
1455 
1456   const uint first_node_index_in_pre_loop_body = Compile::current()->unique();
1457   uint dd_main_head = dom_depth(outer_main_head);
1458   clone_loop(loop, old_new, dd_main_head, ControlAroundStripMined);
1459   CountedLoopNode*    pre_head = old_new[main_head->_idx]->as_CountedLoop();
1460   CountedLoopEndNode* pre_end  = old_new[main_end ->_idx]->as_CountedLoopEnd();
1461   pre_head->set_pre_loop(main_head);
1462   Node *pre_incr = old_new[incr->_idx];
1463 
1464   // Reduce the pre-loop trip count.
1465   pre_end->_prob = PROB_FAIR;
1466 
1467   // Find the pre-loop normal exit.
1468   Node* pre_exit = pre_end->proj_out(false);
1469   assert(pre_exit->Opcode() == Op_IfFalse, "");
1470   IfFalseNode *new_pre_exit = new IfFalseNode(pre_end);
1471   _igvn.register_new_node_with_optimizer(new_pre_exit);
1472   set_idom(new_pre_exit, pre_end, dd_main_head);
1473   set_loop(new_pre_exit, outer_loop->_parent);
1474 
1475   // Step B2: Build a zero-trip guard for the main-loop.  After leaving the
1476   // pre-loop, the main-loop may not execute at all.  Later in life this
1477   // zero-trip guard will become the minimum-trip guard when we unroll
1478   // the main-loop.
1479   Node *min_opaq = new OpaqueZeroTripGuardNode(C, limit, b_test);
1480   Node *min_cmp  = new CmpINode(pre_incr, min_opaq);
1481   Node *min_bol  = new BoolNode(min_cmp, b_test);
1482   register_new_node(min_opaq, new_pre_exit);
1483   register_new_node(min_cmp , new_pre_exit);
1484   register_new_node(min_bol , new_pre_exit);
1485 
1486   // Build the IfNode (assume the main-loop is executed always).
1487   IfNode *min_iff = new IfNode(new_pre_exit, min_bol, PROB_ALWAYS, COUNT_UNKNOWN);
1488   _igvn.register_new_node_with_optimizer(min_iff);
1489   set_idom(min_iff, new_pre_exit, dd_main_head);
1490   set_loop(min_iff, outer_loop->_parent);
1491 
1492   // Plug in the false-path, taken if we need to skip main-loop
1493   _igvn.hash_delete(pre_exit);
1494   pre_exit->set_req(0, min_iff);
1495   set_idom(pre_exit, min_iff, dd_main_head);
1496   set_idom(pre_exit->unique_ctrl_out(), min_iff, dd_main_head);
1497   // Make the true-path, must enter the main loop
1498   Node *min_taken = new IfTrueNode(min_iff);
1499   _igvn.register_new_node_with_optimizer(min_taken);
1500   set_idom(min_taken, min_iff, dd_main_head);
1501   set_loop(min_taken, outer_loop->_parent);
1502   // Plug in the true path
1503   _igvn.hash_delete(outer_main_head);
1504   outer_main_head->set_req(LoopNode::EntryControl, min_taken);
1505   set_idom(outer_main_head, min_taken, dd_main_head);
1506   assert(post_head->in(1)->is_IfProj(), "must be zero-trip guard If node projection of the post loop");
1507 
1508   VectorSet visited;
1509   Node_Stack clones(main_head->back_control()->outcnt());
1510   // Step B3: Make the fall-in values to the main-loop come from the
1511   // fall-out values of the pre-loop.
1512   const uint last_node_index_in_pre_loop_body = Compile::current()->unique() - 1;
1513   for (DUIterator i2 = main_head->outs(); main_head->has_out(i2); i2++) {
1514     Node* main_phi = main_head->out(i2);
1515     if (main_phi->is_Phi() && main_phi->in(0) == main_head && main_phi->outcnt() > 0) {
1516       Node* pre_phi = old_new[main_phi->_idx];
1517       Node* fallpre = clone_up_backedge_goo(pre_head->back_control(),
1518                                             main_head->skip_strip_mined()->in(LoopNode::EntryControl),
1519                                             pre_phi->in(LoopNode::LoopBackControl),
1520                                             visited, clones);
1521       _igvn.hash_delete(main_phi);
1522       main_phi->set_req(LoopNode::EntryControl, fallpre);
1523     }
1524   }
1525   DEBUG_ONLY(const uint last_node_index_from_backedge_goo = Compile::current()->unique() - 1);
1526 
1527   DEBUG_ONLY(ensure_zero_trip_guard_proj(outer_main_head->in(LoopNode::EntryControl), true);)
1528   initialize_assertion_predicates_for_main_loop(pre_head, main_head, first_node_index_in_pre_loop_body,
1529                                                 last_node_index_in_pre_loop_body,
1530                                                 DEBUG_ONLY(last_node_index_from_backedge_goo COMMA) old_new);
1531   // CastII for the main loop:
1532   cast_incr_before_loop(pre_incr, min_taken, main_head);
1533 
1534   // Step B4: Shorten the pre-loop to run only 1 iteration (for now).
1535   // RCE and alignment may change this later.
1536   Node *cmp_end = pre_end->cmp_node();
1537   assert(cmp_end->in(2) == limit, "");
1538   Node *pre_limit = new AddINode(init, stride);
1539 
1540   // Save the original loop limit in this Opaque1 node for
1541   // use by range check elimination.
1542   Node *pre_opaq  = new Opaque1Node(C, pre_limit, limit);
1543 
1544   register_new_node(pre_limit, pre_head->in(LoopNode::EntryControl));
1545   register_new_node(pre_opaq , pre_head->in(LoopNode::EntryControl));
1546 
1547   // Since no other users of pre-loop compare, I can hack limit directly
1548   assert(cmp_end->outcnt() == 1, "no other users");
1549   _igvn.hash_delete(cmp_end);
1550   cmp_end->set_req(2, peel_only ? pre_limit : pre_opaq);
1551 
1552   // Special case for not-equal loop bounds:
1553   // Change pre loop test, main loop test, and the
1554   // main loop guard test to use lt or gt depending on stride
1555   // direction:
1556   // positive stride use <
1557   // negative stride use >
1558   //
1559   // not-equal test is kept for post loop to handle case
1560   // when init > limit when stride > 0 (and reverse).
1561 
1562   if (pre_end->in(CountedLoopEndNode::TestValue)->as_Bool()->_test._test == BoolTest::ne) {
1563 
1564     BoolTest::mask new_test = (main_end->stride_con() > 0) ? BoolTest::lt : BoolTest::gt;
1565     // Modify pre loop end condition
1566     Node* pre_bol = pre_end->in(CountedLoopEndNode::TestValue)->as_Bool();
1567     BoolNode* new_bol0 = new BoolNode(pre_bol->in(1), new_test);
1568     register_new_node(new_bol0, pre_head->in(0));
1569     _igvn.replace_input_of(pre_end, CountedLoopEndNode::TestValue, new_bol0);
1570     // Modify main loop guard condition
1571     assert(min_iff->in(CountedLoopEndNode::TestValue) == min_bol, "guard okay");
1572     BoolNode* new_bol1 = new BoolNode(min_bol->in(1), new_test);
1573     register_new_node(new_bol1, new_pre_exit);
1574     _igvn.hash_delete(min_iff);
1575     min_iff->set_req(CountedLoopEndNode::TestValue, new_bol1);
1576     // Modify main loop end condition
1577     BoolNode* main_bol = main_end->in(CountedLoopEndNode::TestValue)->as_Bool();
1578     BoolNode* new_bol2 = new BoolNode(main_bol->in(1), new_test);
1579     register_new_node(new_bol2, main_end->in(CountedLoopEndNode::TestControl));
1580     _igvn.replace_input_of(main_end, CountedLoopEndNode::TestValue, new_bol2);
1581   }
1582 
1583   // Flag main loop
1584   main_head->set_main_loop();
1585   if (peel_only) {
1586     main_head->set_main_no_pre_loop();
1587   }
1588 
1589   // Subtract a trip count for the pre-loop.
1590   main_head->set_trip_count(main_head->trip_count() - 1);
1591 
1592   // It's difficult to be precise about the trip-counts
1593   // for the pre/post loops.  They are usually very short,
1594   // so guess that 4 trips is a reasonable value.
1595   post_head->set_profile_trip_cnt(4.0);
1596   pre_head->set_profile_trip_cnt(4.0);
1597 
1598   // Now force out all loop-invariant dominating tests.  The optimizer
1599   // finds some, but we _know_ they are all useless.
1600   peeled_dom_test_elim(loop,old_new);
1601   loop->record_for_igvn();
1602 
1603   C->print_method(PHASE_AFTER_PRE_MAIN_POST, 4, main_head);
1604 }
1605 
1606 //------------------------------insert_vector_post_loop------------------------
1607 // Insert a copy of the atomic unrolled vectorized main loop as a post loop,
1608 // unroll_policy has  already informed  us that more  unrolling is  about to
1609 // happen  to the  main  loop.  The  resultant  post loop  will  serve as  a
1610 // vectorized drain loop.
1611 void PhaseIdealLoop::insert_vector_post_loop(IdealLoopTree *loop, Node_List &old_new) {
1612   if (!loop->_head->is_CountedLoop()) return;
1613 
1614   CountedLoopNode *cl = loop->_head->as_CountedLoop();
1615 
1616   // only process vectorized main loops
1617   if (!cl->is_vectorized_loop() || !cl->is_main_loop()) return;
1618 
1619   int slp_max_unroll_factor = cl->slp_max_unroll();
1620   int cur_unroll = cl->unrolled_count();
1621 
1622   if (slp_max_unroll_factor == 0) return;
1623 
1624   // only process atomic unroll vector loops (not super unrolled after vectorization)
1625   if (cur_unroll != slp_max_unroll_factor) return;
1626 
1627   // we only ever process this one time
1628   if (cl->has_atomic_post_loop()) return;
1629 
1630   if (!may_require_nodes(loop->est_loop_clone_sz(2))) {
1631     return;
1632   }
1633 
1634 #ifndef PRODUCT
1635   if (TraceLoopOpts) {
1636     tty->print("PostVector  ");
1637     loop->dump_head();
1638   }
1639 #endif
1640   C->set_major_progress();
1641 
1642   // Find common pieces of the loop being guarded with pre & post loops
1643   CountedLoopNode *main_head = loop->_head->as_CountedLoop();
1644   CountedLoopEndNode *main_end = main_head->loopexit();
1645   // diagnostic to show loop end is not properly formed
1646   assert(main_end->outcnt() == 2, "1 true, 1 false path only");
1647 
1648   // mark this loop as processed
1649   main_head->mark_has_atomic_post_loop();
1650 
1651   Node *incr = main_end->incr();
1652   Node *limit = main_end->limit();
1653 
1654   // In this case we throw away the result as we are not using it to connect anything else.
1655   C->print_method(PHASE_BEFORE_POST_LOOP, 4, main_head);
1656   CountedLoopNode *post_head = nullptr;
1657   insert_post_loop(loop, old_new, main_head, main_end, incr, limit, post_head);
1658   C->print_method(PHASE_AFTER_POST_LOOP, 4, post_head);
1659 
1660   // It's difficult to be precise about the trip-counts
1661   // for post loops.  They are usually very short,
1662   // so guess that unit vector trips is a reasonable value.
1663   post_head->set_profile_trip_cnt(cur_unroll);
1664 
1665   // Now force out all loop-invariant dominating tests.  The optimizer
1666   // finds some, but we _know_ they are all useless.
1667   peeled_dom_test_elim(loop, old_new);
1668   loop->record_for_igvn();
1669 }
1670 
1671 Node* PhaseIdealLoop::find_last_store_in_outer_loop(Node* store, const IdealLoopTree* outer_loop) {
1672   assert(store != nullptr && store->is_Store(), "starting point should be a store node");
1673   // Follow the memory uses until we get out of the loop.
1674   // Store nodes in the outer loop body were moved by PhaseIdealLoop::try_move_store_after_loop.
1675   // Because of the conditions in try_move_store_after_loop (no other usage in the loop body
1676   // except for the phi node associated with the loop head), we have the guarantee of a
1677   // linear memory subgraph within the outer loop body.
1678   Node* last = store;
1679   Node* unique_next = store;
1680   do {
1681     last = unique_next;
1682     for (DUIterator_Fast imax, l = last->fast_outs(imax); l < imax; l++) {
1683       Node* use = last->fast_out(l);
1684       if (use->is_Store() && use->in(MemNode::Memory) == last) {
1685         if (is_member(outer_loop, get_ctrl(use))) {
1686           assert(unique_next == last, "memory node should only have one usage in the loop body");
1687           unique_next = use;
1688         }
1689       }
1690     }
1691   } while (last != unique_next);
1692   return last;
1693 }
1694 
1695 //------------------------------insert_post_loop-------------------------------
1696 // Insert post loops.  Add a post loop to the given loop passed.
1697 Node *PhaseIdealLoop::insert_post_loop(IdealLoopTree* loop, Node_List& old_new,
1698                                        CountedLoopNode* main_head, CountedLoopEndNode* main_end,
1699                                        Node* incr, Node* limit, CountedLoopNode*& post_head) {
1700   IfNode* outer_main_end = main_end;
1701   IdealLoopTree* outer_loop = loop;
1702   if (main_head->is_strip_mined()) {
1703     main_head->verify_strip_mined(1);
1704     outer_main_end = main_head->outer_loop_end();
1705     outer_loop = loop->_parent;
1706     assert(outer_loop->_head == main_head->in(LoopNode::EntryControl), "broken loop tree");
1707   }
1708 
1709   //------------------------------
1710   // Step A: Create a new post-Loop.
1711   Node* main_exit = outer_main_end->proj_out(false);
1712   assert(main_exit->Opcode() == Op_IfFalse, "");
1713   int dd_main_exit = dom_depth(main_exit);
1714 
1715   // Step A1: Clone the loop body of main. The clone becomes the post-loop.
1716   // The main loop pre-header illegally has 2 control users (old & new loops).
1717   const uint first_node_index_in_cloned_loop_body = C->unique();
1718   clone_loop(loop, old_new, dd_main_exit, ControlAroundStripMined);
1719   assert(old_new[main_end->_idx]->Opcode() == Op_CountedLoopEnd, "");
1720   post_head = old_new[main_head->_idx]->as_CountedLoop();
1721   post_head->set_normal_loop();
1722   post_head->set_post_loop(main_head);
1723 
1724   // clone_loop() above changes the exit projection
1725   main_exit = outer_main_end->proj_out(false);
1726 
1727   // Reduce the post-loop trip count.
1728   CountedLoopEndNode* post_end = old_new[main_end->_idx]->as_CountedLoopEnd();
1729   post_end->_prob = PROB_FAIR;
1730 
1731   // Build the main-loop normal exit.
1732   IfFalseNode *new_main_exit = new IfFalseNode(outer_main_end);
1733   _igvn.register_new_node_with_optimizer(new_main_exit);
1734   set_idom(new_main_exit, outer_main_end, dd_main_exit);
1735   set_loop(new_main_exit, outer_loop->_parent);
1736 
1737   // Step A2: Build a zero-trip guard for the post-loop.  After leaving the
1738   // main-loop, the post-loop may not execute at all.  We 'opaque' the incr
1739   // (the previous loop trip-counter exit value) because we will be changing
1740   // the exit value (via additional unrolling) so we cannot constant-fold away the zero
1741   // trip guard until all unrolling is done.
1742   Node *zer_opaq = new OpaqueZeroTripGuardNode(C, incr, main_end->test_trip());
1743   Node *zer_cmp = new CmpINode(zer_opaq, limit);
1744   Node *zer_bol = new BoolNode(zer_cmp, main_end->test_trip());
1745   register_new_node(zer_opaq, new_main_exit);
1746   register_new_node(zer_cmp, new_main_exit);
1747   register_new_node(zer_bol, new_main_exit);
1748 
1749   // Build the IfNode
1750   IfNode *zer_iff = new IfNode(new_main_exit, zer_bol, PROB_FAIR, COUNT_UNKNOWN);
1751   _igvn.register_new_node_with_optimizer(zer_iff);
1752   set_idom(zer_iff, new_main_exit, dd_main_exit);
1753   set_loop(zer_iff, outer_loop->_parent);
1754 
1755   // Plug in the false-path, taken if we need to skip this post-loop
1756   _igvn.replace_input_of(main_exit, 0, zer_iff);
1757   set_idom(main_exit, zer_iff, dd_main_exit);
1758   set_idom(main_exit->unique_out(), zer_iff, dd_main_exit);
1759   // Make the true-path, must enter this post loop
1760   Node *zer_taken = new IfTrueNode(zer_iff);
1761   _igvn.register_new_node_with_optimizer(zer_taken);
1762   set_idom(zer_taken, zer_iff, dd_main_exit);
1763   set_loop(zer_taken, outer_loop->_parent);
1764   // Plug in the true path
1765   _igvn.hash_delete(post_head);
1766   post_head->set_req(LoopNode::EntryControl, zer_taken);
1767   set_idom(post_head, zer_taken, dd_main_exit);
1768 
1769   VectorSet visited;
1770   Node_Stack clones(main_head->back_control()->outcnt());
1771   // Step A3: Make the fall-in values to the post-loop come from the
1772   // fall-out values of the main-loop.
1773   for (DUIterator i = main_head->outs(); main_head->has_out(i); i++) {
1774     Node* main_phi = main_head->out(i);
1775     if (main_phi->is_Phi() && main_phi->in(0) == main_head && main_phi->outcnt() > 0) {
1776       Node* cur_phi = old_new[main_phi->_idx];
1777       Node* fallnew = clone_up_backedge_goo(main_head->back_control(),
1778                                             post_head->init_control(),
1779                                             main_phi->in(LoopNode::LoopBackControl),
1780                                             visited, clones);
1781       _igvn.hash_delete(cur_phi);
1782       cur_phi->set_req(LoopNode::EntryControl, fallnew);
1783     }
1784   }
1785   // Store nodes that were moved to the outer loop by PhaseIdealLoop::try_move_store_after_loop
1786   // do not have an associated Phi node. Such nodes are attached to the false projection of the CountedLoopEnd node,
1787   // right after the execution of the inner CountedLoop.
1788   // We have to make sure that such stores in the post loop have the right memory inputs from the main loop
1789   // The moved store node is always attached right after the inner loop exit, and just before the safepoint
1790   const Node* if_false = main_end->proj_out(false);
1791   for (DUIterator j = if_false->outs(); if_false->has_out(j); j++) {
1792     Node* store = if_false->out(j);
1793     if (store->is_Store()) {
1794       // We only make changes if the memory input of the store is outside the outer loop body,
1795       // as this is when we would normally expect a Phi as input. If the memory input
1796       // is in the loop body as well, then we can safely assume it is still correct as the entire
1797       // body was cloned as a unit
1798       if (!is_member(outer_loop, get_ctrl(store->in(MemNode::Memory)))) {
1799         Node* mem_out = find_last_store_in_outer_loop(store, outer_loop);
1800         Node* store_new = old_new[store->_idx];
1801         store_new->set_req(MemNode::Memory, mem_out);
1802       }
1803     }
1804   }
1805 
1806   DEBUG_ONLY(ensure_zero_trip_guard_proj(post_head->in(LoopNode::EntryControl), false);)
1807   initialize_assertion_predicates_for_post_loop(main_head, post_head, first_node_index_in_cloned_loop_body);
1808   cast_incr_before_loop(zer_opaq->in(1), zer_taken, post_head);
1809   return new_main_exit;
1810 }
1811 
1812 //------------------------------is_invariant-----------------------------
1813 // Return true if n is invariant
1814 bool IdealLoopTree::is_invariant(Node* n) const {
1815   Node *n_c = _phase->has_ctrl(n) ? _phase->get_ctrl(n) : n;
1816   if (n_c->is_top()) return false;
1817   return !is_member(_phase->get_loop(n_c));
1818 }
1819 
1820 // Search the Assertion Predicates added by loop predication and/or range check elimination and update them according
1821 // to the new stride.
1822 void PhaseIdealLoop::update_main_loop_assertion_predicates(CountedLoopNode* new_main_loop_head,
1823                                                            const int stride_con_before_unroll) {
1824   // Compute the value of the loop induction variable at the end of the
1825   // first iteration of the unrolled loop: init + new_stride_con - init_inc
1826   int unrolled_stride_con = stride_con_before_unroll * 2;
1827   Node* unrolled_stride = intcon(unrolled_stride_con);
1828 
1829   Node* loop_entry = new_main_loop_head->skip_strip_mined()->in(LoopNode::EntryControl);
1830   PredicateIterator predicate_iterator(loop_entry);
1831   UpdateStrideForAssertionPredicates update_stride_for_assertion_predicates(unrolled_stride, new_main_loop_head, this);
1832   predicate_iterator.for_each(update_stride_for_assertion_predicates);
1833 }
1834 
1835 // Source Loop: Cloned   - peeled_loop_head
1836 // Target Loop: Original - remaining_loop_head
1837 void PhaseIdealLoop::initialize_assertion_predicates_for_peeled_loop(CountedLoopNode* peeled_loop_head,
1838                                                                      CountedLoopNode* remaining_loop_head,
1839                                                                      const uint first_node_index_in_cloned_loop_body,
1840                                                                      const Node_List& old_new) {
1841   const NodeInOriginalLoopBody node_in_original_loop_body(first_node_index_in_cloned_loop_body, old_new);
1842   create_assertion_predicates_at_loop(peeled_loop_head, remaining_loop_head, node_in_original_loop_body, true);
1843 }
1844 
1845 // Source Loop: Cloned   - pre_loop_head
1846 // Target Loop: Original - main_loop_head
1847 void PhaseIdealLoop::initialize_assertion_predicates_for_main_loop(CountedLoopNode* pre_loop_head,
1848                                                                    CountedLoopNode* main_loop_head,
1849                                                                    const uint first_node_index_in_pre_loop_body,
1850                                                                    const uint last_node_index_in_pre_loop_body,
1851                                                                    DEBUG_ONLY(const uint last_node_index_from_backedge_goo COMMA)
1852                                                                    const Node_List& old_new) {
1853   assert(first_node_index_in_pre_loop_body < last_node_index_in_pre_loop_body, "cloned some nodes");
1854   const NodeInMainLoopBody node_in_main_loop_body(first_node_index_in_pre_loop_body,
1855                                                   last_node_index_in_pre_loop_body,
1856                                                   DEBUG_ONLY(last_node_index_from_backedge_goo COMMA) old_new);
1857   create_assertion_predicates_at_main_or_post_loop(pre_loop_head, main_loop_head, node_in_main_loop_body, true);
1858 }
1859 
1860 // Source Loop: Original - main_loop_head
1861 // Target Loop: Cloned   - post_loop_head
1862 //
1863 // The post loop is cloned before the pre loop. Do not kill the old Template Assertion Predicates, yet. We need to clone
1864 // from them when creating the pre loop. Only then we can kill them.
1865 void PhaseIdealLoop::initialize_assertion_predicates_for_post_loop(CountedLoopNode* main_loop_head,
1866                                                                    CountedLoopNode* post_loop_head,
1867                                                                    const uint first_node_index_in_cloned_loop_body) {
1868   const NodeInClonedLoopBody node_in_cloned_loop_body(first_node_index_in_cloned_loop_body);
1869   create_assertion_predicates_at_main_or_post_loop(main_loop_head, post_loop_head, node_in_cloned_loop_body, false);
1870 }
1871 
1872 void PhaseIdealLoop::create_assertion_predicates_at_loop(CountedLoopNode* source_loop_head,
1873                                                          CountedLoopNode* target_loop_head,
1874                                                          const NodeInLoopBody& _node_in_loop_body,
1875                                                          const bool kill_old_template) {
1876   CreateAssertionPredicatesVisitor create_assertion_predicates_visitor(target_loop_head, this, _node_in_loop_body,
1877                                                                        kill_old_template);
1878   Node* source_loop_entry = source_loop_head->skip_strip_mined()->in(LoopNode::EntryControl);
1879   PredicateIterator predicate_iterator(source_loop_entry);
1880   predicate_iterator.for_each(create_assertion_predicates_visitor);
1881 }
1882 
1883 void PhaseIdealLoop::create_assertion_predicates_at_main_or_post_loop(CountedLoopNode* source_loop_head,
1884                                                                       CountedLoopNode* target_loop_head,
1885                                                                       const NodeInLoopBody& _node_in_loop_body,
1886                                                                       const bool kill_old_template) {
1887   Node* old_target_loop_head_entry = target_loop_head->skip_strip_mined()->in(LoopNode::EntryControl);
1888   const uint node_index_before_new_assertion_predicate_nodes = C->unique();
1889   const bool need_to_rewire_old_target_loop_entry_dependencies = old_target_loop_head_entry->outcnt() > 1;
1890   create_assertion_predicates_at_loop(source_loop_head, target_loop_head, _node_in_loop_body, kill_old_template);
1891   if (need_to_rewire_old_target_loop_entry_dependencies) {
1892     rewire_old_target_loop_entry_dependency_to_new_entry(target_loop_head, old_target_loop_head_entry,
1893                                                          node_index_before_new_assertion_predicate_nodes);
1894   }
1895 }
1896 
1897 // Rewire any control dependent nodes on the old target loop entry before adding Assertion Predicate related nodes.
1898 // These have been added by PhaseIdealLoop::clone_up_backedge_goo() and assume to be ending up at the target loop entry
1899 // which is no longer the case when adding additional Assertion Predicates. Fix this by rewiring these nodes to the new
1900 // target loop entry which corresponds to the tail of the last Assertion Predicate before the target loop. This is safe
1901 // to do because these control dependent nodes on the old target loop entry created by clone_up_backedge_goo() were
1902 // pinned on the loop backedge before. The Assertion Predicates are not control dependent on these nodes in any way.
1903 void PhaseIdealLoop::rewire_old_target_loop_entry_dependency_to_new_entry(
1904   CountedLoopNode* target_loop_head, const Node* old_target_loop_entry,
1905   const uint node_index_before_new_assertion_predicate_nodes) {
1906   Node* new_main_loop_entry = target_loop_head->skip_strip_mined()->in(LoopNode::EntryControl);
1907   if (new_main_loop_entry == old_target_loop_entry) {
1908     // No Assertion Predicates added.
1909     return;
1910   }
1911 
1912   for (DUIterator_Fast imax, i = old_target_loop_entry->fast_outs(imax); i < imax; i++) {
1913     Node* out = old_target_loop_entry->fast_out(i);
1914     if (!out->is_CFG() && out->_idx < node_index_before_new_assertion_predicate_nodes) {
1915       assert(out != target_loop_head->init_trip(), "CastII on loop entry?");
1916       _igvn.replace_input_of(out, 0, new_main_loop_entry);
1917       set_ctrl(out, new_main_loop_entry);
1918       --i;
1919       --imax;
1920     }
1921   }
1922 }
1923 
1924 //------------------------------do_unroll--------------------------------------
1925 // Unroll the loop body one step - make each trip do 2 iterations.
1926 void PhaseIdealLoop::do_unroll(IdealLoopTree *loop, Node_List &old_new, bool adjust_min_trip) {
1927   assert(LoopUnrollLimit, "");
1928   CountedLoopNode *loop_head = loop->_head->as_CountedLoop();
1929   CountedLoopEndNode *loop_end = loop_head->loopexit();
1930 
1931   C->print_method(PHASE_BEFORE_LOOP_UNROLLING, 4, loop_head);
1932 
1933 #ifndef PRODUCT
1934   if (TraceLoopOpts) {
1935     if (loop_head->trip_count() < (uint)LoopUnrollLimit) {
1936       tty->print("Unroll %d(" JULONG_FORMAT_W(2) ") ", loop_head->unrolled_count()*2, loop_head->trip_count());
1937     } else {
1938       tty->print("Unroll %d     ", loop_head->unrolled_count()*2);
1939     }
1940     loop->dump_head();
1941   }
1942 
1943   if (C->do_vector_loop() && (PrintOpto && (VerifyLoopOptimizations || TraceLoopOpts))) {
1944     Node_Stack stack(C->live_nodes() >> 2);
1945     Node_List rpo_list;
1946     VectorSet visited;
1947     visited.set(loop_head->_idx);
1948     rpo(loop_head, stack, visited, rpo_list);
1949     dump(loop, rpo_list.size(), rpo_list);
1950   }
1951 #endif
1952 
1953   // Remember loop node count before unrolling to detect
1954   // if rounds of unroll,optimize are making progress
1955   loop_head->set_node_count_before_unroll(loop->_body.size());
1956 
1957   Node *ctrl  = loop_head->skip_strip_mined()->in(LoopNode::EntryControl);
1958   Node *limit = loop_head->limit();
1959   Node *init  = loop_head->init_trip();
1960   Node *stride = loop_head->stride();
1961 
1962   Node *opaq = nullptr;
1963   if (adjust_min_trip) {       // If not maximally unrolling, need adjustment
1964     // Search for zero-trip guard.
1965 
1966     // Check the shape of the graph at the loop entry. If an inappropriate
1967     // graph shape is encountered, the compiler bails out loop unrolling;
1968     // compilation of the method will still succeed.
1969     opaq = loop_head->is_canonical_loop_entry();
1970     if (opaq == nullptr) {
1971       return;
1972     }
1973     // Zero-trip test uses an 'opaque' node which is not shared.
1974     assert(opaq->outcnt() == 1 && opaq->in(1) == limit, "");
1975   }
1976 
1977   C->set_major_progress();
1978 
1979   Node* new_limit = nullptr;
1980   const int stride_con = stride->get_int();
1981   int stride_p = (stride_con > 0) ? stride_con : -stride_con;
1982   uint old_trip_count = loop_head->trip_count();
1983   // Verify that unroll policy result is still valid.
1984   assert(old_trip_count > 1 && (!adjust_min_trip || stride_p <=
1985     MIN2<int>(max_jint / 2 - 2, MAX2(1<<3, Matcher::max_vector_size(T_BYTE)) * loop_head->unrolled_count())), "sanity");
1986 
1987   // Adjust loop limit to keep valid iterations number after unroll.
1988   // Use (limit - stride) instead of (((limit - init)/stride) & (-2))*stride
1989   // which may overflow.
1990   if (!adjust_min_trip) {
1991     assert(old_trip_count > 1 && (old_trip_count & 1) == 0,
1992         "odd trip count for maximally unroll");
1993     // Don't need to adjust limit for maximally unroll since trip count is even.
1994   } else if (loop_head->has_exact_trip_count() && init->is_Con()) {
1995     // The trip count being exact means it has been set (using CountedLoopNode::set_exact_trip_count in compute_trip_count)
1996     assert(old_trip_count < max_juint, "sanity");
1997     // Loop's limit is constant. Loop's init could be constant when pre-loop
1998     // become peeled iteration.
1999     jlong init_con = init->get_int();
2000     // We can keep old loop limit if iterations count stays the same:
2001     //   old_trip_count == new_trip_count * 2
2002     // Note: since old_trip_count >= 2 then new_trip_count >= 1
2003     // so we also don't need to adjust zero trip test.
2004     jlong limit_con  = limit->get_int();
2005     // (stride_con*2) not overflow since stride_con <= 8.
2006     int new_stride_con = stride_con * 2;
2007     int stride_m    = new_stride_con - (stride_con > 0 ? 1 : -1);
2008     jlong trip_count = (limit_con - init_con + stride_m)/new_stride_con;
2009     // New trip count should satisfy next conditions.
2010     assert(trip_count > 0 && (julong)trip_count <= (julong)max_juint/2, "sanity");
2011     uint new_trip_count = (uint)trip_count;
2012     // Since old_trip_count has been set to < max_juint (that is at most 2^32-2),
2013     // new_trip_count is lower than or equal to 2^31-1 and the multiplication cannot overflow.
2014     adjust_min_trip = (old_trip_count != new_trip_count*2);
2015   }
2016 
2017   if (adjust_min_trip) {
2018     // Step 2: Adjust the trip limit if it is called for.
2019     // The adjustment amount is -stride. Need to make sure if the
2020     // adjustment underflows or overflows, then the main loop is skipped.
2021     Node* cmp = loop_end->cmp_node();
2022     assert(cmp->in(2) == limit, "sanity");
2023     assert(opaq != nullptr && opaq->in(1) == limit, "sanity");
2024 
2025     // Verify that policy_unroll result is still valid.
2026     const TypeInt* limit_type = _igvn.type(limit)->is_int();
2027     assert((stride_con > 0 && ((min_jint + stride_con) <= limit_type->_hi)) ||
2028            (stride_con < 0 && ((max_jint + stride_con) >= limit_type->_lo)),
2029            "sanity");
2030 
2031     if (limit->is_Con()) {
2032       // The check in policy_unroll and the assert above guarantee
2033       // no underflow if limit is constant.
2034       new_limit = intcon(limit->get_int() - stride_con);
2035     } else {
2036       // Limit is not constant. Int subtraction could lead to underflow.
2037       // (1) Convert to long.
2038       Node* limit_l = new ConvI2LNode(limit);
2039       register_new_node_with_ctrl_of(limit_l, limit);
2040       Node* stride_l = longcon(stride_con);
2041 
2042       // (2) Subtract: compute in long, to prevent underflow.
2043       Node* new_limit_l = new SubLNode(limit_l, stride_l);
2044       register_new_node(new_limit_l, ctrl);
2045 
2046       // (3) Clamp to int range, in case we had subtraction underflow.
2047       Node* underflow_clamp_l = longcon((stride_con > 0) ? min_jint : max_jint);
2048       Node* new_limit_no_underflow_l = nullptr;
2049       if (stride_con > 0) {
2050         // limit = MaxL(limit - stride, min_jint)
2051         new_limit_no_underflow_l = new MaxLNode(C, new_limit_l, underflow_clamp_l);
2052       } else {
2053         // limit = MinL(limit - stride, max_jint)
2054         new_limit_no_underflow_l = new MinLNode(C, new_limit_l, underflow_clamp_l);
2055       }
2056       register_new_node(new_limit_no_underflow_l, ctrl);
2057 
2058       // (4) Convert back to int.
2059       new_limit = new ConvL2INode(new_limit_no_underflow_l);
2060       register_new_node(new_limit, ctrl);
2061     }
2062 
2063     assert(new_limit != nullptr, "");
2064     // Replace in loop test.
2065     assert(loop_end->in(1)->in(1) == cmp, "sanity");
2066     if (cmp->outcnt() == 1 && loop_end->in(1)->outcnt() == 1) {
2067       // Don't need to create new test since only one user.
2068       _igvn.hash_delete(cmp);
2069       cmp->set_req(2, new_limit);
2070     } else {
2071       // Create new test since it is shared.
2072       Node* ctrl2 = loop_end->in(0);
2073       Node* cmp2  = cmp->clone();
2074       cmp2->set_req(2, new_limit);
2075       register_new_node(cmp2, ctrl2);
2076       Node* bol2 = loop_end->in(1)->clone();
2077       bol2->set_req(1, cmp2);
2078       register_new_node(bol2, ctrl2);
2079       _igvn.replace_input_of(loop_end, 1, bol2);
2080     }
2081     // Step 3: Find the min-trip test guaranteed before a 'main' loop.
2082     // Make it a 1-trip test (means at least 2 trips).
2083 
2084     // Guard test uses an 'opaque' node which is not shared.  Hence I
2085     // can edit it's inputs directly.  Hammer in the new limit for the
2086     // minimum-trip guard.
2087     assert(opaq->outcnt() == 1, "");
2088     // Notify limit -> opaq -> CmpI, it may constant fold.
2089     _igvn.add_users_to_worklist(opaq->in(1));
2090     _igvn.replace_input_of(opaq, 1, new_limit);
2091   }
2092 
2093   // Adjust max trip count. The trip count is intentionally rounded
2094   // down here (e.g. 15-> 7-> 3-> 1) because if we unwittingly over-unroll,
2095   // the main, unrolled, part of the loop will never execute as it is protected
2096   // by the min-trip test.  See bug 4834191 for a case where we over-unrolled
2097   // and later determined that part of the unrolled loop was dead.
2098   loop_head->set_trip_count(old_trip_count / 2);
2099 
2100   // Double the count of original iterations in the unrolled loop body.
2101   loop_head->double_unrolled_count();
2102 
2103   // ---------
2104   // Step 4: Clone the loop body.  Move it inside the loop.  This loop body
2105   // represents the odd iterations; since the loop trips an even number of
2106   // times its backedge is never taken.  Kill the backedge.
2107   uint dd = dom_depth(loop_head);
2108   clone_loop(loop, old_new, dd, IgnoreStripMined);
2109 
2110   // Make backedges of the clone equal to backedges of the original.
2111   // Make the fall-in from the original come from the fall-out of the clone.
2112   for (DUIterator_Fast jmax, j = loop_head->fast_outs(jmax); j < jmax; j++) {
2113     Node* phi = loop_head->fast_out(j);
2114     if (phi->is_Phi() && phi->in(0) == loop_head && phi->outcnt() > 0) {
2115       Node *newphi = old_new[phi->_idx];
2116       _igvn.hash_delete(phi);
2117       _igvn.hash_delete(newphi);
2118 
2119       phi   ->set_req(LoopNode::   EntryControl, newphi->in(LoopNode::LoopBackControl));
2120       newphi->set_req(LoopNode::LoopBackControl, phi   ->in(LoopNode::LoopBackControl));
2121       phi   ->set_req(LoopNode::LoopBackControl, C->top());
2122     }
2123   }
2124   CountedLoopNode* clone_head = old_new[loop_head->_idx]->as_CountedLoop();
2125   _igvn.hash_delete(clone_head);
2126   loop_head ->set_req(LoopNode::   EntryControl, clone_head->in(LoopNode::LoopBackControl));
2127   clone_head->set_req(LoopNode::LoopBackControl, loop_head ->in(LoopNode::LoopBackControl));
2128   loop_head ->set_req(LoopNode::LoopBackControl, C->top());
2129   loop->_head = clone_head;     // New loop header
2130 
2131   set_idom(loop_head,  loop_head ->in(LoopNode::EntryControl), dd);
2132   set_idom(clone_head, clone_head->in(LoopNode::EntryControl), dd);
2133 
2134   // Kill the clone's backedge
2135   Node *newcle = old_new[loop_end->_idx];
2136   _igvn.hash_delete(newcle);
2137   Node* one = intcon(1);
2138   newcle->set_req(1, one);
2139   // Force clone into same loop body
2140   uint max = loop->_body.size();
2141   for (uint k = 0; k < max; k++) {
2142     Node *old = loop->_body.at(k);
2143     Node *nnn = old_new[old->_idx];
2144     loop->_body.push(nnn);
2145     if (!has_ctrl(old)) {
2146       set_loop(nnn, loop);
2147     }
2148   }
2149 
2150   loop->record_for_igvn();
2151   loop_head->clear_strip_mined();
2152 
2153   update_main_loop_assertion_predicates(clone_head, stride_con);
2154 
2155 #ifndef PRODUCT
2156   if (C->do_vector_loop() && (PrintOpto && (VerifyLoopOptimizations || TraceLoopOpts))) {
2157     tty->print("\nnew loop after unroll\n");       loop->dump_head();
2158     for (uint i = 0; i < loop->_body.size(); i++) {
2159       loop->_body.at(i)->dump();
2160     }
2161     if (C->clone_map().is_debug()) {
2162       tty->print("\nCloneMap\n");
2163       Dict* dict = C->clone_map().dict();
2164       DictI i(dict);
2165       tty->print_cr("Dict@%p[%d] = ", dict, dict->Size());
2166       for (int ii = 0; i.test(); ++i, ++ii) {
2167         NodeCloneInfo cl((uint64_t)dict->operator[]((void*)i._key));
2168         tty->print("%d->%d:%d,", (int)(intptr_t)i._key, cl.idx(), cl.gen());
2169         if (ii % 10 == 9) {
2170           tty->print_cr(" ");
2171         }
2172       }
2173       tty->print_cr(" ");
2174     }
2175   }
2176 #endif
2177 
2178   C->print_method(PHASE_AFTER_LOOP_UNROLLING, 4, clone_head);
2179 }
2180 
2181 //------------------------------do_maximally_unroll----------------------------
2182 
2183 void PhaseIdealLoop::do_maximally_unroll(IdealLoopTree *loop, Node_List &old_new) {
2184   CountedLoopNode *cl = loop->_head->as_CountedLoop();
2185   assert(cl->has_exact_trip_count(), "trip count is not exact");
2186   assert(cl->trip_count() > 0, "");
2187 #ifndef PRODUCT
2188   if (TraceLoopOpts) {
2189     tty->print("MaxUnroll  " JULONG_FORMAT " ", cl->trip_count());
2190     loop->dump_head();
2191   }
2192 #endif
2193 
2194   // If loop is tripping an odd number of times, peel odd iteration
2195   if ((cl->trip_count() & 1) == 1) {
2196     do_peeling(loop, old_new);
2197   }
2198 
2199   // Now its tripping an even number of times remaining.  Double loop body.
2200   // Do not adjust pre-guards; they are not needed and do not exist.
2201   if (cl->trip_count() > 0) {
2202     assert((cl->trip_count() & 1) == 0, "missed peeling");
2203     do_unroll(loop, old_new, false);
2204   }
2205 }
2206 
2207 //------------------------------adjust_limit-----------------------------------
2208 // Helper function that computes new loop limit as (rc_limit-offset)/scale
2209 Node* PhaseIdealLoop::adjust_limit(bool is_positive_stride, Node* scale, Node* offset, Node* rc_limit, Node* old_limit, Node* pre_ctrl, bool round) {
2210   Node* old_limit_long = new ConvI2LNode(old_limit);
2211   register_new_node(old_limit_long, pre_ctrl);
2212 
2213   Node* sub = new SubLNode(rc_limit, offset);
2214   register_new_node(sub, pre_ctrl);
2215   Node* limit = new DivLNode(nullptr, sub, scale);
2216   register_new_node(limit, pre_ctrl);
2217 
2218   // When the absolute value of scale is greater than one, the division
2219   // may round limit down/up, so add/sub one to/from the limit.
2220   if (round) {
2221     limit = new AddLNode(limit, _igvn.longcon(is_positive_stride ? -1 : 1));
2222     register_new_node(limit, pre_ctrl);
2223   }
2224 
2225   // Clamp the limit to handle integer under-/overflows by using long values.
2226   // We only convert the limit back to int when we handled under-/overflows.
2227   // Note that all values are longs in the following computations.
2228   // When reducing the limit, clamp to [min_jint, old_limit]:
2229   //   INT(MINL(old_limit, MAXL(limit, min_jint)))
2230   //   - integer underflow of limit: MAXL chooses min_jint.
2231   //   - integer overflow of limit: MINL chooses old_limit (<= MAX_INT < limit)
2232   // When increasing the limit, clamp to [old_limit, max_jint]:
2233   //   INT(MAXL(old_limit, MINL(limit, max_jint)))
2234   //   - integer overflow of limit: MINL chooses max_jint.
2235   //   - integer underflow of limit: MAXL chooses old_limit (>= MIN_INT > limit)
2236   // INT() is finally converting the limit back to an integer value.
2237 
2238   Node* inner_result_long = nullptr;
2239   Node* outer_result_long = nullptr;
2240   if (is_positive_stride) {
2241     inner_result_long = new MaxLNode(C, limit, _igvn.longcon(min_jint));
2242     outer_result_long = new MinLNode(C, inner_result_long, old_limit_long);
2243   } else {
2244     inner_result_long = new MinLNode(C, limit, _igvn.longcon(max_jint));
2245     outer_result_long = new MaxLNode(C, inner_result_long, old_limit_long);
2246   }
2247   register_new_node(inner_result_long, pre_ctrl);
2248   register_new_node(outer_result_long, pre_ctrl);
2249 
2250   limit = new ConvL2INode(outer_result_long);
2251   register_new_node(limit, pre_ctrl);
2252   return limit;
2253 }
2254 
2255 //------------------------------add_constraint---------------------------------
2256 // Constrain the main loop iterations so the conditions:
2257 //    low_limit <= scale_con*I + offset < upper_limit
2258 // always hold true. That is, either increase the number of iterations in the
2259 // pre-loop or reduce the number of iterations in the main-loop until the condition
2260 // holds true in the main-loop. Stride, scale, offset and limit are all loop
2261 // invariant. Further, stride and scale are constants (offset and limit often are).
2262 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) {
2263   assert(_igvn.type(offset)->isa_long() != nullptr && _igvn.type(low_limit)->isa_long() != nullptr &&
2264          _igvn.type(upper_limit)->isa_long() != nullptr, "arguments should be long values");
2265 
2266   // For a positive stride, we need to reduce the main-loop limit and
2267   // increase the pre-loop limit. This is reversed for a negative stride.
2268   bool is_positive_stride = (stride_con > 0);
2269 
2270   // If the absolute scale value is greater one, division in 'adjust_limit' may require
2271   // rounding. Make sure the ABS method correctly handles min_jint.
2272   // Only do this for the pre-loop, one less iteration of the main loop doesn't hurt.
2273   bool round = ABS(scale_con) > 1;
2274 
2275   Node* scale = longcon(scale_con);
2276 
2277   if ((stride_con^scale_con) >= 0) { // Use XOR to avoid overflow
2278     // Positive stride*scale: the affine function is increasing,
2279     // the pre-loop checks for underflow and the post-loop for overflow.
2280 
2281     // The overflow limit: scale*I+offset < upper_limit
2282     // For the main-loop limit compute:
2283     //   ( if (scale > 0) /* and stride > 0 */
2284     //       I < (upper_limit-offset)/scale
2285     //     else /* scale < 0 and stride < 0 */
2286     //       I > (upper_limit-offset)/scale
2287     //   )
2288     *main_limit = adjust_limit(is_positive_stride, scale, offset, upper_limit, *main_limit, pre_ctrl, false);
2289 
2290     // The underflow limit: low_limit <= scale*I+offset
2291     // For the pre-loop limit compute:
2292     //   NOT(scale*I+offset >= low_limit)
2293     //   scale*I+offset < low_limit
2294     //   ( if (scale > 0) /* and stride > 0 */
2295     //       I < (low_limit-offset)/scale
2296     //     else /* scale < 0 and stride < 0 */
2297     //       I > (low_limit-offset)/scale
2298     //   )
2299     *pre_limit = adjust_limit(!is_positive_stride, scale, offset, low_limit, *pre_limit, pre_ctrl, round);
2300   } else {
2301     // Negative stride*scale: the affine function is decreasing,
2302     // the pre-loop checks for overflow and the post-loop for underflow.
2303 
2304     // The overflow limit: scale*I+offset < upper_limit
2305     // For the pre-loop limit compute:
2306     //   NOT(scale*I+offset < upper_limit)
2307     //   scale*I+offset >= upper_limit
2308     //   scale*I+offset+1 > upper_limit
2309     //   ( if (scale < 0) /* and stride > 0 */
2310     //       I < (upper_limit-(offset+1))/scale
2311     //     else /* scale > 0 and stride < 0 */
2312     //       I > (upper_limit-(offset+1))/scale
2313     //   )
2314     Node* one = longcon(1);
2315     Node* plus_one = new AddLNode(offset, one);
2316     register_new_node(plus_one, pre_ctrl);
2317     *pre_limit = adjust_limit(!is_positive_stride, scale, plus_one, upper_limit, *pre_limit, pre_ctrl, round);
2318 
2319     // The underflow limit: low_limit <= scale*I+offset
2320     // For the main-loop limit compute:
2321     //   scale*I+offset+1 > low_limit
2322     //   ( if (scale < 0) /* and stride > 0 */
2323     //       I < (low_limit-(offset+1))/scale
2324     //     else /* scale > 0 and stride < 0 */
2325     //       I > (low_limit-(offset+1))/scale
2326     //   )
2327     *main_limit = adjust_limit(is_positive_stride, scale, plus_one, low_limit, *main_limit, pre_ctrl, false);
2328   }
2329 }
2330 
2331 //----------------------------------is_iv------------------------------------
2332 // Return true if exp is the value (of type bt) of the given induction var.
2333 // This grammar of cases is recognized, where X is I|L according to bt:
2334 //    VIV[iv] = iv | (CastXX VIV[iv]) | (ConvI2X VIV[iv])
2335 bool PhaseIdealLoop::is_iv(Node* exp, Node* iv, BasicType bt) {
2336   exp = exp->uncast();
2337   if (exp == iv && iv->bottom_type()->isa_integer(bt)) {
2338     return true;
2339   }
2340 
2341   if (bt == T_LONG && iv->bottom_type()->isa_int() && exp->Opcode() == Op_ConvI2L && exp->in(1)->uncast() == iv) {
2342     return true;
2343   }
2344   return false;
2345 }
2346 
2347 //------------------------------is_scaled_iv---------------------------------
2348 // Return true if exp is a constant times the given induction var (of type bt).
2349 // The multiplication is either done in full precision (exactly of type bt),
2350 // or else bt is T_LONG but iv is scaled using 32-bit arithmetic followed by a ConvI2L.
2351 // This grammar of cases is recognized, where X is I|L according to bt:
2352 //    SIV[iv] = VIV[iv] | (CastXX SIV[iv])
2353 //            | (MulX VIV[iv] ConX) | (MulX ConX VIV[iv])
2354 //            | (LShiftX VIV[iv] ConI)
2355 //            | (ConvI2L SIV[iv])  -- a "short-scale" can occur here; note recursion
2356 //            | (SubX 0 SIV[iv])  -- same as MulX(iv, -scale); note recursion
2357 //            | (AddX SIV[iv] SIV[iv])  -- sum of two scaled iv; note recursion
2358 //            | (SubX SIV[iv] SIV[iv])  -- difference of two scaled iv; note recursion
2359 //    VIV[iv] = [either iv or its value converted; see is_iv() above]
2360 // On success, the constant scale value is stored back to *p_scale.
2361 // The value (*p_short_scale) reports if such a ConvI2L conversion was present.
2362 bool PhaseIdealLoop::is_scaled_iv(Node* exp, Node* iv, BasicType bt, jlong* p_scale, bool* p_short_scale, int depth) {
2363   BasicType exp_bt = bt;
2364   exp = exp->uncast();  //strip casts
2365   assert(exp_bt == T_INT || exp_bt == T_LONG, "unexpected int type");
2366   if (is_iv(exp, iv, exp_bt)) {
2367     if (p_scale != nullptr) {
2368       *p_scale = 1;
2369     }
2370     if (p_short_scale != nullptr) {
2371       *p_short_scale = false;
2372     }
2373     return true;
2374   }
2375   if (exp_bt == T_LONG && iv->bottom_type()->isa_int() && exp->Opcode() == Op_ConvI2L) {
2376     exp = exp->in(1);
2377     exp_bt = T_INT;
2378   }
2379   int opc = exp->Opcode();
2380   int which = 0;  // this is which subexpression we find the iv in
2381   // Can't use is_Mul() here as it's true for AndI and AndL
2382   if (opc == Op_Mul(exp_bt)) {
2383     if ((is_iv(exp->in(which = 1), iv, exp_bt) && exp->in(2)->is_Con()) ||
2384         (is_iv(exp->in(which = 2), iv, exp_bt) && exp->in(1)->is_Con())) {
2385       Node* factor = exp->in(which == 1 ? 2 : 1);  // the other argument
2386       jlong scale = factor->find_integer_as_long(exp_bt, 0);
2387       if (scale == 0) {
2388         return false;  // might be top
2389       }
2390       if (p_scale != nullptr) {
2391         *p_scale = scale;
2392       }
2393       if (p_short_scale != nullptr) {
2394         // (ConvI2L (MulI iv K)) can be 64-bit linear if iv is kept small enough...
2395         *p_short_scale = (exp_bt != bt && scale != 1);
2396       }
2397       return true;
2398     }
2399   } else if (opc == Op_LShift(exp_bt)) {
2400     if (is_iv(exp->in(1), iv, exp_bt) && exp->in(2)->is_Con()) {
2401       jint shift_amount = exp->in(2)->find_int_con(min_jint);
2402       if (shift_amount == min_jint) {
2403         return false;  // might be top
2404       }
2405       jlong scale;
2406       if (exp_bt == T_INT) {
2407         scale = java_shift_left((jint)1, (juint)shift_amount);
2408       } else if (exp_bt == T_LONG) {
2409         scale = java_shift_left((jlong)1, (julong)shift_amount);
2410       }
2411       if (p_scale != nullptr) {
2412         *p_scale = scale;
2413       }
2414       if (p_short_scale != nullptr) {
2415         // (ConvI2L (MulI iv K)) can be 64-bit linear if iv is kept small enough...
2416         *p_short_scale = (exp_bt != bt && scale != 1);
2417       }
2418       return true;
2419     }
2420   } else if (opc == Op_Add(exp_bt)) {
2421     jlong scale_l = 0;
2422     jlong scale_r = 0;
2423     bool short_scale_l = false;
2424     bool short_scale_r = false;
2425     if (depth == 0 &&
2426         is_scaled_iv(exp->in(1), iv, exp_bt, &scale_l, &short_scale_l, depth + 1) &&
2427         is_scaled_iv(exp->in(2), iv, exp_bt, &scale_r, &short_scale_r, depth + 1)) {
2428       // AddX(iv*K1, iv*K2) => iv*(K1+K2)
2429       jlong scale_sum = java_add(scale_l, scale_r);
2430       if (scale_sum > max_signed_integer(exp_bt) || scale_sum <= min_signed_integer(exp_bt)) {
2431         // This logic is shared by int and long. For int, the result may overflow
2432         // as we use jlong to compute so do the check here. Long result may also
2433         // overflow but that's fine because result wraps.
2434         return false;
2435       }
2436       if (p_scale != nullptr) {
2437         *p_scale = scale_sum;
2438       }
2439       if (p_short_scale != nullptr) {
2440         *p_short_scale = short_scale_l && short_scale_r;
2441       }
2442       return true;
2443     }
2444   } else if (opc == Op_Sub(exp_bt)) {
2445     if (exp->in(1)->find_integer_as_long(exp_bt, -1) == 0) {
2446       jlong scale = 0;
2447       if (depth == 0 && is_scaled_iv(exp->in(2), iv, exp_bt, &scale, p_short_scale, depth + 1)) {
2448         // SubX(0, iv*K) => iv*(-K)
2449         if (scale == min_signed_integer(exp_bt)) {
2450           // This should work even if -K overflows, but let's not.
2451           return false;
2452         }
2453         scale = java_multiply(scale, (jlong)-1);
2454         if (p_scale != nullptr) {
2455           *p_scale = scale;
2456         }
2457         if (p_short_scale != nullptr) {
2458           // (ConvI2L (MulI iv K)) can be 64-bit linear if iv is kept small enough...
2459           *p_short_scale = *p_short_scale || (exp_bt != bt && scale != 1);
2460         }
2461         return true;
2462       }
2463     } else {
2464       jlong scale_l = 0;
2465       jlong scale_r = 0;
2466       bool short_scale_l = false;
2467       bool short_scale_r = false;
2468       if (depth == 0 &&
2469           is_scaled_iv(exp->in(1), iv, exp_bt, &scale_l, &short_scale_l, depth + 1) &&
2470           is_scaled_iv(exp->in(2), iv, exp_bt, &scale_r, &short_scale_r, depth + 1)) {
2471         // SubX(iv*K1, iv*K2) => iv*(K1-K2)
2472         jlong scale_diff = java_subtract(scale_l, scale_r);
2473         if (scale_diff > max_signed_integer(exp_bt) || scale_diff <= min_signed_integer(exp_bt)) {
2474           // This logic is shared by int and long. For int, the result may
2475           // overflow as we use jlong to compute so do the check here. Long
2476           // result may also overflow but that's fine because result wraps.
2477           return false;
2478         }
2479         if (p_scale != nullptr) {
2480           *p_scale = scale_diff;
2481         }
2482         if (p_short_scale != nullptr) {
2483           *p_short_scale = short_scale_l && short_scale_r;
2484         }
2485         return true;
2486       }
2487     }
2488   }
2489   // We could also recognize (iv*K1)*K2, even with overflow, but let's not.
2490   return false;
2491 }
2492 
2493 //-------------------------is_scaled_iv_plus_offset--------------------------
2494 // Return true if exp is a simple linear transform of the given induction var.
2495 // The scale must be constant and the addition tree (if any) must be simple.
2496 // This grammar of cases is recognized, where X is I|L according to bt:
2497 //
2498 //    OIV[iv] = SIV[iv] | (CastXX OIV[iv])
2499 //            | (AddX SIV[iv] E) | (AddX E SIV[iv])
2500 //            | (SubX SIV[iv] E) | (SubX E SIV[iv])
2501 //    SSIV[iv] = (ConvI2X SIV[iv])  -- a "short scale" might occur here
2502 //    SIV[iv] = [a possibly scaled value of iv; see is_scaled_iv() above]
2503 //
2504 // On success, the constant scale value is stored back to *p_scale unless null.
2505 // Likewise, the addend (perhaps a synthetic AddX node) is stored to *p_offset.
2506 // Also, (*p_short_scale) reports if a ConvI2L conversion was seen after a MulI,
2507 // meaning bt is T_LONG but iv was scaled using 32-bit arithmetic.
2508 // To avoid looping, the match is depth-limited, and so may fail to match the grammar to complex expressions.
2509 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) {
2510   assert(bt == T_INT || bt == T_LONG, "unexpected int type");
2511   jlong scale = 0;  // to catch result from is_scaled_iv()
2512   BasicType exp_bt = bt;
2513   exp = exp->uncast();
2514   if (is_scaled_iv(exp, iv, exp_bt, &scale, p_short_scale)) {
2515     if (p_scale != nullptr) {
2516       *p_scale = scale;
2517     }
2518     if (p_offset != nullptr) {
2519       Node* zero = zerocon(bt);
2520       *p_offset = zero;
2521     }
2522     return true;
2523   }
2524   if (exp_bt != bt) {
2525     // We would now be matching inputs like (ConvI2L exp:(AddI (MulI iv S) E)).
2526     // It's hard to make 32-bit arithmetic linear if it overflows.  Although we do
2527     // cope with overflowing multiplication by S, it would be even more work to
2528     // handle overflowing addition of E.  So we bail out here on ConvI2L input.
2529     return false;
2530   }
2531   int opc = exp->Opcode();
2532   int which = 0;  // this is which subexpression we find the iv in
2533   Node* offset = nullptr;
2534   if (opc == Op_Add(exp_bt)) {
2535     // Check for a scaled IV in (AddX (MulX iv S) E) or (AddX E (MulX iv S)).
2536     if (is_scaled_iv(exp->in(which = 1), iv, bt, &scale, p_short_scale) ||
2537         is_scaled_iv(exp->in(which = 2), iv, bt, &scale, p_short_scale)) {
2538       offset = exp->in(which == 1 ? 2 : 1);  // the other argument
2539       if (p_scale != nullptr) {
2540         *p_scale = scale;
2541       }
2542       if (p_offset != nullptr) {
2543         *p_offset = offset;
2544       }
2545       return true;
2546     }
2547     // Check for more addends, like (AddX (AddX (MulX iv S) E1) E2), etc.
2548     if (is_scaled_iv_plus_extra_offset(exp->in(1), exp->in(2), iv, bt, p_scale, p_offset, p_short_scale, depth) ||
2549         is_scaled_iv_plus_extra_offset(exp->in(2), exp->in(1), iv, bt, p_scale, p_offset, p_short_scale, depth)) {
2550       return true;
2551     }
2552   } else if (opc == Op_Sub(exp_bt)) {
2553     if (is_scaled_iv(exp->in(which = 1), iv, bt, &scale, p_short_scale) ||
2554         is_scaled_iv(exp->in(which = 2), iv, bt, &scale, p_short_scale)) {
2555       // Match (SubX SIV[iv] E) as if (AddX SIV[iv] (SubX 0 E)), and
2556       // match (SubX E SIV[iv]) as if (AddX E (SubX 0 SIV[iv])).
2557       offset = exp->in(which == 1 ? 2 : 1);  // the other argument
2558       if (which == 2) {
2559         // We can't handle a scale of min_jint (or min_jlong) here as -1 * min_jint = min_jint
2560         if (scale == min_signed_integer(bt)) {
2561           return false;   // cannot negate the scale of the iv
2562         }
2563         scale = java_multiply(scale, (jlong)-1);
2564       }
2565       if (p_scale != nullptr) {
2566         *p_scale = scale;
2567       }
2568       if (p_offset != nullptr) {
2569         if (which == 1) {  // must negate the extracted offset
2570           Node* zero = integercon(0, exp_bt);
2571           Node *ctrl_off = get_ctrl(offset);
2572           offset = SubNode::make(zero, offset, exp_bt);
2573           register_new_node(offset, ctrl_off);
2574         }
2575         *p_offset = offset;
2576       }
2577       return true;
2578     }
2579   }
2580   return false;
2581 }
2582 
2583 // Helper for is_scaled_iv_plus_offset(), not called separately.
2584 // The caller encountered (AddX exp1 offset3) or (AddX offset3 exp1).
2585 // Here, exp1 is inspected to see if it is a simple linear transform of iv.
2586 // If so, the offset3 is combined with any other offset2 from inside exp1.
2587 bool PhaseIdealLoop::is_scaled_iv_plus_extra_offset(Node* exp1, Node* offset3, Node* iv,
2588                                                     BasicType bt,
2589                                                     jlong* p_scale, Node** p_offset,
2590                                                     bool* p_short_scale, int depth) {
2591   // By the time we reach here, it is unlikely that exp1 is a simple iv*K.
2592   // If is a linear iv transform, it is probably an add or subtract.
2593   // Let's collect the internal offset2 from it.
2594   Node* offset2 = nullptr;
2595   if (offset3->is_Con() &&
2596       depth < 2 &&
2597       is_scaled_iv_plus_offset(exp1, iv, bt, p_scale,
2598                                &offset2, p_short_scale, depth+1)) {
2599     if (p_offset != nullptr) {
2600       Node* ctrl_off2 = get_ctrl(offset2);
2601       Node* offset = AddNode::make(offset2, offset3, bt);
2602       register_new_node(offset, ctrl_off2);
2603       *p_offset = offset;
2604     }
2605     return true;
2606   }
2607   return false;
2608 }
2609 
2610 //------------------------------do_range_check---------------------------------
2611 // Eliminate range-checks and other trip-counter vs loop-invariant tests.
2612 void PhaseIdealLoop::do_range_check(IdealLoopTree* loop) {
2613 #ifndef PRODUCT
2614   if (TraceLoopOpts) {
2615     tty->print("RangeCheck   ");
2616     loop->dump_head();
2617   }
2618 #endif
2619 
2620   assert(RangeCheckElimination, "");
2621   CountedLoopNode *cl = loop->_head->as_CountedLoop();
2622 
2623   // protect against stride not being a constant
2624   if (!cl->stride_is_con()) {
2625     return;
2626   }
2627   // Find the trip counter; we are iteration splitting based on it
2628   Node *trip_counter = cl->phi();
2629   // Find the main loop limit; we will trim it's iterations
2630   // to not ever trip end tests
2631   Node *main_limit = cl->limit();
2632   Node* main_limit_ctrl = get_ctrl(main_limit);
2633 
2634   // Check graph shape. Cannot optimize a loop if zero-trip
2635   // Opaque1 node is optimized away and then another round
2636   // of loop opts attempted.
2637   if (cl->is_canonical_loop_entry() == nullptr) {
2638     return;
2639   }
2640 
2641   // Need to find the main-loop zero-trip guard
2642   Node *ctrl = cl->skip_assertion_predicates_with_halt();
2643   Node *iffm = ctrl->in(0);
2644   Node *opqzm = iffm->in(1)->in(1)->in(2);
2645   assert(opqzm->in(1) == main_limit, "do not understand situation");
2646 
2647   // Find the pre-loop limit; we will expand its iterations to
2648   // not ever trip low tests.
2649   Node *p_f = iffm->in(0);
2650   // pre loop may have been optimized out
2651   if (p_f->Opcode() != Op_IfFalse) {
2652     return;
2653   }
2654   CountedLoopEndNode *pre_end = p_f->in(0)->as_CountedLoopEnd();
2655   assert(pre_end->loopnode()->is_pre_loop(), "");
2656   Node *pre_opaq1 = pre_end->limit();
2657   // Occasionally it's possible for a pre-loop Opaque1 node to be
2658   // optimized away and then another round of loop opts attempted.
2659   // We can not optimize this particular loop in that case.
2660   if (pre_opaq1->Opcode() != Op_Opaque1) {
2661     return;
2662   }
2663   Opaque1Node *pre_opaq = (Opaque1Node*)pre_opaq1;
2664   Node *pre_limit = pre_opaq->in(1);
2665   Node* pre_limit_ctrl = get_ctrl(pre_limit);
2666 
2667   // Where do we put new limit calculations
2668   Node* pre_ctrl = pre_end->loopnode()->in(LoopNode::EntryControl);
2669   // Range check elimination optimizes out conditions whose parameters are loop invariant in the main loop. They usually
2670   // have control above the pre loop, but there's no guarantee that they do. There's no guarantee either that the pre
2671   // loop limit has control that's out of loop (a previous round of range check elimination could have set a limit that's
2672   // not loop invariant). new_limit_ctrl is used for both the pre and main loops. Early control for the main limit may be
2673   // below the pre loop entry and the pre limit and must be taken into account when initializing new_limit_ctrl.
2674   Node* new_limit_ctrl = dominated_node(pre_ctrl, pre_limit_ctrl, compute_early_ctrl(main_limit, main_limit_ctrl));
2675 
2676   // Ensure the original loop limit is available from the
2677   // pre-loop Opaque1 node.
2678   Node *orig_limit = pre_opaq->original_loop_limit();
2679   if (orig_limit == nullptr || _igvn.type(orig_limit) == Type::TOP) {
2680     return;
2681   }
2682   // Must know if its a count-up or count-down loop
2683 
2684   int stride_con = cl->stride_con();
2685   bool abs_stride_is_one = stride_con == 1 || stride_con == -1;
2686   Node* zero = longcon(0);
2687   Node* one  = longcon(1);
2688   // Use symmetrical int range [-max_jint,max_jint]
2689   Node* mini = longcon(-max_jint);
2690 
2691   Node* loop_entry = cl->skip_strip_mined()->in(LoopNode::EntryControl);
2692   assert(loop_entry->is_Proj() && loop_entry->in(0)->is_If(), "if projection only");
2693 
2694   // if abs(stride) == 1, an Assertion Predicate for the final iv value is added. We don't know the final iv value until
2695   // we're done with range check elimination so use a place holder.
2696   Node* final_iv_placeholder = nullptr;
2697   if (abs_stride_is_one) {
2698     final_iv_placeholder = new Node(1);
2699     _igvn.set_type(final_iv_placeholder, TypeInt::INT);
2700     final_iv_placeholder->init_req(0, loop_entry);
2701   }
2702 
2703   // Check loop body for tests of trip-counter plus loop-invariant vs loop-variant.
2704   for (uint i = 0; i < loop->_body.size(); i++) {
2705     Node *iff = loop->_body[i];
2706     if (iff->Opcode() == Op_If ||
2707         iff->Opcode() == Op_RangeCheck) { // Test?
2708       // Test is an IfNode, has 2 projections.  If BOTH are in the loop
2709       // we need loop unswitching instead of iteration splitting.
2710       Node *exit = loop->is_loop_exit(iff);
2711       if (!exit) continue;
2712       int flip = (exit->Opcode() == Op_IfTrue) ? 1 : 0;
2713 
2714       // Get boolean condition to test
2715       Node *i1 = iff->in(1);
2716       if (!i1->is_Bool()) continue;
2717       BoolNode *bol = i1->as_Bool();
2718       BoolTest b_test = bol->_test;
2719       // Flip sense of test if exit condition is flipped
2720       if (flip) {
2721         b_test = b_test.negate();
2722       }
2723       // Get compare
2724       Node *cmp = bol->in(1);
2725 
2726       // Look for trip_counter + offset vs limit
2727       Node *rc_exp = cmp->in(1);
2728       Node *limit  = cmp->in(2);
2729       int scale_con= 1;        // Assume trip counter not scaled
2730 
2731       Node* limit_ctrl = get_ctrl(limit);
2732       if (loop->is_member(get_loop(limit_ctrl))) {
2733         // Compare might have operands swapped; commute them
2734         b_test = b_test.commute();
2735         rc_exp = cmp->in(2);
2736         limit  = cmp->in(1);
2737         limit_ctrl = get_ctrl(limit);
2738         if (loop->is_member(get_loop(limit_ctrl))) {
2739           continue;             // Both inputs are loop varying; cannot RCE
2740         }
2741       }
2742       // Here we know 'limit' is loop invariant
2743 
2744       // 'limit' maybe pinned below the zero trip test (probably from a
2745       // previous round of rce), in which case, it can't be used in the
2746       // zero trip test expression which must occur before the zero test's if.
2747       if (is_dominator(ctrl, limit_ctrl)) {
2748         continue;  // Don't rce this check but continue looking for other candidates.
2749       }
2750 
2751       assert(is_dominator(compute_early_ctrl(limit, limit_ctrl), pre_end), "node pinned on loop exit test?");
2752 
2753       // Check for scaled induction variable plus an offset
2754       Node *offset = nullptr;
2755 
2756       if (!is_scaled_iv_plus_offset(rc_exp, trip_counter, &scale_con, &offset)) {
2757         continue;
2758       }
2759 
2760       Node* offset_ctrl = get_ctrl(offset);
2761       if (loop->is_member(get_loop(offset_ctrl))) {
2762         continue;               // Offset is not really loop invariant
2763       }
2764       // Here we know 'offset' is loop invariant.
2765 
2766       // As above for the 'limit', the 'offset' maybe pinned below the
2767       // zero trip test.
2768       if (is_dominator(ctrl, offset_ctrl)) {
2769         continue; // Don't rce this check but continue looking for other candidates.
2770       }
2771 
2772       // offset and limit can have control set below the pre loop when they are not loop invariant in the pre loop.
2773       // Update their control (and the control of inputs as needed) to be above pre_end
2774       offset_ctrl = ensure_node_and_inputs_are_above_pre_end(pre_end, offset);
2775       limit_ctrl = ensure_node_and_inputs_are_above_pre_end(pre_end, limit);
2776 
2777       // offset and limit could have control below new_limit_ctrl if they are not loop invariant in the pre loop.
2778       Node* next_limit_ctrl = dominated_node(new_limit_ctrl, offset_ctrl, limit_ctrl);
2779 
2780 #ifdef ASSERT
2781       if (TraceRangeLimitCheck) {
2782         tty->print_cr("RC bool node%s", flip ? " flipped:" : ":");
2783         bol->dump(2);
2784       }
2785 #endif
2786       // At this point we have the expression as:
2787       //   scale_con * trip_counter + offset :: limit
2788       // where scale_con, offset and limit are loop invariant.  Trip_counter
2789       // monotonically increases by stride_con, a constant.  Both (or either)
2790       // stride_con and scale_con can be negative which will flip about the
2791       // sense of the test.
2792 
2793       C->print_method(PHASE_BEFORE_RANGE_CHECK_ELIMINATION, 4, iff);
2794 
2795       // Perform the limit computations in jlong to avoid overflow
2796       jlong lscale_con = scale_con;
2797       Node* int_offset = offset;
2798       offset = new ConvI2LNode(offset);
2799       register_new_node(offset, next_limit_ctrl);
2800       Node* int_limit = limit;
2801       limit = new ConvI2LNode(limit);
2802       register_new_node(limit, next_limit_ctrl);
2803 
2804       // Adjust pre and main loop limits to guard the correct iteration set
2805       if (cmp->Opcode() == Op_CmpU) { // Unsigned compare is really 2 tests
2806         if (b_test._test == BoolTest::lt) { // Range checks always use lt
2807           // The underflow and overflow limits: 0 <= scale*I+offset < limit
2808           add_constraint(stride_con, lscale_con, offset, zero, limit, next_limit_ctrl, &pre_limit, &main_limit);
2809           Node* init = cl->uncasted_init_trip(true);
2810 
2811           Node* opaque_init = new OpaqueLoopInitNode(C, init);
2812           register_new_node(opaque_init, loop_entry);
2813 
2814           InitializedAssertionPredicateCreator initialized_assertion_predicate_creator(this);
2815           if (abs_stride_is_one) {
2816             // If the main loop becomes empty and the array access for this range check is sunk out of the loop, the index
2817             // for the array access will be set to the index value of the final iteration which could be out of loop.
2818             // Add an Initialized Assertion Predicate for that corner case. The final iv is computed from LoopLimit which
2819             // is the LoopNode::limit() only if abs(stride) == 1 otherwise the computation depends on LoopNode::init_trip()
2820             // as well. When LoopLimit only depends on LoopNode::limit(), there are cases where the zero trip guard for
2821             // the main loop doesn't constant fold after range check elimination but, the array access for the final
2822             // iteration of the main loop is out of bound and the index for that access is out of range for the range
2823             // check CastII.
2824             // Note that we do not need to emit a Template Assertion Predicate to update this predicate. When further
2825             // splitting this loop, the final IV will still be the same. When unrolling the loop, we will remove a
2826             // previously added Initialized Assertion Predicate here. But then abs(stride) is greater than 1, and we
2827             // cannot remove an empty loop with a constant limit when init is not a constant as well. We will use
2828             // a LoopLimitCheck node that can only be folded if the zero grip guard is also foldable.
2829             loop_entry = initialized_assertion_predicate_creator.create(final_iv_placeholder, loop_entry, stride_con,
2830                                                                         scale_con, int_offset, int_limit,
2831                                                                         AssertionPredicateType::FinalIv);
2832           }
2833 
2834           // Add two Template Assertion Predicates to create new Initialized Assertion Predicates from when either
2835           // unrolling or splitting this main-loop further.
2836           TemplateAssertionPredicateCreator template_assertion_predicate_creator(cl, scale_con , int_offset, int_limit,
2837                                                                                  this);
2838           loop_entry = template_assertion_predicate_creator.create(loop_entry);
2839 
2840           // Initialized Assertion Predicate for the value of the initial main-loop.
2841           loop_entry = initialized_assertion_predicate_creator.create(init, loop_entry, stride_con, scale_con,
2842                                                                       int_offset, int_limit,
2843                                                                       AssertionPredicateType::InitValue);
2844 
2845         } else {
2846           if (PrintOpto) {
2847             tty->print_cr("missed RCE opportunity");
2848           }
2849           continue;             // In release mode, ignore it
2850         }
2851       } else {                  // Otherwise work on normal compares
2852         switch(b_test._test) {
2853         case BoolTest::gt:
2854           // Fall into GE case
2855         case BoolTest::ge:
2856           // Convert (I*scale+offset) >= Limit to (I*(-scale)+(-offset)) <= -Limit
2857           lscale_con = -lscale_con;
2858           offset = new SubLNode(zero, offset);
2859           register_new_node(offset, next_limit_ctrl);
2860           limit  = new SubLNode(zero, limit);
2861           register_new_node(limit, next_limit_ctrl);
2862           // Fall into LE case
2863         case BoolTest::le:
2864           if (b_test._test != BoolTest::gt) {
2865             // Convert X <= Y to X < Y+1
2866             limit = new AddLNode(limit, one);
2867             register_new_node(limit, next_limit_ctrl);
2868           }
2869           // Fall into LT case
2870         case BoolTest::lt:
2871           // The underflow and overflow limits: MIN_INT <= scale*I+offset < limit
2872           // Note: (MIN_INT+1 == -MAX_INT) is used instead of MIN_INT here
2873           // to avoid problem with scale == -1: MIN_INT/(-1) == MIN_INT.
2874           add_constraint(stride_con, lscale_con, offset, mini, limit, next_limit_ctrl, &pre_limit, &main_limit);
2875           break;
2876         default:
2877           if (PrintOpto) {
2878             tty->print_cr("missed RCE opportunity");
2879           }
2880           continue;             // Unhandled case
2881         }
2882       }
2883       // Only update variable tracking control for new nodes if it's indeed a range check that can be eliminated (and
2884       // limits are updated)
2885       new_limit_ctrl = next_limit_ctrl;
2886 
2887       // Kill the eliminated test
2888       C->set_major_progress();
2889       Node* kill_con = intcon(1-flip);
2890       _igvn.replace_input_of(iff, 1, kill_con);
2891       // Find surviving projection
2892       assert(iff->is_If(), "");
2893       ProjNode* dp = ((IfNode*)iff)->proj_out(1-flip);
2894       // Find loads off the surviving projection; remove their control edge
2895       for (DUIterator_Fast imax, i = dp->fast_outs(imax); i < imax; i++) {
2896         Node* cd = dp->fast_out(i); // Control-dependent node
2897         if (cd->is_Load() && cd->depends_only_on_test()) {   // Loads can now float around in the loop
2898           // Allow the load to float around in the loop, or before it
2899           // but NOT before the pre-loop.
2900           _igvn.replace_input_of(cd, 0, ctrl); // ctrl, not null
2901           --i;
2902           --imax;
2903         }
2904       }
2905     } // End of is IF
2906   }
2907   if (loop_entry != cl->skip_strip_mined()->in(LoopNode::EntryControl)) {
2908     _igvn.replace_input_of(cl->skip_strip_mined(), LoopNode::EntryControl, loop_entry);
2909     set_idom(cl->skip_strip_mined(), loop_entry, dom_depth(cl->skip_strip_mined()));
2910   }
2911 
2912   // Update loop limits
2913   if (pre_limit != orig_limit) {
2914     // Computed pre-loop limit can be outside of loop iterations range.
2915     pre_limit = (stride_con > 0) ? (Node*)new MinINode(pre_limit, orig_limit)
2916                                  : (Node*)new MaxINode(pre_limit, orig_limit);
2917     register_new_node(pre_limit, new_limit_ctrl);
2918   }
2919   // new pre_limit can push Bool/Cmp/Opaque nodes down (when one of the eliminated condition has parameters that are not
2920   // loop invariant in the pre loop.
2921   set_ctrl(pre_opaq, new_limit_ctrl);
2922   // Can't use new_limit_ctrl for Bool/Cmp because it can be out of loop while they are loop variant. Conservatively set
2923   // control to latest possible one.
2924   set_ctrl(pre_end->cmp_node(), pre_end->in(0));
2925   set_ctrl(pre_end->in(1), pre_end->in(0));
2926 
2927   _igvn.replace_input_of(pre_opaq, 1, pre_limit);
2928 
2929   // Note:: we are making the main loop limit no longer precise;
2930   // need to round up based on stride.
2931   cl->set_nonexact_trip_count();
2932   Node *main_cle = cl->loopexit();
2933   Node *main_bol = main_cle->in(1);
2934   // Hacking loop bounds; need private copies of exit test
2935   if (main_bol->outcnt() > 1) {     // BoolNode shared?
2936     main_bol = main_bol->clone();   // Clone a private BoolNode
2937     register_new_node(main_bol, main_cle->in(0));
2938     _igvn.replace_input_of(main_cle, 1, main_bol);
2939   }
2940   Node *main_cmp = main_bol->in(1);
2941   if (main_cmp->outcnt() > 1) {     // CmpNode shared?
2942     main_cmp = main_cmp->clone();   // Clone a private CmpNode
2943     register_new_node(main_cmp, main_cle->in(0));
2944     _igvn.replace_input_of(main_bol, 1, main_cmp);
2945   }
2946   assert(main_limit == cl->limit() || get_ctrl(main_limit) == new_limit_ctrl, "wrong control for added limit");
2947   const TypeInt* orig_limit_t = _igvn.type(orig_limit)->is_int();
2948   bool upward = cl->stride_con() > 0;
2949   // The new loop limit is <= (for an upward loop) >= (for a downward loop) than the orig limit.
2950   // The expression that computes the new limit may be too complicated and the computed type of the new limit
2951   // may be too pessimistic. A CastII here guarantees it's not lost.
2952   main_limit = new CastIINode(pre_ctrl, main_limit, TypeInt::make(upward ? min_jint : orig_limit_t->_lo,
2953                                                         upward ? orig_limit_t->_hi : max_jint, Type::WidenMax));
2954   register_new_node(main_limit, new_limit_ctrl);
2955   // Hack the now-private loop bounds
2956   _igvn.replace_input_of(main_cmp, 2, main_limit);
2957   if (abs_stride_is_one) {
2958     Node* final_iv = new SubINode(main_limit, cl->stride());
2959     register_new_node(final_iv, loop_entry);
2960     _igvn.replace_node(final_iv_placeholder, final_iv);
2961   }
2962   // The OpaqueNode is unshared by design
2963   assert(opqzm->outcnt() == 1, "cannot hack shared node");
2964   _igvn.replace_input_of(opqzm, 1, main_limit);
2965   // new main_limit can push opaque node for zero trip guard down (when one of the eliminated condition has parameters
2966   // that are not loop invariant in the pre loop).
2967   set_ctrl(opqzm, new_limit_ctrl);
2968   // Bool/Cmp nodes for zero trip guard should have been assigned control between the main and pre loop (because zero
2969   // trip guard depends on induction variable value out of pre loop) so shouldn't need to be adjusted
2970   assert(is_dominator(new_limit_ctrl, get_ctrl(iffm->in(1)->in(1))), "control of cmp should be below control of updated input");
2971 
2972   C->print_method(PHASE_AFTER_RANGE_CHECK_ELIMINATION, 4, cl);
2973 }
2974 
2975 // Adjust control for node and its inputs (and inputs of its inputs) to be above the pre end
2976 Node* PhaseIdealLoop::ensure_node_and_inputs_are_above_pre_end(CountedLoopEndNode* pre_end, Node* node) {
2977   Node* control = get_ctrl(node);
2978   assert(is_dominator(compute_early_ctrl(node, control), pre_end), "node pinned on loop exit test?");
2979 
2980   if (is_dominator(control, pre_end)) {
2981     return control;
2982   }
2983   control = pre_end->in(0);
2984   ResourceMark rm;
2985   Unique_Node_List wq;
2986   wq.push(node);
2987   for (uint i = 0; i < wq.size(); i++) {
2988     Node* n = wq.at(i);
2989     assert(is_dominator(compute_early_ctrl(n, get_ctrl(n)), pre_end), "node pinned on loop exit test?");
2990     set_ctrl(n, control);
2991     for (uint j = 0; j < n->req(); j++) {
2992       Node* in = n->in(j);
2993       if (in != nullptr && has_ctrl(in) && !is_dominator(get_ctrl(in), pre_end)) {
2994         wq.push(in);
2995       }
2996     }
2997   }
2998   return control;
2999 }
3000 
3001 bool IdealLoopTree::compute_has_range_checks() const {
3002   assert(_head->is_CountedLoop(), "");
3003   for (uint i = 0; i < _body.size(); i++) {
3004     Node *iff = _body[i];
3005     int iff_opc = iff->Opcode();
3006     if (iff_opc == Op_If || iff_opc == Op_RangeCheck) {
3007       return true;
3008     }
3009   }
3010   return false;
3011 }
3012 
3013 //------------------------------DCE_loop_body----------------------------------
3014 // Remove simplistic dead code from loop body
3015 void IdealLoopTree::DCE_loop_body() {
3016   for (uint i = 0; i < _body.size(); i++) {
3017     if (_body.at(i)->outcnt() == 0) {
3018       _body.map(i, _body.pop());
3019       i--; // Ensure we revisit the updated index.
3020     }
3021   }
3022 }
3023 
3024 
3025 //------------------------------adjust_loop_exit_prob--------------------------
3026 // Look for loop-exit tests with the 50/50 (or worse) guesses from the parsing stage.
3027 // Replace with a 1-in-10 exit guess.
3028 void IdealLoopTree::adjust_loop_exit_prob(PhaseIdealLoop *phase) {
3029   Node *test = tail();
3030   while (test != _head) {
3031     uint top = test->Opcode();
3032     if (top == Op_IfTrue || top == Op_IfFalse) {
3033       int test_con = ((ProjNode*)test)->_con;
3034       assert(top == (uint)(test_con? Op_IfTrue: Op_IfFalse), "sanity");
3035       IfNode *iff = test->in(0)->as_If();
3036       if (iff->outcnt() == 2) {         // Ignore dead tests
3037         Node *bol = iff->in(1);
3038         if (bol && bol->req() > 1 && bol->in(1) &&
3039             ((bol->in(1)->Opcode() == Op_CompareAndExchangeB) ||
3040              (bol->in(1)->Opcode() == Op_CompareAndExchangeS) ||
3041              (bol->in(1)->Opcode() == Op_CompareAndExchangeI) ||
3042              (bol->in(1)->Opcode() == Op_CompareAndExchangeL) ||
3043              (bol->in(1)->Opcode() == Op_CompareAndExchangeP) ||
3044              (bol->in(1)->Opcode() == Op_CompareAndExchangeN) ||
3045              (bol->in(1)->Opcode() == Op_WeakCompareAndSwapB) ||
3046              (bol->in(1)->Opcode() == Op_WeakCompareAndSwapS) ||
3047              (bol->in(1)->Opcode() == Op_WeakCompareAndSwapI) ||
3048              (bol->in(1)->Opcode() == Op_WeakCompareAndSwapL) ||
3049              (bol->in(1)->Opcode() == Op_WeakCompareAndSwapP) ||
3050              (bol->in(1)->Opcode() == Op_WeakCompareAndSwapN) ||
3051              (bol->in(1)->Opcode() == Op_CompareAndSwapB) ||
3052              (bol->in(1)->Opcode() == Op_CompareAndSwapS) ||
3053              (bol->in(1)->Opcode() == Op_CompareAndSwapI) ||
3054              (bol->in(1)->Opcode() == Op_CompareAndSwapL) ||
3055              (bol->in(1)->Opcode() == Op_CompareAndSwapP) ||
3056              (bol->in(1)->Opcode() == Op_CompareAndSwapN) ||
3057              (bol->in(1)->Opcode() == Op_ShenandoahCompareAndExchangeP) ||
3058              (bol->in(1)->Opcode() == Op_ShenandoahCompareAndExchangeN) ||
3059              (bol->in(1)->Opcode() == Op_ShenandoahWeakCompareAndSwapP) ||
3060              (bol->in(1)->Opcode() == Op_ShenandoahWeakCompareAndSwapN) ||
3061              (bol->in(1)->Opcode() == Op_ShenandoahCompareAndSwapP) ||
3062              (bol->in(1)->Opcode() == Op_ShenandoahCompareAndSwapN)))
3063           return;               // Allocation loops RARELY take backedge
3064         // Find the OTHER exit path from the IF
3065         Node* ex = iff->proj_out(1-test_con);
3066         float p = iff->_prob;
3067         if (!phase->is_member(this, ex) && iff->_fcnt == COUNT_UNKNOWN) {
3068           if (top == Op_IfTrue) {
3069             if (p < (PROB_FAIR + PROB_UNLIKELY_MAG(3))) {
3070               iff->_prob = PROB_STATIC_FREQUENT;
3071             }
3072           } else {
3073             if (p > (PROB_FAIR - PROB_UNLIKELY_MAG(3))) {
3074               iff->_prob = PROB_STATIC_INFREQUENT;
3075             }
3076           }
3077         }
3078       }
3079     }
3080     test = phase->idom(test);
3081   }
3082 }
3083 
3084 static CountedLoopNode* locate_pre_from_main(CountedLoopNode* main_loop) {
3085   assert(!main_loop->is_main_no_pre_loop(), "Does not have a pre loop");
3086   Node* ctrl = main_loop->skip_assertion_predicates_with_halt();
3087   assert(ctrl->Opcode() == Op_IfTrue || ctrl->Opcode() == Op_IfFalse, "");
3088   Node* iffm = ctrl->in(0);
3089   assert(iffm->Opcode() == Op_If, "");
3090   Node* p_f = iffm->in(0);
3091   assert(p_f->Opcode() == Op_IfFalse, "");
3092   CountedLoopNode* pre_loop = p_f->in(0)->as_CountedLoopEnd()->loopnode();
3093   assert(pre_loop->is_pre_loop(), "No pre loop found");
3094   return pre_loop;
3095 }
3096 
3097 // Remove the main and post loops and make the pre loop execute all
3098 // iterations. Useful when the pre loop is found empty.
3099 void IdealLoopTree::remove_main_post_loops(CountedLoopNode *cl, PhaseIdealLoop *phase) {
3100   CountedLoopEndNode* pre_end = cl->loopexit();
3101   Node* pre_cmp = pre_end->cmp_node();
3102   if (pre_cmp->in(2)->Opcode() != Op_Opaque1) {
3103     // Only safe to remove the main loop if the compiler optimized it
3104     // out based on an unknown number of iterations
3105     return;
3106   }
3107 
3108   // Can we find the main loop?
3109   if (_next == nullptr) {
3110     return;
3111   }
3112 
3113   Node* next_head = _next->_head;
3114   if (!next_head->is_CountedLoop()) {
3115     return;
3116   }
3117 
3118   CountedLoopNode* main_head = next_head->as_CountedLoop();
3119   if (!main_head->is_main_loop() || main_head->is_main_no_pre_loop()) {
3120     return;
3121   }
3122 
3123   // We found a main-loop after this pre-loop, but they might not belong together.
3124   if (locate_pre_from_main(main_head) != cl) {
3125     return;
3126   }
3127 
3128   Node* main_iff = main_head->skip_assertion_predicates_with_halt()->in(0);
3129 
3130   // Remove the Opaque1Node of the pre loop and make it execute all iterations
3131   phase->_igvn.replace_input_of(pre_cmp, 2, pre_cmp->in(2)->in(2));
3132   // Remove the OpaqueZeroTripGuardNode of the main loop so it can be optimized out
3133   Node* main_cmp = main_iff->in(1)->in(1);
3134   assert(main_cmp->in(2)->Opcode() == Op_OpaqueZeroTripGuard, "main loop has no opaque node?");
3135   phase->_igvn.replace_input_of(main_cmp, 2, main_cmp->in(2)->in(1));
3136 }
3137 
3138 //------------------------------do_remove_empty_loop---------------------------
3139 // We always attempt remove empty loops.   The approach is to replace the trip
3140 // counter with the value it will have on the last iteration.  This will break
3141 // the loop.
3142 bool IdealLoopTree::do_remove_empty_loop(PhaseIdealLoop *phase) {
3143   if (!_head->is_CountedLoop()) {
3144     return false;   // Dead loop
3145   }
3146   if (!empty_loop_candidate(phase)) {
3147     return false;
3148   }
3149   CountedLoopNode *cl = _head->as_CountedLoop();
3150 #ifdef ASSERT
3151   // Call collect_loop_core_nodes to exercise the assert that checks that it finds the right number of nodes
3152   if (empty_loop_with_extra_nodes_candidate(phase)) {
3153     Unique_Node_List wq;
3154     collect_loop_core_nodes(phase, wq);
3155   }
3156 #endif
3157   // Minimum size must be empty loop
3158   if (_body.size() > EMPTY_LOOP_SIZE) {
3159     // This loop has more nodes than an empty loop but, maybe they are only kept alive by the outer strip mined loop's
3160     // safepoint. If they go away once the safepoint is removed, that loop is empty.
3161     if (!empty_loop_with_data_nodes(phase)) {
3162       return false;
3163     }
3164   }
3165   phase->C->print_method(PHASE_BEFORE_REMOVE_EMPTY_LOOP, 4, cl);
3166   if (cl->is_pre_loop()) {
3167     // If the loop we are removing is a pre-loop then the main and post loop
3168     // can be removed as well.
3169     remove_main_post_loops(cl, phase);
3170   }
3171 
3172 #ifdef ASSERT
3173   // Ensure at most one used phi exists, which is the iv.
3174   Node* iv = nullptr;
3175   for (DUIterator_Fast imax, i = cl->fast_outs(imax); i < imax; i++) {
3176     Node* n = cl->fast_out(i);
3177     if ((n->Opcode() == Op_Phi) && (n->outcnt() > 0)) {
3178       assert(iv == nullptr, "Too many phis");
3179       iv = n;
3180     }
3181   }
3182   assert(iv == cl->phi(), "Wrong phi");
3183 #endif
3184 
3185   // main and post loops have explicitly created zero trip guard
3186   bool needs_guard = !cl->is_main_loop() && !cl->is_post_loop();
3187   if (needs_guard) {
3188     // Skip guard if values not overlap.
3189     const TypeInt* init_t = phase->_igvn.type(cl->init_trip())->is_int();
3190     const TypeInt* limit_t = phase->_igvn.type(cl->limit())->is_int();
3191     int  stride_con = cl->stride_con();
3192     if (stride_con > 0) {
3193       needs_guard = (init_t->_hi >= limit_t->_lo);
3194     } else {
3195       needs_guard = (init_t->_lo <= limit_t->_hi);
3196     }
3197   }
3198   if (needs_guard) {
3199     // Check for an obvious zero trip guard.
3200     Predicates predicates(cl->skip_strip_mined()->in(LoopNode::EntryControl));
3201     Node* in_ctrl = predicates.entry();
3202     if (in_ctrl->Opcode() == Op_IfTrue || in_ctrl->Opcode() == Op_IfFalse) {
3203       bool maybe_swapped = (in_ctrl->Opcode() == Op_IfFalse);
3204       // The test should look like just the backedge of a CountedLoop
3205       Node* iff = in_ctrl->in(0);
3206       if (iff->is_If()) {
3207         Node* bol = iff->in(1);
3208         if (bol->is_Bool()) {
3209           BoolTest test = bol->as_Bool()->_test;
3210           if (maybe_swapped) {
3211             test._test = test.commute();
3212             test._test = test.negate();
3213           }
3214           if (test._test == cl->loopexit()->test_trip()) {
3215             Node* cmp = bol->in(1);
3216             int init_idx = maybe_swapped ? 2 : 1;
3217             int limit_idx = maybe_swapped ? 1 : 2;
3218             if (cmp->is_Cmp() && cmp->in(init_idx) == cl->init_trip() && cmp->in(limit_idx) == cl->limit()) {
3219               needs_guard = false;
3220             }
3221           }
3222         }
3223       }
3224     }
3225   }
3226 
3227 #ifndef PRODUCT
3228   if (PrintOpto) {
3229     tty->print("Removing empty loop with%s zero trip guard", needs_guard ? "out" : "");
3230     this->dump_head();
3231   } else if (TraceLoopOpts) {
3232     tty->print("Empty with%s zero trip guard   ", needs_guard ? "out" : "");
3233     this->dump_head();
3234   }
3235 #endif
3236 
3237   if (needs_guard) {
3238     // Peel the loop to ensure there's a zero trip guard
3239     Node_List old_new;
3240     phase->do_peeling(this, old_new);
3241   }
3242 
3243   // Replace the phi at loop head with the final value of the last
3244   // iteration (exact_limit - stride), to make sure the loop exit value
3245   // is correct, for any users after the loop.
3246   // Note: the final value after increment should not overflow since
3247   // counted loop has limit check predicate.
3248   Node* phi = cl->phi();
3249   Node* exact_limit = phase->exact_limit(this);
3250 
3251   // We need to pin the exact limit to prevent it from floating above the zero trip guard.
3252   Node* cast_ii = ConstraintCastNode::make_cast_for_basic_type(
3253       cl->in(LoopNode::EntryControl), exact_limit,
3254       phase->_igvn.type(exact_limit),
3255       ConstraintCastNode::UnconditionalDependency, T_INT);
3256   phase->register_new_node(cast_ii, cl->in(LoopNode::EntryControl));
3257 
3258   Node* final_iv = new SubINode(cast_ii, cl->stride());
3259   phase->register_new_node(final_iv, cl->in(LoopNode::EntryControl));
3260   phase->_igvn.replace_node(phi, final_iv);
3261 
3262   // Set loop-exit condition to false. Then the CountedLoopEnd will collapse,
3263   // because the back edge is never taken.
3264   Node* zero = phase->_igvn.intcon(0);
3265   phase->_igvn.replace_input_of(cl->loopexit(), CountedLoopEndNode::TestValue, zero);
3266 
3267   phase->C->set_major_progress();
3268   phase->C->print_method(PHASE_AFTER_REMOVE_EMPTY_LOOP, 4, final_iv);
3269   return true;
3270 }
3271 
3272 bool IdealLoopTree::empty_loop_candidate(PhaseIdealLoop* phase) const {
3273   CountedLoopNode *cl = _head->as_CountedLoop();
3274   if (!cl->is_valid_counted_loop(T_INT)) {
3275     return false;   // Malformed loop
3276   }
3277   if (!phase->is_member(this, phase->get_ctrl(cl->loopexit()->in(CountedLoopEndNode::TestValue)))) {
3278     return false;   // Infinite loop
3279   }
3280   return true;
3281 }
3282 
3283 bool IdealLoopTree::empty_loop_with_data_nodes(PhaseIdealLoop* phase) const {
3284   CountedLoopNode* cl = _head->as_CountedLoop();
3285   if (!cl->is_strip_mined() || !empty_loop_with_extra_nodes_candidate(phase)) {
3286     return false;
3287   }
3288   Unique_Node_List empty_loop_nodes;
3289   Unique_Node_List wq;
3290 
3291   // Start from all data nodes in the loop body that are not one of the EMPTY_LOOP_SIZE nodes expected in an empty body
3292   enqueue_data_nodes(phase, empty_loop_nodes, wq);
3293   // and now follow uses
3294   for (uint i = 0; i < wq.size(); ++i) {
3295     Node* n = wq.at(i);
3296     for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++) {
3297       Node* u = n->fast_out(j);
3298       if (u->Opcode() == Op_SafePoint) {
3299         // found a safepoint. Maybe this loop's safepoint or another loop safepoint.
3300         if (!process_safepoint(phase, empty_loop_nodes, wq, u)) {
3301           return false;
3302         }
3303       } else {
3304         const Type* u_t = phase->_igvn.type(u);
3305         if (u_t == Type::CONTROL || u_t == Type::MEMORY || u_t == Type::ABIO) {
3306           // found a side effect
3307           return false;
3308         }
3309         wq.push(u);
3310       }
3311     }
3312   }
3313   // Nodes (ignoring the EMPTY_LOOP_SIZE nodes of the "core" of the loop) are kept alive by otherwise empty loops'
3314   // safepoints: kill them.
3315   for (uint i = 0; i < wq.size(); ++i) {
3316     Node* n = wq.at(i);
3317     phase->_igvn.replace_node(n, phase->C->top());
3318   }
3319 
3320 #ifdef ASSERT
3321   for (uint i = 0; i < _body.size(); ++i) {
3322     Node* n = _body.at(i);
3323     assert(wq.member(n) || empty_loop_nodes.member(n), "missed a node in the body?");
3324   }
3325 #endif
3326 
3327   return true;
3328 }
3329 
3330 bool IdealLoopTree::process_safepoint(PhaseIdealLoop* phase, Unique_Node_List& empty_loop_nodes, Unique_Node_List& wq,
3331                                       Node* sfpt) const {
3332   CountedLoopNode* cl = _head->as_CountedLoop();
3333   if (cl->outer_safepoint() == sfpt) {
3334     // the current loop's safepoint
3335     return true;
3336   }
3337 
3338   // Some other loop's safepoint. Maybe that loop is empty too.
3339   IdealLoopTree* sfpt_loop = phase->get_loop(sfpt);
3340   if (!sfpt_loop->_head->is_OuterStripMinedLoop()) {
3341     return false;
3342   }
3343   IdealLoopTree* sfpt_inner_loop = sfpt_loop->_child;
3344   CountedLoopNode* sfpt_cl = sfpt_inner_loop->_head->as_CountedLoop();
3345   assert(sfpt_cl->is_strip_mined(), "inconsistent");
3346 
3347   if (empty_loop_nodes.member(sfpt_cl)) {
3348     // already taken care of
3349     return true;
3350   }
3351 
3352   if (!sfpt_inner_loop->empty_loop_candidate(phase) || !sfpt_inner_loop->empty_loop_with_extra_nodes_candidate(phase)) {
3353     return false;
3354   }
3355 
3356   // Enqueue the nodes of that loop for processing too
3357   sfpt_inner_loop->enqueue_data_nodes(phase, empty_loop_nodes, wq);
3358   return true;
3359 }
3360 
3361 bool IdealLoopTree::empty_loop_with_extra_nodes_candidate(PhaseIdealLoop* phase) const {
3362   CountedLoopNode *cl = _head->as_CountedLoop();
3363   // No other control flow node in the loop body
3364   if (cl->loopexit()->in(0) != cl) {
3365     return false;
3366   }
3367 
3368   if (phase->is_member(this, phase->get_ctrl(cl->limit()))) {
3369     return false;
3370   }
3371   return true;
3372 }
3373 
3374 void IdealLoopTree::enqueue_data_nodes(PhaseIdealLoop* phase, Unique_Node_List& empty_loop_nodes,
3375                                        Unique_Node_List& wq) const {
3376   collect_loop_core_nodes(phase, empty_loop_nodes);
3377   for (uint i = 0; i < _body.size(); ++i) {
3378     Node* n = _body.at(i);
3379     if (!empty_loop_nodes.member(n)) {
3380       wq.push(n);
3381     }
3382   }
3383 }
3384 
3385 // This collects the node that would be left if this body was empty
3386 void IdealLoopTree::collect_loop_core_nodes(PhaseIdealLoop* phase, Unique_Node_List& wq) const {
3387   uint before = wq.size();
3388   wq.push(_head->in(LoopNode::LoopBackControl));
3389   for (uint i = before; i < wq.size(); ++i) {
3390     Node* n = wq.at(i);
3391     for (uint j = 0; j < n->req(); ++j) {
3392       Node* in = n->in(j);
3393       if (in != nullptr) {
3394         if (phase->get_loop(phase->ctrl_or_self(in)) == this) {
3395           wq.push(in);
3396         }
3397       }
3398     }
3399   }
3400   assert(wq.size() - before == EMPTY_LOOP_SIZE, "expect the EMPTY_LOOP_SIZE nodes of this body if empty");
3401 }
3402 
3403 //------------------------------do_one_iteration_loop--------------------------
3404 // Convert one-iteration loop into normal code.
3405 bool IdealLoopTree::do_one_iteration_loop(PhaseIdealLoop *phase) {
3406   if (!_head->as_Loop()->is_valid_counted_loop(T_INT)) {
3407     return false; // Only for counted loop
3408   }
3409   CountedLoopNode *cl = _head->as_CountedLoop();
3410   if (!cl->has_exact_trip_count() || cl->trip_count() != 1) {
3411     return false;
3412   }
3413 
3414 #ifndef PRODUCT
3415   if (TraceLoopOpts) {
3416     tty->print("OneIteration ");
3417     this->dump_head();
3418   }
3419 #endif
3420 
3421   phase->C->print_method(PHASE_BEFORE_ONE_ITERATION_LOOP, 4, cl);
3422   Node *init_n = cl->init_trip();
3423   // Loop boundaries should be constant since trip count is exact.
3424   assert((cl->stride_con() > 0 && init_n->get_int() + cl->stride_con() >= cl->limit()->get_int()) ||
3425          (cl->stride_con() < 0 && init_n->get_int() + cl->stride_con() <= cl->limit()->get_int()), "should be one iteration");
3426   // Replace the phi at loop head with the value of the init_trip.
3427   // Then the CountedLoopEnd will collapse (backedge will not be taken)
3428   // and all loop-invariant uses of the exit values will be correct.
3429   phase->_igvn.replace_node(cl->phi(), cl->init_trip());
3430   phase->C->set_major_progress();
3431   phase->C->print_method(PHASE_AFTER_ONE_ITERATION_LOOP, 4, init_n);
3432   return true;
3433 }
3434 
3435 //=============================================================================
3436 //------------------------------iteration_split_impl---------------------------
3437 bool IdealLoopTree::iteration_split_impl(PhaseIdealLoop *phase, Node_List &old_new) {
3438   if (!_head->is_Loop()) {
3439     // Head could be a region with a NeverBranch that was added in beautify loops but the region was not
3440     // yet transformed into a LoopNode. Bail out and wait until beautify loops turns it into a Loop node.
3441     return false;
3442   }
3443   // Compute loop trip count if possible.
3444   compute_trip_count(phase, T_INT);
3445 
3446   // Convert one-iteration loop into normal code.
3447   if (do_one_iteration_loop(phase)) {
3448     return true;
3449   }
3450   // Check and remove empty loops (spam micro-benchmarks)
3451   if (do_remove_empty_loop(phase)) {
3452     return true;  // Here we removed an empty loop
3453   }
3454 
3455   AutoNodeBudget node_budget(phase);
3456 
3457   // Non-counted loops may be peeled; exactly 1 iteration is peeled.
3458   // This removes loop-invariant tests (usually null checks).
3459   if (!_head->is_CountedLoop()) { // Non-counted loop
3460     if (PartialPeelLoop) {
3461       bool rc = phase->partial_peel(this, old_new);
3462       if (Compile::current()->failing()) { return false; }
3463       if (rc) {
3464         // Partial peel succeeded so terminate this round of loop opts
3465         return false;
3466       }
3467     }
3468     if (policy_peeling(phase)) {    // Should we peel?
3469       if (PrintOpto) { tty->print_cr("should_peel"); }
3470       phase->do_peeling(this, old_new);
3471     } else if (policy_unswitching(phase)) {
3472       phase->do_unswitching(this, old_new);
3473       return false; // need to recalculate idom data
3474     } else if (phase->duplicate_loop_backedge(this, old_new)) {
3475       return false;
3476     } else if (_head->is_LongCountedLoop()) {
3477       phase->create_loop_nest(this, old_new);
3478     }
3479     return true;
3480   }
3481   CountedLoopNode *cl = _head->as_CountedLoop();
3482 
3483   if (!cl->is_valid_counted_loop(T_INT)) return true; // Ignore various kinds of broken loops
3484 
3485   // Do nothing special to pre- and post- loops
3486   if (cl->is_pre_loop() || cl->is_post_loop()) return true;
3487 
3488   // With multiversioning, we create a fast_loop and a slow_loop, and a multiversion_if that
3489   // decides which loop is taken at runtime. At first, the multiversion_if always takes the
3490   // fast_loop, and we only optimize the fast_loop. Since we are not sure if we will ever use
3491   // the slow_loop, we delay optimizations for it, so we do not waste compile time and code
3492   // size. If we never change the condition of the multiversion_if, the slow_loop is eventually
3493   // folded away after loop-opts. While optimizing the fast_loop, we may want to perform some
3494   // speculative optimization, for which we need a runtime-check. We add this runtime-check
3495   // condition to the multiversion_if. Now, it becomes possible to execute the slow_loop at
3496   // runtime, and we resume optimizations for slow_loop ("un-delay" it).
3497   // TLDR: If the slow_loop is still in "delay" mode, check if the multiversion_if was changed
3498   //       and we should now resume optimizations for it.
3499   if (cl->is_multiversion_delayed_slow_loop() &&
3500       !phase->try_resume_optimizations_for_delayed_slow_loop(this)) {
3501     // We are still delayed, so wait with further loop-opts.
3502     return true;
3503   }
3504 
3505   // Compute loop trip count from profile data
3506   compute_profile_trip_cnt(phase);
3507 
3508   // Before attempting fancy unrolling, RCE or alignment, see if we want
3509   // to completely unroll this loop or do loop unswitching.
3510   if (cl->is_normal_loop()) {
3511     if (policy_unswitching(phase)) {
3512       phase->do_unswitching(this, old_new);
3513       return false; // need to recalculate idom data
3514     }
3515     if (policy_maximally_unroll(phase)) {
3516       // Here we did some unrolling and peeling.  Eventually we will
3517       // completely unroll this loop and it will no longer be a loop.
3518       phase->do_maximally_unroll(this, old_new);
3519       return true;
3520     }
3521     if (StressDuplicateBackedge && phase->duplicate_loop_backedge(this, old_new)) {
3522       return false;
3523     }
3524   }
3525 
3526   uint est_peeling = estimate_peeling(phase);
3527   bool should_peel = 0 < est_peeling;
3528 
3529   // Counted loops may be peeled, or may need some iterations run up
3530   // front for RCE. Thus we clone a full loop up front whose trip count is
3531   // at least 1 (if peeling), but may be several more.
3532 
3533   // The main loop will start cache-line aligned with at least 1
3534   // iteration of the unrolled body (zero-trip test required) and
3535   // will have some range checks removed.
3536 
3537   // A post-loop will finish any odd iterations (leftover after
3538   // unrolling), plus any needed for RCE purposes.
3539 
3540   bool should_unroll = policy_unroll(phase);
3541   bool should_rce    = policy_range_check(phase, false, T_INT);
3542   bool should_rce_long = policy_range_check(phase, false, T_LONG);
3543 
3544   // If not RCE'ing (iteration splitting), then we do not need a pre-loop.
3545   // We may still need to peel an initial iteration but we will not
3546   // be needing an unknown number of pre-iterations.
3547   //
3548   // Basically, if peel_only reports TRUE first time through, we will not
3549   // be able to later do RCE on this loop.
3550   bool peel_only = policy_peel_only(phase) && !should_rce;
3551 
3552   // If we have any of these conditions (RCE, unrolling) met, then
3553   // we switch to the pre-/main-/post-loop model.  This model also covers
3554   // peeling.
3555   if (should_rce || should_unroll) {
3556     if (cl->is_normal_loop()) { // Convert to 'pre/main/post' loops
3557       if (should_rce_long && phase->create_loop_nest(this, old_new)) {
3558         return true;
3559       }
3560       uint estimate = est_loop_clone_sz(3);
3561       if (!phase->may_require_nodes(estimate)) {
3562         return false;
3563       }
3564 
3565       if (!peel_only) {
3566         // We are going to add pre-loop and post-loop (PreMainPost).
3567         // But should we also multiversion for auto-vectorization speculative
3568         // checks, i.e. fast and slow-paths?
3569         // Note: Just PeelMainPost is not sufficient, as we could never find the
3570         //       multiversion_if again from the main loop: we need a nicely structured
3571         //       pre-loop, a peeled iteration cannot easily be parsed through.
3572         phase->maybe_multiversion_for_auto_vectorization_runtime_checks(this, old_new);
3573       }
3574 
3575       phase->insert_pre_post_loops(this, old_new, peel_only);
3576     }
3577     // Adjust the pre- and main-loop limits to let the pre and  post loops run
3578     // with full checks, but the main-loop with no checks.  Remove said checks
3579     // from the main body.
3580     if (should_rce) {
3581       phase->do_range_check(this);
3582     }
3583 
3584     // Double loop body for unrolling.  Adjust the minimum-trip test (will do
3585     // twice as many iterations as before) and the main body limit (only do
3586     // an even number of trips).  If we are peeling, we might enable some RCE
3587     // and we'd rather unroll the post-RCE'd loop SO... do not unroll if
3588     // peeling.
3589     if (should_unroll && !should_peel) {
3590       if (SuperWordLoopUnrollAnalysis) {
3591         phase->insert_vector_post_loop(this, old_new);
3592       }
3593       phase->do_unroll(this, old_new, true);
3594     }
3595   } else {                      // Else we have an unchanged counted loop
3596     if (should_peel) {          // Might want to peel but do nothing else
3597       if (phase->may_require_nodes(est_peeling)) {
3598         phase->do_peeling(this, old_new);
3599       }
3600     }
3601     if (should_rce_long) {
3602       phase->create_loop_nest(this, old_new);
3603     }
3604   }
3605   return true;
3606 }
3607 
3608 
3609 //=============================================================================
3610 //------------------------------iteration_split--------------------------------
3611 bool IdealLoopTree::iteration_split(PhaseIdealLoop* phase, Node_List &old_new) {
3612   // Recursively iteration split nested loops
3613   if (_child && !_child->iteration_split(phase, old_new)) {
3614     return false;
3615   }
3616 
3617   // Clean out prior deadwood
3618   DCE_loop_body();
3619 
3620   // Look for loop-exit tests with my 50/50 guesses from the Parsing stage.
3621   // Replace with a 1-in-10 exit guess.
3622   if (!is_root() && is_loop()) {
3623     adjust_loop_exit_prob(phase);
3624   }
3625 
3626   // Unrolling, RCE and peeling efforts, iff innermost loop.
3627   if (_allow_optimizations && is_innermost()) {
3628     if (!_has_call) {
3629       if (!iteration_split_impl(phase, old_new)) {
3630         return false;
3631       }
3632     } else {
3633       AutoNodeBudget node_budget(phase);
3634       if (policy_unswitching(phase)) {
3635         phase->do_unswitching(this, old_new);
3636         return false; // need to recalculate idom data
3637       }
3638     }
3639   }
3640 
3641   if (_next && !_next->iteration_split(phase, old_new)) {
3642     return false;
3643   }
3644   return true;
3645 }
3646 
3647 
3648 //=============================================================================
3649 // Process all the loops in the loop tree and replace any fill
3650 // patterns with an intrinsic version.
3651 bool PhaseIdealLoop::do_intrinsify_fill() {
3652   bool changed = false;
3653   for (LoopTreeIterator iter(_ltree_root); !iter.done(); iter.next()) {
3654     IdealLoopTree* lpt = iter.current();
3655     changed |= intrinsify_fill(lpt);
3656   }
3657   return changed;
3658 }
3659 
3660 
3661 // Examine an inner loop looking for a single store of an invariant
3662 // value in a unit stride loop,
3663 bool PhaseIdealLoop::match_fill_loop(IdealLoopTree* lpt, Node*& store, Node*& store_value,
3664                                      Node*& shift, Node*& con) {
3665   const char* msg = nullptr;
3666   Node* msg_node = nullptr;
3667 
3668   store_value = nullptr;
3669   con = nullptr;
3670   shift = nullptr;
3671 
3672   // Process the loop looking for stores.  If there are multiple
3673   // stores or extra control flow give at this point.
3674   CountedLoopNode* head = lpt->_head->as_CountedLoop();
3675   for (uint i = 0; msg == nullptr && i < lpt->_body.size(); i++) {
3676     Node* n = lpt->_body.at(i);
3677     if (n->outcnt() == 0) continue; // Ignore dead
3678     if (n->is_Store()) {
3679       if (store != nullptr) {
3680         msg = "multiple stores";
3681         break;
3682       }
3683       int opc = n->Opcode();
3684       if (opc == Op_StoreP || opc == Op_StoreN || opc == Op_StoreNKlass) {
3685         msg = "oop fills not handled";
3686         break;
3687       }
3688       Node* value = n->in(MemNode::ValueIn);
3689       if (!lpt->is_invariant(value)) {
3690         msg  = "variant store value";
3691       } else if (!_igvn.type(n->in(MemNode::Address))->isa_aryptr()) {
3692         msg = "not array address";
3693       }
3694       store = n;
3695       store_value = value;
3696     } else if (n->is_If() && n != head->loopexit_or_null()) {
3697       msg = "extra control flow";
3698       msg_node = n;
3699     }
3700   }
3701 
3702   if (store == nullptr) {
3703     // No store in loop
3704     return false;
3705   }
3706 
3707   if (msg == nullptr && store->as_Mem()->is_mismatched_access()) {
3708     // This optimization does not currently support mismatched stores, where the
3709     // type of the value to be stored differs from the element type of the
3710     // destination array. Such patterns arise for example from memory segment
3711     // initialization. This limitation could be overcome by extending this
3712     // function's address matching logic and ensuring that the fill intrinsic
3713     // implementations support mismatched array filling.
3714     msg = "mismatched store";
3715   }
3716 
3717   if (msg == nullptr && head->stride_con() != 1) {
3718     // could handle negative strides too
3719     if (head->stride_con() < 0) {
3720       msg = "negative stride";
3721     } else {
3722       msg = "non-unit stride";
3723     }
3724   }
3725 
3726   if (msg == nullptr && !store->in(MemNode::Address)->is_AddP()) {
3727     msg = "can't handle store address";
3728     msg_node = store->in(MemNode::Address);
3729   }
3730 
3731   if (msg == nullptr &&
3732       (!store->in(MemNode::Memory)->is_Phi() ||
3733        store->in(MemNode::Memory)->in(LoopNode::LoopBackControl) != store)) {
3734     msg = "store memory isn't proper phi";
3735     msg_node = store->in(MemNode::Memory);
3736   }
3737 
3738   // Make sure there is an appropriate fill routine
3739   BasicType t = msg == nullptr ?
3740     store->adr_type()->isa_aryptr()->elem()->array_element_basic_type() : T_VOID;
3741   const char* fill_name;
3742   if (msg == nullptr &&
3743       StubRoutines::select_fill_function(t, false, fill_name) == nullptr) {
3744     msg = "unsupported store";
3745     msg_node = store;
3746   }
3747 
3748   if (msg != nullptr) {
3749 #ifndef PRODUCT
3750     if (TraceOptimizeFill) {
3751       tty->print_cr("not fill intrinsic candidate: %s", msg);
3752       if (msg_node != nullptr) msg_node->dump();
3753     }
3754 #endif
3755     return false;
3756   }
3757 
3758   // Make sure the address expression can be handled.  It should be
3759   // head->phi * elsize + con.  head->phi might have a ConvI2L(CastII()).
3760   Node* elements[4];
3761   Node* cast = nullptr;
3762   Node* conv = nullptr;
3763   bool found_index = false;
3764   int count = store->in(MemNode::Address)->as_AddP()->unpack_offsets(elements, ARRAY_SIZE(elements));
3765   for (int e = 0; e < count; e++) {
3766     Node* n = elements[e];
3767     if (n->is_Con() && con == nullptr) {
3768       con = n;
3769     } else if (n->Opcode() == Op_LShiftX && shift == nullptr) {
3770       Node* value = n->in(1);
3771 #ifdef _LP64
3772       if (value->Opcode() == Op_ConvI2L) {
3773         conv = value;
3774         value = value->in(1);
3775       }
3776       if (value->Opcode() == Op_CastII &&
3777           value->as_CastII()->has_range_check()) {
3778         // Skip range check dependent CastII nodes
3779         cast = value;
3780         value = value->in(1);
3781       }
3782 #endif
3783       if (value != head->phi()) {
3784         msg = "unhandled shift in address";
3785       } else {
3786         if (type2aelembytes(t, true) != (1 << n->in(2)->get_int())) {
3787           msg = "scale doesn't match";
3788         } else {
3789           found_index = true;
3790           shift = n;
3791         }
3792       }
3793     } else if (n->Opcode() == Op_ConvI2L && conv == nullptr) {
3794       conv = n;
3795       n = n->in(1);
3796       if (n->Opcode() == Op_CastII &&
3797           n->as_CastII()->has_range_check()) {
3798         // Skip range check dependent CastII nodes
3799         cast = n;
3800         n = n->in(1);
3801       }
3802       if (n == head->phi()) {
3803         found_index = true;
3804       } else {
3805         msg = "unhandled input to ConvI2L";
3806       }
3807     } else if (n == head->phi()) {
3808       // no shift, check below for allowed cases
3809       found_index = true;
3810     } else {
3811       msg = "unhandled node in address";
3812       msg_node = n;
3813     }
3814   }
3815 
3816   if (count == -1) {
3817     msg = "malformed address expression";
3818     msg_node = store;
3819   }
3820 
3821   if (!found_index) {
3822     msg = "missing use of index";
3823   }
3824 
3825   // byte sized items won't have a shift
3826   if (msg == nullptr && shift == nullptr && t != T_BYTE && t != T_BOOLEAN) {
3827     msg = "can't find shift";
3828     msg_node = store;
3829   }
3830 
3831   if (msg != nullptr) {
3832 #ifndef PRODUCT
3833     if (TraceOptimizeFill) {
3834       tty->print_cr("not fill intrinsic: %s", msg);
3835       if (msg_node != nullptr) msg_node->dump();
3836     }
3837 #endif
3838     return false;
3839   }
3840 
3841   // No make sure all the other nodes in the loop can be handled
3842   VectorSet ok;
3843 
3844   // store related values are ok
3845   ok.set(store->_idx);
3846   ok.set(store->in(MemNode::Memory)->_idx);
3847 
3848   CountedLoopEndNode* loop_exit = head->loopexit();
3849 
3850   // Loop structure is ok
3851   ok.set(head->_idx);
3852   ok.set(loop_exit->_idx);
3853   ok.set(head->phi()->_idx);
3854   ok.set(head->incr()->_idx);
3855   ok.set(loop_exit->cmp_node()->_idx);
3856   ok.set(loop_exit->in(1)->_idx);
3857 
3858   // Address elements are ok
3859   if (con)   ok.set(con->_idx);
3860   if (shift) ok.set(shift->_idx);
3861   if (cast)  ok.set(cast->_idx);
3862   if (conv)  ok.set(conv->_idx);
3863 
3864   for (uint i = 0; msg == nullptr && i < lpt->_body.size(); i++) {
3865     Node* n = lpt->_body.at(i);
3866     if (n->outcnt() == 0) continue; // Ignore dead
3867     if (ok.test(n->_idx)) continue;
3868     // Backedge projection is ok
3869     if (n->is_IfTrue() && n->in(0) == loop_exit) continue;
3870     if (!n->is_AddP()) {
3871       msg = "unhandled node";
3872       msg_node = n;
3873       break;
3874     }
3875   }
3876 
3877   // Make sure no unexpected values are used outside the loop
3878   for (uint i = 0; msg == nullptr && i < lpt->_body.size(); i++) {
3879     Node* n = lpt->_body.at(i);
3880     // These values can be replaced with other nodes if they are used
3881     // outside the loop.
3882     if (n == store || n == loop_exit || n == head->incr() || n == store->in(MemNode::Memory)) continue;
3883     for (SimpleDUIterator iter(n); iter.has_next(); iter.next()) {
3884       Node* use = iter.get();
3885       if (!lpt->_body.contains(use)) {
3886         msg = "node is used outside loop";
3887         msg_node = n;
3888         break;
3889       }
3890     }
3891   }
3892 
3893 #ifdef ASSERT
3894   if (TraceOptimizeFill) {
3895     if (msg != nullptr) {
3896       tty->print_cr("no fill intrinsic: %s", msg);
3897       if (msg_node != nullptr) msg_node->dump();
3898     } else {
3899       tty->print_cr("fill intrinsic for:");
3900     }
3901     store->dump();
3902     if (Verbose) {
3903       lpt->_body.dump();
3904     }
3905   }
3906 #endif
3907 
3908   return msg == nullptr;
3909 }
3910 
3911 
3912 
3913 bool PhaseIdealLoop::intrinsify_fill(IdealLoopTree* lpt) {
3914   // Only for counted inner loops
3915   if (!lpt->is_counted() || !lpt->is_innermost()) {
3916     return false;
3917   }
3918 
3919   // Must have constant stride
3920   CountedLoopNode* head = lpt->_head->as_CountedLoop();
3921   if (!head->is_valid_counted_loop(T_INT) || !head->is_normal_loop()) {
3922     return false;
3923   }
3924 
3925   head->verify_strip_mined(1);
3926 
3927   // Check that the body only contains a store of a loop invariant
3928   // value that is indexed by the loop phi.
3929   Node* store = nullptr;
3930   Node* store_value = nullptr;
3931   Node* shift = nullptr;
3932   Node* offset = nullptr;
3933   if (!match_fill_loop(lpt, store, store_value, shift, offset)) {
3934     return false;
3935   }
3936 
3937   Node* exit = head->loopexit()->proj_out_or_null(0);
3938   if (exit == nullptr) {
3939     return false;
3940   }
3941 
3942 #ifndef PRODUCT
3943   if (TraceLoopOpts) {
3944     tty->print("ArrayFill    ");
3945     lpt->dump_head();
3946   }
3947 #endif
3948 
3949   // Now replace the whole loop body by a call to a fill routine that
3950   // covers the same region as the loop.
3951   Node* base = store->in(MemNode::Address)->as_AddP()->in(AddPNode::Base);
3952 
3953   // Build an expression for the beginning of the copy region
3954   Node* index = head->init_trip();
3955 #ifdef _LP64
3956   index = new ConvI2LNode(index);
3957   _igvn.register_new_node_with_optimizer(index);
3958 #endif
3959   if (shift != nullptr) {
3960     // byte arrays don't require a shift but others do.
3961     index = new LShiftXNode(index, shift->in(2));
3962     _igvn.register_new_node_with_optimizer(index);
3963   }
3964   Node* from = new AddPNode(base, base, index);
3965   _igvn.register_new_node_with_optimizer(from);
3966   // For normal array fills, C2 uses two AddP nodes for array element
3967   // addressing. But for array fills with Unsafe call, there's only one
3968   // AddP node adding an absolute offset, so we do a null check here.
3969   assert(offset != nullptr || C->has_unsafe_access(),
3970          "Only array fills with unsafe have no extra offset");
3971   if (offset != nullptr) {
3972     from = new AddPNode(base, from, offset);
3973     _igvn.register_new_node_with_optimizer(from);
3974   }
3975   // Compute the number of elements to copy
3976   Node* len = new SubINode(head->limit(), head->init_trip());
3977   _igvn.register_new_node_with_optimizer(len);
3978 
3979   // If the store is on the backedge, it is not executed in the last
3980   // iteration, and we must subtract 1 from the len.
3981   Node* backedge = head->loopexit()->proj_out(1);
3982   if (store->in(0) == backedge) {
3983     len = new SubINode(len, _igvn.intcon(1));
3984     _igvn.register_new_node_with_optimizer(len);
3985 #ifndef PRODUCT
3986     if (TraceOptimizeFill) {
3987       tty->print_cr("ArrayFill store on backedge, subtract 1 from len.");
3988     }
3989 #endif
3990   }
3991 
3992   BasicType t = store->adr_type()->isa_aryptr()->elem()->array_element_basic_type();
3993   bool aligned = false;
3994   if (offset != nullptr && head->init_trip()->is_Con()) {
3995     int element_size = type2aelembytes(t);
3996     aligned = (offset->find_intptr_t_type()->get_con() + head->init_trip()->get_int() * element_size) % HeapWordSize == 0;
3997   }
3998 
3999   // Build a call to the fill routine
4000   const char* fill_name;
4001   address fill = StubRoutines::select_fill_function(t, aligned, fill_name);
4002   assert(fill != nullptr, "what?");
4003 
4004   // Convert float/double to int/long for fill routines
4005   if (t == T_FLOAT) {
4006     store_value = new MoveF2INode(store_value);
4007     _igvn.register_new_node_with_optimizer(store_value);
4008   } else if (t == T_DOUBLE) {
4009     store_value = new MoveD2LNode(store_value);
4010     _igvn.register_new_node_with_optimizer(store_value);
4011   }
4012 
4013   Node* mem_phi = store->in(MemNode::Memory);
4014   Node* result_ctrl;
4015   Node* result_mem;
4016   const TypeFunc* call_type = OptoRuntime::array_fill_Type();
4017   CallLeafNode *call = new CallLeafNoFPNode(call_type, fill,
4018                                             fill_name, TypeAryPtr::get_array_body_type(t));
4019   uint cnt = 0;
4020   call->init_req(TypeFunc::Parms + cnt++, from);
4021   call->init_req(TypeFunc::Parms + cnt++, store_value);
4022 #ifdef _LP64
4023   len = new ConvI2LNode(len);
4024   _igvn.register_new_node_with_optimizer(len);
4025 #endif
4026   call->init_req(TypeFunc::Parms + cnt++, len);
4027 #ifdef _LP64
4028   call->init_req(TypeFunc::Parms + cnt++, C->top());
4029 #endif
4030   call->init_req(TypeFunc::Control,   head->init_control());
4031   call->init_req(TypeFunc::I_O,       C->top());       // Does no I/O.
4032   call->init_req(TypeFunc::Memory,    mem_phi->in(LoopNode::EntryControl));
4033   call->init_req(TypeFunc::ReturnAdr, C->start()->proj_out_or_null(TypeFunc::ReturnAdr));
4034   call->init_req(TypeFunc::FramePtr,  C->start()->proj_out_or_null(TypeFunc::FramePtr));
4035   _igvn.register_new_node_with_optimizer(call);
4036   result_ctrl = new ProjNode(call,TypeFunc::Control);
4037   _igvn.register_new_node_with_optimizer(result_ctrl);
4038   result_mem = new ProjNode(call,TypeFunc::Memory);
4039   _igvn.register_new_node_with_optimizer(result_mem);
4040 
4041 /* Disable following optimization until proper fix (add missing checks).
4042 
4043   // If this fill is tightly coupled to an allocation and overwrites
4044   // the whole body, allow it to take over the zeroing.
4045   AllocateNode* alloc = AllocateNode::Ideal_allocation(base, this);
4046   if (alloc != nullptr && alloc->is_AllocateArray()) {
4047     Node* length = alloc->as_AllocateArray()->Ideal_length();
4048     if (head->limit() == length &&
4049         head->init_trip() == _igvn.intcon(0)) {
4050       if (TraceOptimizeFill) {
4051         tty->print_cr("Eliminated zeroing in allocation");
4052       }
4053       alloc->maybe_set_complete(&_igvn);
4054     } else {
4055 #ifdef ASSERT
4056       if (TraceOptimizeFill) {
4057         tty->print_cr("filling array but bounds don't match");
4058         alloc->dump();
4059         head->init_trip()->dump();
4060         head->limit()->dump();
4061         length->dump();
4062       }
4063 #endif
4064     }
4065   }
4066 */
4067 
4068   if (head->is_strip_mined()) {
4069     // Inner strip mined loop goes away so get rid of outer strip
4070     // mined loop
4071     Node* outer_sfpt = head->outer_safepoint();
4072     Node* in = outer_sfpt->in(0);
4073     Node* outer_out = head->outer_loop_exit();
4074     replace_node_and_forward_ctrl(outer_out, in);
4075     _igvn.replace_input_of(outer_sfpt, 0, C->top());
4076   }
4077 
4078   // Redirect the old control and memory edges that are outside the loop.
4079   // Sometimes the memory phi of the head is used as the outgoing
4080   // state of the loop.  It's safe in this case to replace it with the
4081   // result_mem.
4082   _igvn.replace_node(store->in(MemNode::Memory), result_mem);
4083   replace_node_and_forward_ctrl(exit, result_ctrl);
4084   _igvn.replace_node(store, result_mem);
4085   // Any uses the increment outside of the loop become the loop limit.
4086   _igvn.replace_node(head->incr(), head->limit());
4087 
4088   // Disconnect the head from the loop.
4089   for (uint i = 0; i < lpt->_body.size(); i++) {
4090     Node* n = lpt->_body.at(i);
4091     _igvn.replace_node(n, C->top());
4092   }
4093 
4094 #ifndef PRODUCT
4095   if (TraceOptimizeFill) {
4096     tty->print("ArrayFill call   ");
4097     call->dump();
4098   }
4099 #endif
4100 
4101   return true;
4102 }