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