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