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