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