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