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