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 "ci/ciTypeFlow.hpp"
  26 #include "memory/allocation.inline.hpp"
  27 #include "memory/resourceArea.hpp"
  28 #include "opto/addnode.hpp"
  29 #include "opto/castnode.hpp"
  30 #include "opto/cfgnode.hpp"
  31 #include "opto/connode.hpp"
  32 #include "opto/loopnode.hpp"
  33 #include "opto/phaseX.hpp"
  34 #include "opto/predicates.hpp"
  35 #include "opto/runtime.hpp"
  36 #include "opto/rootnode.hpp"
  37 #include "opto/subnode.hpp"
  38 #include "opto/subtypenode.hpp"
  39 
  40 // Portions of code courtesy of Clifford Click
  41 
  42 // Optimization - Graph Style
  43 
  44 
  45 #ifndef PRODUCT
  46 extern uint explicit_null_checks_elided;
  47 #endif
  48 
  49 IfNode::IfNode(Node* control, Node* bol, float p, float fcnt)
  50     : MultiBranchNode(2),
  51       _prob(p),
  52       _fcnt(fcnt),
  53       _assertion_predicate_type(AssertionPredicateType::None) {
  54   init_node(control, bol);
  55 }
  56 
  57 IfNode::IfNode(Node* control, Node* bol, float p, float fcnt, AssertionPredicateType assertion_predicate_type)
  58     : MultiBranchNode(2),
  59       _prob(p),
  60       _fcnt(fcnt),
  61       _assertion_predicate_type(assertion_predicate_type) {
  62   init_node(control, bol);
  63 }
  64 
  65 //=============================================================================
  66 //------------------------------Value------------------------------------------
  67 // Return a tuple for whichever arm of the IF is reachable
  68 const Type* IfNode::Value(PhaseGVN* phase) const {
  69   if( !in(0) ) return Type::TOP;
  70   if( phase->type(in(0)) == Type::TOP )
  71     return Type::TOP;
  72   const Type *t = phase->type(in(1));
  73   if( t == Type::TOP )          // data is undefined
  74     return TypeTuple::IFNEITHER; // unreachable altogether
  75   if( t == TypeInt::ZERO )      // zero, or false
  76     return TypeTuple::IFFALSE;  // only false branch is reachable
  77   if( t == TypeInt::ONE )       // 1, or true
  78     return TypeTuple::IFTRUE;   // only true branch is reachable
  79   assert( t == TypeInt::BOOL, "expected boolean type" );
  80 
  81   return TypeTuple::IFBOTH;     // No progress
  82 }
  83 
  84 const RegMask &IfNode::out_RegMask() const {
  85   return RegMask::Empty;
  86 }
  87 
  88 //------------------------------split_if---------------------------------------
  89 // Look for places where we merge constants, then test on the merged value.
  90 // If the IF test will be constant folded on the path with the constant, we
  91 // win by splitting the IF to before the merge point.
  92 static Node* split_if(IfNode *iff, PhaseIterGVN *igvn) {
  93   // I could be a lot more general here, but I'm trying to squeeze this
  94   // in before the Christmas '98 break so I'm gonna be kinda restrictive
  95   // on the patterns I accept.  CNC
  96 
  97   // Look for a compare of a constant and a merged value
  98   Node *i1 = iff->in(1);
  99   if( !i1->is_Bool() ) return nullptr;
 100   BoolNode *b = i1->as_Bool();
 101   Node *cmp = b->in(1);
 102   if( !cmp->is_Cmp() ) return nullptr;
 103   i1 = cmp->in(1);
 104   if( i1 == nullptr || !i1->is_Phi() ) return nullptr;
 105   PhiNode *phi = i1->as_Phi();
 106   Node *con2 = cmp->in(2);
 107   if( !con2->is_Con() ) return nullptr;
 108   // See that the merge point contains some constants
 109   Node *con1=nullptr;
 110   uint i4;
 111   RegionNode* phi_region = phi->region();
 112   for (i4 = 1; i4 < phi->req(); i4++ ) {
 113     con1 = phi->in(i4);
 114     // Do not optimize partially collapsed merges
 115     if (con1 == nullptr || phi_region->in(i4) == nullptr || igvn->type(phi_region->in(i4)) == Type::TOP) {
 116       igvn->_worklist.push(iff);
 117       return nullptr;
 118     }
 119     if( con1->is_Con() ) break; // Found a constant
 120     // Also allow null-vs-not-null checks
 121     const TypePtr *tp = igvn->type(con1)->isa_ptr();
 122     if( tp && tp->_ptr == TypePtr::NotNull )
 123       break;
 124   }
 125   if( i4 >= phi->req() ) return nullptr; // Found no constants
 126 
 127   igvn->C->set_has_split_ifs(true); // Has chance for split-if
 128 
 129   // Make sure that the compare can be constant folded away
 130   Node *cmp2 = cmp->clone();
 131   cmp2->set_req(1,con1);
 132   cmp2->set_req(2,con2);
 133   const Type *t = cmp2->Value(igvn);
 134   // This compare is dead, so whack it!
 135   igvn->remove_dead_node(cmp2);
 136   if( !t->singleton() ) return nullptr;
 137 
 138   // No intervening control, like a simple Call
 139   Node* r = iff->in(0);
 140   if (!r->is_Region() || r->is_Loop() || phi_region != r || r->as_Region()->is_copy()) {
 141     return nullptr;
 142   }
 143 
 144   // No other users of the cmp/bool
 145   if (b->outcnt() != 1 || cmp->outcnt() != 1) {
 146     //tty->print_cr("many users of cmp/bool");
 147     return nullptr;
 148   }
 149 
 150   // Make sure we can determine where all the uses of merged values go
 151   for (DUIterator_Fast jmax, j = r->fast_outs(jmax); j < jmax; j++) {
 152     Node* u = r->fast_out(j);
 153     if( u == r ) continue;
 154     if( u == iff ) continue;
 155     if( u->outcnt() == 0 ) continue; // use is dead & ignorable
 156     if( !u->is_Phi() ) {
 157       /*
 158       if( u->is_Start() ) {
 159         tty->print_cr("Region has inlined start use");
 160       } else {
 161         tty->print_cr("Region has odd use");
 162         u->dump(2);
 163       }*/
 164       return nullptr;
 165     }
 166     if( u != phi ) {
 167       // CNC - do not allow any other merged value
 168       //tty->print_cr("Merging another value");
 169       //u->dump(2);
 170       return nullptr;
 171     }
 172     // Make sure we can account for all Phi uses
 173     for (DUIterator_Fast kmax, k = u->fast_outs(kmax); k < kmax; k++) {
 174       Node* v = u->fast_out(k); // User of the phi
 175       // CNC - Allow only really simple patterns.
 176       // In particular I disallow AddP of the Phi, a fairly common pattern
 177       if (v == cmp) continue;  // The compare is OK
 178       if (v->is_ConstraintCast()) {
 179         // If the cast is derived from data flow edges, it may not have a control edge.
 180         // If so, it should be safe to split. But follow-up code can not deal with
 181         // this (l. 359). So skip.
 182         if (v->in(0) == nullptr) {
 183           return nullptr;
 184         }
 185         if (v->in(0)->in(0) == iff) {
 186           continue;               // CastPP/II of the IfNode is OK
 187         }
 188       }
 189       // Disabled following code because I cannot tell if exactly one
 190       // path dominates without a real dominator check. CNC 9/9/1999
 191       //uint vop = v->Opcode();
 192       //if( vop == Op_Phi ) {        // Phi from another merge point might be OK
 193       //  Node *r = v->in(0);        // Get controlling point
 194       //  if( !r ) return nullptr;   // Degraded to a copy
 195       //  // Find exactly one path in (either True or False doms, but not IFF)
 196       //  int cnt = 0;
 197       //  for( uint i = 1; i < r->req(); i++ )
 198       //    if( r->in(i) && r->in(i)->in(0) == iff )
 199       //      cnt++;
 200       //  if( cnt == 1 ) continue; // Exactly one of True or False guards Phi
 201       //}
 202       if( !v->is_Call() ) {
 203         /*
 204         if( v->Opcode() == Op_AddP ) {
 205           tty->print_cr("Phi has AddP use");
 206         } else if( v->Opcode() == Op_CastPP ) {
 207           tty->print_cr("Phi has CastPP use");
 208         } else if( v->Opcode() == Op_CastII ) {
 209           tty->print_cr("Phi has CastII use");
 210         } else {
 211           tty->print_cr("Phi has use I can't be bothered with");
 212         }
 213         */
 214       }
 215       return nullptr;
 216 
 217       /* CNC - Cut out all the fancy acceptance tests
 218       // Can we clone this use when doing the transformation?
 219       // If all uses are from Phis at this merge or constants, then YES.
 220       if( !v->in(0) && v != cmp ) {
 221         tty->print_cr("Phi has free-floating use");
 222         v->dump(2);
 223         return nullptr;
 224       }
 225       for( uint l = 1; l < v->req(); l++ ) {
 226         if( (!v->in(l)->is_Phi() || v->in(l)->in(0) != r) &&
 227             !v->in(l)->is_Con() ) {
 228           tty->print_cr("Phi has use");
 229           v->dump(2);
 230           return nullptr;
 231         } // End of if Phi-use input is neither Phi nor Constant
 232       } // End of for all inputs to Phi-use
 233       */
 234     } // End of for all uses of Phi
 235   } // End of for all uses of Region
 236 
 237   // Only do this if the IF node is in a sane state
 238   if (iff->outcnt() != 2)
 239     return nullptr;
 240 
 241   // Got a hit!  Do the Mondo Hack!
 242   //
 243   //ABC  a1c   def   ghi            B     1     e     h   A C   a c   d f   g i
 244   // R - Phi - Phi - Phi            Rc - Phi - Phi - Phi   Rx - Phi - Phi - Phi
 245   //     cmp - 2                         cmp - 2               cmp - 2
 246   //       bool                            bool_c                bool_x
 247   //       if                               if_c                  if_x
 248   //      T  F                              T  F                  T  F
 249   // ..s..    ..t ..                   ..s..    ..t..        ..s..    ..t..
 250   //
 251   // Split the paths coming into the merge point into 2 separate groups of
 252   // merges.  On the left will be all the paths feeding constants into the
 253   // Cmp's Phi.  On the right will be the remaining paths.  The Cmp's Phi
 254   // will fold up into a constant; this will let the Cmp fold up as well as
 255   // all the control flow.  Below the original IF we have 2 control
 256   // dependent regions, 's' and 't'.  Now we will merge the two paths
 257   // just prior to 's' and 't' from the two IFs.  At least 1 path (and quite
 258   // likely 2 or more) will promptly constant fold away.
 259   PhaseGVN *phase = igvn;
 260 
 261   // Make a region merging constants and a region merging the rest
 262   uint req_c = 0;
 263   for (uint ii = 1; ii < r->req(); ii++) {
 264     if (phi->in(ii) == con1) {
 265       req_c++;
 266     }
 267     if (Node::may_be_loop_entry(r->in(ii))) {
 268       // Bail out if splitting through a region with a Parse Predicate input (could
 269       // also be a loop header before loop opts creates a LoopNode for it).
 270       return nullptr;
 271     }
 272   }
 273 
 274   // If all the defs of the phi are the same constant, we already have the desired end state.
 275   // Skip the split that would create empty phi and region nodes.
 276   if ((r->req() - req_c) == 1) {
 277     return nullptr;
 278   }
 279 
 280   // At this point we know that we can apply the split if optimization. If the region is still on the worklist,
 281   // we should wait until it is processed. The region might be removed which makes this optimization redundant.
 282   // This also avoids the creation of dead data loops when rewiring data nodes below when a region is dying.
 283   if (igvn->_worklist.member(r)) {
 284     igvn->_worklist.push(iff); // retry split if later again
 285     return nullptr;
 286   }
 287 
 288   Node *region_c = new RegionNode(req_c + 1);
 289   Node *phi_c    = con1;
 290   uint  len      = r->req();
 291   Node *region_x = new RegionNode(len - req_c);
 292   Node *phi_x    = PhiNode::make_blank(region_x, phi);
 293   for (uint i = 1, i_c = 1, i_x = 1; i < len; i++) {
 294     if (phi->in(i) == con1) {
 295       region_c->init_req( i_c++, r  ->in(i) );
 296     } else {
 297       region_x->init_req( i_x,   r  ->in(i) );
 298       phi_x   ->init_req( i_x++, phi->in(i) );
 299     }
 300   }
 301 
 302   // Register the new RegionNodes but do not transform them.  Cannot
 303   // transform until the entire Region/Phi conglomerate has been hacked
 304   // as a single huge transform.
 305   igvn->register_new_node_with_optimizer( region_c );
 306   igvn->register_new_node_with_optimizer( region_x );
 307   // Prevent the untimely death of phi_x.  Currently he has no uses.  He is
 308   // about to get one.  If this only use goes away, then phi_x will look dead.
 309   // However, he will be picking up some more uses down below.
 310   Node *hook = new Node(4);
 311   hook->init_req(0, phi_x);
 312   hook->init_req(1, phi_c);
 313   phi_x = phase->transform( phi_x );
 314 
 315   // Make the compare
 316   Node *cmp_c = phase->makecon(t);
 317   Node *cmp_x = cmp->clone();
 318   cmp_x->set_req(1,phi_x);
 319   cmp_x->set_req(2,con2);
 320   cmp_x = phase->transform(cmp_x);
 321   // Make the bool
 322   Node *b_c = phase->transform(new BoolNode(cmp_c,b->_test._test));
 323   Node *b_x = phase->transform(new BoolNode(cmp_x,b->_test._test));
 324   // Make the IfNode
 325   IfNode* iff_c = iff->clone()->as_If();
 326   iff_c->set_req(0, region_c);
 327   iff_c->set_req(1, b_c);
 328   igvn->set_type_bottom(iff_c);
 329   igvn->_worklist.push(iff_c);
 330   hook->init_req(2, iff_c);
 331 
 332   IfNode* iff_x = iff->clone()->as_If();
 333   iff_x->set_req(0, region_x);
 334   iff_x->set_req(1, b_x);
 335   igvn->set_type_bottom(iff_x);
 336   igvn->_worklist.push(iff_x);
 337   hook->init_req(3, iff_x);
 338 
 339   // Make the true/false arms
 340   Node *iff_c_t = phase->transform(new IfTrueNode (iff_c));
 341   Node *iff_c_f = phase->transform(new IfFalseNode(iff_c));
 342   Node *iff_x_t = phase->transform(new IfTrueNode (iff_x));
 343   Node *iff_x_f = phase->transform(new IfFalseNode(iff_x));
 344 
 345   // Merge the TRUE paths
 346   Node *region_s = new RegionNode(3);
 347   igvn->_worklist.push(region_s);
 348   region_s->init_req(1, iff_c_t);
 349   region_s->init_req(2, iff_x_t);
 350   igvn->register_new_node_with_optimizer( region_s );
 351 
 352   // Merge the FALSE paths
 353   Node *region_f = new RegionNode(3);
 354   igvn->_worklist.push(region_f);
 355   region_f->init_req(1, iff_c_f);
 356   region_f->init_req(2, iff_x_f);
 357   igvn->register_new_node_with_optimizer( region_f );
 358 
 359   igvn->hash_delete(cmp);// Remove soon-to-be-dead node from hash table.
 360   cmp->set_req(1,nullptr);  // Whack the inputs to cmp because it will be dead
 361   cmp->set_req(2,nullptr);
 362   // Check for all uses of the Phi and give them a new home.
 363   // The 'cmp' got cloned, but CastPP/IIs need to be moved.
 364   Node *phi_s = nullptr;     // do not construct unless needed
 365   Node *phi_f = nullptr;     // do not construct unless needed
 366   for (DUIterator_Last i2min, i2 = phi->last_outs(i2min); i2 >= i2min; --i2) {
 367     Node* v = phi->last_out(i2);// User of the phi
 368     igvn->rehash_node_delayed(v); // Have to fixup other Phi users
 369     uint vop = v->Opcode();
 370     Node *proj = nullptr;
 371     if( vop == Op_Phi ) {       // Remote merge point
 372       Node *r = v->in(0);
 373       for (uint i3 = 1; i3 < r->req(); i3++)
 374         if (r->in(i3) && r->in(i3)->in(0) == iff) {
 375           proj = r->in(i3);
 376           break;
 377         }
 378     } else if( v->is_ConstraintCast() ) {
 379       proj = v->in(0);          // Controlling projection
 380     } else {
 381       assert( 0, "do not know how to handle this guy" );
 382     }
 383     guarantee(proj != nullptr, "sanity");
 384 
 385     Node *proj_path_data, *proj_path_ctrl;
 386     if( proj->Opcode() == Op_IfTrue ) {
 387       if( phi_s == nullptr ) {
 388         // Only construct phi_s if needed, otherwise provides
 389         // interfering use.
 390         phi_s = PhiNode::make_blank(region_s,phi);
 391         phi_s->init_req( 1, phi_c );
 392         phi_s->init_req( 2, phi_x );
 393         hook->add_req(phi_s);
 394         phi_s = phase->transform(phi_s);
 395       }
 396       proj_path_data = phi_s;
 397       proj_path_ctrl = region_s;
 398     } else {
 399       if( phi_f == nullptr ) {
 400         // Only construct phi_f if needed, otherwise provides
 401         // interfering use.
 402         phi_f = PhiNode::make_blank(region_f,phi);
 403         phi_f->init_req( 1, phi_c );
 404         phi_f->init_req( 2, phi_x );
 405         hook->add_req(phi_f);
 406         phi_f = phase->transform(phi_f);
 407       }
 408       proj_path_data = phi_f;
 409       proj_path_ctrl = region_f;
 410     }
 411 
 412     // Fixup 'v' for for the split
 413     if( vop == Op_Phi ) {       // Remote merge point
 414       uint i;
 415       for( i = 1; i < v->req(); i++ )
 416         if( v->in(i) == phi )
 417           break;
 418       v->set_req(i, proj_path_data );
 419     } else if( v->is_ConstraintCast() ) {
 420       v->set_req(0, proj_path_ctrl );
 421       v->set_req(1, proj_path_data );
 422     } else
 423       ShouldNotReachHere();
 424   }
 425 
 426   // Now replace the original iff's True/False with region_s/region_t.
 427   // This makes the original iff go dead.
 428   for (DUIterator_Last i3min, i3 = iff->last_outs(i3min); i3 >= i3min; --i3) {
 429     Node* p = iff->last_out(i3);
 430     assert( p->Opcode() == Op_IfTrue || p->Opcode() == Op_IfFalse, "" );
 431     Node *u = (p->Opcode() == Op_IfTrue) ? region_s : region_f;
 432     // Replace p with u
 433     igvn->add_users_to_worklist(p);
 434     for (DUIterator_Last lmin, l = p->last_outs(lmin); l >= lmin;) {
 435       Node* x = p->last_out(l);
 436       igvn->hash_delete(x);
 437       uint uses_found = 0;
 438       for( uint j = 0; j < x->req(); j++ ) {
 439         if( x->in(j) == p ) {
 440           x->set_req(j, u);
 441           uses_found++;
 442         }
 443       }
 444       l -= uses_found;    // we deleted 1 or more copies of this edge
 445     }
 446     igvn->remove_dead_node(p);
 447   }
 448 
 449   // Force the original merge dead
 450   igvn->hash_delete(r);
 451   // First, remove region's dead users.
 452   for (DUIterator_Last lmin, l = r->last_outs(lmin); l >= lmin;) {
 453     Node* u = r->last_out(l);
 454     if( u == r ) {
 455       r->set_req(0, nullptr);
 456     } else {
 457       assert(u->outcnt() == 0, "only dead users");
 458       igvn->remove_dead_node(u);
 459     }
 460     l -= 1;
 461   }
 462   igvn->remove_dead_node(r);
 463 
 464   // Now remove the bogus extra edges used to keep things alive
 465   igvn->remove_dead_node( hook );
 466 
 467   // Must return either the original node (now dead) or a new node
 468   // (Do not return a top here, since that would break the uniqueness of top.)
 469   return new ConINode(TypeInt::ZERO);
 470 }
 471 
 472 IfNode* IfNode::make_with_same_profile(IfNode* if_node_profile, Node* ctrl, BoolNode* bol) {
 473   // Assert here that we only try to create a clone from an If node with the same profiling if that actually makes sense.
 474   // Some If node subtypes should not be cloned in this way. In theory, we should not clone BaseCountedLoopEndNodes.
 475   // But they can end up being used as normal If nodes when peeling a loop - they serve as zero-trip guard.
 476   // Allow them as well.
 477   assert(if_node_profile->Opcode() == Op_If || if_node_profile->is_RangeCheck()
 478          || if_node_profile->is_BaseCountedLoopEnd(), "should not clone other nodes");
 479   if (if_node_profile->is_RangeCheck()) {
 480     // RangeCheck nodes could be further optimized.
 481     return new RangeCheckNode(ctrl, bol, if_node_profile->_prob, if_node_profile->_fcnt);
 482   } else {
 483     // Not a RangeCheckNode? Fall back to IfNode.
 484     return new IfNode(ctrl, bol, if_node_profile->_prob, if_node_profile->_fcnt);
 485   }
 486 }
 487 
 488 // if this IfNode follows a range check pattern return the projection
 489 // for the failed path
 490 ProjNode* IfNode::range_check_trap_proj(int& flip_test, Node*& l, Node*& r) {
 491   if (outcnt() != 2) {
 492     return nullptr;
 493   }
 494   Node* b = in(1);
 495   if (b == nullptr || !b->is_Bool())  return nullptr;
 496   BoolNode* bn = b->as_Bool();
 497   Node* cmp = bn->in(1);
 498   if (cmp == nullptr)  return nullptr;
 499   if (cmp->Opcode() != Op_CmpU)  return nullptr;
 500 
 501   l = cmp->in(1);
 502   r = cmp->in(2);
 503   flip_test = 1;
 504   if (bn->_test._test == BoolTest::le) {
 505     l = cmp->in(2);
 506     r = cmp->in(1);
 507     flip_test = 2;
 508   } else if (bn->_test._test != BoolTest::lt) {
 509     return nullptr;
 510   }
 511   if (l->is_top())  return nullptr;   // Top input means dead test
 512   if (r->Opcode() != Op_LoadRange && !is_RangeCheck())  return nullptr;
 513 
 514   // We have recognized one of these forms:
 515   //  Flip 1:  If (Bool[<] CmpU(l, LoadRange)) ...
 516   //  Flip 2:  If (Bool[<=] CmpU(LoadRange, l)) ...
 517 
 518   ProjNode* iftrap = proj_out_or_null(flip_test == 2 ? true : false);
 519   return iftrap;
 520 }
 521 
 522 
 523 //------------------------------is_range_check---------------------------------
 524 // Return 0 if not a range check.  Return 1 if a range check and set index and
 525 // offset.  Return 2 if we had to negate the test.  Index is null if the check
 526 // is versus a constant.
 527 int RangeCheckNode::is_range_check(Node* &range, Node* &index, jint &offset) {
 528   int flip_test = 0;
 529   Node* l = nullptr;
 530   Node* r = nullptr;
 531   ProjNode* iftrap = range_check_trap_proj(flip_test, l, r);
 532 
 533   if (iftrap == nullptr) {
 534     return 0;
 535   }
 536 
 537   // Make sure it's a real range check by requiring an uncommon trap
 538   // along the OOB path.  Otherwise, it's possible that the user wrote
 539   // something which optimized to look like a range check but behaves
 540   // in some other way.
 541   if (iftrap->is_uncommon_trap_proj(Deoptimization::Reason_range_check) == nullptr) {
 542     return 0;
 543   }
 544 
 545   // Look for index+offset form
 546   Node* ind = l;
 547   jint  off = 0;
 548   if (l->is_top()) {
 549     return 0;
 550   } else if (l->Opcode() == Op_AddI) {
 551     if ((off = l->in(1)->find_int_con(0)) != 0) {
 552       ind = l->in(2)->uncast();
 553     } else if ((off = l->in(2)->find_int_con(0)) != 0) {
 554       ind = l->in(1)->uncast();
 555     }
 556   } else if ((off = l->find_int_con(-1)) >= 0) {
 557     // constant offset with no variable index
 558     ind = nullptr;
 559   } else {
 560     // variable index with no constant offset (or dead negative index)
 561     off = 0;
 562   }
 563 
 564   // Return all the values:
 565   index  = ind;
 566   offset = off;
 567   range  = r;
 568   return flip_test;
 569 }
 570 
 571 //------------------------------adjust_check-----------------------------------
 572 // Adjust (widen) a prior range check
 573 static void adjust_check(IfProjNode* proj, Node* range, Node* index,
 574                          int flip, jint off_lo, PhaseIterGVN* igvn) {
 575   PhaseGVN *gvn = igvn;
 576   // Break apart the old check
 577   Node *iff = proj->in(0);
 578   Node *bol = iff->in(1);
 579   if( bol->is_top() ) return;   // In case a partially dead range check appears
 580   // bail (or bomb[ASSERT/DEBUG]) if NOT projection-->IfNode-->BoolNode
 581   DEBUG_ONLY( if (!bol->is_Bool()) { proj->dump(3); fatal("Expect projection-->IfNode-->BoolNode"); } )
 582   if (!bol->is_Bool()) return;
 583 
 584   Node *cmp = bol->in(1);
 585   // Compute a new check
 586   Node *new_add = gvn->intcon(off_lo);
 587   if (index) {
 588     new_add = off_lo ? gvn->transform(new AddINode(index, new_add)) : index;
 589   }
 590   Node *new_cmp = (flip == 1)
 591     ? new CmpUNode(new_add, range)
 592     : new CmpUNode(range, new_add);
 593   new_cmp = gvn->transform(new_cmp);
 594   // See if no need to adjust the existing check
 595   if (new_cmp == cmp) return;
 596   // Else, adjust existing check
 597   Node* new_bol = gvn->transform(new BoolNode(new_cmp, bol->as_Bool()->_test._test));
 598   igvn->rehash_node_delayed(iff);
 599   iff->set_req_X(1, new_bol, igvn);
 600   // As part of range check smearing, this range check is widened. Loads and range check Cast nodes that are control
 601   // dependent on this range check now depend on multiple dominating range checks. These control dependent nodes end up
 602   // at the lowest/nearest dominating check in the graph. To ensure that these Loads/Casts do not float above any of the
 603   // dominating checks (even when the lowest dominating check is later replaced by yet another dominating check), we
 604   // need to pin them at the lowest dominating check.
 605   proj->pin_array_access_nodes(igvn);
 606 }
 607 
 608 //------------------------------up_one_dom-------------------------------------
 609 // Walk up the dominator tree one step.  Return null at root or true
 610 // complex merges.  Skips through small diamonds.
 611 Node* IfNode::up_one_dom(Node *curr, bool linear_only) {
 612   Node *dom = curr->in(0);
 613   if( !dom )                    // Found a Region degraded to a copy?
 614     return curr->nonnull_req(); // Skip thru it
 615 
 616   if( curr != dom )             // Normal walk up one step?
 617     return dom;
 618 
 619   // Use linear_only if we are still parsing, since we cannot
 620   // trust the regions to be fully filled in.
 621   if (linear_only)
 622     return nullptr;
 623 
 624   if( dom->is_Root() )
 625     return nullptr;
 626 
 627   // Else hit a Region.  Check for a loop header
 628   if( dom->is_Loop() )
 629     return dom->in(1);          // Skip up thru loops
 630 
 631   // Check for small diamonds
 632   Node *din1, *din2, *din3, *din4;
 633   if( dom->req() == 3 &&        // 2-path merge point
 634       (din1 = dom ->in(1)) &&   // Left  path exists
 635       (din2 = dom ->in(2)) &&   // Right path exists
 636       (din3 = din1->in(0)) &&   // Left  path up one
 637       (din4 = din2->in(0)) ) {  // Right path up one
 638     if( din3->is_Call() &&      // Handle a slow-path call on either arm
 639         (din3 = din3->in(0)) )
 640       din3 = din3->in(0);
 641     if( din4->is_Call() &&      // Handle a slow-path call on either arm
 642         (din4 = din4->in(0)) )
 643       din4 = din4->in(0);
 644     if (din3 != nullptr && din3 == din4 && din3->is_If()) // Regions not degraded to a copy
 645       return din3;              // Skip around diamonds
 646   }
 647 
 648   // Give up the search at true merges
 649   return nullptr;                  // Dead loop?  Or hit root?
 650 }
 651 
 652 
 653 //------------------------------filtered_int_type--------------------------------
 654 // Return a possibly more restrictive type for val based on condition control flow for an if
 655 const TypeInt* IfNode::filtered_int_type(PhaseGVN* gvn, Node* val, Node* if_proj) {
 656   assert(if_proj &&
 657          (if_proj->Opcode() == Op_IfTrue || if_proj->Opcode() == Op_IfFalse), "expecting an if projection");
 658   if (if_proj->in(0) && if_proj->in(0)->is_If()) {
 659     IfNode* iff = if_proj->in(0)->as_If();
 660     if (iff->in(1) && iff->in(1)->is_Bool()) {
 661       BoolNode* bol = iff->in(1)->as_Bool();
 662       if (bol->in(1) && bol->in(1)->is_Cmp()) {
 663         const CmpNode* cmp  = bol->in(1)->as_Cmp();
 664         if (cmp->in(1) == val) {
 665           const TypeInt* cmp2_t = gvn->type(cmp->in(2))->isa_int();
 666           if (cmp2_t != nullptr) {
 667             jint lo = cmp2_t->_lo;
 668             jint hi = cmp2_t->_hi;
 669             BoolTest::mask msk = if_proj->Opcode() == Op_IfTrue ? bol->_test._test : bol->_test.negate();
 670             switch (msk) {
 671             case BoolTest::ne: {
 672               // If val is compared to its lower or upper bound, we can narrow the type
 673               const TypeInt* val_t = gvn->type(val)->isa_int();
 674               if (val_t != nullptr && !val_t->singleton() && cmp2_t->is_con()) {
 675                 if (val_t->_lo == lo) {
 676                   return TypeInt::make(val_t->_lo + 1, val_t->_hi, val_t->_widen);
 677                 } else if (val_t->_hi == hi) {
 678                   return TypeInt::make(val_t->_lo, val_t->_hi - 1, val_t->_widen);
 679                 }
 680               }
 681               // Can't refine type
 682               return nullptr;
 683             }
 684             case BoolTest::eq:
 685               return cmp2_t;
 686             case BoolTest::lt:
 687               lo = TypeInt::INT->_lo;
 688               if (hi != min_jint) {
 689                 hi = hi - 1;
 690               }
 691               break;
 692             case BoolTest::le:
 693               lo = TypeInt::INT->_lo;
 694               break;
 695             case BoolTest::gt:
 696               if (lo != max_jint) {
 697                 lo = lo + 1;
 698               }
 699               hi = TypeInt::INT->_hi;
 700               break;
 701             case BoolTest::ge:
 702               // lo unchanged
 703               hi = TypeInt::INT->_hi;
 704               break;
 705             default:
 706               break;
 707             }
 708             const TypeInt* rtn_t = TypeInt::make(lo, hi, cmp2_t->_widen);
 709             return rtn_t;
 710           }
 711         }
 712       }
 713     }
 714   }
 715   return nullptr;
 716 }
 717 
 718 //------------------------------fold_compares----------------------------
 719 // See if a pair of CmpIs can be converted into a CmpU.  In some cases
 720 // the direction of this if is determined by the preceding if so it
 721 // can be eliminate entirely.
 722 //
 723 // Given an if testing (CmpI n v) check for an immediately control
 724 // dependent if that is testing (CmpI n v2) and has one projection
 725 // leading to this if and the other projection leading to a region
 726 // that merges one of this ifs control projections.
 727 //
 728 //                   If
 729 //                  / |
 730 //                 /  |
 731 //                /   |
 732 //              If    |
 733 //              /\    |
 734 //             /  \   |
 735 //            /    \  |
 736 //           /    Region
 737 //
 738 // Or given an if testing (CmpI n v) check for a dominating if that is
 739 // testing (CmpI n v2), both having one projection leading to an
 740 // uncommon trap. Allow Another independent guard in between to cover
 741 // an explicit range check:
 742 // if (index < 0 || index >= array.length) {
 743 // which may need a null check to guard the LoadRange
 744 //
 745 //                   If
 746 //                  / \
 747 //                 /   \
 748 //                /     \
 749 //              If      unc
 750 //              /\
 751 //             /  \
 752 //            /    \
 753 //           /      unc
 754 //
 755 
 756 // Is the comparison for this If suitable for folding?
 757 bool IfNode::cmpi_folds(PhaseIterGVN* igvn, bool fold_ne) {
 758   return in(1) != nullptr &&
 759     in(1)->is_Bool() &&
 760     in(1)->in(1) != nullptr &&
 761     in(1)->in(1)->Opcode() == Op_CmpI &&
 762     in(1)->in(1)->in(2) != nullptr &&
 763     in(1)->in(1)->in(2) != igvn->C->top() &&
 764     (in(1)->as_Bool()->_test.is_less() ||
 765      in(1)->as_Bool()->_test.is_greater() ||
 766      (fold_ne && in(1)->as_Bool()->_test._test == BoolTest::ne));
 767 }
 768 
 769 // Is a dominating control suitable for folding with this if?
 770 bool IfNode::is_ctrl_folds(Node* ctrl, PhaseIterGVN* igvn) {
 771   return ctrl != nullptr &&
 772     ctrl->is_Proj() &&
 773     ctrl->outcnt() == 1 && // No side-effects
 774     ctrl->in(0) != nullptr &&
 775     ctrl->in(0)->Opcode() == Op_If &&
 776     ctrl->in(0)->outcnt() == 2 &&
 777     ctrl->in(0)->as_If()->cmpi_folds(igvn, true) &&
 778     // Must compare same value
 779     ctrl->in(0)->in(1)->in(1)->in(1) != nullptr &&
 780     ctrl->in(0)->in(1)->in(1)->in(1) != igvn->C->top() &&
 781     ctrl->in(0)->in(1)->in(1)->in(1) == in(1)->in(1)->in(1);
 782 }
 783 
 784 // Do this If and the dominating If share a region?
 785 bool IfNode::has_shared_region(ProjNode* proj, ProjNode*& success, ProjNode*& fail) {
 786   ProjNode* otherproj = proj->other_if_proj();
 787   Node* otherproj_ctrl_use = otherproj->unique_ctrl_out_or_null();
 788   RegionNode* region = (otherproj_ctrl_use != nullptr && otherproj_ctrl_use->is_Region()) ? otherproj_ctrl_use->as_Region() : nullptr;
 789   success = nullptr;
 790   fail = nullptr;
 791 
 792   if (otherproj->outcnt() == 1 && region != nullptr && !region->has_phi()) {
 793     for (int i = 0; i < 2; i++) {
 794       ProjNode* proj = proj_out(i);
 795       if (success == nullptr && proj->outcnt() == 1 && proj->unique_out() == region) {
 796         success = proj;
 797       } else if (fail == nullptr) {
 798         fail = proj;
 799       } else {
 800         success = fail = nullptr;
 801       }
 802     }
 803   }
 804   return success != nullptr && fail != nullptr;
 805 }
 806 
 807 bool IfNode::is_dominator_unc(CallStaticJavaNode* dom_unc, CallStaticJavaNode* unc) {
 808   // Different methods and methods containing jsrs are not supported.
 809   ciMethod* method = unc->jvms()->method();
 810   ciMethod* dom_method = dom_unc->jvms()->method();
 811   if (method != dom_method || method->has_jsrs()) {
 812     return false;
 813   }
 814   // Check that both traps are in the same activation of the method (instead
 815   // of two activations being inlined through different call sites) by verifying
 816   // that the call stacks are equal for both JVMStates.
 817   JVMState* dom_caller = dom_unc->jvms()->caller();
 818   JVMState* caller = unc->jvms()->caller();
 819   if ((dom_caller == nullptr) != (caller == nullptr)) {
 820     // The current method must either be inlined into both dom_caller and
 821     // caller or must not be inlined at all (top method). Bail out otherwise.
 822     return false;
 823   } else if (dom_caller != nullptr && !dom_caller->same_calls_as(caller)) {
 824     return false;
 825   }
 826   // Check that the bci of the dominating uncommon trap dominates the bci
 827   // of the dominated uncommon trap. Otherwise we may not re-execute
 828   // the dominated check after deoptimization from the merged uncommon trap.
 829   ciTypeFlow* flow = dom_method->get_flow_analysis();
 830   int bci = unc->jvms()->bci();
 831   int dom_bci = dom_unc->jvms()->bci();
 832   if (!flow->is_dominated_by(bci, dom_bci)) {
 833     return false;
 834   }
 835 
 836   return true;
 837 }
 838 
 839 // Return projection that leads to an uncommon trap if any
 840 ProjNode* IfNode::uncommon_trap_proj(CallStaticJavaNode*& call, Deoptimization::DeoptReason reason) const {
 841   for (int i = 0; i < 2; i++) {
 842     call = proj_out(i)->is_uncommon_trap_proj(reason);
 843     if (call != nullptr) {
 844       return proj_out(i);
 845     }
 846   }
 847   return nullptr;
 848 }
 849 
 850 // Do this If and the dominating If both branch out to an uncommon trap
 851 bool IfNode::has_only_uncommon_traps(ProjNode* proj, ProjNode*& success, ProjNode*& fail, PhaseIterGVN* igvn) {
 852   ProjNode* otherproj = proj->other_if_proj();
 853   CallStaticJavaNode* dom_unc = otherproj->is_uncommon_trap_proj();
 854 
 855   if (otherproj->outcnt() == 1 && dom_unc != nullptr) {
 856     // We need to re-execute the folded Ifs after deoptimization from the merged traps
 857     if (!dom_unc->jvms()->should_reexecute()) {
 858       return false;
 859     }
 860 
 861     CallStaticJavaNode* unc = nullptr;
 862     ProjNode* unc_proj = uncommon_trap_proj(unc);
 863     if (unc_proj != nullptr && unc_proj->outcnt() == 1) {
 864       if (dom_unc == unc) {
 865         // Allow the uncommon trap to be shared through a region
 866         RegionNode* r = unc->in(0)->as_Region();
 867         if (r->outcnt() != 2 || r->req() != 3 || r->find_edge(otherproj) == -1 || r->find_edge(unc_proj) == -1) {
 868           return false;
 869         }
 870         assert(r->has_phi() == nullptr, "simple region shouldn't have a phi");
 871       } else if (dom_unc->in(0) != otherproj || unc->in(0) != unc_proj) {
 872         return false;
 873       }
 874 
 875       if (!is_dominator_unc(dom_unc, unc)) {
 876         return false;
 877       }
 878 
 879       // See merge_uncommon_traps: the reason of the uncommon trap
 880       // will be changed and the state of the dominating If will be
 881       // used. Checked that we didn't apply this transformation in a
 882       // previous compilation and it didn't cause too many traps
 883       ciMethod* dom_method = dom_unc->jvms()->method();
 884       int dom_bci = dom_unc->jvms()->bci();
 885       if (!igvn->C->too_many_traps(dom_method, dom_bci, Deoptimization::Reason_unstable_fused_if) &&
 886           !igvn->C->too_many_traps(dom_method, dom_bci, Deoptimization::Reason_range_check) &&
 887           // Return true if c2 manages to reconcile with UnstableIf optimization. See the comments for it.
 888           igvn->C->remove_unstable_if_trap(dom_unc, true/*yield*/)) {
 889         success = unc_proj;
 890         fail = unc_proj->other_if_proj();
 891         return true;
 892       }
 893     }
 894   }
 895   return false;
 896 }
 897 
 898 // Check that the 2 CmpI can be folded into as single CmpU and proceed with the folding
 899 bool IfNode::fold_compares_helper(ProjNode* proj, ProjNode* success, ProjNode* fail, PhaseIterGVN* igvn) {
 900   Node* this_cmp = in(1)->in(1);
 901   BoolNode* this_bool = in(1)->as_Bool();
 902   IfNode* dom_iff = proj->in(0)->as_If();
 903   BoolNode* dom_bool = dom_iff->in(1)->as_Bool();
 904   Node* lo = dom_iff->in(1)->in(1)->in(2);
 905   Node* hi = this_cmp->in(2);
 906   Node* n = this_cmp->in(1);
 907   ProjNode* otherproj = proj->other_if_proj();
 908 
 909   const TypeInt* lo_type = IfNode::filtered_int_type(igvn, n, otherproj);
 910   const TypeInt* hi_type = IfNode::filtered_int_type(igvn, n, success);
 911 
 912   BoolTest::mask lo_test = dom_bool->_test._test;
 913   BoolTest::mask hi_test = this_bool->_test._test;
 914   BoolTest::mask cond = hi_test;
 915 
 916   // convert:
 917   //
 918   //          dom_bool = x {<,<=,>,>=} a
 919   //                           / \
 920   //     proj = {True,False}  /   \ otherproj = {False,True}
 921   //                         /
 922   //        this_bool = x {<,<=} b
 923   //                       / \
 924   //  fail = {True,False} /   \ success = {False,True}
 925   //                     /
 926   //
 927   // (Second test guaranteed canonicalized, first one may not have
 928   // been canonicalized yet)
 929   //
 930   // into:
 931   //
 932   // cond = (x - lo) {<u,<=u,>u,>=u} adjusted_lim
 933   //                       / \
 934   //                 fail /   \ success
 935   //                     /
 936   //
 937 
 938   // Figure out which of the two tests sets the upper bound and which
 939   // sets the lower bound if any.
 940   Node* adjusted_lim = nullptr;
 941   if (lo_type != nullptr && hi_type != nullptr && hi_type->_lo > lo_type->_hi &&
 942       hi_type->_hi == max_jint && lo_type->_lo == min_jint && lo_test != BoolTest::ne) {
 943     assert((dom_bool->_test.is_less() && !proj->_con) ||
 944            (dom_bool->_test.is_greater() && proj->_con), "incorrect test");
 945 
 946     // this_bool = <
 947     //   dom_bool = >= (proj = True) or dom_bool = < (proj = False)
 948     //     x in [a, b[ on the fail (= True) projection, b > a-1 (because of hi_type->_lo > lo_type->_hi test above):
 949     //     lo = a, hi = b, adjusted_lim = b-a, cond = <u
 950     //   dom_bool = > (proj = True) or dom_bool = <= (proj = False)
 951     //     x in ]a, b[ on the fail (= True) projection, b > a:
 952     //     lo = a+1, hi = b, adjusted_lim = b-a-1, cond = <u
 953     // this_bool = <=
 954     //   dom_bool = >= (proj = True) or dom_bool = < (proj = False)
 955     //     x in [a, b] on the fail (= True) projection, b+1 > a-1:
 956     //     lo = a, hi = b, adjusted_lim = b-a+1, cond = <u
 957     //     lo = a, hi = b, adjusted_lim = b-a, cond = <=u doesn't work because b = a - 1 is possible, then b-a = -1
 958     //   dom_bool = > (proj = True) or dom_bool = <= (proj = False)
 959     //     x in ]a, b] on the fail (= True) projection b+1 > a:
 960     //     lo = a+1, hi = b, adjusted_lim = b-a, cond = <u
 961     //     lo = a+1, hi = b, adjusted_lim = b-a-1, cond = <=u doesn't work because a = b is possible, then b-a-1 = -1
 962 
 963     if (hi_test == BoolTest::lt) {
 964       if (lo_test == BoolTest::gt || lo_test == BoolTest::le) {
 965         lo = igvn->transform(new AddINode(lo, igvn->intcon(1)));
 966       }
 967     } else if (hi_test == BoolTest::le) {
 968       if (lo_test == BoolTest::ge || lo_test == BoolTest::lt) {
 969         adjusted_lim = igvn->transform(new SubINode(hi, lo));
 970         adjusted_lim = igvn->transform(new AddINode(adjusted_lim, igvn->intcon(1)));
 971         cond = BoolTest::lt;
 972       } else if (lo_test == BoolTest::gt || lo_test == BoolTest::le) {
 973         adjusted_lim = igvn->transform(new SubINode(hi, lo));
 974         lo = igvn->transform(new AddINode(lo, igvn->intcon(1)));
 975         cond = BoolTest::lt;
 976       } else {
 977         assert(false, "unhandled lo_test: %d", lo_test);
 978         return false;
 979       }
 980     } else {
 981       assert(igvn->_worklist.member(in(1)) && in(1)->Value(igvn) != igvn->type(in(1)), "unhandled hi_test: %d", hi_test);
 982       return false;
 983     }
 984     // this test was canonicalized
 985     assert(this_bool->_test.is_less() && fail->_con, "incorrect test");
 986   } else if (lo_type != nullptr && hi_type != nullptr && lo_type->_lo > hi_type->_hi &&
 987              lo_type->_hi == max_jint && hi_type->_lo == min_jint && lo_test != BoolTest::ne) {
 988 
 989     // this_bool = <
 990     //   dom_bool = < (proj = True) or dom_bool = >= (proj = False)
 991     //     x in [b, a[ on the fail (= False) projection, a > b-1 (because of lo_type->_lo > hi_type->_hi above):
 992     //     lo = b, hi = a, adjusted_lim = a-b, cond = >=u
 993     //   dom_bool = <= (proj = True) or dom_bool = > (proj = False)
 994     //     x in [b, a] on the fail (= False) projection, a+1 > b-1:
 995     //     lo = b, hi = a, adjusted_lim = a-b+1, cond = >=u
 996     //     lo = b, hi = a, adjusted_lim = a-b, cond = >u doesn't work because a = b - 1 is possible, then b-a = -1
 997     // this_bool = <=
 998     //   dom_bool = < (proj = True) or dom_bool = >= (proj = False)
 999     //     x in ]b, a[ on the fail (= False) projection, a > b:
1000     //     lo = b+1, hi = a, adjusted_lim = a-b-1, cond = >=u
1001     //   dom_bool = <= (proj = True) or dom_bool = > (proj = False)
1002     //     x in ]b, a] on the fail (= False) projection, a+1 > b:
1003     //     lo = b+1, hi = a, adjusted_lim = a-b, cond = >=u
1004     //     lo = b+1, hi = a, adjusted_lim = a-b-1, cond = >u doesn't work because a = b is possible, then b-a-1 = -1
1005 
1006     swap(lo, hi);
1007     swap(lo_type, hi_type);
1008     swap(lo_test, hi_test);
1009 
1010     assert((dom_bool->_test.is_less() && proj->_con) ||
1011            (dom_bool->_test.is_greater() && !proj->_con), "incorrect test");
1012 
1013     cond = (hi_test == BoolTest::le || hi_test == BoolTest::gt) ? BoolTest::gt : BoolTest::ge;
1014 
1015     if (lo_test == BoolTest::lt) {
1016       if (hi_test == BoolTest::lt || hi_test == BoolTest::ge) {
1017         cond = BoolTest::ge;
1018       } else if (hi_test == BoolTest::le || hi_test == BoolTest::gt) {
1019         adjusted_lim = igvn->transform(new SubINode(hi, lo));
1020         adjusted_lim = igvn->transform(new AddINode(adjusted_lim, igvn->intcon(1)));
1021         cond = BoolTest::ge;
1022       } else {
1023         assert(false, "unhandled hi_test: %d", hi_test);
1024         return false;
1025       }
1026     } else if (lo_test == BoolTest::le) {
1027       if (hi_test == BoolTest::lt || hi_test == BoolTest::ge) {
1028         lo = igvn->transform(new AddINode(lo, igvn->intcon(1)));
1029         cond = BoolTest::ge;
1030       } else if (hi_test == BoolTest::le || hi_test == BoolTest::gt) {
1031         adjusted_lim = igvn->transform(new SubINode(hi, lo));
1032         lo = igvn->transform(new AddINode(lo, igvn->intcon(1)));
1033         cond = BoolTest::ge;
1034       } else {
1035         assert(false, "unhandled hi_test: %d", hi_test);
1036         return false;
1037       }
1038     } else {
1039       assert(igvn->_worklist.member(in(1)) && in(1)->Value(igvn) != igvn->type(in(1)), "unhandled lo_test: %d", lo_test);
1040       return false;
1041     }
1042     // this test was canonicalized
1043     assert(this_bool->_test.is_less() && !fail->_con, "incorrect test");
1044   } else {
1045     const TypeInt* failtype = filtered_int_type(igvn, n, proj);
1046     if (failtype != nullptr) {
1047       const TypeInt* type2 = filtered_int_type(igvn, n, fail);
1048       if (type2 != nullptr) {
1049         failtype = failtype->join(type2)->is_int();
1050         if (failtype->empty()) {
1051           // previous if determines the result of this if so
1052           // replace Bool with constant
1053           igvn->replace_input_of(this, 1, igvn->intcon(success->_con));
1054           return true;
1055         }
1056       }
1057     }
1058     return false;
1059   }
1060 
1061   assert(lo != nullptr && hi != nullptr, "sanity");
1062   Node* hook = new Node(lo); // Add a use to lo to prevent him from dying
1063   // Merge the two compares into a single unsigned compare by building (CmpU (n - lo) (hi - lo))
1064   Node* adjusted_val = igvn->transform(new SubINode(n,  lo));
1065   if (adjusted_lim == nullptr) {
1066     adjusted_lim = igvn->transform(new SubINode(hi, lo));
1067   }
1068   hook->destruct(igvn);
1069 
1070   if (adjusted_val->is_top() || adjusted_lim->is_top()) {
1071     return false;
1072   }
1073 
1074   if (igvn->type(adjusted_lim)->is_int()->_lo < 0 &&
1075       !igvn->C->post_loop_opts_phase()) {
1076     // If range check elimination applies to this comparison, it includes code to protect from overflows that may
1077     // cause the main loop to be skipped entirely. Delay this transformation.
1078     // Example:
1079     // for (int i = 0; i < limit; i++) {
1080     //   if (i < max_jint && i > min_jint) {...
1081     // }
1082     // Comparisons folded as:
1083     // i - min_jint - 1 <u -2
1084     // when RC applies, main loop limit becomes:
1085     // min(limit, max(-2 + min_jint + 1, min_jint))
1086     // = min(limit, min_jint)
1087     // = min_jint
1088     if (adjusted_val->outcnt() == 0) {
1089       igvn->remove_dead_node(adjusted_val);
1090     }
1091     if (adjusted_lim->outcnt() == 0) {
1092       igvn->remove_dead_node(adjusted_lim);
1093     }
1094     igvn->C->record_for_post_loop_opts_igvn(this);
1095     return false;
1096   }
1097 
1098   Node* newcmp = igvn->transform(new CmpUNode(adjusted_val, adjusted_lim));
1099   Node* newbool = igvn->transform(new BoolNode(newcmp, cond));
1100 
1101   igvn->replace_input_of(dom_iff, 1, igvn->intcon(proj->_con));
1102   igvn->replace_input_of(this, 1, newbool);
1103 
1104   return true;
1105 }
1106 
1107 // Merge the branches that trap for this If and the dominating If into
1108 // a single region that branches to the uncommon trap for the
1109 // dominating If
1110 Node* IfNode::merge_uncommon_traps(ProjNode* proj, ProjNode* success, ProjNode* fail, PhaseIterGVN* igvn) {
1111   Node* res = this;
1112   assert(success->in(0) == this, "bad projection");
1113 
1114   ProjNode* otherproj = proj->other_if_proj();
1115 
1116   CallStaticJavaNode* unc = success->is_uncommon_trap_proj();
1117   CallStaticJavaNode* dom_unc = otherproj->is_uncommon_trap_proj();
1118 
1119   if (unc != dom_unc) {
1120     Node* r = new RegionNode(3);
1121 
1122     r->set_req(1, otherproj);
1123     r->set_req(2, success);
1124     r = igvn->transform(r);
1125     assert(r->is_Region(), "can't go away");
1126 
1127     // Make both If trap at the state of the first If: once the CmpI
1128     // nodes are merged, if we trap we don't know which of the CmpI
1129     // nodes would have caused the trap so we have to restart
1130     // execution at the first one
1131     igvn->replace_input_of(dom_unc, 0, r);
1132     igvn->replace_input_of(unc, 0, igvn->C->top());
1133   }
1134   int trap_request = dom_unc->uncommon_trap_request();
1135   Deoptimization::DeoptReason reason = Deoptimization::trap_request_reason(trap_request);
1136   Deoptimization::DeoptAction action = Deoptimization::trap_request_action(trap_request);
1137 
1138   int flip_test = 0;
1139   Node* l = nullptr;
1140   Node* r = nullptr;
1141 
1142   if (success->in(0)->as_If()->range_check_trap_proj(flip_test, l, r) != nullptr) {
1143     // If this looks like a range check, change the trap to
1144     // Reason_range_check so the compiler recognizes it as a range
1145     // check and applies the corresponding optimizations
1146     trap_request = Deoptimization::make_trap_request(Deoptimization::Reason_range_check, action);
1147 
1148     improve_address_types(l, r, fail, igvn);
1149 
1150     res = igvn->transform(new RangeCheckNode(in(0), in(1), _prob, _fcnt));
1151   } else if (unc != dom_unc) {
1152     // If we trap we won't know what CmpI would have caused the trap
1153     // so use a special trap reason to mark this pair of CmpI nodes as
1154     // bad candidate for folding. On recompilation we won't fold them
1155     // and we may trap again but this time we'll know what branch
1156     // traps
1157     trap_request = Deoptimization::make_trap_request(Deoptimization::Reason_unstable_fused_if, action);
1158   }
1159   igvn->replace_input_of(dom_unc, TypeFunc::Parms, igvn->intcon(trap_request));
1160   return res;
1161 }
1162 
1163 // If we are turning 2 CmpI nodes into a CmpU that follows the pattern
1164 // of a rangecheck on index i, on 64 bit the compares may be followed
1165 // by memory accesses using i as index. In that case, the CmpU tells
1166 // us something about the values taken by i that can help the compiler
1167 // (see Compile::conv_I2X_index())
1168 void IfNode::improve_address_types(Node* l, Node* r, ProjNode* fail, PhaseIterGVN* igvn) {
1169 #ifdef _LP64
1170   ResourceMark rm;
1171   Node_Stack stack(2);
1172 
1173   assert(r->Opcode() == Op_LoadRange, "unexpected range check");
1174   const TypeInt* array_size = igvn->type(r)->is_int();
1175 
1176   stack.push(l, 0);
1177 
1178   while(stack.size() > 0) {
1179     Node* n = stack.node();
1180     uint start = stack.index();
1181 
1182     uint i = start;
1183     for (; i < n->outcnt(); i++) {
1184       Node* use = n->raw_out(i);
1185       if (stack.size() == 1) {
1186         if (use->Opcode() == Op_ConvI2L) {
1187           const TypeLong* bounds = use->as_Type()->type()->is_long();
1188           if (bounds->_lo <= array_size->_lo && bounds->_hi >= array_size->_hi &&
1189               (bounds->_lo != array_size->_lo || bounds->_hi != array_size->_hi)) {
1190             stack.set_index(i+1);
1191             stack.push(use, 0);
1192             break;
1193           }
1194         }
1195       } else if (use->is_Mem()) {
1196         Node* ctrl = use->in(0);
1197         for (int i = 0; i < 10 && ctrl != nullptr && ctrl != fail; i++) {
1198           ctrl = up_one_dom(ctrl);
1199         }
1200         if (ctrl == fail) {
1201           Node* init_n = stack.node_at(1);
1202           assert(init_n->Opcode() == Op_ConvI2L, "unexpected first node");
1203           // Create a new narrow ConvI2L node that is dependent on the range check
1204           Node* new_n = igvn->C->conv_I2X_index(igvn, l, array_size, fail);
1205 
1206           // The type of the ConvI2L may be widen and so the new
1207           // ConvI2L may not be better than an existing ConvI2L
1208           if (new_n != init_n) {
1209             for (uint j = 2; j < stack.size(); j++) {
1210               Node* n = stack.node_at(j);
1211               Node* clone = n->clone();
1212               int rep = clone->replace_edge(init_n, new_n, igvn);
1213               assert(rep > 0, "can't find expected node?");
1214               clone = igvn->transform(clone);
1215               init_n = n;
1216               new_n = clone;
1217             }
1218             igvn->hash_delete(use);
1219             int rep = use->replace_edge(init_n, new_n, igvn);
1220             assert(rep > 0, "can't find expected node?");
1221             igvn->transform(use);
1222             if (init_n->outcnt() == 0) {
1223               igvn->_worklist.push(init_n);
1224             }
1225           }
1226         }
1227       } else if (use->in(0) == nullptr && (igvn->type(use)->isa_long() ||
1228                                         igvn->type(use)->isa_ptr())) {
1229         stack.set_index(i+1);
1230         stack.push(use, 0);
1231         break;
1232       }
1233     }
1234     if (i == n->outcnt()) {
1235       stack.pop();
1236     }
1237   }
1238 #endif
1239 }
1240 
1241 bool IfNode::is_cmp_with_loadrange(ProjNode* proj) {
1242   if (in(1) != nullptr &&
1243       in(1)->in(1) != nullptr &&
1244       in(1)->in(1)->in(2) != nullptr) {
1245     Node* other = in(1)->in(1)->in(2);
1246     if (other->Opcode() == Op_LoadRange &&
1247         ((other->in(0) != nullptr && other->in(0) == proj) ||
1248          (other->in(0) == nullptr &&
1249           other->in(2) != nullptr &&
1250           other->in(2)->is_AddP() &&
1251           other->in(2)->in(1) != nullptr &&
1252           other->in(2)->in(1)->Opcode() == Op_CastPP &&
1253           other->in(2)->in(1)->in(0) == proj))) {
1254       return true;
1255     }
1256   }
1257   return false;
1258 }
1259 
1260 bool IfNode::is_null_check(ProjNode* proj, PhaseIterGVN* igvn) {
1261   Node* other = in(1)->in(1)->in(2);
1262   if (other->in(MemNode::Address) != nullptr &&
1263       proj->in(0)->in(1) != nullptr &&
1264       proj->in(0)->in(1)->is_Bool() &&
1265       proj->in(0)->in(1)->in(1) != nullptr &&
1266       proj->in(0)->in(1)->in(1)->Opcode() == Op_CmpP &&
1267       proj->in(0)->in(1)->in(1)->in(2) != nullptr &&
1268       proj->in(0)->in(1)->in(1)->in(1) == other->in(MemNode::Address)->in(AddPNode::Address)->uncast() &&
1269       igvn->type(proj->in(0)->in(1)->in(1)->in(2)) == TypePtr::NULL_PTR) {
1270     return true;
1271   }
1272   return false;
1273 }
1274 
1275 // Returns true if this IfNode belongs to a flat array check
1276 // and returns the corresponding array in the 'array' parameter.
1277 bool IfNode::is_flat_array_check(PhaseTransform* phase, Node** array) {
1278   Node* bol = in(1);
1279   if (!bol->is_Bool()) {
1280     return false;
1281   }
1282   Node* cmp = bol->in(1);
1283   if (cmp->isa_FlatArrayCheck()) {
1284     if (array != nullptr) {
1285       *array = cmp->in(FlatArrayCheckNode::ArrayOrKlass);
1286     }
1287     return true;
1288   }
1289   return false;
1290 }
1291 
1292 // Check that the If that is in between the 2 integer comparisons has
1293 // no side effect
1294 bool IfNode::is_side_effect_free_test(ProjNode* proj, PhaseIterGVN* igvn) {
1295   if (proj == nullptr) {
1296     return false;
1297   }
1298   CallStaticJavaNode* unc = proj->is_uncommon_trap_if_pattern();
1299   if (unc != nullptr && proj->outcnt() <= 2) {
1300     if (proj->outcnt() == 1 ||
1301         // Allow simple null check from LoadRange
1302         (is_cmp_with_loadrange(proj) && is_null_check(proj, igvn))) {
1303       CallStaticJavaNode* unc = proj->is_uncommon_trap_if_pattern();
1304       CallStaticJavaNode* dom_unc = proj->in(0)->in(0)->as_Proj()->is_uncommon_trap_if_pattern();
1305       assert(dom_unc != nullptr, "is_uncommon_trap_if_pattern returned null");
1306 
1307       // reroute_side_effect_free_unc changes the state of this
1308       // uncommon trap to restart execution at the previous
1309       // CmpI. Check that this change in a previous compilation didn't
1310       // cause too many traps.
1311       int trap_request = unc->uncommon_trap_request();
1312       Deoptimization::DeoptReason reason = Deoptimization::trap_request_reason(trap_request);
1313 
1314       if (igvn->C->too_many_traps(dom_unc->jvms()->method(), dom_unc->jvms()->bci(), reason)) {
1315         return false;
1316       }
1317 
1318       if (!is_dominator_unc(dom_unc, unc)) {
1319         return false;
1320       }
1321 
1322       return true;
1323     }
1324   }
1325   return false;
1326 }
1327 
1328 // Make the If between the 2 integer comparisons trap at the state of
1329 // the first If: the last CmpI is the one replaced by a CmpU and the
1330 // first CmpI is eliminated, so the test between the 2 CmpI nodes
1331 // won't be guarded by the first CmpI anymore. It can trap in cases
1332 // where the first CmpI would have prevented it from executing: on a
1333 // trap, we need to restart execution at the state of the first CmpI
1334 void IfNode::reroute_side_effect_free_unc(ProjNode* proj, ProjNode* dom_proj, PhaseIterGVN* igvn) {
1335   CallStaticJavaNode* dom_unc = dom_proj->is_uncommon_trap_if_pattern();
1336   ProjNode* otherproj = proj->other_if_proj();
1337   CallStaticJavaNode* unc = proj->is_uncommon_trap_if_pattern();
1338   Node* call_proj = dom_unc->unique_ctrl_out();
1339   Node* halt = call_proj->unique_ctrl_out();
1340 
1341   Node* new_unc = dom_unc->clone();
1342   call_proj = call_proj->clone();
1343   halt = halt->clone();
1344   Node* c = otherproj->clone();
1345 
1346   c = igvn->transform(c);
1347   new_unc->set_req(TypeFunc::Parms, unc->in(TypeFunc::Parms));
1348   new_unc->set_req(0, c);
1349   new_unc = igvn->transform(new_unc);
1350   call_proj->set_req(0, new_unc);
1351   call_proj = igvn->transform(call_proj);
1352   halt->set_req(0, call_proj);
1353   halt = igvn->transform(halt);
1354 
1355   igvn->replace_node(otherproj, igvn->C->top());
1356   igvn->C->root()->add_req(halt);
1357 }
1358 
1359 Node* IfNode::fold_compares(PhaseIterGVN* igvn) {
1360   if (Opcode() != Op_If) return nullptr;
1361 
1362   if (cmpi_folds(igvn)) {
1363     Node* ctrl = in(0);
1364     if (is_ctrl_folds(ctrl, igvn)) {
1365       // A integer comparison immediately dominated by another integer
1366       // comparison
1367       ProjNode* success = nullptr;
1368       ProjNode* fail = nullptr;
1369       ProjNode* dom_cmp = ctrl->as_Proj();
1370       if (has_shared_region(dom_cmp, success, fail) &&
1371           // Next call modifies graph so must be last
1372           fold_compares_helper(dom_cmp, success, fail, igvn)) {
1373         return this;
1374       }
1375       if (has_only_uncommon_traps(dom_cmp, success, fail, igvn) &&
1376           // Next call modifies graph so must be last
1377           fold_compares_helper(dom_cmp, success, fail, igvn)) {
1378         return merge_uncommon_traps(dom_cmp, success, fail, igvn);
1379       }
1380       return nullptr;
1381     } else if (ctrl->in(0) != nullptr &&
1382                ctrl->in(0)->in(0) != nullptr) {
1383       ProjNode* success = nullptr;
1384       ProjNode* fail = nullptr;
1385       Node* dom = ctrl->in(0)->in(0);
1386       ProjNode* dom_cmp = dom->isa_Proj();
1387       ProjNode* other_cmp = ctrl->isa_Proj();
1388 
1389       // Check if it's an integer comparison dominated by another
1390       // integer comparison with another test in between
1391       if (is_ctrl_folds(dom, igvn) &&
1392           has_only_uncommon_traps(dom_cmp, success, fail, igvn) &&
1393           is_side_effect_free_test(other_cmp, igvn) &&
1394           // Next call modifies graph so must be last
1395           fold_compares_helper(dom_cmp, success, fail, igvn)) {
1396         reroute_side_effect_free_unc(other_cmp, dom_cmp, igvn);
1397         return merge_uncommon_traps(dom_cmp, success, fail, igvn);
1398       }
1399     }
1400   }
1401   return nullptr;
1402 }
1403 
1404 //------------------------------remove_useless_bool----------------------------
1405 // Check for people making a useless boolean: things like
1406 // if( (x < y ? true : false) ) { ... }
1407 // Replace with if( x < y ) { ... }
1408 static Node *remove_useless_bool(IfNode *iff, PhaseGVN *phase) {
1409   Node *i1 = iff->in(1);
1410   if( !i1->is_Bool() ) return nullptr;
1411   BoolNode *bol = i1->as_Bool();
1412 
1413   Node *cmp = bol->in(1);
1414   if( cmp->Opcode() != Op_CmpI ) return nullptr;
1415 
1416   // Must be comparing against a bool
1417   const Type *cmp2_t = phase->type( cmp->in(2) );
1418   if( cmp2_t != TypeInt::ZERO &&
1419       cmp2_t != TypeInt::ONE )
1420     return nullptr;
1421 
1422   // Find a prior merge point merging the boolean
1423   i1 = cmp->in(1);
1424   if( !i1->is_Phi() ) return nullptr;
1425   PhiNode *phi = i1->as_Phi();
1426   if( phase->type( phi ) != TypeInt::BOOL )
1427     return nullptr;
1428 
1429   // Check for diamond pattern
1430   int true_path = phi->is_diamond_phi();
1431   if( true_path == 0 ) return nullptr;
1432 
1433   // Make sure that iff and the control of the phi are different. This
1434   // should really only happen for dead control flow since it requires
1435   // an illegal cycle.
1436   if (phi->in(0)->in(1)->in(0) == iff) return nullptr;
1437 
1438   // phi->region->if_proj->ifnode->bool->cmp
1439   BoolNode *bol2 = phi->in(0)->in(1)->in(0)->in(1)->as_Bool();
1440 
1441   // Now get the 'sense' of the test correct so we can plug in
1442   // either iff2->in(1) or its complement.
1443   int flip = 0;
1444   if( bol->_test._test == BoolTest::ne ) flip = 1-flip;
1445   else if( bol->_test._test != BoolTest::eq ) return nullptr;
1446   if( cmp2_t == TypeInt::ZERO ) flip = 1-flip;
1447 
1448   const Type *phi1_t = phase->type( phi->in(1) );
1449   const Type *phi2_t = phase->type( phi->in(2) );
1450   // Check for Phi(0,1) and flip
1451   if( phi1_t == TypeInt::ZERO ) {
1452     if( phi2_t != TypeInt::ONE ) return nullptr;
1453     flip = 1-flip;
1454   } else {
1455     // Check for Phi(1,0)
1456     if( phi1_t != TypeInt::ONE  ) return nullptr;
1457     if( phi2_t != TypeInt::ZERO ) return nullptr;
1458   }
1459   if( true_path == 2 ) {
1460     flip = 1-flip;
1461   }
1462 
1463   Node* new_bol = (flip ? phase->transform( bol2->negate(phase) ) : bol2);
1464   assert(new_bol != iff->in(1), "must make progress");
1465   iff->set_req_X(1, new_bol, phase);
1466   // Intervening diamond probably goes dead
1467   phase->C->set_major_progress();
1468   return iff;
1469 }
1470 
1471 static IfNode* idealize_test(PhaseGVN* phase, IfNode* iff);
1472 
1473 struct RangeCheck {
1474   IfProjNode* ctl;
1475   jint off;
1476 };
1477 
1478 Node* IfNode::Ideal_common(PhaseGVN *phase, bool can_reshape) {
1479   if (remove_dead_region(phase, can_reshape))  return this;
1480   // No Def-Use info?
1481   if (!can_reshape)  return nullptr;
1482 
1483   // Don't bother trying to transform a dead if
1484   if (in(0)->is_top())  return nullptr;
1485   // Don't bother trying to transform an if with a dead test
1486   if (in(1)->is_top())  return nullptr;
1487   // Another variation of a dead test
1488   if (in(1)->is_Con())  return nullptr;
1489   // Another variation of a dead if
1490   if (outcnt() < 2)  return nullptr;
1491 
1492   // Canonicalize the test.
1493   Node* idt_if = idealize_test(phase, this);
1494   if (idt_if != nullptr)  return idt_if;
1495 
1496   // Try to split the IF
1497   PhaseIterGVN *igvn = phase->is_IterGVN();
1498   Node *s = split_if(this, igvn);
1499   if (s != nullptr)  return s;
1500 
1501   return NodeSentinel;
1502 }
1503 
1504 //------------------------------Ideal------------------------------------------
1505 // Return a node which is more "ideal" than the current node.  Strip out
1506 // control copies
1507 Node* IfNode::Ideal(PhaseGVN *phase, bool can_reshape) {
1508   Node* res = Ideal_common(phase, can_reshape);
1509   if (res != NodeSentinel) {
1510     return res;
1511   }
1512 
1513   // Check for people making a useless boolean: things like
1514   // if( (x < y ? true : false) ) { ... }
1515   // Replace with if( x < y ) { ... }
1516   Node* bol2 = remove_useless_bool(this, phase);
1517   if (bol2) return bol2;
1518 
1519   if (in(0) == nullptr) return nullptr;     // Dead loop?
1520 
1521   PhaseIterGVN* igvn = phase->is_IterGVN();
1522   Node* result = fold_compares(igvn);
1523   if (result != nullptr) {
1524     return result;
1525   }
1526 
1527   // Scan for an equivalent test
1528   int dist = 4;               // Cutoff limit for search
1529   if (is_If() && in(1)->is_Bool()) {
1530     Node* cmp = in(1)->in(1);
1531     if (cmp->Opcode() == Op_CmpP &&
1532         cmp->in(2) != nullptr && // make sure cmp is not already dead
1533         cmp->in(2)->bottom_type() == TypePtr::NULL_PTR) {
1534       dist = 64;              // Limit for null-pointer scans
1535     }
1536   }
1537 
1538   Node* prev_dom = search_identical(dist, igvn);
1539 
1540   if (prev_dom != nullptr) {
1541     // Dominating CountedLoopEnd (left over from some now dead loop) will become the new loop exit. Outer strip mined
1542     // loop will go away. Mark this loop as no longer strip mined.
1543     if (is_CountedLoopEnd()) {
1544       CountedLoopNode* counted_loop_node = as_CountedLoopEnd()->loopnode();
1545       if (counted_loop_node != nullptr) {
1546         counted_loop_node->clear_strip_mined();
1547       }
1548     }
1549     // Replace dominated IfNode
1550     return dominated_by(prev_dom, igvn, false);
1551   }
1552 
1553   return simple_subsuming(igvn);
1554 }
1555 
1556 //------------------------------dominated_by-----------------------------------
1557 Node* IfNode::dominated_by(Node* prev_dom, PhaseIterGVN* igvn, bool pin_array_access_nodes) {
1558 #ifndef PRODUCT
1559   if (TraceIterativeGVN) {
1560     tty->print("   Removing IfNode: "); this->dump();
1561   }
1562 #endif
1563 
1564   igvn->hash_delete(this);      // Remove self to prevent spurious V-N
1565   Node *idom = in(0);
1566   // Need opcode to decide which way 'this' test goes
1567   int prev_op = prev_dom->Opcode();
1568   Node *top = igvn->C->top(); // Shortcut to top
1569 
1570   // Now walk the current IfNode's projections.
1571   // Loop ends when 'this' has no more uses.
1572   for (DUIterator_Last imin, i = last_outs(imin); i >= imin; --i) {
1573     Node *ifp = last_out(i);     // Get IfTrue/IfFalse
1574     igvn->add_users_to_worklist(ifp);
1575     // Check which projection it is and set target.
1576     // Data-target is either the dominating projection of the same type
1577     // or TOP if the dominating projection is of opposite type.
1578     // Data-target will be used as the new control edge for the non-CFG
1579     // nodes like Casts and Loads.
1580     Node *data_target = (ifp->Opcode() == prev_op) ? prev_dom : top;
1581     // Control-target is just the If's immediate dominator or TOP.
1582     Node *ctrl_target = (ifp->Opcode() == prev_op) ?     idom : top;
1583 
1584     // For each child of an IfTrue/IfFalse projection, reroute.
1585     // Loop ends when projection has no more uses.
1586     for (DUIterator_Last jmin, j = ifp->last_outs(jmin); j >= jmin; --j) {
1587       Node* s = ifp->last_out(j);   // Get child of IfTrue/IfFalse
1588       if (s->depends_only_on_test() && igvn->no_dependent_zero_check(s)) {
1589         // For control producers.
1590         // Do not rewire Div and Mod nodes which could have a zero divisor to avoid skipping their zero check.
1591         igvn->replace_input_of(s, 0, data_target); // Move child to data-target
1592         if (pin_array_access_nodes && data_target != top) {
1593           // As a result of range check smearing, Loads and range check Cast nodes that are control dependent on this
1594           // range check (that is about to be removed) now depend on multiple dominating range checks. After the removal
1595           // of this range check, these control dependent nodes end up at the lowest/nearest dominating check in the
1596           // graph. To ensure that these Loads/Casts do not float above any of the dominating checks (even when the
1597           // lowest dominating check is later replaced by yet another dominating check), we need to pin them at the
1598           // lowest dominating check.
1599           Node* clone = s->pin_array_access_node();
1600           if (clone != nullptr) {
1601             clone = igvn->transform(clone);
1602             igvn->replace_node(s, clone);
1603           }
1604         }
1605       } else {
1606         // Find the control input matching this def-use edge.
1607         // For Regions it may not be in slot 0.
1608         uint l;
1609         for (l = 0; s->in(l) != ifp; l++) { }
1610         igvn->replace_input_of(s, l, ctrl_target);
1611       }
1612     } // End for each child of a projection
1613 
1614     igvn->remove_dead_node(ifp);
1615   } // End for each IfTrue/IfFalse child of If
1616 
1617   // Kill the IfNode
1618   igvn->remove_dead_node(this);
1619 
1620   // Must return either the original node (now dead) or a new node
1621   // (Do not return a top here, since that would break the uniqueness of top.)
1622   return new ConINode(TypeInt::ZERO);
1623 }
1624 
1625 Node* IfNode::search_identical(int dist, PhaseIterGVN* igvn) {
1626   // Setup to scan up the CFG looking for a dominating test
1627   Node* dom = in(0);
1628   Node* prev_dom = this;
1629   int op = Opcode();
1630   // Search up the dominator tree for an If with an identical test
1631   while (dom->Opcode() != op ||  // Not same opcode?
1632          !same_condition(dom, igvn) ||  // Not same input 1?
1633          prev_dom->in(0) != dom) {  // One path of test does not dominate?
1634     if (dist < 0) return nullptr;
1635 
1636     dist--;
1637     prev_dom = dom;
1638     dom = up_one_dom(dom);
1639     if (!dom) return nullptr;
1640   }
1641 
1642   // Check that we did not follow a loop back to ourselves
1643   if (this == dom) {
1644     return nullptr;
1645   }
1646 
1647 #ifndef PRODUCT
1648   if (dist > 2) { // Add to count of null checks elided
1649     explicit_null_checks_elided++;
1650   }
1651 #endif
1652 
1653   return prev_dom;
1654 }
1655 
1656 bool IfNode::same_condition(const Node* dom, PhaseIterGVN* igvn) const {
1657   Node* dom_bool = dom->in(1);
1658   Node* this_bool = in(1);
1659   if (dom_bool == this_bool) {
1660     return true;
1661   }
1662 
1663   if (dom_bool == nullptr || !dom_bool->is_Bool() ||
1664       this_bool == nullptr || !this_bool->is_Bool()) {
1665     return false;
1666   }
1667   Node* dom_cmp = dom_bool->in(1);
1668   Node* this_cmp = this_bool->in(1);
1669 
1670   // If the comparison is a subtype check, then SubTypeCheck nodes may have profile data attached to them and may be
1671   // different nodes even-though they perform the same subtype check
1672   if (dom_cmp == nullptr || !dom_cmp->is_SubTypeCheck() ||
1673       this_cmp == nullptr || !this_cmp->is_SubTypeCheck()) {
1674     return false;
1675   }
1676 
1677   if (dom_cmp->in(1) != this_cmp->in(1) ||
1678       dom_cmp->in(2) != this_cmp->in(2) ||
1679       dom_bool->as_Bool()->_test._test != this_bool->as_Bool()->_test._test) {
1680     return false;
1681   }
1682 
1683   return true;
1684 }
1685 
1686 
1687 static int subsuming_bool_test_encode(Node*);
1688 
1689 // Check if dominating test is subsuming 'this' one.
1690 //
1691 //              cmp
1692 //              / \
1693 //     (r1)  bool  \
1694 //            /    bool (r2)
1695 //    (dom) if       \
1696 //            \       )
1697 //    (pre)  if[TF]  /
1698 //               \  /
1699 //                if (this)
1700 //   \r1
1701 //  r2\  eqT  eqF  neT  neF  ltT  ltF  leT  leF  gtT  gtF  geT  geF
1702 //  eq    t    f    f    t    f    -    -    f    f    -    -    f
1703 //  ne    f    t    t    f    t    -    -    t    t    -    -    t
1704 //  lt    f    -    -    f    t    f    -    f    f    -    f    t
1705 //  le    t    -    -    t    t    -    t    f    f    t    -    t
1706 //  gt    f    -    -    f    f    -    f    t    t    f    -    f
1707 //  ge    t    -    -    t    f    t    -    t    t    -    t    f
1708 //
1709 Node* IfNode::simple_subsuming(PhaseIterGVN* igvn) {
1710   // Table encoding: N/A (na), True-branch (tb), False-branch (fb).
1711   static enum { na, tb, fb } s_short_circuit_map[6][12] = {
1712   /*rel: eq+T eq+F ne+T ne+F lt+T lt+F le+T le+F gt+T gt+F ge+T ge+F*/
1713   /*eq*/{ tb,  fb,  fb,  tb,  fb,  na,  na,  fb,  fb,  na,  na,  fb },
1714   /*ne*/{ fb,  tb,  tb,  fb,  tb,  na,  na,  tb,  tb,  na,  na,  tb },
1715   /*lt*/{ fb,  na,  na,  fb,  tb,  fb,  na,  fb,  fb,  na,  fb,  tb },
1716   /*le*/{ tb,  na,  na,  tb,  tb,  na,  tb,  fb,  fb,  tb,  na,  tb },
1717   /*gt*/{ fb,  na,  na,  fb,  fb,  na,  fb,  tb,  tb,  fb,  na,  fb },
1718   /*ge*/{ tb,  na,  na,  tb,  fb,  tb,  na,  tb,  tb,  na,  tb,  fb }};
1719 
1720   Node* pre = in(0);
1721   if (!pre->is_IfTrue() && !pre->is_IfFalse()) {
1722     return nullptr;
1723   }
1724   Node* dom = pre->in(0);
1725   if (!dom->is_If()) {
1726     return nullptr;
1727   }
1728   Node* bol = in(1);
1729   if (!bol->is_Bool()) {
1730     return nullptr;
1731   }
1732   Node* cmp = in(1)->in(1);
1733   if (!cmp->is_Cmp()) {
1734     return nullptr;
1735   }
1736 
1737   if (!dom->in(1)->is_Bool()) {
1738     return nullptr;
1739   }
1740   if (dom->in(1)->in(1) != cmp) {  // Not same cond?
1741     return nullptr;
1742   }
1743 
1744   int drel = subsuming_bool_test_encode(dom->in(1));
1745   int trel = subsuming_bool_test_encode(bol);
1746   int bout = pre->is_IfFalse() ? 1 : 0;
1747 
1748   if (drel < 0 || trel < 0) {
1749     return nullptr;
1750   }
1751   int br = s_short_circuit_map[trel][2*drel+bout];
1752   if (br == na) {
1753     return nullptr;
1754   }
1755 #ifndef PRODUCT
1756   if (TraceIterativeGVN) {
1757     tty->print("   Subsumed IfNode: "); dump();
1758   }
1759 #endif
1760   // Replace condition with constant True(1)/False(0).
1761   bool is_always_true = br == tb;
1762   set_req(1, igvn->intcon(is_always_true ? 1 : 0));
1763 
1764   // Update any data dependencies to the directly dominating test. This subsumed test is not immediately removed by igvn
1765   // and therefore subsequent optimizations might miss these data dependencies otherwise. There might be a dead loop
1766   // ('always_taken_proj' == 'pre') that is cleaned up later. Skip this case to make the iterator work properly.
1767   Node* always_taken_proj = proj_out(is_always_true);
1768   if (always_taken_proj != pre) {
1769     for (DUIterator_Fast imax, i = always_taken_proj->fast_outs(imax); i < imax; i++) {
1770       Node* u = always_taken_proj->fast_out(i);
1771       if (!u->is_CFG()) {
1772         igvn->replace_input_of(u, 0, pre);
1773         --i;
1774         --imax;
1775       }
1776     }
1777   }
1778 
1779   if (bol->outcnt() == 0) {
1780     igvn->remove_dead_node(bol);    // Kill the BoolNode.
1781   }
1782   return this;
1783 }
1784 
1785 // Map BoolTest to local table encoding. The BoolTest (e)numerals
1786 //   { eq = 0, ne = 4, le = 5, ge = 7, lt = 3, gt = 1 }
1787 // are mapped to table indices, while the remaining (e)numerals in BoolTest
1788 //   { overflow = 2, no_overflow = 6, never = 8, illegal = 9 }
1789 // are ignored (these are not modeled in the table).
1790 //
1791 static int subsuming_bool_test_encode(Node* node) {
1792   precond(node->is_Bool());
1793   BoolTest::mask x = node->as_Bool()->_test._test;
1794   switch (x) {
1795     case BoolTest::eq: return 0;
1796     case BoolTest::ne: return 1;
1797     case BoolTest::lt: return 2;
1798     case BoolTest::le: return 3;
1799     case BoolTest::gt: return 4;
1800     case BoolTest::ge: return 5;
1801     case BoolTest::overflow:
1802     case BoolTest::no_overflow:
1803     case BoolTest::never:
1804     case BoolTest::illegal:
1805     default:
1806       return -1;
1807   }
1808 }
1809 
1810 //------------------------------Identity---------------------------------------
1811 // If the test is constant & we match, then we are the input Control
1812 Node* IfProjNode::Identity(PhaseGVN* phase) {
1813   // Can only optimize if cannot go the other way
1814   const TypeTuple *t = phase->type(in(0))->is_tuple();
1815   if (t == TypeTuple::IFNEITHER || (always_taken(t) &&
1816        // During parsing (GVN) we don't remove dead code aggressively.
1817        // Cut off dead branch and let PhaseRemoveUseless take care of it.
1818       (!phase->is_IterGVN() ||
1819        // During IGVN, first wait for the dead branch to be killed.
1820        // Otherwise, the IfNode's control will have two control uses (the IfNode
1821        // that doesn't go away because it still has uses and this branch of the
1822        // If) which breaks other optimizations. Node::has_special_unique_user()
1823        // will cause this node to be reprocessed once the dead branch is killed.
1824        in(0)->outcnt() == 1))) {
1825     // IfNode control
1826     if (in(0)->is_BaseCountedLoopEnd()) {
1827       // CountedLoopEndNode may be eliminated by if subsuming, replace CountedLoopNode with LoopNode to
1828       // avoid mismatching between CountedLoopNode and CountedLoopEndNode in the following optimization.
1829       Node* head = unique_ctrl_out_or_null();
1830       if (head != nullptr && head->is_BaseCountedLoop() && head->in(LoopNode::LoopBackControl) == this) {
1831         Node* new_head = new LoopNode(head->in(LoopNode::EntryControl), this);
1832         phase->is_IterGVN()->register_new_node_with_optimizer(new_head);
1833         phase->is_IterGVN()->replace_node(head, new_head);
1834       }
1835     }
1836     return in(0)->in(0);
1837   }
1838   // no progress
1839   return this;
1840 }
1841 
1842 bool IfNode::is_zero_trip_guard() const {
1843   if (in(1)->is_Bool() && in(1)->in(1)->is_Cmp()) {
1844     return in(1)->in(1)->in(1)->Opcode() == Op_OpaqueZeroTripGuard;
1845   }
1846   return false;
1847 }
1848 
1849 void IfProjNode::pin_array_access_nodes(PhaseIterGVN* igvn) {
1850   for (DUIterator i = outs(); has_out(i); i++) {
1851     Node* u = out(i);
1852     if (!u->depends_only_on_test()) {
1853       continue;
1854     }
1855     Node* clone = u->pin_array_access_node();
1856     if (clone != nullptr) {
1857       clone = igvn->transform(clone);
1858       assert(clone != u, "shouldn't common");
1859       igvn->replace_node(u, clone);
1860       --i;
1861     }
1862   }
1863 }
1864 
1865 #ifndef PRODUCT
1866 void IfNode::dump_spec(outputStream* st) const {
1867   switch (_assertion_predicate_type) {
1868     case AssertionPredicateType::InitValue:
1869       st->print("#Init Value Assertion Predicate  ");
1870       break;
1871     case AssertionPredicateType::LastValue:
1872       st->print("#Last Value Assertion Predicate  ");
1873       break;
1874     case AssertionPredicateType::FinalIv:
1875       st->print("#Final IV Assertion Predicate  ");
1876       break;
1877     case AssertionPredicateType::None:
1878       // No Assertion Predicate
1879       break;
1880     default:
1881       fatal("Unknown Assertion Predicate type");
1882   }
1883   st->print("P=%f, C=%f", _prob, _fcnt);
1884 }
1885 #endif // NOT PRODUCT
1886 
1887 //------------------------------idealize_test----------------------------------
1888 // Try to canonicalize tests better.  Peek at the Cmp/Bool/If sequence and
1889 // come up with a canonical sequence.  Bools getting 'eq', 'gt' and 'ge' forms
1890 // converted to 'ne', 'le' and 'lt' forms.  IfTrue/IfFalse get swapped as
1891 // needed.
1892 static IfNode* idealize_test(PhaseGVN* phase, IfNode* iff) {
1893   assert(iff->in(0) != nullptr, "If must be live");
1894 
1895   if (iff->outcnt() != 2)  return nullptr; // Malformed projections.
1896   Node* old_if_f = iff->proj_out(false);
1897   Node* old_if_t = iff->proj_out(true);
1898 
1899   // CountedLoopEnds want the back-control test to be TRUE, regardless of
1900   // whether they are testing a 'gt' or 'lt' condition.  The 'gt' condition
1901   // happens in count-down loops
1902   if (iff->is_BaseCountedLoopEnd())  return nullptr;
1903   if (!iff->in(1)->is_Bool())  return nullptr; // Happens for partially optimized IF tests
1904   BoolNode *b = iff->in(1)->as_Bool();
1905   BoolTest bt = b->_test;
1906   // Test already in good order?
1907   if( bt.is_canonical() )
1908     return nullptr;
1909 
1910   // Flip test to be canonical.  Requires flipping the IfFalse/IfTrue and
1911   // cloning the IfNode.
1912   Node* new_b = phase->transform( new BoolNode(b->in(1), bt.negate()) );
1913   if( !new_b->is_Bool() ) return nullptr;
1914   b = new_b->as_Bool();
1915 
1916   PhaseIterGVN *igvn = phase->is_IterGVN();
1917   assert( igvn, "Test is not canonical in parser?" );
1918 
1919   // The IF node never really changes, but it needs to be cloned
1920   iff = iff->clone()->as_If();
1921   iff->set_req(1, b);
1922   iff->_prob = 1.0-iff->_prob;
1923 
1924   Node *prior = igvn->hash_find_insert(iff);
1925   if( prior ) {
1926     igvn->remove_dead_node(iff);
1927     iff = (IfNode*)prior;
1928   } else {
1929     // Cannot call transform on it just yet
1930     igvn->set_type_bottom(iff);
1931   }
1932   igvn->_worklist.push(iff);
1933 
1934   // Now handle projections.  Cloning not required.
1935   Node* new_if_f = (Node*)(new IfFalseNode( iff ));
1936   Node* new_if_t = (Node*)(new IfTrueNode ( iff ));
1937 
1938   igvn->register_new_node_with_optimizer(new_if_f);
1939   igvn->register_new_node_with_optimizer(new_if_t);
1940   // Flip test, so flip trailing control
1941   igvn->replace_node(old_if_f, new_if_t);
1942   igvn->replace_node(old_if_t, new_if_f);
1943 
1944   // Progress
1945   return iff;
1946 }
1947 
1948 Node* RangeCheckNode::Ideal(PhaseGVN *phase, bool can_reshape) {
1949   Node* res = Ideal_common(phase, can_reshape);
1950   if (res != NodeSentinel) {
1951     return res;
1952   }
1953 
1954   PhaseIterGVN *igvn = phase->is_IterGVN();
1955   // Setup to scan up the CFG looking for a dominating test
1956   Node* prev_dom = this;
1957 
1958   // Check for range-check vs other kinds of tests
1959   Node* index1;
1960   Node* range1;
1961   jint offset1;
1962   int flip1 = is_range_check(range1, index1, offset1);
1963   if (flip1) {
1964     Node* dom = in(0);
1965     // Try to remove extra range checks.  All 'up_one_dom' gives up at merges
1966     // so all checks we inspect post-dominate the top-most check we find.
1967     // If we are going to fail the current check and we reach the top check
1968     // then we are guaranteed to fail, so just start interpreting there.
1969     // We 'expand' the top 3 range checks to include all post-dominating
1970     // checks.
1971     //
1972     // Example:
1973     // a[i+x] // (1) 1 < x < 6
1974     // a[i+3] // (2)
1975     // a[i+4] // (3)
1976     // a[i+6] // max = max of all constants
1977     // a[i+2]
1978     // a[i+1] // min = min of all constants
1979     //
1980     // If x < 3:
1981     //   (1) a[i+x]: Leave unchanged
1982     //   (2) a[i+3]: Replace with a[i+max] = a[i+6]: i+x < i+3 <= i+6  -> (2) is covered
1983     //   (3) a[i+4]: Replace with a[i+min] = a[i+1]: i+1 < i+4 <= i+6  -> (3) and all following checks are covered
1984     //   Remove all other a[i+c] checks
1985     //
1986     // If x >= 3:
1987     //   (1) a[i+x]: Leave unchanged
1988     //   (2) a[i+3]: Replace with a[i+min] = a[i+1]: i+1 < i+3 <= i+x  -> (2) is covered
1989     //   (3) a[i+4]: Replace with a[i+max] = a[i+6]: i+1 < i+4 <= i+6  -> (3) and all following checks are covered
1990     //   Remove all other a[i+c] checks
1991     //
1992     // We only need the top 2 range checks if x is the min or max of all constants.
1993     //
1994     // This, however, only works if the interval [i+min,i+max] is not larger than max_int (i.e. abs(max - min) < max_int):
1995     // The theoretical max size of an array is max_int with:
1996     // - Valid index space: [0,max_int-1]
1997     // - Invalid index space: [max_int,-1] // max_int, min_int, min_int - 1 ..., -1
1998     //
1999     // The size of the consecutive valid index space is smaller than the size of the consecutive invalid index space.
2000     // If we choose min and max in such a way that:
2001     // - abs(max - min) < max_int
2002     // - i+max and i+min are inside the valid index space
2003     // then all indices [i+min,i+max] must be in the valid index space. Otherwise, the invalid index space must be
2004     // smaller than the valid index space which is never the case for any array size.
2005     //
2006     // Choosing a smaller array size only makes the valid index space smaller and the invalid index space larger and
2007     // the argument above still holds.
2008     //
2009     // Note that the same optimization with the same maximal accepted interval size can also be found in C1.
2010     const jlong maximum_number_of_min_max_interval_indices = (jlong)max_jint;
2011 
2012     // The top 3 range checks seen
2013     const int NRC = 3;
2014     RangeCheck prev_checks[NRC];
2015     int nb_checks = 0;
2016 
2017     // Low and high offsets seen so far
2018     jint off_lo = offset1;
2019     jint off_hi = offset1;
2020 
2021     bool found_immediate_dominator = false;
2022 
2023     // Scan for the top checks and collect range of offsets
2024     for (int dist = 0; dist < 999; dist++) { // Range-Check scan limit
2025       if (dom->Opcode() == Op_RangeCheck &&  // Not same opcode?
2026           prev_dom->in(0) == dom) { // One path of test does dominate?
2027         if (dom == this) return nullptr; // dead loop
2028         // See if this is a range check
2029         Node* index2;
2030         Node* range2;
2031         jint offset2;
2032         int flip2 = dom->as_RangeCheck()->is_range_check(range2, index2, offset2);
2033         // See if this is a _matching_ range check, checking against
2034         // the same array bounds.
2035         if (flip2 == flip1 && range2 == range1 && index2 == index1 &&
2036             dom->outcnt() == 2) {
2037           if (nb_checks == 0 && dom->in(1) == in(1)) {
2038             // Found an immediately dominating test at the same offset.
2039             // This kind of back-to-back test can be eliminated locally,
2040             // and there is no need to search further for dominating tests.
2041             assert(offset2 == offset1, "Same test but different offsets");
2042             found_immediate_dominator = true;
2043             break;
2044           }
2045 
2046           // "x - y" -> must add one to the difference for number of elements in [x,y]
2047           const jlong diff = (jlong)MIN2(offset2, off_lo) - (jlong)MAX2(offset2, off_hi);
2048           if (ABS(diff) < maximum_number_of_min_max_interval_indices) {
2049             // Gather expanded bounds
2050             off_lo = MIN2(off_lo, offset2);
2051             off_hi = MAX2(off_hi, offset2);
2052             // Record top NRC range checks
2053             prev_checks[nb_checks % NRC].ctl = prev_dom->as_IfProj();
2054             prev_checks[nb_checks % NRC].off = offset2;
2055             nb_checks++;
2056           }
2057         }
2058       }
2059       prev_dom = dom;
2060       dom = up_one_dom(dom);
2061       if (!dom) break;
2062     }
2063 
2064     if (!found_immediate_dominator) {
2065       // Attempt to widen the dominating range check to cover some later
2066       // ones.  Since range checks "fail" by uncommon-trapping to the
2067       // interpreter, widening a check can make us speculatively enter
2068       // the interpreter.  If we see range-check deopt's, do not widen!
2069       if (!phase->C->allow_range_check_smearing())  return nullptr;
2070 
2071       if (can_reshape && !phase->C->post_loop_opts_phase()) {
2072         // We are about to perform range check smearing (i.e. remove this RangeCheck if it is dominated by
2073         // a series of RangeChecks which have a range that covers this RangeCheck). This can cause array access nodes to
2074         // be pinned. We want to avoid that and first allow range check elimination a chance to remove the RangeChecks
2075         // from loops. Hence, we delay range check smearing until after loop opts.
2076         phase->C->record_for_post_loop_opts_igvn(this);
2077         return nullptr;
2078       }
2079 
2080       // Didn't find prior covering check, so cannot remove anything.
2081       if (nb_checks == 0) {
2082         return nullptr;
2083       }
2084       // Constant indices only need to check the upper bound.
2085       // Non-constant indices must check both low and high.
2086       int chk0 = (nb_checks - 1) % NRC;
2087       if (index1) {
2088         if (nb_checks == 1) {
2089           return nullptr;
2090         } else {
2091           // If the top range check's constant is the min or max of
2092           // all constants we widen the next one to cover the whole
2093           // range of constants.
2094           RangeCheck rc0 = prev_checks[chk0];
2095           int chk1 = (nb_checks - 2) % NRC;
2096           RangeCheck rc1 = prev_checks[chk1];
2097           if (rc0.off == off_lo) {
2098             adjust_check(rc1.ctl, range1, index1, flip1, off_hi, igvn);
2099             prev_dom = rc1.ctl;
2100           } else if (rc0.off == off_hi) {
2101             adjust_check(rc1.ctl, range1, index1, flip1, off_lo, igvn);
2102             prev_dom = rc1.ctl;
2103           } else {
2104             // If the top test's constant is not the min or max of all
2105             // constants, we need 3 range checks. We must leave the
2106             // top test unchanged because widening it would allow the
2107             // accesses it protects to successfully read/write out of
2108             // bounds.
2109             if (nb_checks == 2) {
2110               return nullptr;
2111             }
2112             int chk2 = (nb_checks - 3) % NRC;
2113             RangeCheck rc2 = prev_checks[chk2];
2114             // The top range check a+i covers interval: -a <= i < length-a
2115             // The second range check b+i covers interval: -b <= i < length-b
2116             if (rc1.off <= rc0.off) {
2117               // if b <= a, we change the second range check to:
2118               // -min_of_all_constants <= i < length-min_of_all_constants
2119               // Together top and second range checks now cover:
2120               // -min_of_all_constants <= i < length-a
2121               // which is more restrictive than -b <= i < length-b:
2122               // -b <= -min_of_all_constants <= i < length-a <= length-b
2123               // The third check is then changed to:
2124               // -max_of_all_constants <= i < length-max_of_all_constants
2125               // so 2nd and 3rd checks restrict allowed values of i to:
2126               // -min_of_all_constants <= i < length-max_of_all_constants
2127               adjust_check(rc1.ctl, range1, index1, flip1, off_lo, igvn);
2128               adjust_check(rc2.ctl, range1, index1, flip1, off_hi, igvn);
2129             } else {
2130               // if b > a, we change the second range check to:
2131               // -max_of_all_constants <= i < length-max_of_all_constants
2132               // Together top and second range checks now cover:
2133               // -a <= i < length-max_of_all_constants
2134               // which is more restrictive than -b <= i < length-b:
2135               // -b < -a <= i < length-max_of_all_constants <= length-b
2136               // The third check is then changed to:
2137               // -max_of_all_constants <= i < length-max_of_all_constants
2138               // so 2nd and 3rd checks restrict allowed values of i to:
2139               // -min_of_all_constants <= i < length-max_of_all_constants
2140               adjust_check(rc1.ctl, range1, index1, flip1, off_hi, igvn);
2141               adjust_check(rc2.ctl, range1, index1, flip1, off_lo, igvn);
2142             }
2143             prev_dom = rc2.ctl;
2144           }
2145         }
2146       } else {
2147         RangeCheck rc0 = prev_checks[chk0];
2148         // 'Widen' the offset of the 1st and only covering check
2149         adjust_check(rc0.ctl, range1, index1, flip1, off_hi, igvn);
2150         // Test is now covered by prior checks, dominate it out
2151         prev_dom = rc0.ctl;
2152       }
2153       // The last RangeCheck is found to be redundant with a sequence of n (n >= 2) preceding RangeChecks.
2154       // If an array load is control dependent on the eliminated range check, the array load nodes (CastII and Load)
2155       // become control dependent on the last range check of the sequence, but they are really dependent on the entire
2156       // sequence of RangeChecks. If RangeCheck#n is later replaced by a dominating identical check, the array load
2157       // nodes must not float above the n-1 other RangeCheck in the sequence. We pin the array load nodes here to
2158       // guarantee it doesn't happen.
2159       //
2160       // RangeCheck#1                 RangeCheck#1
2161       //    |      \                     |      \
2162       //    |      uncommon trap         |      uncommon trap
2163       //    ..                           ..
2164       // RangeCheck#n              -> RangeCheck#n
2165       //    |      \                     |      \
2166       //    |      uncommon trap        CastII  uncommon trap
2167       // RangeCheck                     Load
2168       //    |      \
2169       //   CastII  uncommon trap
2170       //   Load
2171 
2172       return dominated_by(prev_dom, igvn, true);
2173     }
2174   } else {
2175     prev_dom = search_identical(4, igvn);
2176 
2177     if (prev_dom == nullptr) {
2178       return nullptr;
2179     }
2180   }
2181 
2182   // Replace dominated IfNode
2183   return dominated_by(prev_dom, igvn, false);
2184 }
2185 
2186 ParsePredicateNode::ParsePredicateNode(Node* control, Deoptimization::DeoptReason deopt_reason, PhaseGVN* gvn)
2187     : IfNode(control, gvn->intcon(1), PROB_MAX, COUNT_UNKNOWN),
2188       _deopt_reason(deopt_reason),
2189       _useless(false) {
2190   init_class_id(Class_ParsePredicate);
2191   gvn->C->add_parse_predicate(this);
2192   gvn->C->record_for_post_loop_opts_igvn(this);
2193 #ifdef ASSERT
2194   switch (deopt_reason) {
2195     case Deoptimization::Reason_predicate:
2196     case Deoptimization::Reason_profile_predicate:
2197     case Deoptimization::Reason_loop_limit_check:
2198       break;
2199     default:
2200       assert(false, "unsupported deoptimization reason for Parse Predicate");
2201   }
2202 #endif // ASSERT
2203 }
2204 
2205 Node* ParsePredicateNode::uncommon_trap() const {
2206   ParsePredicateUncommonProj* uncommon_proj = proj_out(0)->as_IfFalse();
2207   Node* uct_region_or_call = uncommon_proj->unique_ctrl_out();
2208   assert(uct_region_or_call->is_Region() || uct_region_or_call->is_Call(), "must be a region or call uct");
2209   return uct_region_or_call;
2210 }
2211 
2212 // Fold this node away once it becomes useless or at latest in post loop opts IGVN.
2213 const Type* ParsePredicateNode::Value(PhaseGVN* phase) const {
2214   if (phase->type(in(0)) == Type::TOP) {
2215     return Type::TOP;
2216   }
2217   if (_useless || phase->C->post_loop_opts_phase()) {
2218     return TypeTuple::IFTRUE;
2219   } else {
2220     return bottom_type();
2221   }
2222 }
2223 
2224 #ifndef PRODUCT
2225 void ParsePredicateNode::dump_spec(outputStream* st) const {
2226   st->print(" #");
2227   switch (_deopt_reason) {
2228     case Deoptimization::DeoptReason::Reason_predicate:
2229       st->print("Loop ");
2230       break;
2231     case Deoptimization::DeoptReason::Reason_profile_predicate:
2232       st->print("Profiled Loop ");
2233       break;
2234     case Deoptimization::DeoptReason::Reason_loop_limit_check:
2235       st->print("Loop Limit Check ");
2236       break;
2237     default:
2238       fatal("unknown kind");
2239   }
2240   if (_useless) {
2241     st->print("#useless ");
2242   }
2243 }
2244 #endif // NOT PRODUCT