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