interpreterRuntime.cpp revision 6760:22b98ab2a69f
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
65PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC
66
67class 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
85void 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
102IRT_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);
112IRT_END
113
114IRT_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}
131IRT_END
132
133
134//------------------------------------------------------------------------------------------------------------------------
135// Allocation
136
137IRT_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);
163IRT_END
164
165
166IRT_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);
169IRT_END
170
171
172IRT_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);
179IRT_END
180
181
182IRT_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);
206IRT_END
207
208
209IRT_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);
213IRT_END
214
215
216// Quicken instance-of and check-cast bytecodes
217IRT_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);
227IRT_END
228
229
230//------------------------------------------------------------------------------------------------------------------------
231// Exceptions
232
233void 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.
257void 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.
266IRT_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);
269IRT_END
270
271// Class Deoptimization is not visible in BytecodeInterpreter, so we need a wrapper
272// for each exception.
273void InterpreterRuntime::note_nullCheck_trap(JavaThread* thread, Method *method, int trap_bci)
274  { if (ProfileTraps) note_trap(thread, Deoptimization::Reason_null_check, method, trap_bci); }
275void InterpreterRuntime::note_div0Check_trap(JavaThread* thread, Method *method, int trap_bci)
276  { if (ProfileTraps) note_trap(thread, Deoptimization::Reason_div0_check, method, trap_bci); }
277void InterpreterRuntime::note_rangeCheck_trap(JavaThread* thread, Method *method, int trap_bci)
278  { if (ProfileTraps) note_trap(thread, Deoptimization::Reason_range_check, method, trap_bci); }
279void InterpreterRuntime::note_classCheck_trap(JavaThread* thread, Method *method, int trap_bci)
280  { if (ProfileTraps) note_trap(thread, Deoptimization::Reason_class_check, method, trap_bci); }
281void 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
286static 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).
306IRT_ENTRY(void, InterpreterRuntime::throw_StackOverflowError(JavaThread* thread))
307  Handle exception = get_preinitialized_exception(
308                                 SystemDictionary::StackOverflowError_klass(),
309                                 CHECK);
310  THROW_HANDLE(exception);
311IRT_END
312
313
314IRT_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());
327IRT_END
328
329
330IRT_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());
341IRT_END
342
343
344IRT_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);
354IRT_END
355
356IRT_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);
369IRT_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).
379IRT_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      ttyLocker ttyl;
420      ResourceMark rm(thread);
421      tty->print_cr("Exception <%s> (" INTPTR_FORMAT ")", h_exception->print_value_string(), (address)h_exception());
422      tty->print_cr(" thrown in interpreter method <%s>", h_method->print_value_string());
423      tty->print_cr(" at bci %d for thread " INTPTR_FORMAT, current_bci, thread);
424    }
425// Don't go paging in something which won't be used.
426//     else if (extable->length() == 0) {
427//       // disabled for now - interpreter is not using shortcut yet
428//       // (shortcut is not to call runtime if we have no exception handlers)
429//       // warning("performance bug: should not call runtime if method has no exception handlers");
430//     }
431    // for AbortVMOnException flag
432    NOT_PRODUCT(Exceptions::debug_check_abort(h_exception));
433
434    // exception handler lookup
435    KlassHandle h_klass(THREAD, h_exception->klass());
436    handler_bci = Method::fast_exception_handler_bci_for(h_method, h_klass, current_bci, THREAD);
437    if (HAS_PENDING_EXCEPTION) {
438      // We threw an exception while trying to find the exception handler.
439      // Transfer the new exception to the exception handle which will
440      // be set into thread local storage, and do another lookup for an
441      // exception handler for this exception, this time starting at the
442      // BCI of the exception handler which caused the exception to be
443      // thrown (bug 4307310).
444      h_exception = Handle(THREAD, PENDING_EXCEPTION);
445      CLEAR_PENDING_EXCEPTION;
446      if (handler_bci >= 0) {
447        current_bci = handler_bci;
448        should_repeat = true;
449      }
450    }
451  } while (should_repeat == true);
452
453  // notify JVMTI of an exception throw; JVMTI will detect if this is a first
454  // time throw or a stack unwinding throw and accordingly notify the debugger
455  if (JvmtiExport::can_post_on_exceptions()) {
456    JvmtiExport::post_exception_throw(thread, h_method(), bcp(thread), h_exception());
457  }
458
459#ifdef CC_INTERP
460  address continuation = (address)(intptr_t) handler_bci;
461#else
462  address continuation = NULL;
463#endif
464  address handler_pc = NULL;
465  if (handler_bci < 0 || !thread->reguard_stack((address) &continuation)) {
466    // Forward exception to callee (leaving bci/bcp untouched) because (a) no
467    // handler in this method, or (b) after a stack overflow there is not yet
468    // enough stack space available to reprotect the stack.
469#ifndef CC_INTERP
470    continuation = Interpreter::remove_activation_entry();
471#endif
472    // Count this for compilation purposes
473    h_method->interpreter_throwout_increment(THREAD);
474  } else {
475    // handler in this method => change bci/bcp to handler bci/bcp and continue there
476    handler_pc = h_method->code_base() + handler_bci;
477#ifndef CC_INTERP
478    set_bcp_and_mdp(handler_pc, thread);
479    continuation = Interpreter::dispatch_table(vtos)[*handler_pc];
480#endif
481  }
482  // notify debugger of an exception catch
483  // (this is good for exceptions caught in native methods as well)
484  if (JvmtiExport::can_post_on_exceptions()) {
485    JvmtiExport::notice_unwind_due_to_exception(thread, h_method(), handler_pc, h_exception(), (handler_pc != NULL));
486  }
487
488  thread->set_vm_result(h_exception());
489  return continuation;
490IRT_END
491
492
493IRT_ENTRY(void, InterpreterRuntime::throw_pending_exception(JavaThread* thread))
494  assert(thread->has_pending_exception(), "must only ne called if there's an exception pending");
495  // nothing to do - eventually we should remove this code entirely (see comments @ call sites)
496IRT_END
497
498
499IRT_ENTRY(void, InterpreterRuntime::throw_AbstractMethodError(JavaThread* thread))
500  THROW(vmSymbols::java_lang_AbstractMethodError());
501IRT_END
502
503
504IRT_ENTRY(void, InterpreterRuntime::throw_IncompatibleClassChangeError(JavaThread* thread))
505  THROW(vmSymbols::java_lang_IncompatibleClassChangeError());
506IRT_END
507
508
509//------------------------------------------------------------------------------------------------------------------------
510// Fields
511//
512
513IRT_ENTRY(void, InterpreterRuntime::resolve_get_put(JavaThread* thread, Bytecodes::Code bytecode))
514  // resolve field
515  fieldDescriptor info;
516  constantPoolHandle pool(thread, method(thread)->constants());
517  bool is_put    = (bytecode == Bytecodes::_putfield  || bytecode == Bytecodes::_putstatic);
518  bool is_static = (bytecode == Bytecodes::_getstatic || bytecode == Bytecodes::_putstatic);
519
520  {
521    JvmtiHideSingleStepping jhss(thread);
522    LinkResolver::resolve_field_access(info, pool, get_index_u2_cpcache(thread, bytecode),
523                                       bytecode, CHECK);
524  } // end JvmtiHideSingleStepping
525
526  // check if link resolution caused cpCache to be updated
527  if (already_resolved(thread)) return;
528
529  // compute auxiliary field attributes
530  TosState state  = as_TosState(info.field_type());
531
532  // We need to delay resolving put instructions on final fields
533  // until we actually invoke one. This is required so we throw
534  // exceptions at the correct place. If we do not resolve completely
535  // in the current pass, leaving the put_code set to zero will
536  // cause the next put instruction to reresolve.
537  Bytecodes::Code put_code = (Bytecodes::Code)0;
538
539  // We also need to delay resolving getstatic instructions until the
540  // class is intitialized.  This is required so that access to the static
541  // field will call the initialization function every time until the class
542  // is completely initialized ala. in 2.17.5 in JVM Specification.
543  InstanceKlass* klass = InstanceKlass::cast(info.field_holder());
544  bool uninitialized_static = ((bytecode == Bytecodes::_getstatic || bytecode == Bytecodes::_putstatic) &&
545                               !klass->is_initialized());
546  Bytecodes::Code get_code = (Bytecodes::Code)0;
547
548  if (!uninitialized_static) {
549    get_code = ((is_static) ? Bytecodes::_getstatic : Bytecodes::_getfield);
550    if (is_put || !info.access_flags().is_final()) {
551      put_code = ((is_static) ? Bytecodes::_putstatic : Bytecodes::_putfield);
552    }
553  }
554
555  cache_entry(thread)->set_field(
556    get_code,
557    put_code,
558    info.field_holder(),
559    info.index(),
560    info.offset(),
561    state,
562    info.access_flags().is_final(),
563    info.access_flags().is_volatile(),
564    pool->pool_holder()
565  );
566IRT_END
567
568
569//------------------------------------------------------------------------------------------------------------------------
570// Synchronization
571//
572// The interpreter's synchronization code is factored out so that it can
573// be shared by method invocation and synchronized blocks.
574//%note synchronization_3
575
576//%note monitor_1
577IRT_ENTRY_NO_ASYNC(void, InterpreterRuntime::monitorenter(JavaThread* thread, BasicObjectLock* elem))
578#ifdef ASSERT
579  thread->last_frame().interpreter_frame_verify_monitor(elem);
580#endif
581  if (PrintBiasedLockingStatistics) {
582    Atomic::inc(BiasedLocking::slow_path_entry_count_addr());
583  }
584  Handle h_obj(thread, elem->obj());
585  assert(Universe::heap()->is_in_reserved_or_null(h_obj()),
586         "must be NULL or an object");
587  if (UseBiasedLocking) {
588    // Retry fast entry if bias is revoked to avoid unnecessary inflation
589    ObjectSynchronizer::fast_enter(h_obj, elem->lock(), true, CHECK);
590  } else {
591    ObjectSynchronizer::slow_enter(h_obj, elem->lock(), CHECK);
592  }
593  assert(Universe::heap()->is_in_reserved_or_null(elem->obj()),
594         "must be NULL or an object");
595#ifdef ASSERT
596  thread->last_frame().interpreter_frame_verify_monitor(elem);
597#endif
598IRT_END
599
600
601//%note monitor_1
602IRT_ENTRY_NO_ASYNC(void, InterpreterRuntime::monitorexit(JavaThread* thread, BasicObjectLock* elem))
603#ifdef ASSERT
604  thread->last_frame().interpreter_frame_verify_monitor(elem);
605#endif
606  Handle h_obj(thread, elem->obj());
607  assert(Universe::heap()->is_in_reserved_or_null(h_obj()),
608         "must be NULL or an object");
609  if (elem == NULL || h_obj()->is_unlocked()) {
610    THROW(vmSymbols::java_lang_IllegalMonitorStateException());
611  }
612  ObjectSynchronizer::slow_exit(h_obj(), elem->lock(), thread);
613  // Free entry. This must be done here, since a pending exception might be installed on
614  // exit. If it is not cleared, the exception handling code will try to unlock the monitor again.
615  elem->set_obj(NULL);
616#ifdef ASSERT
617  thread->last_frame().interpreter_frame_verify_monitor(elem);
618#endif
619IRT_END
620
621
622IRT_ENTRY(void, InterpreterRuntime::throw_illegal_monitor_state_exception(JavaThread* thread))
623  THROW(vmSymbols::java_lang_IllegalMonitorStateException());
624IRT_END
625
626
627IRT_ENTRY(void, InterpreterRuntime::new_illegal_monitor_state_exception(JavaThread* thread))
628  // Returns an illegal exception to install into the current thread. The
629  // pending_exception flag is cleared so normal exception handling does not
630  // trigger. Any current installed exception will be overwritten. This
631  // method will be called during an exception unwind.
632
633  assert(!HAS_PENDING_EXCEPTION, "no pending exception");
634  Handle exception(thread, thread->vm_result());
635  assert(exception() != NULL, "vm result should be set");
636  thread->set_vm_result(NULL); // clear vm result before continuing (may cause memory leaks and assert failures)
637  if (!exception->is_a(SystemDictionary::ThreadDeath_klass())) {
638    exception = get_preinitialized_exception(
639                       SystemDictionary::IllegalMonitorStateException_klass(),
640                       CATCH);
641  }
642  thread->set_vm_result(exception());
643IRT_END
644
645
646//------------------------------------------------------------------------------------------------------------------------
647// Invokes
648
649IRT_ENTRY(Bytecodes::Code, InterpreterRuntime::get_original_bytecode_at(JavaThread* thread, Method* method, address bcp))
650  return method->orig_bytecode_at(method->bci_from(bcp));
651IRT_END
652
653IRT_ENTRY(void, InterpreterRuntime::set_original_bytecode_at(JavaThread* thread, Method* method, address bcp, Bytecodes::Code new_code))
654  method->set_orig_bytecode_at(method->bci_from(bcp), new_code);
655IRT_END
656
657IRT_ENTRY(void, InterpreterRuntime::_breakpoint(JavaThread* thread, Method* method, address bcp))
658  JvmtiExport::post_raw_breakpoint(thread, method, bcp);
659IRT_END
660
661IRT_ENTRY(void, InterpreterRuntime::resolve_invoke(JavaThread* thread, Bytecodes::Code bytecode)) {
662  // extract receiver from the outgoing argument list if necessary
663  Handle receiver(thread, NULL);
664  if (bytecode == Bytecodes::_invokevirtual || bytecode == Bytecodes::_invokeinterface) {
665    ResourceMark rm(thread);
666    methodHandle m (thread, method(thread));
667    Bytecode_invoke call(m, bci(thread));
668    Symbol* signature = call.signature();
669    receiver = Handle(thread,
670                  thread->last_frame().interpreter_callee_receiver(signature));
671    assert(Universe::heap()->is_in_reserved_or_null(receiver()),
672           "sanity check");
673    assert(receiver.is_null() ||
674           !Universe::heap()->is_in_reserved(receiver->klass()),
675           "sanity check");
676  }
677
678  // resolve method
679  CallInfo info;
680  constantPoolHandle pool(thread, method(thread)->constants());
681
682  {
683    JvmtiHideSingleStepping jhss(thread);
684    LinkResolver::resolve_invoke(info, receiver, pool,
685                                 get_index_u2_cpcache(thread, bytecode), bytecode, CHECK);
686    if (JvmtiExport::can_hotswap_or_post_breakpoint()) {
687      int retry_count = 0;
688      while (info.resolved_method()->is_old()) {
689        // It is very unlikely that method is redefined more than 100 times
690        // in the middle of resolve. If it is looping here more than 100 times
691        // means then there could be a bug here.
692        guarantee((retry_count++ < 100),
693                  "Could not resolve to latest version of redefined method");
694        // method is redefined in the middle of resolve so re-try.
695        LinkResolver::resolve_invoke(info, receiver, pool,
696                                     get_index_u2_cpcache(thread, bytecode), bytecode, CHECK);
697      }
698    }
699  } // end JvmtiHideSingleStepping
700
701  // check if link resolution caused cpCache to be updated
702  if (already_resolved(thread)) return;
703
704  if (bytecode == Bytecodes::_invokeinterface) {
705    if (TraceItables && Verbose) {
706      ResourceMark rm(thread);
707      tty->print_cr("Resolving: klass: %s to method: %s", info.resolved_klass()->name()->as_C_string(), info.resolved_method()->name()->as_C_string());
708    }
709  }
710#ifdef ASSERT
711  if (bytecode == Bytecodes::_invokeinterface) {
712    if (info.resolved_method()->method_holder() ==
713                                            SystemDictionary::Object_klass()) {
714      // NOTE: THIS IS A FIX FOR A CORNER CASE in the JVM spec
715      // (see also CallInfo::set_interface for details)
716      assert(info.call_kind() == CallInfo::vtable_call ||
717             info.call_kind() == CallInfo::direct_call, "");
718      methodHandle rm = info.resolved_method();
719      assert(rm->is_final() || info.has_vtable_index(),
720             "should have been set already");
721    } else if (!info.resolved_method()->has_itable_index()) {
722      // Resolved something like CharSequence.toString.  Use vtable not itable.
723      assert(info.call_kind() != CallInfo::itable_call, "");
724    } else {
725      // Setup itable entry
726      assert(info.call_kind() == CallInfo::itable_call, "");
727      int index = info.resolved_method()->itable_index();
728      assert(info.itable_index() == index, "");
729    }
730  } else {
731    assert(info.call_kind() == CallInfo::direct_call ||
732           info.call_kind() == CallInfo::vtable_call, "");
733  }
734#endif
735  switch (info.call_kind()) {
736  case CallInfo::direct_call:
737    cache_entry(thread)->set_direct_call(
738      bytecode,
739      info.resolved_method());
740    break;
741  case CallInfo::vtable_call:
742    cache_entry(thread)->set_vtable_call(
743      bytecode,
744      info.resolved_method(),
745      info.vtable_index());
746    break;
747  case CallInfo::itable_call:
748    cache_entry(thread)->set_itable_call(
749      bytecode,
750      info.resolved_method(),
751      info.itable_index());
752    break;
753  default:  ShouldNotReachHere();
754  }
755}
756IRT_END
757
758
759// First time execution:  Resolve symbols, create a permanent MethodType object.
760IRT_ENTRY(void, InterpreterRuntime::resolve_invokehandle(JavaThread* thread)) {
761  const Bytecodes::Code bytecode = Bytecodes::_invokehandle;
762
763  // resolve method
764  CallInfo info;
765  constantPoolHandle pool(thread, method(thread)->constants());
766
767  {
768    JvmtiHideSingleStepping jhss(thread);
769    LinkResolver::resolve_invoke(info, Handle(), pool,
770                                 get_index_u2_cpcache(thread, bytecode), bytecode, CHECK);
771  } // end JvmtiHideSingleStepping
772
773  cache_entry(thread)->set_method_handle(pool, info);
774}
775IRT_END
776
777
778// First time execution:  Resolve symbols, create a permanent CallSite object.
779IRT_ENTRY(void, InterpreterRuntime::resolve_invokedynamic(JavaThread* thread)) {
780  const Bytecodes::Code bytecode = Bytecodes::_invokedynamic;
781
782  //TO DO: consider passing BCI to Java.
783  //  int caller_bci = method(thread)->bci_from(bcp(thread));
784
785  // resolve method
786  CallInfo info;
787  constantPoolHandle pool(thread, method(thread)->constants());
788  int index = get_index_u4(thread, bytecode);
789  {
790    JvmtiHideSingleStepping jhss(thread);
791    LinkResolver::resolve_invoke(info, Handle(), pool,
792                                 index, bytecode, CHECK);
793  } // end JvmtiHideSingleStepping
794
795  ConstantPoolCacheEntry* cp_cache_entry = pool->invokedynamic_cp_cache_entry_at(index);
796  cp_cache_entry->set_dynamic_call(pool, info);
797}
798IRT_END
799
800
801//------------------------------------------------------------------------------------------------------------------------
802// Miscellaneous
803
804
805nmethod* InterpreterRuntime::frequency_counter_overflow(JavaThread* thread, address branch_bcp) {
806  nmethod* nm = frequency_counter_overflow_inner(thread, branch_bcp);
807  assert(branch_bcp != NULL || nm == NULL, "always returns null for non OSR requests");
808  if (branch_bcp != NULL && nm != NULL) {
809    // This was a successful request for an OSR nmethod.  Because
810    // frequency_counter_overflow_inner ends with a safepoint check,
811    // nm could have been unloaded so look it up again.  It's unsafe
812    // to examine nm directly since it might have been freed and used
813    // for something else.
814    frame fr = thread->last_frame();
815    Method* method =  fr.interpreter_frame_method();
816    int bci = method->bci_from(fr.interpreter_frame_bcp());
817    nm = method->lookup_osr_nmethod_for(bci, CompLevel_none, false);
818  }
819#ifndef PRODUCT
820  if (TraceOnStackReplacement) {
821    if (nm != NULL) {
822      tty->print("OSR entry @ pc: " INTPTR_FORMAT ": ", nm->osr_entry());
823      nm->print();
824    }
825  }
826#endif
827  return nm;
828}
829
830IRT_ENTRY(nmethod*,
831          InterpreterRuntime::frequency_counter_overflow_inner(JavaThread* thread, address branch_bcp))
832  // use UnlockFlagSaver to clear and restore the _do_not_unlock_if_synchronized
833  // flag, in case this method triggers classloading which will call into Java.
834  UnlockFlagSaver fs(thread);
835
836  frame fr = thread->last_frame();
837  assert(fr.is_interpreted_frame(), "must come from interpreter");
838  methodHandle method(thread, fr.interpreter_frame_method());
839  const int branch_bci = branch_bcp != NULL ? method->bci_from(branch_bcp) : InvocationEntryBci;
840  const int bci = branch_bcp != NULL ? method->bci_from(fr.interpreter_frame_bcp()) : InvocationEntryBci;
841
842  assert(!HAS_PENDING_EXCEPTION, "Should not have any exceptions pending");
843  nmethod* osr_nm = CompilationPolicy::policy()->event(method, method, branch_bci, bci, CompLevel_none, NULL, thread);
844  assert(!HAS_PENDING_EXCEPTION, "Event handler should not throw any exceptions");
845
846  if (osr_nm != NULL) {
847    // We may need to do on-stack replacement which requires that no
848    // monitors in the activation are biased because their
849    // BasicObjectLocks will need to migrate during OSR. Force
850    // unbiasing of all monitors in the activation now (even though
851    // the OSR nmethod might be invalidated) because we don't have a
852    // safepoint opportunity later once the migration begins.
853    if (UseBiasedLocking) {
854      ResourceMark rm;
855      GrowableArray<Handle>* objects_to_revoke = new GrowableArray<Handle>();
856      for( BasicObjectLock *kptr = fr.interpreter_frame_monitor_end();
857           kptr < fr.interpreter_frame_monitor_begin();
858           kptr = fr.next_monitor_in_interpreter_frame(kptr) ) {
859        if( kptr->obj() != NULL ) {
860          objects_to_revoke->append(Handle(THREAD, kptr->obj()));
861        }
862      }
863      BiasedLocking::revoke(objects_to_revoke);
864    }
865  }
866  return osr_nm;
867IRT_END
868
869IRT_LEAF(jint, InterpreterRuntime::bcp_to_di(Method* method, address cur_bcp))
870  assert(ProfileInterpreter, "must be profiling interpreter");
871  int bci = method->bci_from(cur_bcp);
872  MethodData* mdo = method->method_data();
873  if (mdo == NULL)  return 0;
874  return mdo->bci_to_di(bci);
875IRT_END
876
877IRT_ENTRY(void, InterpreterRuntime::profile_method(JavaThread* thread))
878  // use UnlockFlagSaver to clear and restore the _do_not_unlock_if_synchronized
879  // flag, in case this method triggers classloading which will call into Java.
880  UnlockFlagSaver fs(thread);
881
882  assert(ProfileInterpreter, "must be profiling interpreter");
883  frame fr = thread->last_frame();
884  assert(fr.is_interpreted_frame(), "must come from interpreter");
885  methodHandle method(thread, fr.interpreter_frame_method());
886  Method::build_interpreter_method_data(method, THREAD);
887  if (HAS_PENDING_EXCEPTION) {
888    assert((PENDING_EXCEPTION->is_a(SystemDictionary::OutOfMemoryError_klass())), "we expect only an OOM error here");
889    CLEAR_PENDING_EXCEPTION;
890    // and fall through...
891  }
892IRT_END
893
894
895#ifdef ASSERT
896IRT_LEAF(void, InterpreterRuntime::verify_mdp(Method* method, address bcp, address mdp))
897  assert(ProfileInterpreter, "must be profiling interpreter");
898
899  MethodData* mdo = method->method_data();
900  assert(mdo != NULL, "must not be null");
901
902  int bci = method->bci_from(bcp);
903
904  address mdp2 = mdo->bci_to_dp(bci);
905  if (mdp != mdp2) {
906    ResourceMark rm;
907    ResetNoHandleMark rnm; // In a LEAF entry.
908    HandleMark hm;
909    tty->print_cr("FAILED verify : actual mdp %p   expected mdp %p @ bci %d", mdp, mdp2, bci);
910    int current_di = mdo->dp_to_di(mdp);
911    int expected_di  = mdo->dp_to_di(mdp2);
912    tty->print_cr("  actual di %d   expected di %d", current_di, expected_di);
913    int expected_approx_bci = mdo->data_at(expected_di)->bci();
914    int approx_bci = -1;
915    if (current_di >= 0) {
916      approx_bci = mdo->data_at(current_di)->bci();
917    }
918    tty->print_cr("  actual bci is %d  expected bci %d", approx_bci, expected_approx_bci);
919    mdo->print_on(tty);
920    method->print_codes();
921  }
922  assert(mdp == mdp2, "wrong mdp");
923IRT_END
924#endif // ASSERT
925
926IRT_ENTRY(void, InterpreterRuntime::update_mdp_for_ret(JavaThread* thread, int return_bci))
927  assert(ProfileInterpreter, "must be profiling interpreter");
928  ResourceMark rm(thread);
929  HandleMark hm(thread);
930  frame fr = thread->last_frame();
931  assert(fr.is_interpreted_frame(), "must come from interpreter");
932  MethodData* h_mdo = fr.interpreter_frame_method()->method_data();
933
934  // Grab a lock to ensure atomic access to setting the return bci and
935  // the displacement.  This can block and GC, invalidating all naked oops.
936  MutexLocker ml(RetData_lock);
937
938  // ProfileData is essentially a wrapper around a derived oop, so we
939  // need to take the lock before making any ProfileData structures.
940  ProfileData* data = h_mdo->data_at(h_mdo->dp_to_di(fr.interpreter_frame_mdp()));
941  RetData* rdata = data->as_RetData();
942  address new_mdp = rdata->fixup_ret(return_bci, h_mdo);
943  fr.interpreter_frame_set_mdp(new_mdp);
944IRT_END
945
946IRT_ENTRY(MethodCounters*, InterpreterRuntime::build_method_counters(JavaThread* thread, Method* m))
947  MethodCounters* mcs = Method::build_method_counters(m, thread);
948  if (HAS_PENDING_EXCEPTION) {
949    assert((PENDING_EXCEPTION->is_a(SystemDictionary::OutOfMemoryError_klass())), "we expect only an OOM error here");
950    CLEAR_PENDING_EXCEPTION;
951  }
952  return mcs;
953IRT_END
954
955
956IRT_ENTRY(void, InterpreterRuntime::at_safepoint(JavaThread* thread))
957  // We used to need an explict preserve_arguments here for invoke bytecodes. However,
958  // stack traversal automatically takes care of preserving arguments for invoke, so
959  // this is no longer needed.
960
961  // IRT_END does an implicit safepoint check, hence we are guaranteed to block
962  // if this is called during a safepoint
963
964  if (JvmtiExport::should_post_single_step()) {
965    // We are called during regular safepoints and when the VM is
966    // single stepping. If any thread is marked for single stepping,
967    // then we may have JVMTI work to do.
968    JvmtiExport::at_single_stepping_point(thread, method(thread), bcp(thread));
969  }
970IRT_END
971
972IRT_ENTRY(void, InterpreterRuntime::post_field_access(JavaThread *thread, oopDesc* obj,
973ConstantPoolCacheEntry *cp_entry))
974
975  // check the access_flags for the field in the klass
976
977  InstanceKlass* ik = InstanceKlass::cast(cp_entry->f1_as_klass());
978  int index = cp_entry->field_index();
979  if ((ik->field_access_flags(index) & JVM_ACC_FIELD_ACCESS_WATCHED) == 0) return;
980
981  switch(cp_entry->flag_state()) {
982    case btos:    // fall through
983    case ctos:    // fall through
984    case stos:    // fall through
985    case itos:    // fall through
986    case ftos:    // fall through
987    case ltos:    // fall through
988    case dtos:    // fall through
989    case atos: break;
990    default: ShouldNotReachHere(); return;
991  }
992  bool is_static = (obj == NULL);
993  HandleMark hm(thread);
994
995  Handle h_obj;
996  if (!is_static) {
997    // non-static field accessors have an object, but we need a handle
998    h_obj = Handle(thread, obj);
999  }
1000  instanceKlassHandle h_cp_entry_f1(thread, (Klass*)cp_entry->f1_as_klass());
1001  jfieldID fid = jfieldIDWorkaround::to_jfieldID(h_cp_entry_f1, cp_entry->f2_as_index(), is_static);
1002  JvmtiExport::post_field_access(thread, method(thread), bcp(thread), h_cp_entry_f1, h_obj, fid);
1003IRT_END
1004
1005IRT_ENTRY(void, InterpreterRuntime::post_field_modification(JavaThread *thread,
1006  oopDesc* obj, ConstantPoolCacheEntry *cp_entry, jvalue *value))
1007
1008  Klass* k = (Klass*)cp_entry->f1_as_klass();
1009
1010  // check the access_flags for the field in the klass
1011  InstanceKlass* ik = InstanceKlass::cast(k);
1012  int index = cp_entry->field_index();
1013  // bail out if field modifications are not watched
1014  if ((ik->field_access_flags(index) & JVM_ACC_FIELD_MODIFICATION_WATCHED) == 0) return;
1015
1016  char sig_type = '\0';
1017
1018  switch(cp_entry->flag_state()) {
1019    case btos: sig_type = 'Z'; break;
1020    case ctos: sig_type = 'C'; break;
1021    case stos: sig_type = 'S'; break;
1022    case itos: sig_type = 'I'; break;
1023    case ftos: sig_type = 'F'; break;
1024    case atos: sig_type = 'L'; break;
1025    case ltos: sig_type = 'J'; break;
1026    case dtos: sig_type = 'D'; break;
1027    default:  ShouldNotReachHere(); return;
1028  }
1029  bool is_static = (obj == NULL);
1030
1031  HandleMark hm(thread);
1032  instanceKlassHandle h_klass(thread, k);
1033  jfieldID fid = jfieldIDWorkaround::to_jfieldID(h_klass, cp_entry->f2_as_index(), is_static);
1034  jvalue fvalue;
1035#ifdef _LP64
1036  fvalue = *value;
1037#else
1038  // Long/double values are stored unaligned and also noncontiguously with
1039  // tagged stacks.  We can't just do a simple assignment even in the non-
1040  // J/D cases because a C++ compiler is allowed to assume that a jvalue is
1041  // 8-byte aligned, and interpreter stack slots are only 4-byte aligned.
1042  // We assume that the two halves of longs/doubles are stored in interpreter
1043  // stack slots in platform-endian order.
1044  jlong_accessor u;
1045  jint* newval = (jint*)value;
1046  u.words[0] = newval[0];
1047  u.words[1] = newval[Interpreter::stackElementWords]; // skip if tag
1048  fvalue.j = u.long_value;
1049#endif // _LP64
1050
1051  Handle h_obj;
1052  if (!is_static) {
1053    // non-static field accessors have an object, but we need a handle
1054    h_obj = Handle(thread, obj);
1055  }
1056
1057  JvmtiExport::post_raw_field_modification(thread, method(thread), bcp(thread), h_klass, h_obj,
1058                                           fid, sig_type, &fvalue);
1059IRT_END
1060
1061IRT_ENTRY(void, InterpreterRuntime::post_method_entry(JavaThread *thread))
1062  JvmtiExport::post_method_entry(thread, InterpreterRuntime::method(thread), InterpreterRuntime::last_frame(thread));
1063IRT_END
1064
1065
1066IRT_ENTRY(void, InterpreterRuntime::post_method_exit(JavaThread *thread))
1067  JvmtiExport::post_method_exit(thread, InterpreterRuntime::method(thread), InterpreterRuntime::last_frame(thread));
1068IRT_END
1069
1070IRT_LEAF(int, InterpreterRuntime::interpreter_contains(address pc))
1071{
1072  return (Interpreter::contains(pc) ? 1 : 0);
1073}
1074IRT_END
1075
1076
1077// Implementation of SignatureHandlerLibrary
1078
1079address SignatureHandlerLibrary::set_handler_blob() {
1080  BufferBlob* handler_blob = BufferBlob::create("native signature handlers", blob_size);
1081  if (handler_blob == NULL) {
1082    return NULL;
1083  }
1084  address handler = handler_blob->code_begin();
1085  _handler_blob = handler_blob;
1086  _handler = handler;
1087  return handler;
1088}
1089
1090void SignatureHandlerLibrary::initialize() {
1091  if (_fingerprints != NULL) {
1092    return;
1093  }
1094  if (set_handler_blob() == NULL) {
1095    vm_exit_out_of_memory(blob_size, OOM_MALLOC_ERROR, "native signature handlers");
1096  }
1097
1098  BufferBlob* bb = BufferBlob::create("Signature Handler Temp Buffer",
1099                                      SignatureHandlerLibrary::buffer_size);
1100  _buffer = bb->code_begin();
1101
1102  _fingerprints = new(ResourceObj::C_HEAP, mtCode)GrowableArray<uint64_t>(32, true);
1103  _handlers     = new(ResourceObj::C_HEAP, mtCode)GrowableArray<address>(32, true);
1104}
1105
1106address SignatureHandlerLibrary::set_handler(CodeBuffer* buffer) {
1107  address handler   = _handler;
1108  int     insts_size = buffer->pure_insts_size();
1109  if (handler + insts_size > _handler_blob->code_end()) {
1110    // get a new handler blob
1111    handler = set_handler_blob();
1112  }
1113  if (handler != NULL) {
1114    memcpy(handler, buffer->insts_begin(), insts_size);
1115    pd_set_handler(handler);
1116    ICache::invalidate_range(handler, insts_size);
1117    _handler = handler + insts_size;
1118  }
1119  return handler;
1120}
1121
1122void SignatureHandlerLibrary::add(methodHandle method) {
1123  if (method->signature_handler() == NULL) {
1124    // use slow signature handler if we can't do better
1125    int handler_index = -1;
1126    // check if we can use customized (fast) signature handler
1127    if (UseFastSignatureHandlers && method->size_of_parameters() <= Fingerprinter::max_size_of_parameters) {
1128      // use customized signature handler
1129      MutexLocker mu(SignatureHandlerLibrary_lock);
1130      // make sure data structure is initialized
1131      initialize();
1132      // lookup method signature's fingerprint
1133      uint64_t fingerprint = Fingerprinter(method).fingerprint();
1134      handler_index = _fingerprints->find(fingerprint);
1135      // create handler if necessary
1136      if (handler_index < 0) {
1137        ResourceMark rm;
1138        ptrdiff_t align_offset = (address)
1139          round_to((intptr_t)_buffer, CodeEntryAlignment) - (address)_buffer;
1140        CodeBuffer buffer((address)(_buffer + align_offset),
1141                          SignatureHandlerLibrary::buffer_size - align_offset);
1142        InterpreterRuntime::SignatureHandlerGenerator(method, &buffer).generate(fingerprint);
1143        // copy into code heap
1144        address handler = set_handler(&buffer);
1145        if (handler == NULL) {
1146          // use slow signature handler
1147        } else {
1148          // debugging suppport
1149          if (PrintSignatureHandlers) {
1150            tty->cr();
1151            tty->print_cr("argument handler #%d for: %s %s (fingerprint = " UINT64_FORMAT ", %d bytes generated)",
1152                          _handlers->length(),
1153                          (method->is_static() ? "static" : "receiver"),
1154                          method->name_and_sig_as_C_string(),
1155                          fingerprint,
1156                          buffer.insts_size());
1157            Disassembler::decode(handler, handler + buffer.insts_size());
1158#ifndef PRODUCT
1159            tty->print_cr(" --- associated result handler ---");
1160            address rh_begin = Interpreter::result_handler(method()->result_type());
1161            address rh_end = rh_begin;
1162            while (*(int*)rh_end != 0) {
1163              rh_end += sizeof(int);
1164            }
1165            Disassembler::decode(rh_begin, rh_end);
1166#endif
1167          }
1168          // add handler to library
1169          _fingerprints->append(fingerprint);
1170          _handlers->append(handler);
1171          // set handler index
1172          assert(_fingerprints->length() == _handlers->length(), "sanity check");
1173          handler_index = _fingerprints->length() - 1;
1174        }
1175      }
1176      // Set handler under SignatureHandlerLibrary_lock
1177    if (handler_index < 0) {
1178      // use generic signature handler
1179      method->set_signature_handler(Interpreter::slow_signature_handler());
1180    } else {
1181      // set handler
1182      method->set_signature_handler(_handlers->at(handler_index));
1183    }
1184    } else {
1185      CHECK_UNHANDLED_OOPS_ONLY(Thread::current()->clear_unhandled_oops());
1186      // use generic signature handler
1187      method->set_signature_handler(Interpreter::slow_signature_handler());
1188    }
1189  }
1190#ifdef ASSERT
1191  int handler_index = -1;
1192  int fingerprint_index = -2;
1193  {
1194    // '_handlers' and '_fingerprints' are 'GrowableArray's and are NOT synchronized
1195    // in any way if accessed from multiple threads. To avoid races with another
1196    // thread which may change the arrays in the above, mutex protected block, we
1197    // have to protect this read access here with the same mutex as well!
1198    MutexLocker mu(SignatureHandlerLibrary_lock);
1199    if (_handlers != NULL) {
1200    handler_index = _handlers->find(method->signature_handler());
1201    fingerprint_index = _fingerprints->find(Fingerprinter(method).fingerprint());
1202  }
1203  }
1204  assert(method->signature_handler() == Interpreter::slow_signature_handler() ||
1205         handler_index == fingerprint_index, "sanity check");
1206#endif // ASSERT
1207}
1208
1209
1210BufferBlob*              SignatureHandlerLibrary::_handler_blob = NULL;
1211address                  SignatureHandlerLibrary::_handler      = NULL;
1212GrowableArray<uint64_t>* SignatureHandlerLibrary::_fingerprints = NULL;
1213GrowableArray<address>*  SignatureHandlerLibrary::_handlers     = NULL;
1214address                  SignatureHandlerLibrary::_buffer       = NULL;
1215
1216
1217IRT_ENTRY(void, InterpreterRuntime::prepare_native_call(JavaThread* thread, Method* method))
1218  methodHandle m(thread, method);
1219  assert(m->is_native(), "sanity check");
1220  // lookup native function entry point if it doesn't exist
1221  bool in_base_library;
1222  if (!m->has_native_function()) {
1223    NativeLookup::lookup(m, in_base_library, CHECK);
1224  }
1225  // make sure signature handler is installed
1226  SignatureHandlerLibrary::add(m);
1227  // The interpreter entry point checks the signature handler first,
1228  // before trying to fetch the native entry point and klass mirror.
1229  // We must set the signature handler last, so that multiple processors
1230  // preparing the same method will be sure to see non-null entry & mirror.
1231IRT_END
1232
1233#if defined(IA32) || defined(AMD64) || defined(ARM)
1234IRT_LEAF(void, InterpreterRuntime::popframe_move_outgoing_args(JavaThread* thread, void* src_address, void* dest_address))
1235  if (src_address == dest_address) {
1236    return;
1237  }
1238  ResetNoHandleMark rnm; // In a LEAF entry.
1239  HandleMark hm;
1240  ResourceMark rm;
1241  frame fr = thread->last_frame();
1242  assert(fr.is_interpreted_frame(), "");
1243  jint bci = fr.interpreter_frame_bci();
1244  methodHandle mh(thread, fr.interpreter_frame_method());
1245  Bytecode_invoke invoke(mh, bci);
1246  ArgumentSizeComputer asc(invoke.signature());
1247  int size_of_arguments = (asc.size() + (invoke.has_receiver() ? 1 : 0)); // receiver
1248  Copy::conjoint_jbytes(src_address, dest_address,
1249                       size_of_arguments * Interpreter::stackElementSize);
1250IRT_END
1251#endif
1252
1253#if INCLUDE_JVMTI
1254// This is a support of the JVMTI PopFrame interface.
1255// Make sure it is an invokestatic of a polymorphic intrinsic that has a member_name argument
1256// and return it as a vm_result so that it can be reloaded in the list of invokestatic parameters.
1257// The member_name argument is a saved reference (in local#0) to the member_name.
1258// For backward compatibility with some JDK versions (7, 8) it can also be a direct method handle.
1259// FIXME: remove DMH case after j.l.i.InvokerBytecodeGenerator code shape is updated.
1260IRT_ENTRY(void, InterpreterRuntime::member_name_arg_or_null(JavaThread* thread, address member_name,
1261                                                            Method* method, address bcp))
1262  Bytecodes::Code code = Bytecodes::code_at(method, bcp);
1263  if (code != Bytecodes::_invokestatic) {
1264    return;
1265  }
1266  ConstantPool* cpool = method->constants();
1267  int cp_index = Bytes::get_native_u2(bcp + 1) + ConstantPool::CPCACHE_INDEX_TAG;
1268  Symbol* cname = cpool->klass_name_at(cpool->klass_ref_index_at(cp_index));
1269  Symbol* mname = cpool->name_ref_at(cp_index);
1270
1271  if (MethodHandles::has_member_arg(cname, mname)) {
1272    oop member_name_oop = (oop) member_name;
1273    if (java_lang_invoke_DirectMethodHandle::is_instance(member_name_oop)) {
1274      // FIXME: remove after j.l.i.InvokerBytecodeGenerator code shape is updated.
1275      member_name_oop = java_lang_invoke_DirectMethodHandle::member(member_name_oop);
1276    }
1277    thread->set_vm_result(member_name_oop);
1278  }
1279IRT_END
1280#endif // INCLUDE_JVMTI
1281