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