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