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