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