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