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