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