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