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