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