1 /*
   2  * Copyright (c) 2000, 2026, 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_enums.hpp"
  35 #include "opto/rootnode.hpp"
  36 #include "opto/runtime.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, PhaseIterGVN::NodeOrigin::Speculative);
 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, PhaseIterGVN::NodeOrigin::Graph);
 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, PhaseIterGVN::NodeOrigin::Graph);
 459     }
 460     l -= 1;
 461   }
 462   igvn->remove_dead_node(r, PhaseIterGVN::NodeOrigin::Graph);
 463 
 464   // Now remove the bogus extra edges used to keep things alive
 465   igvn->remove_dead_node(hook, PhaseIterGVN::NodeOrigin::Speculative);
 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, Node* 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 IfProjNode* IfNode::range_check_trap_proj(int& flip_test, Node*& l, Node*& r) const {
 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   if (flip_test == 2) {
 519     return true_proj_or_null();
 520   }
 521   return false_proj_or_null();
 522 }
 523 
 524 
 525 //------------------------------is_range_check---------------------------------
 526 // Return 0 if not a range check.  Return 1 if a range check and set index and
 527 // offset.  Return 2 if we had to negate the test.  Index is null if the check
 528 // is versus a constant.
 529 int RangeCheckNode::is_range_check(Node* &range, Node* &index, jint &offset) {
 530   int flip_test = 0;
 531   Node* l = nullptr;
 532   Node* r = nullptr;
 533   IfProjNode* iftrap = range_check_trap_proj(flip_test, l, r);
 534 
 535   if (iftrap == nullptr) {
 536     return 0;
 537   }
 538 
 539   // Make sure it's a real range check by requiring an uncommon trap
 540   // along the OOB path.  Otherwise, it's possible that the user wrote
 541   // something which optimized to look like a range check but behaves
 542   // in some other way.
 543   if (iftrap->is_uncommon_trap_proj(Deoptimization::Reason_range_check) == nullptr) {
 544     return 0;
 545   }
 546 
 547   // Look for index+offset form
 548   Node* ind = l;
 549   jint  off = 0;
 550   if (l->is_top()) {
 551     return 0;
 552   } else if (l->Opcode() == Op_AddI) {
 553     if ((off = l->in(1)->find_int_con(0)) != 0) {
 554       ind = l->in(2)->uncast();
 555     } else if ((off = l->in(2)->find_int_con(0)) != 0) {
 556       ind = l->in(1)->uncast();
 557     }
 558   } else if ((off = l->find_int_con(-1)) >= 0) {
 559     // constant offset with no variable index
 560     ind = nullptr;
 561   } else {
 562     // variable index with no constant offset (or dead negative index)
 563     off = 0;
 564   }
 565 
 566   // Return all the values:
 567   index  = ind;
 568   offset = off;
 569   range  = r;
 570   return flip_test;
 571 }
 572 
 573 //------------------------------adjust_check-----------------------------------
 574 // Adjust (widen) a prior range check
 575 static void adjust_check(IfProjNode* proj, Node* range, Node* index,
 576                          int flip, jint off_lo, PhaseIterGVN* igvn) {
 577   PhaseGVN *gvn = igvn;
 578   // Break apart the old check
 579   Node *iff = proj->in(0);
 580   Node *bol = iff->in(1);
 581   if( bol->is_top() ) return;   // In case a partially dead range check appears
 582   // bail (or bomb[ASSERT/DEBUG]) if NOT projection-->IfNode-->BoolNode
 583   DEBUG_ONLY( if (!bol->is_Bool()) { proj->dump(3); fatal("Expect projection-->IfNode-->BoolNode"); } )
 584   if (!bol->is_Bool()) return;
 585 
 586   Node *cmp = bol->in(1);
 587   // Compute a new check
 588   Node *new_add = gvn->intcon(off_lo);
 589   if (index) {
 590     new_add = off_lo ? gvn->transform(new AddINode(index, new_add)) : index;
 591   }
 592   Node *new_cmp = (flip == 1)
 593     ? new CmpUNode(new_add, range)
 594     : new CmpUNode(range, new_add);
 595   new_cmp = gvn->transform(new_cmp);
 596   // See if no need to adjust the existing check
 597   if (new_cmp == cmp) return;
 598   // Else, adjust existing check
 599   Node* new_bol = gvn->transform(new BoolNode(new_cmp, bol->as_Bool()->_test._test));
 600   igvn->rehash_node_delayed(iff);
 601   iff->set_req_X(1, new_bol, igvn);
 602   // As part of range check smearing, this range check is widened. Loads and range check Cast nodes that are control
 603   // dependent on this range check now depend on multiple dominating range checks. These control dependent nodes end up
 604   // at the lowest/nearest dominating check in the graph. To ensure that these Loads/Casts do not float above any of the
 605   // dominating checks (even when the lowest dominating check is later replaced by yet another dominating check), we
 606   // need to pin them at the lowest dominating check.
 607   proj->pin_dependent_nodes(igvn);
 608 }
 609 
 610 //------------------------------up_one_dom-------------------------------------
 611 // Walk up the dominator tree one step.  Return null at root or true
 612 // complex merges.  Skips through small diamonds.
 613 Node* IfNode::up_one_dom(Node *curr, bool linear_only) {
 614   Node *dom = curr->in(0);
 615   if( !dom )                    // Found a Region degraded to a copy?
 616     return curr->nonnull_req(); // Skip thru it
 617 
 618   if( curr != dom )             // Normal walk up one step?
 619     return dom;
 620 
 621   // Use linear_only if we are still parsing, since we cannot
 622   // trust the regions to be fully filled in.
 623   if (linear_only)
 624     return nullptr;
 625 
 626   if( dom->is_Root() )
 627     return nullptr;
 628 
 629   // Else hit a Region.  Check for a loop header
 630   if( dom->is_Loop() )
 631     return dom->in(1);          // Skip up thru loops
 632 
 633   // Check for small diamonds
 634   Node *din1, *din2, *din3, *din4;
 635   if( dom->req() == 3 &&        // 2-path merge point
 636       (din1 = dom ->in(1)) &&   // Left  path exists
 637       (din2 = dom ->in(2)) &&   // Right path exists
 638       (din3 = din1->in(0)) &&   // Left  path up one
 639       (din4 = din2->in(0)) ) {  // Right path up one
 640     if( din3->is_Call() &&      // Handle a slow-path call on either arm
 641         (din3 = din3->in(0)) )
 642       din3 = din3->in(0);
 643     if( din4->is_Call() &&      // Handle a slow-path call on either arm
 644         (din4 = din4->in(0)) )
 645       din4 = din4->in(0);
 646     if (din3 != nullptr && din3 == din4 && din3->is_If()) // Regions not degraded to a copy
 647       return din3;              // Skip around diamonds
 648   }
 649 
 650   // Give up the search at true merges
 651   return nullptr;                  // Dead loop?  Or hit root?
 652 }
 653 
 654 
 655 //------------------------------filtered_int_type--------------------------------
 656 // Return a possibly more restrictive type for val based on condition control flow for an if
 657 //
 658 // Important: we only parse if val is on the lhs. This is a limitation, but it makes
 659 //            optimizations simpler. We rely on canonicalization to get us to this
 660 //            shape, which works well for comparisions with constants, as they are
 661 //            canonicalized to the rhs. This may not happen with variables, and so
 662 //            the optimization may not work for those cases, when val stays on the rhs.
 663 const TypeInt* IfNode::filtered_int_type(PhaseGVN* gvn, Node* val, Node* if_proj) {
 664   assert(if_proj &&
 665          (if_proj->Opcode() == Op_IfTrue || if_proj->Opcode() == Op_IfFalse), "expecting an if projection");
 666   if (if_proj->in(0) && if_proj->in(0)->is_If()) {
 667     IfNode* iff = if_proj->in(0)->as_If();
 668     if (iff->in(1) && iff->in(1)->is_Bool()) {
 669       BoolNode* bol = iff->in(1)->as_Bool();
 670       if (bol->in(1) && bol->in(1)->is_Cmp()) {
 671         const CmpNode* cmp  = bol->in(1)->as_Cmp();
 672         // Val is always the lhs of the comparision: val <test> cmp2
 673         if (cmp->in(1) == val) {
 674           assert(cmp->Opcode() == Op_CmpI, "signed comparison required");
 675           const TypeInt* cmp2_t = gvn->type(cmp->in(2))->isa_int();
 676           if (cmp2_t != nullptr) {
 677             jint lo = cmp2_t->_lo;
 678             jint hi = cmp2_t->_hi;
 679             // Negate the test if we are on the false branch.
 680             BoolTest::mask msk = if_proj->Opcode() == Op_IfTrue ? bol->_test._test : bol->_test.negate();
 681             switch (msk) {
 682             case BoolTest::ne: {
 683               // If val is compared to its lower or upper bound, we can narrow the type
 684               const TypeInt* val_t = gvn->type(val)->isa_int();
 685               if (val_t != nullptr && !val_t->singleton() && cmp2_t->is_con()) {
 686                 if (val_t->_lo == lo) {
 687                   // Condition leading to if_proj: val != val->lo
 688                   //   val in [val->lo + 1, val->hi]
 689                   return TypeInt::make(val_t->_lo + 1, val_t->_hi, val_t->_widen);
 690                 } else if (val_t->_hi == hi) {
 691                   // Condition leading to if_proj: val != val->hi
 692                   //   val in [val->lo, val->hi - 1]
 693                   return TypeInt::make(val_t->_lo, val_t->_hi - 1, val_t->_widen);
 694                 }
 695               }
 696               // Can't refine type
 697               return nullptr;
 698             }
 699             case BoolTest::eq:
 700               // Condition leading to if_proj: val == cmp2
 701               //   val in cmp2_t
 702               return cmp2_t;
 703             case BoolTest::lt:
 704               // Condition leading to if_proj: val < cmp2
 705               //   val in [min_int .. max(min_int, cmp2->_hi - 1)]
 706               lo = min_jint;
 707               if (hi != min_jint) {
 708                 hi = hi - 1;
 709               }
 710               break;
 711             case BoolTest::le:
 712               // Condition leading to if_proj: val <= cmp2
 713               //   val in [min_int .. cmp2->_hi]
 714               lo = min_jint;
 715               break;
 716             case BoolTest::gt:
 717               // Condition leading to if_proj: val > cmp2
 718               //   val in [min(cmp2->_lo + 1, max_int) .. max_int]
 719               if (lo != max_jint) {
 720                 lo = lo + 1;
 721               }
 722               hi = max_jint;
 723               break;
 724             case BoolTest::ge:
 725               // Condition leading to if_proj: val >= cmp2
 726               //   val in [cmp2->_lo .. max_int]
 727               hi = max_jint;
 728               break;
 729             default:
 730               assert(false, "impossible case");
 731               return nullptr;
 732             }
 733             const TypeInt* rtn_t = TypeInt::make(lo, hi, cmp2_t->_widen);
 734             return rtn_t;
 735           }
 736         }
 737       }
 738     }
 739   }
 740   return nullptr;
 741 }
 742 
 743 //------------------------------fold_compares----------------------------
 744 // See if a pair of CmpIs can be converted into a CmpU.  In some cases
 745 // the direction of this if is determined by the preceding if so it
 746 // can be eliminate entirely.
 747 //
 748 // Given an if testing (CmpI n v) check for an immediately control
 749 // dependent if that is testing (CmpI n v2) and has one projection
 750 // leading to this if and the other projection leading to a region
 751 // that merges one of this ifs control projections.
 752 //
 753 //                   If
 754 //                  / |
 755 //                 /  |
 756 //                /   |
 757 //              If    |
 758 //              /\    |
 759 //             /  \   |
 760 //            /    \  |
 761 //           /    Region
 762 //
 763 // Or given an if testing (CmpI n v) check for a dominating if that is
 764 // testing (CmpI n v2), both having one projection leading to an
 765 // uncommon trap. Allow Another independent guard in between to cover
 766 // an explicit range check:
 767 // if (index < 0 || index >= array.length) {
 768 // which may need a null check to guard the LoadRange
 769 //
 770 //                   If
 771 //                  / \
 772 //                 /   \
 773 //                /     \
 774 //              If      unc
 775 //              /\
 776 //             /  \
 777 //            /    \
 778 //           /      unc
 779 //
 780 
 781 // Is the comparison for this If suitable for folding?
 782 bool IfNode::cmpi_folds(PhaseIterGVN* igvn, bool fold_ne) {
 783   return in(1) != nullptr &&
 784     in(1)->is_Bool() &&
 785     in(1)->in(1) != nullptr &&
 786     in(1)->in(1)->Opcode() == Op_CmpI &&
 787     in(1)->in(1)->in(2) != nullptr &&
 788     in(1)->in(1)->in(2) != igvn->C->top() &&
 789     (in(1)->as_Bool()->_test.is_less() ||
 790      in(1)->as_Bool()->_test.is_greater() ||
 791      (fold_ne && in(1)->as_Bool()->_test._test == BoolTest::ne));
 792 }
 793 
 794 // Is a dominating control suitable for folding with this if?
 795 bool IfNode::is_ctrl_folds(Node* ctrl, PhaseIterGVN* igvn) {
 796   return ctrl != nullptr &&
 797     ctrl->is_IfProj() &&
 798     ctrl->outcnt() == 1 && // No side-effects
 799     ctrl->in(0) != nullptr &&
 800     ctrl->in(0)->Opcode() == Op_If &&
 801     ctrl->in(0)->outcnt() == 2 &&
 802     ctrl->in(0)->as_If()->cmpi_folds(igvn, true) &&
 803     // Must compare same value
 804     ctrl->in(0)->in(1)->in(1)->in(1) != nullptr &&
 805     ctrl->in(0)->in(1)->in(1)->in(1) != igvn->C->top() &&
 806     ctrl->in(0)->in(1)->in(1)->in(1) == in(1)->in(1)->in(1);
 807 }
 808 
 809 // Do this If and the dominating If share a region?
 810 bool IfNode::has_shared_region(IfProjNode* proj, IfProjNode*& success, IfProjNode*& fail) const {
 811   IfProjNode* otherproj = proj->other_if_proj();
 812   Node* otherproj_ctrl_use = otherproj->unique_ctrl_out_or_null();
 813   RegionNode* region = (otherproj_ctrl_use != nullptr && otherproj_ctrl_use->is_Region()) ? otherproj_ctrl_use->as_Region() : nullptr;
 814   success = nullptr;
 815   fail = nullptr;
 816 
 817   if (otherproj->outcnt() == 1 && region != nullptr && !region->has_phi()) {
 818     for (int i = 0; i < 2; i++) {
 819       IfProjNode* next_proj = proj_out(i)->as_IfProj();
 820       if (success == nullptr && next_proj->outcnt() == 1 && next_proj->unique_out() == region) {
 821         success = next_proj;
 822       } else if (fail == nullptr) {
 823         fail = next_proj;
 824       } else {
 825         success = nullptr;
 826         fail = nullptr;
 827       }
 828     }
 829   }
 830   return success != nullptr && fail != nullptr;
 831 }
 832 
 833 bool IfNode::is_dominator_unc(CallStaticJavaNode* dom_unc, CallStaticJavaNode* unc) {
 834   // Different methods and methods containing jsrs are not supported.
 835   ciMethod* method = unc->jvms()->method();
 836   ciMethod* dom_method = dom_unc->jvms()->method();
 837   if (method != dom_method || method->has_jsrs()) {
 838     return false;
 839   }
 840   // Check that both traps are in the same activation of the method (instead
 841   // of two activations being inlined through different call sites) by verifying
 842   // that the call stacks are equal for both JVMStates.
 843   JVMState* dom_caller = dom_unc->jvms()->caller();
 844   JVMState* caller = unc->jvms()->caller();
 845   if ((dom_caller == nullptr) != (caller == nullptr)) {
 846     // The current method must either be inlined into both dom_caller and
 847     // caller or must not be inlined at all (top method). Bail out otherwise.
 848     return false;
 849   } else if (dom_caller != nullptr && !dom_caller->same_calls_as(caller)) {
 850     return false;
 851   }
 852   // Check that the bci of the dominating uncommon trap dominates the bci
 853   // of the dominated uncommon trap. Otherwise we may not re-execute
 854   // the dominated check after deoptimization from the merged uncommon trap.
 855   ciTypeFlow* flow = dom_method->get_flow_analysis();
 856   int bci = unc->jvms()->bci();
 857   int dom_bci = dom_unc->jvms()->bci();
 858   if (!flow->is_dominated_by(bci, dom_bci)) {
 859     return false;
 860   }
 861 
 862   return true;
 863 }
 864 
 865 // Return projection that leads to an uncommon trap if any
 866 ProjNode* IfNode::uncommon_trap_proj(CallStaticJavaNode*& call, Deoptimization::DeoptReason reason) const {
 867   for (int i = 0; i < 2; i++) {
 868     call = proj_out(i)->is_uncommon_trap_proj(reason);
 869     if (call != nullptr) {
 870       return proj_out(i);
 871     }
 872   }
 873   return nullptr;
 874 }
 875 
 876 // Do this If and the dominating If both branch out to an uncommon trap
 877 bool IfNode::has_only_uncommon_traps(IfProjNode* proj, IfProjNode*& success, IfProjNode*& fail, PhaseIterGVN* igvn) const {
 878   IfProjNode* otherproj = proj->other_if_proj();
 879   CallStaticJavaNode* dom_unc = otherproj->is_uncommon_trap_proj();
 880 
 881   if (otherproj->outcnt() == 1 && dom_unc != nullptr) {
 882     // We need to re-execute the folded Ifs after deoptimization from the merged traps
 883     if (!dom_unc->jvms()->should_reexecute()) {
 884       return false;
 885     }
 886 
 887     CallStaticJavaNode* unc = nullptr;
 888     ProjNode* unc_proj = uncommon_trap_proj(unc);
 889     if (unc_proj != nullptr && unc_proj->outcnt() == 1) {
 890       if (dom_unc == unc) {
 891         // Allow the uncommon trap to be shared through a region
 892         RegionNode* r = unc->in(0)->as_Region();
 893         if (r->outcnt() != 2 || r->req() != 3 || r->find_edge(otherproj) == -1 || r->find_edge(unc_proj) == -1) {
 894           return false;
 895         }
 896         assert(r->has_phi() == nullptr, "simple region shouldn't have a phi");
 897       } else if (dom_unc->in(0) != otherproj || unc->in(0) != unc_proj) {
 898         return false;
 899       }
 900 
 901       if (!is_dominator_unc(dom_unc, unc)) {
 902         return false;
 903       }
 904 
 905       if (!dom_unc->safe_for_fold_compare()) {
 906         return false;
 907       }
 908 
 909       // See merge_uncommon_traps: the reason of the uncommon trap
 910       // will be changed and the state of the dominating If will be
 911       // used. Checked that we didn't apply this transformation in a
 912       // previous compilation and it didn't cause too many traps
 913       ciMethod* dom_method = dom_unc->jvms()->method();
 914       int dom_bci = dom_unc->jvms()->bci();
 915       if (!igvn->C->too_many_traps(dom_method, dom_bci, Deoptimization::Reason_unstable_fused_if) &&
 916           !igvn->C->too_many_traps(dom_method, dom_bci, Deoptimization::Reason_range_check) &&
 917           // Return true if c2 manages to reconcile with UnstableIf optimization. See the comments for it.
 918           igvn->C->remove_unstable_if_trap(dom_unc, true/*yield*/)) {
 919         success = unc_proj->as_IfProj();
 920         fail = unc_proj->as_IfProj()->other_if_proj();
 921         return true;
 922       }
 923     }
 924   }
 925   return false;
 926 }
 927 
 928 // We are given the following code shape with two CmpI:
 929 //
 930 //               n  v1
 931 //               |  |
 932 //               cmp1
 933 //                |
 934 //       entry  bool1(test1)
 935 //           |  |
 936 //           iff1
 937 //           |   \
 938 //        middle  fail1-------------+
 939 //           |                      |
 940 //           |   n  v2              |
 941 //           |   |  |               |
 942 //       maybe   cmp2               |
 943 //  null-check    |                 |
 944 //           |  bool2(test2)        |
 945 //           |  |                   |
 946 //           iff2                   |
 947 //           |   \                  v
 948 //          succ  fail2----> go to same region
 949 //                           or uncommon trap
 950 //
 951 // 1. In some cases, we can prove that succ cannot be reached,
 952 //    and we can fold away the iff2. Example:
 953 //
 954 //      if (n < -1 && n > 1) { succ } else { fail }
 955 //      // 1st condition: n in [min_int .. -2]
 956 //      // 2nd condition: n in [2 ..  max_int]
 957 //      // -> no overlap -> constant fold iff2 towards fail2
 958 //      //
 959 //      // Equivalent, if we flip everything:
 960 //      if (n >= -1 || n <= 1) { fail } else { succ }
 961 //
 962 // 2. In other cases, we can replace the two CmpI with
 963 //    a single CmpU. We fold iff1 towards middle, and
 964 //    replace the iff2 condition with the CmpU. Example:
 965 //
 966 //      if (n >= 0 && n < 10) { succ } else { fail }
 967 //      // transformed to:
 968 //      if (n <u 10) { succ } else { fail }
 969 //
 970 //      if (n < 0 || n >= arr.length) { throw ArrayOutOfBoundsException }
 971 //      // transformed to:
 972 //      if (n >=u arr.length) { throw ArrayOutOfBoundsException }
 973 //
 974 // Note1: we assume that the CmpI nodes are canonicalized to the
 975 // point where n is always on the lhs. This is a limitation,
 976 // but as long as v1 and v2 are constants they will eventually
 977 // be canonicalized to the rhs. For variables, this may not always
 978 // happen.
 979 //
 980 // Note2: We are flexible about the IfProj nodes: middle and succ
 981 // could both be either IfTrue or IfFalse.
 982 //
 983 // Note3: Surrounding code has a different naming scheme!
 984 // In has_only_uncommon_traps, the path towards the
 985 // uncommon trap (e.g. failed range check) is called
 986 // "success", while the path that does not go to
 987 // the uncommon trap (e.g. in-bounds access) is called
 988 // "fail". I think that is counter-intuitive, so I now
 989 // used a different naming scheme here.
 990 //
 991 // Return true iff we could perform one of the optimizations.
 992 bool IfNode::fold_compares_helper(IfProjNode* middle, IfProjNode* fail2, IfProjNode* succ, PhaseIterGVN* igvn) {
 993   assert(fail2->in(0) == this, "link iff2->fail2");
 994   assert(succ->in(0) == this,  "link iff2->succ");
 995 
 996   IfNode* iff1 = middle->in(0)->as_If();
 997   IfNode* iff2 = this;
 998   BoolNode* bool1 = iff1->in(1)->as_Bool();
 999   BoolNode* bool2 = iff2->in(1)->as_Bool();
1000   CmpNode* cmp1 = bool1->in(1)->as_Cmp();
1001   CmpNode* cmp2 = bool2->in(1)->as_Cmp();
1002   assert(cmp1->Opcode() == Op_CmpI, "comparisons must be CmpI");
1003   assert(cmp2->Opcode() == Op_CmpI, "comparisons must be CmpI");
1004 
1005   IfProjNode* fail1 = middle->other_if_proj();
1006 
1007   Node* v1 = cmp1->in(2);
1008   Node* v2 = cmp2->in(2);
1009   Node* n = cmp1->in(1);
1010   assert(cmp2->in(1) == n, "n must be lhs in both CmpI");
1011 
1012   // Optimization 1: try to prove that succ is not reachable.
1013   // Which values of n can pass iff1 to middle AND iff2 to succ?
1014   const TypeInt* type_middle = filtered_int_type(igvn, n, middle);
1015   if (type_middle != nullptr) {
1016     const TypeInt* type_succ = filtered_int_type(igvn, n, succ);
1017     if (type_succ != nullptr) {
1018       if (type_middle->filter(type_succ) == Type::TOP) {
1019         // The intersection is empty -> succ is not reachable.
1020         // Fold iff2 towards fail2 (and away from succ).
1021         igvn->replace_input_of(iff2, 1, igvn->intcon(fail2->_con));
1022         return true; // success: succ not reachable
1023       }
1024     }
1025   }
1026 
1027   // Optimization 2: try to replace the two CmpI with one CmpU
1028   // We can handle the following 4 cases:
1029   //     Input: two CmpI            Output: one CmpU           Assumption
1030   //     --------------------       -------------------------  -------------------
1031   // a)  (n >  lo && n <  hi)  ->   n - lo - 1 <u  hi - lo - 1  (assuming lo <  hi)
1032   //     (n >  2  && n <  5 )       n - 3      <u  2
1033   //     range: [3, 4]
1034   //
1035   // b)  (n >  lo && n <= hi)  ->   n - lo - 1 <u  hi - lo      (assuming lo <= hi)
1036   //     (n >  2  && n <= 5 )       n - 3      <u  3
1037   //     range: [3, 4, 5]
1038   //
1039   // c)  (n >= lo && n <  hi)  ->   n - lo     <u  hi - lo      (assuming lo <= hi)
1040   //     (n >= 2  && n <  5 )       n - 2      <u  3
1041   //     range: [2, 3, 4]
1042   //
1043   // d)  (n >= lo && n <= hi)  ->   n - lo     <=u hi - lo      (assuming lo <= hi)
1044   //     (n >= 2  && n <= 5 )       n - 2      <=u 3
1045   //     range: [2, 3, 4, 5]
1046   //
1047   // Note1: the rhs of the CmpU indicates the cardinality of the range,
1048   //        allowing n to have exactly that many different values.
1049   //
1050   // Note2: all 4 case have an assumption: lo must be sufficiently smaller
1051   //        than hi. Below, and with the use of Lemma1 from below, we will
1052   //        prove that this implies that the rhs of the CmpU never
1053   //        underflows or overflows, which is critical for correctness.
1054   //
1055   // Below, we will prove and implement each of these cases. But first,
1056   // we must handle the combinations of IfTrue/IfFalse projections for
1057   // middle and succ, and extract which one is the lower bound (lo) and
1058   // which one the upper bound (hi).
1059   //
1060   // <---- lower bound -----> <----------- succ -------------> <---- upper bound ----->
1061   // [min_int .. lo_type->hi] [lo_type->hi+1 .. hi_type->lo-1] [hi_type->lo .. max_int]
1062   //                         ^                                ^
1063   //                     n {>/>=} lo                      n {</<=} hi
1064   //
1065   // The trick is then to "shift down" the succ range, to create only
1066   // a single transition point.
1067   //
1068   // <----------- succ -------------> <------------ unsigned upper bound ------------->
1069   // [0           ..                ] [                      ..               max_uint]
1070   //                                 ^
1071   //                               CmpU
1072 
1073   BoolTest::mask test1 = bool1->_test._test;
1074   BoolTest::mask test2 = bool2->_test._test;
1075   if (middle->Opcode() == Op_IfFalse) { test1 = BoolTest::negate_mask(test1); }
1076   if (succ->Opcode()   == Op_IfFalse) { test2 = BoolTest::negate_mask(test2); }
1077 
1078   Node* lo = nullptr;
1079   Node* hi = nullptr;
1080   const TypeInt* lo_type = nullptr;
1081   const TypeInt* hi_type = nullptr;
1082   BoolTest::mask lo_test = BoolTest::illegal;
1083   BoolTest::mask hi_test = BoolTest::illegal;
1084   if (BoolTest::is_greater(test1) && BoolTest::is_less(test2)) {
1085     lo = v1;
1086     hi = v2;
1087     lo_type = IfNode::filtered_int_type(igvn, n, fail1);
1088     hi_type = IfNode::filtered_int_type(igvn, n, fail2);
1089     lo_test = test1;
1090     hi_test = test2;
1091   } else if (BoolTest::is_less(test1) && BoolTest::is_greater(test2)) {
1092     lo = v2;
1093     hi = v1;
1094     lo_type = IfNode::filtered_int_type(igvn, n, fail2);
1095     hi_type = IfNode::filtered_int_type(igvn, n, fail1);
1096     lo_test = test2;
1097     hi_test = test1;
1098   } else {
1099     // Could not find upper and lower bound.
1100     return false;
1101   }
1102   assert(BoolTest::is_greater(lo_test), "lower bound: n {>/>=} lo");
1103   assert(BoolTest::is_less(hi_test),    "upper bound: n {</<=} lo");
1104 
1105   // Check that we got lower and upper bounds as expected.
1106   if (lo_type == nullptr ||
1107       hi_type == nullptr ||
1108       hi_type->_hi != max_jint ||
1109       lo_type->_lo != min_jint) {
1110     // Upper and lower bounds could not be established.
1111     return false;
1112   }
1113 
1114   // -------------------------------------------------------------------
1115   // In the proofs below, we need some basic Lemmas to deal with integer
1116   // signed and unsigned arithmetic.
1117   //
1118   // Lemma1:
1119   //   Let a and b be in [min_int .. max_int].
1120   //   If a >=s b, then:
1121   //     U(a - b) = a - b
1122   //
1123   //   Proof:
1124   //     a >= b
1125   //     -> a - b >= 0
1126   //
1127   //     a <= max_int
1128   //     b >= min_int
1129   //     -> a - b <= max_int - min_int = 2^32-1
1130   //
1131   //     0 <= a - b <= 2^32-1
1132   //     -> cast to unsigned has no overflow
1133   //     -> U(a - b) = a - b
1134   //
1135   // Lemma2:
1136   //   Let a and b be in [min_int .. max_int].
1137   //   If a <s b, then:
1138   //     U(a - b) = a - b + 2^32
1139   //
1140   //   Proof:
1141   //     a < b
1142   //     -> a - b < 0
1143   //
1144   //     a >= min_int
1145   //     b <= max_int
1146   //     -> a - b >= min_int - max_int = 2^32-1
1147   //
1148   //     2^32-1 <= a - b < 0
1149   //     -> cast to unsigned leads to exactly one overflow
1150   //     -> U(a - b) = a - b + 2^32
1151   //
1152   // Lemma3:
1153   //   Let a and b be in [min_int .. max_int].
1154   //     a + 2^32 > b
1155   //
1156   //   Proof:
1157   //     Using a >= min_int, and b <= max_int:
1158   //     a + 2^32 >= min_int + 2^32
1159   //               = max_int + 1
1160   //              >= b       + 1
1161   //              >  b
1162   // -------------------------------------------------------------------
1163 
1164   // Handle the 4 cases.
1165   // All produce this form: n - lo + x1 <cond> hi - lo + x2
1166   Node* x1 = nullptr;
1167   Node* x2 = nullptr;
1168   BoolTest::mask cond = BoolTest::illegal;
1169   if (lo_test == BoolTest::gt && hi_test == BoolTest::lt) {
1170     // We perform the the (CHECK) below, which implies (LO-HI),
1171     // as we will show below.
1172     if (lo_type->_hi >= hi_type->_lo) {
1173       return false; // (CHECK) fails, we cannot establish (LO-HI) assumption.
1174     }
1175     // a)  (n >  lo && n <  hi)  ->   n - lo - 1 <u  hi - lo - 1  (assuming lo <  hi)
1176     //     (BEFORE)                   (AFTER)                     (LO-HI)
1177     //
1178     // Proof:
1179     //   From IfNode::filtered_int_type, we get:
1180     //     lo_type = [min_int .. lo->_hi]    for n <= lo
1181     //     -> lo_type->_hi = lo->_hi
1182     //     hi_type = [hi->_lo .. max_int]    for n >= lo
1183     //     -> hi_type->_lo = hi->_lo
1184     //   We will need the assumption (LO-HI) below, which we can
1185     //   establish with the following (CHECK):
1186     //     lo_type->_hi < hi_type->_lo               (CHECK)
1187     //     -> lo->_hi < hi->_lo
1188     //     -> lo      < hi                           (LO-HI)
1189     //
1190     //   Case n <= lo:
1191     //     (BEFORE) is always false, show (AFTER) is always false.
1192     //     Since lo < hi (LO-HI), S(lo+1) = lo+1 (no overflow):
1193     //     -> lo+1 <= hi
1194     //     -> n < lo+1
1195     //     U(n - (lo + 1))           <  U(hi - (lo + 1))
1196     //     -- Lemma2 (n < lo+1) --     -- Lemma1 (lo+1 <= hi) --
1197     //       n - (lo + 1) + 2^32     <    hi - (lo + 1)
1198     //       n            + 2^32     <    hi
1199     //     Always false by Lemma3.
1200     //
1201     //   Case lo < n < hi:
1202     //     (BEFORE) is always true, show (AFTER) is always true.
1203     //     Since lo < hi (LO-HI), S(lo+1) = lo+1 (no overflow):
1204     //     -> lo+1 <= hi
1205     //     -> n >= lo+1
1206     //     U(n - (lo + 1))           <  U(hi - (lo + 1))
1207     //     -- Lemma1 (n >= lo+1) --   -- Lemma1 (lo+1 <= hi) --
1208     //       n - (lo + 1)            <    hi - (lo + 1)
1209     //       n                       <    hi
1210     //     Corresponds to case assumption, so always true.
1211     //
1212     //   Case n >= hi:
1213     //     (BEFORE) is always false, show (AFTER) is always false.
1214     //     Since lo < hi (LO-HI), S(lo+1) = lo+1 (no overflow):
1215     //     -> lo+1 <= hi
1216     //     U(n - (lo + 1))           <  U(hi - (lo + 1))
1217     //     -- Lemma1 (n >= lo+1) --    -- Lemma1 (lo+1 <= hi) --
1218     //       n - (lo + 1)            <    hi - (lo + 1)
1219     //       n                       <    hi
1220     //     Contradicts case assumption, so always false.
1221     // QED.
1222     //
1223     // Note: we cannot use anything more relaxed than the assumption
1224     //       lo < hi: with lo=hi the rhs of the CmpU would underflow.
1225     //
1226     // Produce form: n - lo + x1 <cond> hi - lo + x2
1227     //               n - lo -  1   <u   hi - lo - 1
1228     x1 = igvn->intcon(-1);
1229     x2 = igvn->intcon(-1);
1230     cond = BoolTest::lt;
1231   } else if (lo_test == BoolTest::gt && hi_test == BoolTest::le) {
1232     // We perform the the (CHECK) below, which implies (LO-HI),
1233     // as we will show below.
1234     if (lo_type->_hi >= hi_type->_lo) {
1235       return false; // (CHECK) fails, we cannot establish (LO-HI) assumption.
1236     }
1237     // b)  (n >  lo && n <= hi)  ->   n - lo - 1 <u  hi - lo      (assuming lo <= hi)
1238     //     (BEFORE)                   (AFTER)                     (LO-HI)
1239     //
1240     // Proof:
1241     //   From IfNode::filtered_int_type, we get:
1242     //     lo_type = [min_int .. lo->_hi]                  for n <= lo
1243     //     -> lo_type->_hi = lo->_hi
1244     //     hi_type = [min(hi->_lo+1, max_int) .. max_int]  for n > hi
1245     //     -> hi_type->_lo <= lo->_lo + 1
1246     //   We will need the assumption (LO-HI) below, which we can
1247     //   establish with the following (CHECK):
1248     //        lo_type->_hi <  hi_type->_lo       (CHECK)
1249     //     -> lo->_hi      <  hi->_lo + 1
1250     //     -> lo           <  hi      + 1
1251     //     -> lo           <= hi                 (LO-HI)
1252     //
1253     //   Case A: lo = hi
1254     //     Let y = lo = hi
1255     //     -> n > lo && n <= hi   vs     n - lo - 1 <u hi - lo
1256     //     -> n > y  && n <= y    vs     n - y  - 1 <u y  - y = 0
1257     //        false                      false
1258     //     Hence, (BEFORE) and (AFTER) are both always false.
1259     //
1260     //   Case B: lo < hi
1261     //     Case n <= lo:
1262     //       (BEFORE) is always false, show (AFTER) is always false.
1263     //       Since lo < hi (Case B), S(lo+1) = lo+1 (no overflow):
1264     //       -> n < lo+1
1265     //       U(n - (lo + 1))         <  U(hi - lo)
1266     //       -- Lemma2 (n < lo+1) --    -- Lemma1 (lo <= hi, LO-HI) --
1267     //         n - (lo + 1) + 2^32   <    hi - lo
1268     //         n -       1  + 2^32   <    hi
1269     //         n            + 2^32   <=   hi
1270     //       Always false by Lemma3.
1271     //       Note: To apply Lemma2 above, we must use (Case B), we
1272     //             could not have done it with (LO-HI) alone.
1273     //
1274     //     Case lo < n <= hi:
1275     //       (BEFORE) is always true, show (AFTER) is always true.
1276     //       Since lo < hi (Case B), S(lo+1) = lo+1 (no overflow):
1277     //       -> n >= lo+1
1278     //       U(n - (lo + 1))          <  U(hi - lo)
1279     //       -- Lemma1 (n >= lo+1) --   -- Lemma1 (lo <= hi, LO-HI) --
1280     //         n - (lo + 1)           <    hi - lo
1281     //         n -       1            <    hi
1282     //         n                      <=   hi
1283     //       Follows from case assumption, so always true.
1284     //
1285     //     Case n > hi:
1286     //       (BEFORE) is always false, show (AFTER) is always false.
1287     //       Since lo < hi (Case B), S(lo+1) = lo+1 (no overflow):
1288     //       -> lo+1 <= hi
1289     //       -> n > lo+1
1290     //       U(n - (lo + 1))          <  U(hi - lo)
1291     //       -- Lemma1 (n > lo+1) --     -- Lemma1 (lo <= hi, LO-HI) --
1292     //         n - (lo + 1)           <    hi - lo
1293     //         n -       1            <    hi
1294     //         n                      <=   hi
1295     //     Contradicts case assumption, so always false.
1296     // QED.
1297     //
1298     // Note: we cannot use anything more relaxed than the assumption
1299     //       lo <= hi: with lo=hi+1 the rhs of the CmpU would underflow.
1300     //
1301     // Produce form: n - lo + x1 <cond> hi - lo + x2
1302     //               n - lo -  1   <u   hi - lo
1303     x1 = igvn->intcon(-1);
1304     x2 = igvn->intcon(0);
1305     cond = BoolTest::lt;
1306   } else if (lo_test == BoolTest::ge && hi_test == BoolTest::lt) {
1307     // We perform the the (CHECK) below, which implies (LO-HI),
1308     // as we will show below.
1309     if (lo_type->_hi >= hi_type->_lo) {
1310       return false; // (CHECK) fails, we cannot establish (LO-HI) assumption.
1311     }
1312     // c)  (n >= lo && n <  hi)  ->   n - lo     <u  hi - lo      (assuming lo <= hi)
1313     //     (BEFORE)                   (AFTER)                     (LO-HI)
1314     //
1315     // Proof:
1316     //   From IfNode::filtered_int_type, we get:
1317     //     lo_type = [min_int .. max(min_int, lo->_hi - 1)]  for n < lo
1318     //     -> lo_type->_hi >= lo->_hi - 1
1319     //     hi_type = [b->_lo .. max_int]                     for n >= hi
1320     //     -> hi_type->_lo = hi->_lo
1321     //   We will need the assumption (LO-HI) below, which we can
1322     //   establish with the following (CHECK):
1323     //        lo_type->_hi < hi_type->_lo
1324     //     -> lo->_hi - 1  <  hi->_lo
1325     //     -> lo->_hi      <= hi->_lo
1326     //     -> lo           <= hi                         (HI-LO)
1327     //
1328     //   Case n < lo:
1329     //     (BEFORE) is always false, show (AFTER) is always false.
1330     //     U(n - lo)              < U(hi - lo)
1331     //     -- Lemma2 (n < lo) --    -- Lemma1 (lo <= hi, LO-HI) --
1332     //       n - lo + 2^32        <   hi - lo
1333     //       n      + 2^32        <   hi
1334     //     Always false by Lemma3.
1335     //
1336     //   Case lo <=s n <s hi:
1337     //     (BEFORE) is always true, show (AFTER) is always true.
1338     //     U(n - lo)              < U(hi - lo)
1339     //     -- Lemma1 (n >= lo) --   -- Lemma1 (lo <= hi, LO-HI) --
1340     //       n - lo               <   hi - lo
1341     //       n                    <   hi
1342     //     Follows from case assumption, so always true.
1343     //
1344     //   Case n >=s hi:
1345     //     (BEFORE) is always false, show (AFTER) is always false.
1346     //     U(n - lo)              < U(hi - lo)
1347     //     -- Lemma1 (n >= lo) --     -- Lemma1 (lo <= hi, LO-HI) --
1348     //       n - lo               <   hi - lo
1349     //       n                    <   hi
1350     //     Contradicts case assumption, so always false.
1351     // QED.
1352     //
1353     /// Note: we cannot use anything more relaxed than the assumption
1354     //       lo <= hi: with lo=hi+1 the rhs of the CmpU would underflow.
1355     //
1356     // Produce form: n - lo + x1 <cond> hi - lo + x2
1357     //               n - lo        <u   hi - lo
1358     x1 = igvn->intcon(0);
1359     x2 = igvn->intcon(0);
1360     cond = BoolTest::lt;
1361   } else {
1362     assert (lo_test == BoolTest::ge && hi_test == BoolTest::le, "");
1363     // We perform the the (CHECK) below, which implies (LO-HI),
1364     // as we will show below.
1365     jlong lo_type_hi = lo_type->_hi;
1366     jlong hi_type_lo = hi_type->_lo;
1367     if (lo_type_hi >= hi_type_lo - 1) {
1368       return false; // (CHECK) fails, we cannot establish (LO-HI) assumption.
1369     }
1370     // d)  (n >= lo && n <= hi)  ->   n - lo     <=u hi - lo      (assuming lo <= hi)
1371     //     (BEFORE)                   (AFTER)                     (LO-HI)
1372     //
1373     // Proof:
1374     //   From IfNode::filtered_int_type, we get:
1375     //     lo_type = [min_int .. max(min_int, lo->_hi-1)]   for n < lo
1376     //     -> lo_type->_hi >= lo->_hi - 1
1377     //     hi_type = [min(hi->_lo+1, max_int) .. max_int]   for n > hi
1378     //     -> hi_type->_lo <= hi->_lo + 1
1379     //   We will need the assumption (LO-HI) below, which we can
1380     //   establish with the following (CHECK), which we must compute in
1381     //   long to avoid underflow:
1382     //        lo_type->_hi     <  hi_type->_lo - 1      (CHECK)
1383     //     -> lo_type->_hi + 1 <= hi_type->_lo - 1
1384     //     -> lo->_hi          <= hi->_lo
1385     //     -> lo               <= hi                    (LO-HI)
1386     //
1387     //   Case n <s lo:
1388     //     (BEFORE) is always false, show (AFTER) is always false.
1389     //     U(n - lo)              <= U(hi - lo)
1390     //     -- Lemma2 (n < lo) --     -- Lemma1 (hi >= lo, LO-HI) --
1391     //       n - lo + 2^32        <=  hi - lo
1392     //       n      + 2^32        <=  hi
1393     //     Always false by Lemma3.
1394     //
1395     //   Case lo <=s n <=s hi:
1396     //     (BEFORE) is always true, show (AFTER) is always true.
1397     //     U(n - lo)              <= U(hi - lo)
1398     //     -- Lemma1 (n >= lo) --    -- Lemma1 (hi >= lo, LO-HI) --
1399     //       n - lo               <=   hi - lo
1400     //       n                    <=   hi
1401     //     Corresponds to case assumption, so always true.
1402     //
1403     //   Case n >s hi:
1404     //     (BEFORE) is always false, show (AFTER) is always false.
1405     //     U(n - lo)              <=  U(hi - lo)
1406     //     -- Lemma1 (n > lo) --      -- Lemma1 (hi >= lo, LO-HI) --
1407     //       n - lo               <=    hi - lo
1408     //       n                    <=    hi
1409     //       n                    <=    hi
1410     //     Contradicts case assumption, so always false.
1411     // QED.
1412     //
1413     // Note: (CHECK) is stronger in this case than in (a, b, c). We have
1414     //       had multiple bugs around this case (d) in the past. For example:
1415     //       - Before JDK-8135069: transform into: n - lo <=u hi - lo
1416     //         leads to rhs underflow with lo=0      and hi=-1
1417     //         -> we are coming back to this solution, but instead
1418     //            of checking   lo_type->_hi <  hi_type->_lo
1419     //            we now check: lo_type->_hi <  hi_type->_lo - 1
1420     //            which implies lo <= hi and excludes this bad case.
1421     //       - Before JDK-8346420: transform into: n - lo <u hi - lo + 1
1422     //         leads to rhs overflow  with lo=min_int and hi=max_int
1423     //
1424     // Produce form: n - lo + x1 <cond> hi - lo + x2
1425     //               n - lo        <=u  hi - lo
1426     x1 = igvn->intcon(0);
1427     x2 = igvn->intcon(0);
1428     cond = BoolTest::le;
1429   }
1430 
1431   // Construct the new check: n - lo + x1 <cond> hi - lo + x2
1432   Node* lhs = igvn->transform(new SubINode(n,  lo));
1433   lhs = igvn->transform(new AddINode(lhs, x1));
1434   Node* rhs = igvn->transform(new SubINode(hi, lo));
1435   rhs = igvn->transform(new AddINode(rhs, x2));
1436   Node* newcmp = igvn->transform(new CmpUNode(lhs, rhs));
1437   if (succ->Opcode() == Op_IfFalse) { cond = BoolTest::negate_mask(cond); }
1438   Node* newbool = igvn->transform(new BoolNode(newcmp, cond));
1439 
1440   // Fold iff1 towards middle, and replace the iff2 condition:
1441   igvn->replace_input_of(iff1, 1, igvn->intcon(middle->_con));
1442   igvn->replace_input_of(iff2, 1, newbool);
1443 
1444   return true; // Success with CmpU
1445 }
1446 
1447 // Merge the branches that trap for this If and the dominating If into
1448 // a single region that branches to the uncommon trap for the
1449 // dominating If
1450 Node* IfNode::merge_uncommon_traps(IfProjNode* proj, IfProjNode* success, IfProjNode* fail, PhaseIterGVN* igvn) {
1451   Node* res = this;
1452   assert(success->in(0) == this, "bad projection");
1453 
1454   IfProjNode* otherproj = proj->other_if_proj();
1455 
1456   CallStaticJavaNode* unc = success->is_uncommon_trap_proj();
1457   CallStaticJavaNode* dom_unc = otherproj->is_uncommon_trap_proj();
1458 
1459   if (unc != dom_unc) {
1460     Node* r = new RegionNode(3);
1461 
1462     r->set_req(1, otherproj);
1463     r->set_req(2, success);
1464     r = igvn->transform(r);
1465     assert(r->is_Region(), "can't go away");
1466 
1467     // Make both If trap at the state of the first If: once the CmpI
1468     // nodes are merged, if we trap we don't know which of the CmpI
1469     // nodes would have caused the trap so we have to restart
1470     // execution at the first one
1471     igvn->replace_input_of(dom_unc, 0, r);
1472     igvn->replace_input_of(unc, 0, igvn->C->top());
1473   }
1474   int trap_request = dom_unc->uncommon_trap_request();
1475   Deoptimization::DeoptReason reason = Deoptimization::trap_request_reason(trap_request);
1476   Deoptimization::DeoptAction action = Deoptimization::trap_request_action(trap_request);
1477 
1478   int flip_test = 0;
1479   Node* l = nullptr;
1480   Node* r = nullptr;
1481 
1482   if (success->in(0)->as_If()->range_check_trap_proj(flip_test, l, r) != nullptr) {
1483     // If this looks like a range check, change the trap to
1484     // Reason_range_check so the compiler recognizes it as a range
1485     // check and applies the corresponding optimizations
1486     trap_request = Deoptimization::make_trap_request(Deoptimization::Reason_range_check, action);
1487 
1488     improve_address_types(l, r, fail, igvn);
1489 
1490     res = igvn->transform(new RangeCheckNode(in(0), in(1), _prob, _fcnt));
1491   } else if (unc != dom_unc) {
1492     // If we trap we won't know what CmpI would have caused the trap
1493     // so use a special trap reason to mark this pair of CmpI nodes as
1494     // bad candidate for folding. On recompilation we won't fold them
1495     // and we may trap again but this time we'll know what branch
1496     // traps
1497     trap_request = Deoptimization::make_trap_request(Deoptimization::Reason_unstable_fused_if, action);
1498   }
1499   igvn->replace_input_of(dom_unc, TypeFunc::Parms, igvn->intcon(trap_request));
1500   return res;
1501 }
1502 
1503 // If we are turning 2 CmpI nodes into a CmpU that follows the pattern
1504 // of a rangecheck on index i, on 64 bit the compares may be followed
1505 // by memory accesses using i as index. In that case, the CmpU tells
1506 // us something about the values taken by i that can help the compiler
1507 // (see Compile::conv_I2X_index())
1508 void IfNode::improve_address_types(Node* l, Node* r, ProjNode* fail, PhaseIterGVN* igvn) {
1509 #ifdef _LP64
1510   ResourceMark rm;
1511   Node_Stack stack(2);
1512 
1513   assert(r->Opcode() == Op_LoadRange, "unexpected range check");
1514   const TypeInt* array_size = igvn->type(r)->is_int();
1515 
1516   stack.push(l, 0);
1517 
1518   while(stack.size() > 0) {
1519     Node* n = stack.node();
1520     uint start = stack.index();
1521 
1522     uint i = start;
1523     for (; i < n->outcnt(); i++) {
1524       Node* use = n->raw_out(i);
1525       if (stack.size() == 1) {
1526         if (use->Opcode() == Op_ConvI2L) {
1527           const TypeLong* bounds = use->as_Type()->type()->is_long();
1528           if (bounds->_lo <= array_size->_lo && bounds->_hi >= array_size->_hi &&
1529               (bounds->_lo != array_size->_lo || bounds->_hi != array_size->_hi)) {
1530             stack.set_index(i+1);
1531             stack.push(use, 0);
1532             break;
1533           }
1534         }
1535       } else if (use->is_Mem()) {
1536         Node* ctrl = use->in(0);
1537         for (int i = 0; i < 10 && ctrl != nullptr && ctrl != fail; i++) {
1538           ctrl = up_one_dom(ctrl);
1539         }
1540         if (ctrl == fail) {
1541           Node* init_n = stack.node_at(1);
1542           assert(init_n->Opcode() == Op_ConvI2L, "unexpected first node");
1543           // Create a new narrow ConvI2L node that is dependent on the range check
1544           Node* new_n = igvn->C->conv_I2X_index(igvn, l, array_size, fail);
1545 
1546           // The type of the ConvI2L may be widen and so the new
1547           // ConvI2L may not be better than an existing ConvI2L
1548           if (new_n != init_n) {
1549             for (uint j = 2; j < stack.size(); j++) {
1550               Node* n = stack.node_at(j);
1551               Node* clone = n->clone();
1552               int rep = clone->replace_edge(init_n, new_n, igvn);
1553               assert(rep > 0, "can't find expected node?");
1554               clone = igvn->transform(clone);
1555               init_n = n;
1556               new_n = clone;
1557             }
1558             igvn->hash_delete(use);
1559             int rep = use->replace_edge(init_n, new_n, igvn);
1560             assert(rep > 0, "can't find expected node?");
1561             igvn->transform(use);
1562             if (init_n->outcnt() == 0) {
1563               igvn->_worklist.push(init_n);
1564             }
1565           }
1566         }
1567       } else if (use->in(0) == nullptr && (igvn->type(use)->isa_long() ||
1568                                         igvn->type(use)->isa_ptr())) {
1569         stack.set_index(i+1);
1570         stack.push(use, 0);
1571         break;
1572       }
1573     }
1574     if (i == n->outcnt()) {
1575       stack.pop();
1576     }
1577   }
1578 #endif
1579 }
1580 
1581 bool IfNode::is_cmp_with_loadrange(IfProjNode* proj) const {
1582   if (in(1) != nullptr &&
1583       in(1)->in(1) != nullptr &&
1584       in(1)->in(1)->in(2) != nullptr) {
1585     Node* other = in(1)->in(1)->in(2);
1586     if (other->Opcode() == Op_LoadRange &&
1587         ((other->in(0) != nullptr && other->in(0) == proj) ||
1588          (other->in(0) == nullptr &&
1589           other->in(2) != nullptr &&
1590           other->in(2)->is_AddP() &&
1591           other->in(2)->in(1) != nullptr &&
1592           other->in(2)->in(1)->Opcode() == Op_CastPP &&
1593           other->in(2)->in(1)->in(0) == proj))) {
1594       return true;
1595     }
1596   }
1597   return false;
1598 }
1599 
1600 bool IfNode::is_null_check(IfProjNode* proj, PhaseIterGVN* igvn) const {
1601   Node* other = in(1)->in(1)->in(2);
1602   if (other->in(MemNode::Address) != nullptr &&
1603       proj->in(0)->in(1) != nullptr &&
1604       proj->in(0)->in(1)->is_Bool() &&
1605       proj->in(0)->in(1)->in(1) != nullptr &&
1606       proj->in(0)->in(1)->in(1)->Opcode() == Op_CmpP &&
1607       proj->in(0)->in(1)->in(1)->in(2) != nullptr &&
1608       proj->in(0)->in(1)->in(1)->in(1) == other->in(MemNode::Address)->in(AddPNode::Address)->uncast() &&
1609       igvn->type(proj->in(0)->in(1)->in(1)->in(2)) == TypePtr::NULL_PTR) {
1610     return true;
1611   }
1612   return false;
1613 }
1614 
1615 // Check that the If that is in between the 2 integer comparisons has
1616 // no side effect
1617 bool IfNode::is_side_effect_free_test(IfProjNode* proj, PhaseIterGVN* igvn) const {
1618   if (proj == nullptr) {
1619     return false;
1620   }
1621   CallStaticJavaNode* unc = proj->is_uncommon_trap_if_pattern();
1622   if (unc != nullptr && proj->outcnt() <= 2) {
1623     if (proj->outcnt() == 1 ||
1624         // Allow simple null check from LoadRange
1625         (is_cmp_with_loadrange(proj) && is_null_check(proj, igvn))) {
1626       CallStaticJavaNode* unc = proj->is_uncommon_trap_if_pattern();
1627       CallStaticJavaNode* dom_unc = proj->in(0)->in(0)->as_Proj()->is_uncommon_trap_if_pattern();
1628       assert(dom_unc != nullptr, "is_uncommon_trap_if_pattern returned null");
1629 
1630       // reroute_side_effect_free_unc changes the state of this
1631       // uncommon trap to restart execution at the previous
1632       // CmpI. Check that this change in a previous compilation didn't
1633       // cause too many traps.
1634       int trap_request = unc->uncommon_trap_request();
1635       Deoptimization::DeoptReason reason = Deoptimization::trap_request_reason(trap_request);
1636 
1637       if (igvn->C->too_many_traps(dom_unc->jvms()->method(), dom_unc->jvms()->bci(), reason)) {
1638         return false;
1639       }
1640 
1641       if (!is_dominator_unc(dom_unc, unc)) {
1642         return false;
1643       }
1644 
1645       return true;
1646     }
1647   }
1648   return false;
1649 }
1650 
1651 // Make the If between the 2 integer comparisons trap at the state of
1652 // the first If: the last CmpI is the one replaced by a CmpU and the
1653 // first CmpI is eliminated, so the test between the 2 CmpI nodes
1654 // won't be guarded by the first CmpI anymore. It can trap in cases
1655 // where the first CmpI would have prevented it from executing: on a
1656 // trap, we need to restart execution at the state of the first CmpI
1657 void IfNode::reroute_side_effect_free_unc(IfProjNode* proj, IfProjNode* dom_proj, PhaseIterGVN* igvn) {
1658   CallStaticJavaNode* dom_unc = dom_proj->is_uncommon_trap_if_pattern();
1659   IfProjNode* otherproj = proj->other_if_proj();
1660   CallStaticJavaNode* unc = proj->is_uncommon_trap_if_pattern();
1661   Node* call_proj = dom_unc->unique_ctrl_out();
1662   Node* halt = call_proj->unique_ctrl_out();
1663 
1664   Node* new_unc = dom_unc->clone();
1665   call_proj = call_proj->clone();
1666   halt = halt->clone();
1667   Node* c = otherproj->clone();
1668 
1669   c = igvn->transform(c);
1670   new_unc->set_req(TypeFunc::Parms, unc->in(TypeFunc::Parms));
1671   new_unc->set_req(0, c);
1672   new_unc = igvn->transform(new_unc);
1673   call_proj->set_req(0, new_unc);
1674   call_proj = igvn->transform(call_proj);
1675   halt->set_req(0, call_proj);
1676   halt = igvn->transform(halt);
1677 
1678   igvn->replace_node(otherproj, igvn->C->top());
1679   igvn->C->root()->add_req(halt);
1680 }
1681 
1682 Node* IfNode::fold_compares(PhaseIterGVN* igvn) {
1683   if (Opcode() != Op_If) return nullptr;
1684 
1685   if (cmpi_folds(igvn)) {
1686     Node* ctrl = in(0);
1687     if (is_ctrl_folds(ctrl, igvn)) {
1688       // A integer comparison immediately dominated by another integer
1689       // comparison
1690       IfProjNode* success = nullptr;
1691       IfProjNode* fail = nullptr;
1692       IfProjNode* dom_cmp = ctrl->as_IfProj();
1693       if (has_shared_region(dom_cmp, success, fail) &&
1694           // Next call modifies graph so must be last
1695           fold_compares_helper(dom_cmp, success, fail, igvn)) {
1696         return this;
1697       }
1698       if (has_only_uncommon_traps(dom_cmp, success, fail, igvn) &&
1699           // Next call modifies graph so must be last
1700           fold_compares_helper(dom_cmp, success, fail, igvn)) {
1701         return merge_uncommon_traps(dom_cmp, success, fail, igvn);
1702       }
1703       return nullptr;
1704     } else if (ctrl->in(0) != nullptr &&
1705                ctrl->in(0)->in(0) != nullptr) {
1706       IfProjNode* success = nullptr;
1707       IfProjNode* fail = nullptr;
1708       Node* dom = ctrl->in(0)->in(0);
1709       IfProjNode* dom_cmp = dom->isa_IfProj();
1710       IfProjNode* other_cmp = ctrl->isa_IfProj();
1711 
1712       // Check if it's an integer comparison dominated by another
1713       // integer comparison with another test in between
1714       if (is_ctrl_folds(dom, igvn) &&
1715           has_only_uncommon_traps(dom_cmp, success, fail, igvn) &&
1716           is_side_effect_free_test(other_cmp, igvn) &&
1717           // Next call modifies graph so must be last
1718           fold_compares_helper(dom_cmp, success, fail, igvn)) {
1719         reroute_side_effect_free_unc(other_cmp, dom_cmp, igvn);
1720         return merge_uncommon_traps(dom_cmp, success, fail, igvn);
1721       }
1722     }
1723   }
1724   return nullptr;
1725 }
1726 
1727 //------------------------------remove_useless_bool----------------------------
1728 // Check for people making a useless boolean: things like
1729 // if( (x < y ? true : false) ) { ... }
1730 // Replace with if( x < y ) { ... }
1731 static Node *remove_useless_bool(IfNode *iff, PhaseGVN *phase) {
1732   Node *i1 = iff->in(1);
1733   if( !i1->is_Bool() ) return nullptr;
1734   BoolNode *bol = i1->as_Bool();
1735 
1736   Node *cmp = bol->in(1);
1737   if( cmp->Opcode() != Op_CmpI ) return nullptr;
1738 
1739   // Must be comparing against a bool
1740   const Type *cmp2_t = phase->type( cmp->in(2) );
1741   if( cmp2_t != TypeInt::ZERO &&
1742       cmp2_t != TypeInt::ONE )
1743     return nullptr;
1744 
1745   // Find a prior merge point merging the boolean
1746   i1 = cmp->in(1);
1747   if( !i1->is_Phi() ) return nullptr;
1748   PhiNode *phi = i1->as_Phi();
1749   if( phase->type( phi ) != TypeInt::BOOL )
1750     return nullptr;
1751 
1752   // Check for diamond pattern
1753   int true_path = phi->is_diamond_phi();
1754   if( true_path == 0 ) return nullptr;
1755 
1756   // Make sure that iff and the control of the phi are different. This
1757   // should really only happen for dead control flow since it requires
1758   // an illegal cycle.
1759   if (phi->in(0)->in(1)->in(0) == iff) return nullptr;
1760 
1761   // phi->region->if_proj->ifnode->bool->cmp
1762   BoolNode *bol2 = phi->in(0)->in(1)->in(0)->in(1)->as_Bool();
1763 
1764   // Now get the 'sense' of the test correct so we can plug in
1765   // either iff2->in(1) or its complement.
1766   int flip = 0;
1767   if( bol->_test._test == BoolTest::ne ) flip = 1-flip;
1768   else if( bol->_test._test != BoolTest::eq ) return nullptr;
1769   if( cmp2_t == TypeInt::ZERO ) flip = 1-flip;
1770 
1771   const Type *phi1_t = phase->type( phi->in(1) );
1772   const Type *phi2_t = phase->type( phi->in(2) );
1773   // Check for Phi(0,1) and flip
1774   if( phi1_t == TypeInt::ZERO ) {
1775     if( phi2_t != TypeInt::ONE ) return nullptr;
1776     flip = 1-flip;
1777   } else {
1778     // Check for Phi(1,0)
1779     if( phi1_t != TypeInt::ONE  ) return nullptr;
1780     if( phi2_t != TypeInt::ZERO ) return nullptr;
1781   }
1782   if( true_path == 2 ) {
1783     flip = 1-flip;
1784   }
1785 
1786   Node* new_bol = (flip ? phase->transform( bol2->negate(phase) ) : bol2);
1787   assert(new_bol != iff->in(1), "must make progress");
1788   iff->set_req_X(1, new_bol, phase);
1789   // Intervening diamond probably goes dead
1790   phase->C->set_major_progress();
1791   return iff;
1792 }
1793 
1794 static IfNode* idealize_test(PhaseGVN* phase, IfNode* iff);
1795 
1796 struct RangeCheck {
1797   IfProjNode* ctl;
1798   jint off;
1799 };
1800 
1801 Node* IfNode::Ideal_common(PhaseGVN *phase, bool can_reshape) {
1802   if (remove_dead_region(phase, can_reshape))  return this;
1803   // No Def-Use info?
1804   if (!can_reshape)  return nullptr;
1805 
1806   // Don't bother trying to transform a dead if
1807   if (in(0)->is_top())  return nullptr;
1808   // Don't bother trying to transform an if with a dead test
1809   if (in(1)->is_top())  return nullptr;
1810   // Another variation of a dead test
1811   if (in(1)->is_Con())  return nullptr;
1812   // Another variation of a dead if
1813   if (outcnt() < 2)  return nullptr;
1814 
1815   // Canonicalize the test.
1816   Node* idt_if = idealize_test(phase, this);
1817   if (idt_if != nullptr)  return idt_if;
1818 
1819   // Try to split the IF
1820   PhaseIterGVN *igvn = phase->is_IterGVN();
1821   Node *s = split_if(this, igvn);
1822   if (s != nullptr)  return s;
1823 
1824   return NodeSentinel;
1825 }
1826 
1827 //------------------------------Ideal------------------------------------------
1828 // Return a node which is more "ideal" than the current node.  Strip out
1829 // control copies
1830 Node* IfNode::Ideal(PhaseGVN *phase, bool can_reshape) {
1831   Node* res = Ideal_common(phase, can_reshape);
1832   if (res != NodeSentinel) {
1833     return res;
1834   }
1835 
1836   // Check for people making a useless boolean: things like
1837   // if( (x < y ? true : false) ) { ... }
1838   // Replace with if( x < y ) { ... }
1839   Node* bol2 = remove_useless_bool(this, phase);
1840   if (bol2) return bol2;
1841 
1842   if (in(0) == nullptr) return nullptr;     // Dead loop?
1843 
1844   PhaseIterGVN* igvn = phase->is_IterGVN();
1845   Node* result = fold_compares(igvn);
1846   if (result != nullptr) {
1847     return result;
1848   }
1849 
1850   // Scan for an equivalent test
1851   int dist = 4;               // Cutoff limit for search
1852   if (is_If() && in(1)->is_Bool()) {
1853     Node* cmp = in(1)->in(1);
1854     if (cmp->Opcode() == Op_CmpP &&
1855         cmp->in(2) != nullptr && // make sure cmp is not already dead
1856         cmp->in(2)->bottom_type() == TypePtr::NULL_PTR) {
1857       dist = 64;              // Limit for null-pointer scans
1858     }
1859   }
1860 
1861   Node* prev_dom = search_identical(dist, igvn);
1862 
1863   if (prev_dom != nullptr) {
1864     // Dominating CountedLoopEnd (left over from some now dead loop) will become the new loop exit. Outer strip mined
1865     // loop will go away. Mark this loop as no longer strip mined.
1866     if (is_CountedLoopEnd()) {
1867       CountedLoopNode* counted_loop_node = as_CountedLoopEnd()->loopnode();
1868       if (counted_loop_node != nullptr) {
1869         counted_loop_node->clear_strip_mined();
1870       }
1871     }
1872     // Replace dominated IfNode
1873     return dominated_by(prev_dom, igvn, false);
1874   }
1875 
1876   return simple_subsuming(igvn);
1877 }
1878 
1879 //------------------------------dominated_by-----------------------------------
1880 Node* IfNode::dominated_by(Node* prev_dom, PhaseIterGVN* igvn, bool prev_dom_not_imply_this) {
1881 #ifndef PRODUCT
1882   if (TraceIterativeGVN) {
1883     tty->print("   Removing IfNode: "); this->dump();
1884   }
1885 #endif
1886 
1887   igvn->hash_delete(this);      // Remove self to prevent spurious V-N
1888   Node *idom = in(0);
1889   // Need opcode to decide which way 'this' test goes
1890   int prev_op = prev_dom->Opcode();
1891   Node *top = igvn->C->top(); // Shortcut to top
1892 
1893   // Now walk the current IfNode's projections.
1894   // Loop ends when 'this' has no more uses.
1895   for (DUIterator_Last imin, i = last_outs(imin); i >= imin; --i) {
1896     Node *ifp = last_out(i);     // Get IfTrue/IfFalse
1897     igvn->add_users_to_worklist(ifp);
1898     // Check which projection it is and set target.
1899     // Data-target is either the dominating projection of the same type
1900     // or TOP if the dominating projection is of opposite type.
1901     // Data-target will be used as the new control edge for the non-CFG
1902     // nodes like Casts and Loads.
1903     Node *data_target = (ifp->Opcode() == prev_op) ? prev_dom : top;
1904     // Control-target is just the If's immediate dominator or TOP.
1905     Node *ctrl_target = (ifp->Opcode() == prev_op) ?     idom : top;
1906 
1907     // For each child of an IfTrue/IfFalse projection, reroute.
1908     // Loop ends when projection has no more uses.
1909     for (DUIterator_Last jmin, j = ifp->last_outs(jmin); j >= jmin; --j) {
1910       Node* s = ifp->last_out(j);   // Get child of IfTrue/IfFalse
1911       if (s->depends_only_on_test()) {
1912         // For control producers
1913         igvn->replace_input_of(s, 0, data_target); // Move child to data-target
1914         if (prev_dom_not_imply_this && data_target != top) {
1915           // If prev_dom_not_imply_this, s now depends on multiple tests with prev_dom being the
1916           // lowest dominating one. As a result, it must be pinned there. Otherwise, it can be
1917           // incorrectly moved to a dominating test equivalent to the lowest one here.
1918           Node* clone = s->pin_node_under_control();
1919           if (clone != nullptr) {
1920             igvn->register_new_node_with_optimizer(clone, s);
1921             igvn->replace_node(s, clone);
1922           }
1923         }
1924       } else {
1925         // Find the control input matching this def-use edge.
1926         // For Regions it may not be in slot 0.
1927         uint l;
1928         for (l = 0; s->in(l) != ifp; l++) { }
1929         igvn->replace_input_of(s, l, ctrl_target);
1930       }
1931     } // End for each child of a projection
1932 
1933     igvn->remove_dead_node(ifp, PhaseIterGVN::NodeOrigin::Graph);
1934   } // End for each IfTrue/IfFalse child of If
1935 
1936   // Kill the IfNode
1937   igvn->remove_dead_node(this, PhaseIterGVN::NodeOrigin::Graph);
1938 
1939   // Must return either the original node (now dead) or a new node
1940   // (Do not return a top here, since that would break the uniqueness of top.)
1941   return new ConINode(TypeInt::ZERO);
1942 }
1943 
1944 Node* IfNode::search_identical(int dist, PhaseIterGVN* igvn) {
1945   // Setup to scan up the CFG looking for a dominating test
1946   Node* dom = in(0);
1947   Node* prev_dom = this;
1948   int op = Opcode();
1949   // Search up the dominator tree for an If with an identical test
1950   while (dom->Opcode() != op ||  // Not same opcode?
1951          !same_condition(dom, igvn) ||  // Not same input 1?
1952          prev_dom->in(0) != dom) {  // One path of test does not dominate?
1953     if (dist < 0) return nullptr;
1954 
1955     dist--;
1956     prev_dom = dom;
1957     dom = up_one_dom(dom);
1958     if (!dom) return nullptr;
1959   }
1960 
1961   // Check that we did not follow a loop back to ourselves
1962   if (this == dom) {
1963     return nullptr;
1964   }
1965 
1966 #ifndef PRODUCT
1967   if (dist > 2) { // Add to count of null checks elided
1968     explicit_null_checks_elided++;
1969   }
1970 #endif
1971 
1972   return prev_dom;
1973 }
1974 
1975 bool IfNode::same_condition(const Node* dom, PhaseIterGVN* igvn) const {
1976   Node* dom_bool = dom->in(1);
1977   Node* this_bool = in(1);
1978   if (dom_bool == this_bool) {
1979     return true;
1980   }
1981 
1982   if (dom_bool == nullptr || !dom_bool->is_Bool() ||
1983       this_bool == nullptr || !this_bool->is_Bool()) {
1984     return false;
1985   }
1986   Node* dom_cmp = dom_bool->in(1);
1987   Node* this_cmp = this_bool->in(1);
1988 
1989   // If the comparison is a subtype check, then SubTypeCheck nodes may have profile data attached to them and may be
1990   // different nodes even-though they perform the same subtype check
1991   if (dom_cmp == nullptr || !dom_cmp->is_SubTypeCheck() ||
1992       this_cmp == nullptr || !this_cmp->is_SubTypeCheck()) {
1993     return false;
1994   }
1995 
1996   if (dom_cmp->in(1) != this_cmp->in(1) ||
1997       dom_cmp->in(2) != this_cmp->in(2) ||
1998       dom_bool->as_Bool()->_test._test != this_bool->as_Bool()->_test._test) {
1999     return false;
2000   }
2001 
2002   return true;
2003 }
2004 
2005 void IfNode::mark_projections_unsafe_for_fold_compare() const {
2006   // With the following code pattern
2007   //
2008   // if (some_condition) {
2009   //     v = 0;
2010   // } else {
2011   //     v = 1;
2012   // } // v is Phi(0, 1)
2013   // if (v == 0) {
2014   //     uncommon_trap(); // reexecutes the "if (v == 0) {" above, captures v as stack argument to ifeq bytecode
2015   // }
2016   // if (some_other_condition) {
2017   //     uncommon_trap(); // reexecutes the "if (some_other_condition) {"
2018   // }
2019   //
2020   // if the second if is split thru Phi, the result is:
2021   //
2022   // if (some_condition) {
2023   //     uncommon_trap(); // reexecutes the "if (v == 0) {" that was removed above, captures v = 0 as stack argument to ifeq bytecode
2024   // }
2025   // if (some_other_condition) {
2026   //     uncommon_trap(); // reexecutes the "if (some_other_condition) {"
2027   // }
2028   //
2029   // some_condition and some_other_condition could be folded into
2030   // a single new condition that is narrower than some_condition
2031   // (done by IfNode::fold_compares(), for instance):
2032   //
2033   // if (combined_narrower_condition) {
2034   //     uncommon_trap(); // reexecutes the "if (v == 0) {" that was removed, captures v = 0 as stack argument to ifeq bytecode
2035   // }
2036   //
2037   // Then combined_narrower_condition is true for some input value for
2038   // which some_condition is false. When such an input value is used
2039   // at runtime, the trap is taken which causes "if (v == 0) {" to be
2040   // reexecuted with v = 0 even though some_condition is wrong, causing
2041   // the wrong branch to be executed.
2042   //
2043   // Mark the uncommon trap nodes to prevent such a transformation
2044   // from happening.
2045   IfProjNode* true_projection = true_proj();
2046   IfProjNode* false_projection = false_proj();
2047   CallStaticJavaNode* unc = true_projection->is_uncommon_trap_proj();
2048   if (unc != nullptr) {
2049     unc->clear_safe_for_fold_compare();
2050   }
2051   unc = false_projection->is_uncommon_trap_proj();
2052   if (unc != nullptr) {
2053     unc->clear_safe_for_fold_compare();
2054   }
2055 }
2056 
2057 static int subsuming_bool_test_encode(Node*);
2058 
2059 // Check if dominating test is subsuming 'this' one.
2060 //
2061 //              cmp
2062 //              / \
2063 //     (r1)  bool  \
2064 //            /    bool (r2)
2065 //    (dom) if       \
2066 //            \       )
2067 //    (pre)  if[TF]  /
2068 //               \  /
2069 //                if (this)
2070 //   \r1
2071 //  r2\  eqT  eqF  neT  neF  ltT  ltF  leT  leF  gtT  gtF  geT  geF
2072 //  eq    t    f    f    t    f    -    -    f    f    -    -    f
2073 //  ne    f    t    t    f    t    -    -    t    t    -    -    t
2074 //  lt    f    -    -    f    t    f    -    f    f    -    f    t
2075 //  le    t    -    -    t    t    -    t    f    f    t    -    t
2076 //  gt    f    -    -    f    f    -    f    t    t    f    -    f
2077 //  ge    t    -    -    t    f    t    -    t    t    -    t    f
2078 //
2079 Node* IfNode::simple_subsuming(PhaseIterGVN* igvn) {
2080   // Table encoding: N/A (na), True-branch (tb), False-branch (fb).
2081   static enum { na, tb, fb } s_short_circuit_map[6][12] = {
2082   /*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*/
2083   /*eq*/{ tb,  fb,  fb,  tb,  fb,  na,  na,  fb,  fb,  na,  na,  fb },
2084   /*ne*/{ fb,  tb,  tb,  fb,  tb,  na,  na,  tb,  tb,  na,  na,  tb },
2085   /*lt*/{ fb,  na,  na,  fb,  tb,  fb,  na,  fb,  fb,  na,  fb,  tb },
2086   /*le*/{ tb,  na,  na,  tb,  tb,  na,  tb,  fb,  fb,  tb,  na,  tb },
2087   /*gt*/{ fb,  na,  na,  fb,  fb,  na,  fb,  tb,  tb,  fb,  na,  fb },
2088   /*ge*/{ tb,  na,  na,  tb,  fb,  tb,  na,  tb,  tb,  na,  tb,  fb }};
2089 
2090   Node* pre = in(0);
2091   if (!pre->is_IfTrue() && !pre->is_IfFalse()) {
2092     return nullptr;
2093   }
2094   Node* dom = pre->in(0);
2095   if (!dom->is_If()) {
2096     return nullptr;
2097   }
2098   Node* bol = in(1);
2099   if (!bol->is_Bool()) {
2100     return nullptr;
2101   }
2102   Node* cmp = in(1)->in(1);
2103   if (!cmp->is_Cmp()) {
2104     return nullptr;
2105   }
2106 
2107   if (!dom->in(1)->is_Bool()) {
2108     return nullptr;
2109   }
2110   if (dom->in(1)->in(1) != cmp) {  // Not same cond?
2111     return nullptr;
2112   }
2113 
2114   int drel = subsuming_bool_test_encode(dom->in(1));
2115   int trel = subsuming_bool_test_encode(bol);
2116   int bout = pre->is_IfFalse() ? 1 : 0;
2117 
2118   if (drel < 0 || trel < 0) {
2119     return nullptr;
2120   }
2121   int br = s_short_circuit_map[trel][2*drel+bout];
2122   if (br == na) {
2123     return nullptr;
2124   }
2125 #ifndef PRODUCT
2126   if (TraceIterativeGVN) {
2127     tty->print("   Subsumed IfNode: "); dump();
2128   }
2129 #endif
2130   // Replace condition with constant True(1)/False(0).
2131   bool is_always_true = br == tb;
2132   set_req(1, igvn->intcon(is_always_true ? 1 : 0));
2133 
2134   // Update any data dependencies to the directly dominating test. This subsumed test is not immediately removed by igvn
2135   // and therefore subsequent optimizations might miss these data dependencies otherwise. There might be a dead loop
2136   // ('always_taken_proj' == 'pre') that is cleaned up later. Skip this case to make the iterator work properly.
2137   Node* always_taken_proj = proj_out(is_always_true);
2138   if (always_taken_proj != pre) {
2139     for (DUIterator_Fast imax, i = always_taken_proj->fast_outs(imax); i < imax; i++) {
2140       Node* u = always_taken_proj->fast_out(i);
2141       if (!u->is_CFG()) {
2142         igvn->replace_input_of(u, 0, pre);
2143         --i;
2144         --imax;
2145       }
2146     }
2147   }
2148 
2149   if (bol->outcnt() == 0) {
2150     igvn->remove_dead_node(bol, PhaseIterGVN::NodeOrigin::Graph);    // Kill the BoolNode.
2151   }
2152   return this;
2153 }
2154 
2155 // Map BoolTest to local table encoding. The BoolTest (e)numerals
2156 //   { eq = 0, ne = 4, le = 5, ge = 7, lt = 3, gt = 1 }
2157 // are mapped to table indices, while the remaining (e)numerals in BoolTest
2158 //   { overflow = 2, no_overflow = 6, never = 8, illegal = 9 }
2159 // are ignored (these are not modeled in the table).
2160 //
2161 static int subsuming_bool_test_encode(Node* node) {
2162   precond(node->is_Bool());
2163   BoolTest::mask x = node->as_Bool()->_test._test;
2164   switch (x) {
2165     case BoolTest::eq: return 0;
2166     case BoolTest::ne: return 1;
2167     case BoolTest::lt: return 2;
2168     case BoolTest::le: return 3;
2169     case BoolTest::gt: return 4;
2170     case BoolTest::ge: return 5;
2171     case BoolTest::overflow:
2172     case BoolTest::no_overflow:
2173     case BoolTest::never:
2174     case BoolTest::illegal:
2175     default:
2176       return -1;
2177   }
2178 }
2179 
2180 //------------------------------Identity---------------------------------------
2181 // If the test is constant & we match, then we are the input Control
2182 Node* IfProjNode::Identity(PhaseGVN* phase) {
2183   // Can only optimize if cannot go the other way
2184   const TypeTuple *t = phase->type(in(0))->is_tuple();
2185   if (t == TypeTuple::IFNEITHER || (always_taken(t) &&
2186        // During parsing (GVN) we don't remove dead code aggressively.
2187        // Cut off dead branch and let PhaseRemoveUseless take care of it.
2188       (!phase->is_IterGVN() ||
2189        // During IGVN, first wait for the dead branch to be killed.
2190        // Otherwise, the IfNode's control will have two control uses (the IfNode
2191        // that doesn't go away because it still has uses and this branch of the
2192        // If) which breaks other optimizations. Node::has_special_unique_user()
2193        // will cause this node to be reprocessed once the dead branch is killed.
2194        in(0)->outcnt() == 1))) {
2195     // IfNode control
2196     if (in(0)->is_BaseCountedLoopEnd()) {
2197       // CountedLoopEndNode may be eliminated by if subsuming, replace CountedLoopNode with LoopNode to
2198       // avoid mismatching between CountedLoopNode and CountedLoopEndNode in the following optimization.
2199       Node* head = unique_ctrl_out_or_null();
2200       if (head != nullptr && head->is_BaseCountedLoop() && head->in(LoopNode::LoopBackControl) == this) {
2201         Node* new_head = new LoopNode(head->in(LoopNode::EntryControl), this);
2202         phase->is_IterGVN()->register_new_node_with_optimizer(new_head);
2203         phase->is_IterGVN()->replace_node(head, new_head);
2204       }
2205     }
2206     return in(0)->in(0);
2207   }
2208   // no progress
2209   return this;
2210 }
2211 
2212 bool IfNode::is_zero_trip_guard() const {
2213   if (in(1)->is_Bool() && in(1)->in(1)->is_Cmp()) {
2214     return in(1)->in(1)->in(1)->Opcode() == Op_OpaqueZeroTripGuard;
2215   }
2216   return false;
2217 }
2218 
2219 void IfProjNode::pin_dependent_nodes(PhaseIterGVN* igvn) {
2220   for (DUIterator i = outs(); has_out(i); i++) {
2221     Node* u = out(i);
2222     if (!u->depends_only_on_test()) {
2223       continue;
2224     }
2225     Node* clone = u->pin_node_under_control();
2226     if (clone != nullptr) {
2227       igvn->register_new_node_with_optimizer(clone, u);
2228       igvn->replace_node(u, clone);
2229       --i;
2230     }
2231   }
2232 }
2233 
2234 #ifndef PRODUCT
2235 void IfNode::dump_spec(outputStream* st) const {
2236   switch (_assertion_predicate_type) {
2237     case AssertionPredicateType::InitValue:
2238       st->print("#Init Value Assertion Predicate  ");
2239       break;
2240     case AssertionPredicateType::LastValue:
2241       st->print("#Last Value Assertion Predicate  ");
2242       break;
2243     case AssertionPredicateType::FinalIv:
2244       st->print("#Final IV Assertion Predicate  ");
2245       break;
2246     case AssertionPredicateType::None:
2247       // No Assertion Predicate
2248       break;
2249     default:
2250       fatal("Unknown Assertion Predicate type");
2251   }
2252   st->print("P=%f, C=%f", _prob, _fcnt);
2253 }
2254 #endif // NOT PRODUCT
2255 
2256 //------------------------------idealize_test----------------------------------
2257 // Try to canonicalize tests better.  Peek at the Cmp/Bool/If sequence and
2258 // come up with a canonical sequence.  Bools getting 'eq', 'gt' and 'ge' forms
2259 // converted to 'ne', 'le' and 'lt' forms.  IfTrue/IfFalse get swapped as
2260 // needed.
2261 static IfNode* idealize_test(PhaseGVN* phase, IfNode* iff) {
2262   assert(iff->in(0) != nullptr, "If must be live");
2263 
2264   if (iff->outcnt() != 2)  return nullptr; // Malformed projections.
2265   IfFalseNode* old_if_f = iff->false_proj();
2266   IfTrueNode* old_if_t = iff->true_proj();
2267 
2268   // CountedLoopEnds want the back-control test to be TRUE, regardless of
2269   // whether they are testing a 'gt' or 'lt' condition.  The 'gt' condition
2270   // happens in count-down loops
2271   if (iff->is_BaseCountedLoopEnd())  return nullptr;
2272   if (!iff->in(1)->is_Bool())  return nullptr; // Happens for partially optimized IF tests
2273   BoolNode *b = iff->in(1)->as_Bool();
2274   BoolTest bt = b->_test;
2275   // Test already in good order?
2276   if( bt.is_canonical() )
2277     return nullptr;
2278 
2279   // Flip test to be canonical.  Requires flipping the IfFalse/IfTrue and
2280   // cloning the IfNode.
2281   Node* new_b = phase->transform( new BoolNode(b->in(1), bt.negate()) );
2282   if( !new_b->is_Bool() ) return nullptr;
2283   b = new_b->as_Bool();
2284 
2285   PhaseIterGVN *igvn = phase->is_IterGVN();
2286   assert( igvn, "Test is not canonical in parser?" );
2287 
2288   // The IF node never really changes, but it needs to be cloned
2289   iff = iff->clone()->as_If();
2290   iff->set_req(1, b);
2291   iff->_prob = 1.0-iff->_prob;
2292 
2293   Node *prior = igvn->hash_find_insert(iff);
2294   if( prior ) {
2295     igvn->remove_dead_node(iff, PhaseIterGVN::NodeOrigin::Graph);
2296     iff = (IfNode*)prior;
2297   } else {
2298     // Cannot call transform on it just yet
2299     igvn->set_type_bottom(iff);
2300   }
2301   igvn->_worklist.push(iff);
2302 
2303   // Now handle projections.  Cloning not required.
2304   Node* new_if_f = (Node*)(new IfFalseNode( iff ));
2305   Node* new_if_t = (Node*)(new IfTrueNode ( iff ));
2306 
2307   igvn->register_new_node_with_optimizer(new_if_f);
2308   igvn->register_new_node_with_optimizer(new_if_t);
2309   // Flip test, so flip trailing control
2310   igvn->replace_node(old_if_f, new_if_t);
2311   igvn->replace_node(old_if_t, new_if_f);
2312 
2313   // Progress
2314   return iff;
2315 }
2316 
2317 Node* RangeCheckNode::Ideal(PhaseGVN *phase, bool can_reshape) {
2318   Node* res = Ideal_common(phase, can_reshape);
2319   if (res != NodeSentinel) {
2320     return res;
2321   }
2322 
2323   PhaseIterGVN *igvn = phase->is_IterGVN();
2324   // Setup to scan up the CFG looking for a dominating test
2325   Node* prev_dom = this;
2326 
2327   // Check for range-check vs other kinds of tests
2328   Node* index1;
2329   Node* range1;
2330   jint offset1;
2331   int flip1 = is_range_check(range1, index1, offset1);
2332   if (flip1) {
2333     Node* dom = in(0);
2334     // Try to remove extra range checks.  All 'up_one_dom' gives up at merges
2335     // so all checks we inspect post-dominate the top-most check we find.
2336     // If we are going to fail the current check and we reach the top check
2337     // then we are guaranteed to fail, so just start interpreting there.
2338     // We 'expand' the top 3 range checks to include all post-dominating
2339     // checks.
2340     //
2341     // Example:
2342     // a[i+x] // (1) 1 < x < 6
2343     // a[i+3] // (2)
2344     // a[i+4] // (3)
2345     // a[i+6] // max = max of all constants
2346     // a[i+2]
2347     // a[i+1] // min = min of all constants
2348     //
2349     // If x < 3:
2350     //   (1) a[i+x]: Leave unchanged
2351     //   (2) a[i+3]: Replace with a[i+max] = a[i+6]: i+x < i+3 <= i+6  -> (2) is covered
2352     //   (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
2353     //   Remove all other a[i+c] checks
2354     //
2355     // If x >= 3:
2356     //   (1) a[i+x]: Leave unchanged
2357     //   (2) a[i+3]: Replace with a[i+min] = a[i+1]: i+1 < i+3 <= i+x  -> (2) is covered
2358     //   (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
2359     //   Remove all other a[i+c] checks
2360     //
2361     // We only need the top 2 range checks if x is the min or max of all constants.
2362     //
2363     // This, however, only works if the interval [i+min,i+max] is not larger than max_int (i.e. abs(max - min) < max_int):
2364     // The theoretical max size of an array is max_int with:
2365     // - Valid index space: [0,max_int-1]
2366     // - Invalid index space: [max_int,-1] // max_int, min_int, min_int - 1 ..., -1
2367     //
2368     // The size of the consecutive valid index space is smaller than the size of the consecutive invalid index space.
2369     // If we choose min and max in such a way that:
2370     // - abs(max - min) < max_int
2371     // - i+max and i+min are inside the valid index space
2372     // then all indices [i+min,i+max] must be in the valid index space. Otherwise, the invalid index space must be
2373     // smaller than the valid index space which is never the case for any array size.
2374     //
2375     // Choosing a smaller array size only makes the valid index space smaller and the invalid index space larger and
2376     // the argument above still holds.
2377     //
2378     // Note that the same optimization with the same maximal accepted interval size can also be found in C1.
2379     const jlong maximum_number_of_min_max_interval_indices = (jlong)max_jint;
2380 
2381     // The top 3 range checks seen
2382     const int NRC = 3;
2383     RangeCheck prev_checks[NRC];
2384     int nb_checks = 0;
2385 
2386     // Low and high offsets seen so far
2387     jint off_lo = offset1;
2388     jint off_hi = offset1;
2389 
2390     bool found_immediate_dominator = false;
2391 
2392     // Scan for the top checks and collect range of offsets
2393     for (int dist = 0; dist < 999; dist++) { // Range-Check scan limit
2394       if (dom->Opcode() == Op_RangeCheck &&  // Not same opcode?
2395           prev_dom->in(0) == dom) { // One path of test does dominate?
2396         if (dom == this) return nullptr; // dead loop
2397         // See if this is a range check
2398         Node* index2;
2399         Node* range2;
2400         jint offset2;
2401         int flip2 = dom->as_RangeCheck()->is_range_check(range2, index2, offset2);
2402         // See if this is a _matching_ range check, checking against
2403         // the same array bounds.
2404         if (flip2 == flip1 && range2 == range1 && index2 == index1 &&
2405             dom->outcnt() == 2) {
2406           if (nb_checks == 0 && dom->in(1) == in(1)) {
2407             // Found an immediately dominating test at the same offset.
2408             // This kind of back-to-back test can be eliminated locally,
2409             // and there is no need to search further for dominating tests.
2410             assert(offset2 == offset1, "Same test but different offsets");
2411             found_immediate_dominator = true;
2412             break;
2413           }
2414 
2415           // "x - y" -> must add one to the difference for number of elements in [x,y]
2416           const jlong diff = (jlong)MIN2(offset2, off_lo) - (jlong)MAX2(offset2, off_hi);
2417           if (ABS(diff) < maximum_number_of_min_max_interval_indices) {
2418             // Gather expanded bounds
2419             off_lo = MIN2(off_lo, offset2);
2420             off_hi = MAX2(off_hi, offset2);
2421             // Record top NRC range checks
2422             prev_checks[nb_checks % NRC].ctl = prev_dom->as_IfProj();
2423             prev_checks[nb_checks % NRC].off = offset2;
2424             nb_checks++;
2425           }
2426         }
2427       }
2428       prev_dom = dom;
2429       dom = up_one_dom(dom);
2430       if (!dom) break;
2431     }
2432 
2433     if (!found_immediate_dominator) {
2434       // Attempt to widen the dominating range check to cover some later
2435       // ones.  Since range checks "fail" by uncommon-trapping to the
2436       // interpreter, widening a check can make us speculatively enter
2437       // the interpreter.  If we see range-check deopt's, do not widen!
2438       if (!phase->C->allow_range_check_smearing())  return nullptr;
2439 
2440       if (can_reshape && !phase->C->post_loop_opts_phase()) {
2441         // We are about to perform range check smearing (i.e. remove this RangeCheck if it is dominated by
2442         // a series of RangeChecks which have a range that covers this RangeCheck). This can cause array access nodes to
2443         // be pinned. We want to avoid that and first allow range check elimination a chance to remove the RangeChecks
2444         // from loops. Hence, we delay range check smearing until after loop opts.
2445         phase->C->record_for_post_loop_opts_igvn(this);
2446         return nullptr;
2447       }
2448 
2449       // Didn't find prior covering check, so cannot remove anything.
2450       if (nb_checks == 0) {
2451         return nullptr;
2452       }
2453       // Constant indices only need to check the upper bound.
2454       // Non-constant indices must check both low and high.
2455       int chk0 = (nb_checks - 1) % NRC;
2456       if (index1) {
2457         if (nb_checks == 1) {
2458           return nullptr;
2459         } else {
2460           // If the top range check's constant is the min or max of
2461           // all constants we widen the next one to cover the whole
2462           // range of constants.
2463           RangeCheck rc0 = prev_checks[chk0];
2464           int chk1 = (nb_checks - 2) % NRC;
2465           RangeCheck rc1 = prev_checks[chk1];
2466           if (rc0.off == off_lo) {
2467             adjust_check(rc1.ctl, range1, index1, flip1, off_hi, igvn);
2468             prev_dom = rc1.ctl;
2469           } else if (rc0.off == off_hi) {
2470             adjust_check(rc1.ctl, range1, index1, flip1, off_lo, igvn);
2471             prev_dom = rc1.ctl;
2472           } else {
2473             // If the top test's constant is not the min or max of all
2474             // constants, we need 3 range checks. We must leave the
2475             // top test unchanged because widening it would allow the
2476             // accesses it protects to successfully read/write out of
2477             // bounds.
2478             if (nb_checks == 2) {
2479               return nullptr;
2480             }
2481             int chk2 = (nb_checks - 3) % NRC;
2482             RangeCheck rc2 = prev_checks[chk2];
2483             // The top range check a+i covers interval: -a <= i < length-a
2484             // The second range check b+i covers interval: -b <= i < length-b
2485             if (rc1.off <= rc0.off) {
2486               // if b <= a, we change the second range check to:
2487               // -min_of_all_constants <= i < length-min_of_all_constants
2488               // Together top and second range checks now cover:
2489               // -min_of_all_constants <= i < length-a
2490               // which is more restrictive than -b <= i < length-b:
2491               // -b <= -min_of_all_constants <= i < length-a <= length-b
2492               // The third check is then changed to:
2493               // -max_of_all_constants <= i < length-max_of_all_constants
2494               // so 2nd and 3rd checks restrict allowed values of i to:
2495               // -min_of_all_constants <= i < length-max_of_all_constants
2496               adjust_check(rc1.ctl, range1, index1, flip1, off_lo, igvn);
2497               adjust_check(rc2.ctl, range1, index1, flip1, off_hi, igvn);
2498             } else {
2499               // if b > a, we change the second range check to:
2500               // -max_of_all_constants <= i < length-max_of_all_constants
2501               // Together top and second range checks now cover:
2502               // -a <= i < length-max_of_all_constants
2503               // which is more restrictive than -b <= i < length-b:
2504               // -b < -a <= i < length-max_of_all_constants <= length-b
2505               // The third check is then changed to:
2506               // -max_of_all_constants <= i < length-max_of_all_constants
2507               // so 2nd and 3rd checks restrict allowed values of i to:
2508               // -min_of_all_constants <= i < length-max_of_all_constants
2509               adjust_check(rc1.ctl, range1, index1, flip1, off_hi, igvn);
2510               adjust_check(rc2.ctl, range1, index1, flip1, off_lo, igvn);
2511             }
2512             prev_dom = rc2.ctl;
2513           }
2514         }
2515       } else {
2516         RangeCheck rc0 = prev_checks[chk0];
2517         // 'Widen' the offset of the 1st and only covering check
2518         adjust_check(rc0.ctl, range1, index1, flip1, off_hi, igvn);
2519         // Test is now covered by prior checks, dominate it out
2520         prev_dom = rc0.ctl;
2521       }
2522       // The last RangeCheck is found to be redundant with a sequence of n (n >= 2) preceding RangeChecks.
2523       // If an array load is control dependent on the eliminated range check, the array load nodes (CastII and Load)
2524       // become control dependent on the last range check of the sequence, but they are really dependent on the entire
2525       // sequence of RangeChecks. If RangeCheck#n is later replaced by a dominating identical check, the array load
2526       // nodes must not float above the n-1 other RangeCheck in the sequence. We pin the array load nodes here to
2527       // guarantee it doesn't happen.
2528       //
2529       // RangeCheck#1                 RangeCheck#1
2530       //    |      \                     |      \
2531       //    |      uncommon trap         |      uncommon trap
2532       //    ..                           ..
2533       // RangeCheck#n              -> RangeCheck#n
2534       //    |      \                     |      \
2535       //    |      uncommon trap        CastII  uncommon trap
2536       // RangeCheck                     Load
2537       //    |      \
2538       //   CastII  uncommon trap
2539       //   Load
2540 
2541       return dominated_by(prev_dom, igvn, true);
2542     }
2543   } else {
2544     prev_dom = search_identical(4, igvn);
2545 
2546     if (prev_dom == nullptr) {
2547       return nullptr;
2548     }
2549   }
2550 
2551   // Replace dominated IfNode
2552   return dominated_by(prev_dom, igvn, false);
2553 }
2554 
2555 ParsePredicateNode::ParsePredicateNode(Node* control, Deoptimization::DeoptReason deopt_reason, PhaseGVN* gvn)
2556     : IfNode(control, gvn->intcon(1), PROB_MAX, COUNT_UNKNOWN),
2557       _deopt_reason(deopt_reason),
2558       _predicate_state(PredicateState::Useful) {
2559   init_class_id(Class_ParsePredicate);
2560   gvn->C->add_parse_predicate(this);
2561   gvn->C->record_for_post_loop_opts_igvn(this);
2562 #ifdef ASSERT
2563   switch (deopt_reason) {
2564     case Deoptimization::Reason_predicate:
2565     case Deoptimization::Reason_profile_predicate:
2566     case Deoptimization::Reason_auto_vectorization_check:
2567     case Deoptimization::Reason_loop_limit_check:
2568     case Deoptimization::Reason_short_running_long_loop:
2569       break;
2570     default:
2571       assert(false, "unsupported deoptimization reason for Parse Predicate");
2572   }
2573 #endif // ASSERT
2574 }
2575 
2576 void ParsePredicateNode::mark_useless(PhaseIterGVN& igvn) {
2577   _predicate_state = PredicateState::Useless;
2578   igvn._worklist.push(this);
2579 }
2580 
2581 Node* ParsePredicateNode::uncommon_trap() const {
2582   ParsePredicateUncommonProj* uncommon_proj = false_proj();
2583   Node* uct_region_or_call = uncommon_proj->unique_ctrl_out();
2584   assert(uct_region_or_call->is_Region() || uct_region_or_call->is_Call(), "must be a region or call uct");
2585   return uct_region_or_call;
2586 }
2587 
2588 // Fold this node away once it becomes useless or at latest in post loop opts IGVN.
2589 const Type* ParsePredicateNode::Value(PhaseGVN* phase) const {
2590   assert(_predicate_state != PredicateState::MaybeUseful, "should only be MaybeUseful when eliminating useless "
2591                                                           "predicates during loop opts");
2592   if (phase->type(in(0)) == Type::TOP) {
2593     return Type::TOP;
2594   }
2595   if (_predicate_state == PredicateState::Useless || phase->C->post_loop_opts_phase()) {
2596     return TypeTuple::IFTRUE;
2597   }
2598   return bottom_type();
2599 }
2600 
2601 #ifndef PRODUCT
2602 void ParsePredicateNode::dump_spec(outputStream* st) const {
2603   st->print(" #");
2604   switch (_deopt_reason) {
2605     case Deoptimization::DeoptReason::Reason_predicate:
2606       st->print("Loop ");
2607       break;
2608     case Deoptimization::DeoptReason::Reason_profile_predicate:
2609       st->print("Profiled_Loop ");
2610       break;
2611     case Deoptimization::DeoptReason::Reason_auto_vectorization_check:
2612       st->print("Auto_Vectorization_Check ");
2613       break;
2614     case Deoptimization::DeoptReason::Reason_loop_limit_check:
2615       st->print("Loop_Limit_Check ");
2616       break;
2617     case Deoptimization::DeoptReason::Reason_short_running_long_loop:
2618       st->print("Short_Running_Long_Loop ");
2619       break;
2620     default:
2621       fatal("unknown kind");
2622   }
2623   if (_predicate_state == PredicateState::Useless) {
2624     st->print("#useless ");
2625   }
2626 }
2627 #endif // NOT PRODUCT