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