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