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