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