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