1 /*
   2  * Copyright (c) 1998, 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 "ci/ciMethodData.hpp"
  27 #include "classfile/systemDictionary.hpp"
  28 #include "classfile/vmSymbols.hpp"
  29 #include "compiler/compileLog.hpp"
  30 #include "interpreter/linkResolver.hpp"
  31 #include "memory/universe.inline.hpp"
  32 #include "opto/addnode.hpp"
  33 #include "opto/castnode.hpp"
  34 #include "opto/convertnode.hpp"
  35 #include "opto/divnode.hpp"
  36 #include "opto/idealGraphPrinter.hpp"
  37 #include "opto/matcher.hpp"
  38 #include "opto/memnode.hpp"
  39 #include "opto/mulnode.hpp"
  40 #include "opto/parse.hpp"
  41 #include "opto/runtime.hpp"
  42 #include "runtime/deoptimization.hpp"
  43 #include "runtime/sharedRuntime.hpp"
  44 
  45 extern int explicit_null_checks_inserted,
  46            explicit_null_checks_elided;
  47 
  48 //---------------------------------array_load----------------------------------
  49 void Parse::array_load(BasicType elem_type) {
  50   const Type* elem = Type::TOP;
  51   Node* adr = array_addressing(elem_type, 0, &elem);
  52   if (stopped())  return;     // guaranteed null or range check
  53   dec_sp(2);                  // Pop array and index
  54   const TypeAryPtr* adr_type = TypeAryPtr::get_array_body_type(elem_type);
  55   Node* ld = make_load(control(), adr, elem, elem_type, adr_type, MemNode::unordered);
  56   push(ld);
  57 }
  58 
  59 
  60 //--------------------------------array_store----------------------------------
  61 void Parse::array_store(BasicType elem_type) {
  62   Node* adr = array_addressing(elem_type, 1);
  63   if (stopped())  return;     // guaranteed null or range check
  64   Node* val = pop();
  65   dec_sp(2);                  // Pop array and index
  66   const TypeAryPtr* adr_type = TypeAryPtr::get_array_body_type(elem_type);
  67   store_to_memory(control(), adr, val, elem_type, adr_type, StoreNode::release_if_reference(elem_type));
  68 }
  69 
  70 
  71 //------------------------------array_addressing-------------------------------
  72 // Pull array and index from the stack.  Compute pointer-to-element.
  73 Node* Parse::array_addressing(BasicType type, int vals, const Type* *result2) {
  74   Node *idx   = peek(0+vals);   // Get from stack without popping
  75   Node *ary   = peek(1+vals);   // in case of exception
  76 
  77   // Null check the array base, with correct stack contents
  78   ary = null_check(ary, T_ARRAY);
  79   // Compile-time detect of null-exception?
  80   if (stopped())  return top();
  81 
  82   const TypeAryPtr* arytype  = _gvn.type(ary)->is_aryptr();
  83   const TypeInt*    sizetype = arytype->size();
  84   const Type*       elemtype = arytype->elem();
  85 
  86   if (UseUniqueSubclasses && result2 != NULL) {
  87     const Type* el = elemtype->make_ptr();
  88     if (el && el->isa_instptr()) {
  89       const TypeInstPtr* toop = el->is_instptr();
  90       if (toop->klass()->as_instance_klass()->unique_concrete_subklass()) {
  91         // If we load from "AbstractClass[]" we must see "ConcreteSubClass".
  92         const Type* subklass = Type::get_const_type(toop->klass());
  93         elemtype = subklass->join_speculative(el);
  94       }
  95     }
  96   }
  97 
  98   // Check for big class initializers with all constant offsets
  99   // feeding into a known-size array.
 100   const TypeInt* idxtype = _gvn.type(idx)->is_int();
 101   // See if the highest idx value is less than the lowest array bound,
 102   // and if the idx value cannot be negative:
 103   bool need_range_check = true;
 104   if (idxtype->_hi < sizetype->_lo && idxtype->_lo >= 0) {
 105     need_range_check = false;
 106     if (C->log() != NULL)   C->log()->elem("observe that='!need_range_check'");
 107   }
 108 
 109   ciKlass * arytype_klass = arytype->klass();
 110   if ((arytype_klass != NULL) && (!arytype_klass->is_loaded())) {
 111     // Only fails for some -Xcomp runs
 112     // The class is unloaded.  We have to run this bytecode in the interpreter.
 113     uncommon_trap(Deoptimization::Reason_unloaded,
 114                   Deoptimization::Action_reinterpret,
 115                   arytype->klass(), "!loaded array");
 116     return top();
 117   }
 118 
 119   // Do the range check
 120   if (GenerateRangeChecks && need_range_check) {
 121     Node* tst;
 122     if (sizetype->_hi <= 0) {
 123       // The greatest array bound is negative, so we can conclude that we're
 124       // compiling unreachable code, but the unsigned compare trick used below
 125       // only works with non-negative lengths.  Instead, hack "tst" to be zero so
 126       // the uncommon_trap path will always be taken.
 127       tst = _gvn.intcon(0);
 128     } else {
 129       // Range is constant in array-oop, so we can use the original state of mem
 130       Node* len = load_array_length(ary);
 131 
 132       // Test length vs index (standard trick using unsigned compare)
 133       Node* chk = _gvn.transform( new (C) CmpUNode(idx, len) );
 134       BoolTest::mask btest = BoolTest::lt;
 135       tst = _gvn.transform( new (C) BoolNode(chk, btest) );
 136     }
 137     // Branch to failure if out of bounds
 138     { BuildCutout unless(this, tst, PROB_MAX);
 139       if (C->allow_range_check_smearing()) {
 140         // Do not use builtin_throw, since range checks are sometimes
 141         // made more stringent by an optimistic transformation.
 142         // This creates "tentative" range checks at this point,
 143         // which are not guaranteed to throw exceptions.
 144         // See IfNode::Ideal, is_range_check, adjust_check.
 145         uncommon_trap(Deoptimization::Reason_range_check,
 146                       Deoptimization::Action_make_not_entrant,
 147                       NULL, "range_check");
 148       } else {
 149         // If we have already recompiled with the range-check-widening
 150         // heroic optimization turned off, then we must really be throwing
 151         // range check exceptions.
 152         builtin_throw(Deoptimization::Reason_range_check, idx);
 153       }
 154     }
 155   }
 156   // Check for always knowing you are throwing a range-check exception
 157   if (stopped())  return top();
 158 
 159   Node* ptr = array_element_address(ary, idx, type, sizetype);
 160 
 161   if (result2 != NULL)  *result2 = elemtype;
 162 
 163   assert(ptr != top(), "top should go hand-in-hand with stopped");
 164 
 165   return ptr;
 166 }
 167 
 168 
 169 // returns IfNode
 170 IfNode* Parse::jump_if_fork_int(Node* a, Node* b, BoolTest::mask mask) {
 171   Node   *cmp = _gvn.transform( new (C) CmpINode( a, b)); // two cases: shiftcount > 32 and shiftcount <= 32
 172   Node   *tst = _gvn.transform( new (C) BoolNode( cmp, mask));
 173   IfNode *iff = create_and_map_if( control(), tst, ((mask == BoolTest::eq) ? PROB_STATIC_INFREQUENT : PROB_FAIR), COUNT_UNKNOWN );
 174   return iff;
 175 }
 176 
 177 // return Region node
 178 Node* Parse::jump_if_join(Node* iffalse, Node* iftrue) {
 179   Node *region  = new (C) RegionNode(3); // 2 results
 180   record_for_igvn(region);
 181   region->init_req(1, iffalse);
 182   region->init_req(2, iftrue );
 183   _gvn.set_type(region, Type::CONTROL);
 184   region = _gvn.transform(region);
 185   set_control (region);
 186   return region;
 187 }
 188 
 189 
 190 //------------------------------helper for tableswitch-------------------------
 191 void Parse::jump_if_true_fork(IfNode *iff, int dest_bci_if_true, int prof_table_index) {
 192   // True branch, use existing map info
 193   { PreserveJVMState pjvms(this);
 194     Node *iftrue  = _gvn.transform( new (C) IfTrueNode (iff) );
 195     set_control( iftrue );
 196     profile_switch_case(prof_table_index);
 197     merge_new_path(dest_bci_if_true);
 198   }
 199 
 200   // False branch
 201   Node *iffalse = _gvn.transform( new (C) IfFalseNode(iff) );
 202   set_control( iffalse );
 203 }
 204 
 205 void Parse::jump_if_false_fork(IfNode *iff, int dest_bci_if_true, int prof_table_index) {
 206   // True branch, use existing map info
 207   { PreserveJVMState pjvms(this);
 208     Node *iffalse  = _gvn.transform( new (C) IfFalseNode (iff) );
 209     set_control( iffalse );
 210     profile_switch_case(prof_table_index);
 211     merge_new_path(dest_bci_if_true);
 212   }
 213 
 214   // False branch
 215   Node *iftrue = _gvn.transform( new (C) IfTrueNode(iff) );
 216   set_control( iftrue );
 217 }
 218 
 219 void Parse::jump_if_always_fork(int dest_bci, int prof_table_index) {
 220   // False branch, use existing map and control()
 221   profile_switch_case(prof_table_index);
 222   merge_new_path(dest_bci);
 223 }
 224 
 225 
 226 extern "C" {
 227   static int jint_cmp(const void *i, const void *j) {
 228     int a = *(jint *)i;
 229     int b = *(jint *)j;
 230     return a > b ? 1 : a < b ? -1 : 0;
 231   }
 232 }
 233 
 234 
 235 // Default value for methodData switch indexing. Must be a negative value to avoid
 236 // conflict with any legal switch index.
 237 #define NullTableIndex -1
 238 
 239 class SwitchRange : public StackObj {
 240   // a range of integers coupled with a bci destination
 241   jint _lo;                     // inclusive lower limit
 242   jint _hi;                     // inclusive upper limit
 243   int _dest;
 244   int _table_index;             // index into method data table
 245 
 246 public:
 247   jint lo() const              { return _lo;   }
 248   jint hi() const              { return _hi;   }
 249   int  dest() const            { return _dest; }
 250   int  table_index() const     { return _table_index; }
 251   bool is_singleton() const    { return _lo == _hi; }
 252 
 253   void setRange(jint lo, jint hi, int dest, int table_index) {
 254     assert(lo <= hi, "must be a non-empty range");
 255     _lo = lo, _hi = hi; _dest = dest; _table_index = table_index;
 256   }
 257   bool adjoinRange(jint lo, jint hi, int dest, int table_index) {
 258     assert(lo <= hi, "must be a non-empty range");
 259     if (lo == _hi+1 && dest == _dest && table_index == _table_index) {
 260       _hi = hi;
 261       return true;
 262     }
 263     return false;
 264   }
 265 
 266   void set (jint value, int dest, int table_index) {
 267     setRange(value, value, dest, table_index);
 268   }
 269   bool adjoin(jint value, int dest, int table_index) {
 270     return adjoinRange(value, value, dest, table_index);
 271   }
 272 
 273   void print() {
 274     if (is_singleton())
 275       tty->print(" {%d}=>%d", lo(), dest());
 276     else if (lo() == min_jint)
 277       tty->print(" {..%d}=>%d", hi(), dest());
 278     else if (hi() == max_jint)
 279       tty->print(" {%d..}=>%d", lo(), dest());
 280     else
 281       tty->print(" {%d..%d}=>%d", lo(), hi(), dest());
 282   }
 283 };
 284 
 285 
 286 //-------------------------------do_tableswitch--------------------------------
 287 void Parse::do_tableswitch() {
 288   Node* lookup = pop();
 289 
 290   // Get information about tableswitch
 291   int default_dest = iter().get_dest_table(0);
 292   int lo_index     = iter().get_int_table(1);
 293   int hi_index     = iter().get_int_table(2);
 294   int len          = hi_index - lo_index + 1;
 295 
 296   if (len < 1) {
 297     // If this is a backward branch, add safepoint
 298     maybe_add_safepoint(default_dest);
 299     merge(default_dest);
 300     return;
 301   }
 302 
 303   // generate decision tree, using trichotomy when possible
 304   int rnum = len+2;
 305   bool makes_backward_branch = false;
 306   SwitchRange* ranges = NEW_RESOURCE_ARRAY(SwitchRange, rnum);
 307   int rp = -1;
 308   if (lo_index != min_jint) {
 309     ranges[++rp].setRange(min_jint, lo_index-1, default_dest, NullTableIndex);
 310   }
 311   for (int j = 0; j < len; j++) {
 312     jint match_int = lo_index+j;
 313     int  dest      = iter().get_dest_table(j+3);
 314     makes_backward_branch |= (dest <= bci());
 315     int  table_index = method_data_update() ? j : NullTableIndex;
 316     if (rp < 0 || !ranges[rp].adjoin(match_int, dest, table_index)) {
 317       ranges[++rp].set(match_int, dest, table_index);
 318     }
 319   }
 320   jint highest = lo_index+(len-1);
 321   assert(ranges[rp].hi() == highest, "");
 322   if (highest != max_jint
 323       && !ranges[rp].adjoinRange(highest+1, max_jint, default_dest, NullTableIndex)) {
 324     ranges[++rp].setRange(highest+1, max_jint, default_dest, NullTableIndex);
 325   }
 326   assert(rp < len+2, "not too many ranges");
 327 
 328   // Safepoint in case if backward branch observed
 329   if( makes_backward_branch && UseLoopSafepoints )
 330     add_safepoint();
 331 
 332   jump_switch_ranges(lookup, &ranges[0], &ranges[rp]);
 333 }
 334 
 335 
 336 //------------------------------do_lookupswitch--------------------------------
 337 void Parse::do_lookupswitch() {
 338   Node *lookup = pop();         // lookup value
 339   // Get information about lookupswitch
 340   int default_dest = iter().get_dest_table(0);
 341   int len          = iter().get_int_table(1);
 342 
 343   if (len < 1) {    // If this is a backward branch, add safepoint
 344     maybe_add_safepoint(default_dest);
 345     merge(default_dest);
 346     return;
 347   }
 348 
 349   // generate decision tree, using trichotomy when possible
 350   jint* table = NEW_RESOURCE_ARRAY(jint, len*2);
 351   {
 352     for( int j = 0; j < len; j++ ) {
 353       table[j+j+0] = iter().get_int_table(2+j+j);
 354       table[j+j+1] = iter().get_dest_table(2+j+j+1);
 355     }
 356     qsort( table, len, 2*sizeof(table[0]), jint_cmp );
 357   }
 358 
 359   int rnum = len*2+1;
 360   bool makes_backward_branch = false;
 361   SwitchRange* ranges = NEW_RESOURCE_ARRAY(SwitchRange, rnum);
 362   int rp = -1;
 363   for( int j = 0; j < len; j++ ) {
 364     jint match_int   = table[j+j+0];
 365     int  dest        = table[j+j+1];
 366     int  next_lo     = rp < 0 ? min_jint : ranges[rp].hi()+1;
 367     int  table_index = method_data_update() ? j : NullTableIndex;
 368     makes_backward_branch |= (dest <= bci());
 369     if( match_int != next_lo ) {
 370       ranges[++rp].setRange(next_lo, match_int-1, default_dest, NullTableIndex);
 371     }
 372     if( rp < 0 || !ranges[rp].adjoin(match_int, dest, table_index) ) {
 373       ranges[++rp].set(match_int, dest, table_index);
 374     }
 375   }
 376   jint highest = table[2*(len-1)];
 377   assert(ranges[rp].hi() == highest, "");
 378   if( highest != max_jint
 379       && !ranges[rp].adjoinRange(highest+1, max_jint, default_dest, NullTableIndex) ) {
 380     ranges[++rp].setRange(highest+1, max_jint, default_dest, NullTableIndex);
 381   }
 382   assert(rp < rnum, "not too many ranges");
 383 
 384   // Safepoint in case backward branch observed
 385   if( makes_backward_branch && UseLoopSafepoints )
 386     add_safepoint();
 387 
 388   jump_switch_ranges(lookup, &ranges[0], &ranges[rp]);
 389 }
 390 
 391 //----------------------------create_jump_tables-------------------------------
 392 bool Parse::create_jump_tables(Node* key_val, SwitchRange* lo, SwitchRange* hi) {
 393   // Are jumptables enabled
 394   if (!UseJumpTables)  return false;
 395 
 396   // Are jumptables supported
 397   if (!Matcher::has_match_rule(Op_Jump))  return false;
 398 
 399   // Don't make jump table if profiling
 400   if (method_data_update())  return false;
 401 
 402   // Decide if a guard is needed to lop off big ranges at either (or
 403   // both) end(s) of the input set. We'll call this the default target
 404   // even though we can't be sure that it is the true "default".
 405 
 406   bool needs_guard = false;
 407   int default_dest;
 408   int64 total_outlier_size = 0;
 409   int64 hi_size = ((int64)hi->hi()) - ((int64)hi->lo()) + 1;
 410   int64 lo_size = ((int64)lo->hi()) - ((int64)lo->lo()) + 1;
 411 
 412   if (lo->dest() == hi->dest()) {
 413     total_outlier_size = hi_size + lo_size;
 414     default_dest = lo->dest();
 415   } else if (lo_size > hi_size) {
 416     total_outlier_size = lo_size;
 417     default_dest = lo->dest();
 418   } else {
 419     total_outlier_size = hi_size;
 420     default_dest = hi->dest();
 421   }
 422 
 423   // If a guard test will eliminate very sparse end ranges, then
 424   // it is worth the cost of an extra jump.
 425   if (total_outlier_size > (MaxJumpTableSparseness * 4)) {
 426     needs_guard = true;
 427     if (default_dest == lo->dest()) lo++;
 428     if (default_dest == hi->dest()) hi--;
 429   }
 430 
 431   // Find the total number of cases and ranges
 432   int64 num_cases = ((int64)hi->hi()) - ((int64)lo->lo()) + 1;
 433   int num_range = hi - lo + 1;
 434 
 435   // Don't create table if: too large, too small, or too sparse.
 436   if (num_cases < MinJumpTableSize || num_cases > MaxJumpTableSize)
 437     return false;
 438   if (num_cases > (MaxJumpTableSparseness * num_range))
 439     return false;
 440 
 441   // Normalize table lookups to zero
 442   int lowval = lo->lo();
 443   key_val = _gvn.transform( new (C) SubINode(key_val, _gvn.intcon(lowval)) );
 444 
 445   // Generate a guard to protect against input keyvals that aren't
 446   // in the switch domain.
 447   if (needs_guard) {
 448     Node*   size = _gvn.intcon(num_cases);
 449     Node*   cmp = _gvn.transform( new (C) CmpUNode(key_val, size) );
 450     Node*   tst = _gvn.transform( new (C) BoolNode(cmp, BoolTest::ge) );
 451     IfNode* iff = create_and_map_if( control(), tst, PROB_FAIR, COUNT_UNKNOWN);
 452     jump_if_true_fork(iff, default_dest, NullTableIndex);
 453   }
 454 
 455   // Create an ideal node JumpTable that has projections
 456   // of all possible ranges for a switch statement
 457   // The key_val input must be converted to a pointer offset and scaled.
 458   // Compare Parse::array_addressing above.
 459 #ifdef _LP64
 460   // Clean the 32-bit int into a real 64-bit offset.
 461   // Otherwise, the jint value 0 might turn into an offset of 0x0800000000.
 462   const TypeLong* lkeytype = TypeLong::make(CONST64(0), num_cases-1, Type::WidenMin);
 463   key_val       = _gvn.transform( new (C) ConvI2LNode(key_val, lkeytype) );
 464 #endif
 465   // Shift the value by wordsize so we have an index into the table, rather
 466   // than a switch value
 467   Node *shiftWord = _gvn.MakeConX(wordSize);
 468   key_val = _gvn.transform( new (C) MulXNode( key_val, shiftWord));
 469 
 470   // Create the JumpNode
 471   Node* jtn = _gvn.transform( new (C) JumpNode(control(), key_val, num_cases) );
 472 
 473   // These are the switch destinations hanging off the jumpnode
 474   int i = 0;
 475   for (SwitchRange* r = lo; r <= hi; r++) {
 476     for (int64 j = r->lo(); j <= r->hi(); j++, i++) {
 477       Node* input = _gvn.transform(new (C) JumpProjNode(jtn, i, r->dest(), (int)(j - lowval)));
 478       {
 479         PreserveJVMState pjvms(this);
 480         set_control(input);
 481         jump_if_always_fork(r->dest(), r->table_index());
 482       }
 483     }
 484   }
 485   assert(i == num_cases, "miscount of cases");
 486   stop_and_kill_map();  // no more uses for this JVMS
 487   return true;
 488 }
 489 
 490 //----------------------------jump_switch_ranges-------------------------------
 491 void Parse::jump_switch_ranges(Node* key_val, SwitchRange *lo, SwitchRange *hi, int switch_depth) {
 492   Block* switch_block = block();
 493 
 494   if (switch_depth == 0) {
 495     // Do special processing for the top-level call.
 496     assert(lo->lo() == min_jint, "initial range must exhaust Type::INT");
 497     assert(hi->hi() == max_jint, "initial range must exhaust Type::INT");
 498 
 499     // Decrement pred-numbers for the unique set of nodes.
 500 #ifdef ASSERT
 501     // Ensure that the block's successors are a (duplicate-free) set.
 502     int successors_counted = 0;  // block occurrences in [hi..lo]
 503     int unique_successors = switch_block->num_successors();
 504     for (int i = 0; i < unique_successors; i++) {
 505       Block* target = switch_block->successor_at(i);
 506 
 507       // Check that the set of successors is the same in both places.
 508       int successors_found = 0;
 509       for (SwitchRange* p = lo; p <= hi; p++) {
 510         if (p->dest() == target->start())  successors_found++;
 511       }
 512       assert(successors_found > 0, "successor must be known");
 513       successors_counted += successors_found;
 514     }
 515     assert(successors_counted == (hi-lo)+1, "no unexpected successors");
 516 #endif
 517 
 518     // Maybe prune the inputs, based on the type of key_val.
 519     jint min_val = min_jint;
 520     jint max_val = max_jint;
 521     const TypeInt* ti = key_val->bottom_type()->isa_int();
 522     if (ti != NULL) {
 523       min_val = ti->_lo;
 524       max_val = ti->_hi;
 525       assert(min_val <= max_val, "invalid int type");
 526     }
 527     while (lo->hi() < min_val)  lo++;
 528     if (lo->lo() < min_val)  lo->setRange(min_val, lo->hi(), lo->dest(), lo->table_index());
 529     while (hi->lo() > max_val)  hi--;
 530     if (hi->hi() > max_val)  hi->setRange(hi->lo(), max_val, hi->dest(), hi->table_index());
 531   }
 532 
 533 #ifndef PRODUCT
 534   if (switch_depth == 0) {
 535     _max_switch_depth = 0;
 536     _est_switch_depth = log2_intptr((hi-lo+1)-1)+1;
 537   }
 538 #endif
 539 
 540   assert(lo <= hi, "must be a non-empty set of ranges");
 541   if (lo == hi) {
 542     jump_if_always_fork(lo->dest(), lo->table_index());
 543   } else {
 544     assert(lo->hi() == (lo+1)->lo()-1, "contiguous ranges");
 545     assert(hi->lo() == (hi-1)->hi()+1, "contiguous ranges");
 546 
 547     if (create_jump_tables(key_val, lo, hi)) return;
 548 
 549     int nr = hi - lo + 1;
 550 
 551     SwitchRange* mid = lo + nr/2;
 552     // if there is an easy choice, pivot at a singleton:
 553     if (nr > 3 && !mid->is_singleton() && (mid-1)->is_singleton())  mid--;
 554 
 555     assert(lo < mid && mid <= hi, "good pivot choice");
 556     assert(nr != 2 || mid == hi,   "should pick higher of 2");
 557     assert(nr != 3 || mid == hi-1, "should pick middle of 3");
 558 
 559     Node *test_val = _gvn.intcon(mid->lo());
 560 
 561     if (mid->is_singleton()) {
 562       IfNode *iff_ne = jump_if_fork_int(key_val, test_val, BoolTest::ne);
 563       jump_if_false_fork(iff_ne, mid->dest(), mid->table_index());
 564 
 565       // Special Case:  If there are exactly three ranges, and the high
 566       // and low range each go to the same place, omit the "gt" test,
 567       // since it will not discriminate anything.
 568       bool eq_test_only = (hi == lo+2 && hi->dest() == lo->dest());
 569       if (eq_test_only) {
 570         assert(mid == hi-1, "");
 571       }
 572 
 573       // if there is a higher range, test for it and process it:
 574       if (mid < hi && !eq_test_only) {
 575         // two comparisons of same values--should enable 1 test for 2 branches
 576         // Use BoolTest::le instead of BoolTest::gt
 577         IfNode *iff_le  = jump_if_fork_int(key_val, test_val, BoolTest::le);
 578         Node   *iftrue  = _gvn.transform( new (C) IfTrueNode(iff_le) );
 579         Node   *iffalse = _gvn.transform( new (C) IfFalseNode(iff_le) );
 580         { PreserveJVMState pjvms(this);
 581           set_control(iffalse);
 582           jump_switch_ranges(key_val, mid+1, hi, switch_depth+1);
 583         }
 584         set_control(iftrue);
 585       }
 586 
 587     } else {
 588       // mid is a range, not a singleton, so treat mid..hi as a unit
 589       IfNode *iff_ge = jump_if_fork_int(key_val, test_val, BoolTest::ge);
 590 
 591       // if there is a higher range, test for it and process it:
 592       if (mid == hi) {
 593         jump_if_true_fork(iff_ge, mid->dest(), mid->table_index());
 594       } else {
 595         Node *iftrue  = _gvn.transform( new (C) IfTrueNode(iff_ge) );
 596         Node *iffalse = _gvn.transform( new (C) IfFalseNode(iff_ge) );
 597         { PreserveJVMState pjvms(this);
 598           set_control(iftrue);
 599           jump_switch_ranges(key_val, mid, hi, switch_depth+1);
 600         }
 601         set_control(iffalse);
 602       }
 603     }
 604 
 605     // in any case, process the lower range
 606     jump_switch_ranges(key_val, lo, mid-1, switch_depth+1);
 607   }
 608 
 609   // Decrease pred_count for each successor after all is done.
 610   if (switch_depth == 0) {
 611     int unique_successors = switch_block->num_successors();
 612     for (int i = 0; i < unique_successors; i++) {
 613       Block* target = switch_block->successor_at(i);
 614       // Throw away the pre-allocated path for each unique successor.
 615       target->next_path_num();
 616     }
 617   }
 618 
 619 #ifndef PRODUCT
 620   _max_switch_depth = MAX2(switch_depth, _max_switch_depth);
 621   if (TraceOptoParse && Verbose && WizardMode && switch_depth == 0) {
 622     SwitchRange* r;
 623     int nsing = 0;
 624     for( r = lo; r <= hi; r++ ) {
 625       if( r->is_singleton() )  nsing++;
 626     }
 627     tty->print(">>> ");
 628     _method->print_short_name();
 629     tty->print_cr(" switch decision tree");
 630     tty->print_cr("    %d ranges (%d singletons), max_depth=%d, est_depth=%d",
 631                   hi-lo+1, nsing, _max_switch_depth, _est_switch_depth);
 632     if (_max_switch_depth > _est_switch_depth) {
 633       tty->print_cr("******** BAD SWITCH DEPTH ********");
 634     }
 635     tty->print("   ");
 636     for( r = lo; r <= hi; r++ ) {
 637       r->print();
 638     }
 639     tty->print_cr("");
 640   }
 641 #endif
 642 }
 643 
 644 void Parse::modf() {
 645   Node *f2 = pop();
 646   Node *f1 = pop();
 647   Node* c = make_runtime_call(RC_LEAF, OptoRuntime::modf_Type(),
 648                               CAST_FROM_FN_PTR(address, SharedRuntime::frem),
 649                               "frem", NULL, //no memory effects
 650                               f1, f2);
 651   Node* res = _gvn.transform(new (C) ProjNode(c, TypeFunc::Parms + 0));
 652 
 653   push(res);
 654 }
 655 
 656 void Parse::modd() {
 657   Node *d2 = pop_pair();
 658   Node *d1 = pop_pair();
 659   Node* c = make_runtime_call(RC_LEAF, OptoRuntime::Math_DD_D_Type(),
 660                               CAST_FROM_FN_PTR(address, SharedRuntime::drem),
 661                               "drem", NULL, //no memory effects
 662                               d1, top(), d2, top());
 663   Node* res_d   = _gvn.transform(new (C) ProjNode(c, TypeFunc::Parms + 0));
 664 
 665 #ifdef ASSERT
 666   Node* res_top = _gvn.transform(new (C) ProjNode(c, TypeFunc::Parms + 1));
 667   assert(res_top == top(), "second value must be top");
 668 #endif
 669 
 670   push_pair(res_d);
 671 }
 672 
 673 void Parse::l2f() {
 674   Node* f2 = pop();
 675   Node* f1 = pop();
 676   Node* c = make_runtime_call(RC_LEAF, OptoRuntime::l2f_Type(),
 677                               CAST_FROM_FN_PTR(address, SharedRuntime::l2f),
 678                               "l2f", NULL, //no memory effects
 679                               f1, f2);
 680   Node* res = _gvn.transform(new (C) ProjNode(c, TypeFunc::Parms + 0));
 681 
 682   push(res);
 683 }
 684 
 685 void Parse::do_irem() {
 686   // Must keep both values on the expression-stack during null-check
 687   zero_check_int(peek());
 688   // Compile-time detect of null-exception?
 689   if (stopped())  return;
 690 
 691   Node* b = pop();
 692   Node* a = pop();
 693 
 694   const Type *t = _gvn.type(b);
 695   if (t != Type::TOP) {
 696     const TypeInt *ti = t->is_int();
 697     if (ti->is_con()) {
 698       int divisor = ti->get_con();
 699       // check for positive power of 2
 700       if (divisor > 0 &&
 701           (divisor & ~(divisor-1)) == divisor) {
 702         // yes !
 703         Node *mask = _gvn.intcon((divisor - 1));
 704         // Sigh, must handle negative dividends
 705         Node *zero = _gvn.intcon(0);
 706         IfNode *ifff = jump_if_fork_int(a, zero, BoolTest::lt);
 707         Node *iff = _gvn.transform( new (C) IfFalseNode(ifff) );
 708         Node *ift = _gvn.transform( new (C) IfTrueNode (ifff) );
 709         Node *reg = jump_if_join(ift, iff);
 710         Node *phi = PhiNode::make(reg, NULL, TypeInt::INT);
 711         // Negative path; negate/and/negate
 712         Node *neg = _gvn.transform( new (C) SubINode(zero, a) );
 713         Node *andn= _gvn.transform( new (C) AndINode(neg, mask) );
 714         Node *negn= _gvn.transform( new (C) SubINode(zero, andn) );
 715         phi->init_req(1, negn);
 716         // Fast positive case
 717         Node *andx = _gvn.transform( new (C) AndINode(a, mask) );
 718         phi->init_req(2, andx);
 719         // Push the merge
 720         push( _gvn.transform(phi) );
 721         return;
 722       }
 723     }
 724   }
 725   // Default case
 726   push( _gvn.transform( new (C) ModINode(control(),a,b) ) );
 727 }
 728 
 729 // Handle jsr and jsr_w bytecode
 730 void Parse::do_jsr() {
 731   assert(bc() == Bytecodes::_jsr || bc() == Bytecodes::_jsr_w, "wrong bytecode");
 732 
 733   // Store information about current state, tagged with new _jsr_bci
 734   int return_bci = iter().next_bci();
 735   int jsr_bci    = (bc() == Bytecodes::_jsr) ? iter().get_dest() : iter().get_far_dest();
 736 
 737   // Update method data
 738   profile_taken_branch(jsr_bci);
 739 
 740   // The way we do things now, there is only one successor block
 741   // for the jsr, because the target code is cloned by ciTypeFlow.
 742   Block* target = successor_for_bci(jsr_bci);
 743 
 744   // What got pushed?
 745   const Type* ret_addr = target->peek();
 746   assert(ret_addr->singleton(), "must be a constant (cloned jsr body)");
 747 
 748   // Effect on jsr on stack
 749   push(_gvn.makecon(ret_addr));
 750 
 751   // Flow to the jsr.
 752   merge(jsr_bci);
 753 }
 754 
 755 // Handle ret bytecode
 756 void Parse::do_ret() {
 757   // Find to whom we return.
 758   assert(block()->num_successors() == 1, "a ret can only go one place now");
 759   Block* target = block()->successor_at(0);
 760   assert(!target->is_ready(), "our arrival must be expected");
 761   profile_ret(target->flow()->start());
 762   int pnum = target->next_path_num();
 763   merge_common(target, pnum);
 764 }
 765 
 766 //--------------------------dynamic_branch_prediction--------------------------
 767 // Try to gather dynamic branch prediction behavior.  Return a probability
 768 // of the branch being taken and set the "cnt" field.  Returns a -1.0
 769 // if we need to use static prediction for some reason.
 770 float Parse::dynamic_branch_prediction(float &cnt) {
 771   ResourceMark rm;
 772 
 773   cnt  = COUNT_UNKNOWN;
 774 
 775   // Use MethodData information if it is available
 776   // FIXME: free the ProfileData structure
 777   ciMethodData* methodData = method()->method_data();
 778   if (!methodData->is_mature())  return PROB_UNKNOWN;
 779   ciProfileData* data = methodData->bci_to_data(bci());
 780   if (!data->is_JumpData())  return PROB_UNKNOWN;
 781 
 782   // get taken and not taken values
 783   int     taken = data->as_JumpData()->taken();
 784   int not_taken = 0;
 785   if (data->is_BranchData()) {
 786     not_taken = data->as_BranchData()->not_taken();
 787   }
 788 
 789   // scale the counts to be commensurate with invocation counts:
 790   taken = method()->scale_count(taken);
 791   not_taken = method()->scale_count(not_taken);
 792 
 793   // Give up if too few (or too many, in which case the sum will overflow) counts to be meaningful.
 794   // We also check that individual counters are positive first, overwise the sum can become positive.
 795   if (taken < 0 || not_taken < 0 || taken + not_taken < 40) {
 796     if (C->log() != NULL) {
 797       C->log()->elem("branch target_bci='%d' taken='%d' not_taken='%d'", iter().get_dest(), taken, not_taken);
 798     }
 799     return PROB_UNKNOWN;
 800   }
 801 
 802   // Compute frequency that we arrive here
 803   float sum = taken + not_taken;
 804   // Adjust, if this block is a cloned private block but the
 805   // Jump counts are shared.  Taken the private counts for
 806   // just this path instead of the shared counts.
 807   if( block()->count() > 0 )
 808     sum = block()->count();
 809   cnt = sum / FreqCountInvocations;
 810 
 811   // Pin probability to sane limits
 812   float prob;
 813   if( !taken )
 814     prob = (0+PROB_MIN) / 2;
 815   else if( !not_taken )
 816     prob = (1+PROB_MAX) / 2;
 817   else {                         // Compute probability of true path
 818     prob = (float)taken / (float)(taken + not_taken);
 819     if (prob > PROB_MAX)  prob = PROB_MAX;
 820     if (prob < PROB_MIN)   prob = PROB_MIN;
 821   }
 822 
 823   assert((cnt > 0.0f) && (prob > 0.0f),
 824          "Bad frequency assignment in if");
 825 
 826   if (C->log() != NULL) {
 827     const char* prob_str = NULL;
 828     if (prob >= PROB_MAX)  prob_str = (prob == PROB_MAX) ? "max" : "always";
 829     if (prob <= PROB_MIN)  prob_str = (prob == PROB_MIN) ? "min" : "never";
 830     char prob_str_buf[30];
 831     if (prob_str == NULL) {
 832       sprintf(prob_str_buf, "%g", prob);
 833       prob_str = prob_str_buf;
 834     }
 835     C->log()->elem("branch target_bci='%d' taken='%d' not_taken='%d' cnt='%g' prob='%s'",
 836                    iter().get_dest(), taken, not_taken, cnt, prob_str);
 837   }
 838   return prob;
 839 }
 840 
 841 //-----------------------------branch_prediction-------------------------------
 842 float Parse::branch_prediction(float& cnt,
 843                                BoolTest::mask btest,
 844                                int target_bci) {
 845   float prob = dynamic_branch_prediction(cnt);
 846   // If prob is unknown, switch to static prediction
 847   if (prob != PROB_UNKNOWN)  return prob;
 848 
 849   prob = PROB_FAIR;                   // Set default value
 850   if (btest == BoolTest::eq)          // Exactly equal test?
 851     prob = PROB_STATIC_INFREQUENT;    // Assume its relatively infrequent
 852   else if (btest == BoolTest::ne)
 853     prob = PROB_STATIC_FREQUENT;      // Assume its relatively frequent
 854 
 855   // If this is a conditional test guarding a backwards branch,
 856   // assume its a loop-back edge.  Make it a likely taken branch.
 857   if (target_bci < bci()) {
 858     if (is_osr_parse()) {    // Could be a hot OSR'd loop; force deopt
 859       // Since it's an OSR, we probably have profile data, but since
 860       // branch_prediction returned PROB_UNKNOWN, the counts are too small.
 861       // Let's make a special check here for completely zero counts.
 862       ciMethodData* methodData = method()->method_data();
 863       if (!methodData->is_empty()) {
 864         ciProfileData* data = methodData->bci_to_data(bci());
 865         // Only stop for truly zero counts, which mean an unknown part
 866         // of the OSR-ed method, and we want to deopt to gather more stats.
 867         // If you have ANY counts, then this loop is simply 'cold' relative
 868         // to the OSR loop.
 869         if (data->as_BranchData()->taken() +
 870             data->as_BranchData()->not_taken() == 0 ) {
 871           // This is the only way to return PROB_UNKNOWN:
 872           return PROB_UNKNOWN;
 873         }
 874       }
 875     }
 876     prob = PROB_STATIC_FREQUENT;     // Likely to take backwards branch
 877   }
 878 
 879   assert(prob != PROB_UNKNOWN, "must have some guess at this point");
 880   return prob;
 881 }
 882 
 883 // The magic constants are chosen so as to match the output of
 884 // branch_prediction() when the profile reports a zero taken count.
 885 // It is important to distinguish zero counts unambiguously, because
 886 // some branches (e.g., _213_javac.Assembler.eliminate) validly produce
 887 // very small but nonzero probabilities, which if confused with zero
 888 // counts would keep the program recompiling indefinitely.
 889 bool Parse::seems_never_taken(float prob) {
 890   return prob < PROB_MIN;
 891 }
 892 
 893 // True if the comparison seems to be the kind that will not change its
 894 // statistics from true to false.  See comments in adjust_map_after_if.
 895 // This question is only asked along paths which are already
 896 // classifed as untaken (by seems_never_taken), so really,
 897 // if a path is never taken, its controlling comparison is
 898 // already acting in a stable fashion.  If the comparison
 899 // seems stable, we will put an expensive uncommon trap
 900 // on the untaken path.  To be conservative, and to allow
 901 // partially executed counted loops to be compiled fully,
 902 // we will plant uncommon traps only after pointer comparisons.
 903 bool Parse::seems_stable_comparison(BoolTest::mask btest, Node* cmp) {
 904   for (int depth = 4; depth > 0; depth--) {
 905     // The following switch can find CmpP here over half the time for
 906     // dynamic language code rich with type tests.
 907     // Code using counted loops or array manipulations (typical
 908     // of benchmarks) will have many (>80%) CmpI instructions.
 909     switch (cmp->Opcode()) {
 910     case Op_CmpP:
 911       // A never-taken null check looks like CmpP/BoolTest::eq.
 912       // These certainly should be closed off as uncommon traps.
 913       if (btest == BoolTest::eq)
 914         return true;
 915       // A never-failed type check looks like CmpP/BoolTest::ne.
 916       // Let's put traps on those, too, so that we don't have to compile
 917       // unused paths with indeterminate dynamic type information.
 918       if (ProfileDynamicTypes)
 919         return true;
 920       return false;
 921 
 922     case Op_CmpI:
 923       // A small minority (< 10%) of CmpP are masked as CmpI,
 924       // as if by boolean conversion ((p == q? 1: 0) != 0).
 925       // Detect that here, even if it hasn't optimized away yet.
 926       // Specifically, this covers the 'instanceof' operator.
 927       if (btest == BoolTest::ne || btest == BoolTest::eq) {
 928         if (_gvn.type(cmp->in(2))->singleton() &&
 929             cmp->in(1)->is_Phi()) {
 930           PhiNode* phi = cmp->in(1)->as_Phi();
 931           int true_path = phi->is_diamond_phi();
 932           if (true_path > 0 &&
 933               _gvn.type(phi->in(1))->singleton() &&
 934               _gvn.type(phi->in(2))->singleton()) {
 935             // phi->region->if_proj->ifnode->bool->cmp
 936             BoolNode* bol = phi->in(0)->in(1)->in(0)->in(1)->as_Bool();
 937             btest = bol->_test._test;
 938             cmp = bol->in(1);
 939             continue;
 940           }
 941         }
 942       }
 943       return false;
 944     }
 945   }
 946   return false;
 947 }
 948 
 949 //-------------------------------repush_if_args--------------------------------
 950 // Push arguments of an "if" bytecode back onto the stack by adjusting _sp.
 951 inline int Parse::repush_if_args() {
 952 #ifndef PRODUCT
 953   if (PrintOpto && WizardMode) {
 954     tty->print("defending against excessive implicit null exceptions on %s @%d in ",
 955                Bytecodes::name(iter().cur_bc()), iter().cur_bci());
 956     method()->print_name(); tty->cr();
 957   }
 958 #endif
 959   int bc_depth = - Bytecodes::depth(iter().cur_bc());
 960   assert(bc_depth == 1 || bc_depth == 2, "only two kinds of branches");
 961   DEBUG_ONLY(sync_jvms());   // argument(n) requires a synced jvms
 962   assert(argument(0) != NULL, "must exist");
 963   assert(bc_depth == 1 || argument(1) != NULL, "two must exist");
 964   inc_sp(bc_depth);
 965   return bc_depth;
 966 }
 967 
 968 //----------------------------------do_ifnull----------------------------------
 969 void Parse::do_ifnull(BoolTest::mask btest, Node *c) {
 970   int target_bci = iter().get_dest();
 971 
 972   Block* branch_block = successor_for_bci(target_bci);
 973   Block* next_block   = successor_for_bci(iter().next_bci());
 974 
 975   float cnt;
 976   float prob = branch_prediction(cnt, btest, target_bci);
 977   if (prob == PROB_UNKNOWN) {
 978     // (An earlier version of do_ifnull omitted this trap for OSR methods.)
 979 #ifndef PRODUCT
 980     if (PrintOpto && Verbose)
 981       tty->print_cr("Never-taken edge stops compilation at bci %d",bci());
 982 #endif
 983     repush_if_args(); // to gather stats on loop
 984     // We need to mark this branch as taken so that if we recompile we will
 985     // see that it is possible. In the tiered system the interpreter doesn't
 986     // do profiling and by the time we get to the lower tier from the interpreter
 987     // the path may be cold again. Make sure it doesn't look untaken
 988     profile_taken_branch(target_bci, !ProfileInterpreter);
 989     uncommon_trap(Deoptimization::Reason_unreached,
 990                   Deoptimization::Action_reinterpret,
 991                   NULL, "cold");
 992     if (C->eliminate_boxing()) {
 993       // Mark the successor blocks as parsed
 994       branch_block->next_path_num();
 995       next_block->next_path_num();
 996     }
 997     return;
 998   }
 999 
1000   explicit_null_checks_inserted++;
1001 
1002   // Generate real control flow
1003   Node   *tst = _gvn.transform( new (C) BoolNode( c, btest ) );
1004 
1005   // Sanity check the probability value
1006   assert(prob > 0.0f,"Bad probability in Parser");
1007  // Need xform to put node in hash table
1008   IfNode *iff = create_and_xform_if( control(), tst, prob, cnt );
1009   assert(iff->_prob > 0.0f,"Optimizer made bad probability in parser");
1010   // True branch
1011   { PreserveJVMState pjvms(this);
1012     Node* iftrue  = _gvn.transform( new (C) IfTrueNode (iff) );
1013     set_control(iftrue);
1014 
1015     if (stopped()) {            // Path is dead?
1016       explicit_null_checks_elided++;
1017       if (C->eliminate_boxing()) {
1018         // Mark the successor block as parsed
1019         branch_block->next_path_num();
1020       }
1021     } else {                    // Path is live.
1022       // Update method data
1023       profile_taken_branch(target_bci);
1024       adjust_map_after_if(btest, c, prob, branch_block, next_block);
1025       if (!stopped()) {
1026         merge(target_bci);
1027       }
1028     }
1029   }
1030 
1031   // False branch
1032   Node* iffalse = _gvn.transform( new (C) IfFalseNode(iff) );
1033   set_control(iffalse);
1034 
1035   if (stopped()) {              // Path is dead?
1036     explicit_null_checks_elided++;
1037     if (C->eliminate_boxing()) {
1038       // Mark the successor block as parsed
1039       next_block->next_path_num();
1040     }
1041   } else  {                     // Path is live.
1042     // Update method data
1043     profile_not_taken_branch();
1044     adjust_map_after_if(BoolTest(btest).negate(), c, 1.0-prob,
1045                         next_block, branch_block);
1046   }
1047 }
1048 
1049 //------------------------------------do_if------------------------------------
1050 void Parse::do_if(BoolTest::mask btest, Node* c) {
1051   int target_bci = iter().get_dest();
1052 
1053   Block* branch_block = successor_for_bci(target_bci);
1054   Block* next_block   = successor_for_bci(iter().next_bci());
1055 
1056   float cnt;
1057   float prob = branch_prediction(cnt, btest, target_bci);
1058   float untaken_prob = 1.0 - prob;
1059 
1060   if (prob == PROB_UNKNOWN) {
1061 #ifndef PRODUCT
1062     if (PrintOpto && Verbose)
1063       tty->print_cr("Never-taken edge stops compilation at bci %d",bci());
1064 #endif
1065     repush_if_args(); // to gather stats on loop
1066     // We need to mark this branch as taken so that if we recompile we will
1067     // see that it is possible. In the tiered system the interpreter doesn't
1068     // do profiling and by the time we get to the lower tier from the interpreter
1069     // the path may be cold again. Make sure it doesn't look untaken
1070     profile_taken_branch(target_bci, !ProfileInterpreter);
1071     uncommon_trap(Deoptimization::Reason_unreached,
1072                   Deoptimization::Action_reinterpret,
1073                   NULL, "cold");
1074     if (C->eliminate_boxing()) {
1075       // Mark the successor blocks as parsed
1076       branch_block->next_path_num();
1077       next_block->next_path_num();
1078     }
1079     return;
1080   }
1081 
1082   // Sanity check the probability value
1083   assert(0.0f < prob && prob < 1.0f,"Bad probability in Parser");
1084 
1085   bool taken_if_true = true;
1086   // Convert BoolTest to canonical form:
1087   if (!BoolTest(btest).is_canonical()) {
1088     btest         = BoolTest(btest).negate();
1089     taken_if_true = false;
1090     // prob is NOT updated here; it remains the probability of the taken
1091     // path (as opposed to the prob of the path guarded by an 'IfTrueNode').
1092   }
1093   assert(btest != BoolTest::eq, "!= is the only canonical exact test");
1094 
1095   Node* tst0 = new (C) BoolNode(c, btest);
1096   Node* tst = _gvn.transform(tst0);
1097   BoolTest::mask taken_btest   = BoolTest::illegal;
1098   BoolTest::mask untaken_btest = BoolTest::illegal;
1099 
1100   if (tst->is_Bool()) {
1101     // Refresh c from the transformed bool node, since it may be
1102     // simpler than the original c.  Also re-canonicalize btest.
1103     // This wins when (Bool ne (Conv2B p) 0) => (Bool ne (CmpP p NULL)).
1104     // That can arise from statements like: if (x instanceof C) ...
1105     if (tst != tst0) {
1106       // Canonicalize one more time since transform can change it.
1107       btest = tst->as_Bool()->_test._test;
1108       if (!BoolTest(btest).is_canonical()) {
1109         // Reverse edges one more time...
1110         tst   = _gvn.transform( tst->as_Bool()->negate(&_gvn) );
1111         btest = tst->as_Bool()->_test._test;
1112         assert(BoolTest(btest).is_canonical(), "sanity");
1113         taken_if_true = !taken_if_true;
1114       }
1115       c = tst->in(1);
1116     }
1117     BoolTest::mask neg_btest = BoolTest(btest).negate();
1118     taken_btest   = taken_if_true ?     btest : neg_btest;
1119     untaken_btest = taken_if_true ? neg_btest :     btest;
1120   }
1121 
1122   // Generate real control flow
1123   float true_prob = (taken_if_true ? prob : untaken_prob);
1124   IfNode* iff = create_and_map_if(control(), tst, true_prob, cnt);
1125   assert(iff->_prob > 0.0f,"Optimizer made bad probability in parser");
1126   Node* taken_branch   = new (C) IfTrueNode(iff);
1127   Node* untaken_branch = new (C) IfFalseNode(iff);
1128   if (!taken_if_true) {  // Finish conversion to canonical form
1129     Node* tmp      = taken_branch;
1130     taken_branch   = untaken_branch;
1131     untaken_branch = tmp;
1132   }
1133 
1134   // Branch is taken:
1135   { PreserveJVMState pjvms(this);
1136     taken_branch = _gvn.transform(taken_branch);
1137     set_control(taken_branch);
1138 
1139     if (stopped()) {
1140       if (C->eliminate_boxing()) {
1141         // Mark the successor block as parsed
1142         branch_block->next_path_num();
1143       }
1144     } else {
1145       // Update method data
1146       profile_taken_branch(target_bci);
1147       adjust_map_after_if(taken_btest, c, prob, branch_block, next_block);
1148       if (!stopped()) {
1149         merge(target_bci);
1150       }
1151     }
1152   }
1153 
1154   untaken_branch = _gvn.transform(untaken_branch);
1155   set_control(untaken_branch);
1156 
1157   // Branch not taken.
1158   if (stopped()) {
1159     if (C->eliminate_boxing()) {
1160       // Mark the successor block as parsed
1161       next_block->next_path_num();
1162     }
1163   } else {
1164     // Update method data
1165     profile_not_taken_branch();
1166     adjust_map_after_if(untaken_btest, c, untaken_prob,
1167                         next_block, branch_block);
1168   }
1169 }
1170 
1171 //----------------------------adjust_map_after_if------------------------------
1172 // Adjust the JVM state to reflect the result of taking this path.
1173 // Basically, it means inspecting the CmpNode controlling this
1174 // branch, seeing how it constrains a tested value, and then
1175 // deciding if it's worth our while to encode this constraint
1176 // as graph nodes in the current abstract interpretation map.
1177 void Parse::adjust_map_after_if(BoolTest::mask btest, Node* c, float prob,
1178                                 Block* path, Block* other_path) {
1179   if (stopped() || !c->is_Cmp() || btest == BoolTest::illegal)
1180     return;                             // nothing to do
1181 
1182   bool is_fallthrough = (path == successor_for_bci(iter().next_bci()));
1183 
1184   if (seems_never_taken(prob) && seems_stable_comparison(btest, c)) {
1185     // If this might possibly turn into an implicit null check,
1186     // and the null has never yet been seen, we need to generate
1187     // an uncommon trap, so as to recompile instead of suffering
1188     // with very slow branches.  (We'll get the slow branches if
1189     // the program ever changes phase and starts seeing nulls here.)
1190     //
1191     // We do not inspect for a null constant, since a node may
1192     // optimize to 'null' later on.
1193     //
1194     // Null checks, and other tests which expect inequality,
1195     // show btest == BoolTest::eq along the non-taken branch.
1196     // On the other hand, type tests, must-be-null tests,
1197     // and other tests which expect pointer equality,
1198     // show btest == BoolTest::ne along the non-taken branch.
1199     // We prune both types of branches if they look unused.
1200     repush_if_args();
1201     // We need to mark this branch as taken so that if we recompile we will
1202     // see that it is possible. In the tiered system the interpreter doesn't
1203     // do profiling and by the time we get to the lower tier from the interpreter
1204     // the path may be cold again. Make sure it doesn't look untaken
1205     if (is_fallthrough) {
1206       profile_not_taken_branch(!ProfileInterpreter);
1207     } else {
1208       profile_taken_branch(iter().get_dest(), !ProfileInterpreter);
1209     }
1210     uncommon_trap(Deoptimization::Reason_unreached,
1211                   Deoptimization::Action_reinterpret,
1212                   NULL,
1213                   (is_fallthrough ? "taken always" : "taken never"));
1214     return;
1215   }
1216 
1217   Node* val = c->in(1);
1218   Node* con = c->in(2);
1219   const Type* tcon = _gvn.type(con);
1220   const Type* tval = _gvn.type(val);
1221   bool have_con = tcon->singleton();
1222   if (tval->singleton()) {
1223     if (!have_con) {
1224       // Swap, so constant is in con.
1225       con  = val;
1226       tcon = tval;
1227       val  = c->in(2);
1228       tval = _gvn.type(val);
1229       btest = BoolTest(btest).commute();
1230       have_con = true;
1231     } else {
1232       // Do we have two constants?  Then leave well enough alone.
1233       have_con = false;
1234     }
1235   }
1236   if (!have_con)                        // remaining adjustments need a con
1237     return;
1238 
1239   sharpen_type_after_if(btest, con, tcon, val, tval);
1240 }
1241 
1242 
1243 static Node* extract_obj_from_klass_load(PhaseGVN* gvn, Node* n) {
1244   Node* ldk;
1245   if (n->is_DecodeNKlass()) {
1246     if (n->in(1)->Opcode() != Op_LoadNKlass) {
1247       return NULL;
1248     } else {
1249       ldk = n->in(1);
1250     }
1251   } else if (n->Opcode() != Op_LoadKlass) {
1252     return NULL;
1253   } else {
1254     ldk = n;
1255   }
1256   assert(ldk != NULL && ldk->is_Load(), "should have found a LoadKlass or LoadNKlass node");
1257 
1258   Node* adr = ldk->in(MemNode::Address);
1259   intptr_t off = 0;
1260   Node* obj = AddPNode::Ideal_base_and_offset(adr, gvn, off);
1261   if (obj == NULL || off != oopDesc::klass_offset_in_bytes()) // loading oopDesc::_klass?
1262     return NULL;
1263   const TypePtr* tp = gvn->type(obj)->is_ptr();
1264   if (tp == NULL || !(tp->isa_instptr() || tp->isa_aryptr())) // is obj a Java object ptr?
1265     return NULL;
1266 
1267   return obj;
1268 }
1269 
1270 void Parse::sharpen_type_after_if(BoolTest::mask btest,
1271                                   Node* con, const Type* tcon,
1272                                   Node* val, const Type* tval) {
1273   // Look for opportunities to sharpen the type of a node
1274   // whose klass is compared with a constant klass.
1275   if (btest == BoolTest::eq && tcon->isa_klassptr()) {
1276     Node* obj = extract_obj_from_klass_load(&_gvn, val);
1277     const TypeOopPtr* con_type = tcon->isa_klassptr()->as_instance_type();
1278     if (obj != NULL && (con_type->isa_instptr() || con_type->isa_aryptr())) {
1279        // Found:
1280        //   Bool(CmpP(LoadKlass(obj._klass), ConP(Foo.klass)), [eq])
1281        // or the narrowOop equivalent.
1282        const Type* obj_type = _gvn.type(obj);
1283        const TypeOopPtr* tboth = obj_type->join_speculative(con_type)->isa_oopptr();
1284        if (tboth != NULL && tboth->klass_is_exact() && tboth != obj_type &&
1285            tboth->higher_equal(obj_type)) {
1286           // obj has to be of the exact type Foo if the CmpP succeeds.
1287           int obj_in_map = map()->find_edge(obj);
1288           JVMState* jvms = this->jvms();
1289           if (obj_in_map >= 0 &&
1290               (jvms->is_loc(obj_in_map) || jvms->is_stk(obj_in_map))) {
1291             TypeNode* ccast = new (C) CheckCastPPNode(control(), obj, tboth);
1292             const Type* tcc = ccast->as_Type()->type();
1293             assert(tcc != obj_type && tcc->higher_equal_speculative(obj_type), "must improve");
1294             // Delay transform() call to allow recovery of pre-cast value
1295             // at the control merge.
1296             _gvn.set_type_bottom(ccast);
1297             record_for_igvn(ccast);
1298             // Here's the payoff.
1299             replace_in_map(obj, ccast);
1300           }
1301        }
1302     }
1303   }
1304 
1305   int val_in_map = map()->find_edge(val);
1306   if (val_in_map < 0)  return;          // replace_in_map would be useless
1307   {
1308     JVMState* jvms = this->jvms();
1309     if (!(jvms->is_loc(val_in_map) ||
1310           jvms->is_stk(val_in_map)))
1311       return;                           // again, it would be useless
1312   }
1313 
1314   // Check for a comparison to a constant, and "know" that the compared
1315   // value is constrained on this path.
1316   assert(tcon->singleton(), "");
1317   ConstraintCastNode* ccast = NULL;
1318   Node* cast = NULL;
1319 
1320   switch (btest) {
1321   case BoolTest::eq:                    // Constant test?
1322     {
1323       const Type* tboth = tcon->join_speculative(tval);
1324       if (tboth == tval)  break;        // Nothing to gain.
1325       if (tcon->isa_int()) {
1326         ccast = new (C) CastIINode(val, tboth);
1327       } else if (tcon == TypePtr::NULL_PTR) {
1328         // Cast to null, but keep the pointer identity temporarily live.
1329         ccast = new (C) CastPPNode(val, tboth);
1330       } else {
1331         const TypeF* tf = tcon->isa_float_constant();
1332         const TypeD* td = tcon->isa_double_constant();
1333         // Exclude tests vs float/double 0 as these could be
1334         // either +0 or -0.  Just because you are equal to +0
1335         // doesn't mean you ARE +0!
1336         // Note, following code also replaces Long and Oop values.
1337         if ((!tf || tf->_f != 0.0) &&
1338             (!td || td->_d != 0.0))
1339           cast = con;                   // Replace non-constant val by con.
1340       }
1341     }
1342     break;
1343 
1344   case BoolTest::ne:
1345     if (tcon == TypePtr::NULL_PTR) {
1346       cast = cast_not_null(val, false);
1347     }
1348     break;
1349 
1350   default:
1351     // (At this point we could record int range types with CastII.)
1352     break;
1353   }
1354 
1355   if (ccast != NULL) {
1356     const Type* tcc = ccast->as_Type()->type();
1357     assert(tcc != tval && tcc->higher_equal_speculative(tval), "must improve");
1358     // Delay transform() call to allow recovery of pre-cast value
1359     // at the control merge.
1360     ccast->set_req(0, control());
1361     _gvn.set_type_bottom(ccast);
1362     record_for_igvn(ccast);
1363     cast = ccast;
1364   }
1365 
1366   if (cast != NULL) {                   // Here's the payoff.
1367     replace_in_map(val, cast);
1368   }
1369 }
1370 
1371 /**
1372  * Use speculative type to optimize CmpP node: if comparison is
1373  * against the low level class, cast the object to the speculative
1374  * type if any. CmpP should then go away.
1375  *
1376  * @param c  expected CmpP node
1377  * @return   result of CmpP on object casted to speculative type
1378  *
1379  */
1380 Node* Parse::optimize_cmp_with_klass(Node* c) {
1381   // If this is transformed by the _gvn to a comparison with the low
1382   // level klass then we may be able to use speculation
1383   if (c->Opcode() == Op_CmpP &&
1384       (c->in(1)->Opcode() == Op_LoadKlass || c->in(1)->Opcode() == Op_DecodeNKlass) &&
1385       c->in(2)->is_Con()) {
1386     Node* load_klass = NULL;
1387     Node* decode = NULL;
1388     if (c->in(1)->Opcode() == Op_DecodeNKlass) {
1389       decode = c->in(1);
1390       load_klass = c->in(1)->in(1);
1391     } else {
1392       load_klass = c->in(1);
1393     }
1394     if (load_klass->in(2)->is_AddP()) {
1395       Node* addp = load_klass->in(2);
1396       Node* obj = addp->in(AddPNode::Address);
1397       const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();
1398       if (obj_type->speculative_type() != NULL) {
1399         ciKlass* k = obj_type->speculative_type();
1400         inc_sp(2);
1401         obj = maybe_cast_profiled_obj(obj, k);
1402         dec_sp(2);
1403         // Make the CmpP use the casted obj
1404         addp = basic_plus_adr(obj, addp->in(AddPNode::Offset));
1405         load_klass = load_klass->clone();
1406         load_klass->set_req(2, addp);
1407         load_klass = _gvn.transform(load_klass);
1408         if (decode != NULL) {
1409           decode = decode->clone();
1410           decode->set_req(1, load_klass);
1411           load_klass = _gvn.transform(decode);
1412         }
1413         c = c->clone();
1414         c->set_req(1, load_klass);
1415         c = _gvn.transform(c);
1416       }
1417     }
1418   }
1419   return c;
1420 }
1421 
1422 //------------------------------do_one_bytecode--------------------------------
1423 // Parse this bytecode, and alter the Parsers JVM->Node mapping
1424 void Parse::do_one_bytecode() {
1425   Node *a, *b, *c, *d;          // Handy temps
1426   BoolTest::mask btest;
1427   int i;
1428 
1429   assert(!has_exceptions(), "bytecode entry state must be clear of throws");
1430 
1431   if (C->check_node_count(NodeLimitFudgeFactor * 5,
1432                           "out of nodes parsing method")) {
1433     return;
1434   }
1435 
1436 #ifdef ASSERT
1437   // for setting breakpoints
1438   if (TraceOptoParse) {
1439     tty->print(" @");
1440     dump_bci(bci());
1441     tty->cr();
1442   }
1443 #endif
1444 
1445   switch (bc()) {
1446   case Bytecodes::_nop:
1447     // do nothing
1448     break;
1449   case Bytecodes::_lconst_0:
1450     push_pair(longcon(0));
1451     break;
1452 
1453   case Bytecodes::_lconst_1:
1454     push_pair(longcon(1));
1455     break;
1456 
1457   case Bytecodes::_fconst_0:
1458     push(zerocon(T_FLOAT));
1459     break;
1460 
1461   case Bytecodes::_fconst_1:
1462     push(makecon(TypeF::ONE));
1463     break;
1464 
1465   case Bytecodes::_fconst_2:
1466     push(makecon(TypeF::make(2.0f)));
1467     break;
1468 
1469   case Bytecodes::_dconst_0:
1470     push_pair(zerocon(T_DOUBLE));
1471     break;
1472 
1473   case Bytecodes::_dconst_1:
1474     push_pair(makecon(TypeD::ONE));
1475     break;
1476 
1477   case Bytecodes::_iconst_m1:push(intcon(-1)); break;
1478   case Bytecodes::_iconst_0: push(intcon( 0)); break;
1479   case Bytecodes::_iconst_1: push(intcon( 1)); break;
1480   case Bytecodes::_iconst_2: push(intcon( 2)); break;
1481   case Bytecodes::_iconst_3: push(intcon( 3)); break;
1482   case Bytecodes::_iconst_4: push(intcon( 4)); break;
1483   case Bytecodes::_iconst_5: push(intcon( 5)); break;
1484   case Bytecodes::_bipush:   push(intcon(iter().get_constant_u1())); break;
1485   case Bytecodes::_sipush:   push(intcon(iter().get_constant_u2())); break;
1486   case Bytecodes::_aconst_null: push(null());  break;
1487   case Bytecodes::_ldc:
1488   case Bytecodes::_ldc_w:
1489   case Bytecodes::_ldc2_w:
1490     // If the constant is unresolved, run this BC once in the interpreter.
1491     {
1492       ciConstant constant = iter().get_constant();
1493       if (constant.basic_type() == T_OBJECT &&
1494           !constant.as_object()->is_loaded()) {
1495         int index = iter().get_constant_pool_index();
1496         constantTag tag = iter().get_constant_pool_tag(index);
1497         uncommon_trap(Deoptimization::make_trap_request
1498                       (Deoptimization::Reason_unloaded,
1499                        Deoptimization::Action_reinterpret,
1500                        index),
1501                       NULL, tag.internal_name());
1502         break;
1503       }
1504       assert(constant.basic_type() != T_OBJECT || constant.as_object()->is_instance(),
1505              "must be java_mirror of klass");
1506       bool pushed = push_constant(constant, true);
1507       guarantee(pushed, "must be possible to push this constant");
1508     }
1509 
1510     break;
1511 
1512   case Bytecodes::_aload_0:
1513     push( local(0) );
1514     break;
1515   case Bytecodes::_aload_1:
1516     push( local(1) );
1517     break;
1518   case Bytecodes::_aload_2:
1519     push( local(2) );
1520     break;
1521   case Bytecodes::_aload_3:
1522     push( local(3) );
1523     break;
1524   case Bytecodes::_aload:
1525     push( local(iter().get_index()) );
1526     break;
1527 
1528   case Bytecodes::_fload_0:
1529   case Bytecodes::_iload_0:
1530     push( local(0) );
1531     break;
1532   case Bytecodes::_fload_1:
1533   case Bytecodes::_iload_1:
1534     push( local(1) );
1535     break;
1536   case Bytecodes::_fload_2:
1537   case Bytecodes::_iload_2:
1538     push( local(2) );
1539     break;
1540   case Bytecodes::_fload_3:
1541   case Bytecodes::_iload_3:
1542     push( local(3) );
1543     break;
1544   case Bytecodes::_fload:
1545   case Bytecodes::_iload:
1546     push( local(iter().get_index()) );
1547     break;
1548   case Bytecodes::_lload_0:
1549     push_pair_local( 0 );
1550     break;
1551   case Bytecodes::_lload_1:
1552     push_pair_local( 1 );
1553     break;
1554   case Bytecodes::_lload_2:
1555     push_pair_local( 2 );
1556     break;
1557   case Bytecodes::_lload_3:
1558     push_pair_local( 3 );
1559     break;
1560   case Bytecodes::_lload:
1561     push_pair_local( iter().get_index() );
1562     break;
1563 
1564   case Bytecodes::_dload_0:
1565     push_pair_local(0);
1566     break;
1567   case Bytecodes::_dload_1:
1568     push_pair_local(1);
1569     break;
1570   case Bytecodes::_dload_2:
1571     push_pair_local(2);
1572     break;
1573   case Bytecodes::_dload_3:
1574     push_pair_local(3);
1575     break;
1576   case Bytecodes::_dload:
1577     push_pair_local(iter().get_index());
1578     break;
1579   case Bytecodes::_fstore_0:
1580   case Bytecodes::_istore_0:
1581   case Bytecodes::_astore_0:
1582     set_local( 0, pop() );
1583     break;
1584   case Bytecodes::_fstore_1:
1585   case Bytecodes::_istore_1:
1586   case Bytecodes::_astore_1:
1587     set_local( 1, pop() );
1588     break;
1589   case Bytecodes::_fstore_2:
1590   case Bytecodes::_istore_2:
1591   case Bytecodes::_astore_2:
1592     set_local( 2, pop() );
1593     break;
1594   case Bytecodes::_fstore_3:
1595   case Bytecodes::_istore_3:
1596   case Bytecodes::_astore_3:
1597     set_local( 3, pop() );
1598     break;
1599   case Bytecodes::_fstore:
1600   case Bytecodes::_istore:
1601   case Bytecodes::_astore:
1602     set_local( iter().get_index(), pop() );
1603     break;
1604   // long stores
1605   case Bytecodes::_lstore_0:
1606     set_pair_local( 0, pop_pair() );
1607     break;
1608   case Bytecodes::_lstore_1:
1609     set_pair_local( 1, pop_pair() );
1610     break;
1611   case Bytecodes::_lstore_2:
1612     set_pair_local( 2, pop_pair() );
1613     break;
1614   case Bytecodes::_lstore_3:
1615     set_pair_local( 3, pop_pair() );
1616     break;
1617   case Bytecodes::_lstore:
1618     set_pair_local( iter().get_index(), pop_pair() );
1619     break;
1620 
1621   // double stores
1622   case Bytecodes::_dstore_0:
1623     set_pair_local( 0, dstore_rounding(pop_pair()) );
1624     break;
1625   case Bytecodes::_dstore_1:
1626     set_pair_local( 1, dstore_rounding(pop_pair()) );
1627     break;
1628   case Bytecodes::_dstore_2:
1629     set_pair_local( 2, dstore_rounding(pop_pair()) );
1630     break;
1631   case Bytecodes::_dstore_3:
1632     set_pair_local( 3, dstore_rounding(pop_pair()) );
1633     break;
1634   case Bytecodes::_dstore:
1635     set_pair_local( iter().get_index(), dstore_rounding(pop_pair()) );
1636     break;
1637 
1638   case Bytecodes::_pop:  dec_sp(1);   break;
1639   case Bytecodes::_pop2: dec_sp(2);   break;
1640   case Bytecodes::_swap:
1641     a = pop();
1642     b = pop();
1643     push(a);
1644     push(b);
1645     break;
1646   case Bytecodes::_dup:
1647     a = pop();
1648     push(a);
1649     push(a);
1650     break;
1651   case Bytecodes::_dup_x1:
1652     a = pop();
1653     b = pop();
1654     push( a );
1655     push( b );
1656     push( a );
1657     break;
1658   case Bytecodes::_dup_x2:
1659     a = pop();
1660     b = pop();
1661     c = pop();
1662     push( a );
1663     push( c );
1664     push( b );
1665     push( a );
1666     break;
1667   case Bytecodes::_dup2:
1668     a = pop();
1669     b = pop();
1670     push( b );
1671     push( a );
1672     push( b );
1673     push( a );
1674     break;
1675 
1676   case Bytecodes::_dup2_x1:
1677     // before: .. c, b, a
1678     // after:  .. b, a, c, b, a
1679     // not tested
1680     a = pop();
1681     b = pop();
1682     c = pop();
1683     push( b );
1684     push( a );
1685     push( c );
1686     push( b );
1687     push( a );
1688     break;
1689   case Bytecodes::_dup2_x2:
1690     // before: .. d, c, b, a
1691     // after:  .. b, a, d, c, b, a
1692     // not tested
1693     a = pop();
1694     b = pop();
1695     c = pop();
1696     d = pop();
1697     push( b );
1698     push( a );
1699     push( d );
1700     push( c );
1701     push( b );
1702     push( a );
1703     break;
1704 
1705   case Bytecodes::_arraylength: {
1706     // Must do null-check with value on expression stack
1707     Node *ary = null_check(peek(), T_ARRAY);
1708     // Compile-time detect of null-exception?
1709     if (stopped())  return;
1710     a = pop();
1711     push(load_array_length(a));
1712     break;
1713   }
1714 
1715   case Bytecodes::_baload: array_load(T_BYTE);   break;
1716   case Bytecodes::_caload: array_load(T_CHAR);   break;
1717   case Bytecodes::_iaload: array_load(T_INT);    break;
1718   case Bytecodes::_saload: array_load(T_SHORT);  break;
1719   case Bytecodes::_faload: array_load(T_FLOAT);  break;
1720   case Bytecodes::_aaload: array_load(T_OBJECT); break;
1721   case Bytecodes::_laload: {
1722     a = array_addressing(T_LONG, 0);
1723     if (stopped())  return;     // guaranteed null or range check
1724     dec_sp(2);                  // Pop array and index
1725     push_pair(make_load(control(), a, TypeLong::LONG, T_LONG, TypeAryPtr::LONGS, MemNode::unordered));
1726     break;
1727   }
1728   case Bytecodes::_daload: {
1729     a = array_addressing(T_DOUBLE, 0);
1730     if (stopped())  return;     // guaranteed null or range check
1731     dec_sp(2);                  // Pop array and index
1732     push_pair(make_load(control(), a, Type::DOUBLE, T_DOUBLE, TypeAryPtr::DOUBLES, MemNode::unordered));
1733     break;
1734   }
1735   case Bytecodes::_bastore: array_store(T_BYTE);  break;
1736   case Bytecodes::_castore: array_store(T_CHAR);  break;
1737   case Bytecodes::_iastore: array_store(T_INT);   break;
1738   case Bytecodes::_sastore: array_store(T_SHORT); break;
1739   case Bytecodes::_fastore: array_store(T_FLOAT); break;
1740   case Bytecodes::_aastore: {
1741     d = array_addressing(T_OBJECT, 1);
1742     if (stopped())  return;     // guaranteed null or range check
1743     array_store_check();
1744     c = pop();                  // Oop to store
1745     b = pop();                  // index (already used)
1746     a = pop();                  // the array itself
1747     const TypeOopPtr* elemtype  = _gvn.type(a)->is_aryptr()->elem()->make_oopptr();
1748     const TypeAryPtr* adr_type = TypeAryPtr::OOPS;
1749     Node* store = store_oop_to_array(control(), a, d, adr_type, c, elemtype, T_OBJECT, MemNode::release);
1750     break;
1751   }
1752   case Bytecodes::_lastore: {
1753     a = array_addressing(T_LONG, 2);
1754     if (stopped())  return;     // guaranteed null or range check
1755     c = pop_pair();
1756     dec_sp(2);                  // Pop array and index
1757     store_to_memory(control(), a, c, T_LONG, TypeAryPtr::LONGS, MemNode::unordered);
1758     break;
1759   }
1760   case Bytecodes::_dastore: {
1761     a = array_addressing(T_DOUBLE, 2);
1762     if (stopped())  return;     // guaranteed null or range check
1763     c = pop_pair();
1764     dec_sp(2);                  // Pop array and index
1765     c = dstore_rounding(c);
1766     store_to_memory(control(), a, c, T_DOUBLE, TypeAryPtr::DOUBLES, MemNode::unordered);
1767     break;
1768   }
1769   case Bytecodes::_getfield:
1770     do_getfield();
1771     break;
1772 
1773   case Bytecodes::_getstatic:
1774     do_getstatic();
1775     break;
1776 
1777   case Bytecodes::_putfield:
1778     do_putfield();
1779     break;
1780 
1781   case Bytecodes::_putstatic:
1782     do_putstatic();
1783     break;
1784 
1785   case Bytecodes::_irem:
1786     do_irem();
1787     break;
1788   case Bytecodes::_idiv:
1789     // Must keep both values on the expression-stack during null-check
1790     zero_check_int(peek());
1791     // Compile-time detect of null-exception?
1792     if (stopped())  return;
1793     b = pop();
1794     a = pop();
1795     push( _gvn.transform( new (C) DivINode(control(),a,b) ) );
1796     break;
1797   case Bytecodes::_imul:
1798     b = pop(); a = pop();
1799     push( _gvn.transform( new (C) MulINode(a,b) ) );
1800     break;
1801   case Bytecodes::_iadd:
1802     b = pop(); a = pop();
1803     push( _gvn.transform( new (C) AddINode(a,b) ) );
1804     break;
1805   case Bytecodes::_ineg:
1806     a = pop();
1807     push( _gvn.transform( new (C) SubINode(_gvn.intcon(0),a)) );
1808     break;
1809   case Bytecodes::_isub:
1810     b = pop(); a = pop();
1811     push( _gvn.transform( new (C) SubINode(a,b) ) );
1812     break;
1813   case Bytecodes::_iand:
1814     b = pop(); a = pop();
1815     push( _gvn.transform( new (C) AndINode(a,b) ) );
1816     break;
1817   case Bytecodes::_ior:
1818     b = pop(); a = pop();
1819     push( _gvn.transform( new (C) OrINode(a,b) ) );
1820     break;
1821   case Bytecodes::_ixor:
1822     b = pop(); a = pop();
1823     push( _gvn.transform( new (C) XorINode(a,b) ) );
1824     break;
1825   case Bytecodes::_ishl:
1826     b = pop(); a = pop();
1827     push( _gvn.transform( new (C) LShiftINode(a,b) ) );
1828     break;
1829   case Bytecodes::_ishr:
1830     b = pop(); a = pop();
1831     push( _gvn.transform( new (C) RShiftINode(a,b) ) );
1832     break;
1833   case Bytecodes::_iushr:
1834     b = pop(); a = pop();
1835     push( _gvn.transform( new (C) URShiftINode(a,b) ) );
1836     break;
1837 
1838   case Bytecodes::_fneg:
1839     a = pop();
1840     b = _gvn.transform(new (C) NegFNode (a));
1841     push(b);
1842     break;
1843 
1844   case Bytecodes::_fsub:
1845     b = pop();
1846     a = pop();
1847     c = _gvn.transform( new (C) SubFNode(a,b) );
1848     d = precision_rounding(c);
1849     push( d );
1850     break;
1851 
1852   case Bytecodes::_fadd:
1853     b = pop();
1854     a = pop();
1855     c = _gvn.transform( new (C) AddFNode(a,b) );
1856     d = precision_rounding(c);
1857     push( d );
1858     break;
1859 
1860   case Bytecodes::_fmul:
1861     b = pop();
1862     a = pop();
1863     c = _gvn.transform( new (C) MulFNode(a,b) );
1864     d = precision_rounding(c);
1865     push( d );
1866     break;
1867 
1868   case Bytecodes::_fdiv:
1869     b = pop();
1870     a = pop();
1871     c = _gvn.transform( new (C) DivFNode(0,a,b) );
1872     d = precision_rounding(c);
1873     push( d );
1874     break;
1875 
1876   case Bytecodes::_frem:
1877     if (Matcher::has_match_rule(Op_ModF)) {
1878       // Generate a ModF node.
1879       b = pop();
1880       a = pop();
1881       c = _gvn.transform( new (C) ModFNode(0,a,b) );
1882       d = precision_rounding(c);
1883       push( d );
1884     }
1885     else {
1886       // Generate a call.
1887       modf();
1888     }
1889     break;
1890 
1891   case Bytecodes::_fcmpl:
1892     b = pop();
1893     a = pop();
1894     c = _gvn.transform( new (C) CmpF3Node( a, b));
1895     push(c);
1896     break;
1897   case Bytecodes::_fcmpg:
1898     b = pop();
1899     a = pop();
1900 
1901     // Same as fcmpl but need to flip the unordered case.  Swap the inputs,
1902     // which negates the result sign except for unordered.  Flip the unordered
1903     // as well by using CmpF3 which implements unordered-lesser instead of
1904     // unordered-greater semantics.  Finally, commute the result bits.  Result
1905     // is same as using a CmpF3Greater except we did it with CmpF3 alone.
1906     c = _gvn.transform( new (C) CmpF3Node( b, a));
1907     c = _gvn.transform( new (C) SubINode(_gvn.intcon(0),c) );
1908     push(c);
1909     break;
1910 
1911   case Bytecodes::_f2i:
1912     a = pop();
1913     push(_gvn.transform(new (C) ConvF2INode(a)));
1914     break;
1915 
1916   case Bytecodes::_d2i:
1917     a = pop_pair();
1918     b = _gvn.transform(new (C) ConvD2INode(a));
1919     push( b );
1920     break;
1921 
1922   case Bytecodes::_f2d:
1923     a = pop();
1924     b = _gvn.transform( new (C) ConvF2DNode(a));
1925     push_pair( b );
1926     break;
1927 
1928   case Bytecodes::_d2f:
1929     a = pop_pair();
1930     b = _gvn.transform( new (C) ConvD2FNode(a));
1931     // This breaks _227_mtrt (speed & correctness) and _222_mpegaudio (speed)
1932     //b = _gvn.transform(new (C) RoundFloatNode(0, b) );
1933     push( b );
1934     break;
1935 
1936   case Bytecodes::_l2f:
1937     if (Matcher::convL2FSupported()) {
1938       a = pop_pair();
1939       b = _gvn.transform( new (C) ConvL2FNode(a));
1940       // For i486.ad, FILD doesn't restrict precision to 24 or 53 bits.
1941       // Rather than storing the result into an FP register then pushing
1942       // out to memory to round, the machine instruction that implements
1943       // ConvL2D is responsible for rounding.
1944       // c = precision_rounding(b);
1945       c = _gvn.transform(b);
1946       push(c);
1947     } else {
1948       l2f();
1949     }
1950     break;
1951 
1952   case Bytecodes::_l2d:
1953     a = pop_pair();
1954     b = _gvn.transform( new (C) ConvL2DNode(a));
1955     // For i486.ad, rounding is always necessary (see _l2f above).
1956     // c = dprecision_rounding(b);
1957     c = _gvn.transform(b);
1958     push_pair(c);
1959     break;
1960 
1961   case Bytecodes::_f2l:
1962     a = pop();
1963     b = _gvn.transform( new (C) ConvF2LNode(a));
1964     push_pair(b);
1965     break;
1966 
1967   case Bytecodes::_d2l:
1968     a = pop_pair();
1969     b = _gvn.transform( new (C) ConvD2LNode(a));
1970     push_pair(b);
1971     break;
1972 
1973   case Bytecodes::_dsub:
1974     b = pop_pair();
1975     a = pop_pair();
1976     c = _gvn.transform( new (C) SubDNode(a,b) );
1977     d = dprecision_rounding(c);
1978     push_pair( d );
1979     break;
1980 
1981   case Bytecodes::_dadd:
1982     b = pop_pair();
1983     a = pop_pair();
1984     c = _gvn.transform( new (C) AddDNode(a,b) );
1985     d = dprecision_rounding(c);
1986     push_pair( d );
1987     break;
1988 
1989   case Bytecodes::_dmul:
1990     b = pop_pair();
1991     a = pop_pair();
1992     c = _gvn.transform( new (C) MulDNode(a,b) );
1993     d = dprecision_rounding(c);
1994     push_pair( d );
1995     break;
1996 
1997   case Bytecodes::_ddiv:
1998     b = pop_pair();
1999     a = pop_pair();
2000     c = _gvn.transform( new (C) DivDNode(0,a,b) );
2001     d = dprecision_rounding(c);
2002     push_pair( d );
2003     break;
2004 
2005   case Bytecodes::_dneg:
2006     a = pop_pair();
2007     b = _gvn.transform(new (C) NegDNode (a));
2008     push_pair(b);
2009     break;
2010 
2011   case Bytecodes::_drem:
2012     if (Matcher::has_match_rule(Op_ModD)) {
2013       // Generate a ModD node.
2014       b = pop_pair();
2015       a = pop_pair();
2016       // a % b
2017 
2018       c = _gvn.transform( new (C) ModDNode(0,a,b) );
2019       d = dprecision_rounding(c);
2020       push_pair( d );
2021     }
2022     else {
2023       // Generate a call.
2024       modd();
2025     }
2026     break;
2027 
2028   case Bytecodes::_dcmpl:
2029     b = pop_pair();
2030     a = pop_pair();
2031     c = _gvn.transform( new (C) CmpD3Node( a, b));
2032     push(c);
2033     break;
2034 
2035   case Bytecodes::_dcmpg:
2036     b = pop_pair();
2037     a = pop_pair();
2038     // Same as dcmpl but need to flip the unordered case.
2039     // Commute the inputs, which negates the result sign except for unordered.
2040     // Flip the unordered as well by using CmpD3 which implements
2041     // unordered-lesser instead of unordered-greater semantics.
2042     // Finally, negate the result bits.  Result is same as using a
2043     // CmpD3Greater except we did it with CmpD3 alone.
2044     c = _gvn.transform( new (C) CmpD3Node( b, a));
2045     c = _gvn.transform( new (C) SubINode(_gvn.intcon(0),c) );
2046     push(c);
2047     break;
2048 
2049 
2050     // Note for longs -> lo word is on TOS, hi word is on TOS - 1
2051   case Bytecodes::_land:
2052     b = pop_pair();
2053     a = pop_pair();
2054     c = _gvn.transform( new (C) AndLNode(a,b) );
2055     push_pair(c);
2056     break;
2057   case Bytecodes::_lor:
2058     b = pop_pair();
2059     a = pop_pair();
2060     c = _gvn.transform( new (C) OrLNode(a,b) );
2061     push_pair(c);
2062     break;
2063   case Bytecodes::_lxor:
2064     b = pop_pair();
2065     a = pop_pair();
2066     c = _gvn.transform( new (C) XorLNode(a,b) );
2067     push_pair(c);
2068     break;
2069 
2070   case Bytecodes::_lshl:
2071     b = pop();                  // the shift count
2072     a = pop_pair();             // value to be shifted
2073     c = _gvn.transform( new (C) LShiftLNode(a,b) );
2074     push_pair(c);
2075     break;
2076   case Bytecodes::_lshr:
2077     b = pop();                  // the shift count
2078     a = pop_pair();             // value to be shifted
2079     c = _gvn.transform( new (C) RShiftLNode(a,b) );
2080     push_pair(c);
2081     break;
2082   case Bytecodes::_lushr:
2083     b = pop();                  // the shift count
2084     a = pop_pair();             // value to be shifted
2085     c = _gvn.transform( new (C) URShiftLNode(a,b) );
2086     push_pair(c);
2087     break;
2088   case Bytecodes::_lmul:
2089     b = pop_pair();
2090     a = pop_pair();
2091     c = _gvn.transform( new (C) MulLNode(a,b) );
2092     push_pair(c);
2093     break;
2094 
2095   case Bytecodes::_lrem:
2096     // Must keep both values on the expression-stack during null-check
2097     assert(peek(0) == top(), "long word order");
2098     zero_check_long(peek(1));
2099     // Compile-time detect of null-exception?
2100     if (stopped())  return;
2101     b = pop_pair();
2102     a = pop_pair();
2103     c = _gvn.transform( new (C) ModLNode(control(),a,b) );
2104     push_pair(c);
2105     break;
2106 
2107   case Bytecodes::_ldiv:
2108     // Must keep both values on the expression-stack during null-check
2109     assert(peek(0) == top(), "long word order");
2110     zero_check_long(peek(1));
2111     // Compile-time detect of null-exception?
2112     if (stopped())  return;
2113     b = pop_pair();
2114     a = pop_pair();
2115     c = _gvn.transform( new (C) DivLNode(control(),a,b) );
2116     push_pair(c);
2117     break;
2118 
2119   case Bytecodes::_ladd:
2120     b = pop_pair();
2121     a = pop_pair();
2122     c = _gvn.transform( new (C) AddLNode(a,b) );
2123     push_pair(c);
2124     break;
2125   case Bytecodes::_lsub:
2126     b = pop_pair();
2127     a = pop_pair();
2128     c = _gvn.transform( new (C) SubLNode(a,b) );
2129     push_pair(c);
2130     break;
2131   case Bytecodes::_lcmp:
2132     // Safepoints are now inserted _before_ branches.  The long-compare
2133     // bytecode painfully produces a 3-way value (-1,0,+1) which requires a
2134     // slew of control flow.  These are usually followed by a CmpI vs zero and
2135     // a branch; this pattern then optimizes to the obvious long-compare and
2136     // branch.  However, if the branch is backwards there's a Safepoint
2137     // inserted.  The inserted Safepoint captures the JVM state at the
2138     // pre-branch point, i.e. it captures the 3-way value.  Thus if a
2139     // long-compare is used to control a loop the debug info will force
2140     // computation of the 3-way value, even though the generated code uses a
2141     // long-compare and branch.  We try to rectify the situation by inserting
2142     // a SafePoint here and have it dominate and kill the safepoint added at a
2143     // following backwards branch.  At this point the JVM state merely holds 2
2144     // longs but not the 3-way value.
2145     if( UseLoopSafepoints ) {
2146       switch( iter().next_bc() ) {
2147       case Bytecodes::_ifgt:
2148       case Bytecodes::_iflt:
2149       case Bytecodes::_ifge:
2150       case Bytecodes::_ifle:
2151       case Bytecodes::_ifne:
2152       case Bytecodes::_ifeq:
2153         // If this is a backwards branch in the bytecodes, add Safepoint
2154         maybe_add_safepoint(iter().next_get_dest());
2155       }
2156     }
2157     b = pop_pair();
2158     a = pop_pair();
2159     c = _gvn.transform( new (C) CmpL3Node( a, b ));
2160     push(c);
2161     break;
2162 
2163   case Bytecodes::_lneg:
2164     a = pop_pair();
2165     b = _gvn.transform( new (C) SubLNode(longcon(0),a));
2166     push_pair(b);
2167     break;
2168   case Bytecodes::_l2i:
2169     a = pop_pair();
2170     push( _gvn.transform( new (C) ConvL2INode(a)));
2171     break;
2172   case Bytecodes::_i2l:
2173     a = pop();
2174     b = _gvn.transform( new (C) ConvI2LNode(a));
2175     push_pair(b);
2176     break;
2177   case Bytecodes::_i2b:
2178     // Sign extend
2179     a = pop();
2180     a = _gvn.transform( new (C) LShiftINode(a,_gvn.intcon(24)) );
2181     a = _gvn.transform( new (C) RShiftINode(a,_gvn.intcon(24)) );
2182     push( a );
2183     break;
2184   case Bytecodes::_i2s:
2185     a = pop();
2186     a = _gvn.transform( new (C) LShiftINode(a,_gvn.intcon(16)) );
2187     a = _gvn.transform( new (C) RShiftINode(a,_gvn.intcon(16)) );
2188     push( a );
2189     break;
2190   case Bytecodes::_i2c:
2191     a = pop();
2192     push( _gvn.transform( new (C) AndINode(a,_gvn.intcon(0xFFFF)) ) );
2193     break;
2194 
2195   case Bytecodes::_i2f:
2196     a = pop();
2197     b = _gvn.transform( new (C) ConvI2FNode(a) ) ;
2198     c = precision_rounding(b);
2199     push (b);
2200     break;
2201 
2202   case Bytecodes::_i2d:
2203     a = pop();
2204     b = _gvn.transform( new (C) ConvI2DNode(a));
2205     push_pair(b);
2206     break;
2207 
2208   case Bytecodes::_iinc:        // Increment local
2209     i = iter().get_index();     // Get local index
2210     set_local( i, _gvn.transform( new (C) AddINode( _gvn.intcon(iter().get_iinc_con()), local(i) ) ) );
2211     break;
2212 
2213   // Exit points of synchronized methods must have an unlock node
2214   case Bytecodes::_return:
2215     return_current(NULL);
2216     break;
2217 
2218   case Bytecodes::_ireturn:
2219   case Bytecodes::_areturn:
2220   case Bytecodes::_freturn:
2221     return_current(pop());
2222     break;
2223   case Bytecodes::_lreturn:
2224     return_current(pop_pair());
2225     break;
2226   case Bytecodes::_dreturn:
2227     return_current(pop_pair());
2228     break;
2229 
2230   case Bytecodes::_athrow:
2231     // null exception oop throws NULL pointer exception
2232     null_check(peek());
2233     if (stopped())  return;
2234     // Hook the thrown exception directly to subsequent handlers.
2235     if (BailoutToInterpreterForThrows) {
2236       // Keep method interpreted from now on.
2237       uncommon_trap(Deoptimization::Reason_unhandled,
2238                     Deoptimization::Action_make_not_compilable);
2239       return;
2240     }
2241     if (env()->jvmti_can_post_on_exceptions()) {
2242       // check if we must post exception events, take uncommon trap if so (with must_throw = false)
2243       uncommon_trap_if_should_post_on_exceptions(Deoptimization::Reason_unhandled, false);
2244     }
2245     // Here if either can_post_on_exceptions or should_post_on_exceptions is false
2246     add_exception_state(make_exception_state(peek()));
2247     break;
2248 
2249   case Bytecodes::_goto:   // fall through
2250   case Bytecodes::_goto_w: {
2251     int target_bci = (bc() == Bytecodes::_goto) ? iter().get_dest() : iter().get_far_dest();
2252 
2253     // If this is a backwards branch in the bytecodes, add Safepoint
2254     maybe_add_safepoint(target_bci);
2255 
2256     // Update method data
2257     profile_taken_branch(target_bci);
2258 
2259     // Merge the current control into the target basic block
2260     merge(target_bci);
2261 
2262     // See if we can get some profile data and hand it off to the next block
2263     Block *target_block = block()->successor_for_bci(target_bci);
2264     if (target_block->pred_count() != 1)  break;
2265     ciMethodData* methodData = method()->method_data();
2266     if (!methodData->is_mature())  break;
2267     ciProfileData* data = methodData->bci_to_data(bci());
2268     assert( data->is_JumpData(), "" );
2269     int taken = ((ciJumpData*)data)->taken();
2270     taken = method()->scale_count(taken);
2271     target_block->set_count(taken);
2272     break;
2273   }
2274 
2275   case Bytecodes::_ifnull:    btest = BoolTest::eq; goto handle_if_null;
2276   case Bytecodes::_ifnonnull: btest = BoolTest::ne; goto handle_if_null;
2277   handle_if_null:
2278     // If this is a backwards branch in the bytecodes, add Safepoint
2279     maybe_add_safepoint(iter().get_dest());
2280     a = null();
2281     b = pop();
2282     c = _gvn.transform( new (C) CmpPNode(b, a) );
2283     do_ifnull(btest, c);
2284     break;
2285 
2286   case Bytecodes::_if_acmpeq: btest = BoolTest::eq; goto handle_if_acmp;
2287   case Bytecodes::_if_acmpne: btest = BoolTest::ne; goto handle_if_acmp;
2288   handle_if_acmp:
2289     // If this is a backwards branch in the bytecodes, add Safepoint
2290     maybe_add_safepoint(iter().get_dest());
2291     a = pop();
2292     b = pop();
2293     c = _gvn.transform( new (C) CmpPNode(b, a) );
2294     c = optimize_cmp_with_klass(c);
2295     do_if(btest, c);
2296     break;
2297 
2298   case Bytecodes::_ifeq: btest = BoolTest::eq; goto handle_ifxx;
2299   case Bytecodes::_ifne: btest = BoolTest::ne; goto handle_ifxx;
2300   case Bytecodes::_iflt: btest = BoolTest::lt; goto handle_ifxx;
2301   case Bytecodes::_ifle: btest = BoolTest::le; goto handle_ifxx;
2302   case Bytecodes::_ifgt: btest = BoolTest::gt; goto handle_ifxx;
2303   case Bytecodes::_ifge: btest = BoolTest::ge; goto handle_ifxx;
2304   handle_ifxx:
2305     // If this is a backwards branch in the bytecodes, add Safepoint
2306     maybe_add_safepoint(iter().get_dest());
2307     a = _gvn.intcon(0);
2308     b = pop();
2309     c = _gvn.transform( new (C) CmpINode(b, a) );
2310     do_if(btest, c);
2311     break;
2312 
2313   case Bytecodes::_if_icmpeq: btest = BoolTest::eq; goto handle_if_icmp;
2314   case Bytecodes::_if_icmpne: btest = BoolTest::ne; goto handle_if_icmp;
2315   case Bytecodes::_if_icmplt: btest = BoolTest::lt; goto handle_if_icmp;
2316   case Bytecodes::_if_icmple: btest = BoolTest::le; goto handle_if_icmp;
2317   case Bytecodes::_if_icmpgt: btest = BoolTest::gt; goto handle_if_icmp;
2318   case Bytecodes::_if_icmpge: btest = BoolTest::ge; goto handle_if_icmp;
2319   handle_if_icmp:
2320     // If this is a backwards branch in the bytecodes, add Safepoint
2321     maybe_add_safepoint(iter().get_dest());
2322     a = pop();
2323     b = pop();
2324     c = _gvn.transform( new (C) CmpINode( b, a ) );
2325     do_if(btest, c);
2326     break;
2327 
2328   case Bytecodes::_tableswitch:
2329     do_tableswitch();
2330     break;
2331 
2332   case Bytecodes::_lookupswitch:
2333     do_lookupswitch();
2334     break;
2335 
2336   case Bytecodes::_invokestatic:
2337   case Bytecodes::_invokedynamic:
2338   case Bytecodes::_invokespecial:
2339   case Bytecodes::_invokevirtual:
2340   case Bytecodes::_invokeinterface:
2341     do_call();
2342     break;
2343   case Bytecodes::_checkcast:
2344     do_checkcast();
2345     break;
2346   case Bytecodes::_instanceof:
2347     do_instanceof();
2348     break;
2349   case Bytecodes::_anewarray:
2350     do_anewarray();
2351     break;
2352   case Bytecodes::_newarray:
2353     do_newarray((BasicType)iter().get_index());
2354     break;
2355   case Bytecodes::_multianewarray:
2356     do_multianewarray();
2357     break;
2358   case Bytecodes::_new:
2359     do_new();
2360     break;
2361 
2362   case Bytecodes::_jsr:
2363   case Bytecodes::_jsr_w:
2364     do_jsr();
2365     break;
2366 
2367   case Bytecodes::_ret:
2368     do_ret();
2369     break;
2370 
2371 
2372   case Bytecodes::_monitorenter:
2373     do_monitor_enter();
2374     break;
2375 
2376   case Bytecodes::_monitorexit:
2377     do_monitor_exit();
2378     break;
2379 
2380   case Bytecodes::_breakpoint:
2381     // Breakpoint set concurrently to compile
2382     // %%% use an uncommon trap?
2383     C->record_failure("breakpoint in method");
2384     return;
2385 
2386   default:
2387 #ifndef PRODUCT
2388     map()->dump(99);
2389 #endif
2390     tty->print("\nUnhandled bytecode %s\n", Bytecodes::name(bc()) );
2391     ShouldNotReachHere();
2392   }
2393 
2394 #ifndef PRODUCT
2395   IdealGraphPrinter *printer = IdealGraphPrinter::printer();
2396   if(printer) {
2397     char buffer[256];
2398     sprintf(buffer, "Bytecode %d: %s", bci(), Bytecodes::name(bc()));
2399     bool old = printer->traverse_outs();
2400     printer->set_traverse_outs(true);
2401     printer->print_method(C, buffer, 4);
2402     printer->set_traverse_outs(old);
2403   }
2404 #endif
2405 }