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