interpreterRuntime.cpp revision 1472:c18cbe5936b8
1251881Speter/*
2251881Speter * Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
3251881Speter * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4251881Speter *
5251881Speter * This code is free software; you can redistribute it and/or modify it
6251881Speter * under the terms of the GNU General Public License version 2 only, as
7251881Speter * published by the Free Software Foundation.
8251881Speter *
9251881Speter * This code is distributed in the hope that it will be useful, but WITHOUT
10251881Speter * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11251881Speter * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12251881Speter * version 2 for more details (a copy is included in the LICENSE file that
13251881Speter * accompanied this code).
14251881Speter *
15251881Speter * You should have received a copy of the GNU General Public License version
16251881Speter * 2 along with this work; if not, write to the Free Software Foundation,
17251881Speter * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18251881Speter *
19251881Speter * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20251881Speter * or visit www.oracle.com if you need additional information or have any
21251881Speter * questions.
22251881Speter *
23251881Speter */
24251881Speter
25251881Speter#include "incls/_precompiled.incl"
26251881Speter#include "incls/_interpreterRuntime.cpp.incl"
27251881Speter
28251881Speterclass UnlockFlagSaver {
29251881Speter  private:
30251881Speter    JavaThread* _thread;
31251881Speter    bool _do_not_unlock;
32251881Speter  public:
33251881Speter    UnlockFlagSaver(JavaThread* t) {
34251881Speter      _thread = t;
35251881Speter      _do_not_unlock = t->do_not_unlock_if_synchronized();
36251881Speter      t->set_do_not_unlock_if_synchronized(false);
37251881Speter    }
38251881Speter    ~UnlockFlagSaver() {
39251881Speter      _thread->set_do_not_unlock_if_synchronized(_do_not_unlock);
40251881Speter    }
41251881Speter};
42251881Speter
43251881Speter//------------------------------------------------------------------------------------------------------------------------
44251881Speter// State accessors
45251881Speter
46251881Spetervoid InterpreterRuntime::set_bcp_and_mdp(address bcp, JavaThread *thread) {
47251881Speter  last_frame(thread).interpreter_frame_set_bcp(bcp);
48251881Speter  if (ProfileInterpreter) {
49251881Speter    // ProfileTraps uses MDOs independently of ProfileInterpreter.
50251881Speter    // That is why we must check both ProfileInterpreter and mdo != NULL.
51251881Speter    methodDataOop mdo = last_frame(thread).interpreter_frame_method()->method_data();
52251881Speter    if (mdo != NULL) {
53251881Speter      NEEDS_CLEANUP;
54251881Speter      last_frame(thread).interpreter_frame_set_mdp(mdo->bci_to_dp(last_frame(thread).interpreter_frame_bci()));
55251881Speter    }
56251881Speter  }
57251881Speter}
58251881Speter
59251881Speter//------------------------------------------------------------------------------------------------------------------------
60251881Speter// Constants
61251881Speter
62251881Speter
63251881SpeterIRT_ENTRY(void, InterpreterRuntime::ldc(JavaThread* thread, bool wide))
64251881Speter  // access constant pool
65251881Speter  constantPoolOop pool = method(thread)->constants();
66251881Speter  int index = wide ? two_byte_index(thread) : one_byte_index(thread);
67251881Speter  constantTag tag = pool->tag_at(index);
68251881Speter
69251881Speter  if (tag.is_unresolved_klass() || tag.is_klass()) {
70251881Speter    klassOop klass = pool->klass_at(index, CHECK);
71251881Speter    oop java_class = klass->klass_part()->java_mirror();
72251881Speter    thread->set_vm_result(java_class);
73251881Speter  } else {
74251881Speter#ifdef ASSERT
75251881Speter    // If we entered this runtime routine, we believed the tag contained
76251881Speter    // an unresolved string, an unresolved class or a resolved class.
77251881Speter    // However, another thread could have resolved the unresolved string
78251881Speter    // or class by the time we go there.
79251881Speter    assert(tag.is_unresolved_string()|| tag.is_string(), "expected string");
80251881Speter#endif
81251881Speter    oop s_oop = pool->string_at(index, CHECK);
82251881Speter    thread->set_vm_result(s_oop);
83251881Speter  }
84251881SpeterIRT_END
85251881Speter
86251881Speter
87251881Speter//------------------------------------------------------------------------------------------------------------------------
88251881Speter// Allocation
89251881Speter
90251881SpeterIRT_ENTRY(void, InterpreterRuntime::_new(JavaThread* thread, constantPoolOopDesc* pool, int index))
91251881Speter  klassOop k_oop = pool->klass_at(index, CHECK);
92251881Speter  instanceKlassHandle klass (THREAD, k_oop);
93251881Speter
94251881Speter  // Make sure we are not instantiating an abstract klass
95251881Speter  klass->check_valid_for_instantiation(true, CHECK);
96251881Speter
97251881Speter  // Make sure klass is initialized
98251881Speter  klass->initialize(CHECK);
99251881Speter
100251881Speter  // At this point the class may not be fully initialized
101251881Speter  // because of recursive initialization. If it is fully
102251881Speter  // initialized & has_finalized is not set, we rewrite
103251881Speter  // it into its fast version (Note: no locking is needed
104251881Speter  // here since this is an atomic byte write and can be
105251881Speter  // done more than once).
106251881Speter  //
107251881Speter  // Note: In case of classes with has_finalized we don't
108251881Speter  //       rewrite since that saves us an extra check in
109251881Speter  //       the fast version which then would call the
110251881Speter  //       slow version anyway (and do a call back into
111251881Speter  //       Java).
112251881Speter  //       If we have a breakpoint, then we don't rewrite
113251881Speter  //       because the _breakpoint bytecode would be lost.
114251881Speter  oop obj = klass->allocate_instance(CHECK);
115251881Speter  thread->set_vm_result(obj);
116251881SpeterIRT_END
117251881Speter
118251881Speter
119251881SpeterIRT_ENTRY(void, InterpreterRuntime::newarray(JavaThread* thread, BasicType type, jint size))
120251881Speter  oop obj = oopFactory::new_typeArray(type, size, CHECK);
121251881Speter  thread->set_vm_result(obj);
122251881SpeterIRT_END
123251881Speter
124251881Speter
125251881SpeterIRT_ENTRY(void, InterpreterRuntime::anewarray(JavaThread* thread, constantPoolOopDesc* pool, int index, jint size))
126251881Speter  // Note: no oopHandle for pool & klass needed since they are not used
127251881Speter  //       anymore after new_objArray() and no GC can happen before.
128251881Speter  //       (This may have to change if this code changes!)
129251881Speter  klassOop  klass = pool->klass_at(index, CHECK);
130251881Speter  objArrayOop obj = oopFactory::new_objArray(klass, size, CHECK);
131251881Speter  thread->set_vm_result(obj);
132251881SpeterIRT_END
133251881Speter
134251881Speter
135251881SpeterIRT_ENTRY(void, InterpreterRuntime::multianewarray(JavaThread* thread, jint* first_size_address))
136251881Speter  // We may want to pass in more arguments - could make this slightly faster
137251881Speter  constantPoolOop constants = method(thread)->constants();
138251881Speter  int          i = two_byte_index(thread);
139251881Speter  klassOop klass = constants->klass_at(i, CHECK);
140251881Speter  int   nof_dims = number_of_dimensions(thread);
141251881Speter  assert(oop(klass)->is_klass(), "not a class");
142251881Speter  assert(nof_dims >= 1, "multianewarray rank must be nonzero");
143251881Speter
144251881Speter  // We must create an array of jints to pass to multi_allocate.
145251881Speter  ResourceMark rm(thread);
146251881Speter  const int small_dims = 10;
147251881Speter  jint dim_array[small_dims];
148251881Speter  jint *dims = &dim_array[0];
149251881Speter  if (nof_dims > small_dims) {
150251881Speter    dims = (jint*) NEW_RESOURCE_ARRAY(jint, nof_dims);
151251881Speter  }
152251881Speter  for (int index = 0; index < nof_dims; index++) {
153251881Speter    // offset from first_size_address is addressed as local[index]
154251881Speter    int n = Interpreter::local_offset_in_bytes(index)/jintSize;
155251881Speter    dims[index] = first_size_address[n];
156251881Speter  }
157251881Speter  oop obj = arrayKlass::cast(klass)->multi_allocate(nof_dims, dims, CHECK);
158251881Speter  thread->set_vm_result(obj);
159251881SpeterIRT_END
160251881Speter
161251881Speter
162251881SpeterIRT_ENTRY(void, InterpreterRuntime::register_finalizer(JavaThread* thread, oopDesc* obj))
163251881Speter  assert(obj->is_oop(), "must be a valid oop");
164251881Speter  assert(obj->klass()->klass_part()->has_finalizer(), "shouldn't be here otherwise");
165251881Speter  instanceKlass::register_finalizer(instanceOop(obj), CHECK);
166251881SpeterIRT_END
167251881Speter
168251881Speter
169251881Speter// Quicken instance-of and check-cast bytecodes
170251881SpeterIRT_ENTRY(void, InterpreterRuntime::quicken_io_cc(JavaThread* thread))
171251881Speter  // Force resolving; quicken the bytecode
172251881Speter  int which = two_byte_index(thread);
173251881Speter  constantPoolOop cpool = method(thread)->constants();
174251881Speter  // We'd expect to assert that we're only here to quicken bytecodes, but in a multithreaded
175251881Speter  // program we might have seen an unquick'd bytecode in the interpreter but have another
176251881Speter  // thread quicken the bytecode before we get here.
177251881Speter  // assert( cpool->tag_at(which).is_unresolved_klass(), "should only come here to quicken bytecodes" );
178251881Speter  klassOop klass = cpool->klass_at(which, CHECK);
179251881Speter  thread->set_vm_result(klass);
180251881SpeterIRT_END
181251881Speter
182251881Speter
183251881Speter//------------------------------------------------------------------------------------------------------------------------
184251881Speter// Exceptions
185251881Speter
186251881Speter// Assume the compiler is (or will be) interested in this event.
187251881Speter// If necessary, create an MDO to hold the information, and record it.
188251881Spetervoid InterpreterRuntime::note_trap(JavaThread* thread, int reason, TRAPS) {
189251881Speter  assert(ProfileTraps, "call me only if profiling");
190251881Speter  methodHandle trap_method(thread, method(thread));
191251881Speter  if (trap_method.not_null()) {
192251881Speter    methodDataHandle trap_mdo(thread, trap_method->method_data());
193251881Speter    if (trap_mdo.is_null()) {
194251881Speter      methodOopDesc::build_interpreter_method_data(trap_method, THREAD);
195251881Speter      if (HAS_PENDING_EXCEPTION) {
196251881Speter        assert((PENDING_EXCEPTION->is_a(SystemDictionary::OutOfMemoryError_klass())), "we expect only an OOM error here");
197251881Speter        CLEAR_PENDING_EXCEPTION;
198251881Speter      }
199251881Speter      trap_mdo = methodDataHandle(thread, trap_method->method_data());
200251881Speter      // and fall through...
201251881Speter    }
202251881Speter    if (trap_mdo.not_null()) {
203251881Speter      // Update per-method count of trap events.  The interpreter
204251881Speter      // is updating the MDO to simulate the effect of compiler traps.
205251881Speter      int trap_bci = trap_method->bci_from(bcp(thread));
206251881Speter      Deoptimization::update_method_data_from_interpreter(trap_mdo, trap_bci, reason);
207251881Speter    }
208251881Speter  }
209251881Speter}
210251881Speter
211251881Speterstatic Handle get_preinitialized_exception(klassOop k, TRAPS) {
212251881Speter  // get klass
213251881Speter  instanceKlass* klass = instanceKlass::cast(k);
214251881Speter  assert(klass->is_initialized(),
215251881Speter         "this klass should have been initialized during VM initialization");
216251881Speter  // create instance - do not call constructor since we may have no
217251881Speter  // (java) stack space left (should assert constructor is empty)
218251881Speter  Handle exception;
219251881Speter  oop exception_oop = klass->allocate_instance(CHECK_(exception));
220251881Speter  exception = Handle(THREAD, exception_oop);
221251881Speter  if (StackTraceInThrowable) {
222251881Speter    java_lang_Throwable::fill_in_stack_trace(exception);
223251881Speter  }
224251881Speter  return exception;
225251881Speter}
226251881Speter
227251881Speter// Special handling for stack overflow: since we don't have any (java) stack
228251881Speter// space left we use the pre-allocated & pre-initialized StackOverflowError
229251881Speter// klass to create an stack overflow error instance.  We do not call its
230251881Speter// constructor for the same reason (it is empty, anyway).
231251881SpeterIRT_ENTRY(void, InterpreterRuntime::throw_StackOverflowError(JavaThread* thread))
232251881Speter  Handle exception = get_preinitialized_exception(
233251881Speter                                 SystemDictionary::StackOverflowError_klass(),
234251881Speter                                 CHECK);
235251881Speter  THROW_HANDLE(exception);
236251881SpeterIRT_END
237251881Speter
238251881Speter
239251881SpeterIRT_ENTRY(void, InterpreterRuntime::create_exception(JavaThread* thread, char* name, char* message))
240251881Speter  // lookup exception klass
241251881Speter  symbolHandle s = oopFactory::new_symbol_handle(name, CHECK);
242251881Speter  if (ProfileTraps) {
243251881Speter    if (s == vmSymbols::java_lang_ArithmeticException()) {
244251881Speter      note_trap(thread, Deoptimization::Reason_div0_check, CHECK);
245251881Speter    } else if (s == vmSymbols::java_lang_NullPointerException()) {
246251881Speter      note_trap(thread, Deoptimization::Reason_null_check, CHECK);
247251881Speter    }
248251881Speter  }
249251881Speter  // create exception
250251881Speter  Handle exception = Exceptions::new_exception(thread, s(), message);
251251881Speter  thread->set_vm_result(exception());
252251881SpeterIRT_END
253251881Speter
254251881Speter
255251881SpeterIRT_ENTRY(void, InterpreterRuntime::create_klass_exception(JavaThread* thread, char* name, oopDesc* obj))
256251881Speter  ResourceMark rm(thread);
257251881Speter  const char* klass_name = Klass::cast(obj->klass())->external_name();
258251881Speter  // lookup exception klass
259251881Speter  symbolHandle s = oopFactory::new_symbol_handle(name, CHECK);
260251881Speter  if (ProfileTraps) {
261251881Speter    note_trap(thread, Deoptimization::Reason_class_check, CHECK);
262251881Speter  }
263251881Speter  // create exception, with klass name as detail message
264251881Speter  Handle exception = Exceptions::new_exception(thread, s(), klass_name);
265251881Speter  thread->set_vm_result(exception());
266251881SpeterIRT_END
267251881Speter
268251881Speter
269251881SpeterIRT_ENTRY(void, InterpreterRuntime::throw_ArrayIndexOutOfBoundsException(JavaThread* thread, char* name, jint index))
270251881Speter  char message[jintAsStringSize];
271251881Speter  // lookup exception klass
272251881Speter  symbolHandle s = oopFactory::new_symbol_handle(name, CHECK);
273251881Speter  if (ProfileTraps) {
274251881Speter    note_trap(thread, Deoptimization::Reason_range_check, CHECK);
275251881Speter  }
276251881Speter  // create exception
277251881Speter  sprintf(message, "%d", index);
278251881Speter  THROW_MSG(s(), message);
279251881SpeterIRT_END
280251881Speter
281251881SpeterIRT_ENTRY(void, InterpreterRuntime::throw_ClassCastException(
282251881Speter  JavaThread* thread, oopDesc* obj))
283251881Speter
284251881Speter  ResourceMark rm(thread);
285251881Speter  char* message = SharedRuntime::generate_class_cast_message(
286251881Speter    thread, Klass::cast(obj->klass())->external_name());
287251881Speter
288251881Speter  if (ProfileTraps) {
289251881Speter    note_trap(thread, Deoptimization::Reason_class_check, CHECK);
290251881Speter  }
291251881Speter
292251881Speter  // create exception
293251881Speter  THROW_MSG(vmSymbols::java_lang_ClassCastException(), message);
294251881SpeterIRT_END
295251881Speter
296251881Speter// required can be either a MethodType, or a Class (for a single argument)
297251881Speter// actual (if not null) can be either a MethodHandle, or an arbitrary value (for a single argument)
298251881SpeterIRT_ENTRY(void, InterpreterRuntime::throw_WrongMethodTypeException(JavaThread* thread,
299251881Speter                                                                   oopDesc* required,
300251881Speter                                                                   oopDesc* actual)) {
301251881Speter  ResourceMark rm(thread);
302251881Speter  char* message = SharedRuntime::generate_wrong_method_type_message(thread, required, actual);
303251881Speter
304251881Speter  if (ProfileTraps) {
305251881Speter    note_trap(thread, Deoptimization::Reason_constraint, CHECK);
306251881Speter  }
307251881Speter
308251881Speter  // create exception
309251881Speter  THROW_MSG(vmSymbols::java_dyn_WrongMethodTypeException(), message);
310251881Speter}
311251881SpeterIRT_END
312251881Speter
313251881Speter
314251881Speter
315251881Speter// exception_handler_for_exception(...) returns the continuation address,
316251881Speter// the exception oop (via TLS) and sets the bci/bcp for the continuation.
317251881Speter// The exception oop is returned to make sure it is preserved over GC (it
318251881Speter// is only on the stack if the exception was thrown explicitly via athrow).
319251881Speter// During this operation, the expression stack contains the values for the
320251881Speter// bci where the exception happened. If the exception was propagated back
321251881Speter// from a call, the expression stack contains the values for the bci at the
322251881Speter// invoke w/o arguments (i.e., as if one were inside the call).
323251881SpeterIRT_ENTRY(address, InterpreterRuntime::exception_handler_for_exception(JavaThread* thread, oopDesc* exception))
324251881Speter
325251881Speter  Handle             h_exception(thread, exception);
326251881Speter  methodHandle       h_method   (thread, method(thread));
327251881Speter  constantPoolHandle h_constants(thread, h_method->constants());
328251881Speter  typeArrayHandle    h_extable  (thread, h_method->exception_table());
329251881Speter  bool               should_repeat;
330251881Speter  int                handler_bci;
331251881Speter  int                current_bci = bcp(thread) - h_method->code_base();
332251881Speter
333251881Speter  // Need to do this check first since when _do_not_unlock_if_synchronized
334251881Speter  // is set, we don't want to trigger any classloading which may make calls
335251881Speter  // into java, or surprisingly find a matching exception handler for bci 0
336251881Speter  // since at this moment the method hasn't been "officially" entered yet.
337251881Speter  if (thread->do_not_unlock_if_synchronized()) {
338251881Speter    ResourceMark rm;
339251881Speter    assert(current_bci == 0,  "bci isn't zero for do_not_unlock_if_synchronized");
340251881Speter    thread->set_vm_result(exception);
341251881Speter#ifdef CC_INTERP
342251881Speter    return (address) -1;
343251881Speter#else
344251881Speter    return Interpreter::remove_activation_entry();
345251881Speter#endif
346251881Speter  }
347251881Speter
348251881Speter  do {
349251881Speter    should_repeat = false;
350251881Speter
351251881Speter    // assertions
352251881Speter#ifdef ASSERT
353251881Speter    assert(h_exception.not_null(), "NULL exceptions should be handled by athrow");
354251881Speter    assert(h_exception->is_oop(), "just checking");
355251881Speter    // Check that exception is a subclass of Throwable, otherwise we have a VerifyError
356251881Speter    if (!(h_exception->is_a(SystemDictionary::Throwable_klass()))) {
357251881Speter      if (ExitVMOnVerifyError) vm_exit(-1);
358251881Speter      ShouldNotReachHere();
359251881Speter    }
360251881Speter#endif
361251881Speter
362251881Speter    // tracing
363251881Speter    if (TraceExceptions) {
364251881Speter      ttyLocker ttyl;
365251881Speter      ResourceMark rm(thread);
366251881Speter      tty->print_cr("Exception <%s> (" INTPTR_FORMAT ")", h_exception->print_value_string(), (address)h_exception());
367251881Speter      tty->print_cr(" thrown in interpreter method <%s>", h_method->print_value_string());
368251881Speter      tty->print_cr(" at bci %d for thread " INTPTR_FORMAT, current_bci, thread);
369251881Speter    }
370251881Speter// Don't go paging in something which won't be used.
371251881Speter//     else if (h_extable->length() == 0) {
372251881Speter//       // disabled for now - interpreter is not using shortcut yet
373251881Speter//       // (shortcut is not to call runtime if we have no exception handlers)
374251881Speter//       // warning("performance bug: should not call runtime if method has no exception handlers");
375251881Speter//     }
376251881Speter    // for AbortVMOnException flag
377251881Speter    NOT_PRODUCT(Exceptions::debug_check_abort(h_exception));
378251881Speter
379251881Speter    // exception handler lookup
380251881Speter    KlassHandle h_klass(THREAD, h_exception->klass());
381251881Speter    handler_bci = h_method->fast_exception_handler_bci_for(h_klass, current_bci, THREAD);
382251881Speter    if (HAS_PENDING_EXCEPTION) {
383251881Speter      // We threw an exception while trying to find the exception handler.
384251881Speter      // Transfer the new exception to the exception handle which will
385251881Speter      // be set into thread local storage, and do another lookup for an
386251881Speter      // exception handler for this exception, this time starting at the
387251881Speter      // BCI of the exception handler which caused the exception to be
388251881Speter      // thrown (bug 4307310).
389251881Speter      h_exception = Handle(THREAD, PENDING_EXCEPTION);
390251881Speter      CLEAR_PENDING_EXCEPTION;
391251881Speter      if (handler_bci >= 0) {
392251881Speter        current_bci = handler_bci;
393251881Speter        should_repeat = true;
394251881Speter      }
395251881Speter    }
396251881Speter  } while (should_repeat == true);
397251881Speter
398251881Speter  // notify JVMTI of an exception throw; JVMTI will detect if this is a first
399251881Speter  // time throw or a stack unwinding throw and accordingly notify the debugger
400251881Speter  if (JvmtiExport::can_post_on_exceptions()) {
401251881Speter    JvmtiExport::post_exception_throw(thread, h_method(), bcp(thread), h_exception());
402251881Speter  }
403251881Speter
404251881Speter#ifdef CC_INTERP
405251881Speter  address continuation = (address)(intptr_t) handler_bci;
406251881Speter#else
407251881Speter  address continuation = NULL;
408251881Speter#endif
409251881Speter  address handler_pc = NULL;
410251881Speter  if (handler_bci < 0 || !thread->reguard_stack((address) &continuation)) {
411251881Speter    // Forward exception to callee (leaving bci/bcp untouched) because (a) no
412251881Speter    // handler in this method, or (b) after a stack overflow there is not yet
413251881Speter    // enough stack space available to reprotect the stack.
414251881Speter#ifndef CC_INTERP
415251881Speter    continuation = Interpreter::remove_activation_entry();
416251881Speter#endif
417251881Speter    // Count this for compilation purposes
418251881Speter    h_method->interpreter_throwout_increment();
419251881Speter  } else {
420251881Speter    // handler in this method => change bci/bcp to handler bci/bcp and continue there
421251881Speter    handler_pc = h_method->code_base() + handler_bci;
422251881Speter#ifndef CC_INTERP
423251881Speter    set_bcp_and_mdp(handler_pc, thread);
424251881Speter    continuation = Interpreter::dispatch_table(vtos)[*handler_pc];
425251881Speter#endif
426251881Speter  }
427251881Speter  // notify debugger of an exception catch
428251881Speter  // (this is good for exceptions caught in native methods as well)
429251881Speter  if (JvmtiExport::can_post_on_exceptions()) {
430251881Speter    JvmtiExport::notice_unwind_due_to_exception(thread, h_method(), handler_pc, h_exception(), (handler_pc != NULL));
431251881Speter  }
432251881Speter
433251881Speter  thread->set_vm_result(h_exception());
434251881Speter  return continuation;
435251881SpeterIRT_END
436251881Speter
437251881Speter
438251881SpeterIRT_ENTRY(void, InterpreterRuntime::throw_pending_exception(JavaThread* thread))
439251881Speter  assert(thread->has_pending_exception(), "must only ne called if there's an exception pending");
440251881Speter  // nothing to do - eventually we should remove this code entirely (see comments @ call sites)
441251881SpeterIRT_END
442251881Speter
443251881Speter
444251881SpeterIRT_ENTRY(void, InterpreterRuntime::throw_AbstractMethodError(JavaThread* thread))
445251881Speter  THROW(vmSymbols::java_lang_AbstractMethodError());
446251881SpeterIRT_END
447251881Speter
448251881Speter
449251881SpeterIRT_ENTRY(void, InterpreterRuntime::throw_IncompatibleClassChangeError(JavaThread* thread))
450251881Speter  THROW(vmSymbols::java_lang_IncompatibleClassChangeError());
451251881SpeterIRT_END
452251881Speter
453251881Speter
454251881Speter//------------------------------------------------------------------------------------------------------------------------
455251881Speter// Fields
456251881Speter//
457251881Speter
458251881SpeterIRT_ENTRY(void, InterpreterRuntime::resolve_get_put(JavaThread* thread, Bytecodes::Code bytecode))
459251881Speter  // resolve field
460251881Speter  FieldAccessInfo info;
461251881Speter  constantPoolHandle pool(thread, method(thread)->constants());
462251881Speter  bool is_static = (bytecode == Bytecodes::_getstatic || bytecode == Bytecodes::_putstatic);
463251881Speter
464251881Speter  {
465251881Speter    JvmtiHideSingleStepping jhss(thread);
466251881Speter    LinkResolver::resolve_field(info, pool, two_byte_index(thread),
467251881Speter                                bytecode, false, CHECK);
468251881Speter  } // end JvmtiHideSingleStepping
469251881Speter
470251881Speter  // check if link resolution caused cpCache to be updated
471251881Speter  if (already_resolved(thread)) return;
472251881Speter
473251881Speter  // compute auxiliary field attributes
474251881Speter  TosState state  = as_TosState(info.field_type());
475251881Speter
476251881Speter  // We need to delay resolving put instructions on final fields
477251881Speter  // until we actually invoke one. This is required so we throw
478251881Speter  // exceptions at the correct place. If we do not resolve completely
479251881Speter  // in the current pass, leaving the put_code set to zero will
480251881Speter  // cause the next put instruction to reresolve.
481251881Speter  bool is_put = (bytecode == Bytecodes::_putfield ||
482251881Speter                 bytecode == Bytecodes::_putstatic);
483251881Speter  Bytecodes::Code put_code = (Bytecodes::Code)0;
484251881Speter
485251881Speter  // We also need to delay resolving getstatic instructions until the
486251881Speter  // class is intitialized.  This is required so that access to the static
487251881Speter  // field will call the initialization function every time until the class
488251881Speter  // is completely initialized ala. in 2.17.5 in JVM Specification.
489251881Speter  instanceKlass *klass = instanceKlass::cast(info.klass()->as_klassOop());
490251881Speter  bool uninitialized_static = ((bytecode == Bytecodes::_getstatic || bytecode == Bytecodes::_putstatic) &&
491251881Speter                               !klass->is_initialized());
492251881Speter  Bytecodes::Code get_code = (Bytecodes::Code)0;
493251881Speter
494251881Speter
495251881Speter  if (!uninitialized_static) {
496251881Speter    get_code = ((is_static) ? Bytecodes::_getstatic : Bytecodes::_getfield);
497251881Speter    if (is_put || !info.access_flags().is_final()) {
498251881Speter      put_code = ((is_static) ? Bytecodes::_putstatic : Bytecodes::_putfield);
499251881Speter    }
500251881Speter  }
501251881Speter
502251881Speter  cache_entry(thread)->set_field(
503251881Speter    get_code,
504251881Speter    put_code,
505251881Speter    info.klass(),
506251881Speter    info.field_index(),
507251881Speter    info.field_offset(),
508251881Speter    state,
509251881Speter    info.access_flags().is_final(),
510251881Speter    info.access_flags().is_volatile()
511251881Speter  );
512251881SpeterIRT_END
513251881Speter
514251881Speter
515251881Speter//------------------------------------------------------------------------------------------------------------------------
516251881Speter// Synchronization
517251881Speter//
518251881Speter// The interpreter's synchronization code is factored out so that it can
519251881Speter// be shared by method invocation and synchronized blocks.
520251881Speter//%note synchronization_3
521251881Speter
522251881Speterstatic void trace_locking(Handle& h_locking_obj, bool is_locking) {
523251881Speter  ObjectSynchronizer::trace_locking(h_locking_obj, false, true, is_locking);
524251881Speter}
525251881Speter
526251881Speter
527251881Speter//%note monitor_1
528251881SpeterIRT_ENTRY_NO_ASYNC(void, InterpreterRuntime::monitorenter(JavaThread* thread, BasicObjectLock* elem))
529251881Speter#ifdef ASSERT
530251881Speter  thread->last_frame().interpreter_frame_verify_monitor(elem);
531251881Speter#endif
532251881Speter  if (PrintBiasedLockingStatistics) {
533251881Speter    Atomic::inc(BiasedLocking::slow_path_entry_count_addr());
534251881Speter  }
535251881Speter  Handle h_obj(thread, elem->obj());
536251881Speter  assert(Universe::heap()->is_in_reserved_or_null(h_obj()),
537251881Speter         "must be NULL or an object");
538251881Speter  if (UseBiasedLocking) {
539251881Speter    // Retry fast entry if bias is revoked to avoid unnecessary inflation
540251881Speter    ObjectSynchronizer::fast_enter(h_obj, elem->lock(), true, CHECK);
541251881Speter  } else {
542251881Speter    ObjectSynchronizer::slow_enter(h_obj, elem->lock(), CHECK);
543251881Speter  }
544251881Speter  assert(Universe::heap()->is_in_reserved_or_null(elem->obj()),
545251881Speter         "must be NULL or an object");
546251881Speter#ifdef ASSERT
547251881Speter  thread->last_frame().interpreter_frame_verify_monitor(elem);
548251881Speter#endif
549251881SpeterIRT_END
550251881Speter
551251881Speter
552251881Speter//%note monitor_1
553251881SpeterIRT_ENTRY_NO_ASYNC(void, InterpreterRuntime::monitorexit(JavaThread* thread, BasicObjectLock* elem))
554251881Speter#ifdef ASSERT
555251881Speter  thread->last_frame().interpreter_frame_verify_monitor(elem);
556251881Speter#endif
557251881Speter  Handle h_obj(thread, elem->obj());
558251881Speter  assert(Universe::heap()->is_in_reserved_or_null(h_obj()),
559251881Speter         "must be NULL or an object");
560251881Speter  if (elem == NULL || h_obj()->is_unlocked()) {
561251881Speter    THROW(vmSymbols::java_lang_IllegalMonitorStateException());
562251881Speter  }
563251881Speter  ObjectSynchronizer::slow_exit(h_obj(), elem->lock(), thread);
564251881Speter  // Free entry. This must be done here, since a pending exception might be installed on
565251881Speter  // exit. If it is not cleared, the exception handling code will try to unlock the monitor again.
566251881Speter  elem->set_obj(NULL);
567251881Speter#ifdef ASSERT
568251881Speter  thread->last_frame().interpreter_frame_verify_monitor(elem);
569251881Speter#endif
570251881SpeterIRT_END
571251881Speter
572251881Speter
573251881SpeterIRT_ENTRY(void, InterpreterRuntime::throw_illegal_monitor_state_exception(JavaThread* thread))
574251881Speter  THROW(vmSymbols::java_lang_IllegalMonitorStateException());
575251881SpeterIRT_END
576251881Speter
577251881Speter
578251881SpeterIRT_ENTRY(void, InterpreterRuntime::new_illegal_monitor_state_exception(JavaThread* thread))
579251881Speter  // Returns an illegal exception to install into the current thread. The
580251881Speter  // pending_exception flag is cleared so normal exception handling does not
581251881Speter  // trigger. Any current installed exception will be overwritten. This
582251881Speter  // method will be called during an exception unwind.
583251881Speter
584251881Speter  assert(!HAS_PENDING_EXCEPTION, "no pending exception");
585251881Speter  Handle exception(thread, thread->vm_result());
586251881Speter  assert(exception() != NULL, "vm result should be set");
587251881Speter  thread->set_vm_result(NULL); // clear vm result before continuing (may cause memory leaks and assert failures)
588251881Speter  if (!exception->is_a(SystemDictionary::ThreadDeath_klass())) {
589251881Speter    exception = get_preinitialized_exception(
590251881Speter                       SystemDictionary::IllegalMonitorStateException_klass(),
591251881Speter                       CATCH);
592251881Speter  }
593251881Speter  thread->set_vm_result(exception());
594251881SpeterIRT_END
595251881Speter
596251881Speter
597251881Speter//------------------------------------------------------------------------------------------------------------------------
598251881Speter// Invokes
599251881Speter
600251881SpeterIRT_ENTRY(Bytecodes::Code, InterpreterRuntime::get_original_bytecode_at(JavaThread* thread, methodOopDesc* method, address bcp))
601251881Speter  return method->orig_bytecode_at(method->bci_from(bcp));
602251881SpeterIRT_END
603251881Speter
604251881SpeterIRT_ENTRY(void, InterpreterRuntime::set_original_bytecode_at(JavaThread* thread, methodOopDesc* method, address bcp, Bytecodes::Code new_code))
605251881Speter  method->set_orig_bytecode_at(method->bci_from(bcp), new_code);
606251881SpeterIRT_END
607251881Speter
608251881SpeterIRT_ENTRY(void, InterpreterRuntime::_breakpoint(JavaThread* thread, methodOopDesc* method, address bcp))
609251881Speter  JvmtiExport::post_raw_breakpoint(thread, method, bcp);
610251881SpeterIRT_END
611251881Speter
612251881SpeterIRT_ENTRY(void, InterpreterRuntime::resolve_invoke(JavaThread* thread, Bytecodes::Code bytecode))
613251881Speter  // extract receiver from the outgoing argument list if necessary
614251881Speter  Handle receiver(thread, NULL);
615251881Speter  if (bytecode == Bytecodes::_invokevirtual || bytecode == Bytecodes::_invokeinterface) {
616251881Speter    ResourceMark rm(thread);
617251881Speter    methodHandle m (thread, method(thread));
618251881Speter    int bci = m->bci_from(bcp(thread));
619251881Speter    Bytecode_invoke* call = Bytecode_invoke_at(m, bci);
620251881Speter    symbolHandle signature (thread, call->signature());
621251881Speter    receiver = Handle(thread,
622251881Speter                  thread->last_frame().interpreter_callee_receiver(signature));
623251881Speter    assert(Universe::heap()->is_in_reserved_or_null(receiver()),
624251881Speter           "sanity check");
625251881Speter    assert(receiver.is_null() ||
626251881Speter           Universe::heap()->is_in_reserved(receiver->klass()),
627251881Speter           "sanity check");
628251881Speter  }
629251881Speter
630251881Speter  // resolve method
631251881Speter  CallInfo info;
632251881Speter  constantPoolHandle pool(thread, method(thread)->constants());
633251881Speter
634251881Speter  {
635251881Speter    JvmtiHideSingleStepping jhss(thread);
636251881Speter    LinkResolver::resolve_invoke(info, receiver, pool,
637251881Speter                                 two_byte_index(thread), bytecode, CHECK);
638251881Speter    if (JvmtiExport::can_hotswap_or_post_breakpoint()) {
639251881Speter      int retry_count = 0;
640251881Speter      while (info.resolved_method()->is_old()) {
641251881Speter        // It is very unlikely that method is redefined more than 100 times
642251881Speter        // in the middle of resolve. If it is looping here more than 100 times
643251881Speter        // means then there could be a bug here.
644251881Speter        guarantee((retry_count++ < 100),
645251881Speter                  "Could not resolve to latest version of redefined method");
646251881Speter        // method is redefined in the middle of resolve so re-try.
647251881Speter        LinkResolver::resolve_invoke(info, receiver, pool,
648251881Speter                                     two_byte_index(thread), bytecode, CHECK);
649251881Speter      }
650251881Speter    }
651251881Speter  } // end JvmtiHideSingleStepping
652251881Speter
653251881Speter  // check if link resolution caused cpCache to be updated
654251881Speter  if (already_resolved(thread)) return;
655251881Speter
656251881Speter  if (bytecode == Bytecodes::_invokeinterface) {
657251881Speter
658251881Speter    if (TraceItables && Verbose) {
659251881Speter      ResourceMark rm(thread);
660251881Speter      tty->print_cr("Resolving: klass: %s to method: %s", info.resolved_klass()->name()->as_C_string(), info.resolved_method()->name()->as_C_string());
661251881Speter    }
662251881Speter    if (info.resolved_method()->method_holder() ==
663251881Speter                                            SystemDictionary::Object_klass()) {
664251881Speter      // NOTE: THIS IS A FIX FOR A CORNER CASE in the JVM spec
665251881Speter      // (see also cpCacheOop.cpp for details)
666251881Speter      methodHandle rm = info.resolved_method();
667251881Speter      assert(rm->is_final() || info.has_vtable_index(),
668251881Speter             "should have been set already");
669251881Speter      cache_entry(thread)->set_method(bytecode, rm, info.vtable_index());
670251881Speter    } else {
671251881Speter      // Setup itable entry
672251881Speter      int index = klassItable::compute_itable_index(info.resolved_method()());
673251881Speter      cache_entry(thread)->set_interface_call(info.resolved_method(), index);
674251881Speter    }
675251881Speter  } else {
676251881Speter    cache_entry(thread)->set_method(
677251881Speter      bytecode,
678251881Speter      info.resolved_method(),
679251881Speter      info.vtable_index());
680251881Speter  }
681251881SpeterIRT_END
682251881Speter
683251881Speter
684251881Speter// First time execution:  Resolve symbols, create a permanent CallSite object.
685251881SpeterIRT_ENTRY(void, InterpreterRuntime::resolve_invokedynamic(JavaThread* thread)) {
686251881Speter  ResourceMark rm(thread);
687251881Speter
688251881Speter  assert(EnableInvokeDynamic, "");
689251881Speter
690251881Speter  const Bytecodes::Code bytecode = Bytecodes::_invokedynamic;
691251881Speter
692251881Speter  methodHandle caller_method(thread, method(thread));
693251881Speter
694251881Speter  // first find the bootstrap method
695251881Speter  KlassHandle caller_klass(thread, caller_method->method_holder());
696251881Speter  Handle bootm = SystemDictionary::find_bootstrap_method(caller_klass, CHECK);
697251881Speter
698251881Speter  constantPoolHandle pool(thread, caller_method->constants());
699251881Speter  pool->set_invokedynamic();    // mark header to flag active call sites
700251881Speter
701251881Speter  int caller_bci = 0;
702251881Speter  int site_index = 0;
703251881Speter  { address caller_bcp = bcp(thread);
704251881Speter    caller_bci = caller_method->bci_from(caller_bcp);
705251881Speter    site_index = Bytes::get_native_u4(caller_bcp+1);
706251881Speter  }
707251881Speter  assert(site_index == four_byte_index(thread), "");
708251881Speter  assert(constantPoolCacheOopDesc::is_secondary_index(site_index), "proper format");
709251881Speter  // there is a second CPC entries that is of interest; it caches signature info:
710251881Speter  int main_index = pool->cache()->secondary_entry_at(site_index)->main_entry_index();
711251881Speter
712251881Speter  // first resolve the signature to a MH.invoke methodOop
713251881Speter  if (!pool->cache()->entry_at(main_index)->is_resolved(bytecode)) {
714251881Speter    JvmtiHideSingleStepping jhss(thread);
715251881Speter    CallInfo info;
716251881Speter    LinkResolver::resolve_invoke(info, Handle(), pool,
717251881Speter                                 site_index, bytecode, CHECK);
718251881Speter    // The main entry corresponds to a JVM_CONSTANT_NameAndType, and serves
719251881Speter    // as a common reference point for all invokedynamic call sites with
720251881Speter    // that exact call descriptor.  We will link it in the CP cache exactly
721251881Speter    // as if it were an invokevirtual of MethodHandle.invoke.
722251881Speter    pool->cache()->entry_at(main_index)->set_method(
723251881Speter      bytecode,
724251881Speter      info.resolved_method(),
725251881Speter      info.vtable_index());
726251881Speter    assert(pool->cache()->entry_at(main_index)->is_vfinal(), "f2 must be a methodOop");
727251881Speter  }
728251881Speter
729251881Speter  // The method (f2 entry) of the main entry is the MH.invoke for the
730251881Speter  // invokedynamic target call signature.
731251881Speter  intptr_t f2_value = pool->cache()->entry_at(main_index)->f2();
732251881Speter  methodHandle signature_invoker(THREAD, (methodOop) f2_value);
733251881Speter  assert(signature_invoker.not_null() && signature_invoker->is_method() && signature_invoker->is_method_handle_invoke(),
734251881Speter         "correct result from LinkResolver::resolve_invokedynamic");
735251881Speter
736251881Speter  symbolHandle call_site_name(THREAD, pool->name_ref_at(site_index));
737251881Speter
738251881Speter  Handle info;  // NYI: Other metadata from a new kind of CP entry.  (Annotations?)
739251881Speter
740251881Speter  // this is the index which gets stored on the CallSite object (as "callerPosition"):
741251881Speter  int call_site_position = constantPoolCacheOopDesc::decode_secondary_index(site_index);
742251881Speter
743251881Speter  Handle call_site
744251881Speter    = SystemDictionary::make_dynamic_call_site(bootm,
745251881Speter                                               // Callee information:
746251881Speter                                               call_site_name,
747251881Speter                                               signature_invoker,
748251881Speter                                               info,
749251881Speter                                               // Caller information:
750251881Speter                                               caller_method,
751251881Speter                                               caller_bci,
752251881Speter                                               CHECK);
753251881Speter
754251881Speter  // In the secondary entry, the f1 field is the call site, and the f2 (index)
755251881Speter  // field is some data about the invoke site.  Currently, it is just the BCI.
756251881Speter  // Later, it might be changed to help manage inlining dependencies.
757251881Speter  pool->cache()->secondary_entry_at(site_index)->set_dynamic_call(call_site, signature_invoker);
758251881Speter}
759251881SpeterIRT_END
760251881Speter
761251881Speter
762251881Speter//------------------------------------------------------------------------------------------------------------------------
763251881Speter// Miscellaneous
764251881Speter
765251881Speter
766251881Speter#ifndef PRODUCT
767251881Speterstatic void trace_frequency_counter_overflow(methodHandle m, int branch_bci, int bci, address branch_bcp) {
768251881Speter  if (TraceInvocationCounterOverflow) {
769251881Speter    InvocationCounter* ic = m->invocation_counter();
770251881Speter    InvocationCounter* bc = m->backedge_counter();
771251881Speter    ResourceMark rm;
772251881Speter    const char* msg =
773251881Speter      branch_bcp == NULL
774251881Speter      ? "comp-policy cntr ovfl @ %d in entry of "
775251881Speter      : "comp-policy cntr ovfl @ %d in loop of ";
776251881Speter    tty->print(msg, bci);
777251881Speter    m->print_value();
778251881Speter    tty->cr();
779251881Speter    ic->print();
780251881Speter    bc->print();
781251881Speter    if (ProfileInterpreter) {
782251881Speter      if (branch_bcp != NULL) {
783251881Speter        methodDataOop mdo = m->method_data();
784251881Speter        if (mdo != NULL) {
785251881Speter          int count = mdo->bci_to_data(branch_bci)->as_JumpData()->taken();
786251881Speter          tty->print_cr("back branch count = %d", count);
787251881Speter        }
788251881Speter      }
789251881Speter    }
790251881Speter  }
791251881Speter}
792251881Speter
793251881Speterstatic void trace_osr_request(methodHandle method, nmethod* osr, int bci) {
794251881Speter  if (TraceOnStackReplacement) {
795251881Speter    ResourceMark rm;
796251881Speter    tty->print(osr != NULL ? "Reused OSR entry for " : "Requesting OSR entry for ");
797251881Speter    method->print_short_name(tty);
798251881Speter    tty->print_cr(" at bci %d", bci);
799251881Speter  }
800251881Speter}
801251881Speter#endif // !PRODUCT
802251881Speter
803251881Speternmethod* InterpreterRuntime::frequency_counter_overflow(JavaThread* thread, address branch_bcp) {
804251881Speter  nmethod* nm = frequency_counter_overflow_inner(thread, branch_bcp);
805251881Speter  assert(branch_bcp != NULL || nm == NULL, "always returns null for non OSR requests");
806251881Speter  if (branch_bcp != NULL && nm != NULL) {
807251881Speter    // This was a successful request for an OSR nmethod.  Because
808251881Speter    // frequency_counter_overflow_inner ends with a safepoint check,
809    // nm could have been unloaded so look it up again.  It's unsafe
810    // to examine nm directly since it might have been freed and used
811    // for something else.
812    frame fr = thread->last_frame();
813    methodOop method =  fr.interpreter_frame_method();
814    int bci = method->bci_from(fr.interpreter_frame_bcp());
815    nm = method->lookup_osr_nmethod_for(bci);
816  }
817  return nm;
818}
819
820IRT_ENTRY(nmethod*,
821          InterpreterRuntime::frequency_counter_overflow_inner(JavaThread* thread, address branch_bcp))
822  // use UnlockFlagSaver to clear and restore the _do_not_unlock_if_synchronized
823  // flag, in case this method triggers classloading which will call into Java.
824  UnlockFlagSaver fs(thread);
825
826  frame fr = thread->last_frame();
827  assert(fr.is_interpreted_frame(), "must come from interpreter");
828  methodHandle method(thread, fr.interpreter_frame_method());
829  const int branch_bci = branch_bcp != NULL ? method->bci_from(branch_bcp) : 0;
830  const int bci = method->bci_from(fr.interpreter_frame_bcp());
831  NOT_PRODUCT(trace_frequency_counter_overflow(method, branch_bci, bci, branch_bcp);)
832
833  if (JvmtiExport::can_post_interpreter_events()) {
834    if (thread->is_interp_only_mode()) {
835      // If certain JVMTI events (e.g. frame pop event) are requested then the
836      // thread is forced to remain in interpreted code. This is
837      // implemented partly by a check in the run_compiled_code
838      // section of the interpreter whether we should skip running
839      // compiled code, and partly by skipping OSR compiles for
840      // interpreted-only threads.
841      if (branch_bcp != NULL) {
842        CompilationPolicy::policy()->reset_counter_for_back_branch_event(method);
843        return NULL;
844      }
845    }
846  }
847
848  if (branch_bcp == NULL) {
849    // when code cache is full, compilation gets switched off, UseCompiler
850    // is set to false
851    if (!method->has_compiled_code() && UseCompiler) {
852      CompilationPolicy::policy()->method_invocation_event(method, CHECK_NULL);
853    } else {
854      // Force counter overflow on method entry, even if no compilation
855      // happened.  (The method_invocation_event call does this also.)
856      CompilationPolicy::policy()->reset_counter_for_invocation_event(method);
857    }
858    // compilation at an invocation overflow no longer goes and retries test for
859    // compiled method. We always run the loser of the race as interpreted.
860    // so return NULL
861    return NULL;
862  } else {
863    // counter overflow in a loop => try to do on-stack-replacement
864    nmethod* osr_nm = method->lookup_osr_nmethod_for(bci);
865    NOT_PRODUCT(trace_osr_request(method, osr_nm, bci);)
866    // when code cache is full, we should not compile any more...
867    if (osr_nm == NULL && UseCompiler) {
868      const int branch_bci = method->bci_from(branch_bcp);
869      CompilationPolicy::policy()->method_back_branch_event(method, branch_bci, bci, CHECK_NULL);
870      osr_nm = method->lookup_osr_nmethod_for(bci);
871    }
872    if (osr_nm == NULL) {
873      CompilationPolicy::policy()->reset_counter_for_back_branch_event(method);
874      return NULL;
875    } else {
876      // We may need to do on-stack replacement which requires that no
877      // monitors in the activation are biased because their
878      // BasicObjectLocks will need to migrate during OSR. Force
879      // unbiasing of all monitors in the activation now (even though
880      // the OSR nmethod might be invalidated) because we don't have a
881      // safepoint opportunity later once the migration begins.
882      if (UseBiasedLocking) {
883        ResourceMark rm;
884        GrowableArray<Handle>* objects_to_revoke = new GrowableArray<Handle>();
885        for( BasicObjectLock *kptr = fr.interpreter_frame_monitor_end();
886             kptr < fr.interpreter_frame_monitor_begin();
887             kptr = fr.next_monitor_in_interpreter_frame(kptr) ) {
888          if( kptr->obj() != NULL ) {
889            objects_to_revoke->append(Handle(THREAD, kptr->obj()));
890          }
891        }
892        BiasedLocking::revoke(objects_to_revoke);
893      }
894      return osr_nm;
895    }
896  }
897IRT_END
898
899IRT_LEAF(jint, InterpreterRuntime::bcp_to_di(methodOopDesc* method, address cur_bcp))
900  assert(ProfileInterpreter, "must be profiling interpreter");
901  int bci = method->bci_from(cur_bcp);
902  methodDataOop mdo = method->method_data();
903  if (mdo == NULL)  return 0;
904  return mdo->bci_to_di(bci);
905IRT_END
906
907IRT_ENTRY(jint, InterpreterRuntime::profile_method(JavaThread* thread, address cur_bcp))
908  // use UnlockFlagSaver to clear and restore the _do_not_unlock_if_synchronized
909  // flag, in case this method triggers classloading which will call into Java.
910  UnlockFlagSaver fs(thread);
911
912  assert(ProfileInterpreter, "must be profiling interpreter");
913  frame fr = thread->last_frame();
914  assert(fr.is_interpreted_frame(), "must come from interpreter");
915  methodHandle method(thread, fr.interpreter_frame_method());
916  int bci = method->bci_from(cur_bcp);
917  methodOopDesc::build_interpreter_method_data(method, THREAD);
918  if (HAS_PENDING_EXCEPTION) {
919    assert((PENDING_EXCEPTION->is_a(SystemDictionary::OutOfMemoryError_klass())), "we expect only an OOM error here");
920    CLEAR_PENDING_EXCEPTION;
921    // and fall through...
922  }
923  methodDataOop mdo = method->method_data();
924  if (mdo == NULL)  return 0;
925  return mdo->bci_to_di(bci);
926IRT_END
927
928
929#ifdef ASSERT
930IRT_LEAF(void, InterpreterRuntime::verify_mdp(methodOopDesc* method, address bcp, address mdp))
931  assert(ProfileInterpreter, "must be profiling interpreter");
932
933  methodDataOop mdo = method->method_data();
934  assert(mdo != NULL, "must not be null");
935
936  int bci = method->bci_from(bcp);
937
938  address mdp2 = mdo->bci_to_dp(bci);
939  if (mdp != mdp2) {
940    ResourceMark rm;
941    ResetNoHandleMark rnm; // In a LEAF entry.
942    HandleMark hm;
943    tty->print_cr("FAILED verify : actual mdp %p   expected mdp %p @ bci %d", mdp, mdp2, bci);
944    int current_di = mdo->dp_to_di(mdp);
945    int expected_di  = mdo->dp_to_di(mdp2);
946    tty->print_cr("  actual di %d   expected di %d", current_di, expected_di);
947    int expected_approx_bci = mdo->data_at(expected_di)->bci();
948    int approx_bci = -1;
949    if (current_di >= 0) {
950      approx_bci = mdo->data_at(current_di)->bci();
951    }
952    tty->print_cr("  actual bci is %d  expected bci %d", approx_bci, expected_approx_bci);
953    mdo->print_on(tty);
954    method->print_codes();
955  }
956  assert(mdp == mdp2, "wrong mdp");
957IRT_END
958#endif // ASSERT
959
960IRT_ENTRY(void, InterpreterRuntime::update_mdp_for_ret(JavaThread* thread, int return_bci))
961  assert(ProfileInterpreter, "must be profiling interpreter");
962  ResourceMark rm(thread);
963  HandleMark hm(thread);
964  frame fr = thread->last_frame();
965  assert(fr.is_interpreted_frame(), "must come from interpreter");
966  methodDataHandle h_mdo(thread, fr.interpreter_frame_method()->method_data());
967
968  // Grab a lock to ensure atomic access to setting the return bci and
969  // the displacement.  This can block and GC, invalidating all naked oops.
970  MutexLocker ml(RetData_lock);
971
972  // ProfileData is essentially a wrapper around a derived oop, so we
973  // need to take the lock before making any ProfileData structures.
974  ProfileData* data = h_mdo->data_at(h_mdo->dp_to_di(fr.interpreter_frame_mdp()));
975  RetData* rdata = data->as_RetData();
976  address new_mdp = rdata->fixup_ret(return_bci, h_mdo);
977  fr.interpreter_frame_set_mdp(new_mdp);
978IRT_END
979
980
981IRT_ENTRY(void, InterpreterRuntime::at_safepoint(JavaThread* thread))
982  // We used to need an explict preserve_arguments here for invoke bytecodes. However,
983  // stack traversal automatically takes care of preserving arguments for invoke, so
984  // this is no longer needed.
985
986  // IRT_END does an implicit safepoint check, hence we are guaranteed to block
987  // if this is called during a safepoint
988
989  if (JvmtiExport::should_post_single_step()) {
990    // We are called during regular safepoints and when the VM is
991    // single stepping. If any thread is marked for single stepping,
992    // then we may have JVMTI work to do.
993    JvmtiExport::at_single_stepping_point(thread, method(thread), bcp(thread));
994  }
995IRT_END
996
997IRT_ENTRY(void, InterpreterRuntime::post_field_access(JavaThread *thread, oopDesc* obj,
998ConstantPoolCacheEntry *cp_entry))
999
1000  // check the access_flags for the field in the klass
1001  instanceKlass* ik = instanceKlass::cast((klassOop)cp_entry->f1());
1002  typeArrayOop fields = ik->fields();
1003  int index = cp_entry->field_index();
1004  assert(index < fields->length(), "holders field index is out of range");
1005  // bail out if field accesses are not watched
1006  if ((fields->ushort_at(index) & JVM_ACC_FIELD_ACCESS_WATCHED) == 0) return;
1007
1008  switch(cp_entry->flag_state()) {
1009    case btos:    // fall through
1010    case ctos:    // fall through
1011    case stos:    // fall through
1012    case itos:    // fall through
1013    case ftos:    // fall through
1014    case ltos:    // fall through
1015    case dtos:    // fall through
1016    case atos: break;
1017    default: ShouldNotReachHere(); return;
1018  }
1019  bool is_static = (obj == NULL);
1020  HandleMark hm(thread);
1021
1022  Handle h_obj;
1023  if (!is_static) {
1024    // non-static field accessors have an object, but we need a handle
1025    h_obj = Handle(thread, obj);
1026  }
1027  instanceKlassHandle h_cp_entry_f1(thread, (klassOop)cp_entry->f1());
1028  jfieldID fid = jfieldIDWorkaround::to_jfieldID(h_cp_entry_f1, cp_entry->f2(), is_static);
1029  JvmtiExport::post_field_access(thread, method(thread), bcp(thread), h_cp_entry_f1, h_obj, fid);
1030IRT_END
1031
1032IRT_ENTRY(void, InterpreterRuntime::post_field_modification(JavaThread *thread,
1033  oopDesc* obj, ConstantPoolCacheEntry *cp_entry, jvalue *value))
1034
1035  klassOop k = (klassOop)cp_entry->f1();
1036
1037  // check the access_flags for the field in the klass
1038  instanceKlass* ik = instanceKlass::cast(k);
1039  typeArrayOop fields = ik->fields();
1040  int index = cp_entry->field_index();
1041  assert(index < fields->length(), "holders field index is out of range");
1042  // bail out if field modifications are not watched
1043  if ((fields->ushort_at(index) & JVM_ACC_FIELD_MODIFICATION_WATCHED) == 0) return;
1044
1045  char sig_type = '\0';
1046
1047  switch(cp_entry->flag_state()) {
1048    case btos: sig_type = 'Z'; break;
1049    case ctos: sig_type = 'C'; break;
1050    case stos: sig_type = 'S'; break;
1051    case itos: sig_type = 'I'; break;
1052    case ftos: sig_type = 'F'; break;
1053    case atos: sig_type = 'L'; break;
1054    case ltos: sig_type = 'J'; break;
1055    case dtos: sig_type = 'D'; break;
1056    default:  ShouldNotReachHere(); return;
1057  }
1058  bool is_static = (obj == NULL);
1059
1060  HandleMark hm(thread);
1061  instanceKlassHandle h_klass(thread, k);
1062  jfieldID fid = jfieldIDWorkaround::to_jfieldID(h_klass, cp_entry->f2(), is_static);
1063  jvalue fvalue;
1064#ifdef _LP64
1065  fvalue = *value;
1066#else
1067  // Long/double values are stored unaligned and also noncontiguously with
1068  // tagged stacks.  We can't just do a simple assignment even in the non-
1069  // J/D cases because a C++ compiler is allowed to assume that a jvalue is
1070  // 8-byte aligned, and interpreter stack slots are only 4-byte aligned.
1071  // We assume that the two halves of longs/doubles are stored in interpreter
1072  // stack slots in platform-endian order.
1073  jlong_accessor u;
1074  jint* newval = (jint*)value;
1075  u.words[0] = newval[0];
1076  u.words[1] = newval[Interpreter::stackElementWords]; // skip if tag
1077  fvalue.j = u.long_value;
1078#endif // _LP64
1079
1080  Handle h_obj;
1081  if (!is_static) {
1082    // non-static field accessors have an object, but we need a handle
1083    h_obj = Handle(thread, obj);
1084  }
1085
1086  JvmtiExport::post_raw_field_modification(thread, method(thread), bcp(thread), h_klass, h_obj,
1087                                           fid, sig_type, &fvalue);
1088IRT_END
1089
1090IRT_ENTRY(void, InterpreterRuntime::post_method_entry(JavaThread *thread))
1091  JvmtiExport::post_method_entry(thread, InterpreterRuntime::method(thread), InterpreterRuntime::last_frame(thread));
1092IRT_END
1093
1094
1095IRT_ENTRY(void, InterpreterRuntime::post_method_exit(JavaThread *thread))
1096  JvmtiExport::post_method_exit(thread, InterpreterRuntime::method(thread), InterpreterRuntime::last_frame(thread));
1097IRT_END
1098
1099IRT_LEAF(int, InterpreterRuntime::interpreter_contains(address pc))
1100{
1101  return (Interpreter::contains(pc) ? 1 : 0);
1102}
1103IRT_END
1104
1105
1106// Implementation of SignatureHandlerLibrary
1107
1108address SignatureHandlerLibrary::set_handler_blob() {
1109  BufferBlob* handler_blob = BufferBlob::create("native signature handlers", blob_size);
1110  if (handler_blob == NULL) {
1111    return NULL;
1112  }
1113  address handler = handler_blob->instructions_begin();
1114  _handler_blob = handler_blob;
1115  _handler = handler;
1116  return handler;
1117}
1118
1119void SignatureHandlerLibrary::initialize() {
1120  if (_fingerprints != NULL) {
1121    return;
1122  }
1123  if (set_handler_blob() == NULL) {
1124    vm_exit_out_of_memory(blob_size, "native signature handlers");
1125  }
1126
1127  BufferBlob* bb = BufferBlob::create("Signature Handler Temp Buffer",
1128                                      SignatureHandlerLibrary::buffer_size);
1129  _buffer = bb->instructions_begin();
1130
1131  _fingerprints = new(ResourceObj::C_HEAP)GrowableArray<uint64_t>(32, true);
1132  _handlers     = new(ResourceObj::C_HEAP)GrowableArray<address>(32, true);
1133}
1134
1135address SignatureHandlerLibrary::set_handler(CodeBuffer* buffer) {
1136  address handler   = _handler;
1137  int     code_size = buffer->pure_code_size();
1138  if (handler + code_size > _handler_blob->instructions_end()) {
1139    // get a new handler blob
1140    handler = set_handler_blob();
1141  }
1142  if (handler != NULL) {
1143    memcpy(handler, buffer->code_begin(), code_size);
1144    pd_set_handler(handler);
1145    ICache::invalidate_range(handler, code_size);
1146    _handler = handler + code_size;
1147  }
1148  return handler;
1149}
1150
1151void SignatureHandlerLibrary::add(methodHandle method) {
1152  if (method->signature_handler() == NULL) {
1153    // use slow signature handler if we can't do better
1154    int handler_index = -1;
1155    // check if we can use customized (fast) signature handler
1156    if (UseFastSignatureHandlers && method->size_of_parameters() <= Fingerprinter::max_size_of_parameters) {
1157      // use customized signature handler
1158      MutexLocker mu(SignatureHandlerLibrary_lock);
1159      // make sure data structure is initialized
1160      initialize();
1161      // lookup method signature's fingerprint
1162      uint64_t fingerprint = Fingerprinter(method).fingerprint();
1163      handler_index = _fingerprints->find(fingerprint);
1164      // create handler if necessary
1165      if (handler_index < 0) {
1166        ResourceMark rm;
1167        ptrdiff_t align_offset = (address)
1168          round_to((intptr_t)_buffer, CodeEntryAlignment) - (address)_buffer;
1169        CodeBuffer buffer((address)(_buffer + align_offset),
1170                          SignatureHandlerLibrary::buffer_size - align_offset);
1171        InterpreterRuntime::SignatureHandlerGenerator(method, &buffer).generate(fingerprint);
1172        // copy into code heap
1173        address handler = set_handler(&buffer);
1174        if (handler == NULL) {
1175          // use slow signature handler
1176        } else {
1177          // debugging suppport
1178          if (PrintSignatureHandlers) {
1179            tty->cr();
1180            tty->print_cr("argument handler #%d for: %s %s (fingerprint = " UINT64_FORMAT ", %d bytes generated)",
1181                          _handlers->length(),
1182                          (method->is_static() ? "static" : "receiver"),
1183                          method->name_and_sig_as_C_string(),
1184                          fingerprint,
1185                          buffer.code_size());
1186            Disassembler::decode(handler, handler + buffer.code_size());
1187#ifndef PRODUCT
1188            tty->print_cr(" --- associated result handler ---");
1189            address rh_begin = Interpreter::result_handler(method()->result_type());
1190            address rh_end = rh_begin;
1191            while (*(int*)rh_end != 0) {
1192              rh_end += sizeof(int);
1193            }
1194            Disassembler::decode(rh_begin, rh_end);
1195#endif
1196          }
1197          // add handler to library
1198          _fingerprints->append(fingerprint);
1199          _handlers->append(handler);
1200          // set handler index
1201          assert(_fingerprints->length() == _handlers->length(), "sanity check");
1202          handler_index = _fingerprints->length() - 1;
1203        }
1204      }
1205    } else {
1206      CHECK_UNHANDLED_OOPS_ONLY(Thread::current()->clear_unhandled_oops());
1207    }
1208    if (handler_index < 0) {
1209      // use generic signature handler
1210      method->set_signature_handler(Interpreter::slow_signature_handler());
1211    } else {
1212      // set handler
1213      method->set_signature_handler(_handlers->at(handler_index));
1214    }
1215  }
1216  assert(method->signature_handler() == Interpreter::slow_signature_handler() ||
1217         _handlers->find(method->signature_handler()) == _fingerprints->find(Fingerprinter(method).fingerprint()),
1218         "sanity check");
1219}
1220
1221
1222BufferBlob*              SignatureHandlerLibrary::_handler_blob = NULL;
1223address                  SignatureHandlerLibrary::_handler      = NULL;
1224GrowableArray<uint64_t>* SignatureHandlerLibrary::_fingerprints = NULL;
1225GrowableArray<address>*  SignatureHandlerLibrary::_handlers     = NULL;
1226address                  SignatureHandlerLibrary::_buffer       = NULL;
1227
1228
1229IRT_ENTRY(void, InterpreterRuntime::prepare_native_call(JavaThread* thread, methodOopDesc* method))
1230  methodHandle m(thread, method);
1231  assert(m->is_native(), "sanity check");
1232  // lookup native function entry point if it doesn't exist
1233  bool in_base_library;
1234  if (!m->has_native_function()) {
1235    NativeLookup::lookup(m, in_base_library, CHECK);
1236  }
1237  // make sure signature handler is installed
1238  SignatureHandlerLibrary::add(m);
1239  // The interpreter entry point checks the signature handler first,
1240  // before trying to fetch the native entry point and klass mirror.
1241  // We must set the signature handler last, so that multiple processors
1242  // preparing the same method will be sure to see non-null entry & mirror.
1243IRT_END
1244
1245#if defined(IA32) || defined(AMD64)
1246IRT_LEAF(void, InterpreterRuntime::popframe_move_outgoing_args(JavaThread* thread, void* src_address, void* dest_address))
1247  if (src_address == dest_address) {
1248    return;
1249  }
1250  ResetNoHandleMark rnm; // In a LEAF entry.
1251  HandleMark hm;
1252  ResourceMark rm;
1253  frame fr = thread->last_frame();
1254  assert(fr.is_interpreted_frame(), "");
1255  jint bci = fr.interpreter_frame_bci();
1256  methodHandle mh(thread, fr.interpreter_frame_method());
1257  Bytecode_invoke* invoke = Bytecode_invoke_at(mh, bci);
1258  ArgumentSizeComputer asc(invoke->signature());
1259  int size_of_arguments = (asc.size() + (invoke->has_receiver() ? 1 : 0)); // receiver
1260  Copy::conjoint_bytes(src_address, dest_address,
1261                       size_of_arguments * Interpreter::stackElementSize);
1262IRT_END
1263#endif
1264