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