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 // Returns true if this IfNode belongs to a flat array check
1240 // and returns the corresponding array in the 'array' parameter.
1241 bool IfNode::is_flat_array_check(PhaseTransform* phase, Node** array) {
1242   Node* bol = in(1);
1243   if (!bol->is_Bool()) {
1244     return false;
1245   }
1246   Node* cmp = bol->in(1);
1247   if (cmp->isa_FlatArrayCheck()) {
1248     if (array != nullptr) {
1249       *array = cmp->in(FlatArrayCheckNode::ArrayOrKlass);
1250     }
1251     return true;
1252   }
1253   return false;
1254 }
1255 
1256 // Check that the If that is in between the 2 integer comparisons has
1257 // no side effect
1258 bool IfNode::is_side_effect_free_test(ProjNode* proj, PhaseIterGVN* igvn) {
1259   if (proj == nullptr) {
1260     return false;
1261   }
1262   CallStaticJavaNode* unc = proj->is_uncommon_trap_if_pattern();
1263   if (unc != nullptr && proj->outcnt() <= 2) {
1264     if (proj->outcnt() == 1 ||
1265         // Allow simple null check from LoadRange
1266         (is_cmp_with_loadrange(proj) && is_null_check(proj, igvn))) {
1267       CallStaticJavaNode* unc = proj->is_uncommon_trap_if_pattern();
1268       CallStaticJavaNode* dom_unc = proj->in(0)->in(0)->as_Proj()->is_uncommon_trap_if_pattern();
1269       assert(dom_unc != nullptr, "is_uncommon_trap_if_pattern returned null");
1270 
1271       // reroute_side_effect_free_unc changes the state of this
1272       // uncommon trap to restart execution at the previous
1273       // CmpI. Check that this change in a previous compilation didn't
1274       // cause too many traps.
1275       int trap_request = unc->uncommon_trap_request();
1276       Deoptimization::DeoptReason reason = Deoptimization::trap_request_reason(trap_request);
1277 
1278       if (igvn->C->too_many_traps(dom_unc->jvms()->method(), dom_unc->jvms()->bci(), reason)) {
1279         return false;
1280       }
1281 
1282       if (!is_dominator_unc(dom_unc, unc)) {
1283         return false;
1284       }
1285 
1286       return true;
1287     }
1288   }
1289   return false;
1290 }
1291 
1292 // Make the If between the 2 integer comparisons trap at the state of
1293 // the first If: the last CmpI is the one replaced by a CmpU and the
1294 // first CmpI is eliminated, so the test between the 2 CmpI nodes
1295 // won't be guarded by the first CmpI anymore. It can trap in cases
1296 // where the first CmpI would have prevented it from executing: on a
1297 // trap, we need to restart execution at the state of the first CmpI
1298 void IfNode::reroute_side_effect_free_unc(ProjNode* proj, ProjNode* dom_proj, PhaseIterGVN* igvn) {
1299   CallStaticJavaNode* dom_unc = dom_proj->is_uncommon_trap_if_pattern();
1300   ProjNode* otherproj = proj->other_if_proj();
1301   CallStaticJavaNode* unc = proj->is_uncommon_trap_if_pattern();
1302   Node* call_proj = dom_unc->unique_ctrl_out();
1303   Node* halt = call_proj->unique_ctrl_out();
1304 
1305   Node* new_unc = dom_unc->clone();
1306   call_proj = call_proj->clone();
1307   halt = halt->clone();
1308   Node* c = otherproj->clone();
1309 
1310   c = igvn->transform(c);
1311   new_unc->set_req(TypeFunc::Parms, unc->in(TypeFunc::Parms));
1312   new_unc->set_req(0, c);
1313   new_unc = igvn->transform(new_unc);
1314   call_proj->set_req(0, new_unc);
1315   call_proj = igvn->transform(call_proj);
1316   halt->set_req(0, call_proj);
1317   halt = igvn->transform(halt);
1318 
1319   igvn->replace_node(otherproj, igvn->C->top());
1320   igvn->C->root()->add_req(halt);
1321 }
1322 
1323 Node* IfNode::fold_compares(PhaseIterGVN* igvn) {
1324   if (Opcode() != Op_If) return nullptr;
1325 
1326   if (cmpi_folds(igvn)) {
1327     Node* ctrl = in(0);
1328     if (is_ctrl_folds(ctrl, igvn) && ctrl->outcnt() == 1) {
1329       // A integer comparison immediately dominated by another integer
1330       // comparison
1331       ProjNode* success = nullptr;
1332       ProjNode* fail = nullptr;
1333       ProjNode* dom_cmp = ctrl->as_Proj();
1334       if (has_shared_region(dom_cmp, success, fail) &&
1335           // Next call modifies graph so must be last
1336           fold_compares_helper(dom_cmp, success, fail, igvn)) {
1337         return this;
1338       }
1339       if (has_only_uncommon_traps(dom_cmp, success, fail, igvn) &&
1340           // Next call modifies graph so must be last
1341           fold_compares_helper(dom_cmp, success, fail, igvn)) {
1342         return merge_uncommon_traps(dom_cmp, success, fail, igvn);
1343       }
1344       return nullptr;
1345     } else if (ctrl->in(0) != nullptr &&
1346                ctrl->in(0)->in(0) != nullptr) {
1347       ProjNode* success = nullptr;
1348       ProjNode* fail = nullptr;
1349       Node* dom = ctrl->in(0)->in(0);
1350       ProjNode* dom_cmp = dom->isa_Proj();
1351       ProjNode* other_cmp = ctrl->isa_Proj();
1352 
1353       // Check if it's an integer comparison dominated by another
1354       // integer comparison with another test in between
1355       if (is_ctrl_folds(dom, igvn) &&
1356           has_only_uncommon_traps(dom_cmp, success, fail, igvn) &&
1357           is_side_effect_free_test(other_cmp, igvn) &&
1358           // Next call modifies graph so must be last
1359           fold_compares_helper(dom_cmp, success, fail, igvn)) {
1360         reroute_side_effect_free_unc(other_cmp, dom_cmp, igvn);
1361         return merge_uncommon_traps(dom_cmp, success, fail, igvn);
1362       }
1363     }
1364   }
1365   return nullptr;
1366 }
1367 
1368 //------------------------------remove_useless_bool----------------------------
1369 // Check for people making a useless boolean: things like
1370 // if( (x < y ? true : false) ) { ... }
1371 // Replace with if( x < y ) { ... }
1372 static Node *remove_useless_bool(IfNode *iff, PhaseGVN *phase) {
1373   Node *i1 = iff->in(1);
1374   if( !i1->is_Bool() ) return nullptr;
1375   BoolNode *bol = i1->as_Bool();
1376 
1377   Node *cmp = bol->in(1);
1378   if( cmp->Opcode() != Op_CmpI ) return nullptr;
1379 
1380   // Must be comparing against a bool
1381   const Type *cmp2_t = phase->type( cmp->in(2) );
1382   if( cmp2_t != TypeInt::ZERO &&
1383       cmp2_t != TypeInt::ONE )
1384     return nullptr;
1385 
1386   // Find a prior merge point merging the boolean
1387   i1 = cmp->in(1);
1388   if( !i1->is_Phi() ) return nullptr;
1389   PhiNode *phi = i1->as_Phi();
1390   if( phase->type( phi ) != TypeInt::BOOL )
1391     return nullptr;
1392 
1393   // Check for diamond pattern
1394   int true_path = phi->is_diamond_phi();
1395   if( true_path == 0 ) return nullptr;
1396 
1397   // Make sure that iff and the control of the phi are different. This
1398   // should really only happen for dead control flow since it requires
1399   // an illegal cycle.
1400   if (phi->in(0)->in(1)->in(0) == iff) return nullptr;
1401 
1402   // phi->region->if_proj->ifnode->bool->cmp
1403   BoolNode *bol2 = phi->in(0)->in(1)->in(0)->in(1)->as_Bool();
1404 
1405   // Now get the 'sense' of the test correct so we can plug in
1406   // either iff2->in(1) or its complement.
1407   int flip = 0;
1408   if( bol->_test._test == BoolTest::ne ) flip = 1-flip;
1409   else if( bol->_test._test != BoolTest::eq ) return nullptr;
1410   if( cmp2_t == TypeInt::ZERO ) flip = 1-flip;
1411 
1412   const Type *phi1_t = phase->type( phi->in(1) );
1413   const Type *phi2_t = phase->type( phi->in(2) );
1414   // Check for Phi(0,1) and flip
1415   if( phi1_t == TypeInt::ZERO ) {
1416     if( phi2_t != TypeInt::ONE ) return nullptr;
1417     flip = 1-flip;
1418   } else {
1419     // Check for Phi(1,0)
1420     if( phi1_t != TypeInt::ONE  ) return nullptr;
1421     if( phi2_t != TypeInt::ZERO ) return nullptr;
1422   }
1423   if( true_path == 2 ) {
1424     flip = 1-flip;
1425   }
1426 
1427   Node* new_bol = (flip ? phase->transform( bol2->negate(phase) ) : bol2);
1428   assert(new_bol != iff->in(1), "must make progress");
1429   iff->set_req_X(1, new_bol, phase);
1430   // Intervening diamond probably goes dead
1431   phase->C->set_major_progress();
1432   return iff;
1433 }
1434 
1435 static IfNode* idealize_test(PhaseGVN* phase, IfNode* iff);
1436 
1437 struct RangeCheck {
1438   Node* ctl;
1439   jint off;
1440 };
1441 
1442 Node* IfNode::Ideal_common(PhaseGVN *phase, bool can_reshape) {
1443   if (remove_dead_region(phase, can_reshape))  return this;
1444   // No Def-Use info?
1445   if (!can_reshape)  return nullptr;
1446 
1447   // Don't bother trying to transform a dead if
1448   if (in(0)->is_top())  return nullptr;
1449   // Don't bother trying to transform an if with a dead test
1450   if (in(1)->is_top())  return nullptr;
1451   // Another variation of a dead test
1452   if (in(1)->is_Con())  return nullptr;
1453   // Another variation of a dead if
1454   if (outcnt() < 2)  return nullptr;
1455 
1456   // Canonicalize the test.
1457   Node* idt_if = idealize_test(phase, this);
1458   if (idt_if != nullptr)  return idt_if;
1459 
1460   // Try to split the IF
1461   PhaseIterGVN *igvn = phase->is_IterGVN();
1462   Node *s = split_if(this, igvn);
1463   if (s != nullptr)  return s;
1464 
1465   return NodeSentinel;
1466 }
1467 
1468 //------------------------------Ideal------------------------------------------
1469 // Return a node which is more "ideal" than the current node.  Strip out
1470 // control copies
1471 Node* IfNode::Ideal(PhaseGVN *phase, bool can_reshape) {
1472   Node* res = Ideal_common(phase, can_reshape);
1473   if (res != NodeSentinel) {
1474     return res;
1475   }
1476 
1477   // Check for people making a useless boolean: things like
1478   // if( (x < y ? true : false) ) { ... }
1479   // Replace with if( x < y ) { ... }
1480   Node* bol2 = remove_useless_bool(this, phase);
1481   if (bol2) return bol2;
1482 
1483   if (in(0) == nullptr) return nullptr;     // Dead loop?
1484 
1485   PhaseIterGVN* igvn = phase->is_IterGVN();
1486   Node* result = fold_compares(igvn);
1487   if (result != nullptr) {
1488     return result;
1489   }
1490 
1491   // Scan for an equivalent test
1492   int dist = 4;               // Cutoff limit for search
1493   if (is_If() && in(1)->is_Bool()) {
1494     Node* cmp = in(1)->in(1);
1495     if (cmp->Opcode() == Op_CmpP &&
1496         cmp->in(2) != nullptr && // make sure cmp is not already dead
1497         cmp->in(2)->bottom_type() == TypePtr::NULL_PTR) {
1498       dist = 64;              // Limit for null-pointer scans
1499     }
1500   }
1501 
1502   Node* prev_dom = search_identical(dist, igvn);
1503 
1504   if (prev_dom != nullptr) {
1505     // Replace dominated IfNode
1506     return dominated_by(prev_dom, igvn);
1507   }
1508 
1509   return simple_subsuming(igvn);
1510 }
1511 
1512 //------------------------------dominated_by-----------------------------------
1513 Node* IfNode::dominated_by(Node* prev_dom, PhaseIterGVN *igvn) {
1514 #ifndef PRODUCT
1515   if (TraceIterativeGVN) {
1516     tty->print("   Removing IfNode: "); this->dump();
1517   }
1518 #endif
1519 
1520   igvn->hash_delete(this);      // Remove self to prevent spurious V-N
1521   Node *idom = in(0);
1522   // Need opcode to decide which way 'this' test goes
1523   int prev_op = prev_dom->Opcode();
1524   Node *top = igvn->C->top(); // Shortcut to top
1525 
1526   // Loop predicates may have depending checks which should not
1527   // be skipped. For example, range check predicate has two checks
1528   // for lower and upper bounds.
1529   ProjNode* unc_proj = proj_out(1 - prev_dom->as_Proj()->_con)->as_Proj();
1530   if (unc_proj->is_uncommon_trap_proj(Deoptimization::Reason_predicate) != nullptr ||
1531       unc_proj->is_uncommon_trap_proj(Deoptimization::Reason_profile_predicate) != nullptr) {
1532     prev_dom = idom;
1533   }
1534 
1535   // Now walk the current IfNode's projections.
1536   // Loop ends when 'this' has no more uses.
1537   for (DUIterator_Last imin, i = last_outs(imin); i >= imin; --i) {
1538     Node *ifp = last_out(i);     // Get IfTrue/IfFalse
1539     igvn->add_users_to_worklist(ifp);
1540     // Check which projection it is and set target.
1541     // Data-target is either the dominating projection of the same type
1542     // or TOP if the dominating projection is of opposite type.
1543     // Data-target will be used as the new control edge for the non-CFG
1544     // nodes like Casts and Loads.
1545     Node *data_target = (ifp->Opcode() == prev_op) ? prev_dom : top;
1546     // Control-target is just the If's immediate dominator or TOP.
1547     Node *ctrl_target = (ifp->Opcode() == prev_op) ?     idom : top;
1548 
1549     // For each child of an IfTrue/IfFalse projection, reroute.
1550     // Loop ends when projection has no more uses.
1551     for (DUIterator_Last jmin, j = ifp->last_outs(jmin); j >= jmin; --j) {
1552       Node* s = ifp->last_out(j);   // Get child of IfTrue/IfFalse
1553       if (s->depends_only_on_test() && igvn->no_dependent_zero_check(s)) {
1554         // For control producers.
1555         // Do not rewire Div and Mod nodes which could have a zero divisor to avoid skipping their zero check.
1556         igvn->replace_input_of(s, 0, data_target); // Move child to data-target
1557       } else {
1558         // Find the control input matching this def-use edge.
1559         // For Regions it may not be in slot 0.
1560         uint l;
1561         for (l = 0; s->in(l) != ifp; l++) { }
1562         igvn->replace_input_of(s, l, ctrl_target);
1563       }
1564     } // End for each child of a projection
1565 
1566     igvn->remove_dead_node(ifp);
1567   } // End for each IfTrue/IfFalse child of If
1568 
1569   // Kill the IfNode
1570   igvn->remove_dead_node(this);
1571 
1572   // Must return either the original node (now dead) or a new node
1573   // (Do not return a top here, since that would break the uniqueness of top.)
1574   return new ConINode(TypeInt::ZERO);
1575 }
1576 
1577 Node* IfNode::search_identical(int dist, PhaseIterGVN* igvn) {
1578   // Setup to scan up the CFG looking for a dominating test
1579   Node* dom = in(0);
1580   Node* prev_dom = this;
1581   int op = Opcode();
1582   // Search up the dominator tree for an If with an identical test
1583   while (dom->Opcode() != op ||  // Not same opcode?
1584          !same_condition(dom, igvn) ||  // Not same input 1?
1585          prev_dom->in(0) != dom) {  // One path of test does not dominate?
1586     if (dist < 0) return nullptr;
1587 
1588     dist--;
1589     prev_dom = dom;
1590     dom = up_one_dom(dom);
1591     if (!dom) return nullptr;
1592   }
1593 
1594   // Check that we did not follow a loop back to ourselves
1595   if (this == dom) {
1596     return nullptr;
1597   }
1598 
1599 #ifndef PRODUCT
1600   if (dist > 2) { // Add to count of null checks elided
1601     explicit_null_checks_elided++;
1602   }
1603 #endif
1604 
1605   return prev_dom;
1606 }
1607 
1608 bool IfNode::same_condition(const Node* dom, PhaseIterGVN* igvn) const {
1609   Node* dom_bool = dom->in(1);
1610   Node* this_bool = in(1);
1611   if (dom_bool == this_bool) {
1612     return true;
1613   }
1614 
1615   if (dom_bool == nullptr || !dom_bool->is_Bool() ||
1616       this_bool == nullptr || !this_bool->is_Bool()) {
1617     return false;
1618   }
1619   Node* dom_cmp = dom_bool->in(1);
1620   Node* this_cmp = this_bool->in(1);
1621 
1622   // If the comparison is a subtype check, then SubTypeCheck nodes may have profile data attached to them and may be
1623   // different nodes even-though they perform the same subtype check
1624   if (dom_cmp == nullptr || !dom_cmp->is_SubTypeCheck() ||
1625       this_cmp == nullptr || !this_cmp->is_SubTypeCheck()) {
1626     return false;
1627   }
1628 
1629   if (dom_cmp->in(1) != this_cmp->in(1) ||
1630       dom_cmp->in(2) != this_cmp->in(2) ||
1631       dom_bool->as_Bool()->_test._test != this_bool->as_Bool()->_test._test) {
1632     return false;
1633   }
1634 
1635   return true;
1636 }
1637 
1638 
1639 static int subsuming_bool_test_encode(Node*);
1640 
1641 // Check if dominating test is subsuming 'this' one.
1642 //
1643 //              cmp
1644 //              / \
1645 //     (r1)  bool  \
1646 //            /    bool (r2)
1647 //    (dom) if       \
1648 //            \       )
1649 //    (pre)  if[TF]  /
1650 //               \  /
1651 //                if (this)
1652 //   \r1
1653 //  r2\  eqT  eqF  neT  neF  ltT  ltF  leT  leF  gtT  gtF  geT  geF
1654 //  eq    t    f    f    t    f    -    -    f    f    -    -    f
1655 //  ne    f    t    t    f    t    -    -    t    t    -    -    t
1656 //  lt    f    -    -    f    t    f    -    f    f    -    f    t
1657 //  le    t    -    -    t    t    -    t    f    f    t    -    t
1658 //  gt    f    -    -    f    f    -    f    t    t    f    -    f
1659 //  ge    t    -    -    t    f    t    -    t    t    -    t    f
1660 //
1661 Node* IfNode::simple_subsuming(PhaseIterGVN* igvn) {
1662   // Table encoding: N/A (na), True-branch (tb), False-branch (fb).
1663   static enum { na, tb, fb } s_short_circuit_map[6][12] = {
1664   /*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*/
1665   /*eq*/{ tb,  fb,  fb,  tb,  fb,  na,  na,  fb,  fb,  na,  na,  fb },
1666   /*ne*/{ fb,  tb,  tb,  fb,  tb,  na,  na,  tb,  tb,  na,  na,  tb },
1667   /*lt*/{ fb,  na,  na,  fb,  tb,  fb,  na,  fb,  fb,  na,  fb,  tb },
1668   /*le*/{ tb,  na,  na,  tb,  tb,  na,  tb,  fb,  fb,  tb,  na,  tb },
1669   /*gt*/{ fb,  na,  na,  fb,  fb,  na,  fb,  tb,  tb,  fb,  na,  fb },
1670   /*ge*/{ tb,  na,  na,  tb,  fb,  tb,  na,  tb,  tb,  na,  tb,  fb }};
1671 
1672   Node* pre = in(0);
1673   if (!pre->is_IfTrue() && !pre->is_IfFalse()) {
1674     return nullptr;
1675   }
1676   Node* dom = pre->in(0);
1677   if (!dom->is_If()) {
1678     return nullptr;
1679   }
1680   Node* bol = in(1);
1681   if (!bol->is_Bool()) {
1682     return nullptr;
1683   }
1684   Node* cmp = in(1)->in(1);
1685   if (!cmp->is_Cmp()) {
1686     return nullptr;
1687   }
1688 
1689   if (!dom->in(1)->is_Bool()) {
1690     return nullptr;
1691   }
1692   if (dom->in(1)->in(1) != cmp) {  // Not same cond?
1693     return nullptr;
1694   }
1695 
1696   int drel = subsuming_bool_test_encode(dom->in(1));
1697   int trel = subsuming_bool_test_encode(bol);
1698   int bout = pre->is_IfFalse() ? 1 : 0;
1699 
1700   if (drel < 0 || trel < 0) {
1701     return nullptr;
1702   }
1703   int br = s_short_circuit_map[trel][2*drel+bout];
1704   if (br == na) {
1705     return nullptr;
1706   }
1707 #ifndef PRODUCT
1708   if (TraceIterativeGVN) {
1709     tty->print("   Subsumed IfNode: "); dump();
1710   }
1711 #endif
1712   // Replace condition with constant True(1)/False(0).
1713   bool is_always_true = br == tb;
1714   set_req(1, igvn->intcon(is_always_true ? 1 : 0));
1715 
1716   // Update any data dependencies to the directly dominating test. This subsumed test is not immediately removed by igvn
1717   // and therefore subsequent optimizations might miss these data dependencies otherwise. There might be a dead loop
1718   // ('always_taken_proj' == 'pre') that is cleaned up later. Skip this case to make the iterator work properly.
1719   Node* always_taken_proj = proj_out(is_always_true);
1720   if (always_taken_proj != pre) {
1721     for (DUIterator_Fast imax, i = always_taken_proj->fast_outs(imax); i < imax; i++) {
1722       Node* u = always_taken_proj->fast_out(i);
1723       if (!u->is_CFG()) {
1724         igvn->replace_input_of(u, 0, pre);
1725         --i;
1726         --imax;
1727       }
1728     }
1729   }
1730 
1731   if (bol->outcnt() == 0) {
1732     igvn->remove_dead_node(bol);    // Kill the BoolNode.
1733   }
1734   return this;
1735 }
1736 
1737 // Map BoolTest to local table encoding. The BoolTest (e)numerals
1738 //   { eq = 0, ne = 4, le = 5, ge = 7, lt = 3, gt = 1 }
1739 // are mapped to table indices, while the remaining (e)numerals in BoolTest
1740 //   { overflow = 2, no_overflow = 6, never = 8, illegal = 9 }
1741 // are ignored (these are not modeled in the table).
1742 //
1743 static int subsuming_bool_test_encode(Node* node) {
1744   precond(node->is_Bool());
1745   BoolTest::mask x = node->as_Bool()->_test._test;
1746   switch (x) {
1747     case BoolTest::eq: return 0;
1748     case BoolTest::ne: return 1;
1749     case BoolTest::lt: return 2;
1750     case BoolTest::le: return 3;
1751     case BoolTest::gt: return 4;
1752     case BoolTest::ge: return 5;
1753     case BoolTest::overflow:
1754     case BoolTest::no_overflow:
1755     case BoolTest::never:
1756     case BoolTest::illegal:
1757     default:
1758       return -1;
1759   }
1760 }
1761 
1762 //------------------------------Identity---------------------------------------
1763 // If the test is constant & we match, then we are the input Control
1764 Node* IfProjNode::Identity(PhaseGVN* phase) {
1765   // Can only optimize if cannot go the other way
1766   const TypeTuple *t = phase->type(in(0))->is_tuple();
1767   if (t == TypeTuple::IFNEITHER || (always_taken(t) &&
1768        // During parsing (GVN) we don't remove dead code aggressively.
1769        // Cut off dead branch and let PhaseRemoveUseless take care of it.
1770       (!phase->is_IterGVN() ||
1771        // During IGVN, first wait for the dead branch to be killed.
1772        // Otherwise, the IfNode's control will have two control uses (the IfNode
1773        // that doesn't go away because it still has uses and this branch of the
1774        // If) which breaks other optimizations. Node::has_special_unique_user()
1775        // will cause this node to be reprocessed once the dead branch is killed.
1776        in(0)->outcnt() == 1))) {
1777     // IfNode control
1778     if (in(0)->is_BaseCountedLoopEnd()) {
1779       // CountedLoopEndNode may be eliminated by if subsuming, replace CountedLoopNode with LoopNode to
1780       // avoid mismatching between CountedLoopNode and CountedLoopEndNode in the following optimization.
1781       Node* head = unique_ctrl_out_or_null();
1782       if (head != nullptr && head->is_BaseCountedLoop() && head->in(LoopNode::LoopBackControl) == this) {
1783         Node* new_head = new LoopNode(head->in(LoopNode::EntryControl), this);
1784         phase->is_IterGVN()->register_new_node_with_optimizer(new_head);
1785         phase->is_IterGVN()->replace_node(head, new_head);
1786       }
1787     }
1788     return in(0)->in(0);
1789   }
1790   // no progress
1791   return this;
1792 }
1793 
1794 bool IfNode::is_zero_trip_guard() const {
1795   if (in(1)->is_Bool() && in(1)->in(1)->is_Cmp()) {
1796     return in(1)->in(1)->in(1)->Opcode() == Op_OpaqueZeroTripGuard;
1797   }
1798   return false;
1799 }
1800 
1801 #ifndef PRODUCT
1802 //------------------------------dump_spec--------------------------------------
1803 void IfNode::dump_spec(outputStream *st) const {
1804   st->print("P=%f, C=%f",_prob,_fcnt);
1805 }
1806 #endif
1807 
1808 //------------------------------idealize_test----------------------------------
1809 // Try to canonicalize tests better.  Peek at the Cmp/Bool/If sequence and
1810 // come up with a canonical sequence.  Bools getting 'eq', 'gt' and 'ge' forms
1811 // converted to 'ne', 'le' and 'lt' forms.  IfTrue/IfFalse get swapped as
1812 // needed.
1813 static IfNode* idealize_test(PhaseGVN* phase, IfNode* iff) {
1814   assert(iff->in(0) != nullptr, "If must be live");
1815 
1816   if (iff->outcnt() != 2)  return nullptr; // Malformed projections.
1817   Node* old_if_f = iff->proj_out(false);
1818   Node* old_if_t = iff->proj_out(true);
1819 
1820   // CountedLoopEnds want the back-control test to be TRUE, regardless of
1821   // whether they are testing a 'gt' or 'lt' condition.  The 'gt' condition
1822   // happens in count-down loops
1823   if (iff->is_BaseCountedLoopEnd())  return nullptr;
1824   if (!iff->in(1)->is_Bool())  return nullptr; // Happens for partially optimized IF tests
1825   BoolNode *b = iff->in(1)->as_Bool();
1826   BoolTest bt = b->_test;
1827   // Test already in good order?
1828   if( bt.is_canonical() )
1829     return nullptr;
1830 
1831   // Flip test to be canonical.  Requires flipping the IfFalse/IfTrue and
1832   // cloning the IfNode.
1833   Node* new_b = phase->transform( new BoolNode(b->in(1), bt.negate()) );
1834   if( !new_b->is_Bool() ) return nullptr;
1835   b = new_b->as_Bool();
1836 
1837   PhaseIterGVN *igvn = phase->is_IterGVN();
1838   assert( igvn, "Test is not canonical in parser?" );
1839 
1840   // The IF node never really changes, but it needs to be cloned
1841   iff = iff->clone()->as_If();
1842   iff->set_req(1, b);
1843   iff->_prob = 1.0-iff->_prob;
1844 
1845   Node *prior = igvn->hash_find_insert(iff);
1846   if( prior ) {
1847     igvn->remove_dead_node(iff);
1848     iff = (IfNode*)prior;
1849   } else {
1850     // Cannot call transform on it just yet
1851     igvn->set_type_bottom(iff);
1852   }
1853   igvn->_worklist.push(iff);
1854 
1855   // Now handle projections.  Cloning not required.
1856   Node* new_if_f = (Node*)(new IfFalseNode( iff ));
1857   Node* new_if_t = (Node*)(new IfTrueNode ( iff ));
1858 
1859   igvn->register_new_node_with_optimizer(new_if_f);
1860   igvn->register_new_node_with_optimizer(new_if_t);
1861   // Flip test, so flip trailing control
1862   igvn->replace_node(old_if_f, new_if_t);
1863   igvn->replace_node(old_if_t, new_if_f);
1864 
1865   // Progress
1866   return iff;
1867 }
1868 
1869 Node* RangeCheckNode::Ideal(PhaseGVN *phase, bool can_reshape) {
1870   Node* res = Ideal_common(phase, can_reshape);
1871   if (res != NodeSentinel) {
1872     return res;
1873   }
1874 
1875   PhaseIterGVN *igvn = phase->is_IterGVN();
1876   // Setup to scan up the CFG looking for a dominating test
1877   Node* prev_dom = this;
1878 
1879   // Check for range-check vs other kinds of tests
1880   Node* index1;
1881   Node* range1;
1882   jint offset1;
1883   int flip1 = is_range_check(range1, index1, offset1);
1884   if (flip1) {
1885     Node* dom = in(0);
1886     // Try to remove extra range checks.  All 'up_one_dom' gives up at merges
1887     // so all checks we inspect post-dominate the top-most check we find.
1888     // If we are going to fail the current check and we reach the top check
1889     // then we are guaranteed to fail, so just start interpreting there.
1890     // We 'expand' the top 3 range checks to include all post-dominating
1891     // checks.
1892 
1893     // The top 3 range checks seen
1894     const int NRC = 3;
1895     RangeCheck prev_checks[NRC];
1896     int nb_checks = 0;
1897 
1898     // Low and high offsets seen so far
1899     jint off_lo = offset1;
1900     jint off_hi = offset1;
1901 
1902     bool found_immediate_dominator = false;
1903 
1904     // Scan for the top checks and collect range of offsets
1905     for (int dist = 0; dist < 999; dist++) { // Range-Check scan limit
1906       if (dom->Opcode() == Op_RangeCheck &&  // Not same opcode?
1907           prev_dom->in(0) == dom) { // One path of test does dominate?
1908         if (dom == this) return nullptr; // dead loop
1909         // See if this is a range check
1910         Node* index2;
1911         Node* range2;
1912         jint offset2;
1913         int flip2 = dom->as_RangeCheck()->is_range_check(range2, index2, offset2);
1914         // See if this is a _matching_ range check, checking against
1915         // the same array bounds.
1916         if (flip2 == flip1 && range2 == range1 && index2 == index1 &&
1917             dom->outcnt() == 2) {
1918           if (nb_checks == 0 && dom->in(1) == in(1)) {
1919             // Found an immediately dominating test at the same offset.
1920             // This kind of back-to-back test can be eliminated locally,
1921             // and there is no need to search further for dominating tests.
1922             assert(offset2 == offset1, "Same test but different offsets");
1923             found_immediate_dominator = true;
1924             break;
1925           }
1926           // Gather expanded bounds
1927           off_lo = MIN2(off_lo,offset2);
1928           off_hi = MAX2(off_hi,offset2);
1929           // Record top NRC range checks
1930           prev_checks[nb_checks%NRC].ctl = prev_dom;
1931           prev_checks[nb_checks%NRC].off = offset2;
1932           nb_checks++;
1933         }
1934       }
1935       prev_dom = dom;
1936       dom = up_one_dom(dom);
1937       if (!dom) break;
1938     }
1939 
1940     if (!found_immediate_dominator) {
1941       // Attempt to widen the dominating range check to cover some later
1942       // ones.  Since range checks "fail" by uncommon-trapping to the
1943       // interpreter, widening a check can make us speculatively enter
1944       // the interpreter.  If we see range-check deopt's, do not widen!
1945       if (!phase->C->allow_range_check_smearing())  return nullptr;
1946 
1947       // Didn't find prior covering check, so cannot remove anything.
1948       if (nb_checks == 0) {
1949         return nullptr;
1950       }
1951       // Constant indices only need to check the upper bound.
1952       // Non-constant indices must check both low and high.
1953       int chk0 = (nb_checks - 1) % NRC;
1954       if (index1) {
1955         if (nb_checks == 1) {
1956           return nullptr;
1957         } else {
1958           // If the top range check's constant is the min or max of
1959           // all constants we widen the next one to cover the whole
1960           // range of constants.
1961           RangeCheck rc0 = prev_checks[chk0];
1962           int chk1 = (nb_checks - 2) % NRC;
1963           RangeCheck rc1 = prev_checks[chk1];
1964           if (rc0.off == off_lo) {
1965             adjust_check(rc1.ctl, range1, index1, flip1, off_hi, igvn);
1966             prev_dom = rc1.ctl;
1967           } else if (rc0.off == off_hi) {
1968             adjust_check(rc1.ctl, range1, index1, flip1, off_lo, igvn);
1969             prev_dom = rc1.ctl;
1970           } else {
1971             // If the top test's constant is not the min or max of all
1972             // constants, we need 3 range checks. We must leave the
1973             // top test unchanged because widening it would allow the
1974             // accesses it protects to successfully read/write out of
1975             // bounds.
1976             if (nb_checks == 2) {
1977               return nullptr;
1978             }
1979             int chk2 = (nb_checks - 3) % NRC;
1980             RangeCheck rc2 = prev_checks[chk2];
1981             // The top range check a+i covers interval: -a <= i < length-a
1982             // The second range check b+i covers interval: -b <= i < length-b
1983             if (rc1.off <= rc0.off) {
1984               // if b <= a, we change the second range check to:
1985               // -min_of_all_constants <= i < length-min_of_all_constants
1986               // Together top and second range checks now cover:
1987               // -min_of_all_constants <= i < length-a
1988               // which is more restrictive than -b <= i < length-b:
1989               // -b <= -min_of_all_constants <= i < length-a <= length-b
1990               // The third check is then changed to:
1991               // -max_of_all_constants <= i < length-max_of_all_constants
1992               // so 2nd and 3rd checks restrict allowed values of i to:
1993               // -min_of_all_constants <= i < length-max_of_all_constants
1994               adjust_check(rc1.ctl, range1, index1, flip1, off_lo, igvn);
1995               adjust_check(rc2.ctl, range1, index1, flip1, off_hi, igvn);
1996             } else {
1997               // if b > a, we change the second range check to:
1998               // -max_of_all_constants <= i < length-max_of_all_constants
1999               // Together top and second range checks now cover:
2000               // -a <= i < length-max_of_all_constants
2001               // which is more restrictive than -b <= i < length-b:
2002               // -b < -a <= i < length-max_of_all_constants <= length-b
2003               // The third check is then changed to:
2004               // -max_of_all_constants <= i < length-max_of_all_constants
2005               // so 2nd and 3rd checks restrict allowed values of i to:
2006               // -min_of_all_constants <= i < length-max_of_all_constants
2007               adjust_check(rc1.ctl, range1, index1, flip1, off_hi, igvn);
2008               adjust_check(rc2.ctl, range1, index1, flip1, off_lo, igvn);
2009             }
2010             prev_dom = rc2.ctl;
2011           }
2012         }
2013       } else {
2014         RangeCheck rc0 = prev_checks[chk0];
2015         // 'Widen' the offset of the 1st and only covering check
2016         adjust_check(rc0.ctl, range1, index1, flip1, off_hi, igvn);
2017         // Test is now covered by prior checks, dominate it out
2018         prev_dom = rc0.ctl;
2019       }
2020     }
2021   } else {
2022     prev_dom = search_identical(4, igvn);
2023 
2024     if (prev_dom == nullptr) {
2025       return nullptr;
2026     }
2027   }
2028 
2029   // Replace dominated IfNode
2030   return dominated_by(prev_dom, igvn);
2031 }
2032 
2033 ParsePredicateNode::ParsePredicateNode(Node* control, Deoptimization::DeoptReason deopt_reason, PhaseGVN* gvn)
2034     : IfNode(control, gvn->intcon(1), PROB_MAX, COUNT_UNKNOWN),
2035       _deopt_reason(deopt_reason),
2036       _useless(false) {
2037   init_class_id(Class_ParsePredicate);
2038   gvn->C->add_parse_predicate(this);
2039   gvn->C->record_for_post_loop_opts_igvn(this);
2040 #ifdef ASSERT
2041   switch (deopt_reason) {
2042     case Deoptimization::Reason_predicate:
2043     case Deoptimization::Reason_profile_predicate:
2044     case Deoptimization::Reason_loop_limit_check:
2045       break;
2046     default:
2047       assert(false, "unsupported deoptimization reason for Parse Predicate");
2048   }
2049 #endif // ASSERT
2050 }
2051 
2052 Node* ParsePredicateNode::uncommon_trap() const {
2053   ParsePredicateUncommonProj* uncommon_proj = proj_out(0)->as_IfFalse();
2054   Node* uct_region_or_call = uncommon_proj->unique_ctrl_out();
2055   assert(uct_region_or_call->is_Region() || uct_region_or_call->is_Call(), "must be a region or call uct");
2056   return uct_region_or_call;
2057 }
2058 
2059 // Fold this node away once it becomes useless or at latest in post loop opts IGVN.
2060 const Type* ParsePredicateNode::Value(PhaseGVN* phase) const {
2061   if (phase->type(in(0)) == Type::TOP) {
2062     return Type::TOP;
2063   }
2064   if (_useless || phase->C->post_loop_opts_phase()) {
2065     return TypeTuple::IFTRUE;
2066   } else {
2067     return bottom_type();
2068   }
2069 }
2070 
2071 #ifndef PRODUCT
2072 void ParsePredicateNode::dump_spec(outputStream* st) const {
2073   st->print(" #");
2074   switch (_deopt_reason) {
2075     case Deoptimization::DeoptReason::Reason_predicate:
2076       st->print("Loop ");
2077       break;
2078     case Deoptimization::DeoptReason::Reason_profile_predicate:
2079       st->print("Profiled_Loop ");
2080       break;
2081     case Deoptimization::DeoptReason::Reason_loop_limit_check:
2082       st->print("Loop_Limit_Check ");
2083       break;
2084     default:
2085       fatal("unknown kind");
2086   }
2087 }
2088 
2089 #endif // NOT PRODUCT
--- EOF ---