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