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