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