1 /* 2 * Copyright (c) 1997, 2025, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. 8 * 9 * This code is distributed in the hope that it will be useful, but WITHOUT 10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 12 * version 2 for more details (a copy is included in the LICENSE file that 13 * accompanied this code). 14 * 15 * You should have received a copy of the GNU General Public License version 16 * 2 along with this work; if not, write to the Free Software Foundation, 17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 18 * 19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 20 * or visit www.oracle.com if you need additional information or have any 21 * questions. 22 * 23 */ 24 25 #include "cds/archiveBuilder.hpp" 26 #include "cds/archiveUtils.inline.hpp" 27 #include "classfile/classLoader.hpp" 28 #include "classfile/javaClasses.inline.hpp" 29 #include "classfile/stringTable.hpp" 30 #include "classfile/vmClasses.hpp" 31 #include "classfile/vmSymbols.hpp" 32 #include "code/aotCodeCache.hpp" 33 #include "code/codeCache.hpp" 34 #include "code/compiledIC.hpp" 35 #include "code/nmethod.inline.hpp" 36 #include "code/scopeDesc.hpp" 37 #include "code/vtableStubs.hpp" 38 #include "compiler/abstractCompiler.hpp" 39 #include "compiler/compileBroker.hpp" 40 #include "compiler/disassembler.hpp" 41 #include "gc/shared/barrierSet.hpp" 42 #include "gc/shared/collectedHeap.hpp" 43 #include "interpreter/interpreter.hpp" 44 #include "interpreter/interpreterRuntime.hpp" 45 #include "jvm.h" 46 #include "jfr/jfrEvents.hpp" 47 #include "logging/log.hpp" 48 #include "memory/resourceArea.hpp" 49 #include "memory/universe.hpp" 50 #include "metaprogramming/primitiveConversions.hpp" 51 #include "oops/klass.hpp" 52 #include "oops/method.inline.hpp" 53 #include "oops/objArrayKlass.hpp" 54 #include "oops/oop.inline.hpp" 55 #include "prims/forte.hpp" 56 #include "prims/jvmtiExport.hpp" 57 #include "prims/jvmtiThreadState.hpp" 58 #include "prims/methodHandles.hpp" 59 #include "prims/nativeLookup.hpp" 60 #include "runtime/arguments.hpp" 61 #include "runtime/atomic.hpp" 62 #include "runtime/basicLock.inline.hpp" 63 #include "runtime/frame.inline.hpp" 64 #include "runtime/handles.inline.hpp" 65 #include "runtime/init.hpp" 66 #include "runtime/interfaceSupport.inline.hpp" 67 #include "runtime/java.hpp" 68 #include "runtime/javaCalls.hpp" 69 #include "runtime/jniHandles.inline.hpp" 70 #include "runtime/perfData.hpp" 71 #include "runtime/sharedRuntime.hpp" 72 #include "runtime/stackWatermarkSet.hpp" 73 #include "runtime/stubRoutines.hpp" 74 #include "runtime/synchronizer.inline.hpp" 75 #include "runtime/timerTrace.hpp" 76 #include "runtime/vframe.inline.hpp" 77 #include "runtime/vframeArray.hpp" 78 #include "runtime/vm_version.hpp" 79 #include "utilities/copy.hpp" 80 #include "utilities/dtrace.hpp" 81 #include "utilities/events.hpp" 82 #include "utilities/globalDefinitions.hpp" 83 #include "utilities/resourceHash.hpp" 84 #include "utilities/macros.hpp" 85 #include "utilities/xmlstream.hpp" 86 #ifdef COMPILER1 87 #include "c1/c1_Runtime1.hpp" 88 #endif 89 #if INCLUDE_JFR 90 #include "jfr/jfr.inline.hpp" 91 #endif 92 93 // Shared runtime stub routines reside in their own unique blob with a 94 // single entry point 95 96 97 #define SHARED_STUB_FIELD_DEFINE(name, type) \ 98 type* SharedRuntime::BLOB_FIELD_NAME(name); 99 SHARED_STUBS_DO(SHARED_STUB_FIELD_DEFINE) 100 #undef SHARED_STUB_FIELD_DEFINE 101 102 #if 0 103 // TODO tweak global stub name generation to match this 104 #define SHARED_STUB_NAME_DECLARE(name, type) "Shared Runtime " # name "_blob", 105 const char *SharedRuntime::_stub_names[] = { 106 SHARED_STUBS_DO(SHARED_STUB_NAME_DECLARE) 107 }; 108 #endif 109 110 //----------------------------generate_stubs----------------------------------- 111 void SharedRuntime::generate_initial_stubs() { 112 // Build this early so it's available for the interpreter. 113 _throw_StackOverflowError_blob = 114 generate_throw_exception(StubId::shared_throw_StackOverflowError_id, 115 CAST_FROM_FN_PTR(address, SharedRuntime::throw_StackOverflowError)); 116 } 117 118 void SharedRuntime::generate_stubs() { 119 _wrong_method_blob = 120 generate_resolve_blob(StubId::shared_wrong_method_id, 121 CAST_FROM_FN_PTR(address, SharedRuntime::handle_wrong_method)); 122 _wrong_method_abstract_blob = 123 generate_resolve_blob(StubId::shared_wrong_method_abstract_id, 124 CAST_FROM_FN_PTR(address, SharedRuntime::handle_wrong_method_abstract)); 125 _ic_miss_blob = 126 generate_resolve_blob(StubId::shared_ic_miss_id, 127 CAST_FROM_FN_PTR(address, SharedRuntime::handle_wrong_method_ic_miss)); 128 _resolve_opt_virtual_call_blob = 129 generate_resolve_blob(StubId::shared_resolve_opt_virtual_call_id, 130 CAST_FROM_FN_PTR(address, SharedRuntime::resolve_opt_virtual_call_C)); 131 _resolve_virtual_call_blob = 132 generate_resolve_blob(StubId::shared_resolve_virtual_call_id, 133 CAST_FROM_FN_PTR(address, SharedRuntime::resolve_virtual_call_C)); 134 _resolve_static_call_blob = 135 generate_resolve_blob(StubId::shared_resolve_static_call_id, 136 CAST_FROM_FN_PTR(address, SharedRuntime::resolve_static_call_C)); 137 138 _throw_delayed_StackOverflowError_blob = 139 generate_throw_exception(StubId::shared_throw_delayed_StackOverflowError_id, 140 CAST_FROM_FN_PTR(address, SharedRuntime::throw_delayed_StackOverflowError)); 141 142 _throw_AbstractMethodError_blob = 143 generate_throw_exception(StubId::shared_throw_AbstractMethodError_id, 144 CAST_FROM_FN_PTR(address, SharedRuntime::throw_AbstractMethodError)); 145 146 _throw_IncompatibleClassChangeError_blob = 147 generate_throw_exception(StubId::shared_throw_IncompatibleClassChangeError_id, 148 CAST_FROM_FN_PTR(address, SharedRuntime::throw_IncompatibleClassChangeError)); 149 150 _throw_NullPointerException_at_call_blob = 151 generate_throw_exception(StubId::shared_throw_NullPointerException_at_call_id, 152 CAST_FROM_FN_PTR(address, SharedRuntime::throw_NullPointerException_at_call)); 153 154 #if COMPILER2_OR_JVMCI 155 // Vectors are generated only by C2 and JVMCI. 156 bool support_wide = is_wide_vector(MaxVectorSize); 157 if (support_wide) { 158 _polling_page_vectors_safepoint_handler_blob = 159 generate_handler_blob(StubId::shared_polling_page_vectors_safepoint_handler_id, 160 CAST_FROM_FN_PTR(address, SafepointSynchronize::handle_polling_page_exception)); 161 } 162 #endif // COMPILER2_OR_JVMCI 163 _polling_page_safepoint_handler_blob = 164 generate_handler_blob(StubId::shared_polling_page_safepoint_handler_id, 165 CAST_FROM_FN_PTR(address, SafepointSynchronize::handle_polling_page_exception)); 166 _polling_page_return_handler_blob = 167 generate_handler_blob(StubId::shared_polling_page_return_handler_id, 168 CAST_FROM_FN_PTR(address, SafepointSynchronize::handle_polling_page_exception)); 169 170 generate_deopt_blob(); 171 } 172 173 void SharedRuntime::init_adapter_library() { 174 AdapterHandlerLibrary::initialize(); 175 } 176 177 #if INCLUDE_JFR 178 //------------------------------generate jfr runtime stubs ------ 179 void SharedRuntime::generate_jfr_stubs() { 180 ResourceMark rm; 181 const char* timer_msg = "SharedRuntime generate_jfr_stubs"; 182 TraceTime timer(timer_msg, TRACETIME_LOG(Info, startuptime)); 183 184 _jfr_write_checkpoint_blob = generate_jfr_write_checkpoint(); 185 _jfr_return_lease_blob = generate_jfr_return_lease(); 186 } 187 188 #endif // INCLUDE_JFR 189 190 #include <math.h> 191 192 // Implementation of SharedRuntime 193 194 #ifndef PRODUCT 195 // For statistics 196 uint SharedRuntime::_ic_miss_ctr = 0; 197 uint SharedRuntime::_wrong_method_ctr = 0; 198 uint SharedRuntime::_resolve_static_ctr = 0; 199 uint SharedRuntime::_resolve_virtual_ctr = 0; 200 uint SharedRuntime::_resolve_opt_virtual_ctr = 0; 201 uint SharedRuntime::_implicit_null_throws = 0; 202 uint SharedRuntime::_implicit_div0_throws = 0; 203 204 int64_t SharedRuntime::_nof_normal_calls = 0; 205 int64_t SharedRuntime::_nof_inlined_calls = 0; 206 int64_t SharedRuntime::_nof_megamorphic_calls = 0; 207 int64_t SharedRuntime::_nof_static_calls = 0; 208 int64_t SharedRuntime::_nof_inlined_static_calls = 0; 209 int64_t SharedRuntime::_nof_interface_calls = 0; 210 int64_t SharedRuntime::_nof_inlined_interface_calls = 0; 211 212 uint SharedRuntime::_new_instance_ctr=0; 213 uint SharedRuntime::_new_array_ctr=0; 214 uint SharedRuntime::_multi2_ctr=0; 215 uint SharedRuntime::_multi3_ctr=0; 216 uint SharedRuntime::_multi4_ctr=0; 217 uint SharedRuntime::_multi5_ctr=0; 218 uint SharedRuntime::_mon_enter_stub_ctr=0; 219 uint SharedRuntime::_mon_exit_stub_ctr=0; 220 uint SharedRuntime::_mon_enter_ctr=0; 221 uint SharedRuntime::_mon_exit_ctr=0; 222 uint SharedRuntime::_partial_subtype_ctr=0; 223 uint SharedRuntime::_jbyte_array_copy_ctr=0; 224 uint SharedRuntime::_jshort_array_copy_ctr=0; 225 uint SharedRuntime::_jint_array_copy_ctr=0; 226 uint SharedRuntime::_jlong_array_copy_ctr=0; 227 uint SharedRuntime::_oop_array_copy_ctr=0; 228 uint SharedRuntime::_checkcast_array_copy_ctr=0; 229 uint SharedRuntime::_unsafe_array_copy_ctr=0; 230 uint SharedRuntime::_generic_array_copy_ctr=0; 231 uint SharedRuntime::_slow_array_copy_ctr=0; 232 uint SharedRuntime::_find_handler_ctr=0; 233 uint SharedRuntime::_rethrow_ctr=0; 234 uint SharedRuntime::_unsafe_set_memory_ctr=0; 235 236 int SharedRuntime::_ICmiss_index = 0; 237 int SharedRuntime::_ICmiss_count[SharedRuntime::maxICmiss_count]; 238 address SharedRuntime::_ICmiss_at[SharedRuntime::maxICmiss_count]; 239 240 241 void SharedRuntime::trace_ic_miss(address at) { 242 for (int i = 0; i < _ICmiss_index; i++) { 243 if (_ICmiss_at[i] == at) { 244 _ICmiss_count[i]++; 245 return; 246 } 247 } 248 int index = _ICmiss_index++; 249 if (_ICmiss_index >= maxICmiss_count) _ICmiss_index = maxICmiss_count - 1; 250 _ICmiss_at[index] = at; 251 _ICmiss_count[index] = 1; 252 } 253 254 void SharedRuntime::print_ic_miss_histogram() { 255 if (ICMissHistogram) { 256 tty->print_cr("IC Miss Histogram:"); 257 int tot_misses = 0; 258 for (int i = 0; i < _ICmiss_index; i++) { 259 tty->print_cr(" at: " INTPTR_FORMAT " nof: %d", p2i(_ICmiss_at[i]), _ICmiss_count[i]); 260 tot_misses += _ICmiss_count[i]; 261 } 262 tty->print_cr("Total IC misses: %7d", tot_misses); 263 } 264 } 265 #endif // PRODUCT 266 267 268 JRT_LEAF(jlong, SharedRuntime::lmul(jlong y, jlong x)) 269 return x * y; 270 JRT_END 271 272 273 JRT_LEAF(jlong, SharedRuntime::ldiv(jlong y, jlong x)) 274 if (x == min_jlong && y == CONST64(-1)) { 275 return x; 276 } else { 277 return x / y; 278 } 279 JRT_END 280 281 282 JRT_LEAF(jlong, SharedRuntime::lrem(jlong y, jlong x)) 283 if (x == min_jlong && y == CONST64(-1)) { 284 return 0; 285 } else { 286 return x % y; 287 } 288 JRT_END 289 290 291 #ifdef _WIN64 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 #endif 297 298 #if !defined(X86) 299 JRT_LEAF(jfloat, SharedRuntime::frem(jfloat x, jfloat y)) 300 #ifdef _WIN64 301 // 64-bit Windows on amd64 returns the wrong values for 302 // infinity operands. 303 juint xbits = PrimitiveConversions::cast<juint>(x); 304 juint ybits = PrimitiveConversions::cast<juint>(y); 305 // x Mod Infinity == x unless x is infinity 306 if (((xbits & float_sign_mask) != float_infinity) && 307 ((ybits & float_sign_mask) == float_infinity) ) { 308 return x; 309 } 310 return ((jfloat)fmod_winx64((double)x, (double)y)); 311 #else 312 return ((jfloat)fmod((double)x,(double)y)); 313 #endif 314 JRT_END 315 316 JRT_LEAF(jdouble, SharedRuntime::drem(jdouble x, jdouble y)) 317 #ifdef _WIN64 318 julong xbits = PrimitiveConversions::cast<julong>(x); 319 julong ybits = PrimitiveConversions::cast<julong>(y); 320 // x Mod Infinity == x unless x is infinity 321 if (((xbits & double_sign_mask) != double_infinity) && 322 ((ybits & double_sign_mask) == double_infinity) ) { 323 return x; 324 } 325 return ((jdouble)fmod_winx64((double)x, (double)y)); 326 #else 327 return ((jdouble)fmod((double)x,(double)y)); 328 #endif 329 JRT_END 330 #endif // !X86 331 332 JRT_LEAF(jfloat, SharedRuntime::i2f(jint x)) 333 return (jfloat)x; 334 JRT_END 335 336 #ifdef __SOFTFP__ 337 JRT_LEAF(jfloat, SharedRuntime::fadd(jfloat x, jfloat y)) 338 return x + y; 339 JRT_END 340 341 JRT_LEAF(jfloat, SharedRuntime::fsub(jfloat x, jfloat y)) 342 return x - y; 343 JRT_END 344 345 JRT_LEAF(jfloat, SharedRuntime::fmul(jfloat x, jfloat y)) 346 return x * y; 347 JRT_END 348 349 JRT_LEAF(jfloat, SharedRuntime::fdiv(jfloat x, jfloat y)) 350 return x / y; 351 JRT_END 352 353 JRT_LEAF(jdouble, SharedRuntime::dadd(jdouble x, jdouble y)) 354 return x + y; 355 JRT_END 356 357 JRT_LEAF(jdouble, SharedRuntime::dsub(jdouble x, jdouble y)) 358 return x - y; 359 JRT_END 360 361 JRT_LEAF(jdouble, SharedRuntime::dmul(jdouble x, jdouble y)) 362 return x * y; 363 JRT_END 364 365 JRT_LEAF(jdouble, SharedRuntime::ddiv(jdouble x, jdouble y)) 366 return x / y; 367 JRT_END 368 369 JRT_LEAF(jdouble, SharedRuntime::i2d(jint x)) 370 return (jdouble)x; 371 JRT_END 372 373 JRT_LEAF(jdouble, SharedRuntime::f2d(jfloat x)) 374 return (jdouble)x; 375 JRT_END 376 377 JRT_LEAF(int, SharedRuntime::fcmpl(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::fcmpg(float x, float y)) 382 return x<y ? -1 : (x==y ? 0 : 1); /* x>y or is_nan */ 383 JRT_END 384 385 JRT_LEAF(int, SharedRuntime::dcmpl(double x, double y)) 386 return x>y ? 1 : (x==y ? 0 : -1); /* x<y or is_nan */ 387 JRT_END 388 389 JRT_LEAF(int, SharedRuntime::dcmpg(double x, double y)) 390 return x<y ? -1 : (x==y ? 0 : 1); /* x>y or is_nan */ 391 JRT_END 392 393 // Functions to return the opposite of the aeabi functions for nan. 394 JRT_LEAF(int, SharedRuntime::unordered_fcmplt(float x, float y)) 395 return (x < y) ? 1 : ((g_isnan(x) || g_isnan(y)) ? 1 : 0); 396 JRT_END 397 398 JRT_LEAF(int, SharedRuntime::unordered_dcmplt(double x, double y)) 399 return (x < y) ? 1 : ((g_isnan(x) || g_isnan(y)) ? 1 : 0); 400 JRT_END 401 402 JRT_LEAF(int, SharedRuntime::unordered_fcmple(float x, float y)) 403 return (x <= y) ? 1 : ((g_isnan(x) || g_isnan(y)) ? 1 : 0); 404 JRT_END 405 406 JRT_LEAF(int, SharedRuntime::unordered_dcmple(double x, double y)) 407 return (x <= y) ? 1 : ((g_isnan(x) || g_isnan(y)) ? 1 : 0); 408 JRT_END 409 410 JRT_LEAF(int, SharedRuntime::unordered_fcmpge(float x, float y)) 411 return (x >= y) ? 1 : ((g_isnan(x) || g_isnan(y)) ? 1 : 0); 412 JRT_END 413 414 JRT_LEAF(int, SharedRuntime::unordered_dcmpge(double x, double y)) 415 return (x >= y) ? 1 : ((g_isnan(x) || g_isnan(y)) ? 1 : 0); 416 JRT_END 417 418 JRT_LEAF(int, SharedRuntime::unordered_fcmpgt(float x, float y)) 419 return (x > y) ? 1 : ((g_isnan(x) || g_isnan(y)) ? 1 : 0); 420 JRT_END 421 422 JRT_LEAF(int, SharedRuntime::unordered_dcmpgt(double x, double y)) 423 return (x > y) ? 1 : ((g_isnan(x) || g_isnan(y)) ? 1 : 0); 424 JRT_END 425 426 // Intrinsics make gcc generate code for these. 427 float SharedRuntime::fneg(float f) { 428 return -f; 429 } 430 431 double SharedRuntime::dneg(double f) { 432 return -f; 433 } 434 435 #endif // __SOFTFP__ 436 437 #if defined(__SOFTFP__) || defined(E500V2) 438 // Intrinsics make gcc generate code for these. 439 double SharedRuntime::dabs(double f) { 440 return (f <= (double)0.0) ? (double)0.0 - f : f; 441 } 442 443 #endif 444 445 #if defined(__SOFTFP__) 446 double SharedRuntime::dsqrt(double f) { 447 return sqrt(f); 448 } 449 #endif 450 451 JRT_LEAF(jint, SharedRuntime::f2i(jfloat x)) 452 if (g_isnan(x)) 453 return 0; 454 if (x >= (jfloat) max_jint) 455 return max_jint; 456 if (x <= (jfloat) min_jint) 457 return min_jint; 458 return (jint) x; 459 JRT_END 460 461 462 JRT_LEAF(jlong, SharedRuntime::f2l(jfloat x)) 463 if (g_isnan(x)) 464 return 0; 465 if (x >= (jfloat) max_jlong) 466 return max_jlong; 467 if (x <= (jfloat) min_jlong) 468 return min_jlong; 469 return (jlong) x; 470 JRT_END 471 472 473 JRT_LEAF(jint, SharedRuntime::d2i(jdouble x)) 474 if (g_isnan(x)) 475 return 0; 476 if (x >= (jdouble) max_jint) 477 return max_jint; 478 if (x <= (jdouble) min_jint) 479 return min_jint; 480 return (jint) x; 481 JRT_END 482 483 484 JRT_LEAF(jlong, SharedRuntime::d2l(jdouble x)) 485 if (g_isnan(x)) 486 return 0; 487 if (x >= (jdouble) max_jlong) 488 return max_jlong; 489 if (x <= (jdouble) min_jlong) 490 return min_jlong; 491 return (jlong) x; 492 JRT_END 493 494 495 JRT_LEAF(jfloat, SharedRuntime::d2f(jdouble x)) 496 return (jfloat)x; 497 JRT_END 498 499 500 JRT_LEAF(jfloat, SharedRuntime::l2f(jlong x)) 501 return (jfloat)x; 502 JRT_END 503 504 505 JRT_LEAF(jdouble, SharedRuntime::l2d(jlong x)) 506 return (jdouble)x; 507 JRT_END 508 509 510 // Exception handling across interpreter/compiler boundaries 511 // 512 // exception_handler_for_return_address(...) returns the continuation address. 513 // The continuation address is the entry point of the exception handler of the 514 // previous frame depending on the return address. 515 516 address SharedRuntime::raw_exception_handler_for_return_address(JavaThread* current, address return_address) { 517 // Note: This is called when we have unwound the frame of the callee that did 518 // throw an exception. So far, no check has been performed by the StackWatermarkSet. 519 // Notably, the stack is not walkable at this point, and hence the check must 520 // be deferred until later. Specifically, any of the handlers returned here in 521 // this function, will get dispatched to, and call deferred checks to 522 // StackWatermarkSet::after_unwind at a point where the stack is walkable. 523 assert(frame::verify_return_pc(return_address), "must be a return address: " INTPTR_FORMAT, p2i(return_address)); 524 assert(current->frames_to_pop_failed_realloc() == 0 || Interpreter::contains(return_address), "missed frames to pop?"); 525 526 // Reset method handle flag. 527 current->set_is_method_handle_return(false); 528 529 #if INCLUDE_JVMCI 530 // JVMCI's ExceptionHandlerStub expects the thread local exception PC to be clear 531 // and other exception handler continuations do not read it 532 current->set_exception_pc(nullptr); 533 #endif // INCLUDE_JVMCI 534 535 if (Continuation::is_return_barrier_entry(return_address)) { 536 return StubRoutines::cont_returnBarrierExc(); 537 } 538 539 // The fastest case first 540 CodeBlob* blob = CodeCache::find_blob(return_address); 541 nmethod* nm = (blob != nullptr) ? blob->as_nmethod_or_null() : nullptr; 542 if (nm != nullptr) { 543 // Set flag if return address is a method handle call site. 544 current->set_is_method_handle_return(nm->is_method_handle_return(return_address)); 545 // native nmethods don't have exception handlers 546 assert(!nm->is_native_method() || nm->method()->is_continuation_enter_intrinsic(), "no exception handler"); 547 assert(nm->header_begin() != nm->exception_begin(), "no exception handler"); 548 if (nm->is_deopt_pc(return_address)) { 549 // If we come here because of a stack overflow, the stack may be 550 // unguarded. Reguard the stack otherwise if we return to the 551 // deopt blob and the stack bang causes a stack overflow we 552 // crash. 553 StackOverflow* overflow_state = current->stack_overflow_state(); 554 bool guard_pages_enabled = overflow_state->reguard_stack_if_needed(); 555 if (overflow_state->reserved_stack_activation() != current->stack_base()) { 556 overflow_state->set_reserved_stack_activation(current->stack_base()); 557 } 558 assert(guard_pages_enabled, "stack banging in deopt blob may cause crash"); 559 // The deferred StackWatermarkSet::after_unwind check will be performed in 560 // Deoptimization::fetch_unroll_info (with exec_mode == Unpack_exception) 561 return SharedRuntime::deopt_blob()->unpack_with_exception(); 562 } else { 563 // The deferred StackWatermarkSet::after_unwind check will be performed in 564 // * OptoRuntime::handle_exception_C_helper for C2 code 565 // * exception_handler_for_pc_helper via Runtime1::handle_exception_from_callee_id for C1 code 566 return nm->exception_begin(); 567 } 568 } 569 570 // Entry code 571 if (StubRoutines::returns_to_call_stub(return_address)) { 572 // The deferred StackWatermarkSet::after_unwind check will be performed in 573 // JavaCallWrapper::~JavaCallWrapper 574 assert (StubRoutines::catch_exception_entry() != nullptr, "must be generated before"); 575 return StubRoutines::catch_exception_entry(); 576 } 577 if (blob != nullptr && blob->is_upcall_stub()) { 578 return StubRoutines::upcall_stub_exception_handler(); 579 } 580 // Interpreted code 581 if (Interpreter::contains(return_address)) { 582 // The deferred StackWatermarkSet::after_unwind check will be performed in 583 // InterpreterRuntime::exception_handler_for_exception 584 return Interpreter::rethrow_exception_entry(); 585 } 586 587 guarantee(blob == nullptr || !blob->is_runtime_stub(), "caller should have skipped stub"); 588 guarantee(!VtableStubs::contains(return_address), "null exceptions in vtables should have been handled already!"); 589 590 #ifndef PRODUCT 591 { ResourceMark rm; 592 tty->print_cr("No exception handler found for exception at " INTPTR_FORMAT " - potential problems:", p2i(return_address)); 593 os::print_location(tty, (intptr_t)return_address); 594 tty->print_cr("a) exception happened in (new?) code stubs/buffers that is not handled here"); 595 tty->print_cr("b) other problem"); 596 } 597 #endif // PRODUCT 598 ShouldNotReachHere(); 599 return nullptr; 600 } 601 602 603 JRT_LEAF(address, SharedRuntime::exception_handler_for_return_address(JavaThread* current, address return_address)) 604 return raw_exception_handler_for_return_address(current, return_address); 605 JRT_END 606 607 608 address SharedRuntime::get_poll_stub(address pc) { 609 address stub; 610 // Look up the code blob 611 CodeBlob *cb = CodeCache::find_blob(pc); 612 613 // Should be an nmethod 614 guarantee(cb != nullptr && cb->is_nmethod(), "safepoint polling: pc must refer to an nmethod"); 615 616 // Look up the relocation information 617 assert(cb->as_nmethod()->is_at_poll_or_poll_return(pc), 618 "safepoint polling: type must be poll at pc " INTPTR_FORMAT, p2i(pc)); 619 620 #ifdef ASSERT 621 if (!((NativeInstruction*)pc)->is_safepoint_poll()) { 622 tty->print_cr("bad pc: " PTR_FORMAT, p2i(pc)); 623 Disassembler::decode(cb); 624 fatal("Only polling locations are used for safepoint"); 625 } 626 #endif 627 628 bool at_poll_return = cb->as_nmethod()->is_at_poll_return(pc); 629 bool has_wide_vectors = cb->as_nmethod()->has_wide_vectors(); 630 if (at_poll_return) { 631 assert(SharedRuntime::polling_page_return_handler_blob() != nullptr, 632 "polling page return stub not created yet"); 633 stub = SharedRuntime::polling_page_return_handler_blob()->entry_point(); 634 } else if (has_wide_vectors) { 635 assert(SharedRuntime::polling_page_vectors_safepoint_handler_blob() != nullptr, 636 "polling page vectors safepoint stub not created yet"); 637 stub = SharedRuntime::polling_page_vectors_safepoint_handler_blob()->entry_point(); 638 } else { 639 assert(SharedRuntime::polling_page_safepoint_handler_blob() != nullptr, 640 "polling page safepoint stub not created yet"); 641 stub = SharedRuntime::polling_page_safepoint_handler_blob()->entry_point(); 642 } 643 log_debug(safepoint)("... found polling page %s exception at pc = " 644 INTPTR_FORMAT ", stub =" INTPTR_FORMAT, 645 at_poll_return ? "return" : "loop", 646 (intptr_t)pc, (intptr_t)stub); 647 return stub; 648 } 649 650 void SharedRuntime::throw_and_post_jvmti_exception(JavaThread* current, Handle h_exception) { 651 if (JvmtiExport::can_post_on_exceptions()) { 652 vframeStream vfst(current, true); 653 methodHandle method = methodHandle(current, vfst.method()); 654 address bcp = method()->bcp_from(vfst.bci()); 655 JvmtiExport::post_exception_throw(current, method(), bcp, h_exception()); 656 } 657 658 #if INCLUDE_JVMCI 659 if (EnableJVMCI) { 660 vframeStream vfst(current, true); 661 methodHandle method = methodHandle(current, vfst.method()); 662 int bci = vfst.bci(); 663 MethodData* trap_mdo = method->method_data(); 664 if (trap_mdo != nullptr) { 665 // Set exception_seen if the exceptional bytecode is an invoke 666 Bytecode_invoke call = Bytecode_invoke_check(method, bci); 667 if (call.is_valid()) { 668 ResourceMark rm(current); 669 670 // Lock to read ProfileData, and ensure lock is not broken by a safepoint 671 MutexLocker ml(trap_mdo->extra_data_lock(), Mutex::_no_safepoint_check_flag); 672 673 ProfileData* pdata = trap_mdo->allocate_bci_to_data(bci, nullptr); 674 if (pdata != nullptr && pdata->is_BitData()) { 675 BitData* bit_data = (BitData*) pdata; 676 bit_data->set_exception_seen(); 677 } 678 } 679 } 680 } 681 #endif 682 683 Exceptions::_throw(current, __FILE__, __LINE__, h_exception); 684 } 685 686 void SharedRuntime::throw_and_post_jvmti_exception(JavaThread* current, Symbol* name, const char *message) { 687 Handle h_exception = Exceptions::new_exception(current, name, message); 688 throw_and_post_jvmti_exception(current, h_exception); 689 } 690 691 #if INCLUDE_JVMTI 692 JRT_ENTRY(void, SharedRuntime::notify_jvmti_vthread_start(oopDesc* vt, jboolean hide, JavaThread* current)) 693 assert(hide == JNI_FALSE, "must be VTMS transition finish"); 694 jobject vthread = JNIHandles::make_local(const_cast<oopDesc*>(vt)); 695 JvmtiVTMSTransitionDisabler::VTMS_vthread_start(vthread); 696 JNIHandles::destroy_local(vthread); 697 JRT_END 698 699 JRT_ENTRY(void, SharedRuntime::notify_jvmti_vthread_end(oopDesc* vt, jboolean hide, JavaThread* current)) 700 assert(hide == JNI_TRUE, "must be VTMS transition start"); 701 jobject vthread = JNIHandles::make_local(const_cast<oopDesc*>(vt)); 702 JvmtiVTMSTransitionDisabler::VTMS_vthread_end(vthread); 703 JNIHandles::destroy_local(vthread); 704 JRT_END 705 706 JRT_ENTRY(void, SharedRuntime::notify_jvmti_vthread_mount(oopDesc* vt, jboolean hide, JavaThread* current)) 707 jobject vthread = JNIHandles::make_local(const_cast<oopDesc*>(vt)); 708 JvmtiVTMSTransitionDisabler::VTMS_vthread_mount(vthread, hide); 709 JNIHandles::destroy_local(vthread); 710 JRT_END 711 712 JRT_ENTRY(void, SharedRuntime::notify_jvmti_vthread_unmount(oopDesc* vt, jboolean hide, JavaThread* current)) 713 jobject vthread = JNIHandles::make_local(const_cast<oopDesc*>(vt)); 714 JvmtiVTMSTransitionDisabler::VTMS_vthread_unmount(vthread, hide); 715 JNIHandles::destroy_local(vthread); 716 JRT_END 717 #endif // INCLUDE_JVMTI 718 719 // The interpreter code to call this tracing function is only 720 // called/generated when UL is on for redefine, class and has the right level 721 // and tags. Since obsolete methods are never compiled, we don't have 722 // to modify the compilers to generate calls to this function. 723 // 724 JRT_LEAF(int, SharedRuntime::rc_trace_method_entry( 725 JavaThread* thread, Method* method)) 726 if (method->is_obsolete()) { 727 // We are calling an obsolete method, but this is not necessarily 728 // an error. Our method could have been redefined just after we 729 // fetched the Method* from the constant pool. 730 ResourceMark rm; 731 log_trace(redefine, class, obsolete)("calling obsolete method '%s'", method->name_and_sig_as_C_string()); 732 } 733 return 0; 734 JRT_END 735 736 // ret_pc points into caller; we are returning caller's exception handler 737 // for given exception 738 // Note that the implementation of this method assumes it's only called when an exception has actually occured 739 address SharedRuntime::compute_compiled_exc_handler(nmethod* nm, address ret_pc, Handle& exception, 740 bool force_unwind, bool top_frame_only, bool& recursive_exception_occurred) { 741 assert(nm != nullptr, "must exist"); 742 ResourceMark rm; 743 744 #if INCLUDE_JVMCI 745 if (nm->is_compiled_by_jvmci()) { 746 // lookup exception handler for this pc 747 int catch_pco = pointer_delta_as_int(ret_pc, nm->code_begin()); 748 ExceptionHandlerTable table(nm); 749 HandlerTableEntry *t = table.entry_for(catch_pco, -1, 0); 750 if (t != nullptr) { 751 return nm->code_begin() + t->pco(); 752 } else { 753 return Deoptimization::deoptimize_for_missing_exception_handler(nm); 754 } 755 } 756 #endif // INCLUDE_JVMCI 757 758 ScopeDesc* sd = nm->scope_desc_at(ret_pc); 759 // determine handler bci, if any 760 EXCEPTION_MARK; 761 762 int handler_bci = -1; 763 int scope_depth = 0; 764 if (!force_unwind) { 765 int bci = sd->bci(); 766 bool recursive_exception = false; 767 do { 768 bool skip_scope_increment = false; 769 // exception handler lookup 770 Klass* ek = exception->klass(); 771 methodHandle mh(THREAD, sd->method()); 772 handler_bci = Method::fast_exception_handler_bci_for(mh, ek, bci, THREAD); 773 if (HAS_PENDING_EXCEPTION) { 774 recursive_exception = true; 775 // We threw an exception while trying to find the exception handler. 776 // Transfer the new exception to the exception handle which will 777 // be set into thread local storage, and do another lookup for an 778 // exception handler for this exception, this time starting at the 779 // BCI of the exception handler which caused the exception to be 780 // thrown (bugs 4307310 and 4546590). Set "exception" reference 781 // argument to ensure that the correct exception is thrown (4870175). 782 recursive_exception_occurred = true; 783 exception = Handle(THREAD, PENDING_EXCEPTION); 784 CLEAR_PENDING_EXCEPTION; 785 if (handler_bci >= 0) { 786 bci = handler_bci; 787 handler_bci = -1; 788 skip_scope_increment = true; 789 } 790 } 791 else { 792 recursive_exception = false; 793 } 794 if (!top_frame_only && handler_bci < 0 && !skip_scope_increment) { 795 sd = sd->sender(); 796 if (sd != nullptr) { 797 bci = sd->bci(); 798 } 799 ++scope_depth; 800 } 801 } while (recursive_exception || (!top_frame_only && handler_bci < 0 && sd != nullptr)); 802 } 803 804 // found handling method => lookup exception handler 805 int catch_pco = pointer_delta_as_int(ret_pc, nm->code_begin()); 806 807 ExceptionHandlerTable table(nm); 808 HandlerTableEntry *t = table.entry_for(catch_pco, handler_bci, scope_depth); 809 if (t == nullptr && (nm->is_compiled_by_c1() || handler_bci != -1)) { 810 // Allow abbreviated catch tables. The idea is to allow a method 811 // to materialize its exceptions without committing to the exact 812 // routing of exceptions. In particular this is needed for adding 813 // a synthetic handler to unlock monitors when inlining 814 // synchronized methods since the unlock path isn't represented in 815 // the bytecodes. 816 t = table.entry_for(catch_pco, -1, 0); 817 } 818 819 #ifdef COMPILER1 820 if (t == nullptr && nm->is_compiled_by_c1()) { 821 assert(nm->unwind_handler_begin() != nullptr, ""); 822 return nm->unwind_handler_begin(); 823 } 824 #endif 825 826 if (t == nullptr) { 827 ttyLocker ttyl; 828 tty->print_cr("MISSING EXCEPTION HANDLER for pc " INTPTR_FORMAT " and handler bci %d, catch_pco: %d", p2i(ret_pc), handler_bci, catch_pco); 829 tty->print_cr(" Exception:"); 830 exception->print(); 831 tty->cr(); 832 tty->print_cr(" Compiled exception table :"); 833 table.print(); 834 nm->print(); 835 nm->print_code(); 836 guarantee(false, "missing exception handler"); 837 return nullptr; 838 } 839 840 if (handler_bci != -1) { // did we find a handler in this method? 841 sd->method()->set_exception_handler_entered(handler_bci); // profile 842 } 843 return nm->code_begin() + t->pco(); 844 } 845 846 JRT_ENTRY(void, SharedRuntime::throw_AbstractMethodError(JavaThread* current)) 847 // These errors occur only at call sites 848 throw_and_post_jvmti_exception(current, vmSymbols::java_lang_AbstractMethodError()); 849 JRT_END 850 851 JRT_ENTRY(void, SharedRuntime::throw_IncompatibleClassChangeError(JavaThread* current)) 852 // These errors occur only at call sites 853 throw_and_post_jvmti_exception(current, vmSymbols::java_lang_IncompatibleClassChangeError(), "vtable stub"); 854 JRT_END 855 856 JRT_ENTRY(void, SharedRuntime::throw_ArithmeticException(JavaThread* current)) 857 throw_and_post_jvmti_exception(current, vmSymbols::java_lang_ArithmeticException(), "/ by zero"); 858 JRT_END 859 860 JRT_ENTRY(void, SharedRuntime::throw_NullPointerException(JavaThread* current)) 861 throw_and_post_jvmti_exception(current, vmSymbols::java_lang_NullPointerException(), nullptr); 862 JRT_END 863 864 JRT_ENTRY(void, SharedRuntime::throw_NullPointerException_at_call(JavaThread* current)) 865 // This entry point is effectively only used for NullPointerExceptions which occur at inline 866 // cache sites (when the callee activation is not yet set up) so we are at a call site 867 throw_and_post_jvmti_exception(current, vmSymbols::java_lang_NullPointerException(), nullptr); 868 JRT_END 869 870 JRT_ENTRY(void, SharedRuntime::throw_StackOverflowError(JavaThread* current)) 871 throw_StackOverflowError_common(current, false); 872 JRT_END 873 874 JRT_ENTRY(void, SharedRuntime::throw_delayed_StackOverflowError(JavaThread* current)) 875 throw_StackOverflowError_common(current, true); 876 JRT_END 877 878 void SharedRuntime::throw_StackOverflowError_common(JavaThread* current, bool delayed) { 879 // We avoid using the normal exception construction in this case because 880 // it performs an upcall to Java, and we're already out of stack space. 881 JavaThread* THREAD = current; // For exception macros. 882 Klass* k = vmClasses::StackOverflowError_klass(); 883 oop exception_oop = InstanceKlass::cast(k)->allocate_instance(CHECK); 884 if (delayed) { 885 java_lang_Throwable::set_message(exception_oop, 886 Universe::delayed_stack_overflow_error_message()); 887 } 888 Handle exception (current, exception_oop); 889 if (StackTraceInThrowable) { 890 java_lang_Throwable::fill_in_stack_trace(exception); 891 } 892 // Remove the ScopedValue bindings in case we got a 893 // StackOverflowError while we were trying to remove ScopedValue 894 // bindings. 895 current->clear_scopedValueBindings(); 896 // Increment counter for hs_err file reporting 897 Atomic::inc(&Exceptions::_stack_overflow_errors); 898 throw_and_post_jvmti_exception(current, exception); 899 } 900 901 address SharedRuntime::continuation_for_implicit_exception(JavaThread* current, 902 address pc, 903 ImplicitExceptionKind exception_kind) 904 { 905 address target_pc = nullptr; 906 907 if (Interpreter::contains(pc)) { 908 switch (exception_kind) { 909 case IMPLICIT_NULL: return Interpreter::throw_NullPointerException_entry(); 910 case IMPLICIT_DIVIDE_BY_ZERO: return Interpreter::throw_ArithmeticException_entry(); 911 case STACK_OVERFLOW: return Interpreter::throw_StackOverflowError_entry(); 912 default: ShouldNotReachHere(); 913 } 914 } else { 915 switch (exception_kind) { 916 case STACK_OVERFLOW: { 917 // Stack overflow only occurs upon frame setup; the callee is 918 // going to be unwound. Dispatch to a shared runtime stub 919 // which will cause the StackOverflowError to be fabricated 920 // and processed. 921 // Stack overflow should never occur during deoptimization: 922 // the compiled method bangs the stack by as much as the 923 // interpreter would need in case of a deoptimization. The 924 // deoptimization blob and uncommon trap blob bang the stack 925 // in a debug VM to verify the correctness of the compiled 926 // method stack banging. 927 assert(current->deopt_mark() == nullptr, "no stack overflow from deopt blob/uncommon trap"); 928 Events::log_exception(current, "StackOverflowError at " INTPTR_FORMAT, p2i(pc)); 929 return SharedRuntime::throw_StackOverflowError_entry(); 930 } 931 932 case IMPLICIT_NULL: { 933 if (VtableStubs::contains(pc)) { 934 // We haven't yet entered the callee frame. Fabricate an 935 // exception and begin dispatching it in the caller. Since 936 // the caller was at a call site, it's safe to destroy all 937 // caller-saved registers, as these entry points do. 938 VtableStub* vt_stub = VtableStubs::stub_containing(pc); 939 940 // If vt_stub is null, then return null to signal handler to report the SEGV error. 941 if (vt_stub == nullptr) return nullptr; 942 943 if (vt_stub->is_abstract_method_error(pc)) { 944 assert(!vt_stub->is_vtable_stub(), "should never see AbstractMethodErrors from vtable-type VtableStubs"); 945 Events::log_exception(current, "AbstractMethodError at " INTPTR_FORMAT, p2i(pc)); 946 // Instead of throwing the abstract method error here directly, we re-resolve 947 // and will throw the AbstractMethodError during resolve. As a result, we'll 948 // get a more detailed error message. 949 return SharedRuntime::get_handle_wrong_method_stub(); 950 } else { 951 Events::log_exception(current, "NullPointerException at vtable entry " INTPTR_FORMAT, p2i(pc)); 952 // Assert that the signal comes from the expected location in stub code. 953 assert(vt_stub->is_null_pointer_exception(pc), 954 "obtained signal from unexpected location in stub code"); 955 return SharedRuntime::throw_NullPointerException_at_call_entry(); 956 } 957 } else { 958 CodeBlob* cb = CodeCache::find_blob(pc); 959 960 // If code blob is null, then return null to signal handler to report the SEGV error. 961 if (cb == nullptr) return nullptr; 962 963 // Exception happened in CodeCache. Must be either: 964 // 1. Inline-cache check in C2I handler blob, 965 // 2. Inline-cache check in nmethod, or 966 // 3. Implicit null exception in nmethod 967 968 if (!cb->is_nmethod()) { 969 bool is_in_blob = cb->is_adapter_blob() || cb->is_method_handles_adapter_blob(); 970 if (!is_in_blob) { 971 // Allow normal crash reporting to handle this 972 return nullptr; 973 } 974 Events::log_exception(current, "NullPointerException in code blob at " INTPTR_FORMAT, p2i(pc)); 975 // There is no handler here, so we will simply unwind. 976 return SharedRuntime::throw_NullPointerException_at_call_entry(); 977 } 978 979 // Otherwise, it's a compiled method. Consult its exception handlers. 980 nmethod* nm = cb->as_nmethod(); 981 if (nm->inlinecache_check_contains(pc)) { 982 // exception happened inside inline-cache check code 983 // => the nmethod is not yet active (i.e., the frame 984 // is not set up yet) => use return address pushed by 985 // caller => don't push another return address 986 Events::log_exception(current, "NullPointerException in IC check " INTPTR_FORMAT, p2i(pc)); 987 return SharedRuntime::throw_NullPointerException_at_call_entry(); 988 } 989 990 if (nm->method()->is_method_handle_intrinsic()) { 991 // exception happened inside MH dispatch code, similar to a vtable stub 992 Events::log_exception(current, "NullPointerException in MH adapter " INTPTR_FORMAT, p2i(pc)); 993 return SharedRuntime::throw_NullPointerException_at_call_entry(); 994 } 995 996 #ifndef PRODUCT 997 _implicit_null_throws++; 998 #endif 999 target_pc = nm->continuation_for_implicit_null_exception(pc); 1000 // If there's an unexpected fault, target_pc might be null, 1001 // in which case we want to fall through into the normal 1002 // error handling code. 1003 } 1004 1005 break; // fall through 1006 } 1007 1008 1009 case IMPLICIT_DIVIDE_BY_ZERO: { 1010 nmethod* nm = CodeCache::find_nmethod(pc); 1011 guarantee(nm != nullptr, "must have containing compiled method for implicit division-by-zero exceptions"); 1012 #ifndef PRODUCT 1013 _implicit_div0_throws++; 1014 #endif 1015 target_pc = nm->continuation_for_implicit_div0_exception(pc); 1016 // If there's an unexpected fault, target_pc might be null, 1017 // in which case we want to fall through into the normal 1018 // error handling code. 1019 break; // fall through 1020 } 1021 1022 default: ShouldNotReachHere(); 1023 } 1024 1025 assert(exception_kind == IMPLICIT_NULL || exception_kind == IMPLICIT_DIVIDE_BY_ZERO, "wrong implicit exception kind"); 1026 1027 if (exception_kind == IMPLICIT_NULL) { 1028 #ifndef PRODUCT 1029 // for AbortVMOnException flag 1030 Exceptions::debug_check_abort("java.lang.NullPointerException"); 1031 #endif //PRODUCT 1032 Events::log_exception(current, "Implicit null exception at " INTPTR_FORMAT " to " INTPTR_FORMAT, p2i(pc), p2i(target_pc)); 1033 } else { 1034 #ifndef PRODUCT 1035 // for AbortVMOnException flag 1036 Exceptions::debug_check_abort("java.lang.ArithmeticException"); 1037 #endif //PRODUCT 1038 Events::log_exception(current, "Implicit division by zero exception at " INTPTR_FORMAT " to " INTPTR_FORMAT, p2i(pc), p2i(target_pc)); 1039 } 1040 return target_pc; 1041 } 1042 1043 ShouldNotReachHere(); 1044 return nullptr; 1045 } 1046 1047 1048 /** 1049 * Throws an java/lang/UnsatisfiedLinkError. The address of this method is 1050 * installed in the native function entry of all native Java methods before 1051 * they get linked to their actual native methods. 1052 * 1053 * \note 1054 * This method actually never gets called! The reason is because 1055 * the interpreter's native entries call NativeLookup::lookup() which 1056 * throws the exception when the lookup fails. The exception is then 1057 * caught and forwarded on the return from NativeLookup::lookup() call 1058 * before the call to the native function. This might change in the future. 1059 */ 1060 JNI_ENTRY(void*, throw_unsatisfied_link_error(JNIEnv* env, ...)) 1061 { 1062 // We return a bad value here to make sure that the exception is 1063 // forwarded before we look at the return value. 1064 THROW_(vmSymbols::java_lang_UnsatisfiedLinkError(), (void*)badAddress); 1065 } 1066 JNI_END 1067 1068 address SharedRuntime::native_method_throw_unsatisfied_link_error_entry() { 1069 return CAST_FROM_FN_PTR(address, &throw_unsatisfied_link_error); 1070 } 1071 1072 JRT_ENTRY_NO_ASYNC(void, SharedRuntime::register_finalizer(JavaThread* current, oopDesc* obj)) 1073 #if INCLUDE_JVMCI 1074 if (!obj->klass()->has_finalizer()) { 1075 return; 1076 } 1077 #endif // INCLUDE_JVMCI 1078 assert(oopDesc::is_oop(obj), "must be a valid oop"); 1079 assert(obj->klass()->has_finalizer(), "shouldn't be here otherwise"); 1080 InstanceKlass::register_finalizer(instanceOop(obj), CHECK); 1081 JRT_END 1082 1083 jlong SharedRuntime::get_java_tid(JavaThread* thread) { 1084 assert(thread != nullptr, "No thread"); 1085 if (thread == nullptr) { 1086 return 0; 1087 } 1088 guarantee(Thread::current() != thread || thread->is_oop_safe(), 1089 "current cannot touch oops after its GC barrier is detached."); 1090 oop obj = thread->threadObj(); 1091 return (obj == nullptr) ? 0 : java_lang_Thread::thread_id(obj); 1092 } 1093 1094 /** 1095 * This function ought to be a void function, but cannot be because 1096 * it gets turned into a tail-call on sparc, which runs into dtrace bug 1097 * 6254741. Once that is fixed we can remove the dummy return value. 1098 */ 1099 int SharedRuntime::dtrace_object_alloc(oopDesc* o) { 1100 return dtrace_object_alloc(JavaThread::current(), o, o->size()); 1101 } 1102 1103 int SharedRuntime::dtrace_object_alloc(JavaThread* thread, oopDesc* o) { 1104 return dtrace_object_alloc(thread, o, o->size()); 1105 } 1106 1107 int SharedRuntime::dtrace_object_alloc(JavaThread* thread, oopDesc* o, size_t size) { 1108 assert(DTraceAllocProbes, "wrong call"); 1109 Klass* klass = o->klass(); 1110 Symbol* name = klass->name(); 1111 HOTSPOT_OBJECT_ALLOC( 1112 get_java_tid(thread), 1113 (char *) name->bytes(), name->utf8_length(), size * HeapWordSize); 1114 return 0; 1115 } 1116 1117 JRT_LEAF(int, SharedRuntime::dtrace_method_entry( 1118 JavaThread* current, Method* method)) 1119 assert(current == JavaThread::current(), "pre-condition"); 1120 1121 assert(DTraceMethodProbes, "wrong call"); 1122 Symbol* kname = method->klass_name(); 1123 Symbol* name = method->name(); 1124 Symbol* sig = method->signature(); 1125 HOTSPOT_METHOD_ENTRY( 1126 get_java_tid(current), 1127 (char *) kname->bytes(), kname->utf8_length(), 1128 (char *) name->bytes(), name->utf8_length(), 1129 (char *) sig->bytes(), sig->utf8_length()); 1130 return 0; 1131 JRT_END 1132 1133 JRT_LEAF(int, SharedRuntime::dtrace_method_exit( 1134 JavaThread* current, Method* method)) 1135 assert(current == JavaThread::current(), "pre-condition"); 1136 assert(DTraceMethodProbes, "wrong call"); 1137 Symbol* kname = method->klass_name(); 1138 Symbol* name = method->name(); 1139 Symbol* sig = method->signature(); 1140 HOTSPOT_METHOD_RETURN( 1141 get_java_tid(current), 1142 (char *) kname->bytes(), kname->utf8_length(), 1143 (char *) name->bytes(), name->utf8_length(), 1144 (char *) sig->bytes(), sig->utf8_length()); 1145 return 0; 1146 JRT_END 1147 1148 1149 // Finds receiver, CallInfo (i.e. receiver method), and calling bytecode) 1150 // for a call current in progress, i.e., arguments has been pushed on stack 1151 // put callee has not been invoked yet. Used by: resolve virtual/static, 1152 // vtable updates, etc. Caller frame must be compiled. 1153 Handle SharedRuntime::find_callee_info(Bytecodes::Code& bc, CallInfo& callinfo, TRAPS) { 1154 JavaThread* current = THREAD; 1155 ResourceMark rm(current); 1156 1157 // last java frame on stack (which includes native call frames) 1158 vframeStream vfst(current, true); // Do not skip and javaCalls 1159 1160 return find_callee_info_helper(vfst, bc, callinfo, THREAD); 1161 } 1162 1163 Method* SharedRuntime::extract_attached_method(vframeStream& vfst) { 1164 nmethod* caller = vfst.nm(); 1165 1166 address pc = vfst.frame_pc(); 1167 { // Get call instruction under lock because another thread may be busy patching it. 1168 CompiledICLocker ic_locker(caller); 1169 return caller->attached_method_before_pc(pc); 1170 } 1171 return nullptr; 1172 } 1173 1174 // Finds receiver, CallInfo (i.e. receiver method), and calling bytecode 1175 // for a call current in progress, i.e., arguments has been pushed on stack 1176 // but callee has not been invoked yet. Caller frame must be compiled. 1177 Handle SharedRuntime::find_callee_info_helper(vframeStream& vfst, Bytecodes::Code& bc, 1178 CallInfo& callinfo, TRAPS) { 1179 Handle receiver; 1180 Handle nullHandle; // create a handy null handle for exception returns 1181 JavaThread* current = THREAD; 1182 1183 assert(!vfst.at_end(), "Java frame must exist"); 1184 1185 // Find caller and bci from vframe 1186 methodHandle caller(current, vfst.method()); 1187 int bci = vfst.bci(); 1188 1189 if (caller->is_continuation_enter_intrinsic()) { 1190 bc = Bytecodes::_invokestatic; 1191 LinkResolver::resolve_continuation_enter(callinfo, CHECK_NH); 1192 return receiver; 1193 } 1194 1195 Bytecode_invoke bytecode(caller, bci); 1196 int bytecode_index = bytecode.index(); 1197 bc = bytecode.invoke_code(); 1198 1199 methodHandle attached_method(current, extract_attached_method(vfst)); 1200 if (attached_method.not_null()) { 1201 Method* callee = bytecode.static_target(CHECK_NH); 1202 vmIntrinsics::ID id = callee->intrinsic_id(); 1203 // When VM replaces MH.invokeBasic/linkTo* call with a direct/virtual call, 1204 // it attaches statically resolved method to the call site. 1205 if (MethodHandles::is_signature_polymorphic(id) && 1206 MethodHandles::is_signature_polymorphic_intrinsic(id)) { 1207 bc = MethodHandles::signature_polymorphic_intrinsic_bytecode(id); 1208 1209 // Adjust invocation mode according to the attached method. 1210 switch (bc) { 1211 case Bytecodes::_invokevirtual: 1212 if (attached_method->method_holder()->is_interface()) { 1213 bc = Bytecodes::_invokeinterface; 1214 } 1215 break; 1216 case Bytecodes::_invokeinterface: 1217 if (!attached_method->method_holder()->is_interface()) { 1218 bc = Bytecodes::_invokevirtual; 1219 } 1220 break; 1221 case Bytecodes::_invokehandle: 1222 if (!MethodHandles::is_signature_polymorphic_method(attached_method())) { 1223 bc = attached_method->is_static() ? Bytecodes::_invokestatic 1224 : Bytecodes::_invokevirtual; 1225 } 1226 break; 1227 default: 1228 break; 1229 } 1230 } 1231 } 1232 1233 assert(bc != Bytecodes::_illegal, "not initialized"); 1234 1235 bool has_receiver = bc != Bytecodes::_invokestatic && 1236 bc != Bytecodes::_invokedynamic && 1237 bc != Bytecodes::_invokehandle; 1238 1239 // Find receiver for non-static call 1240 if (has_receiver) { 1241 // This register map must be update since we need to find the receiver for 1242 // compiled frames. The receiver might be in a register. 1243 RegisterMap reg_map2(current, 1244 RegisterMap::UpdateMap::include, 1245 RegisterMap::ProcessFrames::include, 1246 RegisterMap::WalkContinuation::skip); 1247 frame stubFrame = current->last_frame(); 1248 // Caller-frame is a compiled frame 1249 frame callerFrame = stubFrame.sender(®_map2); 1250 1251 if (attached_method.is_null()) { 1252 Method* callee = bytecode.static_target(CHECK_NH); 1253 if (callee == nullptr) { 1254 THROW_(vmSymbols::java_lang_NoSuchMethodException(), nullHandle); 1255 } 1256 } 1257 1258 // Retrieve from a compiled argument list 1259 receiver = Handle(current, callerFrame.retrieve_receiver(®_map2)); 1260 assert(oopDesc::is_oop_or_null(receiver()), ""); 1261 1262 if (receiver.is_null()) { 1263 THROW_(vmSymbols::java_lang_NullPointerException(), nullHandle); 1264 } 1265 } 1266 1267 // Resolve method 1268 if (attached_method.not_null()) { 1269 // Parameterized by attached method. 1270 LinkResolver::resolve_invoke(callinfo, receiver, attached_method, bc, CHECK_NH); 1271 } else { 1272 // Parameterized by bytecode. 1273 constantPoolHandle constants(current, caller->constants()); 1274 LinkResolver::resolve_invoke(callinfo, receiver, constants, bytecode_index, bc, CHECK_NH); 1275 } 1276 1277 #ifdef ASSERT 1278 // Check that the receiver klass is of the right subtype and that it is initialized for virtual calls 1279 if (has_receiver) { 1280 assert(receiver.not_null(), "should have thrown exception"); 1281 Klass* receiver_klass = receiver->klass(); 1282 Klass* rk = nullptr; 1283 if (attached_method.not_null()) { 1284 // In case there's resolved method attached, use its holder during the check. 1285 rk = attached_method->method_holder(); 1286 } else { 1287 // Klass is already loaded. 1288 constantPoolHandle constants(current, caller->constants()); 1289 rk = constants->klass_ref_at(bytecode_index, bc, CHECK_NH); 1290 } 1291 Klass* static_receiver_klass = rk; 1292 assert(receiver_klass->is_subtype_of(static_receiver_klass), 1293 "actual receiver must be subclass of static receiver klass"); 1294 if (receiver_klass->is_instance_klass()) { 1295 if (InstanceKlass::cast(receiver_klass)->is_not_initialized()) { 1296 tty->print_cr("ERROR: Klass not yet initialized!!"); 1297 receiver_klass->print(); 1298 } 1299 assert(!InstanceKlass::cast(receiver_klass)->is_not_initialized(), "receiver_klass must be initialized"); 1300 } 1301 } 1302 #endif 1303 1304 return receiver; 1305 } 1306 1307 methodHandle SharedRuntime::find_callee_method(TRAPS) { 1308 JavaThread* current = THREAD; 1309 ResourceMark rm(current); 1310 // We need first to check if any Java activations (compiled, interpreted) 1311 // exist on the stack since last JavaCall. If not, we need 1312 // to get the target method from the JavaCall wrapper. 1313 vframeStream vfst(current, true); // Do not skip any javaCalls 1314 methodHandle callee_method; 1315 if (vfst.at_end()) { 1316 // No Java frames were found on stack since we did the JavaCall. 1317 // Hence the stack can only contain an entry_frame. We need to 1318 // find the target method from the stub frame. 1319 RegisterMap reg_map(current, 1320 RegisterMap::UpdateMap::skip, 1321 RegisterMap::ProcessFrames::include, 1322 RegisterMap::WalkContinuation::skip); 1323 frame fr = current->last_frame(); 1324 assert(fr.is_runtime_frame(), "must be a runtimeStub"); 1325 fr = fr.sender(®_map); 1326 assert(fr.is_entry_frame(), "must be"); 1327 // fr is now pointing to the entry frame. 1328 callee_method = methodHandle(current, fr.entry_frame_call_wrapper()->callee_method()); 1329 } else { 1330 Bytecodes::Code bc; 1331 CallInfo callinfo; 1332 find_callee_info_helper(vfst, bc, callinfo, CHECK_(methodHandle())); 1333 callee_method = methodHandle(current, callinfo.selected_method()); 1334 } 1335 assert(callee_method()->is_method(), "must be"); 1336 return callee_method; 1337 } 1338 1339 // Resolves a call. 1340 methodHandle SharedRuntime::resolve_helper(bool is_virtual, bool is_optimized, TRAPS) { 1341 JavaThread* current = THREAD; 1342 ResourceMark rm(current); 1343 RegisterMap cbl_map(current, 1344 RegisterMap::UpdateMap::skip, 1345 RegisterMap::ProcessFrames::include, 1346 RegisterMap::WalkContinuation::skip); 1347 frame caller_frame = current->last_frame().sender(&cbl_map); 1348 1349 CodeBlob* caller_cb = caller_frame.cb(); 1350 guarantee(caller_cb != nullptr && caller_cb->is_nmethod(), "must be called from compiled method"); 1351 nmethod* caller_nm = caller_cb->as_nmethod(); 1352 1353 // determine call info & receiver 1354 // note: a) receiver is null for static calls 1355 // b) an exception is thrown if receiver is null for non-static calls 1356 CallInfo call_info; 1357 Bytecodes::Code invoke_code = Bytecodes::_illegal; 1358 Handle receiver = find_callee_info(invoke_code, call_info, CHECK_(methodHandle())); 1359 1360 NoSafepointVerifier nsv; 1361 1362 methodHandle callee_method(current, call_info.selected_method()); 1363 1364 assert((!is_virtual && invoke_code == Bytecodes::_invokestatic ) || 1365 (!is_virtual && invoke_code == Bytecodes::_invokespecial) || 1366 (!is_virtual && invoke_code == Bytecodes::_invokehandle ) || 1367 (!is_virtual && invoke_code == Bytecodes::_invokedynamic) || 1368 ( is_virtual && invoke_code != Bytecodes::_invokestatic ), "inconsistent bytecode"); 1369 1370 assert(!caller_nm->is_unloading(), "It should not be unloading"); 1371 1372 #ifndef PRODUCT 1373 // tracing/debugging/statistics 1374 uint *addr = (is_optimized) ? (&_resolve_opt_virtual_ctr) : 1375 (is_virtual) ? (&_resolve_virtual_ctr) : 1376 (&_resolve_static_ctr); 1377 Atomic::inc(addr); 1378 1379 if (TraceCallFixup) { 1380 ResourceMark rm(current); 1381 tty->print("resolving %s%s (%s) call to", 1382 (is_optimized) ? "optimized " : "", (is_virtual) ? "virtual" : "static", 1383 Bytecodes::name(invoke_code)); 1384 callee_method->print_short_name(tty); 1385 tty->print_cr(" at pc: " INTPTR_FORMAT " to code: " INTPTR_FORMAT, 1386 p2i(caller_frame.pc()), p2i(callee_method->code())); 1387 } 1388 #endif 1389 1390 if (invoke_code == Bytecodes::_invokestatic) { 1391 assert(callee_method->method_holder()->is_initialized() || 1392 callee_method->method_holder()->is_reentrant_initialization(current), 1393 "invalid class initialization state for invoke_static"); 1394 if (!VM_Version::supports_fast_class_init_checks() && callee_method->needs_clinit_barrier()) { 1395 // In order to keep class initialization check, do not patch call 1396 // site for static call when the class is not fully initialized. 1397 // Proper check is enforced by call site re-resolution on every invocation. 1398 // 1399 // When fast class initialization checks are supported (VM_Version::supports_fast_class_init_checks() == true), 1400 // explicit class initialization check is put in nmethod entry (VEP). 1401 assert(callee_method->method_holder()->is_linked(), "must be"); 1402 return callee_method; 1403 } 1404 } 1405 1406 1407 // JSR 292 key invariant: 1408 // If the resolved method is a MethodHandle invoke target, the call 1409 // site must be a MethodHandle call site, because the lambda form might tail-call 1410 // leaving the stack in a state unknown to either caller or callee 1411 1412 // Compute entry points. The computation of the entry points is independent of 1413 // patching the call. 1414 1415 // Make sure the callee nmethod does not get deoptimized and removed before 1416 // we are done patching the code. 1417 1418 1419 CompiledICLocker ml(caller_nm); 1420 if (is_virtual && !is_optimized) { 1421 CompiledIC* inline_cache = CompiledIC_before(caller_nm, caller_frame.pc()); 1422 inline_cache->update(&call_info, receiver->klass()); 1423 } else { 1424 // Callsite is a direct call - set it to the destination method 1425 CompiledDirectCall* callsite = CompiledDirectCall::before(caller_frame.pc()); 1426 callsite->set(callee_method); 1427 } 1428 1429 return callee_method; 1430 } 1431 1432 // Inline caches exist only in compiled code 1433 JRT_BLOCK_ENTRY(address, SharedRuntime::handle_wrong_method_ic_miss(JavaThread* current)) 1434 #ifdef ASSERT 1435 RegisterMap reg_map(current, 1436 RegisterMap::UpdateMap::skip, 1437 RegisterMap::ProcessFrames::include, 1438 RegisterMap::WalkContinuation::skip); 1439 frame stub_frame = current->last_frame(); 1440 assert(stub_frame.is_runtime_frame(), "sanity check"); 1441 frame caller_frame = stub_frame.sender(®_map); 1442 assert(!caller_frame.is_interpreted_frame() && !caller_frame.is_entry_frame() && !caller_frame.is_upcall_stub_frame(), "unexpected frame"); 1443 #endif /* ASSERT */ 1444 1445 methodHandle callee_method; 1446 JRT_BLOCK 1447 callee_method = SharedRuntime::handle_ic_miss_helper(CHECK_NULL); 1448 // Return Method* through TLS 1449 current->set_vm_result_metadata(callee_method()); 1450 JRT_BLOCK_END 1451 // return compiled code entry point after potential safepoints 1452 return get_resolved_entry(current, callee_method); 1453 JRT_END 1454 1455 1456 // Handle call site that has been made non-entrant 1457 JRT_BLOCK_ENTRY(address, SharedRuntime::handle_wrong_method(JavaThread* current)) 1458 // 6243940 We might end up in here if the callee is deoptimized 1459 // as we race to call it. We don't want to take a safepoint if 1460 // the caller was interpreted because the caller frame will look 1461 // interpreted to the stack walkers and arguments are now 1462 // "compiled" so it is much better to make this transition 1463 // invisible to the stack walking code. The i2c path will 1464 // place the callee method in the callee_target. It is stashed 1465 // there because if we try and find the callee by normal means a 1466 // safepoint is possible and have trouble gc'ing the compiled args. 1467 RegisterMap reg_map(current, 1468 RegisterMap::UpdateMap::skip, 1469 RegisterMap::ProcessFrames::include, 1470 RegisterMap::WalkContinuation::skip); 1471 frame stub_frame = current->last_frame(); 1472 assert(stub_frame.is_runtime_frame(), "sanity check"); 1473 frame caller_frame = stub_frame.sender(®_map); 1474 1475 if (caller_frame.is_interpreted_frame() || 1476 caller_frame.is_entry_frame() || 1477 caller_frame.is_upcall_stub_frame()) { 1478 Method* callee = current->callee_target(); 1479 guarantee(callee != nullptr && callee->is_method(), "bad handshake"); 1480 current->set_vm_result_metadata(callee); 1481 current->set_callee_target(nullptr); 1482 if (caller_frame.is_entry_frame() && VM_Version::supports_fast_class_init_checks()) { 1483 // Bypass class initialization checks in c2i when caller is in native. 1484 // JNI calls to static methods don't have class initialization checks. 1485 // Fast class initialization checks are present in c2i adapters and call into 1486 // SharedRuntime::handle_wrong_method() on the slow path. 1487 // 1488 // JVM upcalls may land here as well, but there's a proper check present in 1489 // LinkResolver::resolve_static_call (called from JavaCalls::call_static), 1490 // so bypassing it in c2i adapter is benign. 1491 return callee->get_c2i_no_clinit_check_entry(); 1492 } else { 1493 return callee->get_c2i_entry(); 1494 } 1495 } 1496 1497 // Must be compiled to compiled path which is safe to stackwalk 1498 methodHandle callee_method; 1499 JRT_BLOCK 1500 // Force resolving of caller (if we called from compiled frame) 1501 callee_method = SharedRuntime::reresolve_call_site(CHECK_NULL); 1502 current->set_vm_result_metadata(callee_method()); 1503 JRT_BLOCK_END 1504 // return compiled code entry point after potential safepoints 1505 return get_resolved_entry(current, callee_method); 1506 JRT_END 1507 1508 // Handle abstract method call 1509 JRT_BLOCK_ENTRY(address, SharedRuntime::handle_wrong_method_abstract(JavaThread* current)) 1510 // Verbose error message for AbstractMethodError. 1511 // Get the called method from the invoke bytecode. 1512 vframeStream vfst(current, true); 1513 assert(!vfst.at_end(), "Java frame must exist"); 1514 methodHandle caller(current, vfst.method()); 1515 Bytecode_invoke invoke(caller, vfst.bci()); 1516 DEBUG_ONLY( invoke.verify(); ) 1517 1518 // Find the compiled caller frame. 1519 RegisterMap reg_map(current, 1520 RegisterMap::UpdateMap::include, 1521 RegisterMap::ProcessFrames::include, 1522 RegisterMap::WalkContinuation::skip); 1523 frame stubFrame = current->last_frame(); 1524 assert(stubFrame.is_runtime_frame(), "must be"); 1525 frame callerFrame = stubFrame.sender(®_map); 1526 assert(callerFrame.is_compiled_frame(), "must be"); 1527 1528 // Install exception and return forward entry. 1529 address res = SharedRuntime::throw_AbstractMethodError_entry(); 1530 JRT_BLOCK 1531 methodHandle callee(current, invoke.static_target(current)); 1532 if (!callee.is_null()) { 1533 oop recv = callerFrame.retrieve_receiver(®_map); 1534 Klass *recv_klass = (recv != nullptr) ? recv->klass() : nullptr; 1535 res = StubRoutines::forward_exception_entry(); 1536 LinkResolver::throw_abstract_method_error(callee, recv_klass, CHECK_(res)); 1537 } 1538 JRT_BLOCK_END 1539 return res; 1540 JRT_END 1541 1542 // return verified_code_entry if interp_only_mode is not set for the current thread; 1543 // otherwise return c2i entry. 1544 address SharedRuntime::get_resolved_entry(JavaThread* current, methodHandle callee_method) { 1545 if (current->is_interp_only_mode() && !callee_method->is_special_native_intrinsic()) { 1546 // In interp_only_mode we need to go to the interpreted entry 1547 // The c2i won't patch in this mode -- see fixup_callers_callsite 1548 return callee_method->get_c2i_entry(); 1549 } 1550 assert(callee_method->verified_code_entry() != nullptr, " Jump to zero!"); 1551 return callee_method->verified_code_entry(); 1552 } 1553 1554 // resolve a static call and patch code 1555 JRT_BLOCK_ENTRY(address, SharedRuntime::resolve_static_call_C(JavaThread* current )) 1556 methodHandle callee_method; 1557 bool enter_special = false; 1558 JRT_BLOCK 1559 callee_method = SharedRuntime::resolve_helper(false, false, CHECK_NULL); 1560 current->set_vm_result_metadata(callee_method()); 1561 JRT_BLOCK_END 1562 // return compiled code entry point after potential safepoints 1563 return get_resolved_entry(current, callee_method); 1564 JRT_END 1565 1566 // resolve virtual call and update inline cache to monomorphic 1567 JRT_BLOCK_ENTRY(address, SharedRuntime::resolve_virtual_call_C(JavaThread* current)) 1568 methodHandle callee_method; 1569 JRT_BLOCK 1570 callee_method = SharedRuntime::resolve_helper(true, false, CHECK_NULL); 1571 current->set_vm_result_metadata(callee_method()); 1572 JRT_BLOCK_END 1573 // return compiled code entry point after potential safepoints 1574 return get_resolved_entry(current, callee_method); 1575 JRT_END 1576 1577 1578 // Resolve a virtual call that can be statically bound (e.g., always 1579 // monomorphic, so it has no inline cache). Patch code to resolved target. 1580 JRT_BLOCK_ENTRY(address, SharedRuntime::resolve_opt_virtual_call_C(JavaThread* current)) 1581 methodHandle callee_method; 1582 JRT_BLOCK 1583 callee_method = SharedRuntime::resolve_helper(true, true, CHECK_NULL); 1584 current->set_vm_result_metadata(callee_method()); 1585 JRT_BLOCK_END 1586 // return compiled code entry point after potential safepoints 1587 return get_resolved_entry(current, callee_method); 1588 JRT_END 1589 1590 methodHandle SharedRuntime::handle_ic_miss_helper(TRAPS) { 1591 JavaThread* current = THREAD; 1592 ResourceMark rm(current); 1593 CallInfo call_info; 1594 Bytecodes::Code bc; 1595 1596 // receiver is null for static calls. An exception is thrown for null 1597 // receivers for non-static calls 1598 Handle receiver = find_callee_info(bc, call_info, CHECK_(methodHandle())); 1599 1600 methodHandle callee_method(current, call_info.selected_method()); 1601 1602 #ifndef PRODUCT 1603 Atomic::inc(&_ic_miss_ctr); 1604 1605 // Statistics & Tracing 1606 if (TraceCallFixup) { 1607 ResourceMark rm(current); 1608 tty->print("IC miss (%s) call to", Bytecodes::name(bc)); 1609 callee_method->print_short_name(tty); 1610 tty->print_cr(" code: " INTPTR_FORMAT, p2i(callee_method->code())); 1611 } 1612 1613 if (ICMissHistogram) { 1614 MutexLocker m(VMStatistic_lock); 1615 RegisterMap reg_map(current, 1616 RegisterMap::UpdateMap::skip, 1617 RegisterMap::ProcessFrames::include, 1618 RegisterMap::WalkContinuation::skip); 1619 frame f = current->last_frame().real_sender(®_map);// skip runtime stub 1620 // produce statistics under the lock 1621 trace_ic_miss(f.pc()); 1622 } 1623 #endif 1624 1625 // install an event collector so that when a vtable stub is created the 1626 // profiler can be notified via a DYNAMIC_CODE_GENERATED event. The 1627 // event can't be posted when the stub is created as locks are held 1628 // - instead the event will be deferred until the event collector goes 1629 // out of scope. 1630 JvmtiDynamicCodeEventCollector event_collector; 1631 1632 // Update inline cache to megamorphic. Skip update if we are called from interpreted. 1633 RegisterMap reg_map(current, 1634 RegisterMap::UpdateMap::skip, 1635 RegisterMap::ProcessFrames::include, 1636 RegisterMap::WalkContinuation::skip); 1637 frame caller_frame = current->last_frame().sender(®_map); 1638 CodeBlob* cb = caller_frame.cb(); 1639 nmethod* caller_nm = cb->as_nmethod(); 1640 1641 CompiledICLocker ml(caller_nm); 1642 CompiledIC* inline_cache = CompiledIC_before(caller_nm, caller_frame.pc()); 1643 inline_cache->update(&call_info, receiver()->klass()); 1644 1645 return callee_method; 1646 } 1647 1648 // 1649 // Resets a call-site in compiled code so it will get resolved again. 1650 // This routines handles both virtual call sites, optimized virtual call 1651 // sites, and static call sites. Typically used to change a call sites 1652 // destination from compiled to interpreted. 1653 // 1654 methodHandle SharedRuntime::reresolve_call_site(TRAPS) { 1655 JavaThread* current = THREAD; 1656 ResourceMark rm(current); 1657 RegisterMap reg_map(current, 1658 RegisterMap::UpdateMap::skip, 1659 RegisterMap::ProcessFrames::include, 1660 RegisterMap::WalkContinuation::skip); 1661 frame stub_frame = current->last_frame(); 1662 assert(stub_frame.is_runtime_frame(), "must be a runtimeStub"); 1663 frame caller = stub_frame.sender(®_map); 1664 1665 // Do nothing if the frame isn't a live compiled frame. 1666 // nmethod could be deoptimized by the time we get here 1667 // so no update to the caller is needed. 1668 1669 if ((caller.is_compiled_frame() && !caller.is_deoptimized_frame()) || 1670 (caller.is_native_frame() && caller.cb()->as_nmethod()->method()->is_continuation_enter_intrinsic())) { 1671 1672 address pc = caller.pc(); 1673 1674 nmethod* caller_nm = CodeCache::find_nmethod(pc); 1675 assert(caller_nm != nullptr, "did not find caller nmethod"); 1676 1677 // Default call_addr is the location of the "basic" call. 1678 // Determine the address of the call we a reresolving. With 1679 // Inline Caches we will always find a recognizable call. 1680 // With Inline Caches disabled we may or may not find a 1681 // recognizable call. We will always find a call for static 1682 // calls and for optimized virtual calls. For vanilla virtual 1683 // calls it depends on the state of the UseInlineCaches switch. 1684 // 1685 // With Inline Caches disabled we can get here for a virtual call 1686 // for two reasons: 1687 // 1 - calling an abstract method. The vtable for abstract methods 1688 // will run us thru handle_wrong_method and we will eventually 1689 // end up in the interpreter to throw the ame. 1690 // 2 - a racing deoptimization. We could be doing a vanilla vtable 1691 // call and between the time we fetch the entry address and 1692 // we jump to it the target gets deoptimized. Similar to 1 1693 // we will wind up in the interprter (thru a c2i with c2). 1694 // 1695 CompiledICLocker ml(caller_nm); 1696 address call_addr = caller_nm->call_instruction_address(pc); 1697 1698 if (call_addr != nullptr) { 1699 // On x86 the logic for finding a call instruction is blindly checking for a call opcode 5 1700 // bytes back in the instruction stream so we must also check for reloc info. 1701 RelocIterator iter(caller_nm, call_addr, call_addr+1); 1702 bool ret = iter.next(); // Get item 1703 if (ret) { 1704 switch (iter.type()) { 1705 case relocInfo::static_call_type: 1706 case relocInfo::opt_virtual_call_type: { 1707 CompiledDirectCall* cdc = CompiledDirectCall::at(call_addr); 1708 cdc->set_to_clean(); 1709 break; 1710 } 1711 1712 case relocInfo::virtual_call_type: { 1713 // compiled, dispatched call (which used to call an interpreted method) 1714 CompiledIC* inline_cache = CompiledIC_at(caller_nm, call_addr); 1715 inline_cache->set_to_clean(); 1716 break; 1717 } 1718 default: 1719 break; 1720 } 1721 } 1722 } 1723 } 1724 1725 methodHandle callee_method = find_callee_method(CHECK_(methodHandle())); 1726 1727 1728 #ifndef PRODUCT 1729 Atomic::inc(&_wrong_method_ctr); 1730 1731 if (TraceCallFixup) { 1732 ResourceMark rm(current); 1733 tty->print("handle_wrong_method reresolving call to"); 1734 callee_method->print_short_name(tty); 1735 tty->print_cr(" code: " INTPTR_FORMAT, p2i(callee_method->code())); 1736 } 1737 #endif 1738 1739 return callee_method; 1740 } 1741 1742 address SharedRuntime::handle_unsafe_access(JavaThread* thread, address next_pc) { 1743 // The faulting unsafe accesses should be changed to throw the error 1744 // synchronously instead. Meanwhile the faulting instruction will be 1745 // skipped over (effectively turning it into a no-op) and an 1746 // asynchronous exception will be raised which the thread will 1747 // handle at a later point. If the instruction is a load it will 1748 // return garbage. 1749 1750 // Request an async exception. 1751 thread->set_pending_unsafe_access_error(); 1752 1753 // Return address of next instruction to execute. 1754 return next_pc; 1755 } 1756 1757 #ifdef ASSERT 1758 void SharedRuntime::check_member_name_argument_is_last_argument(const methodHandle& method, 1759 const BasicType* sig_bt, 1760 const VMRegPair* regs) { 1761 ResourceMark rm; 1762 const int total_args_passed = method->size_of_parameters(); 1763 const VMRegPair* regs_with_member_name = regs; 1764 VMRegPair* regs_without_member_name = NEW_RESOURCE_ARRAY(VMRegPair, total_args_passed - 1); 1765 1766 const int member_arg_pos = total_args_passed - 1; 1767 assert(member_arg_pos >= 0 && member_arg_pos < total_args_passed, "oob"); 1768 assert(sig_bt[member_arg_pos] == T_OBJECT, "dispatch argument must be an object"); 1769 1770 java_calling_convention(sig_bt, regs_without_member_name, total_args_passed - 1); 1771 1772 for (int i = 0; i < member_arg_pos; i++) { 1773 VMReg a = regs_with_member_name[i].first(); 1774 VMReg b = regs_without_member_name[i].first(); 1775 assert(a->value() == b->value(), "register allocation mismatch: a= %d, b= %d", a->value(), b->value()); 1776 } 1777 assert(regs_with_member_name[member_arg_pos].first()->is_valid(), "bad member arg"); 1778 } 1779 #endif 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 JRT_LEAF(void, SharedRuntime::fixup_callers_callsite(Method* method, address caller_pc)) 1788 AARCH64_PORT_ONLY(assert(pauth_ptr_is_raw(caller_pc), "should be raw")); 1789 1790 // It's possible that deoptimization can occur at a call site which hasn't 1791 // been resolved yet, in which case this function will be called from 1792 // an nmethod that has been patched for deopt and we can ignore the 1793 // request for a fixup. 1794 // Also it is possible that we lost a race in that from_compiled_entry 1795 // is now back to the i2c in that case we don't need to patch and if 1796 // we did we'd leap into space because the callsite needs to use 1797 // "to interpreter" stub in order to load up the Method*. Don't 1798 // ask me how I know this... 1799 1800 // Result from nmethod::is_unloading is not stable across safepoints. 1801 NoSafepointVerifier nsv; 1802 1803 nmethod* callee = method->code(); 1804 if (callee == nullptr) { 1805 return; 1806 } 1807 1808 // write lock needed because we might patch call site by set_to_clean() 1809 // and is_unloading() can modify nmethod's state 1810 MACOS_AARCH64_ONLY(ThreadWXEnable __wx(WXWrite, JavaThread::current())); 1811 1812 CodeBlob* cb = CodeCache::find_blob(caller_pc); 1813 if (cb == nullptr || !cb->is_nmethod() || !callee->is_in_use() || callee->is_unloading()) { 1814 return; 1815 } 1816 1817 // The check above makes sure this is an nmethod. 1818 nmethod* caller = cb->as_nmethod(); 1819 1820 // Get the return PC for the passed caller PC. 1821 address return_pc = caller_pc + frame::pc_return_offset; 1822 1823 if (!caller->is_in_use() || !NativeCall::is_call_before(return_pc)) { 1824 return; 1825 } 1826 1827 // Expect to find a native call there (unless it was no-inline cache vtable dispatch) 1828 CompiledICLocker ic_locker(caller); 1829 ResourceMark rm; 1830 1831 // If we got here through a static call or opt_virtual call, then we know where the 1832 // call address would be; let's peek at it 1833 address callsite_addr = (address)nativeCall_before(return_pc); 1834 RelocIterator iter(caller, callsite_addr, callsite_addr + 1); 1835 if (!iter.next()) { 1836 // No reloc entry found; not a static or optimized virtual call 1837 return; 1838 } 1839 1840 relocInfo::relocType type = iter.reloc()->type(); 1841 if (type != relocInfo::static_call_type && 1842 type != relocInfo::opt_virtual_call_type) { 1843 return; 1844 } 1845 1846 CompiledDirectCall* callsite = CompiledDirectCall::before(return_pc); 1847 callsite->set_to_clean(); 1848 JRT_END 1849 1850 1851 // same as JVM_Arraycopy, but called directly from compiled code 1852 JRT_ENTRY(void, SharedRuntime::slow_arraycopy_C(oopDesc* src, jint src_pos, 1853 oopDesc* dest, jint dest_pos, 1854 jint length, 1855 JavaThread* current)) { 1856 #ifndef PRODUCT 1857 _slow_array_copy_ctr++; 1858 #endif 1859 // Check if we have null pointers 1860 if (src == nullptr || dest == nullptr) { 1861 THROW(vmSymbols::java_lang_NullPointerException()); 1862 } 1863 // Do the copy. The casts to arrayOop are necessary to the copy_array API, 1864 // even though the copy_array API also performs dynamic checks to ensure 1865 // that src and dest are truly arrays (and are conformable). 1866 // The copy_array mechanism is awkward and could be removed, but 1867 // the compilers don't call this function except as a last resort, 1868 // so it probably doesn't matter. 1869 src->klass()->copy_array((arrayOopDesc*)src, src_pos, 1870 (arrayOopDesc*)dest, dest_pos, 1871 length, current); 1872 } 1873 JRT_END 1874 1875 // The caller of generate_class_cast_message() (or one of its callers) 1876 // must use a ResourceMark in order to correctly free the result. 1877 char* SharedRuntime::generate_class_cast_message( 1878 JavaThread* thread, Klass* caster_klass) { 1879 1880 // Get target class name from the checkcast instruction 1881 vframeStream vfst(thread, true); 1882 assert(!vfst.at_end(), "Java frame must exist"); 1883 Bytecode_checkcast cc(vfst.method(), vfst.method()->bcp_from(vfst.bci())); 1884 constantPoolHandle cpool(thread, vfst.method()->constants()); 1885 Klass* target_klass = ConstantPool::klass_at_if_loaded(cpool, cc.index()); 1886 Symbol* target_klass_name = nullptr; 1887 if (target_klass == nullptr) { 1888 // This klass should be resolved, but just in case, get the name in the klass slot. 1889 target_klass_name = cpool->klass_name_at(cc.index()); 1890 } 1891 return generate_class_cast_message(caster_klass, target_klass, target_klass_name); 1892 } 1893 1894 1895 // The caller of generate_class_cast_message() (or one of its callers) 1896 // must use a ResourceMark in order to correctly free the result. 1897 char* SharedRuntime::generate_class_cast_message( 1898 Klass* caster_klass, Klass* target_klass, Symbol* target_klass_name) { 1899 const char* caster_name = caster_klass->external_name(); 1900 1901 assert(target_klass != nullptr || target_klass_name != nullptr, "one must be provided"); 1902 const char* target_name = target_klass == nullptr ? target_klass_name->as_klass_external_name() : 1903 target_klass->external_name(); 1904 1905 size_t msglen = strlen(caster_name) + strlen("class ") + strlen(" cannot be cast to class ") + strlen(target_name) + 1; 1906 1907 const char* caster_klass_description = ""; 1908 const char* target_klass_description = ""; 1909 const char* klass_separator = ""; 1910 if (target_klass != nullptr && caster_klass->module() == target_klass->module()) { 1911 caster_klass_description = caster_klass->joint_in_module_of_loader(target_klass); 1912 } else { 1913 caster_klass_description = caster_klass->class_in_module_of_loader(); 1914 target_klass_description = (target_klass != nullptr) ? target_klass->class_in_module_of_loader() : ""; 1915 klass_separator = (target_klass != nullptr) ? "; " : ""; 1916 } 1917 1918 // add 3 for parenthesis and preceding space 1919 msglen += strlen(caster_klass_description) + strlen(target_klass_description) + strlen(klass_separator) + 3; 1920 1921 char* message = NEW_RESOURCE_ARRAY_RETURN_NULL(char, msglen); 1922 if (message == nullptr) { 1923 // Shouldn't happen, but don't cause even more problems if it does 1924 message = const_cast<char*>(caster_klass->external_name()); 1925 } else { 1926 jio_snprintf(message, 1927 msglen, 1928 "class %s cannot be cast to class %s (%s%s%s)", 1929 caster_name, 1930 target_name, 1931 caster_klass_description, 1932 klass_separator, 1933 target_klass_description 1934 ); 1935 } 1936 return message; 1937 } 1938 1939 JRT_LEAF(void, SharedRuntime::reguard_yellow_pages()) 1940 (void) JavaThread::current()->stack_overflow_state()->reguard_stack(); 1941 JRT_END 1942 1943 void SharedRuntime::monitor_enter_helper(oopDesc* obj, BasicLock* lock, JavaThread* current) { 1944 if (!SafepointSynchronize::is_synchronizing()) { 1945 // Only try quick_enter() if we're not trying to reach a safepoint 1946 // so that the calling thread reaches the safepoint more quickly. 1947 if (ObjectSynchronizer::quick_enter(obj, lock, current)) { 1948 return; 1949 } 1950 } 1951 // NO_ASYNC required because an async exception on the state transition destructor 1952 // would leave you with the lock held and it would never be released. 1953 // The normal monitorenter NullPointerException is thrown without acquiring a lock 1954 // and the model is that an exception implies the method failed. 1955 JRT_BLOCK_NO_ASYNC 1956 Handle h_obj(THREAD, obj); 1957 ObjectSynchronizer::enter(h_obj, lock, current); 1958 assert(!HAS_PENDING_EXCEPTION, "Should have no exception here"); 1959 JRT_BLOCK_END 1960 } 1961 1962 // Handles the uncommon case in locking, i.e., contention or an inflated lock. 1963 JRT_BLOCK_ENTRY(void, SharedRuntime::complete_monitor_locking_C(oopDesc* obj, BasicLock* lock, JavaThread* current)) 1964 SharedRuntime::monitor_enter_helper(obj, lock, current); 1965 JRT_END 1966 1967 void SharedRuntime::monitor_exit_helper(oopDesc* obj, BasicLock* lock, JavaThread* current) { 1968 assert(JavaThread::current() == current, "invariant"); 1969 // Exit must be non-blocking, and therefore no exceptions can be thrown. 1970 ExceptionMark em(current); 1971 1972 // Check if C2_MacroAssembler::fast_unlock() or 1973 // C2_MacroAssembler::fast_unlock_lightweight() unlocked an inflated 1974 // monitor before going slow path. Since there is no safepoint 1975 // polling when calling into the VM, we can be sure that the monitor 1976 // hasn't been deallocated. 1977 ObjectMonitor* m = current->unlocked_inflated_monitor(); 1978 if (m != nullptr) { 1979 assert(!m->has_owner(current), "must be"); 1980 current->clear_unlocked_inflated_monitor(); 1981 1982 // We need to reacquire the lock before we can call ObjectSynchronizer::exit(). 1983 if (!m->try_enter(current, /*check_for_recursion*/ false)) { 1984 // Some other thread acquired the lock (or the monitor was 1985 // deflated). Either way we are done. 1986 current->dec_held_monitor_count(); 1987 return; 1988 } 1989 } 1990 1991 // The object could become unlocked through a JNI call, which we have no other checks for. 1992 // Give a fatal message if CheckJNICalls. Otherwise we ignore it. 1993 if (obj->is_unlocked()) { 1994 if (CheckJNICalls) { 1995 fatal("Object has been unlocked by JNI"); 1996 } 1997 return; 1998 } 1999 ObjectSynchronizer::exit(obj, lock, current); 2000 } 2001 2002 // Handles the uncommon cases of monitor unlocking in compiled code 2003 JRT_LEAF(void, SharedRuntime::complete_monitor_unlocking_C(oopDesc* obj, BasicLock* lock, JavaThread* current)) 2004 assert(current == JavaThread::current(), "pre-condition"); 2005 SharedRuntime::monitor_exit_helper(obj, lock, current); 2006 JRT_END 2007 2008 // This is only called when CheckJNICalls is true, and only 2009 // for virtual thread termination. 2010 JRT_LEAF(void, SharedRuntime::log_jni_monitor_still_held()) 2011 assert(CheckJNICalls, "Only call this when checking JNI usage"); 2012 if (log_is_enabled(Debug, jni)) { 2013 JavaThread* current = JavaThread::current(); 2014 int64_t vthread_id = java_lang_Thread::thread_id(current->vthread()); 2015 int64_t carrier_id = java_lang_Thread::thread_id(current->threadObj()); 2016 log_debug(jni)("VirtualThread (tid: " INT64_FORMAT ", carrier id: " INT64_FORMAT 2017 ") exiting with Objects still locked by JNI MonitorEnter.", 2018 vthread_id, carrier_id); 2019 } 2020 JRT_END 2021 2022 #ifndef PRODUCT 2023 2024 void SharedRuntime::print_statistics() { 2025 ttyLocker ttyl; 2026 if (xtty != nullptr) xtty->head("statistics type='SharedRuntime'"); 2027 2028 SharedRuntime::print_ic_miss_histogram(); 2029 2030 // Dump the JRT_ENTRY counters 2031 if (_new_instance_ctr) tty->print_cr("%5u new instance requires GC", _new_instance_ctr); 2032 if (_new_array_ctr) tty->print_cr("%5u new array requires GC", _new_array_ctr); 2033 if (_multi2_ctr) tty->print_cr("%5u multianewarray 2 dim", _multi2_ctr); 2034 if (_multi3_ctr) tty->print_cr("%5u multianewarray 3 dim", _multi3_ctr); 2035 if (_multi4_ctr) tty->print_cr("%5u multianewarray 4 dim", _multi4_ctr); 2036 if (_multi5_ctr) tty->print_cr("%5u multianewarray 5 dim", _multi5_ctr); 2037 2038 tty->print_cr("%5u inline cache miss in compiled", _ic_miss_ctr); 2039 tty->print_cr("%5u wrong method", _wrong_method_ctr); 2040 tty->print_cr("%5u unresolved static call site", _resolve_static_ctr); 2041 tty->print_cr("%5u unresolved virtual call site", _resolve_virtual_ctr); 2042 tty->print_cr("%5u unresolved opt virtual call site", _resolve_opt_virtual_ctr); 2043 2044 if (_mon_enter_stub_ctr) tty->print_cr("%5u monitor enter stub", _mon_enter_stub_ctr); 2045 if (_mon_exit_stub_ctr) tty->print_cr("%5u monitor exit stub", _mon_exit_stub_ctr); 2046 if (_mon_enter_ctr) tty->print_cr("%5u monitor enter slow", _mon_enter_ctr); 2047 if (_mon_exit_ctr) tty->print_cr("%5u monitor exit slow", _mon_exit_ctr); 2048 if (_partial_subtype_ctr) tty->print_cr("%5u slow partial subtype", _partial_subtype_ctr); 2049 if (_jbyte_array_copy_ctr) tty->print_cr("%5u byte array copies", _jbyte_array_copy_ctr); 2050 if (_jshort_array_copy_ctr) tty->print_cr("%5u short array copies", _jshort_array_copy_ctr); 2051 if (_jint_array_copy_ctr) tty->print_cr("%5u int array copies", _jint_array_copy_ctr); 2052 if (_jlong_array_copy_ctr) tty->print_cr("%5u long array copies", _jlong_array_copy_ctr); 2053 if (_oop_array_copy_ctr) tty->print_cr("%5u oop array copies", _oop_array_copy_ctr); 2054 if (_checkcast_array_copy_ctr) tty->print_cr("%5u checkcast array copies", _checkcast_array_copy_ctr); 2055 if (_unsafe_array_copy_ctr) tty->print_cr("%5u unsafe array copies", _unsafe_array_copy_ctr); 2056 if (_generic_array_copy_ctr) tty->print_cr("%5u generic array copies", _generic_array_copy_ctr); 2057 if (_slow_array_copy_ctr) tty->print_cr("%5u slow array copies", _slow_array_copy_ctr); 2058 if (_find_handler_ctr) tty->print_cr("%5u find exception handler", _find_handler_ctr); 2059 if (_rethrow_ctr) tty->print_cr("%5u rethrow handler", _rethrow_ctr); 2060 if (_unsafe_set_memory_ctr) tty->print_cr("%5u unsafe set memorys", _unsafe_set_memory_ctr); 2061 2062 AdapterHandlerLibrary::print_statistics(); 2063 2064 if (xtty != nullptr) xtty->tail("statistics"); 2065 } 2066 2067 inline double percent(int64_t x, int64_t y) { 2068 return 100.0 * (double)x / (double)MAX2(y, (int64_t)1); 2069 } 2070 2071 class MethodArityHistogram { 2072 public: 2073 enum { MAX_ARITY = 256 }; 2074 private: 2075 static uint64_t _arity_histogram[MAX_ARITY]; // histogram of #args 2076 static uint64_t _size_histogram[MAX_ARITY]; // histogram of arg size in words 2077 static uint64_t _total_compiled_calls; 2078 static uint64_t _max_compiled_calls_per_method; 2079 static int _max_arity; // max. arity seen 2080 static int _max_size; // max. arg size seen 2081 2082 static void add_method_to_histogram(nmethod* nm) { 2083 Method* method = (nm == nullptr) ? nullptr : nm->method(); 2084 if (method != nullptr) { 2085 ArgumentCount args(method->signature()); 2086 int arity = args.size() + (method->is_static() ? 0 : 1); 2087 int argsize = method->size_of_parameters(); 2088 arity = MIN2(arity, MAX_ARITY-1); 2089 argsize = MIN2(argsize, MAX_ARITY-1); 2090 uint64_t count = (uint64_t)method->compiled_invocation_count(); 2091 _max_compiled_calls_per_method = count > _max_compiled_calls_per_method ? count : _max_compiled_calls_per_method; 2092 _total_compiled_calls += count; 2093 _arity_histogram[arity] += count; 2094 _size_histogram[argsize] += count; 2095 _max_arity = MAX2(_max_arity, arity); 2096 _max_size = MAX2(_max_size, argsize); 2097 } 2098 } 2099 2100 void print_histogram_helper(int n, uint64_t* histo, const char* name) { 2101 const int N = MIN2(9, n); 2102 double sum = 0; 2103 double weighted_sum = 0; 2104 for (int i = 0; i <= n; i++) { sum += (double)histo[i]; weighted_sum += (double)(i*histo[i]); } 2105 if (sum >= 1) { // prevent divide by zero or divide overflow 2106 double rest = sum; 2107 double percent = sum / 100; 2108 for (int i = 0; i <= N; i++) { 2109 rest -= (double)histo[i]; 2110 tty->print_cr("%4d: " UINT64_FORMAT_W(12) " (%5.1f%%)", i, histo[i], (double)histo[i] / percent); 2111 } 2112 tty->print_cr("rest: " INT64_FORMAT_W(12) " (%5.1f%%)", (int64_t)rest, rest / percent); 2113 tty->print_cr("(avg. %s = %3.1f, max = %d)", name, weighted_sum / sum, n); 2114 tty->print_cr("(total # of compiled calls = " INT64_FORMAT_W(14) ")", _total_compiled_calls); 2115 tty->print_cr("(max # of compiled calls = " INT64_FORMAT_W(14) ")", _max_compiled_calls_per_method); 2116 } else { 2117 tty->print_cr("Histogram generation failed for %s. n = %d, sum = %7.5f", name, n, sum); 2118 } 2119 } 2120 2121 void print_histogram() { 2122 tty->print_cr("\nHistogram of call arity (incl. rcvr, calls to compiled methods only):"); 2123 print_histogram_helper(_max_arity, _arity_histogram, "arity"); 2124 tty->print_cr("\nHistogram of parameter block size (in words, incl. rcvr):"); 2125 print_histogram_helper(_max_size, _size_histogram, "size"); 2126 tty->cr(); 2127 } 2128 2129 public: 2130 MethodArityHistogram() { 2131 // Take the Compile_lock to protect against changes in the CodeBlob structures 2132 MutexLocker mu1(Compile_lock, Mutex::_safepoint_check_flag); 2133 // Take the CodeCache_lock to protect against changes in the CodeHeap structure 2134 MutexLocker mu2(CodeCache_lock, Mutex::_no_safepoint_check_flag); 2135 _max_arity = _max_size = 0; 2136 _total_compiled_calls = 0; 2137 _max_compiled_calls_per_method = 0; 2138 for (int i = 0; i < MAX_ARITY; i++) _arity_histogram[i] = _size_histogram[i] = 0; 2139 CodeCache::nmethods_do(add_method_to_histogram); 2140 print_histogram(); 2141 } 2142 }; 2143 2144 uint64_t MethodArityHistogram::_arity_histogram[MethodArityHistogram::MAX_ARITY]; 2145 uint64_t MethodArityHistogram::_size_histogram[MethodArityHistogram::MAX_ARITY]; 2146 uint64_t MethodArityHistogram::_total_compiled_calls; 2147 uint64_t MethodArityHistogram::_max_compiled_calls_per_method; 2148 int MethodArityHistogram::_max_arity; 2149 int MethodArityHistogram::_max_size; 2150 2151 void SharedRuntime::print_call_statistics(uint64_t comp_total) { 2152 tty->print_cr("Calls from compiled code:"); 2153 int64_t total = _nof_normal_calls + _nof_interface_calls + _nof_static_calls; 2154 int64_t mono_c = _nof_normal_calls - _nof_megamorphic_calls; 2155 int64_t mono_i = _nof_interface_calls; 2156 tty->print_cr("\t" INT64_FORMAT_W(12) " (100%%) total non-inlined ", total); 2157 tty->print_cr("\t" INT64_FORMAT_W(12) " (%4.1f%%) |- virtual calls ", _nof_normal_calls, percent(_nof_normal_calls, total)); 2158 tty->print_cr("\t" INT64_FORMAT_W(12) " (%4.0f%%) | |- inlined ", _nof_inlined_calls, percent(_nof_inlined_calls, _nof_normal_calls)); 2159 tty->print_cr("\t" INT64_FORMAT_W(12) " (%4.0f%%) | |- monomorphic ", mono_c, percent(mono_c, _nof_normal_calls)); 2160 tty->print_cr("\t" INT64_FORMAT_W(12) " (%4.0f%%) | |- megamorphic ", _nof_megamorphic_calls, percent(_nof_megamorphic_calls, _nof_normal_calls)); 2161 tty->print_cr("\t" INT64_FORMAT_W(12) " (%4.1f%%) |- interface calls ", _nof_interface_calls, percent(_nof_interface_calls, total)); 2162 tty->print_cr("\t" INT64_FORMAT_W(12) " (%4.0f%%) | |- inlined ", _nof_inlined_interface_calls, percent(_nof_inlined_interface_calls, _nof_interface_calls)); 2163 tty->print_cr("\t" INT64_FORMAT_W(12) " (%4.0f%%) | |- monomorphic ", mono_i, percent(mono_i, _nof_interface_calls)); 2164 tty->print_cr("\t" INT64_FORMAT_W(12) " (%4.1f%%) |- static/special calls", _nof_static_calls, percent(_nof_static_calls, total)); 2165 tty->print_cr("\t" INT64_FORMAT_W(12) " (%4.0f%%) | |- inlined ", _nof_inlined_static_calls, percent(_nof_inlined_static_calls, _nof_static_calls)); 2166 tty->cr(); 2167 tty->print_cr("Note 1: counter updates are not MT-safe."); 2168 tty->print_cr("Note 2: %% in major categories are relative to total non-inlined calls;"); 2169 tty->print_cr(" %% in nested categories are relative to their category"); 2170 tty->print_cr(" (and thus add up to more than 100%% with inlining)"); 2171 tty->cr(); 2172 2173 MethodArityHistogram h; 2174 } 2175 #endif 2176 2177 #ifndef PRODUCT 2178 static int _lookups; // number of calls to lookup 2179 static int _equals; // number of buckets checked with matching hash 2180 static int _archived_hits; // number of successful lookups in archived table 2181 static int _runtime_hits; // number of successful lookups in runtime table 2182 #endif 2183 2184 // A simple wrapper class around the calling convention information 2185 // that allows sharing of adapters for the same calling convention. 2186 class AdapterFingerPrint : public MetaspaceObj { 2187 private: 2188 enum { 2189 _basic_type_bits = 4, 2190 _basic_type_mask = right_n_bits(_basic_type_bits), 2191 _basic_types_per_int = BitsPerInt / _basic_type_bits, 2192 }; 2193 // TO DO: Consider integrating this with a more global scheme for compressing signatures. 2194 // For now, 4 bits per components (plus T_VOID gaps after double/long) is not excessive. 2195 2196 int _length; 2197 2198 static int data_offset() { return sizeof(AdapterFingerPrint); } 2199 int* data_pointer() { 2200 return (int*)((address)this + data_offset()); 2201 } 2202 2203 // Private construtor. Use allocate() to get an instance. 2204 AdapterFingerPrint(int total_args_passed, BasicType* sig_bt, int len) { 2205 int* data = data_pointer(); 2206 // Pack the BasicTypes with 8 per int 2207 assert(len == length(total_args_passed), "sanity"); 2208 _length = len; 2209 int sig_index = 0; 2210 for (int index = 0; index < _length; index++) { 2211 int value = 0; 2212 for (int byte = 0; sig_index < total_args_passed && byte < _basic_types_per_int; byte++) { 2213 int bt = adapter_encoding(sig_bt[sig_index++]); 2214 assert((bt & _basic_type_mask) == bt, "must fit in 4 bits"); 2215 value = (value << _basic_type_bits) | bt; 2216 } 2217 data[index] = value; 2218 } 2219 } 2220 2221 // Call deallocate instead 2222 ~AdapterFingerPrint() { 2223 ShouldNotCallThis(); 2224 } 2225 2226 static int length(int total_args) { 2227 return (total_args + (_basic_types_per_int-1)) / _basic_types_per_int; 2228 } 2229 2230 static int compute_size_in_words(int len) { 2231 return (int)heap_word_size(sizeof(AdapterFingerPrint) + (len * sizeof(int))); 2232 } 2233 2234 // Remap BasicTypes that are handled equivalently by the adapters. 2235 // These are correct for the current system but someday it might be 2236 // necessary to make this mapping platform dependent. 2237 static int adapter_encoding(BasicType in) { 2238 switch (in) { 2239 case T_BOOLEAN: 2240 case T_BYTE: 2241 case T_SHORT: 2242 case T_CHAR: 2243 // There are all promoted to T_INT in the calling convention 2244 return T_INT; 2245 2246 case T_OBJECT: 2247 case T_ARRAY: 2248 // In other words, we assume that any register good enough for 2249 // an int or long is good enough for a managed pointer. 2250 #ifdef _LP64 2251 return T_LONG; 2252 #else 2253 return T_INT; 2254 #endif 2255 2256 case T_INT: 2257 case T_LONG: 2258 case T_FLOAT: 2259 case T_DOUBLE: 2260 case T_VOID: 2261 return in; 2262 2263 default: 2264 ShouldNotReachHere(); 2265 return T_CONFLICT; 2266 } 2267 } 2268 2269 void* operator new(size_t size, size_t fp_size) throw() { 2270 assert(fp_size >= size, "sanity check"); 2271 void* p = AllocateHeap(fp_size, mtCode); 2272 memset(p, 0, fp_size); 2273 return p; 2274 } 2275 2276 template<typename Function> 2277 void iterate_args(Function function) { 2278 for (int i = 0; i < length(); i++) { 2279 unsigned val = (unsigned)value(i); 2280 // args are packed so that first/lower arguments are in the highest 2281 // bits of each int value, so iterate from highest to the lowest 2282 for (int j = 32 - _basic_type_bits; j >= 0; j -= _basic_type_bits) { 2283 unsigned v = (val >> j) & _basic_type_mask; 2284 if (v == 0) { 2285 continue; 2286 } 2287 function(v); 2288 } 2289 } 2290 } 2291 2292 public: 2293 static AdapterFingerPrint* allocate(int total_args_passed, BasicType* sig_bt) { 2294 int len = length(total_args_passed); 2295 int size_in_bytes = BytesPerWord * compute_size_in_words(len); 2296 AdapterFingerPrint* afp = new (size_in_bytes) AdapterFingerPrint(total_args_passed, sig_bt, len); 2297 assert((afp->size() * BytesPerWord) == size_in_bytes, "should match"); 2298 return afp; 2299 } 2300 2301 static void deallocate(AdapterFingerPrint* fp) { 2302 FreeHeap(fp); 2303 } 2304 2305 int value(int index) { 2306 int* data = data_pointer(); 2307 return data[index]; 2308 } 2309 2310 int length() { 2311 return _length; 2312 } 2313 2314 unsigned int compute_hash() { 2315 int hash = 0; 2316 for (int i = 0; i < length(); i++) { 2317 int v = value(i); 2318 //Add arithmetic operation to the hash, like +3 to improve hashing 2319 hash = ((hash << 8) ^ v ^ (hash >> 5)) + 3; 2320 } 2321 return (unsigned int)hash; 2322 } 2323 2324 const char* as_string() { 2325 stringStream st; 2326 st.print("0x"); 2327 for (int i = 0; i < length(); i++) { 2328 st.print("%x", value(i)); 2329 } 2330 return st.as_string(); 2331 } 2332 2333 const char* as_basic_args_string() { 2334 stringStream st; 2335 bool long_prev = false; 2336 iterate_args([&] (int arg) { 2337 if (long_prev) { 2338 long_prev = false; 2339 if (arg == T_VOID) { 2340 st.print("J"); 2341 } else { 2342 st.print("L"); 2343 } 2344 } 2345 switch (arg) { 2346 case T_INT: st.print("I"); break; 2347 case T_LONG: long_prev = true; break; 2348 case T_FLOAT: st.print("F"); break; 2349 case T_DOUBLE: st.print("D"); break; 2350 case T_VOID: break; 2351 default: ShouldNotReachHere(); 2352 } 2353 }); 2354 if (long_prev) { 2355 st.print("L"); 2356 } 2357 return st.as_string(); 2358 } 2359 2360 BasicType* as_basic_type(int& nargs) { 2361 nargs = 0; 2362 GrowableArray<BasicType> btarray; 2363 bool long_prev = false; 2364 2365 iterate_args([&] (int arg) { 2366 if (long_prev) { 2367 long_prev = false; 2368 if (arg == T_VOID) { 2369 btarray.append(T_LONG); 2370 } else { 2371 btarray.append(T_OBJECT); // it could be T_ARRAY; it shouldn't matter 2372 } 2373 } 2374 switch (arg) { 2375 case T_INT: // fallthrough 2376 case T_FLOAT: // fallthrough 2377 case T_DOUBLE: 2378 case T_VOID: 2379 btarray.append((BasicType)arg); 2380 break; 2381 case T_LONG: 2382 long_prev = true; 2383 break; 2384 default: ShouldNotReachHere(); 2385 } 2386 }); 2387 2388 if (long_prev) { 2389 btarray.append(T_OBJECT); 2390 } 2391 2392 nargs = btarray.length(); 2393 BasicType* sig_bt = NEW_RESOURCE_ARRAY(BasicType, nargs); 2394 int index = 0; 2395 GrowableArrayIterator<BasicType> iter = btarray.begin(); 2396 while (iter != btarray.end()) { 2397 sig_bt[index++] = *iter; 2398 ++iter; 2399 } 2400 assert(index == btarray.length(), "sanity check"); 2401 #ifdef ASSERT 2402 { 2403 AdapterFingerPrint* compare_fp = AdapterFingerPrint::allocate(nargs, sig_bt); 2404 assert(this->equals(compare_fp), "sanity check"); 2405 AdapterFingerPrint::deallocate(compare_fp); 2406 } 2407 #endif 2408 return sig_bt; 2409 } 2410 2411 bool equals(AdapterFingerPrint* other) { 2412 if (other->_length != _length) { 2413 return false; 2414 } else { 2415 for (int i = 0; i < _length; i++) { 2416 if (value(i) != other->value(i)) { 2417 return false; 2418 } 2419 } 2420 } 2421 return true; 2422 } 2423 2424 // methods required by virtue of being a MetaspaceObj 2425 void metaspace_pointers_do(MetaspaceClosure* it) { return; /* nothing to do here */ } 2426 int size() const { return compute_size_in_words(_length); } 2427 MetaspaceObj::Type type() const { return AdapterFingerPrintType; } 2428 2429 static bool equals(AdapterFingerPrint* const& fp1, AdapterFingerPrint* const& fp2) { 2430 NOT_PRODUCT(_equals++); 2431 return fp1->equals(fp2); 2432 } 2433 2434 static unsigned int compute_hash(AdapterFingerPrint* const& fp) { 2435 return fp->compute_hash(); 2436 } 2437 }; 2438 2439 #if INCLUDE_CDS 2440 static inline bool adapter_fp_equals_compact_hashtable_entry(AdapterHandlerEntry* entry, AdapterFingerPrint* fp, int len_unused) { 2441 return AdapterFingerPrint::equals(entry->fingerprint(), fp); 2442 } 2443 2444 class ArchivedAdapterTable : public OffsetCompactHashtable< 2445 AdapterFingerPrint*, 2446 AdapterHandlerEntry*, 2447 adapter_fp_equals_compact_hashtable_entry> {}; 2448 #endif // INCLUDE_CDS 2449 2450 // A hashtable mapping from AdapterFingerPrints to AdapterHandlerEntries 2451 using AdapterHandlerTable = ResourceHashtable<AdapterFingerPrint*, AdapterHandlerEntry*, 293, 2452 AnyObj::C_HEAP, mtCode, 2453 AdapterFingerPrint::compute_hash, 2454 AdapterFingerPrint::equals>; 2455 static AdapterHandlerTable* _adapter_handler_table; 2456 static GrowableArray<AdapterHandlerEntry*>* _adapter_handler_list = nullptr; 2457 2458 // Find a entry with the same fingerprint if it exists 2459 AdapterHandlerEntry* AdapterHandlerLibrary::lookup(int total_args_passed, BasicType* sig_bt) { 2460 NOT_PRODUCT(_lookups++); 2461 assert_lock_strong(AdapterHandlerLibrary_lock); 2462 AdapterFingerPrint* fp = AdapterFingerPrint::allocate(total_args_passed, sig_bt); 2463 AdapterHandlerEntry* entry = nullptr; 2464 #if INCLUDE_CDS 2465 // if we are building the archive then the archived adapter table is 2466 // not valid and we need to use the ones added to the runtime table 2467 if (AOTCodeCache::is_using_adapter()) { 2468 // Search archived table first. It is read-only table so can be searched without lock 2469 entry = _aot_adapter_handler_table.lookup(fp, fp->compute_hash(), 0 /* unused */); 2470 #ifndef PRODUCT 2471 if (entry != nullptr) { 2472 _archived_hits++; 2473 } 2474 #endif 2475 } 2476 #endif // INCLUDE_CDS 2477 if (entry == nullptr) { 2478 assert_lock_strong(AdapterHandlerLibrary_lock); 2479 AdapterHandlerEntry** entry_p = _adapter_handler_table->get(fp); 2480 if (entry_p != nullptr) { 2481 entry = *entry_p; 2482 assert(entry->fingerprint()->equals(fp), "fingerprint mismatch key fp %s %s (hash=%d) != found fp %s %s (hash=%d)", 2483 entry->fingerprint()->as_basic_args_string(), entry->fingerprint()->as_string(), entry->fingerprint()->compute_hash(), 2484 fp->as_basic_args_string(), fp->as_string(), fp->compute_hash()); 2485 #ifndef PRODUCT 2486 _runtime_hits++; 2487 #endif 2488 } 2489 } 2490 AdapterFingerPrint::deallocate(fp); 2491 return entry; 2492 } 2493 2494 #ifndef PRODUCT 2495 static void print_table_statistics() { 2496 auto size = [&] (AdapterFingerPrint* key, AdapterHandlerEntry* a) { 2497 return sizeof(*key) + sizeof(*a); 2498 }; 2499 TableStatistics ts = _adapter_handler_table->statistics_calculate(size); 2500 ts.print(tty, "AdapterHandlerTable"); 2501 tty->print_cr("AdapterHandlerTable (table_size=%d, entries=%d)", 2502 _adapter_handler_table->table_size(), _adapter_handler_table->number_of_entries()); 2503 int total_hits = _archived_hits + _runtime_hits; 2504 tty->print_cr("AdapterHandlerTable: lookups %d equals %d hits %d (archived=%d+runtime=%d)", 2505 _lookups, _equals, total_hits, _archived_hits, _runtime_hits); 2506 } 2507 #endif 2508 2509 // --------------------------------------------------------------------------- 2510 // Implementation of AdapterHandlerLibrary 2511 AdapterHandlerEntry* AdapterHandlerLibrary::_abstract_method_handler = nullptr; 2512 AdapterHandlerEntry* AdapterHandlerLibrary::_no_arg_handler = nullptr; 2513 AdapterHandlerEntry* AdapterHandlerLibrary::_int_arg_handler = nullptr; 2514 AdapterHandlerEntry* AdapterHandlerLibrary::_obj_arg_handler = nullptr; 2515 AdapterHandlerEntry* AdapterHandlerLibrary::_obj_int_arg_handler = nullptr; 2516 AdapterHandlerEntry* AdapterHandlerLibrary::_obj_obj_arg_handler = nullptr; 2517 #if INCLUDE_CDS 2518 ArchivedAdapterTable AdapterHandlerLibrary::_aot_adapter_handler_table; 2519 #endif // INCLUDE_CDS 2520 static const int AdapterHandlerLibrary_size = 16*K; 2521 BufferBlob* AdapterHandlerLibrary::_buffer = nullptr; 2522 2523 BufferBlob* AdapterHandlerLibrary::buffer_blob() { 2524 assert(_buffer != nullptr, "should be initialized"); 2525 return _buffer; 2526 } 2527 2528 static void post_adapter_creation(const AdapterBlob* new_adapter, 2529 const AdapterHandlerEntry* entry) { 2530 if (Forte::is_enabled() || JvmtiExport::should_post_dynamic_code_generated()) { 2531 char blob_id[256]; 2532 jio_snprintf(blob_id, 2533 sizeof(blob_id), 2534 "%s(%s)", 2535 new_adapter->name(), 2536 entry->fingerprint()->as_string()); 2537 if (Forte::is_enabled()) { 2538 Forte::register_stub(blob_id, new_adapter->content_begin(), new_adapter->content_end()); 2539 } 2540 2541 if (JvmtiExport::should_post_dynamic_code_generated()) { 2542 JvmtiExport::post_dynamic_code_generated(blob_id, new_adapter->content_begin(), new_adapter->content_end()); 2543 } 2544 } 2545 } 2546 2547 void AdapterHandlerLibrary::create_abstract_method_handler() { 2548 assert_lock_strong(AdapterHandlerLibrary_lock); 2549 // Create a special handler for abstract methods. Abstract methods 2550 // are never compiled so an i2c entry is somewhat meaningless, but 2551 // throw AbstractMethodError just in case. 2552 // Pass wrong_method_abstract for the c2i transitions to return 2553 // AbstractMethodError for invalid invocations. 2554 address wrong_method_abstract = SharedRuntime::get_handle_wrong_method_abstract_stub(); 2555 _abstract_method_handler = AdapterHandlerLibrary::new_entry(AdapterFingerPrint::allocate(0, nullptr)); 2556 _abstract_method_handler->set_entry_points(SharedRuntime::throw_AbstractMethodError_entry(), 2557 wrong_method_abstract, 2558 wrong_method_abstract, 2559 nullptr); 2560 } 2561 2562 void AdapterHandlerLibrary::initialize() { 2563 { 2564 ResourceMark rm; 2565 MutexLocker mu(AdapterHandlerLibrary_lock); 2566 _adapter_handler_table = new (mtCode) AdapterHandlerTable(); 2567 _buffer = BufferBlob::create("adapters", AdapterHandlerLibrary_size); 2568 create_abstract_method_handler(); 2569 } 2570 2571 #if INCLUDE_CDS 2572 // Link adapters in AOT Cache to their code in AOT Code Cache 2573 if (AOTCodeCache::is_using_adapter() && !_aot_adapter_handler_table.empty()) { 2574 link_aot_adapters(); 2575 lookup_simple_adapters(); 2576 return; 2577 } 2578 #endif // INCLUDE_CDS 2579 2580 ResourceMark rm; 2581 AdapterBlob* no_arg_blob = nullptr; 2582 AdapterBlob* int_arg_blob = nullptr; 2583 AdapterBlob* obj_arg_blob = nullptr; 2584 AdapterBlob* obj_int_arg_blob = nullptr; 2585 AdapterBlob* obj_obj_arg_blob = nullptr; 2586 { 2587 MutexLocker mu(AdapterHandlerLibrary_lock); 2588 2589 _no_arg_handler = create_adapter(no_arg_blob, 0, nullptr); 2590 2591 BasicType obj_args[] = { T_OBJECT }; 2592 _obj_arg_handler = create_adapter(obj_arg_blob, 1, obj_args); 2593 2594 BasicType int_args[] = { T_INT }; 2595 _int_arg_handler = create_adapter(int_arg_blob, 1, int_args); 2596 2597 BasicType obj_int_args[] = { T_OBJECT, T_INT }; 2598 _obj_int_arg_handler = create_adapter(obj_int_arg_blob, 2, obj_int_args); 2599 2600 BasicType obj_obj_args[] = { T_OBJECT, T_OBJECT }; 2601 _obj_obj_arg_handler = create_adapter(obj_obj_arg_blob, 2, obj_obj_args); 2602 2603 assert(no_arg_blob != nullptr && 2604 obj_arg_blob != nullptr && 2605 int_arg_blob != nullptr && 2606 obj_int_arg_blob != nullptr && 2607 obj_obj_arg_blob != nullptr, "Initial adapters must be properly created"); 2608 } 2609 2610 // Outside of the lock 2611 post_adapter_creation(no_arg_blob, _no_arg_handler); 2612 post_adapter_creation(obj_arg_blob, _obj_arg_handler); 2613 post_adapter_creation(int_arg_blob, _int_arg_handler); 2614 post_adapter_creation(obj_int_arg_blob, _obj_int_arg_handler); 2615 post_adapter_creation(obj_obj_arg_blob, _obj_obj_arg_handler); 2616 } 2617 2618 AdapterHandlerEntry* AdapterHandlerLibrary::new_entry(AdapterFingerPrint* fingerprint) { 2619 return AdapterHandlerEntry::allocate(fingerprint); 2620 } 2621 2622 AdapterHandlerEntry* AdapterHandlerLibrary::get_simple_adapter(const methodHandle& method) { 2623 if (method->is_abstract()) { 2624 return _abstract_method_handler; 2625 } 2626 int total_args_passed = method->size_of_parameters(); // All args on stack 2627 if (total_args_passed == 0) { 2628 return _no_arg_handler; 2629 } else if (total_args_passed == 1) { 2630 if (!method->is_static()) { 2631 return _obj_arg_handler; 2632 } 2633 switch (method->signature()->char_at(1)) { 2634 case JVM_SIGNATURE_CLASS: 2635 case JVM_SIGNATURE_ARRAY: 2636 return _obj_arg_handler; 2637 case JVM_SIGNATURE_INT: 2638 case JVM_SIGNATURE_BOOLEAN: 2639 case JVM_SIGNATURE_CHAR: 2640 case JVM_SIGNATURE_BYTE: 2641 case JVM_SIGNATURE_SHORT: 2642 return _int_arg_handler; 2643 } 2644 } else if (total_args_passed == 2 && 2645 !method->is_static()) { 2646 switch (method->signature()->char_at(1)) { 2647 case JVM_SIGNATURE_CLASS: 2648 case JVM_SIGNATURE_ARRAY: 2649 return _obj_obj_arg_handler; 2650 case JVM_SIGNATURE_INT: 2651 case JVM_SIGNATURE_BOOLEAN: 2652 case JVM_SIGNATURE_CHAR: 2653 case JVM_SIGNATURE_BYTE: 2654 case JVM_SIGNATURE_SHORT: 2655 return _obj_int_arg_handler; 2656 } 2657 } 2658 return nullptr; 2659 } 2660 2661 class AdapterSignatureIterator : public SignatureIterator { 2662 private: 2663 BasicType stack_sig_bt[16]; 2664 BasicType* sig_bt; 2665 int index; 2666 2667 public: 2668 AdapterSignatureIterator(Symbol* signature, 2669 fingerprint_t fingerprint, 2670 bool is_static, 2671 int total_args_passed) : 2672 SignatureIterator(signature, fingerprint), 2673 index(0) 2674 { 2675 sig_bt = (total_args_passed <= 16) ? stack_sig_bt : NEW_RESOURCE_ARRAY(BasicType, total_args_passed); 2676 if (!is_static) { // Pass in receiver first 2677 sig_bt[index++] = T_OBJECT; 2678 } 2679 do_parameters_on(this); 2680 } 2681 2682 BasicType* basic_types() { 2683 return sig_bt; 2684 } 2685 2686 #ifdef ASSERT 2687 int slots() { 2688 return index; 2689 } 2690 #endif 2691 2692 private: 2693 2694 friend class SignatureIterator; // so do_parameters_on can call do_type 2695 void do_type(BasicType type) { 2696 sig_bt[index++] = type; 2697 if (type == T_LONG || type == T_DOUBLE) { 2698 sig_bt[index++] = T_VOID; // Longs & doubles take 2 Java slots 2699 } 2700 } 2701 }; 2702 2703 2704 const char* AdapterHandlerEntry::_entry_names[] = { 2705 "i2c", "c2i", "c2i_unverified", "c2i_no_clinit_check" 2706 }; 2707 2708 #ifdef ASSERT 2709 void AdapterHandlerLibrary::verify_adapter_sharing(int total_args_passed, BasicType* sig_bt, AdapterHandlerEntry* cached_entry) { 2710 AdapterBlob* comparison_blob = nullptr; 2711 AdapterHandlerEntry* comparison_entry = create_adapter(comparison_blob, total_args_passed, sig_bt, true); 2712 assert(comparison_blob == nullptr, "no blob should be created when creating an adapter for comparison"); 2713 assert(comparison_entry->compare_code(cached_entry), "code must match"); 2714 // Release the one just created 2715 AdapterHandlerEntry::deallocate(comparison_entry); 2716 } 2717 #endif /* ASSERT*/ 2718 2719 AdapterHandlerEntry* AdapterHandlerLibrary::get_adapter(const methodHandle& method) { 2720 // Use customized signature handler. Need to lock around updates to 2721 // the _adapter_handler_table (it is not safe for concurrent readers 2722 // and a single writer: this could be fixed if it becomes a 2723 // problem). 2724 2725 // Fast-path for trivial adapters 2726 AdapterHandlerEntry* entry = get_simple_adapter(method); 2727 if (entry != nullptr) { 2728 return entry; 2729 } 2730 2731 ResourceMark rm; 2732 AdapterBlob* adapter_blob = nullptr; 2733 2734 // Fill in the signature array, for the calling-convention call. 2735 int total_args_passed = method->size_of_parameters(); // All args on stack 2736 2737 AdapterSignatureIterator si(method->signature(), method->constMethod()->fingerprint(), 2738 method->is_static(), total_args_passed); 2739 assert(si.slots() == total_args_passed, ""); 2740 BasicType* sig_bt = si.basic_types(); 2741 { 2742 MutexLocker mu(AdapterHandlerLibrary_lock); 2743 2744 // Lookup method signature's fingerprint 2745 entry = lookup(total_args_passed, sig_bt); 2746 2747 if (entry != nullptr) { 2748 assert(entry->is_linked(), "AdapterHandlerEntry must have been linked"); 2749 #ifdef ASSERT 2750 if (!entry->is_shared() && VerifyAdapterSharing) { 2751 verify_adapter_sharing(total_args_passed, sig_bt, entry); 2752 } 2753 #endif 2754 } else { 2755 entry = create_adapter(adapter_blob, total_args_passed, sig_bt); 2756 } 2757 } 2758 2759 // Outside of the lock 2760 if (adapter_blob != nullptr) { 2761 post_adapter_creation(adapter_blob, entry); 2762 } 2763 return entry; 2764 } 2765 2766 AdapterBlob* AdapterHandlerLibrary::lookup_aot_cache(AdapterHandlerEntry* handler) { 2767 ResourceMark rm; 2768 const char* name = AdapterHandlerLibrary::name(handler->fingerprint()); 2769 const uint32_t id = AdapterHandlerLibrary::id(handler->fingerprint()); 2770 int offsets[AdapterHandlerEntry::ENTRIES_COUNT]; 2771 2772 AdapterBlob* adapter_blob = nullptr; 2773 CodeBlob* blob = AOTCodeCache::load_code_blob(AOTCodeEntry::Adapter, id, name, AdapterHandlerEntry::ENTRIES_COUNT, offsets); 2774 if (blob != nullptr) { 2775 adapter_blob = blob->as_adapter_blob(); 2776 address i2c_entry = adapter_blob->content_begin(); 2777 assert(offsets[0] == 0, "sanity check"); 2778 handler->set_entry_points(i2c_entry, i2c_entry + offsets[1], i2c_entry + offsets[2], i2c_entry + offsets[3]); 2779 } 2780 return adapter_blob; 2781 } 2782 2783 #ifndef PRODUCT 2784 void AdapterHandlerLibrary::print_adapter_handler_info(outputStream* st, AdapterHandlerEntry* handler, AdapterBlob* adapter_blob) { 2785 ttyLocker ttyl; 2786 ResourceMark rm; 2787 int insts_size = adapter_blob->code_size(); 2788 handler->print_adapter_on(tty); 2789 st->print_cr("i2c argument handler for: %s %s (%d bytes generated)", 2790 handler->fingerprint()->as_basic_args_string(), 2791 handler->fingerprint()->as_string(), insts_size); 2792 st->print_cr("c2i argument handler starts at " INTPTR_FORMAT, p2i(handler->get_c2i_entry())); 2793 if (Verbose || PrintStubCode) { 2794 address first_pc = handler->base_address(); 2795 if (first_pc != nullptr) { 2796 Disassembler::decode(first_pc, first_pc + insts_size, st, &adapter_blob->asm_remarks()); 2797 st->cr(); 2798 } 2799 } 2800 } 2801 #endif // PRODUCT 2802 2803 bool AdapterHandlerLibrary::generate_adapter_code(AdapterBlob*& adapter_blob, 2804 AdapterHandlerEntry* handler, 2805 int total_args_passed, 2806 BasicType* sig_bt, 2807 bool is_transient) { 2808 if (log_is_enabled(Info, perf, class, link)) { 2809 ClassLoader::perf_method_adapters_count()->inc(); 2810 } 2811 2812 BufferBlob* buf = buffer_blob(); // the temporary code buffer in CodeCache 2813 CodeBuffer buffer(buf); 2814 short buffer_locs[20]; 2815 buffer.insts()->initialize_shared_locs((relocInfo*)buffer_locs, 2816 sizeof(buffer_locs)/sizeof(relocInfo)); 2817 MacroAssembler masm(&buffer); 2818 VMRegPair stack_regs[16]; 2819 VMRegPair* regs = (total_args_passed <= 16) ? stack_regs : NEW_RESOURCE_ARRAY(VMRegPair, total_args_passed); 2820 2821 // Get a description of the compiled java calling convention and the largest used (VMReg) stack slot usage 2822 int comp_args_on_stack = SharedRuntime::java_calling_convention(sig_bt, regs, total_args_passed); 2823 SharedRuntime::generate_i2c2i_adapters(&masm, 2824 total_args_passed, 2825 comp_args_on_stack, 2826 sig_bt, 2827 regs, 2828 handler); 2829 #ifdef ASSERT 2830 if (VerifyAdapterSharing) { 2831 handler->save_code(buf->code_begin(), buffer.insts_size()); 2832 if (is_transient) { 2833 return true; 2834 } 2835 } 2836 #endif 2837 2838 adapter_blob = AdapterBlob::create(&buffer); 2839 if (adapter_blob == nullptr) { 2840 // CodeCache is full, disable compilation 2841 // Ought to log this but compile log is only per compile thread 2842 // and we're some non descript Java thread. 2843 return false; 2844 } 2845 if (!is_transient && AOTCodeCache::is_dumping_adapter()) { 2846 // try to save generated code 2847 const char* name = AdapterHandlerLibrary::name(handler->fingerprint()); 2848 const uint32_t id = AdapterHandlerLibrary::id(handler->fingerprint()); 2849 int entry_offset[AdapterHandlerEntry::ENTRIES_COUNT]; 2850 assert(AdapterHandlerEntry::ENTRIES_COUNT == 4, "sanity"); 2851 address i2c_entry = handler->get_i2c_entry(); 2852 entry_offset[0] = 0; // i2c_entry offset 2853 entry_offset[1] = handler->get_c2i_entry() - i2c_entry; 2854 entry_offset[2] = handler->get_c2i_unverified_entry() - i2c_entry; 2855 entry_offset[3] = handler->get_c2i_no_clinit_check_entry() - i2c_entry; 2856 bool success = AOTCodeCache::store_code_blob(*adapter_blob, AOTCodeEntry::Adapter, id, name, AdapterHandlerEntry::ENTRIES_COUNT, entry_offset); 2857 assert(success || !AOTCodeCache::is_dumping_adapter(), "caching of adapter must be disabled"); 2858 } 2859 handler->relocate(adapter_blob->content_begin()); 2860 #ifndef PRODUCT 2861 // debugging support 2862 if (PrintAdapterHandlers || PrintStubCode) { 2863 print_adapter_handler_info(tty, handler, adapter_blob); 2864 } 2865 #endif 2866 return true; 2867 } 2868 2869 AdapterHandlerEntry* AdapterHandlerLibrary::create_adapter(AdapterBlob*& adapter_blob, 2870 int total_args_passed, 2871 BasicType* sig_bt, 2872 bool is_transient) { 2873 AdapterFingerPrint* fp = AdapterFingerPrint::allocate(total_args_passed, sig_bt); 2874 AdapterHandlerEntry* handler = AdapterHandlerLibrary::new_entry(fp); 2875 if (!generate_adapter_code(adapter_blob, handler, total_args_passed, sig_bt, is_transient)) { 2876 AdapterHandlerEntry::deallocate(handler); 2877 return nullptr; 2878 } 2879 if (!is_transient) { 2880 assert_lock_strong(AdapterHandlerLibrary_lock); 2881 _adapter_handler_table->put(fp, handler); 2882 } 2883 return handler; 2884 } 2885 2886 #if INCLUDE_CDS 2887 void AdapterHandlerEntry::remove_unshareable_info() { 2888 #ifdef ASSERT 2889 _saved_code = nullptr; 2890 _saved_code_length = 0; 2891 #endif // ASSERT 2892 set_entry_points(nullptr, nullptr, nullptr, nullptr, false); 2893 } 2894 2895 class CopyAdapterTableToArchive : StackObj { 2896 private: 2897 CompactHashtableWriter* _writer; 2898 ArchiveBuilder* _builder; 2899 public: 2900 CopyAdapterTableToArchive(CompactHashtableWriter* writer) : _writer(writer), 2901 _builder(ArchiveBuilder::current()) 2902 {} 2903 2904 bool do_entry(AdapterFingerPrint* fp, AdapterHandlerEntry* entry) { 2905 LogStreamHandle(Trace, aot) lsh; 2906 if (ArchiveBuilder::current()->has_been_archived((address)entry)) { 2907 assert(ArchiveBuilder::current()->has_been_archived((address)fp), "must be"); 2908 AdapterFingerPrint* buffered_fp = ArchiveBuilder::current()->get_buffered_addr(fp); 2909 assert(buffered_fp != nullptr,"sanity check"); 2910 AdapterHandlerEntry* buffered_entry = ArchiveBuilder::current()->get_buffered_addr(entry); 2911 assert(buffered_entry != nullptr,"sanity check"); 2912 2913 uint hash = fp->compute_hash(); 2914 u4 delta = _builder->buffer_to_offset_u4((address)buffered_entry); 2915 _writer->add(hash, delta); 2916 if (lsh.is_enabled()) { 2917 address fp_runtime_addr = (address)buffered_fp + ArchiveBuilder::current()->buffer_to_requested_delta(); 2918 address entry_runtime_addr = (address)buffered_entry + ArchiveBuilder::current()->buffer_to_requested_delta(); 2919 log_trace(aot)("Added fp=%p (%s), entry=%p to the archived adater table", buffered_fp, buffered_fp->as_basic_args_string(), buffered_entry); 2920 } 2921 } else { 2922 if (lsh.is_enabled()) { 2923 log_trace(aot)("Skipping adapter handler %p (fp=%s) as it is not archived", entry, fp->as_basic_args_string()); 2924 } 2925 } 2926 return true; 2927 } 2928 }; 2929 2930 void AdapterHandlerLibrary::dump_aot_adapter_table() { 2931 CompactHashtableStats stats; 2932 CompactHashtableWriter writer(_adapter_handler_table->number_of_entries(), &stats); 2933 CopyAdapterTableToArchive copy(&writer); 2934 _adapter_handler_table->iterate(©); 2935 writer.dump(&_aot_adapter_handler_table, "archived adapter table"); 2936 } 2937 2938 void AdapterHandlerLibrary::serialize_shared_table_header(SerializeClosure* soc) { 2939 _aot_adapter_handler_table.serialize_header(soc); 2940 } 2941 2942 AdapterBlob* AdapterHandlerLibrary::link_aot_adapter_handler(AdapterHandlerEntry* handler) { 2943 #ifdef ASSERT 2944 if (TestAOTAdapterLinkFailure) { 2945 return nullptr; 2946 } 2947 #endif 2948 AdapterBlob* blob = lookup_aot_cache(handler); 2949 #ifndef PRODUCT 2950 // debugging support 2951 if ((blob != nullptr) && (PrintAdapterHandlers || PrintStubCode)) { 2952 print_adapter_handler_info(tty, handler, blob); 2953 } 2954 #endif 2955 return blob; 2956 } 2957 2958 // This method is used during production run to link archived adapters (stored in AOT Cache) 2959 // to their code in AOT Code Cache 2960 void AdapterHandlerEntry::link() { 2961 AdapterBlob* adapter_blob = nullptr; 2962 ResourceMark rm; 2963 assert(_fingerprint != nullptr, "_fingerprint must not be null"); 2964 bool generate_code = false; 2965 // Generate code only if AOTCodeCache is not available, or 2966 // caching adapters is disabled, or we fail to link 2967 // the AdapterHandlerEntry to its code in the AOTCodeCache 2968 if (AOTCodeCache::is_using_adapter()) { 2969 adapter_blob = AdapterHandlerLibrary::link_aot_adapter_handler(this); 2970 if (adapter_blob == nullptr) { 2971 log_warning(aot)("Failed to link AdapterHandlerEntry (fp=%s) to its code in the AOT code cache", _fingerprint->as_basic_args_string()); 2972 generate_code = true; 2973 } 2974 } else { 2975 generate_code = true; 2976 } 2977 if (generate_code) { 2978 int nargs; 2979 BasicType* bt = _fingerprint->as_basic_type(nargs); 2980 if (!AdapterHandlerLibrary::generate_adapter_code(adapter_blob, this, nargs, bt, /* is_transient */ false)) { 2981 // Don't throw exceptions during VM initialization because java.lang.* classes 2982 // might not have been initialized, causing problems when constructing the 2983 // Java exception object. 2984 vm_exit_during_initialization("Out of space in CodeCache for adapters"); 2985 } 2986 } 2987 // Outside of the lock 2988 if (adapter_blob != nullptr) { 2989 post_adapter_creation(adapter_blob, this); 2990 } 2991 assert(_linked, "AdapterHandlerEntry must now be linked"); 2992 } 2993 2994 void AdapterHandlerLibrary::link_aot_adapters() { 2995 assert(AOTCodeCache::is_using_adapter(), "AOT adapters code should be available"); 2996 _aot_adapter_handler_table.iterate([](AdapterHandlerEntry* entry) { 2997 assert(!entry->is_linked(), "AdapterHandlerEntry is already linked!"); 2998 entry->link(); 2999 }); 3000 } 3001 3002 // This method is called during production run to lookup simple adapters 3003 // in the archived adapter handler table 3004 void AdapterHandlerLibrary::lookup_simple_adapters() { 3005 assert(!_aot_adapter_handler_table.empty(), "archived adapter handler table is empty"); 3006 3007 MutexLocker mu(AdapterHandlerLibrary_lock); 3008 _no_arg_handler = lookup(0, nullptr); 3009 3010 BasicType obj_args[] = { T_OBJECT }; 3011 _obj_arg_handler = lookup(1, obj_args); 3012 3013 BasicType int_args[] = { T_INT }; 3014 _int_arg_handler = lookup(1, int_args); 3015 3016 BasicType obj_int_args[] = { T_OBJECT, T_INT }; 3017 _obj_int_arg_handler = lookup(2, obj_int_args); 3018 3019 BasicType obj_obj_args[] = { T_OBJECT, T_OBJECT }; 3020 _obj_obj_arg_handler = lookup(2, obj_obj_args); 3021 3022 assert(_no_arg_handler != nullptr && 3023 _obj_arg_handler != nullptr && 3024 _int_arg_handler != nullptr && 3025 _obj_int_arg_handler != nullptr && 3026 _obj_obj_arg_handler != nullptr, "Initial adapters not found in archived adapter handler table"); 3027 assert(_no_arg_handler->is_linked() && 3028 _obj_arg_handler->is_linked() && 3029 _int_arg_handler->is_linked() && 3030 _obj_int_arg_handler->is_linked() && 3031 _obj_obj_arg_handler->is_linked(), "Initial adapters not in linked state"); 3032 } 3033 #endif // INCLUDE_CDS 3034 3035 address AdapterHandlerEntry::base_address() { 3036 address base = _i2c_entry; 3037 if (base == nullptr) base = _c2i_entry; 3038 assert(base <= _c2i_entry || _c2i_entry == nullptr, ""); 3039 assert(base <= _c2i_unverified_entry || _c2i_unverified_entry == nullptr, ""); 3040 assert(base <= _c2i_no_clinit_check_entry || _c2i_no_clinit_check_entry == nullptr, ""); 3041 return base; 3042 } 3043 3044 void AdapterHandlerEntry::relocate(address new_base) { 3045 address old_base = base_address(); 3046 assert(old_base != nullptr, ""); 3047 ptrdiff_t delta = new_base - old_base; 3048 if (_i2c_entry != nullptr) 3049 _i2c_entry += delta; 3050 if (_c2i_entry != nullptr) 3051 _c2i_entry += delta; 3052 if (_c2i_unverified_entry != nullptr) 3053 _c2i_unverified_entry += delta; 3054 if (_c2i_no_clinit_check_entry != nullptr) 3055 _c2i_no_clinit_check_entry += delta; 3056 assert(base_address() == new_base, ""); 3057 } 3058 3059 void AdapterHandlerEntry::metaspace_pointers_do(MetaspaceClosure* it) { 3060 LogStreamHandle(Trace, aot) lsh; 3061 if (lsh.is_enabled()) { 3062 lsh.print("Iter(AdapterHandlerEntry): %p(%s)", this, _fingerprint->as_basic_args_string()); 3063 lsh.cr(); 3064 } 3065 it->push(&_fingerprint); 3066 } 3067 3068 AdapterHandlerEntry::~AdapterHandlerEntry() { 3069 if (_fingerprint != nullptr) { 3070 AdapterFingerPrint::deallocate(_fingerprint); 3071 _fingerprint = nullptr; 3072 } 3073 #ifdef ASSERT 3074 FREE_C_HEAP_ARRAY(unsigned char, _saved_code); 3075 #endif 3076 FreeHeap(this); 3077 } 3078 3079 3080 #ifdef ASSERT 3081 // Capture the code before relocation so that it can be compared 3082 // against other versions. If the code is captured after relocation 3083 // then relative instructions won't be equivalent. 3084 void AdapterHandlerEntry::save_code(unsigned char* buffer, int length) { 3085 _saved_code = NEW_C_HEAP_ARRAY(unsigned char, length, mtCode); 3086 _saved_code_length = length; 3087 memcpy(_saved_code, buffer, length); 3088 } 3089 3090 3091 bool AdapterHandlerEntry::compare_code(AdapterHandlerEntry* other) { 3092 assert(_saved_code != nullptr && other->_saved_code != nullptr, "code not saved"); 3093 3094 if (other->_saved_code_length != _saved_code_length) { 3095 return false; 3096 } 3097 3098 return memcmp(other->_saved_code, _saved_code, _saved_code_length) == 0; 3099 } 3100 #endif 3101 3102 3103 /** 3104 * Create a native wrapper for this native method. The wrapper converts the 3105 * Java-compiled calling convention to the native convention, handles 3106 * arguments, and transitions to native. On return from the native we transition 3107 * back to java blocking if a safepoint is in progress. 3108 */ 3109 void AdapterHandlerLibrary::create_native_wrapper(const methodHandle& method) { 3110 ResourceMark rm; 3111 nmethod* nm = nullptr; 3112 3113 // Check if memory should be freed before allocation 3114 CodeCache::gc_on_allocation(); 3115 3116 assert(method->is_native(), "must be native"); 3117 assert(method->is_special_native_intrinsic() || 3118 method->has_native_function(), "must have something valid to call!"); 3119 3120 { 3121 // Perform the work while holding the lock, but perform any printing outside the lock 3122 MutexLocker mu(AdapterHandlerLibrary_lock); 3123 // See if somebody beat us to it 3124 if (method->code() != nullptr) { 3125 return; 3126 } 3127 3128 const int compile_id = CompileBroker::assign_compile_id(method, CompileBroker::standard_entry_bci); 3129 assert(compile_id > 0, "Must generate native wrapper"); 3130 3131 3132 ResourceMark rm; 3133 BufferBlob* buf = buffer_blob(); // the temporary code buffer in CodeCache 3134 if (buf != nullptr) { 3135 CodeBuffer buffer(buf); 3136 3137 if (method->is_continuation_enter_intrinsic()) { 3138 buffer.initialize_stubs_size(192); 3139 } 3140 3141 struct { double data[20]; } locs_buf; 3142 struct { double data[20]; } stubs_locs_buf; 3143 buffer.insts()->initialize_shared_locs((relocInfo*)&locs_buf, sizeof(locs_buf) / sizeof(relocInfo)); 3144 #if defined(AARCH64) || defined(PPC64) 3145 // On AArch64 with ZGC and nmethod entry barriers, we need all oops to be 3146 // in the constant pool to ensure ordering between the barrier and oops 3147 // accesses. For native_wrappers we need a constant. 3148 // On PPC64 the continuation enter intrinsic needs the constant pool for the compiled 3149 // static java call that is resolved in the runtime. 3150 if (PPC64_ONLY(method->is_continuation_enter_intrinsic() &&) true) { 3151 buffer.initialize_consts_size(8 PPC64_ONLY(+ 24)); 3152 } 3153 #endif 3154 buffer.stubs()->initialize_shared_locs((relocInfo*)&stubs_locs_buf, sizeof(stubs_locs_buf) / sizeof(relocInfo)); 3155 MacroAssembler _masm(&buffer); 3156 3157 // Fill in the signature array, for the calling-convention call. 3158 const int total_args_passed = method->size_of_parameters(); 3159 3160 VMRegPair stack_regs[16]; 3161 VMRegPair* regs = (total_args_passed <= 16) ? stack_regs : NEW_RESOURCE_ARRAY(VMRegPair, total_args_passed); 3162 3163 AdapterSignatureIterator si(method->signature(), method->constMethod()->fingerprint(), 3164 method->is_static(), total_args_passed); 3165 BasicType* sig_bt = si.basic_types(); 3166 assert(si.slots() == total_args_passed, ""); 3167 BasicType ret_type = si.return_type(); 3168 3169 // Now get the compiled-Java arguments layout. 3170 SharedRuntime::java_calling_convention(sig_bt, regs, total_args_passed); 3171 3172 // Generate the compiled-to-native wrapper code 3173 nm = SharedRuntime::generate_native_wrapper(&_masm, method, compile_id, sig_bt, regs, ret_type); 3174 3175 if (nm != nullptr) { 3176 { 3177 MutexLocker pl(NMethodState_lock, Mutex::_no_safepoint_check_flag); 3178 if (nm->make_in_use()) { 3179 method->set_code(method, nm); 3180 } 3181 } 3182 3183 DirectiveSet* directive = DirectivesStack::getMatchingDirective(method, CompileBroker::compiler(CompLevel_simple)); 3184 if (directive->PrintAssemblyOption) { 3185 nm->print_code(); 3186 } 3187 DirectivesStack::release(directive); 3188 } 3189 } 3190 } // Unlock AdapterHandlerLibrary_lock 3191 3192 3193 // Install the generated code. 3194 if (nm != nullptr) { 3195 const char *msg = method->is_static() ? "(static)" : ""; 3196 CompileTask::print_ul(nm, msg); 3197 if (PrintCompilation) { 3198 ttyLocker ttyl; 3199 CompileTask::print(tty, nm, msg); 3200 } 3201 nm->post_compiled_method_load_event(); 3202 } 3203 } 3204 3205 // ------------------------------------------------------------------------- 3206 // Java-Java calling convention 3207 // (what you use when Java calls Java) 3208 3209 //------------------------------name_for_receiver---------------------------------- 3210 // For a given signature, return the VMReg for parameter 0. 3211 VMReg SharedRuntime::name_for_receiver() { 3212 VMRegPair regs; 3213 BasicType sig_bt = T_OBJECT; 3214 (void) java_calling_convention(&sig_bt, ®s, 1); 3215 // Return argument 0 register. In the LP64 build pointers 3216 // take 2 registers, but the VM wants only the 'main' name. 3217 return regs.first(); 3218 } 3219 3220 VMRegPair *SharedRuntime::find_callee_arguments(Symbol* sig, bool has_receiver, bool has_appendix, int* arg_size) { 3221 // This method is returning a data structure allocating as a 3222 // ResourceObject, so do not put any ResourceMarks in here. 3223 3224 BasicType *sig_bt = NEW_RESOURCE_ARRAY(BasicType, 256); 3225 VMRegPair *regs = NEW_RESOURCE_ARRAY(VMRegPair, 256); 3226 int cnt = 0; 3227 if (has_receiver) { 3228 sig_bt[cnt++] = T_OBJECT; // Receiver is argument 0; not in signature 3229 } 3230 3231 for (SignatureStream ss(sig); !ss.at_return_type(); ss.next()) { 3232 BasicType type = ss.type(); 3233 sig_bt[cnt++] = type; 3234 if (is_double_word_type(type)) 3235 sig_bt[cnt++] = T_VOID; 3236 } 3237 3238 if (has_appendix) { 3239 sig_bt[cnt++] = T_OBJECT; 3240 } 3241 3242 assert(cnt < 256, "grow table size"); 3243 3244 int comp_args_on_stack; 3245 comp_args_on_stack = java_calling_convention(sig_bt, regs, cnt); 3246 3247 // the calling convention doesn't count out_preserve_stack_slots so 3248 // we must add that in to get "true" stack offsets. 3249 3250 if (comp_args_on_stack) { 3251 for (int i = 0; i < cnt; i++) { 3252 VMReg reg1 = regs[i].first(); 3253 if (reg1->is_stack()) { 3254 // Yuck 3255 reg1 = reg1->bias(out_preserve_stack_slots()); 3256 } 3257 VMReg reg2 = regs[i].second(); 3258 if (reg2->is_stack()) { 3259 // Yuck 3260 reg2 = reg2->bias(out_preserve_stack_slots()); 3261 } 3262 regs[i].set_pair(reg2, reg1); 3263 } 3264 } 3265 3266 // results 3267 *arg_size = cnt; 3268 return regs; 3269 } 3270 3271 // OSR Migration Code 3272 // 3273 // This code is used convert interpreter frames into compiled frames. It is 3274 // called from very start of a compiled OSR nmethod. A temp array is 3275 // allocated to hold the interesting bits of the interpreter frame. All 3276 // active locks are inflated to allow them to move. The displaced headers and 3277 // active interpreter locals are copied into the temp buffer. Then we return 3278 // back to the compiled code. The compiled code then pops the current 3279 // interpreter frame off the stack and pushes a new compiled frame. Then it 3280 // copies the interpreter locals and displaced headers where it wants. 3281 // Finally it calls back to free the temp buffer. 3282 // 3283 // All of this is done NOT at any Safepoint, nor is any safepoint or GC allowed. 3284 3285 JRT_LEAF(intptr_t*, SharedRuntime::OSR_migration_begin( JavaThread *current) ) 3286 assert(current == JavaThread::current(), "pre-condition"); 3287 JFR_ONLY(Jfr::check_and_process_sample_request(current);) 3288 // During OSR migration, we unwind the interpreted frame and replace it with a compiled 3289 // frame. The stack watermark code below ensures that the interpreted frame is processed 3290 // before it gets unwound. This is helpful as the size of the compiled frame could be 3291 // larger than the interpreted frame, which could result in the new frame not being 3292 // processed correctly. 3293 StackWatermarkSet::before_unwind(current); 3294 3295 // 3296 // This code is dependent on the memory layout of the interpreter local 3297 // array and the monitors. On all of our platforms the layout is identical 3298 // so this code is shared. If some platform lays the their arrays out 3299 // differently then this code could move to platform specific code or 3300 // the code here could be modified to copy items one at a time using 3301 // frame accessor methods and be platform independent. 3302 3303 frame fr = current->last_frame(); 3304 assert(fr.is_interpreted_frame(), ""); 3305 assert(fr.interpreter_frame_expression_stack_size()==0, "only handle empty stacks"); 3306 3307 // Figure out how many monitors are active. 3308 int active_monitor_count = 0; 3309 for (BasicObjectLock *kptr = fr.interpreter_frame_monitor_end(); 3310 kptr < fr.interpreter_frame_monitor_begin(); 3311 kptr = fr.next_monitor_in_interpreter_frame(kptr) ) { 3312 if (kptr->obj() != nullptr) active_monitor_count++; 3313 } 3314 3315 // QQQ we could place number of active monitors in the array so that compiled code 3316 // could double check it. 3317 3318 Method* moop = fr.interpreter_frame_method(); 3319 int max_locals = moop->max_locals(); 3320 // Allocate temp buffer, 1 word per local & 2 per active monitor 3321 int buf_size_words = max_locals + active_monitor_count * BasicObjectLock::size(); 3322 intptr_t *buf = NEW_C_HEAP_ARRAY(intptr_t,buf_size_words, mtCode); 3323 3324 // Copy the locals. Order is preserved so that loading of longs works. 3325 // Since there's no GC I can copy the oops blindly. 3326 assert(sizeof(HeapWord)==sizeof(intptr_t), "fix this code"); 3327 Copy::disjoint_words((HeapWord*)fr.interpreter_frame_local_at(max_locals-1), 3328 (HeapWord*)&buf[0], 3329 max_locals); 3330 3331 // Inflate locks. Copy the displaced headers. Be careful, there can be holes. 3332 int i = max_locals; 3333 for (BasicObjectLock *kptr2 = fr.interpreter_frame_monitor_end(); 3334 kptr2 < fr.interpreter_frame_monitor_begin(); 3335 kptr2 = fr.next_monitor_in_interpreter_frame(kptr2) ) { 3336 if (kptr2->obj() != nullptr) { // Avoid 'holes' in the monitor array 3337 BasicLock *lock = kptr2->lock(); 3338 if (LockingMode == LM_LEGACY) { 3339 // Inflate so the object's header no longer refers to the BasicLock. 3340 if (lock->displaced_header().is_unlocked()) { 3341 // The object is locked and the resulting ObjectMonitor* will also be 3342 // locked so it can't be async deflated until ownership is dropped. 3343 // See the big comment in basicLock.cpp: BasicLock::move_to(). 3344 ObjectSynchronizer::inflate_helper(kptr2->obj()); 3345 } 3346 // Now the displaced header is free to move because the 3347 // object's header no longer refers to it. 3348 buf[i] = (intptr_t)lock->displaced_header().value(); 3349 } else if (UseObjectMonitorTable) { 3350 buf[i] = (intptr_t)lock->object_monitor_cache(); 3351 } 3352 #ifdef ASSERT 3353 else { 3354 buf[i] = badDispHeaderOSR; 3355 } 3356 #endif 3357 i++; 3358 buf[i++] = cast_from_oop<intptr_t>(kptr2->obj()); 3359 } 3360 } 3361 assert(i - max_locals == active_monitor_count*2, "found the expected number of monitors"); 3362 3363 RegisterMap map(current, 3364 RegisterMap::UpdateMap::skip, 3365 RegisterMap::ProcessFrames::include, 3366 RegisterMap::WalkContinuation::skip); 3367 frame sender = fr.sender(&map); 3368 if (sender.is_interpreted_frame()) { 3369 current->push_cont_fastpath(sender.sp()); 3370 } 3371 3372 return buf; 3373 JRT_END 3374 3375 JRT_LEAF(void, SharedRuntime::OSR_migration_end( intptr_t* buf) ) 3376 FREE_C_HEAP_ARRAY(intptr_t, buf); 3377 JRT_END 3378 3379 bool AdapterHandlerLibrary::contains(const CodeBlob* b) { 3380 bool found = false; 3381 #if INCLUDE_CDS 3382 if (AOTCodeCache::is_using_adapter()) { 3383 auto findblob_archived_table = [&] (AdapterHandlerEntry* handler) { 3384 return (found = (b == CodeCache::find_blob(handler->get_i2c_entry()))); 3385 }; 3386 _aot_adapter_handler_table.iterate(findblob_archived_table); 3387 } 3388 #endif // INCLUDE_CDS 3389 if (!found) { 3390 auto findblob_runtime_table = [&] (AdapterFingerPrint* key, AdapterHandlerEntry* a) { 3391 return (found = (b == CodeCache::find_blob(a->get_i2c_entry()))); 3392 }; 3393 assert_locked_or_safepoint(AdapterHandlerLibrary_lock); 3394 _adapter_handler_table->iterate(findblob_runtime_table); 3395 } 3396 return found; 3397 } 3398 3399 const char* AdapterHandlerLibrary::name(AdapterFingerPrint* fingerprint) { 3400 return fingerprint->as_basic_args_string(); 3401 } 3402 3403 uint32_t AdapterHandlerLibrary::id(AdapterFingerPrint* fingerprint) { 3404 unsigned int hash = fingerprint->compute_hash(); 3405 return hash; 3406 } 3407 3408 void AdapterHandlerLibrary::print_handler_on(outputStream* st, const CodeBlob* b) { 3409 bool found = false; 3410 #if INCLUDE_CDS 3411 if (AOTCodeCache::is_using_adapter()) { 3412 auto findblob_archived_table = [&] (AdapterHandlerEntry* handler) { 3413 if (b == CodeCache::find_blob(handler->get_i2c_entry())) { 3414 found = true; 3415 st->print("Adapter for signature: "); 3416 handler->print_adapter_on(st); 3417 return true; 3418 } else { 3419 return false; // keep looking 3420 } 3421 }; 3422 _aot_adapter_handler_table.iterate(findblob_archived_table); 3423 } 3424 #endif // INCLUDE_CDS 3425 if (!found) { 3426 auto findblob_runtime_table = [&] (AdapterFingerPrint* key, AdapterHandlerEntry* a) { 3427 if (b == CodeCache::find_blob(a->get_i2c_entry())) { 3428 found = true; 3429 st->print("Adapter for signature: "); 3430 a->print_adapter_on(st); 3431 return true; 3432 } else { 3433 return false; // keep looking 3434 } 3435 }; 3436 assert_locked_or_safepoint(AdapterHandlerLibrary_lock); 3437 _adapter_handler_table->iterate(findblob_runtime_table); 3438 } 3439 assert(found, "Should have found handler"); 3440 } 3441 3442 void AdapterHandlerEntry::print_adapter_on(outputStream* st) const { 3443 st->print("AHE@" INTPTR_FORMAT ": %s", p2i(this), fingerprint()->as_string()); 3444 if (get_i2c_entry() != nullptr) { 3445 st->print(" i2c: " INTPTR_FORMAT, p2i(get_i2c_entry())); 3446 } 3447 if (get_c2i_entry() != nullptr) { 3448 st->print(" c2i: " INTPTR_FORMAT, p2i(get_c2i_entry())); 3449 } 3450 if (get_c2i_unverified_entry() != nullptr) { 3451 st->print(" c2iUV: " INTPTR_FORMAT, p2i(get_c2i_unverified_entry())); 3452 } 3453 if (get_c2i_no_clinit_check_entry() != nullptr) { 3454 st->print(" c2iNCI: " INTPTR_FORMAT, p2i(get_c2i_no_clinit_check_entry())); 3455 } 3456 st->cr(); 3457 } 3458 3459 #ifndef PRODUCT 3460 3461 void AdapterHandlerLibrary::print_statistics() { 3462 print_table_statistics(); 3463 } 3464 3465 #endif /* PRODUCT */ 3466 3467 bool AdapterHandlerLibrary::is_abstract_method_adapter(AdapterHandlerEntry* entry) { 3468 if (entry == _abstract_method_handler) { 3469 return true; 3470 } 3471 return false; 3472 } 3473 3474 JRT_LEAF(void, SharedRuntime::enable_stack_reserved_zone(JavaThread* current)) 3475 assert(current == JavaThread::current(), "pre-condition"); 3476 StackOverflow* overflow_state = current->stack_overflow_state(); 3477 overflow_state->enable_stack_reserved_zone(/*check_if_disabled*/true); 3478 overflow_state->set_reserved_stack_activation(current->stack_base()); 3479 JRT_END 3480 3481 frame SharedRuntime::look_for_reserved_stack_annotated_method(JavaThread* current, frame fr) { 3482 ResourceMark rm(current); 3483 frame activation; 3484 nmethod* nm = nullptr; 3485 int count = 1; 3486 3487 assert(fr.is_java_frame(), "Must start on Java frame"); 3488 3489 RegisterMap map(JavaThread::current(), 3490 RegisterMap::UpdateMap::skip, 3491 RegisterMap::ProcessFrames::skip, 3492 RegisterMap::WalkContinuation::skip); // don't walk continuations 3493 for (; !fr.is_first_frame(); fr = fr.sender(&map)) { 3494 if (!fr.is_java_frame()) { 3495 continue; 3496 } 3497 3498 Method* method = nullptr; 3499 bool found = false; 3500 if (fr.is_interpreted_frame()) { 3501 method = fr.interpreter_frame_method(); 3502 if (method != nullptr && method->has_reserved_stack_access()) { 3503 found = true; 3504 } 3505 } else { 3506 CodeBlob* cb = fr.cb(); 3507 if (cb != nullptr && cb->is_nmethod()) { 3508 nm = cb->as_nmethod(); 3509 method = nm->method(); 3510 // scope_desc_near() must be used, instead of scope_desc_at() because on 3511 // SPARC, the pcDesc can be on the delay slot after the call instruction. 3512 for (ScopeDesc *sd = nm->scope_desc_near(fr.pc()); sd != nullptr; sd = sd->sender()) { 3513 method = sd->method(); 3514 if (method != nullptr && method->has_reserved_stack_access()) { 3515 found = true; 3516 } 3517 } 3518 } 3519 } 3520 if (found) { 3521 activation = fr; 3522 warning("Potentially dangerous stack overflow in " 3523 "ReservedStackAccess annotated method %s [%d]", 3524 method->name_and_sig_as_C_string(), count++); 3525 EventReservedStackActivation event; 3526 if (event.should_commit()) { 3527 event.set_method(method); 3528 event.commit(); 3529 } 3530 } 3531 } 3532 return activation; 3533 } 3534 3535 void SharedRuntime::on_slowpath_allocation_exit(JavaThread* current) { 3536 // After any safepoint, just before going back to compiled code, 3537 // we inform the GC that we will be doing initializing writes to 3538 // this object in the future without emitting card-marks, so 3539 // GC may take any compensating steps. 3540 3541 oop new_obj = current->vm_result_oop(); 3542 if (new_obj == nullptr) return; 3543 3544 BarrierSet *bs = BarrierSet::barrier_set(); 3545 bs->on_slowpath_allocation_exit(current, new_obj); 3546 }