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