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