src/share/vm/c1/c1_Runtime1.cpp

Tue, 17 Oct 2017 12:58:25 +0800

author
aoqi
date
Tue, 17 Oct 2017 12:58:25 +0800
changeset 7994
04ff2f6cd0eb
parent 7598
ddce0b7cee93
parent 7535
7ae4e26cb1e0
child 8604
04d83ba48607
permissions
-rw-r--r--

merge

     1 /*
     2  * Copyright (c) 1999, 2015, 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  */
    25 /*
    26  * This file has been modified by Loongson Technology in 2015. These
    27  * modifications are Copyright (c) 2015 Loongson Technology, and are made
    28  * available on the same license terms set forth above.
    29  */
    31 #include "precompiled.hpp"
    32 #include "asm/codeBuffer.hpp"
    33 #include "c1/c1_CodeStubs.hpp"
    34 #include "c1/c1_Defs.hpp"
    35 #include "c1/c1_FrameMap.hpp"
    36 #include "c1/c1_LIRAssembler.hpp"
    37 #include "c1/c1_MacroAssembler.hpp"
    38 #include "c1/c1_Runtime1.hpp"
    39 #include "classfile/systemDictionary.hpp"
    40 #include "classfile/vmSymbols.hpp"
    41 #include "code/codeBlob.hpp"
    42 #include "code/compiledIC.hpp"
    43 #include "code/pcDesc.hpp"
    44 #include "code/scopeDesc.hpp"
    45 #include "code/vtableStubs.hpp"
    46 #include "compiler/disassembler.hpp"
    47 #include "gc_interface/collectedHeap.hpp"
    48 #include "interpreter/bytecode.hpp"
    49 #include "interpreter/interpreter.hpp"
    50 #include "memory/allocation.inline.hpp"
    51 #include "memory/barrierSet.hpp"
    52 #include "memory/oopFactory.hpp"
    53 #include "memory/resourceArea.hpp"
    54 #include "oops/objArrayKlass.hpp"
    55 #include "oops/oop.inline.hpp"
    56 #include "runtime/biasedLocking.hpp"
    57 #include "runtime/compilationPolicy.hpp"
    58 #include "runtime/interfaceSupport.hpp"
    59 #include "runtime/javaCalls.hpp"
    60 #include "runtime/sharedRuntime.hpp"
    61 #include "runtime/threadCritical.hpp"
    62 #include "runtime/vframe.hpp"
    63 #include "runtime/vframeArray.hpp"
    64 #include "utilities/copy.hpp"
    65 #include "utilities/events.hpp"
    68 // Implementation of StubAssembler
    70 StubAssembler::StubAssembler(CodeBuffer* code, const char * name, int stub_id) : C1_MacroAssembler(code) {
    71   _name = name;
    72   _must_gc_arguments = false;
    73   _frame_size = no_frame_size;
    74   _num_rt_args = 0;
    75   _stub_id = stub_id;
    76 }
    79 void StubAssembler::set_info(const char* name, bool must_gc_arguments) {
    80   _name = name;
    81   _must_gc_arguments = must_gc_arguments;
    82 }
    85 void StubAssembler::set_frame_size(int size) {
    86   if (_frame_size == no_frame_size) {
    87     _frame_size = size;
    88   }
    89   assert(_frame_size == size, "can't change the frame size");
    90 }
    93 void StubAssembler::set_num_rt_args(int args) {
    94   if (_num_rt_args == 0) {
    95     _num_rt_args = args;
    96   }
    97   assert(_num_rt_args == args, "can't change the number of args");
    98 }
   100 // Implementation of Runtime1
   102 CodeBlob* Runtime1::_blobs[Runtime1::number_of_ids];
   103 const char *Runtime1::_blob_names[] = {
   104   RUNTIME1_STUBS(STUB_NAME, LAST_STUB_NAME)
   105 };
   107 #ifndef PRODUCT
   108 // statistics
   109 int Runtime1::_generic_arraycopy_cnt = 0;
   110 int Runtime1::_primitive_arraycopy_cnt = 0;
   111 int Runtime1::_oop_arraycopy_cnt = 0;
   112 int Runtime1::_generic_arraycopystub_cnt = 0;
   113 int Runtime1::_arraycopy_slowcase_cnt = 0;
   114 int Runtime1::_arraycopy_checkcast_cnt = 0;
   115 int Runtime1::_arraycopy_checkcast_attempt_cnt = 0;
   116 int Runtime1::_new_type_array_slowcase_cnt = 0;
   117 int Runtime1::_new_object_array_slowcase_cnt = 0;
   118 int Runtime1::_new_instance_slowcase_cnt = 0;
   119 int Runtime1::_new_multi_array_slowcase_cnt = 0;
   120 int Runtime1::_monitorenter_slowcase_cnt = 0;
   121 int Runtime1::_monitorexit_slowcase_cnt = 0;
   122 int Runtime1::_patch_code_slowcase_cnt = 0;
   123 int Runtime1::_throw_range_check_exception_count = 0;
   124 int Runtime1::_throw_index_exception_count = 0;
   125 int Runtime1::_throw_div0_exception_count = 0;
   126 int Runtime1::_throw_null_pointer_exception_count = 0;
   127 int Runtime1::_throw_class_cast_exception_count = 0;
   128 int Runtime1::_throw_incompatible_class_change_error_count = 0;
   129 int Runtime1::_throw_array_store_exception_count = 0;
   130 int Runtime1::_throw_count = 0;
   132 static int _byte_arraycopy_cnt = 0;
   133 static int _short_arraycopy_cnt = 0;
   134 static int _int_arraycopy_cnt = 0;
   135 static int _long_arraycopy_cnt = 0;
   136 static int _oop_arraycopy_cnt = 0;
   138 address Runtime1::arraycopy_count_address(BasicType type) {
   139   switch (type) {
   140   case T_BOOLEAN:
   141   case T_BYTE:   return (address)&_byte_arraycopy_cnt;
   142   case T_CHAR:
   143   case T_SHORT:  return (address)&_short_arraycopy_cnt;
   144   case T_FLOAT:
   145   case T_INT:    return (address)&_int_arraycopy_cnt;
   146   case T_DOUBLE:
   147   case T_LONG:   return (address)&_long_arraycopy_cnt;
   148   case T_ARRAY:
   149   case T_OBJECT: return (address)&_oop_arraycopy_cnt;
   150   default:
   151     ShouldNotReachHere();
   152     return NULL;
   153   }
   154 }
   157 #endif
   159 // Simple helper to see if the caller of a runtime stub which
   160 // entered the VM has been deoptimized
   162 static bool caller_is_deopted() {
   163   JavaThread* thread = JavaThread::current();
   164   RegisterMap reg_map(thread, false);
   165   frame runtime_frame = thread->last_frame();
   166   frame caller_frame = runtime_frame.sender(&reg_map);
   167   assert(caller_frame.is_compiled_frame(), "must be compiled");
   168   return caller_frame.is_deoptimized_frame();
   169 }
   171 // Stress deoptimization
   172 static void deopt_caller() {
   173   if ( !caller_is_deopted()) {
   174     JavaThread* thread = JavaThread::current();
   175     RegisterMap reg_map(thread, false);
   176     frame runtime_frame = thread->last_frame();
   177     frame caller_frame = runtime_frame.sender(&reg_map);
   178     Deoptimization::deoptimize_frame(thread, caller_frame.id());
   179     assert(caller_is_deopted(), "Must be deoptimized");
   180   }
   181 }
   184 void Runtime1::generate_blob_for(BufferBlob* buffer_blob, StubID id) {
   185   assert(0 <= id && id < number_of_ids, "illegal stub id");
   186   ResourceMark rm;
   187   // create code buffer for code storage
   188   CodeBuffer code(buffer_blob);
   190   Compilation::setup_code_buffer(&code, 0);
   192   // create assembler for code generation
   193   StubAssembler* sasm = new StubAssembler(&code, name_for(id), id);
   194   // generate code for runtime stub
   195   OopMapSet* oop_maps;
   196   oop_maps = generate_code_for(id, sasm);
   197   assert(oop_maps == NULL || sasm->frame_size() != no_frame_size,
   198          "if stub has an oop map it must have a valid frame size");
   200 #ifdef ASSERT
   201   // Make sure that stubs that need oopmaps have them
   202   switch (id) {
   203     // These stubs don't need to have an oopmap
   204     case dtrace_object_alloc_id:
   205     case g1_pre_barrier_slow_id:
   206     case g1_post_barrier_slow_id:
   207     case slow_subtype_check_id:
   208     case fpu2long_stub_id:
   209     case unwind_exception_id:
   210     case counter_overflow_id:
   211 #if defined(SPARC) || defined(PPC)
   212     case handle_exception_nofpu_id:  // Unused on sparc
   213 #endif
   214       break;
   216     // All other stubs should have oopmaps
   217     default:
   218       assert(oop_maps != NULL, "must have an oopmap");
   219   }
   220 #endif
   222   // align so printing shows nop's instead of random code at the end (SimpleStubs are aligned)
   223   sasm->align(BytesPerWord);
   224   // make sure all code is in code buffer
   225   sasm->flush();
   226   // create blob - distinguish a few special cases
   227   CodeBlob* blob = RuntimeStub::new_runtime_stub(name_for(id),
   228                                                  &code,
   229                                                  CodeOffsets::frame_never_safe,
   230                                                  sasm->frame_size(),
   231                                                  oop_maps,
   232                                                  sasm->must_gc_arguments());
   233   // install blob
   234   assert(blob != NULL, "blob must exist");
   235   _blobs[id] = blob;
   236 }
   239 void Runtime1::initialize(BufferBlob* blob) {
   240   // platform-dependent initialization
   241   initialize_pd();
   242   // generate stubs
   243   for (int id = 0; id < number_of_ids; id++) generate_blob_for(blob, (StubID)id);
   244   // printing
   245 #ifndef PRODUCT
   246   if (PrintSimpleStubs) {
   247     ResourceMark rm;
   248     for (int id = 0; id < number_of_ids; id++) {
   249       _blobs[id]->print();
   250       if (_blobs[id]->oop_maps() != NULL) {
   251         _blobs[id]->oop_maps()->print();
   252       }
   253     }
   254   }
   255 #endif
   256 }
   259 CodeBlob* Runtime1::blob_for(StubID id) {
   260   assert(0 <= id && id < number_of_ids, "illegal stub id");
   261   return _blobs[id];
   262 }
   265 const char* Runtime1::name_for(StubID id) {
   266   assert(0 <= id && id < number_of_ids, "illegal stub id");
   267   return _blob_names[id];
   268 }
   270 const char* Runtime1::name_for_address(address entry) {
   271   for (int id = 0; id < number_of_ids; id++) {
   272     if (entry == entry_for((StubID)id)) return name_for((StubID)id);
   273   }
   275 #define FUNCTION_CASE(a, f) \
   276   if ((intptr_t)a == CAST_FROM_FN_PTR(intptr_t, f))  return #f
   278   FUNCTION_CASE(entry, os::javaTimeMillis);
   279   FUNCTION_CASE(entry, os::javaTimeNanos);
   280   FUNCTION_CASE(entry, SharedRuntime::OSR_migration_end);
   281   FUNCTION_CASE(entry, SharedRuntime::d2f);
   282   FUNCTION_CASE(entry, SharedRuntime::d2i);
   283   FUNCTION_CASE(entry, SharedRuntime::d2l);
   284   FUNCTION_CASE(entry, SharedRuntime::dcos);
   285   FUNCTION_CASE(entry, SharedRuntime::dexp);
   286   FUNCTION_CASE(entry, SharedRuntime::dlog);
   287   FUNCTION_CASE(entry, SharedRuntime::dlog10);
   288   FUNCTION_CASE(entry, SharedRuntime::dpow);
   289   FUNCTION_CASE(entry, SharedRuntime::drem);
   290   FUNCTION_CASE(entry, SharedRuntime::dsin);
   291   FUNCTION_CASE(entry, SharedRuntime::dtan);
   292   FUNCTION_CASE(entry, SharedRuntime::f2i);
   293   FUNCTION_CASE(entry, SharedRuntime::f2l);
   294   FUNCTION_CASE(entry, SharedRuntime::frem);
   295   FUNCTION_CASE(entry, SharedRuntime::l2d);
   296   FUNCTION_CASE(entry, SharedRuntime::l2f);
   297   FUNCTION_CASE(entry, SharedRuntime::ldiv);
   298   FUNCTION_CASE(entry, SharedRuntime::lmul);
   299   FUNCTION_CASE(entry, SharedRuntime::lrem);
   300   FUNCTION_CASE(entry, SharedRuntime::lrem);
   301   FUNCTION_CASE(entry, SharedRuntime::dtrace_method_entry);
   302   FUNCTION_CASE(entry, SharedRuntime::dtrace_method_exit);
   303   FUNCTION_CASE(entry, is_instance_of);
   304   FUNCTION_CASE(entry, trace_block_entry);
   305 #ifdef TRACE_HAVE_INTRINSICS
   306   FUNCTION_CASE(entry, TRACE_TIME_METHOD);
   307 #endif
   308   FUNCTION_CASE(entry, StubRoutines::updateBytesCRC32());
   310 #undef FUNCTION_CASE
   312   // Soft float adds more runtime names.
   313   return pd_name_for_address(entry);
   314 }
   317 JRT_ENTRY(void, Runtime1::new_instance(JavaThread* thread, Klass* klass))
   318   NOT_PRODUCT(_new_instance_slowcase_cnt++;)
   320   assert(klass->is_klass(), "not a class");
   321   instanceKlassHandle h(thread, klass);
   322   h->check_valid_for_instantiation(true, CHECK);
   323   // make sure klass is initialized
   324   h->initialize(CHECK);
   325   // allocate instance and return via TLS
   326   oop obj = h->allocate_instance(CHECK);
   327   thread->set_vm_result(obj);
   328 JRT_END
   331 JRT_ENTRY(void, Runtime1::new_type_array(JavaThread* thread, Klass* klass, jint length))
   332   NOT_PRODUCT(_new_type_array_slowcase_cnt++;)
   333   // Note: no handle for klass needed since they are not used
   334   //       anymore after new_typeArray() and no GC can happen before.
   335   //       (This may have to change if this code changes!)
   336   assert(klass->is_klass(), "not a class");
   337   BasicType elt_type = TypeArrayKlass::cast(klass)->element_type();
   338   oop obj = oopFactory::new_typeArray(elt_type, length, CHECK);
   339   thread->set_vm_result(obj);
   340   // This is pretty rare but this runtime patch is stressful to deoptimization
   341   // if we deoptimize here so force a deopt to stress the path.
   342   if (DeoptimizeALot) {
   343     deopt_caller();
   344   }
   346 JRT_END
   349 JRT_ENTRY(void, Runtime1::new_object_array(JavaThread* thread, Klass* array_klass, jint length))
   350   NOT_PRODUCT(_new_object_array_slowcase_cnt++;)
   352   // Note: no handle for klass needed since they are not used
   353   //       anymore after new_objArray() and no GC can happen before.
   354   //       (This may have to change if this code changes!)
   355   assert(array_klass->is_klass(), "not a class");
   356   Klass* elem_klass = ObjArrayKlass::cast(array_klass)->element_klass();
   357   objArrayOop obj = oopFactory::new_objArray(elem_klass, length, CHECK);
   358   thread->set_vm_result(obj);
   359   // This is pretty rare but this runtime patch is stressful to deoptimization
   360   // if we deoptimize here so force a deopt to stress the path.
   361   if (DeoptimizeALot) {
   362     deopt_caller();
   363   }
   364 JRT_END
   367 JRT_ENTRY(void, Runtime1::new_multi_array(JavaThread* thread, Klass* klass, int rank, jint* dims))
   368   NOT_PRODUCT(_new_multi_array_slowcase_cnt++;)
   370   assert(klass->is_klass(), "not a class");
   371   assert(rank >= 1, "rank must be nonzero");
   372   oop obj = ArrayKlass::cast(klass)->multi_allocate(rank, dims, CHECK);
   373   thread->set_vm_result(obj);
   374 JRT_END
   377 JRT_ENTRY(void, Runtime1::unimplemented_entry(JavaThread* thread, StubID id))
   378   tty->print_cr("Runtime1::entry_for(%d) returned unimplemented entry point", id);
   379 JRT_END
   382 JRT_ENTRY(void, Runtime1::throw_array_store_exception(JavaThread* thread, oopDesc* obj))
   383   ResourceMark rm(thread);
   384   const char* klass_name = obj->klass()->external_name();
   385   SharedRuntime::throw_and_post_jvmti_exception(thread, vmSymbols::java_lang_ArrayStoreException(), klass_name);
   386 JRT_END
   389 // counter_overflow() is called from within C1-compiled methods. The enclosing method is the method
   390 // associated with the top activation record. The inlinee (that is possibly included in the enclosing
   391 // method) method oop is passed as an argument. In order to do that it is embedded in the code as
   392 // a constant.
   393 static nmethod* counter_overflow_helper(JavaThread* THREAD, int branch_bci, Method* m) {
   394   nmethod* osr_nm = NULL;
   395   methodHandle method(THREAD, m);
   397   RegisterMap map(THREAD, false);
   398   frame fr =  THREAD->last_frame().sender(&map);
   399   nmethod* nm = (nmethod*) fr.cb();
   400   assert(nm!= NULL && nm->is_nmethod(), "Sanity check");
   401   methodHandle enclosing_method(THREAD, nm->method());
   403   CompLevel level = (CompLevel)nm->comp_level();
   404   int bci = InvocationEntryBci;
   405   if (branch_bci != InvocationEntryBci) {
   406     // Compute desination bci
   407     address pc = method()->code_base() + branch_bci;
   408     Bytecodes::Code branch = Bytecodes::code_at(method(), pc);
   409     int offset = 0;
   410     switch (branch) {
   411       case Bytecodes::_if_icmplt: case Bytecodes::_iflt:
   412       case Bytecodes::_if_icmpgt: case Bytecodes::_ifgt:
   413       case Bytecodes::_if_icmple: case Bytecodes::_ifle:
   414       case Bytecodes::_if_icmpge: case Bytecodes::_ifge:
   415       case Bytecodes::_if_icmpeq: case Bytecodes::_if_acmpeq: case Bytecodes::_ifeq:
   416       case Bytecodes::_if_icmpne: case Bytecodes::_if_acmpne: case Bytecodes::_ifne:
   417       case Bytecodes::_ifnull: case Bytecodes::_ifnonnull: case Bytecodes::_goto:
   418         offset = (int16_t)Bytes::get_Java_u2(pc + 1);
   419         break;
   420       case Bytecodes::_goto_w:
   421         offset = Bytes::get_Java_u4(pc + 1);
   422         break;
   423       default: ;
   424     }
   425     bci = branch_bci + offset;
   426   }
   427   assert(!HAS_PENDING_EXCEPTION, "Should not have any exceptions pending");
   428   osr_nm = CompilationPolicy::policy()->event(enclosing_method, method, branch_bci, bci, level, nm, THREAD);
   429   assert(!HAS_PENDING_EXCEPTION, "Event handler should not throw any exceptions");
   430   return osr_nm;
   431 }
   433 JRT_BLOCK_ENTRY(address, Runtime1::counter_overflow(JavaThread* thread, int bci, Method* method))
   434   nmethod* osr_nm;
   435   JRT_BLOCK
   436     osr_nm = counter_overflow_helper(thread, bci, method);
   437     if (osr_nm != NULL) {
   438       RegisterMap map(thread, false);
   439       frame fr =  thread->last_frame().sender(&map);
   440       Deoptimization::deoptimize_frame(thread, fr.id());
   441     }
   442   JRT_BLOCK_END
   443   return NULL;
   444 JRT_END
   446 extern void vm_exit(int code);
   448 // Enter this method from compiled code handler below. This is where we transition
   449 // to VM mode. This is done as a helper routine so that the method called directly
   450 // from compiled code does not have to transition to VM. This allows the entry
   451 // method to see if the nmethod that we have just looked up a handler for has
   452 // been deoptimized while we were in the vm. This simplifies the assembly code
   453 // cpu directories.
   454 //
   455 // We are entering here from exception stub (via the entry method below)
   456 // If there is a compiled exception handler in this method, we will continue there;
   457 // otherwise we will unwind the stack and continue at the caller of top frame method
   458 // Note: we enter in Java using a special JRT wrapper. This wrapper allows us to
   459 // control the area where we can allow a safepoint. After we exit the safepoint area we can
   460 // check to see if the handler we are going to return is now in a nmethod that has
   461 // been deoptimized. If that is the case we return the deopt blob
   462 // unpack_with_exception entry instead. This makes life for the exception blob easier
   463 // because making that same check and diverting is painful from assembly language.
   464 JRT_ENTRY_NO_ASYNC(static address, exception_handler_for_pc_helper(JavaThread* thread, oopDesc* ex, address pc, nmethod*& nm))
   465   // Reset method handle flag.
   466   thread->set_is_method_handle_return(false);
   468   Handle exception(thread, ex);
   469   nm = CodeCache::find_nmethod(pc);
   470   assert(nm != NULL, "this is not an nmethod");
   471   // Adjust the pc as needed/
   472   if (nm->is_deopt_pc(pc)) {
   473     RegisterMap map(thread, false);
   474     frame exception_frame = thread->last_frame().sender(&map);
   475     // if the frame isn't deopted then pc must not correspond to the caller of last_frame
   476     assert(exception_frame.is_deoptimized_frame(), "must be deopted");
   477     pc = exception_frame.pc();
   478   }
   479 #ifdef ASSERT
   480   assert(exception.not_null(), "NULL exceptions should be handled by throw_exception");
   481   assert(exception->is_oop(), "just checking");
   482   // Check that exception is a subclass of Throwable, otherwise we have a VerifyError
   483   if (!(exception->is_a(SystemDictionary::Throwable_klass()))) {
   484     if (ExitVMOnVerifyError) vm_exit(-1);
   485     ShouldNotReachHere();
   486   }
   487 #endif
   489   // Check the stack guard pages and reenable them if necessary and there is
   490   // enough space on the stack to do so.  Use fast exceptions only if the guard
   491   // pages are enabled.
   492   bool guard_pages_enabled = thread->stack_yellow_zone_enabled();
   493   if (!guard_pages_enabled) guard_pages_enabled = thread->reguard_stack();
   495   if (JvmtiExport::can_post_on_exceptions()) {
   496     // To ensure correct notification of exception catches and throws
   497     // we have to deoptimize here.  If we attempted to notify the
   498     // catches and throws during this exception lookup it's possible
   499     // we could deoptimize on the way out of the VM and end back in
   500     // the interpreter at the throw site.  This would result in double
   501     // notifications since the interpreter would also notify about
   502     // these same catches and throws as it unwound the frame.
   504     RegisterMap reg_map(thread);
   505     frame stub_frame = thread->last_frame();
   506     frame caller_frame = stub_frame.sender(&reg_map);
   508     // We don't really want to deoptimize the nmethod itself since we
   509     // can actually continue in the exception handler ourselves but I
   510     // don't see an easy way to have the desired effect.
   511     Deoptimization::deoptimize_frame(thread, caller_frame.id());
   512     assert(caller_is_deopted(), "Must be deoptimized");
   514     return SharedRuntime::deopt_blob()->unpack_with_exception_in_tls();
   515   }
   517   // ExceptionCache is used only for exceptions at call sites and not for implicit exceptions
   518   if (guard_pages_enabled) {
   519     address fast_continuation = nm->handler_for_exception_and_pc(exception, pc);
   520     if (fast_continuation != NULL) {
   521       // Set flag if return address is a method handle call site.
   522       thread->set_is_method_handle_return(nm->is_method_handle_return(pc));
   523       return fast_continuation;
   524     }
   525   }
   527   // If the stack guard pages are enabled, check whether there is a handler in
   528   // the current method.  Otherwise (guard pages disabled), force an unwind and
   529   // skip the exception cache update (i.e., just leave continuation==NULL).
   530   address continuation = NULL;
   531   if (guard_pages_enabled) {
   533     // New exception handling mechanism can support inlined methods
   534     // with exception handlers since the mappings are from PC to PC
   536     // debugging support
   537     // tracing
   538     if (TraceExceptions) {
   539       ttyLocker ttyl;
   540       ResourceMark rm;
   541       tty->print_cr("Exception <%s> (" INTPTR_FORMAT ") thrown in compiled method <%s> at PC " INTPTR_FORMAT " for thread " INTPTR_FORMAT "",
   542                     exception->print_value_string(), p2i((address)exception()), nm->method()->print_value_string(), p2i(pc), p2i(thread));
   543     }
   544     // for AbortVMOnException flag
   545     NOT_PRODUCT(Exceptions::debug_check_abort(exception));
   547     // Clear out the exception oop and pc since looking up an
   548     // exception handler can cause class loading, which might throw an
   549     // exception and those fields are expected to be clear during
   550     // normal bytecode execution.
   551     thread->clear_exception_oop_and_pc();
   553     Handle original_exception(thread, exception());
   555     continuation = SharedRuntime::compute_compiled_exc_handler(nm, pc, exception, false, false);
   556     // If an exception was thrown during exception dispatch, the exception oop may have changed
   557     thread->set_exception_oop(exception());
   558     thread->set_exception_pc(pc);
   560     // the exception cache is used only by non-implicit exceptions
   561     // Update the exception cache only when there didn't happen
   562     // another exception during the computation of the compiled
   563     // exception handler.
   564     if (continuation != NULL && original_exception() == exception()) {
   565       nm->add_handler_for_exception_and_pc(exception, pc, continuation);
   566     }
   567   }
   569   thread->set_vm_result(exception());
   570   // Set flag if return address is a method handle call site.
   571   thread->set_is_method_handle_return(nm->is_method_handle_return(pc));
   573   if (TraceExceptions) {
   574     ttyLocker ttyl;
   575     ResourceMark rm;
   576     tty->print_cr("Thread " PTR_FORMAT " continuing at PC " PTR_FORMAT " for exception thrown at PC " PTR_FORMAT,
   577                   p2i(thread), p2i(continuation), p2i(pc));
   578   }
   580   return continuation;
   581 JRT_END
   583 // Enter this method from compiled code only if there is a Java exception handler
   584 // in the method handling the exception.
   585 // We are entering here from exception stub. We don't do a normal VM transition here.
   586 // We do it in a helper. This is so we can check to see if the nmethod we have just
   587 // searched for an exception handler has been deoptimized in the meantime.
   588 address Runtime1::exception_handler_for_pc(JavaThread* thread) {
   589   oop exception = thread->exception_oop();
   590   address pc = thread->exception_pc();
   591   // Still in Java mode
   592   DEBUG_ONLY(ResetNoHandleMark rnhm);
   593   nmethod* nm = NULL;
   594   address continuation = NULL;
   595   {
   596     // Enter VM mode by calling the helper
   597     ResetNoHandleMark rnhm;
   598     continuation = exception_handler_for_pc_helper(thread, exception, pc, nm);
   599   }
   600   // Back in JAVA, use no oops DON'T safepoint
   602   // Now check to see if the nmethod we were called from is now deoptimized.
   603   // If so we must return to the deopt blob and deoptimize the nmethod
   604   if (nm != NULL && caller_is_deopted()) {
   605     continuation = SharedRuntime::deopt_blob()->unpack_with_exception_in_tls();
   606   }
   608   assert(continuation != NULL, "no handler found");
   609   return continuation;
   610 }
   613 JRT_ENTRY(void, Runtime1::throw_range_check_exception(JavaThread* thread, int index))
   614   NOT_PRODUCT(_throw_range_check_exception_count++;)
   615   char message[jintAsStringSize];
   616   sprintf(message, "%d", index);
   617   SharedRuntime::throw_and_post_jvmti_exception(thread, vmSymbols::java_lang_ArrayIndexOutOfBoundsException(), message);
   618 JRT_END
   621 JRT_ENTRY(void, Runtime1::throw_index_exception(JavaThread* thread, int index))
   622   NOT_PRODUCT(_throw_index_exception_count++;)
   623   char message[16];
   624   sprintf(message, "%d", index);
   625   SharedRuntime::throw_and_post_jvmti_exception(thread, vmSymbols::java_lang_IndexOutOfBoundsException(), message);
   626 JRT_END
   629 JRT_ENTRY(void, Runtime1::throw_div0_exception(JavaThread* thread))
   630   NOT_PRODUCT(_throw_div0_exception_count++;)
   631   SharedRuntime::throw_and_post_jvmti_exception(thread, vmSymbols::java_lang_ArithmeticException(), "/ by zero");
   632 JRT_END
   635 JRT_ENTRY(void, Runtime1::throw_null_pointer_exception(JavaThread* thread))
   636   NOT_PRODUCT(_throw_null_pointer_exception_count++;)
   637   SharedRuntime::throw_and_post_jvmti_exception(thread, vmSymbols::java_lang_NullPointerException());
   638 JRT_END
   641 JRT_ENTRY(void, Runtime1::throw_class_cast_exception(JavaThread* thread, oopDesc* object))
   642   NOT_PRODUCT(_throw_class_cast_exception_count++;)
   643   ResourceMark rm(thread);
   644   char* message = SharedRuntime::generate_class_cast_message(
   645     thread, object->klass()->external_name());
   646   SharedRuntime::throw_and_post_jvmti_exception(
   647     thread, vmSymbols::java_lang_ClassCastException(), message);
   648 JRT_END
   651 JRT_ENTRY(void, Runtime1::throw_incompatible_class_change_error(JavaThread* thread))
   652   NOT_PRODUCT(_throw_incompatible_class_change_error_count++;)
   653   ResourceMark rm(thread);
   654   SharedRuntime::throw_and_post_jvmti_exception(thread, vmSymbols::java_lang_IncompatibleClassChangeError());
   655 JRT_END
   658 JRT_ENTRY_NO_ASYNC(void, Runtime1::monitorenter(JavaThread* thread, oopDesc* obj, BasicObjectLock* lock))
   659   NOT_PRODUCT(_monitorenter_slowcase_cnt++;)
   660   if (PrintBiasedLockingStatistics) {
   661     Atomic::inc(BiasedLocking::slow_path_entry_count_addr());
   662   }
   663   Handle h_obj(thread, obj);
   664   assert(h_obj()->is_oop(), "must be NULL or an object");
   665   if (UseBiasedLocking) {
   666     // Retry fast entry if bias is revoked to avoid unnecessary inflation
   667     ObjectSynchronizer::fast_enter(h_obj, lock->lock(), true, CHECK);
   668   } else {
   669     if (UseFastLocking) {
   670       // When using fast locking, the compiled code has already tried the fast case
   671       assert(obj == lock->obj(), "must match");
   672       ObjectSynchronizer::slow_enter(h_obj, lock->lock(), THREAD);
   673     } else {
   674       lock->set_obj(obj);
   675       ObjectSynchronizer::fast_enter(h_obj, lock->lock(), false, THREAD);
   676     }
   677   }
   678 JRT_END
   681 JRT_LEAF(void, Runtime1::monitorexit(JavaThread* thread, BasicObjectLock* lock))
   682   NOT_PRODUCT(_monitorexit_slowcase_cnt++;)
   683   assert(thread == JavaThread::current(), "threads must correspond");
   684   assert(thread->last_Java_sp(), "last_Java_sp must be set");
   685   // monitorexit is non-blocking (leaf routine) => no exceptions can be thrown
   686   EXCEPTION_MARK;
   688   oop obj = lock->obj();
   689   assert(obj->is_oop(), "must be NULL or an object");
   690   if (UseFastLocking) {
   691     // When using fast locking, the compiled code has already tried the fast case
   692     ObjectSynchronizer::slow_exit(obj, lock->lock(), THREAD);
   693   } else {
   694     ObjectSynchronizer::fast_exit(obj, lock->lock(), THREAD);
   695   }
   696 JRT_END
   698 // Cf. OptoRuntime::deoptimize_caller_frame
   699 JRT_ENTRY(void, Runtime1::deoptimize(JavaThread* thread))
   700   // Called from within the owner thread, so no need for safepoint
   701   RegisterMap reg_map(thread, false);
   702   frame stub_frame = thread->last_frame();
   703   assert(stub_frame.is_runtime_frame(), "sanity check");
   704   frame caller_frame = stub_frame.sender(&reg_map);
   706   // We are coming from a compiled method; check this is true.
   707   assert(CodeCache::find_nmethod(caller_frame.pc()) != NULL, "sanity");
   709   // Deoptimize the caller frame.
   710   Deoptimization::deoptimize_frame(thread, caller_frame.id());
   712   // Return to the now deoptimized frame.
   713 JRT_END
   716 static Klass* resolve_field_return_klass(methodHandle caller, int bci, TRAPS) {
   717   Bytecode_field field_access(caller, bci);
   718   // This can be static or non-static field access
   719   Bytecodes::Code code       = field_access.code();
   721   // We must load class, initialize class and resolvethe field
   722   fieldDescriptor result; // initialize class if needed
   723   constantPoolHandle constants(THREAD, caller->constants());
   724   LinkResolver::resolve_field_access(result, constants, field_access.index(), Bytecodes::java_code(code), CHECK_NULL);
   725   return result.field_holder();
   726 }
   729 //
   730 // This routine patches sites where a class wasn't loaded or
   731 // initialized at the time the code was generated.  It handles
   732 // references to classes, fields and forcing of initialization.  Most
   733 // of the cases are straightforward and involving simply forcing
   734 // resolution of a class, rewriting the instruction stream with the
   735 // needed constant and replacing the call in this function with the
   736 // patched code.  The case for static field is more complicated since
   737 // the thread which is in the process of initializing a class can
   738 // access it's static fields but other threads can't so the code
   739 // either has to deoptimize when this case is detected or execute a
   740 // check that the current thread is the initializing thread.  The
   741 // current
   742 //
   743 // Patches basically look like this:
   744 //
   745 //
   746 // patch_site: jmp patch stub     ;; will be patched
   747 // continue:   ...
   748 //             ...
   749 //             ...
   750 //             ...
   751 //
   752 // They have a stub which looks like this:
   753 //
   754 //             ;; patch body
   755 //             movl <const>, reg           (for class constants)
   756 //        <or> movl [reg1 + <const>], reg  (for field offsets)
   757 //        <or> movl reg, [reg1 + <const>]  (for field offsets)
   758 //             <being_init offset> <bytes to copy> <bytes to skip>
   759 // patch_stub: call Runtime1::patch_code (through a runtime stub)
   760 //             jmp patch_site
   761 //
   762 //
   763 // A normal patch is done by rewriting the patch body, usually a move,
   764 // and then copying it into place over top of the jmp instruction
   765 // being careful to flush caches and doing it in an MP-safe way.  The
   766 // constants following the patch body are used to find various pieces
   767 // of the patch relative to the call site for Runtime1::patch_code.
   768 // The case for getstatic and putstatic is more complicated because
   769 // getstatic and putstatic have special semantics when executing while
   770 // the class is being initialized.  getstatic/putstatic on a class
   771 // which is being_initialized may be executed by the initializing
   772 // thread but other threads have to block when they execute it.  This
   773 // is accomplished in compiled code by executing a test of the current
   774 // thread against the initializing thread of the class.  It's emitted
   775 // as boilerplate in their stub which allows the patched code to be
   776 // executed before it's copied back into the main body of the nmethod.
   777 //
   778 // being_init: get_thread(<tmp reg>
   779 //             cmpl [reg1 + <init_thread_offset>], <tmp reg>
   780 //             jne patch_stub
   781 //             movl [reg1 + <const>], reg  (for field offsets)  <or>
   782 //             movl reg, [reg1 + <const>]  (for field offsets)
   783 //             jmp continue
   784 //             <being_init offset> <bytes to copy> <bytes to skip>
   785 // patch_stub: jmp Runtim1::patch_code (through a runtime stub)
   786 //             jmp patch_site
   787 //
   788 // If the class is being initialized the patch body is rewritten and
   789 // the patch site is rewritten to jump to being_init, instead of
   790 // patch_stub.  Whenever this code is executed it checks the current
   791 // thread against the intializing thread so other threads will enter
   792 // the runtime and end up blocked waiting the class to finish
   793 // initializing inside the calls to resolve_field below.  The
   794 // initializing class will continue on it's way.  Once the class is
   795 // fully_initialized, the intializing_thread of the class becomes
   796 // NULL, so the next thread to execute this code will fail the test,
   797 // call into patch_code and complete the patching process by copying
   798 // the patch body back into the main part of the nmethod and resume
   799 // executing.
   800 //
   801 //
   803 JRT_ENTRY(void, Runtime1::patch_code(JavaThread* thread, Runtime1::StubID stub_id ))
   804   NOT_PRODUCT(_patch_code_slowcase_cnt++;)
   806   ResourceMark rm(thread);
   807   RegisterMap reg_map(thread, false);
   808   frame runtime_frame = thread->last_frame();
   809   frame caller_frame = runtime_frame.sender(&reg_map);
   811   // last java frame on stack
   812   vframeStream vfst(thread, true);
   813   assert(!vfst.at_end(), "Java frame must exist");
   815   methodHandle caller_method(THREAD, vfst.method());
   816   // Note that caller_method->code() may not be same as caller_code because of OSR's
   817   // Note also that in the presence of inlining it is not guaranteed
   818   // that caller_method() == caller_code->method()
   820   int bci = vfst.bci();
   821   Bytecodes::Code code = caller_method()->java_code_at(bci);
   823 #ifndef PRODUCT
   824   // this is used by assertions in the access_field_patching_id
   825   BasicType patch_field_type = T_ILLEGAL;
   826 #endif // PRODUCT
   827   bool deoptimize_for_volatile = false;
   828   int patch_field_offset = -1;
   829   KlassHandle init_klass(THREAD, NULL); // klass needed by load_klass_patching code
   830   KlassHandle load_klass(THREAD, NULL); // klass needed by load_klass_patching code
   831   Handle mirror(THREAD, NULL);                    // oop needed by load_mirror_patching code
   832   Handle appendix(THREAD, NULL);                  // oop needed by appendix_patching code
   833   bool load_klass_or_mirror_patch_id =
   834     (stub_id == Runtime1::load_klass_patching_id || stub_id == Runtime1::load_mirror_patching_id);
   836   if (stub_id == Runtime1::access_field_patching_id) {
   838     Bytecode_field field_access(caller_method, bci);
   839     fieldDescriptor result; // initialize class if needed
   840     Bytecodes::Code code = field_access.code();
   841     constantPoolHandle constants(THREAD, caller_method->constants());
   842     LinkResolver::resolve_field_access(result, constants, field_access.index(), Bytecodes::java_code(code), CHECK);
   843     patch_field_offset = result.offset();
   845     // If we're patching a field which is volatile then at compile it
   846     // must not have been know to be volatile, so the generated code
   847     // isn't correct for a volatile reference.  The nmethod has to be
   848     // deoptimized so that the code can be regenerated correctly.
   849     // This check is only needed for access_field_patching since this
   850     // is the path for patching field offsets.  load_klass is only
   851     // used for patching references to oops which don't need special
   852     // handling in the volatile case.
   853     deoptimize_for_volatile = result.access_flags().is_volatile();
   855 #ifndef PRODUCT
   856     patch_field_type = result.field_type();
   857 #endif
   858   } else if (load_klass_or_mirror_patch_id) {
   859     Klass* k = NULL;
   860     switch (code) {
   861       case Bytecodes::_putstatic:
   862       case Bytecodes::_getstatic:
   863         { Klass* klass = resolve_field_return_klass(caller_method, bci, CHECK);
   864           init_klass = KlassHandle(THREAD, klass);
   865           mirror = Handle(THREAD, klass->java_mirror());
   866         }
   867         break;
   868       case Bytecodes::_new:
   869         { Bytecode_new bnew(caller_method(), caller_method->bcp_from(bci));
   870           k = caller_method->constants()->klass_at(bnew.index(), CHECK);
   871         }
   872         break;
   873       case Bytecodes::_multianewarray:
   874         { Bytecode_multianewarray mna(caller_method(), caller_method->bcp_from(bci));
   875           k = caller_method->constants()->klass_at(mna.index(), CHECK);
   876         }
   877         break;
   878       case Bytecodes::_instanceof:
   879         { Bytecode_instanceof io(caller_method(), caller_method->bcp_from(bci));
   880           k = caller_method->constants()->klass_at(io.index(), CHECK);
   881         }
   882         break;
   883       case Bytecodes::_checkcast:
   884         { Bytecode_checkcast cc(caller_method(), caller_method->bcp_from(bci));
   885           k = caller_method->constants()->klass_at(cc.index(), CHECK);
   886         }
   887         break;
   888       case Bytecodes::_anewarray:
   889         { Bytecode_anewarray anew(caller_method(), caller_method->bcp_from(bci));
   890           Klass* ek = caller_method->constants()->klass_at(anew.index(), CHECK);
   891           k = ek->array_klass(CHECK);
   892         }
   893         break;
   894       case Bytecodes::_ldc:
   895       case Bytecodes::_ldc_w:
   896         {
   897           Bytecode_loadconstant cc(caller_method, bci);
   898           oop m = cc.resolve_constant(CHECK);
   899           mirror = Handle(THREAD, m);
   900         }
   901         break;
   902       default: fatal("unexpected bytecode for load_klass_or_mirror_patch_id");
   903     }
   904     // convert to handle
   905     load_klass = KlassHandle(THREAD, k);
   906   } else if (stub_id == load_appendix_patching_id) {
   907     Bytecode_invoke bytecode(caller_method, bci);
   908     Bytecodes::Code bc = bytecode.invoke_code();
   910     CallInfo info;
   911     constantPoolHandle pool(thread, caller_method->constants());
   912     int index = bytecode.index();
   913     LinkResolver::resolve_invoke(info, Handle(), pool, index, bc, CHECK);
   914     appendix = info.resolved_appendix();
   915     switch (bc) {
   916       case Bytecodes::_invokehandle: {
   917         int cache_index = ConstantPool::decode_cpcache_index(index, true);
   918         assert(cache_index >= 0 && cache_index < pool->cache()->length(), "unexpected cache index");
   919         pool->cache()->entry_at(cache_index)->set_method_handle(pool, info);
   920         break;
   921       }
   922       case Bytecodes::_invokedynamic: {
   923         pool->invokedynamic_cp_cache_entry_at(index)->set_dynamic_call(pool, info);
   924         break;
   925       }
   926       default: fatal("unexpected bytecode for load_appendix_patching_id");
   927     }
   928   } else {
   929     ShouldNotReachHere();
   930   }
   932   if (deoptimize_for_volatile) {
   933     // At compile time we assumed the field wasn't volatile but after
   934     // loading it turns out it was volatile so we have to throw the
   935     // compiled code out and let it be regenerated.
   936     if (TracePatching) {
   937       tty->print_cr("Deoptimizing for patching volatile field reference");
   938     }
   939     // It's possible the nmethod was invalidated in the last
   940     // safepoint, but if it's still alive then make it not_entrant.
   941     nmethod* nm = CodeCache::find_nmethod(caller_frame.pc());
   942     if (nm != NULL) {
   943       nm->make_not_entrant();
   944     }
   946     Deoptimization::deoptimize_frame(thread, caller_frame.id());
   948     // Return to the now deoptimized frame.
   949   }
   951   // Now copy code back
   953   {
   954     MutexLockerEx ml_patch (Patching_lock, Mutex::_no_safepoint_check_flag);
   955     //
   956     // Deoptimization may have happened while we waited for the lock.
   957     // In that case we don't bother to do any patching we just return
   958     // and let the deopt happen
   959     if (!caller_is_deopted()) {
   960       NativeGeneralJump* jump = nativeGeneralJump_at(caller_frame.pc());
   961       address instr_pc = jump->jump_destination();
   962       NativeInstruction* ni = nativeInstruction_at(instr_pc);
   963       if (ni->is_jump() ) {
   964         // the jump has not been patched yet
   965         // The jump destination is slow case and therefore not part of the stubs
   966         // (stubs are only for StaticCalls)
   968         // format of buffer
   969         //    ....
   970         //    instr byte 0     <-- copy_buff
   971         //    instr byte 1
   972         //    ..
   973         //    instr byte n-1
   974         //      n
   975         //    ....             <-- call destination
   977         address stub_location = caller_frame.pc() + PatchingStub::patch_info_offset();
   979 #if defined(MIPS32) && defined(_LP64)
   980 /* Jin: In MIPS64, byte_skip is much larger than that in X86. It can not be contained in a byte:
   981  *	int bc = 0x20;
   982  *	int bs = 0x190;
   983  *	int bi = 0x1b0;
   984  * 
   985  *   To minimize the modification of share codes, the values are decreased 4 times when generated.
   986  *   See [mips/c1_CodeStubs_mips.cpp 307] PatchingStub::emit_code().
   987  */
   988         int bc = *(unsigned char*) (stub_location - 1) * 4;
   989         int bs = *(unsigned char*) (stub_location - 2) * 4;
   990         int bi = *(unsigned char*) (stub_location - 3) * 4;
   992 	int *byte_count = &bc;
   993 	int *byte_skip = &bs;
   994 	int *being_initialized_entry_offset = &bi;
   995 #else
   996         unsigned char* byte_count = (unsigned char*) (stub_location - 1);
   997         unsigned char* byte_skip = (unsigned char*) (stub_location - 2);
   998         unsigned char* being_initialized_entry_offset = (unsigned char*) (stub_location - 3);
   999 #endif
  1000         address copy_buff = stub_location - *byte_skip - *byte_count;
  1001         address being_initialized_entry = stub_location - *being_initialized_entry_offset;
  1003         if (TracePatching) {
  1004           tty->print_cr(" Patching %s at bci %d at address " INTPTR_FORMAT "  (%s)", Bytecodes::name(code), bci,
  1005                         p2i(instr_pc), (stub_id == Runtime1::access_field_patching_id) ? "field" : "klass");
  1006           nmethod* caller_code = CodeCache::find_nmethod(caller_frame.pc());
  1007           assert(caller_code != NULL, "nmethod not found");
  1009           // NOTE we use pc() not original_pc() because we already know they are
  1010           // identical otherwise we'd have never entered this block of code
  1012           OopMap* map = caller_code->oop_map_for_return_address(caller_frame.pc());
  1013           assert(map != NULL, "null check");
  1014           map->print();
  1015           tty->cr();
  1017           Disassembler::decode(copy_buff, copy_buff + *byte_count, tty);
  1019         // depending on the code below, do_patch says whether to copy the patch body back into the nmethod
  1020         bool do_patch = true;
  1021         if (stub_id == Runtime1::access_field_patching_id) {
  1022           // The offset may not be correct if the class was not loaded at code generation time.
  1023           // Set it now.
  1024           NativeMovRegMem* n_move = nativeMovRegMem_at(copy_buff);
  1025           assert(n_move->offset() == 0 || (n_move->offset() == 4 && (patch_field_type == T_DOUBLE || patch_field_type == T_LONG)), "illegal offset for type");
  1026           assert(patch_field_offset >= 0, "illegal offset");
  1027           n_move->add_offset_in_bytes(patch_field_offset);
  1028         } else if (load_klass_or_mirror_patch_id) {
  1029           // If a getstatic or putstatic is referencing a klass which
  1030           // isn't fully initialized, the patch body isn't copied into
  1031           // place until initialization is complete.  In this case the
  1032           // patch site is setup so that any threads besides the
  1033           // initializing thread are forced to come into the VM and
  1034           // block.
  1035           do_patch = (code != Bytecodes::_getstatic && code != Bytecodes::_putstatic) ||
  1036                      InstanceKlass::cast(init_klass())->is_initialized();
  1037           NativeGeneralJump* jump = nativeGeneralJump_at(instr_pc);
  1038           if (jump->jump_destination() == being_initialized_entry) {
  1039             assert(do_patch == true, "initialization must be complete at this point");
  1040           } else {
  1041             // patch the instruction <move reg, klass>
  1042             NativeMovConstReg* n_copy = nativeMovConstReg_at(copy_buff);
  1044             assert(n_copy->data() == 0 ||
  1045                    n_copy->data() == (intptr_t)Universe::non_oop_word(),
  1046                    "illegal init value");
  1047             if (stub_id == Runtime1::load_klass_patching_id) {
  1048               assert(load_klass() != NULL, "klass not set");
  1049               n_copy->set_data((intx) (load_klass()));
  1050             } else {
  1051               assert(mirror() != NULL, "klass not set");
  1052               // Don't need a G1 pre-barrier here since we assert above that data isn't an oop.
  1053               n_copy->set_data(cast_from_oop<intx>(mirror()));
  1056             if (TracePatching) {
  1057               Disassembler::decode(copy_buff, copy_buff + *byte_count, tty);
  1060         } else if (stub_id == Runtime1::load_appendix_patching_id) {
  1061           NativeMovConstReg* n_copy = nativeMovConstReg_at(copy_buff);
  1062           assert(n_copy->data() == 0 ||
  1063                  n_copy->data() == (intptr_t)Universe::non_oop_word(),
  1064                  "illegal init value");
  1065           n_copy->set_data(cast_from_oop<intx>(appendix()));
  1067           if (TracePatching) {
  1068             Disassembler::decode(copy_buff, copy_buff + *byte_count, tty);
  1070         } else {
  1071           ShouldNotReachHere();
  1074 #if defined(SPARC) || defined(PPC)
  1075         if (load_klass_or_mirror_patch_id ||
  1076             stub_id == Runtime1::load_appendix_patching_id) {
  1077           // Update the location in the nmethod with the proper
  1078           // metadata.  When the code was generated, a NULL was stuffed
  1079           // in the metadata table and that table needs to be update to
  1080           // have the right value.  On intel the value is kept
  1081           // directly in the instruction instead of in the metadata
  1082           // table, so set_data above effectively updated the value.
  1083           nmethod* nm = CodeCache::find_nmethod(instr_pc);
  1084           assert(nm != NULL, "invalid nmethod_pc");
  1085           RelocIterator mds(nm, copy_buff, copy_buff + 1);
  1086           bool found = false;
  1087           while (mds.next() && !found) {
  1088             if (mds.type() == relocInfo::oop_type) {
  1089               assert(stub_id == Runtime1::load_mirror_patching_id ||
  1090                      stub_id == Runtime1::load_appendix_patching_id, "wrong stub id");
  1091               oop_Relocation* r = mds.oop_reloc();
  1092               oop* oop_adr = r->oop_addr();
  1093               *oop_adr = stub_id == Runtime1::load_mirror_patching_id ? mirror() : appendix();
  1094               r->fix_oop_relocation();
  1095               found = true;
  1096             } else if (mds.type() == relocInfo::metadata_type) {
  1097               assert(stub_id == Runtime1::load_klass_patching_id, "wrong stub id");
  1098               metadata_Relocation* r = mds.metadata_reloc();
  1099               Metadata** metadata_adr = r->metadata_addr();
  1100               *metadata_adr = load_klass();
  1101               r->fix_metadata_relocation();
  1102               found = true;
  1105           assert(found, "the metadata must exist!");
  1107 #endif
  1108         if (do_patch) {
  1109           // replace instructions
  1110           // first replace the tail, then the call
  1111 #ifdef ARM
  1112           if((load_klass_or_mirror_patch_id ||
  1113               stub_id == Runtime1::load_appendix_patching_id) &&
  1114               nativeMovConstReg_at(copy_buff)->is_pc_relative()) {
  1115             nmethod* nm = CodeCache::find_nmethod(instr_pc);
  1116             address addr = NULL;
  1117             assert(nm != NULL, "invalid nmethod_pc");
  1118             RelocIterator mds(nm, copy_buff, copy_buff + 1);
  1119             while (mds.next()) {
  1120               if (mds.type() == relocInfo::oop_type) {
  1121                 assert(stub_id == Runtime1::load_mirror_patching_id ||
  1122                        stub_id == Runtime1::load_appendix_patching_id, "wrong stub id");
  1123                 oop_Relocation* r = mds.oop_reloc();
  1124                 addr = (address)r->oop_addr();
  1125                 break;
  1126               } else if (mds.type() == relocInfo::metadata_type) {
  1127                 assert(stub_id == Runtime1::load_klass_patching_id, "wrong stub id");
  1128                 metadata_Relocation* r = mds.metadata_reloc();
  1129                 addr = (address)r->metadata_addr();
  1130                 break;
  1133             assert(addr != NULL, "metadata relocation must exist");
  1134             copy_buff -= *byte_count;
  1135             NativeMovConstReg* n_copy2 = nativeMovConstReg_at(copy_buff);
  1136             n_copy2->set_pc_relative_offset(addr, instr_pc);
  1138 #endif
  1140           for (int i = NativeCall::instruction_size; i < *byte_count; i++) {
  1141             address ptr = copy_buff + i;
  1142             int a_byte = (*ptr) & 0xFF;
  1143             address dst = instr_pc + i;
  1144             *(unsigned char*)dst = (unsigned char) a_byte;
  1146           ICache::invalidate_range(instr_pc, *byte_count);
  1147           NativeGeneralJump::replace_mt_safe(instr_pc, copy_buff);
  1149           if (load_klass_or_mirror_patch_id ||
  1150               stub_id == Runtime1::load_appendix_patching_id) {
  1151             relocInfo::relocType rtype =
  1152               (stub_id == Runtime1::load_klass_patching_id) ?
  1153                                    relocInfo::metadata_type :
  1154                                    relocInfo::oop_type;
  1155             // update relocInfo to metadata
  1156             nmethod* nm = CodeCache::find_nmethod(instr_pc);
  1157             assert(nm != NULL, "invalid nmethod_pc");
  1159             // The old patch site is now a move instruction so update
  1160             // the reloc info so that it will get updated during
  1161             // future GCs.
  1162             RelocIterator iter(nm, (address)instr_pc, (address)(instr_pc + 1));
  1163             relocInfo::change_reloc_info_for_address(&iter, (address) instr_pc,
  1164                                                      relocInfo::none, rtype);
  1165 #ifdef SPARC
  1166             // Sparc takes two relocations for an metadata so update the second one.
  1167             address instr_pc2 = instr_pc + NativeMovConstReg::add_offset;
  1168             RelocIterator iter2(nm, instr_pc2, instr_pc2 + 1);
  1169             relocInfo::change_reloc_info_for_address(&iter2, (address) instr_pc2,
  1170                                                      relocInfo::none, rtype);
  1171 #endif
  1172 #ifdef PPC
  1173           { address instr_pc2 = instr_pc + NativeMovConstReg::lo_offset;
  1174             RelocIterator iter2(nm, instr_pc2, instr_pc2 + 1);
  1175             relocInfo::change_reloc_info_for_address(&iter2, (address) instr_pc2,
  1176                                                      relocInfo::none, rtype);
  1178 #endif
  1181         } else {
  1182           ICache::invalidate_range(copy_buff, *byte_count);
  1183           NativeGeneralJump::insert_unconditional(instr_pc, being_initialized_entry);
  1189   // If we are patching in a non-perm oop, make sure the nmethod
  1190   // is on the right list.
  1191   if (ScavengeRootsInCode && ((mirror.not_null() && mirror()->is_scavengable()) ||
  1192                               (appendix.not_null() && appendix->is_scavengable()))) {
  1193     MutexLockerEx ml_code (CodeCache_lock, Mutex::_no_safepoint_check_flag);
  1194     nmethod* nm = CodeCache::find_nmethod(caller_frame.pc());
  1195     guarantee(nm != NULL, "only nmethods can contain non-perm oops");
  1196     if (!nm->on_scavenge_root_list()) {
  1197       CodeCache::add_scavenge_root_nmethod(nm);
  1200     // Since we've patched some oops in the nmethod,
  1201     // (re)register it with the heap.
  1202     Universe::heap()->register_nmethod(nm);
  1204 JRT_END
  1206 //
  1207 // Entry point for compiled code. We want to patch a nmethod.
  1208 // We don't do a normal VM transition here because we want to
  1209 // know after the patching is complete and any safepoint(s) are taken
  1210 // if the calling nmethod was deoptimized. We do this by calling a
  1211 // helper method which does the normal VM transition and when it
  1212 // completes we can check for deoptimization. This simplifies the
  1213 // assembly code in the cpu directories.
  1214 //
  1215 int Runtime1::move_klass_patching(JavaThread* thread) {
  1216 //
  1217 // NOTE: we are still in Java
  1218 //
  1219   Thread* THREAD = thread;
  1220   debug_only(NoHandleMark nhm;)
  1222     // Enter VM mode
  1224     ResetNoHandleMark rnhm;
  1225     patch_code(thread, load_klass_patching_id);
  1227   // Back in JAVA, use no oops DON'T safepoint
  1229   // Return true if calling code is deoptimized
  1231   return caller_is_deopted();
  1234 int Runtime1::move_mirror_patching(JavaThread* thread) {
  1235 //
  1236 // NOTE: we are still in Java
  1237 //
  1238   Thread* THREAD = thread;
  1239   debug_only(NoHandleMark nhm;)
  1241     // Enter VM mode
  1243     ResetNoHandleMark rnhm;
  1244     patch_code(thread, load_mirror_patching_id);
  1246   // Back in JAVA, use no oops DON'T safepoint
  1248   // Return true if calling code is deoptimized
  1250   return caller_is_deopted();
  1253 int Runtime1::move_appendix_patching(JavaThread* thread) {
  1254 //
  1255 // NOTE: we are still in Java
  1256 //
  1257   Thread* THREAD = thread;
  1258   debug_only(NoHandleMark nhm;)
  1260     // Enter VM mode
  1262     ResetNoHandleMark rnhm;
  1263     patch_code(thread, load_appendix_patching_id);
  1265   // Back in JAVA, use no oops DON'T safepoint
  1267   // Return true if calling code is deoptimized
  1269   return caller_is_deopted();
  1271 //
  1272 // Entry point for compiled code. We want to patch a nmethod.
  1273 // We don't do a normal VM transition here because we want to
  1274 // know after the patching is complete and any safepoint(s) are taken
  1275 // if the calling nmethod was deoptimized. We do this by calling a
  1276 // helper method which does the normal VM transition and when it
  1277 // completes we can check for deoptimization. This simplifies the
  1278 // assembly code in the cpu directories.
  1279 //
  1281 int Runtime1::access_field_patching(JavaThread* thread) {
  1282 //
  1283 // NOTE: we are still in Java
  1284 //
  1285   Thread* THREAD = thread;
  1286   debug_only(NoHandleMark nhm;)
  1288     // Enter VM mode
  1290     ResetNoHandleMark rnhm;
  1291     patch_code(thread, access_field_patching_id);
  1293   // Back in JAVA, use no oops DON'T safepoint
  1295   // Return true if calling code is deoptimized
  1297   return caller_is_deopted();
  1298 JRT_END
  1301 JRT_LEAF(void, Runtime1::trace_block_entry(jint block_id))
  1302   // for now we just print out the block id
  1303   tty->print("%d ", block_id);
  1304 JRT_END
  1307 // Array copy return codes.
  1308 enum {
  1309   ac_failed = -1, // arraycopy failed
  1310   ac_ok = 0       // arraycopy succeeded
  1311 };
  1314 // Below length is the # elements copied.
  1315 template <class T> int obj_arraycopy_work(oopDesc* src, T* src_addr,
  1316                                           oopDesc* dst, T* dst_addr,
  1317                                           int length) {
  1319   // For performance reasons, we assume we are using a card marking write
  1320   // barrier. The assert will fail if this is not the case.
  1321   // Note that we use the non-virtual inlineable variant of write_ref_array.
  1322   BarrierSet* bs = Universe::heap()->barrier_set();
  1323   assert(bs->has_write_ref_array_opt(), "Barrier set must have ref array opt");
  1324   assert(bs->has_write_ref_array_pre_opt(), "For pre-barrier as well.");
  1325   if (src == dst) {
  1326     // same object, no check
  1327     bs->write_ref_array_pre(dst_addr, length);
  1328     Copy::conjoint_oops_atomic(src_addr, dst_addr, length);
  1329     bs->write_ref_array((HeapWord*)dst_addr, length);
  1330     return ac_ok;
  1331   } else {
  1332     Klass* bound = ObjArrayKlass::cast(dst->klass())->element_klass();
  1333     Klass* stype = ObjArrayKlass::cast(src->klass())->element_klass();
  1334     if (stype == bound || stype->is_subtype_of(bound)) {
  1335       // Elements are guaranteed to be subtypes, so no check necessary
  1336       bs->write_ref_array_pre(dst_addr, length);
  1337       Copy::conjoint_oops_atomic(src_addr, dst_addr, length);
  1338       bs->write_ref_array((HeapWord*)dst_addr, length);
  1339       return ac_ok;
  1342   return ac_failed;
  1345 // fast and direct copy of arrays; returning -1, means that an exception may be thrown
  1346 // and we did not copy anything
  1347 JRT_LEAF(int, Runtime1::arraycopy(oopDesc* src, int src_pos, oopDesc* dst, int dst_pos, int length))
  1348 #ifndef PRODUCT
  1349   _generic_arraycopy_cnt++;        // Slow-path oop array copy
  1350 #endif
  1352   if (src == NULL || dst == NULL || src_pos < 0 || dst_pos < 0 || length < 0) return ac_failed;
  1353   if (!dst->is_array() || !src->is_array()) return ac_failed;
  1354   if ((unsigned int) arrayOop(src)->length() < (unsigned int)src_pos + (unsigned int)length) return ac_failed;
  1355   if ((unsigned int) arrayOop(dst)->length() < (unsigned int)dst_pos + (unsigned int)length) return ac_failed;
  1357   if (length == 0) return ac_ok;
  1358   if (src->is_typeArray()) {
  1359     Klass* klass_oop = src->klass();
  1360     if (klass_oop != dst->klass()) return ac_failed;
  1361     TypeArrayKlass* klass = TypeArrayKlass::cast(klass_oop);
  1362     const int l2es = klass->log2_element_size();
  1363     const int ihs = klass->array_header_in_bytes() / wordSize;
  1364     char* src_addr = (char*) ((oopDesc**)src + ihs) + (src_pos << l2es);
  1365     char* dst_addr = (char*) ((oopDesc**)dst + ihs) + (dst_pos << l2es);
  1366     // Potential problem: memmove is not guaranteed to be word atomic
  1367     // Revisit in Merlin
  1368     memmove(dst_addr, src_addr, length << l2es);
  1369     return ac_ok;
  1370   } else if (src->is_objArray() && dst->is_objArray()) {
  1371     if (UseCompressedOops) {
  1372       narrowOop *src_addr  = objArrayOop(src)->obj_at_addr<narrowOop>(src_pos);
  1373       narrowOop *dst_addr  = objArrayOop(dst)->obj_at_addr<narrowOop>(dst_pos);
  1374       return obj_arraycopy_work(src, src_addr, dst, dst_addr, length);
  1375     } else {
  1376       oop *src_addr  = objArrayOop(src)->obj_at_addr<oop>(src_pos);
  1377       oop *dst_addr  = objArrayOop(dst)->obj_at_addr<oop>(dst_pos);
  1378       return obj_arraycopy_work(src, src_addr, dst, dst_addr, length);
  1381   return ac_failed;
  1382 JRT_END
  1385 JRT_LEAF(void, Runtime1::primitive_arraycopy(HeapWord* src, HeapWord* dst, int length))
  1386 #ifndef PRODUCT
  1387   _primitive_arraycopy_cnt++;
  1388 #endif
  1390   if (length == 0) return;
  1391   // Not guaranteed to be word atomic, but that doesn't matter
  1392   // for anything but an oop array, which is covered by oop_arraycopy.
  1393   Copy::conjoint_jbytes(src, dst, length);
  1394 JRT_END
  1396 JRT_LEAF(void, Runtime1::oop_arraycopy(HeapWord* src, HeapWord* dst, int num))
  1397 #ifndef PRODUCT
  1398   _oop_arraycopy_cnt++;
  1399 #endif
  1401   if (num == 0) return;
  1402   BarrierSet* bs = Universe::heap()->barrier_set();
  1403   assert(bs->has_write_ref_array_opt(), "Barrier set must have ref array opt");
  1404   assert(bs->has_write_ref_array_pre_opt(), "For pre-barrier as well.");
  1405   if (UseCompressedOops) {
  1406     bs->write_ref_array_pre((narrowOop*)dst, num);
  1407     Copy::conjoint_oops_atomic((narrowOop*) src, (narrowOop*) dst, num);
  1408   } else {
  1409     bs->write_ref_array_pre((oop*)dst, num);
  1410     Copy::conjoint_oops_atomic((oop*) src, (oop*) dst, num);
  1412   bs->write_ref_array(dst, num);
  1413 JRT_END
  1416 JRT_LEAF(int, Runtime1::is_instance_of(oopDesc* mirror, oopDesc* obj))
  1417   // had to return int instead of bool, otherwise there may be a mismatch
  1418   // between the C calling convention and the Java one.
  1419   // e.g., on x86, GCC may clear only %al when returning a bool false, but
  1420   // JVM takes the whole %eax as the return value, which may misinterpret
  1421   // the return value as a boolean true.
  1423   assert(mirror != NULL, "should null-check on mirror before calling");
  1424   Klass* k = java_lang_Class::as_Klass(mirror);
  1425   return (k != NULL && obj != NULL && obj->is_a(k)) ? 1 : 0;
  1426 JRT_END
  1428 JRT_ENTRY(void, Runtime1::predicate_failed_trap(JavaThread* thread))
  1429   ResourceMark rm;
  1431   assert(!TieredCompilation, "incompatible with tiered compilation");
  1433   RegisterMap reg_map(thread, false);
  1434   frame runtime_frame = thread->last_frame();
  1435   frame caller_frame = runtime_frame.sender(&reg_map);
  1437   nmethod* nm = CodeCache::find_nmethod(caller_frame.pc());
  1438   assert (nm != NULL, "no more nmethod?");
  1439   nm->make_not_entrant();
  1441   methodHandle m(nm->method());
  1442   MethodData* mdo = m->method_data();
  1444   if (mdo == NULL && !HAS_PENDING_EXCEPTION) {
  1445     // Build an MDO.  Ignore errors like OutOfMemory;
  1446     // that simply means we won't have an MDO to update.
  1447     Method::build_interpreter_method_data(m, THREAD);
  1448     if (HAS_PENDING_EXCEPTION) {
  1449       assert((PENDING_EXCEPTION->is_a(SystemDictionary::OutOfMemoryError_klass())), "we expect only an OOM error here");
  1450       CLEAR_PENDING_EXCEPTION;
  1452     mdo = m->method_data();
  1455   if (mdo != NULL) {
  1456     mdo->inc_trap_count(Deoptimization::Reason_none);
  1459   if (TracePredicateFailedTraps) {
  1460     stringStream ss1, ss2;
  1461     vframeStream vfst(thread);
  1462     methodHandle inlinee = methodHandle(vfst.method());
  1463     inlinee->print_short_name(&ss1);
  1464     m->print_short_name(&ss2);
  1465     tty->print_cr("Predicate failed trap in method %s at bci %d inlined in %s at pc " INTPTR_FORMAT, ss1.as_string(), vfst.bci(), ss2.as_string(), p2i(caller_frame.pc()));
  1469   Deoptimization::deoptimize_frame(thread, caller_frame.id());
  1471 JRT_END
  1473 #ifndef PRODUCT
  1474 void Runtime1::print_statistics() {
  1475   tty->print_cr("C1 Runtime statistics:");
  1476   tty->print_cr(" _resolve_invoke_virtual_cnt:     %d", SharedRuntime::_resolve_virtual_ctr);
  1477   tty->print_cr(" _resolve_invoke_opt_virtual_cnt: %d", SharedRuntime::_resolve_opt_virtual_ctr);
  1478   tty->print_cr(" _resolve_invoke_static_cnt:      %d", SharedRuntime::_resolve_static_ctr);
  1479   tty->print_cr(" _handle_wrong_method_cnt:        %d", SharedRuntime::_wrong_method_ctr);
  1480   tty->print_cr(" _ic_miss_cnt:                    %d", SharedRuntime::_ic_miss_ctr);
  1481   tty->print_cr(" _generic_arraycopy_cnt:          %d", _generic_arraycopy_cnt);
  1482   tty->print_cr(" _generic_arraycopystub_cnt:      %d", _generic_arraycopystub_cnt);
  1483   tty->print_cr(" _byte_arraycopy_cnt:             %d", _byte_arraycopy_cnt);
  1484   tty->print_cr(" _short_arraycopy_cnt:            %d", _short_arraycopy_cnt);
  1485   tty->print_cr(" _int_arraycopy_cnt:              %d", _int_arraycopy_cnt);
  1486   tty->print_cr(" _long_arraycopy_cnt:             %d", _long_arraycopy_cnt);
  1487   tty->print_cr(" _primitive_arraycopy_cnt:        %d", _primitive_arraycopy_cnt);
  1488   tty->print_cr(" _oop_arraycopy_cnt (C):          %d", Runtime1::_oop_arraycopy_cnt);
  1489   tty->print_cr(" _oop_arraycopy_cnt (stub):       %d", _oop_arraycopy_cnt);
  1490   tty->print_cr(" _arraycopy_slowcase_cnt:         %d", _arraycopy_slowcase_cnt);
  1491   tty->print_cr(" _arraycopy_checkcast_cnt:        %d", _arraycopy_checkcast_cnt);
  1492   tty->print_cr(" _arraycopy_checkcast_attempt_cnt:%d", _arraycopy_checkcast_attempt_cnt);
  1494   tty->print_cr(" _new_type_array_slowcase_cnt:    %d", _new_type_array_slowcase_cnt);
  1495   tty->print_cr(" _new_object_array_slowcase_cnt:  %d", _new_object_array_slowcase_cnt);
  1496   tty->print_cr(" _new_instance_slowcase_cnt:      %d", _new_instance_slowcase_cnt);
  1497   tty->print_cr(" _new_multi_array_slowcase_cnt:   %d", _new_multi_array_slowcase_cnt);
  1498   tty->print_cr(" _monitorenter_slowcase_cnt:      %d", _monitorenter_slowcase_cnt);
  1499   tty->print_cr(" _monitorexit_slowcase_cnt:       %d", _monitorexit_slowcase_cnt);
  1500   tty->print_cr(" _patch_code_slowcase_cnt:        %d", _patch_code_slowcase_cnt);
  1502   tty->print_cr(" _throw_range_check_exception_count:            %d:", _throw_range_check_exception_count);
  1503   tty->print_cr(" _throw_index_exception_count:                  %d:", _throw_index_exception_count);
  1504   tty->print_cr(" _throw_div0_exception_count:                   %d:", _throw_div0_exception_count);
  1505   tty->print_cr(" _throw_null_pointer_exception_count:           %d:", _throw_null_pointer_exception_count);
  1506   tty->print_cr(" _throw_class_cast_exception_count:             %d:", _throw_class_cast_exception_count);
  1507   tty->print_cr(" _throw_incompatible_class_change_error_count:  %d:", _throw_incompatible_class_change_error_count);
  1508   tty->print_cr(" _throw_array_store_exception_count:            %d:", _throw_array_store_exception_count);
  1509   tty->print_cr(" _throw_count:                                  %d:", _throw_count);
  1511   SharedRuntime::print_ic_miss_histogram();
  1512   tty->cr();
  1514 #endif // PRODUCT

mercurial