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