1 /*
   2  * Copyright (c) 1998, 2025, 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 "ci/ciMethodData.hpp"
  26 #include "classfile/vmSymbols.hpp"
  27 #include "compiler/compileLog.hpp"
  28 #include "interpreter/linkResolver.hpp"
  29 #include "jvm_io.h"
  30 #include "memory/resourceArea.hpp"
  31 #include "memory/universe.hpp"
  32 #include "oops/oop.inline.hpp"
  33 #include "opto/addnode.hpp"
  34 #include "opto/castnode.hpp"
  35 #include "opto/convertnode.hpp"
  36 #include "opto/divnode.hpp"
  37 #include "opto/idealGraphPrinter.hpp"
  38 #include "opto/matcher.hpp"
  39 #include "opto/memnode.hpp"
  40 #include "opto/mulnode.hpp"
  41 #include "opto/opaquenode.hpp"
  42 #include "opto/parse.hpp"
  43 #include "opto/runtime.hpp"
  44 #include "runtime/deoptimization.hpp"
  45 #include "runtime/sharedRuntime.hpp"
  46 
  47 #ifndef PRODUCT
  48 extern uint explicit_null_checks_inserted,
  49             explicit_null_checks_elided;
  50 #endif
  51 
  52 //---------------------------------array_load----------------------------------
  53 void Parse::array_load(BasicType bt) {
  54   const Type* elemtype = Type::TOP;
  55   bool big_val = bt == T_DOUBLE || bt == T_LONG;
  56   Node* adr = array_addressing(bt, 0, elemtype);
  57   if (stopped())  return;     // guaranteed null or range check
  58 
  59   pop();                      // index (already used)
  60   Node* array = pop();        // the array itself
  61 
  62   if (elemtype == TypeInt::BOOL) {
  63     bt = T_BOOLEAN;
  64   }
  65   const TypeAryPtr* adr_type = TypeAryPtr::get_array_body_type(bt);
  66 
  67   Node* ld = access_load_at(array, adr, adr_type, elemtype, bt,
  68                             IN_HEAP | IS_ARRAY | C2_CONTROL_DEPENDENT_LOAD);
  69   if (big_val) {
  70     push_pair(ld);
  71   } else {
  72     push(ld);
  73   }
  74 }
  75 
  76 
  77 //--------------------------------array_store----------------------------------
  78 void Parse::array_store(BasicType bt) {
  79   const Type* elemtype = Type::TOP;
  80   bool big_val = bt == T_DOUBLE || bt == T_LONG;
  81   Node* adr = array_addressing(bt, big_val ? 2 : 1, elemtype);
  82   if (stopped())  return;     // guaranteed null or range check
  83   if (bt == T_OBJECT) {
  84     array_store_check();
  85     if (stopped()) {
  86       return;
  87     }
  88   }
  89   Node* val;                  // Oop to store
  90   if (big_val) {
  91     val = pop_pair();
  92   } else {
  93     val = pop();
  94   }
  95   pop();                      // index (already used)
  96   Node* array = pop();        // the array itself
  97 
  98   if (elemtype == TypeInt::BOOL) {
  99     bt = T_BOOLEAN;
 100   }
 101   const TypeAryPtr* adr_type = TypeAryPtr::get_array_body_type(bt);
 102 
 103   access_store_at(array, adr, adr_type, val, elemtype, bt, MO_UNORDERED | IN_HEAP | IS_ARRAY);
 104 }
 105 
 106 
 107 //------------------------------array_addressing-------------------------------
 108 // Pull array and index from the stack.  Compute pointer-to-element.
 109 Node* Parse::array_addressing(BasicType type, int vals, const Type*& elemtype) {
 110   Node *idx   = peek(0+vals);   // Get from stack without popping
 111   Node *ary   = peek(1+vals);   // in case of exception
 112 
 113   // Null check the array base, with correct stack contents
 114   ary = null_check(ary, T_ARRAY);
 115   // Compile-time detect of null-exception?
 116   if (stopped())  return top();
 117 
 118   const TypeAryPtr* arytype  = _gvn.type(ary)->is_aryptr();
 119   const TypeInt*    sizetype = arytype->size();
 120   elemtype = arytype->elem();
 121 
 122   if (UseUniqueSubclasses) {
 123     const Type* el = elemtype->make_ptr();
 124     if (el && el->isa_instptr()) {
 125       const TypeInstPtr* toop = el->is_instptr();
 126       if (toop->instance_klass()->unique_concrete_subklass()) {
 127         // If we load from "AbstractClass[]" we must see "ConcreteSubClass".
 128         const Type* subklass = Type::get_const_type(toop->instance_klass());
 129         elemtype = subklass->join_speculative(el);
 130       }
 131     }
 132   }
 133 
 134   // Check for big class initializers with all constant offsets
 135   // feeding into a known-size array.
 136   const TypeInt* idxtype = _gvn.type(idx)->is_int();
 137   // See if the highest idx value is less than the lowest array bound,
 138   // and if the idx value cannot be negative:
 139   bool need_range_check = true;
 140   if (idxtype->_hi < sizetype->_lo && idxtype->_lo >= 0) {
 141     need_range_check = false;
 142     if (C->log() != nullptr)   C->log()->elem("observe that='!need_range_check'");
 143   }
 144 
 145   if (!arytype->is_loaded()) {
 146     // Only fails for some -Xcomp runs
 147     // The class is unloaded.  We have to run this bytecode in the interpreter.
 148     ciKlass* klass = arytype->unloaded_klass();
 149 
 150     uncommon_trap(Deoptimization::Reason_unloaded,
 151                   Deoptimization::Action_reinterpret,
 152                   klass, "!loaded array");
 153     return top();
 154   }
 155 
 156   // Do the range check
 157   if (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                       nullptr, "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);
 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                     nullptr,
 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                     nullptr,
 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                   nullptr,
 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 = nullptr;
 427   if (methodData->is_mature() && UseSwitchProfiling) {
 428     ciProfileData* data = methodData->bci_to_data(bci());
 429     if (data != nullptr && 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 = (default_dest <= bci());
 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 != nullptr) {
 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 != nullptr) {
 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 != nullptr) {
 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 = nullptr;
 501   if (methodData->is_mature() && UseSwitchProfiling) {
 502     ciProfileData* data = methodData->bci_to_data(bci());
 503     if (data != nullptr && 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 == nullptr) ? 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 != nullptr) {
 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 = (default_dest <= bci());
 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(nullptr),
 608       _cost(0), _state(Start) {
 609   }
 610 
 611   SwitchRanges()
 612     : _lo(nullptr), _hi(nullptr), _mid(nullptr),
 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 == nullptr) {
 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 = nullptr;
 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 = nullptr;
 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(java_subtract(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 = nullptr;
 881   if (methodData->is_mature()) {
 882     ciProfileData* data = methodData->bci_to_data(bci());
 883     if (data != nullptr && data->is_MultiBranchData()) {
 884       profile = (ciMultiBranchData*)data;
 885     }
 886   }
 887 
 888   Node* jtn = _gvn.transform(new JumpNode(control(), key_val, num_cases, probs, profile == nullptr ? 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 != nullptr) {
 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 = nullptr;
 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 Node* Parse::floating_point_mod(Node* a, Node* b, BasicType type) {
1099   assert(type == BasicType::T_FLOAT || type == BasicType::T_DOUBLE, "only float and double are floating points");
1100   CallNode* mod = type == BasicType::T_DOUBLE ? static_cast<CallNode*>(new ModDNode(C, a, b)) : new ModFNode(C, a, b);
1101 
1102   Node* prev_mem = set_predefined_input_for_runtime_call(mod);
1103   mod = _gvn.transform(mod)->as_Call();
1104   set_predefined_output_for_runtime_call(mod, prev_mem, TypeRawPtr::BOTTOM);
1105   Node* result = _gvn.transform(new ProjNode(mod, TypeFunc::Parms + 0));
1106   record_for_igvn(mod);
1107   return result;
1108 }
1109 
1110 void Parse::l2f() {
1111   Node* f2 = pop();
1112   Node* f1 = pop();
1113   Node* c = make_runtime_call(RC_LEAF, OptoRuntime::l2f_Type(),
1114                               CAST_FROM_FN_PTR(address, SharedRuntime::l2f),
1115                               "l2f", nullptr, //no memory effects
1116                               f1, f2);
1117   Node* res = _gvn.transform(new ProjNode(c, TypeFunc::Parms + 0));
1118 
1119   push(res);
1120 }
1121 
1122 // Handle jsr and jsr_w bytecode
1123 void Parse::do_jsr() {
1124   assert(bc() == Bytecodes::_jsr || bc() == Bytecodes::_jsr_w, "wrong bytecode");
1125 
1126   // Store information about current state, tagged with new _jsr_bci
1127   int return_bci = iter().next_bci();
1128   int jsr_bci    = (bc() == Bytecodes::_jsr) ? iter().get_dest() : iter().get_far_dest();
1129 
1130   // The way we do things now, there is only one successor block
1131   // for the jsr, because the target code is cloned by ciTypeFlow.
1132   Block* target = successor_for_bci(jsr_bci);
1133 
1134   // What got pushed?
1135   const Type* ret_addr = target->peek();
1136   assert(ret_addr->singleton(), "must be a constant (cloned jsr body)");
1137 
1138   // Effect on jsr on stack
1139   push(_gvn.makecon(ret_addr));
1140 
1141   // Flow to the jsr.
1142   merge(jsr_bci);
1143 }
1144 
1145 // Handle ret bytecode
1146 void Parse::do_ret() {
1147   // Find to whom we return.
1148   assert(block()->num_successors() == 1, "a ret can only go one place now");
1149   Block* target = block()->successor_at(0);
1150   assert(!target->is_ready(), "our arrival must be expected");
1151   int pnum = target->next_path_num();
1152   merge_common(target, pnum);
1153 }
1154 
1155 static bool has_injected_profile(BoolTest::mask btest, Node* test, int& taken, int& not_taken) {
1156   if (btest != BoolTest::eq && btest != BoolTest::ne) {
1157     // Only ::eq and ::ne are supported for profile injection.
1158     return false;
1159   }
1160   if (test->is_Cmp() &&
1161       test->in(1)->Opcode() == Op_ProfileBoolean) {
1162     ProfileBooleanNode* profile = (ProfileBooleanNode*)test->in(1);
1163     int false_cnt = profile->false_count();
1164     int  true_cnt = profile->true_count();
1165 
1166     // Counts matching depends on the actual test operation (::eq or ::ne).
1167     // No need to scale the counts because profile injection was designed
1168     // to feed exact counts into VM.
1169     taken     = (btest == BoolTest::eq) ? false_cnt :  true_cnt;
1170     not_taken = (btest == BoolTest::eq) ?  true_cnt : false_cnt;
1171 
1172     profile->consume();
1173     return true;
1174   }
1175   return false;
1176 }
1177 
1178 // Give up if too few (or too many, in which case the sum will overflow) counts to be meaningful.
1179 // We also check that individual counters are positive first, otherwise the sum can become positive.
1180 // (check for saturation, integer overflow, and immature counts)
1181 static bool counters_are_meaningful(int counter1, int counter2, int min) {
1182   // check for saturation, including "uint" values too big to fit in "int"
1183   if (counter1 < 0 || counter2 < 0) {
1184     return false;
1185   }
1186   // check for integer overflow of the sum
1187   int64_t sum = (int64_t)counter1 + (int64_t)counter2;
1188   STATIC_ASSERT(sizeof(counter1) < sizeof(sum));
1189   if (sum > INT_MAX) {
1190     return false;
1191   }
1192   // check if mature
1193   return (counter1 + counter2) >= min;
1194 }
1195 
1196 //--------------------------dynamic_branch_prediction--------------------------
1197 // Try to gather dynamic branch prediction behavior.  Return a probability
1198 // of the branch being taken and set the "cnt" field.  Returns a -1.0
1199 // if we need to use static prediction for some reason.
1200 float Parse::dynamic_branch_prediction(float &cnt, BoolTest::mask btest, Node* test) {
1201   ResourceMark rm;
1202 
1203   cnt  = COUNT_UNKNOWN;
1204 
1205   int     taken = 0;
1206   int not_taken = 0;
1207 
1208   bool use_mdo = !has_injected_profile(btest, test, taken, not_taken);
1209 
1210   if (use_mdo) {
1211     // Use MethodData information if it is available
1212     // FIXME: free the ProfileData structure
1213     ciMethodData* methodData = method()->method_data();
1214     if (!methodData->is_mature())  return PROB_UNKNOWN;
1215     ciProfileData* data = methodData->bci_to_data(bci());
1216     if (data == nullptr) {
1217       return PROB_UNKNOWN;
1218     }
1219     if (!data->is_JumpData())  return PROB_UNKNOWN;
1220 
1221     // get taken and not taken values
1222     // NOTE: saturated UINT_MAX values become negative,
1223     // as do counts above INT_MAX.
1224     taken = data->as_JumpData()->taken();
1225     not_taken = 0;
1226     if (data->is_BranchData()) {
1227       not_taken = data->as_BranchData()->not_taken();
1228     }
1229 
1230     // scale the counts to be commensurate with invocation counts:
1231     // NOTE: overflow for positive values is clamped at INT_MAX
1232     taken = method()->scale_count(taken);
1233     not_taken = method()->scale_count(not_taken);
1234   }
1235   // At this point, saturation or overflow is indicated by INT_MAX
1236   // or a negative value.
1237 
1238   // Give up if too few (or too many, in which case the sum will overflow) counts to be meaningful.
1239   // We also check that individual counters are positive first, otherwise the sum can become positive.
1240   if (!counters_are_meaningful(taken, not_taken, 40)) {
1241     if (C->log() != nullptr) {
1242       C->log()->elem("branch target_bci='%d' taken='%d' not_taken='%d'", iter().get_dest(), taken, not_taken);
1243     }
1244     return PROB_UNKNOWN;
1245   }
1246 
1247   // Compute frequency that we arrive here
1248   float sum = taken + not_taken;
1249   // Adjust, if this block is a cloned private block but the
1250   // Jump counts are shared.  Taken the private counts for
1251   // just this path instead of the shared counts.
1252   if( block()->count() > 0 )
1253     sum = block()->count();
1254   cnt = sum / FreqCountInvocations;
1255 
1256   // Pin probability to sane limits
1257   float prob;
1258   if( !taken )
1259     prob = (0+PROB_MIN) / 2;
1260   else if( !not_taken )
1261     prob = (1+PROB_MAX) / 2;
1262   else {                         // Compute probability of true path
1263     prob = (float)taken / (float)(taken + not_taken);
1264     if (prob > PROB_MAX)  prob = PROB_MAX;
1265     if (prob < PROB_MIN)   prob = PROB_MIN;
1266   }
1267 
1268   assert((cnt > 0.0f) && (prob > 0.0f),
1269          "Bad frequency assignment in if cnt=%g prob=%g taken=%d not_taken=%d", cnt, prob, taken, not_taken);
1270 
1271   if (C->log() != nullptr) {
1272     const char* prob_str = nullptr;
1273     if (prob >= PROB_MAX)  prob_str = (prob == PROB_MAX) ? "max" : "always";
1274     if (prob <= PROB_MIN)  prob_str = (prob == PROB_MIN) ? "min" : "never";
1275     char prob_str_buf[30];
1276     if (prob_str == nullptr) {
1277       jio_snprintf(prob_str_buf, sizeof(prob_str_buf), "%20.2f", prob);
1278       prob_str = prob_str_buf;
1279       // The %20.2f adds many spaces to the string, to avoid some
1280       // picky overflow warning as noted in 8211929.  But, 20 is the
1281       // *minimum* width, not *maximum*, so it's not clear how this
1282       // helps prevent overflow.  Looks like we were forced to work
1283       // around a bug in gcc.  In any case, strip the blanks.
1284       while (*prob_str == ' ')  ++prob_str;
1285     }
1286     C->log()->elem("branch target_bci='%d' taken='%d' not_taken='%d' cnt='%f' prob='%s'",
1287                    iter().get_dest(), taken, not_taken, cnt, prob_str);
1288   }
1289   return prob;
1290 }
1291 
1292 //-----------------------------branch_prediction-------------------------------
1293 float Parse::branch_prediction(float& cnt,
1294                                BoolTest::mask btest,
1295                                int target_bci,
1296                                Node* test) {
1297   float prob = dynamic_branch_prediction(cnt, btest, test);
1298   // If prob is unknown, switch to static prediction
1299   if (prob != PROB_UNKNOWN)  return prob;
1300 
1301   prob = PROB_FAIR;                   // Set default value
1302   if (btest == BoolTest::eq)          // Exactly equal test?
1303     prob = PROB_STATIC_INFREQUENT;    // Assume its relatively infrequent
1304   else if (btest == BoolTest::ne)
1305     prob = PROB_STATIC_FREQUENT;      // Assume its relatively frequent
1306 
1307   // If this is a conditional test guarding a backwards branch,
1308   // assume its a loop-back edge.  Make it a likely taken branch.
1309   if (target_bci < bci()) {
1310     if (is_osr_parse()) {    // Could be a hot OSR'd loop; force deopt
1311       // Since it's an OSR, we probably have profile data, but since
1312       // branch_prediction returned PROB_UNKNOWN, the counts are too small.
1313       // Let's make a special check here for completely zero counts.
1314       ciMethodData* methodData = method()->method_data();
1315       if (!methodData->is_empty()) {
1316         ciProfileData* data = methodData->bci_to_data(bci());
1317         // Only stop for truly zero counts, which mean an unknown part
1318         // of the OSR-ed method, and we want to deopt to gather more stats.
1319         // If you have ANY counts, then this loop is simply 'cold' relative
1320         // to the OSR loop.
1321         if (data == nullptr ||
1322             (data->as_BranchData()->taken() +  data->as_BranchData()->not_taken() == 0)) {
1323           // This is the only way to return PROB_UNKNOWN:
1324           return PROB_UNKNOWN;
1325         }
1326       }
1327     }
1328     prob = PROB_STATIC_FREQUENT;     // Likely to take backwards branch
1329   }
1330 
1331   assert(prob != PROB_UNKNOWN, "must have some guess at this point");
1332   return prob;
1333 }
1334 
1335 // The magic constants are chosen so as to match the output of
1336 // branch_prediction() when the profile reports a zero taken count.
1337 // It is important to distinguish zero counts unambiguously, because
1338 // some branches (e.g., _213_javac.Assembler.eliminate) validly produce
1339 // very small but nonzero probabilities, which if confused with zero
1340 // counts would keep the program recompiling indefinitely.
1341 bool Parse::seems_never_taken(float prob) const {
1342   return prob < PROB_MIN;
1343 }
1344 
1345 //-------------------------------repush_if_args--------------------------------
1346 // Push arguments of an "if" bytecode back onto the stack by adjusting _sp.
1347 inline int Parse::repush_if_args() {
1348   if (PrintOpto && WizardMode) {
1349     tty->print("defending against excessive implicit null exceptions on %s @%d in ",
1350                Bytecodes::name(iter().cur_bc()), iter().cur_bci());
1351     method()->print_name(); tty->cr();
1352   }
1353   int bc_depth = - Bytecodes::depth(iter().cur_bc());
1354   assert(bc_depth == 1 || bc_depth == 2, "only two kinds of branches");
1355   DEBUG_ONLY(sync_jvms());   // argument(n) requires a synced jvms
1356   assert(argument(0) != nullptr, "must exist");
1357   assert(bc_depth == 1 || argument(1) != nullptr, "two must exist");
1358   inc_sp(bc_depth);
1359   return bc_depth;
1360 }
1361 
1362 // Used by StressUnstableIfTraps
1363 static volatile int _trap_stress_counter = 0;
1364 
1365 void Parse::increment_trap_stress_counter(Node*& counter, Node*& incr_store) {
1366   Node* counter_addr = makecon(TypeRawPtr::make((address)&_trap_stress_counter));
1367   counter = make_load(control(), counter_addr, TypeInt::INT, T_INT, MemNode::unordered);
1368   counter = _gvn.transform(new AddINode(counter, intcon(1)));
1369   incr_store = store_to_memory(control(), counter_addr, counter, T_INT, MemNode::unordered);
1370 }
1371 
1372 //----------------------------------do_ifnull----------------------------------
1373 void Parse::do_ifnull(BoolTest::mask btest, Node *c) {
1374   int target_bci = iter().get_dest();
1375 
1376   Node* counter = nullptr;
1377   Node* incr_store = nullptr;
1378   bool do_stress_trap = StressUnstableIfTraps && ((C->random() % 2) == 0);
1379   if (do_stress_trap) {
1380     increment_trap_stress_counter(counter, incr_store);
1381   }
1382 
1383   Block* branch_block = successor_for_bci(target_bci);
1384   Block* next_block   = successor_for_bci(iter().next_bci());
1385 
1386   float cnt;
1387   float prob = branch_prediction(cnt, btest, target_bci, c);
1388   if (prob == PROB_UNKNOWN) {
1389     // (An earlier version of do_ifnull omitted this trap for OSR methods.)
1390     if (PrintOpto && Verbose) {
1391       tty->print_cr("Never-taken edge stops compilation at bci %d", bci());
1392     }
1393     repush_if_args(); // to gather stats on loop
1394     uncommon_trap(Deoptimization::Reason_unreached,
1395                   Deoptimization::Action_reinterpret,
1396                   nullptr, "cold");
1397     if (C->eliminate_boxing()) {
1398       // Mark the successor blocks as parsed
1399       branch_block->next_path_num();
1400       next_block->next_path_num();
1401     }
1402     return;
1403   }
1404 
1405   NOT_PRODUCT(explicit_null_checks_inserted++);
1406 
1407   // Generate real control flow
1408   Node   *tst = _gvn.transform( new BoolNode( c, btest ) );
1409 
1410   // Sanity check the probability value
1411   assert(prob > 0.0f,"Bad probability in Parser");
1412  // Need xform to put node in hash table
1413   IfNode *iff = create_and_xform_if( control(), tst, prob, cnt );
1414   assert(iff->_prob > 0.0f,"Optimizer made bad probability in parser");
1415   // True branch
1416   { PreserveJVMState pjvms(this);
1417     Node* iftrue  = _gvn.transform( new IfTrueNode (iff) );
1418     set_control(iftrue);
1419 
1420     if (stopped()) {            // Path is dead?
1421       NOT_PRODUCT(explicit_null_checks_elided++);
1422       if (C->eliminate_boxing()) {
1423         // Mark the successor block as parsed
1424         branch_block->next_path_num();
1425       }
1426     } else {                    // Path is live.
1427       adjust_map_after_if(btest, c, prob, branch_block);
1428       if (!stopped()) {
1429         merge(target_bci);
1430       }
1431     }
1432   }
1433 
1434   // False branch
1435   Node* iffalse = _gvn.transform( new IfFalseNode(iff) );
1436   set_control(iffalse);
1437 
1438   if (stopped()) {              // Path is dead?
1439     NOT_PRODUCT(explicit_null_checks_elided++);
1440     if (C->eliminate_boxing()) {
1441       // Mark the successor block as parsed
1442       next_block->next_path_num();
1443     }
1444   } else  {                     // Path is live.
1445     adjust_map_after_if(BoolTest(btest).negate(), c, 1.0-prob, next_block);
1446   }
1447 
1448   if (do_stress_trap) {
1449     stress_trap(iff, counter, incr_store);
1450   }
1451 }
1452 
1453 //------------------------------------do_if------------------------------------
1454 void Parse::do_if(BoolTest::mask btest, Node* c) {
1455   int target_bci = iter().get_dest();
1456 
1457   Block* branch_block = successor_for_bci(target_bci);
1458   Block* next_block   = successor_for_bci(iter().next_bci());
1459 
1460   float cnt;
1461   float prob = branch_prediction(cnt, btest, target_bci, c);
1462   float untaken_prob = 1.0 - prob;
1463 
1464   if (prob == PROB_UNKNOWN) {
1465     if (PrintOpto && Verbose) {
1466       tty->print_cr("Never-taken edge stops compilation at bci %d", bci());
1467     }
1468     repush_if_args(); // to gather stats on loop
1469     uncommon_trap(Deoptimization::Reason_unreached,
1470                   Deoptimization::Action_reinterpret,
1471                   nullptr, "cold");
1472     if (C->eliminate_boxing()) {
1473       // Mark the successor blocks as parsed
1474       branch_block->next_path_num();
1475       next_block->next_path_num();
1476     }
1477     return;
1478   }
1479 
1480   Node* counter = nullptr;
1481   Node* incr_store = nullptr;
1482   bool do_stress_trap = StressUnstableIfTraps && ((C->random() % 2) == 0);
1483   if (do_stress_trap) {
1484     increment_trap_stress_counter(counter, incr_store);
1485   }
1486 
1487   // Sanity check the probability value
1488   assert(0.0f < prob && prob < 1.0f,"Bad probability in Parser");
1489 
1490   bool taken_if_true = true;
1491   // Convert BoolTest to canonical form:
1492   if (!BoolTest(btest).is_canonical()) {
1493     btest         = BoolTest(btest).negate();
1494     taken_if_true = false;
1495     // prob is NOT updated here; it remains the probability of the taken
1496     // path (as opposed to the prob of the path guarded by an 'IfTrueNode').
1497   }
1498   assert(btest != BoolTest::eq, "!= is the only canonical exact test");
1499 
1500   Node* tst0 = new BoolNode(c, btest);
1501   Node* tst = _gvn.transform(tst0);
1502   BoolTest::mask taken_btest   = BoolTest::illegal;
1503   BoolTest::mask untaken_btest = BoolTest::illegal;
1504 
1505   if (tst->is_Bool()) {
1506     // Refresh c from the transformed bool node, since it may be
1507     // simpler than the original c.  Also re-canonicalize btest.
1508     // This wins when (Bool ne (Conv2B p) 0) => (Bool ne (CmpP p null)).
1509     // That can arise from statements like: if (x instanceof C) ...
1510     if (tst != tst0) {
1511       // Canonicalize one more time since transform can change it.
1512       btest = tst->as_Bool()->_test._test;
1513       if (!BoolTest(btest).is_canonical()) {
1514         // Reverse edges one more time...
1515         tst   = _gvn.transform( tst->as_Bool()->negate(&_gvn) );
1516         btest = tst->as_Bool()->_test._test;
1517         assert(BoolTest(btest).is_canonical(), "sanity");
1518         taken_if_true = !taken_if_true;
1519       }
1520       c = tst->in(1);
1521     }
1522     BoolTest::mask neg_btest = BoolTest(btest).negate();
1523     taken_btest   = taken_if_true ?     btest : neg_btest;
1524     untaken_btest = taken_if_true ? neg_btest :     btest;
1525   }
1526 
1527   // Generate real control flow
1528   float true_prob = (taken_if_true ? prob : untaken_prob);
1529   IfNode* iff = create_and_map_if(control(), tst, true_prob, cnt);
1530   assert(iff->_prob > 0.0f,"Optimizer made bad probability in parser");
1531   Node* taken_branch   = new IfTrueNode(iff);
1532   Node* untaken_branch = new IfFalseNode(iff);
1533   if (!taken_if_true) {  // Finish conversion to canonical form
1534     Node* tmp      = taken_branch;
1535     taken_branch   = untaken_branch;
1536     untaken_branch = tmp;
1537   }
1538 
1539   // Branch is taken:
1540   { PreserveJVMState pjvms(this);
1541     taken_branch = _gvn.transform(taken_branch);
1542     set_control(taken_branch);
1543 
1544     if (stopped()) {
1545       if (C->eliminate_boxing()) {
1546         // Mark the successor block as parsed
1547         branch_block->next_path_num();
1548       }
1549     } else {
1550       adjust_map_after_if(taken_btest, c, prob, branch_block);
1551       if (!stopped()) {
1552         merge(target_bci);
1553       }
1554     }
1555   }
1556 
1557   untaken_branch = _gvn.transform(untaken_branch);
1558   set_control(untaken_branch);
1559 
1560   // Branch not taken.
1561   if (stopped()) {
1562     if (C->eliminate_boxing()) {
1563       // Mark the successor block as parsed
1564       next_block->next_path_num();
1565     }
1566   } else {
1567     adjust_map_after_if(untaken_btest, c, untaken_prob, next_block);
1568   }
1569 
1570   if (do_stress_trap) {
1571     stress_trap(iff, counter, incr_store);
1572   }
1573 }
1574 
1575 // Force unstable if traps to be taken randomly to trigger intermittent bugs such as incorrect debug information.
1576 // Add another if before the unstable if that checks a "random" condition at runtime (a simple shared counter) and
1577 // then either takes the trap or executes the original, unstable if.
1578 void Parse::stress_trap(IfNode* orig_iff, Node* counter, Node* incr_store) {
1579   // Search for an unstable if trap
1580   CallStaticJavaNode* trap = nullptr;
1581   assert(orig_iff->Opcode() == Op_If && orig_iff->outcnt() == 2, "malformed if");
1582   ProjNode* trap_proj = orig_iff->uncommon_trap_proj(trap, Deoptimization::Reason_unstable_if);
1583   if (trap == nullptr || !trap->jvms()->should_reexecute()) {
1584     // No suitable trap found. Remove unused counter load and increment.
1585     C->gvn_replace_by(incr_store, incr_store->in(MemNode::Memory));
1586     return;
1587   }
1588 
1589   // Remove trap from optimization list since we add another path to the trap.
1590   bool success = C->remove_unstable_if_trap(trap, true);
1591   assert(success, "Trap already modified");
1592 
1593   // Add a check before the original if that will trap with a certain frequency and execute the original if otherwise
1594   int freq_log = (C->random() % 31) + 1; // Random logarithmic frequency in [1, 31]
1595   Node* mask = intcon(right_n_bits(freq_log));
1596   counter = _gvn.transform(new AndINode(counter, mask));
1597   Node* cmp = _gvn.transform(new CmpINode(counter, intcon(0)));
1598   Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::mask::eq));
1599   IfNode* iff = _gvn.transform(new IfNode(orig_iff->in(0), bol, orig_iff->_prob, orig_iff->_fcnt))->as_If();
1600   Node* if_true = _gvn.transform(new IfTrueNode(iff));
1601   Node* if_false = _gvn.transform(new IfFalseNode(iff));
1602   assert(!if_true->is_top() && !if_false->is_top(), "trap always / never taken");
1603 
1604   // Trap
1605   assert(trap_proj->outcnt() == 1, "some other nodes are dependent on the trap projection");
1606 
1607   Node* trap_region = new RegionNode(3);
1608   trap_region->set_req(1, trap_proj);
1609   trap_region->set_req(2, if_true);
1610   trap->set_req(0, _gvn.transform(trap_region));
1611 
1612   // Don't trap, execute original if
1613   orig_iff->set_req(0, if_false);
1614 }
1615 
1616 bool Parse::path_is_suitable_for_uncommon_trap(float prob) const {
1617   // Randomly skip emitting an uncommon trap
1618   if (StressUnstableIfTraps && ((C->random() % 2) == 0)) {
1619     return false;
1620   }
1621   // Don't want to speculate on uncommon traps when running with -Xcomp
1622   if (!UseInterpreter) {
1623     return false;
1624   }
1625   return seems_never_taken(prob) &&
1626          !C->too_many_traps(method(), bci(), Deoptimization::Reason_unstable_if);
1627 }
1628 
1629 void Parse::maybe_add_predicate_after_if(Block* path) {
1630   if (path->is_SEL_head() && path->preds_parsed() == 0) {
1631     // Add predicates at bci of if dominating the loop so traps can be
1632     // recorded on the if's profile data
1633     int bc_depth = repush_if_args();
1634     add_parse_predicates();
1635     dec_sp(bc_depth);
1636     path->set_has_predicates();
1637   }
1638 }
1639 
1640 
1641 //----------------------------adjust_map_after_if------------------------------
1642 // Adjust the JVM state to reflect the result of taking this path.
1643 // Basically, it means inspecting the CmpNode controlling this
1644 // branch, seeing how it constrains a tested value, and then
1645 // deciding if it's worth our while to encode this constraint
1646 // as graph nodes in the current abstract interpretation map.
1647 void Parse::adjust_map_after_if(BoolTest::mask btest, Node* c, float prob, Block* path) {
1648   if (!c->is_Cmp()) {
1649     maybe_add_predicate_after_if(path);
1650     return;
1651   }
1652 
1653   if (stopped() || btest == BoolTest::illegal) {
1654     return;                             // nothing to do
1655   }
1656 
1657   bool is_fallthrough = (path == successor_for_bci(iter().next_bci()));
1658 
1659   if (path_is_suitable_for_uncommon_trap(prob)) {
1660     repush_if_args();
1661     Node* call = uncommon_trap(Deoptimization::Reason_unstable_if,
1662                   Deoptimization::Action_reinterpret,
1663                   nullptr,
1664                   (is_fallthrough ? "taken always" : "taken never"));
1665 
1666     if (call != nullptr) {
1667       C->record_unstable_if_trap(new UnstableIfTrap(call->as_CallStaticJava(), path));
1668     }
1669     return;
1670   }
1671 
1672   Node* val = c->in(1);
1673   Node* con = c->in(2);
1674   const Type* tcon = _gvn.type(con);
1675   const Type* tval = _gvn.type(val);
1676   bool have_con = tcon->singleton();
1677   if (tval->singleton()) {
1678     if (!have_con) {
1679       // Swap, so constant is in con.
1680       con  = val;
1681       tcon = tval;
1682       val  = c->in(2);
1683       tval = _gvn.type(val);
1684       btest = BoolTest(btest).commute();
1685       have_con = true;
1686     } else {
1687       // Do we have two constants?  Then leave well enough alone.
1688       have_con = false;
1689     }
1690   }
1691   if (!have_con) {                        // remaining adjustments need a con
1692     maybe_add_predicate_after_if(path);
1693     return;
1694   }
1695 
1696   sharpen_type_after_if(btest, con, tcon, val, tval);
1697   maybe_add_predicate_after_if(path);
1698 }
1699 
1700 
1701 static Node* extract_obj_from_klass_load(PhaseGVN* gvn, Node* n) {
1702   Node* ldk;
1703   if (n->is_DecodeNKlass()) {
1704     if (n->in(1)->Opcode() != Op_LoadNKlass) {
1705       return nullptr;
1706     } else {
1707       ldk = n->in(1);
1708     }
1709   } else if (n->Opcode() != Op_LoadKlass) {
1710     return nullptr;
1711   } else {
1712     ldk = n;
1713   }
1714   assert(ldk != nullptr && ldk->is_Load(), "should have found a LoadKlass or LoadNKlass node");
1715 
1716   Node* adr = ldk->in(MemNode::Address);
1717   intptr_t off = 0;
1718   Node* obj = AddPNode::Ideal_base_and_offset(adr, gvn, off);
1719   if (obj == nullptr || off != oopDesc::klass_offset_in_bytes()) // loading oopDesc::_klass?
1720     return nullptr;
1721   const TypePtr* tp = gvn->type(obj)->is_ptr();
1722   if (tp == nullptr || !(tp->isa_instptr() || tp->isa_aryptr())) // is obj a Java object ptr?
1723     return nullptr;
1724 
1725   return obj;
1726 }
1727 
1728 void Parse::sharpen_type_after_if(BoolTest::mask btest,
1729                                   Node* con, const Type* tcon,
1730                                   Node* val, const Type* tval) {
1731   // Look for opportunities to sharpen the type of a node
1732   // whose klass is compared with a constant klass.
1733   if (btest == BoolTest::eq && tcon->isa_klassptr()) {
1734     Node* obj = extract_obj_from_klass_load(&_gvn, val);
1735     const TypeOopPtr* con_type = tcon->isa_klassptr()->as_instance_type();
1736     if (obj != nullptr && (con_type->isa_instptr() || con_type->isa_aryptr())) {
1737        // Found:
1738        //   Bool(CmpP(LoadKlass(obj._klass), ConP(Foo.klass)), [eq])
1739        // or the narrowOop equivalent.
1740        const Type* obj_type = _gvn.type(obj);
1741        const TypeOopPtr* tboth = obj_type->join_speculative(con_type)->isa_oopptr();
1742        if (tboth != nullptr && tboth->klass_is_exact() && tboth != obj_type &&
1743            tboth->higher_equal(obj_type)) {
1744           // obj has to be of the exact type Foo if the CmpP succeeds.
1745           int obj_in_map = map()->find_edge(obj);
1746           JVMState* jvms = this->jvms();
1747           if (obj_in_map >= 0 &&
1748               (jvms->is_loc(obj_in_map) || jvms->is_stk(obj_in_map))) {
1749             TypeNode* ccast = new CheckCastPPNode(control(), obj, tboth);
1750             const Type* tcc = ccast->as_Type()->type();
1751             assert(tcc != obj_type && tcc->higher_equal(obj_type), "must improve");
1752             // Delay transform() call to allow recovery of pre-cast value
1753             // at the control merge.
1754             _gvn.set_type_bottom(ccast);
1755             record_for_igvn(ccast);
1756             // Here's the payoff.
1757             replace_in_map(obj, ccast);
1758           }
1759        }
1760     }
1761   }
1762 
1763   int val_in_map = map()->find_edge(val);
1764   if (val_in_map < 0)  return;          // replace_in_map would be useless
1765   {
1766     JVMState* jvms = this->jvms();
1767     if (!(jvms->is_loc(val_in_map) ||
1768           jvms->is_stk(val_in_map)))
1769       return;                           // again, it would be useless
1770   }
1771 
1772   // Check for a comparison to a constant, and "know" that the compared
1773   // value is constrained on this path.
1774   assert(tcon->singleton(), "");
1775   ConstraintCastNode* ccast = nullptr;
1776   Node* cast = nullptr;
1777 
1778   switch (btest) {
1779   case BoolTest::eq:                    // Constant test?
1780     {
1781       const Type* tboth = tcon->join_speculative(tval);
1782       if (tboth == tval)  break;        // Nothing to gain.
1783       if (tcon->isa_int()) {
1784         ccast = new CastIINode(control(), val, tboth);
1785       } else if (tcon == TypePtr::NULL_PTR) {
1786         // Cast to null, but keep the pointer identity temporarily live.
1787         ccast = new CastPPNode(control(), val, tboth);
1788       } else {
1789         const TypeF* tf = tcon->isa_float_constant();
1790         const TypeD* td = tcon->isa_double_constant();
1791         // Exclude tests vs float/double 0 as these could be
1792         // either +0 or -0.  Just because you are equal to +0
1793         // doesn't mean you ARE +0!
1794         // Note, following code also replaces Long and Oop values.
1795         if ((!tf || tf->_f != 0.0) &&
1796             (!td || td->_d != 0.0))
1797           cast = con;                   // Replace non-constant val by con.
1798       }
1799     }
1800     break;
1801 
1802   case BoolTest::ne:
1803     if (tcon == TypePtr::NULL_PTR) {
1804       cast = cast_not_null(val, false);
1805     }
1806     break;
1807 
1808   default:
1809     // (At this point we could record int range types with CastII.)
1810     break;
1811   }
1812 
1813   if (ccast != nullptr) {
1814     const Type* tcc = ccast->as_Type()->type();
1815     assert(tcc != tval && tcc->higher_equal(tval), "must improve");
1816     // Delay transform() call to allow recovery of pre-cast value
1817     // at the control merge.
1818     _gvn.set_type_bottom(ccast);
1819     record_for_igvn(ccast);
1820     cast = ccast;
1821   }
1822 
1823   if (cast != nullptr) {                   // Here's the payoff.
1824     replace_in_map(val, cast);
1825   }
1826 }
1827 
1828 /**
1829  * Use speculative type to optimize CmpP node: if comparison is
1830  * against the low level class, cast the object to the speculative
1831  * type if any. CmpP should then go away.
1832  *
1833  * @param c  expected CmpP node
1834  * @return   result of CmpP on object casted to speculative type
1835  *
1836  */
1837 Node* Parse::optimize_cmp_with_klass(Node* c) {
1838   // If this is transformed by the _gvn to a comparison with the low
1839   // level klass then we may be able to use speculation
1840   if (c->Opcode() == Op_CmpP &&
1841       (c->in(1)->Opcode() == Op_LoadKlass || c->in(1)->Opcode() == Op_DecodeNKlass) &&
1842       c->in(2)->is_Con()) {
1843     Node* load_klass = nullptr;
1844     Node* decode = nullptr;
1845     if (c->in(1)->Opcode() == Op_DecodeNKlass) {
1846       decode = c->in(1);
1847       load_klass = c->in(1)->in(1);
1848     } else {
1849       load_klass = c->in(1);
1850     }
1851     if (load_klass->in(2)->is_AddP()) {
1852       Node* addp = load_klass->in(2);
1853       Node* obj = addp->in(AddPNode::Address);
1854       const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();
1855       if (obj_type->speculative_type_not_null() != nullptr) {
1856         ciKlass* k = obj_type->speculative_type();
1857         inc_sp(2);
1858         obj = maybe_cast_profiled_obj(obj, k);
1859         dec_sp(2);
1860         // Make the CmpP use the casted obj
1861         addp = basic_plus_adr(obj, addp->in(AddPNode::Offset));
1862         load_klass = load_klass->clone();
1863         load_klass->set_req(2, addp);
1864         load_klass = _gvn.transform(load_klass);
1865         if (decode != nullptr) {
1866           decode = decode->clone();
1867           decode->set_req(1, load_klass);
1868           load_klass = _gvn.transform(decode);
1869         }
1870         c = c->clone();
1871         c->set_req(1, load_klass);
1872         c = _gvn.transform(c);
1873       }
1874     }
1875   }
1876   return c;
1877 }
1878 
1879 //------------------------------do_one_bytecode--------------------------------
1880 // Parse this bytecode, and alter the Parsers JVM->Node mapping
1881 void Parse::do_one_bytecode() {
1882   Node *a, *b, *c, *d;          // Handy temps
1883   BoolTest::mask btest;
1884   int i;
1885 
1886   assert(!has_exceptions(), "bytecode entry state must be clear of throws");
1887 
1888   if (C->check_node_count(NodeLimitFudgeFactor * 5,
1889                           "out of nodes parsing method")) {
1890     return;
1891   }
1892 
1893 #ifdef ASSERT
1894   // for setting breakpoints
1895   if (TraceOptoParse) {
1896     tty->print(" @");
1897     dump_bci(bci());
1898     tty->print(" %s", Bytecodes::name(bc()));
1899     tty->cr();
1900   }
1901 #endif
1902 
1903   switch (bc()) {
1904   case Bytecodes::_nop:
1905     // do nothing
1906     break;
1907   case Bytecodes::_lconst_0:
1908     push_pair(longcon(0));
1909     break;
1910 
1911   case Bytecodes::_lconst_1:
1912     push_pair(longcon(1));
1913     break;
1914 
1915   case Bytecodes::_fconst_0:
1916     push(zerocon(T_FLOAT));
1917     break;
1918 
1919   case Bytecodes::_fconst_1:
1920     push(makecon(TypeF::ONE));
1921     break;
1922 
1923   case Bytecodes::_fconst_2:
1924     push(makecon(TypeF::make(2.0f)));
1925     break;
1926 
1927   case Bytecodes::_dconst_0:
1928     push_pair(zerocon(T_DOUBLE));
1929     break;
1930 
1931   case Bytecodes::_dconst_1:
1932     push_pair(makecon(TypeD::ONE));
1933     break;
1934 
1935   case Bytecodes::_iconst_m1:push(intcon(-1)); break;
1936   case Bytecodes::_iconst_0: push(intcon( 0)); break;
1937   case Bytecodes::_iconst_1: push(intcon( 1)); break;
1938   case Bytecodes::_iconst_2: push(intcon( 2)); break;
1939   case Bytecodes::_iconst_3: push(intcon( 3)); break;
1940   case Bytecodes::_iconst_4: push(intcon( 4)); break;
1941   case Bytecodes::_iconst_5: push(intcon( 5)); break;
1942   case Bytecodes::_bipush:   push(intcon(iter().get_constant_u1())); break;
1943   case Bytecodes::_sipush:   push(intcon(iter().get_constant_u2())); break;
1944   case Bytecodes::_aconst_null: push(null());  break;
1945 
1946   case Bytecodes::_ldc:
1947   case Bytecodes::_ldc_w:
1948   case Bytecodes::_ldc2_w: {
1949     // ciTypeFlow should trap if the ldc is in error state or if the constant is not loaded
1950     assert(!iter().is_in_error(), "ldc is in error state");
1951     ciConstant constant = iter().get_constant();
1952     assert(constant.is_loaded(), "constant is not loaded");
1953     const Type* con_type = Type::make_from_constant(constant);
1954     if (con_type != nullptr) {
1955       push_node(con_type->basic_type(), makecon(con_type));
1956     }
1957     break;
1958   }
1959 
1960   case Bytecodes::_aload_0:
1961     push( local(0) );
1962     break;
1963   case Bytecodes::_aload_1:
1964     push( local(1) );
1965     break;
1966   case Bytecodes::_aload_2:
1967     push( local(2) );
1968     break;
1969   case Bytecodes::_aload_3:
1970     push( local(3) );
1971     break;
1972   case Bytecodes::_aload:
1973     push( local(iter().get_index()) );
1974     break;
1975 
1976   case Bytecodes::_fload_0:
1977   case Bytecodes::_iload_0:
1978     push( local(0) );
1979     break;
1980   case Bytecodes::_fload_1:
1981   case Bytecodes::_iload_1:
1982     push( local(1) );
1983     break;
1984   case Bytecodes::_fload_2:
1985   case Bytecodes::_iload_2:
1986     push( local(2) );
1987     break;
1988   case Bytecodes::_fload_3:
1989   case Bytecodes::_iload_3:
1990     push( local(3) );
1991     break;
1992   case Bytecodes::_fload:
1993   case Bytecodes::_iload:
1994     push( local(iter().get_index()) );
1995     break;
1996   case Bytecodes::_lload_0:
1997     push_pair_local( 0 );
1998     break;
1999   case Bytecodes::_lload_1:
2000     push_pair_local( 1 );
2001     break;
2002   case Bytecodes::_lload_2:
2003     push_pair_local( 2 );
2004     break;
2005   case Bytecodes::_lload_3:
2006     push_pair_local( 3 );
2007     break;
2008   case Bytecodes::_lload:
2009     push_pair_local( iter().get_index() );
2010     break;
2011 
2012   case Bytecodes::_dload_0:
2013     push_pair_local(0);
2014     break;
2015   case Bytecodes::_dload_1:
2016     push_pair_local(1);
2017     break;
2018   case Bytecodes::_dload_2:
2019     push_pair_local(2);
2020     break;
2021   case Bytecodes::_dload_3:
2022     push_pair_local(3);
2023     break;
2024   case Bytecodes::_dload:
2025     push_pair_local(iter().get_index());
2026     break;
2027   case Bytecodes::_fstore_0:
2028   case Bytecodes::_istore_0:
2029   case Bytecodes::_astore_0:
2030     set_local( 0, pop() );
2031     break;
2032   case Bytecodes::_fstore_1:
2033   case Bytecodes::_istore_1:
2034   case Bytecodes::_astore_1:
2035     set_local( 1, pop() );
2036     break;
2037   case Bytecodes::_fstore_2:
2038   case Bytecodes::_istore_2:
2039   case Bytecodes::_astore_2:
2040     set_local( 2, pop() );
2041     break;
2042   case Bytecodes::_fstore_3:
2043   case Bytecodes::_istore_3:
2044   case Bytecodes::_astore_3:
2045     set_local( 3, pop() );
2046     break;
2047   case Bytecodes::_fstore:
2048   case Bytecodes::_istore:
2049   case Bytecodes::_astore:
2050     set_local( iter().get_index(), pop() );
2051     break;
2052   // long stores
2053   case Bytecodes::_lstore_0:
2054     set_pair_local( 0, pop_pair() );
2055     break;
2056   case Bytecodes::_lstore_1:
2057     set_pair_local( 1, pop_pair() );
2058     break;
2059   case Bytecodes::_lstore_2:
2060     set_pair_local( 2, pop_pair() );
2061     break;
2062   case Bytecodes::_lstore_3:
2063     set_pair_local( 3, pop_pair() );
2064     break;
2065   case Bytecodes::_lstore:
2066     set_pair_local( iter().get_index(), pop_pair() );
2067     break;
2068 
2069   // double stores
2070   case Bytecodes::_dstore_0:
2071     set_pair_local( 0, dprecision_rounding(pop_pair()) );
2072     break;
2073   case Bytecodes::_dstore_1:
2074     set_pair_local( 1, dprecision_rounding(pop_pair()) );
2075     break;
2076   case Bytecodes::_dstore_2:
2077     set_pair_local( 2, dprecision_rounding(pop_pair()) );
2078     break;
2079   case Bytecodes::_dstore_3:
2080     set_pair_local( 3, dprecision_rounding(pop_pair()) );
2081     break;
2082   case Bytecodes::_dstore:
2083     set_pair_local( iter().get_index(), dprecision_rounding(pop_pair()) );
2084     break;
2085 
2086   case Bytecodes::_pop:  dec_sp(1);   break;
2087   case Bytecodes::_pop2: dec_sp(2);   break;
2088   case Bytecodes::_swap:
2089     a = pop();
2090     b = pop();
2091     push(a);
2092     push(b);
2093     break;
2094   case Bytecodes::_dup:
2095     a = pop();
2096     push(a);
2097     push(a);
2098     break;
2099   case Bytecodes::_dup_x1:
2100     a = pop();
2101     b = pop();
2102     push( a );
2103     push( b );
2104     push( a );
2105     break;
2106   case Bytecodes::_dup_x2:
2107     a = pop();
2108     b = pop();
2109     c = pop();
2110     push( a );
2111     push( c );
2112     push( b );
2113     push( a );
2114     break;
2115   case Bytecodes::_dup2:
2116     a = pop();
2117     b = pop();
2118     push( b );
2119     push( a );
2120     push( b );
2121     push( a );
2122     break;
2123 
2124   case Bytecodes::_dup2_x1:
2125     // before: .. c, b, a
2126     // after:  .. b, a, c, b, a
2127     // not tested
2128     a = pop();
2129     b = pop();
2130     c = pop();
2131     push( b );
2132     push( a );
2133     push( c );
2134     push( b );
2135     push( a );
2136     break;
2137   case Bytecodes::_dup2_x2:
2138     // before: .. d, c, b, a
2139     // after:  .. b, a, d, c, b, a
2140     // not tested
2141     a = pop();
2142     b = pop();
2143     c = pop();
2144     d = pop();
2145     push( b );
2146     push( a );
2147     push( d );
2148     push( c );
2149     push( b );
2150     push( a );
2151     break;
2152 
2153   case Bytecodes::_arraylength: {
2154     // Must do null-check with value on expression stack
2155     Node *ary = null_check(peek(), T_ARRAY);
2156     // Compile-time detect of null-exception?
2157     if (stopped())  return;
2158     a = pop();
2159     push(load_array_length(a));
2160     break;
2161   }
2162 
2163   case Bytecodes::_baload:  array_load(T_BYTE);    break;
2164   case Bytecodes::_caload:  array_load(T_CHAR);    break;
2165   case Bytecodes::_iaload:  array_load(T_INT);     break;
2166   case Bytecodes::_saload:  array_load(T_SHORT);   break;
2167   case Bytecodes::_faload:  array_load(T_FLOAT);   break;
2168   case Bytecodes::_aaload:  array_load(T_OBJECT);  break;
2169   case Bytecodes::_laload:  array_load(T_LONG);    break;
2170   case Bytecodes::_daload:  array_load(T_DOUBLE);  break;
2171   case Bytecodes::_bastore: array_store(T_BYTE);   break;
2172   case Bytecodes::_castore: array_store(T_CHAR);   break;
2173   case Bytecodes::_iastore: array_store(T_INT);    break;
2174   case Bytecodes::_sastore: array_store(T_SHORT);  break;
2175   case Bytecodes::_fastore: array_store(T_FLOAT);  break;
2176   case Bytecodes::_aastore: array_store(T_OBJECT); break;
2177   case Bytecodes::_lastore: array_store(T_LONG);   break;
2178   case Bytecodes::_dastore: array_store(T_DOUBLE); break;
2179 
2180   case Bytecodes::_getfield:
2181     do_getfield();
2182     break;
2183 
2184   case Bytecodes::_getstatic:
2185     do_getstatic();
2186     break;
2187 
2188   case Bytecodes::_putfield:
2189     do_putfield();
2190     break;
2191 
2192   case Bytecodes::_putstatic:
2193     do_putstatic();
2194     break;
2195 
2196   case Bytecodes::_irem:
2197     // Must keep both values on the expression-stack during null-check
2198     zero_check_int(peek());
2199     // Compile-time detect of null-exception?
2200     if (stopped())  return;
2201     b = pop();
2202     a = pop();
2203     push(_gvn.transform(new ModINode(control(), a, b)));
2204     break;
2205   case Bytecodes::_idiv:
2206     // Must keep both values on the expression-stack during null-check
2207     zero_check_int(peek());
2208     // Compile-time detect of null-exception?
2209     if (stopped())  return;
2210     b = pop();
2211     a = pop();
2212     push( _gvn.transform( new DivINode(control(),a,b) ) );
2213     break;
2214   case Bytecodes::_imul:
2215     b = pop(); a = pop();
2216     push( _gvn.transform( new MulINode(a,b) ) );
2217     break;
2218   case Bytecodes::_iadd:
2219     b = pop(); a = pop();
2220     push( _gvn.transform( new AddINode(a,b) ) );
2221     break;
2222   case Bytecodes::_ineg:
2223     a = pop();
2224     push( _gvn.transform( new SubINode(_gvn.intcon(0),a)) );
2225     break;
2226   case Bytecodes::_isub:
2227     b = pop(); a = pop();
2228     push( _gvn.transform( new SubINode(a,b) ) );
2229     break;
2230   case Bytecodes::_iand:
2231     b = pop(); a = pop();
2232     push( _gvn.transform( new AndINode(a,b) ) );
2233     break;
2234   case Bytecodes::_ior:
2235     b = pop(); a = pop();
2236     push( _gvn.transform( new OrINode(a,b) ) );
2237     break;
2238   case Bytecodes::_ixor:
2239     b = pop(); a = pop();
2240     push( _gvn.transform( new XorINode(a,b) ) );
2241     break;
2242   case Bytecodes::_ishl:
2243     b = pop(); a = pop();
2244     push( _gvn.transform( new LShiftINode(a,b) ) );
2245     break;
2246   case Bytecodes::_ishr:
2247     b = pop(); a = pop();
2248     push( _gvn.transform( new RShiftINode(a,b) ) );
2249     break;
2250   case Bytecodes::_iushr:
2251     b = pop(); a = pop();
2252     push( _gvn.transform( new URShiftINode(a,b) ) );
2253     break;
2254 
2255   case Bytecodes::_fneg:
2256     a = pop();
2257     b = _gvn.transform(new NegFNode (a));
2258     push(b);
2259     break;
2260 
2261   case Bytecodes::_fsub:
2262     b = pop();
2263     a = pop();
2264     c = _gvn.transform( new SubFNode(a,b) );
2265     d = precision_rounding(c);
2266     push( d );
2267     break;
2268 
2269   case Bytecodes::_fadd:
2270     b = pop();
2271     a = pop();
2272     c = _gvn.transform( new AddFNode(a,b) );
2273     d = precision_rounding(c);
2274     push( d );
2275     break;
2276 
2277   case Bytecodes::_fmul:
2278     b = pop();
2279     a = pop();
2280     c = _gvn.transform( new MulFNode(a,b) );
2281     d = precision_rounding(c);
2282     push( d );
2283     break;
2284 
2285   case Bytecodes::_fdiv:
2286     b = pop();
2287     a = pop();
2288     c = _gvn.transform( new DivFNode(nullptr,a,b) );
2289     d = precision_rounding(c);
2290     push( d );
2291     break;
2292 
2293   case Bytecodes::_frem:
2294     // Generate a ModF node.
2295     b = pop();
2296     a = pop();
2297     push(floating_point_mod(a, b, BasicType::T_FLOAT));
2298     break;
2299 
2300   case Bytecodes::_fcmpl:
2301     b = pop();
2302     a = pop();
2303     c = _gvn.transform( new CmpF3Node( a, b));
2304     push(c);
2305     break;
2306   case Bytecodes::_fcmpg:
2307     b = pop();
2308     a = pop();
2309 
2310     // Same as fcmpl but need to flip the unordered case.  Swap the inputs,
2311     // which negates the result sign except for unordered.  Flip the unordered
2312     // as well by using CmpF3 which implements unordered-lesser instead of
2313     // unordered-greater semantics.  Finally, commute the result bits.  Result
2314     // is same as using a CmpF3Greater except we did it with CmpF3 alone.
2315     c = _gvn.transform( new CmpF3Node( b, a));
2316     c = _gvn.transform( new SubINode(_gvn.intcon(0),c) );
2317     push(c);
2318     break;
2319 
2320   case Bytecodes::_f2i:
2321     a = pop();
2322     push(_gvn.transform(new ConvF2INode(a)));
2323     break;
2324 
2325   case Bytecodes::_d2i:
2326     a = pop_pair();
2327     b = _gvn.transform(new ConvD2INode(a));
2328     push( b );
2329     break;
2330 
2331   case Bytecodes::_f2d:
2332     a = pop();
2333     b = _gvn.transform( new ConvF2DNode(a));
2334     push_pair( b );
2335     break;
2336 
2337   case Bytecodes::_d2f:
2338     a = pop_pair();
2339     b = _gvn.transform( new ConvD2FNode(a));
2340     // This breaks _227_mtrt (speed & correctness) and _222_mpegaudio (speed)
2341     //b = _gvn.transform(new RoundFloatNode(nullptr, b) );
2342     push( b );
2343     break;
2344 
2345   case Bytecodes::_l2f:
2346     if (Matcher::convL2FSupported()) {
2347       a = pop_pair();
2348       b = _gvn.transform( new ConvL2FNode(a));
2349       // For x86_32.ad, FILD doesn't restrict precision to 24 or 53 bits.
2350       // Rather than storing the result into an FP register then pushing
2351       // out to memory to round, the machine instruction that implements
2352       // ConvL2D is responsible for rounding.
2353       // c = precision_rounding(b);
2354       push(b);
2355     } else {
2356       l2f();
2357     }
2358     break;
2359 
2360   case Bytecodes::_l2d:
2361     a = pop_pair();
2362     b = _gvn.transform( new ConvL2DNode(a));
2363     // For x86_32.ad, rounding is always necessary (see _l2f above).
2364     // c = dprecision_rounding(b);
2365     push_pair(b);
2366     break;
2367 
2368   case Bytecodes::_f2l:
2369     a = pop();
2370     b = _gvn.transform( new ConvF2LNode(a));
2371     push_pair(b);
2372     break;
2373 
2374   case Bytecodes::_d2l:
2375     a = pop_pair();
2376     b = _gvn.transform( new ConvD2LNode(a));
2377     push_pair(b);
2378     break;
2379 
2380   case Bytecodes::_dsub:
2381     b = pop_pair();
2382     a = pop_pair();
2383     c = _gvn.transform( new SubDNode(a,b) );
2384     d = dprecision_rounding(c);
2385     push_pair( d );
2386     break;
2387 
2388   case Bytecodes::_dadd:
2389     b = pop_pair();
2390     a = pop_pair();
2391     c = _gvn.transform( new AddDNode(a,b) );
2392     d = dprecision_rounding(c);
2393     push_pair( d );
2394     break;
2395 
2396   case Bytecodes::_dmul:
2397     b = pop_pair();
2398     a = pop_pair();
2399     c = _gvn.transform( new MulDNode(a,b) );
2400     d = dprecision_rounding(c);
2401     push_pair( d );
2402     break;
2403 
2404   case Bytecodes::_ddiv:
2405     b = pop_pair();
2406     a = pop_pair();
2407     c = _gvn.transform( new DivDNode(nullptr,a,b) );
2408     d = dprecision_rounding(c);
2409     push_pair( d );
2410     break;
2411 
2412   case Bytecodes::_dneg:
2413     a = pop_pair();
2414     b = _gvn.transform(new NegDNode (a));
2415     push_pair(b);
2416     break;
2417 
2418   case Bytecodes::_drem:
2419     // Generate a ModD node.
2420     b = pop_pair();
2421     a = pop_pair();
2422     push_pair(floating_point_mod(a, b, BasicType::T_DOUBLE));
2423     break;
2424 
2425   case Bytecodes::_dcmpl:
2426     b = pop_pair();
2427     a = pop_pair();
2428     c = _gvn.transform( new CmpD3Node( a, b));
2429     push(c);
2430     break;
2431 
2432   case Bytecodes::_dcmpg:
2433     b = pop_pair();
2434     a = pop_pair();
2435     // Same as dcmpl but need to flip the unordered case.
2436     // Commute the inputs, which negates the result sign except for unordered.
2437     // Flip the unordered as well by using CmpD3 which implements
2438     // unordered-lesser instead of unordered-greater semantics.
2439     // Finally, negate the result bits.  Result is same as using a
2440     // CmpD3Greater except we did it with CmpD3 alone.
2441     c = _gvn.transform( new CmpD3Node( b, a));
2442     c = _gvn.transform( new SubINode(_gvn.intcon(0),c) );
2443     push(c);
2444     break;
2445 
2446 
2447     // Note for longs -> lo word is on TOS, hi word is on TOS - 1
2448   case Bytecodes::_land:
2449     b = pop_pair();
2450     a = pop_pair();
2451     c = _gvn.transform( new AndLNode(a,b) );
2452     push_pair(c);
2453     break;
2454   case Bytecodes::_lor:
2455     b = pop_pair();
2456     a = pop_pair();
2457     c = _gvn.transform( new OrLNode(a,b) );
2458     push_pair(c);
2459     break;
2460   case Bytecodes::_lxor:
2461     b = pop_pair();
2462     a = pop_pair();
2463     c = _gvn.transform( new XorLNode(a,b) );
2464     push_pair(c);
2465     break;
2466 
2467   case Bytecodes::_lshl:
2468     b = pop();                  // the shift count
2469     a = pop_pair();             // value to be shifted
2470     c = _gvn.transform( new LShiftLNode(a,b) );
2471     push_pair(c);
2472     break;
2473   case Bytecodes::_lshr:
2474     b = pop();                  // the shift count
2475     a = pop_pair();             // value to be shifted
2476     c = _gvn.transform( new RShiftLNode(a,b) );
2477     push_pair(c);
2478     break;
2479   case Bytecodes::_lushr:
2480     b = pop();                  // the shift count
2481     a = pop_pair();             // value to be shifted
2482     c = _gvn.transform( new URShiftLNode(a,b) );
2483     push_pair(c);
2484     break;
2485   case Bytecodes::_lmul:
2486     b = pop_pair();
2487     a = pop_pair();
2488     c = _gvn.transform( new MulLNode(a,b) );
2489     push_pair(c);
2490     break;
2491 
2492   case Bytecodes::_lrem:
2493     // Must keep both values on the expression-stack during null-check
2494     assert(peek(0) == top(), "long word order");
2495     zero_check_long(peek(1));
2496     // Compile-time detect of null-exception?
2497     if (stopped())  return;
2498     b = pop_pair();
2499     a = pop_pair();
2500     c = _gvn.transform( new ModLNode(control(),a,b) );
2501     push_pair(c);
2502     break;
2503 
2504   case Bytecodes::_ldiv:
2505     // Must keep both values on the expression-stack during null-check
2506     assert(peek(0) == top(), "long word order");
2507     zero_check_long(peek(1));
2508     // Compile-time detect of null-exception?
2509     if (stopped())  return;
2510     b = pop_pair();
2511     a = pop_pair();
2512     c = _gvn.transform( new DivLNode(control(),a,b) );
2513     push_pair(c);
2514     break;
2515 
2516   case Bytecodes::_ladd:
2517     b = pop_pair();
2518     a = pop_pair();
2519     c = _gvn.transform( new AddLNode(a,b) );
2520     push_pair(c);
2521     break;
2522   case Bytecodes::_lsub:
2523     b = pop_pair();
2524     a = pop_pair();
2525     c = _gvn.transform( new SubLNode(a,b) );
2526     push_pair(c);
2527     break;
2528   case Bytecodes::_lcmp:
2529     // Safepoints are now inserted _before_ branches.  The long-compare
2530     // bytecode painfully produces a 3-way value (-1,0,+1) which requires a
2531     // slew of control flow.  These are usually followed by a CmpI vs zero and
2532     // a branch; this pattern then optimizes to the obvious long-compare and
2533     // branch.  However, if the branch is backwards there's a Safepoint
2534     // inserted.  The inserted Safepoint captures the JVM state at the
2535     // pre-branch point, i.e. it captures the 3-way value.  Thus if a
2536     // long-compare is used to control a loop the debug info will force
2537     // computation of the 3-way value, even though the generated code uses a
2538     // long-compare and branch.  We try to rectify the situation by inserting
2539     // a SafePoint here and have it dominate and kill the safepoint added at a
2540     // following backwards branch.  At this point the JVM state merely holds 2
2541     // longs but not the 3-way value.
2542     switch (iter().next_bc()) {
2543       case Bytecodes::_ifgt:
2544       case Bytecodes::_iflt:
2545       case Bytecodes::_ifge:
2546       case Bytecodes::_ifle:
2547       case Bytecodes::_ifne:
2548       case Bytecodes::_ifeq:
2549         // If this is a backwards branch in the bytecodes, add Safepoint
2550         maybe_add_safepoint(iter().next_get_dest());
2551       default:
2552         break;
2553     }
2554     b = pop_pair();
2555     a = pop_pair();
2556     c = _gvn.transform( new CmpL3Node( a, b ));
2557     push(c);
2558     break;
2559 
2560   case Bytecodes::_lneg:
2561     a = pop_pair();
2562     b = _gvn.transform( new SubLNode(longcon(0),a));
2563     push_pair(b);
2564     break;
2565   case Bytecodes::_l2i:
2566     a = pop_pair();
2567     push( _gvn.transform( new ConvL2INode(a)));
2568     break;
2569   case Bytecodes::_i2l:
2570     a = pop();
2571     b = _gvn.transform( new ConvI2LNode(a));
2572     push_pair(b);
2573     break;
2574   case Bytecodes::_i2b:
2575     // Sign extend
2576     a = pop();
2577     a = Compile::narrow_value(T_BYTE, a, nullptr, &_gvn, true);
2578     push(a);
2579     break;
2580   case Bytecodes::_i2s:
2581     a = pop();
2582     a = Compile::narrow_value(T_SHORT, a, nullptr, &_gvn, true);
2583     push(a);
2584     break;
2585   case Bytecodes::_i2c:
2586     a = pop();
2587     a = Compile::narrow_value(T_CHAR, a, nullptr, &_gvn, true);
2588     push(a);
2589     break;
2590 
2591   case Bytecodes::_i2f:
2592     a = pop();
2593     b = _gvn.transform( new ConvI2FNode(a) ) ;
2594     c = precision_rounding(b);
2595     push (b);
2596     break;
2597 
2598   case Bytecodes::_i2d:
2599     a = pop();
2600     b = _gvn.transform( new ConvI2DNode(a));
2601     push_pair(b);
2602     break;
2603 
2604   case Bytecodes::_iinc:        // Increment local
2605     i = iter().get_index();     // Get local index
2606     set_local( i, _gvn.transform( new AddINode( _gvn.intcon(iter().get_iinc_con()), local(i) ) ) );
2607     break;
2608 
2609   // Exit points of synchronized methods must have an unlock node
2610   case Bytecodes::_return:
2611     return_current(nullptr);
2612     break;
2613 
2614   case Bytecodes::_ireturn:
2615   case Bytecodes::_areturn:
2616   case Bytecodes::_freturn:
2617     return_current(pop());
2618     break;
2619   case Bytecodes::_lreturn:
2620     return_current(pop_pair());
2621     break;
2622   case Bytecodes::_dreturn:
2623     return_current(pop_pair());
2624     break;
2625 
2626   case Bytecodes::_athrow:
2627     // null exception oop throws null pointer exception
2628     null_check(peek());
2629     if (stopped())  return;
2630     // Hook the thrown exception directly to subsequent handlers.
2631     if (BailoutToInterpreterForThrows) {
2632       // Keep method interpreted from now on.
2633       uncommon_trap(Deoptimization::Reason_unhandled,
2634                     Deoptimization::Action_make_not_compilable);
2635       return;
2636     }
2637     if (env()->jvmti_can_post_on_exceptions()) {
2638       // check if we must post exception events, take uncommon trap if so (with must_throw = false)
2639       uncommon_trap_if_should_post_on_exceptions(Deoptimization::Reason_unhandled, false);
2640     }
2641     // Here if either can_post_on_exceptions or should_post_on_exceptions is false
2642     add_exception_state(make_exception_state(peek()));
2643     break;
2644 
2645   case Bytecodes::_goto:   // fall through
2646   case Bytecodes::_goto_w: {
2647     int target_bci = (bc() == Bytecodes::_goto) ? iter().get_dest() : iter().get_far_dest();
2648 
2649     // If this is a backwards branch in the bytecodes, add Safepoint
2650     maybe_add_safepoint(target_bci);
2651 
2652     // Merge the current control into the target basic block
2653     merge(target_bci);
2654 
2655     // See if we can get some profile data and hand it off to the next block
2656     Block *target_block = block()->successor_for_bci(target_bci);
2657     if (target_block->pred_count() != 1)  break;
2658     ciMethodData* methodData = method()->method_data();
2659     if (!methodData->is_mature())  break;
2660     ciProfileData* data = methodData->bci_to_data(bci());
2661     assert(data != nullptr && data->is_JumpData(), "need JumpData for taken branch");
2662     int taken = ((ciJumpData*)data)->taken();
2663     taken = method()->scale_count(taken);
2664     target_block->set_count(taken);
2665     break;
2666   }
2667 
2668   case Bytecodes::_ifnull:    btest = BoolTest::eq; goto handle_if_null;
2669   case Bytecodes::_ifnonnull: btest = BoolTest::ne; goto handle_if_null;
2670   handle_if_null:
2671     // If this is a backwards branch in the bytecodes, add Safepoint
2672     maybe_add_safepoint(iter().get_dest());
2673     a = null();
2674     b = pop();
2675     if (!_gvn.type(b)->speculative_maybe_null() &&
2676         !too_many_traps(Deoptimization::Reason_speculate_null_check)) {
2677       inc_sp(1);
2678       Node* null_ctl = top();
2679       b = null_check_oop(b, &null_ctl, true, true, true);
2680       assert(null_ctl->is_top(), "no null control here");
2681       dec_sp(1);
2682     } else if (_gvn.type(b)->speculative_always_null() &&
2683                !too_many_traps(Deoptimization::Reason_speculate_null_assert)) {
2684       inc_sp(1);
2685       b = null_assert(b);
2686       dec_sp(1);
2687     }
2688     c = _gvn.transform( new CmpPNode(b, a) );
2689     do_ifnull(btest, c);
2690     break;
2691 
2692   case Bytecodes::_if_acmpeq: btest = BoolTest::eq; goto handle_if_acmp;
2693   case Bytecodes::_if_acmpne: btest = BoolTest::ne; goto handle_if_acmp;
2694   handle_if_acmp:
2695     // If this is a backwards branch in the bytecodes, add Safepoint
2696     maybe_add_safepoint(iter().get_dest());
2697     a = pop();
2698     b = pop();
2699     c = _gvn.transform( new CmpPNode(b, a) );
2700     c = optimize_cmp_with_klass(c);
2701     do_if(btest, c);
2702     break;
2703 
2704   case Bytecodes::_ifeq: btest = BoolTest::eq; goto handle_ifxx;
2705   case Bytecodes::_ifne: btest = BoolTest::ne; goto handle_ifxx;
2706   case Bytecodes::_iflt: btest = BoolTest::lt; goto handle_ifxx;
2707   case Bytecodes::_ifle: btest = BoolTest::le; goto handle_ifxx;
2708   case Bytecodes::_ifgt: btest = BoolTest::gt; goto handle_ifxx;
2709   case Bytecodes::_ifge: btest = BoolTest::ge; goto handle_ifxx;
2710   handle_ifxx:
2711     // If this is a backwards branch in the bytecodes, add Safepoint
2712     maybe_add_safepoint(iter().get_dest());
2713     a = _gvn.intcon(0);
2714     b = pop();
2715     c = _gvn.transform( new CmpINode(b, a) );
2716     do_if(btest, c);
2717     break;
2718 
2719   case Bytecodes::_if_icmpeq: btest = BoolTest::eq; goto handle_if_icmp;
2720   case Bytecodes::_if_icmpne: btest = BoolTest::ne; goto handle_if_icmp;
2721   case Bytecodes::_if_icmplt: btest = BoolTest::lt; goto handle_if_icmp;
2722   case Bytecodes::_if_icmple: btest = BoolTest::le; goto handle_if_icmp;
2723   case Bytecodes::_if_icmpgt: btest = BoolTest::gt; goto handle_if_icmp;
2724   case Bytecodes::_if_icmpge: btest = BoolTest::ge; goto handle_if_icmp;
2725   handle_if_icmp:
2726     // If this is a backwards branch in the bytecodes, add Safepoint
2727     maybe_add_safepoint(iter().get_dest());
2728     a = pop();
2729     b = pop();
2730     c = _gvn.transform( new CmpINode( b, a ) );
2731     do_if(btest, c);
2732     break;
2733 
2734   case Bytecodes::_tableswitch:
2735     do_tableswitch();
2736     break;
2737 
2738   case Bytecodes::_lookupswitch:
2739     do_lookupswitch();
2740     break;
2741 
2742   case Bytecodes::_invokestatic:
2743   case Bytecodes::_invokedynamic:
2744   case Bytecodes::_invokespecial:
2745   case Bytecodes::_invokevirtual:
2746   case Bytecodes::_invokeinterface:
2747     do_call();
2748     break;
2749   case Bytecodes::_checkcast:
2750     do_checkcast();
2751     break;
2752   case Bytecodes::_instanceof:
2753     do_instanceof();
2754     break;
2755   case Bytecodes::_anewarray:
2756     do_anewarray();
2757     break;
2758   case Bytecodes::_newarray:
2759     do_newarray((BasicType)iter().get_index());
2760     break;
2761   case Bytecodes::_multianewarray:
2762     do_multianewarray();
2763     break;
2764   case Bytecodes::_new:
2765     do_new();
2766     break;
2767 
2768   case Bytecodes::_jsr:
2769   case Bytecodes::_jsr_w:
2770     do_jsr();
2771     break;
2772 
2773   case Bytecodes::_ret:
2774     do_ret();
2775     break;
2776 
2777 
2778   case Bytecodes::_monitorenter:
2779     do_monitor_enter();
2780     break;
2781 
2782   case Bytecodes::_monitorexit:
2783     do_monitor_exit();
2784     break;
2785 
2786   case Bytecodes::_breakpoint:
2787     // Breakpoint set concurrently to compile
2788     // %%% use an uncommon trap?
2789     C->record_failure("breakpoint in method");
2790     return;
2791 
2792   default:
2793 #ifndef PRODUCT
2794     map()->dump(99);
2795 #endif
2796     tty->print("\nUnhandled bytecode %s\n", Bytecodes::name(bc()) );
2797     ShouldNotReachHere();
2798   }
2799 
2800 #ifndef PRODUCT
2801   if (failing()) { return; }
2802   constexpr int perBytecode = 6;
2803   if (C->should_print_igv(perBytecode)) {
2804     IdealGraphPrinter* printer = C->igv_printer();
2805     char buffer[256];
2806     jio_snprintf(buffer, sizeof(buffer), "Bytecode %d: %s", bci(), Bytecodes::name(bc()));
2807     bool old = printer->traverse_outs();
2808     printer->set_traverse_outs(true);
2809     printer->print_graph(buffer);
2810     printer->set_traverse_outs(old);
2811   }
2812 #endif
2813 }