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