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