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