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