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