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