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