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