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