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