1 /*
   2  * Copyright (c) 1998, 2024, 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 "ci/ciSymbols.hpp"
  28 #include "classfile/vmSymbols.hpp"
  29 #include "compiler/compileLog.hpp"
  30 #include "interpreter/linkResolver.hpp"
  31 #include "jvm_io.h"
  32 #include "memory/resourceArea.hpp"
  33 #include "memory/universe.hpp"
  34 #include "oops/oop.inline.hpp"
  35 #include "opto/addnode.hpp"
  36 #include "opto/castnode.hpp"
  37 #include "opto/convertnode.hpp"
  38 #include "opto/divnode.hpp"
  39 #include "opto/idealGraphPrinter.hpp"
  40 #include "opto/idealKit.hpp"
  41 #include "opto/inlinetypenode.hpp"
  42 #include "opto/matcher.hpp"
  43 #include "opto/memnode.hpp"
  44 #include "opto/mulnode.hpp"
  45 #include "opto/opaquenode.hpp"
  46 #include "opto/parse.hpp"
  47 #include "opto/runtime.hpp"
  48 #include "runtime/deoptimization.hpp"
  49 #include "runtime/sharedRuntime.hpp"
  50 
  51 #ifndef PRODUCT
  52 extern uint explicit_null_checks_inserted,
  53             explicit_null_checks_elided;
  54 #endif
  55 
  56 Node* Parse::record_profile_for_speculation_at_array_load(Node* ld) {
  57   // Feed unused profile data to type speculation
  58   if (UseTypeSpeculation && UseArrayLoadStoreProfile) {
  59     ciKlass* array_type = nullptr;
  60     ciKlass* element_type = nullptr;
  61     ProfilePtrKind element_ptr = ProfileMaybeNull;
  62     bool flat_array = true;
  63     bool null_free_array = true;
  64     method()->array_access_profiled_type(bci(), array_type, element_type, element_ptr, flat_array, null_free_array);
  65     if (element_type != nullptr || element_ptr != ProfileMaybeNull) {
  66       ld = record_profile_for_speculation(ld, element_type, element_ptr);
  67     }
  68   }
  69   return ld;
  70 }
  71 
  72 
  73 //---------------------------------array_load----------------------------------
  74 void Parse::array_load(BasicType bt) {
  75   const Type* elemtype = Type::TOP;
  76   Node* adr = array_addressing(bt, 0, elemtype);
  77   if (stopped())  return;     // guaranteed null or range check
  78 
  79   Node* idx = pop();
  80   Node* ary = pop();
  81 
  82   // Handle inline type arrays
  83   const TypeOopPtr* elemptr = elemtype->make_oopptr();
  84   const TypeAryPtr* ary_t = _gvn.type(ary)->is_aryptr();
  85   if (ary_t->is_flat()) {
  86     // Load from flat inline type array
  87     Node* vt = InlineTypeNode::make_from_flat(this, elemtype->inline_klass(), ary, adr);
  88     push(vt);
  89     return;
  90   } else if (ary_t->is_null_free()) {
  91     // Load from non-flat inline type array (elements can never be null)
  92     bt = T_OBJECT;
  93   } else if (!ary_t->is_not_flat()) {
  94     // Cannot statically determine if array is a flat array, emit runtime check
  95     assert(UseFlatArray && is_reference_type(bt) && elemptr->can_be_inline_type() && !ary_t->is_not_null_free() &&
  96            (!elemptr->is_inlinetypeptr() || elemptr->inline_klass()->flat_in_array()), "array can't be flat");
  97     IdealKit ideal(this);
  98     IdealVariable res(ideal);
  99     ideal.declarations_done();
 100     ideal.if_then(flat_array_test(ary, /* flat = */ false)); {
 101       // non-flat array
 102       assert(ideal.ctrl()->in(0)->as_If()->is_flat_array_check(&_gvn), "Should be found");
 103       sync_kit(ideal);
 104       const TypeAryPtr* adr_type = TypeAryPtr::get_array_body_type(bt);
 105       DecoratorSet decorator_set = IN_HEAP | IS_ARRAY | C2_CONTROL_DEPENDENT_LOAD;
 106       if (needs_range_check(ary_t->size(), idx)) {
 107         // We've emitted a RangeCheck but now insert an additional check between the range check and the actual load.
 108         // We cannot pin the load to two separate nodes. Instead, we pin it conservatively here such that it cannot
 109         // possibly float above the range check at any point.
 110         decorator_set |= C2_UNKNOWN_CONTROL_LOAD;
 111       }
 112       Node* ld = access_load_at(ary, adr, adr_type, elemptr, bt, decorator_set);
 113       if (elemptr->is_inlinetypeptr()) {
 114         assert(elemptr->maybe_null(), "null free array should be handled above");
 115         ld = InlineTypeNode::make_from_oop(this, ld, elemptr->inline_klass(), false);
 116       }
 117       ideal.sync_kit(this);
 118       ideal.set(res, ld);
 119     } ideal.else_(); {
 120       // flat array
 121       sync_kit(ideal);
 122       if (elemptr->is_inlinetypeptr()) {
 123         // Element type is known, cast and load from flat representation
 124         ciInlineKlass* vk = elemptr->inline_klass();
 125         assert(vk->flat_in_array() && elemptr->maybe_null(), "never/always flat - should be optimized");
 126         ciArrayKlass* array_klass = ciArrayKlass::make(vk, /* null_free */ true);
 127         const TypeAryPtr* arytype = TypeOopPtr::make_from_klass(array_klass)->isa_aryptr();
 128         Node* cast = _gvn.transform(new CheckCastPPNode(control(), ary, arytype));
 129         Node* casted_adr = array_element_address(cast, idx, T_OBJECT, ary_t->size(), control());
 130         // Re-execute flat array load if buffering triggers deoptimization
 131         PreserveReexecuteState preexecs(this);
 132         jvms()->set_should_reexecute(true);
 133         inc_sp(2);
 134         Node* vt = InlineTypeNode::make_from_flat(this, vk, cast, casted_adr)->buffer(this, false);
 135         ideal.set(res, vt);
 136         ideal.sync_kit(this);
 137       } else {
 138         // Element type is unknown, emit runtime call
 139 
 140         // Below membars keep this access to an unknown flat array correctly
 141         // ordered with other unknown and known flat array accesses.
 142         insert_mem_bar_volatile(Op_MemBarCPUOrder, C->get_alias_index(TypeAryPtr::INLINES));
 143 
 144         Node* call = nullptr;
 145         {
 146           // Re-execute flat array load if runtime call triggers deoptimization
 147           PreserveReexecuteState preexecs(this);
 148           jvms()->set_bci(_bci);
 149           jvms()->set_should_reexecute(true);
 150           inc_sp(2);
 151           kill_dead_locals();
 152           call = make_runtime_call(RC_NO_LEAF | RC_NO_IO,
 153                                    OptoRuntime::load_unknown_inline_type(),
 154                                    OptoRuntime::load_unknown_inline_Java(),
 155                                    nullptr, TypeRawPtr::BOTTOM,
 156                                    ary, idx);
 157         }
 158         make_slow_call_ex(call, env()->Throwable_klass(), false);
 159         Node* buffer = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
 160 
 161         insert_mem_bar_volatile(Op_MemBarCPUOrder, C->get_alias_index(TypeAryPtr::INLINES));
 162 
 163         // Keep track of the information that the inline type is in flat arrays
 164         const Type* unknown_value = elemptr->is_instptr()->cast_to_flat_in_array();
 165         buffer = _gvn.transform(new CheckCastPPNode(control(), buffer, unknown_value));
 166 
 167         ideal.sync_kit(this);
 168         ideal.set(res, buffer);
 169       }
 170     } ideal.end_if();
 171     sync_kit(ideal);
 172     Node* ld = _gvn.transform(ideal.value(res));
 173     ld = record_profile_for_speculation_at_array_load(ld);
 174     push_node(bt, ld);
 175     return;
 176   }
 177 
 178   if (elemtype == TypeInt::BOOL) {
 179     bt = T_BOOLEAN;
 180   }
 181   const TypeAryPtr* adr_type = TypeAryPtr::get_array_body_type(bt);
 182   Node* ld = access_load_at(ary, adr, adr_type, elemtype, bt,
 183                             IN_HEAP | IS_ARRAY | C2_CONTROL_DEPENDENT_LOAD);
 184   ld = record_profile_for_speculation_at_array_load(ld);
 185   // Loading an inline type from a non-flat array
 186   if (elemptr != nullptr && elemptr->is_inlinetypeptr()) {
 187     assert(!ary_t->is_null_free() || !elemptr->maybe_null(), "inline type array elements should never be null");
 188     ld = InlineTypeNode::make_from_oop(this, ld, elemptr->inline_klass(), !elemptr->maybe_null());
 189   }
 190   push_node(bt, ld);
 191 }
 192 
 193 
 194 //--------------------------------array_store----------------------------------
 195 void Parse::array_store(BasicType bt) {
 196   const Type* elemtype = Type::TOP;
 197   Node* adr = array_addressing(bt, type2size[bt], elemtype);
 198   if (stopped())  return;     // guaranteed null or range check
 199   Node* cast_val = nullptr;
 200   if (bt == T_OBJECT) {
 201     cast_val = array_store_check(adr, elemtype);
 202     if (stopped()) return;
 203   }
 204   Node* val = pop_node(bt); // Value to store
 205   Node* idx = pop();        // Index in the array
 206   Node* ary = pop();        // The array itself
 207 
 208   const TypeAryPtr* ary_t = _gvn.type(ary)->is_aryptr();
 209   const TypeAryPtr* adr_type = TypeAryPtr::get_array_body_type(bt);
 210 
 211   if (elemtype == TypeInt::BOOL) {
 212     bt = T_BOOLEAN;
 213   } else if (bt == T_OBJECT) {
 214     elemtype = elemtype->make_oopptr();
 215     const Type* tval = _gvn.type(cast_val);
 216     // Based on the value to be stored, try to determine if the array is not null-free and/or not flat.
 217     // This is only legal for non-null stores because the array_store_check always passes for null, even
 218     // if the array is null-free. Null stores are handled in GraphKit::gen_inline_array_null_guard().
 219     bool not_null_free = !tval->maybe_null() && !tval->is_oopptr()->can_be_inline_type();
 220     bool not_flat = not_null_free || (tval->is_inlinetypeptr() && !tval->inline_klass()->flat_in_array());
 221     if (!ary_t->is_not_null_free() && not_null_free) {
 222       // Storing a non-inline type, mark array as not null-free (-> not flat).
 223       ary_t = ary_t->cast_to_not_null_free();
 224       Node* cast = _gvn.transform(new CheckCastPPNode(control(), ary, ary_t));
 225       replace_in_map(ary, cast);
 226       ary = cast;
 227     } else if (!ary_t->is_not_flat() && not_flat) {
 228       // Storing to a non-flat array, mark array as not flat.
 229       ary_t = ary_t->cast_to_not_flat();
 230       Node* cast = _gvn.transform(new CheckCastPPNode(control(), ary, ary_t));
 231       replace_in_map(ary, cast);
 232       ary = cast;
 233     }
 234 
 235     if (ary_t->is_flat()) {
 236       // Store to flat inline type array
 237       assert(!tval->maybe_null(), "should be guaranteed by array store check");
 238       // Re-execute flat array store if buffering triggers deoptimization
 239       PreserveReexecuteState preexecs(this);
 240       inc_sp(3);
 241       jvms()->set_should_reexecute(true);
 242       cast_val->as_InlineType()->store_flat(this, ary, adr, nullptr, 0, MO_UNORDERED | IN_HEAP | IS_ARRAY);
 243       return;
 244     } else if (ary_t->is_null_free()) {
 245       // Store to non-flat inline type array (elements can never be null)
 246       assert(!tval->maybe_null(), "should be guaranteed by array store check");
 247       if (elemtype->inline_klass()->is_empty()) {
 248         // Ignore empty inline stores, array is already initialized.
 249         return;
 250       }
 251     } else if (!ary_t->is_not_flat() && (tval != TypePtr::NULL_PTR || StressReflectiveCode)) {
 252       // Array might be a flat array, emit runtime checks (for nullptr, a simple inline_array_null_guard is sufficient).
 253       assert(UseFlatArray && !not_flat && elemtype->is_oopptr()->can_be_inline_type() &&
 254              !ary_t->klass_is_exact() && !ary_t->is_not_null_free(), "array can't be a flat array");
 255       IdealKit ideal(this);
 256       ideal.if_then(flat_array_test(ary, /* flat = */ false)); {
 257         // non-flat array
 258         assert(ideal.ctrl()->in(0)->as_If()->is_flat_array_check(&_gvn), "Should be found");
 259         sync_kit(ideal);
 260         Node* cast_ary = inline_array_null_guard(ary, cast_val, 3);
 261         inc_sp(3);
 262         access_store_at(cast_ary, adr, adr_type, cast_val, elemtype, bt, MO_UNORDERED | IN_HEAP | IS_ARRAY, false);
 263         dec_sp(3);
 264         ideal.sync_kit(this);
 265       } ideal.else_(); {
 266         sync_kit(ideal);
 267         // flat array
 268         Node* null_ctl = top();
 269         Node* val = null_check_oop(cast_val, &null_ctl);
 270         if (null_ctl != top()) {
 271           PreserveJVMState pjvms(this);
 272           inc_sp(3);
 273           set_control(null_ctl);
 274           uncommon_trap(Deoptimization::Reason_null_check, Deoptimization::Action_none);
 275           dec_sp(3);
 276         }
 277         // Try to determine the inline klass
 278         ciInlineKlass* vk = nullptr;
 279         if (tval->is_inlinetypeptr()) {
 280           vk = tval->inline_klass();
 281         } else if (elemtype->is_inlinetypeptr()) {
 282           vk = elemtype->inline_klass();
 283         }
 284         Node* casted_ary = ary;
 285         if (vk != nullptr && !stopped()) {
 286           // Element type is known, cast and store to flat representation
 287           assert(vk->flat_in_array() && elemtype->maybe_null(), "never/always flat - should be optimized");
 288           ciArrayKlass* array_klass = ciArrayKlass::make(vk, /* null_free */ true);
 289           const TypeAryPtr* arytype = TypeOopPtr::make_from_klass(array_klass)->isa_aryptr();
 290           casted_ary = _gvn.transform(new CheckCastPPNode(control(), casted_ary, arytype));
 291           Node* casted_adr = array_element_address(casted_ary, idx, T_OBJECT, arytype->size(), control());
 292           if (!val->is_InlineType()) {
 293             assert(!gvn().type(val)->maybe_null(), "inline type array elements should never be null");
 294             val = InlineTypeNode::make_from_oop(this, val, vk);
 295           }
 296           // Re-execute flat array store if buffering triggers deoptimization
 297           PreserveReexecuteState preexecs(this);
 298           inc_sp(3);
 299           jvms()->set_should_reexecute(true);
 300           val->as_InlineType()->store_flat(this, casted_ary, casted_adr, nullptr, 0, MO_UNORDERED | IN_HEAP | IS_ARRAY);
 301         } else if (!stopped()) {
 302           // Element type is unknown, emit runtime call
 303 
 304           // Below membars keep this access to an unknown flat array correctly
 305           // ordered with other unknown and known flat array accesses.
 306           insert_mem_bar_volatile(Op_MemBarCPUOrder, C->get_alias_index(TypeAryPtr::INLINES));
 307 
 308           make_runtime_call(RC_LEAF,
 309                             OptoRuntime::store_unknown_inline_type(),
 310                             CAST_FROM_FN_PTR(address, OptoRuntime::store_unknown_inline),
 311                             "store_unknown_inline", TypeRawPtr::BOTTOM,
 312                             val, casted_ary, idx);
 313 
 314           insert_mem_bar_volatile(Op_MemBarCPUOrder, C->get_alias_index(TypeAryPtr::INLINES));
 315         }
 316         ideal.sync_kit(this);
 317       }
 318       ideal.end_if();
 319       sync_kit(ideal);
 320       return;
 321     } else if (!ary_t->is_not_null_free()) {
 322       // Array is not flat but may be null free
 323       assert(elemtype->is_oopptr()->can_be_inline_type(), "array can't be null-free");
 324       ary = inline_array_null_guard(ary, cast_val, 3, true);
 325     }
 326   }
 327   inc_sp(3);
 328   access_store_at(ary, adr, adr_type, val, elemtype, bt, MO_UNORDERED | IN_HEAP | IS_ARRAY);
 329   dec_sp(3);
 330 }
 331 
 332 
 333 //------------------------------array_addressing-------------------------------
 334 // Pull array and index from the stack.  Compute pointer-to-element.
 335 Node* Parse::array_addressing(BasicType type, int vals, const Type*& elemtype) {
 336   Node *idx   = peek(0+vals);   // Get from stack without popping
 337   Node *ary   = peek(1+vals);   // in case of exception
 338 
 339   // Null check the array base, with correct stack contents
 340   ary = null_check(ary, T_ARRAY);
 341   // Compile-time detect of null-exception?
 342   if (stopped())  return top();
 343 
 344   const TypeAryPtr* arytype  = _gvn.type(ary)->is_aryptr();
 345   const TypeInt*    sizetype = arytype->size();
 346   elemtype = arytype->elem();
 347 
 348   if (UseUniqueSubclasses) {
 349     const Type* el = elemtype->make_ptr();
 350     if (el && el->isa_instptr()) {
 351       const TypeInstPtr* toop = el->is_instptr();
 352       if (toop->instance_klass()->unique_concrete_subklass()) {
 353         // If we load from "AbstractClass[]" we must see "ConcreteSubClass".
 354         const Type* subklass = Type::get_const_type(toop->instance_klass());
 355         elemtype = subklass->join_speculative(el);
 356       }
 357     }
 358   }
 359 
 360   if (!arytype->is_loaded()) {
 361     // Only fails for some -Xcomp runs
 362     // The class is unloaded.  We have to run this bytecode in the interpreter.
 363     ciKlass* klass = arytype->unloaded_klass();
 364 
 365     uncommon_trap(Deoptimization::Reason_unloaded,
 366                   Deoptimization::Action_reinterpret,
 367                   klass, "!loaded array");
 368     return top();
 369   }
 370 
 371   ary = create_speculative_inline_type_array_checks(ary, arytype, elemtype);
 372 
 373   if (needs_range_check(sizetype, idx)) {
 374     create_range_check(idx, ary, sizetype);
 375   } else if (C->log() != nullptr) {
 376     C->log()->elem("observe that='!need_range_check'");
 377   }
 378 
 379   // Check for always knowing you are throwing a range-check exception
 380   if (stopped())  return top();
 381 
 382   // Make array address computation control dependent to prevent it
 383   // from floating above the range check during loop optimizations.
 384   Node* ptr = array_element_address(ary, idx, type, sizetype, control());
 385   assert(ptr != top(), "top should go hand-in-hand with stopped");
 386 
 387   return ptr;
 388 }
 389 
 390 // Check if we need a range check for an array access. This is the case if the index is either negative or if it could
 391 // be greater or equal the smallest possible array size (i.e. out-of-bounds).
 392 bool Parse::needs_range_check(const TypeInt* size_type, const Node* index) const {
 393   const TypeInt* index_type = _gvn.type(index)->is_int();
 394   return index_type->_hi >= size_type->_lo || index_type->_lo < 0;
 395 }
 396 
 397 void Parse::create_range_check(Node* idx, Node* ary, const TypeInt* sizetype) {
 398   Node* tst;
 399   if (sizetype->_hi <= 0) {
 400     // The greatest array bound is negative, so we can conclude that we're
 401     // compiling unreachable code, but the unsigned compare trick used below
 402     // only works with non-negative lengths.  Instead, hack "tst" to be zero so
 403     // the uncommon_trap path will always be taken.
 404     tst = _gvn.intcon(0);
 405   } else {
 406     // Range is constant in array-oop, so we can use the original state of mem
 407     Node* len = load_array_length(ary);
 408 
 409     // Test length vs index (standard trick using unsigned compare)
 410     Node* chk = _gvn.transform(new CmpUNode(idx, len) );
 411     BoolTest::mask btest = BoolTest::lt;
 412     tst = _gvn.transform(new BoolNode(chk, btest) );
 413   }
 414   RangeCheckNode* rc = new RangeCheckNode(control(), tst, PROB_MAX, COUNT_UNKNOWN);
 415   _gvn.set_type(rc, rc->Value(&_gvn));
 416   if (!tst->is_Con()) {
 417     record_for_igvn(rc);
 418   }
 419   set_control(_gvn.transform(new IfTrueNode(rc)));
 420   // Branch to failure if out of bounds
 421   {
 422     PreserveJVMState pjvms(this);
 423     set_control(_gvn.transform(new IfFalseNode(rc)));
 424     if (C->allow_range_check_smearing()) {
 425       // Do not use builtin_throw, since range checks are sometimes
 426       // made more stringent by an optimistic transformation.
 427       // This creates "tentative" range checks at this point,
 428       // which are not guaranteed to throw exceptions.
 429       // See IfNode::Ideal, is_range_check, adjust_check.
 430       uncommon_trap(Deoptimization::Reason_range_check,
 431                     Deoptimization::Action_make_not_entrant,
 432                     nullptr, "range_check");
 433     } else {
 434       // If we have already recompiled with the range-check-widening
 435       // heroic optimization turned off, then we must really be throwing
 436       // range check exceptions.
 437       builtin_throw(Deoptimization::Reason_range_check);
 438     }
 439   }
 440 }
 441 
 442 // For inline type arrays, we can use the profiling information for array accesses to speculate on the type, flatness,
 443 // and null-freeness. We can either prepare the speculative type for later uses or emit explicit speculative checks with
 444 // traps now. In the latter case, the speculative type guarantees can avoid additional runtime checks later (e.g.
 445 // non-null-free implies non-flat which allows us to remove flatness checks). This makes the graph simpler.
 446 Node* Parse::create_speculative_inline_type_array_checks(Node* array, const TypeAryPtr* array_type,
 447                                                          const Type*& element_type) {
 448   if (!array_type->is_flat() && !array_type->is_not_flat()) {
 449     // For arrays that might be flat, speculate that the array has the exact type reported in the profile data such that
 450     // we can rely on a fixed memory layout (i.e. either a flat layout or not).
 451     array = cast_to_speculative_array_type(array, array_type, element_type);
 452   } else if (UseTypeSpeculation && UseArrayLoadStoreProfile) {
 453     // Array is known to be either flat or not flat. If possible, update the speculative type by using the profile data
 454     // at this bci.
 455     array = cast_to_profiled_array_type(array);
 456   }
 457 
 458   // Even though the type does not tell us whether we have an inline type array or not, we can still check the profile data
 459   // whether we have a non-null-free or non-flat array. Since non-null-free implies non-flat, we check this first.
 460   // Speculating on a non-null-free array doesn't help aaload but could be profitable for a subsequent aastore.
 461   if (!array_type->is_null_free() && !array_type->is_not_null_free()) {
 462     array = speculate_non_null_free_array(array, array_type);
 463   }
 464 
 465   if (!array_type->is_flat() && !array_type->is_not_flat()) {
 466     array = speculate_non_flat_array(array, array_type);
 467   }
 468   return array;
 469 }
 470 
 471 // Speculate that the array has the exact type reported in the profile data. We emit a trap when this turns out to be
 472 // wrong. On the fast path, we add a CheckCastPP to use the exact type.
 473 Node* Parse::cast_to_speculative_array_type(Node* const array, const TypeAryPtr*& array_type, const Type*& element_type) {
 474   Deoptimization::DeoptReason reason = Deoptimization::Reason_speculate_class_check;
 475   ciKlass* speculative_array_type = array_type->speculative_type();
 476   if (too_many_traps_or_recompiles(reason) || speculative_array_type == nullptr) {
 477     // No speculative type, check profile data at this bci
 478     speculative_array_type = nullptr;
 479     reason = Deoptimization::Reason_class_check;
 480     if (UseArrayLoadStoreProfile && !too_many_traps_or_recompiles(reason)) {
 481       ciKlass* profiled_element_type = nullptr;
 482       ProfilePtrKind element_ptr = ProfileMaybeNull;
 483       bool flat_array = true;
 484       bool null_free_array = true;
 485       method()->array_access_profiled_type(bci(), speculative_array_type, profiled_element_type, element_ptr, flat_array,
 486                                            null_free_array);
 487     }
 488   }
 489   if (speculative_array_type != nullptr) {
 490     // Speculate that this array has the exact type reported by profile data
 491     Node* casted_array = nullptr;
 492     DEBUG_ONLY(Node* old_control = control();)
 493     Node* slow_ctl = type_check_receiver(array, speculative_array_type, 1.0, &casted_array);
 494     if (stopped()) {
 495       // The check always fails and therefore profile information is incorrect. Don't use it.
 496       assert(old_control == slow_ctl, "type check should have been removed");
 497       set_control(slow_ctl);
 498     } else if (!slow_ctl->is_top()) {
 499       { PreserveJVMState pjvms(this);
 500         set_control(slow_ctl);
 501         uncommon_trap_exact(reason, Deoptimization::Action_maybe_recompile);
 502       }
 503       replace_in_map(array, casted_array);
 504       array_type = _gvn.type(casted_array)->is_aryptr();
 505       element_type = array_type->elem();
 506       return casted_array;
 507     }
 508   }
 509   return array;
 510 }
 511 
 512 // Create a CheckCastPP when the speculative type can improve the current type.
 513 Node* Parse::cast_to_profiled_array_type(Node* const array) {
 514   ciKlass* array_type = nullptr;
 515   ciKlass* element_type = nullptr;
 516   ProfilePtrKind element_ptr = ProfileMaybeNull;
 517   bool flat_array = true;
 518   bool null_free_array = true;
 519   method()->array_access_profiled_type(bci(), array_type, element_type, element_ptr, flat_array, null_free_array);
 520   if (array_type != nullptr) {
 521     return record_profile_for_speculation(array, array_type, ProfileMaybeNull);
 522   }
 523   return array;
 524 }
 525 
 526 // Speculate that the array is non-null-free. This will imply non-flatness. We emit a trap when this turns out to be
 527 // wrong. On the fast path, we add a CheckCastPP to use the non-null-free type.
 528 Node* Parse::speculate_non_null_free_array(Node* const array, const TypeAryPtr*& array_type) {
 529   bool null_free_array = true;
 530   Deoptimization::DeoptReason reason = Deoptimization::Reason_none;
 531   if (array_type->speculative() != nullptr &&
 532       array_type->speculative()->is_aryptr()->is_not_null_free() &&
 533       !too_many_traps_or_recompiles(Deoptimization::Reason_speculate_class_check)) {
 534     null_free_array = false;
 535     reason = Deoptimization::Reason_speculate_class_check;
 536   } else if (UseArrayLoadStoreProfile && !too_many_traps_or_recompiles(Deoptimization::Reason_class_check)) {
 537     ciKlass* profiled_array_type = nullptr;
 538     ciKlass* profiled_element_type = nullptr;
 539     ProfilePtrKind element_ptr = ProfileMaybeNull;
 540     bool flat_array = true;
 541     method()->array_access_profiled_type(bci(), profiled_array_type, profiled_element_type, element_ptr, flat_array,
 542                                          null_free_array);
 543     reason = Deoptimization::Reason_class_check;
 544   }
 545   if (!null_free_array) {
 546     { // Deoptimize if null-free array
 547       BuildCutout unless(this, null_free_array_test(array, /* null_free = */ false), PROB_MAX);
 548       uncommon_trap_exact(reason, Deoptimization::Action_maybe_recompile);
 549     }
 550     assert(!stopped(), "null-free array should have been caught earlier");
 551     Node* casted_array = _gvn.transform(new CheckCastPPNode(control(), array, array_type->cast_to_not_null_free()));
 552     replace_in_map(array, casted_array);
 553     array_type = _gvn.type(casted_array)->is_aryptr();
 554     return casted_array;
 555   }
 556   return array;
 557 }
 558 
 559 // Speculate that the array is non-flat. We emit a trap when this turns out to be wrong. On the fast path, we add a
 560 // CheckCastPP to use the non-flat type.
 561 Node* Parse::speculate_non_flat_array(Node* const array, const TypeAryPtr* const array_type) {
 562   bool flat_array = true;
 563   Deoptimization::DeoptReason reason = Deoptimization::Reason_none;
 564   if (array_type->speculative() != nullptr &&
 565       array_type->speculative()->is_aryptr()->is_not_flat() &&
 566       !too_many_traps_or_recompiles(Deoptimization::Reason_speculate_class_check)) {
 567     flat_array = false;
 568     reason = Deoptimization::Reason_speculate_class_check;
 569   } else if (UseArrayLoadStoreProfile && !too_many_traps_or_recompiles(reason)) {
 570     ciKlass* profiled_array_type = nullptr;
 571     ciKlass* profiled_element_type = nullptr;
 572     ProfilePtrKind element_ptr = ProfileMaybeNull;
 573     bool null_free_array = true;
 574     method()->array_access_profiled_type(bci(), profiled_array_type, profiled_element_type, element_ptr, flat_array,
 575                                          null_free_array);
 576     reason = Deoptimization::Reason_class_check;
 577   }
 578   if (!flat_array) {
 579     { // Deoptimize if flat array
 580       BuildCutout unless(this, flat_array_test(array, /* flat = */ false), PROB_MAX);
 581       uncommon_trap_exact(reason, Deoptimization::Action_maybe_recompile);
 582     }
 583     assert(!stopped(), "flat array should have been caught earlier");
 584     Node* casted_array = _gvn.transform(new CheckCastPPNode(control(), array, array_type->cast_to_not_flat()));
 585     replace_in_map(array, casted_array);
 586     return casted_array;
 587   }
 588   return array;
 589 }
 590 
 591 // returns IfNode
 592 IfNode* Parse::jump_if_fork_int(Node* a, Node* b, BoolTest::mask mask, float prob, float cnt) {
 593   Node   *cmp = _gvn.transform(new CmpINode(a, b)); // two cases: shiftcount > 32 and shiftcount <= 32
 594   Node   *tst = _gvn.transform(new BoolNode(cmp, mask));
 595   IfNode *iff = create_and_map_if(control(), tst, prob, cnt);
 596   return iff;
 597 }
 598 
 599 
 600 // sentinel value for the target bci to mark never taken branches
 601 // (according to profiling)
 602 static const int never_reached = INT_MAX;
 603 
 604 //------------------------------helper for tableswitch-------------------------
 605 void Parse::jump_if_true_fork(IfNode *iff, int dest_bci_if_true, bool unc) {
 606   // True branch, use existing map info
 607   { PreserveJVMState pjvms(this);
 608     Node *iftrue  = _gvn.transform( new IfTrueNode (iff) );
 609     set_control( iftrue );
 610     if (unc) {
 611       repush_if_args();
 612       uncommon_trap(Deoptimization::Reason_unstable_if,
 613                     Deoptimization::Action_reinterpret,
 614                     nullptr,
 615                     "taken always");
 616     } else {
 617       assert(dest_bci_if_true != never_reached, "inconsistent dest");
 618       merge_new_path(dest_bci_if_true);
 619     }
 620   }
 621 
 622   // False branch
 623   Node *iffalse = _gvn.transform( new IfFalseNode(iff) );
 624   set_control( iffalse );
 625 }
 626 
 627 void Parse::jump_if_false_fork(IfNode *iff, int dest_bci_if_true, bool unc) {
 628   // True branch, use existing map info
 629   { PreserveJVMState pjvms(this);
 630     Node *iffalse  = _gvn.transform( new IfFalseNode (iff) );
 631     set_control( iffalse );
 632     if (unc) {
 633       repush_if_args();
 634       uncommon_trap(Deoptimization::Reason_unstable_if,
 635                     Deoptimization::Action_reinterpret,
 636                     nullptr,
 637                     "taken never");
 638     } else {
 639       assert(dest_bci_if_true != never_reached, "inconsistent dest");
 640       merge_new_path(dest_bci_if_true);
 641     }
 642   }
 643 
 644   // False branch
 645   Node *iftrue = _gvn.transform( new IfTrueNode(iff) );
 646   set_control( iftrue );
 647 }
 648 
 649 void Parse::jump_if_always_fork(int dest_bci, bool unc) {
 650   // False branch, use existing map and control()
 651   if (unc) {
 652     repush_if_args();
 653     uncommon_trap(Deoptimization::Reason_unstable_if,
 654                   Deoptimization::Action_reinterpret,
 655                   nullptr,
 656                   "taken never");
 657   } else {
 658     assert(dest_bci != never_reached, "inconsistent dest");
 659     merge_new_path(dest_bci);
 660   }
 661 }
 662 
 663 
 664 extern "C" {
 665   static int jint_cmp(const void *i, const void *j) {
 666     int a = *(jint *)i;
 667     int b = *(jint *)j;
 668     return a > b ? 1 : a < b ? -1 : 0;
 669   }
 670 }
 671 
 672 
 673 class SwitchRange : public StackObj {
 674   // a range of integers coupled with a bci destination
 675   jint _lo;                     // inclusive lower limit
 676   jint _hi;                     // inclusive upper limit
 677   int _dest;
 678   float _cnt;                   // how many times this range was hit according to profiling
 679 
 680 public:
 681   jint lo() const              { return _lo;   }
 682   jint hi() const              { return _hi;   }
 683   int  dest() const            { return _dest; }
 684   bool is_singleton() const    { return _lo == _hi; }
 685   float cnt() const            { return _cnt; }
 686 
 687   void setRange(jint lo, jint hi, int dest, float cnt) {
 688     assert(lo <= hi, "must be a non-empty range");
 689     _lo = lo, _hi = hi; _dest = dest; _cnt = cnt;
 690     assert(_cnt >= 0, "");
 691   }
 692   bool adjoinRange(jint lo, jint hi, int dest, float cnt, bool trim_ranges) {
 693     assert(lo <= hi, "must be a non-empty range");
 694     if (lo == _hi+1) {
 695       // see merge_ranges() comment below
 696       if (trim_ranges) {
 697         if (cnt == 0) {
 698           if (_cnt != 0) {
 699             return false;
 700           }
 701           if (dest != _dest) {
 702             _dest = never_reached;
 703           }
 704         } else {
 705           if (_cnt == 0) {
 706             return false;
 707           }
 708           if (dest != _dest) {
 709             return false;
 710           }
 711         }
 712       } else {
 713         if (dest != _dest) {
 714           return false;
 715         }
 716       }
 717       _hi = hi;
 718       _cnt += cnt;
 719       return true;
 720     }
 721     return false;
 722   }
 723 
 724   void set (jint value, int dest, float cnt) {
 725     setRange(value, value, dest, cnt);
 726   }
 727   bool adjoin(jint value, int dest, float cnt, bool trim_ranges) {
 728     return adjoinRange(value, value, dest, cnt, trim_ranges);
 729   }
 730   bool adjoin(SwitchRange& other) {
 731     return adjoinRange(other._lo, other._hi, other._dest, other._cnt, false);
 732   }
 733 
 734   void print() {
 735     if (is_singleton())
 736       tty->print(" {%d}=>%d (cnt=%f)", lo(), dest(), cnt());
 737     else if (lo() == min_jint)
 738       tty->print(" {..%d}=>%d (cnt=%f)", hi(), dest(), cnt());
 739     else if (hi() == max_jint)
 740       tty->print(" {%d..}=>%d (cnt=%f)", lo(), dest(), cnt());
 741     else
 742       tty->print(" {%d..%d}=>%d (cnt=%f)", lo(), hi(), dest(), cnt());
 743   }
 744 };
 745 
 746 // We try to minimize the number of ranges and the size of the taken
 747 // ones using profiling data. When ranges are created,
 748 // SwitchRange::adjoinRange() only allows 2 adjoining ranges to merge
 749 // if both were never hit or both were hit to build longer unreached
 750 // ranges. Here, we now merge adjoining ranges with the same
 751 // destination and finally set destination of unreached ranges to the
 752 // special value never_reached because it can help minimize the number
 753 // of tests that are necessary.
 754 //
 755 // For instance:
 756 // [0, 1] to target1 sometimes taken
 757 // [1, 2] to target1 never taken
 758 // [2, 3] to target2 never taken
 759 // would lead to:
 760 // [0, 1] to target1 sometimes taken
 761 // [1, 3] never taken
 762 //
 763 // (first 2 ranges to target1 are not merged)
 764 static void merge_ranges(SwitchRange* ranges, int& rp) {
 765   if (rp == 0) {
 766     return;
 767   }
 768   int shift = 0;
 769   for (int j = 0; j < rp; j++) {
 770     SwitchRange& r1 = ranges[j-shift];
 771     SwitchRange& r2 = ranges[j+1];
 772     if (r1.adjoin(r2)) {
 773       shift++;
 774     } else if (shift > 0) {
 775       ranges[j+1-shift] = r2;
 776     }
 777   }
 778   rp -= shift;
 779   for (int j = 0; j <= rp; j++) {
 780     SwitchRange& r = ranges[j];
 781     if (r.cnt() == 0 && r.dest() != never_reached) {
 782       r.setRange(r.lo(), r.hi(), never_reached, r.cnt());
 783     }
 784   }
 785 }
 786 
 787 //-------------------------------do_tableswitch--------------------------------
 788 void Parse::do_tableswitch() {
 789   // Get information about tableswitch
 790   int default_dest = iter().get_dest_table(0);
 791   jint lo_index    = iter().get_int_table(1);
 792   jint hi_index    = iter().get_int_table(2);
 793   int len          = hi_index - lo_index + 1;
 794 
 795   if (len < 1) {
 796     // If this is a backward branch, add safepoint
 797     maybe_add_safepoint(default_dest);
 798     pop(); // the effect of the instruction execution on the operand stack
 799     merge(default_dest);
 800     return;
 801   }
 802 
 803   ciMethodData* methodData = method()->method_data();
 804   ciMultiBranchData* profile = nullptr;
 805   if (methodData->is_mature() && UseSwitchProfiling) {
 806     ciProfileData* data = methodData->bci_to_data(bci());
 807     if (data != nullptr && data->is_MultiBranchData()) {
 808       profile = (ciMultiBranchData*)data;
 809     }
 810   }
 811   bool trim_ranges = !C->too_many_traps(method(), bci(), Deoptimization::Reason_unstable_if);
 812 
 813   // generate decision tree, using trichotomy when possible
 814   int rnum = len+2;
 815   bool makes_backward_branch = (default_dest <= bci());
 816   SwitchRange* ranges = NEW_RESOURCE_ARRAY(SwitchRange, rnum);
 817   int rp = -1;
 818   if (lo_index != min_jint) {
 819     float cnt = 1.0F;
 820     if (profile != nullptr) {
 821       cnt = (float)profile->default_count() / (hi_index != max_jint ? 2.0F : 1.0F);
 822     }
 823     ranges[++rp].setRange(min_jint, lo_index-1, default_dest, cnt);
 824   }
 825   for (int j = 0; j < len; j++) {
 826     jint match_int = lo_index+j;
 827     int  dest      = iter().get_dest_table(j+3);
 828     makes_backward_branch |= (dest <= bci());
 829     float cnt = 1.0F;
 830     if (profile != nullptr) {
 831       cnt = (float)profile->count_at(j);
 832     }
 833     if (rp < 0 || !ranges[rp].adjoin(match_int, dest, cnt, trim_ranges)) {
 834       ranges[++rp].set(match_int, dest, cnt);
 835     }
 836   }
 837   jint highest = lo_index+(len-1);
 838   assert(ranges[rp].hi() == highest, "");
 839   if (highest != max_jint) {
 840     float cnt = 1.0F;
 841     if (profile != nullptr) {
 842       cnt = (float)profile->default_count() / (lo_index != min_jint ? 2.0F : 1.0F);
 843     }
 844     if (!ranges[rp].adjoinRange(highest+1, max_jint, default_dest, cnt, trim_ranges)) {
 845       ranges[++rp].setRange(highest+1, max_jint, default_dest, cnt);
 846     }
 847   }
 848   assert(rp < len+2, "not too many ranges");
 849 
 850   if (trim_ranges) {
 851     merge_ranges(ranges, rp);
 852   }
 853 
 854   // Safepoint in case if backward branch observed
 855   if (makes_backward_branch) {
 856     add_safepoint();
 857   }
 858 
 859   Node* lookup = pop(); // lookup value
 860   jump_switch_ranges(lookup, &ranges[0], &ranges[rp]);
 861 }
 862 
 863 
 864 //------------------------------do_lookupswitch--------------------------------
 865 void Parse::do_lookupswitch() {
 866   // Get information about lookupswitch
 867   int default_dest = iter().get_dest_table(0);
 868   jint len          = iter().get_int_table(1);
 869 
 870   if (len < 1) {    // If this is a backward branch, add safepoint
 871     maybe_add_safepoint(default_dest);
 872     pop(); // the effect of the instruction execution on the operand stack
 873     merge(default_dest);
 874     return;
 875   }
 876 
 877   ciMethodData* methodData = method()->method_data();
 878   ciMultiBranchData* profile = nullptr;
 879   if (methodData->is_mature() && UseSwitchProfiling) {
 880     ciProfileData* data = methodData->bci_to_data(bci());
 881     if (data != nullptr && data->is_MultiBranchData()) {
 882       profile = (ciMultiBranchData*)data;
 883     }
 884   }
 885   bool trim_ranges = !C->too_many_traps(method(), bci(), Deoptimization::Reason_unstable_if);
 886 
 887   // generate decision tree, using trichotomy when possible
 888   jint* table = NEW_RESOURCE_ARRAY(jint, len*3);
 889   {
 890     for (int j = 0; j < len; j++) {
 891       table[3*j+0] = iter().get_int_table(2+2*j);
 892       table[3*j+1] = iter().get_dest_table(2+2*j+1);
 893       // Handle overflow when converting from uint to jint
 894       table[3*j+2] = (profile == nullptr) ? 1 : (jint)MIN2<uint>((uint)max_jint, profile->count_at(j));
 895     }
 896     qsort(table, len, 3*sizeof(table[0]), jint_cmp);
 897   }
 898 
 899   float default_cnt = 1.0F;
 900   if (profile != nullptr) {
 901     juint defaults = max_juint - len;
 902     default_cnt = (float)profile->default_count()/(float)defaults;
 903   }
 904 
 905   int rnum = len*2+1;
 906   bool makes_backward_branch = (default_dest <= bci());
 907   SwitchRange* ranges = NEW_RESOURCE_ARRAY(SwitchRange, rnum);
 908   int rp = -1;
 909   for (int j = 0; j < len; j++) {
 910     jint match_int   = table[3*j+0];
 911     jint  dest        = table[3*j+1];
 912     jint  cnt         = table[3*j+2];
 913     jint  next_lo     = rp < 0 ? min_jint : ranges[rp].hi()+1;
 914     makes_backward_branch |= (dest <= bci());
 915     float c = default_cnt * ((float)match_int - (float)next_lo);
 916     if (match_int != next_lo && (rp < 0 || !ranges[rp].adjoinRange(next_lo, match_int-1, default_dest, c, trim_ranges))) {
 917       assert(default_dest != never_reached, "sentinel value for dead destinations");
 918       ranges[++rp].setRange(next_lo, match_int-1, default_dest, c);
 919     }
 920     if (rp < 0 || !ranges[rp].adjoin(match_int, dest, (float)cnt, trim_ranges)) {
 921       assert(dest != never_reached, "sentinel value for dead destinations");
 922       ranges[++rp].set(match_int, dest,  (float)cnt);
 923     }
 924   }
 925   jint highest = table[3*(len-1)];
 926   assert(ranges[rp].hi() == highest, "");
 927   if (highest != max_jint &&
 928       !ranges[rp].adjoinRange(highest+1, max_jint, default_dest, default_cnt * ((float)max_jint - (float)highest), trim_ranges)) {
 929     ranges[++rp].setRange(highest+1, max_jint, default_dest, default_cnt * ((float)max_jint - (float)highest));
 930   }
 931   assert(rp < rnum, "not too many ranges");
 932 
 933   if (trim_ranges) {
 934     merge_ranges(ranges, rp);
 935   }
 936 
 937   // Safepoint in case backward branch observed
 938   if (makes_backward_branch) {
 939     add_safepoint();
 940   }
 941 
 942   Node *lookup = pop(); // lookup value
 943   jump_switch_ranges(lookup, &ranges[0], &ranges[rp]);
 944 }
 945 
 946 static float if_prob(float taken_cnt, float total_cnt) {
 947   assert(taken_cnt <= total_cnt, "");
 948   if (total_cnt == 0) {
 949     return PROB_FAIR;
 950   }
 951   float p = taken_cnt / total_cnt;
 952   return clamp(p, PROB_MIN, PROB_MAX);
 953 }
 954 
 955 static float if_cnt(float cnt) {
 956   if (cnt == 0) {
 957     return COUNT_UNKNOWN;
 958   }
 959   return cnt;
 960 }
 961 
 962 static float sum_of_cnts(SwitchRange *lo, SwitchRange *hi) {
 963   float total_cnt = 0;
 964   for (SwitchRange* sr = lo; sr <= hi; sr++) {
 965     total_cnt += sr->cnt();
 966   }
 967   return total_cnt;
 968 }
 969 
 970 class SwitchRanges : public ResourceObj {
 971 public:
 972   SwitchRange* _lo;
 973   SwitchRange* _hi;
 974   SwitchRange* _mid;
 975   float _cost;
 976 
 977   enum {
 978     Start,
 979     LeftDone,
 980     RightDone,
 981     Done
 982   } _state;
 983 
 984   SwitchRanges(SwitchRange *lo, SwitchRange *hi)
 985     : _lo(lo), _hi(hi), _mid(nullptr),
 986       _cost(0), _state(Start) {
 987   }
 988 
 989   SwitchRanges()
 990     : _lo(nullptr), _hi(nullptr), _mid(nullptr),
 991       _cost(0), _state(Start) {}
 992 };
 993 
 994 // Estimate cost of performing a binary search on lo..hi
 995 static float compute_tree_cost(SwitchRange *lo, SwitchRange *hi, float total_cnt) {
 996   GrowableArray<SwitchRanges> tree;
 997   SwitchRanges root(lo, hi);
 998   tree.push(root);
 999 
1000   float cost = 0;
1001   do {
1002     SwitchRanges& r = *tree.adr_at(tree.length()-1);
1003     if (r._hi != r._lo) {
1004       if (r._mid == nullptr) {
1005         float r_cnt = sum_of_cnts(r._lo, r._hi);
1006 
1007         if (r_cnt == 0) {
1008           tree.pop();
1009           cost = 0;
1010           continue;
1011         }
1012 
1013         SwitchRange* mid = nullptr;
1014         mid = r._lo;
1015         for (float cnt = 0; ; ) {
1016           assert(mid <= r._hi, "out of bounds");
1017           cnt += mid->cnt();
1018           if (cnt > r_cnt / 2) {
1019             break;
1020           }
1021           mid++;
1022         }
1023         assert(mid <= r._hi, "out of bounds");
1024         r._mid = mid;
1025         r._cost = r_cnt / total_cnt;
1026       }
1027       r._cost += cost;
1028       if (r._state < SwitchRanges::LeftDone && r._mid > r._lo) {
1029         cost = 0;
1030         r._state = SwitchRanges::LeftDone;
1031         tree.push(SwitchRanges(r._lo, r._mid-1));
1032       } else if (r._state < SwitchRanges::RightDone) {
1033         cost = 0;
1034         r._state = SwitchRanges::RightDone;
1035         tree.push(SwitchRanges(r._mid == r._lo ? r._mid+1 : r._mid, r._hi));
1036       } else {
1037         tree.pop();
1038         cost = r._cost;
1039       }
1040     } else {
1041       tree.pop();
1042       cost = r._cost;
1043     }
1044   } while (tree.length() > 0);
1045 
1046 
1047   return cost;
1048 }
1049 
1050 // It sometimes pays off to test most common ranges before the binary search
1051 void Parse::linear_search_switch_ranges(Node* key_val, SwitchRange*& lo, SwitchRange*& hi) {
1052   uint nr = hi - lo + 1;
1053   float total_cnt = sum_of_cnts(lo, hi);
1054 
1055   float min = compute_tree_cost(lo, hi, total_cnt);
1056   float extra = 1;
1057   float sub = 0;
1058 
1059   SwitchRange* array1 = lo;
1060   SwitchRange* array2 = NEW_RESOURCE_ARRAY(SwitchRange, nr);
1061 
1062   SwitchRange* ranges = nullptr;
1063 
1064   while (nr >= 2) {
1065     assert(lo == array1 || lo == array2, "one the 2 already allocated arrays");
1066     ranges = (lo == array1) ? array2 : array1;
1067 
1068     // Find highest frequency range
1069     SwitchRange* candidate = lo;
1070     for (SwitchRange* sr = lo+1; sr <= hi; sr++) {
1071       if (sr->cnt() > candidate->cnt()) {
1072         candidate = sr;
1073       }
1074     }
1075     SwitchRange most_freq = *candidate;
1076     if (most_freq.cnt() == 0) {
1077       break;
1078     }
1079 
1080     // Copy remaining ranges into another array
1081     int shift = 0;
1082     for (uint i = 0; i < nr; i++) {
1083       SwitchRange* sr = &lo[i];
1084       if (sr != candidate) {
1085         ranges[i-shift] = *sr;
1086       } else {
1087         shift++;
1088         if (i > 0 && i < nr-1) {
1089           SwitchRange prev = lo[i-1];
1090           prev.setRange(prev.lo(), sr->hi(), prev.dest(), prev.cnt());
1091           if (prev.adjoin(lo[i+1])) {
1092             shift++;
1093             i++;
1094           }
1095           ranges[i-shift] = prev;
1096         }
1097       }
1098     }
1099     nr -= shift;
1100 
1101     // Evaluate cost of testing the most common range and performing a
1102     // binary search on the other ranges
1103     float cost = extra + compute_tree_cost(&ranges[0], &ranges[nr-1], total_cnt);
1104     if (cost >= min) {
1105       break;
1106     }
1107     // swap arrays
1108     lo = &ranges[0];
1109     hi = &ranges[nr-1];
1110 
1111     // It pays off: emit the test for the most common range
1112     assert(most_freq.cnt() > 0, "must be taken");
1113     Node* val = _gvn.transform(new SubINode(key_val, _gvn.intcon(most_freq.lo())));
1114     Node* cmp = _gvn.transform(new CmpUNode(val, _gvn.intcon(java_subtract(most_freq.hi(), most_freq.lo()))));
1115     Node* tst = _gvn.transform(new BoolNode(cmp, BoolTest::le));
1116     IfNode* iff = create_and_map_if(control(), tst, if_prob(most_freq.cnt(), total_cnt), if_cnt(most_freq.cnt()));
1117     jump_if_true_fork(iff, most_freq.dest(), false);
1118 
1119     sub += most_freq.cnt() / total_cnt;
1120     extra += 1 - sub;
1121     min = cost;
1122   }
1123 }
1124 
1125 //----------------------------create_jump_tables-------------------------------
1126 bool Parse::create_jump_tables(Node* key_val, SwitchRange* lo, SwitchRange* hi) {
1127   // Are jumptables enabled
1128   if (!UseJumpTables)  return false;
1129 
1130   // Are jumptables supported
1131   if (!Matcher::has_match_rule(Op_Jump))  return false;
1132 
1133   bool trim_ranges = !C->too_many_traps(method(), bci(), Deoptimization::Reason_unstable_if);
1134 
1135   // Decide if a guard is needed to lop off big ranges at either (or
1136   // both) end(s) of the input set. We'll call this the default target
1137   // even though we can't be sure that it is the true "default".
1138 
1139   bool needs_guard = false;
1140   int default_dest;
1141   int64_t total_outlier_size = 0;
1142   int64_t hi_size = ((int64_t)hi->hi()) - ((int64_t)hi->lo()) + 1;
1143   int64_t lo_size = ((int64_t)lo->hi()) - ((int64_t)lo->lo()) + 1;
1144 
1145   if (lo->dest() == hi->dest()) {
1146     total_outlier_size = hi_size + lo_size;
1147     default_dest = lo->dest();
1148   } else if (lo_size > hi_size) {
1149     total_outlier_size = lo_size;
1150     default_dest = lo->dest();
1151   } else {
1152     total_outlier_size = hi_size;
1153     default_dest = hi->dest();
1154   }
1155 
1156   float total = sum_of_cnts(lo, hi);
1157   float cost = compute_tree_cost(lo, hi, total);
1158 
1159   // If a guard test will eliminate very sparse end ranges, then
1160   // it is worth the cost of an extra jump.
1161   float trimmed_cnt = 0;
1162   if (total_outlier_size > (MaxJumpTableSparseness * 4)) {
1163     needs_guard = true;
1164     if (default_dest == lo->dest()) {
1165       trimmed_cnt += lo->cnt();
1166       lo++;
1167     }
1168     if (default_dest == hi->dest()) {
1169       trimmed_cnt += hi->cnt();
1170       hi--;
1171     }
1172   }
1173 
1174   // Find the total number of cases and ranges
1175   int64_t num_cases = ((int64_t)hi->hi()) - ((int64_t)lo->lo()) + 1;
1176   int num_range = hi - lo + 1;
1177 
1178   // Don't create table if: too large, too small, or too sparse.
1179   if (num_cases > MaxJumpTableSize)
1180     return false;
1181   if (UseSwitchProfiling) {
1182     // MinJumpTableSize is set so with a well balanced binary tree,
1183     // when the number of ranges is MinJumpTableSize, it's cheaper to
1184     // go through a JumpNode that a tree of IfNodes. Average cost of a
1185     // tree of IfNodes with MinJumpTableSize is
1186     // log2f(MinJumpTableSize) comparisons. So if the cost computed
1187     // from profile data is less than log2f(MinJumpTableSize) then
1188     // going with the binary search is cheaper.
1189     if (cost < log2f(MinJumpTableSize)) {
1190       return false;
1191     }
1192   } else {
1193     if (num_cases < MinJumpTableSize)
1194       return false;
1195   }
1196   if (num_cases > (MaxJumpTableSparseness * num_range))
1197     return false;
1198 
1199   // Normalize table lookups to zero
1200   int lowval = lo->lo();
1201   key_val = _gvn.transform( new SubINode(key_val, _gvn.intcon(lowval)) );
1202 
1203   // Generate a guard to protect against input keyvals that aren't
1204   // in the switch domain.
1205   if (needs_guard) {
1206     Node*   size = _gvn.intcon(num_cases);
1207     Node*   cmp = _gvn.transform(new CmpUNode(key_val, size));
1208     Node*   tst = _gvn.transform(new BoolNode(cmp, BoolTest::ge));
1209     IfNode* iff = create_and_map_if(control(), tst, if_prob(trimmed_cnt, total), if_cnt(trimmed_cnt));
1210     jump_if_true_fork(iff, default_dest, trim_ranges && trimmed_cnt == 0);
1211 
1212     total -= trimmed_cnt;
1213   }
1214 
1215   // Create an ideal node JumpTable that has projections
1216   // of all possible ranges for a switch statement
1217   // The key_val input must be converted to a pointer offset and scaled.
1218   // Compare Parse::array_addressing above.
1219 
1220   // Clean the 32-bit int into a real 64-bit offset.
1221   // Otherwise, the jint value 0 might turn into an offset of 0x0800000000.
1222   // Make I2L conversion control dependent to prevent it from
1223   // floating above the range check during loop optimizations.
1224   // Do not use a narrow int type here to prevent the data path from dying
1225   // while the control path is not removed. This can happen if the type of key_val
1226   // is later known to be out of bounds of [0, num_cases] and therefore a narrow cast
1227   // would be replaced by TOP while C2 is not able to fold the corresponding range checks.
1228   // Set _carry_dependency for the cast to avoid being removed by IGVN.
1229 #ifdef _LP64
1230   key_val = C->constrained_convI2L(&_gvn, key_val, TypeInt::INT, control(), true /* carry_dependency */);
1231 #endif
1232 
1233   // Shift the value by wordsize so we have an index into the table, rather
1234   // than a switch value
1235   Node *shiftWord = _gvn.MakeConX(wordSize);
1236   key_val = _gvn.transform( new MulXNode( key_val, shiftWord));
1237 
1238   // Create the JumpNode
1239   Arena* arena = C->comp_arena();
1240   float* probs = (float*)arena->Amalloc(sizeof(float)*num_cases);
1241   int i = 0;
1242   if (total == 0) {
1243     for (SwitchRange* r = lo; r <= hi; r++) {
1244       for (int64_t j = r->lo(); j <= r->hi(); j++, i++) {
1245         probs[i] = 1.0F / num_cases;
1246       }
1247     }
1248   } else {
1249     for (SwitchRange* r = lo; r <= hi; r++) {
1250       float prob = r->cnt()/total;
1251       for (int64_t j = r->lo(); j <= r->hi(); j++, i++) {
1252         probs[i] = prob / (r->hi() - r->lo() + 1);
1253       }
1254     }
1255   }
1256 
1257   ciMethodData* methodData = method()->method_data();
1258   ciMultiBranchData* profile = nullptr;
1259   if (methodData->is_mature()) {
1260     ciProfileData* data = methodData->bci_to_data(bci());
1261     if (data != nullptr && data->is_MultiBranchData()) {
1262       profile = (ciMultiBranchData*)data;
1263     }
1264   }
1265 
1266   Node* jtn = _gvn.transform(new JumpNode(control(), key_val, num_cases, probs, profile == nullptr ? COUNT_UNKNOWN : total));
1267 
1268   // These are the switch destinations hanging off the jumpnode
1269   i = 0;
1270   for (SwitchRange* r = lo; r <= hi; r++) {
1271     for (int64_t j = r->lo(); j <= r->hi(); j++, i++) {
1272       Node* input = _gvn.transform(new JumpProjNode(jtn, i, r->dest(), (int)(j - lowval)));
1273       {
1274         PreserveJVMState pjvms(this);
1275         set_control(input);
1276         jump_if_always_fork(r->dest(), trim_ranges && r->cnt() == 0);
1277       }
1278     }
1279   }
1280   assert(i == num_cases, "miscount of cases");
1281   stop_and_kill_map();  // no more uses for this JVMS
1282   return true;
1283 }
1284 
1285 //----------------------------jump_switch_ranges-------------------------------
1286 void Parse::jump_switch_ranges(Node* key_val, SwitchRange *lo, SwitchRange *hi, int switch_depth) {
1287   Block* switch_block = block();
1288   bool trim_ranges = !C->too_many_traps(method(), bci(), Deoptimization::Reason_unstable_if);
1289 
1290   if (switch_depth == 0) {
1291     // Do special processing for the top-level call.
1292     assert(lo->lo() == min_jint, "initial range must exhaust Type::INT");
1293     assert(hi->hi() == max_jint, "initial range must exhaust Type::INT");
1294 
1295     // Decrement pred-numbers for the unique set of nodes.
1296 #ifdef ASSERT
1297     if (!trim_ranges) {
1298       // Ensure that the block's successors are a (duplicate-free) set.
1299       int successors_counted = 0;  // block occurrences in [hi..lo]
1300       int unique_successors = switch_block->num_successors();
1301       for (int i = 0; i < unique_successors; i++) {
1302         Block* target = switch_block->successor_at(i);
1303 
1304         // Check that the set of successors is the same in both places.
1305         int successors_found = 0;
1306         for (SwitchRange* p = lo; p <= hi; p++) {
1307           if (p->dest() == target->start())  successors_found++;
1308         }
1309         assert(successors_found > 0, "successor must be known");
1310         successors_counted += successors_found;
1311       }
1312       assert(successors_counted == (hi-lo)+1, "no unexpected successors");
1313     }
1314 #endif
1315 
1316     // Maybe prune the inputs, based on the type of key_val.
1317     jint min_val = min_jint;
1318     jint max_val = max_jint;
1319     const TypeInt* ti = key_val->bottom_type()->isa_int();
1320     if (ti != nullptr) {
1321       min_val = ti->_lo;
1322       max_val = ti->_hi;
1323       assert(min_val <= max_val, "invalid int type");
1324     }
1325     while (lo->hi() < min_val) {
1326       lo++;
1327     }
1328     if (lo->lo() < min_val)  {
1329       lo->setRange(min_val, lo->hi(), lo->dest(), lo->cnt());
1330     }
1331     while (hi->lo() > max_val) {
1332       hi--;
1333     }
1334     if (hi->hi() > max_val) {
1335       hi->setRange(hi->lo(), max_val, hi->dest(), hi->cnt());
1336     }
1337 
1338     linear_search_switch_ranges(key_val, lo, hi);
1339   }
1340 
1341 #ifndef PRODUCT
1342   if (switch_depth == 0) {
1343     _max_switch_depth = 0;
1344     _est_switch_depth = log2i_graceful((hi - lo + 1) - 1) + 1;
1345   }
1346 #endif
1347 
1348   assert(lo <= hi, "must be a non-empty set of ranges");
1349   if (lo == hi) {
1350     jump_if_always_fork(lo->dest(), trim_ranges && lo->cnt() == 0);
1351   } else {
1352     assert(lo->hi() == (lo+1)->lo()-1, "contiguous ranges");
1353     assert(hi->lo() == (hi-1)->hi()+1, "contiguous ranges");
1354 
1355     if (create_jump_tables(key_val, lo, hi)) return;
1356 
1357     SwitchRange* mid = nullptr;
1358     float total_cnt = sum_of_cnts(lo, hi);
1359 
1360     int nr = hi - lo + 1;
1361     if (UseSwitchProfiling) {
1362       // Don't keep the binary search tree balanced: pick up mid point
1363       // that split frequencies in half.
1364       float cnt = 0;
1365       for (SwitchRange* sr = lo; sr <= hi; sr++) {
1366         cnt += sr->cnt();
1367         if (cnt >= total_cnt / 2) {
1368           mid = sr;
1369           break;
1370         }
1371       }
1372     } else {
1373       mid = lo + nr/2;
1374 
1375       // if there is an easy choice, pivot at a singleton:
1376       if (nr > 3 && !mid->is_singleton() && (mid-1)->is_singleton())  mid--;
1377 
1378       assert(lo < mid && mid <= hi, "good pivot choice");
1379       assert(nr != 2 || mid == hi,   "should pick higher of 2");
1380       assert(nr != 3 || mid == hi-1, "should pick middle of 3");
1381     }
1382 
1383 
1384     Node *test_val = _gvn.intcon(mid == lo ? mid->hi() : mid->lo());
1385 
1386     if (mid->is_singleton()) {
1387       IfNode *iff_ne = jump_if_fork_int(key_val, test_val, BoolTest::ne, 1-if_prob(mid->cnt(), total_cnt), if_cnt(mid->cnt()));
1388       jump_if_false_fork(iff_ne, mid->dest(), trim_ranges && mid->cnt() == 0);
1389 
1390       // Special Case:  If there are exactly three ranges, and the high
1391       // and low range each go to the same place, omit the "gt" test,
1392       // since it will not discriminate anything.
1393       bool eq_test_only = (hi == lo+2 && hi->dest() == lo->dest() && mid == hi-1) || mid == lo;
1394 
1395       // if there is a higher range, test for it and process it:
1396       if (mid < hi && !eq_test_only) {
1397         // two comparisons of same values--should enable 1 test for 2 branches
1398         // Use BoolTest::lt instead of BoolTest::gt
1399         float cnt = sum_of_cnts(lo, mid-1);
1400         IfNode *iff_lt  = jump_if_fork_int(key_val, test_val, BoolTest::lt, if_prob(cnt, total_cnt), if_cnt(cnt));
1401         Node   *iftrue  = _gvn.transform( new IfTrueNode(iff_lt) );
1402         Node   *iffalse = _gvn.transform( new IfFalseNode(iff_lt) );
1403         { PreserveJVMState pjvms(this);
1404           set_control(iffalse);
1405           jump_switch_ranges(key_val, mid+1, hi, switch_depth+1);
1406         }
1407         set_control(iftrue);
1408       }
1409 
1410     } else {
1411       // mid is a range, not a singleton, so treat mid..hi as a unit
1412       float cnt = sum_of_cnts(mid == lo ? mid+1 : mid, hi);
1413       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));
1414 
1415       // if there is a higher range, test for it and process it:
1416       if (mid == hi) {
1417         jump_if_true_fork(iff_ge, mid->dest(), trim_ranges && cnt == 0);
1418       } else {
1419         Node *iftrue  = _gvn.transform( new IfTrueNode(iff_ge) );
1420         Node *iffalse = _gvn.transform( new IfFalseNode(iff_ge) );
1421         { PreserveJVMState pjvms(this);
1422           set_control(iftrue);
1423           jump_switch_ranges(key_val, mid == lo ? mid+1 : mid, hi, switch_depth+1);
1424         }
1425         set_control(iffalse);
1426       }
1427     }
1428 
1429     // in any case, process the lower range
1430     if (mid == lo) {
1431       if (mid->is_singleton()) {
1432         jump_switch_ranges(key_val, lo+1, hi, switch_depth+1);
1433       } else {
1434         jump_if_always_fork(lo->dest(), trim_ranges && lo->cnt() == 0);
1435       }
1436     } else {
1437       jump_switch_ranges(key_val, lo, mid-1, switch_depth+1);
1438     }
1439   }
1440 
1441   // Decrease pred_count for each successor after all is done.
1442   if (switch_depth == 0) {
1443     int unique_successors = switch_block->num_successors();
1444     for (int i = 0; i < unique_successors; i++) {
1445       Block* target = switch_block->successor_at(i);
1446       // Throw away the pre-allocated path for each unique successor.
1447       target->next_path_num();
1448     }
1449   }
1450 
1451 #ifndef PRODUCT
1452   _max_switch_depth = MAX2(switch_depth, _max_switch_depth);
1453   if (TraceOptoParse && Verbose && WizardMode && switch_depth == 0) {
1454     SwitchRange* r;
1455     int nsing = 0;
1456     for( r = lo; r <= hi; r++ ) {
1457       if( r->is_singleton() )  nsing++;
1458     }
1459     tty->print(">>> ");
1460     _method->print_short_name();
1461     tty->print_cr(" switch decision tree");
1462     tty->print_cr("    %d ranges (%d singletons), max_depth=%d, est_depth=%d",
1463                   (int) (hi-lo+1), nsing, _max_switch_depth, _est_switch_depth);
1464     if (_max_switch_depth > _est_switch_depth) {
1465       tty->print_cr("******** BAD SWITCH DEPTH ********");
1466     }
1467     tty->print("   ");
1468     for( r = lo; r <= hi; r++ ) {
1469       r->print();
1470     }
1471     tty->cr();
1472   }
1473 #endif
1474 }
1475 
1476 void Parse::modf() {
1477   Node *f2 = pop();
1478   Node *f1 = pop();
1479   Node* c = make_runtime_call(RC_LEAF, OptoRuntime::modf_Type(),
1480                               CAST_FROM_FN_PTR(address, SharedRuntime::frem),
1481                               "frem", nullptr, //no memory effects
1482                               f1, f2);
1483   Node* res = _gvn.transform(new ProjNode(c, TypeFunc::Parms + 0));
1484 
1485   push(res);
1486 }
1487 
1488 void Parse::modd() {
1489   Node *d2 = pop_pair();
1490   Node *d1 = pop_pair();
1491   Node* c = make_runtime_call(RC_LEAF, OptoRuntime::Math_DD_D_Type(),
1492                               CAST_FROM_FN_PTR(address, SharedRuntime::drem),
1493                               "drem", nullptr, //no memory effects
1494                               d1, top(), d2, top());
1495   Node* res_d   = _gvn.transform(new ProjNode(c, TypeFunc::Parms + 0));
1496 
1497 #ifdef ASSERT
1498   Node* res_top = _gvn.transform(new ProjNode(c, TypeFunc::Parms + 1));
1499   assert(res_top == top(), "second value must be top");
1500 #endif
1501 
1502   push_pair(res_d);
1503 }
1504 
1505 void Parse::l2f() {
1506   Node* f2 = pop();
1507   Node* f1 = pop();
1508   Node* c = make_runtime_call(RC_LEAF, OptoRuntime::l2f_Type(),
1509                               CAST_FROM_FN_PTR(address, SharedRuntime::l2f),
1510                               "l2f", nullptr, //no memory effects
1511                               f1, f2);
1512   Node* res = _gvn.transform(new ProjNode(c, TypeFunc::Parms + 0));
1513 
1514   push(res);
1515 }
1516 
1517 // Handle jsr and jsr_w bytecode
1518 void Parse::do_jsr() {
1519   assert(bc() == Bytecodes::_jsr || bc() == Bytecodes::_jsr_w, "wrong bytecode");
1520 
1521   // Store information about current state, tagged with new _jsr_bci
1522   int return_bci = iter().next_bci();
1523   int jsr_bci    = (bc() == Bytecodes::_jsr) ? iter().get_dest() : iter().get_far_dest();
1524 
1525   // The way we do things now, there is only one successor block
1526   // for the jsr, because the target code is cloned by ciTypeFlow.
1527   Block* target = successor_for_bci(jsr_bci);
1528 
1529   // What got pushed?
1530   const Type* ret_addr = target->peek();
1531   assert(ret_addr->singleton(), "must be a constant (cloned jsr body)");
1532 
1533   // Effect on jsr on stack
1534   push(_gvn.makecon(ret_addr));
1535 
1536   // Flow to the jsr.
1537   merge(jsr_bci);
1538 }
1539 
1540 // Handle ret bytecode
1541 void Parse::do_ret() {
1542   // Find to whom we return.
1543   assert(block()->num_successors() == 1, "a ret can only go one place now");
1544   Block* target = block()->successor_at(0);
1545   assert(!target->is_ready(), "our arrival must be expected");
1546   int pnum = target->next_path_num();
1547   merge_common(target, pnum);
1548 }
1549 
1550 static bool has_injected_profile(BoolTest::mask btest, Node* test, int& taken, int& not_taken) {
1551   if (btest != BoolTest::eq && btest != BoolTest::ne) {
1552     // Only ::eq and ::ne are supported for profile injection.
1553     return false;
1554   }
1555   if (test->is_Cmp() &&
1556       test->in(1)->Opcode() == Op_ProfileBoolean) {
1557     ProfileBooleanNode* profile = (ProfileBooleanNode*)test->in(1);
1558     int false_cnt = profile->false_count();
1559     int  true_cnt = profile->true_count();
1560 
1561     // Counts matching depends on the actual test operation (::eq or ::ne).
1562     // No need to scale the counts because profile injection was designed
1563     // to feed exact counts into VM.
1564     taken     = (btest == BoolTest::eq) ? false_cnt :  true_cnt;
1565     not_taken = (btest == BoolTest::eq) ?  true_cnt : false_cnt;
1566 
1567     profile->consume();
1568     return true;
1569   }
1570   return false;
1571 }
1572 
1573 // Give up if too few (or too many, in which case the sum will overflow) counts to be meaningful.
1574 // We also check that individual counters are positive first, otherwise the sum can become positive.
1575 // (check for saturation, integer overflow, and immature counts)
1576 static bool counters_are_meaningful(int counter1, int counter2, int min) {
1577   // check for saturation, including "uint" values too big to fit in "int"
1578   if (counter1 < 0 || counter2 < 0) {
1579     return false;
1580   }
1581   // check for integer overflow of the sum
1582   int64_t sum = (int64_t)counter1 + (int64_t)counter2;
1583   STATIC_ASSERT(sizeof(counter1) < sizeof(sum));
1584   if (sum > INT_MAX) {
1585     return false;
1586   }
1587   // check if mature
1588   return (counter1 + counter2) >= min;
1589 }
1590 
1591 //--------------------------dynamic_branch_prediction--------------------------
1592 // Try to gather dynamic branch prediction behavior.  Return a probability
1593 // of the branch being taken and set the "cnt" field.  Returns a -1.0
1594 // if we need to use static prediction for some reason.
1595 float Parse::dynamic_branch_prediction(float &cnt, BoolTest::mask btest, Node* test) {
1596   ResourceMark rm;
1597 
1598   cnt  = COUNT_UNKNOWN;
1599 
1600   int     taken = 0;
1601   int not_taken = 0;
1602 
1603   bool use_mdo = !has_injected_profile(btest, test, taken, not_taken);
1604 
1605   if (use_mdo) {
1606     // Use MethodData information if it is available
1607     // FIXME: free the ProfileData structure
1608     ciMethodData* methodData = method()->method_data();
1609     if (!methodData->is_mature())  return PROB_UNKNOWN;
1610     ciProfileData* data = methodData->bci_to_data(bci());
1611     if (data == nullptr) {
1612       return PROB_UNKNOWN;
1613     }
1614     if (!data->is_JumpData())  return PROB_UNKNOWN;
1615 
1616     // get taken and not taken values
1617     // NOTE: saturated UINT_MAX values become negative,
1618     // as do counts above INT_MAX.
1619     taken = data->as_JumpData()->taken();
1620     not_taken = 0;
1621     if (data->is_BranchData()) {
1622       not_taken = data->as_BranchData()->not_taken();
1623     }
1624 
1625     // scale the counts to be commensurate with invocation counts:
1626     // NOTE: overflow for positive values is clamped at INT_MAX
1627     taken = method()->scale_count(taken);
1628     not_taken = method()->scale_count(not_taken);
1629   }
1630   // At this point, saturation or overflow is indicated by INT_MAX
1631   // or a negative value.
1632 
1633   // Give up if too few (or too many, in which case the sum will overflow) counts to be meaningful.
1634   // We also check that individual counters are positive first, otherwise the sum can become positive.
1635   if (!counters_are_meaningful(taken, not_taken, 40)) {
1636     if (C->log() != nullptr) {
1637       C->log()->elem("branch target_bci='%d' taken='%d' not_taken='%d'", iter().get_dest(), taken, not_taken);
1638     }
1639     return PROB_UNKNOWN;
1640   }
1641 
1642   // Compute frequency that we arrive here
1643   float sum = taken + not_taken;
1644   // Adjust, if this block is a cloned private block but the
1645   // Jump counts are shared.  Taken the private counts for
1646   // just this path instead of the shared counts.
1647   if( block()->count() > 0 )
1648     sum = block()->count();
1649   cnt = sum / FreqCountInvocations;
1650 
1651   // Pin probability to sane limits
1652   float prob;
1653   if( !taken )
1654     prob = (0+PROB_MIN) / 2;
1655   else if( !not_taken )
1656     prob = (1+PROB_MAX) / 2;
1657   else {                         // Compute probability of true path
1658     prob = (float)taken / (float)(taken + not_taken);
1659     if (prob > PROB_MAX)  prob = PROB_MAX;
1660     if (prob < PROB_MIN)   prob = PROB_MIN;
1661   }
1662 
1663   assert((cnt > 0.0f) && (prob > 0.0f),
1664          "Bad frequency assignment in if cnt=%g prob=%g taken=%d not_taken=%d", cnt, prob, taken, not_taken);
1665 
1666   if (C->log() != nullptr) {
1667     const char* prob_str = nullptr;
1668     if (prob >= PROB_MAX)  prob_str = (prob == PROB_MAX) ? "max" : "always";
1669     if (prob <= PROB_MIN)  prob_str = (prob == PROB_MIN) ? "min" : "never";
1670     char prob_str_buf[30];
1671     if (prob_str == nullptr) {
1672       jio_snprintf(prob_str_buf, sizeof(prob_str_buf), "%20.2f", prob);
1673       prob_str = prob_str_buf;
1674     }
1675     C->log()->elem("branch target_bci='%d' taken='%d' not_taken='%d' cnt='%f' prob='%s'",
1676                    iter().get_dest(), taken, not_taken, cnt, prob_str);
1677   }
1678   return prob;
1679 }
1680 
1681 //-----------------------------branch_prediction-------------------------------
1682 float Parse::branch_prediction(float& cnt,
1683                                BoolTest::mask btest,
1684                                int target_bci,
1685                                Node* test) {
1686   float prob = dynamic_branch_prediction(cnt, btest, test);
1687   // If prob is unknown, switch to static prediction
1688   if (prob != PROB_UNKNOWN)  return prob;
1689 
1690   prob = PROB_FAIR;                   // Set default value
1691   if (btest == BoolTest::eq)          // Exactly equal test?
1692     prob = PROB_STATIC_INFREQUENT;    // Assume its relatively infrequent
1693   else if (btest == BoolTest::ne)
1694     prob = PROB_STATIC_FREQUENT;      // Assume its relatively frequent
1695 
1696   // If this is a conditional test guarding a backwards branch,
1697   // assume its a loop-back edge.  Make it a likely taken branch.
1698   if (target_bci < bci()) {
1699     if (is_osr_parse()) {    // Could be a hot OSR'd loop; force deopt
1700       // Since it's an OSR, we probably have profile data, but since
1701       // branch_prediction returned PROB_UNKNOWN, the counts are too small.
1702       // Let's make a special check here for completely zero counts.
1703       ciMethodData* methodData = method()->method_data();
1704       if (!methodData->is_empty()) {
1705         ciProfileData* data = methodData->bci_to_data(bci());
1706         // Only stop for truly zero counts, which mean an unknown part
1707         // of the OSR-ed method, and we want to deopt to gather more stats.
1708         // If you have ANY counts, then this loop is simply 'cold' relative
1709         // to the OSR loop.
1710         if (data == nullptr ||
1711             (data->as_BranchData()->taken() +  data->as_BranchData()->not_taken() == 0)) {
1712           // This is the only way to return PROB_UNKNOWN:
1713           return PROB_UNKNOWN;
1714         }
1715       }
1716     }
1717     prob = PROB_STATIC_FREQUENT;     // Likely to take backwards branch
1718   }
1719 
1720   assert(prob != PROB_UNKNOWN, "must have some guess at this point");
1721   return prob;
1722 }
1723 
1724 // The magic constants are chosen so as to match the output of
1725 // branch_prediction() when the profile reports a zero taken count.
1726 // It is important to distinguish zero counts unambiguously, because
1727 // some branches (e.g., _213_javac.Assembler.eliminate) validly produce
1728 // very small but nonzero probabilities, which if confused with zero
1729 // counts would keep the program recompiling indefinitely.
1730 bool Parse::seems_never_taken(float prob) const {
1731   return prob < PROB_MIN;
1732 }
1733 
1734 //-------------------------------repush_if_args--------------------------------
1735 // Push arguments of an "if" bytecode back onto the stack by adjusting _sp.
1736 inline int Parse::repush_if_args() {
1737   if (PrintOpto && WizardMode) {
1738     tty->print("defending against excessive implicit null exceptions on %s @%d in ",
1739                Bytecodes::name(iter().cur_bc()), iter().cur_bci());
1740     method()->print_name(); tty->cr();
1741   }
1742   int bc_depth = - Bytecodes::depth(iter().cur_bc());
1743   assert(bc_depth == 1 || bc_depth == 2, "only two kinds of branches");
1744   DEBUG_ONLY(sync_jvms());   // argument(n) requires a synced jvms
1745   assert(argument(0) != nullptr, "must exist");
1746   assert(bc_depth == 1 || argument(1) != nullptr, "two must exist");
1747   inc_sp(bc_depth);
1748   return bc_depth;
1749 }
1750 
1751 //----------------------------------do_ifnull----------------------------------
1752 void Parse::do_ifnull(BoolTest::mask btest, Node *c) {
1753   int target_bci = iter().get_dest();
1754 
1755   Block* branch_block = successor_for_bci(target_bci);
1756   Block* next_block   = successor_for_bci(iter().next_bci());
1757 
1758   float cnt;
1759   float prob = branch_prediction(cnt, btest, target_bci, c);
1760   if (prob == PROB_UNKNOWN) {
1761     // (An earlier version of do_ifnull omitted this trap for OSR methods.)
1762     if (PrintOpto && Verbose) {
1763       tty->print_cr("Never-taken edge stops compilation at bci %d", bci());
1764     }
1765     repush_if_args(); // to gather stats on loop
1766     uncommon_trap(Deoptimization::Reason_unreached,
1767                   Deoptimization::Action_reinterpret,
1768                   nullptr, "cold");
1769     if (C->eliminate_boxing()) {
1770       // Mark the successor blocks as parsed
1771       branch_block->next_path_num();
1772       next_block->next_path_num();
1773     }
1774     return;
1775   }
1776 
1777   NOT_PRODUCT(explicit_null_checks_inserted++);
1778 
1779   // Generate real control flow
1780   Node   *tst = _gvn.transform( new BoolNode( c, btest ) );
1781 
1782   // Sanity check the probability value
1783   assert(prob > 0.0f,"Bad probability in Parser");
1784  // Need xform to put node in hash table
1785   IfNode *iff = create_and_xform_if( control(), tst, prob, cnt );
1786   assert(iff->_prob > 0.0f,"Optimizer made bad probability in parser");
1787   // True branch
1788   { PreserveJVMState pjvms(this);
1789     Node* iftrue  = _gvn.transform( new IfTrueNode (iff) );
1790     set_control(iftrue);
1791 
1792     if (stopped()) {            // Path is dead?
1793       NOT_PRODUCT(explicit_null_checks_elided++);
1794       if (C->eliminate_boxing()) {
1795         // Mark the successor block as parsed
1796         branch_block->next_path_num();
1797       }
1798     } else {                    // Path is live.
1799       adjust_map_after_if(btest, c, prob, branch_block);
1800       if (!stopped()) {
1801         merge(target_bci);
1802       }
1803     }
1804   }
1805 
1806   // False branch
1807   Node* iffalse = _gvn.transform( new IfFalseNode(iff) );
1808   set_control(iffalse);
1809 
1810   if (stopped()) {              // Path is dead?
1811     NOT_PRODUCT(explicit_null_checks_elided++);
1812     if (C->eliminate_boxing()) {
1813       // Mark the successor block as parsed
1814       next_block->next_path_num();
1815     }
1816   } else  {                     // Path is live.
1817     adjust_map_after_if(BoolTest(btest).negate(), c, 1.0-prob, next_block);
1818   }
1819 }
1820 
1821 //------------------------------------do_if------------------------------------
1822 void Parse::do_if(BoolTest::mask btest, Node* c, bool can_trap, bool new_path, Node** ctrl_taken) {
1823   int target_bci = iter().get_dest();
1824 
1825   Block* branch_block = successor_for_bci(target_bci);
1826   Block* next_block   = successor_for_bci(iter().next_bci());
1827 
1828   float cnt;
1829   float prob = branch_prediction(cnt, btest, target_bci, c);
1830   float untaken_prob = 1.0 - prob;
1831 
1832   if (prob == PROB_UNKNOWN) {
1833     if (PrintOpto && Verbose) {
1834       tty->print_cr("Never-taken edge stops compilation at bci %d", bci());
1835     }
1836     repush_if_args(); // to gather stats on loop
1837     uncommon_trap(Deoptimization::Reason_unreached,
1838                   Deoptimization::Action_reinterpret,
1839                   nullptr, "cold");
1840     if (C->eliminate_boxing()) {
1841       // Mark the successor blocks as parsed
1842       branch_block->next_path_num();
1843       next_block->next_path_num();
1844     }
1845     return;
1846   }
1847 
1848   // Sanity check the probability value
1849   assert(0.0f < prob && prob < 1.0f,"Bad probability in Parser");
1850 
1851   bool taken_if_true = true;
1852   // Convert BoolTest to canonical form:
1853   if (!BoolTest(btest).is_canonical()) {
1854     btest         = BoolTest(btest).negate();
1855     taken_if_true = false;
1856     // prob is NOT updated here; it remains the probability of the taken
1857     // path (as opposed to the prob of the path guarded by an 'IfTrueNode').
1858   }
1859   assert(btest != BoolTest::eq, "!= is the only canonical exact test");
1860 
1861   Node* tst0 = new BoolNode(c, btest);
1862   Node* tst = _gvn.transform(tst0);
1863   BoolTest::mask taken_btest   = BoolTest::illegal;
1864   BoolTest::mask untaken_btest = BoolTest::illegal;
1865 
1866   if (tst->is_Bool()) {
1867     // Refresh c from the transformed bool node, since it may be
1868     // simpler than the original c.  Also re-canonicalize btest.
1869     // This wins when (Bool ne (Conv2B p) 0) => (Bool ne (CmpP p null)).
1870     // That can arise from statements like: if (x instanceof C) ...
1871     if (tst != tst0) {
1872       // Canonicalize one more time since transform can change it.
1873       btest = tst->as_Bool()->_test._test;
1874       if (!BoolTest(btest).is_canonical()) {
1875         // Reverse edges one more time...
1876         tst   = _gvn.transform( tst->as_Bool()->negate(&_gvn) );
1877         btest = tst->as_Bool()->_test._test;
1878         assert(BoolTest(btest).is_canonical(), "sanity");
1879         taken_if_true = !taken_if_true;
1880       }
1881       c = tst->in(1);
1882     }
1883     BoolTest::mask neg_btest = BoolTest(btest).negate();
1884     taken_btest   = taken_if_true ?     btest : neg_btest;
1885     untaken_btest = taken_if_true ? neg_btest :     btest;
1886   }
1887 
1888   // Generate real control flow
1889   float true_prob = (taken_if_true ? prob : untaken_prob);
1890   IfNode* iff = create_and_map_if(control(), tst, true_prob, cnt);
1891   assert(iff->_prob > 0.0f,"Optimizer made bad probability in parser");
1892   Node* taken_branch   = new IfTrueNode(iff);
1893   Node* untaken_branch = new IfFalseNode(iff);
1894   if (!taken_if_true) {  // Finish conversion to canonical form
1895     Node* tmp      = taken_branch;
1896     taken_branch   = untaken_branch;
1897     untaken_branch = tmp;
1898   }
1899 
1900   // Branch is taken:
1901   { PreserveJVMState pjvms(this);
1902     taken_branch = _gvn.transform(taken_branch);
1903     set_control(taken_branch);
1904 
1905     if (stopped()) {
1906       if (C->eliminate_boxing() && !new_path) {
1907         // Mark the successor block as parsed (if we haven't created a new path)
1908         branch_block->next_path_num();
1909       }
1910     } else {
1911       adjust_map_after_if(taken_btest, c, prob, branch_block, can_trap);
1912       if (!stopped()) {
1913         if (new_path) {
1914           // Merge by using a new path
1915           merge_new_path(target_bci);
1916         } else if (ctrl_taken != nullptr) {
1917           // Don't merge but save taken branch to be wired by caller
1918           *ctrl_taken = control();
1919         } else {
1920           merge(target_bci);
1921         }
1922       }
1923     }
1924   }
1925 
1926   untaken_branch = _gvn.transform(untaken_branch);
1927   set_control(untaken_branch);
1928 
1929   // Branch not taken.
1930   if (stopped() && ctrl_taken == nullptr) {
1931     if (C->eliminate_boxing()) {
1932       // Mark the successor block as parsed (if caller does not re-wire control flow)
1933       next_block->next_path_num();
1934     }
1935   } else {
1936     adjust_map_after_if(untaken_btest, c, untaken_prob, next_block, can_trap);
1937   }
1938 }
1939 
1940 
1941 static ProfilePtrKind speculative_ptr_kind(const TypeOopPtr* t) {
1942   if (t->speculative() == nullptr) {
1943     return ProfileUnknownNull;
1944   }
1945   if (t->speculative_always_null()) {
1946     return ProfileAlwaysNull;
1947   }
1948   if (t->speculative_maybe_null()) {
1949     return ProfileMaybeNull;
1950   }
1951   return ProfileNeverNull;
1952 }
1953 
1954 void Parse::acmp_always_null_input(Node* input, const TypeOopPtr* tinput, BoolTest::mask btest, Node* eq_region) {
1955   inc_sp(2);
1956   Node* cast = null_check_common(input, T_OBJECT, true, nullptr,
1957                                  !too_many_traps_or_recompiles(Deoptimization::Reason_speculate_null_check) &&
1958                                  speculative_ptr_kind(tinput) == ProfileAlwaysNull);
1959   dec_sp(2);
1960   if (btest == BoolTest::ne) {
1961     {
1962       PreserveJVMState pjvms(this);
1963       replace_in_map(input, cast);
1964       int target_bci = iter().get_dest();
1965       merge(target_bci);
1966     }
1967     record_for_igvn(eq_region);
1968     set_control(_gvn.transform(eq_region));
1969   } else {
1970     replace_in_map(input, cast);
1971   }
1972 }
1973 
1974 Node* Parse::acmp_null_check(Node* input, const TypeOopPtr* tinput, ProfilePtrKind input_ptr, Node*& null_ctl) {
1975   inc_sp(2);
1976   null_ctl = top();
1977   Node* cast = null_check_oop(input, &null_ctl,
1978                               input_ptr == ProfileNeverNull || (input_ptr == ProfileUnknownNull && !too_many_traps_or_recompiles(Deoptimization::Reason_null_check)),
1979                               false,
1980                               speculative_ptr_kind(tinput) == ProfileNeverNull &&
1981                               !too_many_traps_or_recompiles(Deoptimization::Reason_speculate_null_check));
1982   dec_sp(2);
1983   assert(!stopped(), "null input should have been caught earlier");
1984   return cast;
1985 }
1986 
1987 void Parse::acmp_known_non_inline_type_input(Node* input, const TypeOopPtr* tinput, ProfilePtrKind input_ptr, ciKlass* input_type, BoolTest::mask btest, Node* eq_region) {
1988   Node* ne_region = new RegionNode(1);
1989   Node* null_ctl;
1990   Node* cast = acmp_null_check(input, tinput, input_ptr, null_ctl);
1991   ne_region->add_req(null_ctl);
1992 
1993   Node* slow_ctl = type_check_receiver(cast, input_type, 1.0, &cast);
1994   {
1995     PreserveJVMState pjvms(this);
1996     inc_sp(2);
1997     set_control(slow_ctl);
1998     Deoptimization::DeoptReason reason;
1999     if (tinput->speculative_type() != nullptr && !too_many_traps_or_recompiles(Deoptimization::Reason_speculate_class_check)) {
2000       reason = Deoptimization::Reason_speculate_class_check;
2001     } else {
2002       reason = Deoptimization::Reason_class_check;
2003     }
2004     uncommon_trap_exact(reason, Deoptimization::Action_maybe_recompile);
2005   }
2006   ne_region->add_req(control());
2007 
2008   record_for_igvn(ne_region);
2009   set_control(_gvn.transform(ne_region));
2010   if (btest == BoolTest::ne) {
2011     {
2012       PreserveJVMState pjvms(this);
2013       if (null_ctl == top()) {
2014         replace_in_map(input, cast);
2015       }
2016       int target_bci = iter().get_dest();
2017       merge(target_bci);
2018     }
2019     record_for_igvn(eq_region);
2020     set_control(_gvn.transform(eq_region));
2021   } else {
2022     if (null_ctl == top()) {
2023       replace_in_map(input, cast);
2024     }
2025     set_control(_gvn.transform(ne_region));
2026   }
2027 }
2028 
2029 void Parse::acmp_unknown_non_inline_type_input(Node* input, const TypeOopPtr* tinput, ProfilePtrKind input_ptr, BoolTest::mask btest, Node* eq_region) {
2030   Node* ne_region = new RegionNode(1);
2031   Node* null_ctl;
2032   Node* cast = acmp_null_check(input, tinput, input_ptr, null_ctl);
2033   ne_region->add_req(null_ctl);
2034 
2035   {
2036     BuildCutout unless(this, inline_type_test(cast, /* is_inline = */ false), PROB_MAX);
2037     inc_sp(2);
2038     uncommon_trap_exact(Deoptimization::Reason_class_check, Deoptimization::Action_maybe_recompile);
2039   }
2040 
2041   ne_region->add_req(control());
2042 
2043   record_for_igvn(ne_region);
2044   set_control(_gvn.transform(ne_region));
2045   if (btest == BoolTest::ne) {
2046     {
2047       PreserveJVMState pjvms(this);
2048       if (null_ctl == top()) {
2049         replace_in_map(input, cast);
2050       }
2051       int target_bci = iter().get_dest();
2052       merge(target_bci);
2053     }
2054     record_for_igvn(eq_region);
2055     set_control(_gvn.transform(eq_region));
2056   } else {
2057     if (null_ctl == top()) {
2058       replace_in_map(input, cast);
2059     }
2060     set_control(_gvn.transform(ne_region));
2061   }
2062 }
2063 
2064 void Parse::do_acmp(BoolTest::mask btest, Node* left, Node* right) {
2065   ciKlass* left_type = nullptr;
2066   ciKlass* right_type = nullptr;
2067   ProfilePtrKind left_ptr = ProfileUnknownNull;
2068   ProfilePtrKind right_ptr = ProfileUnknownNull;
2069   bool left_inline_type = true;
2070   bool right_inline_type = true;
2071 
2072   // Leverage profiling at acmp
2073   if (UseACmpProfile) {
2074     method()->acmp_profiled_type(bci(), left_type, right_type, left_ptr, right_ptr, left_inline_type, right_inline_type);
2075     if (too_many_traps_or_recompiles(Deoptimization::Reason_class_check)) {
2076       left_type = nullptr;
2077       right_type = nullptr;
2078       left_inline_type = true;
2079       right_inline_type = true;
2080     }
2081     if (too_many_traps_or_recompiles(Deoptimization::Reason_null_check)) {
2082       left_ptr = ProfileUnknownNull;
2083       right_ptr = ProfileUnknownNull;
2084     }
2085   }
2086 
2087   if (UseTypeSpeculation) {
2088     record_profile_for_speculation(left, left_type, left_ptr);
2089     record_profile_for_speculation(right, right_type, right_ptr);
2090   }
2091 
2092   if (!EnableValhalla) {
2093     Node* cmp = CmpP(left, right);
2094     cmp = optimize_cmp_with_klass(cmp);
2095     do_if(btest, cmp);
2096     return;
2097   }
2098 
2099   // Check for equality before potentially allocating
2100   if (left == right) {
2101     do_if(btest, makecon(TypeInt::CC_EQ));
2102     return;
2103   }
2104 
2105   // Allocate inline type operands and re-execute on deoptimization
2106   if (left->is_InlineType()) {
2107     if (_gvn.type(right)->is_zero_type() ||
2108         (right->is_InlineType() && _gvn.type(right->as_InlineType()->get_is_init())->is_zero_type())) {
2109       // Null checking a scalarized but nullable inline type. Check the IsInit
2110       // input instead of the oop input to avoid keeping buffer allocations alive.
2111       Node* cmp = CmpI(left->as_InlineType()->get_is_init(), intcon(0));
2112       do_if(btest, cmp);
2113       return;
2114     } else {
2115       PreserveReexecuteState preexecs(this);
2116       inc_sp(2);
2117       jvms()->set_should_reexecute(true);
2118       left = left->as_InlineType()->buffer(this)->get_oop();
2119     }
2120   }
2121   if (right->is_InlineType()) {
2122     PreserveReexecuteState preexecs(this);
2123     inc_sp(2);
2124     jvms()->set_should_reexecute(true);
2125     right = right->as_InlineType()->buffer(this)->get_oop();
2126   }
2127 
2128   // First, do a normal pointer comparison
2129   const TypeOopPtr* tleft = _gvn.type(left)->isa_oopptr();
2130   const TypeOopPtr* tright = _gvn.type(right)->isa_oopptr();
2131   Node* cmp = CmpP(left, right);
2132   cmp = optimize_cmp_with_klass(cmp);
2133   if (tleft == nullptr || !tleft->can_be_inline_type() ||
2134       tright == nullptr || !tright->can_be_inline_type()) {
2135     // This is sufficient, if one of the operands can't be an inline type
2136     do_if(btest, cmp);
2137     return;
2138   }
2139 
2140   // Don't add traps to unstable if branches because additional checks are required to
2141   // decide if the operands are equal/substitutable and we therefore shouldn't prune
2142   // branches for one if based on the profiling of the acmp branches.
2143   // Also, OptimizeUnstableIf would set an incorrect re-rexecution state because it
2144   // assumes that there is a 1-1 mapping between the if and the acmp branches and that
2145   // hitting a trap means that we will take the corresponding acmp branch on re-execution.
2146   const bool can_trap = true;
2147 
2148   Node* eq_region = nullptr;
2149   if (btest == BoolTest::eq) {
2150     do_if(btest, cmp, !can_trap, true);
2151     if (stopped()) {
2152       // Pointers are equal, operands must be equal
2153       return;
2154     }
2155   } else {
2156     assert(btest == BoolTest::ne, "only eq or ne");
2157     Node* is_not_equal = nullptr;
2158     eq_region = new RegionNode(3);
2159     {
2160       PreserveJVMState pjvms(this);
2161       // Pointers are not equal, but more checks are needed to determine if the operands are (not) substitutable
2162       do_if(btest, cmp, !can_trap, false, &is_not_equal);
2163       if (!stopped()) {
2164         eq_region->init_req(1, control());
2165       }
2166     }
2167     if (is_not_equal == nullptr || is_not_equal->is_top()) {
2168       record_for_igvn(eq_region);
2169       set_control(_gvn.transform(eq_region));
2170       return;
2171     }
2172     set_control(is_not_equal);
2173   }
2174 
2175   // Prefer speculative types if available
2176   if (!too_many_traps_or_recompiles(Deoptimization::Reason_speculate_class_check)) {
2177     if (tleft->speculative_type() != nullptr) {
2178       left_type = tleft->speculative_type();
2179     }
2180     if (tright->speculative_type() != nullptr) {
2181       right_type = tright->speculative_type();
2182     }
2183   }
2184 
2185   if (speculative_ptr_kind(tleft) != ProfileMaybeNull && speculative_ptr_kind(tleft) != ProfileUnknownNull) {
2186     ProfilePtrKind speculative_left_ptr = speculative_ptr_kind(tleft);
2187     if (speculative_left_ptr == ProfileAlwaysNull && !too_many_traps_or_recompiles(Deoptimization::Reason_speculate_null_assert)) {
2188       left_ptr = speculative_left_ptr;
2189     } else if (speculative_left_ptr == ProfileNeverNull && !too_many_traps_or_recompiles(Deoptimization::Reason_speculate_null_check)) {
2190       left_ptr = speculative_left_ptr;
2191     }
2192   }
2193   if (speculative_ptr_kind(tright) != ProfileMaybeNull && speculative_ptr_kind(tright) != ProfileUnknownNull) {
2194     ProfilePtrKind speculative_right_ptr = speculative_ptr_kind(tright);
2195     if (speculative_right_ptr == ProfileAlwaysNull && !too_many_traps_or_recompiles(Deoptimization::Reason_speculate_null_assert)) {
2196       right_ptr = speculative_right_ptr;
2197     } else if (speculative_right_ptr == ProfileNeverNull && !too_many_traps_or_recompiles(Deoptimization::Reason_speculate_null_check)) {
2198       right_ptr = speculative_right_ptr;
2199     }
2200   }
2201 
2202   if (left_ptr == ProfileAlwaysNull) {
2203     // Comparison with null. Assert the input is indeed null and we're done.
2204     acmp_always_null_input(left, tleft, btest, eq_region);
2205     return;
2206   }
2207   if (right_ptr == ProfileAlwaysNull) {
2208     // Comparison with null. Assert the input is indeed null and we're done.
2209     acmp_always_null_input(right, tright, btest, eq_region);
2210     return;
2211   }
2212   if (left_type != nullptr && !left_type->is_inlinetype()) {
2213     // Comparison with an object of known type
2214     acmp_known_non_inline_type_input(left, tleft, left_ptr, left_type, btest, eq_region);
2215     return;
2216   }
2217   if (right_type != nullptr && !right_type->is_inlinetype()) {
2218     // Comparison with an object of known type
2219     acmp_known_non_inline_type_input(right, tright, right_ptr, right_type, btest, eq_region);
2220     return;
2221   }
2222   if (!left_inline_type) {
2223     // Comparison with an object known not to be an inline type
2224     acmp_unknown_non_inline_type_input(left, tleft, left_ptr, btest, eq_region);
2225     return;
2226   }
2227   if (!right_inline_type) {
2228     // Comparison with an object known not to be an inline type
2229     acmp_unknown_non_inline_type_input(right, tright, right_ptr, btest, eq_region);
2230     return;
2231   }
2232 
2233   // Pointers are not equal, check if first operand is non-null
2234   Node* ne_region = new RegionNode(6);
2235   Node* null_ctl;
2236   Node* not_null_right = acmp_null_check(right, tright, right_ptr, null_ctl);
2237   ne_region->init_req(1, null_ctl);
2238 
2239   // First operand is non-null, check if it is an inline type
2240   Node* is_value = inline_type_test(not_null_right);
2241   IfNode* is_value_iff = create_and_map_if(control(), is_value, PROB_FAIR, COUNT_UNKNOWN);
2242   Node* not_value = _gvn.transform(new IfFalseNode(is_value_iff));
2243   ne_region->init_req(2, not_value);
2244   set_control(_gvn.transform(new IfTrueNode(is_value_iff)));
2245 
2246   // The first operand is an inline type, check if the second operand is non-null
2247   Node* not_null_left = acmp_null_check(left, tleft, left_ptr, null_ctl);
2248   ne_region->init_req(3, null_ctl);
2249 
2250   // Check if both operands are of the same class.
2251   Node* kls_left = load_object_klass(not_null_left);
2252   Node* kls_right = load_object_klass(not_null_right);
2253   Node* kls_cmp = CmpP(kls_left, kls_right);
2254   Node* kls_bol = _gvn.transform(new BoolNode(kls_cmp, BoolTest::ne));
2255   IfNode* kls_iff = create_and_map_if(control(), kls_bol, PROB_FAIR, COUNT_UNKNOWN);
2256   Node* kls_ne = _gvn.transform(new IfTrueNode(kls_iff));
2257   set_control(_gvn.transform(new IfFalseNode(kls_iff)));
2258   ne_region->init_req(4, kls_ne);
2259 
2260   if (stopped()) {
2261     record_for_igvn(ne_region);
2262     set_control(_gvn.transform(ne_region));
2263     if (btest == BoolTest::ne) {
2264       {
2265         PreserveJVMState pjvms(this);
2266         int target_bci = iter().get_dest();
2267         merge(target_bci);
2268       }
2269       record_for_igvn(eq_region);
2270       set_control(_gvn.transform(eq_region));
2271     }
2272     return;
2273   }
2274 
2275   // Both operands are values types of the same class, we need to perform a
2276   // substitutability test. Delegate to ValueObjectMethods::isSubstitutable().
2277   Node* ne_io_phi = PhiNode::make(ne_region, i_o());
2278   Node* mem = reset_memory();
2279   Node* ne_mem_phi = PhiNode::make(ne_region, mem);
2280 
2281   Node* eq_io_phi = nullptr;
2282   Node* eq_mem_phi = nullptr;
2283   if (eq_region != nullptr) {
2284     eq_io_phi = PhiNode::make(eq_region, i_o());
2285     eq_mem_phi = PhiNode::make(eq_region, mem);
2286   }
2287 
2288   set_all_memory(mem);
2289 
2290   kill_dead_locals();
2291   ciMethod* subst_method = ciEnv::current()->ValueObjectMethods_klass()->find_method(ciSymbols::isSubstitutable_name(), ciSymbols::object_object_boolean_signature());
2292   CallStaticJavaNode *call = new CallStaticJavaNode(C, TypeFunc::make(subst_method), SharedRuntime::get_resolve_static_call_stub(), subst_method);
2293   call->set_override_symbolic_info(true);
2294   call->init_req(TypeFunc::Parms, not_null_left);
2295   call->init_req(TypeFunc::Parms+1, not_null_right);
2296   inc_sp(2);
2297   set_edges_for_java_call(call, false, false);
2298   Node* ret = set_results_for_java_call(call, false, true);
2299   dec_sp(2);
2300 
2301   // Test the return value of ValueObjectMethods::isSubstitutable()
2302   // This is the last check, do_if can emit traps now.
2303   Node* subst_cmp = _gvn.transform(new CmpINode(ret, intcon(1)));
2304   Node* ctl = C->top();
2305   if (btest == BoolTest::eq) {
2306     PreserveJVMState pjvms(this);
2307     do_if(btest, subst_cmp, can_trap);
2308     if (!stopped()) {
2309       ctl = control();
2310     }
2311   } else {
2312     assert(btest == BoolTest::ne, "only eq or ne");
2313     PreserveJVMState pjvms(this);
2314     do_if(btest, subst_cmp, can_trap, false, &ctl);
2315     if (!stopped()) {
2316       eq_region->init_req(2, control());
2317       eq_io_phi->init_req(2, i_o());
2318       eq_mem_phi->init_req(2, reset_memory());
2319     }
2320   }
2321   ne_region->init_req(5, ctl);
2322   ne_io_phi->init_req(5, i_o());
2323   ne_mem_phi->init_req(5, reset_memory());
2324 
2325   record_for_igvn(ne_region);
2326   set_control(_gvn.transform(ne_region));
2327   set_i_o(_gvn.transform(ne_io_phi));
2328   set_all_memory(_gvn.transform(ne_mem_phi));
2329 
2330   if (btest == BoolTest::ne) {
2331     {
2332       PreserveJVMState pjvms(this);
2333       int target_bci = iter().get_dest();
2334       merge(target_bci);
2335     }
2336 
2337     record_for_igvn(eq_region);
2338     set_control(_gvn.transform(eq_region));
2339     set_i_o(_gvn.transform(eq_io_phi));
2340     set_all_memory(_gvn.transform(eq_mem_phi));
2341   }
2342 }
2343 
2344 bool Parse::path_is_suitable_for_uncommon_trap(float prob) const {
2345   // Don't want to speculate on uncommon traps when running with -Xcomp
2346   if (!UseInterpreter) {
2347     return false;
2348   }
2349   return seems_never_taken(prob) &&
2350          !C->too_many_traps(method(), bci(), Deoptimization::Reason_unstable_if);
2351 }
2352 
2353 void Parse::maybe_add_predicate_after_if(Block* path) {
2354   if (path->is_SEL_head() && path->preds_parsed() == 0) {
2355     // Add predicates at bci of if dominating the loop so traps can be
2356     // recorded on the if's profile data
2357     int bc_depth = repush_if_args();
2358     add_parse_predicates();
2359     dec_sp(bc_depth);
2360     path->set_has_predicates();
2361   }
2362 }
2363 
2364 
2365 //----------------------------adjust_map_after_if------------------------------
2366 // Adjust the JVM state to reflect the result of taking this path.
2367 // Basically, it means inspecting the CmpNode controlling this
2368 // branch, seeing how it constrains a tested value, and then
2369 // deciding if it's worth our while to encode this constraint
2370 // as graph nodes in the current abstract interpretation map.
2371 void Parse::adjust_map_after_if(BoolTest::mask btest, Node* c, float prob, Block* path, bool can_trap) {
2372   if (!c->is_Cmp()) {
2373     maybe_add_predicate_after_if(path);
2374     return;
2375   }
2376 
2377   if (stopped() || btest == BoolTest::illegal) {
2378     return;                             // nothing to do
2379   }
2380 
2381   bool is_fallthrough = (path == successor_for_bci(iter().next_bci()));
2382 
2383   if (can_trap && path_is_suitable_for_uncommon_trap(prob)) {
2384     repush_if_args();
2385     Node* call = uncommon_trap(Deoptimization::Reason_unstable_if,
2386                   Deoptimization::Action_reinterpret,
2387                   nullptr,
2388                   (is_fallthrough ? "taken always" : "taken never"));
2389 
2390     if (call != nullptr) {
2391       C->record_unstable_if_trap(new UnstableIfTrap(call->as_CallStaticJava(), path));
2392     }
2393     return;
2394   }
2395 
2396   Node* val = c->in(1);
2397   Node* con = c->in(2);
2398   const Type* tcon = _gvn.type(con);
2399   const Type* tval = _gvn.type(val);
2400   bool have_con = tcon->singleton();
2401   if (tval->singleton()) {
2402     if (!have_con) {
2403       // Swap, so constant is in con.
2404       con  = val;
2405       tcon = tval;
2406       val  = c->in(2);
2407       tval = _gvn.type(val);
2408       btest = BoolTest(btest).commute();
2409       have_con = true;
2410     } else {
2411       // Do we have two constants?  Then leave well enough alone.
2412       have_con = false;
2413     }
2414   }
2415   if (!have_con) {                        // remaining adjustments need a con
2416     maybe_add_predicate_after_if(path);
2417     return;
2418   }
2419 
2420   sharpen_type_after_if(btest, con, tcon, val, tval);
2421   maybe_add_predicate_after_if(path);
2422 }
2423 
2424 
2425 static Node* extract_obj_from_klass_load(PhaseGVN* gvn, Node* n) {
2426   Node* ldk;
2427   if (n->is_DecodeNKlass()) {
2428     if (n->in(1)->Opcode() != Op_LoadNKlass) {
2429       return nullptr;
2430     } else {
2431       ldk = n->in(1);
2432     }
2433   } else if (n->Opcode() != Op_LoadKlass) {
2434     return nullptr;
2435   } else {
2436     ldk = n;
2437   }
2438   assert(ldk != nullptr && ldk->is_Load(), "should have found a LoadKlass or LoadNKlass node");
2439 
2440   Node* adr = ldk->in(MemNode::Address);
2441   intptr_t off = 0;
2442   Node* obj = AddPNode::Ideal_base_and_offset(adr, gvn, off);
2443   if (obj == nullptr || off != oopDesc::klass_offset_in_bytes()) // loading oopDesc::_klass?
2444     return nullptr;
2445   const TypePtr* tp = gvn->type(obj)->is_ptr();
2446   if (tp == nullptr || !(tp->isa_instptr() || tp->isa_aryptr())) // is obj a Java object ptr?
2447     return nullptr;
2448 
2449   return obj;
2450 }
2451 
2452 void Parse::sharpen_type_after_if(BoolTest::mask btest,
2453                                   Node* con, const Type* tcon,
2454                                   Node* val, const Type* tval) {
2455   // Look for opportunities to sharpen the type of a node
2456   // whose klass is compared with a constant klass.
2457   if (btest == BoolTest::eq && tcon->isa_klassptr()) {
2458     Node* obj = extract_obj_from_klass_load(&_gvn, val);
2459     const TypeOopPtr* con_type = tcon->isa_klassptr()->as_instance_type();
2460     if (obj != nullptr && (con_type->isa_instptr() || con_type->isa_aryptr())) {
2461        // Found:
2462        //   Bool(CmpP(LoadKlass(obj._klass), ConP(Foo.klass)), [eq])
2463        // or the narrowOop equivalent.
2464        const Type* obj_type = _gvn.type(obj);
2465        const TypeOopPtr* tboth = obj_type->join_speculative(con_type)->isa_oopptr();
2466        if (tboth != nullptr && tboth->klass_is_exact() && tboth != obj_type &&
2467            tboth->higher_equal(obj_type)) {
2468           // obj has to be of the exact type Foo if the CmpP succeeds.
2469           int obj_in_map = map()->find_edge(obj);
2470           JVMState* jvms = this->jvms();
2471           if (obj_in_map >= 0 &&
2472               (jvms->is_loc(obj_in_map) || jvms->is_stk(obj_in_map))) {
2473             TypeNode* ccast = new CheckCastPPNode(control(), obj, tboth);
2474             const Type* tcc = ccast->as_Type()->type();
2475             assert(tcc != obj_type && tcc->higher_equal(obj_type), "must improve");
2476             // Delay transform() call to allow recovery of pre-cast value
2477             // at the control merge.
2478             _gvn.set_type_bottom(ccast);
2479             record_for_igvn(ccast);
2480             if (tboth->is_inlinetypeptr()) {
2481               ccast = InlineTypeNode::make_from_oop(this, ccast, tboth->exact_klass(true)->as_inline_klass());
2482             }
2483             // Here's the payoff.
2484             replace_in_map(obj, ccast);
2485           }
2486        }
2487     }
2488   }
2489 
2490   int val_in_map = map()->find_edge(val);
2491   if (val_in_map < 0)  return;          // replace_in_map would be useless
2492   {
2493     JVMState* jvms = this->jvms();
2494     if (!(jvms->is_loc(val_in_map) ||
2495           jvms->is_stk(val_in_map)))
2496       return;                           // again, it would be useless
2497   }
2498 
2499   // Check for a comparison to a constant, and "know" that the compared
2500   // value is constrained on this path.
2501   assert(tcon->singleton(), "");
2502   ConstraintCastNode* ccast = nullptr;
2503   Node* cast = nullptr;
2504 
2505   switch (btest) {
2506   case BoolTest::eq:                    // Constant test?
2507     {
2508       const Type* tboth = tcon->join_speculative(tval);
2509       if (tboth == tval)  break;        // Nothing to gain.
2510       if (tcon->isa_int()) {
2511         ccast = new CastIINode(control(), val, tboth);
2512       } else if (tcon == TypePtr::NULL_PTR) {
2513         // Cast to null, but keep the pointer identity temporarily live.
2514         ccast = new CastPPNode(control(), val, tboth);
2515       } else {
2516         const TypeF* tf = tcon->isa_float_constant();
2517         const TypeD* td = tcon->isa_double_constant();
2518         // Exclude tests vs float/double 0 as these could be
2519         // either +0 or -0.  Just because you are equal to +0
2520         // doesn't mean you ARE +0!
2521         // Note, following code also replaces Long and Oop values.
2522         if ((!tf || tf->_f != 0.0) &&
2523             (!td || td->_d != 0.0))
2524           cast = con;                   // Replace non-constant val by con.
2525       }
2526     }
2527     break;
2528 
2529   case BoolTest::ne:
2530     if (tcon == TypePtr::NULL_PTR) {
2531       cast = cast_not_null(val, false);
2532     }
2533     break;
2534 
2535   default:
2536     // (At this point we could record int range types with CastII.)
2537     break;
2538   }
2539 
2540   if (ccast != nullptr) {
2541     const Type* tcc = ccast->as_Type()->type();
2542     assert(tcc != tval && tcc->higher_equal(tval), "must improve");
2543     // Delay transform() call to allow recovery of pre-cast value
2544     // at the control merge.
2545     _gvn.set_type_bottom(ccast);
2546     record_for_igvn(ccast);
2547     cast = ccast;
2548   }
2549 
2550   if (cast != nullptr) {                   // Here's the payoff.
2551     replace_in_map(val, cast);
2552   }
2553 }
2554 
2555 /**
2556  * Use speculative type to optimize CmpP node: if comparison is
2557  * against the low level class, cast the object to the speculative
2558  * type if any. CmpP should then go away.
2559  *
2560  * @param c  expected CmpP node
2561  * @return   result of CmpP on object casted to speculative type
2562  *
2563  */
2564 Node* Parse::optimize_cmp_with_klass(Node* c) {
2565   // If this is transformed by the _gvn to a comparison with the low
2566   // level klass then we may be able to use speculation
2567   if (c->Opcode() == Op_CmpP &&
2568       (c->in(1)->Opcode() == Op_LoadKlass || c->in(1)->Opcode() == Op_DecodeNKlass) &&
2569       c->in(2)->is_Con()) {
2570     Node* load_klass = nullptr;
2571     Node* decode = nullptr;
2572     if (c->in(1)->Opcode() == Op_DecodeNKlass) {
2573       decode = c->in(1);
2574       load_klass = c->in(1)->in(1);
2575     } else {
2576       load_klass = c->in(1);
2577     }
2578     if (load_klass->in(2)->is_AddP()) {
2579       Node* addp = load_klass->in(2);
2580       Node* obj = addp->in(AddPNode::Address);
2581       const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();
2582       if (obj_type->speculative_type_not_null() != nullptr) {
2583         ciKlass* k = obj_type->speculative_type();
2584         inc_sp(2);
2585         obj = maybe_cast_profiled_obj(obj, k);
2586         dec_sp(2);
2587         if (obj->is_InlineType()) {
2588           assert(obj->as_InlineType()->is_allocated(&_gvn), "must be allocated");
2589           obj = obj->as_InlineType()->get_oop();
2590         }
2591         // Make the CmpP use the casted obj
2592         addp = basic_plus_adr(obj, addp->in(AddPNode::Offset));
2593         load_klass = load_klass->clone();
2594         load_klass->set_req(2, addp);
2595         load_klass = _gvn.transform(load_klass);
2596         if (decode != nullptr) {
2597           decode = decode->clone();
2598           decode->set_req(1, load_klass);
2599           load_klass = _gvn.transform(decode);
2600         }
2601         c = c->clone();
2602         c->set_req(1, load_klass);
2603         c = _gvn.transform(c);
2604       }
2605     }
2606   }
2607   return c;
2608 }
2609 
2610 //------------------------------do_one_bytecode--------------------------------
2611 // Parse this bytecode, and alter the Parsers JVM->Node mapping
2612 void Parse::do_one_bytecode() {
2613   Node *a, *b, *c, *d;          // Handy temps
2614   BoolTest::mask btest;
2615   int i;
2616 
2617   assert(!has_exceptions(), "bytecode entry state must be clear of throws");
2618 
2619   if (C->check_node_count(NodeLimitFudgeFactor * 5,
2620                           "out of nodes parsing method")) {
2621     return;
2622   }
2623 
2624 #ifdef ASSERT
2625   // for setting breakpoints
2626   if (TraceOptoParse) {
2627     tty->print(" @");
2628     dump_bci(bci());
2629     tty->print(" %s", Bytecodes::name(bc()));
2630     tty->cr();
2631   }
2632 #endif
2633 
2634   switch (bc()) {
2635   case Bytecodes::_nop:
2636     // do nothing
2637     break;
2638   case Bytecodes::_lconst_0:
2639     push_pair(longcon(0));
2640     break;
2641 
2642   case Bytecodes::_lconst_1:
2643     push_pair(longcon(1));
2644     break;
2645 
2646   case Bytecodes::_fconst_0:
2647     push(zerocon(T_FLOAT));
2648     break;
2649 
2650   case Bytecodes::_fconst_1:
2651     push(makecon(TypeF::ONE));
2652     break;
2653 
2654   case Bytecodes::_fconst_2:
2655     push(makecon(TypeF::make(2.0f)));
2656     break;
2657 
2658   case Bytecodes::_dconst_0:
2659     push_pair(zerocon(T_DOUBLE));
2660     break;
2661 
2662   case Bytecodes::_dconst_1:
2663     push_pair(makecon(TypeD::ONE));
2664     break;
2665 
2666   case Bytecodes::_iconst_m1:push(intcon(-1)); break;
2667   case Bytecodes::_iconst_0: push(intcon( 0)); break;
2668   case Bytecodes::_iconst_1: push(intcon( 1)); break;
2669   case Bytecodes::_iconst_2: push(intcon( 2)); break;
2670   case Bytecodes::_iconst_3: push(intcon( 3)); break;
2671   case Bytecodes::_iconst_4: push(intcon( 4)); break;
2672   case Bytecodes::_iconst_5: push(intcon( 5)); break;
2673   case Bytecodes::_bipush:   push(intcon(iter().get_constant_u1())); break;
2674   case Bytecodes::_sipush:   push(intcon(iter().get_constant_u2())); break;
2675   case Bytecodes::_aconst_null: push(null());  break;
2676 
2677   case Bytecodes::_ldc:
2678   case Bytecodes::_ldc_w:
2679   case Bytecodes::_ldc2_w: {
2680     ciConstant constant = iter().get_constant();
2681     if (constant.is_loaded()) {
2682       const Type* con_type = Type::make_from_constant(constant);
2683       if (con_type != nullptr) {
2684         push_node(con_type->basic_type(), makecon(con_type));
2685       }
2686     } else {
2687       // If the constant is unresolved or in error state, run this BC in the interpreter.
2688       if (iter().is_in_error()) {
2689         uncommon_trap(Deoptimization::make_trap_request(Deoptimization::Reason_unhandled,
2690                                                         Deoptimization::Action_none),
2691                       nullptr, "constant in error state", true /* must_throw */);
2692 
2693       } else {
2694         int index = iter().get_constant_pool_index();
2695         uncommon_trap(Deoptimization::make_trap_request(Deoptimization::Reason_unloaded,
2696                                                         Deoptimization::Action_reinterpret,
2697                                                         index),
2698                       nullptr, "unresolved constant", false /* must_throw */);
2699       }
2700     }
2701     break;
2702   }
2703 
2704   case Bytecodes::_aload_0:
2705     push( local(0) );
2706     break;
2707   case Bytecodes::_aload_1:
2708     push( local(1) );
2709     break;
2710   case Bytecodes::_aload_2:
2711     push( local(2) );
2712     break;
2713   case Bytecodes::_aload_3:
2714     push( local(3) );
2715     break;
2716   case Bytecodes::_aload:
2717     push( local(iter().get_index()) );
2718     break;
2719 
2720   case Bytecodes::_fload_0:
2721   case Bytecodes::_iload_0:
2722     push( local(0) );
2723     break;
2724   case Bytecodes::_fload_1:
2725   case Bytecodes::_iload_1:
2726     push( local(1) );
2727     break;
2728   case Bytecodes::_fload_2:
2729   case Bytecodes::_iload_2:
2730     push( local(2) );
2731     break;
2732   case Bytecodes::_fload_3:
2733   case Bytecodes::_iload_3:
2734     push( local(3) );
2735     break;
2736   case Bytecodes::_fload:
2737   case Bytecodes::_iload:
2738     push( local(iter().get_index()) );
2739     break;
2740   case Bytecodes::_lload_0:
2741     push_pair_local( 0 );
2742     break;
2743   case Bytecodes::_lload_1:
2744     push_pair_local( 1 );
2745     break;
2746   case Bytecodes::_lload_2:
2747     push_pair_local( 2 );
2748     break;
2749   case Bytecodes::_lload_3:
2750     push_pair_local( 3 );
2751     break;
2752   case Bytecodes::_lload:
2753     push_pair_local( iter().get_index() );
2754     break;
2755 
2756   case Bytecodes::_dload_0:
2757     push_pair_local(0);
2758     break;
2759   case Bytecodes::_dload_1:
2760     push_pair_local(1);
2761     break;
2762   case Bytecodes::_dload_2:
2763     push_pair_local(2);
2764     break;
2765   case Bytecodes::_dload_3:
2766     push_pair_local(3);
2767     break;
2768   case Bytecodes::_dload:
2769     push_pair_local(iter().get_index());
2770     break;
2771   case Bytecodes::_fstore_0:
2772   case Bytecodes::_istore_0:
2773   case Bytecodes::_astore_0:
2774     set_local( 0, pop() );
2775     break;
2776   case Bytecodes::_fstore_1:
2777   case Bytecodes::_istore_1:
2778   case Bytecodes::_astore_1:
2779     set_local( 1, pop() );
2780     break;
2781   case Bytecodes::_fstore_2:
2782   case Bytecodes::_istore_2:
2783   case Bytecodes::_astore_2:
2784     set_local( 2, pop() );
2785     break;
2786   case Bytecodes::_fstore_3:
2787   case Bytecodes::_istore_3:
2788   case Bytecodes::_astore_3:
2789     set_local( 3, pop() );
2790     break;
2791   case Bytecodes::_fstore:
2792   case Bytecodes::_istore:
2793   case Bytecodes::_astore:
2794     set_local( iter().get_index(), pop() );
2795     break;
2796   // long stores
2797   case Bytecodes::_lstore_0:
2798     set_pair_local( 0, pop_pair() );
2799     break;
2800   case Bytecodes::_lstore_1:
2801     set_pair_local( 1, pop_pair() );
2802     break;
2803   case Bytecodes::_lstore_2:
2804     set_pair_local( 2, pop_pair() );
2805     break;
2806   case Bytecodes::_lstore_3:
2807     set_pair_local( 3, pop_pair() );
2808     break;
2809   case Bytecodes::_lstore:
2810     set_pair_local( iter().get_index(), pop_pair() );
2811     break;
2812 
2813   // double stores
2814   case Bytecodes::_dstore_0:
2815     set_pair_local( 0, dprecision_rounding(pop_pair()) );
2816     break;
2817   case Bytecodes::_dstore_1:
2818     set_pair_local( 1, dprecision_rounding(pop_pair()) );
2819     break;
2820   case Bytecodes::_dstore_2:
2821     set_pair_local( 2, dprecision_rounding(pop_pair()) );
2822     break;
2823   case Bytecodes::_dstore_3:
2824     set_pair_local( 3, dprecision_rounding(pop_pair()) );
2825     break;
2826   case Bytecodes::_dstore:
2827     set_pair_local( iter().get_index(), dprecision_rounding(pop_pair()) );
2828     break;
2829 
2830   case Bytecodes::_pop:  dec_sp(1);   break;
2831   case Bytecodes::_pop2: dec_sp(2);   break;
2832   case Bytecodes::_swap:
2833     a = pop();
2834     b = pop();
2835     push(a);
2836     push(b);
2837     break;
2838   case Bytecodes::_dup:
2839     a = pop();
2840     push(a);
2841     push(a);
2842     break;
2843   case Bytecodes::_dup_x1:
2844     a = pop();
2845     b = pop();
2846     push( a );
2847     push( b );
2848     push( a );
2849     break;
2850   case Bytecodes::_dup_x2:
2851     a = pop();
2852     b = pop();
2853     c = pop();
2854     push( a );
2855     push( c );
2856     push( b );
2857     push( a );
2858     break;
2859   case Bytecodes::_dup2:
2860     a = pop();
2861     b = pop();
2862     push( b );
2863     push( a );
2864     push( b );
2865     push( a );
2866     break;
2867 
2868   case Bytecodes::_dup2_x1:
2869     // before: .. c, b, a
2870     // after:  .. b, a, c, b, a
2871     // not tested
2872     a = pop();
2873     b = pop();
2874     c = pop();
2875     push( b );
2876     push( a );
2877     push( c );
2878     push( b );
2879     push( a );
2880     break;
2881   case Bytecodes::_dup2_x2:
2882     // before: .. d, c, b, a
2883     // after:  .. b, a, d, c, b, a
2884     // not tested
2885     a = pop();
2886     b = pop();
2887     c = pop();
2888     d = pop();
2889     push( b );
2890     push( a );
2891     push( d );
2892     push( c );
2893     push( b );
2894     push( a );
2895     break;
2896 
2897   case Bytecodes::_arraylength: {
2898     // Must do null-check with value on expression stack
2899     Node *ary = null_check(peek(), T_ARRAY);
2900     // Compile-time detect of null-exception?
2901     if (stopped())  return;
2902     a = pop();
2903     push(load_array_length(a));
2904     break;
2905   }
2906 
2907   case Bytecodes::_baload:  array_load(T_BYTE);    break;
2908   case Bytecodes::_caload:  array_load(T_CHAR);    break;
2909   case Bytecodes::_iaload:  array_load(T_INT);     break;
2910   case Bytecodes::_saload:  array_load(T_SHORT);   break;
2911   case Bytecodes::_faload:  array_load(T_FLOAT);   break;
2912   case Bytecodes::_aaload:  array_load(T_OBJECT);  break;
2913   case Bytecodes::_laload:  array_load(T_LONG);    break;
2914   case Bytecodes::_daload:  array_load(T_DOUBLE);  break;
2915   case Bytecodes::_bastore: array_store(T_BYTE);   break;
2916   case Bytecodes::_castore: array_store(T_CHAR);   break;
2917   case Bytecodes::_iastore: array_store(T_INT);    break;
2918   case Bytecodes::_sastore: array_store(T_SHORT);  break;
2919   case Bytecodes::_fastore: array_store(T_FLOAT);  break;
2920   case Bytecodes::_aastore: array_store(T_OBJECT); break;
2921   case Bytecodes::_lastore: array_store(T_LONG);   break;
2922   case Bytecodes::_dastore: array_store(T_DOUBLE); break;
2923 
2924   case Bytecodes::_getfield:
2925     do_getfield();
2926     break;
2927 
2928   case Bytecodes::_getstatic:
2929     do_getstatic();
2930     break;
2931 
2932   case Bytecodes::_putfield:
2933     do_putfield();
2934     break;
2935 
2936   case Bytecodes::_putstatic:
2937     do_putstatic();
2938     break;
2939 
2940   case Bytecodes::_irem:
2941     // Must keep both values on the expression-stack during null-check
2942     zero_check_int(peek());
2943     // Compile-time detect of null-exception?
2944     if (stopped())  return;
2945     b = pop();
2946     a = pop();
2947     push(_gvn.transform(new ModINode(control(), a, b)));
2948     break;
2949   case Bytecodes::_idiv:
2950     // Must keep both values on the expression-stack during null-check
2951     zero_check_int(peek());
2952     // Compile-time detect of null-exception?
2953     if (stopped())  return;
2954     b = pop();
2955     a = pop();
2956     push( _gvn.transform( new DivINode(control(),a,b) ) );
2957     break;
2958   case Bytecodes::_imul:
2959     b = pop(); a = pop();
2960     push( _gvn.transform( new MulINode(a,b) ) );
2961     break;
2962   case Bytecodes::_iadd:
2963     b = pop(); a = pop();
2964     push( _gvn.transform( new AddINode(a,b) ) );
2965     break;
2966   case Bytecodes::_ineg:
2967     a = pop();
2968     push( _gvn.transform( new SubINode(_gvn.intcon(0),a)) );
2969     break;
2970   case Bytecodes::_isub:
2971     b = pop(); a = pop();
2972     push( _gvn.transform( new SubINode(a,b) ) );
2973     break;
2974   case Bytecodes::_iand:
2975     b = pop(); a = pop();
2976     push( _gvn.transform( new AndINode(a,b) ) );
2977     break;
2978   case Bytecodes::_ior:
2979     b = pop(); a = pop();
2980     push( _gvn.transform( new OrINode(a,b) ) );
2981     break;
2982   case Bytecodes::_ixor:
2983     b = pop(); a = pop();
2984     push( _gvn.transform( new XorINode(a,b) ) );
2985     break;
2986   case Bytecodes::_ishl:
2987     b = pop(); a = pop();
2988     push( _gvn.transform( new LShiftINode(a,b) ) );
2989     break;
2990   case Bytecodes::_ishr:
2991     b = pop(); a = pop();
2992     push( _gvn.transform( new RShiftINode(a,b) ) );
2993     break;
2994   case Bytecodes::_iushr:
2995     b = pop(); a = pop();
2996     push( _gvn.transform( new URShiftINode(a,b) ) );
2997     break;
2998 
2999   case Bytecodes::_fneg:
3000     a = pop();
3001     b = _gvn.transform(new NegFNode (a));
3002     push(b);
3003     break;
3004 
3005   case Bytecodes::_fsub:
3006     b = pop();
3007     a = pop();
3008     c = _gvn.transform( new SubFNode(a,b) );
3009     d = precision_rounding(c);
3010     push( d );
3011     break;
3012 
3013   case Bytecodes::_fadd:
3014     b = pop();
3015     a = pop();
3016     c = _gvn.transform( new AddFNode(a,b) );
3017     d = precision_rounding(c);
3018     push( d );
3019     break;
3020 
3021   case Bytecodes::_fmul:
3022     b = pop();
3023     a = pop();
3024     c = _gvn.transform( new MulFNode(a,b) );
3025     d = precision_rounding(c);
3026     push( d );
3027     break;
3028 
3029   case Bytecodes::_fdiv:
3030     b = pop();
3031     a = pop();
3032     c = _gvn.transform( new DivFNode(0,a,b) );
3033     d = precision_rounding(c);
3034     push( d );
3035     break;
3036 
3037   case Bytecodes::_frem:
3038     if (Matcher::has_match_rule(Op_ModF)) {
3039       // Generate a ModF node.
3040       b = pop();
3041       a = pop();
3042       c = _gvn.transform( new ModFNode(0,a,b) );
3043       d = precision_rounding(c);
3044       push( d );
3045     }
3046     else {
3047       // Generate a call.
3048       modf();
3049     }
3050     break;
3051 
3052   case Bytecodes::_fcmpl:
3053     b = pop();
3054     a = pop();
3055     c = _gvn.transform( new CmpF3Node( a, b));
3056     push(c);
3057     break;
3058   case Bytecodes::_fcmpg:
3059     b = pop();
3060     a = pop();
3061 
3062     // Same as fcmpl but need to flip the unordered case.  Swap the inputs,
3063     // which negates the result sign except for unordered.  Flip the unordered
3064     // as well by using CmpF3 which implements unordered-lesser instead of
3065     // unordered-greater semantics.  Finally, commute the result bits.  Result
3066     // is same as using a CmpF3Greater except we did it with CmpF3 alone.
3067     c = _gvn.transform( new CmpF3Node( b, a));
3068     c = _gvn.transform( new SubINode(_gvn.intcon(0),c) );
3069     push(c);
3070     break;
3071 
3072   case Bytecodes::_f2i:
3073     a = pop();
3074     push(_gvn.transform(new ConvF2INode(a)));
3075     break;
3076 
3077   case Bytecodes::_d2i:
3078     a = pop_pair();
3079     b = _gvn.transform(new ConvD2INode(a));
3080     push( b );
3081     break;
3082 
3083   case Bytecodes::_f2d:
3084     a = pop();
3085     b = _gvn.transform( new ConvF2DNode(a));
3086     push_pair( b );
3087     break;
3088 
3089   case Bytecodes::_d2f:
3090     a = pop_pair();
3091     b = _gvn.transform( new ConvD2FNode(a));
3092     // This breaks _227_mtrt (speed & correctness) and _222_mpegaudio (speed)
3093     //b = _gvn.transform(new RoundFloatNode(0, b) );
3094     push( b );
3095     break;
3096 
3097   case Bytecodes::_l2f:
3098     if (Matcher::convL2FSupported()) {
3099       a = pop_pair();
3100       b = _gvn.transform( new ConvL2FNode(a));
3101       // For x86_32.ad, FILD doesn't restrict precision to 24 or 53 bits.
3102       // Rather than storing the result into an FP register then pushing
3103       // out to memory to round, the machine instruction that implements
3104       // ConvL2D is responsible for rounding.
3105       // c = precision_rounding(b);
3106       push(b);
3107     } else {
3108       l2f();
3109     }
3110     break;
3111 
3112   case Bytecodes::_l2d:
3113     a = pop_pair();
3114     b = _gvn.transform( new ConvL2DNode(a));
3115     // For x86_32.ad, rounding is always necessary (see _l2f above).
3116     // c = dprecision_rounding(b);
3117     push_pair(b);
3118     break;
3119 
3120   case Bytecodes::_f2l:
3121     a = pop();
3122     b = _gvn.transform( new ConvF2LNode(a));
3123     push_pair(b);
3124     break;
3125 
3126   case Bytecodes::_d2l:
3127     a = pop_pair();
3128     b = _gvn.transform( new ConvD2LNode(a));
3129     push_pair(b);
3130     break;
3131 
3132   case Bytecodes::_dsub:
3133     b = pop_pair();
3134     a = pop_pair();
3135     c = _gvn.transform( new SubDNode(a,b) );
3136     d = dprecision_rounding(c);
3137     push_pair( d );
3138     break;
3139 
3140   case Bytecodes::_dadd:
3141     b = pop_pair();
3142     a = pop_pair();
3143     c = _gvn.transform( new AddDNode(a,b) );
3144     d = dprecision_rounding(c);
3145     push_pair( d );
3146     break;
3147 
3148   case Bytecodes::_dmul:
3149     b = pop_pair();
3150     a = pop_pair();
3151     c = _gvn.transform( new MulDNode(a,b) );
3152     d = dprecision_rounding(c);
3153     push_pair( d );
3154     break;
3155 
3156   case Bytecodes::_ddiv:
3157     b = pop_pair();
3158     a = pop_pair();
3159     c = _gvn.transform( new DivDNode(0,a,b) );
3160     d = dprecision_rounding(c);
3161     push_pair( d );
3162     break;
3163 
3164   case Bytecodes::_dneg:
3165     a = pop_pair();
3166     b = _gvn.transform(new NegDNode (a));
3167     push_pair(b);
3168     break;
3169 
3170   case Bytecodes::_drem:
3171     if (Matcher::has_match_rule(Op_ModD)) {
3172       // Generate a ModD node.
3173       b = pop_pair();
3174       a = pop_pair();
3175       // a % b
3176 
3177       c = _gvn.transform( new ModDNode(0,a,b) );
3178       d = dprecision_rounding(c);
3179       push_pair( d );
3180     }
3181     else {
3182       // Generate a call.
3183       modd();
3184     }
3185     break;
3186 
3187   case Bytecodes::_dcmpl:
3188     b = pop_pair();
3189     a = pop_pair();
3190     c = _gvn.transform( new CmpD3Node( a, b));
3191     push(c);
3192     break;
3193 
3194   case Bytecodes::_dcmpg:
3195     b = pop_pair();
3196     a = pop_pair();
3197     // Same as dcmpl but need to flip the unordered case.
3198     // Commute the inputs, which negates the result sign except for unordered.
3199     // Flip the unordered as well by using CmpD3 which implements
3200     // unordered-lesser instead of unordered-greater semantics.
3201     // Finally, negate the result bits.  Result is same as using a
3202     // CmpD3Greater except we did it with CmpD3 alone.
3203     c = _gvn.transform( new CmpD3Node( b, a));
3204     c = _gvn.transform( new SubINode(_gvn.intcon(0),c) );
3205     push(c);
3206     break;
3207 
3208 
3209     // Note for longs -> lo word is on TOS, hi word is on TOS - 1
3210   case Bytecodes::_land:
3211     b = pop_pair();
3212     a = pop_pair();
3213     c = _gvn.transform( new AndLNode(a,b) );
3214     push_pair(c);
3215     break;
3216   case Bytecodes::_lor:
3217     b = pop_pair();
3218     a = pop_pair();
3219     c = _gvn.transform( new OrLNode(a,b) );
3220     push_pair(c);
3221     break;
3222   case Bytecodes::_lxor:
3223     b = pop_pair();
3224     a = pop_pair();
3225     c = _gvn.transform( new XorLNode(a,b) );
3226     push_pair(c);
3227     break;
3228 
3229   case Bytecodes::_lshl:
3230     b = pop();                  // the shift count
3231     a = pop_pair();             // value to be shifted
3232     c = _gvn.transform( new LShiftLNode(a,b) );
3233     push_pair(c);
3234     break;
3235   case Bytecodes::_lshr:
3236     b = pop();                  // the shift count
3237     a = pop_pair();             // value to be shifted
3238     c = _gvn.transform( new RShiftLNode(a,b) );
3239     push_pair(c);
3240     break;
3241   case Bytecodes::_lushr:
3242     b = pop();                  // the shift count
3243     a = pop_pair();             // value to be shifted
3244     c = _gvn.transform( new URShiftLNode(a,b) );
3245     push_pair(c);
3246     break;
3247   case Bytecodes::_lmul:
3248     b = pop_pair();
3249     a = pop_pair();
3250     c = _gvn.transform( new MulLNode(a,b) );
3251     push_pair(c);
3252     break;
3253 
3254   case Bytecodes::_lrem:
3255     // Must keep both values on the expression-stack during null-check
3256     assert(peek(0) == top(), "long word order");
3257     zero_check_long(peek(1));
3258     // Compile-time detect of null-exception?
3259     if (stopped())  return;
3260     b = pop_pair();
3261     a = pop_pair();
3262     c = _gvn.transform( new ModLNode(control(),a,b) );
3263     push_pair(c);
3264     break;
3265 
3266   case Bytecodes::_ldiv:
3267     // Must keep both values on the expression-stack during null-check
3268     assert(peek(0) == top(), "long word order");
3269     zero_check_long(peek(1));
3270     // Compile-time detect of null-exception?
3271     if (stopped())  return;
3272     b = pop_pair();
3273     a = pop_pair();
3274     c = _gvn.transform( new DivLNode(control(),a,b) );
3275     push_pair(c);
3276     break;
3277 
3278   case Bytecodes::_ladd:
3279     b = pop_pair();
3280     a = pop_pair();
3281     c = _gvn.transform( new AddLNode(a,b) );
3282     push_pair(c);
3283     break;
3284   case Bytecodes::_lsub:
3285     b = pop_pair();
3286     a = pop_pair();
3287     c = _gvn.transform( new SubLNode(a,b) );
3288     push_pair(c);
3289     break;
3290   case Bytecodes::_lcmp:
3291     // Safepoints are now inserted _before_ branches.  The long-compare
3292     // bytecode painfully produces a 3-way value (-1,0,+1) which requires a
3293     // slew of control flow.  These are usually followed by a CmpI vs zero and
3294     // a branch; this pattern then optimizes to the obvious long-compare and
3295     // branch.  However, if the branch is backwards there's a Safepoint
3296     // inserted.  The inserted Safepoint captures the JVM state at the
3297     // pre-branch point, i.e. it captures the 3-way value.  Thus if a
3298     // long-compare is used to control a loop the debug info will force
3299     // computation of the 3-way value, even though the generated code uses a
3300     // long-compare and branch.  We try to rectify the situation by inserting
3301     // a SafePoint here and have it dominate and kill the safepoint added at a
3302     // following backwards branch.  At this point the JVM state merely holds 2
3303     // longs but not the 3-way value.
3304     switch (iter().next_bc()) {
3305       case Bytecodes::_ifgt:
3306       case Bytecodes::_iflt:
3307       case Bytecodes::_ifge:
3308       case Bytecodes::_ifle:
3309       case Bytecodes::_ifne:
3310       case Bytecodes::_ifeq:
3311         // If this is a backwards branch in the bytecodes, add Safepoint
3312         maybe_add_safepoint(iter().next_get_dest());
3313       default:
3314         break;
3315     }
3316     b = pop_pair();
3317     a = pop_pair();
3318     c = _gvn.transform( new CmpL3Node( a, b ));
3319     push(c);
3320     break;
3321 
3322   case Bytecodes::_lneg:
3323     a = pop_pair();
3324     b = _gvn.transform( new SubLNode(longcon(0),a));
3325     push_pair(b);
3326     break;
3327   case Bytecodes::_l2i:
3328     a = pop_pair();
3329     push( _gvn.transform( new ConvL2INode(a)));
3330     break;
3331   case Bytecodes::_i2l:
3332     a = pop();
3333     b = _gvn.transform( new ConvI2LNode(a));
3334     push_pair(b);
3335     break;
3336   case Bytecodes::_i2b:
3337     // Sign extend
3338     a = pop();
3339     a = Compile::narrow_value(T_BYTE, a, nullptr, &_gvn, true);
3340     push(a);
3341     break;
3342   case Bytecodes::_i2s:
3343     a = pop();
3344     a = Compile::narrow_value(T_SHORT, a, nullptr, &_gvn, true);
3345     push(a);
3346     break;
3347   case Bytecodes::_i2c:
3348     a = pop();
3349     a = Compile::narrow_value(T_CHAR, a, nullptr, &_gvn, true);
3350     push(a);
3351     break;
3352 
3353   case Bytecodes::_i2f:
3354     a = pop();
3355     b = _gvn.transform( new ConvI2FNode(a) ) ;
3356     c = precision_rounding(b);
3357     push (b);
3358     break;
3359 
3360   case Bytecodes::_i2d:
3361     a = pop();
3362     b = _gvn.transform( new ConvI2DNode(a));
3363     push_pair(b);
3364     break;
3365 
3366   case Bytecodes::_iinc:        // Increment local
3367     i = iter().get_index();     // Get local index
3368     set_local( i, _gvn.transform( new AddINode( _gvn.intcon(iter().get_iinc_con()), local(i) ) ) );
3369     break;
3370 
3371   // Exit points of synchronized methods must have an unlock node
3372   case Bytecodes::_return:
3373     return_current(nullptr);
3374     break;
3375 
3376   case Bytecodes::_ireturn:
3377   case Bytecodes::_areturn:
3378   case Bytecodes::_freturn:
3379     return_current(pop());
3380     break;
3381   case Bytecodes::_lreturn:
3382     return_current(pop_pair());
3383     break;
3384   case Bytecodes::_dreturn:
3385     return_current(pop_pair());
3386     break;
3387 
3388   case Bytecodes::_athrow:
3389     // null exception oop throws null pointer exception
3390     null_check(peek());
3391     if (stopped())  return;
3392     // Hook the thrown exception directly to subsequent handlers.
3393     if (BailoutToInterpreterForThrows) {
3394       // Keep method interpreted from now on.
3395       uncommon_trap(Deoptimization::Reason_unhandled,
3396                     Deoptimization::Action_make_not_compilable);
3397       return;
3398     }
3399     if (env()->jvmti_can_post_on_exceptions()) {
3400       // check if we must post exception events, take uncommon trap if so (with must_throw = false)
3401       uncommon_trap_if_should_post_on_exceptions(Deoptimization::Reason_unhandled, false);
3402     }
3403     // Here if either can_post_on_exceptions or should_post_on_exceptions is false
3404     add_exception_state(make_exception_state(peek()));
3405     break;
3406 
3407   case Bytecodes::_goto:   // fall through
3408   case Bytecodes::_goto_w: {
3409     int target_bci = (bc() == Bytecodes::_goto) ? iter().get_dest() : iter().get_far_dest();
3410 
3411     // If this is a backwards branch in the bytecodes, add Safepoint
3412     maybe_add_safepoint(target_bci);
3413 
3414     // Merge the current control into the target basic block
3415     merge(target_bci);
3416 
3417     // See if we can get some profile data and hand it off to the next block
3418     Block *target_block = block()->successor_for_bci(target_bci);
3419     if (target_block->pred_count() != 1)  break;
3420     ciMethodData* methodData = method()->method_data();
3421     if (!methodData->is_mature())  break;
3422     ciProfileData* data = methodData->bci_to_data(bci());
3423     assert(data != nullptr && data->is_JumpData(), "need JumpData for taken branch");
3424     int taken = ((ciJumpData*)data)->taken();
3425     taken = method()->scale_count(taken);
3426     target_block->set_count(taken);
3427     break;
3428   }
3429 
3430   case Bytecodes::_ifnull:    btest = BoolTest::eq; goto handle_if_null;
3431   case Bytecodes::_ifnonnull: btest = BoolTest::ne; goto handle_if_null;
3432   handle_if_null:
3433     // If this is a backwards branch in the bytecodes, add Safepoint
3434     maybe_add_safepoint(iter().get_dest());
3435     a = null();
3436     b = pop();
3437     if (b->is_InlineType()) {
3438       // Null checking a scalarized but nullable inline type. Check the IsInit
3439       // input instead of the oop input to avoid keeping buffer allocations alive
3440       c = _gvn.transform(new CmpINode(b->as_InlineType()->get_is_init(), zerocon(T_INT)));
3441     } else {
3442       if (!_gvn.type(b)->speculative_maybe_null() &&
3443           !too_many_traps(Deoptimization::Reason_speculate_null_check)) {
3444         inc_sp(1);
3445         Node* null_ctl = top();
3446         b = null_check_oop(b, &null_ctl, true, true, true);
3447         assert(null_ctl->is_top(), "no null control here");
3448         dec_sp(1);
3449       } else if (_gvn.type(b)->speculative_always_null() &&
3450                  !too_many_traps(Deoptimization::Reason_speculate_null_assert)) {
3451         inc_sp(1);
3452         b = null_assert(b);
3453         dec_sp(1);
3454       }
3455       c = _gvn.transform( new CmpPNode(b, a) );
3456     }
3457     do_ifnull(btest, c);
3458     break;
3459 
3460   case Bytecodes::_if_acmpeq: btest = BoolTest::eq; goto handle_if_acmp;
3461   case Bytecodes::_if_acmpne: btest = BoolTest::ne; goto handle_if_acmp;
3462   handle_if_acmp:
3463     // If this is a backwards branch in the bytecodes, add Safepoint
3464     maybe_add_safepoint(iter().get_dest());
3465     a = pop();
3466     b = pop();
3467     do_acmp(btest, b, a);
3468     break;
3469 
3470   case Bytecodes::_ifeq: btest = BoolTest::eq; goto handle_ifxx;
3471   case Bytecodes::_ifne: btest = BoolTest::ne; goto handle_ifxx;
3472   case Bytecodes::_iflt: btest = BoolTest::lt; goto handle_ifxx;
3473   case Bytecodes::_ifle: btest = BoolTest::le; goto handle_ifxx;
3474   case Bytecodes::_ifgt: btest = BoolTest::gt; goto handle_ifxx;
3475   case Bytecodes::_ifge: btest = BoolTest::ge; goto handle_ifxx;
3476   handle_ifxx:
3477     // If this is a backwards branch in the bytecodes, add Safepoint
3478     maybe_add_safepoint(iter().get_dest());
3479     a = _gvn.intcon(0);
3480     b = pop();
3481     c = _gvn.transform( new CmpINode(b, a) );
3482     do_if(btest, c);
3483     break;
3484 
3485   case Bytecodes::_if_icmpeq: btest = BoolTest::eq; goto handle_if_icmp;
3486   case Bytecodes::_if_icmpne: btest = BoolTest::ne; goto handle_if_icmp;
3487   case Bytecodes::_if_icmplt: btest = BoolTest::lt; goto handle_if_icmp;
3488   case Bytecodes::_if_icmple: btest = BoolTest::le; goto handle_if_icmp;
3489   case Bytecodes::_if_icmpgt: btest = BoolTest::gt; goto handle_if_icmp;
3490   case Bytecodes::_if_icmpge: btest = BoolTest::ge; goto handle_if_icmp;
3491   handle_if_icmp:
3492     // If this is a backwards branch in the bytecodes, add Safepoint
3493     maybe_add_safepoint(iter().get_dest());
3494     a = pop();
3495     b = pop();
3496     c = _gvn.transform( new CmpINode( b, a ) );
3497     do_if(btest, c);
3498     break;
3499 
3500   case Bytecodes::_tableswitch:
3501     do_tableswitch();
3502     break;
3503 
3504   case Bytecodes::_lookupswitch:
3505     do_lookupswitch();
3506     break;
3507 
3508   case Bytecodes::_invokestatic:
3509   case Bytecodes::_invokedynamic:
3510   case Bytecodes::_invokespecial:
3511   case Bytecodes::_invokevirtual:
3512   case Bytecodes::_invokeinterface:
3513     do_call();
3514     break;
3515   case Bytecodes::_checkcast:
3516     do_checkcast();
3517     break;
3518   case Bytecodes::_instanceof:
3519     do_instanceof();
3520     break;
3521   case Bytecodes::_anewarray:
3522     do_newarray();
3523     break;
3524   case Bytecodes::_newarray:
3525     do_newarray((BasicType)iter().get_index());
3526     break;
3527   case Bytecodes::_multianewarray:
3528     do_multianewarray();
3529     break;
3530   case Bytecodes::_new:
3531     do_new();
3532     break;
3533 
3534   case Bytecodes::_jsr:
3535   case Bytecodes::_jsr_w:
3536     do_jsr();
3537     break;
3538 
3539   case Bytecodes::_ret:
3540     do_ret();
3541     break;
3542 
3543 
3544   case Bytecodes::_monitorenter:
3545     do_monitor_enter();
3546     break;
3547 
3548   case Bytecodes::_monitorexit:
3549     do_monitor_exit();
3550     break;
3551 
3552   case Bytecodes::_breakpoint:
3553     // Breakpoint set concurrently to compile
3554     // %%% use an uncommon trap?
3555     C->record_failure("breakpoint in method");
3556     return;
3557 
3558   default:
3559 #ifndef PRODUCT
3560     map()->dump(99);
3561 #endif
3562     tty->print("\nUnhandled bytecode %s\n", Bytecodes::name(bc()) );
3563     ShouldNotReachHere();
3564   }
3565 
3566 #ifndef PRODUCT
3567   if (failing()) { return; }
3568   constexpr int perBytecode = 6;
3569   if (C->should_print_igv(perBytecode)) {
3570     IdealGraphPrinter* printer = C->igv_printer();
3571     char buffer[256];
3572     jio_snprintf(buffer, sizeof(buffer), "Bytecode %d: %s", bci(), Bytecodes::name(bc()));
3573     bool old = printer->traverse_outs();
3574     printer->set_traverse_outs(true);
3575     printer->print_method(buffer, perBytecode);
3576     printer->set_traverse_outs(old);
3577   }
3578 #endif
3579 }