1 /*
   2  * Copyright (c) 1999, 2025, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "asm/codeBuffer.hpp"
  26 #include "c1/c1_CodeStubs.hpp"
  27 #include "c1/c1_Defs.hpp"
  28 #include "c1/c1_LIRAssembler.hpp"
  29 #include "c1/c1_MacroAssembler.hpp"
  30 #include "c1/c1_Runtime1.hpp"
  31 #include "classfile/javaClasses.inline.hpp"
  32 #include "classfile/vmClasses.hpp"
  33 #include "classfile/vmSymbols.hpp"
  34 #include "code/aotCodeCache.hpp"
  35 #include "code/codeBlob.hpp"
  36 #include "code/compiledIC.hpp"
  37 #include "code/scopeDesc.hpp"
  38 #include "code/vtableStubs.hpp"
  39 #include "compiler/compilationPolicy.hpp"
  40 #include "compiler/disassembler.hpp"
  41 #include "compiler/oopMap.hpp"
  42 #include "gc/shared/barrierSet.hpp"
  43 #include "gc/shared/c1/barrierSetC1.hpp"
  44 #include "gc/shared/collectedHeap.hpp"
  45 #include "interpreter/bytecode.hpp"
  46 #include "interpreter/interpreter.hpp"
  47 #include "jfr/support/jfrIntrinsics.hpp"
  48 #include "logging/log.hpp"
  49 #include "memory/oopFactory.hpp"
  50 #include "memory/resourceArea.hpp"
  51 #include "memory/universe.hpp"
  52 #include "oops/access.inline.hpp"
  53 #include "oops/flatArrayKlass.hpp"
  54 #include "oops/flatArrayOop.inline.hpp"
  55 #include "oops/objArrayKlass.hpp"
  56 #include "oops/objArrayOop.inline.hpp"
  57 #include "oops/oop.inline.hpp"
  58 #include "prims/jvmtiExport.hpp"
  59 #include "runtime/atomic.hpp"
  60 #include "runtime/fieldDescriptor.inline.hpp"
  61 #include "runtime/frame.inline.hpp"
  62 #include "runtime/handles.inline.hpp"
  63 #include "runtime/interfaceSupport.inline.hpp"
  64 #include "runtime/javaCalls.hpp"
  65 #include "runtime/sharedRuntime.hpp"
  66 #include "runtime/stackWatermarkSet.hpp"
  67 #include "runtime/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   // Reset method handle flag.
 677   current->set_is_method_handle_return(false);
 678 
 679   Handle exception(current, ex);
 680 
 681   // This function is called when we are about to throw an exception. Therefore,
 682   // we have to poll the stack watermark barrier to make sure that not yet safe
 683   // stack frames are made safe before returning into them.
 684   if (current->last_frame().cb() == Runtime1::blob_for(StubId::c1_handle_exception_from_callee_id)) {
 685     // The StubId::c1_handle_exception_from_callee_id handler is invoked after the
 686     // frame has been unwound. It instead builds its own stub frame, to call the
 687     // runtime. But the throwing frame has already been unwound here.
 688     StackWatermarkSet::after_unwind(current);
 689   }
 690 
 691   nm = CodeCache::find_nmethod(pc);
 692   assert(nm != nullptr, "this is not an nmethod");
 693   // Adjust the pc as needed/
 694   if (nm->is_deopt_pc(pc)) {
 695     RegisterMap map(current,
 696                     RegisterMap::UpdateMap::skip,
 697                     RegisterMap::ProcessFrames::include,
 698                     RegisterMap::WalkContinuation::skip);
 699     frame exception_frame = current->last_frame().sender(&map);
 700     // if the frame isn't deopted then pc must not correspond to the caller of last_frame
 701     assert(exception_frame.is_deoptimized_frame(), "must be deopted");
 702     pc = exception_frame.pc();
 703   }
 704   assert(exception.not_null(), "null exceptions should be handled by throw_exception");
 705   // Check that exception is a subclass of Throwable
 706   assert(exception->is_a(vmClasses::Throwable_klass()),
 707          "Exception not subclass of Throwable");
 708 
 709   // debugging support
 710   // tracing
 711   if (log_is_enabled(Info, exceptions)) {
 712     ResourceMark rm; // print_value_string
 713     stringStream tempst;
 714     assert(nm->method() != nullptr, "Unexpected null method()");
 715     tempst.print("C1 compiled method <%s>\n"
 716                  " at PC" INTPTR_FORMAT " for thread " INTPTR_FORMAT,
 717                  nm->method()->print_value_string(), p2i(pc), p2i(current));
 718     Exceptions::log_exception(exception, tempst.freeze());
 719   }
 720   // for AbortVMOnException flag
 721   Exceptions::debug_check_abort(exception);
 722 
 723   // Check the stack guard pages and re-enable them if necessary and there is
 724   // enough space on the stack to do so.  Use fast exceptions only if the guard
 725   // pages are enabled.
 726   bool guard_pages_enabled = current->stack_overflow_state()->reguard_stack_if_needed();
 727 
 728   if (JvmtiExport::can_post_on_exceptions()) {
 729     // To ensure correct notification of exception catches and throws
 730     // we have to deoptimize here.  If we attempted to notify the
 731     // catches and throws during this exception lookup it's possible
 732     // we could deoptimize on the way out of the VM and end back in
 733     // the interpreter at the throw site.  This would result in double
 734     // notifications since the interpreter would also notify about
 735     // these same catches and throws as it unwound the frame.
 736 
 737     RegisterMap reg_map(current,
 738                         RegisterMap::UpdateMap::include,
 739                         RegisterMap::ProcessFrames::include,
 740                         RegisterMap::WalkContinuation::skip);
 741     frame stub_frame = current->last_frame();
 742     frame caller_frame = stub_frame.sender(&reg_map);
 743 
 744     // We don't really want to deoptimize the nmethod itself since we
 745     // can actually continue in the exception handler ourselves but I
 746     // don't see an easy way to have the desired effect.
 747     Deoptimization::deoptimize_frame(current, caller_frame.id());
 748     assert(caller_is_deopted(current), "Must be deoptimized");
 749 
 750     return SharedRuntime::deopt_blob()->unpack_with_exception_in_tls();
 751   }
 752 
 753   // ExceptionCache is used only for exceptions at call sites and not for implicit exceptions
 754   if (guard_pages_enabled) {
 755     address fast_continuation = nm->handler_for_exception_and_pc(exception, pc);
 756     if (fast_continuation != nullptr) {
 757       // Set flag if return address is a method handle call site.
 758       current->set_is_method_handle_return(nm->is_method_handle_return(pc));
 759       return fast_continuation;
 760     }
 761   }
 762 
 763   // If the stack guard pages are enabled, check whether there is a handler in
 764   // the current method.  Otherwise (guard pages disabled), force an unwind and
 765   // skip the exception cache update (i.e., just leave continuation as null).
 766   address continuation = nullptr;
 767   if (guard_pages_enabled) {
 768 
 769     // New exception handling mechanism can support inlined methods
 770     // with exception handlers since the mappings are from PC to PC
 771 
 772     // Clear out the exception oop and pc since looking up an
 773     // exception handler can cause class loading, which might throw an
 774     // exception and those fields are expected to be clear during
 775     // normal bytecode execution.
 776     current->clear_exception_oop_and_pc();
 777 
 778     bool recursive_exception = false;
 779     continuation = SharedRuntime::compute_compiled_exc_handler(nm, pc, exception, false, false, recursive_exception);
 780     // If an exception was thrown during exception dispatch, the exception oop may have changed
 781     current->set_exception_oop(exception());
 782     current->set_exception_pc(pc);
 783 
 784     // the exception cache is used only by non-implicit exceptions
 785     // Update the exception cache only when there didn't happen
 786     // another exception during the computation of the compiled
 787     // exception handler. Checking for exception oop equality is not
 788     // sufficient because some exceptions are pre-allocated and reused.
 789     if (continuation != nullptr && !recursive_exception) {
 790       nm->add_handler_for_exception_and_pc(exception, pc, continuation);
 791     }
 792   }
 793 
 794   current->set_vm_result_oop(exception());
 795   // Set flag if return address is a method handle call site.
 796   current->set_is_method_handle_return(nm->is_method_handle_return(pc));
 797 
 798   if (log_is_enabled(Info, exceptions)) {
 799     ResourceMark rm;
 800     log_info(exceptions)("Thread " PTR_FORMAT " continuing at PC " PTR_FORMAT
 801                          " for exception thrown at PC " PTR_FORMAT,
 802                          p2i(current), p2i(continuation), p2i(pc));
 803   }
 804 
 805   return continuation;
 806 JRT_END
 807 
 808 // Enter this method from compiled code only if there is a Java exception handler
 809 // in the method handling the exception.
 810 // We are entering here from exception stub. We don't do a normal VM transition here.
 811 // We do it in a helper. This is so we can check to see if the nmethod we have just
 812 // searched for an exception handler has been deoptimized in the meantime.
 813 address Runtime1::exception_handler_for_pc(JavaThread* current) {
 814   oop exception = current->exception_oop();
 815   address pc = current->exception_pc();
 816   // Still in Java mode
 817   DEBUG_ONLY(NoHandleMark nhm);
 818   nmethod* nm = nullptr;
 819   address continuation = nullptr;
 820   {
 821     // Enter VM mode by calling the helper
 822     ResetNoHandleMark rnhm;
 823     continuation = exception_handler_for_pc_helper(current, exception, pc, nm);
 824   }
 825   // Back in JAVA, use no oops DON'T safepoint
 826 
 827   // Now check to see if the nmethod we were called from is now deoptimized.
 828   // If so we must return to the deopt blob and deoptimize the nmethod
 829   if (nm != nullptr && caller_is_deopted(current)) {
 830     continuation = SharedRuntime::deopt_blob()->unpack_with_exception_in_tls();
 831   }
 832 
 833   assert(continuation != nullptr, "no handler found");
 834   return continuation;
 835 }
 836 
 837 
 838 JRT_ENTRY(void, Runtime1::throw_range_check_exception(JavaThread* current, int index, arrayOopDesc* a))
 839 #ifndef PRODUCT
 840   if (PrintC1Statistics) {
 841     _throw_range_check_exception_count++;
 842   }
 843 #endif
 844   const int len = 35;
 845   assert(len < strlen("Index %d out of bounds for length %d"), "Must allocate more space for message.");
 846   char message[2 * jintAsStringSize + len];
 847   os::snprintf_checked(message, sizeof(message), "Index %d out of bounds for length %d", index, a->length());
 848   SharedRuntime::throw_and_post_jvmti_exception(current, vmSymbols::java_lang_ArrayIndexOutOfBoundsException(), message);
 849 JRT_END
 850 
 851 
 852 JRT_ENTRY(void, Runtime1::throw_index_exception(JavaThread* current, int index))
 853 #ifndef PRODUCT
 854   if (PrintC1Statistics) {
 855     _throw_index_exception_count++;
 856   }
 857 #endif
 858   char message[16];
 859   os::snprintf_checked(message, sizeof(message), "%d", index);
 860   SharedRuntime::throw_and_post_jvmti_exception(current, vmSymbols::java_lang_IndexOutOfBoundsException(), message);
 861 JRT_END
 862 
 863 
 864 JRT_ENTRY(void, Runtime1::throw_div0_exception(JavaThread* current))
 865 #ifndef PRODUCT
 866   if (PrintC1Statistics) {
 867     _throw_div0_exception_count++;
 868   }
 869 #endif
 870   SharedRuntime::throw_and_post_jvmti_exception(current, vmSymbols::java_lang_ArithmeticException(), "/ by zero");
 871 JRT_END
 872 
 873 
 874 JRT_ENTRY(void, Runtime1::throw_null_pointer_exception(JavaThread* current))
 875 #ifndef PRODUCT
 876   if (PrintC1Statistics) {
 877     _throw_null_pointer_exception_count++;
 878   }
 879 #endif
 880   SharedRuntime::throw_and_post_jvmti_exception(current, vmSymbols::java_lang_NullPointerException());
 881 JRT_END
 882 
 883 
 884 JRT_ENTRY(void, Runtime1::throw_class_cast_exception(JavaThread* current, oopDesc* object))
 885 #ifndef PRODUCT
 886   if (PrintC1Statistics) {
 887     _throw_class_cast_exception_count++;
 888   }
 889 #endif
 890   ResourceMark rm(current);
 891   char* message = SharedRuntime::generate_class_cast_message(current, object->klass());
 892   SharedRuntime::throw_and_post_jvmti_exception(current, vmSymbols::java_lang_ClassCastException(), message);
 893 JRT_END
 894 
 895 
 896 JRT_ENTRY(void, Runtime1::throw_incompatible_class_change_error(JavaThread* current))
 897 #ifndef PRODUCT
 898   if (PrintC1Statistics) {
 899     _throw_incompatible_class_change_error_count++;
 900   }
 901 #endif
 902   ResourceMark rm(current);
 903   SharedRuntime::throw_and_post_jvmti_exception(current, vmSymbols::java_lang_IncompatibleClassChangeError());
 904 JRT_END
 905 
 906 
 907 JRT_ENTRY(void, Runtime1::throw_illegal_monitor_state_exception(JavaThread* current))
 908   NOT_PRODUCT(_throw_illegal_monitor_state_exception_count++;)
 909   ResourceMark rm(current);
 910   SharedRuntime::throw_and_post_jvmti_exception(current, vmSymbols::java_lang_IllegalMonitorStateException());
 911 JRT_END
 912 
 913 JRT_ENTRY(void, Runtime1::throw_identity_exception(JavaThread* current, oopDesc* object))
 914   NOT_PRODUCT(_throw_identity_exception_count++;)
 915   ResourceMark rm(current);
 916   char* message = SharedRuntime::generate_identity_exception_message(current, object->klass());
 917   SharedRuntime::throw_and_post_jvmti_exception(current, vmSymbols::java_lang_IdentityException(), message);
 918 JRT_END
 919 
 920 JRT_BLOCK_ENTRY(void, Runtime1::monitorenter(JavaThread* current, oopDesc* obj, BasicObjectLock* lock))
 921 #ifndef PRODUCT
 922   if (PrintC1Statistics) {
 923     _monitorenter_slowcase_cnt++;
 924   }
 925 #endif
 926   if (LockingMode == LM_MONITOR) {
 927     lock->set_obj(obj);
 928   }
 929   assert(obj == lock->obj(), "must match");
 930   SharedRuntime::monitor_enter_helper(obj, lock->lock(), current);
 931 JRT_END
 932 
 933 
 934 JRT_LEAF(void, Runtime1::monitorexit(JavaThread* current, BasicObjectLock* lock))
 935   assert(current == JavaThread::current(), "pre-condition");
 936 #ifndef PRODUCT
 937   if (PrintC1Statistics) {
 938     _monitorexit_slowcase_cnt++;
 939   }
 940 #endif
 941   assert(current->last_Java_sp(), "last_Java_sp must be set");
 942   oop obj = lock->obj();
 943   assert(oopDesc::is_oop(obj), "must be null or an object");
 944   SharedRuntime::monitor_exit_helper(obj, lock->lock(), current);
 945 JRT_END
 946 
 947 // Cf. OptoRuntime::deoptimize_caller_frame
 948 JRT_ENTRY(void, Runtime1::deoptimize(JavaThread* current, jint trap_request))
 949   // Called from within the owner thread, so no need for safepoint
 950   RegisterMap reg_map(current,
 951                       RegisterMap::UpdateMap::skip,
 952                       RegisterMap::ProcessFrames::include,
 953                       RegisterMap::WalkContinuation::skip);
 954   frame stub_frame = current->last_frame();
 955   assert(stub_frame.is_runtime_frame(), "Sanity check");
 956   frame caller_frame = stub_frame.sender(&reg_map);
 957   nmethod* nm = caller_frame.cb()->as_nmethod_or_null();
 958   assert(nm != nullptr, "Sanity check");
 959   methodHandle method(current, nm->method());
 960   assert(nm == CodeCache::find_nmethod(caller_frame.pc()), "Should be the same");
 961   Deoptimization::DeoptAction action = Deoptimization::trap_request_action(trap_request);
 962   Deoptimization::DeoptReason reason = Deoptimization::trap_request_reason(trap_request);
 963 
 964   if (action == Deoptimization::Action_make_not_entrant) {
 965     if (nm->make_not_entrant(nmethod::InvalidationReason::C1_DEOPTIMIZE)) {
 966       if (reason == Deoptimization::Reason_tenured) {
 967         MethodData* trap_mdo = Deoptimization::get_method_data(current, method, true /*create_if_missing*/);
 968         if (trap_mdo != nullptr) {
 969           trap_mdo->inc_tenure_traps();
 970         }
 971       }
 972     }
 973   }
 974 
 975   // Deoptimize the caller frame.
 976   Deoptimization::deoptimize_frame(current, caller_frame.id());
 977   // Return to the now deoptimized frame.
 978 JRT_END
 979 
 980 
 981 #ifndef DEOPTIMIZE_WHEN_PATCHING
 982 
 983 static Klass* resolve_field_return_klass(const methodHandle& caller, int bci, TRAPS) {
 984   Bytecode_field field_access(caller, bci);
 985   // This can be static or non-static field access
 986   Bytecodes::Code code       = field_access.code();
 987 
 988   // We must load class, initialize class and resolve the field
 989   fieldDescriptor result; // initialize class if needed
 990   constantPoolHandle constants(THREAD, caller->constants());
 991   LinkResolver::resolve_field_access(result, constants, field_access.index(), caller, Bytecodes::java_code(code), CHECK_NULL);
 992   return result.field_holder();
 993 }
 994 
 995 
 996 //
 997 // This routine patches sites where a class wasn't loaded or
 998 // initialized at the time the code was generated.  It handles
 999 // references to classes, fields and forcing of initialization.  Most
1000 // of the cases are straightforward and involving simply forcing
1001 // resolution of a class, rewriting the instruction stream with the
1002 // needed constant and replacing the call in this function with the
1003 // patched code.  The case for static field is more complicated since
1004 // the thread which is in the process of initializing a class can
1005 // access it's static fields but other threads can't so the code
1006 // either has to deoptimize when this case is detected or execute a
1007 // check that the current thread is the initializing thread.  The
1008 // current
1009 //
1010 // Patches basically look like this:
1011 //
1012 //
1013 // patch_site: jmp patch stub     ;; will be patched
1014 // continue:   ...
1015 //             ...
1016 //             ...
1017 //             ...
1018 //
1019 // They have a stub which looks like this:
1020 //
1021 //             ;; patch body
1022 //             movl <const>, reg           (for class constants)
1023 //        <or> movl [reg1 + <const>], reg  (for field offsets)
1024 //        <or> movl reg, [reg1 + <const>]  (for field offsets)
1025 //             <being_init offset> <bytes to copy> <bytes to skip>
1026 // patch_stub: call Runtime1::patch_code (through a runtime stub)
1027 //             jmp patch_site
1028 //
1029 //
1030 // A normal patch is done by rewriting the patch body, usually a move,
1031 // and then copying it into place over top of the jmp instruction
1032 // being careful to flush caches and doing it in an MP-safe way.  The
1033 // constants following the patch body are used to find various pieces
1034 // of the patch relative to the call site for Runtime1::patch_code.
1035 // The case for getstatic and putstatic is more complicated because
1036 // getstatic and putstatic have special semantics when executing while
1037 // the class is being initialized.  getstatic/putstatic on a class
1038 // which is being_initialized may be executed by the initializing
1039 // thread but other threads have to block when they execute it.  This
1040 // is accomplished in compiled code by executing a test of the current
1041 // thread against the initializing thread of the class.  It's emitted
1042 // as boilerplate in their stub which allows the patched code to be
1043 // executed before it's copied back into the main body of the nmethod.
1044 //
1045 // being_init: get_thread(<tmp reg>
1046 //             cmpl [reg1 + <init_thread_offset>], <tmp reg>
1047 //             jne patch_stub
1048 //             movl [reg1 + <const>], reg  (for field offsets)  <or>
1049 //             movl reg, [reg1 + <const>]  (for field offsets)
1050 //             jmp continue
1051 //             <being_init offset> <bytes to copy> <bytes to skip>
1052 // patch_stub: jmp Runtime1::patch_code (through a runtime stub)
1053 //             jmp patch_site
1054 //
1055 // If the class is being initialized the patch body is rewritten and
1056 // the patch site is rewritten to jump to being_init, instead of
1057 // patch_stub.  Whenever this code is executed it checks the current
1058 // thread against the initializing thread so other threads will enter
1059 // the runtime and end up blocked waiting the class to finish
1060 // initializing inside the calls to resolve_field below.  The
1061 // initializing class will continue on it's way.  Once the class is
1062 // fully_initialized, the intializing_thread of the class becomes
1063 // null, so the next thread to execute this code will fail the test,
1064 // call into patch_code and complete the patching process by copying
1065 // the patch body back into the main part of the nmethod and resume
1066 // executing.
1067 
1068 // NB:
1069 //
1070 // Patchable instruction sequences inherently exhibit race conditions,
1071 // where thread A is patching an instruction at the same time thread B
1072 // is executing it.  The algorithms we use ensure that any observation
1073 // that B can make on any intermediate states during A's patching will
1074 // always end up with a correct outcome.  This is easiest if there are
1075 // few or no intermediate states.  (Some inline caches have two
1076 // related instructions that must be patched in tandem.  For those,
1077 // intermediate states seem to be unavoidable, but we will get the
1078 // right answer from all possible observation orders.)
1079 //
1080 // When patching the entry instruction at the head of a method, or a
1081 // linkable call instruction inside of a method, we try very hard to
1082 // use a patch sequence which executes as a single memory transaction.
1083 // This means, in practice, that when thread A patches an instruction,
1084 // it should patch a 32-bit or 64-bit word that somehow overlaps the
1085 // instruction or is contained in it.  We believe that memory hardware
1086 // will never break up such a word write, if it is naturally aligned
1087 // for the word being written.  We also know that some CPUs work very
1088 // hard to create atomic updates even of naturally unaligned words,
1089 // but we don't want to bet the farm on this always working.
1090 //
1091 // Therefore, if there is any chance of a race condition, we try to
1092 // patch only naturally aligned words, as single, full-word writes.
1093 
1094 JRT_ENTRY(void, Runtime1::patch_code(JavaThread* current, StubId stub_id ))
1095 #ifndef PRODUCT
1096   if (PrintC1Statistics) {
1097     _patch_code_slowcase_cnt++;
1098   }
1099 #endif
1100 
1101   ResourceMark rm(current);
1102   RegisterMap reg_map(current,
1103                       RegisterMap::UpdateMap::skip,
1104                       RegisterMap::ProcessFrames::include,
1105                       RegisterMap::WalkContinuation::skip);
1106   frame runtime_frame = current->last_frame();
1107   frame caller_frame = runtime_frame.sender(&reg_map);
1108 
1109   // last java frame on stack
1110   vframeStream vfst(current, true);
1111   assert(!vfst.at_end(), "Java frame must exist");
1112 
1113   methodHandle caller_method(current, vfst.method());
1114   // Note that caller_method->code() may not be same as caller_code because of OSR's
1115   // Note also that in the presence of inlining it is not guaranteed
1116   // that caller_method() == caller_code->method()
1117 
1118   int bci = vfst.bci();
1119   Bytecodes::Code code = caller_method()->java_code_at(bci);
1120 
1121   // this is used by assertions in the access_field_patching_id
1122   BasicType patch_field_type = T_ILLEGAL;
1123   bool deoptimize_for_volatile = false;
1124   bool deoptimize_for_atomic = false;
1125   bool deoptimize_for_null_free = false;
1126   bool deoptimize_for_flat = false;
1127   bool deoptimize_for_strict_static = false;
1128   int patch_field_offset = -1;
1129   Klass* init_klass = nullptr; // klass needed by load_klass_patching code
1130   Klass* load_klass = nullptr; // klass needed by load_klass_patching code
1131   Handle mirror(current, nullptr); // oop needed by load_mirror_patching code
1132   Handle appendix(current, nullptr); // oop needed by appendix_patching code
1133   bool load_klass_or_mirror_patch_id =
1134     (stub_id == StubId::c1_load_klass_patching_id || stub_id == StubId::c1_load_mirror_patching_id);
1135 
1136   if (stub_id == StubId::c1_access_field_patching_id) {
1137 
1138     Bytecode_field field_access(caller_method, bci);
1139     fieldDescriptor result; // initialize class if needed
1140     Bytecodes::Code code = field_access.code();
1141     constantPoolHandle constants(current, caller_method->constants());
1142     LinkResolver::resolve_field_access(result, constants, field_access.index(), caller_method, Bytecodes::java_code(code), CHECK);
1143     patch_field_offset = result.offset();
1144 
1145     // If we're patching a field which is volatile then at compile it
1146     // must not have been know to be volatile, so the generated code
1147     // isn't correct for a volatile reference.  The nmethod has to be
1148     // deoptimized so that the code can be regenerated correctly.
1149     // This check is only needed for access_field_patching since this
1150     // is the path for patching field offsets.  load_klass is only
1151     // used for patching references to oops which don't need special
1152     // handling in the volatile case.
1153 
1154     deoptimize_for_volatile = result.access_flags().is_volatile();
1155 
1156     // If we are patching a field which should be atomic, then
1157     // the generated code is not correct either, force deoptimizing.
1158     // We need to only cover T_LONG and T_DOUBLE fields, as we can
1159     // break access atomicity only for them.
1160 
1161     // Strictly speaking, the deoptimization on 64-bit platforms
1162     // is unnecessary, and T_LONG stores on 32-bit platforms need
1163     // to be handled by special patching code when AlwaysAtomicAccesses
1164     // becomes product feature. At this point, we are still going
1165     // for the deoptimization for consistency against volatile
1166     // accesses.
1167 
1168     patch_field_type = result.field_type();
1169     deoptimize_for_atomic = (AlwaysAtomicAccesses && (patch_field_type == T_DOUBLE || patch_field_type == T_LONG));
1170 
1171     // The field we are patching is null-free. Deoptimize and regenerate
1172     // the compiled code if we patch a putfield/putstatic because it
1173     // does not contain the required null check.
1174     deoptimize_for_null_free = result.is_null_free_inline_type() && (field_access.is_putfield() || field_access.is_putstatic());
1175 
1176     // The field we are patching is flat. Deoptimize and regenerate
1177     // the compiled code which can't handle the layout of the flat
1178     // field because it was unknown at compile time.
1179     deoptimize_for_flat = result.is_flat();
1180 
1181     // Strict statics may require tracking if their class is not fully initialized.
1182     // For now we can bail out of the compiler and let the interpreter handle it.
1183     deoptimize_for_strict_static = result.is_strict_static_unset();
1184   } else if (load_klass_or_mirror_patch_id) {
1185     Klass* k = nullptr;
1186     switch (code) {
1187       case Bytecodes::_putstatic:
1188       case Bytecodes::_getstatic:
1189         { Klass* klass = resolve_field_return_klass(caller_method, bci, CHECK);
1190           init_klass = klass;
1191           mirror = Handle(current, klass->java_mirror());
1192         }
1193         break;
1194       case Bytecodes::_new:
1195         { Bytecode_new bnew(caller_method(), caller_method->bcp_from(bci));
1196           k = caller_method->constants()->klass_at(bnew.index(), CHECK);
1197         }
1198         break;
1199       case Bytecodes::_multianewarray:
1200         { Bytecode_multianewarray mna(caller_method(), caller_method->bcp_from(bci));
1201           k = caller_method->constants()->klass_at(mna.index(), CHECK);
1202         }
1203         break;
1204       case Bytecodes::_instanceof:
1205         { Bytecode_instanceof io(caller_method(), caller_method->bcp_from(bci));
1206           k = caller_method->constants()->klass_at(io.index(), CHECK);
1207         }
1208         break;
1209       case Bytecodes::_checkcast:
1210         { Bytecode_checkcast cc(caller_method(), caller_method->bcp_from(bci));
1211           k = caller_method->constants()->klass_at(cc.index(), CHECK);
1212         }
1213         break;
1214       case Bytecodes::_anewarray:
1215         { Bytecode_anewarray anew(caller_method(), caller_method->bcp_from(bci));
1216           Klass* ek = caller_method->constants()->klass_at(anew.index(), CHECK);
1217           k = ek->array_klass(CHECK);
1218           if (!k->is_typeArray_klass() && !k->is_refArray_klass() && !k->is_flatArray_klass()) {
1219             k = ObjArrayKlass::cast(k)->klass_with_properties(ArrayKlass::ArrayProperties::DEFAULT, THREAD);
1220           }
1221           if (k->is_flatArray_klass()) {
1222             deoptimize_for_flat = true;
1223           }
1224         }
1225         break;
1226       case Bytecodes::_ldc:
1227       case Bytecodes::_ldc_w:
1228       case Bytecodes::_ldc2_w:
1229         {
1230           Bytecode_loadconstant cc(caller_method, bci);
1231           oop m = cc.resolve_constant(CHECK);
1232           mirror = Handle(current, m);
1233         }
1234         break;
1235       default: fatal("unexpected bytecode for load_klass_or_mirror_patch_id");
1236     }
1237     load_klass = k;
1238   } else if (stub_id == StubId::c1_load_appendix_patching_id) {
1239     Bytecode_invoke bytecode(caller_method, bci);
1240     Bytecodes::Code bc = bytecode.invoke_code();
1241 
1242     CallInfo info;
1243     constantPoolHandle pool(current, caller_method->constants());
1244     int index = bytecode.index();
1245     LinkResolver::resolve_invoke(info, Handle(), pool, index, bc, CHECK);
1246     switch (bc) {
1247       case Bytecodes::_invokehandle: {
1248         ResolvedMethodEntry* entry = pool->cache()->set_method_handle(index, info);
1249         appendix = Handle(current, pool->cache()->appendix_if_resolved(entry));
1250         break;
1251       }
1252       case Bytecodes::_invokedynamic: {
1253         appendix = Handle(current, pool->cache()->set_dynamic_call(info, index));
1254         break;
1255       }
1256       default: fatal("unexpected bytecode for load_appendix_patching_id");
1257     }
1258   } else {
1259     ShouldNotReachHere();
1260   }
1261 
1262   if (deoptimize_for_volatile  ||
1263       deoptimize_for_atomic    ||
1264       deoptimize_for_null_free ||
1265       deoptimize_for_flat      ||
1266       deoptimize_for_strict_static) {
1267     // At compile time we assumed the field wasn't volatile/atomic but after
1268     // loading it turns out it was volatile/atomic so we have to throw the
1269     // compiled code out and let it be regenerated.
1270     if (TracePatching) {
1271       if (deoptimize_for_volatile) {
1272         tty->print_cr("Deoptimizing for patching volatile field reference");
1273       }
1274       if (deoptimize_for_atomic) {
1275         tty->print_cr("Deoptimizing for patching atomic field reference");
1276       }
1277       if (deoptimize_for_null_free) {
1278         tty->print_cr("Deoptimizing for patching null-free field reference");
1279       }
1280       if (deoptimize_for_flat) {
1281         tty->print_cr("Deoptimizing for patching flat field or array reference");
1282       }
1283       if (deoptimize_for_strict_static) {
1284         tty->print_cr("Deoptimizing for patching strict static field reference");
1285       }
1286     }
1287 
1288     // It's possible the nmethod was invalidated in the last
1289     // safepoint, but if it's still alive then make it not_entrant.
1290     nmethod* nm = CodeCache::find_nmethod(caller_frame.pc());
1291     if (nm != nullptr) {
1292       nm->make_not_entrant(nmethod::InvalidationReason::C1_CODEPATCH);
1293     }
1294 
1295     Deoptimization::deoptimize_frame(current, caller_frame.id());
1296 
1297     // Return to the now deoptimized frame.
1298   }
1299 
1300   // Now copy code back
1301 
1302   {
1303     MutexLocker ml_code (current, CodeCache_lock, Mutex::_no_safepoint_check_flag);
1304     //
1305     // Deoptimization may have happened while we waited for the lock.
1306     // In that case we don't bother to do any patching we just return
1307     // and let the deopt happen
1308     if (!caller_is_deopted(current)) {
1309       NativeGeneralJump* jump = nativeGeneralJump_at(caller_frame.pc());
1310       address instr_pc = jump->jump_destination();
1311       NativeInstruction* ni = nativeInstruction_at(instr_pc);
1312       if (ni->is_jump() ) {
1313         // the jump has not been patched yet
1314         // The jump destination is slow case and therefore not part of the stubs
1315         // (stubs are only for StaticCalls)
1316 
1317         // format of buffer
1318         //    ....
1319         //    instr byte 0     <-- copy_buff
1320         //    instr byte 1
1321         //    ..
1322         //    instr byte n-1
1323         //      n
1324         //    ....             <-- call destination
1325 
1326         address stub_location = caller_frame.pc() + PatchingStub::patch_info_offset();
1327         unsigned char* byte_count = (unsigned char*) (stub_location - 1);
1328         unsigned char* byte_skip = (unsigned char*) (stub_location - 2);
1329         unsigned char* being_initialized_entry_offset = (unsigned char*) (stub_location - 3);
1330         address copy_buff = stub_location - *byte_skip - *byte_count;
1331         address being_initialized_entry = stub_location - *being_initialized_entry_offset;
1332         if (TracePatching) {
1333           ttyLocker ttyl;
1334           tty->print_cr(" Patching %s at bci %d at address " INTPTR_FORMAT "  (%s)", Bytecodes::name(code), bci,
1335                         p2i(instr_pc), (stub_id == StubId::c1_access_field_patching_id) ? "field" : "klass");
1336           nmethod* caller_code = CodeCache::find_nmethod(caller_frame.pc());
1337           assert(caller_code != nullptr, "nmethod not found");
1338 
1339           // NOTE we use pc() not original_pc() because we already know they are
1340           // identical otherwise we'd have never entered this block of code
1341 
1342           const ImmutableOopMap* map = caller_code->oop_map_for_return_address(caller_frame.pc());
1343           assert(map != nullptr, "null check");
1344           map->print();
1345           tty->cr();
1346 
1347           Disassembler::decode(copy_buff, copy_buff + *byte_count, tty);
1348         }
1349         // depending on the code below, do_patch says whether to copy the patch body back into the nmethod
1350         bool do_patch = true;
1351         if (stub_id == StubId::c1_access_field_patching_id) {
1352           // The offset may not be correct if the class was not loaded at code generation time.
1353           // Set it now.
1354           NativeMovRegMem* n_move = nativeMovRegMem_at(copy_buff);
1355           assert(n_move->offset() == 0 || (n_move->offset() == 4 && (patch_field_type == T_DOUBLE || patch_field_type == T_LONG)), "illegal offset for type");
1356           assert(patch_field_offset >= 0, "illegal offset");
1357           n_move->add_offset_in_bytes(patch_field_offset);
1358         } else if (load_klass_or_mirror_patch_id) {
1359           // If a getstatic or putstatic is referencing a klass which
1360           // isn't fully initialized, the patch body isn't copied into
1361           // place until initialization is complete.  In this case the
1362           // patch site is setup so that any threads besides the
1363           // initializing thread are forced to come into the VM and
1364           // block.
1365           do_patch = (code != Bytecodes::_getstatic && code != Bytecodes::_putstatic) ||
1366                      InstanceKlass::cast(init_klass)->is_initialized();
1367           NativeGeneralJump* jump = nativeGeneralJump_at(instr_pc);
1368           if (jump->jump_destination() == being_initialized_entry) {
1369             assert(do_patch == true, "initialization must be complete at this point");
1370           } else {
1371             // patch the instruction <move reg, klass>
1372             NativeMovConstReg* n_copy = nativeMovConstReg_at(copy_buff);
1373 
1374             assert(n_copy->data() == 0 ||
1375                    n_copy->data() == (intptr_t)Universe::non_oop_word(),
1376                    "illegal init value");
1377             if (stub_id == StubId::c1_load_klass_patching_id) {
1378               assert(load_klass != nullptr, "klass not set");
1379               n_copy->set_data((intx) (load_klass));
1380             } else {
1381               // Don't need a G1 pre-barrier here since we assert above that data isn't an oop.
1382               n_copy->set_data(cast_from_oop<intx>(mirror()));
1383             }
1384 
1385             if (TracePatching) {
1386               Disassembler::decode(copy_buff, copy_buff + *byte_count, tty);
1387             }
1388           }
1389         } else if (stub_id == StubId::c1_load_appendix_patching_id) {
1390           NativeMovConstReg* n_copy = nativeMovConstReg_at(copy_buff);
1391           assert(n_copy->data() == 0 ||
1392                  n_copy->data() == (intptr_t)Universe::non_oop_word(),
1393                  "illegal init value");
1394           n_copy->set_data(cast_from_oop<intx>(appendix()));
1395 
1396           if (TracePatching) {
1397             Disassembler::decode(copy_buff, copy_buff + *byte_count, tty);
1398           }
1399         } else {
1400           ShouldNotReachHere();
1401         }
1402 
1403         if (do_patch) {
1404           // replace instructions
1405           // first replace the tail, then the call
1406 #ifdef ARM
1407           if((load_klass_or_mirror_patch_id ||
1408               stub_id == StubId::c1_load_appendix_patching_id) &&
1409               nativeMovConstReg_at(copy_buff)->is_pc_relative()) {
1410             nmethod* nm = CodeCache::find_nmethod(instr_pc);
1411             address addr = nullptr;
1412             assert(nm != nullptr, "invalid nmethod_pc");
1413             RelocIterator mds(nm, copy_buff, copy_buff + 1);
1414             while (mds.next()) {
1415               if (mds.type() == relocInfo::oop_type) {
1416                 assert(stub_id == StubId::c1_load_mirror_patching_id ||
1417                        stub_id == StubId::c1_load_appendix_patching_id, "wrong stub id");
1418                 oop_Relocation* r = mds.oop_reloc();
1419                 addr = (address)r->oop_addr();
1420                 break;
1421               } else if (mds.type() == relocInfo::metadata_type) {
1422                 assert(stub_id == StubId::c1_load_klass_patching_id, "wrong stub id");
1423                 metadata_Relocation* r = mds.metadata_reloc();
1424                 addr = (address)r->metadata_addr();
1425                 break;
1426               }
1427             }
1428             assert(addr != nullptr, "metadata relocation must exist");
1429             copy_buff -= *byte_count;
1430             NativeMovConstReg* n_copy2 = nativeMovConstReg_at(copy_buff);
1431             n_copy2->set_pc_relative_offset(addr, instr_pc);
1432           }
1433 #endif
1434 
1435           for (int i = NativeGeneralJump::instruction_size; i < *byte_count; i++) {
1436             address ptr = copy_buff + i;
1437             int a_byte = (*ptr) & 0xFF;
1438             address dst = instr_pc + i;
1439             *(unsigned char*)dst = (unsigned char) a_byte;
1440           }
1441           ICache::invalidate_range(instr_pc, *byte_count);
1442           NativeGeneralJump::replace_mt_safe(instr_pc, copy_buff);
1443 
1444           if (load_klass_or_mirror_patch_id ||
1445               stub_id == StubId::c1_load_appendix_patching_id) {
1446             relocInfo::relocType rtype =
1447               (stub_id == StubId::c1_load_klass_patching_id) ?
1448                                    relocInfo::metadata_type :
1449                                    relocInfo::oop_type;
1450             // update relocInfo to metadata
1451             nmethod* nm = CodeCache::find_nmethod(instr_pc);
1452             assert(nm != nullptr, "invalid nmethod_pc");
1453 
1454             // The old patch site is now a move instruction so update
1455             // the reloc info so that it will get updated during
1456             // future GCs.
1457             RelocIterator iter(nm, (address)instr_pc, (address)(instr_pc + 1));
1458             relocInfo::change_reloc_info_for_address(&iter, (address) instr_pc,
1459                                                      relocInfo::none, rtype);
1460           }
1461 
1462         } else {
1463           ICache::invalidate_range(copy_buff, *byte_count);
1464           NativeGeneralJump::insert_unconditional(instr_pc, being_initialized_entry);
1465         }
1466       }
1467     }
1468     // If we are patching in a non-perm oop, make sure the nmethod
1469     // is on the right list.
1470     nmethod* nm = CodeCache::find_nmethod(caller_frame.pc());
1471     guarantee(nm != nullptr, "only nmethods can contain non-perm oops");
1472 
1473     // Since we've patched some oops in the nmethod,
1474     // (re)register it with the heap.
1475     Universe::heap()->register_nmethod(nm);
1476   }
1477 JRT_END
1478 
1479 #else // DEOPTIMIZE_WHEN_PATCHING
1480 
1481 static bool is_patching_needed(JavaThread* current, StubId stub_id) {
1482   if (stub_id == StubId::c1_load_klass_patching_id ||
1483       stub_id == StubId::c1_load_mirror_patching_id) {
1484     // last java frame on stack
1485     vframeStream vfst(current, true);
1486     assert(!vfst.at_end(), "Java frame must exist");
1487 
1488     methodHandle caller_method(current, vfst.method());
1489     int bci = vfst.bci();
1490     Bytecodes::Code code = caller_method()->java_code_at(bci);
1491 
1492     switch (code) {
1493       case Bytecodes::_new:
1494       case Bytecodes::_anewarray:
1495       case Bytecodes::_multianewarray:
1496       case Bytecodes::_instanceof:
1497       case Bytecodes::_checkcast: {
1498         Bytecode bc(caller_method(), caller_method->bcp_from(bci));
1499         constantTag tag = caller_method->constants()->tag_at(bc.get_index_u2(code));
1500         if (tag.is_unresolved_klass_in_error()) {
1501           return false; // throws resolution error
1502         }
1503         break;
1504       }
1505 
1506       default: break;
1507     }
1508   }
1509   return true;
1510 }
1511 
1512 void Runtime1::patch_code(JavaThread* current, StubId stub_id) {
1513 #ifndef PRODUCT
1514   if (PrintC1Statistics) {
1515     _patch_code_slowcase_cnt++;
1516   }
1517 #endif
1518 
1519   // Enable WXWrite: the function is called by c1 stub as a runtime function
1520   // (see another implementation above).
1521   MACOS_AARCH64_ONLY(ThreadWXEnable wx(WXWrite, current));
1522 
1523   if (TracePatching) {
1524     tty->print_cr("Deoptimizing because patch is needed");
1525   }
1526 
1527   RegisterMap reg_map(current,
1528                       RegisterMap::UpdateMap::skip,
1529                       RegisterMap::ProcessFrames::include,
1530                       RegisterMap::WalkContinuation::skip);
1531 
1532   frame runtime_frame = current->last_frame();
1533   frame caller_frame = runtime_frame.sender(&reg_map);
1534   assert(caller_frame.is_compiled_frame(), "Wrong frame type");
1535 
1536   if (is_patching_needed(current, stub_id)) {
1537     // Make sure the nmethod is invalidated, i.e. made not entrant.
1538     nmethod* nm = CodeCache::find_nmethod(caller_frame.pc());
1539     if (nm != nullptr) {
1540       nm->make_not_entrant(nmethod::InvalidationReason::C1_DEOPTIMIZE_FOR_PATCHING);
1541     }
1542   }
1543 
1544   Deoptimization::deoptimize_frame(current, caller_frame.id());
1545   // Return to the now deoptimized frame.
1546   postcond(caller_is_deopted(current));
1547 }
1548 
1549 #endif // DEOPTIMIZE_WHEN_PATCHING
1550 
1551 // Entry point for compiled code. We want to patch a nmethod.
1552 // We don't do a normal VM transition here because we want to
1553 // know after the patching is complete and any safepoint(s) are taken
1554 // if the calling nmethod was deoptimized. We do this by calling a
1555 // helper method which does the normal VM transition and when it
1556 // completes we can check for deoptimization. This simplifies the
1557 // assembly code in the cpu directories.
1558 //
1559 int Runtime1::move_klass_patching(JavaThread* current) {
1560 //
1561 // NOTE: we are still in Java
1562 //
1563   DEBUG_ONLY(NoHandleMark nhm;)
1564   {
1565     // Enter VM mode
1566     ResetNoHandleMark rnhm;
1567     patch_code(current, StubId::c1_load_klass_patching_id);
1568   }
1569   // Back in JAVA, use no oops DON'T safepoint
1570 
1571   // Return true if calling code is deoptimized
1572 
1573   return caller_is_deopted(current);
1574 }
1575 
1576 int Runtime1::move_mirror_patching(JavaThread* current) {
1577 //
1578 // NOTE: we are still in Java
1579 //
1580   DEBUG_ONLY(NoHandleMark nhm;)
1581   {
1582     // Enter VM mode
1583     ResetNoHandleMark rnhm;
1584     patch_code(current, StubId::c1_load_mirror_patching_id);
1585   }
1586   // Back in JAVA, use no oops DON'T safepoint
1587 
1588   // Return true if calling code is deoptimized
1589 
1590   return caller_is_deopted(current);
1591 }
1592 
1593 int Runtime1::move_appendix_patching(JavaThread* current) {
1594 //
1595 // NOTE: we are still in Java
1596 //
1597   DEBUG_ONLY(NoHandleMark nhm;)
1598   {
1599     // Enter VM mode
1600     ResetNoHandleMark rnhm;
1601     patch_code(current, StubId::c1_load_appendix_patching_id);
1602   }
1603   // Back in JAVA, use no oops DON'T safepoint
1604 
1605   // Return true if calling code is deoptimized
1606 
1607   return caller_is_deopted(current);
1608 }
1609 
1610 // Entry point for compiled code. We want to patch a nmethod.
1611 // We don't do a normal VM transition here because we want to
1612 // know after the patching is complete and any safepoint(s) are taken
1613 // if the calling nmethod was deoptimized. We do this by calling a
1614 // helper method which does the normal VM transition and when it
1615 // completes we can check for deoptimization. This simplifies the
1616 // assembly code in the cpu directories.
1617 //
1618 int Runtime1::access_field_patching(JavaThread* current) {
1619   //
1620   // NOTE: we are still in Java
1621   //
1622   // Handles created in this function will be deleted by the
1623   // HandleMarkCleaner in the transition to the VM.
1624   NoHandleMark nhm;
1625   {
1626     // Enter VM mode
1627     ResetNoHandleMark rnhm;
1628     patch_code(current, StubId::c1_access_field_patching_id);
1629   }
1630   // Back in JAVA, use no oops DON'T safepoint
1631 
1632   // Return true if calling code is deoptimized
1633 
1634   return caller_is_deopted(current);
1635 }
1636 
1637 
1638 JRT_LEAF(void, Runtime1::trace_block_entry(jint block_id))
1639   // for now we just print out the block id
1640   tty->print("%d ", block_id);
1641 JRT_END
1642 
1643 
1644 JRT_LEAF(int, Runtime1::is_instance_of(oopDesc* mirror, oopDesc* obj))
1645   // had to return int instead of bool, otherwise there may be a mismatch
1646   // between the C calling convention and the Java one.
1647   // e.g., on x86, GCC may clear only %al when returning a bool false, but
1648   // JVM takes the whole %eax as the return value, which may misinterpret
1649   // the return value as a boolean true.
1650 
1651   assert(mirror != nullptr, "should null-check on mirror before calling");
1652   Klass* k = java_lang_Class::as_Klass(mirror);
1653   return (k != nullptr && obj != nullptr && obj->is_a(k)) ? 1 : 0;
1654 JRT_END
1655 
1656 JRT_ENTRY(void, Runtime1::predicate_failed_trap(JavaThread* current))
1657   ResourceMark rm;
1658 
1659   RegisterMap reg_map(current,
1660                       RegisterMap::UpdateMap::skip,
1661                       RegisterMap::ProcessFrames::include,
1662                       RegisterMap::WalkContinuation::skip);
1663   frame runtime_frame = current->last_frame();
1664   frame caller_frame = runtime_frame.sender(&reg_map);
1665 
1666   nmethod* nm = CodeCache::find_nmethod(caller_frame.pc());
1667   assert (nm != nullptr, "no more nmethod?");
1668   nm->make_not_entrant(nmethod::InvalidationReason::C1_PREDICATE_FAILED_TRAP);
1669 
1670   methodHandle m(current, nm->method());
1671   MethodData* mdo = m->method_data();
1672 
1673   if (mdo == nullptr && !HAS_PENDING_EXCEPTION) {
1674     // Build an MDO.  Ignore errors like OutOfMemory;
1675     // that simply means we won't have an MDO to update.
1676     Method::build_profiling_method_data(m, THREAD);
1677     if (HAS_PENDING_EXCEPTION) {
1678       // Only metaspace OOM is expected. No Java code executed.
1679       assert((PENDING_EXCEPTION->is_a(vmClasses::OutOfMemoryError_klass())), "we expect only an OOM error here");
1680       CLEAR_PENDING_EXCEPTION;
1681     }
1682     mdo = m->method_data();
1683   }
1684 
1685   if (mdo != nullptr) {
1686     mdo->inc_trap_count(Deoptimization::Reason_none);
1687   }
1688 
1689   if (TracePredicateFailedTraps) {
1690     stringStream ss1, ss2;
1691     vframeStream vfst(current);
1692     Method* inlinee = vfst.method();
1693     inlinee->print_short_name(&ss1);
1694     m->print_short_name(&ss2);
1695     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()));
1696   }
1697 
1698 
1699   Deoptimization::deoptimize_frame(current, caller_frame.id());
1700 
1701 JRT_END
1702 
1703 // Check exception if AbortVMOnException flag set
1704 JRT_LEAF(void, Runtime1::check_abort_on_vm_exception(oopDesc* ex))
1705   ResourceMark rm;
1706   const char* message = nullptr;
1707   if (ex->is_a(vmClasses::Throwable_klass())) {
1708     oop msg = java_lang_Throwable::message(ex);
1709     if (msg != nullptr) {
1710       message = java_lang_String::as_utf8_string(msg);
1711     }
1712   }
1713   Exceptions::debug_check_abort(ex->klass()->external_name(), message);
1714 JRT_END
1715 
1716 #ifndef PRODUCT
1717 void Runtime1::print_statistics() {
1718   tty->print_cr("C1 Runtime statistics:");
1719   tty->print_cr(" _resolve_invoke_virtual_cnt:     %u", SharedRuntime::_resolve_virtual_ctr);
1720   tty->print_cr(" _resolve_invoke_opt_virtual_cnt: %u", SharedRuntime::_resolve_opt_virtual_ctr);
1721   tty->print_cr(" _resolve_invoke_static_cnt:      %u", SharedRuntime::_resolve_static_ctr);
1722   tty->print_cr(" _handle_wrong_method_cnt:        %u", SharedRuntime::_wrong_method_ctr);
1723   tty->print_cr(" _ic_miss_cnt:                    %u", SharedRuntime::_ic_miss_ctr);
1724   tty->print_cr(" _generic_arraycopystub_cnt:      %u", _generic_arraycopystub_cnt);
1725   tty->print_cr(" _byte_arraycopy_cnt:             %u", _byte_arraycopy_stub_cnt);
1726   tty->print_cr(" _short_arraycopy_cnt:            %u", _short_arraycopy_stub_cnt);
1727   tty->print_cr(" _int_arraycopy_cnt:              %u", _int_arraycopy_stub_cnt);
1728   tty->print_cr(" _long_arraycopy_cnt:             %u", _long_arraycopy_stub_cnt);
1729   tty->print_cr(" _oop_arraycopy_cnt:              %u", _oop_arraycopy_stub_cnt);
1730   tty->print_cr(" _arraycopy_slowcase_cnt:         %u", _arraycopy_slowcase_cnt);
1731   tty->print_cr(" _arraycopy_checkcast_cnt:        %u", _arraycopy_checkcast_cnt);
1732   tty->print_cr(" _arraycopy_checkcast_attempt_cnt:%u", _arraycopy_checkcast_attempt_cnt);
1733 
1734   tty->print_cr(" _new_type_array_slowcase_cnt:    %u", _new_type_array_slowcase_cnt);
1735   tty->print_cr(" _new_object_array_slowcase_cnt:  %u", _new_object_array_slowcase_cnt);
1736   tty->print_cr(" _new_null_free_array_slowcase_cnt: %u", _new_null_free_array_slowcase_cnt);
1737   tty->print_cr(" _new_instance_slowcase_cnt:      %u", _new_instance_slowcase_cnt);
1738   tty->print_cr(" _new_multi_array_slowcase_cnt:   %u", _new_multi_array_slowcase_cnt);
1739   tty->print_cr(" _load_flat_array_slowcase_cnt:   %u", _load_flat_array_slowcase_cnt);
1740   tty->print_cr(" _store_flat_array_slowcase_cnt:  %u", _store_flat_array_slowcase_cnt);
1741   tty->print_cr(" _substitutability_check_slowcase_cnt: %u", _substitutability_check_slowcase_cnt);
1742   tty->print_cr(" _buffer_inline_args_slowcase_cnt:%u", _buffer_inline_args_slowcase_cnt);
1743   tty->print_cr(" _buffer_inline_args_no_receiver_slowcase_cnt:%u", _buffer_inline_args_no_receiver_slowcase_cnt);
1744 
1745   tty->print_cr(" _monitorenter_slowcase_cnt:      %u", _monitorenter_slowcase_cnt);
1746   tty->print_cr(" _monitorexit_slowcase_cnt:       %u", _monitorexit_slowcase_cnt);
1747   tty->print_cr(" _patch_code_slowcase_cnt:        %u", _patch_code_slowcase_cnt);
1748 
1749   tty->print_cr(" _throw_range_check_exception_count:            %u:", _throw_range_check_exception_count);
1750   tty->print_cr(" _throw_index_exception_count:                  %u:", _throw_index_exception_count);
1751   tty->print_cr(" _throw_div0_exception_count:                   %u:", _throw_div0_exception_count);
1752   tty->print_cr(" _throw_null_pointer_exception_count:           %u:", _throw_null_pointer_exception_count);
1753   tty->print_cr(" _throw_class_cast_exception_count:             %u:", _throw_class_cast_exception_count);
1754   tty->print_cr(" _throw_incompatible_class_change_error_count:  %u:", _throw_incompatible_class_change_error_count);
1755   tty->print_cr(" _throw_illegal_monitor_state_exception_count:  %u:", _throw_illegal_monitor_state_exception_count);
1756   tty->print_cr(" _throw_identity_exception_count:               %u:", _throw_identity_exception_count);
1757   tty->print_cr(" _throw_count:                                  %u:", _throw_count);
1758 
1759   SharedRuntime::print_ic_miss_histogram();
1760   tty->cr();
1761 }
1762 #endif // PRODUCT