1 /* 2 * Copyright (c) 1997, 2011, 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 "classfile/systemDictionary.hpp" 27 #include "classfile/vmSymbols.hpp" 28 #include "code/compiledIC.hpp" 29 #include "code/scopeDesc.hpp" 30 #include "code/vtableStubs.hpp" 31 #include "compiler/abstractCompiler.hpp" 32 #include "compiler/compileBroker.hpp" 33 #include "compiler/compilerOracle.hpp" 34 #include "interpreter/interpreter.hpp" 35 #include "interpreter/interpreterRuntime.hpp" 36 #include "memory/gcLocker.inline.hpp" 37 #include "memory/universe.inline.hpp" 38 #include "oops/oop.inline.hpp" 39 #include "prims/forte.hpp" 40 #include "prims/jvmtiExport.hpp" 41 #include "prims/jvmtiRedefineClassesTrace.hpp" 42 #include "prims/methodHandles.hpp" 43 #include "prims/nativeLookup.hpp" 44 #include "runtime/arguments.hpp" 45 #include "runtime/biasedLocking.hpp" 46 #include "runtime/handles.inline.hpp" 47 #include "runtime/init.hpp" 48 #include "runtime/interfaceSupport.hpp" 49 #include "runtime/javaCalls.hpp" 50 #include "runtime/sharedRuntime.hpp" 51 #include "runtime/stubRoutines.hpp" 52 #include "runtime/vframe.hpp" 53 #include "runtime/vframeArray.hpp" 54 #include "utilities/copy.hpp" 55 #include "utilities/dtrace.hpp" 56 #include "utilities/events.hpp" 57 #include "utilities/hashtable.inline.hpp" 58 #include "utilities/xmlstream.hpp" 59 #ifdef TARGET_ARCH_x86 60 # include "nativeInst_x86.hpp" 61 # include "vmreg_x86.inline.hpp" 62 #endif 63 #ifdef TARGET_ARCH_sparc 64 # include "nativeInst_sparc.hpp" 65 # include "vmreg_sparc.inline.hpp" 66 #endif 67 #ifdef TARGET_ARCH_zero 68 # include "nativeInst_zero.hpp" 69 # include "vmreg_zero.inline.hpp" 70 #endif 71 #ifdef TARGET_ARCH_arm 72 # include "nativeInst_arm.hpp" 73 # include "vmreg_arm.inline.hpp" 74 #endif 75 #ifdef TARGET_ARCH_ppc 76 # include "nativeInst_ppc.hpp" 77 # include "vmreg_ppc.inline.hpp" 78 #endif 79 #ifdef COMPILER1 80 #include "c1/c1_Runtime1.hpp" 81 #include "runtime/compilationPolicy.hpp" 82 #endif 83 84 // Shared stub locations 85 RuntimeStub* SharedRuntime::_wrong_method_blob; 86 RuntimeStub* SharedRuntime::_ic_miss_blob; 87 RuntimeStub* SharedRuntime::_resolve_opt_virtual_call_blob; 88 RuntimeStub* SharedRuntime::_resolve_virtual_call_blob; 89 RuntimeStub* SharedRuntime::_resolve_static_call_blob; 90 #ifdef COMPILER1 91 RuntimeStub* SharedRuntime::_resolve_profile_call_blob; 92 RuntimeStub* SharedRuntime::_resolve_static_profile_call_blob; 93 #endif 94 95 DeoptimizationBlob* SharedRuntime::_deopt_blob; 96 RicochetBlob* SharedRuntime::_ricochet_blob; 97 98 SafepointBlob* SharedRuntime::_polling_page_safepoint_handler_blob; 99 SafepointBlob* SharedRuntime::_polling_page_return_handler_blob; 100 101 #ifdef COMPILER2 102 UncommonTrapBlob* SharedRuntime::_uncommon_trap_blob; 103 #endif // COMPILER2 104 105 106 //----------------------------generate_stubs----------------------------------- 107 void SharedRuntime::generate_stubs() { 108 _wrong_method_blob = generate_resolve_blob(CAST_FROM_FN_PTR(address, SharedRuntime::handle_wrong_method), "wrong_method_stub"); 109 _ic_miss_blob = generate_resolve_blob(CAST_FROM_FN_PTR(address, SharedRuntime::handle_wrong_method_ic_miss), "ic_miss_stub"); 110 _resolve_opt_virtual_call_blob = generate_resolve_blob(CAST_FROM_FN_PTR(address, SharedRuntime::resolve_opt_virtual_call_C), "resolve_opt_virtual_call"); 111 _resolve_virtual_call_blob = generate_resolve_blob(CAST_FROM_FN_PTR(address, SharedRuntime::resolve_virtual_call_C), "resolve_virtual_call"); 112 _resolve_static_call_blob = generate_resolve_blob(CAST_FROM_FN_PTR(address, SharedRuntime::resolve_static_call_C), "resolve_static_call"); 113 #ifdef COMPILER1 114 _resolve_profile_call_blob = generate_resolve_blob(CAST_FROM_FN_PTR(address, SharedRuntime::resolve_profile_call_C), "resolve_profile_call"); 115 _resolve_static_profile_call_blob = generate_resolve_blob(CAST_FROM_FN_PTR(address, SharedRuntime::resolve_static_profile_call_C),"resolve_static_profile_call"); 116 #endif 117 118 _polling_page_safepoint_handler_blob = generate_handler_blob(CAST_FROM_FN_PTR(address, SafepointSynchronize::handle_polling_page_exception), false); 119 _polling_page_return_handler_blob = generate_handler_blob(CAST_FROM_FN_PTR(address, SafepointSynchronize::handle_polling_page_exception), true); 120 121 generate_ricochet_blob(); 122 generate_deopt_blob(); 123 124 #ifdef COMPILER2 125 generate_uncommon_trap_blob(); 126 #endif // COMPILER2 127 } 128 129 //----------------------------generate_ricochet_blob--------------------------- 130 void SharedRuntime::generate_ricochet_blob() { 131 if (!EnableInvokeDynamic) return; // leave it as a null 132 133 #ifndef TARGET_ARCH_NYI_6939861 134 // allocate space for the code 135 ResourceMark rm; 136 // setup code generation tools 137 CodeBuffer buffer("ricochet_blob", 256 LP64_ONLY(+ 256), 256); // XXX x86 LP64L: 512, 512 138 MacroAssembler* masm = new MacroAssembler(&buffer); 139 140 int bounce_offset = -1, exception_offset = -1, frame_size_in_words = -1; 141 MethodHandles::RicochetFrame::generate_ricochet_blob(masm, &bounce_offset, &exception_offset, &frame_size_in_words); 142 143 // ------------- 144 // make sure all code is generated 145 masm->flush(); 146 147 // failed to generate? 148 if (bounce_offset < 0 || exception_offset < 0 || frame_size_in_words < 0) { 149 assert(false, "bad ricochet blob"); 150 return; 151 } 152 153 _ricochet_blob = RicochetBlob::create(&buffer, bounce_offset, exception_offset, frame_size_in_words); 154 #endif 155 } 156 157 158 #include <math.h> 159 160 #ifndef USDT2 161 HS_DTRACE_PROBE_DECL4(hotspot, object__alloc, Thread*, char*, int, size_t); 162 HS_DTRACE_PROBE_DECL7(hotspot, method__entry, int, 163 char*, int, char*, int, char*, int); 164 HS_DTRACE_PROBE_DECL7(hotspot, method__return, int, 165 char*, int, char*, int, char*, int); 166 #endif /* !USDT2 */ 167 168 // Implementation of SharedRuntime 169 170 #ifndef PRODUCT 171 // For statistics 172 int SharedRuntime::_ic_miss_ctr = 0; 173 int SharedRuntime::_wrong_method_ctr = 0; 174 int SharedRuntime::_resolve_static_ctr = 0; 175 int SharedRuntime::_resolve_virtual_ctr = 0; 176 int SharedRuntime::_resolve_opt_virtual_ctr = 0; 177 int SharedRuntime::_implicit_null_throws = 0; 178 int SharedRuntime::_implicit_div0_throws = 0; 179 int SharedRuntime::_throw_null_ctr = 0; 180 181 int SharedRuntime::_nof_normal_calls = 0; 182 int SharedRuntime::_nof_optimized_calls = 0; 183 int SharedRuntime::_nof_inlined_calls = 0; 184 int SharedRuntime::_nof_megamorphic_calls = 0; 185 int SharedRuntime::_nof_static_calls = 0; 186 int SharedRuntime::_nof_inlined_static_calls = 0; 187 int SharedRuntime::_nof_interface_calls = 0; 188 int SharedRuntime::_nof_optimized_interface_calls = 0; 189 int SharedRuntime::_nof_inlined_interface_calls = 0; 190 int SharedRuntime::_nof_megamorphic_interface_calls = 0; 191 int SharedRuntime::_nof_removable_exceptions = 0; 192 193 int SharedRuntime::_new_instance_ctr=0; 194 int SharedRuntime::_new_array_ctr=0; 195 int SharedRuntime::_multi1_ctr=0; 196 int SharedRuntime::_multi2_ctr=0; 197 int SharedRuntime::_multi3_ctr=0; 198 int SharedRuntime::_multi4_ctr=0; 199 int SharedRuntime::_multi5_ctr=0; 200 int SharedRuntime::_mon_enter_stub_ctr=0; 201 int SharedRuntime::_mon_exit_stub_ctr=0; 202 int SharedRuntime::_mon_enter_ctr=0; 203 int SharedRuntime::_mon_exit_ctr=0; 204 int SharedRuntime::_partial_subtype_ctr=0; 205 int SharedRuntime::_jbyte_array_copy_ctr=0; 206 int SharedRuntime::_jshort_array_copy_ctr=0; 207 int SharedRuntime::_jint_array_copy_ctr=0; 208 int SharedRuntime::_jlong_array_copy_ctr=0; 209 int SharedRuntime::_oop_array_copy_ctr=0; 210 int SharedRuntime::_checkcast_array_copy_ctr=0; 211 int SharedRuntime::_unsafe_array_copy_ctr=0; 212 int SharedRuntime::_generic_array_copy_ctr=0; 213 int SharedRuntime::_slow_array_copy_ctr=0; 214 int SharedRuntime::_find_handler_ctr=0; 215 int SharedRuntime::_rethrow_ctr=0; 216 217 int SharedRuntime::_ICmiss_index = 0; 218 int SharedRuntime::_ICmiss_count[SharedRuntime::maxICmiss_count]; 219 address SharedRuntime::_ICmiss_at[SharedRuntime::maxICmiss_count]; 220 221 222 void SharedRuntime::trace_ic_miss(address at) { 223 for (int i = 0; i < _ICmiss_index; i++) { 224 if (_ICmiss_at[i] == at) { 225 _ICmiss_count[i]++; 226 return; 227 } 228 } 229 int index = _ICmiss_index++; 230 if (_ICmiss_index >= maxICmiss_count) _ICmiss_index = maxICmiss_count - 1; 231 _ICmiss_at[index] = at; 232 _ICmiss_count[index] = 1; 233 } 234 235 void SharedRuntime::print_ic_miss_histogram() { 236 if (ICMissHistogram) { 237 tty->print_cr ("IC Miss Histogram:"); 238 int tot_misses = 0; 239 for (int i = 0; i < _ICmiss_index; i++) { 240 tty->print_cr(" at: " INTPTR_FORMAT " nof: %d", _ICmiss_at[i], _ICmiss_count[i]); 241 tot_misses += _ICmiss_count[i]; 242 } 243 tty->print_cr ("Total IC misses: %7d", tot_misses); 244 } 245 } 246 #endif // PRODUCT 247 248 #ifndef SERIALGC 249 250 // G1 write-barrier pre: executed before a pointer store. 251 JRT_LEAF(void, SharedRuntime::g1_wb_pre(oopDesc* orig, JavaThread *thread)) 252 if (orig == NULL) { 253 assert(false, "should be optimized out"); 254 return; 255 } 256 assert(orig->is_oop(true /* ignore mark word */), "Error"); 257 // store the original value that was in the field reference 258 thread->satb_mark_queue().enqueue(orig); 259 JRT_END 260 261 // G1 write-barrier post: executed after a pointer store. 262 JRT_LEAF(void, SharedRuntime::g1_wb_post(void* card_addr, JavaThread* thread)) 263 thread->dirty_card_queue().enqueue(card_addr); 264 JRT_END 265 266 #endif // !SERIALGC 267 268 269 JRT_LEAF(jlong, SharedRuntime::lmul(jlong y, jlong x)) 270 return x * y; 271 JRT_END 272 273 274 JRT_LEAF(jlong, SharedRuntime::ldiv(jlong y, jlong x)) 275 if (x == min_jlong && y == CONST64(-1)) { 276 return x; 277 } else { 278 return x / y; 279 } 280 JRT_END 281 282 283 JRT_LEAF(jlong, SharedRuntime::lrem(jlong y, jlong x)) 284 if (x == min_jlong && y == CONST64(-1)) { 285 return 0; 286 } else { 287 return x % y; 288 } 289 JRT_END 290 291 292 const juint float_sign_mask = 0x7FFFFFFF; 293 const juint float_infinity = 0x7F800000; 294 const julong double_sign_mask = CONST64(0x7FFFFFFFFFFFFFFF); 295 const julong double_infinity = CONST64(0x7FF0000000000000); 296 297 JRT_LEAF(jfloat, SharedRuntime::frem(jfloat x, jfloat y)) 298 #ifdef _WIN64 299 // 64-bit Windows on amd64 returns the wrong values for 300 // infinity operands. 301 union { jfloat f; juint i; } xbits, ybits; 302 xbits.f = x; 303 ybits.f = y; 304 // x Mod Infinity == x unless x is infinity 305 if ( ((xbits.i & float_sign_mask) != float_infinity) && 306 ((ybits.i & float_sign_mask) == float_infinity) ) { 307 return x; 308 } 309 #endif 310 return ((jfloat)fmod((double)x,(double)y)); 311 JRT_END 312 313 314 JRT_LEAF(jdouble, SharedRuntime::drem(jdouble x, jdouble y)) 315 #ifdef _WIN64 316 union { jdouble d; julong l; } xbits, ybits; 317 xbits.d = x; 318 ybits.d = y; 319 // x Mod Infinity == x unless x is infinity 320 if ( ((xbits.l & double_sign_mask) != double_infinity) && 321 ((ybits.l & double_sign_mask) == double_infinity) ) { 322 return x; 323 } 324 #endif 325 return ((jdouble)fmod((double)x,(double)y)); 326 JRT_END 327 328 #ifdef __SOFTFP__ 329 JRT_LEAF(jfloat, SharedRuntime::fadd(jfloat x, jfloat y)) 330 return x + y; 331 JRT_END 332 333 JRT_LEAF(jfloat, SharedRuntime::fsub(jfloat x, jfloat y)) 334 return x - y; 335 JRT_END 336 337 JRT_LEAF(jfloat, SharedRuntime::fmul(jfloat x, jfloat y)) 338 return x * y; 339 JRT_END 340 341 JRT_LEAF(jfloat, SharedRuntime::fdiv(jfloat x, jfloat y)) 342 return x / y; 343 JRT_END 344 345 JRT_LEAF(jdouble, SharedRuntime::dadd(jdouble x, jdouble y)) 346 return x + y; 347 JRT_END 348 349 JRT_LEAF(jdouble, SharedRuntime::dsub(jdouble x, jdouble y)) 350 return x - y; 351 JRT_END 352 353 JRT_LEAF(jdouble, SharedRuntime::dmul(jdouble x, jdouble y)) 354 return x * y; 355 JRT_END 356 357 JRT_LEAF(jdouble, SharedRuntime::ddiv(jdouble x, jdouble y)) 358 return x / y; 359 JRT_END 360 361 JRT_LEAF(jfloat, SharedRuntime::i2f(jint x)) 362 return (jfloat)x; 363 JRT_END 364 365 JRT_LEAF(jdouble, SharedRuntime::i2d(jint x)) 366 return (jdouble)x; 367 JRT_END 368 369 JRT_LEAF(jdouble, SharedRuntime::f2d(jfloat x)) 370 return (jdouble)x; 371 JRT_END 372 373 JRT_LEAF(int, SharedRuntime::fcmpl(float x, float y)) 374 return x>y ? 1 : (x==y ? 0 : -1); /* x<y or is_nan*/ 375 JRT_END 376 377 JRT_LEAF(int, SharedRuntime::fcmpg(float x, float y)) 378 return x<y ? -1 : (x==y ? 0 : 1); /* x>y or is_nan */ 379 JRT_END 380 381 JRT_LEAF(int, SharedRuntime::dcmpl(double x, double y)) 382 return x>y ? 1 : (x==y ? 0 : -1); /* x<y or is_nan */ 383 JRT_END 384 385 JRT_LEAF(int, SharedRuntime::dcmpg(double x, double y)) 386 return x<y ? -1 : (x==y ? 0 : 1); /* x>y or is_nan */ 387 JRT_END 388 389 // Functions to return the opposite of the aeabi functions for nan. 390 JRT_LEAF(int, SharedRuntime::unordered_fcmplt(float x, float y)) 391 return (x < y) ? 1 : ((g_isnan(x) || g_isnan(y)) ? 1 : 0); 392 JRT_END 393 394 JRT_LEAF(int, SharedRuntime::unordered_dcmplt(double x, double y)) 395 return (x < y) ? 1 : ((g_isnan(x) || g_isnan(y)) ? 1 : 0); 396 JRT_END 397 398 JRT_LEAF(int, SharedRuntime::unordered_fcmple(float x, float y)) 399 return (x <= y) ? 1 : ((g_isnan(x) || g_isnan(y)) ? 1 : 0); 400 JRT_END 401 402 JRT_LEAF(int, SharedRuntime::unordered_dcmple(double x, double y)) 403 return (x <= y) ? 1 : ((g_isnan(x) || g_isnan(y)) ? 1 : 0); 404 JRT_END 405 406 JRT_LEAF(int, SharedRuntime::unordered_fcmpge(float x, float y)) 407 return (x >= y) ? 1 : ((g_isnan(x) || g_isnan(y)) ? 1 : 0); 408 JRT_END 409 410 JRT_LEAF(int, SharedRuntime::unordered_dcmpge(double x, double y)) 411 return (x >= y) ? 1 : ((g_isnan(x) || g_isnan(y)) ? 1 : 0); 412 JRT_END 413 414 JRT_LEAF(int, SharedRuntime::unordered_fcmpgt(float x, float y)) 415 return (x > y) ? 1 : ((g_isnan(x) || g_isnan(y)) ? 1 : 0); 416 JRT_END 417 418 JRT_LEAF(int, SharedRuntime::unordered_dcmpgt(double x, double y)) 419 return (x > y) ? 1 : ((g_isnan(x) || g_isnan(y)) ? 1 : 0); 420 JRT_END 421 422 // Intrinsics make gcc generate code for these. 423 float SharedRuntime::fneg(float f) { 424 return -f; 425 } 426 427 double SharedRuntime::dneg(double f) { 428 return -f; 429 } 430 431 #endif // __SOFTFP__ 432 433 #if defined(__SOFTFP__) || defined(E500V2) 434 // Intrinsics make gcc generate code for these. 435 double SharedRuntime::dabs(double f) { 436 return (f <= (double)0.0) ? (double)0.0 - f : f; 437 } 438 439 #endif 440 441 #if defined(__SOFTFP__) || defined(PPC) 442 double SharedRuntime::dsqrt(double f) { 443 return sqrt(f); 444 } 445 #endif 446 447 JRT_LEAF(jint, SharedRuntime::f2i(jfloat x)) 448 if (g_isnan(x)) 449 return 0; 450 if (x >= (jfloat) max_jint) 451 return max_jint; 452 if (x <= (jfloat) min_jint) 453 return min_jint; 454 return (jint) x; 455 JRT_END 456 457 458 JRT_LEAF(jlong, SharedRuntime::f2l(jfloat x)) 459 if (g_isnan(x)) 460 return 0; 461 if (x >= (jfloat) max_jlong) 462 return max_jlong; 463 if (x <= (jfloat) min_jlong) 464 return min_jlong; 465 return (jlong) x; 466 JRT_END 467 468 469 JRT_LEAF(jint, SharedRuntime::d2i(jdouble x)) 470 if (g_isnan(x)) 471 return 0; 472 if (x >= (jdouble) max_jint) 473 return max_jint; 474 if (x <= (jdouble) min_jint) 475 return min_jint; 476 return (jint) x; 477 JRT_END 478 479 480 JRT_LEAF(jlong, SharedRuntime::d2l(jdouble x)) 481 if (g_isnan(x)) 482 return 0; 483 if (x >= (jdouble) max_jlong) 484 return max_jlong; 485 if (x <= (jdouble) min_jlong) 486 return min_jlong; 487 return (jlong) x; 488 JRT_END 489 490 491 JRT_LEAF(jfloat, SharedRuntime::d2f(jdouble x)) 492 return (jfloat)x; 493 JRT_END 494 495 496 JRT_LEAF(jfloat, SharedRuntime::l2f(jlong x)) 497 return (jfloat)x; 498 JRT_END 499 500 501 JRT_LEAF(jdouble, SharedRuntime::l2d(jlong x)) 502 return (jdouble)x; 503 JRT_END 504 505 // Exception handling accross interpreter/compiler boundaries 506 // 507 // exception_handler_for_return_address(...) returns the continuation address. 508 // The continuation address is the entry point of the exception handler of the 509 // previous frame depending on the return address. 510 511 address SharedRuntime::raw_exception_handler_for_return_address(JavaThread* thread, address return_address) { 512 assert(frame::verify_return_pc(return_address), err_msg("must be a return address: " INTPTR_FORMAT, return_address)); 513 514 // Reset method handle flag. 515 thread->set_is_method_handle_return(false); 516 517 // The fastest case first 518 CodeBlob* blob = CodeCache::find_blob(return_address); 519 nmethod* nm = (blob != NULL) ? blob->as_nmethod_or_null() : NULL; 520 if (nm != NULL) { 521 // Set flag if return address is a method handle call site. 522 thread->set_is_method_handle_return(nm->is_method_handle_return(return_address)); 523 // native nmethods don't have exception handlers 524 assert(!nm->is_native_method(), "no exception handler"); 525 assert(nm->header_begin() != nm->exception_begin(), "no exception handler"); 526 if (nm->is_deopt_pc(return_address)) { 527 return SharedRuntime::deopt_blob()->unpack_with_exception(); 528 } else { 529 return nm->exception_begin(); 530 } 531 } 532 533 // Entry code 534 if (StubRoutines::returns_to_call_stub(return_address)) { 535 return StubRoutines::catch_exception_entry(); 536 } 537 // Interpreted code 538 if (Interpreter::contains(return_address)) { 539 return Interpreter::rethrow_exception_entry(); 540 } 541 // Ricochet frame unwind code 542 if (SharedRuntime::ricochet_blob() != NULL && SharedRuntime::ricochet_blob()->returns_to_bounce_addr(return_address)) { 543 return SharedRuntime::ricochet_blob()->exception_addr(); 544 } 545 546 guarantee(blob == NULL || !blob->is_runtime_stub(), "caller should have skipped stub"); 547 guarantee(!VtableStubs::contains(return_address), "NULL exceptions in vtables should have been handled already!"); 548 549 #ifndef PRODUCT 550 { ResourceMark rm; 551 tty->print_cr("No exception handler found for exception at " INTPTR_FORMAT " - potential problems:", return_address); 552 tty->print_cr("a) exception happened in (new?) code stubs/buffers that is not handled here"); 553 tty->print_cr("b) other problem"); 554 } 555 #endif // PRODUCT 556 557 ShouldNotReachHere(); 558 return NULL; 559 } 560 561 562 JRT_LEAF(address, SharedRuntime::exception_handler_for_return_address(JavaThread* thread, address return_address)) 563 return raw_exception_handler_for_return_address(thread, return_address); 564 JRT_END 565 566 567 address SharedRuntime::get_poll_stub(address pc) { 568 address stub; 569 // Look up the code blob 570 CodeBlob *cb = CodeCache::find_blob(pc); 571 572 // Should be an nmethod 573 assert( cb && cb->is_nmethod(), "safepoint polling: pc must refer to an nmethod" ); 574 575 // Look up the relocation information 576 assert( ((nmethod*)cb)->is_at_poll_or_poll_return(pc), 577 "safepoint polling: type must be poll" ); 578 579 assert( ((NativeInstruction*)pc)->is_safepoint_poll(), 580 "Only polling locations are used for safepoint"); 581 582 bool at_poll_return = ((nmethod*)cb)->is_at_poll_return(pc); 583 if (at_poll_return) { 584 assert(SharedRuntime::polling_page_return_handler_blob() != NULL, 585 "polling page return stub not created yet"); 586 stub = SharedRuntime::polling_page_return_handler_blob()->entry_point(); 587 } else { 588 assert(SharedRuntime::polling_page_safepoint_handler_blob() != NULL, 589 "polling page safepoint stub not created yet"); 590 stub = SharedRuntime::polling_page_safepoint_handler_blob()->entry_point(); 591 } 592 #ifndef PRODUCT 593 if( TraceSafepoint ) { 594 char buf[256]; 595 jio_snprintf(buf, sizeof(buf), 596 "... found polling page %s exception at pc = " 597 INTPTR_FORMAT ", stub =" INTPTR_FORMAT, 598 at_poll_return ? "return" : "loop", 599 (intptr_t)pc, (intptr_t)stub); 600 tty->print_raw_cr(buf); 601 } 602 #endif // PRODUCT 603 return stub; 604 } 605 606 607 oop SharedRuntime::retrieve_receiver( Symbol* sig, frame caller ) { 608 assert(caller.is_interpreted_frame(), ""); 609 int args_size = ArgumentSizeComputer(sig).size() + 1; 610 assert(args_size <= caller.interpreter_frame_expression_stack_size(), "receiver must be on interpreter stack"); 611 oop result = (oop) *caller.interpreter_frame_tos_at(args_size - 1); 612 assert(Universe::heap()->is_in(result) && result->is_oop(), "receiver must be an oop"); 613 return result; 614 } 615 616 617 void SharedRuntime::throw_and_post_jvmti_exception(JavaThread *thread, Handle h_exception) { 618 if (JvmtiExport::can_post_on_exceptions()) { 619 vframeStream vfst(thread, true); 620 methodHandle method = methodHandle(thread, vfst.method()); 621 address bcp = method()->bcp_from(vfst.bci()); 622 JvmtiExport::post_exception_throw(thread, method(), bcp, h_exception()); 623 } 624 Exceptions::_throw(thread, __FILE__, __LINE__, h_exception); 625 } 626 627 void SharedRuntime::throw_and_post_jvmti_exception(JavaThread *thread, Symbol* name, const char *message) { 628 Handle h_exception = Exceptions::new_exception(thread, name, message); 629 throw_and_post_jvmti_exception(thread, h_exception); 630 } 631 632 // The interpreter code to call this tracing function is only 633 // called/generated when TraceRedefineClasses has the right bits 634 // set. Since obsolete methods are never compiled, we don't have 635 // to modify the compilers to generate calls to this function. 636 // 637 JRT_LEAF(int, SharedRuntime::rc_trace_method_entry( 638 JavaThread* thread, methodOopDesc* method)) 639 assert(RC_TRACE_IN_RANGE(0x00001000, 0x00002000), "wrong call"); 640 641 if (method->is_obsolete()) { 642 // We are calling an obsolete method, but this is not necessarily 643 // an error. Our method could have been redefined just after we 644 // fetched the methodOop from the constant pool. 645 646 // RC_TRACE macro has an embedded ResourceMark 647 RC_TRACE_WITH_THREAD(0x00001000, thread, 648 ("calling obsolete method '%s'", 649 method->name_and_sig_as_C_string())); 650 if (RC_TRACE_ENABLED(0x00002000)) { 651 // this option is provided to debug calls to obsolete methods 652 guarantee(false, "faulting at call to an obsolete method."); 653 } 654 } 655 return 0; 656 JRT_END 657 658 // ret_pc points into caller; we are returning caller's exception handler 659 // for given exception 660 address SharedRuntime::compute_compiled_exc_handler(nmethod* nm, address ret_pc, Handle& exception, 661 bool force_unwind, bool top_frame_only) { 662 assert(nm != NULL, "must exist"); 663 ResourceMark rm; 664 665 ScopeDesc* sd = nm->scope_desc_at(ret_pc); 666 // determine handler bci, if any 667 EXCEPTION_MARK; 668 669 int handler_bci = -1; 670 int scope_depth = 0; 671 if (!force_unwind) { 672 int bci = sd->bci(); 673 bool recursive_exception = false; 674 do { 675 bool skip_scope_increment = false; 676 // exception handler lookup 677 KlassHandle ek (THREAD, exception->klass()); 678 handler_bci = sd->method()->fast_exception_handler_bci_for(ek, bci, THREAD); 679 if (HAS_PENDING_EXCEPTION) { 680 recursive_exception = true; 681 // We threw an exception while trying to find the exception handler. 682 // Transfer the new exception to the exception handle which will 683 // be set into thread local storage, and do another lookup for an 684 // exception handler for this exception, this time starting at the 685 // BCI of the exception handler which caused the exception to be 686 // thrown (bugs 4307310 and 4546590). Set "exception" reference 687 // argument to ensure that the correct exception is thrown (4870175). 688 exception = Handle(THREAD, PENDING_EXCEPTION); 689 CLEAR_PENDING_EXCEPTION; 690 if (handler_bci >= 0) { 691 bci = handler_bci; 692 handler_bci = -1; 693 skip_scope_increment = true; 694 } 695 } 696 else { 697 recursive_exception = false; 698 } 699 if (!top_frame_only && handler_bci < 0 && !skip_scope_increment) { 700 sd = sd->sender(); 701 if (sd != NULL) { 702 bci = sd->bci(); 703 } 704 ++scope_depth; 705 } 706 } while (recursive_exception || (!top_frame_only && handler_bci < 0 && sd != NULL)); 707 } 708 709 // found handling method => lookup exception handler 710 int catch_pco = ret_pc - nm->code_begin(); 711 712 ExceptionHandlerTable table(nm); 713 HandlerTableEntry *t = table.entry_for(catch_pco, handler_bci, scope_depth); 714 if (t == NULL && (nm->is_compiled_by_c1() || handler_bci != -1)) { 715 // Allow abbreviated catch tables. The idea is to allow a method 716 // to materialize its exceptions without committing to the exact 717 // routing of exceptions. In particular this is needed for adding 718 // a synthethic handler to unlock monitors when inlining 719 // synchonized methods since the unlock path isn't represented in 720 // the bytecodes. 721 t = table.entry_for(catch_pco, -1, 0); 722 } 723 724 #ifdef COMPILER1 725 if (t == NULL && nm->is_compiled_by_c1()) { 726 assert(nm->unwind_handler_begin() != NULL, ""); 727 return nm->unwind_handler_begin(); 728 } 729 #endif 730 731 if (t == NULL) { 732 tty->print_cr("MISSING EXCEPTION HANDLER for pc " INTPTR_FORMAT " and handler bci %d", ret_pc, handler_bci); 733 tty->print_cr(" Exception:"); 734 exception->print(); 735 tty->cr(); 736 tty->print_cr(" Compiled exception table :"); 737 table.print(); 738 nm->print_code(); 739 guarantee(false, "missing exception handler"); 740 return NULL; 741 } 742 743 return nm->code_begin() + t->pco(); 744 } 745 746 JRT_ENTRY(void, SharedRuntime::throw_AbstractMethodError(JavaThread* thread)) 747 // These errors occur only at call sites 748 throw_and_post_jvmti_exception(thread, vmSymbols::java_lang_AbstractMethodError()); 749 JRT_END 750 751 JRT_ENTRY(void, SharedRuntime::throw_IncompatibleClassChangeError(JavaThread* thread)) 752 // These errors occur only at call sites 753 throw_and_post_jvmti_exception(thread, vmSymbols::java_lang_IncompatibleClassChangeError(), "vtable stub"); 754 JRT_END 755 756 JRT_ENTRY(void, SharedRuntime::throw_ArithmeticException(JavaThread* thread)) 757 throw_and_post_jvmti_exception(thread, vmSymbols::java_lang_ArithmeticException(), "/ by zero"); 758 JRT_END 759 760 JRT_ENTRY(void, SharedRuntime::throw_NullPointerException(JavaThread* thread)) 761 throw_and_post_jvmti_exception(thread, vmSymbols::java_lang_NullPointerException()); 762 JRT_END 763 764 JRT_ENTRY(void, SharedRuntime::throw_NullPointerException_at_call(JavaThread* thread)) 765 // This entry point is effectively only used for NullPointerExceptions which occur at inline 766 // cache sites (when the callee activation is not yet set up) so we are at a call site 767 throw_and_post_jvmti_exception(thread, vmSymbols::java_lang_NullPointerException()); 768 JRT_END 769 770 JRT_ENTRY(void, SharedRuntime::throw_StackOverflowError(JavaThread* thread)) 771 // We avoid using the normal exception construction in this case because 772 // it performs an upcall to Java, and we're already out of stack space. 773 klassOop k = SystemDictionary::StackOverflowError_klass(); 774 oop exception_oop = instanceKlass::cast(k)->allocate_instance(CHECK); 775 Handle exception (thread, exception_oop); 776 if (StackTraceInThrowable) { 777 java_lang_Throwable::fill_in_stack_trace(exception); 778 } 779 throw_and_post_jvmti_exception(thread, exception); 780 JRT_END 781 782 JRT_ENTRY(void, SharedRuntime::throw_WrongMethodTypeException(JavaThread* thread, oopDesc* required, oopDesc* actual)) 783 assert(thread == JavaThread::current() && required->is_oop() && actual->is_oop(), "bad args"); 784 ResourceMark rm; 785 char* message = SharedRuntime::generate_wrong_method_type_message(thread, required, actual); 786 throw_and_post_jvmti_exception(thread, vmSymbols::java_lang_invoke_WrongMethodTypeException(), message); 787 JRT_END 788 789 address SharedRuntime::continuation_for_implicit_exception(JavaThread* thread, 790 address pc, 791 SharedRuntime::ImplicitExceptionKind exception_kind) 792 { 793 address target_pc = NULL; 794 795 if (Interpreter::contains(pc)) { 796 #ifdef CC_INTERP 797 // C++ interpreter doesn't throw implicit exceptions 798 ShouldNotReachHere(); 799 #else 800 switch (exception_kind) { 801 case IMPLICIT_NULL: return Interpreter::throw_NullPointerException_entry(); 802 case IMPLICIT_DIVIDE_BY_ZERO: return Interpreter::throw_ArithmeticException_entry(); 803 case STACK_OVERFLOW: return Interpreter::throw_StackOverflowError_entry(); 804 default: ShouldNotReachHere(); 805 } 806 #endif // !CC_INTERP 807 } else { 808 switch (exception_kind) { 809 case STACK_OVERFLOW: { 810 // Stack overflow only occurs upon frame setup; the callee is 811 // going to be unwound. Dispatch to a shared runtime stub 812 // which will cause the StackOverflowError to be fabricated 813 // and processed. 814 // For stack overflow in deoptimization blob, cleanup thread. 815 if (thread->deopt_mark() != NULL) { 816 Deoptimization::cleanup_deopt_info(thread, NULL); 817 } 818 return StubRoutines::throw_StackOverflowError_entry(); 819 } 820 821 case IMPLICIT_NULL: { 822 if (VtableStubs::contains(pc)) { 823 // We haven't yet entered the callee frame. Fabricate an 824 // exception and begin dispatching it in the caller. Since 825 // the caller was at a call site, it's safe to destroy all 826 // caller-saved registers, as these entry points do. 827 VtableStub* vt_stub = VtableStubs::stub_containing(pc); 828 829 // If vt_stub is NULL, then return NULL to signal handler to report the SEGV error. 830 if (vt_stub == NULL) return NULL; 831 832 if (vt_stub->is_abstract_method_error(pc)) { 833 assert(!vt_stub->is_vtable_stub(), "should never see AbstractMethodErrors from vtable-type VtableStubs"); 834 return StubRoutines::throw_AbstractMethodError_entry(); 835 } else { 836 return StubRoutines::throw_NullPointerException_at_call_entry(); 837 } 838 } else { 839 CodeBlob* cb = CodeCache::find_blob(pc); 840 841 // If code blob is NULL, then return NULL to signal handler to report the SEGV error. 842 if (cb == NULL) return NULL; 843 844 // Exception happened in CodeCache. Must be either: 845 // 1. Inline-cache check in C2I handler blob, 846 // 2. Inline-cache check in nmethod, or 847 // 3. Implict null exception in nmethod 848 849 if (!cb->is_nmethod()) { 850 guarantee(cb->is_adapter_blob() || cb->is_method_handles_adapter_blob(), 851 "exception happened outside interpreter, nmethods and vtable stubs (1)"); 852 // There is no handler here, so we will simply unwind. 853 return StubRoutines::throw_NullPointerException_at_call_entry(); 854 } 855 856 // Otherwise, it's an nmethod. Consult its exception handlers. 857 nmethod* nm = (nmethod*)cb; 858 if (nm->inlinecache_check_contains(pc)) { 859 // exception happened inside inline-cache check code 860 // => the nmethod is not yet active (i.e., the frame 861 // is not set up yet) => use return address pushed by 862 // caller => don't push another return address 863 return StubRoutines::throw_NullPointerException_at_call_entry(); 864 } 865 866 #ifndef PRODUCT 867 _implicit_null_throws++; 868 #endif 869 target_pc = nm->continuation_for_implicit_exception(pc); 870 // If there's an unexpected fault, target_pc might be NULL, 871 // in which case we want to fall through into the normal 872 // error handling code. 873 } 874 875 break; // fall through 876 } 877 878 879 case IMPLICIT_DIVIDE_BY_ZERO: { 880 nmethod* nm = CodeCache::find_nmethod(pc); 881 guarantee(nm != NULL, "must have containing nmethod for implicit division-by-zero exceptions"); 882 #ifndef PRODUCT 883 _implicit_div0_throws++; 884 #endif 885 target_pc = nm->continuation_for_implicit_exception(pc); 886 // If there's an unexpected fault, target_pc might be NULL, 887 // in which case we want to fall through into the normal 888 // error handling code. 889 break; // fall through 890 } 891 892 default: ShouldNotReachHere(); 893 } 894 895 assert(exception_kind == IMPLICIT_NULL || exception_kind == IMPLICIT_DIVIDE_BY_ZERO, "wrong implicit exception kind"); 896 897 // for AbortVMOnException flag 898 NOT_PRODUCT(Exceptions::debug_check_abort("java.lang.NullPointerException")); 899 if (exception_kind == IMPLICIT_NULL) { 900 Events::log("Implicit null exception at " INTPTR_FORMAT " to " INTPTR_FORMAT, pc, target_pc); 901 } else { 902 Events::log("Implicit division by zero exception at " INTPTR_FORMAT " to " INTPTR_FORMAT, pc, target_pc); 903 } 904 return target_pc; 905 } 906 907 ShouldNotReachHere(); 908 return NULL; 909 } 910 911 912 JNI_ENTRY(void, throw_unsatisfied_link_error(JNIEnv* env, ...)) 913 { 914 THROW(vmSymbols::java_lang_UnsatisfiedLinkError()); 915 } 916 JNI_END 917 918 919 address SharedRuntime::native_method_throw_unsatisfied_link_error_entry() { 920 return CAST_FROM_FN_PTR(address, &throw_unsatisfied_link_error); 921 } 922 923 924 #ifndef PRODUCT 925 JRT_ENTRY(intptr_t, SharedRuntime::trace_bytecode(JavaThread* thread, intptr_t preserve_this_value, intptr_t tos, intptr_t tos2)) 926 const frame f = thread->last_frame(); 927 assert(f.is_interpreted_frame(), "must be an interpreted frame"); 928 #ifndef PRODUCT 929 methodHandle mh(THREAD, f.interpreter_frame_method()); 930 BytecodeTracer::trace(mh, f.interpreter_frame_bcp(), tos, tos2); 931 #endif // !PRODUCT 932 return preserve_this_value; 933 JRT_END 934 #endif // !PRODUCT 935 936 937 JRT_ENTRY(void, SharedRuntime::yield_all(JavaThread* thread, int attempts)) 938 os::yield_all(attempts); 939 JRT_END 940 941 942 JRT_ENTRY_NO_ASYNC(void, SharedRuntime::register_finalizer(JavaThread* thread, oopDesc* obj)) 943 assert(obj->is_oop(), "must be a valid oop"); 944 assert(obj->klass()->klass_part()->has_finalizer(), "shouldn't be here otherwise"); 945 instanceKlass::register_finalizer(instanceOop(obj), CHECK); 946 JRT_END 947 948 949 jlong SharedRuntime::get_java_tid(Thread* thread) { 950 if (thread != NULL) { 951 if (thread->is_Java_thread()) { 952 oop obj = ((JavaThread*)thread)->threadObj(); 953 return (obj == NULL) ? 0 : java_lang_Thread::thread_id(obj); 954 } 955 } 956 return 0; 957 } 958 959 /** 960 * This function ought to be a void function, but cannot be because 961 * it gets turned into a tail-call on sparc, which runs into dtrace bug 962 * 6254741. Once that is fixed we can remove the dummy return value. 963 */ 964 int SharedRuntime::dtrace_object_alloc(oopDesc* o) { 965 return dtrace_object_alloc_base(Thread::current(), o); 966 } 967 968 int SharedRuntime::dtrace_object_alloc_base(Thread* thread, oopDesc* o) { 969 assert(DTraceAllocProbes, "wrong call"); 970 Klass* klass = o->blueprint(); 971 int size = o->size(); 972 Symbol* name = klass->name(); 973 #ifndef USDT2 974 HS_DTRACE_PROBE4(hotspot, object__alloc, get_java_tid(thread), 975 name->bytes(), name->utf8_length(), size * HeapWordSize); 976 #else /* USDT2 */ 977 HOTSPOT_OBJECT_ALLOC( 978 get_java_tid(thread), 979 (char *) name->bytes(), name->utf8_length(), size * HeapWordSize); 980 #endif /* USDT2 */ 981 return 0; 982 } 983 984 JRT_LEAF(int, SharedRuntime::dtrace_method_entry( 985 JavaThread* thread, methodOopDesc* method)) 986 assert(DTraceMethodProbes, "wrong call"); 987 Symbol* kname = method->klass_name(); 988 Symbol* name = method->name(); 989 Symbol* sig = method->signature(); 990 #ifndef USDT2 991 HS_DTRACE_PROBE7(hotspot, method__entry, get_java_tid(thread), 992 kname->bytes(), kname->utf8_length(), 993 name->bytes(), name->utf8_length(), 994 sig->bytes(), sig->utf8_length()); 995 #else /* USDT2 */ 996 HOTSPOT_METHOD_ENTRY( 997 get_java_tid(thread), 998 (char *) kname->bytes(), kname->utf8_length(), 999 (char *) name->bytes(), name->utf8_length(), 1000 (char *) sig->bytes(), sig->utf8_length()); 1001 #endif /* USDT2 */ 1002 return 0; 1003 JRT_END 1004 1005 JRT_LEAF(int, SharedRuntime::dtrace_method_exit( 1006 JavaThread* thread, methodOopDesc* method)) 1007 assert(DTraceMethodProbes, "wrong call"); 1008 Symbol* kname = method->klass_name(); 1009 Symbol* name = method->name(); 1010 Symbol* sig = method->signature(); 1011 #ifndef USDT2 1012 HS_DTRACE_PROBE7(hotspot, method__return, get_java_tid(thread), 1013 kname->bytes(), kname->utf8_length(), 1014 name->bytes(), name->utf8_length(), 1015 sig->bytes(), sig->utf8_length()); 1016 #else /* USDT2 */ 1017 HOTSPOT_METHOD_RETURN( 1018 get_java_tid(thread), 1019 (char *) kname->bytes(), kname->utf8_length(), 1020 (char *) name->bytes(), name->utf8_length(), 1021 (char *) sig->bytes(), sig->utf8_length()); 1022 #endif /* USDT2 */ 1023 return 0; 1024 JRT_END 1025 1026 1027 // Finds receiver, CallInfo (i.e. receiver method), and calling bytecode) 1028 // for a call current in progress, i.e., arguments has been pushed on stack 1029 // put callee has not been invoked yet. Used by: resolve virtual/static, 1030 // vtable updates, etc. Caller frame must be compiled. 1031 Handle SharedRuntime::find_callee_info(JavaThread* thread, Bytecodes::Code& bc, CallInfo& callinfo, TRAPS) { 1032 ResourceMark rm(THREAD); 1033 1034 // last java frame on stack (which includes native call frames) 1035 vframeStream vfst(thread, true); // Do not skip and javaCalls 1036 1037 return find_callee_info_helper(thread, vfst, bc, callinfo, CHECK_(Handle())); 1038 } 1039 1040 1041 // Finds receiver, CallInfo (i.e. receiver method), and calling bytecode 1042 // for a call current in progress, i.e., arguments has been pushed on stack 1043 // but callee has not been invoked yet. Caller frame must be compiled. 1044 Handle SharedRuntime::find_callee_info_helper(JavaThread* thread, 1045 vframeStream& vfst, 1046 Bytecodes::Code& bc, 1047 CallInfo& callinfo, TRAPS) { 1048 Handle receiver; 1049 Handle nullHandle; //create a handy null handle for exception returns 1050 1051 assert(!vfst.at_end(), "Java frame must exist"); 1052 1053 // Find caller and bci from vframe 1054 methodHandle caller (THREAD, vfst.method()); 1055 int bci = vfst.bci(); 1056 1057 // Find bytecode 1058 Bytecode_invoke bytecode(caller, bci); 1059 bc = bytecode.java_code(); 1060 int bytecode_index = bytecode.index(); 1061 1062 // Find receiver for non-static call 1063 if (bc != Bytecodes::_invokestatic) { 1064 // This register map must be update since we need to find the receiver for 1065 // compiled frames. The receiver might be in a register. 1066 RegisterMap reg_map2(thread); 1067 frame stubFrame = thread->last_frame(); 1068 // Caller-frame is a compiled frame 1069 frame callerFrame = stubFrame.sender(®_map2); 1070 1071 methodHandle callee = bytecode.static_target(CHECK_(nullHandle)); 1072 if (callee.is_null()) { 1073 THROW_(vmSymbols::java_lang_NoSuchMethodException(), nullHandle); 1074 } 1075 // Retrieve from a compiled argument list 1076 receiver = Handle(THREAD, callerFrame.retrieve_receiver(®_map2)); 1077 1078 if (receiver.is_null()) { 1079 THROW_(vmSymbols::java_lang_NullPointerException(), nullHandle); 1080 } 1081 } 1082 1083 // Resolve method. This is parameterized by bytecode. 1084 constantPoolHandle constants (THREAD, caller->constants()); 1085 assert (receiver.is_null() || receiver->is_oop(), "wrong receiver"); 1086 LinkResolver::resolve_invoke(callinfo, receiver, constants, bytecode_index, bc, CHECK_(nullHandle)); 1087 1088 #ifdef ASSERT 1089 // Check that the receiver klass is of the right subtype and that it is initialized for virtual calls 1090 if (bc != Bytecodes::_invokestatic && bc != Bytecodes::_invokedynamic) { 1091 assert(receiver.not_null(), "should have thrown exception"); 1092 KlassHandle receiver_klass (THREAD, receiver->klass()); 1093 klassOop rk = constants->klass_ref_at(bytecode_index, CHECK_(nullHandle)); 1094 // klass is already loaded 1095 KlassHandle static_receiver_klass (THREAD, rk); 1096 assert(receiver_klass->is_subtype_of(static_receiver_klass()), "actual receiver must be subclass of static receiver klass"); 1097 if (receiver_klass->oop_is_instance()) { 1098 if (instanceKlass::cast(receiver_klass())->is_not_initialized()) { 1099 tty->print_cr("ERROR: Klass not yet initialized!!"); 1100 receiver_klass.print(); 1101 } 1102 assert (!instanceKlass::cast(receiver_klass())->is_not_initialized(), "receiver_klass must be initialized"); 1103 } 1104 } 1105 #endif 1106 1107 return receiver; 1108 } 1109 1110 methodHandle SharedRuntime::find_callee_method(JavaThread* thread, TRAPS) { 1111 ResourceMark rm(THREAD); 1112 // We need first to check if any Java activations (compiled, interpreted) 1113 // exist on the stack since last JavaCall. If not, we need 1114 // to get the target method from the JavaCall wrapper. 1115 vframeStream vfst(thread, true); // Do not skip any javaCalls 1116 methodHandle callee_method; 1117 if (vfst.at_end()) { 1118 // No Java frames were found on stack since we did the JavaCall. 1119 // Hence the stack can only contain an entry_frame. We need to 1120 // find the target method from the stub frame. 1121 RegisterMap reg_map(thread, false); 1122 frame fr = thread->last_frame(); 1123 assert(fr.is_runtime_frame(), "must be a runtimeStub"); 1124 fr = fr.sender(®_map); 1125 assert(fr.is_entry_frame(), "must be"); 1126 // fr is now pointing to the entry frame. 1127 callee_method = methodHandle(THREAD, fr.entry_frame_call_wrapper()->callee_method()); 1128 assert(fr.entry_frame_call_wrapper()->receiver() == NULL || !callee_method->is_static(), "non-null receiver for static call??"); 1129 } else { 1130 Bytecodes::Code bc; 1131 CallInfo callinfo; 1132 find_callee_info_helper(thread, vfst, bc, callinfo, CHECK_(methodHandle())); 1133 callee_method = callinfo.selected_method(); 1134 } 1135 assert(callee_method()->is_method(), "must be"); 1136 return callee_method; 1137 } 1138 1139 // Resolves a call. 1140 methodHandle SharedRuntime::resolve_helper(JavaThread *thread, 1141 bool is_virtual, 1142 bool is_optimized, TRAPS) { 1143 methodHandle callee_method; 1144 callee_method = resolve_sub_helper(thread, is_virtual, is_optimized, THREAD); 1145 if (JvmtiExport::can_hotswap_or_post_breakpoint()) { 1146 int retry_count = 0; 1147 while (!HAS_PENDING_EXCEPTION && callee_method->is_old() && 1148 callee_method->method_holder() != SystemDictionary::Object_klass()) { 1149 // If has a pending exception then there is no need to re-try to 1150 // resolve this method. 1151 // If the method has been redefined, we need to try again. 1152 // Hack: we have no way to update the vtables of arrays, so don't 1153 // require that java.lang.Object has been updated. 1154 1155 // It is very unlikely that method is redefined more than 100 times 1156 // in the middle of resolve. If it is looping here more than 100 times 1157 // means then there could be a bug here. 1158 guarantee((retry_count++ < 100), 1159 "Could not resolve to latest version of redefined method"); 1160 // method is redefined in the middle of resolve so re-try. 1161 callee_method = resolve_sub_helper(thread, is_virtual, is_optimized, THREAD); 1162 } 1163 } 1164 return callee_method; 1165 } 1166 1167 // Resolves a call. The compilers generate code for calls that go here 1168 // and are patched with the real destination of the call. 1169 methodHandle SharedRuntime::resolve_sub_helper(JavaThread *thread, 1170 bool is_virtual, 1171 bool is_optimized, TRAPS) { 1172 1173 ResourceMark rm(thread); 1174 RegisterMap cbl_map(thread, false); 1175 frame caller_frame = thread->last_frame().sender(&cbl_map); 1176 1177 CodeBlob* caller_cb = caller_frame.cb(); 1178 guarantee(caller_cb != NULL && caller_cb->is_nmethod(), "must be called from nmethod"); 1179 nmethod* caller_nm = caller_cb->as_nmethod_or_null(); 1180 // make sure caller is not getting deoptimized 1181 // and removed before we are done with it. 1182 // CLEANUP - with lazy deopt shouldn't need this lock 1183 nmethodLocker caller_lock(caller_nm); 1184 1185 1186 // determine call info & receiver 1187 // note: a) receiver is NULL for static calls 1188 // b) an exception is thrown if receiver is NULL for non-static calls 1189 CallInfo call_info; 1190 Bytecodes::Code invoke_code = Bytecodes::_illegal; 1191 Handle receiver = find_callee_info(thread, invoke_code, 1192 call_info, CHECK_(methodHandle())); 1193 methodHandle callee_method = call_info.selected_method(); 1194 1195 assert((!is_virtual && invoke_code == Bytecodes::_invokestatic) || 1196 ( is_virtual && invoke_code != Bytecodes::_invokestatic), "inconsistent bytecode"); 1197 1198 bool is_profiled = false; 1199 1200 #ifdef COMPILER1 1201 is_profiled = caller_nm->is_profiled_call(caller_frame.pc()); 1202 if (is_profiled) { 1203 if (callee_method->code_size() > SimpleProfiledCompPolicy::max_inline_size()) { 1204 is_profiled = false; 1205 } 1206 if (is_profiled) { 1207 vframeStream vfst(thread); 1208 methodOop m = vfst.method(); 1209 int bci = vfst.bci(); 1210 1211 CounterData* profile = m->method_data()->bci_to_data(bci)->as_CounterData(); 1212 1213 profile->init_if_first_seen(); 1214 } 1215 } 1216 #endif 1217 1218 1219 #ifndef PRODUCT 1220 // tracing/debugging/statistics 1221 int *addr = (is_optimized) ? (&_resolve_opt_virtual_ctr) : 1222 (is_virtual) ? (&_resolve_virtual_ctr) : 1223 (&_resolve_static_ctr); 1224 Atomic::inc(addr); 1225 1226 if (TraceCallFixup) { 1227 ResourceMark rm(thread); 1228 tty->print("resolving %s%s (%s) call to", 1229 (is_optimized) ? "optimized " : "", (is_virtual) ? "virtual" : "static", 1230 Bytecodes::name(invoke_code)); 1231 callee_method->print_short_name(tty); 1232 tty->print_cr(" code: " INTPTR_FORMAT, callee_method->code()); 1233 } 1234 #endif 1235 1236 // JSR 292 1237 // If the resolved method is a MethodHandle invoke target the call 1238 // site must be a MethodHandle call site. 1239 if (callee_method->is_method_handle_invoke()) { 1240 assert(caller_nm->is_method_handle_return(caller_frame.pc()), "must be MH call site"); 1241 } 1242 1243 // Compute entry points. This might require generation of C2I converter 1244 // frames, so we cannot be holding any locks here. Furthermore, the 1245 // computation of the entry points is independent of patching the call. We 1246 // always return the entry-point, but we only patch the stub if the call has 1247 // not been deoptimized. Return values: For a virtual call this is an 1248 // (cached_oop, destination address) pair. For a static call/optimized 1249 // virtual this is just a destination address. 1250 1251 StaticCallInfo static_call_info; 1252 CompiledICInfo virtual_call_info; 1253 1254 // Make sure the callee nmethod does not get deoptimized and removed before 1255 // we are done patching the code. 1256 nmethod* callee_nm = callee_method->code(); 1257 nmethodLocker nl_callee(callee_nm); 1258 #ifdef ASSERT 1259 address dest_entry_point = callee_nm == NULL ? 0 : callee_nm->entry_point(); // used below 1260 #endif 1261 1262 if (is_virtual) { 1263 assert(receiver.not_null(), "sanity check"); 1264 bool static_bound = call_info.resolved_method()->can_be_statically_bound(); 1265 KlassHandle h_klass(THREAD, receiver->klass()); 1266 CompiledIC::compute_monomorphic_entry(callee_method, h_klass, 1267 is_optimized, static_bound, virtual_call_info, is_profiled, 1268 CHECK_(methodHandle())); 1269 } else { 1270 // static call 1271 CompiledStaticCall::compute_entry(callee_method, static_call_info, is_profiled); 1272 } 1273 1274 // grab lock, check for deoptimization and potentially patch caller 1275 { 1276 MutexLocker ml_patch(CompiledIC_lock); 1277 1278 // Now that we are ready to patch if the methodOop was redefined then 1279 // don't update call site and let the caller retry. 1280 1281 if (!callee_method->is_old()) { 1282 #ifdef ASSERT 1283 // We must not try to patch to jump to an already unloaded method. 1284 if (dest_entry_point != 0) { 1285 assert(CodeCache::find_blob(dest_entry_point) != NULL, 1286 "should not unload nmethod while locked"); 1287 } 1288 #endif 1289 if (is_virtual) { 1290 CompiledIC* inline_cache = CompiledIC_before(caller_frame.pc()); 1291 if (inline_cache->is_clean()) { 1292 inline_cache->set_to_monomorphic(virtual_call_info); 1293 #ifdef COMPILER1 1294 if (is_profiled && !is_optimized) { 1295 assert(invoke_code == Bytecodes::_invokevirtual || invoke_code == Bytecodes::_invokeinterface, "unexpected call"); 1296 vframeStream vfst(thread); 1297 methodOop m = vfst.method(); 1298 int bci = vfst.bci(); 1299 1300 VirtualCallData* profile = m->method_data()->bci_to_data(bci)->as_VirtualCallData(); 1301 1302 profile->new_receiver(receiver); 1303 } 1304 #endif 1305 } 1306 } else { 1307 CompiledStaticCall* ssc = compiledStaticCall_before(caller_frame.pc()); 1308 if (ssc->is_clean()) ssc->set(static_call_info); 1309 } 1310 } 1311 1312 } // unlock CompiledIC_lock 1313 1314 return callee_method; 1315 } 1316 1317 1318 // Inline caches exist only in compiled code 1319 JRT_BLOCK_ENTRY(address, SharedRuntime::handle_wrong_method_ic_miss(JavaThread* thread)) 1320 #ifdef ASSERT 1321 RegisterMap reg_map(thread, false); 1322 frame stub_frame = thread->last_frame(); 1323 assert(stub_frame.is_runtime_frame(), "sanity check"); 1324 frame caller_frame = stub_frame.sender(®_map); 1325 assert(!caller_frame.is_interpreted_frame() && !caller_frame.is_entry_frame(), "unexpected frame"); 1326 assert(!caller_frame.is_ricochet_frame(), "unexpected frame"); 1327 #endif /* ASSERT */ 1328 1329 methodHandle callee_method; 1330 JRT_BLOCK 1331 callee_method = SharedRuntime::handle_ic_miss_helper(thread, CHECK_NULL); 1332 // Return methodOop through TLS 1333 thread->set_vm_result(callee_method()); 1334 JRT_BLOCK_END 1335 // return compiled code entry point after potential safepoints 1336 assert(callee_method->verified_code_entry() != NULL, " Jump to zero!"); 1337 return callee_method->verified_code_entry(); 1338 JRT_END 1339 1340 1341 // Handle call site that has been made non-entrant 1342 JRT_BLOCK_ENTRY(address, SharedRuntime::handle_wrong_method(JavaThread* thread)) 1343 // 6243940 We might end up in here if the callee is deoptimized 1344 // as we race to call it. We don't want to take a safepoint if 1345 // the caller was interpreted because the caller frame will look 1346 // interpreted to the stack walkers and arguments are now 1347 // "compiled" so it is much better to make this transition 1348 // invisible to the stack walking code. The i2c path will 1349 // place the callee method in the callee_target. It is stashed 1350 // there because if we try and find the callee by normal means a 1351 // safepoint is possible and have trouble gc'ing the compiled args. 1352 RegisterMap reg_map(thread, false); 1353 frame stub_frame = thread->last_frame(); 1354 assert(stub_frame.is_runtime_frame(), "sanity check"); 1355 frame caller_frame = stub_frame.sender(®_map); 1356 1357 // MethodHandle invokes don't have a CompiledIC and should always 1358 // simply redispatch to the callee_target. 1359 address sender_pc = caller_frame.pc(); 1360 CodeBlob* sender_cb = caller_frame.cb(); 1361 nmethod* sender_nm = sender_cb->as_nmethod_or_null(); 1362 bool is_mh_invoke_via_adapter = false; // Direct c2c call or via adapter? 1363 if (sender_nm != NULL && sender_nm->is_method_handle_return(sender_pc)) { 1364 // If the callee_target is set, then we have come here via an i2c 1365 // adapter. 1366 methodOop callee = thread->callee_target(); 1367 if (callee != NULL) { 1368 assert(callee->is_method(), "sanity"); 1369 is_mh_invoke_via_adapter = true; 1370 } 1371 } 1372 1373 if (caller_frame.is_interpreted_frame() || 1374 caller_frame.is_entry_frame() || 1375 caller_frame.is_ricochet_frame() || 1376 is_mh_invoke_via_adapter) { 1377 methodOop callee = thread->callee_target(); 1378 guarantee(callee != NULL && callee->is_method(), "bad handshake"); 1379 thread->set_vm_result(callee); 1380 thread->set_callee_target(NULL); 1381 return callee->get_c2i_entry(); 1382 } 1383 1384 // Must be compiled to compiled path which is safe to stackwalk 1385 methodHandle callee_method; 1386 JRT_BLOCK 1387 // Force resolving of caller (if we called from compiled frame) 1388 callee_method = SharedRuntime::reresolve_call_site(thread, CHECK_NULL); 1389 thread->set_vm_result(callee_method()); 1390 JRT_BLOCK_END 1391 // return compiled code entry point after potential safepoints 1392 assert(callee_method->verified_code_entry() != NULL, " Jump to zero!"); 1393 return callee_method->verified_code_entry(); 1394 JRT_END 1395 1396 1397 // resolve a static call and patch code 1398 JRT_BLOCK_ENTRY(address, SharedRuntime::resolve_static_call_C(JavaThread *thread )) 1399 methodHandle callee_method; 1400 JRT_BLOCK 1401 callee_method = SharedRuntime::resolve_helper(thread, false, false, CHECK_NULL); 1402 thread->set_vm_result(callee_method()); 1403 JRT_BLOCK_END 1404 // return compiled code entry point after potential safepoints 1405 assert(callee_method->verified_code_entry() != NULL, " Jump to zero!"); 1406 return callee_method->verified_code_entry(); 1407 JRT_END 1408 1409 1410 // resolve virtual call and update inline cache to monomorphic 1411 JRT_BLOCK_ENTRY(address, SharedRuntime::resolve_virtual_call_C(JavaThread *thread )) 1412 methodHandle callee_method; 1413 JRT_BLOCK 1414 callee_method = SharedRuntime::resolve_helper(thread, true, false, CHECK_NULL); 1415 thread->set_vm_result(callee_method()); 1416 JRT_BLOCK_END 1417 // return compiled code entry point after potential safepoints 1418 assert(callee_method->verified_code_entry() != NULL, " Jump to zero!"); 1419 return callee_method->verified_code_entry(); 1420 JRT_END 1421 1422 1423 // Resolve a virtual call that can be statically bound (e.g., always 1424 // monomorphic, so it has no inline cache). Patch code to resolved target. 1425 JRT_BLOCK_ENTRY(address, SharedRuntime::resolve_opt_virtual_call_C(JavaThread *thread)) 1426 methodHandle callee_method; 1427 JRT_BLOCK 1428 callee_method = SharedRuntime::resolve_helper(thread, true, true, CHECK_NULL); 1429 thread->set_vm_result(callee_method()); 1430 JRT_BLOCK_END 1431 // return compiled code entry point after potential safepoints 1432 assert(callee_method->verified_code_entry() != NULL, " Jump to zero!"); 1433 return callee_method->verified_code_entry(); 1434 JRT_END 1435 1436 #ifdef COMPILER1 1437 methodHandle SharedRuntime::resolve_profile_helper(JavaThread *thread, TRAPS) { 1438 ResourceMark rm(thread); 1439 RegisterMap cbl_map(thread, false); 1440 frame caller_frame = thread->last_frame().sender(&cbl_map); 1441 1442 CodeBlob* cb = caller_frame.cb(); 1443 guarantee(cb != NULL && cb->is_nmethod(), "must be called from nmethod"); 1444 nmethodLocker caller_lock((nmethod*)cb); 1445 CallInfo call_info; 1446 Bytecodes::Code invoke_code = Bytecodes::_illegal; 1447 Handle receiver = find_callee_info(thread, invoke_code, 1448 call_info, CHECK_(methodHandle())); 1449 1450 return call_info.selected_method(); 1451 } 1452 1453 JRT_BLOCK_ENTRY(address, SharedRuntime::resolve_profile_call_C(JavaThread *thread )) 1454 methodHandle callee_method; 1455 JRT_BLOCK 1456 { 1457 callee_method = resolve_profile_helper(thread, CHECK_NULL); 1458 1459 bool fix_call = SimpleProfiledCompPolicy::profile_overflow_event(thread, CHECK_NULL); 1460 1461 if (fix_call) { 1462 ResourceMark rm; 1463 RegisterMap map(thread, false); 1464 frame fr = thread->last_frame().sender(&map); 1465 1466 MutexLocker ml_patch(CompiledIC_lock); 1467 1468 CompiledIC* inline_cache = CompiledIC_before(fr.pc()); 1469 1470 inline_cache->drop_profiling(); 1471 } 1472 thread->set_vm_result(callee_method()); 1473 } 1474 JRT_BLOCK_END 1475 // return compiled code entry point after potential safepoints 1476 assert(callee_method->verified_code_entry() != NULL, " Jump to zero!"); 1477 return callee_method->verified_code_entry(); 1478 JRT_END 1479 1480 JRT_BLOCK_ENTRY(address, SharedRuntime::resolve_static_profile_call_C(JavaThread *thread )) 1481 methodHandle callee_method; 1482 JRT_BLOCK 1483 { 1484 callee_method = resolve_profile_helper(thread, CHECK_NULL); 1485 1486 bool fix_call = SimpleProfiledCompPolicy::profile_overflow_event(thread, CHECK_NULL); 1487 1488 if (fix_call) { 1489 1490 RegisterMap map(thread, false); 1491 frame fr = thread->last_frame().sender(&map); 1492 1493 MutexLocker ml_patch(CompiledIC_lock); 1494 CompiledStaticCall* ssc = compiledStaticCall_before(fr.pc()); 1495 ssc->drop_profiling(); 1496 } 1497 thread->set_vm_result(callee_method()); 1498 } 1499 JRT_BLOCK_END 1500 // return compiled code entry point after potential safepoints 1501 assert(callee_method->verified_code_entry() != NULL, " Jump to zero!"); 1502 return callee_method->verified_code_entry(); 1503 JRT_END 1504 #endif 1505 1506 methodHandle SharedRuntime::handle_ic_miss_helper(JavaThread *thread, TRAPS) { 1507 ResourceMark rm(thread); 1508 CallInfo call_info; 1509 Bytecodes::Code bc; 1510 1511 // receiver is NULL for static calls. An exception is thrown for NULL 1512 // receivers for non-static calls 1513 Handle receiver = find_callee_info(thread, bc, call_info, 1514 CHECK_(methodHandle())); 1515 // Compiler1 can produce virtual call sites that can actually be statically bound 1516 // If we fell thru to below we would think that the site was going megamorphic 1517 // when in fact the site can never miss. Worse because we'd think it was megamorphic 1518 // we'd try and do a vtable dispatch however methods that can be statically bound 1519 // don't have vtable entries (vtable_index < 0) and we'd blow up. So we force a 1520 // reresolution of the call site (as if we did a handle_wrong_method and not an 1521 // plain ic_miss) and the site will be converted to an optimized virtual call site 1522 // never to miss again. I don't believe C2 will produce code like this but if it 1523 // did this would still be the correct thing to do for it too, hence no ifdef. 1524 // 1525 if (call_info.resolved_method()->can_be_statically_bound()) { 1526 methodHandle callee_method = SharedRuntime::reresolve_call_site(thread, CHECK_(methodHandle())); 1527 if (TraceCallFixup) { 1528 RegisterMap reg_map(thread, false); 1529 frame caller_frame = thread->last_frame().sender(®_map); 1530 ResourceMark rm(thread); 1531 tty->print("converting IC miss to reresolve (%s) call to", Bytecodes::name(bc)); 1532 callee_method->print_short_name(tty); 1533 tty->print_cr(" from pc: " INTPTR_FORMAT, caller_frame.pc()); 1534 tty->print_cr(" code: " INTPTR_FORMAT, callee_method->code()); 1535 } 1536 return callee_method; 1537 } 1538 1539 methodHandle callee_method = call_info.selected_method(); 1540 1541 bool should_be_mono = false; 1542 1543 #ifndef PRODUCT 1544 Atomic::inc(&_ic_miss_ctr); 1545 1546 // Statistics & Tracing 1547 if (TraceCallFixup) { 1548 ResourceMark rm(thread); 1549 tty->print("IC miss (%s) call to", Bytecodes::name(bc)); 1550 callee_method->print_short_name(tty); 1551 tty->print_cr(" code: " INTPTR_FORMAT, callee_method->code()); 1552 } 1553 1554 if (ICMissHistogram) { 1555 MutexLocker m(VMStatistic_lock); 1556 RegisterMap reg_map(thread, false); 1557 frame f = thread->last_frame().real_sender(®_map);// skip runtime stub 1558 // produce statistics under the lock 1559 trace_ic_miss(f.pc()); 1560 } 1561 #endif 1562 1563 // install an event collector so that when a vtable stub is created the 1564 // profiler can be notified via a DYNAMIC_CODE_GENERATED event. The 1565 // event can't be posted when the stub is created as locks are held 1566 // - instead the event will be deferred until the event collector goes 1567 // out of scope. 1568 JvmtiDynamicCodeEventCollector event_collector; 1569 1570 // Update inline cache to megamorphic. Skip update if caller has been 1571 // made non-entrant or we are called from interpreted. 1572 { MutexLocker ml_patch (CompiledIC_lock); 1573 RegisterMap reg_map(thread, false); 1574 frame caller_frame = thread->last_frame().sender(®_map); 1575 CodeBlob* cb = caller_frame.cb(); 1576 if (cb->is_nmethod() && ((nmethod*)cb)->is_in_use()) { 1577 // Not a non-entrant nmethod, so find inline_cache 1578 CompiledIC* inline_cache = CompiledIC_before(caller_frame.pc()); 1579 bool should_be_mono = false; 1580 if (inline_cache->is_optimized()) { 1581 if (TraceCallFixup) { 1582 ResourceMark rm(thread); 1583 tty->print("OPTIMIZED IC miss (%s) call to", Bytecodes::name(bc)); 1584 callee_method->print_short_name(tty); 1585 tty->print_cr(" code: " INTPTR_FORMAT, callee_method->code()); 1586 } 1587 should_be_mono = true; 1588 } else { 1589 compiledICHolderOop ic_oop = (compiledICHolderOop) inline_cache->cached_oop(); 1590 if ( ic_oop != NULL && ic_oop->is_compiledICHolder()) { 1591 1592 if (receiver()->klass() == ic_oop->holder_klass()) { 1593 // This isn't a real miss. We must have seen that compiled code 1594 // is now available and we want the call site converted to a 1595 // monomorphic compiled call site. 1596 // We can't assert for callee_method->code() != NULL because it 1597 // could have been deoptimized in the meantime 1598 if (TraceCallFixup) { 1599 ResourceMark rm(thread); 1600 tty->print("FALSE IC miss (%s) converting to compiled call to", Bytecodes::name(bc)); 1601 callee_method->print_short_name(tty); 1602 tty->print_cr(" code: " INTPTR_FORMAT, callee_method->code()); 1603 } 1604 should_be_mono = true; 1605 } 1606 } 1607 } 1608 1609 if (should_be_mono) { 1610 1611 bool is_profiled = false; 1612 #ifdef COMPILER1 1613 is_profiled = ((nmethod*)cb)->is_profiled_call(caller_frame.pc()); 1614 #endif 1615 // We have a path that was monomorphic but was going interpreted 1616 // and now we have (or had) a compiled entry. We correct the IC 1617 // by using a new icBuffer. 1618 CompiledICInfo info; 1619 KlassHandle receiver_klass(THREAD, receiver()->klass()); 1620 inline_cache->compute_monomorphic_entry(callee_method, 1621 receiver_klass, 1622 inline_cache->is_optimized(), 1623 false, 1624 info, is_profiled, CHECK_(methodHandle())); 1625 #ifdef COMPILER1 1626 if (is_profiled) { 1627 vframeStream vfst(thread); 1628 methodOop m = vfst.method(); 1629 int bci = vfst.bci(); 1630 1631 CounterData* profile = m->method_data()->bci_to_data(bci)->as_CounterData(); 1632 1633 profile->init_if_first_seen(); 1634 } 1635 #endif 1636 1637 inline_cache->set_to_monomorphic(info); 1638 } else if (!inline_cache->is_megamorphic() && !inline_cache->is_clean()) { 1639 // Change to megamorphic 1640 inline_cache->set_to_megamorphic(&call_info, bc, CHECK_(methodHandle())); 1641 #ifdef COMPILER1 1642 if (((nmethod*)cb)->is_profiled_call(caller_frame.pc())) { 1643 vframeStream vfst(thread); 1644 methodOop m = vfst.method(); 1645 int bci = vfst.bci(); 1646 1647 VirtualCallData* profile = m->method_data()->bci_to_data(bci)->as_VirtualCallData(); 1648 1649 profile->new_receiver(receiver); 1650 } 1651 #endif 1652 1653 } else { 1654 // Either clean or megamorphic 1655 } 1656 } 1657 } // Release CompiledIC_lock 1658 1659 return callee_method; 1660 } 1661 1662 // 1663 // Resets a call-site in compiled code so it will get resolved again. 1664 // This routines handles both virtual call sites, optimized virtual call 1665 // sites, and static call sites. Typically used to change a call sites 1666 // destination from compiled to interpreted. 1667 // 1668 methodHandle SharedRuntime::reresolve_call_site(JavaThread *thread, TRAPS) { 1669 ResourceMark rm(thread); 1670 RegisterMap reg_map(thread, false); 1671 frame stub_frame = thread->last_frame(); 1672 assert(stub_frame.is_runtime_frame(), "must be a runtimeStub"); 1673 frame caller = stub_frame.sender(®_map); 1674 1675 // Do nothing if the frame isn't a live compiled frame. 1676 // nmethod could be deoptimized by the time we get here 1677 // so no update to the caller is needed. 1678 1679 if (caller.is_compiled_frame() && !caller.is_deoptimized_frame()) { 1680 1681 address pc = caller.pc(); 1682 Events::log("update call-site at pc " INTPTR_FORMAT, pc); 1683 1684 // Default call_addr is the location of the "basic" call. 1685 // Determine the address of the call we a reresolving. With 1686 // Inline Caches we will always find a recognizable call. 1687 // With Inline Caches disabled we may or may not find a 1688 // recognizable call. We will always find a call for static 1689 // calls and for optimized virtual calls. For vanilla virtual 1690 // calls it depends on the state of the UseInlineCaches switch. 1691 // 1692 // With Inline Caches disabled we can get here for a virtual call 1693 // for two reasons: 1694 // 1 - calling an abstract method. The vtable for abstract methods 1695 // will run us thru handle_wrong_method and we will eventually 1696 // end up in the interpreter to throw the ame. 1697 // 2 - a racing deoptimization. We could be doing a vanilla vtable 1698 // call and between the time we fetch the entry address and 1699 // we jump to it the target gets deoptimized. Similar to 1 1700 // we will wind up in the interprter (thru a c2i with c2). 1701 // 1702 address call_addr = NULL; 1703 { 1704 // Get call instruction under lock because another thread may be 1705 // busy patching it. 1706 MutexLockerEx ml_patch(Patching_lock, Mutex::_no_safepoint_check_flag); 1707 // Location of call instruction 1708 if (NativeCall::is_call_before(pc)) { 1709 NativeCall *ncall = nativeCall_before(pc); 1710 call_addr = ncall->instruction_address(); 1711 } 1712 } 1713 1714 // Check for static or virtual call 1715 bool is_static_call = false; 1716 nmethod* caller_nm = CodeCache::find_nmethod(pc); 1717 // Make sure nmethod doesn't get deoptimized and removed until 1718 // this is done with it. 1719 // CLEANUP - with lazy deopt shouldn't need this lock 1720 nmethodLocker nmlock(caller_nm); 1721 1722 if (call_addr != NULL) { 1723 RelocIterator iter(caller_nm, call_addr, call_addr+1); 1724 int ret = iter.next(); // Get item 1725 if (ret) { 1726 assert(iter.addr() == call_addr, "must find call"); 1727 if (iter.type() == relocInfo::static_call_type) { 1728 is_static_call = true; 1729 } else { 1730 assert(iter.type() == relocInfo::virtual_call_type || 1731 iter.type() == relocInfo::opt_virtual_call_type 1732 , "unexpected relocInfo. type"); 1733 } 1734 } else { 1735 assert(!UseInlineCaches, "relocation info. must exist for this address"); 1736 } 1737 1738 // Cleaning the inline cache will force a new resolve. This is more robust 1739 // than directly setting it to the new destination, since resolving of calls 1740 // is always done through the same code path. (experience shows that it 1741 // leads to very hard to track down bugs, if an inline cache gets updated 1742 // to a wrong method). It should not be performance critical, since the 1743 // resolve is only done once. 1744 1745 MutexLocker ml(CompiledIC_lock); 1746 // 1747 // We do not patch the call site if the nmethod has been made non-entrant 1748 // as it is a waste of time 1749 // 1750 if (caller_nm->is_in_use()) { 1751 if (is_static_call) { 1752 CompiledStaticCall* ssc= compiledStaticCall_at(call_addr); 1753 ssc->set_to_clean(); 1754 } else { 1755 // compiled, dispatched call (which used to call an interpreted method) 1756 CompiledIC* inline_cache = CompiledIC_at(call_addr); 1757 inline_cache->set_to_clean(); 1758 } 1759 } 1760 } 1761 1762 } 1763 1764 methodHandle callee_method = find_callee_method(thread, CHECK_(methodHandle())); 1765 1766 1767 #ifndef PRODUCT 1768 Atomic::inc(&_wrong_method_ctr); 1769 1770 if (TraceCallFixup) { 1771 ResourceMark rm(thread); 1772 tty->print("handle_wrong_method reresolving call to"); 1773 callee_method->print_short_name(tty); 1774 tty->print_cr(" code: " INTPTR_FORMAT, callee_method->code()); 1775 } 1776 #endif 1777 1778 return callee_method; 1779 } 1780 1781 // --------------------------------------------------------------------------- 1782 // We are calling the interpreter via a c2i. Normally this would mean that 1783 // we were called by a compiled method. However we could have lost a race 1784 // where we went int -> i2c -> c2i and so the caller could in fact be 1785 // interpreted. If the caller is compiled we attempt to patch the caller 1786 // so he no longer calls into the interpreter. 1787 IRT_LEAF(void, SharedRuntime::fixup_callers_callsite(methodOopDesc* method, address caller_pc)) 1788 methodOop moop(method); 1789 1790 address entry_point = moop->from_compiled_entry(); 1791 1792 // It's possible that deoptimization can occur at a call site which hasn't 1793 // been resolved yet, in which case this function will be called from 1794 // an nmethod that has been patched for deopt and we can ignore the 1795 // request for a fixup. 1796 // Also it is possible that we lost a race in that from_compiled_entry 1797 // is now back to the i2c in that case we don't need to patch and if 1798 // we did we'd leap into space because the callsite needs to use 1799 // "to interpreter" stub in order to load up the methodOop. Don't 1800 // ask me how I know this... 1801 1802 CodeBlob* cb = CodeCache::find_blob(caller_pc); 1803 if (!cb->is_nmethod() || entry_point == moop->get_c2i_entry()) { 1804 return; 1805 } 1806 1807 // The check above makes sure this is a nmethod. 1808 nmethod* nm = cb->as_nmethod_or_null(); 1809 assert(nm, "must be"); 1810 1811 // Get the return PC for the passed caller PC. 1812 address return_pc = caller_pc + frame::pc_return_offset; 1813 1814 // Don't fixup method handle call sites as the executed method 1815 // handle adapters are doing the required MethodHandle chain work. 1816 if (nm->is_method_handle_return(return_pc)) { 1817 return; 1818 } 1819 1820 bool is_profiled = false; 1821 #ifdef COMPILER1 1822 is_profiled = nm->is_profiled_call(caller_pc+frame::pc_return_offset); 1823 #endif 1824 1825 // There is a benign race here. We could be attempting to patch to a compiled 1826 // entry point at the same time the callee is being deoptimized. If that is 1827 // the case then entry_point may in fact point to a c2i and we'd patch the 1828 // call site with the same old data. clear_code will set code() to NULL 1829 // at the end of it. If we happen to see that NULL then we can skip trying 1830 // to patch. If we hit the window where the callee has a c2i in the 1831 // from_compiled_entry and the NULL isn't present yet then we lose the race 1832 // and patch the code with the same old data. Asi es la vida. 1833 1834 if (moop->code() == NULL) return; 1835 1836 if (nm->is_in_use()) { 1837 1838 // Expect to find a native call there (unless it was no-inline cache vtable dispatch) 1839 MutexLockerEx ml_patch(Patching_lock, Mutex::_no_safepoint_check_flag); 1840 if (NativeCall::is_call_before(return_pc)) { 1841 NativeCall *call = nativeCall_before(return_pc); 1842 // 1843 // bug 6281185. We might get here after resolving a call site to a vanilla 1844 // virtual call. Because the resolvee uses the verified entry it may then 1845 // see compiled code and attempt to patch the site by calling us. This would 1846 // then incorrectly convert the call site to optimized and its downhill from 1847 // there. If you're lucky you'll get the assert in the bugid, if not you've 1848 // just made a call site that could be megamorphic into a monomorphic site 1849 // for the rest of its life! Just another racing bug in the life of 1850 // fixup_callers_callsite ... 1851 // 1852 RelocIterator iter(nm, call->instruction_address(), call->next_instruction_address()); 1853 iter.next(); 1854 assert(iter.has_current(), "must have a reloc at java call site"); 1855 relocInfo::relocType typ = iter.reloc()->type(); 1856 if ( typ != relocInfo::static_call_type && 1857 typ != relocInfo::opt_virtual_call_type && 1858 typ != relocInfo::static_stub_type) { 1859 return; 1860 } 1861 address destination = call->destination(); 1862 address stub = NULL; 1863 if (is_profiled) { 1864 stub = CompiledProfile::find_profile_stub(call); 1865 } 1866 if (destination != entry_point && !CompiledProfile::is_call_to_stub(call, stub)) { 1867 CodeBlob* callee = CodeCache::find_blob(destination); 1868 // callee == cb seems weird. It means calling interpreter thru stub. 1869 if (callee == cb || callee->is_adapter_blob()) { 1870 // static call or optimized virtual 1871 if (TraceCallFixup) { 1872 tty->print("fixup callsite at " INTPTR_FORMAT " to compiled code for", caller_pc); 1873 moop->print_short_name(tty); 1874 tty->print_cr(" to " INTPTR_FORMAT, entry_point); 1875 } 1876 if (is_profiled) { 1877 CompiledProfile::set_up_profiling(call, stub, entry_point); 1878 } else { 1879 call->set_destination_mt_safe(entry_point); 1880 } 1881 } else { 1882 if (TraceCallFixup) { 1883 tty->print("failed to fixup callsite at " INTPTR_FORMAT " to compiled code for", caller_pc); 1884 moop->print_short_name(tty); 1885 tty->print_cr(" to " INTPTR_FORMAT, entry_point); 1886 } 1887 // assert is too strong could also be resolve destinations. 1888 // assert(InlineCacheBuffer::contains(destination) || VtableStubs::contains(destination), "must be"); 1889 } 1890 } else { 1891 if (TraceCallFixup) { 1892 tty->print("already patched callsite at " INTPTR_FORMAT " to compiled code for", caller_pc); 1893 moop->print_short_name(tty); 1894 tty->print_cr(" to " INTPTR_FORMAT, entry_point); 1895 } 1896 } 1897 } 1898 } 1899 IRT_END 1900 1901 1902 // same as JVM_Arraycopy, but called directly from compiled code 1903 JRT_ENTRY(void, SharedRuntime::slow_arraycopy_C(oopDesc* src, jint src_pos, 1904 oopDesc* dest, jint dest_pos, 1905 jint length, 1906 JavaThread* thread)) { 1907 #ifndef PRODUCT 1908 _slow_array_copy_ctr++; 1909 #endif 1910 // Check if we have null pointers 1911 if (src == NULL || dest == NULL) { 1912 THROW(vmSymbols::java_lang_NullPointerException()); 1913 } 1914 // Do the copy. The casts to arrayOop are necessary to the copy_array API, 1915 // even though the copy_array API also performs dynamic checks to ensure 1916 // that src and dest are truly arrays (and are conformable). 1917 // The copy_array mechanism is awkward and could be removed, but 1918 // the compilers don't call this function except as a last resort, 1919 // so it probably doesn't matter. 1920 Klass::cast(src->klass())->copy_array((arrayOopDesc*)src, src_pos, 1921 (arrayOopDesc*)dest, dest_pos, 1922 length, thread); 1923 } 1924 JRT_END 1925 1926 char* SharedRuntime::generate_class_cast_message( 1927 JavaThread* thread, const char* objName) { 1928 1929 // Get target class name from the checkcast instruction 1930 vframeStream vfst(thread, true); 1931 assert(!vfst.at_end(), "Java frame must exist"); 1932 Bytecode_checkcast cc(vfst.method(), vfst.method()->bcp_from(vfst.bci())); 1933 Klass* targetKlass = Klass::cast(vfst.method()->constants()->klass_at( 1934 cc.index(), thread)); 1935 return generate_class_cast_message(objName, targetKlass->external_name()); 1936 } 1937 1938 char* SharedRuntime::generate_wrong_method_type_message(JavaThread* thread, 1939 oopDesc* required, 1940 oopDesc* actual) { 1941 if (TraceMethodHandles) { 1942 tty->print_cr("WrongMethodType thread="PTR_FORMAT" req="PTR_FORMAT" act="PTR_FORMAT"", 1943 thread, required, actual); 1944 } 1945 assert(EnableInvokeDynamic, ""); 1946 oop singleKlass = wrong_method_type_is_for_single_argument(thread, required); 1947 char* message = NULL; 1948 if (singleKlass != NULL) { 1949 const char* objName = "argument or return value"; 1950 if (actual != NULL) { 1951 // be flexible about the junk passed in: 1952 klassOop ak = (actual->is_klass() 1953 ? (klassOop)actual 1954 : actual->klass()); 1955 objName = Klass::cast(ak)->external_name(); 1956 } 1957 Klass* targetKlass = Klass::cast(required->is_klass() 1958 ? (klassOop)required 1959 : java_lang_Class::as_klassOop(required)); 1960 message = generate_class_cast_message(objName, targetKlass->external_name()); 1961 } else { 1962 // %%% need to get the MethodType string, without messing around too much 1963 const char* desc = NULL; 1964 // Get a signature from the invoke instruction 1965 const char* mhName = "method handle"; 1966 const char* targetType = "the required signature"; 1967 int targetArity = -1, mhArity = -1; 1968 vframeStream vfst(thread, true); 1969 if (!vfst.at_end()) { 1970 Bytecode_invoke call(vfst.method(), vfst.bci()); 1971 methodHandle target; 1972 { 1973 EXCEPTION_MARK; 1974 target = call.static_target(THREAD); 1975 if (HAS_PENDING_EXCEPTION) { CLEAR_PENDING_EXCEPTION; } 1976 } 1977 if (target.not_null() 1978 && target->is_method_handle_invoke() 1979 && required == target->method_handle_type()) { 1980 targetType = target->signature()->as_C_string(); 1981 targetArity = ArgumentCount(target->signature()).size(); 1982 } 1983 } 1984 KlassHandle kignore; int dmf_flags = 0; 1985 methodHandle actual_method = MethodHandles::decode_method(actual, kignore, dmf_flags); 1986 if ((dmf_flags & ~(MethodHandles::_dmf_has_receiver | 1987 MethodHandles::_dmf_does_dispatch | 1988 MethodHandles::_dmf_from_interface)) != 0) 1989 actual_method = methodHandle(); // MH does extra binds, drops, etc. 1990 bool has_receiver = ((dmf_flags & MethodHandles::_dmf_has_receiver) != 0); 1991 if (actual_method.not_null()) { 1992 mhName = actual_method->signature()->as_C_string(); 1993 mhArity = ArgumentCount(actual_method->signature()).size(); 1994 if (!actual_method->is_static()) mhArity += 1; 1995 } else if (java_lang_invoke_MethodHandle::is_instance(actual)) { 1996 oopDesc* mhType = java_lang_invoke_MethodHandle::type(actual); 1997 mhArity = java_lang_invoke_MethodType::ptype_count(mhType); 1998 stringStream st; 1999 java_lang_invoke_MethodType::print_signature(mhType, &st); 2000 mhName = st.as_string(); 2001 } 2002 if (targetArity != -1 && targetArity != mhArity) { 2003 if (has_receiver && targetArity == mhArity-1) 2004 desc = " cannot be called without a receiver argument as "; 2005 else 2006 desc = " cannot be called with a different arity as "; 2007 } 2008 message = generate_class_cast_message(mhName, targetType, 2009 desc != NULL ? desc : 2010 " cannot be called as "); 2011 } 2012 if (TraceMethodHandles) { 2013 tty->print_cr("WrongMethodType => message=%s", message); 2014 } 2015 return message; 2016 } 2017 2018 oop SharedRuntime::wrong_method_type_is_for_single_argument(JavaThread* thr, 2019 oopDesc* required) { 2020 if (required == NULL) return NULL; 2021 if (required->klass() == SystemDictionary::Class_klass()) 2022 return required; 2023 if (required->is_klass()) 2024 return Klass::cast(klassOop(required))->java_mirror(); 2025 return NULL; 2026 } 2027 2028 2029 char* SharedRuntime::generate_class_cast_message( 2030 const char* objName, const char* targetKlassName, const char* desc) { 2031 size_t msglen = strlen(objName) + strlen(desc) + strlen(targetKlassName) + 1; 2032 2033 char* message = NEW_RESOURCE_ARRAY(char, msglen); 2034 if (NULL == message) { 2035 // Shouldn't happen, but don't cause even more problems if it does 2036 message = const_cast<char*>(objName); 2037 } else { 2038 jio_snprintf(message, msglen, "%s%s%s", objName, desc, targetKlassName); 2039 } 2040 return message; 2041 } 2042 2043 JRT_LEAF(void, SharedRuntime::reguard_yellow_pages()) 2044 (void) JavaThread::current()->reguard_stack(); 2045 JRT_END 2046 2047 2048 // Handles the uncommon case in locking, i.e., contention or an inflated lock. 2049 #ifndef PRODUCT 2050 int SharedRuntime::_monitor_enter_ctr=0; 2051 #endif 2052 JRT_ENTRY_NO_ASYNC(void, SharedRuntime::complete_monitor_locking_C(oopDesc* _obj, BasicLock* lock, JavaThread* thread)) 2053 oop obj(_obj); 2054 #ifndef PRODUCT 2055 _monitor_enter_ctr++; // monitor enter slow 2056 #endif 2057 if (PrintBiasedLockingStatistics) { 2058 Atomic::inc(BiasedLocking::slow_path_entry_count_addr()); 2059 } 2060 Handle h_obj(THREAD, obj); 2061 if (UseBiasedLocking) { 2062 // Retry fast entry if bias is revoked to avoid unnecessary inflation 2063 ObjectSynchronizer::fast_enter(h_obj, lock, true, CHECK); 2064 } else { 2065 ObjectSynchronizer::slow_enter(h_obj, lock, CHECK); 2066 } 2067 assert(!HAS_PENDING_EXCEPTION, "Should have no exception here"); 2068 JRT_END 2069 2070 #ifndef PRODUCT 2071 int SharedRuntime::_monitor_exit_ctr=0; 2072 #endif 2073 // Handles the uncommon cases of monitor unlocking in compiled code 2074 JRT_LEAF(void, SharedRuntime::complete_monitor_unlocking_C(oopDesc* _obj, BasicLock* lock)) 2075 oop obj(_obj); 2076 #ifndef PRODUCT 2077 _monitor_exit_ctr++; // monitor exit slow 2078 #endif 2079 Thread* THREAD = JavaThread::current(); 2080 // I'm not convinced we need the code contained by MIGHT_HAVE_PENDING anymore 2081 // testing was unable to ever fire the assert that guarded it so I have removed it. 2082 assert(!HAS_PENDING_EXCEPTION, "Do we need code below anymore?"); 2083 #undef MIGHT_HAVE_PENDING 2084 #ifdef MIGHT_HAVE_PENDING 2085 // Save and restore any pending_exception around the exception mark. 2086 // While the slow_exit must not throw an exception, we could come into 2087 // this routine with one set. 2088 oop pending_excep = NULL; 2089 const char* pending_file; 2090 int pending_line; 2091 if (HAS_PENDING_EXCEPTION) { 2092 pending_excep = PENDING_EXCEPTION; 2093 pending_file = THREAD->exception_file(); 2094 pending_line = THREAD->exception_line(); 2095 CLEAR_PENDING_EXCEPTION; 2096 } 2097 #endif /* MIGHT_HAVE_PENDING */ 2098 2099 { 2100 // Exit must be non-blocking, and therefore no exceptions can be thrown. 2101 EXCEPTION_MARK; 2102 ObjectSynchronizer::slow_exit(obj, lock, THREAD); 2103 } 2104 2105 #ifdef MIGHT_HAVE_PENDING 2106 if (pending_excep != NULL) { 2107 THREAD->set_pending_exception(pending_excep, pending_file, pending_line); 2108 } 2109 #endif /* MIGHT_HAVE_PENDING */ 2110 JRT_END 2111 2112 #ifndef PRODUCT 2113 2114 void SharedRuntime::print_statistics() { 2115 ttyLocker ttyl; 2116 if (xtty != NULL) xtty->head("statistics type='SharedRuntime'"); 2117 2118 if (_monitor_enter_ctr ) tty->print_cr("%5d monitor enter slow", _monitor_enter_ctr); 2119 if (_monitor_exit_ctr ) tty->print_cr("%5d monitor exit slow", _monitor_exit_ctr); 2120 if (_throw_null_ctr) tty->print_cr("%5d implicit null throw", _throw_null_ctr); 2121 2122 SharedRuntime::print_ic_miss_histogram(); 2123 2124 if (CountRemovableExceptions) { 2125 if (_nof_removable_exceptions > 0) { 2126 Unimplemented(); // this counter is not yet incremented 2127 tty->print_cr("Removable exceptions: %d", _nof_removable_exceptions); 2128 } 2129 } 2130 2131 // Dump the JRT_ENTRY counters 2132 if( _new_instance_ctr ) tty->print_cr("%5d new instance requires GC", _new_instance_ctr); 2133 if( _new_array_ctr ) tty->print_cr("%5d new array requires GC", _new_array_ctr); 2134 if( _multi1_ctr ) tty->print_cr("%5d multianewarray 1 dim", _multi1_ctr); 2135 if( _multi2_ctr ) tty->print_cr("%5d multianewarray 2 dim", _multi2_ctr); 2136 if( _multi3_ctr ) tty->print_cr("%5d multianewarray 3 dim", _multi3_ctr); 2137 if( _multi4_ctr ) tty->print_cr("%5d multianewarray 4 dim", _multi4_ctr); 2138 if( _multi5_ctr ) tty->print_cr("%5d multianewarray 5 dim", _multi5_ctr); 2139 2140 tty->print_cr("%5d inline cache miss in compiled", _ic_miss_ctr ); 2141 tty->print_cr("%5d wrong method", _wrong_method_ctr ); 2142 tty->print_cr("%5d unresolved static call site", _resolve_static_ctr ); 2143 tty->print_cr("%5d unresolved virtual call site", _resolve_virtual_ctr ); 2144 tty->print_cr("%5d unresolved opt virtual call site", _resolve_opt_virtual_ctr ); 2145 2146 if( _mon_enter_stub_ctr ) tty->print_cr("%5d monitor enter stub", _mon_enter_stub_ctr ); 2147 if( _mon_exit_stub_ctr ) tty->print_cr("%5d monitor exit stub", _mon_exit_stub_ctr ); 2148 if( _mon_enter_ctr ) tty->print_cr("%5d monitor enter slow", _mon_enter_ctr ); 2149 if( _mon_exit_ctr ) tty->print_cr("%5d monitor exit slow", _mon_exit_ctr ); 2150 if( _partial_subtype_ctr) tty->print_cr("%5d slow partial subtype", _partial_subtype_ctr ); 2151 if( _jbyte_array_copy_ctr ) tty->print_cr("%5d byte array copies", _jbyte_array_copy_ctr ); 2152 if( _jshort_array_copy_ctr ) tty->print_cr("%5d short array copies", _jshort_array_copy_ctr ); 2153 if( _jint_array_copy_ctr ) tty->print_cr("%5d int array copies", _jint_array_copy_ctr ); 2154 if( _jlong_array_copy_ctr ) tty->print_cr("%5d long array copies", _jlong_array_copy_ctr ); 2155 if( _oop_array_copy_ctr ) tty->print_cr("%5d oop array copies", _oop_array_copy_ctr ); 2156 if( _checkcast_array_copy_ctr ) tty->print_cr("%5d checkcast array copies", _checkcast_array_copy_ctr ); 2157 if( _unsafe_array_copy_ctr ) tty->print_cr("%5d unsafe array copies", _unsafe_array_copy_ctr ); 2158 if( _generic_array_copy_ctr ) tty->print_cr("%5d generic array copies", _generic_array_copy_ctr ); 2159 if( _slow_array_copy_ctr ) tty->print_cr("%5d slow array copies", _slow_array_copy_ctr ); 2160 if( _find_handler_ctr ) tty->print_cr("%5d find exception handler", _find_handler_ctr ); 2161 if( _rethrow_ctr ) tty->print_cr("%5d rethrow handler", _rethrow_ctr ); 2162 2163 AdapterHandlerLibrary::print_statistics(); 2164 2165 if (xtty != NULL) xtty->tail("statistics"); 2166 } 2167 2168 inline double percent(int x, int y) { 2169 return 100.0 * x / MAX2(y, 1); 2170 } 2171 2172 class MethodArityHistogram { 2173 public: 2174 enum { MAX_ARITY = 256 }; 2175 private: 2176 static int _arity_histogram[MAX_ARITY]; // histogram of #args 2177 static int _size_histogram[MAX_ARITY]; // histogram of arg size in words 2178 static int _max_arity; // max. arity seen 2179 static int _max_size; // max. arg size seen 2180 2181 static void add_method_to_histogram(nmethod* nm) { 2182 methodOop m = nm->method(); 2183 ArgumentCount args(m->signature()); 2184 int arity = args.size() + (m->is_static() ? 0 : 1); 2185 int argsize = m->size_of_parameters(); 2186 arity = MIN2(arity, MAX_ARITY-1); 2187 argsize = MIN2(argsize, MAX_ARITY-1); 2188 int count = nm->method()->compiled_invocation_count(); 2189 _arity_histogram[arity] += count; 2190 _size_histogram[argsize] += count; 2191 _max_arity = MAX2(_max_arity, arity); 2192 _max_size = MAX2(_max_size, argsize); 2193 } 2194 2195 void print_histogram_helper(int n, int* histo, const char* name) { 2196 const int N = MIN2(5, n); 2197 tty->print_cr("\nHistogram of call arity (incl. rcvr, calls to compiled methods only):"); 2198 double sum = 0; 2199 double weighted_sum = 0; 2200 int i; 2201 for (i = 0; i <= n; i++) { sum += histo[i]; weighted_sum += i*histo[i]; } 2202 double rest = sum; 2203 double percent = sum / 100; 2204 for (i = 0; i <= N; i++) { 2205 rest -= histo[i]; 2206 tty->print_cr("%4d: %7d (%5.1f%%)", i, histo[i], histo[i] / percent); 2207 } 2208 tty->print_cr("rest: %7d (%5.1f%%))", (int)rest, rest / percent); 2209 tty->print_cr("(avg. %s = %3.1f, max = %d)", name, weighted_sum / sum, n); 2210 } 2211 2212 void print_histogram() { 2213 tty->print_cr("\nHistogram of call arity (incl. rcvr, calls to compiled methods only):"); 2214 print_histogram_helper(_max_arity, _arity_histogram, "arity"); 2215 tty->print_cr("\nSame for parameter size (in words):"); 2216 print_histogram_helper(_max_size, _size_histogram, "size"); 2217 tty->cr(); 2218 } 2219 2220 public: 2221 MethodArityHistogram() { 2222 MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag); 2223 _max_arity = _max_size = 0; 2224 for (int i = 0; i < MAX_ARITY; i++) _arity_histogram[i] = _size_histogram [i] = 0; 2225 CodeCache::nmethods_do(add_method_to_histogram); 2226 print_histogram(); 2227 } 2228 }; 2229 2230 int MethodArityHistogram::_arity_histogram[MethodArityHistogram::MAX_ARITY]; 2231 int MethodArityHistogram::_size_histogram[MethodArityHistogram::MAX_ARITY]; 2232 int MethodArityHistogram::_max_arity; 2233 int MethodArityHistogram::_max_size; 2234 2235 void SharedRuntime::print_call_statistics(int comp_total) { 2236 tty->print_cr("Calls from compiled code:"); 2237 int total = _nof_normal_calls + _nof_interface_calls + _nof_static_calls; 2238 int mono_c = _nof_normal_calls - _nof_optimized_calls - _nof_megamorphic_calls; 2239 int mono_i = _nof_interface_calls - _nof_optimized_interface_calls - _nof_megamorphic_interface_calls; 2240 tty->print_cr("\t%9d (%4.1f%%) total non-inlined ", total, percent(total, total)); 2241 tty->print_cr("\t%9d (%4.1f%%) virtual calls ", _nof_normal_calls, percent(_nof_normal_calls, total)); 2242 tty->print_cr("\t %9d (%3.0f%%) inlined ", _nof_inlined_calls, percent(_nof_inlined_calls, _nof_normal_calls)); 2243 tty->print_cr("\t %9d (%3.0f%%) optimized ", _nof_optimized_calls, percent(_nof_optimized_calls, _nof_normal_calls)); 2244 tty->print_cr("\t %9d (%3.0f%%) monomorphic ", mono_c, percent(mono_c, _nof_normal_calls)); 2245 tty->print_cr("\t %9d (%3.0f%%) megamorphic ", _nof_megamorphic_calls, percent(_nof_megamorphic_calls, _nof_normal_calls)); 2246 tty->print_cr("\t%9d (%4.1f%%) interface calls ", _nof_interface_calls, percent(_nof_interface_calls, total)); 2247 tty->print_cr("\t %9d (%3.0f%%) inlined ", _nof_inlined_interface_calls, percent(_nof_inlined_interface_calls, _nof_interface_calls)); 2248 tty->print_cr("\t %9d (%3.0f%%) optimized ", _nof_optimized_interface_calls, percent(_nof_optimized_interface_calls, _nof_interface_calls)); 2249 tty->print_cr("\t %9d (%3.0f%%) monomorphic ", mono_i, percent(mono_i, _nof_interface_calls)); 2250 tty->print_cr("\t %9d (%3.0f%%) megamorphic ", _nof_megamorphic_interface_calls, percent(_nof_megamorphic_interface_calls, _nof_interface_calls)); 2251 tty->print_cr("\t%9d (%4.1f%%) static/special calls", _nof_static_calls, percent(_nof_static_calls, total)); 2252 tty->print_cr("\t %9d (%3.0f%%) inlined ", _nof_inlined_static_calls, percent(_nof_inlined_static_calls, _nof_static_calls)); 2253 tty->cr(); 2254 tty->print_cr("Note 1: counter updates are not MT-safe."); 2255 tty->print_cr("Note 2: %% in major categories are relative to total non-inlined calls;"); 2256 tty->print_cr(" %% in nested categories are relative to their category"); 2257 tty->print_cr(" (and thus add up to more than 100%% with inlining)"); 2258 tty->cr(); 2259 2260 MethodArityHistogram h; 2261 } 2262 #endif 2263 2264 2265 // A simple wrapper class around the calling convention information 2266 // that allows sharing of adapters for the same calling convention. 2267 class AdapterFingerPrint : public CHeapObj { 2268 private: 2269 union { 2270 int _compact[3]; 2271 int* _fingerprint; 2272 } _value; 2273 int _length; // A negative length indicates the fingerprint is in the compact form, 2274 // Otherwise _value._fingerprint is the array. 2275 2276 // Remap BasicTypes that are handled equivalently by the adapters. 2277 // These are correct for the current system but someday it might be 2278 // necessary to make this mapping platform dependent. 2279 static BasicType adapter_encoding(BasicType in) { 2280 assert((~0xf & in) == 0, "must fit in 4 bits"); 2281 switch(in) { 2282 case T_BOOLEAN: 2283 case T_BYTE: 2284 case T_SHORT: 2285 case T_CHAR: 2286 // There are all promoted to T_INT in the calling convention 2287 return T_INT; 2288 2289 case T_OBJECT: 2290 case T_ARRAY: 2291 #ifdef _LP64 2292 return T_LONG; 2293 #else 2294 return T_INT; 2295 #endif 2296 2297 case T_INT: 2298 case T_LONG: 2299 case T_FLOAT: 2300 case T_DOUBLE: 2301 case T_VOID: 2302 return in; 2303 2304 default: 2305 ShouldNotReachHere(); 2306 return T_CONFLICT; 2307 } 2308 } 2309 2310 public: 2311 AdapterFingerPrint(int total_args_passed, BasicType* sig_bt) { 2312 // The fingerprint is based on the BasicType signature encoded 2313 // into an array of ints with eight entries per int. 2314 int* ptr; 2315 int len = (total_args_passed + 7) >> 3; 2316 if (len <= (int)(sizeof(_value._compact) / sizeof(int))) { 2317 _value._compact[0] = _value._compact[1] = _value._compact[2] = 0; 2318 // Storing the signature encoded as signed chars hits about 98% 2319 // of the time. 2320 _length = -len; 2321 ptr = _value._compact; 2322 } else { 2323 _length = len; 2324 _value._fingerprint = NEW_C_HEAP_ARRAY(int, _length); 2325 ptr = _value._fingerprint; 2326 } 2327 2328 // Now pack the BasicTypes with 8 per int 2329 int sig_index = 0; 2330 for (int index = 0; index < len; index++) { 2331 int value = 0; 2332 for (int byte = 0; byte < 8; byte++) { 2333 if (sig_index < total_args_passed) { 2334 value = (value << 4) | adapter_encoding(sig_bt[sig_index++]); 2335 } 2336 } 2337 ptr[index] = value; 2338 } 2339 } 2340 2341 ~AdapterFingerPrint() { 2342 if (_length > 0) { 2343 FREE_C_HEAP_ARRAY(int, _value._fingerprint); 2344 } 2345 } 2346 2347 int value(int index) { 2348 if (_length < 0) { 2349 return _value._compact[index]; 2350 } 2351 return _value._fingerprint[index]; 2352 } 2353 int length() { 2354 if (_length < 0) return -_length; 2355 return _length; 2356 } 2357 2358 bool is_compact() { 2359 return _length <= 0; 2360 } 2361 2362 unsigned int compute_hash() { 2363 int hash = 0; 2364 for (int i = 0; i < length(); i++) { 2365 int v = value(i); 2366 hash = (hash << 8) ^ v ^ (hash >> 5); 2367 } 2368 return (unsigned int)hash; 2369 } 2370 2371 const char* as_string() { 2372 stringStream st; 2373 st.print("0x"); 2374 for (int i = 0; i < length(); i++) { 2375 st.print("%08x", value(i)); 2376 } 2377 return st.as_string(); 2378 } 2379 2380 bool equals(AdapterFingerPrint* other) { 2381 if (other->_length != _length) { 2382 return false; 2383 } 2384 if (_length < 0) { 2385 return _value._compact[0] == other->_value._compact[0] && 2386 _value._compact[1] == other->_value._compact[1] && 2387 _value._compact[2] == other->_value._compact[2]; 2388 } else { 2389 for (int i = 0; i < _length; i++) { 2390 if (_value._fingerprint[i] != other->_value._fingerprint[i]) { 2391 return false; 2392 } 2393 } 2394 } 2395 return true; 2396 } 2397 }; 2398 2399 2400 // A hashtable mapping from AdapterFingerPrints to AdapterHandlerEntries 2401 class AdapterHandlerTable : public BasicHashtable { 2402 friend class AdapterHandlerTableIterator; 2403 2404 private: 2405 2406 #ifndef PRODUCT 2407 static int _lookups; // number of calls to lookup 2408 static int _buckets; // number of buckets checked 2409 static int _equals; // number of buckets checked with matching hash 2410 static int _hits; // number of successful lookups 2411 static int _compact; // number of equals calls with compact signature 2412 #endif 2413 2414 AdapterHandlerEntry* bucket(int i) { 2415 return (AdapterHandlerEntry*)BasicHashtable::bucket(i); 2416 } 2417 2418 public: 2419 AdapterHandlerTable() 2420 : BasicHashtable(293, sizeof(AdapterHandlerEntry)) { } 2421 2422 // Create a new entry suitable for insertion in the table 2423 AdapterHandlerEntry* new_entry(AdapterFingerPrint* fingerprint, address i2c_entry, address c2i_entry, address c2i_unverified_entry) { 2424 AdapterHandlerEntry* entry = (AdapterHandlerEntry*)BasicHashtable::new_entry(fingerprint->compute_hash()); 2425 entry->init(fingerprint, i2c_entry, c2i_entry, c2i_unverified_entry); 2426 return entry; 2427 } 2428 2429 // Insert an entry into the table 2430 void add(AdapterHandlerEntry* entry) { 2431 int index = hash_to_index(entry->hash()); 2432 add_entry(index, entry); 2433 } 2434 2435 void free_entry(AdapterHandlerEntry* entry) { 2436 entry->deallocate(); 2437 BasicHashtable::free_entry(entry); 2438 } 2439 2440 // Find a entry with the same fingerprint if it exists 2441 AdapterHandlerEntry* lookup(int total_args_passed, BasicType* sig_bt) { 2442 NOT_PRODUCT(_lookups++); 2443 AdapterFingerPrint fp(total_args_passed, sig_bt); 2444 unsigned int hash = fp.compute_hash(); 2445 int index = hash_to_index(hash); 2446 for (AdapterHandlerEntry* e = bucket(index); e != NULL; e = e->next()) { 2447 NOT_PRODUCT(_buckets++); 2448 if (e->hash() == hash) { 2449 NOT_PRODUCT(_equals++); 2450 if (fp.equals(e->fingerprint())) { 2451 #ifndef PRODUCT 2452 if (fp.is_compact()) _compact++; 2453 _hits++; 2454 #endif 2455 return e; 2456 } 2457 } 2458 } 2459 return NULL; 2460 } 2461 2462 #ifndef PRODUCT 2463 void print_statistics() { 2464 ResourceMark rm; 2465 int longest = 0; 2466 int empty = 0; 2467 int total = 0; 2468 int nonempty = 0; 2469 for (int index = 0; index < table_size(); index++) { 2470 int count = 0; 2471 for (AdapterHandlerEntry* e = bucket(index); e != NULL; e = e->next()) { 2472 count++; 2473 } 2474 if (count != 0) nonempty++; 2475 if (count == 0) empty++; 2476 if (count > longest) longest = count; 2477 total += count; 2478 } 2479 tty->print_cr("AdapterHandlerTable: empty %d longest %d total %d average %f", 2480 empty, longest, total, total / (double)nonempty); 2481 tty->print_cr("AdapterHandlerTable: lookups %d buckets %d equals %d hits %d compact %d", 2482 _lookups, _buckets, _equals, _hits, _compact); 2483 } 2484 #endif 2485 }; 2486 2487 2488 #ifndef PRODUCT 2489 2490 int AdapterHandlerTable::_lookups; 2491 int AdapterHandlerTable::_buckets; 2492 int AdapterHandlerTable::_equals; 2493 int AdapterHandlerTable::_hits; 2494 int AdapterHandlerTable::_compact; 2495 2496 #endif 2497 2498 class AdapterHandlerTableIterator : public StackObj { 2499 private: 2500 AdapterHandlerTable* _table; 2501 int _index; 2502 AdapterHandlerEntry* _current; 2503 2504 void scan() { 2505 while (_index < _table->table_size()) { 2506 AdapterHandlerEntry* a = _table->bucket(_index); 2507 _index++; 2508 if (a != NULL) { 2509 _current = a; 2510 return; 2511 } 2512 } 2513 } 2514 2515 public: 2516 AdapterHandlerTableIterator(AdapterHandlerTable* table): _table(table), _index(0), _current(NULL) { 2517 scan(); 2518 } 2519 bool has_next() { 2520 return _current != NULL; 2521 } 2522 AdapterHandlerEntry* next() { 2523 if (_current != NULL) { 2524 AdapterHandlerEntry* result = _current; 2525 _current = _current->next(); 2526 if (_current == NULL) scan(); 2527 return result; 2528 } else { 2529 return NULL; 2530 } 2531 } 2532 }; 2533 2534 2535 // --------------------------------------------------------------------------- 2536 // Implementation of AdapterHandlerLibrary 2537 AdapterHandlerTable* AdapterHandlerLibrary::_adapters = NULL; 2538 AdapterHandlerEntry* AdapterHandlerLibrary::_abstract_method_handler = NULL; 2539 const int AdapterHandlerLibrary_size = 16*K; 2540 BufferBlob* AdapterHandlerLibrary::_buffer = NULL; 2541 2542 BufferBlob* AdapterHandlerLibrary::buffer_blob() { 2543 // Should be called only when AdapterHandlerLibrary_lock is active. 2544 if (_buffer == NULL) // Initialize lazily 2545 _buffer = BufferBlob::create("adapters", AdapterHandlerLibrary_size); 2546 return _buffer; 2547 } 2548 2549 void AdapterHandlerLibrary::initialize() { 2550 if (_adapters != NULL) return; 2551 _adapters = new AdapterHandlerTable(); 2552 2553 // Create a special handler for abstract methods. Abstract methods 2554 // are never compiled so an i2c entry is somewhat meaningless, but 2555 // fill it in with something appropriate just in case. Pass handle 2556 // wrong method for the c2i transitions. 2557 address wrong_method = SharedRuntime::get_handle_wrong_method_stub(); 2558 _abstract_method_handler = AdapterHandlerLibrary::new_entry(new AdapterFingerPrint(0, NULL), 2559 StubRoutines::throw_AbstractMethodError_entry(), 2560 wrong_method, wrong_method); 2561 } 2562 2563 AdapterHandlerEntry* AdapterHandlerLibrary::new_entry(AdapterFingerPrint* fingerprint, 2564 address i2c_entry, 2565 address c2i_entry, 2566 address c2i_unverified_entry) { 2567 return _adapters->new_entry(fingerprint, i2c_entry, c2i_entry, c2i_unverified_entry); 2568 } 2569 2570 AdapterHandlerEntry* AdapterHandlerLibrary::get_adapter(methodHandle method) { 2571 // Use customized signature handler. Need to lock around updates to 2572 // the AdapterHandlerTable (it is not safe for concurrent readers 2573 // and a single writer: this could be fixed if it becomes a 2574 // problem). 2575 2576 // Get the address of the ic_miss handlers before we grab the 2577 // AdapterHandlerLibrary_lock. This fixes bug 6236259 which 2578 // was caused by the initialization of the stubs happening 2579 // while we held the lock and then notifying jvmti while 2580 // holding it. This just forces the initialization to be a little 2581 // earlier. 2582 address ic_miss = SharedRuntime::get_ic_miss_stub(); 2583 assert(ic_miss != NULL, "must have handler"); 2584 2585 ResourceMark rm; 2586 2587 NOT_PRODUCT(int insts_size); 2588 AdapterBlob* B = NULL; 2589 AdapterHandlerEntry* entry = NULL; 2590 AdapterFingerPrint* fingerprint = NULL; 2591 { 2592 MutexLocker mu(AdapterHandlerLibrary_lock); 2593 // make sure data structure is initialized 2594 initialize(); 2595 2596 if (method->is_abstract()) { 2597 return _abstract_method_handler; 2598 } 2599 2600 // Fill in the signature array, for the calling-convention call. 2601 int total_args_passed = method->size_of_parameters(); // All args on stack 2602 2603 BasicType* sig_bt = NEW_RESOURCE_ARRAY(BasicType, total_args_passed); 2604 VMRegPair* regs = NEW_RESOURCE_ARRAY(VMRegPair, total_args_passed); 2605 int i = 0; 2606 if (!method->is_static()) // Pass in receiver first 2607 sig_bt[i++] = T_OBJECT; 2608 for (SignatureStream ss(method->signature()); !ss.at_return_type(); ss.next()) { 2609 sig_bt[i++] = ss.type(); // Collect remaining bits of signature 2610 if (ss.type() == T_LONG || ss.type() == T_DOUBLE) 2611 sig_bt[i++] = T_VOID; // Longs & doubles take 2 Java slots 2612 } 2613 assert(i == total_args_passed, ""); 2614 2615 // Lookup method signature's fingerprint 2616 entry = _adapters->lookup(total_args_passed, sig_bt); 2617 2618 #ifdef ASSERT 2619 AdapterHandlerEntry* shared_entry = NULL; 2620 if (VerifyAdapterSharing && entry != NULL) { 2621 shared_entry = entry; 2622 entry = NULL; 2623 } 2624 #endif 2625 2626 if (entry != NULL) { 2627 return entry; 2628 } 2629 2630 // Get a description of the compiled java calling convention and the largest used (VMReg) stack slot usage 2631 int comp_args_on_stack = SharedRuntime::java_calling_convention(sig_bt, regs, total_args_passed, false); 2632 2633 // Make a C heap allocated version of the fingerprint to store in the adapter 2634 fingerprint = new AdapterFingerPrint(total_args_passed, sig_bt); 2635 2636 // Create I2C & C2I handlers 2637 2638 BufferBlob* buf = buffer_blob(); // the temporary code buffer in CodeCache 2639 if (buf != NULL) { 2640 CodeBuffer buffer(buf); 2641 short buffer_locs[20]; 2642 buffer.insts()->initialize_shared_locs((relocInfo*)buffer_locs, 2643 sizeof(buffer_locs)/sizeof(relocInfo)); 2644 MacroAssembler _masm(&buffer); 2645 2646 entry = SharedRuntime::generate_i2c2i_adapters(&_masm, 2647 total_args_passed, 2648 comp_args_on_stack, 2649 sig_bt, 2650 regs, 2651 fingerprint); 2652 2653 #ifdef ASSERT 2654 if (VerifyAdapterSharing) { 2655 if (shared_entry != NULL) { 2656 assert(shared_entry->compare_code(buf->code_begin(), buffer.insts_size(), total_args_passed, sig_bt), 2657 "code must match"); 2658 // Release the one just created and return the original 2659 _adapters->free_entry(entry); 2660 return shared_entry; 2661 } else { 2662 entry->save_code(buf->code_begin(), buffer.insts_size(), total_args_passed, sig_bt); 2663 } 2664 } 2665 #endif 2666 2667 B = AdapterBlob::create(&buffer); 2668 NOT_PRODUCT(insts_size = buffer.insts_size()); 2669 } 2670 if (B == NULL) { 2671 // CodeCache is full, disable compilation 2672 // Ought to log this but compile log is only per compile thread 2673 // and we're some non descript Java thread. 2674 MutexUnlocker mu(AdapterHandlerLibrary_lock); 2675 CompileBroker::handle_full_code_cache(); 2676 return NULL; // Out of CodeCache space 2677 } 2678 entry->relocate(B->content_begin()); 2679 #ifndef PRODUCT 2680 // debugging suppport 2681 if (PrintAdapterHandlers) { 2682 tty->cr(); 2683 tty->print_cr("i2c argument handler #%d for: %s %s (fingerprint = %s, %d bytes generated)", 2684 _adapters->number_of_entries(), (method->is_static() ? "static" : "receiver"), 2685 method->signature()->as_C_string(), fingerprint->as_string(), insts_size ); 2686 tty->print_cr("c2i argument handler starts at %p",entry->get_c2i_entry()); 2687 Disassembler::decode(entry->get_i2c_entry(), entry->get_i2c_entry() + insts_size); 2688 } 2689 #endif 2690 2691 _adapters->add(entry); 2692 } 2693 // Outside of the lock 2694 if (B != NULL) { 2695 char blob_id[256]; 2696 jio_snprintf(blob_id, 2697 sizeof(blob_id), 2698 "%s(%s)@" PTR_FORMAT, 2699 B->name(), 2700 fingerprint->as_string(), 2701 B->content_begin()); 2702 Forte::register_stub(blob_id, B->content_begin(), B->content_end()); 2703 2704 if (JvmtiExport::should_post_dynamic_code_generated()) { 2705 JvmtiExport::post_dynamic_code_generated(blob_id, B->content_begin(), B->content_end()); 2706 } 2707 } 2708 return entry; 2709 } 2710 2711 void AdapterHandlerEntry::relocate(address new_base) { 2712 ptrdiff_t delta = new_base - _i2c_entry; 2713 _i2c_entry += delta; 2714 _c2i_entry += delta; 2715 _c2i_unverified_entry += delta; 2716 } 2717 2718 2719 void AdapterHandlerEntry::deallocate() { 2720 delete _fingerprint; 2721 #ifdef ASSERT 2722 if (_saved_code) FREE_C_HEAP_ARRAY(unsigned char, _saved_code); 2723 if (_saved_sig) FREE_C_HEAP_ARRAY(Basictype, _saved_sig); 2724 #endif 2725 } 2726 2727 2728 #ifdef ASSERT 2729 // Capture the code before relocation so that it can be compared 2730 // against other versions. If the code is captured after relocation 2731 // then relative instructions won't be equivalent. 2732 void AdapterHandlerEntry::save_code(unsigned char* buffer, int length, int total_args_passed, BasicType* sig_bt) { 2733 _saved_code = NEW_C_HEAP_ARRAY(unsigned char, length); 2734 _code_length = length; 2735 memcpy(_saved_code, buffer, length); 2736 _total_args_passed = total_args_passed; 2737 _saved_sig = NEW_C_HEAP_ARRAY(BasicType, _total_args_passed); 2738 memcpy(_saved_sig, sig_bt, _total_args_passed * sizeof(BasicType)); 2739 } 2740 2741 2742 bool AdapterHandlerEntry::compare_code(unsigned char* buffer, int length, int total_args_passed, BasicType* sig_bt) { 2743 if (length != _code_length) { 2744 return false; 2745 } 2746 for (int i = 0; i < length; i++) { 2747 if (buffer[i] != _saved_code[i]) { 2748 return false; 2749 } 2750 } 2751 return true; 2752 } 2753 #endif 2754 2755 2756 // Create a native wrapper for this native method. The wrapper converts the 2757 // java compiled calling convention to the native convention, handlizes 2758 // arguments, and transitions to native. On return from the native we transition 2759 // back to java blocking if a safepoint is in progress. 2760 nmethod *AdapterHandlerLibrary::create_native_wrapper(methodHandle method, int compile_id) { 2761 ResourceMark rm; 2762 nmethod* nm = NULL; 2763 2764 assert(method->has_native_function(), "must have something valid to call!"); 2765 2766 { 2767 // perform the work while holding the lock, but perform any printing outside the lock 2768 MutexLocker mu(AdapterHandlerLibrary_lock); 2769 // See if somebody beat us to it 2770 nm = method->code(); 2771 if (nm) { 2772 return nm; 2773 } 2774 2775 ResourceMark rm; 2776 2777 BufferBlob* buf = buffer_blob(); // the temporary code buffer in CodeCache 2778 if (buf != NULL) { 2779 CodeBuffer buffer(buf); 2780 double locs_buf[20]; 2781 buffer.insts()->initialize_shared_locs((relocInfo*)locs_buf, sizeof(locs_buf) / sizeof(relocInfo)); 2782 MacroAssembler _masm(&buffer); 2783 2784 // Fill in the signature array, for the calling-convention call. 2785 int total_args_passed = method->size_of_parameters(); 2786 2787 BasicType* sig_bt = NEW_RESOURCE_ARRAY(BasicType,total_args_passed); 2788 VMRegPair* regs = NEW_RESOURCE_ARRAY(VMRegPair,total_args_passed); 2789 int i=0; 2790 if( !method->is_static() ) // Pass in receiver first 2791 sig_bt[i++] = T_OBJECT; 2792 SignatureStream ss(method->signature()); 2793 for( ; !ss.at_return_type(); ss.next()) { 2794 sig_bt[i++] = ss.type(); // Collect remaining bits of signature 2795 if( ss.type() == T_LONG || ss.type() == T_DOUBLE ) 2796 sig_bt[i++] = T_VOID; // Longs & doubles take 2 Java slots 2797 } 2798 assert( i==total_args_passed, "" ); 2799 BasicType ret_type = ss.type(); 2800 2801 // Now get the compiled-Java layout as input arguments 2802 int comp_args_on_stack; 2803 comp_args_on_stack = SharedRuntime::java_calling_convention(sig_bt, regs, total_args_passed, false); 2804 2805 // Generate the compiled-to-native wrapper code 2806 nm = SharedRuntime::generate_native_wrapper(&_masm, 2807 method, 2808 compile_id, 2809 total_args_passed, 2810 comp_args_on_stack, 2811 sig_bt,regs, 2812 ret_type); 2813 } 2814 } 2815 2816 // Must unlock before calling set_code 2817 2818 // Install the generated code. 2819 if (nm != NULL) { 2820 if (PrintCompilation) { 2821 ttyLocker ttyl; 2822 CompileTask::print_compilation(tty, nm, method->is_static() ? "(static)" : ""); 2823 } 2824 method->set_code(method, nm); 2825 nm->post_compiled_method_load_event(); 2826 } else { 2827 // CodeCache is full, disable compilation 2828 CompileBroker::handle_full_code_cache(); 2829 } 2830 return nm; 2831 } 2832 2833 #ifdef HAVE_DTRACE_H 2834 // Create a dtrace nmethod for this method. The wrapper converts the 2835 // java compiled calling convention to the native convention, makes a dummy call 2836 // (actually nops for the size of the call instruction, which become a trap if 2837 // probe is enabled). The returns to the caller. Since this all looks like a 2838 // leaf no thread transition is needed. 2839 2840 nmethod *AdapterHandlerLibrary::create_dtrace_nmethod(methodHandle method) { 2841 ResourceMark rm; 2842 nmethod* nm = NULL; 2843 2844 if (PrintCompilation) { 2845 ttyLocker ttyl; 2846 tty->print("--- n%s "); 2847 method->print_short_name(tty); 2848 if (method->is_static()) { 2849 tty->print(" (static)"); 2850 } 2851 tty->cr(); 2852 } 2853 2854 { 2855 // perform the work while holding the lock, but perform any printing 2856 // outside the lock 2857 MutexLocker mu(AdapterHandlerLibrary_lock); 2858 // See if somebody beat us to it 2859 nm = method->code(); 2860 if (nm) { 2861 return nm; 2862 } 2863 2864 ResourceMark rm; 2865 2866 BufferBlob* buf = buffer_blob(); // the temporary code buffer in CodeCache 2867 if (buf != NULL) { 2868 CodeBuffer buffer(buf); 2869 // Need a few relocation entries 2870 double locs_buf[20]; 2871 buffer.insts()->initialize_shared_locs( 2872 (relocInfo*)locs_buf, sizeof(locs_buf) / sizeof(relocInfo)); 2873 MacroAssembler _masm(&buffer); 2874 2875 // Generate the compiled-to-native wrapper code 2876 nm = SharedRuntime::generate_dtrace_nmethod(&_masm, method); 2877 } 2878 } 2879 return nm; 2880 } 2881 2882 // the dtrace method needs to convert java lang string to utf8 string. 2883 void SharedRuntime::get_utf(oopDesc* src, address dst) { 2884 typeArrayOop jlsValue = java_lang_String::value(src); 2885 int jlsOffset = java_lang_String::offset(src); 2886 int jlsLen = java_lang_String::length(src); 2887 jchar* jlsPos = (jlsLen == 0) ? NULL : 2888 jlsValue->char_at_addr(jlsOffset); 2889 assert(typeArrayKlass::cast(jlsValue->klass())->element_type() == T_CHAR, "compressed string"); 2890 (void) UNICODE::as_utf8(jlsPos, jlsLen, (char *)dst, max_dtrace_string_size); 2891 } 2892 #endif // ndef HAVE_DTRACE_H 2893 2894 // ------------------------------------------------------------------------- 2895 // Java-Java calling convention 2896 // (what you use when Java calls Java) 2897 2898 //------------------------------name_for_receiver---------------------------------- 2899 // For a given signature, return the VMReg for parameter 0. 2900 VMReg SharedRuntime::name_for_receiver() { 2901 VMRegPair regs; 2902 BasicType sig_bt = T_OBJECT; 2903 (void) java_calling_convention(&sig_bt, ®s, 1, true); 2904 // Return argument 0 register. In the LP64 build pointers 2905 // take 2 registers, but the VM wants only the 'main' name. 2906 return regs.first(); 2907 } 2908 2909 VMRegPair *SharedRuntime::find_callee_arguments(Symbol* sig, bool has_receiver, int* arg_size) { 2910 // This method is returning a data structure allocating as a 2911 // ResourceObject, so do not put any ResourceMarks in here. 2912 char *s = sig->as_C_string(); 2913 int len = (int)strlen(s); 2914 *s++; len--; // Skip opening paren 2915 char *t = s+len; 2916 while( *(--t) != ')' ) ; // Find close paren 2917 2918 BasicType *sig_bt = NEW_RESOURCE_ARRAY( BasicType, 256 ); 2919 VMRegPair *regs = NEW_RESOURCE_ARRAY( VMRegPair, 256 ); 2920 int cnt = 0; 2921 if (has_receiver) { 2922 sig_bt[cnt++] = T_OBJECT; // Receiver is argument 0; not in signature 2923 } 2924 2925 while( s < t ) { 2926 switch( *s++ ) { // Switch on signature character 2927 case 'B': sig_bt[cnt++] = T_BYTE; break; 2928 case 'C': sig_bt[cnt++] = T_CHAR; break; 2929 case 'D': sig_bt[cnt++] = T_DOUBLE; sig_bt[cnt++] = T_VOID; break; 2930 case 'F': sig_bt[cnt++] = T_FLOAT; break; 2931 case 'I': sig_bt[cnt++] = T_INT; break; 2932 case 'J': sig_bt[cnt++] = T_LONG; sig_bt[cnt++] = T_VOID; break; 2933 case 'S': sig_bt[cnt++] = T_SHORT; break; 2934 case 'Z': sig_bt[cnt++] = T_BOOLEAN; break; 2935 case 'V': sig_bt[cnt++] = T_VOID; break; 2936 case 'L': // Oop 2937 while( *s++ != ';' ) ; // Skip signature 2938 sig_bt[cnt++] = T_OBJECT; 2939 break; 2940 case '[': { // Array 2941 do { // Skip optional size 2942 while( *s >= '0' && *s <= '9' ) s++; 2943 } while( *s++ == '[' ); // Nested arrays? 2944 // Skip element type 2945 if( s[-1] == 'L' ) 2946 while( *s++ != ';' ) ; // Skip signature 2947 sig_bt[cnt++] = T_ARRAY; 2948 break; 2949 } 2950 default : ShouldNotReachHere(); 2951 } 2952 } 2953 assert( cnt < 256, "grow table size" ); 2954 2955 int comp_args_on_stack; 2956 comp_args_on_stack = java_calling_convention(sig_bt, regs, cnt, true); 2957 2958 // the calling convention doesn't count out_preserve_stack_slots so 2959 // we must add that in to get "true" stack offsets. 2960 2961 if (comp_args_on_stack) { 2962 for (int i = 0; i < cnt; i++) { 2963 VMReg reg1 = regs[i].first(); 2964 if( reg1->is_stack()) { 2965 // Yuck 2966 reg1 = reg1->bias(out_preserve_stack_slots()); 2967 } 2968 VMReg reg2 = regs[i].second(); 2969 if( reg2->is_stack()) { 2970 // Yuck 2971 reg2 = reg2->bias(out_preserve_stack_slots()); 2972 } 2973 regs[i].set_pair(reg2, reg1); 2974 } 2975 } 2976 2977 // results 2978 *arg_size = cnt; 2979 return regs; 2980 } 2981 2982 // OSR Migration Code 2983 // 2984 // This code is used convert interpreter frames into compiled frames. It is 2985 // called from very start of a compiled OSR nmethod. A temp array is 2986 // allocated to hold the interesting bits of the interpreter frame. All 2987 // active locks are inflated to allow them to move. The displaced headers and 2988 // active interpeter locals are copied into the temp buffer. Then we return 2989 // back to the compiled code. The compiled code then pops the current 2990 // interpreter frame off the stack and pushes a new compiled frame. Then it 2991 // copies the interpreter locals and displaced headers where it wants. 2992 // Finally it calls back to free the temp buffer. 2993 // 2994 // All of this is done NOT at any Safepoint, nor is any safepoint or GC allowed. 2995 2996 JRT_LEAF(intptr_t*, SharedRuntime::OSR_migration_begin( JavaThread *thread) ) 2997 2998 #ifdef IA64 2999 ShouldNotReachHere(); // NYI 3000 #endif /* IA64 */ 3001 3002 // 3003 // This code is dependent on the memory layout of the interpreter local 3004 // array and the monitors. On all of our platforms the layout is identical 3005 // so this code is shared. If some platform lays the their arrays out 3006 // differently then this code could move to platform specific code or 3007 // the code here could be modified to copy items one at a time using 3008 // frame accessor methods and be platform independent. 3009 3010 frame fr = thread->last_frame(); 3011 assert( fr.is_interpreted_frame(), "" ); 3012 assert( fr.interpreter_frame_expression_stack_size()==0, "only handle empty stacks" ); 3013 3014 // Figure out how many monitors are active. 3015 int active_monitor_count = 0; 3016 for( BasicObjectLock *kptr = fr.interpreter_frame_monitor_end(); 3017 kptr < fr.interpreter_frame_monitor_begin(); 3018 kptr = fr.next_monitor_in_interpreter_frame(kptr) ) { 3019 if( kptr->obj() != NULL ) active_monitor_count++; 3020 } 3021 3022 // QQQ we could place number of active monitors in the array so that compiled code 3023 // could double check it. 3024 3025 methodOop moop = fr.interpreter_frame_method(); 3026 int max_locals = moop->max_locals(); 3027 // Allocate temp buffer, 1 word per local & 2 per active monitor 3028 int buf_size_words = max_locals + active_monitor_count*2; 3029 intptr_t *buf = NEW_C_HEAP_ARRAY(intptr_t,buf_size_words); 3030 3031 // Copy the locals. Order is preserved so that loading of longs works. 3032 // Since there's no GC I can copy the oops blindly. 3033 assert( sizeof(HeapWord)==sizeof(intptr_t), "fix this code"); 3034 Copy::disjoint_words((HeapWord*)fr.interpreter_frame_local_at(max_locals-1), 3035 (HeapWord*)&buf[0], 3036 max_locals); 3037 3038 // Inflate locks. Copy the displaced headers. Be careful, there can be holes. 3039 int i = max_locals; 3040 for( BasicObjectLock *kptr2 = fr.interpreter_frame_monitor_end(); 3041 kptr2 < fr.interpreter_frame_monitor_begin(); 3042 kptr2 = fr.next_monitor_in_interpreter_frame(kptr2) ) { 3043 if( kptr2->obj() != NULL) { // Avoid 'holes' in the monitor array 3044 BasicLock *lock = kptr2->lock(); 3045 // Inflate so the displaced header becomes position-independent 3046 if (lock->displaced_header()->is_unlocked()) 3047 ObjectSynchronizer::inflate_helper(kptr2->obj()); 3048 // Now the displaced header is free to move 3049 buf[i++] = (intptr_t)lock->displaced_header(); 3050 buf[i++] = (intptr_t)kptr2->obj(); 3051 } 3052 } 3053 assert( i - max_locals == active_monitor_count*2, "found the expected number of monitors" ); 3054 3055 return buf; 3056 JRT_END 3057 3058 JRT_LEAF(void, SharedRuntime::OSR_migration_end( intptr_t* buf) ) 3059 FREE_C_HEAP_ARRAY(intptr_t,buf); 3060 JRT_END 3061 3062 bool AdapterHandlerLibrary::contains(CodeBlob* b) { 3063 AdapterHandlerTableIterator iter(_adapters); 3064 while (iter.has_next()) { 3065 AdapterHandlerEntry* a = iter.next(); 3066 if ( b == CodeCache::find_blob(a->get_i2c_entry()) ) return true; 3067 } 3068 return false; 3069 } 3070 3071 void AdapterHandlerLibrary::print_handler_on(outputStream* st, CodeBlob* b) { 3072 AdapterHandlerTableIterator iter(_adapters); 3073 while (iter.has_next()) { 3074 AdapterHandlerEntry* a = iter.next(); 3075 if ( b == CodeCache::find_blob(a->get_i2c_entry()) ) { 3076 st->print("Adapter for signature: "); 3077 st->print_cr("%s i2c: " INTPTR_FORMAT " c2i: " INTPTR_FORMAT " c2iUV: " INTPTR_FORMAT, 3078 a->fingerprint()->as_string(), 3079 a->get_i2c_entry(), a->get_c2i_entry(), a->get_c2i_unverified_entry()); 3080 3081 return; 3082 } 3083 } 3084 assert(false, "Should have found handler"); 3085 } 3086 3087 #ifndef PRODUCT 3088 3089 void AdapterHandlerLibrary::print_statistics() { 3090 _adapters->print_statistics(); 3091 } 3092 3093 #endif /* PRODUCT */