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