1 /*
   2  * Copyright (c) 1997, 2024, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "classfile/javaClasses.inline.hpp"
  27 #include "classfile/symbolTable.hpp"
  28 #include "classfile/systemDictionary.hpp"
  29 #include "classfile/vmClasses.hpp"
  30 #include "classfile/vmSymbols.hpp"
  31 #include "code/codeCache.hpp"
  32 #include "compiler/compilationPolicy.hpp"
  33 #include "compiler/compileBroker.hpp"
  34 #include "compiler/disassembler.hpp"
  35 #include "gc/shared/barrierSetNMethod.hpp"
  36 #include "gc/shared/collectedHeap.hpp"
  37 #include "interpreter/bytecodeTracer.hpp"
  38 #include "interpreter/interpreter.hpp"
  39 #include "interpreter/interpreterRuntime.hpp"
  40 #include "interpreter/linkResolver.hpp"
  41 #include "interpreter/templateTable.hpp"
  42 #include "jvm_io.h"
  43 #include "logging/log.hpp"
  44 #include "memory/oopFactory.hpp"
  45 #include "memory/resourceArea.hpp"
  46 #include "memory/universe.hpp"
  47 #include "oops/constantPool.inline.hpp"
  48 #include "oops/cpCache.inline.hpp"
  49 #include "oops/flatArrayKlass.hpp"
  50 #include "oops/flatArrayOop.inline.hpp"
  51 #include "oops/inlineKlass.inline.hpp"
  52 #include "oops/instanceKlass.inline.hpp"
  53 #include "oops/klass.inline.hpp"
  54 #include "oops/methodData.hpp"
  55 #include "oops/method.inline.hpp"
  56 #include "oops/objArrayKlass.hpp"
  57 #include "oops/objArrayOop.inline.hpp"
  58 #include "oops/oop.inline.hpp"
  59 #include "oops/symbol.hpp"
  60 #include "prims/jvmtiExport.hpp"
  61 #include "prims/methodHandles.hpp"
  62 #include "prims/nativeLookup.hpp"
  63 #include "runtime/atomic.hpp"
  64 #include "runtime/continuation.hpp"
  65 #include "runtime/deoptimization.hpp"
  66 #include "runtime/fieldDescriptor.inline.hpp"
  67 #include "runtime/frame.inline.hpp"
  68 #include "runtime/handles.inline.hpp"
  69 #include "runtime/icache.hpp"
  70 #include "runtime/interfaceSupport.inline.hpp"
  71 #include "runtime/java.hpp"
  72 #include "runtime/javaCalls.hpp"
  73 #include "runtime/jfieldIDWorkaround.hpp"
  74 #include "runtime/osThread.hpp"
  75 #include "runtime/sharedRuntime.hpp"
  76 #include "runtime/stackWatermarkSet.hpp"
  77 #include "runtime/stubRoutines.hpp"
  78 #include "runtime/synchronizer.inline.hpp"
  79 #include "runtime/threadCritical.hpp"
  80 #include "utilities/align.hpp"
  81 #include "utilities/checkedCast.hpp"
  82 #include "utilities/copy.hpp"
  83 #include "utilities/events.hpp"
  84 #include "utilities/globalDefinitions.hpp"
  85 #ifdef COMPILER2
  86 #include "opto/runtime.hpp"
  87 #endif
  88 
  89 // Helper class to access current interpreter state
  90 class LastFrameAccessor : public StackObj {
  91   frame _last_frame;
  92 public:
  93   LastFrameAccessor(JavaThread* current) {
  94     assert(current == Thread::current(), "sanity");
  95     _last_frame = current->last_frame();
  96   }
  97   bool is_interpreted_frame() const              { return _last_frame.is_interpreted_frame(); }
  98   Method*   method() const                       { return _last_frame.interpreter_frame_method(); }
  99   address   bcp() const                          { return _last_frame.interpreter_frame_bcp(); }
 100   int       bci() const                          { return _last_frame.interpreter_frame_bci(); }
 101   address   mdp() const                          { return _last_frame.interpreter_frame_mdp(); }
 102 
 103   void      set_bcp(address bcp)                 { _last_frame.interpreter_frame_set_bcp(bcp); }
 104   void      set_mdp(address dp)                  { _last_frame.interpreter_frame_set_mdp(dp); }
 105 
 106   // pass method to avoid calling unsafe bcp_to_method (partial fix 4926272)
 107   Bytecodes::Code code() const                   { return Bytecodes::code_at(method(), bcp()); }
 108 
 109   Bytecode  bytecode() const                     { return Bytecode(method(), bcp()); }
 110   int get_index_u1(Bytecodes::Code bc) const     { return bytecode().get_index_u1(bc); }
 111   int get_index_u2(Bytecodes::Code bc) const     { return bytecode().get_index_u2(bc); }
 112   int get_index_u4(Bytecodes::Code bc) const     { return bytecode().get_index_u4(bc); }
 113   int number_of_dimensions() const               { return bcp()[3]; }
 114 
 115   oop callee_receiver(Symbol* signature) {
 116     return _last_frame.interpreter_callee_receiver(signature);
 117   }
 118   BasicObjectLock* monitor_begin() const {
 119     return _last_frame.interpreter_frame_monitor_begin();
 120   }
 121   BasicObjectLock* monitor_end() const {
 122     return _last_frame.interpreter_frame_monitor_end();
 123   }
 124   BasicObjectLock* next_monitor(BasicObjectLock* current) const {
 125     return _last_frame.next_monitor_in_interpreter_frame(current);
 126   }
 127 
 128   frame& get_frame()                             { return _last_frame; }
 129 };
 130 
 131 //------------------------------------------------------------------------------------------------------------------------
 132 // State accessors
 133 
 134 void InterpreterRuntime::set_bcp_and_mdp(address bcp, JavaThread* current) {
 135   LastFrameAccessor last_frame(current);
 136   last_frame.set_bcp(bcp);
 137   if (ProfileInterpreter) {
 138     // ProfileTraps uses MDOs independently of ProfileInterpreter.
 139     // That is why we must check both ProfileInterpreter and mdo != nullptr.
 140     MethodData* mdo = last_frame.method()->method_data();
 141     if (mdo != nullptr) {
 142       NEEDS_CLEANUP;
 143       last_frame.set_mdp(mdo->bci_to_dp(last_frame.bci()));
 144     }
 145   }
 146 }
 147 
 148 //------------------------------------------------------------------------------------------------------------------------
 149 // Constants
 150 
 151 
 152 JRT_ENTRY(void, InterpreterRuntime::ldc(JavaThread* current, bool wide))
 153   // access constant pool
 154   LastFrameAccessor last_frame(current);
 155   ConstantPool* pool = last_frame.method()->constants();
 156   int cp_index = wide ? last_frame.get_index_u2(Bytecodes::_ldc_w) : last_frame.get_index_u1(Bytecodes::_ldc);
 157   constantTag tag = pool->tag_at(cp_index);
 158 
 159   assert (tag.is_unresolved_klass() || tag.is_klass(), "wrong ldc call");
 160   Klass* klass = pool->klass_at(cp_index, CHECK);
 161   oop java_class = klass->java_mirror();
 162   current->set_vm_result(java_class);
 163 JRT_END
 164 
 165 JRT_ENTRY(void, InterpreterRuntime::resolve_ldc(JavaThread* current, Bytecodes::Code bytecode)) {
 166   assert(bytecode == Bytecodes::_ldc ||
 167          bytecode == Bytecodes::_ldc_w ||
 168          bytecode == Bytecodes::_ldc2_w ||
 169          bytecode == Bytecodes::_fast_aldc ||
 170          bytecode == Bytecodes::_fast_aldc_w, "wrong bc");
 171   ResourceMark rm(current);
 172   const bool is_fast_aldc = (bytecode == Bytecodes::_fast_aldc ||
 173                              bytecode == Bytecodes::_fast_aldc_w);
 174   LastFrameAccessor last_frame(current);
 175   methodHandle m (current, last_frame.method());
 176   Bytecode_loadconstant ldc(m, last_frame.bci());
 177 
 178   // Double-check the size.  (Condy can have any type.)
 179   BasicType type = ldc.result_type();
 180   switch (type2size[type]) {
 181   case 2: guarantee(bytecode == Bytecodes::_ldc2_w, ""); break;
 182   case 1: guarantee(bytecode != Bytecodes::_ldc2_w, ""); break;
 183   default: ShouldNotReachHere();
 184   }
 185 
 186   // Resolve the constant.  This does not do unboxing.
 187   // But it does replace Universe::the_null_sentinel by null.
 188   oop result = ldc.resolve_constant(CHECK);
 189   assert(result != nullptr || is_fast_aldc, "null result only valid for fast_aldc");
 190 
 191 #ifdef ASSERT
 192   {
 193     // The bytecode wrappers aren't GC-safe so construct a new one
 194     Bytecode_loadconstant ldc2(m, last_frame.bci());
 195     int rindex = ldc2.cache_index();
 196     if (rindex < 0)
 197       rindex = m->constants()->cp_to_object_index(ldc2.pool_index());
 198     if (rindex >= 0) {
 199       oop coop = m->constants()->resolved_reference_at(rindex);
 200       oop roop = (result == nullptr ? Universe::the_null_sentinel() : result);
 201       assert(roop == coop, "expected result for assembly code");
 202     }
 203   }
 204 #endif
 205   current->set_vm_result(result);
 206   if (!is_fast_aldc) {
 207     // Tell the interpreter how to unbox the primitive.
 208     guarantee(java_lang_boxing_object::is_instance(result, type), "");
 209     int offset = java_lang_boxing_object::value_offset(type);
 210     intptr_t flags = ((as_TosState(type) << ConstantPoolCache::tos_state_shift)
 211                       | (offset & ConstantPoolCache::field_index_mask));
 212     current->set_vm_result_2((Metadata*)flags);
 213   }
 214 }
 215 JRT_END
 216 
 217 
 218 //------------------------------------------------------------------------------------------------------------------------
 219 // Allocation
 220 
 221 JRT_ENTRY(void, InterpreterRuntime::_new(JavaThread* current, ConstantPool* pool, int index))
 222   Klass* k = pool->klass_at(index, CHECK);
 223   InstanceKlass* klass = InstanceKlass::cast(k);
 224 
 225   // Make sure we are not instantiating an abstract klass
 226   klass->check_valid_for_instantiation(true, CHECK);
 227 
 228   // Make sure klass is initialized
 229   klass->initialize(CHECK);
 230 
 231   oop obj = klass->allocate_instance(CHECK);
 232   current->set_vm_result(obj);
 233 JRT_END
 234 
 235 JRT_ENTRY(void, InterpreterRuntime::uninitialized_static_inline_type_field(JavaThread* current, oopDesc* mirror, ResolvedFieldEntry* entry))
 236   // The interpreter tries to access an inline static field that has not been initialized.
 237   // This situation can happen in different scenarios:
 238   //   1 - if the load or initialization of the field failed during step 8 of
 239   //       the initialization of the holder of the field, in this case the access to the field
 240   //       must fail
 241   //   2 - it can also happen when the initialization of the holder class triggered the initialization of
 242   //       another class which accesses this field in its static initializer, in this case the
 243   //       access must succeed to allow circularity
 244   // The code below tries to load and initialize the field's class again before returning the default value.
 245   // If the field was not initialized because of an error, an exception should be thrown.
 246   // If the class is being initialized, the default value is returned.
 247   assert(entry->is_valid(), "Invalid ResolvedFieldEntry");
 248   instanceHandle mirror_h(THREAD, (instanceOop)mirror);
 249   InstanceKlass* klass = entry->field_holder();
 250   u2 index = entry->field_index();
 251   assert(klass == java_lang_Class::as_Klass(mirror), "Not the field holder klass");
 252   assert(klass->field_is_null_free_inline_type(index), "Sanity check");
 253   if (klass->is_being_initialized() && klass->is_reentrant_initialization(THREAD)) {
 254     int offset = klass->field_offset(index);
 255     Klass* field_k = klass->get_inline_type_field_klass_or_null(index);
 256     if (field_k == nullptr) {
 257       field_k = SystemDictionary::resolve_or_fail(klass->field_signature(index)->fundamental_name(THREAD),
 258           Handle(THREAD, klass->class_loader()),
 259           Handle(THREAD, klass->protection_domain()),
 260           true, CHECK);
 261       assert(field_k != nullptr, "Should have been loaded or an exception thrown above");
 262       klass->set_inline_type_field_klass(index, InlineKlass::cast(field_k));
 263     }
 264     field_k->initialize(CHECK);
 265     oop defaultvalue = InlineKlass::cast(field_k)->default_value();
 266     // It is safe to initialize the static field because 1) the current thread is the initializing thread
 267     // and is the only one that can access it, and 2) the field is actually not initialized (i.e. null)
 268     // otherwise the JVM should not be executing this code.
 269     mirror_h()->obj_field_put(offset, defaultvalue);
 270     current->set_vm_result(defaultvalue);
 271   } else {
 272     assert(klass->is_in_error_state(), "If not initializing, initialization must have failed to get there");
 273     ResourceMark rm(THREAD);
 274     const char* desc = "Could not initialize class ";
 275     const char* className = klass->external_name();
 276     size_t msglen = strlen(desc) + strlen(className) + 1;
 277     char* message = NEW_RESOURCE_ARRAY(char, msglen);
 278     if (nullptr == message) {
 279       // Out of memory: can't create detailed error message
 280       THROW_MSG(vmSymbols::java_lang_NoClassDefFoundError(), className);
 281     } else {
 282       jio_snprintf(message, msglen, "%s%s", desc, className);
 283       THROW_MSG(vmSymbols::java_lang_NoClassDefFoundError(), message);
 284     }
 285   }
 286 JRT_END
 287 
 288 JRT_ENTRY(void, InterpreterRuntime::read_flat_field(JavaThread* current, oopDesc* obj, int index, Klass* field_holder))
 289   Handle obj_h(THREAD, obj);
 290 
 291   assert(oopDesc::is_oop(obj), "Sanity check");
 292 
 293   assert(field_holder->is_instance_klass(), "Sanity check");
 294   InstanceKlass* klass = InstanceKlass::cast(field_holder);
 295 
 296   assert(klass->field_is_flat(index), "Sanity check");
 297 
 298   InlineKlass* field_vklass = InlineKlass::cast(klass->get_inline_type_field_klass(index));
 299 
 300   oop res = field_vklass->read_flat_field(obj_h(), klass->field_offset(index), CHECK);
 301   current->set_vm_result(res);
 302 JRT_END
 303 
 304 // The protocol to read a nullable flat field is:
 305 // Step 1: read the null marker with an load_acquire barrier to ensure that
 306 //         reordered loads won't try to load the value before the null marker is read
 307 // Step 2: if the null marker value is zero, the field's value is null
 308 //         otherwise the flat field value can be read like a regular flat field
 309 JRT_ENTRY(void, InterpreterRuntime::read_nullable_flat_field(JavaThread* current, oopDesc* obj, ResolvedFieldEntry* entry))
 310   assert(oopDesc::is_oop(obj), "Sanity check");
 311   assert(entry->has_null_marker(), "Otherwise should not get there");
 312   Handle obj_h(THREAD, obj);
 313 
 314   InstanceKlass* ik = InstanceKlass::cast(obj_h()->klass());
 315   int field_index = entry->field_index();
 316   int nm_offset = ik->null_marker_offsets_array()->at(field_index);
 317   if (obj_h()->byte_field_acquire(nm_offset) == 0) {
 318     current->set_vm_result(nullptr);
 319   } else {
 320     InlineKlass* field_vklass = InlineKlass::cast(ik->get_inline_type_field_klass(field_index));
 321     oop res = field_vklass->read_flat_field(obj_h(), ik->field_offset(field_index), CHECK);
 322     current->set_vm_result(res);
 323   }
 324 JRT_END
 325 
 326 // The protocol to write a nullable flat field is:
 327 // If the new field value is null, just write zero to the null marker
 328 // Otherwise:
 329 // Step 1: write the field value like a regular flat field
 330 // Step 2: have a memory barrier to ensure that the whole value content is visible
 331 // Step 3: update the null marker to a non zero value
 332 JRT_ENTRY(void, InterpreterRuntime::write_nullable_flat_field(JavaThread* current, oopDesc* obj, oopDesc* value, ResolvedFieldEntry* entry))
 333   assert(oopDesc::is_oop(obj), "Sanity check");
 334   Handle obj_h(THREAD, obj);
 335   assert(value == nullptr || oopDesc::is_oop(value), "Sanity check");
 336   Handle val_h(THREAD, value);
 337 
 338   InstanceKlass* ik = InstanceKlass::cast(obj_h()->klass());
 339   int nm_offset = ik->null_marker_offsets_array()->at(entry->field_index());
 340   if (val_h() == nullptr) {
 341     obj_h()->byte_field_put(nm_offset, (jbyte)0);
 342     return;
 343   }
 344   InlineKlass* vk = InlineKlass::cast(val_h()->klass());
 345   if (entry->has_internal_null_marker()) {
 346     // The interpreter copies values with a bulk operation
 347     // To avoid accidently setting the null marker to "null" during
 348     // the copying, the null marker is set to non zero in the source object
 349     if (val_h()->byte_field(vk->get_internal_null_marker_offset()) == 0) {
 350       val_h()->byte_field_put(vk->get_internal_null_marker_offset(), (jbyte)1);
 351     }
 352     vk->write_non_null_flat_field(obj_h(), entry->field_offset(), val_h());
 353   } else {
 354     vk->write_non_null_flat_field(obj_h(), entry->field_offset(), val_h());
 355     OrderAccess::release();
 356     obj_h()->byte_field_put(nm_offset, (jbyte)1);
 357   }
 358 JRT_END
 359 
 360 JRT_ENTRY(void, InterpreterRuntime::newarray(JavaThread* current, BasicType type, jint size))
 361   oop obj = oopFactory::new_typeArray(type, size, CHECK);
 362   current->set_vm_result(obj);
 363 JRT_END
 364 
 365 
 366 JRT_ENTRY(void, InterpreterRuntime::anewarray(JavaThread* current, ConstantPool* pool, int index, jint size))
 367   Klass*    klass = pool->klass_at(index, CHECK);
 368   arrayOop obj = oopFactory::new_objArray(klass, size, CHECK);
 369   current->set_vm_result(obj);
 370 JRT_END
 371 
 372 JRT_ENTRY(void, InterpreterRuntime::value_array_load(JavaThread* current, arrayOopDesc* array, int index))
 373   flatArrayHandle vah(current, (flatArrayOop)array);
 374   oop value_holder = flatArrayOopDesc::value_alloc_copy_from_index(vah, index, CHECK);
 375   current->set_vm_result(value_holder);
 376 JRT_END
 377 
 378 JRT_ENTRY(void, InterpreterRuntime::value_array_store(JavaThread* current, void* val, arrayOopDesc* array, int index))
 379   assert(val != nullptr, "can't store null into flat array");
 380   ((flatArrayOop)array)->value_copy_to_index(cast_to_oop(val), index);
 381 JRT_END
 382 
 383 JRT_ENTRY(void, InterpreterRuntime::multianewarray(JavaThread* current, jint* first_size_address))
 384   // We may want to pass in more arguments - could make this slightly faster
 385   LastFrameAccessor last_frame(current);
 386   ConstantPool* constants = last_frame.method()->constants();
 387   int i = last_frame.get_index_u2(Bytecodes::_multianewarray);
 388   Klass* klass = constants->klass_at(i, CHECK);
 389   int   nof_dims = last_frame.number_of_dimensions();
 390   assert(klass->is_klass(), "not a class");
 391   assert(nof_dims >= 1, "multianewarray rank must be nonzero");
 392 
 393   // We must create an array of jints to pass to multi_allocate.
 394   ResourceMark rm(current);
 395   const int small_dims = 10;
 396   jint dim_array[small_dims];
 397   jint *dims = &dim_array[0];
 398   if (nof_dims > small_dims) {
 399     dims = (jint*) NEW_RESOURCE_ARRAY(jint, nof_dims);
 400   }
 401   for (int index = 0; index < nof_dims; index++) {
 402     // offset from first_size_address is addressed as local[index]
 403     int n = Interpreter::local_offset_in_bytes(index)/jintSize;
 404     dims[index] = first_size_address[n];
 405   }
 406   oop obj = ArrayKlass::cast(klass)->multi_allocate(nof_dims, dims, CHECK);
 407   current->set_vm_result(obj);
 408 JRT_END
 409 
 410 
 411 JRT_ENTRY(void, InterpreterRuntime::register_finalizer(JavaThread* current, oopDesc* obj))
 412   assert(oopDesc::is_oop(obj), "must be a valid oop");
 413   assert(obj->klass()->has_finalizer(), "shouldn't be here otherwise");
 414   InstanceKlass::register_finalizer(instanceOop(obj), CHECK);
 415 JRT_END
 416 
 417 JRT_ENTRY(jboolean, InterpreterRuntime::is_substitutable(JavaThread* current, oopDesc* aobj, oopDesc* bobj))
 418   assert(oopDesc::is_oop(aobj) && oopDesc::is_oop(bobj), "must be valid oops");
 419 
 420   Handle ha(THREAD, aobj);
 421   Handle hb(THREAD, bobj);
 422   JavaValue result(T_BOOLEAN);
 423   JavaCallArguments args;
 424   args.push_oop(ha);
 425   args.push_oop(hb);
 426   methodHandle method(current, Universe::is_substitutable_method());
 427   method->method_holder()->initialize(CHECK_false); // Ensure class ValueObjectMethods is initialized
 428   JavaCalls::call(&result, method, &args, THREAD);
 429   if (HAS_PENDING_EXCEPTION) {
 430     // Something really bad happened because isSubstitutable() should not throw exceptions
 431     // If it is an error, just let it propagate
 432     // If it is an exception, wrap it into an InternalError
 433     if (!PENDING_EXCEPTION->is_a(vmClasses::Error_klass())) {
 434       Handle e(THREAD, PENDING_EXCEPTION);
 435       CLEAR_PENDING_EXCEPTION;
 436       THROW_MSG_CAUSE_(vmSymbols::java_lang_InternalError(), "Internal error in substitutability test", e, false);
 437     }
 438   }
 439   return result.get_jboolean();
 440 JRT_END
 441 
 442 // Quicken instance-of and check-cast bytecodes
 443 JRT_ENTRY(void, InterpreterRuntime::quicken_io_cc(JavaThread* current))
 444   // Force resolving; quicken the bytecode
 445   LastFrameAccessor last_frame(current);
 446   int which = last_frame.get_index_u2(Bytecodes::_checkcast);
 447   ConstantPool* cpool = last_frame.method()->constants();
 448   // We'd expect to assert that we're only here to quicken bytecodes, but in a multithreaded
 449   // program we might have seen an unquick'd bytecode in the interpreter but have another
 450   // thread quicken the bytecode before we get here.
 451   // assert( cpool->tag_at(which).is_unresolved_klass(), "should only come here to quicken bytecodes" );
 452   Klass* klass = cpool->klass_at(which, CHECK);
 453   current->set_vm_result_2(klass);
 454 JRT_END
 455 
 456 
 457 //------------------------------------------------------------------------------------------------------------------------
 458 // Exceptions
 459 
 460 void InterpreterRuntime::note_trap_inner(JavaThread* current, int reason,
 461                                          const methodHandle& trap_method, int trap_bci) {
 462   if (trap_method.not_null()) {
 463     MethodData* trap_mdo = trap_method->method_data();
 464     if (trap_mdo == nullptr) {
 465       ExceptionMark em(current);
 466       JavaThread* THREAD = current; // For exception macros.
 467       Method::build_profiling_method_data(trap_method, THREAD);
 468       if (HAS_PENDING_EXCEPTION) {
 469         // Only metaspace OOM is expected. No Java code executed.
 470         assert((PENDING_EXCEPTION->is_a(vmClasses::OutOfMemoryError_klass())),
 471                "we expect only an OOM error here");
 472         CLEAR_PENDING_EXCEPTION;
 473       }
 474       trap_mdo = trap_method->method_data();
 475       // and fall through...
 476     }
 477     if (trap_mdo != nullptr) {
 478       // Update per-method count of trap events.  The interpreter
 479       // is updating the MDO to simulate the effect of compiler traps.
 480       Deoptimization::update_method_data_from_interpreter(trap_mdo, trap_bci, reason);
 481     }
 482   }
 483 }
 484 
 485 // Assume the compiler is (or will be) interested in this event.
 486 // If necessary, create an MDO to hold the information, and record it.
 487 void InterpreterRuntime::note_trap(JavaThread* current, int reason) {
 488   assert(ProfileTraps, "call me only if profiling");
 489   LastFrameAccessor last_frame(current);
 490   methodHandle trap_method(current, last_frame.method());
 491   int trap_bci = trap_method->bci_from(last_frame.bcp());
 492   note_trap_inner(current, reason, trap_method, trap_bci);
 493 }
 494 
 495 static Handle get_preinitialized_exception(Klass* k, TRAPS) {
 496   // get klass
 497   InstanceKlass* klass = InstanceKlass::cast(k);
 498   assert(klass->is_initialized(),
 499          "this klass should have been initialized during VM initialization");
 500   // create instance - do not call constructor since we may have no
 501   // (java) stack space left (should assert constructor is empty)
 502   Handle exception;
 503   oop exception_oop = klass->allocate_instance(CHECK_(exception));
 504   exception = Handle(THREAD, exception_oop);
 505   if (StackTraceInThrowable) {
 506     java_lang_Throwable::fill_in_stack_trace(exception);
 507   }
 508   return exception;
 509 }
 510 
 511 // Special handling for stack overflow: since we don't have any (java) stack
 512 // space left we use the pre-allocated & pre-initialized StackOverflowError
 513 // klass to create an stack overflow error instance.  We do not call its
 514 // constructor for the same reason (it is empty, anyway).
 515 JRT_ENTRY(void, InterpreterRuntime::throw_StackOverflowError(JavaThread* current))
 516   Handle exception = get_preinitialized_exception(
 517                                  vmClasses::StackOverflowError_klass(),
 518                                  CHECK);
 519   // Increment counter for hs_err file reporting
 520   Atomic::inc(&Exceptions::_stack_overflow_errors);
 521   // Remove the ScopedValue bindings in case we got a StackOverflowError
 522   // while we were trying to manipulate ScopedValue bindings.
 523   current->clear_scopedValueBindings();
 524   THROW_HANDLE(exception);
 525 JRT_END
 526 
 527 JRT_ENTRY(void, InterpreterRuntime::throw_delayed_StackOverflowError(JavaThread* current))
 528   Handle exception = get_preinitialized_exception(
 529                                  vmClasses::StackOverflowError_klass(),
 530                                  CHECK);
 531   java_lang_Throwable::set_message(exception(),
 532           Universe::delayed_stack_overflow_error_message());
 533   // Increment counter for hs_err file reporting
 534   Atomic::inc(&Exceptions::_stack_overflow_errors);
 535   // Remove the ScopedValue bindings in case we got a StackOverflowError
 536   // while we were trying to manipulate ScopedValue bindings.
 537   current->clear_scopedValueBindings();
 538   THROW_HANDLE(exception);
 539 JRT_END
 540 
 541 JRT_ENTRY(void, InterpreterRuntime::create_exception(JavaThread* current, char* name, char* message))
 542   // lookup exception klass
 543   TempNewSymbol s = SymbolTable::new_symbol(name);
 544   if (ProfileTraps) {
 545     if (s == vmSymbols::java_lang_ArithmeticException()) {
 546       note_trap(current, Deoptimization::Reason_div0_check);
 547     } else if (s == vmSymbols::java_lang_NullPointerException()) {
 548       note_trap(current, Deoptimization::Reason_null_check);
 549     }
 550   }
 551   // create exception
 552   Handle exception = Exceptions::new_exception(current, s, message);
 553   current->set_vm_result(exception());
 554 JRT_END
 555 
 556 
 557 JRT_ENTRY(void, InterpreterRuntime::create_klass_exception(JavaThread* current, char* name, oopDesc* obj))
 558   // Produce the error message first because note_trap can safepoint
 559   ResourceMark rm(current);
 560   const char* klass_name = obj->klass()->external_name();
 561   // lookup exception klass
 562   TempNewSymbol s = SymbolTable::new_symbol(name);
 563   if (ProfileTraps) {
 564     if (s == vmSymbols::java_lang_ArrayStoreException()) {
 565       note_trap(current, Deoptimization::Reason_array_check);
 566     } else {
 567       note_trap(current, Deoptimization::Reason_class_check);
 568     }
 569   }
 570   // create exception, with klass name as detail message
 571   Handle exception = Exceptions::new_exception(current, s, klass_name);
 572   current->set_vm_result(exception());
 573 JRT_END
 574 
 575 JRT_ENTRY(void, InterpreterRuntime::throw_ArrayIndexOutOfBoundsException(JavaThread* current, arrayOopDesc* a, jint index))
 576   // Produce the error message first because note_trap can safepoint
 577   ResourceMark rm(current);
 578   stringStream ss;
 579   ss.print("Index %d out of bounds for length %d", index, a->length());
 580 
 581   if (ProfileTraps) {
 582     note_trap(current, Deoptimization::Reason_range_check);
 583   }
 584 
 585   THROW_MSG(vmSymbols::java_lang_ArrayIndexOutOfBoundsException(), ss.as_string());
 586 JRT_END
 587 
 588 JRT_ENTRY(void, InterpreterRuntime::throw_ClassCastException(
 589   JavaThread* current, oopDesc* obj))
 590 
 591   // Produce the error message first because note_trap can safepoint
 592   ResourceMark rm(current);
 593   char* message = SharedRuntime::generate_class_cast_message(
 594     current, obj->klass());
 595 
 596   if (ProfileTraps) {
 597     note_trap(current, Deoptimization::Reason_class_check);
 598   }
 599 
 600   // create exception
 601   THROW_MSG(vmSymbols::java_lang_ClassCastException(), message);
 602 JRT_END
 603 
 604 // exception_handler_for_exception(...) returns the continuation address,
 605 // the exception oop (via TLS) and sets the bci/bcp for the continuation.
 606 // The exception oop is returned to make sure it is preserved over GC (it
 607 // is only on the stack if the exception was thrown explicitly via athrow).
 608 // During this operation, the expression stack contains the values for the
 609 // bci where the exception happened. If the exception was propagated back
 610 // from a call, the expression stack contains the values for the bci at the
 611 // invoke w/o arguments (i.e., as if one were inside the call).
 612 // Note that the implementation of this method assumes it's only called when an exception has actually occured
 613 JRT_ENTRY(address, InterpreterRuntime::exception_handler_for_exception(JavaThread* current, oopDesc* exception))
 614   // We get here after we have unwound from a callee throwing an exception
 615   // into the interpreter. Any deferred stack processing is notified of
 616   // the event via the StackWatermarkSet.
 617   StackWatermarkSet::after_unwind(current);
 618 
 619   LastFrameAccessor last_frame(current);
 620   Handle             h_exception(current, exception);
 621   methodHandle       h_method   (current, last_frame.method());
 622   constantPoolHandle h_constants(current, h_method->constants());
 623   bool               should_repeat;
 624   int                handler_bci;
 625   int                current_bci = last_frame.bci();
 626 
 627   if (current->frames_to_pop_failed_realloc() > 0) {
 628     // Allocation of scalar replaced object used in this frame
 629     // failed. Unconditionally pop the frame.
 630     current->dec_frames_to_pop_failed_realloc();
 631     current->set_vm_result(h_exception());
 632     // If the method is synchronized we already unlocked the monitor
 633     // during deoptimization so the interpreter needs to skip it when
 634     // the frame is popped.
 635     current->set_do_not_unlock_if_synchronized(true);
 636     return Interpreter::remove_activation_entry();
 637   }
 638 
 639   // Need to do this check first since when _do_not_unlock_if_synchronized
 640   // is set, we don't want to trigger any classloading which may make calls
 641   // into java, or surprisingly find a matching exception handler for bci 0
 642   // since at this moment the method hasn't been "officially" entered yet.
 643   if (current->do_not_unlock_if_synchronized()) {
 644     ResourceMark rm;
 645     assert(current_bci == 0,  "bci isn't zero for do_not_unlock_if_synchronized");
 646     current->set_vm_result(exception);
 647     return Interpreter::remove_activation_entry();
 648   }
 649 
 650   do {
 651     should_repeat = false;
 652 
 653     // assertions
 654     assert(h_exception.not_null(), "null exceptions should be handled by athrow");
 655     // Check that exception is a subclass of Throwable.
 656     assert(h_exception->is_a(vmClasses::Throwable_klass()),
 657            "Exception not subclass of Throwable");
 658 
 659     // tracing
 660     if (log_is_enabled(Info, exceptions)) {
 661       ResourceMark rm(current);
 662       stringStream tempst;
 663       tempst.print("interpreter method <%s>\n"
 664                    " at bci %d for thread " INTPTR_FORMAT " (%s)",
 665                    h_method->print_value_string(), current_bci, p2i(current), current->name());
 666       Exceptions::log_exception(h_exception, tempst.as_string());
 667     }
 668 // Don't go paging in something which won't be used.
 669 //     else if (extable->length() == 0) {
 670 //       // disabled for now - interpreter is not using shortcut yet
 671 //       // (shortcut is not to call runtime if we have no exception handlers)
 672 //       // warning("performance bug: should not call runtime if method has no exception handlers");
 673 //     }
 674     // for AbortVMOnException flag
 675     Exceptions::debug_check_abort(h_exception);
 676 
 677     // exception handler lookup
 678     Klass* klass = h_exception->klass();
 679     handler_bci = Method::fast_exception_handler_bci_for(h_method, klass, current_bci, THREAD);
 680     if (HAS_PENDING_EXCEPTION) {
 681       // We threw an exception while trying to find the exception handler.
 682       // Transfer the new exception to the exception handle which will
 683       // be set into thread local storage, and do another lookup for an
 684       // exception handler for this exception, this time starting at the
 685       // BCI of the exception handler which caused the exception to be
 686       // thrown (bug 4307310).
 687       h_exception = Handle(THREAD, PENDING_EXCEPTION);
 688       CLEAR_PENDING_EXCEPTION;
 689       if (handler_bci >= 0) {
 690         current_bci = handler_bci;
 691         should_repeat = true;
 692       }
 693     }
 694   } while (should_repeat == true);
 695 
 696 #if INCLUDE_JVMCI
 697   if (EnableJVMCI && h_method->method_data() != nullptr) {
 698     ResourceMark rm(current);
 699     MethodData* mdo = h_method->method_data();
 700 
 701     // Lock to read ProfileData, and ensure lock is not broken by a safepoint
 702     MutexLocker ml(mdo->extra_data_lock(), Mutex::_no_safepoint_check_flag);
 703 
 704     ProfileData* pdata = mdo->allocate_bci_to_data(current_bci, nullptr);
 705     if (pdata != nullptr && pdata->is_BitData()) {
 706       BitData* bit_data = (BitData*) pdata;
 707       bit_data->set_exception_seen();
 708     }
 709   }
 710 #endif
 711 
 712   // notify JVMTI of an exception throw; JVMTI will detect if this is a first
 713   // time throw or a stack unwinding throw and accordingly notify the debugger
 714   if (JvmtiExport::can_post_on_exceptions()) {
 715     JvmtiExport::post_exception_throw(current, h_method(), last_frame.bcp(), h_exception());
 716   }
 717 
 718   address continuation = nullptr;
 719   address handler_pc = nullptr;
 720   if (handler_bci < 0 || !current->stack_overflow_state()->reguard_stack((address) &continuation)) {
 721     // Forward exception to callee (leaving bci/bcp untouched) because (a) no
 722     // handler in this method, or (b) after a stack overflow there is not yet
 723     // enough stack space available to reprotect the stack.
 724     continuation = Interpreter::remove_activation_entry();
 725 #if COMPILER2_OR_JVMCI
 726     // Count this for compilation purposes
 727     h_method->interpreter_throwout_increment(THREAD);
 728 #endif
 729   } else {
 730     // handler in this method => change bci/bcp to handler bci/bcp and continue there
 731     handler_pc = h_method->code_base() + handler_bci;
 732     h_method->set_exception_handler_entered(handler_bci); // profiling
 733 #ifndef ZERO
 734     set_bcp_and_mdp(handler_pc, current);
 735     continuation = Interpreter::dispatch_table(vtos)[*handler_pc];
 736 #else
 737     continuation = (address)(intptr_t) handler_bci;
 738 #endif
 739   }
 740 
 741   // notify debugger of an exception catch
 742   // (this is good for exceptions caught in native methods as well)
 743   if (JvmtiExport::can_post_on_exceptions()) {
 744     JvmtiExport::notice_unwind_due_to_exception(current, h_method(), handler_pc, h_exception(), (handler_pc != nullptr));
 745   }
 746 
 747   current->set_vm_result(h_exception());
 748   return continuation;
 749 JRT_END
 750 
 751 
 752 JRT_ENTRY(void, InterpreterRuntime::throw_pending_exception(JavaThread* current))
 753   assert(current->has_pending_exception(), "must only be called if there's an exception pending");
 754   // nothing to do - eventually we should remove this code entirely (see comments @ call sites)
 755 JRT_END
 756 
 757 
 758 JRT_ENTRY(void, InterpreterRuntime::throw_AbstractMethodError(JavaThread* current))
 759   THROW(vmSymbols::java_lang_AbstractMethodError());
 760 JRT_END
 761 
 762 // This method is called from the "abstract_entry" of the interpreter.
 763 // At that point, the arguments have already been removed from the stack
 764 // and therefore we don't have the receiver object at our fingertips. (Though,
 765 // on some platforms the receiver still resides in a register...). Thus,
 766 // we have no choice but print an error message not containing the receiver
 767 // type.
 768 JRT_ENTRY(void, InterpreterRuntime::throw_AbstractMethodErrorWithMethod(JavaThread* current,
 769                                                                         Method* missingMethod))
 770   ResourceMark rm(current);
 771   assert(missingMethod != nullptr, "sanity");
 772   methodHandle m(current, missingMethod);
 773   LinkResolver::throw_abstract_method_error(m, THREAD);
 774 JRT_END
 775 
 776 JRT_ENTRY(void, InterpreterRuntime::throw_AbstractMethodErrorVerbose(JavaThread* current,
 777                                                                      Klass* recvKlass,
 778                                                                      Method* missingMethod))
 779   ResourceMark rm(current);
 780   methodHandle mh = methodHandle(current, missingMethod);
 781   LinkResolver::throw_abstract_method_error(mh, recvKlass, THREAD);
 782 JRT_END
 783 
 784 JRT_ENTRY(void, InterpreterRuntime::throw_InstantiationError(JavaThread* current))
 785   THROW(vmSymbols::java_lang_InstantiationError());
 786 JRT_END
 787 
 788 
 789 JRT_ENTRY(void, InterpreterRuntime::throw_IncompatibleClassChangeError(JavaThread* current))
 790   THROW(vmSymbols::java_lang_IncompatibleClassChangeError());
 791 JRT_END
 792 
 793 JRT_ENTRY(void, InterpreterRuntime::throw_IncompatibleClassChangeErrorVerbose(JavaThread* current,
 794                                                                               Klass* recvKlass,
 795                                                                               Klass* interfaceKlass))
 796   ResourceMark rm(current);
 797   char buf[1000];
 798   buf[0] = '\0';
 799   jio_snprintf(buf, sizeof(buf),
 800                "Class %s does not implement the requested interface %s",
 801                recvKlass ? recvKlass->external_name() : "nullptr",
 802                interfaceKlass ? interfaceKlass->external_name() : "nullptr");
 803   THROW_MSG(vmSymbols::java_lang_IncompatibleClassChangeError(), buf);
 804 JRT_END
 805 
 806 JRT_ENTRY(void, InterpreterRuntime::throw_NullPointerException(JavaThread* current))
 807   THROW(vmSymbols::java_lang_NullPointerException());
 808 JRT_END
 809 
 810 //------------------------------------------------------------------------------------------------------------------------
 811 // Fields
 812 //
 813 
 814 void InterpreterRuntime::resolve_get_put(JavaThread* current, Bytecodes::Code bytecode) {
 815   LastFrameAccessor last_frame(current);
 816   constantPoolHandle pool(current, last_frame.method()->constants());
 817   methodHandle m(current, last_frame.method());
 818 
 819   resolve_get_put(bytecode, last_frame.get_index_u2(bytecode), m, pool, true /*initialize_holder*/, current);
 820 }
 821 
 822 void InterpreterRuntime::resolve_get_put(Bytecodes::Code bytecode, int field_index,
 823                                          methodHandle& m,
 824                                          constantPoolHandle& pool,
 825                                          bool initialize_holder, TRAPS) {
 826   fieldDescriptor info;
 827   bool is_put    = (bytecode == Bytecodes::_putfield  || bytecode == Bytecodes::_nofast_putfield ||
 828                     bytecode == Bytecodes::_putstatic);
 829   bool is_static = (bytecode == Bytecodes::_getstatic || bytecode == Bytecodes::_putstatic);
 830 
 831   {
 832     JvmtiHideSingleStepping jhss(THREAD);
 833     LinkResolver::resolve_field_access(info, pool, field_index,
 834                                        m, bytecode, initialize_holder, CHECK);
 835   } // end JvmtiHideSingleStepping
 836 
 837   // check if link resolution caused cpCache to be updated
 838   if (pool->resolved_field_entry_at(field_index)->is_resolved(bytecode)) return;
 839 
 840   // compute auxiliary field attributes
 841   TosState state  = as_TosState(info.field_type());
 842 
 843   // Resolution of put instructions on final fields is delayed. That is required so that
 844   // exceptions are thrown at the correct place (when the instruction is actually invoked).
 845   // If we do not resolve an instruction in the current pass, leaving the put_code
 846   // set to zero will cause the next put instruction to the same field to reresolve.
 847 
 848   // Resolution of put instructions to final instance fields with invalid updates (i.e.,
 849   // to final instance fields with updates originating from a method different than <init>)
 850   // is inhibited. A putfield instruction targeting an instance final field must throw
 851   // an IllegalAccessError if the instruction is not in an instance
 852   // initializer method <init>. If resolution were not inhibited, a putfield
 853   // in an initializer method could be resolved in the initializer. Subsequent
 854   // putfield instructions to the same field would then use cached information.
 855   // As a result, those instructions would not pass through the VM. That is,
 856   // checks in resolve_field_access() would not be executed for those instructions
 857   // and the required IllegalAccessError would not be thrown.
 858   //
 859   // Also, we need to delay resolving getstatic and putstatic instructions until the
 860   // class is initialized.  This is required so that access to the static
 861   // field will call the initialization function every time until the class
 862   // is completely initialized ala. in 2.17.5 in JVM Specification.
 863   InstanceKlass* klass = info.field_holder();
 864   bool uninitialized_static = is_static && !klass->is_initialized();
 865   bool has_initialized_final_update = info.field_holder()->major_version() >= 53 &&
 866                                       info.has_initialized_final_update();
 867   assert(!(has_initialized_final_update && !info.access_flags().is_final()), "Fields with initialized final updates must be final");
 868 
 869   Bytecodes::Code get_code = (Bytecodes::Code)0;
 870   Bytecodes::Code put_code = (Bytecodes::Code)0;
 871   if (!uninitialized_static) {
 872     if (is_static) {
 873       get_code = Bytecodes::_getstatic;
 874     } else {
 875       get_code = Bytecodes::_getfield;
 876     }
 877     if ((is_put && !has_initialized_final_update) || !info.access_flags().is_final()) {
 878         put_code = ((is_static) ? Bytecodes::_putstatic : Bytecodes::_putfield);
 879     }
 880   }
 881 
 882   ResolvedFieldEntry* entry = pool->resolved_field_entry_at(field_index);
 883   entry->set_flags(info.access_flags().is_final(), info.access_flags().is_volatile(),
 884                    info.is_flat(), info.is_null_free_inline_type(),
 885                    info.has_null_marker(), info.has_internal_null_marker());
 886 
 887   entry->fill_in(info.field_holder(), info.offset(),
 888                  checked_cast<u2>(info.index()), checked_cast<u1>(state),
 889                  static_cast<u1>(get_code), static_cast<u1>(put_code));
 890 }
 891 
 892 
 893 //------------------------------------------------------------------------------------------------------------------------
 894 // Synchronization
 895 //
 896 // The interpreter's synchronization code is factored out so that it can
 897 // be shared by method invocation and synchronized blocks.
 898 //%note synchronization_3
 899 
 900 //%note monitor_1
 901 JRT_ENTRY_NO_ASYNC(void, InterpreterRuntime::monitorenter(JavaThread* current, BasicObjectLock* elem))
 902 #ifdef ASSERT
 903   current->last_frame().interpreter_frame_verify_monitor(elem);
 904 #endif
 905   Handle h_obj(current, elem->obj());
 906   assert(Universe::heap()->is_in_or_null(h_obj()),
 907          "must be null or an object");
 908   ObjectSynchronizer::enter(h_obj, elem->lock(), current);
 909   assert(Universe::heap()->is_in_or_null(elem->obj()),
 910          "must be null or an object");
 911 #ifdef ASSERT
 912   current->last_frame().interpreter_frame_verify_monitor(elem);
 913 #endif
 914 JRT_END
 915 
 916 JRT_LEAF(void, InterpreterRuntime::monitorexit(BasicObjectLock* elem))
 917   oop obj = elem->obj();
 918   assert(Universe::heap()->is_in(obj), "must be an object");
 919   // The object could become unlocked through a JNI call, which we have no other checks for.
 920   // Give a fatal message if CheckJNICalls. Otherwise we ignore it.
 921   if (obj->is_unlocked()) {
 922     if (CheckJNICalls) {
 923       fatal("Object has been unlocked by JNI");
 924     }
 925     return;
 926   }
 927   ObjectSynchronizer::exit(obj, elem->lock(), JavaThread::current());
 928   // Free entry. If it is not cleared, the exception handling code will try to unlock the monitor
 929   // again at method exit or in the case of an exception.
 930   elem->set_obj(nullptr);
 931 JRT_END
 932 
 933 JRT_ENTRY(void, InterpreterRuntime::throw_illegal_monitor_state_exception(JavaThread* current))
 934   THROW(vmSymbols::java_lang_IllegalMonitorStateException());
 935 JRT_END
 936 
 937 JRT_ENTRY(void, InterpreterRuntime::new_illegal_monitor_state_exception(JavaThread* current))
 938   // Returns an illegal exception to install into the current thread. The
 939   // pending_exception flag is cleared so normal exception handling does not
 940   // trigger. Any current installed exception will be overwritten. This
 941   // method will be called during an exception unwind.
 942 
 943   assert(!HAS_PENDING_EXCEPTION, "no pending exception");
 944   Handle exception(current, current->vm_result());
 945   assert(exception() != nullptr, "vm result should be set");
 946   current->set_vm_result(nullptr); // clear vm result before continuing (may cause memory leaks and assert failures)
 947   exception = get_preinitialized_exception(vmClasses::IllegalMonitorStateException_klass(), CATCH);
 948   current->set_vm_result(exception());
 949 JRT_END
 950 
 951 JRT_ENTRY(void, InterpreterRuntime::throw_identity_exception(JavaThread* current, oopDesc* obj))
 952   Klass* klass = cast_to_oop(obj)->klass();
 953   ResourceMark rm(THREAD);
 954   const char* desc = "Cannot synchronize on an instance of value class ";
 955   const char* className = klass->external_name();
 956   size_t msglen = strlen(desc) + strlen(className) + 1;
 957   char* message = NEW_RESOURCE_ARRAY(char, msglen);
 958   if (nullptr == message) {
 959     // Out of memory: can't create detailed error message
 960     THROW_MSG(vmSymbols::java_lang_IdentityException(), className);
 961   } else {
 962     jio_snprintf(message, msglen, "%s%s", desc, className);
 963     THROW_MSG(vmSymbols::java_lang_IdentityException(), message);
 964   }
 965 JRT_END
 966 
 967 //------------------------------------------------------------------------------------------------------------------------
 968 // Invokes
 969 
 970 JRT_ENTRY(Bytecodes::Code, InterpreterRuntime::get_original_bytecode_at(JavaThread* current, Method* method, address bcp))
 971   return method->orig_bytecode_at(method->bci_from(bcp));
 972 JRT_END
 973 
 974 JRT_ENTRY(void, InterpreterRuntime::set_original_bytecode_at(JavaThread* current, Method* method, address bcp, Bytecodes::Code new_code))
 975   method->set_orig_bytecode_at(method->bci_from(bcp), new_code);
 976 JRT_END
 977 
 978 JRT_ENTRY(void, InterpreterRuntime::_breakpoint(JavaThread* current, Method* method, address bcp))
 979   JvmtiExport::post_raw_breakpoint(current, method, bcp);
 980 JRT_END
 981 
 982 void InterpreterRuntime::resolve_invoke(JavaThread* current, Bytecodes::Code bytecode) {
 983   LastFrameAccessor last_frame(current);
 984   // extract receiver from the outgoing argument list if necessary
 985   Handle receiver(current, nullptr);
 986   if (bytecode == Bytecodes::_invokevirtual || bytecode == Bytecodes::_invokeinterface ||
 987       bytecode == Bytecodes::_invokespecial) {
 988     ResourceMark rm(current);
 989     methodHandle m (current, last_frame.method());
 990     Bytecode_invoke call(m, last_frame.bci());
 991     Symbol* signature = call.signature();
 992     receiver = Handle(current, last_frame.callee_receiver(signature));
 993 
 994     assert(Universe::heap()->is_in_or_null(receiver()),
 995            "sanity check");
 996     assert(receiver.is_null() ||
 997            !Universe::heap()->is_in(receiver->klass()),
 998            "sanity check");
 999   }
1000 
1001   // resolve method
1002   CallInfo info;
1003   constantPoolHandle pool(current, last_frame.method()->constants());
1004 
1005   methodHandle resolved_method;
1006 
1007   int method_index = last_frame.get_index_u2(bytecode);
1008   {
1009     JvmtiHideSingleStepping jhss(current);
1010     JavaThread* THREAD = current; // For exception macros.
1011     LinkResolver::resolve_invoke(info, receiver, pool,
1012                                  method_index, bytecode,
1013                                  THREAD);
1014 
1015     if (HAS_PENDING_EXCEPTION) {
1016       if (ProfileTraps && PENDING_EXCEPTION->klass()->name() == vmSymbols::java_lang_NullPointerException()) {
1017         // Preserve the original exception across the call to note_trap()
1018         PreserveExceptionMark pm(current);
1019         // Recording the trap will help the compiler to potentially recognize this exception as "hot"
1020         note_trap(current, Deoptimization::Reason_null_check);
1021       }
1022       return;
1023     }
1024 
1025     resolved_method = methodHandle(current, info.resolved_method());
1026   } // end JvmtiHideSingleStepping
1027 
1028   update_invoke_cp_cache_entry(info, bytecode, resolved_method, pool, method_index);
1029 }
1030 
1031 void InterpreterRuntime::update_invoke_cp_cache_entry(CallInfo& info, Bytecodes::Code bytecode,
1032                                                       methodHandle& resolved_method,
1033                                                       constantPoolHandle& pool,
1034                                                       int method_index) {
1035   // Don't allow safepoints until the method is cached.
1036   NoSafepointVerifier nsv;
1037 
1038   // check if link resolution caused cpCache to be updated
1039   ConstantPoolCache* cache = pool->cache();
1040   if (cache->resolved_method_entry_at(method_index)->is_resolved(bytecode)) return;
1041 
1042 #ifdef ASSERT
1043   if (bytecode == Bytecodes::_invokeinterface) {
1044     if (resolved_method->method_holder() == vmClasses::Object_klass()) {
1045       // NOTE: THIS IS A FIX FOR A CORNER CASE in the JVM spec
1046       // (see also CallInfo::set_interface for details)
1047       assert(info.call_kind() == CallInfo::vtable_call ||
1048              info.call_kind() == CallInfo::direct_call, "");
1049       assert(resolved_method->is_final() || info.has_vtable_index(),
1050              "should have been set already");
1051     } else if (!resolved_method->has_itable_index()) {
1052       // Resolved something like CharSequence.toString.  Use vtable not itable.
1053       assert(info.call_kind() != CallInfo::itable_call, "");
1054     } else {
1055       // Setup itable entry
1056       assert(info.call_kind() == CallInfo::itable_call, "");
1057       int index = resolved_method->itable_index();
1058       assert(info.itable_index() == index, "");
1059     }
1060   } else if (bytecode == Bytecodes::_invokespecial) {
1061     assert(info.call_kind() == CallInfo::direct_call, "must be direct call");
1062   } else {
1063     assert(info.call_kind() == CallInfo::direct_call ||
1064            info.call_kind() == CallInfo::vtable_call, "");
1065   }
1066 #endif
1067   // Get sender and only set cpCache entry to resolved if it is not an
1068   // interface.  The receiver for invokespecial calls within interface
1069   // methods must be checked for every call.
1070   InstanceKlass* sender = pool->pool_holder();
1071 
1072   switch (info.call_kind()) {
1073   case CallInfo::direct_call:
1074     cache->set_direct_call(bytecode, method_index, resolved_method, sender->is_interface());
1075     break;
1076   case CallInfo::vtable_call:
1077     cache->set_vtable_call(bytecode, method_index, resolved_method, info.vtable_index());
1078     break;
1079   case CallInfo::itable_call:
1080     cache->set_itable_call(
1081       bytecode,
1082       method_index,
1083       info.resolved_klass(),
1084       resolved_method,
1085       info.itable_index());
1086     break;
1087   default:  ShouldNotReachHere();
1088   }
1089 }
1090 
1091 void InterpreterRuntime::cds_resolve_invoke(Bytecodes::Code bytecode, int method_index,
1092                                             constantPoolHandle& pool, TRAPS) {
1093   LinkInfo link_info(pool, method_index, bytecode, CHECK);
1094 
1095   if (!link_info.resolved_klass()->is_instance_klass() || InstanceKlass::cast(link_info.resolved_klass())->is_linked()) {
1096     CallInfo call_info;
1097     switch (bytecode) {
1098       case Bytecodes::_invokevirtual:   LinkResolver::cds_resolve_virtual_call  (call_info, link_info, CHECK); break;
1099       case Bytecodes::_invokeinterface: LinkResolver::cds_resolve_interface_call(call_info, link_info, CHECK); break;
1100       case Bytecodes::_invokespecial:   LinkResolver::cds_resolve_special_call  (call_info, link_info, CHECK); break;
1101 
1102       default: fatal("Unimplemented: %s", Bytecodes::name(bytecode));
1103     }
1104     methodHandle resolved_method(THREAD, call_info.resolved_method());
1105     guarantee(resolved_method->method_holder()->is_linked(), "");
1106     update_invoke_cp_cache_entry(call_info, bytecode, resolved_method, pool, method_index);
1107   } else {
1108     // FIXME: why a shared class is not linked yet?
1109     // Can't link it here since there are no guarantees it'll be prelinked on the next run.
1110     ResourceMark rm;
1111     InstanceKlass* resolved_iklass = InstanceKlass::cast(link_info.resolved_klass());
1112     log_info(cds, resolve)("Not resolved: class not linked: %s %s %s",
1113                            resolved_iklass->is_shared() ? "is_shared" : "",
1114                            resolved_iklass->init_state_name(),
1115                            resolved_iklass->external_name());
1116   }
1117 }
1118 
1119 // First time execution:  Resolve symbols, create a permanent MethodType object.
1120 void InterpreterRuntime::resolve_invokehandle(JavaThread* current) {
1121   const Bytecodes::Code bytecode = Bytecodes::_invokehandle;
1122   LastFrameAccessor last_frame(current);
1123 
1124   // resolve method
1125   CallInfo info;
1126   constantPoolHandle pool(current, last_frame.method()->constants());
1127   int method_index = last_frame.get_index_u2(bytecode);
1128   {
1129     JvmtiHideSingleStepping jhss(current);
1130     JavaThread* THREAD = current; // For exception macros.
1131     LinkResolver::resolve_invoke(info, Handle(), pool,
1132                                  method_index, bytecode,
1133                                  CHECK);
1134   } // end JvmtiHideSingleStepping
1135 
1136   pool->cache()->set_method_handle(method_index, info);
1137 }
1138 
1139 // First time execution:  Resolve symbols, create a permanent CallSite object.
1140 void InterpreterRuntime::resolve_invokedynamic(JavaThread* current) {
1141   LastFrameAccessor last_frame(current);
1142   const Bytecodes::Code bytecode = Bytecodes::_invokedynamic;
1143 
1144   // resolve method
1145   CallInfo info;
1146   constantPoolHandle pool(current, last_frame.method()->constants());
1147   int index = last_frame.get_index_u4(bytecode);
1148   {
1149     JvmtiHideSingleStepping jhss(current);
1150     JavaThread* THREAD = current; // For exception macros.
1151     LinkResolver::resolve_invoke(info, Handle(), pool,
1152                                  index, bytecode, CHECK);
1153   } // end JvmtiHideSingleStepping
1154 
1155   pool->cache()->set_dynamic_call(info, index);
1156 }
1157 
1158 // This function is the interface to the assembly code. It returns the resolved
1159 // cpCache entry.  This doesn't safepoint, but the helper routines safepoint.
1160 // This function will check for redefinition!
1161 JRT_ENTRY(void, InterpreterRuntime::resolve_from_cache(JavaThread* current, Bytecodes::Code bytecode)) {
1162   switch (bytecode) {
1163   case Bytecodes::_getstatic:
1164   case Bytecodes::_putstatic:
1165   case Bytecodes::_getfield:
1166   case Bytecodes::_putfield:
1167     resolve_get_put(current, bytecode);
1168     break;
1169   case Bytecodes::_invokevirtual:
1170   case Bytecodes::_invokespecial:
1171   case Bytecodes::_invokestatic:
1172   case Bytecodes::_invokeinterface:
1173     resolve_invoke(current, bytecode);
1174     break;
1175   case Bytecodes::_invokehandle:
1176     resolve_invokehandle(current);
1177     break;
1178   case Bytecodes::_invokedynamic:
1179     resolve_invokedynamic(current);
1180     break;
1181   default:
1182     fatal("unexpected bytecode: %s", Bytecodes::name(bytecode));
1183     break;
1184   }
1185 }
1186 JRT_END
1187 
1188 //------------------------------------------------------------------------------------------------------------------------
1189 // Miscellaneous
1190 
1191 
1192 nmethod* InterpreterRuntime::frequency_counter_overflow(JavaThread* current, address branch_bcp) {
1193   // Enable WXWrite: the function is called directly by interpreter.
1194   MACOS_AARCH64_ONLY(ThreadWXEnable wx(WXWrite, current));
1195 
1196   // frequency_counter_overflow_inner can throw async exception.
1197   nmethod* nm = frequency_counter_overflow_inner(current, branch_bcp);
1198   assert(branch_bcp != nullptr || nm == nullptr, "always returns null for non OSR requests");
1199   if (branch_bcp != nullptr && nm != nullptr) {
1200     // This was a successful request for an OSR nmethod.  Because
1201     // frequency_counter_overflow_inner ends with a safepoint check,
1202     // nm could have been unloaded so look it up again.  It's unsafe
1203     // to examine nm directly since it might have been freed and used
1204     // for something else.
1205     LastFrameAccessor last_frame(current);
1206     Method* method =  last_frame.method();
1207     int bci = method->bci_from(last_frame.bcp());
1208     nm = method->lookup_osr_nmethod_for(bci, CompLevel_none, false);
1209     BarrierSetNMethod* bs_nm = BarrierSet::barrier_set()->barrier_set_nmethod();
1210     if (nm != nullptr && bs_nm != nullptr) {
1211       // in case the transition passed a safepoint we need to barrier this again
1212       if (!bs_nm->nmethod_osr_entry_barrier(nm)) {
1213         nm = nullptr;
1214       }
1215     }
1216   }
1217   if (nm != nullptr && current->is_interp_only_mode()) {
1218     // Normally we never get an nm if is_interp_only_mode() is true, because
1219     // policy()->event has a check for this and won't compile the method when
1220     // true. However, it's possible for is_interp_only_mode() to become true
1221     // during the compilation. We don't want to return the nm in that case
1222     // because we want to continue to execute interpreted.
1223     nm = nullptr;
1224   }
1225 #ifndef PRODUCT
1226   if (TraceOnStackReplacement) {
1227     if (nm != nullptr) {
1228       tty->print("OSR entry @ pc: " INTPTR_FORMAT ": ", p2i(nm->osr_entry()));
1229       nm->print();
1230     }
1231   }
1232 #endif
1233   return nm;
1234 }
1235 
1236 JRT_ENTRY(nmethod*,
1237           InterpreterRuntime::frequency_counter_overflow_inner(JavaThread* current, address branch_bcp))
1238   // use UnlockFlagSaver to clear and restore the _do_not_unlock_if_synchronized
1239   // flag, in case this method triggers classloading which will call into Java.
1240   UnlockFlagSaver fs(current);
1241 
1242   LastFrameAccessor last_frame(current);
1243   assert(last_frame.is_interpreted_frame(), "must come from interpreter");
1244   methodHandle method(current, last_frame.method());
1245   const int branch_bci = branch_bcp != nullptr ? method->bci_from(branch_bcp) : InvocationEntryBci;
1246   const int bci = branch_bcp != nullptr ? method->bci_from(last_frame.bcp()) : InvocationEntryBci;
1247 
1248   nmethod* osr_nm = CompilationPolicy::event(method, method, branch_bci, bci, CompLevel_none, nullptr, CHECK_NULL);
1249 
1250   BarrierSetNMethod* bs_nm = BarrierSet::barrier_set()->barrier_set_nmethod();
1251   if (osr_nm != nullptr && bs_nm != nullptr) {
1252     if (!bs_nm->nmethod_osr_entry_barrier(osr_nm)) {
1253       osr_nm = nullptr;
1254     }
1255   }
1256   return osr_nm;
1257 JRT_END
1258 
1259 JRT_LEAF(jint, InterpreterRuntime::bcp_to_di(Method* method, address cur_bcp))
1260   assert(ProfileInterpreter, "must be profiling interpreter");
1261   int bci = method->bci_from(cur_bcp);
1262   MethodData* mdo = method->method_data();
1263   if (mdo == nullptr)  return 0;
1264   return mdo->bci_to_di(bci);
1265 JRT_END
1266 
1267 #ifdef ASSERT
1268 JRT_LEAF(void, InterpreterRuntime::verify_mdp(Method* method, address bcp, address mdp))
1269   assert(ProfileInterpreter, "must be profiling interpreter");
1270 
1271   MethodData* mdo = method->method_data();
1272   assert(mdo != nullptr, "must not be null");
1273 
1274   int bci = method->bci_from(bcp);
1275 
1276   address mdp2 = mdo->bci_to_dp(bci);
1277   if (mdp != mdp2) {
1278     ResourceMark rm;
1279     tty->print_cr("FAILED verify : actual mdp %p   expected mdp %p @ bci %d", mdp, mdp2, bci);
1280     int current_di = mdo->dp_to_di(mdp);
1281     int expected_di  = mdo->dp_to_di(mdp2);
1282     tty->print_cr("  actual di %d   expected di %d", current_di, expected_di);
1283     int expected_approx_bci = mdo->data_at(expected_di)->bci();
1284     int approx_bci = -1;
1285     if (current_di >= 0) {
1286       approx_bci = mdo->data_at(current_di)->bci();
1287     }
1288     tty->print_cr("  actual bci is %d  expected bci %d", approx_bci, expected_approx_bci);
1289     mdo->print_on(tty);
1290     method->print_codes();
1291   }
1292   assert(mdp == mdp2, "wrong mdp");
1293 JRT_END
1294 #endif // ASSERT
1295 
1296 JRT_ENTRY(void, InterpreterRuntime::update_mdp_for_ret(JavaThread* current, int return_bci))
1297   assert(ProfileInterpreter, "must be profiling interpreter");
1298   ResourceMark rm(current);
1299   LastFrameAccessor last_frame(current);
1300   assert(last_frame.is_interpreted_frame(), "must come from interpreter");
1301   MethodData* h_mdo = last_frame.method()->method_data();
1302 
1303   // Grab a lock to ensure atomic access to setting the return bci and
1304   // the displacement.  This can block and GC, invalidating all naked oops.
1305   MutexLocker ml(RetData_lock);
1306 
1307   // ProfileData is essentially a wrapper around a derived oop, so we
1308   // need to take the lock before making any ProfileData structures.
1309   ProfileData* data = h_mdo->data_at(h_mdo->dp_to_di(last_frame.mdp()));
1310   guarantee(data != nullptr, "profile data must be valid");
1311   RetData* rdata = data->as_RetData();
1312   address new_mdp = rdata->fixup_ret(return_bci, h_mdo);
1313   last_frame.set_mdp(new_mdp);
1314 JRT_END
1315 
1316 JRT_ENTRY(MethodCounters*, InterpreterRuntime::build_method_counters(JavaThread* current, Method* m))
1317   return Method::build_method_counters(current, m);
1318 JRT_END
1319 
1320 
1321 JRT_ENTRY(void, InterpreterRuntime::at_safepoint(JavaThread* current))
1322   // We used to need an explicit preserve_arguments here for invoke bytecodes. However,
1323   // stack traversal automatically takes care of preserving arguments for invoke, so
1324   // this is no longer needed.
1325 
1326   // JRT_END does an implicit safepoint check, hence we are guaranteed to block
1327   // if this is called during a safepoint
1328 
1329   if (JvmtiExport::should_post_single_step()) {
1330     // This function is called by the interpreter when single stepping. Such single
1331     // stepping could unwind a frame. Then, it is important that we process any frames
1332     // that we might return into.
1333     StackWatermarkSet::before_unwind(current);
1334 
1335     // We are called during regular safepoints and when the VM is
1336     // single stepping. If any thread is marked for single stepping,
1337     // then we may have JVMTI work to do.
1338     LastFrameAccessor last_frame(current);
1339     JvmtiExport::at_single_stepping_point(current, last_frame.method(), last_frame.bcp());
1340   }
1341 JRT_END
1342 
1343 JRT_LEAF(void, InterpreterRuntime::at_unwind(JavaThread* current))
1344   assert(current == JavaThread::current(), "pre-condition");
1345   // This function is called by the interpreter when the return poll found a reason
1346   // to call the VM. The reason could be that we are returning into a not yet safe
1347   // to access frame. We handle that below.
1348   // Note that this path does not check for single stepping, because we do not want
1349   // to single step when unwinding frames for an exception being thrown. Instead,
1350   // such single stepping code will use the safepoint table, which will use the
1351   // InterpreterRuntime::at_safepoint callback.
1352   StackWatermarkSet::before_unwind(current);
1353 JRT_END
1354 
1355 JRT_ENTRY(void, InterpreterRuntime::post_field_access(JavaThread* current, oopDesc* obj,
1356                                                       ResolvedFieldEntry *entry))
1357 
1358   assert(entry->is_valid(), "Invalid ResolvedFieldEntry");
1359   // check the access_flags for the field in the klass
1360 
1361   InstanceKlass* ik = entry->field_holder();
1362   int index = entry->field_index();
1363   if (!ik->field_status(index).is_access_watched()) return;
1364 
1365   bool is_static = (obj == nullptr);
1366   bool is_flat = entry->is_flat();
1367   HandleMark hm(current);
1368 
1369   Handle h_obj;
1370   if (!is_static) {
1371     // non-static field accessors have an object, but we need a handle
1372     h_obj = Handle(current, obj);
1373   }
1374   InstanceKlass* field_holder = entry->field_holder(); // HERE
1375   jfieldID fid = jfieldIDWorkaround::to_jfieldID(field_holder, entry->field_offset(), is_static, is_flat);
1376   LastFrameAccessor last_frame(current);
1377   JvmtiExport::post_field_access(current, last_frame.method(), last_frame.bcp(), field_holder, h_obj, fid);
1378 JRT_END
1379 
1380 JRT_ENTRY(void, InterpreterRuntime::post_field_modification(JavaThread* current, oopDesc* obj,
1381                                                             ResolvedFieldEntry *entry, jvalue *value))
1382 
1383   assert(entry->is_valid(), "Invalid ResolvedFieldEntry");
1384   InstanceKlass* ik = entry->field_holder();
1385 
1386   // check the access_flags for the field in the klass
1387   int index = entry->field_index();
1388   // bail out if field modifications are not watched
1389   if (!ik->field_status(index).is_modification_watched()) return;
1390 
1391   char sig_type = '\0';
1392 
1393   switch((TosState)entry->tos_state()) {
1394     case btos: sig_type = JVM_SIGNATURE_BYTE;    break;
1395     case ztos: sig_type = JVM_SIGNATURE_BOOLEAN; break;
1396     case ctos: sig_type = JVM_SIGNATURE_CHAR;    break;
1397     case stos: sig_type = JVM_SIGNATURE_SHORT;   break;
1398     case itos: sig_type = JVM_SIGNATURE_INT;     break;
1399     case ftos: sig_type = JVM_SIGNATURE_FLOAT;   break;
1400     case atos: sig_type = JVM_SIGNATURE_CLASS;   break;
1401     case ltos: sig_type = JVM_SIGNATURE_LONG;    break;
1402     case dtos: sig_type = JVM_SIGNATURE_DOUBLE;  break;
1403     default:  ShouldNotReachHere(); return;
1404   }
1405 
1406   bool is_static = (obj == nullptr);
1407   bool is_flat = entry->is_flat();
1408 
1409   HandleMark hm(current);
1410   jfieldID fid = jfieldIDWorkaround::to_jfieldID(ik, entry->field_offset(), is_static, is_flat);
1411   jvalue fvalue;
1412 #ifdef _LP64
1413   fvalue = *value;
1414 #else
1415   // Long/double values are stored unaligned and also noncontiguously with
1416   // tagged stacks.  We can't just do a simple assignment even in the non-
1417   // J/D cases because a C++ compiler is allowed to assume that a jvalue is
1418   // 8-byte aligned, and interpreter stack slots are only 4-byte aligned.
1419   // We assume that the two halves of longs/doubles are stored in interpreter
1420   // stack slots in platform-endian order.
1421   jlong_accessor u;
1422   jint* newval = (jint*)value;
1423   u.words[0] = newval[0];
1424   u.words[1] = newval[Interpreter::stackElementWords]; // skip if tag
1425   fvalue.j = u.long_value;
1426 #endif // _LP64
1427 
1428   Handle h_obj;
1429   if (!is_static) {
1430     // non-static field accessors have an object, but we need a handle
1431     h_obj = Handle(current, obj);
1432   }
1433 
1434   LastFrameAccessor last_frame(current);
1435   JvmtiExport::post_raw_field_modification(current, last_frame.method(), last_frame.bcp(), ik, h_obj,
1436                                            fid, sig_type, &fvalue);
1437 JRT_END
1438 
1439 JRT_ENTRY(void, InterpreterRuntime::post_method_entry(JavaThread* current))
1440   LastFrameAccessor last_frame(current);
1441   JvmtiExport::post_method_entry(current, last_frame.method(), last_frame.get_frame());
1442 JRT_END
1443 
1444 
1445 // This is a JRT_BLOCK_ENTRY because we have to stash away the return oop
1446 // before transitioning to VM, and restore it after transitioning back
1447 // to Java. The return oop at the top-of-stack, is not walked by the GC.
1448 JRT_BLOCK_ENTRY(void, InterpreterRuntime::post_method_exit(JavaThread* current))
1449   LastFrameAccessor last_frame(current);
1450   JvmtiExport::post_method_exit(current, last_frame.method(), last_frame.get_frame());
1451 JRT_END
1452 
1453 JRT_LEAF(int, InterpreterRuntime::interpreter_contains(address pc))
1454 {
1455   return (Interpreter::contains(Continuation::get_top_return_pc_post_barrier(JavaThread::current(), pc)) ? 1 : 0);
1456 }
1457 JRT_END
1458 
1459 
1460 // Implementation of SignatureHandlerLibrary
1461 
1462 #ifndef SHARING_FAST_NATIVE_FINGERPRINTS
1463 // Dummy definition (else normalization method is defined in CPU
1464 // dependent code)
1465 uint64_t InterpreterRuntime::normalize_fast_native_fingerprint(uint64_t fingerprint) {
1466   return fingerprint;
1467 }
1468 #endif
1469 
1470 address SignatureHandlerLibrary::set_handler_blob() {
1471   BufferBlob* handler_blob = BufferBlob::create("native signature handlers", blob_size);
1472   if (handler_blob == nullptr) {
1473     return nullptr;
1474   }
1475   address handler = handler_blob->code_begin();
1476   _handler_blob = handler_blob;
1477   _handler = handler;
1478   return handler;
1479 }
1480 
1481 void SignatureHandlerLibrary::initialize() {
1482   if (_fingerprints != nullptr) {
1483     return;
1484   }
1485   if (set_handler_blob() == nullptr) {
1486     vm_exit_out_of_memory(blob_size, OOM_MALLOC_ERROR, "native signature handlers");
1487   }
1488 
1489   BufferBlob* bb = BufferBlob::create("Signature Handler Temp Buffer",
1490                                       SignatureHandlerLibrary::buffer_size);
1491   _buffer = bb->code_begin();
1492 
1493   _fingerprints = new (mtCode) GrowableArray<uint64_t>(32, mtCode);
1494   _handlers     = new (mtCode) GrowableArray<address>(32, mtCode);
1495 }
1496 
1497 address SignatureHandlerLibrary::set_handler(CodeBuffer* buffer) {
1498   address handler   = _handler;
1499   int     insts_size = buffer->pure_insts_size();
1500   if (handler + insts_size > _handler_blob->code_end()) {
1501     // get a new handler blob
1502     handler = set_handler_blob();
1503   }
1504   if (handler != nullptr) {
1505     memcpy(handler, buffer->insts_begin(), insts_size);
1506     pd_set_handler(handler);
1507     ICache::invalidate_range(handler, insts_size);
1508     _handler = handler + insts_size;
1509   }
1510   return handler;
1511 }
1512 
1513 void SignatureHandlerLibrary::add(const methodHandle& method) {
1514   if (method->signature_handler() == nullptr) {
1515     // use slow signature handler if we can't do better
1516     int handler_index = -1;
1517     // check if we can use customized (fast) signature handler
1518     if (UseFastSignatureHandlers && method->size_of_parameters() <= Fingerprinter::fp_max_size_of_parameters) {
1519       // use customized signature handler
1520       MutexLocker mu(SignatureHandlerLibrary_lock);
1521       // make sure data structure is initialized
1522       initialize();
1523       // lookup method signature's fingerprint
1524       uint64_t fingerprint = Fingerprinter(method).fingerprint();
1525       // allow CPU dependent code to optimize the fingerprints for the fast handler
1526       fingerprint = InterpreterRuntime::normalize_fast_native_fingerprint(fingerprint);
1527       handler_index = _fingerprints->find(fingerprint);
1528       // create handler if necessary
1529       if (handler_index < 0) {
1530         ResourceMark rm;
1531         ptrdiff_t align_offset = align_up(_buffer, CodeEntryAlignment) - (address)_buffer;
1532         CodeBuffer buffer((address)(_buffer + align_offset),
1533                           checked_cast<int>(SignatureHandlerLibrary::buffer_size - align_offset));
1534         InterpreterRuntime::SignatureHandlerGenerator(method, &buffer).generate(fingerprint);
1535         // copy into code heap
1536         address handler = set_handler(&buffer);
1537         if (handler == nullptr) {
1538           // use slow signature handler (without memorizing it in the fingerprints)
1539         } else {
1540           // debugging support
1541           if (PrintSignatureHandlers && (handler != Interpreter::slow_signature_handler())) {
1542             ttyLocker ttyl;
1543             tty->cr();
1544             tty->print_cr("argument handler #%d for: %s %s (fingerprint = " UINT64_FORMAT ", %d bytes generated)",
1545                           _handlers->length(),
1546                           (method->is_static() ? "static" : "receiver"),
1547                           method->name_and_sig_as_C_string(),
1548                           fingerprint,
1549                           buffer.insts_size());
1550             if (buffer.insts_size() > 0) {
1551               Disassembler::decode(handler, handler + buffer.insts_size(), tty
1552                                    NOT_PRODUCT(COMMA &buffer.asm_remarks()));
1553             }
1554 #ifndef PRODUCT
1555             address rh_begin = Interpreter::result_handler(method()->result_type());
1556             if (CodeCache::contains(rh_begin)) {
1557               // else it might be special platform dependent values
1558               tty->print_cr(" --- associated result handler ---");
1559               address rh_end = rh_begin;
1560               while (*(int*)rh_end != 0) {
1561                 rh_end += sizeof(int);
1562               }
1563               Disassembler::decode(rh_begin, rh_end);
1564             } else {
1565               tty->print_cr(" associated result handler: " PTR_FORMAT, p2i(rh_begin));
1566             }
1567 #endif
1568           }
1569           // add handler to library
1570           _fingerprints->append(fingerprint);
1571           _handlers->append(handler);
1572           // set handler index
1573           assert(_fingerprints->length() == _handlers->length(), "sanity check");
1574           handler_index = _fingerprints->length() - 1;
1575         }
1576       }
1577       // Set handler under SignatureHandlerLibrary_lock
1578       if (handler_index < 0) {
1579         // use generic signature handler
1580         method->set_signature_handler(Interpreter::slow_signature_handler());
1581       } else {
1582         // set handler
1583         method->set_signature_handler(_handlers->at(handler_index));
1584       }
1585     } else {
1586       DEBUG_ONLY(JavaThread::current()->check_possible_safepoint());
1587       // use generic signature handler
1588       method->set_signature_handler(Interpreter::slow_signature_handler());
1589     }
1590   }
1591 #ifdef ASSERT
1592   int handler_index = -1;
1593   int fingerprint_index = -2;
1594   {
1595     // '_handlers' and '_fingerprints' are 'GrowableArray's and are NOT synchronized
1596     // in any way if accessed from multiple threads. To avoid races with another
1597     // thread which may change the arrays in the above, mutex protected block, we
1598     // have to protect this read access here with the same mutex as well!
1599     MutexLocker mu(SignatureHandlerLibrary_lock);
1600     if (_handlers != nullptr) {
1601       handler_index = _handlers->find(method->signature_handler());
1602       uint64_t fingerprint = Fingerprinter(method).fingerprint();
1603       fingerprint = InterpreterRuntime::normalize_fast_native_fingerprint(fingerprint);
1604       fingerprint_index = _fingerprints->find(fingerprint);
1605     }
1606   }
1607   assert(method->signature_handler() == Interpreter::slow_signature_handler() ||
1608          handler_index == fingerprint_index, "sanity check");
1609 #endif // ASSERT
1610 }
1611 
1612 void SignatureHandlerLibrary::add(uint64_t fingerprint, address handler) {
1613   int handler_index = -1;
1614   // use customized signature handler
1615   MutexLocker mu(SignatureHandlerLibrary_lock);
1616   // make sure data structure is initialized
1617   initialize();
1618   fingerprint = InterpreterRuntime::normalize_fast_native_fingerprint(fingerprint);
1619   handler_index = _fingerprints->find(fingerprint);
1620   // create handler if necessary
1621   if (handler_index < 0) {
1622     if (PrintSignatureHandlers && (handler != Interpreter::slow_signature_handler())) {
1623       tty->cr();
1624       tty->print_cr("argument handler #%d at " PTR_FORMAT " for fingerprint " UINT64_FORMAT,
1625                     _handlers->length(),
1626                     p2i(handler),
1627                     fingerprint);
1628     }
1629     _fingerprints->append(fingerprint);
1630     _handlers->append(handler);
1631   } else {
1632     if (PrintSignatureHandlers) {
1633       tty->cr();
1634       tty->print_cr("duplicate argument handler #%d for fingerprint " UINT64_FORMAT "(old: " PTR_FORMAT ", new : " PTR_FORMAT ")",
1635                     _handlers->length(),
1636                     fingerprint,
1637                     p2i(_handlers->at(handler_index)),
1638                     p2i(handler));
1639     }
1640   }
1641 }
1642 
1643 
1644 BufferBlob*              SignatureHandlerLibrary::_handler_blob = nullptr;
1645 address                  SignatureHandlerLibrary::_handler      = nullptr;
1646 GrowableArray<uint64_t>* SignatureHandlerLibrary::_fingerprints = nullptr;
1647 GrowableArray<address>*  SignatureHandlerLibrary::_handlers     = nullptr;
1648 address                  SignatureHandlerLibrary::_buffer       = nullptr;
1649 
1650 
1651 JRT_ENTRY(void, InterpreterRuntime::prepare_native_call(JavaThread* current, Method* method))
1652   methodHandle m(current, method);
1653   assert(m->is_native(), "sanity check");
1654   // lookup native function entry point if it doesn't exist
1655   if (!m->has_native_function()) {
1656     NativeLookup::lookup(m, CHECK);
1657   }
1658   // make sure signature handler is installed
1659   SignatureHandlerLibrary::add(m);
1660   // The interpreter entry point checks the signature handler first,
1661   // before trying to fetch the native entry point and klass mirror.
1662   // We must set the signature handler last, so that multiple processors
1663   // preparing the same method will be sure to see non-null entry & mirror.
1664 JRT_END
1665 
1666 #if defined(IA32) || defined(AMD64) || defined(ARM)
1667 JRT_LEAF(void, InterpreterRuntime::popframe_move_outgoing_args(JavaThread* current, void* src_address, void* dest_address))
1668   assert(current == JavaThread::current(), "pre-condition");
1669   if (src_address == dest_address) {
1670     return;
1671   }
1672   ResourceMark rm;
1673   LastFrameAccessor last_frame(current);
1674   assert(last_frame.is_interpreted_frame(), "");
1675   jint bci = last_frame.bci();
1676   methodHandle mh(current, last_frame.method());
1677   Bytecode_invoke invoke(mh, bci);
1678   ArgumentSizeComputer asc(invoke.signature());
1679   int size_of_arguments = (asc.size() + (invoke.has_receiver() ? 1 : 0)); // receiver
1680   Copy::conjoint_jbytes(src_address, dest_address,
1681                        size_of_arguments * Interpreter::stackElementSize);
1682 JRT_END
1683 #endif
1684 
1685 #if INCLUDE_JVMTI
1686 // This is a support of the JVMTI PopFrame interface.
1687 // Make sure it is an invokestatic of a polymorphic intrinsic that has a member_name argument
1688 // and return it as a vm_result so that it can be reloaded in the list of invokestatic parameters.
1689 // The member_name argument is a saved reference (in local#0) to the member_name.
1690 // For backward compatibility with some JDK versions (7, 8) it can also be a direct method handle.
1691 // FIXME: remove DMH case after j.l.i.InvokerBytecodeGenerator code shape is updated.
1692 JRT_ENTRY(void, InterpreterRuntime::member_name_arg_or_null(JavaThread* current, address member_name,
1693                                                             Method* method, address bcp))
1694   Bytecodes::Code code = Bytecodes::code_at(method, bcp);
1695   if (code != Bytecodes::_invokestatic) {
1696     return;
1697   }
1698   ConstantPool* cpool = method->constants();
1699   int cp_index = Bytes::get_native_u2(bcp + 1);
1700   Symbol* cname = cpool->klass_name_at(cpool->klass_ref_index_at(cp_index, code));
1701   Symbol* mname = cpool->name_ref_at(cp_index, code);
1702 
1703   if (MethodHandles::has_member_arg(cname, mname)) {
1704     oop member_name_oop = cast_to_oop(member_name);
1705     if (java_lang_invoke_DirectMethodHandle::is_instance(member_name_oop)) {
1706       // FIXME: remove after j.l.i.InvokerBytecodeGenerator code shape is updated.
1707       member_name_oop = java_lang_invoke_DirectMethodHandle::member(member_name_oop);
1708     }
1709     current->set_vm_result(member_name_oop);
1710   } else {
1711     current->set_vm_result(nullptr);
1712   }
1713 JRT_END
1714 #endif // INCLUDE_JVMTI
1715 
1716 #ifndef PRODUCT
1717 // This must be a JRT_LEAF function because the interpreter must save registers on x86 to
1718 // call this, which changes rsp and makes the interpreter's expression stack not walkable.
1719 // The generated code still uses call_VM because that will set up the frame pointer for
1720 // bcp and method.
1721 JRT_LEAF(intptr_t, InterpreterRuntime::trace_bytecode(JavaThread* current, intptr_t preserve_this_value, intptr_t tos, intptr_t tos2))
1722   assert(current == JavaThread::current(), "pre-condition");
1723   LastFrameAccessor last_frame(current);
1724   assert(last_frame.is_interpreted_frame(), "must be an interpreted frame");
1725   methodHandle mh(current, last_frame.method());
1726   BytecodeTracer::trace_interpreter(mh, last_frame.bcp(), tos, tos2);
1727   return preserve_this_value;
1728 JRT_END
1729 #endif // !PRODUCT