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