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->klass()->as_instance_klass()->unique_concrete_subklass()) {
 128         // If we load from "AbstractClass[]" we must see "ConcreteSubClass".
 129         const Type* subklass = Type::get_const_type(toop->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   ciKlass * arytype_klass = arytype->klass();
 147   if ((arytype_klass != NULL) && (!arytype_klass->is_loaded())) {
 148     // Only fails for some -Xcomp runs
 149     // The class is unloaded.  We have to run this bytecode in the interpreter.
 150     uncommon_trap(Deoptimization::Reason_unloaded,
 151                   Deoptimization::Action_reinterpret,
 152                   arytype->klass(), "!loaded array");
 153     return top();
 154   }
 155 
 156   // Do the range check
 157   if (GenerateRangeChecks && need_range_check) {
 158     Node* tst;
 159     if (sizetype->_hi <= 0) {
 160       // The greatest array bound is negative, so we can conclude that we're
 161       // compiling unreachable code, but the unsigned compare trick used below
 162       // only works with non-negative lengths.  Instead, hack "tst" to be zero so
 163       // the uncommon_trap path will always be taken.
 164       tst = _gvn.intcon(0);
 165     } else {
 166       // Range is constant in array-oop, so we can use the original state of mem
 167       Node* len = load_array_length(ary);
 168 
 169       // Test length vs index (standard trick using unsigned compare)
 170       Node* chk = _gvn.transform( new CmpUNode(idx, len) );
 171       BoolTest::mask btest = BoolTest::lt;
 172       tst = _gvn.transform( new BoolNode(chk, btest) );
 173     }
 174     RangeCheckNode* rc = new RangeCheckNode(control(), tst, PROB_MAX, COUNT_UNKNOWN);
 175     _gvn.set_type(rc, rc->Value(&_gvn));
 176     if (!tst->is_Con()) {
 177       record_for_igvn(rc);
 178     }
 179     set_control(_gvn.transform(new IfTrueNode(rc)));
 180     // Branch to failure if out of bounds
 181     {
 182       PreserveJVMState pjvms(this);
 183       set_control(_gvn.transform(new IfFalseNode(rc)));
 184       if (C->allow_range_check_smearing()) {
 185         // Do not use builtin_throw, since range checks are sometimes
 186         // made more stringent by an optimistic transformation.
 187         // This creates "tentative" range checks at this point,
 188         // which are not guaranteed to throw exceptions.
 189         // See IfNode::Ideal, is_range_check, adjust_check.
 190         uncommon_trap(Deoptimization::Reason_range_check,
 191                       Deoptimization::Action_make_not_entrant,
 192                       NULL, "range_check");
 193       } else {
 194         // If we have already recompiled with the range-check-widening
 195         // heroic optimization turned off, then we must really be throwing
 196         // range check exceptions.
 197         builtin_throw(Deoptimization::Reason_range_check, idx);
 198       }
 199     }
 200   }
 201   // Check for always knowing you are throwing a range-check exception
 202   if (stopped())  return top();
 203 




















































































































 204   // Make array address computation control dependent to prevent it
 205   // from floating above the range check during loop optimizations.
 206   Node* ptr = array_element_address(ary, idx, type, sizetype, control());
 207   assert(ptr != top(), "top should go hand-in-hand with stopped");
 208 
 209   return ptr;
 210 }
 211 
 212 
 213 // returns IfNode
 214 IfNode* Parse::jump_if_fork_int(Node* a, Node* b, BoolTest::mask mask, float prob, float cnt) {
 215   Node   *cmp = _gvn.transform(new CmpINode(a, b)); // two cases: shiftcount > 32 and shiftcount <= 32
 216   Node   *tst = _gvn.transform(new BoolNode(cmp, mask));
 217   IfNode *iff = create_and_map_if(control(), tst, prob, cnt);
 218   return iff;
 219 }
 220 
 221 
 222 // sentinel value for the target bci to mark never taken branches
 223 // (according to profiling)
 224 static const int never_reached = INT_MAX;
 225 
 226 //------------------------------helper for tableswitch-------------------------
 227 void Parse::jump_if_true_fork(IfNode *iff, int dest_bci_if_true, bool unc) {
 228   // True branch, use existing map info
 229   { PreserveJVMState pjvms(this);
 230     Node *iftrue  = _gvn.transform( new IfTrueNode (iff) );
 231     set_control( iftrue );
 232     if (unc) {
 233       repush_if_args();
 234       uncommon_trap(Deoptimization::Reason_unstable_if,
 235                     Deoptimization::Action_reinterpret,
 236                     NULL,
 237                     "taken always");
 238     } else {
 239       assert(dest_bci_if_true != never_reached, "inconsistent dest");
 240       merge_new_path(dest_bci_if_true);
 241     }
 242   }
 243 
 244   // False branch
 245   Node *iffalse = _gvn.transform( new IfFalseNode(iff) );
 246   set_control( iffalse );
 247 }
 248 
 249 void Parse::jump_if_false_fork(IfNode *iff, int dest_bci_if_true, bool unc) {
 250   // True branch, use existing map info
 251   { PreserveJVMState pjvms(this);
 252     Node *iffalse  = _gvn.transform( new IfFalseNode (iff) );
 253     set_control( iffalse );
 254     if (unc) {
 255       repush_if_args();
 256       uncommon_trap(Deoptimization::Reason_unstable_if,
 257                     Deoptimization::Action_reinterpret,
 258                     NULL,
 259                     "taken never");
 260     } else {
 261       assert(dest_bci_if_true != never_reached, "inconsistent dest");
 262       merge_new_path(dest_bci_if_true);
 263     }
 264   }
 265 
 266   // False branch
 267   Node *iftrue = _gvn.transform( new IfTrueNode(iff) );
 268   set_control( iftrue );
 269 }
 270 
 271 void Parse::jump_if_always_fork(int dest_bci, bool unc) {
 272   // False branch, use existing map and control()
 273   if (unc) {
 274     repush_if_args();
 275     uncommon_trap(Deoptimization::Reason_unstable_if,
 276                   Deoptimization::Action_reinterpret,
 277                   NULL,
 278                   "taken never");
 279   } else {
 280     assert(dest_bci != never_reached, "inconsistent dest");
 281     merge_new_path(dest_bci);
 282   }
 283 }
 284 
 285 
 286 extern "C" {
 287   static int jint_cmp(const void *i, const void *j) {
 288     int a = *(jint *)i;
 289     int b = *(jint *)j;
 290     return a > b ? 1 : a < b ? -1 : 0;
 291   }
 292 }
 293 
 294 
 295 class SwitchRange : public StackObj {
 296   // a range of integers coupled with a bci destination
 297   jint _lo;                     // inclusive lower limit
 298   jint _hi;                     // inclusive upper limit
 299   int _dest;
 300   float _cnt;                   // how many times this range was hit according to profiling
 301 
 302 public:
 303   jint lo() const              { return _lo;   }
 304   jint hi() const              { return _hi;   }
 305   int  dest() const            { return _dest; }
 306   bool is_singleton() const    { return _lo == _hi; }
 307   float cnt() const            { return _cnt; }
 308 
 309   void setRange(jint lo, jint hi, int dest, float cnt) {
 310     assert(lo <= hi, "must be a non-empty range");
 311     _lo = lo, _hi = hi; _dest = dest; _cnt = cnt;
 312     assert(_cnt >= 0, "");
 313   }
 314   bool adjoinRange(jint lo, jint hi, int dest, float cnt, bool trim_ranges) {
 315     assert(lo <= hi, "must be a non-empty range");
 316     if (lo == _hi+1) {
 317       // see merge_ranges() comment below
 318       if (trim_ranges) {
 319         if (cnt == 0) {
 320           if (_cnt != 0) {
 321             return false;
 322           }
 323           if (dest != _dest) {
 324             _dest = never_reached;
 325           }
 326         } else {
 327           if (_cnt == 0) {
 328             return false;
 329           }
 330           if (dest != _dest) {
 331             return false;
 332           }
 333         }
 334       } else {
 335         if (dest != _dest) {
 336           return false;
 337         }
 338       }
 339       _hi = hi;
 340       _cnt += cnt;
 341       return true;
 342     }
 343     return false;
 344   }
 345 
 346   void set (jint value, int dest, float cnt) {
 347     setRange(value, value, dest, cnt);
 348   }
 349   bool adjoin(jint value, int dest, float cnt, bool trim_ranges) {
 350     return adjoinRange(value, value, dest, cnt, trim_ranges);
 351   }
 352   bool adjoin(SwitchRange& other) {
 353     return adjoinRange(other._lo, other._hi, other._dest, other._cnt, false);
 354   }
 355 
 356   void print() {
 357     if (is_singleton())
 358       tty->print(" {%d}=>%d (cnt=%f)", lo(), dest(), cnt());
 359     else if (lo() == min_jint)
 360       tty->print(" {..%d}=>%d (cnt=%f)", hi(), dest(), cnt());
 361     else if (hi() == max_jint)
 362       tty->print(" {%d..}=>%d (cnt=%f)", lo(), dest(), cnt());
 363     else
 364       tty->print(" {%d..%d}=>%d (cnt=%f)", lo(), hi(), dest(), cnt());
 365   }
 366 };
 367 
 368 // We try to minimize the number of ranges and the size of the taken
 369 // ones using profiling data. When ranges are created,
 370 // SwitchRange::adjoinRange() only allows 2 adjoining ranges to merge
 371 // if both were never hit or both were hit to build longer unreached
 372 // ranges. Here, we now merge adjoining ranges with the same
 373 // destination and finally set destination of unreached ranges to the
 374 // special value never_reached because it can help minimize the number
 375 // of tests that are necessary.
 376 //
 377 // For instance:
 378 // [0, 1] to target1 sometimes taken
 379 // [1, 2] to target1 never taken
 380 // [2, 3] to target2 never taken
 381 // would lead to:
 382 // [0, 1] to target1 sometimes taken
 383 // [1, 3] never taken
 384 //
 385 // (first 2 ranges to target1 are not merged)
 386 static void merge_ranges(SwitchRange* ranges, int& rp) {
 387   if (rp == 0) {
 388     return;
 389   }
 390   int shift = 0;
 391   for (int j = 0; j < rp; j++) {
 392     SwitchRange& r1 = ranges[j-shift];
 393     SwitchRange& r2 = ranges[j+1];
 394     if (r1.adjoin(r2)) {
 395       shift++;
 396     } else if (shift > 0) {
 397       ranges[j+1-shift] = r2;
 398     }
 399   }
 400   rp -= shift;
 401   for (int j = 0; j <= rp; j++) {
 402     SwitchRange& r = ranges[j];
 403     if (r.cnt() == 0 && r.dest() != never_reached) {
 404       r.setRange(r.lo(), r.hi(), never_reached, r.cnt());
 405     }
 406   }
 407 }
 408 
 409 //-------------------------------do_tableswitch--------------------------------
 410 void Parse::do_tableswitch() {
 411   // Get information about tableswitch
 412   int default_dest = iter().get_dest_table(0);
 413   jint lo_index    = iter().get_int_table(1);
 414   jint hi_index    = iter().get_int_table(2);
 415   int len          = hi_index - lo_index + 1;
 416 
 417   if (len < 1) {
 418     // If this is a backward branch, add safepoint
 419     maybe_add_safepoint(default_dest);
 420     pop(); // the effect of the instruction execution on the operand stack
 421     merge(default_dest);
 422     return;
 423   }
 424 
 425   ciMethodData* methodData = method()->method_data();
 426   ciMultiBranchData* profile = NULL;
 427   if (methodData->is_mature() && UseSwitchProfiling) {
 428     ciProfileData* data = methodData->bci_to_data(bci());
 429     if (data != NULL && data->is_MultiBranchData()) {
 430       profile = (ciMultiBranchData*)data;
 431     }
 432   }
 433   bool trim_ranges = !C->too_many_traps(method(), bci(), Deoptimization::Reason_unstable_if);
 434 
 435   // generate decision tree, using trichotomy when possible
 436   int rnum = len+2;
 437   bool makes_backward_branch = false;
 438   SwitchRange* ranges = NEW_RESOURCE_ARRAY(SwitchRange, rnum);
 439   int rp = -1;
 440   if (lo_index != min_jint) {
 441     float cnt = 1.0F;
 442     if (profile != NULL) {
 443       cnt = (float)profile->default_count() / (hi_index != max_jint ? 2.0F : 1.0F);
 444     }
 445     ranges[++rp].setRange(min_jint, lo_index-1, default_dest, cnt);
 446   }
 447   for (int j = 0; j < len; j++) {
 448     jint match_int = lo_index+j;
 449     int  dest      = iter().get_dest_table(j+3);
 450     makes_backward_branch |= (dest <= bci());
 451     float cnt = 1.0F;
 452     if (profile != NULL) {
 453       cnt = (float)profile->count_at(j);
 454     }
 455     if (rp < 0 || !ranges[rp].adjoin(match_int, dest, cnt, trim_ranges)) {
 456       ranges[++rp].set(match_int, dest, cnt);
 457     }
 458   }
 459   jint highest = lo_index+(len-1);
 460   assert(ranges[rp].hi() == highest, "");
 461   if (highest != max_jint) {
 462     float cnt = 1.0F;
 463     if (profile != NULL) {
 464       cnt = (float)profile->default_count() / (lo_index != min_jint ? 2.0F : 1.0F);
 465     }
 466     if (!ranges[rp].adjoinRange(highest+1, max_jint, default_dest, cnt, trim_ranges)) {
 467       ranges[++rp].setRange(highest+1, max_jint, default_dest, cnt);
 468     }
 469   }
 470   assert(rp < len+2, "not too many ranges");
 471 
 472   if (trim_ranges) {
 473     merge_ranges(ranges, rp);
 474   }
 475 
 476   // Safepoint in case if backward branch observed
 477   if (makes_backward_branch) {
 478     add_safepoint();
 479   }
 480 
 481   Node* lookup = pop(); // lookup value
 482   jump_switch_ranges(lookup, &ranges[0], &ranges[rp]);
 483 }
 484 
 485 
 486 //------------------------------do_lookupswitch--------------------------------
 487 void Parse::do_lookupswitch() {
 488   // Get information about lookupswitch
 489   int default_dest = iter().get_dest_table(0);
 490   jint len          = iter().get_int_table(1);
 491 
 492   if (len < 1) {    // If this is a backward branch, add safepoint
 493     maybe_add_safepoint(default_dest);
 494     pop(); // the effect of the instruction execution on the operand stack
 495     merge(default_dest);
 496     return;
 497   }
 498 
 499   ciMethodData* methodData = method()->method_data();
 500   ciMultiBranchData* profile = NULL;
 501   if (methodData->is_mature() && UseSwitchProfiling) {
 502     ciProfileData* data = methodData->bci_to_data(bci());
 503     if (data != NULL && data->is_MultiBranchData()) {
 504       profile = (ciMultiBranchData*)data;
 505     }
 506   }
 507   bool trim_ranges = !C->too_many_traps(method(), bci(), Deoptimization::Reason_unstable_if);
 508 
 509   // generate decision tree, using trichotomy when possible
 510   jint* table = NEW_RESOURCE_ARRAY(jint, len*3);
 511   {
 512     for (int j = 0; j < len; j++) {
 513       table[3*j+0] = iter().get_int_table(2+2*j);
 514       table[3*j+1] = iter().get_dest_table(2+2*j+1);
 515       // Handle overflow when converting from uint to jint
 516       table[3*j+2] = (profile == NULL) ? 1 : (jint)MIN2<uint>((uint)max_jint, profile->count_at(j));
 517     }
 518     qsort(table, len, 3*sizeof(table[0]), jint_cmp);
 519   }
 520 
 521   float default_cnt = 1.0F;
 522   if (profile != NULL) {
 523     juint defaults = max_juint - len;
 524     default_cnt = (float)profile->default_count()/(float)defaults;
 525   }
 526 
 527   int rnum = len*2+1;
 528   bool makes_backward_branch = false;
 529   SwitchRange* ranges = NEW_RESOURCE_ARRAY(SwitchRange, rnum);
 530   int rp = -1;
 531   for (int j = 0; j < len; j++) {
 532     jint match_int   = table[3*j+0];
 533     jint  dest        = table[3*j+1];
 534     jint  cnt         = table[3*j+2];
 535     jint  next_lo     = rp < 0 ? min_jint : ranges[rp].hi()+1;
 536     makes_backward_branch |= (dest <= bci());
 537     float c = default_cnt * ((float)match_int - (float)next_lo);
 538     if (match_int != next_lo && (rp < 0 || !ranges[rp].adjoinRange(next_lo, match_int-1, default_dest, c, trim_ranges))) {
 539       assert(default_dest != never_reached, "sentinel value for dead destinations");
 540       ranges[++rp].setRange(next_lo, match_int-1, default_dest, c);
 541     }
 542     if (rp < 0 || !ranges[rp].adjoin(match_int, dest, (float)cnt, trim_ranges)) {
 543       assert(dest != never_reached, "sentinel value for dead destinations");
 544       ranges[++rp].set(match_int, dest,  (float)cnt);
 545     }
 546   }
 547   jint highest = table[3*(len-1)];
 548   assert(ranges[rp].hi() == highest, "");
 549   if (highest != max_jint &&
 550       !ranges[rp].adjoinRange(highest+1, max_jint, default_dest, default_cnt * ((float)max_jint - (float)highest), trim_ranges)) {
 551     ranges[++rp].setRange(highest+1, max_jint, default_dest, default_cnt * ((float)max_jint - (float)highest));
 552   }
 553   assert(rp < rnum, "not too many ranges");
 554 
 555   if (trim_ranges) {
 556     merge_ranges(ranges, rp);
 557   }
 558 
 559   // Safepoint in case backward branch observed
 560   if (makes_backward_branch) {
 561     add_safepoint();
 562   }
 563 
 564   Node *lookup = pop(); // lookup value
 565   jump_switch_ranges(lookup, &ranges[0], &ranges[rp]);
 566 }
 567 
 568 static float if_prob(float taken_cnt, float total_cnt) {
 569   assert(taken_cnt <= total_cnt, "");
 570   if (total_cnt == 0) {
 571     return PROB_FAIR;
 572   }
 573   float p = taken_cnt / total_cnt;
 574   return clamp(p, PROB_MIN, PROB_MAX);
 575 }
 576 
 577 static float if_cnt(float cnt) {
 578   if (cnt == 0) {
 579     return COUNT_UNKNOWN;
 580   }
 581   return cnt;
 582 }
 583 
 584 static float sum_of_cnts(SwitchRange *lo, SwitchRange *hi) {
 585   float total_cnt = 0;
 586   for (SwitchRange* sr = lo; sr <= hi; sr++) {
 587     total_cnt += sr->cnt();
 588   }
 589   return total_cnt;
 590 }
 591 
 592 class SwitchRanges : public ResourceObj {
 593 public:
 594   SwitchRange* _lo;
 595   SwitchRange* _hi;
 596   SwitchRange* _mid;
 597   float _cost;
 598 
 599   enum {
 600     Start,
 601     LeftDone,
 602     RightDone,
 603     Done
 604   } _state;
 605 
 606   SwitchRanges(SwitchRange *lo, SwitchRange *hi)
 607     : _lo(lo), _hi(hi), _mid(NULL),
 608       _cost(0), _state(Start) {
 609   }
 610 
 611   SwitchRanges()
 612     : _lo(NULL), _hi(NULL), _mid(NULL),
 613       _cost(0), _state(Start) {}
 614 };
 615 
 616 // Estimate cost of performing a binary search on lo..hi
 617 static float compute_tree_cost(SwitchRange *lo, SwitchRange *hi, float total_cnt) {
 618   GrowableArray<SwitchRanges> tree;
 619   SwitchRanges root(lo, hi);
 620   tree.push(root);
 621 
 622   float cost = 0;
 623   do {
 624     SwitchRanges& r = *tree.adr_at(tree.length()-1);
 625     if (r._hi != r._lo) {
 626       if (r._mid == NULL) {
 627         float r_cnt = sum_of_cnts(r._lo, r._hi);
 628 
 629         if (r_cnt == 0) {
 630           tree.pop();
 631           cost = 0;
 632           continue;
 633         }
 634 
 635         SwitchRange* mid = NULL;
 636         mid = r._lo;
 637         for (float cnt = 0; ; ) {
 638           assert(mid <= r._hi, "out of bounds");
 639           cnt += mid->cnt();
 640           if (cnt > r_cnt / 2) {
 641             break;
 642           }
 643           mid++;
 644         }
 645         assert(mid <= r._hi, "out of bounds");
 646         r._mid = mid;
 647         r._cost = r_cnt / total_cnt;
 648       }
 649       r._cost += cost;
 650       if (r._state < SwitchRanges::LeftDone && r._mid > r._lo) {
 651         cost = 0;
 652         r._state = SwitchRanges::LeftDone;
 653         tree.push(SwitchRanges(r._lo, r._mid-1));
 654       } else if (r._state < SwitchRanges::RightDone) {
 655         cost = 0;
 656         r._state = SwitchRanges::RightDone;
 657         tree.push(SwitchRanges(r._mid == r._lo ? r._mid+1 : r._mid, r._hi));
 658       } else {
 659         tree.pop();
 660         cost = r._cost;
 661       }
 662     } else {
 663       tree.pop();
 664       cost = r._cost;
 665     }
 666   } while (tree.length() > 0);
 667 
 668 
 669   return cost;
 670 }
 671 
 672 // It sometimes pays off to test most common ranges before the binary search
 673 void Parse::linear_search_switch_ranges(Node* key_val, SwitchRange*& lo, SwitchRange*& hi) {
 674   uint nr = hi - lo + 1;
 675   float total_cnt = sum_of_cnts(lo, hi);
 676 
 677   float min = compute_tree_cost(lo, hi, total_cnt);
 678   float extra = 1;
 679   float sub = 0;
 680 
 681   SwitchRange* array1 = lo;
 682   SwitchRange* array2 = NEW_RESOURCE_ARRAY(SwitchRange, nr);
 683 
 684   SwitchRange* ranges = NULL;
 685 
 686   while (nr >= 2) {
 687     assert(lo == array1 || lo == array2, "one the 2 already allocated arrays");
 688     ranges = (lo == array1) ? array2 : array1;
 689 
 690     // Find highest frequency range
 691     SwitchRange* candidate = lo;
 692     for (SwitchRange* sr = lo+1; sr <= hi; sr++) {
 693       if (sr->cnt() > candidate->cnt()) {
 694         candidate = sr;
 695       }
 696     }
 697     SwitchRange most_freq = *candidate;
 698     if (most_freq.cnt() == 0) {
 699       break;
 700     }
 701 
 702     // Copy remaining ranges into another array
 703     int shift = 0;
 704     for (uint i = 0; i < nr; i++) {
 705       SwitchRange* sr = &lo[i];
 706       if (sr != candidate) {
 707         ranges[i-shift] = *sr;
 708       } else {
 709         shift++;
 710         if (i > 0 && i < nr-1) {
 711           SwitchRange prev = lo[i-1];
 712           prev.setRange(prev.lo(), sr->hi(), prev.dest(), prev.cnt());
 713           if (prev.adjoin(lo[i+1])) {
 714             shift++;
 715             i++;
 716           }
 717           ranges[i-shift] = prev;
 718         }
 719       }
 720     }
 721     nr -= shift;
 722 
 723     // Evaluate cost of testing the most common range and performing a
 724     // binary search on the other ranges
 725     float cost = extra + compute_tree_cost(&ranges[0], &ranges[nr-1], total_cnt);
 726     if (cost >= min) {
 727       break;
 728     }
 729     // swap arrays
 730     lo = &ranges[0];
 731     hi = &ranges[nr-1];
 732 
 733     // It pays off: emit the test for the most common range
 734     assert(most_freq.cnt() > 0, "must be taken");
 735     Node* val = _gvn.transform(new SubINode(key_val, _gvn.intcon(most_freq.lo())));
 736     Node* cmp = _gvn.transform(new CmpUNode(val, _gvn.intcon(most_freq.hi() - most_freq.lo())));
 737     Node* tst = _gvn.transform(new BoolNode(cmp, BoolTest::le));
 738     IfNode* iff = create_and_map_if(control(), tst, if_prob(most_freq.cnt(), total_cnt), if_cnt(most_freq.cnt()));
 739     jump_if_true_fork(iff, most_freq.dest(), false);
 740 
 741     sub += most_freq.cnt() / total_cnt;
 742     extra += 1 - sub;
 743     min = cost;
 744   }
 745 }
 746 
 747 //----------------------------create_jump_tables-------------------------------
 748 bool Parse::create_jump_tables(Node* key_val, SwitchRange* lo, SwitchRange* hi) {
 749   // Are jumptables enabled
 750   if (!UseJumpTables)  return false;
 751 
 752   // Are jumptables supported
 753   if (!Matcher::has_match_rule(Op_Jump))  return false;
 754 
 755   bool trim_ranges = !C->too_many_traps(method(), bci(), Deoptimization::Reason_unstable_if);
 756 
 757   // Decide if a guard is needed to lop off big ranges at either (or
 758   // both) end(s) of the input set. We'll call this the default target
 759   // even though we can't be sure that it is the true "default".
 760 
 761   bool needs_guard = false;
 762   int default_dest;
 763   int64_t total_outlier_size = 0;
 764   int64_t hi_size = ((int64_t)hi->hi()) - ((int64_t)hi->lo()) + 1;
 765   int64_t lo_size = ((int64_t)lo->hi()) - ((int64_t)lo->lo()) + 1;
 766 
 767   if (lo->dest() == hi->dest()) {
 768     total_outlier_size = hi_size + lo_size;
 769     default_dest = lo->dest();
 770   } else if (lo_size > hi_size) {
 771     total_outlier_size = lo_size;
 772     default_dest = lo->dest();
 773   } else {
 774     total_outlier_size = hi_size;
 775     default_dest = hi->dest();
 776   }
 777 
 778   float total = sum_of_cnts(lo, hi);
 779   float cost = compute_tree_cost(lo, hi, total);
 780 
 781   // If a guard test will eliminate very sparse end ranges, then
 782   // it is worth the cost of an extra jump.
 783   float trimmed_cnt = 0;
 784   if (total_outlier_size > (MaxJumpTableSparseness * 4)) {
 785     needs_guard = true;
 786     if (default_dest == lo->dest()) {
 787       trimmed_cnt += lo->cnt();
 788       lo++;
 789     }
 790     if (default_dest == hi->dest()) {
 791       trimmed_cnt += hi->cnt();
 792       hi--;
 793     }
 794   }
 795 
 796   // Find the total number of cases and ranges
 797   int64_t num_cases = ((int64_t)hi->hi()) - ((int64_t)lo->lo()) + 1;
 798   int num_range = hi - lo + 1;
 799 
 800   // Don't create table if: too large, too small, or too sparse.
 801   if (num_cases > MaxJumpTableSize)
 802     return false;
 803   if (UseSwitchProfiling) {
 804     // MinJumpTableSize is set so with a well balanced binary tree,
 805     // when the number of ranges is MinJumpTableSize, it's cheaper to
 806     // go through a JumpNode that a tree of IfNodes. Average cost of a
 807     // tree of IfNodes with MinJumpTableSize is
 808     // log2f(MinJumpTableSize) comparisons. So if the cost computed
 809     // from profile data is less than log2f(MinJumpTableSize) then
 810     // going with the binary search is cheaper.
 811     if (cost < log2f(MinJumpTableSize)) {
 812       return false;
 813     }
 814   } else {
 815     if (num_cases < MinJumpTableSize)
 816       return false;
 817   }
 818   if (num_cases > (MaxJumpTableSparseness * num_range))
 819     return false;
 820 
 821   // Normalize table lookups to zero
 822   int lowval = lo->lo();
 823   key_val = _gvn.transform( new SubINode(key_val, _gvn.intcon(lowval)) );
 824 
 825   // Generate a guard to protect against input keyvals that aren't
 826   // in the switch domain.
 827   if (needs_guard) {
 828     Node*   size = _gvn.intcon(num_cases);
 829     Node*   cmp = _gvn.transform(new CmpUNode(key_val, size));
 830     Node*   tst = _gvn.transform(new BoolNode(cmp, BoolTest::ge));
 831     IfNode* iff = create_and_map_if(control(), tst, if_prob(trimmed_cnt, total), if_cnt(trimmed_cnt));
 832     jump_if_true_fork(iff, default_dest, trim_ranges && trimmed_cnt == 0);
 833 
 834     total -= trimmed_cnt;
 835   }
 836 
 837   // Create an ideal node JumpTable that has projections
 838   // of all possible ranges for a switch statement
 839   // The key_val input must be converted to a pointer offset and scaled.
 840   // Compare Parse::array_addressing above.
 841 
 842   // Clean the 32-bit int into a real 64-bit offset.
 843   // Otherwise, the jint value 0 might turn into an offset of 0x0800000000.
 844   // Make I2L conversion control dependent to prevent it from
 845   // floating above the range check during loop optimizations.
 846   // Do not use a narrow int type here to prevent the data path from dying
 847   // while the control path is not removed. This can happen if the type of key_val
 848   // is later known to be out of bounds of [0, num_cases] and therefore a narrow cast
 849   // would be replaced by TOP while C2 is not able to fold the corresponding range checks.
 850   // Set _carry_dependency for the cast to avoid being removed by IGVN.
 851 #ifdef _LP64
 852   key_val = C->constrained_convI2L(&_gvn, key_val, TypeInt::INT, control(), true /* carry_dependency */);
 853 #endif
 854 
 855   // Shift the value by wordsize so we have an index into the table, rather
 856   // than a switch value
 857   Node *shiftWord = _gvn.MakeConX(wordSize);
 858   key_val = _gvn.transform( new MulXNode( key_val, shiftWord));
 859 
 860   // Create the JumpNode
 861   Arena* arena = C->comp_arena();
 862   float* probs = (float*)arena->Amalloc(sizeof(float)*num_cases);
 863   int i = 0;
 864   if (total == 0) {
 865     for (SwitchRange* r = lo; r <= hi; r++) {
 866       for (int64_t j = r->lo(); j <= r->hi(); j++, i++) {
 867         probs[i] = 1.0F / num_cases;
 868       }
 869     }
 870   } else {
 871     for (SwitchRange* r = lo; r <= hi; r++) {
 872       float prob = r->cnt()/total;
 873       for (int64_t j = r->lo(); j <= r->hi(); j++, i++) {
 874         probs[i] = prob / (r->hi() - r->lo() + 1);
 875       }
 876     }
 877   }
 878 
 879   ciMethodData* methodData = method()->method_data();
 880   ciMultiBranchData* profile = NULL;
 881   if (methodData->is_mature()) {
 882     ciProfileData* data = methodData->bci_to_data(bci());
 883     if (data != NULL && data->is_MultiBranchData()) {
 884       profile = (ciMultiBranchData*)data;
 885     }
 886   }
 887 
 888   Node* jtn = _gvn.transform(new JumpNode(control(), key_val, num_cases, probs, profile == NULL ? COUNT_UNKNOWN : total));
 889 
 890   // These are the switch destinations hanging off the jumpnode
 891   i = 0;
 892   for (SwitchRange* r = lo; r <= hi; r++) {
 893     for (int64_t j = r->lo(); j <= r->hi(); j++, i++) {
 894       Node* input = _gvn.transform(new JumpProjNode(jtn, i, r->dest(), (int)(j - lowval)));
 895       {
 896         PreserveJVMState pjvms(this);
 897         set_control(input);
 898         jump_if_always_fork(r->dest(), trim_ranges && r->cnt() == 0);
 899       }
 900     }
 901   }
 902   assert(i == num_cases, "miscount of cases");
 903   stop_and_kill_map();  // no more uses for this JVMS
 904   return true;
 905 }
 906 
 907 //----------------------------jump_switch_ranges-------------------------------
 908 void Parse::jump_switch_ranges(Node* key_val, SwitchRange *lo, SwitchRange *hi, int switch_depth) {
 909   Block* switch_block = block();
 910   bool trim_ranges = !C->too_many_traps(method(), bci(), Deoptimization::Reason_unstable_if);
 911 
 912   if (switch_depth == 0) {
 913     // Do special processing for the top-level call.
 914     assert(lo->lo() == min_jint, "initial range must exhaust Type::INT");
 915     assert(hi->hi() == max_jint, "initial range must exhaust Type::INT");
 916 
 917     // Decrement pred-numbers for the unique set of nodes.
 918 #ifdef ASSERT
 919     if (!trim_ranges) {
 920       // Ensure that the block's successors are a (duplicate-free) set.
 921       int successors_counted = 0;  // block occurrences in [hi..lo]
 922       int unique_successors = switch_block->num_successors();
 923       for (int i = 0; i < unique_successors; i++) {
 924         Block* target = switch_block->successor_at(i);
 925 
 926         // Check that the set of successors is the same in both places.
 927         int successors_found = 0;
 928         for (SwitchRange* p = lo; p <= hi; p++) {
 929           if (p->dest() == target->start())  successors_found++;
 930         }
 931         assert(successors_found > 0, "successor must be known");
 932         successors_counted += successors_found;
 933       }
 934       assert(successors_counted == (hi-lo)+1, "no unexpected successors");
 935     }
 936 #endif
 937 
 938     // Maybe prune the inputs, based on the type of key_val.
 939     jint min_val = min_jint;
 940     jint max_val = max_jint;
 941     const TypeInt* ti = key_val->bottom_type()->isa_int();
 942     if (ti != NULL) {
 943       min_val = ti->_lo;
 944       max_val = ti->_hi;
 945       assert(min_val <= max_val, "invalid int type");
 946     }
 947     while (lo->hi() < min_val) {
 948       lo++;
 949     }
 950     if (lo->lo() < min_val)  {
 951       lo->setRange(min_val, lo->hi(), lo->dest(), lo->cnt());
 952     }
 953     while (hi->lo() > max_val) {
 954       hi--;
 955     }
 956     if (hi->hi() > max_val) {
 957       hi->setRange(hi->lo(), max_val, hi->dest(), hi->cnt());
 958     }
 959 
 960     linear_search_switch_ranges(key_val, lo, hi);
 961   }
 962 
 963 #ifndef PRODUCT
 964   if (switch_depth == 0) {
 965     _max_switch_depth = 0;
 966     _est_switch_depth = log2i_graceful((hi - lo + 1) - 1) + 1;
 967   }
 968 #endif
 969 
 970   assert(lo <= hi, "must be a non-empty set of ranges");
 971   if (lo == hi) {
 972     jump_if_always_fork(lo->dest(), trim_ranges && lo->cnt() == 0);
 973   } else {
 974     assert(lo->hi() == (lo+1)->lo()-1, "contiguous ranges");
 975     assert(hi->lo() == (hi-1)->hi()+1, "contiguous ranges");
 976 
 977     if (create_jump_tables(key_val, lo, hi)) return;
 978 
 979     SwitchRange* mid = NULL;
 980     float total_cnt = sum_of_cnts(lo, hi);
 981 
 982     int nr = hi - lo + 1;
 983     if (UseSwitchProfiling) {
 984       // Don't keep the binary search tree balanced: pick up mid point
 985       // that split frequencies in half.
 986       float cnt = 0;
 987       for (SwitchRange* sr = lo; sr <= hi; sr++) {
 988         cnt += sr->cnt();
 989         if (cnt >= total_cnt / 2) {
 990           mid = sr;
 991           break;
 992         }
 993       }
 994     } else {
 995       mid = lo + nr/2;
 996 
 997       // if there is an easy choice, pivot at a singleton:
 998       if (nr > 3 && !mid->is_singleton() && (mid-1)->is_singleton())  mid--;
 999 
1000       assert(lo < mid && mid <= hi, "good pivot choice");
1001       assert(nr != 2 || mid == hi,   "should pick higher of 2");
1002       assert(nr != 3 || mid == hi-1, "should pick middle of 3");
1003     }
1004 
1005 
1006     Node *test_val = _gvn.intcon(mid == lo ? mid->hi() : mid->lo());
1007 
1008     if (mid->is_singleton()) {
1009       IfNode *iff_ne = jump_if_fork_int(key_val, test_val, BoolTest::ne, 1-if_prob(mid->cnt(), total_cnt), if_cnt(mid->cnt()));
1010       jump_if_false_fork(iff_ne, mid->dest(), trim_ranges && mid->cnt() == 0);
1011 
1012       // Special Case:  If there are exactly three ranges, and the high
1013       // and low range each go to the same place, omit the "gt" test,
1014       // since it will not discriminate anything.
1015       bool eq_test_only = (hi == lo+2 && hi->dest() == lo->dest() && mid == hi-1) || mid == lo;
1016 
1017       // if there is a higher range, test for it and process it:
1018       if (mid < hi && !eq_test_only) {
1019         // two comparisons of same values--should enable 1 test for 2 branches
1020         // Use BoolTest::lt instead of BoolTest::gt
1021         float cnt = sum_of_cnts(lo, mid-1);
1022         IfNode *iff_lt  = jump_if_fork_int(key_val, test_val, BoolTest::lt, if_prob(cnt, total_cnt), if_cnt(cnt));
1023         Node   *iftrue  = _gvn.transform( new IfTrueNode(iff_lt) );
1024         Node   *iffalse = _gvn.transform( new IfFalseNode(iff_lt) );
1025         { PreserveJVMState pjvms(this);
1026           set_control(iffalse);
1027           jump_switch_ranges(key_val, mid+1, hi, switch_depth+1);
1028         }
1029         set_control(iftrue);
1030       }
1031 
1032     } else {
1033       // mid is a range, not a singleton, so treat mid..hi as a unit
1034       float cnt = sum_of_cnts(mid == lo ? mid+1 : mid, hi);
1035       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));
1036 
1037       // if there is a higher range, test for it and process it:
1038       if (mid == hi) {
1039         jump_if_true_fork(iff_ge, mid->dest(), trim_ranges && cnt == 0);
1040       } else {
1041         Node *iftrue  = _gvn.transform( new IfTrueNode(iff_ge) );
1042         Node *iffalse = _gvn.transform( new IfFalseNode(iff_ge) );
1043         { PreserveJVMState pjvms(this);
1044           set_control(iftrue);
1045           jump_switch_ranges(key_val, mid == lo ? mid+1 : mid, hi, switch_depth+1);
1046         }
1047         set_control(iffalse);
1048       }
1049     }
1050 
1051     // in any case, process the lower range
1052     if (mid == lo) {
1053       if (mid->is_singleton()) {
1054         jump_switch_ranges(key_val, lo+1, hi, switch_depth+1);
1055       } else {
1056         jump_if_always_fork(lo->dest(), trim_ranges && lo->cnt() == 0);
1057       }
1058     } else {
1059       jump_switch_ranges(key_val, lo, mid-1, switch_depth+1);
1060     }
1061   }
1062 
1063   // Decrease pred_count for each successor after all is done.
1064   if (switch_depth == 0) {
1065     int unique_successors = switch_block->num_successors();
1066     for (int i = 0; i < unique_successors; i++) {
1067       Block* target = switch_block->successor_at(i);
1068       // Throw away the pre-allocated path for each unique successor.
1069       target->next_path_num();
1070     }
1071   }
1072 
1073 #ifndef PRODUCT
1074   _max_switch_depth = MAX2(switch_depth, _max_switch_depth);
1075   if (TraceOptoParse && Verbose && WizardMode && switch_depth == 0) {
1076     SwitchRange* r;
1077     int nsing = 0;
1078     for( r = lo; r <= hi; r++ ) {
1079       if( r->is_singleton() )  nsing++;
1080     }
1081     tty->print(">>> ");
1082     _method->print_short_name();
1083     tty->print_cr(" switch decision tree");
1084     tty->print_cr("    %d ranges (%d singletons), max_depth=%d, est_depth=%d",
1085                   (int) (hi-lo+1), nsing, _max_switch_depth, _est_switch_depth);
1086     if (_max_switch_depth > _est_switch_depth) {
1087       tty->print_cr("******** BAD SWITCH DEPTH ********");
1088     }
1089     tty->print("   ");
1090     for( r = lo; r <= hi; r++ ) {
1091       r->print();
1092     }
1093     tty->cr();
1094   }
1095 #endif
1096 }
1097 
1098 void Parse::modf() {
1099   Node *f2 = pop();
1100   Node *f1 = pop();
1101   Node* c = make_runtime_call(RC_LEAF, OptoRuntime::modf_Type(),
1102                               CAST_FROM_FN_PTR(address, SharedRuntime::frem),
1103                               "frem", NULL, //no memory effects
1104                               f1, f2);
1105   Node* res = _gvn.transform(new ProjNode(c, TypeFunc::Parms + 0));
1106 
1107   push(res);
1108 }
1109 
1110 void Parse::modd() {
1111   Node *d2 = pop_pair();
1112   Node *d1 = pop_pair();
1113   Node* c = make_runtime_call(RC_LEAF, OptoRuntime::Math_DD_D_Type(),
1114                               CAST_FROM_FN_PTR(address, SharedRuntime::drem),
1115                               "drem", NULL, //no memory effects
1116                               d1, top(), d2, top());
1117   Node* res_d   = _gvn.transform(new ProjNode(c, TypeFunc::Parms + 0));
1118 
1119 #ifdef ASSERT
1120   Node* res_top = _gvn.transform(new ProjNode(c, TypeFunc::Parms + 1));
1121   assert(res_top == top(), "second value must be top");
1122 #endif
1123 
1124   push_pair(res_d);
1125 }
1126 
1127 void Parse::l2f() {
1128   Node* f2 = pop();
1129   Node* f1 = pop();
1130   Node* c = make_runtime_call(RC_LEAF, OptoRuntime::l2f_Type(),
1131                               CAST_FROM_FN_PTR(address, SharedRuntime::l2f),
1132                               "l2f", NULL, //no memory effects
1133                               f1, f2);
1134   Node* res = _gvn.transform(new ProjNode(c, TypeFunc::Parms + 0));
1135 
1136   push(res);
1137 }
1138 
1139 // Handle jsr and jsr_w bytecode
1140 void Parse::do_jsr() {
1141   assert(bc() == Bytecodes::_jsr || bc() == Bytecodes::_jsr_w, "wrong bytecode");
1142 
1143   // Store information about current state, tagged with new _jsr_bci
1144   int return_bci = iter().next_bci();
1145   int jsr_bci    = (bc() == Bytecodes::_jsr) ? iter().get_dest() : iter().get_far_dest();
1146 
1147   // The way we do things now, there is only one successor block
1148   // for the jsr, because the target code is cloned by ciTypeFlow.
1149   Block* target = successor_for_bci(jsr_bci);
1150 
1151   // What got pushed?
1152   const Type* ret_addr = target->peek();
1153   assert(ret_addr->singleton(), "must be a constant (cloned jsr body)");
1154 
1155   // Effect on jsr on stack
1156   push(_gvn.makecon(ret_addr));
1157 
1158   // Flow to the jsr.
1159   merge(jsr_bci);
1160 }
1161 
1162 // Handle ret bytecode
1163 void Parse::do_ret() {
1164   // Find to whom we return.
1165   assert(block()->num_successors() == 1, "a ret can only go one place now");
1166   Block* target = block()->successor_at(0);
1167   assert(!target->is_ready(), "our arrival must be expected");
1168   int pnum = target->next_path_num();
1169   merge_common(target, pnum);
1170 }
1171 
1172 static bool has_injected_profile(BoolTest::mask btest, Node* test, int& taken, int& not_taken) {
1173   if (btest != BoolTest::eq && btest != BoolTest::ne) {
1174     // Only ::eq and ::ne are supported for profile injection.
1175     return false;
1176   }
1177   if (test->is_Cmp() &&
1178       test->in(1)->Opcode() == Op_ProfileBoolean) {
1179     ProfileBooleanNode* profile = (ProfileBooleanNode*)test->in(1);
1180     int false_cnt = profile->false_count();
1181     int  true_cnt = profile->true_count();
1182 
1183     // Counts matching depends on the actual test operation (::eq or ::ne).
1184     // No need to scale the counts because profile injection was designed
1185     // to feed exact counts into VM.
1186     taken     = (btest == BoolTest::eq) ? false_cnt :  true_cnt;
1187     not_taken = (btest == BoolTest::eq) ?  true_cnt : false_cnt;
1188 
1189     profile->consume();
1190     return true;
1191   }
1192   return false;
1193 }
1194 //--------------------------dynamic_branch_prediction--------------------------
1195 // Try to gather dynamic branch prediction behavior.  Return a probability
1196 // of the branch being taken and set the "cnt" field.  Returns a -1.0
1197 // if we need to use static prediction for some reason.
1198 float Parse::dynamic_branch_prediction(float &cnt, BoolTest::mask btest, Node* test) {
1199   ResourceMark rm;
1200 
1201   cnt  = COUNT_UNKNOWN;
1202 
1203   int     taken = 0;
1204   int not_taken = 0;
1205 
1206   bool use_mdo = !has_injected_profile(btest, test, taken, not_taken);
1207 
1208   if (use_mdo) {
1209     // Use MethodData information if it is available
1210     // FIXME: free the ProfileData structure
1211     ciMethodData* methodData = method()->method_data();
1212     if (!methodData->is_mature())  return PROB_UNKNOWN;
1213     ciProfileData* data = methodData->bci_to_data(bci());
1214     if (data == NULL) {
1215       return PROB_UNKNOWN;
1216     }
1217     if (!data->is_JumpData())  return PROB_UNKNOWN;
1218 
1219     // get taken and not taken values
1220     taken = data->as_JumpData()->taken();
1221     not_taken = 0;
1222     if (data->is_BranchData()) {
1223       not_taken = data->as_BranchData()->not_taken();
1224     }
1225 
1226     // scale the counts to be commensurate with invocation counts:
1227     taken = method()->scale_count(taken);
1228     not_taken = method()->scale_count(not_taken);
1229   }
1230 
1231   // Give up if too few (or too many, in which case the sum will overflow) counts to be meaningful.
1232   // We also check that individual counters are positive first, otherwise the sum can become positive.
1233   if (taken < 0 || not_taken < 0 || taken + not_taken < 40) {
1234     if (C->log() != NULL) {
1235       C->log()->elem("branch target_bci='%d' taken='%d' not_taken='%d'", iter().get_dest(), taken, not_taken);
1236     }
1237     return PROB_UNKNOWN;
1238   }
1239 
1240   // Compute frequency that we arrive here
1241   float sum = taken + not_taken;
1242   // Adjust, if this block is a cloned private block but the
1243   // Jump counts are shared.  Taken the private counts for
1244   // just this path instead of the shared counts.
1245   if( block()->count() > 0 )
1246     sum = block()->count();
1247   cnt = sum / FreqCountInvocations;
1248 
1249   // Pin probability to sane limits
1250   float prob;
1251   if( !taken )
1252     prob = (0+PROB_MIN) / 2;
1253   else if( !not_taken )
1254     prob = (1+PROB_MAX) / 2;
1255   else {                         // Compute probability of true path
1256     prob = (float)taken / (float)(taken + not_taken);
1257     if (prob > PROB_MAX)  prob = PROB_MAX;
1258     if (prob < PROB_MIN)   prob = PROB_MIN;
1259   }
1260 
1261   assert((cnt > 0.0f) && (prob > 0.0f),
1262          "Bad frequency assignment in if");
1263 
1264   if (C->log() != NULL) {
1265     const char* prob_str = NULL;
1266     if (prob >= PROB_MAX)  prob_str = (prob == PROB_MAX) ? "max" : "always";
1267     if (prob <= PROB_MIN)  prob_str = (prob == PROB_MIN) ? "min" : "never";
1268     char prob_str_buf[30];
1269     if (prob_str == NULL) {
1270       jio_snprintf(prob_str_buf, sizeof(prob_str_buf), "%20.2f", prob);
1271       prob_str = prob_str_buf;
1272     }
1273     C->log()->elem("branch target_bci='%d' taken='%d' not_taken='%d' cnt='%f' prob='%s'",
1274                    iter().get_dest(), taken, not_taken, cnt, prob_str);
1275   }
1276   return prob;
1277 }
1278 
1279 //-----------------------------branch_prediction-------------------------------
1280 float Parse::branch_prediction(float& cnt,
1281                                BoolTest::mask btest,
1282                                int target_bci,
1283                                Node* test) {
1284   float prob = dynamic_branch_prediction(cnt, btest, test);
1285   // If prob is unknown, switch to static prediction
1286   if (prob != PROB_UNKNOWN)  return prob;
1287 
1288   prob = PROB_FAIR;                   // Set default value
1289   if (btest == BoolTest::eq)          // Exactly equal test?
1290     prob = PROB_STATIC_INFREQUENT;    // Assume its relatively infrequent
1291   else if (btest == BoolTest::ne)
1292     prob = PROB_STATIC_FREQUENT;      // Assume its relatively frequent
1293 
1294   // If this is a conditional test guarding a backwards branch,
1295   // assume its a loop-back edge.  Make it a likely taken branch.
1296   if (target_bci < bci()) {
1297     if (is_osr_parse()) {    // Could be a hot OSR'd loop; force deopt
1298       // Since it's an OSR, we probably have profile data, but since
1299       // branch_prediction returned PROB_UNKNOWN, the counts are too small.
1300       // Let's make a special check here for completely zero counts.
1301       ciMethodData* methodData = method()->method_data();
1302       if (!methodData->is_empty()) {
1303         ciProfileData* data = methodData->bci_to_data(bci());
1304         // Only stop for truly zero counts, which mean an unknown part
1305         // of the OSR-ed method, and we want to deopt to gather more stats.
1306         // If you have ANY counts, then this loop is simply 'cold' relative
1307         // to the OSR loop.
1308         if (data == NULL ||
1309             (data->as_BranchData()->taken() +  data->as_BranchData()->not_taken() == 0)) {
1310           // This is the only way to return PROB_UNKNOWN:
1311           return PROB_UNKNOWN;
1312         }
1313       }
1314     }
1315     prob = PROB_STATIC_FREQUENT;     // Likely to take backwards branch
1316   }
1317 
1318   assert(prob != PROB_UNKNOWN, "must have some guess at this point");
1319   return prob;
1320 }
1321 
1322 // The magic constants are chosen so as to match the output of
1323 // branch_prediction() when the profile reports a zero taken count.
1324 // It is important to distinguish zero counts unambiguously, because
1325 // some branches (e.g., _213_javac.Assembler.eliminate) validly produce
1326 // very small but nonzero probabilities, which if confused with zero
1327 // counts would keep the program recompiling indefinitely.
1328 bool Parse::seems_never_taken(float prob) const {
1329   return prob < PROB_MIN;
1330 }
1331 
1332 // True if the comparison seems to be the kind that will not change its
1333 // statistics from true to false.  See comments in adjust_map_after_if.
1334 // This question is only asked along paths which are already
1335 // classifed as untaken (by seems_never_taken), so really,
1336 // if a path is never taken, its controlling comparison is
1337 // already acting in a stable fashion.  If the comparison
1338 // seems stable, we will put an expensive uncommon trap
1339 // on the untaken path.
1340 bool Parse::seems_stable_comparison() const {
1341   if (C->too_many_traps(method(), bci(), Deoptimization::Reason_unstable_if)) {
1342     return false;
1343   }
1344   return true;
1345 }
1346 
1347 //-------------------------------repush_if_args--------------------------------
1348 // Push arguments of an "if" bytecode back onto the stack by adjusting _sp.
1349 inline int Parse::repush_if_args() {
1350   if (PrintOpto && WizardMode) {
1351     tty->print("defending against excessive implicit null exceptions on %s @%d in ",
1352                Bytecodes::name(iter().cur_bc()), iter().cur_bci());
1353     method()->print_name(); tty->cr();
1354   }
1355   int bc_depth = - Bytecodes::depth(iter().cur_bc());
1356   assert(bc_depth == 1 || bc_depth == 2, "only two kinds of branches");
1357   DEBUG_ONLY(sync_jvms());   // argument(n) requires a synced jvms
1358   assert(argument(0) != NULL, "must exist");
1359   assert(bc_depth == 1 || argument(1) != NULL, "two must exist");
1360   inc_sp(bc_depth);
1361   return bc_depth;
1362 }
1363 
1364 //----------------------------------do_ifnull----------------------------------
1365 void Parse::do_ifnull(BoolTest::mask btest, Node *c) {
1366   int target_bci = iter().get_dest();
1367 
1368   Block* branch_block = successor_for_bci(target_bci);
1369   Block* next_block   = successor_for_bci(iter().next_bci());
1370 
1371   float cnt;
1372   float prob = branch_prediction(cnt, btest, target_bci, c);
1373   if (prob == PROB_UNKNOWN) {
1374     // (An earlier version of do_ifnull omitted this trap for OSR methods.)
1375     if (PrintOpto && Verbose) {
1376       tty->print_cr("Never-taken edge stops compilation at bci %d", bci());
1377     }
1378     repush_if_args(); // to gather stats on loop
1379     uncommon_trap(Deoptimization::Reason_unreached,
1380                   Deoptimization::Action_reinterpret,
1381                   NULL, "cold");
1382     if (C->eliminate_boxing()) {
1383       // Mark the successor blocks as parsed
1384       branch_block->next_path_num();
1385       next_block->next_path_num();
1386     }
1387     return;
1388   }
1389 
1390   NOT_PRODUCT(explicit_null_checks_inserted++);
1391 
1392   // Generate real control flow
1393   Node   *tst = _gvn.transform( new BoolNode( c, btest ) );
1394 
1395   // Sanity check the probability value
1396   assert(prob > 0.0f,"Bad probability in Parser");
1397  // Need xform to put node in hash table
1398   IfNode *iff = create_and_xform_if( control(), tst, prob, cnt );
1399   assert(iff->_prob > 0.0f,"Optimizer made bad probability in parser");
1400   // True branch
1401   { PreserveJVMState pjvms(this);
1402     Node* iftrue  = _gvn.transform( new IfTrueNode (iff) );
1403     set_control(iftrue);
1404 
1405     if (stopped()) {            // Path is dead?
1406       NOT_PRODUCT(explicit_null_checks_elided++);
1407       if (C->eliminate_boxing()) {
1408         // Mark the successor block as parsed
1409         branch_block->next_path_num();
1410       }
1411     } else {                    // Path is live.
1412       adjust_map_after_if(btest, c, prob, branch_block, next_block);
1413       if (!stopped()) {
1414         merge(target_bci);
1415       }
1416     }
1417   }
1418 
1419   // False branch
1420   Node* iffalse = _gvn.transform( new IfFalseNode(iff) );
1421   set_control(iffalse);
1422 
1423   if (stopped()) {              // Path is dead?
1424     NOT_PRODUCT(explicit_null_checks_elided++);
1425     if (C->eliminate_boxing()) {
1426       // Mark the successor block as parsed
1427       next_block->next_path_num();
1428     }
1429   } else  {                     // Path is live.
1430     adjust_map_after_if(BoolTest(btest).negate(), c, 1.0-prob,
1431                         next_block, branch_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, next_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,
1543                         next_block, branch_block);










































































































































































































































































































































































































1544   }
1545 }
1546 
1547 bool Parse::path_is_suitable_for_uncommon_trap(float prob) const {
1548   // Don't want to speculate on uncommon traps when running with -Xcomp
1549   if (!UseInterpreter) {
1550     return false;
1551   }
1552   return (seems_never_taken(prob) && seems_stable_comparison());
1553 }
1554 
1555 void Parse::maybe_add_predicate_after_if(Block* path) {
1556   if (path->is_SEL_head() && path->preds_parsed() == 0) {
1557     // Add predicates at bci of if dominating the loop so traps can be
1558     // recorded on the if's profile data
1559     int bc_depth = repush_if_args();
1560     add_empty_predicates();
1561     dec_sp(bc_depth);
1562     path->set_has_predicates();
1563   }
1564 }
1565 
1566 
1567 //----------------------------adjust_map_after_if------------------------------
1568 // Adjust the JVM state to reflect the result of taking this path.
1569 // Basically, it means inspecting the CmpNode controlling this
1570 // branch, seeing how it constrains a tested value, and then
1571 // deciding if it's worth our while to encode this constraint
1572 // as graph nodes in the current abstract interpretation map.
1573 void Parse::adjust_map_after_if(BoolTest::mask btest, Node* c, float prob,
1574                                 Block* path, Block* other_path) {
1575   if (!c->is_Cmp()) {
1576     maybe_add_predicate_after_if(path);
1577     return;
1578   }
1579 
1580   if (stopped() || btest == BoolTest::illegal) {
1581     return;                             // nothing to do
1582   }
1583 
1584   bool is_fallthrough = (path == successor_for_bci(iter().next_bci()));
1585 
1586   if (path_is_suitable_for_uncommon_trap(prob)) {
1587     repush_if_args();
1588     uncommon_trap(Deoptimization::Reason_unstable_if,
1589                   Deoptimization::Action_reinterpret,
1590                   NULL,
1591                   (is_fallthrough ? "taken always" : "taken never"));
1592     return;
1593   }
1594 
1595   Node* val = c->in(1);
1596   Node* con = c->in(2);
1597   const Type* tcon = _gvn.type(con);
1598   const Type* tval = _gvn.type(val);
1599   bool have_con = tcon->singleton();
1600   if (tval->singleton()) {
1601     if (!have_con) {
1602       // Swap, so constant is in con.
1603       con  = val;
1604       tcon = tval;
1605       val  = c->in(2);
1606       tval = _gvn.type(val);
1607       btest = BoolTest(btest).commute();
1608       have_con = true;
1609     } else {
1610       // Do we have two constants?  Then leave well enough alone.
1611       have_con = false;
1612     }
1613   }
1614   if (!have_con) {                        // remaining adjustments need a con
1615     maybe_add_predicate_after_if(path);
1616     return;
1617   }
1618 
1619   sharpen_type_after_if(btest, con, tcon, val, tval);
1620   maybe_add_predicate_after_if(path);
1621 }
1622 
1623 
1624 static Node* extract_obj_from_klass_load(PhaseGVN* gvn, Node* n) {
1625   Node* ldk;
1626   if (n->is_DecodeNKlass()) {
1627     if (n->in(1)->Opcode() != Op_LoadNKlass) {
1628       return NULL;
1629     } else {
1630       ldk = n->in(1);
1631     }
1632   } else if (n->Opcode() != Op_LoadKlass) {
1633     return NULL;
1634   } else {
1635     ldk = n;
1636   }
1637   assert(ldk != NULL && ldk->is_Load(), "should have found a LoadKlass or LoadNKlass node");
1638 
1639   Node* adr = ldk->in(MemNode::Address);
1640   intptr_t off = 0;
1641   Node* obj = AddPNode::Ideal_base_and_offset(adr, gvn, off);
1642   if (obj == NULL || off != oopDesc::klass_offset_in_bytes()) // loading oopDesc::_klass?
1643     return NULL;
1644   const TypePtr* tp = gvn->type(obj)->is_ptr();
1645   if (tp == NULL || !(tp->isa_instptr() || tp->isa_aryptr())) // is obj a Java object ptr?
1646     return NULL;
1647 
1648   return obj;
1649 }
1650 
1651 void Parse::sharpen_type_after_if(BoolTest::mask btest,
1652                                   Node* con, const Type* tcon,
1653                                   Node* val, const Type* tval) {
1654   // Look for opportunities to sharpen the type of a node
1655   // whose klass is compared with a constant klass.
1656   if (btest == BoolTest::eq && tcon->isa_klassptr()) {
1657     Node* obj = extract_obj_from_klass_load(&_gvn, val);
1658     const TypeOopPtr* con_type = tcon->isa_klassptr()->as_instance_type();
1659     if (obj != NULL && (con_type->isa_instptr() || con_type->isa_aryptr())) {
1660        // Found:
1661        //   Bool(CmpP(LoadKlass(obj._klass), ConP(Foo.klass)), [eq])
1662        // or the narrowOop equivalent.
1663        const Type* obj_type = _gvn.type(obj);
1664        const TypeOopPtr* tboth = obj_type->join_speculative(con_type)->isa_oopptr();
1665        if (tboth != NULL && tboth->klass_is_exact() && tboth != obj_type &&
1666            tboth->higher_equal(obj_type)) {
1667           // obj has to be of the exact type Foo if the CmpP succeeds.
1668           int obj_in_map = map()->find_edge(obj);
1669           JVMState* jvms = this->jvms();
1670           if (obj_in_map >= 0 &&
1671               (jvms->is_loc(obj_in_map) || jvms->is_stk(obj_in_map))) {
1672             TypeNode* ccast = new CheckCastPPNode(control(), obj, tboth);
1673             const Type* tcc = ccast->as_Type()->type();
1674             assert(tcc != obj_type && tcc->higher_equal(obj_type), "must improve");
1675             // Delay transform() call to allow recovery of pre-cast value
1676             // at the control merge.
1677             _gvn.set_type_bottom(ccast);
1678             record_for_igvn(ccast);
1679             // Here's the payoff.
1680             replace_in_map(obj, ccast);
1681           }
1682        }
1683     }
1684   }
1685 
1686   int val_in_map = map()->find_edge(val);
1687   if (val_in_map < 0)  return;          // replace_in_map would be useless
1688   {
1689     JVMState* jvms = this->jvms();
1690     if (!(jvms->is_loc(val_in_map) ||
1691           jvms->is_stk(val_in_map)))
1692       return;                           // again, it would be useless
1693   }
1694 
1695   // Check for a comparison to a constant, and "know" that the compared
1696   // value is constrained on this path.
1697   assert(tcon->singleton(), "");
1698   ConstraintCastNode* ccast = NULL;
1699   Node* cast = NULL;
1700 
1701   switch (btest) {
1702   case BoolTest::eq:                    // Constant test?
1703     {
1704       const Type* tboth = tcon->join_speculative(tval);
1705       if (tboth == tval)  break;        // Nothing to gain.
1706       if (tcon->isa_int()) {
1707         ccast = new CastIINode(val, tboth);
1708       } else if (tcon == TypePtr::NULL_PTR) {
1709         // Cast to null, but keep the pointer identity temporarily live.
1710         ccast = new CastPPNode(val, tboth);
1711       } else {
1712         const TypeF* tf = tcon->isa_float_constant();
1713         const TypeD* td = tcon->isa_double_constant();
1714         // Exclude tests vs float/double 0 as these could be
1715         // either +0 or -0.  Just because you are equal to +0
1716         // doesn't mean you ARE +0!
1717         // Note, following code also replaces Long and Oop values.
1718         if ((!tf || tf->_f != 0.0) &&
1719             (!td || td->_d != 0.0))
1720           cast = con;                   // Replace non-constant val by con.
1721       }
1722     }
1723     break;
1724 
1725   case BoolTest::ne:
1726     if (tcon == TypePtr::NULL_PTR) {
1727       cast = cast_not_null(val, false);
1728     }
1729     break;
1730 
1731   default:
1732     // (At this point we could record int range types with CastII.)
1733     break;
1734   }
1735 
1736   if (ccast != NULL) {
1737     const Type* tcc = ccast->as_Type()->type();
1738     assert(tcc != tval && tcc->higher_equal(tval), "must improve");
1739     // Delay transform() call to allow recovery of pre-cast value
1740     // at the control merge.
1741     ccast->set_req(0, control());
1742     _gvn.set_type_bottom(ccast);
1743     record_for_igvn(ccast);
1744     cast = ccast;
1745   }
1746 
1747   if (cast != NULL) {                   // Here's the payoff.
1748     replace_in_map(val, cast);
1749   }
1750 }
1751 
1752 /**
1753  * Use speculative type to optimize CmpP node: if comparison is
1754  * against the low level class, cast the object to the speculative
1755  * type if any. CmpP should then go away.
1756  *
1757  * @param c  expected CmpP node
1758  * @return   result of CmpP on object casted to speculative type
1759  *
1760  */
1761 Node* Parse::optimize_cmp_with_klass(Node* c) {
1762   // If this is transformed by the _gvn to a comparison with the low
1763   // level klass then we may be able to use speculation
1764   if (c->Opcode() == Op_CmpP &&
1765       (c->in(1)->Opcode() == Op_LoadKlass || c->in(1)->Opcode() == Op_DecodeNKlass) &&
1766       c->in(2)->is_Con()) {
1767     Node* load_klass = NULL;
1768     Node* decode = NULL;
1769     if (c->in(1)->Opcode() == Op_DecodeNKlass) {
1770       decode = c->in(1);
1771       load_klass = c->in(1)->in(1);
1772     } else {
1773       load_klass = c->in(1);
1774     }
1775     if (load_klass->in(2)->is_AddP()) {
1776       Node* addp = load_klass->in(2);
1777       Node* obj = addp->in(AddPNode::Address);
1778       const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();
1779       if (obj_type->speculative_type_not_null() != NULL) {
1780         ciKlass* k = obj_type->speculative_type();
1781         inc_sp(2);
1782         obj = maybe_cast_profiled_obj(obj, k);
1783         dec_sp(2);




1784         // Make the CmpP use the casted obj
1785         addp = basic_plus_adr(obj, addp->in(AddPNode::Offset));
1786         load_klass = load_klass->clone();
1787         load_klass->set_req(2, addp);
1788         load_klass = _gvn.transform(load_klass);
1789         if (decode != NULL) {
1790           decode = decode->clone();
1791           decode->set_req(1, load_klass);
1792           load_klass = _gvn.transform(decode);
1793         }
1794         c = c->clone();
1795         c->set_req(1, load_klass);
1796         c = _gvn.transform(c);
1797       }
1798     }
1799   }
1800   return c;
1801 }
1802 
1803 //------------------------------do_one_bytecode--------------------------------
1804 // Parse this bytecode, and alter the Parsers JVM->Node mapping
1805 void Parse::do_one_bytecode() {
1806   Node *a, *b, *c, *d;          // Handy temps
1807   BoolTest::mask btest;
1808   int i;
1809 
1810   assert(!has_exceptions(), "bytecode entry state must be clear of throws");
1811 
1812   if (C->check_node_count(NodeLimitFudgeFactor * 5,
1813                           "out of nodes parsing method")) {
1814     return;
1815   }
1816 
1817 #ifdef ASSERT
1818   // for setting breakpoints
1819   if (TraceOptoParse) {
1820     tty->print(" @");
1821     dump_bci(bci());
1822     tty->cr();
1823   }
1824 #endif
1825 
1826   switch (bc()) {
1827   case Bytecodes::_nop:
1828     // do nothing
1829     break;
1830   case Bytecodes::_lconst_0:
1831     push_pair(longcon(0));
1832     break;
1833 
1834   case Bytecodes::_lconst_1:
1835     push_pair(longcon(1));
1836     break;
1837 
1838   case Bytecodes::_fconst_0:
1839     push(zerocon(T_FLOAT));
1840     break;
1841 
1842   case Bytecodes::_fconst_1:
1843     push(makecon(TypeF::ONE));
1844     break;
1845 
1846   case Bytecodes::_fconst_2:
1847     push(makecon(TypeF::make(2.0f)));
1848     break;
1849 
1850   case Bytecodes::_dconst_0:
1851     push_pair(zerocon(T_DOUBLE));
1852     break;
1853 
1854   case Bytecodes::_dconst_1:
1855     push_pair(makecon(TypeD::ONE));
1856     break;
1857 
1858   case Bytecodes::_iconst_m1:push(intcon(-1)); break;
1859   case Bytecodes::_iconst_0: push(intcon( 0)); break;
1860   case Bytecodes::_iconst_1: push(intcon( 1)); break;
1861   case Bytecodes::_iconst_2: push(intcon( 2)); break;
1862   case Bytecodes::_iconst_3: push(intcon( 3)); break;
1863   case Bytecodes::_iconst_4: push(intcon( 4)); break;
1864   case Bytecodes::_iconst_5: push(intcon( 5)); break;
1865   case Bytecodes::_bipush:   push(intcon(iter().get_constant_u1())); break;
1866   case Bytecodes::_sipush:   push(intcon(iter().get_constant_u2())); break;
1867   case Bytecodes::_aconst_null: push(null());  break;
1868 
1869   case Bytecodes::_ldc:
1870   case Bytecodes::_ldc_w:
1871   case Bytecodes::_ldc2_w: {
1872     ciConstant constant = iter().get_constant();
1873     if (constant.is_loaded()) {
1874       const Type* con_type = Type::make_from_constant(constant);
1875       if (con_type != NULL) {
1876         push_node(con_type->basic_type(), makecon(con_type));
1877       }
1878     } else {
1879       // If the constant is unresolved or in error state, run this BC in the interpreter.
1880       if (iter().is_in_error()) {
1881         uncommon_trap(Deoptimization::make_trap_request(Deoptimization::Reason_unhandled,
1882                                                         Deoptimization::Action_none),
1883                       NULL, "constant in error state", true /* must_throw */);
1884 
1885       } else {
1886         int index = iter().get_constant_pool_index();
1887         uncommon_trap(Deoptimization::make_trap_request(Deoptimization::Reason_unloaded,
1888                                                         Deoptimization::Action_reinterpret,
1889                                                         index),
1890                       NULL, "unresolved constant", false /* must_throw */);
1891       }
1892     }
1893     break;
1894   }
1895 
1896   case Bytecodes::_aload_0:
1897     push( local(0) );
1898     break;
1899   case Bytecodes::_aload_1:
1900     push( local(1) );
1901     break;
1902   case Bytecodes::_aload_2:
1903     push( local(2) );
1904     break;
1905   case Bytecodes::_aload_3:
1906     push( local(3) );
1907     break;
1908   case Bytecodes::_aload:
1909     push( local(iter().get_index()) );
1910     break;
1911 
1912   case Bytecodes::_fload_0:
1913   case Bytecodes::_iload_0:
1914     push( local(0) );
1915     break;
1916   case Bytecodes::_fload_1:
1917   case Bytecodes::_iload_1:
1918     push( local(1) );
1919     break;
1920   case Bytecodes::_fload_2:
1921   case Bytecodes::_iload_2:
1922     push( local(2) );
1923     break;
1924   case Bytecodes::_fload_3:
1925   case Bytecodes::_iload_3:
1926     push( local(3) );
1927     break;
1928   case Bytecodes::_fload:
1929   case Bytecodes::_iload:
1930     push( local(iter().get_index()) );
1931     break;
1932   case Bytecodes::_lload_0:
1933     push_pair_local( 0 );
1934     break;
1935   case Bytecodes::_lload_1:
1936     push_pair_local( 1 );
1937     break;
1938   case Bytecodes::_lload_2:
1939     push_pair_local( 2 );
1940     break;
1941   case Bytecodes::_lload_3:
1942     push_pair_local( 3 );
1943     break;
1944   case Bytecodes::_lload:
1945     push_pair_local( iter().get_index() );
1946     break;
1947 
1948   case Bytecodes::_dload_0:
1949     push_pair_local(0);
1950     break;
1951   case Bytecodes::_dload_1:
1952     push_pair_local(1);
1953     break;
1954   case Bytecodes::_dload_2:
1955     push_pair_local(2);
1956     break;
1957   case Bytecodes::_dload_3:
1958     push_pair_local(3);
1959     break;
1960   case Bytecodes::_dload:
1961     push_pair_local(iter().get_index());
1962     break;
1963   case Bytecodes::_fstore_0:
1964   case Bytecodes::_istore_0:
1965   case Bytecodes::_astore_0:
1966     set_local( 0, pop() );
1967     break;
1968   case Bytecodes::_fstore_1:
1969   case Bytecodes::_istore_1:
1970   case Bytecodes::_astore_1:
1971     set_local( 1, pop() );
1972     break;
1973   case Bytecodes::_fstore_2:
1974   case Bytecodes::_istore_2:
1975   case Bytecodes::_astore_2:
1976     set_local( 2, pop() );
1977     break;
1978   case Bytecodes::_fstore_3:
1979   case Bytecodes::_istore_3:
1980   case Bytecodes::_astore_3:
1981     set_local( 3, pop() );
1982     break;
1983   case Bytecodes::_fstore:
1984   case Bytecodes::_istore:
1985   case Bytecodes::_astore:
1986     set_local( iter().get_index(), pop() );
1987     break;
1988   // long stores
1989   case Bytecodes::_lstore_0:
1990     set_pair_local( 0, pop_pair() );
1991     break;
1992   case Bytecodes::_lstore_1:
1993     set_pair_local( 1, pop_pair() );
1994     break;
1995   case Bytecodes::_lstore_2:
1996     set_pair_local( 2, pop_pair() );
1997     break;
1998   case Bytecodes::_lstore_3:
1999     set_pair_local( 3, pop_pair() );
2000     break;
2001   case Bytecodes::_lstore:
2002     set_pair_local( iter().get_index(), pop_pair() );
2003     break;
2004 
2005   // double stores
2006   case Bytecodes::_dstore_0:
2007     set_pair_local( 0, dprecision_rounding(pop_pair()) );
2008     break;
2009   case Bytecodes::_dstore_1:
2010     set_pair_local( 1, dprecision_rounding(pop_pair()) );
2011     break;
2012   case Bytecodes::_dstore_2:
2013     set_pair_local( 2, dprecision_rounding(pop_pair()) );
2014     break;
2015   case Bytecodes::_dstore_3:
2016     set_pair_local( 3, dprecision_rounding(pop_pair()) );
2017     break;
2018   case Bytecodes::_dstore:
2019     set_pair_local( iter().get_index(), dprecision_rounding(pop_pair()) );
2020     break;
2021 
2022   case Bytecodes::_pop:  dec_sp(1);   break;
2023   case Bytecodes::_pop2: dec_sp(2);   break;
2024   case Bytecodes::_swap:
2025     a = pop();
2026     b = pop();
2027     push(a);
2028     push(b);
2029     break;
2030   case Bytecodes::_dup:
2031     a = pop();
2032     push(a);
2033     push(a);
2034     break;
2035   case Bytecodes::_dup_x1:
2036     a = pop();
2037     b = pop();
2038     push( a );
2039     push( b );
2040     push( a );
2041     break;
2042   case Bytecodes::_dup_x2:
2043     a = pop();
2044     b = pop();
2045     c = pop();
2046     push( a );
2047     push( c );
2048     push( b );
2049     push( a );
2050     break;
2051   case Bytecodes::_dup2:
2052     a = pop();
2053     b = pop();
2054     push( b );
2055     push( a );
2056     push( b );
2057     push( a );
2058     break;
2059 
2060   case Bytecodes::_dup2_x1:
2061     // before: .. c, b, a
2062     // after:  .. b, a, c, b, a
2063     // not tested
2064     a = pop();
2065     b = pop();
2066     c = pop();
2067     push( b );
2068     push( a );
2069     push( c );
2070     push( b );
2071     push( a );
2072     break;
2073   case Bytecodes::_dup2_x2:
2074     // before: .. d, c, b, a
2075     // after:  .. b, a, d, c, b, a
2076     // not tested
2077     a = pop();
2078     b = pop();
2079     c = pop();
2080     d = pop();
2081     push( b );
2082     push( a );
2083     push( d );
2084     push( c );
2085     push( b );
2086     push( a );
2087     break;
2088 
2089   case Bytecodes::_arraylength: {
2090     // Must do null-check with value on expression stack
2091     Node *ary = null_check(peek(), T_ARRAY);
2092     // Compile-time detect of null-exception?
2093     if (stopped())  return;
2094     a = pop();
2095     push(load_array_length(a));
2096     break;
2097   }
2098 
2099   case Bytecodes::_baload:  array_load(T_BYTE);    break;
2100   case Bytecodes::_caload:  array_load(T_CHAR);    break;
2101   case Bytecodes::_iaload:  array_load(T_INT);     break;
2102   case Bytecodes::_saload:  array_load(T_SHORT);   break;
2103   case Bytecodes::_faload:  array_load(T_FLOAT);   break;
2104   case Bytecodes::_aaload:  array_load(T_OBJECT);  break;
2105   case Bytecodes::_laload:  array_load(T_LONG);    break;
2106   case Bytecodes::_daload:  array_load(T_DOUBLE);  break;
2107   case Bytecodes::_bastore: array_store(T_BYTE);   break;
2108   case Bytecodes::_castore: array_store(T_CHAR);   break;
2109   case Bytecodes::_iastore: array_store(T_INT);    break;
2110   case Bytecodes::_sastore: array_store(T_SHORT);  break;
2111   case Bytecodes::_fastore: array_store(T_FLOAT);  break;
2112   case Bytecodes::_aastore: array_store(T_OBJECT); break;
2113   case Bytecodes::_lastore: array_store(T_LONG);   break;
2114   case Bytecodes::_dastore: array_store(T_DOUBLE); break;
2115 
2116   case Bytecodes::_getfield:
2117     do_getfield();
2118     break;
2119 
2120   case Bytecodes::_getstatic:
2121     do_getstatic();
2122     break;
2123 
2124   case Bytecodes::_putfield:
2125     do_putfield();
2126     break;
2127 
2128   case Bytecodes::_putstatic:
2129     do_putstatic();
2130     break;
2131 
2132   case Bytecodes::_irem:
2133     // Must keep both values on the expression-stack during null-check
2134     zero_check_int(peek());
2135     // Compile-time detect of null-exception?
2136     if (stopped())  return;
2137     b = pop();
2138     a = pop();
2139     push(_gvn.transform(new ModINode(control(), a, b)));
2140     break;
2141   case Bytecodes::_idiv:
2142     // Must keep both values on the expression-stack during null-check
2143     zero_check_int(peek());
2144     // Compile-time detect of null-exception?
2145     if (stopped())  return;
2146     b = pop();
2147     a = pop();
2148     push( _gvn.transform( new DivINode(control(),a,b) ) );
2149     break;
2150   case Bytecodes::_imul:
2151     b = pop(); a = pop();
2152     push( _gvn.transform( new MulINode(a,b) ) );
2153     break;
2154   case Bytecodes::_iadd:
2155     b = pop(); a = pop();
2156     push( _gvn.transform( new AddINode(a,b) ) );
2157     break;
2158   case Bytecodes::_ineg:
2159     a = pop();
2160     push( _gvn.transform( new SubINode(_gvn.intcon(0),a)) );
2161     break;
2162   case Bytecodes::_isub:
2163     b = pop(); a = pop();
2164     push( _gvn.transform( new SubINode(a,b) ) );
2165     break;
2166   case Bytecodes::_iand:
2167     b = pop(); a = pop();
2168     push( _gvn.transform( new AndINode(a,b) ) );
2169     break;
2170   case Bytecodes::_ior:
2171     b = pop(); a = pop();
2172     push( _gvn.transform( new OrINode(a,b) ) );
2173     break;
2174   case Bytecodes::_ixor:
2175     b = pop(); a = pop();
2176     push( _gvn.transform( new XorINode(a,b) ) );
2177     break;
2178   case Bytecodes::_ishl:
2179     b = pop(); a = pop();
2180     push( _gvn.transform( new LShiftINode(a,b) ) );
2181     break;
2182   case Bytecodes::_ishr:
2183     b = pop(); a = pop();
2184     push( _gvn.transform( new RShiftINode(a,b) ) );
2185     break;
2186   case Bytecodes::_iushr:
2187     b = pop(); a = pop();
2188     push( _gvn.transform( new URShiftINode(a,b) ) );
2189     break;
2190 
2191   case Bytecodes::_fneg:
2192     a = pop();
2193     b = _gvn.transform(new NegFNode (a));
2194     push(b);
2195     break;
2196 
2197   case Bytecodes::_fsub:
2198     b = pop();
2199     a = pop();
2200     c = _gvn.transform( new SubFNode(a,b) );
2201     d = precision_rounding(c);
2202     push( d );
2203     break;
2204 
2205   case Bytecodes::_fadd:
2206     b = pop();
2207     a = pop();
2208     c = _gvn.transform( new AddFNode(a,b) );
2209     d = precision_rounding(c);
2210     push( d );
2211     break;
2212 
2213   case Bytecodes::_fmul:
2214     b = pop();
2215     a = pop();
2216     c = _gvn.transform( new MulFNode(a,b) );
2217     d = precision_rounding(c);
2218     push( d );
2219     break;
2220 
2221   case Bytecodes::_fdiv:
2222     b = pop();
2223     a = pop();
2224     c = _gvn.transform( new DivFNode(0,a,b) );
2225     d = precision_rounding(c);
2226     push( d );
2227     break;
2228 
2229   case Bytecodes::_frem:
2230     if (Matcher::has_match_rule(Op_ModF)) {
2231       // Generate a ModF node.
2232       b = pop();
2233       a = pop();
2234       c = _gvn.transform( new ModFNode(0,a,b) );
2235       d = precision_rounding(c);
2236       push( d );
2237     }
2238     else {
2239       // Generate a call.
2240       modf();
2241     }
2242     break;
2243 
2244   case Bytecodes::_fcmpl:
2245     b = pop();
2246     a = pop();
2247     c = _gvn.transform( new CmpF3Node( a, b));
2248     push(c);
2249     break;
2250   case Bytecodes::_fcmpg:
2251     b = pop();
2252     a = pop();
2253 
2254     // Same as fcmpl but need to flip the unordered case.  Swap the inputs,
2255     // which negates the result sign except for unordered.  Flip the unordered
2256     // as well by using CmpF3 which implements unordered-lesser instead of
2257     // unordered-greater semantics.  Finally, commute the result bits.  Result
2258     // is same as using a CmpF3Greater except we did it with CmpF3 alone.
2259     c = _gvn.transform( new CmpF3Node( b, a));
2260     c = _gvn.transform( new SubINode(_gvn.intcon(0),c) );
2261     push(c);
2262     break;
2263 
2264   case Bytecodes::_f2i:
2265     a = pop();
2266     push(_gvn.transform(new ConvF2INode(a)));
2267     break;
2268 
2269   case Bytecodes::_d2i:
2270     a = pop_pair();
2271     b = _gvn.transform(new ConvD2INode(a));
2272     push( b );
2273     break;
2274 
2275   case Bytecodes::_f2d:
2276     a = pop();
2277     b = _gvn.transform( new ConvF2DNode(a));
2278     push_pair( b );
2279     break;
2280 
2281   case Bytecodes::_d2f:
2282     a = pop_pair();
2283     b = _gvn.transform( new ConvD2FNode(a));
2284     // This breaks _227_mtrt (speed & correctness) and _222_mpegaudio (speed)
2285     //b = _gvn.transform(new RoundFloatNode(0, b) );
2286     push( b );
2287     break;
2288 
2289   case Bytecodes::_l2f:
2290     if (Matcher::convL2FSupported()) {
2291       a = pop_pair();
2292       b = _gvn.transform( new ConvL2FNode(a));
2293       // For x86_32.ad, FILD doesn't restrict precision to 24 or 53 bits.
2294       // Rather than storing the result into an FP register then pushing
2295       // out to memory to round, the machine instruction that implements
2296       // ConvL2D is responsible for rounding.
2297       // c = precision_rounding(b);
2298       push(b);
2299     } else {
2300       l2f();
2301     }
2302     break;
2303 
2304   case Bytecodes::_l2d:
2305     a = pop_pair();
2306     b = _gvn.transform( new ConvL2DNode(a));
2307     // For x86_32.ad, rounding is always necessary (see _l2f above).
2308     // c = dprecision_rounding(b);
2309     push_pair(b);
2310     break;
2311 
2312   case Bytecodes::_f2l:
2313     a = pop();
2314     b = _gvn.transform( new ConvF2LNode(a));
2315     push_pair(b);
2316     break;
2317 
2318   case Bytecodes::_d2l:
2319     a = pop_pair();
2320     b = _gvn.transform( new ConvD2LNode(a));
2321     push_pair(b);
2322     break;
2323 
2324   case Bytecodes::_dsub:
2325     b = pop_pair();
2326     a = pop_pair();
2327     c = _gvn.transform( new SubDNode(a,b) );
2328     d = dprecision_rounding(c);
2329     push_pair( d );
2330     break;
2331 
2332   case Bytecodes::_dadd:
2333     b = pop_pair();
2334     a = pop_pair();
2335     c = _gvn.transform( new AddDNode(a,b) );
2336     d = dprecision_rounding(c);
2337     push_pair( d );
2338     break;
2339 
2340   case Bytecodes::_dmul:
2341     b = pop_pair();
2342     a = pop_pair();
2343     c = _gvn.transform( new MulDNode(a,b) );
2344     d = dprecision_rounding(c);
2345     push_pair( d );
2346     break;
2347 
2348   case Bytecodes::_ddiv:
2349     b = pop_pair();
2350     a = pop_pair();
2351     c = _gvn.transform( new DivDNode(0,a,b) );
2352     d = dprecision_rounding(c);
2353     push_pair( d );
2354     break;
2355 
2356   case Bytecodes::_dneg:
2357     a = pop_pair();
2358     b = _gvn.transform(new NegDNode (a));
2359     push_pair(b);
2360     break;
2361 
2362   case Bytecodes::_drem:
2363     if (Matcher::has_match_rule(Op_ModD)) {
2364       // Generate a ModD node.
2365       b = pop_pair();
2366       a = pop_pair();
2367       // a % b
2368 
2369       c = _gvn.transform( new ModDNode(0,a,b) );
2370       d = dprecision_rounding(c);
2371       push_pair( d );
2372     }
2373     else {
2374       // Generate a call.
2375       modd();
2376     }
2377     break;
2378 
2379   case Bytecodes::_dcmpl:
2380     b = pop_pair();
2381     a = pop_pair();
2382     c = _gvn.transform( new CmpD3Node( a, b));
2383     push(c);
2384     break;
2385 
2386   case Bytecodes::_dcmpg:
2387     b = pop_pair();
2388     a = pop_pair();
2389     // Same as dcmpl but need to flip the unordered case.
2390     // Commute the inputs, which negates the result sign except for unordered.
2391     // Flip the unordered as well by using CmpD3 which implements
2392     // unordered-lesser instead of unordered-greater semantics.
2393     // Finally, negate the result bits.  Result is same as using a
2394     // CmpD3Greater except we did it with CmpD3 alone.
2395     c = _gvn.transform( new CmpD3Node( b, a));
2396     c = _gvn.transform( new SubINode(_gvn.intcon(0),c) );
2397     push(c);
2398     break;
2399 
2400 
2401     // Note for longs -> lo word is on TOS, hi word is on TOS - 1
2402   case Bytecodes::_land:
2403     b = pop_pair();
2404     a = pop_pair();
2405     c = _gvn.transform( new AndLNode(a,b) );
2406     push_pair(c);
2407     break;
2408   case Bytecodes::_lor:
2409     b = pop_pair();
2410     a = pop_pair();
2411     c = _gvn.transform( new OrLNode(a,b) );
2412     push_pair(c);
2413     break;
2414   case Bytecodes::_lxor:
2415     b = pop_pair();
2416     a = pop_pair();
2417     c = _gvn.transform( new XorLNode(a,b) );
2418     push_pair(c);
2419     break;
2420 
2421   case Bytecodes::_lshl:
2422     b = pop();                  // the shift count
2423     a = pop_pair();             // value to be shifted
2424     c = _gvn.transform( new LShiftLNode(a,b) );
2425     push_pair(c);
2426     break;
2427   case Bytecodes::_lshr:
2428     b = pop();                  // the shift count
2429     a = pop_pair();             // value to be shifted
2430     c = _gvn.transform( new RShiftLNode(a,b) );
2431     push_pair(c);
2432     break;
2433   case Bytecodes::_lushr:
2434     b = pop();                  // the shift count
2435     a = pop_pair();             // value to be shifted
2436     c = _gvn.transform( new URShiftLNode(a,b) );
2437     push_pair(c);
2438     break;
2439   case Bytecodes::_lmul:
2440     b = pop_pair();
2441     a = pop_pair();
2442     c = _gvn.transform( new MulLNode(a,b) );
2443     push_pair(c);
2444     break;
2445 
2446   case Bytecodes::_lrem:
2447     // Must keep both values on the expression-stack during null-check
2448     assert(peek(0) == top(), "long word order");
2449     zero_check_long(peek(1));
2450     // Compile-time detect of null-exception?
2451     if (stopped())  return;
2452     b = pop_pair();
2453     a = pop_pair();
2454     c = _gvn.transform( new ModLNode(control(),a,b) );
2455     push_pair(c);
2456     break;
2457 
2458   case Bytecodes::_ldiv:
2459     // Must keep both values on the expression-stack during null-check
2460     assert(peek(0) == top(), "long word order");
2461     zero_check_long(peek(1));
2462     // Compile-time detect of null-exception?
2463     if (stopped())  return;
2464     b = pop_pair();
2465     a = pop_pair();
2466     c = _gvn.transform( new DivLNode(control(),a,b) );
2467     push_pair(c);
2468     break;
2469 
2470   case Bytecodes::_ladd:
2471     b = pop_pair();
2472     a = pop_pair();
2473     c = _gvn.transform( new AddLNode(a,b) );
2474     push_pair(c);
2475     break;
2476   case Bytecodes::_lsub:
2477     b = pop_pair();
2478     a = pop_pair();
2479     c = _gvn.transform( new SubLNode(a,b) );
2480     push_pair(c);
2481     break;
2482   case Bytecodes::_lcmp:
2483     // Safepoints are now inserted _before_ branches.  The long-compare
2484     // bytecode painfully produces a 3-way value (-1,0,+1) which requires a
2485     // slew of control flow.  These are usually followed by a CmpI vs zero and
2486     // a branch; this pattern then optimizes to the obvious long-compare and
2487     // branch.  However, if the branch is backwards there's a Safepoint
2488     // inserted.  The inserted Safepoint captures the JVM state at the
2489     // pre-branch point, i.e. it captures the 3-way value.  Thus if a
2490     // long-compare is used to control a loop the debug info will force
2491     // computation of the 3-way value, even though the generated code uses a
2492     // long-compare and branch.  We try to rectify the situation by inserting
2493     // a SafePoint here and have it dominate and kill the safepoint added at a
2494     // following backwards branch.  At this point the JVM state merely holds 2
2495     // longs but not the 3-way value.
2496     switch (iter().next_bc()) {
2497       case Bytecodes::_ifgt:
2498       case Bytecodes::_iflt:
2499       case Bytecodes::_ifge:
2500       case Bytecodes::_ifle:
2501       case Bytecodes::_ifne:
2502       case Bytecodes::_ifeq:
2503         // If this is a backwards branch in the bytecodes, add Safepoint
2504         maybe_add_safepoint(iter().next_get_dest());
2505       default:
2506         break;
2507     }
2508     b = pop_pair();
2509     a = pop_pair();
2510     c = _gvn.transform( new CmpL3Node( a, b ));
2511     push(c);
2512     break;
2513 
2514   case Bytecodes::_lneg:
2515     a = pop_pair();
2516     b = _gvn.transform( new SubLNode(longcon(0),a));
2517     push_pair(b);
2518     break;
2519   case Bytecodes::_l2i:
2520     a = pop_pair();
2521     push( _gvn.transform( new ConvL2INode(a)));
2522     break;
2523   case Bytecodes::_i2l:
2524     a = pop();
2525     b = _gvn.transform( new ConvI2LNode(a));
2526     push_pair(b);
2527     break;
2528   case Bytecodes::_i2b:
2529     // Sign extend
2530     a = pop();
2531     a = Compile::narrow_value(T_BYTE, a, NULL, &_gvn, true);
2532     push(a);
2533     break;
2534   case Bytecodes::_i2s:
2535     a = pop();
2536     a = Compile::narrow_value(T_SHORT, a, NULL, &_gvn, true);
2537     push(a);
2538     break;
2539   case Bytecodes::_i2c:
2540     a = pop();
2541     a = Compile::narrow_value(T_CHAR, a, NULL, &_gvn, true);
2542     push(a);
2543     break;
2544 
2545   case Bytecodes::_i2f:
2546     a = pop();
2547     b = _gvn.transform( new ConvI2FNode(a) ) ;
2548     c = precision_rounding(b);
2549     push (b);
2550     break;
2551 
2552   case Bytecodes::_i2d:
2553     a = pop();
2554     b = _gvn.transform( new ConvI2DNode(a));
2555     push_pair(b);
2556     break;
2557 
2558   case Bytecodes::_iinc:        // Increment local
2559     i = iter().get_index();     // Get local index
2560     set_local( i, _gvn.transform( new AddINode( _gvn.intcon(iter().get_iinc_con()), local(i) ) ) );
2561     break;
2562 
2563   // Exit points of synchronized methods must have an unlock node
2564   case Bytecodes::_return:
2565     return_current(NULL);
2566     break;
2567 
2568   case Bytecodes::_ireturn:
2569   case Bytecodes::_areturn:
2570   case Bytecodes::_freturn:
2571     return_current(pop());
2572     break;
2573   case Bytecodes::_lreturn:
2574     return_current(pop_pair());
2575     break;
2576   case Bytecodes::_dreturn:
2577     return_current(pop_pair());
2578     break;
2579 
2580   case Bytecodes::_athrow:
2581     // null exception oop throws NULL pointer exception
2582     null_check(peek());
2583     if (stopped())  return;
2584     // Hook the thrown exception directly to subsequent handlers.
2585     if (BailoutToInterpreterForThrows) {
2586       // Keep method interpreted from now on.
2587       uncommon_trap(Deoptimization::Reason_unhandled,
2588                     Deoptimization::Action_make_not_compilable);
2589       return;
2590     }
2591     if (env()->jvmti_can_post_on_exceptions()) {
2592       // check if we must post exception events, take uncommon trap if so (with must_throw = false)
2593       uncommon_trap_if_should_post_on_exceptions(Deoptimization::Reason_unhandled, false);
2594     }
2595     // Here if either can_post_on_exceptions or should_post_on_exceptions is false
2596     add_exception_state(make_exception_state(peek()));
2597     break;
2598 
2599   case Bytecodes::_goto:   // fall through
2600   case Bytecodes::_goto_w: {
2601     int target_bci = (bc() == Bytecodes::_goto) ? iter().get_dest() : iter().get_far_dest();
2602 
2603     // If this is a backwards branch in the bytecodes, add Safepoint
2604     maybe_add_safepoint(target_bci);
2605 
2606     // Merge the current control into the target basic block
2607     merge(target_bci);
2608 
2609     // See if we can get some profile data and hand it off to the next block
2610     Block *target_block = block()->successor_for_bci(target_bci);
2611     if (target_block->pred_count() != 1)  break;
2612     ciMethodData* methodData = method()->method_data();
2613     if (!methodData->is_mature())  break;
2614     ciProfileData* data = methodData->bci_to_data(bci());
2615     assert(data != NULL && data->is_JumpData(), "need JumpData for taken branch");
2616     int taken = ((ciJumpData*)data)->taken();
2617     taken = method()->scale_count(taken);
2618     target_block->set_count(taken);
2619     break;
2620   }
2621 
2622   case Bytecodes::_ifnull:    btest = BoolTest::eq; goto handle_if_null;
2623   case Bytecodes::_ifnonnull: btest = BoolTest::ne; goto handle_if_null;
2624   handle_if_null:
2625     // If this is a backwards branch in the bytecodes, add Safepoint
2626     maybe_add_safepoint(iter().get_dest());
2627     a = null();
2628     b = pop();
2629     if (!_gvn.type(b)->speculative_maybe_null() &&
2630         !too_many_traps(Deoptimization::Reason_speculate_null_check)) {
2631       inc_sp(1);
2632       Node* null_ctl = top();
2633       b = null_check_oop(b, &null_ctl, true, true, true);
2634       assert(null_ctl->is_top(), "no null control here");
2635       dec_sp(1);
2636     } else if (_gvn.type(b)->speculative_always_null() &&
2637                !too_many_traps(Deoptimization::Reason_speculate_null_assert)) {
2638       inc_sp(1);
2639       b = null_assert(b);
2640       dec_sp(1);
2641     }
2642     c = _gvn.transform( new CmpPNode(b, a) );






2643     do_ifnull(btest, c);
2644     break;
2645 
2646   case Bytecodes::_if_acmpeq: btest = BoolTest::eq; goto handle_if_acmp;
2647   case Bytecodes::_if_acmpne: btest = BoolTest::ne; goto handle_if_acmp;
2648   handle_if_acmp:
2649     // If this is a backwards branch in the bytecodes, add Safepoint
2650     maybe_add_safepoint(iter().get_dest());
2651     a = pop();
2652     b = pop();
2653     c = _gvn.transform( new CmpPNode(b, a) );
2654     c = optimize_cmp_with_klass(c);
2655     do_if(btest, c);
2656     break;
2657 
2658   case Bytecodes::_ifeq: btest = BoolTest::eq; goto handle_ifxx;
2659   case Bytecodes::_ifne: btest = BoolTest::ne; goto handle_ifxx;
2660   case Bytecodes::_iflt: btest = BoolTest::lt; goto handle_ifxx;
2661   case Bytecodes::_ifle: btest = BoolTest::le; goto handle_ifxx;
2662   case Bytecodes::_ifgt: btest = BoolTest::gt; goto handle_ifxx;
2663   case Bytecodes::_ifge: btest = BoolTest::ge; goto handle_ifxx;
2664   handle_ifxx:
2665     // If this is a backwards branch in the bytecodes, add Safepoint
2666     maybe_add_safepoint(iter().get_dest());
2667     a = _gvn.intcon(0);
2668     b = pop();
2669     c = _gvn.transform( new CmpINode(b, a) );
2670     do_if(btest, c);
2671     break;
2672 
2673   case Bytecodes::_if_icmpeq: btest = BoolTest::eq; goto handle_if_icmp;
2674   case Bytecodes::_if_icmpne: btest = BoolTest::ne; goto handle_if_icmp;
2675   case Bytecodes::_if_icmplt: btest = BoolTest::lt; goto handle_if_icmp;
2676   case Bytecodes::_if_icmple: btest = BoolTest::le; goto handle_if_icmp;
2677   case Bytecodes::_if_icmpgt: btest = BoolTest::gt; goto handle_if_icmp;
2678   case Bytecodes::_if_icmpge: btest = BoolTest::ge; goto handle_if_icmp;
2679   handle_if_icmp:
2680     // If this is a backwards branch in the bytecodes, add Safepoint
2681     maybe_add_safepoint(iter().get_dest());
2682     a = pop();
2683     b = pop();
2684     c = _gvn.transform( new CmpINode( b, a ) );
2685     do_if(btest, c);
2686     break;
2687 
2688   case Bytecodes::_tableswitch:
2689     do_tableswitch();
2690     break;
2691 
2692   case Bytecodes::_lookupswitch:
2693     do_lookupswitch();
2694     break;
2695 
2696   case Bytecodes::_invokestatic:
2697   case Bytecodes::_invokedynamic:
2698   case Bytecodes::_invokespecial:
2699   case Bytecodes::_invokevirtual:
2700   case Bytecodes::_invokeinterface:
2701     do_call();
2702     break;
2703   case Bytecodes::_checkcast:
2704     do_checkcast();
2705     break;
2706   case Bytecodes::_instanceof:
2707     do_instanceof();
2708     break;
2709   case Bytecodes::_anewarray:
2710     do_anewarray();
2711     break;
2712   case Bytecodes::_newarray:
2713     do_newarray((BasicType)iter().get_index());
2714     break;
2715   case Bytecodes::_multianewarray:
2716     do_multianewarray();
2717     break;
2718   case Bytecodes::_new:
2719     do_new();
2720     break;






2721 
2722   case Bytecodes::_jsr:
2723   case Bytecodes::_jsr_w:
2724     do_jsr();
2725     break;
2726 
2727   case Bytecodes::_ret:
2728     do_ret();
2729     break;
2730 
2731 
2732   case Bytecodes::_monitorenter:
2733     do_monitor_enter();
2734     break;
2735 
2736   case Bytecodes::_monitorexit:
2737     do_monitor_exit();
2738     break;
2739 
2740   case Bytecodes::_breakpoint:
2741     // Breakpoint set concurrently to compile
2742     // %%% use an uncommon trap?
2743     C->record_failure("breakpoint in method");
2744     return;
2745 
2746   default:
2747 #ifndef PRODUCT
2748     map()->dump(99);
2749 #endif
2750     tty->print("\nUnhandled bytecode %s\n", Bytecodes::name(bc()) );
2751     ShouldNotReachHere();
2752   }
2753 
2754 #ifndef PRODUCT
2755   if (C->should_print_igv(1)) {
2756     IdealGraphPrinter* printer = C->igv_printer();
2757     char buffer[256];
2758     jio_snprintf(buffer, sizeof(buffer), "Bytecode %d: %s", bci(), Bytecodes::name(bc()));
2759     bool old = printer->traverse_outs();
2760     printer->set_traverse_outs(true);
2761     printer->print_method(buffer, 4);
2762     printer->set_traverse_outs(old);
2763   }
2764 #endif
2765 }
--- EOF ---