1 /*
   2  * Copyright (c) 2000, 2013, 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 "memory/allocation.inline.hpp"
  27 #include "opto/addnode.hpp"
  28 #include "opto/cfgnode.hpp"
  29 #include "opto/connode.hpp"
  30 #include "opto/loopnode.hpp"
  31 #include "opto/phaseX.hpp"
  32 #include "opto/runtime.hpp"
  33 #include "opto/subnode.hpp"
  34 
  35 // Portions of code courtesy of Clifford Click
  36 
  37 // Optimization - Graph Style
  38 
  39 
  40 extern int explicit_null_checks_elided;
  41 
  42 //=============================================================================
  43 //------------------------------Value------------------------------------------
  44 // Return a tuple for whichever arm of the IF is reachable
  45 const Type *IfNode::Value( PhaseTransform *phase ) const {
  46   if( !in(0) ) return Type::TOP;
  47   if( phase->type(in(0)) == Type::TOP )
  48     return Type::TOP;
  49   const Type *t = phase->type(in(1));
  50   if( t == Type::TOP )          // data is undefined
  51     return TypeTuple::IFNEITHER; // unreachable altogether
  52   if( t == TypeInt::ZERO )      // zero, or false
  53     return TypeTuple::IFFALSE;  // only false branch is reachable
  54   if( t == TypeInt::ONE )       // 1, or true
  55     return TypeTuple::IFTRUE;   // only true branch is reachable
  56   assert( t == TypeInt::BOOL, "expected boolean type" );
  57 
  58   return TypeTuple::IFBOTH;     // No progress
  59 }
  60 
  61 const RegMask &IfNode::out_RegMask() const {
  62   return RegMask::Empty;
  63 }
  64 
  65 //------------------------------split_if---------------------------------------
  66 // Look for places where we merge constants, then test on the merged value.
  67 // If the IF test will be constant folded on the path with the constant, we
  68 // win by splitting the IF to before the merge point.
  69 static Node* split_if(IfNode *iff, PhaseIterGVN *igvn) {
  70   // I could be a lot more general here, but I'm trying to squeeze this
  71   // in before the Christmas '98 break so I'm gonna be kinda restrictive
  72   // on the patterns I accept.  CNC
  73 
  74   // Look for a compare of a constant and a merged value
  75   Node *i1 = iff->in(1);
  76   if( !i1->is_Bool() ) return NULL;
  77   BoolNode *b = i1->as_Bool();
  78   Node *cmp = b->in(1);
  79   if( !cmp->is_Cmp() ) return NULL;
  80   i1 = cmp->in(1);
  81   if( i1 == NULL || !i1->is_Phi() ) return NULL;
  82   PhiNode *phi = i1->as_Phi();
  83   if( phi->is_copy() ) return NULL;
  84   Node *con2 = cmp->in(2);
  85   if( !con2->is_Con() ) return NULL;
  86   // See that the merge point contains some constants
  87   Node *con1=NULL;
  88   uint i4;
  89   for( i4 = 1; i4 < phi->req(); i4++ ) {
  90     con1 = phi->in(i4);
  91     if( !con1 ) return NULL;    // Do not optimize partially collapsed merges
  92     if( con1->is_Con() ) break; // Found a constant
  93     // Also allow null-vs-not-null checks
  94     const TypePtr *tp = igvn->type(con1)->isa_ptr();
  95     if( tp && tp->_ptr == TypePtr::NotNull )
  96       break;
  97   }
  98   if( i4 >= phi->req() ) return NULL; // Found no constants
  99 
 100   igvn->C->set_has_split_ifs(true); // Has chance for split-if
 101 
 102   // Make sure that the compare can be constant folded away
 103   Node *cmp2 = cmp->clone();
 104   cmp2->set_req(1,con1);
 105   cmp2->set_req(2,con2);
 106   const Type *t = cmp2->Value(igvn);
 107   // This compare is dead, so whack it!
 108   igvn->remove_dead_node(cmp2);
 109   if( !t->singleton() ) return NULL;
 110 
 111   // No intervening control, like a simple Call
 112   Node *r = iff->in(0);
 113   if( !r->is_Region() ) return NULL;
 114   if( phi->region() != r ) return NULL;
 115   // No other users of the cmp/bool
 116   if (b->outcnt() != 1 || cmp->outcnt() != 1) {
 117     //tty->print_cr("many users of cmp/bool");
 118     return NULL;
 119   }
 120 
 121   // Make sure we can determine where all the uses of merged values go
 122   for (DUIterator_Fast jmax, j = r->fast_outs(jmax); j < jmax; j++) {
 123     Node* u = r->fast_out(j);
 124     if( u == r ) continue;
 125     if( u == iff ) continue;
 126     if( u->outcnt() == 0 ) continue; // use is dead & ignorable
 127     if( !u->is_Phi() ) {
 128       /*
 129       if( u->is_Start() ) {
 130         tty->print_cr("Region has inlined start use");
 131       } else {
 132         tty->print_cr("Region has odd use");
 133         u->dump(2);
 134       }*/
 135       return NULL;
 136     }
 137     if( u != phi ) {
 138       // CNC - do not allow any other merged value
 139       //tty->print_cr("Merging another value");
 140       //u->dump(2);
 141       return NULL;
 142     }
 143     // Make sure we can account for all Phi uses
 144     for (DUIterator_Fast kmax, k = u->fast_outs(kmax); k < kmax; k++) {
 145       Node* v = u->fast_out(k); // User of the phi
 146       // CNC - Allow only really simple patterns.
 147       // In particular I disallow AddP of the Phi, a fairly common pattern
 148       if (v == cmp) continue;  // The compare is OK
 149       if (v->is_ConstraintCast()) {
 150         // If the cast is derived from data flow edges, it may not have a control.
 151         // If so, it should be save to split. But follow-up code can not deal with
 152         // this (l. 359). So skip.
 153         if (v->in(0) == NULL) {
 154           return NULL;
 155         }
 156         if (v->in(0)->in(0) == iff) {
 157           continue;               // CastPP/II of the IfNode is OK
 158         }
 159       }
 160       // Disabled following code because I cannot tell if exactly one
 161       // path dominates without a real dominator check. CNC 9/9/1999
 162       //uint vop = v->Opcode();
 163       //if( vop == Op_Phi ) {     // Phi from another merge point might be OK
 164       //  Node *r = v->in(0);     // Get controlling point
 165       //  if( !r ) return NULL;   // Degraded to a copy
 166       //  // Find exactly one path in (either True or False doms, but not IFF)
 167       //  int cnt = 0;
 168       //  for( uint i = 1; i < r->req(); i++ )
 169       //    if( r->in(i) && r->in(i)->in(0) == iff )
 170       //      cnt++;
 171       //  if( cnt == 1 ) continue; // Exactly one of True or False guards Phi
 172       //}
 173       if( !v->is_Call() ) {
 174         /*
 175         if( v->Opcode() == Op_AddP ) {
 176           tty->print_cr("Phi has AddP use");
 177         } else if( v->Opcode() == Op_CastPP ) {
 178           tty->print_cr("Phi has CastPP use");
 179         } else if( v->Opcode() == Op_CastII ) {
 180           tty->print_cr("Phi has CastII use");
 181         } else {
 182           tty->print_cr("Phi has use I cant be bothered with");
 183         }
 184         */
 185       }
 186       return NULL;
 187 
 188       /* CNC - Cut out all the fancy acceptance tests
 189       // Can we clone this use when doing the transformation?
 190       // If all uses are from Phis at this merge or constants, then YES.
 191       if( !v->in(0) && v != cmp ) {
 192         tty->print_cr("Phi has free-floating use");
 193         v->dump(2);
 194         return NULL;
 195       }
 196       for( uint l = 1; l < v->req(); l++ ) {
 197         if( (!v->in(l)->is_Phi() || v->in(l)->in(0) != r) &&
 198             !v->in(l)->is_Con() ) {
 199           tty->print_cr("Phi has use");
 200           v->dump(2);
 201           return NULL;
 202         } // End of if Phi-use input is neither Phi nor Constant
 203       } // End of for all inputs to Phi-use
 204       */
 205     } // End of for all uses of Phi
 206   } // End of for all uses of Region
 207 
 208   // Only do this if the IF node is in a sane state
 209   if (iff->outcnt() != 2)
 210     return NULL;
 211 
 212   // Got a hit!  Do the Mondo Hack!
 213   //
 214   //ABC  a1c   def   ghi            B     1     e     h   A C   a c   d f   g i
 215   // R - Phi - Phi - Phi            Rc - Phi - Phi - Phi   Rx - Phi - Phi - Phi
 216   //     cmp - 2                         cmp - 2               cmp - 2
 217   //       bool                            bool_c                bool_x
 218   //       if                               if_c                  if_x
 219   //      T  F                              T  F                  T  F
 220   // ..s..    ..t ..                   ..s..    ..t..        ..s..    ..t..
 221   //
 222   // Split the paths coming into the merge point into 2 separate groups of
 223   // merges.  On the left will be all the paths feeding constants into the
 224   // Cmp's Phi.  On the right will be the remaining paths.  The Cmp's Phi
 225   // will fold up into a constant; this will let the Cmp fold up as well as
 226   // all the control flow.  Below the original IF we have 2 control
 227   // dependent regions, 's' and 't'.  Now we will merge the two paths
 228   // just prior to 's' and 't' from the two IFs.  At least 1 path (and quite
 229   // likely 2 or more) will promptly constant fold away.
 230   PhaseGVN *phase = igvn;
 231 
 232   // Make a region merging constants and a region merging the rest
 233   uint req_c = 0;
 234   Node* predicate_proj = NULL;
 235   for (uint ii = 1; ii < r->req(); ii++) {
 236     if (phi->in(ii) == con1) {
 237       req_c++;
 238     }
 239     Node* proj = PhaseIdealLoop::find_predicate(r->in(ii));
 240     if (proj != NULL) {
 241       assert(predicate_proj == NULL, "only one predicate entry expected");
 242       predicate_proj = proj;
 243     }
 244   }
 245   Node* predicate_c = NULL;
 246   Node* predicate_x = NULL;
 247   bool counted_loop = r->is_CountedLoop();
 248 
 249   Node *region_c = new RegionNode(req_c + 1);
 250   Node *phi_c    = con1;
 251   uint  len      = r->req();
 252   Node *region_x = new RegionNode(len - req_c);
 253   Node *phi_x    = PhiNode::make_blank(region_x, phi);
 254   for (uint i = 1, i_c = 1, i_x = 1; i < len; i++) {
 255     if (phi->in(i) == con1) {
 256       region_c->init_req( i_c++, r  ->in(i) );
 257       if (r->in(i) == predicate_proj)
 258         predicate_c = predicate_proj;
 259     } else {
 260       region_x->init_req( i_x,   r  ->in(i) );
 261       phi_x   ->init_req( i_x++, phi->in(i) );
 262       if (r->in(i) == predicate_proj)
 263         predicate_x = predicate_proj;
 264     }
 265   }
 266   if (predicate_c != NULL && (req_c > 1)) {
 267     assert(predicate_x == NULL, "only one predicate entry expected");
 268     predicate_c = NULL; // Do not clone predicate below merge point
 269   }
 270   if (predicate_x != NULL && ((len - req_c) > 2)) {
 271     assert(predicate_c == NULL, "only one predicate entry expected");
 272     predicate_x = NULL; // Do not clone predicate below merge point
 273   }
 274 
 275   // Register the new RegionNodes but do not transform them.  Cannot
 276   // transform until the entire Region/Phi conglomerate has been hacked
 277   // as a single huge transform.
 278   igvn->register_new_node_with_optimizer( region_c );
 279   igvn->register_new_node_with_optimizer( region_x );
 280   // Prevent the untimely death of phi_x.  Currently he has no uses.  He is
 281   // about to get one.  If this only use goes away, then phi_x will look dead.
 282   // However, he will be picking up some more uses down below.
 283   Node *hook = new Node(4);
 284   hook->init_req(0, phi_x);
 285   hook->init_req(1, phi_c);
 286   phi_x = phase->transform( phi_x );
 287 
 288   // Make the compare
 289   Node *cmp_c = phase->makecon(t);
 290   Node *cmp_x = cmp->clone();
 291   cmp_x->set_req(1,phi_x);
 292   cmp_x->set_req(2,con2);
 293   cmp_x = phase->transform(cmp_x);
 294   // Make the bool
 295   Node *b_c = phase->transform(new BoolNode(cmp_c,b->_test._test));
 296   Node *b_x = phase->transform(new BoolNode(cmp_x,b->_test._test));
 297   // Make the IfNode
 298   IfNode *iff_c = new IfNode(region_c,b_c,iff->_prob,iff->_fcnt);
 299   igvn->set_type_bottom(iff_c);
 300   igvn->_worklist.push(iff_c);
 301   hook->init_req(2, iff_c);
 302 
 303   IfNode *iff_x = new IfNode(region_x,b_x,iff->_prob, iff->_fcnt);
 304   igvn->set_type_bottom(iff_x);
 305   igvn->_worklist.push(iff_x);
 306   hook->init_req(3, iff_x);
 307 
 308   // Make the true/false arms
 309   Node *iff_c_t = phase->transform(new IfTrueNode (iff_c));
 310   Node *iff_c_f = phase->transform(new IfFalseNode(iff_c));
 311   if (predicate_c != NULL) {
 312     assert(predicate_x == NULL, "only one predicate entry expected");
 313     // Clone loop predicates to each path
 314     iff_c_t = igvn->clone_loop_predicates(predicate_c, iff_c_t, !counted_loop);
 315     iff_c_f = igvn->clone_loop_predicates(predicate_c, iff_c_f, !counted_loop);
 316   }
 317   Node *iff_x_t = phase->transform(new IfTrueNode (iff_x));
 318   Node *iff_x_f = phase->transform(new IfFalseNode(iff_x));
 319   if (predicate_x != NULL) {
 320     assert(predicate_c == NULL, "only one predicate entry expected");
 321     // Clone loop predicates to each path
 322     iff_x_t = igvn->clone_loop_predicates(predicate_x, iff_x_t, !counted_loop);
 323     iff_x_f = igvn->clone_loop_predicates(predicate_x, iff_x_f, !counted_loop);
 324   }
 325 
 326   // Merge the TRUE paths
 327   Node *region_s = new RegionNode(3);
 328   igvn->_worklist.push(region_s);
 329   region_s->init_req(1, iff_c_t);
 330   region_s->init_req(2, iff_x_t);
 331   igvn->register_new_node_with_optimizer( region_s );
 332 
 333   // Merge the FALSE paths
 334   Node *region_f = new RegionNode(3);
 335   igvn->_worklist.push(region_f);
 336   region_f->init_req(1, iff_c_f);
 337   region_f->init_req(2, iff_x_f);
 338   igvn->register_new_node_with_optimizer( region_f );
 339 
 340   igvn->hash_delete(cmp);// Remove soon-to-be-dead node from hash table.
 341   cmp->set_req(1,NULL);  // Whack the inputs to cmp because it will be dead
 342   cmp->set_req(2,NULL);
 343   // Check for all uses of the Phi and give them a new home.
 344   // The 'cmp' got cloned, but CastPP/IIs need to be moved.
 345   Node *phi_s = NULL;     // do not construct unless needed
 346   Node *phi_f = NULL;     // do not construct unless needed
 347   for (DUIterator_Last i2min, i2 = phi->last_outs(i2min); i2 >= i2min; --i2) {
 348     Node* v = phi->last_out(i2);// User of the phi
 349     igvn->rehash_node_delayed(v); // Have to fixup other Phi users
 350     uint vop = v->Opcode();
 351     Node *proj = NULL;
 352     if( vop == Op_Phi ) {       // Remote merge point
 353       Node *r = v->in(0);
 354       for (uint i3 = 1; i3 < r->req(); i3++)
 355         if (r->in(i3) && r->in(i3)->in(0) == iff) {
 356           proj = r->in(i3);
 357           break;
 358         }
 359     } else if( v->is_ConstraintCast() ) {
 360       proj = v->in(0);          // Controlling projection
 361     } else {
 362       assert( 0, "do not know how to handle this guy" );
 363     }
 364 
 365     Node *proj_path_data, *proj_path_ctrl;
 366     if( proj->Opcode() == Op_IfTrue ) {
 367       if( phi_s == NULL ) {
 368         // Only construct phi_s if needed, otherwise provides
 369         // interfering use.
 370         phi_s = PhiNode::make_blank(region_s,phi);
 371         phi_s->init_req( 1, phi_c );
 372         phi_s->init_req( 2, phi_x );
 373         hook->add_req(phi_s);
 374         phi_s = phase->transform(phi_s);
 375       }
 376       proj_path_data = phi_s;
 377       proj_path_ctrl = region_s;
 378     } else {
 379       if( phi_f == NULL ) {
 380         // Only construct phi_f if needed, otherwise provides
 381         // interfering use.
 382         phi_f = PhiNode::make_blank(region_f,phi);
 383         phi_f->init_req( 1, phi_c );
 384         phi_f->init_req( 2, phi_x );
 385         hook->add_req(phi_f);
 386         phi_f = phase->transform(phi_f);
 387       }
 388       proj_path_data = phi_f;
 389       proj_path_ctrl = region_f;
 390     }
 391 
 392     // Fixup 'v' for for the split
 393     if( vop == Op_Phi ) {       // Remote merge point
 394       uint i;
 395       for( i = 1; i < v->req(); i++ )
 396         if( v->in(i) == phi )
 397           break;
 398       v->set_req(i, proj_path_data );
 399     } else if( v->is_ConstraintCast() ) {
 400       v->set_req(0, proj_path_ctrl );
 401       v->set_req(1, proj_path_data );
 402     } else
 403       ShouldNotReachHere();
 404   }
 405 
 406   // Now replace the original iff's True/False with region_s/region_t.
 407   // This makes the original iff go dead.
 408   for (DUIterator_Last i3min, i3 = iff->last_outs(i3min); i3 >= i3min; --i3) {
 409     Node* p = iff->last_out(i3);
 410     assert( p->Opcode() == Op_IfTrue || p->Opcode() == Op_IfFalse, "" );
 411     Node *u = (p->Opcode() == Op_IfTrue) ? region_s : region_f;
 412     // Replace p with u
 413     igvn->add_users_to_worklist(p);
 414     for (DUIterator_Last lmin, l = p->last_outs(lmin); l >= lmin;) {
 415       Node* x = p->last_out(l);
 416       igvn->hash_delete(x);
 417       uint uses_found = 0;
 418       for( uint j = 0; j < x->req(); j++ ) {
 419         if( x->in(j) == p ) {
 420           x->set_req(j, u);
 421           uses_found++;
 422         }
 423       }
 424       l -= uses_found;    // we deleted 1 or more copies of this edge
 425     }
 426     igvn->remove_dead_node(p);
 427   }
 428 
 429   // Force the original merge dead
 430   igvn->hash_delete(r);
 431   // First, remove region's dead users.
 432   for (DUIterator_Last lmin, l = r->last_outs(lmin); l >= lmin;) {
 433     Node* u = r->last_out(l);
 434     if( u == r ) {
 435       r->set_req(0, NULL);
 436     } else {
 437       assert(u->outcnt() == 0, "only dead users");
 438       igvn->remove_dead_node(u);
 439     }
 440     l -= 1;
 441   }
 442   igvn->remove_dead_node(r);
 443 
 444   // Now remove the bogus extra edges used to keep things alive
 445   igvn->remove_dead_node( hook );
 446 
 447   // Must return either the original node (now dead) or a new node
 448   // (Do not return a top here, since that would break the uniqueness of top.)
 449   return new ConINode(TypeInt::ZERO);
 450 }
 451 
 452 //------------------------------is_range_check---------------------------------
 453 // Return 0 if not a range check.  Return 1 if a range check and set index and
 454 // offset.  Return 2 if we had to negate the test.  Index is NULL if the check
 455 // is versus a constant.
 456 int IfNode::is_range_check(Node* &range, Node* &index, jint &offset) {
 457   Node* b = in(1);
 458   if (b == NULL || !b->is_Bool())  return 0;
 459   BoolNode* bn = b->as_Bool();
 460   Node* cmp = bn->in(1);
 461   if (cmp == NULL)  return 0;
 462   if (cmp->Opcode() != Op_CmpU)  return 0;
 463 
 464   Node* l = cmp->in(1);
 465   Node* r = cmp->in(2);
 466   int flip_test = 1;
 467   if (bn->_test._test == BoolTest::le) {
 468     l = cmp->in(2);
 469     r = cmp->in(1);
 470     flip_test = 2;
 471   } else if (bn->_test._test != BoolTest::lt) {
 472     return 0;
 473   }
 474   if (l->is_top())  return 0;   // Top input means dead test
 475   if (r->Opcode() != Op_LoadRange)  return 0;
 476 
 477   // We have recognized one of these forms:
 478   //  Flip 1:  If (Bool[<] CmpU(l, LoadRange)) ...
 479   //  Flip 2:  If (Bool[<=] CmpU(LoadRange, l)) ...
 480 
 481   // Make sure it's a real range check by requiring an uncommon trap
 482   // along the OOB path.  Otherwise, it's possible that the user wrote
 483   // something which optimized to look like a range check but behaves
 484   // in some other way.
 485   Node* iftrap = proj_out(flip_test == 2 ? true : false);
 486   bool found_trap = false;
 487   if (iftrap != NULL) {
 488     Node* u = iftrap->unique_ctrl_out();
 489     if (u != NULL) {
 490       // It could be a merge point (Region) for uncommon trap.
 491       if (u->is_Region()) {
 492         Node* c = u->unique_ctrl_out();
 493         if (c != NULL) {
 494           iftrap = u;
 495           u = c;
 496         }
 497       }
 498       if (u->in(0) == iftrap && u->is_CallStaticJava()) {
 499         int req = u->as_CallStaticJava()->uncommon_trap_request();
 500         if (Deoptimization::trap_request_reason(req) ==
 501             Deoptimization::Reason_range_check) {
 502           found_trap = true;
 503         }
 504       }
 505     }
 506   }
 507   if (!found_trap)  return 0;   // sorry, no cigar
 508 
 509   // Look for index+offset form
 510   Node* ind = l;
 511   jint  off = 0;
 512   if (l->is_top()) {
 513     return 0;
 514   } else if (l->Opcode() == Op_AddI) {
 515     if ((off = l->in(1)->find_int_con(0)) != 0) {
 516       ind = l->in(2);
 517     } else if ((off = l->in(2)->find_int_con(0)) != 0) {
 518       ind = l->in(1);
 519     }
 520   } else if ((off = l->find_int_con(-1)) >= 0) {
 521     // constant offset with no variable index
 522     ind = NULL;
 523   } else {
 524     // variable index with no constant offset (or dead negative index)
 525     off = 0;
 526   }
 527 
 528   // Return all the values:
 529   index  = ind;
 530   offset = off;
 531   range  = r;
 532   return flip_test;
 533 }
 534 
 535 //------------------------------adjust_check-----------------------------------
 536 // Adjust (widen) a prior range check
 537 static void adjust_check(Node* proj, Node* range, Node* index,
 538                          int flip, jint off_lo, PhaseIterGVN* igvn) {
 539   PhaseGVN *gvn = igvn;
 540   // Break apart the old check
 541   Node *iff = proj->in(0);
 542   Node *bol = iff->in(1);
 543   if( bol->is_top() ) return;   // In case a partially dead range check appears
 544   // bail (or bomb[ASSERT/DEBUG]) if NOT projection-->IfNode-->BoolNode
 545   DEBUG_ONLY( if( !bol->is_Bool() ) { proj->dump(3); fatal("Expect projection-->IfNode-->BoolNode"); } )
 546   if( !bol->is_Bool() ) return;
 547 
 548   Node *cmp = bol->in(1);
 549   // Compute a new check
 550   Node *new_add = gvn->intcon(off_lo);
 551   if( index ) {
 552     new_add = off_lo ? gvn->transform(new AddINode( index, new_add )) : index;
 553   }
 554   Node *new_cmp = (flip == 1)
 555     ? new CmpUNode( new_add, range )
 556     : new CmpUNode( range, new_add );
 557   new_cmp = gvn->transform(new_cmp);
 558   // See if no need to adjust the existing check
 559   if( new_cmp == cmp ) return;
 560   // Else, adjust existing check
 561   Node *new_bol = gvn->transform( new BoolNode( new_cmp, bol->as_Bool()->_test._test ) );
 562   igvn->rehash_node_delayed( iff );
 563   iff->set_req_X( 1, new_bol, igvn );
 564 }
 565 
 566 //------------------------------up_one_dom-------------------------------------
 567 // Walk up the dominator tree one step.  Return NULL at root or true
 568 // complex merges.  Skips through small diamonds.
 569 Node* IfNode::up_one_dom(Node *curr, bool linear_only) {
 570   Node *dom = curr->in(0);
 571   if( !dom )                    // Found a Region degraded to a copy?
 572     return curr->nonnull_req(); // Skip thru it
 573 
 574   if( curr != dom )             // Normal walk up one step?
 575     return dom;
 576 
 577   // Use linear_only if we are still parsing, since we cannot
 578   // trust the regions to be fully filled in.
 579   if (linear_only)
 580     return NULL;
 581 
 582   if( dom->is_Root() )
 583     return NULL;
 584 
 585   // Else hit a Region.  Check for a loop header
 586   if( dom->is_Loop() )
 587     return dom->in(1);          // Skip up thru loops
 588 
 589   // Check for small diamonds
 590   Node *din1, *din2, *din3, *din4;
 591   if( dom->req() == 3 &&        // 2-path merge point
 592       (din1 = dom ->in(1)) &&   // Left  path exists
 593       (din2 = dom ->in(2)) &&   // Right path exists
 594       (din3 = din1->in(0)) &&   // Left  path up one
 595       (din4 = din2->in(0)) ) {  // Right path up one
 596     if( din3->is_Call() &&      // Handle a slow-path call on either arm
 597         (din3 = din3->in(0)) )
 598       din3 = din3->in(0);
 599     if( din4->is_Call() &&      // Handle a slow-path call on either arm
 600         (din4 = din4->in(0)) )
 601       din4 = din4->in(0);
 602     if( din3 == din4 && din3->is_If() )
 603       return din3;              // Skip around diamonds
 604   }
 605 
 606   // Give up the search at true merges
 607   return NULL;                  // Dead loop?  Or hit root?
 608 }
 609 
 610 
 611 //------------------------------filtered_int_type--------------------------------
 612 // Return a possibly more restrictive type for val based on condition control flow for an if
 613 const TypeInt* IfNode::filtered_int_type(PhaseGVN* gvn, Node *val, Node* if_proj) {
 614   assert(if_proj &&
 615          (if_proj->Opcode() == Op_IfTrue || if_proj->Opcode() == Op_IfFalse), "expecting an if projection");
 616   if (if_proj->in(0) && if_proj->in(0)->is_If()) {
 617     IfNode* iff = if_proj->in(0)->as_If();
 618     if (iff->in(1) && iff->in(1)->is_Bool()) {
 619       BoolNode* bol = iff->in(1)->as_Bool();
 620       if (bol->in(1) && bol->in(1)->is_Cmp()) {
 621         const CmpNode* cmp  = bol->in(1)->as_Cmp();
 622         if (cmp->in(1) == val) {
 623           const TypeInt* cmp2_t = gvn->type(cmp->in(2))->isa_int();
 624           if (cmp2_t != NULL) {
 625             jint lo = cmp2_t->_lo;
 626             jint hi = cmp2_t->_hi;
 627             BoolTest::mask msk = if_proj->Opcode() == Op_IfTrue ? bol->_test._test : bol->_test.negate();
 628             switch (msk) {
 629             case BoolTest::ne:
 630               // Can't refine type
 631               return NULL;
 632             case BoolTest::eq:
 633               return cmp2_t;
 634             case BoolTest::lt:
 635               lo = TypeInt::INT->_lo;
 636               if (hi - 1 < hi) {
 637                 hi = hi - 1;
 638               }
 639               break;
 640             case BoolTest::le:
 641               lo = TypeInt::INT->_lo;
 642               break;
 643             case BoolTest::gt:
 644               if (lo + 1 > lo) {
 645                 lo = lo + 1;
 646               }
 647               hi = TypeInt::INT->_hi;
 648               break;
 649             case BoolTest::ge:
 650               // lo unchanged
 651               hi = TypeInt::INT->_hi;
 652               break;
 653             }
 654             const TypeInt* rtn_t = TypeInt::make(lo, hi, cmp2_t->_widen);
 655             return rtn_t;
 656           }
 657         }
 658       }
 659     }
 660   }
 661   return NULL;
 662 }
 663 
 664 //------------------------------fold_compares----------------------------
 665 // See if a pair of CmpIs can be converted into a CmpU.  In some cases
 666 // the direction of this if is determined by the preceding if so it
 667 // can be eliminate entirely.  Given an if testing (CmpI n c) check
 668 // for an immediately control dependent if that is testing (CmpI n c2)
 669 // and has one projection leading to this if and the other projection
 670 // leading to a region that merges one of this ifs control
 671 // projections.
 672 //
 673 //                   If
 674 //                  / |
 675 //                 /  |
 676 //                /   |
 677 //              If    |
 678 //              /\    |
 679 //             /  \   |
 680 //            /    \  |
 681 //           /    Region
 682 //
 683 Node* IfNode::fold_compares(PhaseGVN* phase) {
 684   if (Opcode() != Op_If) return NULL;
 685 
 686   Node* this_cmp = in(1)->in(1);
 687   if (this_cmp != NULL && this_cmp->Opcode() == Op_CmpI &&
 688       this_cmp->in(2)->is_Con() && this_cmp->in(2) != phase->C->top()) {
 689     Node* ctrl = in(0);
 690     BoolNode* this_bool = in(1)->as_Bool();
 691     Node* n = this_cmp->in(1);
 692     int hi = this_cmp->in(2)->get_int();
 693     if (ctrl != NULL && ctrl->is_Proj() && ctrl->outcnt() == 1 &&
 694         ctrl->in(0)->is_If() &&
 695         ctrl->in(0)->outcnt() == 2 &&
 696         ctrl->in(0)->in(1)->is_Bool() &&
 697         ctrl->in(0)->in(1)->in(1)->Opcode() == Op_CmpI &&
 698         ctrl->in(0)->in(1)->in(1)->in(2)->is_Con() &&
 699         ctrl->in(0)->in(1)->in(1)->in(2) != phase->C->top() &&
 700         ctrl->in(0)->in(1)->in(1)->in(1) == n) {
 701       IfNode* dom_iff = ctrl->in(0)->as_If();
 702       Node* otherproj = dom_iff->proj_out(!ctrl->as_Proj()->_con);
 703       if (otherproj->outcnt() == 1 && otherproj->unique_out()->is_Region() &&
 704           this_bool->_test._test != BoolTest::ne && this_bool->_test._test != BoolTest::eq) {
 705         // Identify which proj goes to the region and which continues on
 706         RegionNode* region = otherproj->unique_out()->as_Region();
 707         Node* success = NULL;
 708         Node* fail = NULL;
 709         for (int i = 0; i < 2; i++) {
 710           Node* proj = proj_out(i);
 711           if (success == NULL && proj->outcnt() == 1 && proj->unique_out() == region) {
 712             success = proj;
 713           } else if (fail == NULL) {
 714             fail = proj;
 715           } else {
 716             success = fail = NULL;
 717           }
 718         }
 719         if (success != NULL && fail != NULL && !region->has_phi()) {
 720           int lo = dom_iff->in(1)->in(1)->in(2)->get_int();
 721           BoolNode* dom_bool = dom_iff->in(1)->as_Bool();
 722           Node* dom_cmp =  dom_bool->in(1);
 723           const TypeInt* failtype  = filtered_int_type(phase, n, ctrl);
 724           if (failtype != NULL) {
 725             const TypeInt* type2 = filtered_int_type(phase, n, fail);
 726             if (type2 != NULL) {
 727               failtype = failtype->join(type2)->is_int();
 728             } else {
 729               failtype = NULL;
 730             }
 731           }
 732 
 733           if (failtype != NULL &&
 734               dom_bool->_test._test != BoolTest::ne && dom_bool->_test._test != BoolTest::eq) {
 735             int bound = failtype->_hi - failtype->_lo + 1;
 736             if (failtype->_hi != max_jint && failtype->_lo != min_jint && bound > 1) {
 737               // Merge the two compares into a single unsigned compare by building  (CmpU (n - lo) hi)
 738               BoolTest::mask cond = fail->as_Proj()->_con ? BoolTest::lt : BoolTest::ge;
 739               Node* adjusted = phase->transform(new SubINode(n, phase->intcon(failtype->_lo)));
 740               Node* newcmp = phase->transform(new CmpUNode(adjusted, phase->intcon(bound)));
 741               Node* newbool = phase->transform(new BoolNode(newcmp, cond));
 742               phase->is_IterGVN()->replace_input_of(dom_iff, 1, phase->intcon(ctrl->as_Proj()->_con));
 743               phase->hash_delete(this);
 744               set_req(1, newbool);
 745               return this;
 746             }
 747             if (failtype->_lo > failtype->_hi) {
 748               // previous if determines the result of this if so
 749               // replace Bool with constant
 750               phase->hash_delete(this);
 751               set_req(1, phase->intcon(success->as_Proj()->_con));
 752               return this;
 753             }
 754           }
 755         }
 756       }
 757     }
 758   }
 759   return NULL;
 760 }
 761 
 762 //------------------------------remove_useless_bool----------------------------
 763 // Check for people making a useless boolean: things like
 764 // if( (x < y ? true : false) ) { ... }
 765 // Replace with if( x < y ) { ... }
 766 static Node *remove_useless_bool(IfNode *iff, PhaseGVN *phase) {
 767   Node *i1 = iff->in(1);
 768   if( !i1->is_Bool() ) return NULL;
 769   BoolNode *bol = i1->as_Bool();
 770 
 771   Node *cmp = bol->in(1);
 772   if( cmp->Opcode() != Op_CmpI ) return NULL;
 773 
 774   // Must be comparing against a bool
 775   const Type *cmp2_t = phase->type( cmp->in(2) );
 776   if( cmp2_t != TypeInt::ZERO &&
 777       cmp2_t != TypeInt::ONE )
 778     return NULL;
 779 
 780   // Find a prior merge point merging the boolean
 781   i1 = cmp->in(1);
 782   if( !i1->is_Phi() ) return NULL;
 783   PhiNode *phi = i1->as_Phi();
 784   if( phase->type( phi ) != TypeInt::BOOL )
 785     return NULL;
 786 
 787   // Check for diamond pattern
 788   int true_path = phi->is_diamond_phi();
 789   if( true_path == 0 ) return NULL;
 790 
 791   // Make sure that iff and the control of the phi are different. This
 792   // should really only happen for dead control flow since it requires
 793   // an illegal cycle.
 794   if (phi->in(0)->in(1)->in(0) == iff) return NULL;
 795 
 796   // phi->region->if_proj->ifnode->bool->cmp
 797   BoolNode *bol2 = phi->in(0)->in(1)->in(0)->in(1)->as_Bool();
 798 
 799   // Now get the 'sense' of the test correct so we can plug in
 800   // either iff2->in(1) or its complement.
 801   int flip = 0;
 802   if( bol->_test._test == BoolTest::ne ) flip = 1-flip;
 803   else if( bol->_test._test != BoolTest::eq ) return NULL;
 804   if( cmp2_t == TypeInt::ZERO ) flip = 1-flip;
 805 
 806   const Type *phi1_t = phase->type( phi->in(1) );
 807   const Type *phi2_t = phase->type( phi->in(2) );
 808   // Check for Phi(0,1) and flip
 809   if( phi1_t == TypeInt::ZERO ) {
 810     if( phi2_t != TypeInt::ONE ) return NULL;
 811     flip = 1-flip;
 812   } else {
 813     // Check for Phi(1,0)
 814     if( phi1_t != TypeInt::ONE  ) return NULL;
 815     if( phi2_t != TypeInt::ZERO ) return NULL;
 816   }
 817   if( true_path == 2 ) {
 818     flip = 1-flip;
 819   }
 820 
 821   Node* new_bol = (flip ? phase->transform( bol2->negate(phase) ) : bol2);
 822   assert(new_bol != iff->in(1), "must make progress");
 823   iff->set_req(1, new_bol);
 824   // Intervening diamond probably goes dead
 825   phase->C->set_major_progress();
 826   return iff;
 827 }
 828 
 829 static IfNode* idealize_test(PhaseGVN* phase, IfNode* iff);
 830 
 831 struct RangeCheck {
 832   Node* ctl;
 833   jint off;
 834 };
 835 
 836 //------------------------------Ideal------------------------------------------
 837 // Return a node which is more "ideal" than the current node.  Strip out
 838 // control copies
 839 Node *IfNode::Ideal(PhaseGVN *phase, bool can_reshape) {
 840   if (remove_dead_region(phase, can_reshape))  return this;
 841   // No Def-Use info?
 842   if (!can_reshape)  return NULL;
 843   PhaseIterGVN *igvn = phase->is_IterGVN();
 844 
 845   // Don't bother trying to transform a dead if
 846   if (in(0)->is_top())  return NULL;
 847   // Don't bother trying to transform an if with a dead test
 848   if (in(1)->is_top())  return NULL;
 849   // Another variation of a dead test
 850   if (in(1)->is_Con())  return NULL;
 851   // Another variation of a dead if
 852   if (outcnt() < 2)  return NULL;
 853 
 854   // Canonicalize the test.
 855   Node* idt_if = idealize_test(phase, this);
 856   if (idt_if != NULL)  return idt_if;
 857 
 858   // Try to split the IF
 859   Node *s = split_if(this, igvn);
 860   if (s != NULL)  return s;
 861 
 862   // Check for people making a useless boolean: things like
 863   // if( (x < y ? true : false) ) { ... }
 864   // Replace with if( x < y ) { ... }
 865   Node *bol2 = remove_useless_bool(this, phase);
 866   if( bol2 ) return bol2;
 867 
 868   // Setup to scan up the CFG looking for a dominating test
 869   Node *dom = in(0);
 870   Node *prev_dom = this;
 871 
 872   // Check for range-check vs other kinds of tests
 873   Node *index1, *range1;
 874   jint offset1;
 875   int flip1 = is_range_check(range1, index1, offset1);
 876   if( flip1 ) {
 877     // Try to remove extra range checks.  All 'up_one_dom' gives up at merges
 878     // so all checks we inspect post-dominate the top-most check we find.
 879     // If we are going to fail the current check and we reach the top check
 880     // then we are guaranteed to fail, so just start interpreting there.
 881     // We 'expand' the top 3 range checks to include all post-dominating
 882     // checks.
 883 
 884     // The top 3 range checks seen
 885     const int NRC =3;
 886     RangeCheck prev_checks[NRC];
 887     int nb_checks = 0;
 888 
 889     // Low and high offsets seen so far
 890     jint off_lo = offset1;
 891     jint off_hi = offset1;
 892 
 893     bool found_immediate_dominator = false;
 894 
 895     // Scan for the top checks and collect range of offsets
 896     for (int dist = 0; dist < 999; dist++) { // Range-Check scan limit
 897       if (dom->Opcode() == Op_If &&  // Not same opcode?
 898           prev_dom->in(0) == dom) { // One path of test does dominate?
 899         if (dom == this) return NULL; // dead loop
 900         // See if this is a range check
 901         Node *index2, *range2;
 902         jint offset2;
 903         int flip2 = dom->as_If()->is_range_check(range2, index2, offset2);
 904         // See if this is a _matching_ range check, checking against
 905         // the same array bounds.
 906         if (flip2 == flip1 && range2 == range1 && index2 == index1 &&
 907             dom->outcnt() == 2) {
 908           if (nb_checks == 0 && dom->in(1) == in(1)) {
 909             // Found an immediately dominating test at the same offset.
 910             // This kind of back-to-back test can be eliminated locally,
 911             // and there is no need to search further for dominating tests.
 912             assert(offset2 == offset1, "Same test but different offsets");
 913             found_immediate_dominator = true;
 914             break;
 915           }
 916           // Gather expanded bounds
 917           off_lo = MIN2(off_lo,offset2);
 918           off_hi = MAX2(off_hi,offset2);
 919           // Record top NRC range checks
 920           prev_checks[nb_checks%NRC].ctl = prev_dom;
 921           prev_checks[nb_checks%NRC].off = offset2;
 922           nb_checks++;
 923         }
 924       }
 925       prev_dom = dom;
 926       dom = up_one_dom(dom);
 927       if (!dom) break;
 928     }
 929 
 930     if (!found_immediate_dominator) {
 931       // Attempt to widen the dominating range check to cover some later
 932       // ones.  Since range checks "fail" by uncommon-trapping to the
 933       // interpreter, widening a check can make us speculatively enter
 934       // the interpreter.  If we see range-check deopt's, do not widen!
 935       if (!phase->C->allow_range_check_smearing())  return NULL;
 936 
 937       // Didn't find prior covering check, so cannot remove anything.
 938       if (nb_checks == 0) {
 939         return NULL;
 940       }
 941       // Constant indices only need to check the upper bound.
 942       // Non-constant indices must check both low and high.
 943       int chk0 = (nb_checks - 1) % NRC;
 944       if (index1) {
 945         if (nb_checks == 1) {
 946           return NULL;
 947         } else {
 948           // If the top range check's constant is the min or max of
 949           // all constants we widen the next one to cover the whole
 950           // range of constants.
 951           RangeCheck rc0 = prev_checks[chk0];
 952           int chk1 = (nb_checks - 2) % NRC;
 953           RangeCheck rc1 = prev_checks[chk1];
 954           if (rc0.off == off_lo) {
 955             adjust_check(rc1.ctl, range1, index1, flip1, off_hi, igvn);
 956             prev_dom = rc1.ctl;
 957           } else if (rc0.off == off_hi) {
 958             adjust_check(rc1.ctl, range1, index1, flip1, off_lo, igvn);
 959             prev_dom = rc1.ctl;
 960           } else {
 961             // If the top test's constant is not the min or max of all
 962             // constants, we need 3 range checks. We must leave the
 963             // top test unchanged because widening it would allow the
 964             // accesses it protects to successfully read/write out of
 965             // bounds.
 966             if (nb_checks == 2) {
 967               return NULL;
 968             }
 969             int chk2 = (nb_checks - 3) % NRC;
 970             RangeCheck rc2 = prev_checks[chk2];
 971             // The top range check a+i covers interval: -a <= i < length-a
 972             // The second range check b+i covers interval: -b <= i < length-b
 973             if (rc1.off <= rc0.off) {
 974               // if b <= a, we change the second range check to:
 975               // -min_of_all_constants <= i < length-min_of_all_constants
 976               // Together top and second range checks now cover:
 977               // -min_of_all_constants <= i < length-a
 978               // which is more restrictive than -b <= i < length-b:
 979               // -b <= -min_of_all_constants <= i < length-a <= length-b
 980               // The third check is then changed to:
 981               // -max_of_all_constants <= i < length-max_of_all_constants
 982               // so 2nd and 3rd checks restrict allowed values of i to:
 983               // -min_of_all_constants <= i < length-max_of_all_constants
 984               adjust_check(rc1.ctl, range1, index1, flip1, off_lo, igvn);
 985               adjust_check(rc2.ctl, range1, index1, flip1, off_hi, igvn);
 986             } else {
 987               // if b > a, we change the second range check to:
 988               // -max_of_all_constants <= i < length-max_of_all_constants
 989               // Together top and second range checks now cover:
 990               // -a <= i < length-max_of_all_constants
 991               // which is more restrictive than -b <= i < length-b:
 992               // -b < -a <= i < length-max_of_all_constants <= length-b
 993               // The third check is then changed to:
 994               // -max_of_all_constants <= i < length-max_of_all_constants
 995               // so 2nd and 3rd checks restrict allowed values of i to:
 996               // -min_of_all_constants <= i < length-max_of_all_constants
 997               adjust_check(rc1.ctl, range1, index1, flip1, off_hi, igvn);
 998               adjust_check(rc2.ctl, range1, index1, flip1, off_lo, igvn);
 999             }
1000             prev_dom = rc2.ctl;
1001           }
1002         }
1003       } else {
1004         RangeCheck rc0 = prev_checks[chk0];
1005         // 'Widen' the offset of the 1st and only covering check
1006         adjust_check(rc0.ctl, range1, index1, flip1, off_hi, igvn);
1007         // Test is now covered by prior checks, dominate it out
1008         prev_dom = rc0.ctl;
1009       }
1010     }
1011 
1012   } else {                      // Scan for an equivalent test
1013 
1014     Node *cmp;
1015     int dist = 0;               // Cutoff limit for search
1016     int op = Opcode();
1017     if( op == Op_If &&
1018         (cmp=in(1)->in(1))->Opcode() == Op_CmpP ) {
1019       if( cmp->in(2) != NULL && // make sure cmp is not already dead
1020           cmp->in(2)->bottom_type() == TypePtr::NULL_PTR ) {
1021         dist = 64;              // Limit for null-pointer scans
1022       } else {
1023         dist = 4;               // Do not bother for random pointer tests
1024       }
1025     } else {
1026       dist = 4;                 // Limit for random junky scans
1027     }
1028 
1029     // Normal equivalent-test check.
1030     if( !dom ) return NULL;     // Dead loop?
1031 
1032     Node* result = fold_compares(phase);
1033     if (result != NULL) {
1034       return result;
1035     }
1036 
1037     // Search up the dominator tree for an If with an identical test
1038     while( dom->Opcode() != op    ||  // Not same opcode?
1039            dom->in(1)    != in(1) ||  // Not same input 1?
1040            (req() == 3 && dom->in(2) != in(2)) || // Not same input 2?
1041            prev_dom->in(0) != dom ) { // One path of test does not dominate?
1042       if( dist < 0 ) return NULL;
1043 
1044       dist--;
1045       prev_dom = dom;
1046       dom = up_one_dom( dom );
1047       if( !dom ) return NULL;
1048     }
1049 
1050     // Check that we did not follow a loop back to ourselves
1051     if( this == dom )
1052       return NULL;
1053 
1054     if( dist > 2 )              // Add to count of NULL checks elided
1055       explicit_null_checks_elided++;
1056 
1057   } // End of Else scan for an equivalent test
1058 
1059   // Hit!  Remove this IF
1060 #ifndef PRODUCT
1061   if( TraceIterativeGVN ) {
1062     tty->print("   Removing IfNode: "); this->dump();
1063   }
1064   if( VerifyOpto && !phase->allow_progress() ) {
1065     // Found an equivalent dominating test,
1066     // we can not guarantee reaching a fix-point for these during iterativeGVN
1067     // since intervening nodes may not change.
1068     return NULL;
1069   }
1070 #endif
1071 
1072   // Replace dominated IfNode
1073   dominated_by( prev_dom, igvn );
1074 
1075   // Must return either the original node (now dead) or a new node
1076   // (Do not return a top here, since that would break the uniqueness of top.)
1077   return new ConINode(TypeInt::ZERO);
1078 }
1079 
1080 //------------------------------dominated_by-----------------------------------
1081 void IfNode::dominated_by( Node *prev_dom, PhaseIterGVN *igvn ) {
1082   igvn->hash_delete(this);      // Remove self to prevent spurious V-N
1083   Node *idom = in(0);
1084   // Need opcode to decide which way 'this' test goes
1085   int prev_op = prev_dom->Opcode();
1086   Node *top = igvn->C->top(); // Shortcut to top
1087 
1088   // Loop predicates may have depending checks which should not
1089   // be skipped. For example, range check predicate has two checks
1090   // for lower and upper bounds.
1091   ProjNode* unc_proj = proj_out(1 - prev_dom->as_Proj()->_con)->as_Proj();
1092   if (unc_proj->is_uncommon_trap_proj(Deoptimization::Reason_predicate))
1093    prev_dom = idom;
1094 
1095   // Now walk the current IfNode's projections.
1096   // Loop ends when 'this' has no more uses.
1097   for (DUIterator_Last imin, i = last_outs(imin); i >= imin; --i) {
1098     Node *ifp = last_out(i);     // Get IfTrue/IfFalse
1099     igvn->add_users_to_worklist(ifp);
1100     // Check which projection it is and set target.
1101     // Data-target is either the dominating projection of the same type
1102     // or TOP if the dominating projection is of opposite type.
1103     // Data-target will be used as the new control edge for the non-CFG
1104     // nodes like Casts and Loads.
1105     Node *data_target = (ifp->Opcode() == prev_op) ? prev_dom : top;
1106     // Control-target is just the If's immediate dominator or TOP.
1107     Node *ctrl_target = (ifp->Opcode() == prev_op) ?     idom : top;
1108 
1109     // For each child of an IfTrue/IfFalse projection, reroute.
1110     // Loop ends when projection has no more uses.
1111     for (DUIterator_Last jmin, j = ifp->last_outs(jmin); j >= jmin; --j) {
1112       Node* s = ifp->last_out(j);   // Get child of IfTrue/IfFalse
1113       if( !s->depends_only_on_test() ) {
1114         // Find the control input matching this def-use edge.
1115         // For Regions it may not be in slot 0.
1116         uint l;
1117         for( l = 0; s->in(l) != ifp; l++ ) { }
1118         igvn->replace_input_of(s, l, ctrl_target);
1119       } else {                      // Else, for control producers,
1120         igvn->replace_input_of(s, 0, data_target); // Move child to data-target
1121       }
1122     } // End for each child of a projection
1123 
1124     igvn->remove_dead_node(ifp);
1125   } // End for each IfTrue/IfFalse child of If
1126 
1127   // Kill the IfNode
1128   igvn->remove_dead_node(this);
1129 }
1130 
1131 //------------------------------Identity---------------------------------------
1132 // If the test is constant & we match, then we are the input Control
1133 Node *IfProjNode::Identity(PhaseTransform *phase) {
1134   // Can only optimize if cannot go the other way
1135   const TypeTuple *t = phase->type(in(0))->is_tuple();
1136   if (t == TypeTuple::IFNEITHER ||
1137       // kill dead branch first otherwise the IfNode's control will
1138       // have 2 control uses (the IfNode that doesn't go away because
1139       // it still has uses and this branch of the
1140       // If). Node::has_special_unique_user() will cause this node to
1141       // be reprocessed once the dead branch is killed.
1142       (always_taken(t) && in(0)->outcnt() == 1)) {
1143     // IfNode control
1144     return in(0)->in(0);
1145   }
1146   // no progress
1147   return this;
1148 }
1149 
1150 //------------------------------dump_spec--------------------------------------
1151 #ifndef PRODUCT
1152 void IfNode::dump_spec(outputStream *st) const {
1153   st->print("P=%f, C=%f",_prob,_fcnt);
1154 }
1155 #endif
1156 
1157 //------------------------------idealize_test----------------------------------
1158 // Try to canonicalize tests better.  Peek at the Cmp/Bool/If sequence and
1159 // come up with a canonical sequence.  Bools getting 'eq', 'gt' and 'ge' forms
1160 // converted to 'ne', 'le' and 'lt' forms.  IfTrue/IfFalse get swapped as
1161 // needed.
1162 static IfNode* idealize_test(PhaseGVN* phase, IfNode* iff) {
1163   assert(iff->in(0) != NULL, "If must be live");
1164 
1165   if (iff->outcnt() != 2)  return NULL; // Malformed projections.
1166   Node* old_if_f = iff->proj_out(false);
1167   Node* old_if_t = iff->proj_out(true);
1168 
1169   // CountedLoopEnds want the back-control test to be TRUE, irregardless of
1170   // whether they are testing a 'gt' or 'lt' condition.  The 'gt' condition
1171   // happens in count-down loops
1172   if (iff->is_CountedLoopEnd())  return NULL;
1173   if (!iff->in(1)->is_Bool())  return NULL; // Happens for partially optimized IF tests
1174   BoolNode *b = iff->in(1)->as_Bool();
1175   BoolTest bt = b->_test;
1176   // Test already in good order?
1177   if( bt.is_canonical() )
1178     return NULL;
1179 
1180   // Flip test to be canonical.  Requires flipping the IfFalse/IfTrue and
1181   // cloning the IfNode.
1182   Node* new_b = phase->transform( new BoolNode(b->in(1), bt.negate()) );
1183   if( !new_b->is_Bool() ) return NULL;
1184   b = new_b->as_Bool();
1185 
1186   PhaseIterGVN *igvn = phase->is_IterGVN();
1187   assert( igvn, "Test is not canonical in parser?" );
1188 
1189   // The IF node never really changes, but it needs to be cloned
1190   iff = new IfNode( iff->in(0), b, 1.0-iff->_prob, iff->_fcnt);
1191 
1192   Node *prior = igvn->hash_find_insert(iff);
1193   if( prior ) {
1194     igvn->remove_dead_node(iff);
1195     iff = (IfNode*)prior;
1196   } else {
1197     // Cannot call transform on it just yet
1198     igvn->set_type_bottom(iff);
1199   }
1200   igvn->_worklist.push(iff);
1201 
1202   // Now handle projections.  Cloning not required.
1203   Node* new_if_f = (Node*)(new IfFalseNode( iff ));
1204   Node* new_if_t = (Node*)(new IfTrueNode ( iff ));
1205 
1206   igvn->register_new_node_with_optimizer(new_if_f);
1207   igvn->register_new_node_with_optimizer(new_if_t);
1208   // Flip test, so flip trailing control
1209   igvn->replace_node(old_if_f, new_if_t);
1210   igvn->replace_node(old_if_t, new_if_f);
1211 
1212   // Progress
1213   return iff;
1214 }