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