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