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