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