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