c1_Runtime1.cpp revision 3274:0105f367a14c
1/*
2 * Copyright (c) 1999, 2012, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
24
25#include "precompiled.hpp"
26#include "asm/codeBuffer.hpp"
27#include "c1/c1_CodeStubs.hpp"
28#include "c1/c1_Defs.hpp"
29#include "c1/c1_FrameMap.hpp"
30#include "c1/c1_LIRAssembler.hpp"
31#include "c1/c1_MacroAssembler.hpp"
32#include "c1/c1_Runtime1.hpp"
33#include "classfile/systemDictionary.hpp"
34#include "classfile/vmSymbols.hpp"
35#include "code/codeBlob.hpp"
36#include "code/compiledIC.hpp"
37#include "code/pcDesc.hpp"
38#include "code/scopeDesc.hpp"
39#include "code/vtableStubs.hpp"
40#include "compiler/disassembler.hpp"
41#include "gc_interface/collectedHeap.hpp"
42#include "interpreter/bytecode.hpp"
43#include "interpreter/interpreter.hpp"
44#include "memory/allocation.inline.hpp"
45#include "memory/barrierSet.hpp"
46#include "memory/oopFactory.hpp"
47#include "memory/resourceArea.hpp"
48#include "oops/objArrayKlass.hpp"
49#include "oops/oop.inline.hpp"
50#include "runtime/biasedLocking.hpp"
51#include "runtime/compilationPolicy.hpp"
52#include "runtime/interfaceSupport.hpp"
53#include "runtime/javaCalls.hpp"
54#include "runtime/sharedRuntime.hpp"
55#include "runtime/threadCritical.hpp"
56#include "runtime/vframe.hpp"
57#include "runtime/vframeArray.hpp"
58#include "utilities/copy.hpp"
59#include "utilities/events.hpp"
60
61
62// Implementation of StubAssembler
63
64StubAssembler::StubAssembler(CodeBuffer* code, const char * name, int stub_id) : C1_MacroAssembler(code) {
65  _name = name;
66  _must_gc_arguments = false;
67  _frame_size = no_frame_size;
68  _num_rt_args = 0;
69  _stub_id = stub_id;
70}
71
72
73void StubAssembler::set_info(const char* name, bool must_gc_arguments) {
74  _name = name;
75  _must_gc_arguments = must_gc_arguments;
76}
77
78
79void StubAssembler::set_frame_size(int size) {
80  if (_frame_size == no_frame_size) {
81    _frame_size = size;
82  }
83  assert(_frame_size == size, "can't change the frame size");
84}
85
86
87void StubAssembler::set_num_rt_args(int args) {
88  if (_num_rt_args == 0) {
89    _num_rt_args = args;
90  }
91  assert(_num_rt_args == args, "can't change the number of args");
92}
93
94// Implementation of Runtime1
95
96CodeBlob* Runtime1::_blobs[Runtime1::number_of_ids];
97const char *Runtime1::_blob_names[] = {
98  RUNTIME1_STUBS(STUB_NAME, LAST_STUB_NAME)
99};
100
101#ifndef PRODUCT
102// statistics
103int Runtime1::_generic_arraycopy_cnt = 0;
104int Runtime1::_primitive_arraycopy_cnt = 0;
105int Runtime1::_oop_arraycopy_cnt = 0;
106int Runtime1::_generic_arraycopystub_cnt = 0;
107int Runtime1::_arraycopy_slowcase_cnt = 0;
108int Runtime1::_arraycopy_checkcast_cnt = 0;
109int Runtime1::_arraycopy_checkcast_attempt_cnt = 0;
110int Runtime1::_new_type_array_slowcase_cnt = 0;
111int Runtime1::_new_object_array_slowcase_cnt = 0;
112int Runtime1::_new_instance_slowcase_cnt = 0;
113int Runtime1::_new_multi_array_slowcase_cnt = 0;
114int Runtime1::_monitorenter_slowcase_cnt = 0;
115int Runtime1::_monitorexit_slowcase_cnt = 0;
116int Runtime1::_patch_code_slowcase_cnt = 0;
117int Runtime1::_throw_range_check_exception_count = 0;
118int Runtime1::_throw_index_exception_count = 0;
119int Runtime1::_throw_div0_exception_count = 0;
120int Runtime1::_throw_null_pointer_exception_count = 0;
121int Runtime1::_throw_class_cast_exception_count = 0;
122int Runtime1::_throw_incompatible_class_change_error_count = 0;
123int Runtime1::_throw_array_store_exception_count = 0;
124int Runtime1::_throw_count = 0;
125
126static int _byte_arraycopy_cnt = 0;
127static int _short_arraycopy_cnt = 0;
128static int _int_arraycopy_cnt = 0;
129static int _long_arraycopy_cnt = 0;
130static int _oop_arraycopy_cnt = 0;
131
132address Runtime1::arraycopy_count_address(BasicType type) {
133  switch (type) {
134  case T_BOOLEAN:
135  case T_BYTE:   return (address)&_byte_arraycopy_cnt;
136  case T_CHAR:
137  case T_SHORT:  return (address)&_short_arraycopy_cnt;
138  case T_FLOAT:
139  case T_INT:    return (address)&_int_arraycopy_cnt;
140  case T_DOUBLE:
141  case T_LONG:   return (address)&_long_arraycopy_cnt;
142  case T_ARRAY:
143  case T_OBJECT: return (address)&_oop_arraycopy_cnt;
144  default:
145    ShouldNotReachHere();
146    return NULL;
147  }
148}
149
150
151#endif
152
153// Simple helper to see if the caller of a runtime stub which
154// entered the VM has been deoptimized
155
156static bool caller_is_deopted() {
157  JavaThread* thread = JavaThread::current();
158  RegisterMap reg_map(thread, false);
159  frame runtime_frame = thread->last_frame();
160  frame caller_frame = runtime_frame.sender(&reg_map);
161  assert(caller_frame.is_compiled_frame(), "must be compiled");
162  return caller_frame.is_deoptimized_frame();
163}
164
165// Stress deoptimization
166static void deopt_caller() {
167  if ( !caller_is_deopted()) {
168    JavaThread* thread = JavaThread::current();
169    RegisterMap reg_map(thread, false);
170    frame runtime_frame = thread->last_frame();
171    frame caller_frame = runtime_frame.sender(&reg_map);
172    Deoptimization::deoptimize_frame(thread, caller_frame.id());
173    assert(caller_is_deopted(), "Must be deoptimized");
174  }
175}
176
177
178void Runtime1::generate_blob_for(BufferBlob* buffer_blob, StubID id) {
179  assert(0 <= id && id < number_of_ids, "illegal stub id");
180  ResourceMark rm;
181  // create code buffer for code storage
182  CodeBuffer code(buffer_blob);
183
184  Compilation::setup_code_buffer(&code, 0);
185
186  // create assembler for code generation
187  StubAssembler* sasm = new StubAssembler(&code, name_for(id), id);
188  // generate code for runtime stub
189  OopMapSet* oop_maps;
190  oop_maps = generate_code_for(id, sasm);
191  assert(oop_maps == NULL || sasm->frame_size() != no_frame_size,
192         "if stub has an oop map it must have a valid frame size");
193
194#ifdef ASSERT
195  // Make sure that stubs that need oopmaps have them
196  switch (id) {
197    // These stubs don't need to have an oopmap
198    case dtrace_object_alloc_id:
199    case g1_pre_barrier_slow_id:
200    case g1_post_barrier_slow_id:
201    case slow_subtype_check_id:
202    case fpu2long_stub_id:
203    case unwind_exception_id:
204    case counter_overflow_id:
205#if defined(SPARC) || defined(PPC)
206    case handle_exception_nofpu_id:  // Unused on sparc
207#endif
208      break;
209
210    // All other stubs should have oopmaps
211    default:
212      assert(oop_maps != NULL, "must have an oopmap");
213  }
214#endif
215
216  // align so printing shows nop's instead of random code at the end (SimpleStubs are aligned)
217  sasm->align(BytesPerWord);
218  // make sure all code is in code buffer
219  sasm->flush();
220  // create blob - distinguish a few special cases
221  CodeBlob* blob = RuntimeStub::new_runtime_stub(name_for(id),
222                                                 &code,
223                                                 CodeOffsets::frame_never_safe,
224                                                 sasm->frame_size(),
225                                                 oop_maps,
226                                                 sasm->must_gc_arguments());
227  // install blob
228  assert(blob != NULL, "blob must exist");
229  _blobs[id] = blob;
230}
231
232
233void Runtime1::initialize(BufferBlob* blob) {
234  // platform-dependent initialization
235  initialize_pd();
236  // generate stubs
237  for (int id = 0; id < number_of_ids; id++) generate_blob_for(blob, (StubID)id);
238  // printing
239#ifndef PRODUCT
240  if (PrintSimpleStubs) {
241    ResourceMark rm;
242    for (int id = 0; id < number_of_ids; id++) {
243      _blobs[id]->print();
244      if (_blobs[id]->oop_maps() != NULL) {
245        _blobs[id]->oop_maps()->print();
246      }
247    }
248  }
249#endif
250}
251
252
253CodeBlob* Runtime1::blob_for(StubID id) {
254  assert(0 <= id && id < number_of_ids, "illegal stub id");
255  return _blobs[id];
256}
257
258
259const char* Runtime1::name_for(StubID id) {
260  assert(0 <= id && id < number_of_ids, "illegal stub id");
261  return _blob_names[id];
262}
263
264const char* Runtime1::name_for_address(address entry) {
265  for (int id = 0; id < number_of_ids; id++) {
266    if (entry == entry_for((StubID)id)) return name_for((StubID)id);
267  }
268
269#define FUNCTION_CASE(a, f) \
270  if ((intptr_t)a == CAST_FROM_FN_PTR(intptr_t, f))  return #f
271
272  FUNCTION_CASE(entry, os::javaTimeMillis);
273  FUNCTION_CASE(entry, os::javaTimeNanos);
274  FUNCTION_CASE(entry, SharedRuntime::OSR_migration_end);
275  FUNCTION_CASE(entry, SharedRuntime::d2f);
276  FUNCTION_CASE(entry, SharedRuntime::d2i);
277  FUNCTION_CASE(entry, SharedRuntime::d2l);
278  FUNCTION_CASE(entry, SharedRuntime::dcos);
279  FUNCTION_CASE(entry, SharedRuntime::dexp);
280  FUNCTION_CASE(entry, SharedRuntime::dlog);
281  FUNCTION_CASE(entry, SharedRuntime::dlog10);
282  FUNCTION_CASE(entry, SharedRuntime::dpow);
283  FUNCTION_CASE(entry, SharedRuntime::drem);
284  FUNCTION_CASE(entry, SharedRuntime::dsin);
285  FUNCTION_CASE(entry, SharedRuntime::dtan);
286  FUNCTION_CASE(entry, SharedRuntime::f2i);
287  FUNCTION_CASE(entry, SharedRuntime::f2l);
288  FUNCTION_CASE(entry, SharedRuntime::frem);
289  FUNCTION_CASE(entry, SharedRuntime::l2d);
290  FUNCTION_CASE(entry, SharedRuntime::l2f);
291  FUNCTION_CASE(entry, SharedRuntime::ldiv);
292  FUNCTION_CASE(entry, SharedRuntime::lmul);
293  FUNCTION_CASE(entry, SharedRuntime::lrem);
294  FUNCTION_CASE(entry, SharedRuntime::lrem);
295  FUNCTION_CASE(entry, SharedRuntime::dtrace_method_entry);
296  FUNCTION_CASE(entry, SharedRuntime::dtrace_method_exit);
297  FUNCTION_CASE(entry, trace_block_entry);
298#ifdef TRACE_HAVE_INTRINSICS
299  FUNCTION_CASE(entry, TRACE_TIME_METHOD);
300#endif
301
302#undef FUNCTION_CASE
303
304  // Soft float adds more runtime names.
305  return pd_name_for_address(entry);
306}
307
308
309JRT_ENTRY(void, Runtime1::new_instance(JavaThread* thread, klassOopDesc* klass))
310  NOT_PRODUCT(_new_instance_slowcase_cnt++;)
311
312  assert(oop(klass)->is_klass(), "not a class");
313  instanceKlassHandle h(thread, klass);
314  h->check_valid_for_instantiation(true, CHECK);
315  // make sure klass is initialized
316  h->initialize(CHECK);
317  // allocate instance and return via TLS
318  oop obj = h->allocate_instance(CHECK);
319  thread->set_vm_result(obj);
320JRT_END
321
322
323JRT_ENTRY(void, Runtime1::new_type_array(JavaThread* thread, klassOopDesc* klass, jint length))
324  NOT_PRODUCT(_new_type_array_slowcase_cnt++;)
325  // Note: no handle for klass needed since they are not used
326  //       anymore after new_typeArray() and no GC can happen before.
327  //       (This may have to change if this code changes!)
328  assert(oop(klass)->is_klass(), "not a class");
329  BasicType elt_type = typeArrayKlass::cast(klass)->element_type();
330  oop obj = oopFactory::new_typeArray(elt_type, length, CHECK);
331  thread->set_vm_result(obj);
332  // This is pretty rare but this runtime patch is stressful to deoptimization
333  // if we deoptimize here so force a deopt to stress the path.
334  if (DeoptimizeALot) {
335    deopt_caller();
336  }
337
338JRT_END
339
340
341JRT_ENTRY(void, Runtime1::new_object_array(JavaThread* thread, klassOopDesc* array_klass, jint length))
342  NOT_PRODUCT(_new_object_array_slowcase_cnt++;)
343
344  // Note: no handle for klass needed since they are not used
345  //       anymore after new_objArray() and no GC can happen before.
346  //       (This may have to change if this code changes!)
347  assert(oop(array_klass)->is_klass(), "not a class");
348  klassOop elem_klass = objArrayKlass::cast(array_klass)->element_klass();
349  objArrayOop obj = oopFactory::new_objArray(elem_klass, length, CHECK);
350  thread->set_vm_result(obj);
351  // This is pretty rare but this runtime patch is stressful to deoptimization
352  // if we deoptimize here so force a deopt to stress the path.
353  if (DeoptimizeALot) {
354    deopt_caller();
355  }
356JRT_END
357
358
359JRT_ENTRY(void, Runtime1::new_multi_array(JavaThread* thread, klassOopDesc* klass, int rank, jint* dims))
360  NOT_PRODUCT(_new_multi_array_slowcase_cnt++;)
361
362  assert(oop(klass)->is_klass(), "not a class");
363  assert(rank >= 1, "rank must be nonzero");
364  oop obj = arrayKlass::cast(klass)->multi_allocate(rank, dims, CHECK);
365  thread->set_vm_result(obj);
366JRT_END
367
368
369JRT_ENTRY(void, Runtime1::unimplemented_entry(JavaThread* thread, StubID id))
370  tty->print_cr("Runtime1::entry_for(%d) returned unimplemented entry point", id);
371JRT_END
372
373
374JRT_ENTRY(void, Runtime1::throw_array_store_exception(JavaThread* thread, oopDesc* obj))
375  ResourceMark rm(thread);
376  const char* klass_name = Klass::cast(obj->klass())->external_name();
377  SharedRuntime::throw_and_post_jvmti_exception(thread, vmSymbols::java_lang_ArrayStoreException(), klass_name);
378JRT_END
379
380
381// counter_overflow() is called from within C1-compiled methods. The enclosing method is the method
382// associated with the top activation record. The inlinee (that is possibly included in the enclosing
383// method) method oop is passed as an argument. In order to do that it is embedded in the code as
384// a constant.
385static nmethod* counter_overflow_helper(JavaThread* THREAD, int branch_bci, methodOopDesc* m) {
386  nmethod* osr_nm = NULL;
387  methodHandle method(THREAD, m);
388
389  RegisterMap map(THREAD, false);
390  frame fr =  THREAD->last_frame().sender(&map);
391  nmethod* nm = (nmethod*) fr.cb();
392  assert(nm!= NULL && nm->is_nmethod(), "Sanity check");
393  methodHandle enclosing_method(THREAD, nm->method());
394
395  CompLevel level = (CompLevel)nm->comp_level();
396  int bci = InvocationEntryBci;
397  if (branch_bci != InvocationEntryBci) {
398    // Compute desination bci
399    address pc = method()->code_base() + branch_bci;
400    Bytecodes::Code branch = Bytecodes::code_at(method(), pc);
401    int offset = 0;
402    switch (branch) {
403      case Bytecodes::_if_icmplt: case Bytecodes::_iflt:
404      case Bytecodes::_if_icmpgt: case Bytecodes::_ifgt:
405      case Bytecodes::_if_icmple: case Bytecodes::_ifle:
406      case Bytecodes::_if_icmpge: case Bytecodes::_ifge:
407      case Bytecodes::_if_icmpeq: case Bytecodes::_if_acmpeq: case Bytecodes::_ifeq:
408      case Bytecodes::_if_icmpne: case Bytecodes::_if_acmpne: case Bytecodes::_ifne:
409      case Bytecodes::_ifnull: case Bytecodes::_ifnonnull: case Bytecodes::_goto:
410        offset = (int16_t)Bytes::get_Java_u2(pc + 1);
411        break;
412      case Bytecodes::_goto_w:
413        offset = Bytes::get_Java_u4(pc + 1);
414        break;
415      default: ;
416    }
417    bci = branch_bci + offset;
418  }
419  assert(!HAS_PENDING_EXCEPTION, "Should not have any exceptions pending");
420  osr_nm = CompilationPolicy::policy()->event(enclosing_method, method, branch_bci, bci, level, nm, THREAD);
421  assert(!HAS_PENDING_EXCEPTION, "Event handler should not throw any exceptions");
422  return osr_nm;
423}
424
425JRT_BLOCK_ENTRY(address, Runtime1::counter_overflow(JavaThread* thread, int bci, methodOopDesc* method))
426  nmethod* osr_nm;
427  JRT_BLOCK
428    osr_nm = counter_overflow_helper(thread, bci, method);
429    if (osr_nm != NULL) {
430      RegisterMap map(thread, false);
431      frame fr =  thread->last_frame().sender(&map);
432      Deoptimization::deoptimize_frame(thread, fr.id());
433    }
434  JRT_BLOCK_END
435  return NULL;
436JRT_END
437
438extern void vm_exit(int code);
439
440// Enter this method from compiled code handler below. This is where we transition
441// to VM mode. This is done as a helper routine so that the method called directly
442// from compiled code does not have to transition to VM. This allows the entry
443// method to see if the nmethod that we have just looked up a handler for has
444// been deoptimized while we were in the vm. This simplifies the assembly code
445// cpu directories.
446//
447// We are entering here from exception stub (via the entry method below)
448// If there is a compiled exception handler in this method, we will continue there;
449// otherwise we will unwind the stack and continue at the caller of top frame method
450// Note: we enter in Java using a special JRT wrapper. This wrapper allows us to
451// control the area where we can allow a safepoint. After we exit the safepoint area we can
452// check to see if the handler we are going to return is now in a nmethod that has
453// been deoptimized. If that is the case we return the deopt blob
454// unpack_with_exception entry instead. This makes life for the exception blob easier
455// because making that same check and diverting is painful from assembly language.
456JRT_ENTRY_NO_ASYNC(static address, exception_handler_for_pc_helper(JavaThread* thread, oopDesc* ex, address pc, nmethod*& nm))
457  // Reset method handle flag.
458  thread->set_is_method_handle_return(false);
459
460  Handle exception(thread, ex);
461  nm = CodeCache::find_nmethod(pc);
462  assert(nm != NULL, "this is not an nmethod");
463  // Adjust the pc as needed/
464  if (nm->is_deopt_pc(pc)) {
465    RegisterMap map(thread, false);
466    frame exception_frame = thread->last_frame().sender(&map);
467    // if the frame isn't deopted then pc must not correspond to the caller of last_frame
468    assert(exception_frame.is_deoptimized_frame(), "must be deopted");
469    pc = exception_frame.pc();
470  }
471#ifdef ASSERT
472  assert(exception.not_null(), "NULL exceptions should be handled by throw_exception");
473  assert(exception->is_oop(), "just checking");
474  // Check that exception is a subclass of Throwable, otherwise we have a VerifyError
475  if (!(exception->is_a(SystemDictionary::Throwable_klass()))) {
476    if (ExitVMOnVerifyError) vm_exit(-1);
477    ShouldNotReachHere();
478  }
479#endif
480
481  // Check the stack guard pages and reenable them if necessary and there is
482  // enough space on the stack to do so.  Use fast exceptions only if the guard
483  // pages are enabled.
484  bool guard_pages_enabled = thread->stack_yellow_zone_enabled();
485  if (!guard_pages_enabled) guard_pages_enabled = thread->reguard_stack();
486
487  if (JvmtiExport::can_post_on_exceptions()) {
488    // To ensure correct notification of exception catches and throws
489    // we have to deoptimize here.  If we attempted to notify the
490    // catches and throws during this exception lookup it's possible
491    // we could deoptimize on the way out of the VM and end back in
492    // the interpreter at the throw site.  This would result in double
493    // notifications since the interpreter would also notify about
494    // these same catches and throws as it unwound the frame.
495
496    RegisterMap reg_map(thread);
497    frame stub_frame = thread->last_frame();
498    frame caller_frame = stub_frame.sender(&reg_map);
499
500    // We don't really want to deoptimize the nmethod itself since we
501    // can actually continue in the exception handler ourselves but I
502    // don't see an easy way to have the desired effect.
503    Deoptimization::deoptimize_frame(thread, caller_frame.id());
504    assert(caller_is_deopted(), "Must be deoptimized");
505
506    return SharedRuntime::deopt_blob()->unpack_with_exception_in_tls();
507  }
508
509  // ExceptionCache is used only for exceptions at call sites and not for implicit exceptions
510  if (guard_pages_enabled) {
511    address fast_continuation = nm->handler_for_exception_and_pc(exception, pc);
512    if (fast_continuation != NULL) {
513      // Set flag if return address is a method handle call site.
514      thread->set_is_method_handle_return(nm->is_method_handle_return(pc));
515      return fast_continuation;
516    }
517  }
518
519  // If the stack guard pages are enabled, check whether there is a handler in
520  // the current method.  Otherwise (guard pages disabled), force an unwind and
521  // skip the exception cache update (i.e., just leave continuation==NULL).
522  address continuation = NULL;
523  if (guard_pages_enabled) {
524
525    // New exception handling mechanism can support inlined methods
526    // with exception handlers since the mappings are from PC to PC
527
528    // debugging support
529    // tracing
530    if (TraceExceptions) {
531      ttyLocker ttyl;
532      ResourceMark rm;
533      tty->print_cr("Exception <%s> (0x%x) thrown in compiled method <%s> at PC " PTR_FORMAT " for thread 0x%x",
534                    exception->print_value_string(), (address)exception(), nm->method()->print_value_string(), pc, thread);
535    }
536    // for AbortVMOnException flag
537    NOT_PRODUCT(Exceptions::debug_check_abort(exception));
538
539    // Clear out the exception oop and pc since looking up an
540    // exception handler can cause class loading, which might throw an
541    // exception and those fields are expected to be clear during
542    // normal bytecode execution.
543    thread->set_exception_oop(NULL);
544    thread->set_exception_pc(NULL);
545
546    continuation = SharedRuntime::compute_compiled_exc_handler(nm, pc, exception, false, false);
547    // If an exception was thrown during exception dispatch, the exception oop may have changed
548    thread->set_exception_oop(exception());
549    thread->set_exception_pc(pc);
550
551    // the exception cache is used only by non-implicit exceptions
552    if (continuation != NULL) {
553      nm->add_handler_for_exception_and_pc(exception, pc, continuation);
554    }
555  }
556
557  thread->set_vm_result(exception());
558  // Set flag if return address is a method handle call site.
559  thread->set_is_method_handle_return(nm->is_method_handle_return(pc));
560
561  if (TraceExceptions) {
562    ttyLocker ttyl;
563    ResourceMark rm;
564    tty->print_cr("Thread " PTR_FORMAT " continuing at PC " PTR_FORMAT " for exception thrown at PC " PTR_FORMAT,
565                  thread, continuation, pc);
566  }
567
568  return continuation;
569JRT_END
570
571// Enter this method from compiled code only if there is a Java exception handler
572// in the method handling the exception.
573// We are entering here from exception stub. We don't do a normal VM transition here.
574// We do it in a helper. This is so we can check to see if the nmethod we have just
575// searched for an exception handler has been deoptimized in the meantime.
576address Runtime1::exception_handler_for_pc(JavaThread* thread) {
577  oop exception = thread->exception_oop();
578  address pc = thread->exception_pc();
579  // Still in Java mode
580  DEBUG_ONLY(ResetNoHandleMark rnhm);
581  nmethod* nm = NULL;
582  address continuation = NULL;
583  {
584    // Enter VM mode by calling the helper
585    ResetNoHandleMark rnhm;
586    continuation = exception_handler_for_pc_helper(thread, exception, pc, nm);
587  }
588  // Back in JAVA, use no oops DON'T safepoint
589
590  // Now check to see if the nmethod we were called from is now deoptimized.
591  // If so we must return to the deopt blob and deoptimize the nmethod
592  if (nm != NULL && caller_is_deopted()) {
593    continuation = SharedRuntime::deopt_blob()->unpack_with_exception_in_tls();
594  }
595
596  assert(continuation != NULL, "no handler found");
597  return continuation;
598}
599
600
601JRT_ENTRY(void, Runtime1::throw_range_check_exception(JavaThread* thread, int index))
602  NOT_PRODUCT(_throw_range_check_exception_count++;)
603  char message[jintAsStringSize];
604  sprintf(message, "%d", index);
605  SharedRuntime::throw_and_post_jvmti_exception(thread, vmSymbols::java_lang_ArrayIndexOutOfBoundsException(), message);
606JRT_END
607
608
609JRT_ENTRY(void, Runtime1::throw_index_exception(JavaThread* thread, int index))
610  NOT_PRODUCT(_throw_index_exception_count++;)
611  char message[16];
612  sprintf(message, "%d", index);
613  SharedRuntime::throw_and_post_jvmti_exception(thread, vmSymbols::java_lang_IndexOutOfBoundsException(), message);
614JRT_END
615
616
617JRT_ENTRY(void, Runtime1::throw_div0_exception(JavaThread* thread))
618  NOT_PRODUCT(_throw_div0_exception_count++;)
619  SharedRuntime::throw_and_post_jvmti_exception(thread, vmSymbols::java_lang_ArithmeticException(), "/ by zero");
620JRT_END
621
622
623JRT_ENTRY(void, Runtime1::throw_null_pointer_exception(JavaThread* thread))
624  NOT_PRODUCT(_throw_null_pointer_exception_count++;)
625  SharedRuntime::throw_and_post_jvmti_exception(thread, vmSymbols::java_lang_NullPointerException());
626JRT_END
627
628
629JRT_ENTRY(void, Runtime1::throw_class_cast_exception(JavaThread* thread, oopDesc* object))
630  NOT_PRODUCT(_throw_class_cast_exception_count++;)
631  ResourceMark rm(thread);
632  char* message = SharedRuntime::generate_class_cast_message(
633    thread, Klass::cast(object->klass())->external_name());
634  SharedRuntime::throw_and_post_jvmti_exception(
635    thread, vmSymbols::java_lang_ClassCastException(), message);
636JRT_END
637
638
639JRT_ENTRY(void, Runtime1::throw_incompatible_class_change_error(JavaThread* thread))
640  NOT_PRODUCT(_throw_incompatible_class_change_error_count++;)
641  ResourceMark rm(thread);
642  SharedRuntime::throw_and_post_jvmti_exception(thread, vmSymbols::java_lang_IncompatibleClassChangeError());
643JRT_END
644
645
646JRT_ENTRY_NO_ASYNC(void, Runtime1::monitorenter(JavaThread* thread, oopDesc* obj, BasicObjectLock* lock))
647  NOT_PRODUCT(_monitorenter_slowcase_cnt++;)
648  if (PrintBiasedLockingStatistics) {
649    Atomic::inc(BiasedLocking::slow_path_entry_count_addr());
650  }
651  Handle h_obj(thread, obj);
652  assert(h_obj()->is_oop(), "must be NULL or an object");
653  if (UseBiasedLocking) {
654    // Retry fast entry if bias is revoked to avoid unnecessary inflation
655    ObjectSynchronizer::fast_enter(h_obj, lock->lock(), true, CHECK);
656  } else {
657    if (UseFastLocking) {
658      // When using fast locking, the compiled code has already tried the fast case
659      assert(obj == lock->obj(), "must match");
660      ObjectSynchronizer::slow_enter(h_obj, lock->lock(), THREAD);
661    } else {
662      lock->set_obj(obj);
663      ObjectSynchronizer::fast_enter(h_obj, lock->lock(), false, THREAD);
664    }
665  }
666JRT_END
667
668
669JRT_LEAF(void, Runtime1::monitorexit(JavaThread* thread, BasicObjectLock* lock))
670  NOT_PRODUCT(_monitorexit_slowcase_cnt++;)
671  assert(thread == JavaThread::current(), "threads must correspond");
672  assert(thread->last_Java_sp(), "last_Java_sp must be set");
673  // monitorexit is non-blocking (leaf routine) => no exceptions can be thrown
674  EXCEPTION_MARK;
675
676  oop obj = lock->obj();
677  assert(obj->is_oop(), "must be NULL or an object");
678  if (UseFastLocking) {
679    // When using fast locking, the compiled code has already tried the fast case
680    ObjectSynchronizer::slow_exit(obj, lock->lock(), THREAD);
681  } else {
682    ObjectSynchronizer::fast_exit(obj, lock->lock(), THREAD);
683  }
684JRT_END
685
686// Cf. OptoRuntime::deoptimize_caller_frame
687JRT_ENTRY(void, Runtime1::deoptimize(JavaThread* thread))
688  // Called from within the owner thread, so no need for safepoint
689  RegisterMap reg_map(thread, false);
690  frame stub_frame = thread->last_frame();
691  assert(stub_frame.is_runtime_frame(), "sanity check");
692  frame caller_frame = stub_frame.sender(&reg_map);
693
694  // We are coming from a compiled method; check this is true.
695  assert(CodeCache::find_nmethod(caller_frame.pc()) != NULL, "sanity");
696
697  // Deoptimize the caller frame.
698  Deoptimization::deoptimize_frame(thread, caller_frame.id());
699
700  // Return to the now deoptimized frame.
701JRT_END
702
703
704static klassOop resolve_field_return_klass(methodHandle caller, int bci, TRAPS) {
705  Bytecode_field field_access(caller, bci);
706  // This can be static or non-static field access
707  Bytecodes::Code code       = field_access.code();
708
709  // We must load class, initialize class and resolvethe field
710  FieldAccessInfo result; // initialize class if needed
711  constantPoolHandle constants(THREAD, caller->constants());
712  LinkResolver::resolve_field(result, constants, field_access.index(), Bytecodes::java_code(code), false, CHECK_NULL);
713  return result.klass()();
714}
715
716
717//
718// This routine patches sites where a class wasn't loaded or
719// initialized at the time the code was generated.  It handles
720// references to classes, fields and forcing of initialization.  Most
721// of the cases are straightforward and involving simply forcing
722// resolution of a class, rewriting the instruction stream with the
723// needed constant and replacing the call in this function with the
724// patched code.  The case for static field is more complicated since
725// the thread which is in the process of initializing a class can
726// access it's static fields but other threads can't so the code
727// either has to deoptimize when this case is detected or execute a
728// check that the current thread is the initializing thread.  The
729// current
730//
731// Patches basically look like this:
732//
733//
734// patch_site: jmp patch stub     ;; will be patched
735// continue:   ...
736//             ...
737//             ...
738//             ...
739//
740// They have a stub which looks like this:
741//
742//             ;; patch body
743//             movl <const>, reg           (for class constants)
744//        <or> movl [reg1 + <const>], reg  (for field offsets)
745//        <or> movl reg, [reg1 + <const>]  (for field offsets)
746//             <being_init offset> <bytes to copy> <bytes to skip>
747// patch_stub: call Runtime1::patch_code (through a runtime stub)
748//             jmp patch_site
749//
750//
751// A normal patch is done by rewriting the patch body, usually a move,
752// and then copying it into place over top of the jmp instruction
753// being careful to flush caches and doing it in an MP-safe way.  The
754// constants following the patch body are used to find various pieces
755// of the patch relative to the call site for Runtime1::patch_code.
756// The case for getstatic and putstatic is more complicated because
757// getstatic and putstatic have special semantics when executing while
758// the class is being initialized.  getstatic/putstatic on a class
759// which is being_initialized may be executed by the initializing
760// thread but other threads have to block when they execute it.  This
761// is accomplished in compiled code by executing a test of the current
762// thread against the initializing thread of the class.  It's emitted
763// as boilerplate in their stub which allows the patched code to be
764// executed before it's copied back into the main body of the nmethod.
765//
766// being_init: get_thread(<tmp reg>
767//             cmpl [reg1 + <init_thread_offset>], <tmp reg>
768//             jne patch_stub
769//             movl [reg1 + <const>], reg  (for field offsets)  <or>
770//             movl reg, [reg1 + <const>]  (for field offsets)
771//             jmp continue
772//             <being_init offset> <bytes to copy> <bytes to skip>
773// patch_stub: jmp Runtim1::patch_code (through a runtime stub)
774//             jmp patch_site
775//
776// If the class is being initialized the patch body is rewritten and
777// the patch site is rewritten to jump to being_init, instead of
778// patch_stub.  Whenever this code is executed it checks the current
779// thread against the intializing thread so other threads will enter
780// the runtime and end up blocked waiting the class to finish
781// initializing inside the calls to resolve_field below.  The
782// initializing class will continue on it's way.  Once the class is
783// fully_initialized, the intializing_thread of the class becomes
784// NULL, so the next thread to execute this code will fail the test,
785// call into patch_code and complete the patching process by copying
786// the patch body back into the main part of the nmethod and resume
787// executing.
788//
789//
790
791JRT_ENTRY(void, Runtime1::patch_code(JavaThread* thread, Runtime1::StubID stub_id ))
792  NOT_PRODUCT(_patch_code_slowcase_cnt++;)
793
794  ResourceMark rm(thread);
795  RegisterMap reg_map(thread, false);
796  frame runtime_frame = thread->last_frame();
797  frame caller_frame = runtime_frame.sender(&reg_map);
798
799  // last java frame on stack
800  vframeStream vfst(thread, true);
801  assert(!vfst.at_end(), "Java frame must exist");
802
803  methodHandle caller_method(THREAD, vfst.method());
804  // Note that caller_method->code() may not be same as caller_code because of OSR's
805  // Note also that in the presence of inlining it is not guaranteed
806  // that caller_method() == caller_code->method()
807
808  int bci = vfst.bci();
809  Bytecodes::Code code = caller_method()->java_code_at(bci);
810
811#ifndef PRODUCT
812  // this is used by assertions in the access_field_patching_id
813  BasicType patch_field_type = T_ILLEGAL;
814#endif // PRODUCT
815  bool deoptimize_for_volatile = false;
816  int patch_field_offset = -1;
817  KlassHandle init_klass(THREAD, klassOop(NULL)); // klass needed by access_field_patching code
818  Handle load_klass(THREAD, NULL);                // oop needed by load_klass_patching code
819  if (stub_id == Runtime1::access_field_patching_id) {
820
821    Bytecode_field field_access(caller_method, bci);
822    FieldAccessInfo result; // initialize class if needed
823    Bytecodes::Code code = field_access.code();
824    constantPoolHandle constants(THREAD, caller_method->constants());
825    LinkResolver::resolve_field(result, constants, field_access.index(), Bytecodes::java_code(code), false, CHECK);
826    patch_field_offset = result.field_offset();
827
828    // If we're patching a field which is volatile then at compile it
829    // must not have been know to be volatile, so the generated code
830    // isn't correct for a volatile reference.  The nmethod has to be
831    // deoptimized so that the code can be regenerated correctly.
832    // This check is only needed for access_field_patching since this
833    // is the path for patching field offsets.  load_klass is only
834    // used for patching references to oops which don't need special
835    // handling in the volatile case.
836    deoptimize_for_volatile = result.access_flags().is_volatile();
837
838#ifndef PRODUCT
839    patch_field_type = result.field_type();
840#endif
841  } else if (stub_id == Runtime1::load_klass_patching_id) {
842    oop k;
843    switch (code) {
844      case Bytecodes::_putstatic:
845      case Bytecodes::_getstatic:
846        { klassOop klass = resolve_field_return_klass(caller_method, bci, CHECK);
847          // Save a reference to the class that has to be checked for initialization
848          init_klass = KlassHandle(THREAD, klass);
849          k = klass->java_mirror();
850        }
851        break;
852      case Bytecodes::_new:
853        { Bytecode_new bnew(caller_method(), caller_method->bcp_from(bci));
854          k = caller_method->constants()->klass_at(bnew.index(), CHECK);
855        }
856        break;
857      case Bytecodes::_multianewarray:
858        { Bytecode_multianewarray mna(caller_method(), caller_method->bcp_from(bci));
859          k = caller_method->constants()->klass_at(mna.index(), CHECK);
860        }
861        break;
862      case Bytecodes::_instanceof:
863        { Bytecode_instanceof io(caller_method(), caller_method->bcp_from(bci));
864          k = caller_method->constants()->klass_at(io.index(), CHECK);
865        }
866        break;
867      case Bytecodes::_checkcast:
868        { Bytecode_checkcast cc(caller_method(), caller_method->bcp_from(bci));
869          k = caller_method->constants()->klass_at(cc.index(), CHECK);
870        }
871        break;
872      case Bytecodes::_anewarray:
873        { Bytecode_anewarray anew(caller_method(), caller_method->bcp_from(bci));
874          klassOop ek = caller_method->constants()->klass_at(anew.index(), CHECK);
875          k = Klass::cast(ek)->array_klass(CHECK);
876        }
877        break;
878      case Bytecodes::_ldc:
879      case Bytecodes::_ldc_w:
880        {
881          Bytecode_loadconstant cc(caller_method, bci);
882          k = cc.resolve_constant(CHECK);
883          assert(k != NULL && !k->is_klass(), "must be class mirror or other Java constant");
884        }
885        break;
886      default: Unimplemented();
887    }
888    // convert to handle
889    load_klass = Handle(THREAD, k);
890  } else {
891    ShouldNotReachHere();
892  }
893
894  if (deoptimize_for_volatile) {
895    // At compile time we assumed the field wasn't volatile but after
896    // loading it turns out it was volatile so we have to throw the
897    // compiled code out and let it be regenerated.
898    if (TracePatching) {
899      tty->print_cr("Deoptimizing for patching volatile field reference");
900    }
901    // It's possible the nmethod was invalidated in the last
902    // safepoint, but if it's still alive then make it not_entrant.
903    nmethod* nm = CodeCache::find_nmethod(caller_frame.pc());
904    if (nm != NULL) {
905      nm->make_not_entrant();
906    }
907
908    Deoptimization::deoptimize_frame(thread, caller_frame.id());
909
910    // Return to the now deoptimized frame.
911  }
912
913  // If we are patching in a non-perm oop, make sure the nmethod
914  // is on the right list.
915  if (ScavengeRootsInCode && load_klass.not_null() && load_klass->is_scavengable()) {
916    MutexLockerEx ml_code (CodeCache_lock, Mutex::_no_safepoint_check_flag);
917    nmethod* nm = CodeCache::find_nmethod(caller_frame.pc());
918    guarantee(nm != NULL, "only nmethods can contain non-perm oops");
919    if (!nm->on_scavenge_root_list())
920      CodeCache::add_scavenge_root_nmethod(nm);
921  }
922
923  // Now copy code back
924
925  {
926    MutexLockerEx ml_patch (Patching_lock, Mutex::_no_safepoint_check_flag);
927    //
928    // Deoptimization may have happened while we waited for the lock.
929    // In that case we don't bother to do any patching we just return
930    // and let the deopt happen
931    if (!caller_is_deopted()) {
932      NativeGeneralJump* jump = nativeGeneralJump_at(caller_frame.pc());
933      address instr_pc = jump->jump_destination();
934      NativeInstruction* ni = nativeInstruction_at(instr_pc);
935      if (ni->is_jump() ) {
936        // the jump has not been patched yet
937        // The jump destination is slow case and therefore not part of the stubs
938        // (stubs are only for StaticCalls)
939
940        // format of buffer
941        //    ....
942        //    instr byte 0     <-- copy_buff
943        //    instr byte 1
944        //    ..
945        //    instr byte n-1
946        //      n
947        //    ....             <-- call destination
948
949        address stub_location = caller_frame.pc() + PatchingStub::patch_info_offset();
950        unsigned char* byte_count = (unsigned char*) (stub_location - 1);
951        unsigned char* byte_skip = (unsigned char*) (stub_location - 2);
952        unsigned char* being_initialized_entry_offset = (unsigned char*) (stub_location - 3);
953        address copy_buff = stub_location - *byte_skip - *byte_count;
954        address being_initialized_entry = stub_location - *being_initialized_entry_offset;
955        if (TracePatching) {
956          tty->print_cr(" Patching %s at bci %d at address 0x%x  (%s)", Bytecodes::name(code), bci,
957                        instr_pc, (stub_id == Runtime1::access_field_patching_id) ? "field" : "klass");
958          nmethod* caller_code = CodeCache::find_nmethod(caller_frame.pc());
959          assert(caller_code != NULL, "nmethod not found");
960
961          // NOTE we use pc() not original_pc() because we already know they are
962          // identical otherwise we'd have never entered this block of code
963
964          OopMap* map = caller_code->oop_map_for_return_address(caller_frame.pc());
965          assert(map != NULL, "null check");
966          map->print();
967          tty->cr();
968
969          Disassembler::decode(copy_buff, copy_buff + *byte_count, tty);
970        }
971        // depending on the code below, do_patch says whether to copy the patch body back into the nmethod
972        bool do_patch = true;
973        if (stub_id == Runtime1::access_field_patching_id) {
974          // The offset may not be correct if the class was not loaded at code generation time.
975          // Set it now.
976          NativeMovRegMem* n_move = nativeMovRegMem_at(copy_buff);
977          assert(n_move->offset() == 0 || (n_move->offset() == 4 && (patch_field_type == T_DOUBLE || patch_field_type == T_LONG)), "illegal offset for type");
978          assert(patch_field_offset >= 0, "illegal offset");
979          n_move->add_offset_in_bytes(patch_field_offset);
980        } else if (stub_id == Runtime1::load_klass_patching_id) {
981          // If a getstatic or putstatic is referencing a klass which
982          // isn't fully initialized, the patch body isn't copied into
983          // place until initialization is complete.  In this case the
984          // patch site is setup so that any threads besides the
985          // initializing thread are forced to come into the VM and
986          // block.
987          do_patch = (code != Bytecodes::_getstatic && code != Bytecodes::_putstatic) ||
988                     instanceKlass::cast(init_klass())->is_initialized();
989          NativeGeneralJump* jump = nativeGeneralJump_at(instr_pc);
990          if (jump->jump_destination() == being_initialized_entry) {
991            assert(do_patch == true, "initialization must be complete at this point");
992          } else {
993            // patch the instruction <move reg, klass>
994            NativeMovConstReg* n_copy = nativeMovConstReg_at(copy_buff);
995
996            assert(n_copy->data() == 0 ||
997                   n_copy->data() == (intptr_t)Universe::non_oop_word(),
998                   "illegal init value");
999            assert(load_klass() != NULL, "klass not set");
1000            n_copy->set_data((intx) (load_klass()));
1001
1002            if (TracePatching) {
1003              Disassembler::decode(copy_buff, copy_buff + *byte_count, tty);
1004            }
1005
1006#if defined(SPARC) || defined(PPC)
1007            // Update the oop location in the nmethod with the proper
1008            // oop.  When the code was generated, a NULL was stuffed
1009            // in the oop table and that table needs to be update to
1010            // have the right value.  On intel the value is kept
1011            // directly in the instruction instead of in the oop
1012            // table, so set_data above effectively updated the value.
1013            nmethod* nm = CodeCache::find_nmethod(instr_pc);
1014            assert(nm != NULL, "invalid nmethod_pc");
1015            RelocIterator oops(nm, copy_buff, copy_buff + 1);
1016            bool found = false;
1017            while (oops.next() && !found) {
1018              if (oops.type() == relocInfo::oop_type) {
1019                oop_Relocation* r = oops.oop_reloc();
1020                oop* oop_adr = r->oop_addr();
1021                *oop_adr = load_klass();
1022                r->fix_oop_relocation();
1023                found = true;
1024              }
1025            }
1026            assert(found, "the oop must exist!");
1027#endif
1028
1029          }
1030        } else {
1031          ShouldNotReachHere();
1032        }
1033        if (do_patch) {
1034          // replace instructions
1035          // first replace the tail, then the call
1036#ifdef ARM
1037          if(stub_id == Runtime1::load_klass_patching_id && !VM_Version::supports_movw()) {
1038            nmethod* nm = CodeCache::find_nmethod(instr_pc);
1039            oop* oop_addr = NULL;
1040            assert(nm != NULL, "invalid nmethod_pc");
1041            RelocIterator oops(nm, copy_buff, copy_buff + 1);
1042            while (oops.next()) {
1043              if (oops.type() == relocInfo::oop_type) {
1044                oop_Relocation* r = oops.oop_reloc();
1045                oop_addr = r->oop_addr();
1046                break;
1047              }
1048            }
1049            assert(oop_addr != NULL, "oop relocation must exist");
1050            copy_buff -= *byte_count;
1051            NativeMovConstReg* n_copy2 = nativeMovConstReg_at(copy_buff);
1052            n_copy2->set_pc_relative_offset((address)oop_addr, instr_pc);
1053          }
1054#endif
1055
1056          for (int i = NativeCall::instruction_size; i < *byte_count; i++) {
1057            address ptr = copy_buff + i;
1058            int a_byte = (*ptr) & 0xFF;
1059            address dst = instr_pc + i;
1060            *(unsigned char*)dst = (unsigned char) a_byte;
1061          }
1062          ICache::invalidate_range(instr_pc, *byte_count);
1063          NativeGeneralJump::replace_mt_safe(instr_pc, copy_buff);
1064
1065          if (stub_id == Runtime1::load_klass_patching_id) {
1066            // update relocInfo to oop
1067            nmethod* nm = CodeCache::find_nmethod(instr_pc);
1068            assert(nm != NULL, "invalid nmethod_pc");
1069
1070            // The old patch site is now a move instruction so update
1071            // the reloc info so that it will get updated during
1072            // future GCs.
1073            RelocIterator iter(nm, (address)instr_pc, (address)(instr_pc + 1));
1074            relocInfo::change_reloc_info_for_address(&iter, (address) instr_pc,
1075                                                     relocInfo::none, relocInfo::oop_type);
1076#ifdef SPARC
1077            // Sparc takes two relocations for an oop so update the second one.
1078            address instr_pc2 = instr_pc + NativeMovConstReg::add_offset;
1079            RelocIterator iter2(nm, instr_pc2, instr_pc2 + 1);
1080            relocInfo::change_reloc_info_for_address(&iter2, (address) instr_pc2,
1081                                                     relocInfo::none, relocInfo::oop_type);
1082#endif
1083#ifdef PPC
1084          { address instr_pc2 = instr_pc + NativeMovConstReg::lo_offset;
1085            RelocIterator iter2(nm, instr_pc2, instr_pc2 + 1);
1086            relocInfo::change_reloc_info_for_address(&iter2, (address) instr_pc2, relocInfo::none, relocInfo::oop_type);
1087          }
1088#endif
1089          }
1090
1091        } else {
1092          ICache::invalidate_range(copy_buff, *byte_count);
1093          NativeGeneralJump::insert_unconditional(instr_pc, being_initialized_entry);
1094        }
1095      }
1096    }
1097  }
1098JRT_END
1099
1100//
1101// Entry point for compiled code. We want to patch a nmethod.
1102// We don't do a normal VM transition here because we want to
1103// know after the patching is complete and any safepoint(s) are taken
1104// if the calling nmethod was deoptimized. We do this by calling a
1105// helper method which does the normal VM transition and when it
1106// completes we can check for deoptimization. This simplifies the
1107// assembly code in the cpu directories.
1108//
1109int Runtime1::move_klass_patching(JavaThread* thread) {
1110//
1111// NOTE: we are still in Java
1112//
1113  Thread* THREAD = thread;
1114  debug_only(NoHandleMark nhm;)
1115  {
1116    // Enter VM mode
1117
1118    ResetNoHandleMark rnhm;
1119    patch_code(thread, load_klass_patching_id);
1120  }
1121  // Back in JAVA, use no oops DON'T safepoint
1122
1123  // Return true if calling code is deoptimized
1124
1125  return caller_is_deopted();
1126}
1127
1128//
1129// Entry point for compiled code. We want to patch a nmethod.
1130// We don't do a normal VM transition here because we want to
1131// know after the patching is complete and any safepoint(s) are taken
1132// if the calling nmethod was deoptimized. We do this by calling a
1133// helper method which does the normal VM transition and when it
1134// completes we can check for deoptimization. This simplifies the
1135// assembly code in the cpu directories.
1136//
1137
1138int Runtime1::access_field_patching(JavaThread* thread) {
1139//
1140// NOTE: we are still in Java
1141//
1142  Thread* THREAD = thread;
1143  debug_only(NoHandleMark nhm;)
1144  {
1145    // Enter VM mode
1146
1147    ResetNoHandleMark rnhm;
1148    patch_code(thread, access_field_patching_id);
1149  }
1150  // Back in JAVA, use no oops DON'T safepoint
1151
1152  // Return true if calling code is deoptimized
1153
1154  return caller_is_deopted();
1155JRT_END
1156
1157
1158JRT_LEAF(void, Runtime1::trace_block_entry(jint block_id))
1159  // for now we just print out the block id
1160  tty->print("%d ", block_id);
1161JRT_END
1162
1163
1164// Array copy return codes.
1165enum {
1166  ac_failed = -1, // arraycopy failed
1167  ac_ok = 0       // arraycopy succeeded
1168};
1169
1170
1171// Below length is the # elements copied.
1172template <class T> int obj_arraycopy_work(oopDesc* src, T* src_addr,
1173                                          oopDesc* dst, T* dst_addr,
1174                                          int length) {
1175
1176  // For performance reasons, we assume we are using a card marking write
1177  // barrier. The assert will fail if this is not the case.
1178  // Note that we use the non-virtual inlineable variant of write_ref_array.
1179  BarrierSet* bs = Universe::heap()->barrier_set();
1180  assert(bs->has_write_ref_array_opt(), "Barrier set must have ref array opt");
1181  assert(bs->has_write_ref_array_pre_opt(), "For pre-barrier as well.");
1182  if (src == dst) {
1183    // same object, no check
1184    bs->write_ref_array_pre(dst_addr, length);
1185    Copy::conjoint_oops_atomic(src_addr, dst_addr, length);
1186    bs->write_ref_array((HeapWord*)dst_addr, length);
1187    return ac_ok;
1188  } else {
1189    klassOop bound = objArrayKlass::cast(dst->klass())->element_klass();
1190    klassOop stype = objArrayKlass::cast(src->klass())->element_klass();
1191    if (stype == bound || Klass::cast(stype)->is_subtype_of(bound)) {
1192      // Elements are guaranteed to be subtypes, so no check necessary
1193      bs->write_ref_array_pre(dst_addr, length);
1194      Copy::conjoint_oops_atomic(src_addr, dst_addr, length);
1195      bs->write_ref_array((HeapWord*)dst_addr, length);
1196      return ac_ok;
1197    }
1198  }
1199  return ac_failed;
1200}
1201
1202// fast and direct copy of arrays; returning -1, means that an exception may be thrown
1203// and we did not copy anything
1204JRT_LEAF(int, Runtime1::arraycopy(oopDesc* src, int src_pos, oopDesc* dst, int dst_pos, int length))
1205#ifndef PRODUCT
1206  _generic_arraycopy_cnt++;        // Slow-path oop array copy
1207#endif
1208
1209  if (src == NULL || dst == NULL || src_pos < 0 || dst_pos < 0 || length < 0) return ac_failed;
1210  if (!dst->is_array() || !src->is_array()) return ac_failed;
1211  if ((unsigned int) arrayOop(src)->length() < (unsigned int)src_pos + (unsigned int)length) return ac_failed;
1212  if ((unsigned int) arrayOop(dst)->length() < (unsigned int)dst_pos + (unsigned int)length) return ac_failed;
1213
1214  if (length == 0) return ac_ok;
1215  if (src->is_typeArray()) {
1216    const klassOop klass_oop = src->klass();
1217    if (klass_oop != dst->klass()) return ac_failed;
1218    typeArrayKlass* klass = typeArrayKlass::cast(klass_oop);
1219    const int l2es = klass->log2_element_size();
1220    const int ihs = klass->array_header_in_bytes() / wordSize;
1221    char* src_addr = (char*) ((oopDesc**)src + ihs) + (src_pos << l2es);
1222    char* dst_addr = (char*) ((oopDesc**)dst + ihs) + (dst_pos << l2es);
1223    // Potential problem: memmove is not guaranteed to be word atomic
1224    // Revisit in Merlin
1225    memmove(dst_addr, src_addr, length << l2es);
1226    return ac_ok;
1227  } else if (src->is_objArray() && dst->is_objArray()) {
1228    if (UseCompressedOops) {
1229      narrowOop *src_addr  = objArrayOop(src)->obj_at_addr<narrowOop>(src_pos);
1230      narrowOop *dst_addr  = objArrayOop(dst)->obj_at_addr<narrowOop>(dst_pos);
1231      return obj_arraycopy_work(src, src_addr, dst, dst_addr, length);
1232    } else {
1233      oop *src_addr  = objArrayOop(src)->obj_at_addr<oop>(src_pos);
1234      oop *dst_addr  = objArrayOop(dst)->obj_at_addr<oop>(dst_pos);
1235      return obj_arraycopy_work(src, src_addr, dst, dst_addr, length);
1236    }
1237  }
1238  return ac_failed;
1239JRT_END
1240
1241
1242JRT_LEAF(void, Runtime1::primitive_arraycopy(HeapWord* src, HeapWord* dst, int length))
1243#ifndef PRODUCT
1244  _primitive_arraycopy_cnt++;
1245#endif
1246
1247  if (length == 0) return;
1248  // Not guaranteed to be word atomic, but that doesn't matter
1249  // for anything but an oop array, which is covered by oop_arraycopy.
1250  Copy::conjoint_jbytes(src, dst, length);
1251JRT_END
1252
1253JRT_LEAF(void, Runtime1::oop_arraycopy(HeapWord* src, HeapWord* dst, int num))
1254#ifndef PRODUCT
1255  _oop_arraycopy_cnt++;
1256#endif
1257
1258  if (num == 0) return;
1259  BarrierSet* bs = Universe::heap()->barrier_set();
1260  assert(bs->has_write_ref_array_opt(), "Barrier set must have ref array opt");
1261  assert(bs->has_write_ref_array_pre_opt(), "For pre-barrier as well.");
1262  if (UseCompressedOops) {
1263    bs->write_ref_array_pre((narrowOop*)dst, num);
1264    Copy::conjoint_oops_atomic((narrowOop*) src, (narrowOop*) dst, num);
1265  } else {
1266    bs->write_ref_array_pre((oop*)dst, num);
1267    Copy::conjoint_oops_atomic((oop*) src, (oop*) dst, num);
1268  }
1269  bs->write_ref_array(dst, num);
1270JRT_END
1271
1272
1273#ifndef PRODUCT
1274void Runtime1::print_statistics() {
1275  tty->print_cr("C1 Runtime statistics:");
1276  tty->print_cr(" _resolve_invoke_virtual_cnt:     %d", SharedRuntime::_resolve_virtual_ctr);
1277  tty->print_cr(" _resolve_invoke_opt_virtual_cnt: %d", SharedRuntime::_resolve_opt_virtual_ctr);
1278  tty->print_cr(" _resolve_invoke_static_cnt:      %d", SharedRuntime::_resolve_static_ctr);
1279  tty->print_cr(" _handle_wrong_method_cnt:        %d", SharedRuntime::_wrong_method_ctr);
1280  tty->print_cr(" _ic_miss_cnt:                    %d", SharedRuntime::_ic_miss_ctr);
1281  tty->print_cr(" _generic_arraycopy_cnt:          %d", _generic_arraycopy_cnt);
1282  tty->print_cr(" _generic_arraycopystub_cnt:      %d", _generic_arraycopystub_cnt);
1283  tty->print_cr(" _byte_arraycopy_cnt:             %d", _byte_arraycopy_cnt);
1284  tty->print_cr(" _short_arraycopy_cnt:            %d", _short_arraycopy_cnt);
1285  tty->print_cr(" _int_arraycopy_cnt:              %d", _int_arraycopy_cnt);
1286  tty->print_cr(" _long_arraycopy_cnt:             %d", _long_arraycopy_cnt);
1287  tty->print_cr(" _primitive_arraycopy_cnt:        %d", _primitive_arraycopy_cnt);
1288  tty->print_cr(" _oop_arraycopy_cnt (C):          %d", Runtime1::_oop_arraycopy_cnt);
1289  tty->print_cr(" _oop_arraycopy_cnt (stub):       %d", _oop_arraycopy_cnt);
1290  tty->print_cr(" _arraycopy_slowcase_cnt:         %d", _arraycopy_slowcase_cnt);
1291  tty->print_cr(" _arraycopy_checkcast_cnt:        %d", _arraycopy_checkcast_cnt);
1292  tty->print_cr(" _arraycopy_checkcast_attempt_cnt:%d", _arraycopy_checkcast_attempt_cnt);
1293
1294  tty->print_cr(" _new_type_array_slowcase_cnt:    %d", _new_type_array_slowcase_cnt);
1295  tty->print_cr(" _new_object_array_slowcase_cnt:  %d", _new_object_array_slowcase_cnt);
1296  tty->print_cr(" _new_instance_slowcase_cnt:      %d", _new_instance_slowcase_cnt);
1297  tty->print_cr(" _new_multi_array_slowcase_cnt:   %d", _new_multi_array_slowcase_cnt);
1298  tty->print_cr(" _monitorenter_slowcase_cnt:      %d", _monitorenter_slowcase_cnt);
1299  tty->print_cr(" _monitorexit_slowcase_cnt:       %d", _monitorexit_slowcase_cnt);
1300  tty->print_cr(" _patch_code_slowcase_cnt:        %d", _patch_code_slowcase_cnt);
1301
1302  tty->print_cr(" _throw_range_check_exception_count:            %d:", _throw_range_check_exception_count);
1303  tty->print_cr(" _throw_index_exception_count:                  %d:", _throw_index_exception_count);
1304  tty->print_cr(" _throw_div0_exception_count:                   %d:", _throw_div0_exception_count);
1305  tty->print_cr(" _throw_null_pointer_exception_count:           %d:", _throw_null_pointer_exception_count);
1306  tty->print_cr(" _throw_class_cast_exception_count:             %d:", _throw_class_cast_exception_count);
1307  tty->print_cr(" _throw_incompatible_class_change_error_count:  %d:", _throw_incompatible_class_change_error_count);
1308  tty->print_cr(" _throw_array_store_exception_count:            %d:", _throw_array_store_exception_count);
1309  tty->print_cr(" _throw_count:                                  %d:", _throw_count);
1310
1311  SharedRuntime::print_ic_miss_histogram();
1312  tty->cr();
1313}
1314#endif // PRODUCT
1315