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