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