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