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