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