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