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