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