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