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