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