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