1 /*
   2  * Copyright (c) 1997, 2025, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "cds/archiveBuilder.hpp"
  26 #include "cds/archiveUtils.inline.hpp"
  27 #include "classfile/classLoader.hpp"
  28 #include "classfile/javaClasses.inline.hpp"
  29 #include "classfile/stringTable.hpp"
  30 #include "classfile/vmClasses.hpp"
  31 #include "classfile/vmSymbols.hpp"
  32 #include "code/aotCodeCache.hpp"
  33 #include "code/codeCache.hpp"
  34 #include "code/compiledIC.hpp"
  35 #include "code/nmethod.inline.hpp"
  36 #include "code/scopeDesc.hpp"
  37 #include "code/vtableStubs.hpp"
  38 #include "compiler/abstractCompiler.hpp"
  39 #include "compiler/compileBroker.hpp"
  40 #include "compiler/disassembler.hpp"
  41 #include "gc/shared/barrierSet.hpp"
  42 #include "gc/shared/collectedHeap.hpp"
  43 #include "interpreter/interpreter.hpp"
  44 #include "interpreter/interpreterRuntime.hpp"
  45 #include "jvm.h"
  46 #include "jfr/jfrEvents.hpp"
  47 #include "logging/log.hpp"
  48 #include "memory/resourceArea.hpp"
  49 #include "memory/universe.hpp"
  50 #include "metaprogramming/primitiveConversions.hpp"
  51 #include "oops/klass.hpp"
  52 #include "oops/method.inline.hpp"
  53 #include "oops/objArrayKlass.hpp"
  54 #include "oops/oop.inline.hpp"
  55 #include "prims/forte.hpp"
  56 #include "prims/jvmtiExport.hpp"
  57 #include "prims/jvmtiThreadState.hpp"
  58 #include "prims/methodHandles.hpp"
  59 #include "prims/nativeLookup.hpp"
  60 #include "runtime/arguments.hpp"
  61 #include "runtime/atomic.hpp"
  62 #include "runtime/basicLock.inline.hpp"
  63 #include "runtime/frame.inline.hpp"
  64 #include "runtime/handles.inline.hpp"
  65 #include "runtime/init.hpp"
  66 #include "runtime/interfaceSupport.inline.hpp"
  67 #include "runtime/java.hpp"
  68 #include "runtime/javaCalls.hpp"
  69 #include "runtime/jniHandles.inline.hpp"
  70 #include "runtime/perfData.hpp"
  71 #include "runtime/sharedRuntime.hpp"
  72 #include "runtime/stackWatermarkSet.hpp"
  73 #include "runtime/stubRoutines.hpp"
  74 #include "runtime/synchronizer.inline.hpp"
  75 #include "runtime/timerTrace.hpp"
  76 #include "runtime/vframe.inline.hpp"
  77 #include "runtime/vframeArray.hpp"
  78 #include "runtime/vm_version.hpp"
  79 #include "utilities/copy.hpp"
  80 #include "utilities/dtrace.hpp"
  81 #include "utilities/events.hpp"
  82 #include "utilities/globalDefinitions.hpp"
  83 #include "utilities/resourceHash.hpp"
  84 #include "utilities/macros.hpp"
  85 #include "utilities/xmlstream.hpp"
  86 #ifdef COMPILER1
  87 #include "c1/c1_Runtime1.hpp"
  88 #endif
  89 #if INCLUDE_JFR
  90 #include "jfr/jfr.hpp"
  91 #endif
  92 
  93 // Shared runtime stub routines reside in their own unique blob with a
  94 // single entry point
  95 
  96 
  97 #define SHARED_STUB_FIELD_DEFINE(name, type) \
  98   type        SharedRuntime::BLOB_FIELD_NAME(name);
  99   SHARED_STUBS_DO(SHARED_STUB_FIELD_DEFINE)
 100 #undef SHARED_STUB_FIELD_DEFINE
 101 
 102 nmethod*            SharedRuntime::_cont_doYield_stub;
 103 
 104 #define SHARED_STUB_NAME_DECLARE(name, type) "Shared Runtime " # name "_blob",
 105 const char *SharedRuntime::_stub_names[] = {
 106   SHARED_STUBS_DO(SHARED_STUB_NAME_DECLARE)
 107 };
 108 
 109 //----------------------------generate_stubs-----------------------------------
 110 void SharedRuntime::generate_initial_stubs() {
 111   // Build this early so it's available for the interpreter.
 112   _throw_StackOverflowError_blob =
 113     generate_throw_exception(SharedStubId::throw_StackOverflowError_id,
 114                              CAST_FROM_FN_PTR(address, SharedRuntime::throw_StackOverflowError));
 115 }
 116 
 117 void SharedRuntime::generate_stubs() {
 118   _wrong_method_blob =
 119     generate_resolve_blob(SharedStubId::wrong_method_id,
 120                           CAST_FROM_FN_PTR(address, SharedRuntime::handle_wrong_method));
 121   _wrong_method_abstract_blob =
 122     generate_resolve_blob(SharedStubId::wrong_method_abstract_id,
 123                           CAST_FROM_FN_PTR(address, SharedRuntime::handle_wrong_method_abstract));
 124   _ic_miss_blob =
 125     generate_resolve_blob(SharedStubId::ic_miss_id,
 126                           CAST_FROM_FN_PTR(address, SharedRuntime::handle_wrong_method_ic_miss));
 127   _resolve_opt_virtual_call_blob =
 128     generate_resolve_blob(SharedStubId::resolve_opt_virtual_call_id,
 129                           CAST_FROM_FN_PTR(address, SharedRuntime::resolve_opt_virtual_call_C));
 130   _resolve_virtual_call_blob =
 131     generate_resolve_blob(SharedStubId::resolve_virtual_call_id,
 132                           CAST_FROM_FN_PTR(address, SharedRuntime::resolve_virtual_call_C));
 133   _resolve_static_call_blob =
 134     generate_resolve_blob(SharedStubId::resolve_static_call_id,
 135                           CAST_FROM_FN_PTR(address, SharedRuntime::resolve_static_call_C));
 136 
 137   _throw_delayed_StackOverflowError_blob =
 138     generate_throw_exception(SharedStubId::throw_delayed_StackOverflowError_id,
 139                              CAST_FROM_FN_PTR(address, SharedRuntime::throw_delayed_StackOverflowError));
 140 
 141   _throw_AbstractMethodError_blob =
 142     generate_throw_exception(SharedStubId::throw_AbstractMethodError_id,
 143                              CAST_FROM_FN_PTR(address, SharedRuntime::throw_AbstractMethodError));
 144 
 145   _throw_IncompatibleClassChangeError_blob =
 146     generate_throw_exception(SharedStubId::throw_IncompatibleClassChangeError_id,
 147                              CAST_FROM_FN_PTR(address, SharedRuntime::throw_IncompatibleClassChangeError));
 148 
 149   _throw_NullPointerException_at_call_blob =
 150     generate_throw_exception(SharedStubId::throw_NullPointerException_at_call_id,
 151                              CAST_FROM_FN_PTR(address, SharedRuntime::throw_NullPointerException_at_call));
 152 
 153 #if COMPILER2_OR_JVMCI
 154   // Vectors are generated only by C2 and JVMCI.
 155   bool support_wide = is_wide_vector(MaxVectorSize);
 156   if (support_wide) {
 157     _polling_page_vectors_safepoint_handler_blob =
 158       generate_handler_blob(SharedStubId::polling_page_vectors_safepoint_handler_id,
 159                             CAST_FROM_FN_PTR(address, SafepointSynchronize::handle_polling_page_exception));
 160   }
 161 #endif // COMPILER2_OR_JVMCI
 162   _polling_page_safepoint_handler_blob =
 163     generate_handler_blob(SharedStubId::polling_page_safepoint_handler_id,
 164                           CAST_FROM_FN_PTR(address, SafepointSynchronize::handle_polling_page_exception));
 165   _polling_page_return_handler_blob =
 166     generate_handler_blob(SharedStubId::polling_page_return_handler_id,
 167                           CAST_FROM_FN_PTR(address, SafepointSynchronize::handle_polling_page_exception));
 168 
 169   generate_deopt_blob();
 170 }
 171 
 172 void SharedRuntime::init_adapter_library() {
 173   AdapterHandlerLibrary::initialize();
 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   Bytecode_invoke bytecode(caller, bci);
1194   int bytecode_index = bytecode.index();
1195   bc = bytecode.invoke_code();
1196 
1197   methodHandle attached_method(current, extract_attached_method(vfst));
1198   if (attached_method.not_null()) {
1199     Method* callee = bytecode.static_target(CHECK_NH);
1200     vmIntrinsics::ID id = callee->intrinsic_id();
1201     // When VM replaces MH.invokeBasic/linkTo* call with a direct/virtual call,
1202     // it attaches statically resolved method to the call site.
1203     if (MethodHandles::is_signature_polymorphic(id) &&
1204         MethodHandles::is_signature_polymorphic_intrinsic(id)) {
1205       bc = MethodHandles::signature_polymorphic_intrinsic_bytecode(id);
1206 
1207       // Adjust invocation mode according to the attached method.
1208       switch (bc) {
1209         case Bytecodes::_invokevirtual:
1210           if (attached_method->method_holder()->is_interface()) {
1211             bc = Bytecodes::_invokeinterface;
1212           }
1213           break;
1214         case Bytecodes::_invokeinterface:
1215           if (!attached_method->method_holder()->is_interface()) {
1216             bc = Bytecodes::_invokevirtual;
1217           }
1218           break;
1219         case Bytecodes::_invokehandle:
1220           if (!MethodHandles::is_signature_polymorphic_method(attached_method())) {
1221             bc = attached_method->is_static() ? Bytecodes::_invokestatic
1222                                               : Bytecodes::_invokevirtual;
1223           }
1224           break;
1225         default:
1226           break;
1227       }
1228     }
1229   }
1230 
1231   assert(bc != Bytecodes::_illegal, "not initialized");
1232 
1233   bool has_receiver = bc != Bytecodes::_invokestatic &&
1234                       bc != Bytecodes::_invokedynamic &&
1235                       bc != Bytecodes::_invokehandle;
1236 
1237   // Find receiver for non-static call
1238   if (has_receiver) {
1239     // This register map must be update since we need to find the receiver for
1240     // compiled frames. The receiver might be in a register.
1241     RegisterMap reg_map2(current,
1242                          RegisterMap::UpdateMap::include,
1243                          RegisterMap::ProcessFrames::include,
1244                          RegisterMap::WalkContinuation::skip);
1245     frame stubFrame   = current->last_frame();
1246     // Caller-frame is a compiled frame
1247     frame callerFrame = stubFrame.sender(&reg_map2);
1248 
1249     if (attached_method.is_null()) {
1250       Method* callee = bytecode.static_target(CHECK_NH);
1251       if (callee == nullptr) {
1252         THROW_(vmSymbols::java_lang_NoSuchMethodException(), nullHandle);
1253       }
1254     }
1255 
1256     // Retrieve from a compiled argument list
1257     receiver = Handle(current, callerFrame.retrieve_receiver(&reg_map2));
1258     assert(oopDesc::is_oop_or_null(receiver()), "");
1259 
1260     if (receiver.is_null()) {
1261       THROW_(vmSymbols::java_lang_NullPointerException(), nullHandle);
1262     }
1263   }
1264 
1265   // Resolve method
1266   if (attached_method.not_null()) {
1267     // Parameterized by attached method.
1268     LinkResolver::resolve_invoke(callinfo, receiver, attached_method, bc, CHECK_NH);
1269   } else {
1270     // Parameterized by bytecode.
1271     constantPoolHandle constants(current, caller->constants());
1272     LinkResolver::resolve_invoke(callinfo, receiver, constants, bytecode_index, bc, CHECK_NH);
1273   }
1274 
1275 #ifdef ASSERT
1276   // Check that the receiver klass is of the right subtype and that it is initialized for virtual calls
1277   if (has_receiver) {
1278     assert(receiver.not_null(), "should have thrown exception");
1279     Klass* receiver_klass = receiver->klass();
1280     Klass* rk = nullptr;
1281     if (attached_method.not_null()) {
1282       // In case there's resolved method attached, use its holder during the check.
1283       rk = attached_method->method_holder();
1284     } else {
1285       // Klass is already loaded.
1286       constantPoolHandle constants(current, caller->constants());
1287       rk = constants->klass_ref_at(bytecode_index, bc, CHECK_NH);
1288     }
1289     Klass* static_receiver_klass = rk;
1290     assert(receiver_klass->is_subtype_of(static_receiver_klass),
1291            "actual receiver must be subclass of static receiver klass");
1292     if (receiver_klass->is_instance_klass()) {
1293       if (InstanceKlass::cast(receiver_klass)->is_not_initialized()) {
1294         tty->print_cr("ERROR: Klass not yet initialized!!");
1295         receiver_klass->print();
1296       }
1297       assert(!InstanceKlass::cast(receiver_klass)->is_not_initialized(), "receiver_klass must be initialized");
1298     }
1299   }
1300 #endif
1301 
1302   return receiver;
1303 }
1304 
1305 methodHandle SharedRuntime::find_callee_method(TRAPS) {
1306   JavaThread* current = THREAD;
1307   ResourceMark rm(current);
1308   // We need first to check if any Java activations (compiled, interpreted)
1309   // exist on the stack since last JavaCall.  If not, we need
1310   // to get the target method from the JavaCall wrapper.
1311   vframeStream vfst(current, true);  // Do not skip any javaCalls
1312   methodHandle callee_method;
1313   if (vfst.at_end()) {
1314     // No Java frames were found on stack since we did the JavaCall.
1315     // Hence the stack can only contain an entry_frame.  We need to
1316     // find the target method from the stub frame.
1317     RegisterMap reg_map(current,
1318                         RegisterMap::UpdateMap::skip,
1319                         RegisterMap::ProcessFrames::include,
1320                         RegisterMap::WalkContinuation::skip);
1321     frame fr = current->last_frame();
1322     assert(fr.is_runtime_frame(), "must be a runtimeStub");
1323     fr = fr.sender(&reg_map);
1324     assert(fr.is_entry_frame(), "must be");
1325     // fr is now pointing to the entry frame.
1326     callee_method = methodHandle(current, fr.entry_frame_call_wrapper()->callee_method());
1327   } else {
1328     Bytecodes::Code bc;
1329     CallInfo callinfo;
1330     find_callee_info_helper(vfst, bc, callinfo, CHECK_(methodHandle()));
1331     callee_method = methodHandle(current, callinfo.selected_method());
1332   }
1333   assert(callee_method()->is_method(), "must be");
1334   return callee_method;
1335 }
1336 
1337 // Resolves a call.
1338 methodHandle SharedRuntime::resolve_helper(bool is_virtual, bool is_optimized, TRAPS) {
1339   JavaThread* current = THREAD;
1340   ResourceMark rm(current);
1341   RegisterMap cbl_map(current,
1342                       RegisterMap::UpdateMap::skip,
1343                       RegisterMap::ProcessFrames::include,
1344                       RegisterMap::WalkContinuation::skip);
1345   frame caller_frame = current->last_frame().sender(&cbl_map);
1346 
1347   CodeBlob* caller_cb = caller_frame.cb();
1348   guarantee(caller_cb != nullptr && caller_cb->is_nmethod(), "must be called from compiled method");
1349   nmethod* caller_nm = caller_cb->as_nmethod();
1350 
1351   // determine call info & receiver
1352   // note: a) receiver is null for static calls
1353   //       b) an exception is thrown if receiver is null for non-static calls
1354   CallInfo call_info;
1355   Bytecodes::Code invoke_code = Bytecodes::_illegal;
1356   Handle receiver = find_callee_info(invoke_code, call_info, CHECK_(methodHandle()));
1357 
1358   NoSafepointVerifier nsv;
1359 
1360   methodHandle callee_method(current, call_info.selected_method());
1361 
1362   assert((!is_virtual && invoke_code == Bytecodes::_invokestatic ) ||
1363          (!is_virtual && invoke_code == Bytecodes::_invokespecial) ||
1364          (!is_virtual && invoke_code == Bytecodes::_invokehandle ) ||
1365          (!is_virtual && invoke_code == Bytecodes::_invokedynamic) ||
1366          ( is_virtual && invoke_code != Bytecodes::_invokestatic ), "inconsistent bytecode");
1367 
1368   assert(!caller_nm->is_unloading(), "It should not be unloading");
1369 
1370 #ifndef PRODUCT
1371   // tracing/debugging/statistics
1372   uint *addr = (is_optimized) ? (&_resolve_opt_virtual_ctr) :
1373                  (is_virtual) ? (&_resolve_virtual_ctr) :
1374                                 (&_resolve_static_ctr);
1375   Atomic::inc(addr);
1376 
1377   if (TraceCallFixup) {
1378     ResourceMark rm(current);
1379     tty->print("resolving %s%s (%s) call to",
1380                (is_optimized) ? "optimized " : "", (is_virtual) ? "virtual" : "static",
1381                Bytecodes::name(invoke_code));
1382     callee_method->print_short_name(tty);
1383     tty->print_cr(" at pc: " INTPTR_FORMAT " to code: " INTPTR_FORMAT,
1384                   p2i(caller_frame.pc()), p2i(callee_method->code()));
1385   }
1386 #endif
1387 
1388   if (invoke_code == Bytecodes::_invokestatic) {
1389     assert(callee_method->method_holder()->is_initialized() ||
1390            callee_method->method_holder()->is_reentrant_initialization(current),
1391            "invalid class initialization state for invoke_static");
1392     if (!VM_Version::supports_fast_class_init_checks() && callee_method->needs_clinit_barrier()) {
1393       // In order to keep class initialization check, do not patch call
1394       // site for static call when the class is not fully initialized.
1395       // Proper check is enforced by call site re-resolution on every invocation.
1396       //
1397       // When fast class initialization checks are supported (VM_Version::supports_fast_class_init_checks() == true),
1398       // explicit class initialization check is put in nmethod entry (VEP).
1399       assert(callee_method->method_holder()->is_linked(), "must be");
1400       return callee_method;
1401     }
1402   }
1403 
1404 
1405   // JSR 292 key invariant:
1406   // If the resolved method is a MethodHandle invoke target, the call
1407   // site must be a MethodHandle call site, because the lambda form might tail-call
1408   // leaving the stack in a state unknown to either caller or callee
1409 
1410   // Compute entry points. The computation of the entry points is independent of
1411   // patching the call.
1412 
1413   // Make sure the callee nmethod does not get deoptimized and removed before
1414   // we are done patching the code.
1415 
1416 
1417   CompiledICLocker ml(caller_nm);
1418   if (is_virtual && !is_optimized) {
1419     CompiledIC* inline_cache = CompiledIC_before(caller_nm, caller_frame.pc());
1420     inline_cache->update(&call_info, receiver->klass());
1421   } else {
1422     // Callsite is a direct call - set it to the destination method
1423     CompiledDirectCall* callsite = CompiledDirectCall::before(caller_frame.pc());
1424     callsite->set(callee_method);
1425   }
1426 
1427   return callee_method;
1428 }
1429 
1430 // Inline caches exist only in compiled code
1431 JRT_BLOCK_ENTRY(address, SharedRuntime::handle_wrong_method_ic_miss(JavaThread* current))
1432 #ifdef ASSERT
1433   RegisterMap reg_map(current,
1434                       RegisterMap::UpdateMap::skip,
1435                       RegisterMap::ProcessFrames::include,
1436                       RegisterMap::WalkContinuation::skip);
1437   frame stub_frame = current->last_frame();
1438   assert(stub_frame.is_runtime_frame(), "sanity check");
1439   frame caller_frame = stub_frame.sender(&reg_map);
1440   assert(!caller_frame.is_interpreted_frame() && !caller_frame.is_entry_frame() && !caller_frame.is_upcall_stub_frame(), "unexpected frame");
1441 #endif /* ASSERT */
1442 
1443   methodHandle callee_method;
1444   JRT_BLOCK
1445     callee_method = SharedRuntime::handle_ic_miss_helper(CHECK_NULL);
1446     // Return Method* through TLS
1447     current->set_vm_result_metadata(callee_method());
1448   JRT_BLOCK_END
1449   // return compiled code entry point after potential safepoints
1450   return get_resolved_entry(current, callee_method);
1451 JRT_END
1452 
1453 
1454 // Handle call site that has been made non-entrant
1455 JRT_BLOCK_ENTRY(address, SharedRuntime::handle_wrong_method(JavaThread* current))
1456   // 6243940 We might end up in here if the callee is deoptimized
1457   // as we race to call it.  We don't want to take a safepoint if
1458   // the caller was interpreted because the caller frame will look
1459   // interpreted to the stack walkers and arguments are now
1460   // "compiled" so it is much better to make this transition
1461   // invisible to the stack walking code. The i2c path will
1462   // place the callee method in the callee_target. It is stashed
1463   // there because if we try and find the callee by normal means a
1464   // safepoint is possible and have trouble gc'ing the compiled args.
1465   RegisterMap reg_map(current,
1466                       RegisterMap::UpdateMap::skip,
1467                       RegisterMap::ProcessFrames::include,
1468                       RegisterMap::WalkContinuation::skip);
1469   frame stub_frame = current->last_frame();
1470   assert(stub_frame.is_runtime_frame(), "sanity check");
1471   frame caller_frame = stub_frame.sender(&reg_map);
1472 
1473   if (caller_frame.is_interpreted_frame() ||
1474       caller_frame.is_entry_frame() ||
1475       caller_frame.is_upcall_stub_frame()) {
1476     Method* callee = current->callee_target();
1477     guarantee(callee != nullptr && callee->is_method(), "bad handshake");
1478     current->set_vm_result_metadata(callee);
1479     current->set_callee_target(nullptr);
1480     if (caller_frame.is_entry_frame() && VM_Version::supports_fast_class_init_checks()) {
1481       // Bypass class initialization checks in c2i when caller is in native.
1482       // JNI calls to static methods don't have class initialization checks.
1483       // Fast class initialization checks are present in c2i adapters and call into
1484       // SharedRuntime::handle_wrong_method() on the slow path.
1485       //
1486       // JVM upcalls may land here as well, but there's a proper check present in
1487       // LinkResolver::resolve_static_call (called from JavaCalls::call_static),
1488       // so bypassing it in c2i adapter is benign.
1489       return callee->get_c2i_no_clinit_check_entry();
1490     } else {
1491       return callee->get_c2i_entry();
1492     }
1493   }
1494 
1495   // Must be compiled to compiled path which is safe to stackwalk
1496   methodHandle callee_method;
1497   JRT_BLOCK
1498     // Force resolving of caller (if we called from compiled frame)
1499     callee_method = SharedRuntime::reresolve_call_site(CHECK_NULL);
1500     current->set_vm_result_metadata(callee_method());
1501   JRT_BLOCK_END
1502   // return compiled code entry point after potential safepoints
1503   return get_resolved_entry(current, callee_method);
1504 JRT_END
1505 
1506 // Handle abstract method call
1507 JRT_BLOCK_ENTRY(address, SharedRuntime::handle_wrong_method_abstract(JavaThread* current))
1508   // Verbose error message for AbstractMethodError.
1509   // Get the called method from the invoke bytecode.
1510   vframeStream vfst(current, true);
1511   assert(!vfst.at_end(), "Java frame must exist");
1512   methodHandle caller(current, vfst.method());
1513   Bytecode_invoke invoke(caller, vfst.bci());
1514   DEBUG_ONLY( invoke.verify(); )
1515 
1516   // Find the compiled caller frame.
1517   RegisterMap reg_map(current,
1518                       RegisterMap::UpdateMap::include,
1519                       RegisterMap::ProcessFrames::include,
1520                       RegisterMap::WalkContinuation::skip);
1521   frame stubFrame = current->last_frame();
1522   assert(stubFrame.is_runtime_frame(), "must be");
1523   frame callerFrame = stubFrame.sender(&reg_map);
1524   assert(callerFrame.is_compiled_frame(), "must be");
1525 
1526   // Install exception and return forward entry.
1527   address res = SharedRuntime::throw_AbstractMethodError_entry();
1528   JRT_BLOCK
1529     methodHandle callee(current, invoke.static_target(current));
1530     if (!callee.is_null()) {
1531       oop recv = callerFrame.retrieve_receiver(&reg_map);
1532       Klass *recv_klass = (recv != nullptr) ? recv->klass() : nullptr;
1533       res = StubRoutines::forward_exception_entry();
1534       LinkResolver::throw_abstract_method_error(callee, recv_klass, CHECK_(res));
1535     }
1536   JRT_BLOCK_END
1537   return res;
1538 JRT_END
1539 
1540 // return verified_code_entry if interp_only_mode is not set for the current thread;
1541 // otherwise return c2i entry.
1542 address SharedRuntime::get_resolved_entry(JavaThread* current, methodHandle callee_method) {
1543   if (current->is_interp_only_mode() && !callee_method->is_special_native_intrinsic()) {
1544     // In interp_only_mode we need to go to the interpreted entry
1545     // The c2i won't patch in this mode -- see fixup_callers_callsite
1546     return callee_method->get_c2i_entry();
1547   }
1548   assert(callee_method->verified_code_entry() != nullptr, " Jump to zero!");
1549   return callee_method->verified_code_entry();
1550 }
1551 
1552 // resolve a static call and patch code
1553 JRT_BLOCK_ENTRY(address, SharedRuntime::resolve_static_call_C(JavaThread* current ))
1554   methodHandle callee_method;
1555   bool enter_special = false;
1556   JRT_BLOCK
1557     callee_method = SharedRuntime::resolve_helper(false, false, CHECK_NULL);
1558     current->set_vm_result_metadata(callee_method());
1559   JRT_BLOCK_END
1560   // return compiled code entry point after potential safepoints
1561   return get_resolved_entry(current, callee_method);
1562 JRT_END
1563 
1564 // resolve virtual call and update inline cache to monomorphic
1565 JRT_BLOCK_ENTRY(address, SharedRuntime::resolve_virtual_call_C(JavaThread* current))
1566   methodHandle callee_method;
1567   JRT_BLOCK
1568     callee_method = SharedRuntime::resolve_helper(true, false, CHECK_NULL);
1569     current->set_vm_result_metadata(callee_method());
1570   JRT_BLOCK_END
1571   // return compiled code entry point after potential safepoints
1572   return get_resolved_entry(current, callee_method);
1573 JRT_END
1574 
1575 
1576 // Resolve a virtual call that can be statically bound (e.g., always
1577 // monomorphic, so it has no inline cache).  Patch code to resolved target.
1578 JRT_BLOCK_ENTRY(address, SharedRuntime::resolve_opt_virtual_call_C(JavaThread* current))
1579   methodHandle callee_method;
1580   JRT_BLOCK
1581     callee_method = SharedRuntime::resolve_helper(true, true, CHECK_NULL);
1582     current->set_vm_result_metadata(callee_method());
1583   JRT_BLOCK_END
1584   // return compiled code entry point after potential safepoints
1585   return get_resolved_entry(current, callee_method);
1586 JRT_END
1587 
1588 methodHandle SharedRuntime::handle_ic_miss_helper(TRAPS) {
1589   JavaThread* current = THREAD;
1590   ResourceMark rm(current);
1591   CallInfo call_info;
1592   Bytecodes::Code bc;
1593 
1594   // receiver is null for static calls. An exception is thrown for null
1595   // receivers for non-static calls
1596   Handle receiver = find_callee_info(bc, call_info, CHECK_(methodHandle()));
1597 
1598   methodHandle callee_method(current, call_info.selected_method());
1599 
1600 #ifndef PRODUCT
1601   Atomic::inc(&_ic_miss_ctr);
1602 
1603   // Statistics & Tracing
1604   if (TraceCallFixup) {
1605     ResourceMark rm(current);
1606     tty->print("IC miss (%s) call to", Bytecodes::name(bc));
1607     callee_method->print_short_name(tty);
1608     tty->print_cr(" code: " INTPTR_FORMAT, p2i(callee_method->code()));
1609   }
1610 
1611   if (ICMissHistogram) {
1612     MutexLocker m(VMStatistic_lock);
1613     RegisterMap reg_map(current,
1614                         RegisterMap::UpdateMap::skip,
1615                         RegisterMap::ProcessFrames::include,
1616                         RegisterMap::WalkContinuation::skip);
1617     frame f = current->last_frame().real_sender(&reg_map);// skip runtime stub
1618     // produce statistics under the lock
1619     trace_ic_miss(f.pc());
1620   }
1621 #endif
1622 
1623   // install an event collector so that when a vtable stub is created the
1624   // profiler can be notified via a DYNAMIC_CODE_GENERATED event. The
1625   // event can't be posted when the stub is created as locks are held
1626   // - instead the event will be deferred until the event collector goes
1627   // out of scope.
1628   JvmtiDynamicCodeEventCollector event_collector;
1629 
1630   // Update inline cache to megamorphic. Skip update if we are called from interpreted.
1631   RegisterMap reg_map(current,
1632                       RegisterMap::UpdateMap::skip,
1633                       RegisterMap::ProcessFrames::include,
1634                       RegisterMap::WalkContinuation::skip);
1635   frame caller_frame = current->last_frame().sender(&reg_map);
1636   CodeBlob* cb = caller_frame.cb();
1637   nmethod* caller_nm = cb->as_nmethod();
1638 
1639   CompiledICLocker ml(caller_nm);
1640   CompiledIC* inline_cache = CompiledIC_before(caller_nm, caller_frame.pc());
1641   inline_cache->update(&call_info, receiver()->klass());
1642 
1643   return callee_method;
1644 }
1645 
1646 //
1647 // Resets a call-site in compiled code so it will get resolved again.
1648 // This routines handles both virtual call sites, optimized virtual call
1649 // sites, and static call sites. Typically used to change a call sites
1650 // destination from compiled to interpreted.
1651 //
1652 methodHandle SharedRuntime::reresolve_call_site(TRAPS) {
1653   JavaThread* current = THREAD;
1654   ResourceMark rm(current);
1655   RegisterMap reg_map(current,
1656                       RegisterMap::UpdateMap::skip,
1657                       RegisterMap::ProcessFrames::include,
1658                       RegisterMap::WalkContinuation::skip);
1659   frame stub_frame = current->last_frame();
1660   assert(stub_frame.is_runtime_frame(), "must be a runtimeStub");
1661   frame caller = stub_frame.sender(&reg_map);
1662 
1663   // Do nothing if the frame isn't a live compiled frame.
1664   // nmethod could be deoptimized by the time we get here
1665   // so no update to the caller is needed.
1666 
1667   if ((caller.is_compiled_frame() && !caller.is_deoptimized_frame()) ||
1668       (caller.is_native_frame() && caller.cb()->as_nmethod()->method()->is_continuation_enter_intrinsic())) {
1669 
1670     address pc = caller.pc();
1671 
1672     nmethod* caller_nm = CodeCache::find_nmethod(pc);
1673     assert(caller_nm != nullptr, "did not find caller nmethod");
1674 
1675     // Default call_addr is the location of the "basic" call.
1676     // Determine the address of the call we a reresolving. With
1677     // Inline Caches we will always find a recognizable call.
1678     // With Inline Caches disabled we may or may not find a
1679     // recognizable call. We will always find a call for static
1680     // calls and for optimized virtual calls. For vanilla virtual
1681     // calls it depends on the state of the UseInlineCaches switch.
1682     //
1683     // With Inline Caches disabled we can get here for a virtual call
1684     // for two reasons:
1685     //   1 - calling an abstract method. The vtable for abstract methods
1686     //       will run us thru handle_wrong_method and we will eventually
1687     //       end up in the interpreter to throw the ame.
1688     //   2 - a racing deoptimization. We could be doing a vanilla vtable
1689     //       call and between the time we fetch the entry address and
1690     //       we jump to it the target gets deoptimized. Similar to 1
1691     //       we will wind up in the interprter (thru a c2i with c2).
1692     //
1693     CompiledICLocker ml(caller_nm);
1694     address call_addr = caller_nm->call_instruction_address(pc);
1695 
1696     if (call_addr != nullptr) {
1697       // On x86 the logic for finding a call instruction is blindly checking for a call opcode 5
1698       // bytes back in the instruction stream so we must also check for reloc info.
1699       RelocIterator iter(caller_nm, call_addr, call_addr+1);
1700       bool ret = iter.next(); // Get item
1701       if (ret) {
1702         switch (iter.type()) {
1703           case relocInfo::static_call_type:
1704           case relocInfo::opt_virtual_call_type: {
1705             CompiledDirectCall* cdc = CompiledDirectCall::at(call_addr);
1706             cdc->set_to_clean();
1707             break;
1708           }
1709 
1710           case relocInfo::virtual_call_type: {
1711             // compiled, dispatched call (which used to call an interpreted method)
1712             CompiledIC* inline_cache = CompiledIC_at(caller_nm, call_addr);
1713             inline_cache->set_to_clean();
1714             break;
1715           }
1716           default:
1717             break;
1718         }
1719       }
1720     }
1721   }
1722 
1723   methodHandle callee_method = find_callee_method(CHECK_(methodHandle()));
1724 
1725 
1726 #ifndef PRODUCT
1727   Atomic::inc(&_wrong_method_ctr);
1728 
1729   if (TraceCallFixup) {
1730     ResourceMark rm(current);
1731     tty->print("handle_wrong_method reresolving call to");
1732     callee_method->print_short_name(tty);
1733     tty->print_cr(" code: " INTPTR_FORMAT, p2i(callee_method->code()));
1734   }
1735 #endif
1736 
1737   return callee_method;
1738 }
1739 
1740 address SharedRuntime::handle_unsafe_access(JavaThread* thread, address next_pc) {
1741   // The faulting unsafe accesses should be changed to throw the error
1742   // synchronously instead. Meanwhile the faulting instruction will be
1743   // skipped over (effectively turning it into a no-op) and an
1744   // asynchronous exception will be raised which the thread will
1745   // handle at a later point. If the instruction is a load it will
1746   // return garbage.
1747 
1748   // Request an async exception.
1749   thread->set_pending_unsafe_access_error();
1750 
1751   // Return address of next instruction to execute.
1752   return next_pc;
1753 }
1754 
1755 #ifdef ASSERT
1756 void SharedRuntime::check_member_name_argument_is_last_argument(const methodHandle& method,
1757                                                                 const BasicType* sig_bt,
1758                                                                 const VMRegPair* regs) {
1759   ResourceMark rm;
1760   const int total_args_passed = method->size_of_parameters();
1761   const VMRegPair*    regs_with_member_name = regs;
1762         VMRegPair* regs_without_member_name = NEW_RESOURCE_ARRAY(VMRegPair, total_args_passed - 1);
1763 
1764   const int member_arg_pos = total_args_passed - 1;
1765   assert(member_arg_pos >= 0 && member_arg_pos < total_args_passed, "oob");
1766   assert(sig_bt[member_arg_pos] == T_OBJECT, "dispatch argument must be an object");
1767 
1768   java_calling_convention(sig_bt, regs_without_member_name, total_args_passed - 1);
1769 
1770   for (int i = 0; i < member_arg_pos; i++) {
1771     VMReg a =    regs_with_member_name[i].first();
1772     VMReg b = regs_without_member_name[i].first();
1773     assert(a->value() == b->value(), "register allocation mismatch: a= %d, b= %d", a->value(), b->value());
1774   }
1775   assert(regs_with_member_name[member_arg_pos].first()->is_valid(), "bad member arg");
1776 }
1777 #endif
1778 
1779 // ---------------------------------------------------------------------------
1780 // We are calling the interpreter via a c2i. Normally this would mean that
1781 // we were called by a compiled method. However we could have lost a race
1782 // where we went int -> i2c -> c2i and so the caller could in fact be
1783 // interpreted. If the caller is compiled we attempt to patch the caller
1784 // so he no longer calls into the interpreter.
1785 JRT_LEAF(void, SharedRuntime::fixup_callers_callsite(Method* method, address caller_pc))
1786   AARCH64_PORT_ONLY(assert(pauth_ptr_is_raw(caller_pc), "should be raw"));
1787 
1788   // It's possible that deoptimization can occur at a call site which hasn't
1789   // been resolved yet, in which case this function will be called from
1790   // an nmethod that has been patched for deopt and we can ignore the
1791   // request for a fixup.
1792   // Also it is possible that we lost a race in that from_compiled_entry
1793   // is now back to the i2c in that case we don't need to patch and if
1794   // we did we'd leap into space because the callsite needs to use
1795   // "to interpreter" stub in order to load up the Method*. Don't
1796   // ask me how I know this...
1797 
1798   // Result from nmethod::is_unloading is not stable across safepoints.
1799   NoSafepointVerifier nsv;
1800 
1801   nmethod* callee = method->code();
1802   if (callee == nullptr) {
1803     return;
1804   }
1805 
1806   // write lock needed because we might patch call site by set_to_clean()
1807   // and is_unloading() can modify nmethod's state
1808   MACOS_AARCH64_ONLY(ThreadWXEnable __wx(WXWrite, JavaThread::current()));
1809 
1810   CodeBlob* cb = CodeCache::find_blob(caller_pc);
1811   if (cb == nullptr || !cb->is_nmethod() || !callee->is_in_use() || callee->is_unloading()) {
1812     return;
1813   }
1814 
1815   // The check above makes sure this is an nmethod.
1816   nmethod* caller = cb->as_nmethod();
1817 
1818   // Get the return PC for the passed caller PC.
1819   address return_pc = caller_pc + frame::pc_return_offset;
1820 
1821   if (!caller->is_in_use() || !NativeCall::is_call_before(return_pc)) {
1822     return;
1823   }
1824 
1825   // Expect to find a native call there (unless it was no-inline cache vtable dispatch)
1826   CompiledICLocker ic_locker(caller);
1827   ResourceMark rm;
1828 
1829   // If we got here through a static call or opt_virtual call, then we know where the
1830   // call address would be; let's peek at it
1831   address callsite_addr = (address)nativeCall_before(return_pc);
1832   RelocIterator iter(caller, callsite_addr, callsite_addr + 1);
1833   if (!iter.next()) {
1834     // No reloc entry found; not a static or optimized virtual call
1835     return;
1836   }
1837 
1838   relocInfo::relocType type = iter.reloc()->type();
1839   if (type != relocInfo::static_call_type &&
1840       type != relocInfo::opt_virtual_call_type) {
1841     return;
1842   }
1843 
1844   CompiledDirectCall* callsite = CompiledDirectCall::before(return_pc);
1845   callsite->set_to_clean();
1846 JRT_END
1847 
1848 
1849 // same as JVM_Arraycopy, but called directly from compiled code
1850 JRT_ENTRY(void, SharedRuntime::slow_arraycopy_C(oopDesc* src,  jint src_pos,
1851                                                 oopDesc* dest, jint dest_pos,
1852                                                 jint length,
1853                                                 JavaThread* current)) {
1854 #ifndef PRODUCT
1855   _slow_array_copy_ctr++;
1856 #endif
1857   // Check if we have null pointers
1858   if (src == nullptr || dest == nullptr) {
1859     THROW(vmSymbols::java_lang_NullPointerException());
1860   }
1861   // Do the copy.  The casts to arrayOop are necessary to the copy_array API,
1862   // even though the copy_array API also performs dynamic checks to ensure
1863   // that src and dest are truly arrays (and are conformable).
1864   // The copy_array mechanism is awkward and could be removed, but
1865   // the compilers don't call this function except as a last resort,
1866   // so it probably doesn't matter.
1867   src->klass()->copy_array((arrayOopDesc*)src, src_pos,
1868                                         (arrayOopDesc*)dest, dest_pos,
1869                                         length, current);
1870 }
1871 JRT_END
1872 
1873 // The caller of generate_class_cast_message() (or one of its callers)
1874 // must use a ResourceMark in order to correctly free the result.
1875 char* SharedRuntime::generate_class_cast_message(
1876     JavaThread* thread, Klass* caster_klass) {
1877 
1878   // Get target class name from the checkcast instruction
1879   vframeStream vfst(thread, true);
1880   assert(!vfst.at_end(), "Java frame must exist");
1881   Bytecode_checkcast cc(vfst.method(), vfst.method()->bcp_from(vfst.bci()));
1882   constantPoolHandle cpool(thread, vfst.method()->constants());
1883   Klass* target_klass = ConstantPool::klass_at_if_loaded(cpool, cc.index());
1884   Symbol* target_klass_name = nullptr;
1885   if (target_klass == nullptr) {
1886     // This klass should be resolved, but just in case, get the name in the klass slot.
1887     target_klass_name = cpool->klass_name_at(cc.index());
1888   }
1889   return generate_class_cast_message(caster_klass, target_klass, target_klass_name);
1890 }
1891 
1892 
1893 // The caller of generate_class_cast_message() (or one of its callers)
1894 // must use a ResourceMark in order to correctly free the result.
1895 char* SharedRuntime::generate_class_cast_message(
1896     Klass* caster_klass, Klass* target_klass, Symbol* target_klass_name) {
1897   const char* caster_name = caster_klass->external_name();
1898 
1899   assert(target_klass != nullptr || target_klass_name != nullptr, "one must be provided");
1900   const char* target_name = target_klass == nullptr ? target_klass_name->as_klass_external_name() :
1901                                                    target_klass->external_name();
1902 
1903   size_t msglen = strlen(caster_name) + strlen("class ") + strlen(" cannot be cast to class ") + strlen(target_name) + 1;
1904 
1905   const char* caster_klass_description = "";
1906   const char* target_klass_description = "";
1907   const char* klass_separator = "";
1908   if (target_klass != nullptr && caster_klass->module() == target_klass->module()) {
1909     caster_klass_description = caster_klass->joint_in_module_of_loader(target_klass);
1910   } else {
1911     caster_klass_description = caster_klass->class_in_module_of_loader();
1912     target_klass_description = (target_klass != nullptr) ? target_klass->class_in_module_of_loader() : "";
1913     klass_separator = (target_klass != nullptr) ? "; " : "";
1914   }
1915 
1916   // add 3 for parenthesis and preceding space
1917   msglen += strlen(caster_klass_description) + strlen(target_klass_description) + strlen(klass_separator) + 3;
1918 
1919   char* message = NEW_RESOURCE_ARRAY_RETURN_NULL(char, msglen);
1920   if (message == nullptr) {
1921     // Shouldn't happen, but don't cause even more problems if it does
1922     message = const_cast<char*>(caster_klass->external_name());
1923   } else {
1924     jio_snprintf(message,
1925                  msglen,
1926                  "class %s cannot be cast to class %s (%s%s%s)",
1927                  caster_name,
1928                  target_name,
1929                  caster_klass_description,
1930                  klass_separator,
1931                  target_klass_description
1932                  );
1933   }
1934   return message;
1935 }
1936 
1937 JRT_LEAF(void, SharedRuntime::reguard_yellow_pages())
1938   (void) JavaThread::current()->stack_overflow_state()->reguard_stack();
1939 JRT_END
1940 
1941 void SharedRuntime::monitor_enter_helper(oopDesc* obj, BasicLock* lock, JavaThread* current) {
1942   if (!SafepointSynchronize::is_synchronizing()) {
1943     // Only try quick_enter() if we're not trying to reach a safepoint
1944     // so that the calling thread reaches the safepoint more quickly.
1945     if (ObjectSynchronizer::quick_enter(obj, lock, current)) {
1946       return;
1947     }
1948   }
1949   // NO_ASYNC required because an async exception on the state transition destructor
1950   // would leave you with the lock held and it would never be released.
1951   // The normal monitorenter NullPointerException is thrown without acquiring a lock
1952   // and the model is that an exception implies the method failed.
1953   JRT_BLOCK_NO_ASYNC
1954   Handle h_obj(THREAD, obj);
1955   ObjectSynchronizer::enter(h_obj, lock, current);
1956   assert(!HAS_PENDING_EXCEPTION, "Should have no exception here");
1957   JRT_BLOCK_END
1958 }
1959 
1960 // Handles the uncommon case in locking, i.e., contention or an inflated lock.
1961 JRT_BLOCK_ENTRY(void, SharedRuntime::complete_monitor_locking_C(oopDesc* obj, BasicLock* lock, JavaThread* current))
1962   SharedRuntime::monitor_enter_helper(obj, lock, current);
1963 JRT_END
1964 
1965 void SharedRuntime::monitor_exit_helper(oopDesc* obj, BasicLock* lock, JavaThread* current) {
1966   assert(JavaThread::current() == current, "invariant");
1967   // Exit must be non-blocking, and therefore no exceptions can be thrown.
1968   ExceptionMark em(current);
1969 
1970   // Check if C2_MacroAssembler::fast_unlock() or
1971   // C2_MacroAssembler::fast_unlock_lightweight() unlocked an inflated
1972   // monitor before going slow path.  Since there is no safepoint
1973   // polling when calling into the VM, we can be sure that the monitor
1974   // hasn't been deallocated.
1975   ObjectMonitor* m = current->unlocked_inflated_monitor();
1976   if (m != nullptr) {
1977     assert(!m->has_owner(current), "must be");
1978     current->clear_unlocked_inflated_monitor();
1979 
1980     // We need to reacquire the lock before we can call ObjectSynchronizer::exit().
1981     if (!m->try_enter(current, /*check_for_recursion*/ false)) {
1982       // Some other thread acquired the lock (or the monitor was
1983       // deflated). Either way we are done.
1984       current->dec_held_monitor_count();
1985       return;
1986     }
1987   }
1988 
1989   // The object could become unlocked through a JNI call, which we have no other checks for.
1990   // Give a fatal message if CheckJNICalls. Otherwise we ignore it.
1991   if (obj->is_unlocked()) {
1992     if (CheckJNICalls) {
1993       fatal("Object has been unlocked by JNI");
1994     }
1995     return;
1996   }
1997   ObjectSynchronizer::exit(obj, lock, current);
1998 }
1999 
2000 // Handles the uncommon cases of monitor unlocking in compiled code
2001 JRT_LEAF(void, SharedRuntime::complete_monitor_unlocking_C(oopDesc* obj, BasicLock* lock, JavaThread* current))
2002   assert(current == JavaThread::current(), "pre-condition");
2003   SharedRuntime::monitor_exit_helper(obj, lock, current);
2004 JRT_END
2005 
2006 // This is only called when CheckJNICalls is true, and only
2007 // for virtual thread termination.
2008 JRT_LEAF(void,  SharedRuntime::log_jni_monitor_still_held())
2009   assert(CheckJNICalls, "Only call this when checking JNI usage");
2010   if (log_is_enabled(Debug, jni)) {
2011     JavaThread* current = JavaThread::current();
2012     int64_t vthread_id = java_lang_Thread::thread_id(current->vthread());
2013     int64_t carrier_id = java_lang_Thread::thread_id(current->threadObj());
2014     log_debug(jni)("VirtualThread (tid: " INT64_FORMAT ", carrier id: " INT64_FORMAT
2015                    ") exiting with Objects still locked by JNI MonitorEnter.",
2016                    vthread_id, carrier_id);
2017   }
2018 JRT_END
2019 
2020 #ifndef PRODUCT
2021 
2022 void SharedRuntime::print_statistics() {
2023   ttyLocker ttyl;
2024   if (xtty != nullptr)  xtty->head("statistics type='SharedRuntime'");
2025 
2026   SharedRuntime::print_ic_miss_histogram();
2027 
2028   // Dump the JRT_ENTRY counters
2029   if (_new_instance_ctr) tty->print_cr("%5u new instance requires GC", _new_instance_ctr);
2030   if (_new_array_ctr) tty->print_cr("%5u new array requires GC", _new_array_ctr);
2031   if (_multi2_ctr) tty->print_cr("%5u multianewarray 2 dim", _multi2_ctr);
2032   if (_multi3_ctr) tty->print_cr("%5u multianewarray 3 dim", _multi3_ctr);
2033   if (_multi4_ctr) tty->print_cr("%5u multianewarray 4 dim", _multi4_ctr);
2034   if (_multi5_ctr) tty->print_cr("%5u multianewarray 5 dim", _multi5_ctr);
2035 
2036   tty->print_cr("%5u inline cache miss in compiled", _ic_miss_ctr);
2037   tty->print_cr("%5u wrong method", _wrong_method_ctr);
2038   tty->print_cr("%5u unresolved static call site", _resolve_static_ctr);
2039   tty->print_cr("%5u unresolved virtual call site", _resolve_virtual_ctr);
2040   tty->print_cr("%5u unresolved opt virtual call site", _resolve_opt_virtual_ctr);
2041 
2042   if (_mon_enter_stub_ctr) tty->print_cr("%5u monitor enter stub", _mon_enter_stub_ctr);
2043   if (_mon_exit_stub_ctr) tty->print_cr("%5u monitor exit stub", _mon_exit_stub_ctr);
2044   if (_mon_enter_ctr) tty->print_cr("%5u monitor enter slow", _mon_enter_ctr);
2045   if (_mon_exit_ctr) tty->print_cr("%5u monitor exit slow", _mon_exit_ctr);
2046   if (_partial_subtype_ctr) tty->print_cr("%5u slow partial subtype", _partial_subtype_ctr);
2047   if (_jbyte_array_copy_ctr) tty->print_cr("%5u byte array copies", _jbyte_array_copy_ctr);
2048   if (_jshort_array_copy_ctr) tty->print_cr("%5u short array copies", _jshort_array_copy_ctr);
2049   if (_jint_array_copy_ctr) tty->print_cr("%5u int array copies", _jint_array_copy_ctr);
2050   if (_jlong_array_copy_ctr) tty->print_cr("%5u long array copies", _jlong_array_copy_ctr);
2051   if (_oop_array_copy_ctr) tty->print_cr("%5u oop array copies", _oop_array_copy_ctr);
2052   if (_checkcast_array_copy_ctr) tty->print_cr("%5u checkcast array copies", _checkcast_array_copy_ctr);
2053   if (_unsafe_array_copy_ctr) tty->print_cr("%5u unsafe array copies", _unsafe_array_copy_ctr);
2054   if (_generic_array_copy_ctr) tty->print_cr("%5u generic array copies", _generic_array_copy_ctr);
2055   if (_slow_array_copy_ctr) tty->print_cr("%5u slow array copies", _slow_array_copy_ctr);
2056   if (_find_handler_ctr) tty->print_cr("%5u find exception handler", _find_handler_ctr);
2057   if (_rethrow_ctr) tty->print_cr("%5u rethrow handler", _rethrow_ctr);
2058   if (_unsafe_set_memory_ctr) tty->print_cr("%5u unsafe set memorys", _unsafe_set_memory_ctr);
2059 
2060   AdapterHandlerLibrary::print_statistics();
2061 
2062   if (xtty != nullptr)  xtty->tail("statistics");
2063 }
2064 
2065 inline double percent(int64_t x, int64_t y) {
2066   return 100.0 * (double)x / (double)MAX2(y, (int64_t)1);
2067 }
2068 
2069 class MethodArityHistogram {
2070  public:
2071   enum { MAX_ARITY = 256 };
2072  private:
2073   static uint64_t _arity_histogram[MAX_ARITY]; // histogram of #args
2074   static uint64_t _size_histogram[MAX_ARITY];  // histogram of arg size in words
2075   static uint64_t _total_compiled_calls;
2076   static uint64_t _max_compiled_calls_per_method;
2077   static int _max_arity;                       // max. arity seen
2078   static int _max_size;                        // max. arg size seen
2079 
2080   static void add_method_to_histogram(nmethod* nm) {
2081     Method* method = (nm == nullptr) ? nullptr : nm->method();
2082     if (method != nullptr) {
2083       ArgumentCount args(method->signature());
2084       int arity   = args.size() + (method->is_static() ? 0 : 1);
2085       int argsize = method->size_of_parameters();
2086       arity   = MIN2(arity, MAX_ARITY-1);
2087       argsize = MIN2(argsize, MAX_ARITY-1);
2088       uint64_t count = (uint64_t)method->compiled_invocation_count();
2089       _max_compiled_calls_per_method = count > _max_compiled_calls_per_method ? count : _max_compiled_calls_per_method;
2090       _total_compiled_calls    += count;
2091       _arity_histogram[arity]  += count;
2092       _size_histogram[argsize] += count;
2093       _max_arity = MAX2(_max_arity, arity);
2094       _max_size  = MAX2(_max_size, argsize);
2095     }
2096   }
2097 
2098   void print_histogram_helper(int n, uint64_t* histo, const char* name) {
2099     const int N = MIN2(9, n);
2100     double sum = 0;
2101     double weighted_sum = 0;
2102     for (int i = 0; i <= n; i++) { sum += (double)histo[i]; weighted_sum += (double)(i*histo[i]); }
2103     if (sum >= 1) { // prevent divide by zero or divide overflow
2104       double rest = sum;
2105       double percent = sum / 100;
2106       for (int i = 0; i <= N; i++) {
2107         rest -= (double)histo[i];
2108         tty->print_cr("%4d: " UINT64_FORMAT_W(12) " (%5.1f%%)", i, histo[i], (double)histo[i] / percent);
2109       }
2110       tty->print_cr("rest: " INT64_FORMAT_W(12) " (%5.1f%%)", (int64_t)rest, rest / percent);
2111       tty->print_cr("(avg. %s = %3.1f, max = %d)", name, weighted_sum / sum, n);
2112       tty->print_cr("(total # of compiled calls = " INT64_FORMAT_W(14) ")", _total_compiled_calls);
2113       tty->print_cr("(max # of compiled calls   = " INT64_FORMAT_W(14) ")", _max_compiled_calls_per_method);
2114     } else {
2115       tty->print_cr("Histogram generation failed for %s. n = %d, sum = %7.5f", name, n, sum);
2116     }
2117   }
2118 
2119   void print_histogram() {
2120     tty->print_cr("\nHistogram of call arity (incl. rcvr, calls to compiled methods only):");
2121     print_histogram_helper(_max_arity, _arity_histogram, "arity");
2122     tty->print_cr("\nHistogram of parameter block size (in words, incl. rcvr):");
2123     print_histogram_helper(_max_size, _size_histogram, "size");
2124     tty->cr();
2125   }
2126 
2127  public:
2128   MethodArityHistogram() {
2129     // Take the Compile_lock to protect against changes in the CodeBlob structures
2130     MutexLocker mu1(Compile_lock, Mutex::_safepoint_check_flag);
2131     // Take the CodeCache_lock to protect against changes in the CodeHeap structure
2132     MutexLocker mu2(CodeCache_lock, Mutex::_no_safepoint_check_flag);
2133     _max_arity = _max_size = 0;
2134     _total_compiled_calls = 0;
2135     _max_compiled_calls_per_method = 0;
2136     for (int i = 0; i < MAX_ARITY; i++) _arity_histogram[i] = _size_histogram[i] = 0;
2137     CodeCache::nmethods_do(add_method_to_histogram);
2138     print_histogram();
2139   }
2140 };
2141 
2142 uint64_t MethodArityHistogram::_arity_histogram[MethodArityHistogram::MAX_ARITY];
2143 uint64_t MethodArityHistogram::_size_histogram[MethodArityHistogram::MAX_ARITY];
2144 uint64_t MethodArityHistogram::_total_compiled_calls;
2145 uint64_t MethodArityHistogram::_max_compiled_calls_per_method;
2146 int MethodArityHistogram::_max_arity;
2147 int MethodArityHistogram::_max_size;
2148 
2149 void SharedRuntime::print_call_statistics(uint64_t comp_total) {
2150   tty->print_cr("Calls from compiled code:");
2151   int64_t total  = _nof_normal_calls + _nof_interface_calls + _nof_static_calls;
2152   int64_t mono_c = _nof_normal_calls - _nof_megamorphic_calls;
2153   int64_t mono_i = _nof_interface_calls;
2154   tty->print_cr("\t" INT64_FORMAT_W(12) " (100%%)  total non-inlined   ", total);
2155   tty->print_cr("\t" INT64_FORMAT_W(12) " (%4.1f%%) |- virtual calls       ", _nof_normal_calls, percent(_nof_normal_calls, total));
2156   tty->print_cr("\t" INT64_FORMAT_W(12) " (%4.0f%%) |  |- inlined          ", _nof_inlined_calls, percent(_nof_inlined_calls, _nof_normal_calls));
2157   tty->print_cr("\t" INT64_FORMAT_W(12) " (%4.0f%%) |  |- monomorphic      ", mono_c, percent(mono_c, _nof_normal_calls));
2158   tty->print_cr("\t" INT64_FORMAT_W(12) " (%4.0f%%) |  |- megamorphic      ", _nof_megamorphic_calls, percent(_nof_megamorphic_calls, _nof_normal_calls));
2159   tty->print_cr("\t" INT64_FORMAT_W(12) " (%4.1f%%) |- interface calls     ", _nof_interface_calls, percent(_nof_interface_calls, total));
2160   tty->print_cr("\t" INT64_FORMAT_W(12) " (%4.0f%%) |  |- inlined          ", _nof_inlined_interface_calls, percent(_nof_inlined_interface_calls, _nof_interface_calls));
2161   tty->print_cr("\t" INT64_FORMAT_W(12) " (%4.0f%%) |  |- monomorphic      ", mono_i, percent(mono_i, _nof_interface_calls));
2162   tty->print_cr("\t" INT64_FORMAT_W(12) " (%4.1f%%) |- static/special calls", _nof_static_calls, percent(_nof_static_calls, total));
2163   tty->print_cr("\t" INT64_FORMAT_W(12) " (%4.0f%%) |  |- inlined          ", _nof_inlined_static_calls, percent(_nof_inlined_static_calls, _nof_static_calls));
2164   tty->cr();
2165   tty->print_cr("Note 1: counter updates are not MT-safe.");
2166   tty->print_cr("Note 2: %% in major categories are relative to total non-inlined calls;");
2167   tty->print_cr("        %% in nested categories are relative to their category");
2168   tty->print_cr("        (and thus add up to more than 100%% with inlining)");
2169   tty->cr();
2170 
2171   MethodArityHistogram h;
2172 }
2173 #endif
2174 
2175 #ifndef PRODUCT
2176 static int _lookups; // number of calls to lookup
2177 static int _equals;  // number of buckets checked with matching hash
2178 static int _archived_hits; // number of successful lookups in archived table
2179 static int _runtime_hits;  // number of successful lookups in runtime table
2180 static int _compact; // number of equals calls with compact signature
2181 #endif
2182 
2183 // A simple wrapper class around the calling convention information
2184 // that allows sharing of adapters for the same calling convention.
2185 class AdapterFingerPrint : public MetaspaceObj {
2186  private:
2187   enum {
2188     _basic_type_bits = 4,
2189     _basic_type_mask = right_n_bits(_basic_type_bits),
2190     _basic_types_per_int = BitsPerInt / _basic_type_bits,
2191     _compact_int_count = 3
2192   };
2193   // TO DO:  Consider integrating this with a more global scheme for compressing signatures.
2194   // For now, 4 bits per components (plus T_VOID gaps after double/long) is not excessive.
2195 
2196   int _length;
2197   int _value[_compact_int_count];
2198 
2199   // Private construtor. Use allocate() to get an instance.
2200   AdapterFingerPrint(int total_args_passed, BasicType* sig_bt) {
2201     // Pack the BasicTypes with 8 per int
2202     _length = (total_args_passed + (_basic_types_per_int-1)) / _basic_types_per_int;
2203     int sig_index = 0;
2204     for (int index = 0; index < _length; index++) {
2205       int value = 0;
2206       for (int byte = 0; sig_index < total_args_passed && byte < _basic_types_per_int; byte++) {
2207         int bt = adapter_encoding(sig_bt[sig_index++]);
2208         assert((bt & _basic_type_mask) == bt, "must fit in 4 bits");
2209         value = (value << _basic_type_bits) | bt;
2210       }
2211       _value[index] = value;
2212     }
2213   }
2214 
2215   // Call deallocate instead
2216   ~AdapterFingerPrint() {
2217     FreeHeap(this);
2218   }
2219 
2220   // Remap BasicTypes that are handled equivalently by the adapters.
2221   // These are correct for the current system but someday it might be
2222   // necessary to make this mapping platform dependent.
2223   static int adapter_encoding(BasicType in) {
2224     switch (in) {
2225       case T_BOOLEAN:
2226       case T_BYTE:
2227       case T_SHORT:
2228       case T_CHAR:
2229         // There are all promoted to T_INT in the calling convention
2230         return T_INT;
2231 
2232       case T_OBJECT:
2233       case T_ARRAY:
2234         // In other words, we assume that any register good enough for
2235         // an int or long is good enough for a managed pointer.
2236 #ifdef _LP64
2237         return T_LONG;
2238 #else
2239         return T_INT;
2240 #endif
2241 
2242       case T_INT:
2243       case T_LONG:
2244       case T_FLOAT:
2245       case T_DOUBLE:
2246       case T_VOID:
2247         return in;
2248 
2249       default:
2250         ShouldNotReachHere();
2251         return T_CONFLICT;
2252     }
2253   }
2254 
2255   void* operator new(size_t size, size_t fp_size) throw() {
2256     assert(fp_size >= size, "sanity check");
2257     void* p = AllocateHeap(fp_size, mtCode);
2258     memset(p, 0, fp_size);
2259     return p;
2260   }
2261 
2262   template<typename Function>
2263   void iterate_args(Function function) {
2264     for (int i = 0; i < length(); i++) {
2265       unsigned val = (unsigned)value(i);
2266       // args are packed so that first/lower arguments are in the highest
2267       // bits of each int value, so iterate from highest to the lowest
2268       for (int j = 32 - _basic_type_bits; j >= 0; j -= _basic_type_bits) {
2269         unsigned v = (val >> j) & _basic_type_mask;
2270         if (v == 0) {
2271           continue;
2272         }
2273         function(v);
2274       }
2275     }
2276   }
2277 
2278  public:
2279   static int allocation_size(int total_args_passed, BasicType* sig_bt) {
2280     int len = (total_args_passed + (_basic_types_per_int-1)) / _basic_types_per_int;
2281     return sizeof(AdapterFingerPrint) + (len > _compact_int_count ? (len - _compact_int_count) * sizeof(int) : 0);
2282   }
2283 
2284   static AdapterFingerPrint* allocate(int total_args_passed, BasicType* sig_bt) {
2285     int size_in_bytes = allocation_size(total_args_passed, sig_bt);
2286     return new (size_in_bytes) AdapterFingerPrint(total_args_passed, sig_bt);
2287   }
2288 
2289   static void deallocate(AdapterFingerPrint* fp) {
2290     fp->~AdapterFingerPrint();
2291   }
2292 
2293   int value(int index) {
2294     return _value[index];
2295   }
2296 
2297   int length() {
2298     if (_length < 0) return -_length;
2299     return _length;
2300   }
2301 
2302   bool is_compact() {
2303     return _length <= _compact_int_count;
2304   }
2305 
2306   unsigned int compute_hash() {
2307     int hash = 0;
2308     for (int i = 0; i < length(); i++) {
2309       int v = value(i);
2310       //Add arithmetic operation to the hash, like +3 to improve hashing
2311       hash = ((hash << 8) ^ v ^ (hash >> 5)) + 3;
2312     }
2313     return (unsigned int)hash;
2314   }
2315 
2316   const char* as_string() {
2317     stringStream st;
2318     st.print("0x");
2319     for (int i = 0; i < length(); i++) {
2320       st.print("%x", value(i));
2321     }
2322     return st.as_string();
2323   }
2324 
2325   const char* as_basic_args_string() {
2326     stringStream st;
2327     bool long_prev = false;
2328     iterate_args([&] (int arg) {
2329       if (long_prev) {
2330         long_prev = false;
2331         if (arg == T_VOID) {
2332           st.print("J");
2333         } else {
2334           st.print("L");
2335         }
2336       }
2337       switch (arg) {
2338         case T_INT:    st.print("I");    break;
2339         case T_LONG:   long_prev = true; break;
2340         case T_FLOAT:  st.print("F");    break;
2341         case T_DOUBLE: st.print("D");    break;
2342         case T_VOID:   break;
2343         default: ShouldNotReachHere();
2344       }
2345     });
2346     if (long_prev) {
2347       st.print("L");
2348     }
2349     return st.as_string();
2350   }
2351 
2352   BasicType* as_basic_type(int& nargs) {
2353     nargs = 0;
2354     GrowableArray<BasicType> btarray;
2355     bool long_prev = false;
2356 
2357     iterate_args([&] (int arg) {
2358       if (long_prev) {
2359         long_prev = false;
2360         if (arg == T_VOID) {
2361           btarray.append(T_LONG);
2362         } else {
2363           btarray.append(T_OBJECT); // it could be T_ARRAY; it shouldn't matter
2364         }
2365       }
2366       switch (arg) {
2367         case T_INT: // fallthrough
2368         case T_FLOAT: // fallthrough
2369         case T_DOUBLE:
2370         case T_VOID:
2371           btarray.append((BasicType)arg);
2372           break;
2373         case T_LONG:
2374           long_prev = true;
2375           break;
2376         default: ShouldNotReachHere();
2377       }
2378     });
2379 
2380     if (long_prev) {
2381       btarray.append(T_OBJECT);
2382     }
2383 
2384     nargs = btarray.length();
2385     BasicType* sig_bt = NEW_RESOURCE_ARRAY(BasicType, nargs);
2386     int index = 0;
2387     GrowableArrayIterator<BasicType> iter = btarray.begin();
2388     while (iter != btarray.end()) {
2389       sig_bt[index++] = *iter;
2390       ++iter;
2391     }
2392     assert(index == btarray.length(), "sanity check");
2393 #ifdef ASSERT
2394     {
2395       AdapterFingerPrint* compare_fp = AdapterFingerPrint::allocate(nargs, sig_bt);
2396       assert(this->equals(compare_fp), "sanity check");
2397       AdapterFingerPrint::deallocate(compare_fp);
2398     }
2399 #endif
2400     return sig_bt;
2401   }
2402 
2403   bool equals(AdapterFingerPrint* other) {
2404     if (other->_length != _length) {
2405       return false;
2406     } else {
2407       for (int i = 0; i < _length; i++) {
2408         if (_value[i] != other->_value[i]) {
2409           return false;
2410         }
2411       }
2412     }
2413     return true;
2414   }
2415 
2416   // methods required by virtue of being a MetaspaceObj
2417   void metaspace_pointers_do(MetaspaceClosure* it) { return; /* nothing to do here */ }
2418   int size() const { return (int)heap_word_size(sizeof(AdapterFingerPrint) + (_length > _compact_int_count ? (_length - _compact_int_count) * sizeof(int) : 0)); }
2419   MetaspaceObj::Type type() const { return AdapterFingerPrintType; }
2420 
2421   static bool equals(AdapterFingerPrint* const& fp1, AdapterFingerPrint* const& fp2) {
2422     NOT_PRODUCT(_equals++);
2423     return fp1->equals(fp2);
2424   }
2425 
2426   static unsigned int compute_hash(AdapterFingerPrint* const& fp) {
2427     return fp->compute_hash();
2428   }
2429 };
2430 
2431 #if INCLUDE_CDS
2432 static inline bool adapter_fp_equals_compact_hashtable_entry(AdapterHandlerEntry* entry, AdapterFingerPrint* fp, int len_unused) {
2433   return AdapterFingerPrint::equals(entry->fingerprint(), fp);
2434 }
2435 
2436 class ArchivedAdapterTable : public OffsetCompactHashtable<
2437   AdapterFingerPrint*,
2438   AdapterHandlerEntry*,
2439   adapter_fp_equals_compact_hashtable_entry> {};
2440 #endif // INCLUDE_CDS
2441 
2442 // A hashtable mapping from AdapterFingerPrints to AdapterHandlerEntries
2443 using AdapterHandlerTable = ResourceHashtable<AdapterFingerPrint*, AdapterHandlerEntry*, 293,
2444                   AnyObj::C_HEAP, mtCode,
2445                   AdapterFingerPrint::compute_hash,
2446                   AdapterFingerPrint::equals>;
2447 static AdapterHandlerTable* _adapter_handler_table;
2448 static GrowableArray<AdapterHandlerEntry*>* _adapter_handler_list = nullptr;
2449 
2450 // Find a entry with the same fingerprint if it exists
2451 AdapterHandlerEntry* AdapterHandlerLibrary::lookup(int total_args_passed, BasicType* sig_bt) {
2452   NOT_PRODUCT(_lookups++);
2453   assert_lock_strong(AdapterHandlerLibrary_lock);
2454   AdapterFingerPrint* fp = AdapterFingerPrint::allocate(total_args_passed, sig_bt);
2455   AdapterHandlerEntry* entry = nullptr;
2456 #if INCLUDE_CDS
2457   // if we are building the archive then the archived adapter table is
2458   // not valid and we need to use the ones added to the runtime table
2459   if (!AOTCodeCache::is_dumping_adapters()) {
2460     // Search archived table first. It is read-only table so can be searched without lock
2461     entry = _aot_adapter_handler_table.lookup(fp, fp->compute_hash(), 0 /* unused */);
2462     if (entry != nullptr) {
2463 #ifndef PRODUCT
2464       if (fp->is_compact()) {
2465         _compact++;
2466       }
2467       _archived_hits++;
2468 #endif
2469     }
2470   }
2471 #endif // INCLUDE_CDS
2472   if (entry == nullptr) {
2473     assert_lock_strong(AdapterHandlerLibrary_lock);
2474     AdapterHandlerEntry** entry_p = _adapter_handler_table->get(fp);
2475     if (entry_p != nullptr) {
2476       entry = *entry_p;
2477       assert(entry->fingerprint()->equals(fp), "fingerprint mismatch key fp %s %s (hash=%d) != found fp %s %s (hash=%d)",
2478              entry->fingerprint()->as_basic_args_string(), entry->fingerprint()->as_string(), entry->fingerprint()->compute_hash(),
2479              fp->as_basic_args_string(), fp->as_string(), fp->compute_hash());
2480   #ifndef PRODUCT
2481       if (fp->is_compact()) _compact++;
2482       _runtime_hits++;
2483   #endif
2484     }
2485   }
2486   AdapterFingerPrint::deallocate(fp);
2487   return entry;
2488 }
2489 
2490 #ifndef PRODUCT
2491 static void print_table_statistics() {
2492   auto size = [&] (AdapterFingerPrint* key, AdapterHandlerEntry* a) {
2493     return sizeof(*key) + sizeof(*a);
2494   };
2495   TableStatistics ts = _adapter_handler_table->statistics_calculate(size);
2496   ts.print(tty, "AdapterHandlerTable");
2497   tty->print_cr("AdapterHandlerTable (table_size=%d, entries=%d)",
2498                 _adapter_handler_table->table_size(), _adapter_handler_table->number_of_entries());
2499   int total_hits = _archived_hits + _runtime_hits;
2500   tty->print_cr("AdapterHandlerTable: lookups %d equals %d hits %d (archived=%d+runtime=%d) compact %d",
2501                 _lookups, _equals, total_hits, _archived_hits, _runtime_hits, _compact);
2502 }
2503 #endif
2504 
2505 // ---------------------------------------------------------------------------
2506 // Implementation of AdapterHandlerLibrary
2507 AdapterHandlerEntry* AdapterHandlerLibrary::_abstract_method_handler = nullptr;
2508 AdapterHandlerEntry* AdapterHandlerLibrary::_no_arg_handler = nullptr;
2509 AdapterHandlerEntry* AdapterHandlerLibrary::_int_arg_handler = nullptr;
2510 AdapterHandlerEntry* AdapterHandlerLibrary::_obj_arg_handler = nullptr;
2511 AdapterHandlerEntry* AdapterHandlerLibrary::_obj_int_arg_handler = nullptr;
2512 AdapterHandlerEntry* AdapterHandlerLibrary::_obj_obj_arg_handler = nullptr;
2513 #if INCLUDE_CDS
2514 ArchivedAdapterTable AdapterHandlerLibrary::_aot_adapter_handler_table;
2515 #endif // INCLUDE_CDS
2516 static const int AdapterHandlerLibrary_size = 16*K;
2517 BufferBlob* AdapterHandlerLibrary::_buffer = nullptr;
2518 
2519 BufferBlob* AdapterHandlerLibrary::buffer_blob() {
2520   assert(_buffer != nullptr, "should be initialized");
2521   return _buffer;
2522 }
2523 
2524 static void post_adapter_creation(const AdapterBlob* new_adapter,
2525                                   const AdapterHandlerEntry* entry) {
2526   if (Forte::is_enabled() || JvmtiExport::should_post_dynamic_code_generated()) {
2527     char blob_id[256];
2528     jio_snprintf(blob_id,
2529                  sizeof(blob_id),
2530                  "%s(%s)",
2531                  new_adapter->name(),
2532                  entry->fingerprint()->as_string());
2533     if (Forte::is_enabled()) {
2534       Forte::register_stub(blob_id, new_adapter->content_begin(), new_adapter->content_end());
2535     }
2536 
2537     if (JvmtiExport::should_post_dynamic_code_generated()) {
2538       JvmtiExport::post_dynamic_code_generated(blob_id, new_adapter->content_begin(), new_adapter->content_end());
2539     }
2540   }
2541 }
2542 
2543 void AdapterHandlerLibrary::create_abstract_method_handler() {
2544   assert_lock_strong(AdapterHandlerLibrary_lock);
2545   // Create a special handler for abstract methods.  Abstract methods
2546   // are never compiled so an i2c entry is somewhat meaningless, but
2547   // throw AbstractMethodError just in case.
2548   // Pass wrong_method_abstract for the c2i transitions to return
2549   // AbstractMethodError for invalid invocations.
2550   address wrong_method_abstract = SharedRuntime::get_handle_wrong_method_abstract_stub();
2551   _abstract_method_handler = AdapterHandlerLibrary::new_entry(AdapterFingerPrint::allocate(0, nullptr));
2552   _abstract_method_handler->set_entry_points(SharedRuntime::throw_AbstractMethodError_entry(),
2553                                              wrong_method_abstract,
2554                                              wrong_method_abstract,
2555                                              nullptr);
2556 }
2557 
2558 void AdapterHandlerLibrary::initialize() {
2559   {
2560     ResourceMark rm;
2561     MutexLocker mu(AdapterHandlerLibrary_lock);
2562     _adapter_handler_table = new (mtCode) AdapterHandlerTable();
2563     _buffer = BufferBlob::create("adapters", AdapterHandlerLibrary_size);
2564     create_abstract_method_handler();
2565   }
2566 
2567 #if INCLUDE_CDS
2568   // Link adapters in AOT Cache to their code in AOT Code Cache
2569   if (!_aot_adapter_handler_table.empty()) {
2570     link_aot_adapters();
2571     lookup_simple_adapters();
2572     return;
2573   }
2574 #endif // INCLUDE_CDS
2575 
2576   ResourceMark rm;
2577   AdapterBlob* no_arg_blob = nullptr;
2578   AdapterBlob* int_arg_blob = nullptr;
2579   AdapterBlob* obj_arg_blob = nullptr;
2580   AdapterBlob* obj_int_arg_blob = nullptr;
2581   AdapterBlob* obj_obj_arg_blob = nullptr;
2582   {
2583     MutexLocker mu(AdapterHandlerLibrary_lock);
2584 
2585     _no_arg_handler = create_adapter(no_arg_blob, 0, nullptr);
2586 
2587     BasicType obj_args[] = { T_OBJECT };
2588     _obj_arg_handler = create_adapter(obj_arg_blob, 1, obj_args);
2589 
2590     BasicType int_args[] = { T_INT };
2591     _int_arg_handler = create_adapter(int_arg_blob, 1, int_args);
2592 
2593     BasicType obj_int_args[] = { T_OBJECT, T_INT };
2594     _obj_int_arg_handler = create_adapter(obj_int_arg_blob, 2, obj_int_args);
2595 
2596     BasicType obj_obj_args[] = { T_OBJECT, T_OBJECT };
2597     _obj_obj_arg_handler = create_adapter(obj_obj_arg_blob, 2, obj_obj_args);
2598 
2599     assert(no_arg_blob != nullptr &&
2600            obj_arg_blob != nullptr &&
2601            int_arg_blob != nullptr &&
2602            obj_int_arg_blob != nullptr &&
2603            obj_obj_arg_blob != nullptr, "Initial adapters must be properly created");
2604   }
2605 
2606   // Outside of the lock
2607   post_adapter_creation(no_arg_blob, _no_arg_handler);
2608   post_adapter_creation(obj_arg_blob, _obj_arg_handler);
2609   post_adapter_creation(int_arg_blob, _int_arg_handler);
2610   post_adapter_creation(obj_int_arg_blob, _obj_int_arg_handler);
2611   post_adapter_creation(obj_obj_arg_blob, _obj_obj_arg_handler);
2612 }
2613 
2614 AdapterHandlerEntry* AdapterHandlerLibrary::new_entry(AdapterFingerPrint* fingerprint) {
2615   return AdapterHandlerEntry::allocate(fingerprint);
2616 }
2617 
2618 AdapterHandlerEntry* AdapterHandlerLibrary::get_simple_adapter(const methodHandle& method) {
2619   if (method->is_abstract()) {
2620     return _abstract_method_handler;
2621   }
2622   int total_args_passed = method->size_of_parameters(); // All args on stack
2623   if (total_args_passed == 0) {
2624     return _no_arg_handler;
2625   } else if (total_args_passed == 1) {
2626     if (!method->is_static()) {
2627       return _obj_arg_handler;
2628     }
2629     switch (method->signature()->char_at(1)) {
2630       case JVM_SIGNATURE_CLASS:
2631       case JVM_SIGNATURE_ARRAY:
2632         return _obj_arg_handler;
2633       case JVM_SIGNATURE_INT:
2634       case JVM_SIGNATURE_BOOLEAN:
2635       case JVM_SIGNATURE_CHAR:
2636       case JVM_SIGNATURE_BYTE:
2637       case JVM_SIGNATURE_SHORT:
2638         return _int_arg_handler;
2639     }
2640   } else if (total_args_passed == 2 &&
2641              !method->is_static()) {
2642     switch (method->signature()->char_at(1)) {
2643       case JVM_SIGNATURE_CLASS:
2644       case JVM_SIGNATURE_ARRAY:
2645         return _obj_obj_arg_handler;
2646       case JVM_SIGNATURE_INT:
2647       case JVM_SIGNATURE_BOOLEAN:
2648       case JVM_SIGNATURE_CHAR:
2649       case JVM_SIGNATURE_BYTE:
2650       case JVM_SIGNATURE_SHORT:
2651         return _obj_int_arg_handler;
2652     }
2653   }
2654   return nullptr;
2655 }
2656 
2657 class AdapterSignatureIterator : public SignatureIterator {
2658  private:
2659   BasicType stack_sig_bt[16];
2660   BasicType* sig_bt;
2661   int index;
2662 
2663  public:
2664   AdapterSignatureIterator(Symbol* signature,
2665                            fingerprint_t fingerprint,
2666                            bool is_static,
2667                            int total_args_passed) :
2668     SignatureIterator(signature, fingerprint),
2669     index(0)
2670   {
2671     sig_bt = (total_args_passed <= 16) ? stack_sig_bt : NEW_RESOURCE_ARRAY(BasicType, total_args_passed);
2672     if (!is_static) { // Pass in receiver first
2673       sig_bt[index++] = T_OBJECT;
2674     }
2675     do_parameters_on(this);
2676   }
2677 
2678   BasicType* basic_types() {
2679     return sig_bt;
2680   }
2681 
2682 #ifdef ASSERT
2683   int slots() {
2684     return index;
2685   }
2686 #endif
2687 
2688  private:
2689 
2690   friend class SignatureIterator;  // so do_parameters_on can call do_type
2691   void do_type(BasicType type) {
2692     sig_bt[index++] = type;
2693     if (type == T_LONG || type == T_DOUBLE) {
2694       sig_bt[index++] = T_VOID; // Longs & doubles take 2 Java slots
2695     }
2696   }
2697 };
2698 
2699 
2700 const char* AdapterHandlerEntry::_entry_names[] = {
2701   "i2c", "c2i", "c2i_unverified", "c2i_no_clinit_check"
2702 };
2703 
2704 #ifdef ASSERT
2705 void AdapterHandlerLibrary::verify_adapter_sharing(int total_args_passed, BasicType* sig_bt, AdapterHandlerEntry* cached_entry) {
2706   AdapterBlob* comparison_blob = nullptr;
2707   AdapterHandlerEntry* comparison_entry = create_adapter(comparison_blob, total_args_passed, sig_bt, true);
2708   assert(comparison_blob == nullptr, "no blob should be created when creating an adapter for comparison");
2709   assert(comparison_entry->compare_code(cached_entry), "code must match");
2710   // Release the one just created
2711   AdapterHandlerEntry::deallocate(comparison_entry);
2712 }
2713 #endif /* ASSERT*/
2714 
2715 AdapterHandlerEntry* AdapterHandlerLibrary::get_adapter(const methodHandle& method) {
2716   // Use customized signature handler.  Need to lock around updates to
2717   // the _adapter_handler_table (it is not safe for concurrent readers
2718   // and a single writer: this could be fixed if it becomes a
2719   // problem).
2720 
2721   // Fast-path for trivial adapters
2722   AdapterHandlerEntry* entry = get_simple_adapter(method);
2723   if (entry != nullptr) {
2724     return entry;
2725   }
2726 
2727   ResourceMark rm;
2728   AdapterBlob* adapter_blob = nullptr;
2729 
2730   // Fill in the signature array, for the calling-convention call.
2731   int total_args_passed = method->size_of_parameters(); // All args on stack
2732 
2733   AdapterSignatureIterator si(method->signature(), method->constMethod()->fingerprint(),
2734                               method->is_static(), total_args_passed);
2735   assert(si.slots() == total_args_passed, "");
2736   BasicType* sig_bt = si.basic_types();
2737   {
2738     MutexLocker mu(AdapterHandlerLibrary_lock);
2739 
2740     // Lookup method signature's fingerprint
2741     entry = lookup(total_args_passed, sig_bt);
2742 
2743     if (entry != nullptr) {
2744       assert(entry->is_linked(), "AdapterHandlerEntry must have been linked");
2745 #ifdef ASSERT
2746       if (!entry->is_shared() && VerifyAdapterSharing) {
2747         verify_adapter_sharing(total_args_passed, sig_bt, entry);
2748       }
2749 #endif
2750     } else {
2751       entry = create_adapter(adapter_blob, total_args_passed, sig_bt);
2752     }
2753   }
2754 
2755   // Outside of the lock
2756   if (adapter_blob != nullptr) {
2757     post_adapter_creation(adapter_blob, entry);
2758   }
2759   return entry;
2760 }
2761 
2762 AdapterBlob* AdapterHandlerLibrary::lookup_aot_cache(AdapterHandlerEntry* handler) {
2763   ResourceMark rm;
2764   const char* name = AdapterHandlerLibrary::name(handler->fingerprint());
2765   const uint32_t id = AdapterHandlerLibrary::id(handler->fingerprint());
2766   int offsets[AdapterHandlerEntry::ENTRIES_COUNT];
2767 
2768   AdapterBlob* adapter_blob = nullptr;
2769   CodeBlob* blob = AOTCodeCache::load_code_blob(AOTCodeEntry::Adapter, id, name, AdapterHandlerEntry::ENTRIES_COUNT, offsets);
2770   if (blob != nullptr) {
2771     adapter_blob = blob->as_adapter_blob();
2772     address i2c_entry = adapter_blob->content_begin();
2773     assert(offsets[0] == 0, "sanity check");
2774     handler->set_entry_points(i2c_entry, i2c_entry + offsets[1], i2c_entry + offsets[2], i2c_entry + offsets[3]);
2775   }
2776   return adapter_blob;
2777 }
2778 
2779 #ifndef PRODUCT
2780 void AdapterHandlerLibrary::print_adapter_handler_info(outputStream* st, AdapterHandlerEntry* handler, AdapterBlob* adapter_blob) {
2781   ttyLocker ttyl;
2782   ResourceMark rm;
2783   int insts_size = adapter_blob->code_size();
2784   handler->print_adapter_on(tty);
2785   st->print_cr("i2c argument handler for: %s %s (%d bytes generated)",
2786                 handler->fingerprint()->as_basic_args_string(),
2787                 handler->fingerprint()->as_string(), insts_size);
2788   st->print_cr("c2i argument handler starts at " INTPTR_FORMAT, p2i(handler->get_c2i_entry()));
2789   if (Verbose || PrintStubCode) {
2790     address first_pc = handler->base_address();
2791     if (first_pc != nullptr) {
2792       Disassembler::decode(first_pc, first_pc + insts_size, st, &adapter_blob->asm_remarks());
2793       st->cr();
2794     }
2795   }
2796 }
2797 #endif // PRODUCT
2798 
2799 bool AdapterHandlerLibrary::generate_adapter_code(AdapterBlob*& adapter_blob,
2800                                                   AdapterHandlerEntry* handler,
2801                                                   int total_args_passed,
2802                                                   BasicType* sig_bt,
2803                                                   bool is_transient) {
2804   if (log_is_enabled(Info, perf, class, link)) {
2805     ClassLoader::perf_method_adapters_count()->inc();
2806   }
2807 
2808   BufferBlob* buf = buffer_blob(); // the temporary code buffer in CodeCache
2809   CodeBuffer buffer(buf);
2810   short buffer_locs[20];
2811   buffer.insts()->initialize_shared_locs((relocInfo*)buffer_locs,
2812                                          sizeof(buffer_locs)/sizeof(relocInfo));
2813   MacroAssembler masm(&buffer);
2814   VMRegPair stack_regs[16];
2815   VMRegPair* regs = (total_args_passed <= 16) ? stack_regs : NEW_RESOURCE_ARRAY(VMRegPair, total_args_passed);
2816 
2817   // Get a description of the compiled java calling convention and the largest used (VMReg) stack slot usage
2818   int comp_args_on_stack = SharedRuntime::java_calling_convention(sig_bt, regs, total_args_passed);
2819   SharedRuntime::generate_i2c2i_adapters(&masm,
2820                                          total_args_passed,
2821                                          comp_args_on_stack,
2822                                          sig_bt,
2823                                          regs,
2824                                          handler);
2825 #ifdef ASSERT
2826   if (VerifyAdapterSharing) {
2827     handler->save_code(buf->code_begin(), buffer.insts_size());
2828     if (is_transient) {
2829       return true;
2830     }
2831   }
2832 #endif
2833 
2834   adapter_blob = AdapterBlob::create(&buffer);
2835   if (adapter_blob == nullptr) {
2836     // CodeCache is full, disable compilation
2837     // Ought to log this but compile log is only per compile thread
2838     // and we're some non descript Java thread.
2839     return false;
2840   }
2841   if (!is_transient && AOTCodeCache::is_dumping_adapters()) {
2842     // try to save generated code
2843     const char* name = AdapterHandlerLibrary::name(handler->fingerprint());
2844     const uint32_t id = AdapterHandlerLibrary::id(handler->fingerprint());
2845     int entry_offset[AdapterHandlerEntry::ENTRIES_COUNT];
2846     assert(AdapterHandlerEntry::ENTRIES_COUNT == 4, "sanity");
2847     address i2c_entry = handler->get_i2c_entry();
2848     entry_offset[0] = 0; // i2c_entry offset
2849     entry_offset[1] = handler->get_c2i_entry() - i2c_entry;
2850     entry_offset[2] = handler->get_c2i_unverified_entry() - i2c_entry;
2851     entry_offset[3] = handler->get_c2i_no_clinit_check_entry() - i2c_entry;
2852     bool success = AOTCodeCache::store_code_blob(*adapter_blob, AOTCodeEntry::Adapter, id, name, AdapterHandlerEntry::ENTRIES_COUNT, entry_offset);
2853     assert(success || !AOTCodeCache::is_dumping_adapters(), "caching of adapter must be disabled");
2854   }
2855   handler->relocate(adapter_blob->content_begin());
2856 #ifndef PRODUCT
2857   // debugging support
2858   if (PrintAdapterHandlers || PrintStubCode) {
2859     print_adapter_handler_info(tty, handler, adapter_blob);
2860   }
2861 #endif
2862   return true;
2863 }
2864 
2865 AdapterHandlerEntry* AdapterHandlerLibrary::create_adapter(AdapterBlob*& adapter_blob,
2866                                                            int total_args_passed,
2867                                                            BasicType* sig_bt,
2868                                                            bool is_transient) {
2869   AdapterFingerPrint* fp = AdapterFingerPrint::allocate(total_args_passed, sig_bt);
2870   AdapterHandlerEntry* handler = AdapterHandlerLibrary::new_entry(fp);
2871   if (!generate_adapter_code(adapter_blob, handler, total_args_passed, sig_bt, is_transient)) {
2872     AdapterHandlerEntry::deallocate(handler);
2873     return nullptr;
2874   }
2875   if (!is_transient) {
2876     assert_lock_strong(AdapterHandlerLibrary_lock);
2877     _adapter_handler_table->put(fp, handler);
2878   }
2879   return handler;
2880 }
2881 
2882 #if INCLUDE_CDS
2883 void AdapterHandlerEntry::remove_unshareable_info() {
2884 #ifdef ASSERT
2885    _saved_code = nullptr;
2886    _saved_code_length = 0;
2887 #endif // ASSERT
2888   set_entry_points(nullptr, nullptr, nullptr, nullptr, false);
2889 }
2890 
2891 class CopyAdapterTableToArchive : StackObj {
2892 private:
2893   CompactHashtableWriter* _writer;
2894   ArchiveBuilder* _builder;
2895 public:
2896   CopyAdapterTableToArchive(CompactHashtableWriter* writer) : _writer(writer),
2897                                                              _builder(ArchiveBuilder::current())
2898   {}
2899 
2900   bool do_entry(AdapterFingerPrint* fp, AdapterHandlerEntry* entry) {
2901     LogStreamHandle(Trace, cds) lsh;
2902     if (ArchiveBuilder::current()->has_been_archived((address)entry)) {
2903       assert(ArchiveBuilder::current()->has_been_archived((address)fp), "must be");
2904       AdapterFingerPrint* buffered_fp = ArchiveBuilder::current()->get_buffered_addr(fp);
2905       assert(buffered_fp != nullptr,"sanity check");
2906       AdapterHandlerEntry* buffered_entry = ArchiveBuilder::current()->get_buffered_addr(entry);
2907       assert(buffered_entry != nullptr,"sanity check");
2908 
2909       uint hash = fp->compute_hash();
2910       u4 delta = _builder->buffer_to_offset_u4((address)buffered_entry);
2911       _writer->add(hash, delta);
2912       if (lsh.is_enabled()) {
2913         address fp_runtime_addr = (address)buffered_fp + ArchiveBuilder::current()->buffer_to_requested_delta();
2914         address entry_runtime_addr = (address)buffered_entry + ArchiveBuilder::current()->buffer_to_requested_delta();
2915         log_trace(cds)("Added fp=%p (%s), entry=%p to the archived adater table", buffered_fp, buffered_fp->as_basic_args_string(), buffered_entry);
2916       }
2917     } else {
2918       if (lsh.is_enabled()) {
2919         log_trace(cds)("Skipping adapter handler %p (fp=%s) as it is not archived", entry, fp->as_basic_args_string());
2920       }
2921     }
2922     return true;
2923   }
2924 };
2925 
2926 void AdapterHandlerLibrary::dump_aot_adapter_table() {
2927   CompactHashtableStats stats;
2928   CompactHashtableWriter writer(_adapter_handler_table->number_of_entries(), &stats);
2929   CopyAdapterTableToArchive copy(&writer);
2930   _adapter_handler_table->iterate(&copy);
2931   writer.dump(&_aot_adapter_handler_table, "archived adapter table");
2932 }
2933 
2934 void AdapterHandlerLibrary::serialize_shared_table_header(SerializeClosure* soc) {
2935   _aot_adapter_handler_table.serialize_header(soc);
2936 }
2937 
2938 AdapterBlob* AdapterHandlerLibrary::link_aot_adapter_handler(AdapterHandlerEntry* handler) {
2939 #ifdef ASSERT
2940   if (TestAOTAdapterLinkFailure) {
2941     return nullptr;
2942   }
2943 #endif
2944   AdapterBlob* blob = lookup_aot_cache(handler);
2945 #ifndef PRODUCT
2946   // debugging support
2947   if ((blob != nullptr) && (PrintAdapterHandlers || PrintStubCode)) {
2948     print_adapter_handler_info(tty, handler, blob);
2949   }
2950 #endif
2951   return blob;
2952 }
2953 
2954 // This method is used during production run to link archived adapters (stored in AOT Cache)
2955 // to their code in AOT Code Cache
2956 void AdapterHandlerEntry::link() {
2957   AdapterBlob* adapter_blob = nullptr;
2958   ResourceMark rm;
2959   assert(_fingerprint != nullptr, "_fingerprint must not be null");
2960   bool generate_code = false;
2961   // Generate code only if AOTCodeCache is not available, or
2962   // caching adapters is disabled, or we fail to link
2963   // the AdapterHandlerEntry to its code in the AOTCodeCache
2964   if (AOTCodeCache::is_using_adapters()) {
2965     adapter_blob = AdapterHandlerLibrary::link_aot_adapter_handler(this);
2966     if (adapter_blob == nullptr) {
2967       log_warning(cds)("Failed to link AdapterHandlerEntry (fp=%s) to its code in the AOT code cache", _fingerprint->as_basic_args_string());
2968       generate_code = true;
2969     }
2970   } else {
2971     generate_code = true;
2972   }
2973   if (generate_code) {
2974     int nargs;
2975     BasicType* bt = _fingerprint->as_basic_type(nargs);
2976     if (!AdapterHandlerLibrary::generate_adapter_code(adapter_blob, this, nargs, bt, /* is_transient */ false)) {
2977       // Don't throw exceptions during VM initialization because java.lang.* classes
2978       // might not have been initialized, causing problems when constructing the
2979       // Java exception object.
2980       vm_exit_during_initialization("Out of space in CodeCache for adapters");
2981     }
2982   }
2983   // Outside of the lock
2984   if (adapter_blob != nullptr) {
2985     post_adapter_creation(adapter_blob, this);
2986   }
2987   assert(_linked, "AdapterHandlerEntry must now be linked");
2988 }
2989 
2990 void AdapterHandlerLibrary::link_aot_adapters() {
2991   _aot_adapter_handler_table.iterate([](AdapterHandlerEntry* entry) {
2992     assert(!entry->is_linked(), "AdapterHandlerEntry is already linked!");
2993     entry->link();
2994   });
2995 }
2996 
2997 // This method is called during production run to lookup simple adapters
2998 // in the archived adapter handler table
2999 void AdapterHandlerLibrary::lookup_simple_adapters() {
3000   assert(!_aot_adapter_handler_table.empty(), "archived adapter handler table is empty");
3001 
3002   MutexLocker mu(AdapterHandlerLibrary_lock);
3003   _no_arg_handler = lookup(0, nullptr);
3004 
3005   BasicType obj_args[] = { T_OBJECT };
3006   _obj_arg_handler = lookup(1, obj_args);
3007 
3008   BasicType int_args[] = { T_INT };
3009   _int_arg_handler = lookup(1, int_args);
3010 
3011   BasicType obj_int_args[] = { T_OBJECT, T_INT };
3012   _obj_int_arg_handler = lookup(2, obj_int_args);
3013 
3014   BasicType obj_obj_args[] = { T_OBJECT, T_OBJECT };
3015   _obj_obj_arg_handler = lookup(2, obj_obj_args);
3016 
3017   assert(_no_arg_handler != nullptr &&
3018          _obj_arg_handler != nullptr &&
3019          _int_arg_handler != nullptr &&
3020          _obj_int_arg_handler != nullptr &&
3021          _obj_obj_arg_handler != nullptr, "Initial adapters not found in archived adapter handler table");
3022   assert(_no_arg_handler->is_linked() &&
3023          _obj_arg_handler->is_linked() &&
3024          _int_arg_handler->is_linked() &&
3025          _obj_int_arg_handler->is_linked() &&
3026          _obj_obj_arg_handler->is_linked(), "Initial adapters not in linked state");
3027 }
3028 #endif // INCLUDE_CDS
3029 
3030 address AdapterHandlerEntry::base_address() {
3031   address base = _i2c_entry;
3032   if (base == nullptr)  base = _c2i_entry;
3033   assert(base <= _c2i_entry || _c2i_entry == nullptr, "");
3034   assert(base <= _c2i_unverified_entry || _c2i_unverified_entry == nullptr, "");
3035   assert(base <= _c2i_no_clinit_check_entry || _c2i_no_clinit_check_entry == nullptr, "");
3036   return base;
3037 }
3038 
3039 void AdapterHandlerEntry::relocate(address new_base) {
3040   address old_base = base_address();
3041   assert(old_base != nullptr, "");
3042   ptrdiff_t delta = new_base - old_base;
3043   if (_i2c_entry != nullptr)
3044     _i2c_entry += delta;
3045   if (_c2i_entry != nullptr)
3046     _c2i_entry += delta;
3047   if (_c2i_unverified_entry != nullptr)
3048     _c2i_unverified_entry += delta;
3049   if (_c2i_no_clinit_check_entry != nullptr)
3050     _c2i_no_clinit_check_entry += delta;
3051   assert(base_address() == new_base, "");
3052 }
3053 
3054 void AdapterHandlerEntry::metaspace_pointers_do(MetaspaceClosure* it) {
3055   LogStreamHandle(Trace, cds) lsh;
3056   if (lsh.is_enabled()) {
3057     lsh.print("Iter(AdapterHandlerEntry): %p(%s)", this, _fingerprint->as_basic_args_string());
3058     lsh.cr();
3059   }
3060   it->push(&_fingerprint);
3061 }
3062 
3063 AdapterHandlerEntry::~AdapterHandlerEntry() {
3064   if (_fingerprint != nullptr) {
3065     AdapterFingerPrint::deallocate(_fingerprint);
3066     _fingerprint = nullptr;
3067   }
3068 #ifdef ASSERT
3069   FREE_C_HEAP_ARRAY(unsigned char, _saved_code);
3070 #endif
3071   FreeHeap(this);
3072 }
3073 
3074 
3075 #ifdef ASSERT
3076 // Capture the code before relocation so that it can be compared
3077 // against other versions.  If the code is captured after relocation
3078 // then relative instructions won't be equivalent.
3079 void AdapterHandlerEntry::save_code(unsigned char* buffer, int length) {
3080   _saved_code = NEW_C_HEAP_ARRAY(unsigned char, length, mtCode);
3081   _saved_code_length = length;
3082   memcpy(_saved_code, buffer, length);
3083 }
3084 
3085 
3086 bool AdapterHandlerEntry::compare_code(AdapterHandlerEntry* other) {
3087   assert(_saved_code != nullptr && other->_saved_code != nullptr, "code not saved");
3088 
3089   if (other->_saved_code_length != _saved_code_length) {
3090     return false;
3091   }
3092 
3093   return memcmp(other->_saved_code, _saved_code, _saved_code_length) == 0;
3094 }
3095 #endif
3096 
3097 
3098 /**
3099  * Create a native wrapper for this native method.  The wrapper converts the
3100  * Java-compiled calling convention to the native convention, handles
3101  * arguments, and transitions to native.  On return from the native we transition
3102  * back to java blocking if a safepoint is in progress.
3103  */
3104 void AdapterHandlerLibrary::create_native_wrapper(const methodHandle& method) {
3105   ResourceMark rm;
3106   nmethod* nm = nullptr;
3107 
3108   // Check if memory should be freed before allocation
3109   CodeCache::gc_on_allocation();
3110 
3111   assert(method->is_native(), "must be native");
3112   assert(method->is_special_native_intrinsic() ||
3113          method->has_native_function(), "must have something valid to call!");
3114 
3115   {
3116     // Perform the work while holding the lock, but perform any printing outside the lock
3117     MutexLocker mu(AdapterHandlerLibrary_lock);
3118     // See if somebody beat us to it
3119     if (method->code() != nullptr) {
3120       return;
3121     }
3122 
3123     const int compile_id = CompileBroker::assign_compile_id(method, CompileBroker::standard_entry_bci);
3124     assert(compile_id > 0, "Must generate native wrapper");
3125 
3126 
3127     ResourceMark rm;
3128     BufferBlob*  buf = buffer_blob(); // the temporary code buffer in CodeCache
3129     if (buf != nullptr) {
3130       CodeBuffer buffer(buf);
3131 
3132       if (method->is_continuation_enter_intrinsic()) {
3133         buffer.initialize_stubs_size(192);
3134       }
3135 
3136       struct { double data[20]; } locs_buf;
3137       struct { double data[20]; } stubs_locs_buf;
3138       buffer.insts()->initialize_shared_locs((relocInfo*)&locs_buf, sizeof(locs_buf) / sizeof(relocInfo));
3139 #if defined(AARCH64) || defined(PPC64)
3140       // On AArch64 with ZGC and nmethod entry barriers, we need all oops to be
3141       // in the constant pool to ensure ordering between the barrier and oops
3142       // accesses. For native_wrappers we need a constant.
3143       // On PPC64 the continuation enter intrinsic needs the constant pool for the compiled
3144       // static java call that is resolved in the runtime.
3145       if (PPC64_ONLY(method->is_continuation_enter_intrinsic() &&) true) {
3146         buffer.initialize_consts_size(8 PPC64_ONLY(+ 24));
3147       }
3148 #endif
3149       buffer.stubs()->initialize_shared_locs((relocInfo*)&stubs_locs_buf, sizeof(stubs_locs_buf) / sizeof(relocInfo));
3150       MacroAssembler _masm(&buffer);
3151 
3152       // Fill in the signature array, for the calling-convention call.
3153       const int total_args_passed = method->size_of_parameters();
3154 
3155       VMRegPair stack_regs[16];
3156       VMRegPair* regs = (total_args_passed <= 16) ? stack_regs : NEW_RESOURCE_ARRAY(VMRegPair, total_args_passed);
3157 
3158       AdapterSignatureIterator si(method->signature(), method->constMethod()->fingerprint(),
3159                               method->is_static(), total_args_passed);
3160       BasicType* sig_bt = si.basic_types();
3161       assert(si.slots() == total_args_passed, "");
3162       BasicType ret_type = si.return_type();
3163 
3164       // Now get the compiled-Java arguments layout.
3165       SharedRuntime::java_calling_convention(sig_bt, regs, total_args_passed);
3166 
3167       // Generate the compiled-to-native wrapper code
3168       nm = SharedRuntime::generate_native_wrapper(&_masm, method, compile_id, sig_bt, regs, ret_type);
3169 
3170       if (nm != nullptr) {
3171         {
3172           MutexLocker pl(NMethodState_lock, Mutex::_no_safepoint_check_flag);
3173           if (nm->make_in_use()) {
3174             method->set_code(method, nm);
3175           }
3176         }
3177 
3178         DirectiveSet* directive = DirectivesStack::getMatchingDirective(method, CompileBroker::compiler(CompLevel_simple));
3179         if (directive->PrintAssemblyOption) {
3180           nm->print_code();
3181         }
3182         DirectivesStack::release(directive);
3183       }
3184     }
3185   } // Unlock AdapterHandlerLibrary_lock
3186 
3187 
3188   // Install the generated code.
3189   if (nm != nullptr) {
3190     const char *msg = method->is_static() ? "(static)" : "";
3191     CompileTask::print_ul(nm, msg);
3192     if (PrintCompilation) {
3193       ttyLocker ttyl;
3194       CompileTask::print(tty, nm, msg);
3195     }
3196     nm->post_compiled_method_load_event();
3197   }
3198 }
3199 
3200 // -------------------------------------------------------------------------
3201 // Java-Java calling convention
3202 // (what you use when Java calls Java)
3203 
3204 //------------------------------name_for_receiver----------------------------------
3205 // For a given signature, return the VMReg for parameter 0.
3206 VMReg SharedRuntime::name_for_receiver() {
3207   VMRegPair regs;
3208   BasicType sig_bt = T_OBJECT;
3209   (void) java_calling_convention(&sig_bt, &regs, 1);
3210   // Return argument 0 register.  In the LP64 build pointers
3211   // take 2 registers, but the VM wants only the 'main' name.
3212   return regs.first();
3213 }
3214 
3215 VMRegPair *SharedRuntime::find_callee_arguments(Symbol* sig, bool has_receiver, bool has_appendix, int* arg_size) {
3216   // This method is returning a data structure allocating as a
3217   // ResourceObject, so do not put any ResourceMarks in here.
3218 
3219   BasicType *sig_bt = NEW_RESOURCE_ARRAY(BasicType, 256);
3220   VMRegPair *regs = NEW_RESOURCE_ARRAY(VMRegPair, 256);
3221   int cnt = 0;
3222   if (has_receiver) {
3223     sig_bt[cnt++] = T_OBJECT; // Receiver is argument 0; not in signature
3224   }
3225 
3226   for (SignatureStream ss(sig); !ss.at_return_type(); ss.next()) {
3227     BasicType type = ss.type();
3228     sig_bt[cnt++] = type;
3229     if (is_double_word_type(type))
3230       sig_bt[cnt++] = T_VOID;
3231   }
3232 
3233   if (has_appendix) {
3234     sig_bt[cnt++] = T_OBJECT;
3235   }
3236 
3237   assert(cnt < 256, "grow table size");
3238 
3239   int comp_args_on_stack;
3240   comp_args_on_stack = java_calling_convention(sig_bt, regs, cnt);
3241 
3242   // the calling convention doesn't count out_preserve_stack_slots so
3243   // we must add that in to get "true" stack offsets.
3244 
3245   if (comp_args_on_stack) {
3246     for (int i = 0; i < cnt; i++) {
3247       VMReg reg1 = regs[i].first();
3248       if (reg1->is_stack()) {
3249         // Yuck
3250         reg1 = reg1->bias(out_preserve_stack_slots());
3251       }
3252       VMReg reg2 = regs[i].second();
3253       if (reg2->is_stack()) {
3254         // Yuck
3255         reg2 = reg2->bias(out_preserve_stack_slots());
3256       }
3257       regs[i].set_pair(reg2, reg1);
3258     }
3259   }
3260 
3261   // results
3262   *arg_size = cnt;
3263   return regs;
3264 }
3265 
3266 // OSR Migration Code
3267 //
3268 // This code is used convert interpreter frames into compiled frames.  It is
3269 // called from very start of a compiled OSR nmethod.  A temp array is
3270 // allocated to hold the interesting bits of the interpreter frame.  All
3271 // active locks are inflated to allow them to move.  The displaced headers and
3272 // active interpreter locals are copied into the temp buffer.  Then we return
3273 // back to the compiled code.  The compiled code then pops the current
3274 // interpreter frame off the stack and pushes a new compiled frame.  Then it
3275 // copies the interpreter locals and displaced headers where it wants.
3276 // Finally it calls back to free the temp buffer.
3277 //
3278 // All of this is done NOT at any Safepoint, nor is any safepoint or GC allowed.
3279 
3280 JRT_LEAF(intptr_t*, SharedRuntime::OSR_migration_begin( JavaThread *current) )
3281   assert(current == JavaThread::current(), "pre-condition");
3282 
3283   // During OSR migration, we unwind the interpreted frame and replace it with a compiled
3284   // frame. The stack watermark code below ensures that the interpreted frame is processed
3285   // before it gets unwound. This is helpful as the size of the compiled frame could be
3286   // larger than the interpreted frame, which could result in the new frame not being
3287   // processed correctly.
3288   StackWatermarkSet::before_unwind(current);
3289 
3290   //
3291   // This code is dependent on the memory layout of the interpreter local
3292   // array and the monitors. On all of our platforms the layout is identical
3293   // so this code is shared. If some platform lays the their arrays out
3294   // differently then this code could move to platform specific code or
3295   // the code here could be modified to copy items one at a time using
3296   // frame accessor methods and be platform independent.
3297 
3298   frame fr = current->last_frame();
3299   assert(fr.is_interpreted_frame(), "");
3300   assert(fr.interpreter_frame_expression_stack_size()==0, "only handle empty stacks");
3301 
3302   // Figure out how many monitors are active.
3303   int active_monitor_count = 0;
3304   for (BasicObjectLock *kptr = fr.interpreter_frame_monitor_end();
3305        kptr < fr.interpreter_frame_monitor_begin();
3306        kptr = fr.next_monitor_in_interpreter_frame(kptr) ) {
3307     if (kptr->obj() != nullptr) active_monitor_count++;
3308   }
3309 
3310   // QQQ we could place number of active monitors in the array so that compiled code
3311   // could double check it.
3312 
3313   Method* moop = fr.interpreter_frame_method();
3314   int max_locals = moop->max_locals();
3315   // Allocate temp buffer, 1 word per local & 2 per active monitor
3316   int buf_size_words = max_locals + active_monitor_count * BasicObjectLock::size();
3317   intptr_t *buf = NEW_C_HEAP_ARRAY(intptr_t,buf_size_words, mtCode);
3318 
3319   // Copy the locals.  Order is preserved so that loading of longs works.
3320   // Since there's no GC I can copy the oops blindly.
3321   assert(sizeof(HeapWord)==sizeof(intptr_t), "fix this code");
3322   Copy::disjoint_words((HeapWord*)fr.interpreter_frame_local_at(max_locals-1),
3323                        (HeapWord*)&buf[0],
3324                        max_locals);
3325 
3326   // Inflate locks.  Copy the displaced headers.  Be careful, there can be holes.
3327   int i = max_locals;
3328   for (BasicObjectLock *kptr2 = fr.interpreter_frame_monitor_end();
3329        kptr2 < fr.interpreter_frame_monitor_begin();
3330        kptr2 = fr.next_monitor_in_interpreter_frame(kptr2) ) {
3331     if (kptr2->obj() != nullptr) {         // Avoid 'holes' in the monitor array
3332       BasicLock *lock = kptr2->lock();
3333       if (LockingMode == LM_LEGACY) {
3334         // Inflate so the object's header no longer refers to the BasicLock.
3335         if (lock->displaced_header().is_unlocked()) {
3336           // The object is locked and the resulting ObjectMonitor* will also be
3337           // locked so it can't be async deflated until ownership is dropped.
3338           // See the big comment in basicLock.cpp: BasicLock::move_to().
3339           ObjectSynchronizer::inflate_helper(kptr2->obj());
3340         }
3341         // Now the displaced header is free to move because the
3342         // object's header no longer refers to it.
3343         buf[i] = (intptr_t)lock->displaced_header().value();
3344       } else if (UseObjectMonitorTable) {
3345         buf[i] = (intptr_t)lock->object_monitor_cache();
3346       }
3347 #ifdef ASSERT
3348       else {
3349         buf[i] = badDispHeaderOSR;
3350       }
3351 #endif
3352       i++;
3353       buf[i++] = cast_from_oop<intptr_t>(kptr2->obj());
3354     }
3355   }
3356   assert(i - max_locals == active_monitor_count*2, "found the expected number of monitors");
3357 
3358   RegisterMap map(current,
3359                   RegisterMap::UpdateMap::skip,
3360                   RegisterMap::ProcessFrames::include,
3361                   RegisterMap::WalkContinuation::skip);
3362   frame sender = fr.sender(&map);
3363   if (sender.is_interpreted_frame()) {
3364     current->push_cont_fastpath(sender.sp());
3365   }
3366 
3367   return buf;
3368 JRT_END
3369 
3370 JRT_LEAF(void, SharedRuntime::OSR_migration_end( intptr_t* buf) )
3371   FREE_C_HEAP_ARRAY(intptr_t, buf);
3372 JRT_END
3373 
3374 bool AdapterHandlerLibrary::contains(const CodeBlob* b) {
3375   bool found = false;
3376 #if INCLUDE_CDS
3377   auto findblob_archived_table = [&] (AdapterHandlerEntry* handler) {
3378     return (found = (b == CodeCache::find_blob(handler->get_i2c_entry())));
3379   };
3380   _aot_adapter_handler_table.iterate(findblob_archived_table);
3381 #endif // INCLUDE_CDS
3382   if (!found) {
3383     auto findblob_runtime_table = [&] (AdapterFingerPrint* key, AdapterHandlerEntry* a) {
3384       return (found = (b == CodeCache::find_blob(a->get_i2c_entry())));
3385     };
3386     assert_locked_or_safepoint(AdapterHandlerLibrary_lock);
3387     _adapter_handler_table->iterate(findblob_runtime_table);
3388   }
3389   return found;
3390 }
3391 
3392 const char* AdapterHandlerLibrary::name(AdapterFingerPrint* fingerprint) {
3393   return fingerprint->as_basic_args_string();
3394 }
3395 
3396 uint32_t AdapterHandlerLibrary::id(AdapterFingerPrint* fingerprint) {
3397   unsigned int hash = fingerprint->compute_hash();
3398   return hash;
3399 }
3400 
3401 void AdapterHandlerLibrary::print_handler_on(outputStream* st, const CodeBlob* b) {
3402   bool found = false;
3403 #if INCLUDE_CDS
3404   auto findblob_archived_table = [&] (AdapterHandlerEntry* handler) {
3405     if (b == CodeCache::find_blob(handler->get_i2c_entry())) {
3406       found = true;
3407       st->print("Adapter for signature: ");
3408       handler->print_adapter_on(st);
3409       return true;
3410     } else {
3411       return false; // keep looking
3412 
3413     }
3414   };
3415   _aot_adapter_handler_table.iterate(findblob_archived_table);
3416 #endif // INCLUDE_CDS
3417   if (!found) {
3418     auto findblob_runtime_table = [&] (AdapterFingerPrint* key, AdapterHandlerEntry* a) {
3419       if (b == CodeCache::find_blob(a->get_i2c_entry())) {
3420         found = true;
3421         st->print("Adapter for signature: ");
3422         a->print_adapter_on(st);
3423         return true;
3424       } else {
3425         return false; // keep looking
3426       }
3427     };
3428     assert_locked_or_safepoint(AdapterHandlerLibrary_lock);
3429     _adapter_handler_table->iterate(findblob_runtime_table);
3430   }
3431   assert(found, "Should have found handler");
3432 }
3433 
3434 void AdapterHandlerEntry::print_adapter_on(outputStream* st) const {
3435   st->print("AHE@" INTPTR_FORMAT ": %s", p2i(this), fingerprint()->as_string());
3436   if (get_i2c_entry() != nullptr) {
3437     st->print(" i2c: " INTPTR_FORMAT, p2i(get_i2c_entry()));
3438   }
3439   if (get_c2i_entry() != nullptr) {
3440     st->print(" c2i: " INTPTR_FORMAT, p2i(get_c2i_entry()));
3441   }
3442   if (get_c2i_unverified_entry() != nullptr) {
3443     st->print(" c2iUV: " INTPTR_FORMAT, p2i(get_c2i_unverified_entry()));
3444   }
3445   if (get_c2i_no_clinit_check_entry() != nullptr) {
3446     st->print(" c2iNCI: " INTPTR_FORMAT, p2i(get_c2i_no_clinit_check_entry()));
3447   }
3448   st->cr();
3449 }
3450 
3451 #ifndef PRODUCT
3452 
3453 void AdapterHandlerLibrary::print_statistics() {
3454   print_table_statistics();
3455 }
3456 
3457 #endif /* PRODUCT */
3458 
3459 bool AdapterHandlerLibrary::is_abstract_method_adapter(AdapterHandlerEntry* entry) {
3460   if (entry == _abstract_method_handler) {
3461     return true;
3462   }
3463   return false;
3464 }
3465 
3466 JRT_LEAF(void, SharedRuntime::enable_stack_reserved_zone(JavaThread* current))
3467   assert(current == JavaThread::current(), "pre-condition");
3468   StackOverflow* overflow_state = current->stack_overflow_state();
3469   overflow_state->enable_stack_reserved_zone(/*check_if_disabled*/true);
3470   overflow_state->set_reserved_stack_activation(current->stack_base());
3471 JRT_END
3472 
3473 frame SharedRuntime::look_for_reserved_stack_annotated_method(JavaThread* current, frame fr) {
3474   ResourceMark rm(current);
3475   frame activation;
3476   nmethod* nm = nullptr;
3477   int count = 1;
3478 
3479   assert(fr.is_java_frame(), "Must start on Java frame");
3480 
3481   RegisterMap map(JavaThread::current(),
3482                   RegisterMap::UpdateMap::skip,
3483                   RegisterMap::ProcessFrames::skip,
3484                   RegisterMap::WalkContinuation::skip); // don't walk continuations
3485   for (; !fr.is_first_frame(); fr = fr.sender(&map)) {
3486     if (!fr.is_java_frame()) {
3487       continue;
3488     }
3489 
3490     Method* method = nullptr;
3491     bool found = false;
3492     if (fr.is_interpreted_frame()) {
3493       method = fr.interpreter_frame_method();
3494       if (method != nullptr && method->has_reserved_stack_access()) {
3495         found = true;
3496       }
3497     } else {
3498       CodeBlob* cb = fr.cb();
3499       if (cb != nullptr && cb->is_nmethod()) {
3500         nm = cb->as_nmethod();
3501         method = nm->method();
3502         // scope_desc_near() must be used, instead of scope_desc_at() because on
3503         // SPARC, the pcDesc can be on the delay slot after the call instruction.
3504         for (ScopeDesc *sd = nm->scope_desc_near(fr.pc()); sd != nullptr; sd = sd->sender()) {
3505           method = sd->method();
3506           if (method != nullptr && method->has_reserved_stack_access()) {
3507             found = true;
3508           }
3509         }
3510       }
3511     }
3512     if (found) {
3513       activation = fr;
3514       warning("Potentially dangerous stack overflow in "
3515               "ReservedStackAccess annotated method %s [%d]",
3516               method->name_and_sig_as_C_string(), count++);
3517       EventReservedStackActivation event;
3518       if (event.should_commit()) {
3519         event.set_method(method);
3520         event.commit();
3521       }
3522     }
3523   }
3524   return activation;
3525 }
3526 
3527 void SharedRuntime::on_slowpath_allocation_exit(JavaThread* current) {
3528   // After any safepoint, just before going back to compiled code,
3529   // we inform the GC that we will be doing initializing writes to
3530   // this object in the future without emitting card-marks, so
3531   // GC may take any compensating steps.
3532 
3533   oop new_obj = current->vm_result_oop();
3534   if (new_obj == nullptr) return;
3535 
3536   BarrierSet *bs = BarrierSet::barrier_set();
3537   bs->on_slowpath_allocation_exit(current, new_obj);
3538 }