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