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