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