1 /*
   2  * Copyright (c) 1997, 2021, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "classfile/javaClasses.hpp"
  27 #include "jvm.h"
  28 #include "classfile/stringTable.hpp"
  29 #include "classfile/vmClasses.hpp"
  30 #include "classfile/vmSymbols.hpp"
  31 #include "code/codeCache.hpp"
  32 #include "code/compiledIC.hpp"
  33 #include "code/icBuffer.hpp"
  34 #include "code/compiledMethod.inline.hpp"
  35 #include "code/scopeDesc.hpp"
  36 #include "code/vtableStubs.hpp"
  37 #include "compiler/abstractCompiler.hpp"
  38 #include "compiler/compileBroker.hpp"
  39 #include "compiler/disassembler.hpp"
  40 #include "gc/shared/barrierSet.hpp"
  41 #include "gc/shared/collectedHeap.hpp"
  42 #include "gc/shared/gcLocker.inline.hpp"
  43 #include "interpreter/interpreter.hpp"
  44 #include "interpreter/interpreterRuntime.hpp"
  45 #include "jfr/jfrEvents.hpp"
  46 #include "logging/log.hpp"

  47 #include "memory/resourceArea.hpp"
  48 #include "memory/universe.hpp"


  49 #include "oops/compiledICHolder.inline.hpp"
  50 #include "oops/klass.hpp"
  51 #include "oops/method.inline.hpp"
  52 #include "oops/objArrayKlass.hpp"

  53 #include "oops/oop.inline.hpp"

  54 #include "prims/forte.hpp"
  55 #include "prims/jvmtiExport.hpp"
  56 #include "prims/methodHandles.hpp"
  57 #include "prims/nativeLookup.hpp"
  58 #include "runtime/atomic.hpp"
  59 #include "runtime/frame.inline.hpp"
  60 #include "runtime/handles.inline.hpp"
  61 #include "runtime/init.hpp"
  62 #include "runtime/interfaceSupport.inline.hpp"
  63 #include "runtime/java.hpp"
  64 #include "runtime/javaCalls.hpp"
  65 #include "runtime/sharedRuntime.hpp"
  66 #include "runtime/stackWatermarkSet.hpp"
  67 #include "runtime/stubRoutines.hpp"
  68 #include "runtime/synchronizer.hpp"
  69 #include "runtime/vframe.inline.hpp"
  70 #include "runtime/vframeArray.hpp"
  71 #include "runtime/vm_version.hpp"
  72 #include "utilities/copy.hpp"
  73 #include "utilities/dtrace.hpp"
  74 #include "utilities/events.hpp"
  75 #include "utilities/hashtable.inline.hpp"
  76 #include "utilities/macros.hpp"
  77 #include "utilities/xmlstream.hpp"
  78 #ifdef COMPILER1
  79 #include "c1/c1_Runtime1.hpp"
  80 #endif
  81 
  82 // Shared stub locations
  83 RuntimeStub*        SharedRuntime::_wrong_method_blob;
  84 RuntimeStub*        SharedRuntime::_wrong_method_abstract_blob;
  85 RuntimeStub*        SharedRuntime::_ic_miss_blob;
  86 RuntimeStub*        SharedRuntime::_resolve_opt_virtual_call_blob;
  87 RuntimeStub*        SharedRuntime::_resolve_virtual_call_blob;
  88 RuntimeStub*        SharedRuntime::_resolve_static_call_blob;
  89 address             SharedRuntime::_resolve_static_call_entry;
  90 
  91 DeoptimizationBlob* SharedRuntime::_deopt_blob;
  92 SafepointBlob*      SharedRuntime::_polling_page_vectors_safepoint_handler_blob;
  93 SafepointBlob*      SharedRuntime::_polling_page_safepoint_handler_blob;
  94 SafepointBlob*      SharedRuntime::_polling_page_return_handler_blob;
  95 
  96 #ifdef COMPILER2
  97 UncommonTrapBlob*   SharedRuntime::_uncommon_trap_blob;
  98 #endif // COMPILER2
  99 
 100 
 101 //----------------------------generate_stubs-----------------------------------
 102 void SharedRuntime::generate_stubs() {
 103   _wrong_method_blob                   = generate_resolve_blob(CAST_FROM_FN_PTR(address, SharedRuntime::handle_wrong_method),          "wrong_method_stub");
 104   _wrong_method_abstract_blob          = generate_resolve_blob(CAST_FROM_FN_PTR(address, SharedRuntime::handle_wrong_method_abstract), "wrong_method_abstract_stub");
 105   _ic_miss_blob                        = generate_resolve_blob(CAST_FROM_FN_PTR(address, SharedRuntime::handle_wrong_method_ic_miss),  "ic_miss_stub");
 106   _resolve_opt_virtual_call_blob       = generate_resolve_blob(CAST_FROM_FN_PTR(address, SharedRuntime::resolve_opt_virtual_call_C),   "resolve_opt_virtual_call");
 107   _resolve_virtual_call_blob           = generate_resolve_blob(CAST_FROM_FN_PTR(address, SharedRuntime::resolve_virtual_call_C),       "resolve_virtual_call");
 108   _resolve_static_call_blob            = generate_resolve_blob(CAST_FROM_FN_PTR(address, SharedRuntime::resolve_static_call_C),        "resolve_static_call");
 109   _resolve_static_call_entry           = _resolve_static_call_blob->entry_point();
 110 
 111   AdapterHandlerLibrary::initialize();
 112 
 113 #if COMPILER2_OR_JVMCI
 114   // Vectors are generated only by C2 and JVMCI.
 115   bool support_wide = is_wide_vector(MaxVectorSize);
 116   if (support_wide) {
 117     _polling_page_vectors_safepoint_handler_blob = generate_handler_blob(CAST_FROM_FN_PTR(address, SafepointSynchronize::handle_polling_page_exception), POLL_AT_VECTOR_LOOP);
 118   }
 119 #endif // COMPILER2_OR_JVMCI
 120   _polling_page_safepoint_handler_blob = generate_handler_blob(CAST_FROM_FN_PTR(address, SafepointSynchronize::handle_polling_page_exception), POLL_AT_LOOP);
 121   _polling_page_return_handler_blob    = generate_handler_blob(CAST_FROM_FN_PTR(address, SafepointSynchronize::handle_polling_page_exception), POLL_AT_RETURN);
 122 
 123   generate_deopt_blob();
 124 
 125 #ifdef COMPILER2
 126   generate_uncommon_trap_blob();
 127 #endif // COMPILER2
 128 }
 129 
 130 #include <math.h>
 131 
 132 // Implementation of SharedRuntime
 133 
 134 #ifndef PRODUCT
 135 // For statistics
 136 int SharedRuntime::_ic_miss_ctr = 0;
 137 int SharedRuntime::_wrong_method_ctr = 0;
 138 int SharedRuntime::_resolve_static_ctr = 0;
 139 int SharedRuntime::_resolve_virtual_ctr = 0;
 140 int SharedRuntime::_resolve_opt_virtual_ctr = 0;
 141 int SharedRuntime::_implicit_null_throws = 0;
 142 int SharedRuntime::_implicit_div0_throws = 0;
 143 
 144 int64_t SharedRuntime::_nof_normal_calls = 0;
 145 int64_t SharedRuntime::_nof_optimized_calls = 0;
 146 int64_t SharedRuntime::_nof_inlined_calls = 0;
 147 int64_t SharedRuntime::_nof_megamorphic_calls = 0;
 148 int64_t SharedRuntime::_nof_static_calls = 0;
 149 int64_t SharedRuntime::_nof_inlined_static_calls = 0;
 150 int64_t SharedRuntime::_nof_interface_calls = 0;
 151 int64_t SharedRuntime::_nof_optimized_interface_calls = 0;
 152 int64_t SharedRuntime::_nof_inlined_interface_calls = 0;
 153 int64_t SharedRuntime::_nof_megamorphic_interface_calls = 0;
 154 
 155 int SharedRuntime::_new_instance_ctr=0;
 156 int SharedRuntime::_new_array_ctr=0;
 157 int SharedRuntime::_multi2_ctr=0;
 158 int SharedRuntime::_multi3_ctr=0;
 159 int SharedRuntime::_multi4_ctr=0;
 160 int SharedRuntime::_multi5_ctr=0;
 161 int SharedRuntime::_mon_enter_stub_ctr=0;
 162 int SharedRuntime::_mon_exit_stub_ctr=0;
 163 int SharedRuntime::_mon_enter_ctr=0;
 164 int SharedRuntime::_mon_exit_ctr=0;
 165 int SharedRuntime::_partial_subtype_ctr=0;
 166 int SharedRuntime::_jbyte_array_copy_ctr=0;
 167 int SharedRuntime::_jshort_array_copy_ctr=0;
 168 int SharedRuntime::_jint_array_copy_ctr=0;
 169 int SharedRuntime::_jlong_array_copy_ctr=0;
 170 int SharedRuntime::_oop_array_copy_ctr=0;
 171 int SharedRuntime::_checkcast_array_copy_ctr=0;
 172 int SharedRuntime::_unsafe_array_copy_ctr=0;
 173 int SharedRuntime::_generic_array_copy_ctr=0;
 174 int SharedRuntime::_slow_array_copy_ctr=0;
 175 int SharedRuntime::_find_handler_ctr=0;
 176 int SharedRuntime::_rethrow_ctr=0;
 177 
 178 int     SharedRuntime::_ICmiss_index                    = 0;
 179 int     SharedRuntime::_ICmiss_count[SharedRuntime::maxICmiss_count];
 180 address SharedRuntime::_ICmiss_at[SharedRuntime::maxICmiss_count];
 181 
 182 
 183 void SharedRuntime::trace_ic_miss(address at) {
 184   for (int i = 0; i < _ICmiss_index; i++) {
 185     if (_ICmiss_at[i] == at) {
 186       _ICmiss_count[i]++;
 187       return;
 188     }
 189   }
 190   int index = _ICmiss_index++;
 191   if (_ICmiss_index >= maxICmiss_count) _ICmiss_index = maxICmiss_count - 1;
 192   _ICmiss_at[index] = at;
 193   _ICmiss_count[index] = 1;
 194 }
 195 
 196 void SharedRuntime::print_ic_miss_histogram() {
 197   if (ICMissHistogram) {
 198     tty->print_cr("IC Miss Histogram:");
 199     int tot_misses = 0;
 200     for (int i = 0; i < _ICmiss_index; i++) {
 201       tty->print_cr("  at: " INTPTR_FORMAT "  nof: %d", p2i(_ICmiss_at[i]), _ICmiss_count[i]);
 202       tot_misses += _ICmiss_count[i];
 203     }
 204     tty->print_cr("Total IC misses: %7d", tot_misses);
 205   }
 206 }
 207 #endif // PRODUCT
 208 
 209 
 210 JRT_LEAF(jlong, SharedRuntime::lmul(jlong y, jlong x))
 211   return x * y;
 212 JRT_END
 213 
 214 
 215 JRT_LEAF(jlong, SharedRuntime::ldiv(jlong y, jlong x))
 216   if (x == min_jlong && y == CONST64(-1)) {
 217     return x;
 218   } else {
 219     return x / y;
 220   }
 221 JRT_END
 222 
 223 
 224 JRT_LEAF(jlong, SharedRuntime::lrem(jlong y, jlong x))
 225   if (x == min_jlong && y == CONST64(-1)) {
 226     return 0;
 227   } else {
 228     return x % y;
 229   }
 230 JRT_END
 231 
 232 
 233 const juint  float_sign_mask  = 0x7FFFFFFF;
 234 const juint  float_infinity   = 0x7F800000;
 235 const julong double_sign_mask = CONST64(0x7FFFFFFFFFFFFFFF);
 236 const julong double_infinity  = CONST64(0x7FF0000000000000);
 237 
 238 JRT_LEAF(jfloat, SharedRuntime::frem(jfloat  x, jfloat  y))
 239 #ifdef _WIN64
 240   // 64-bit Windows on amd64 returns the wrong values for
 241   // infinity operands.
 242   union { jfloat f; juint i; } xbits, ybits;
 243   xbits.f = x;
 244   ybits.f = y;
 245   // x Mod Infinity == x unless x is infinity
 246   if (((xbits.i & float_sign_mask) != float_infinity) &&
 247        ((ybits.i & float_sign_mask) == float_infinity) ) {
 248     return x;
 249   }
 250   return ((jfloat)fmod_winx64((double)x, (double)y));
 251 #else
 252   return ((jfloat)fmod((double)x,(double)y));
 253 #endif
 254 JRT_END
 255 
 256 
 257 JRT_LEAF(jdouble, SharedRuntime::drem(jdouble x, jdouble y))
 258 #ifdef _WIN64
 259   union { jdouble d; julong l; } xbits, ybits;
 260   xbits.d = x;
 261   ybits.d = y;
 262   // x Mod Infinity == x unless x is infinity
 263   if (((xbits.l & double_sign_mask) != double_infinity) &&
 264        ((ybits.l & double_sign_mask) == double_infinity) ) {
 265     return x;
 266   }
 267   return ((jdouble)fmod_winx64((double)x, (double)y));
 268 #else
 269   return ((jdouble)fmod((double)x,(double)y));
 270 #endif
 271 JRT_END
 272 
 273 #ifdef __SOFTFP__
 274 JRT_LEAF(jfloat, SharedRuntime::fadd(jfloat x, jfloat y))
 275   return x + y;
 276 JRT_END
 277 
 278 JRT_LEAF(jfloat, SharedRuntime::fsub(jfloat x, jfloat y))
 279   return x - y;
 280 JRT_END
 281 
 282 JRT_LEAF(jfloat, SharedRuntime::fmul(jfloat x, jfloat y))
 283   return x * y;
 284 JRT_END
 285 
 286 JRT_LEAF(jfloat, SharedRuntime::fdiv(jfloat x, jfloat y))
 287   return x / y;
 288 JRT_END
 289 
 290 JRT_LEAF(jdouble, SharedRuntime::dadd(jdouble x, jdouble y))
 291   return x + y;
 292 JRT_END
 293 
 294 JRT_LEAF(jdouble, SharedRuntime::dsub(jdouble x, jdouble y))
 295   return x - y;
 296 JRT_END
 297 
 298 JRT_LEAF(jdouble, SharedRuntime::dmul(jdouble x, jdouble y))
 299   return x * y;
 300 JRT_END
 301 
 302 JRT_LEAF(jdouble, SharedRuntime::ddiv(jdouble x, jdouble y))
 303   return x / y;
 304 JRT_END
 305 
 306 JRT_LEAF(jfloat, SharedRuntime::i2f(jint x))
 307   return (jfloat)x;
 308 JRT_END
 309 
 310 JRT_LEAF(jdouble, SharedRuntime::i2d(jint x))
 311   return (jdouble)x;
 312 JRT_END
 313 
 314 JRT_LEAF(jdouble, SharedRuntime::f2d(jfloat x))
 315   return (jdouble)x;
 316 JRT_END
 317 
 318 JRT_LEAF(int,  SharedRuntime::fcmpl(float x, float y))
 319   return x>y ? 1 : (x==y ? 0 : -1);  /* x<y or is_nan*/
 320 JRT_END
 321 
 322 JRT_LEAF(int,  SharedRuntime::fcmpg(float x, float y))
 323   return x<y ? -1 : (x==y ? 0 : 1);  /* x>y or is_nan */
 324 JRT_END
 325 
 326 JRT_LEAF(int,  SharedRuntime::dcmpl(double x, double y))
 327   return x>y ? 1 : (x==y ? 0 : -1); /* x<y or is_nan */
 328 JRT_END
 329 
 330 JRT_LEAF(int,  SharedRuntime::dcmpg(double x, double y))
 331   return x<y ? -1 : (x==y ? 0 : 1);  /* x>y or is_nan */
 332 JRT_END
 333 
 334 // Functions to return the opposite of the aeabi functions for nan.
 335 JRT_LEAF(int, SharedRuntime::unordered_fcmplt(float x, float y))
 336   return (x < y) ? 1 : ((g_isnan(x) || g_isnan(y)) ? 1 : 0);
 337 JRT_END
 338 
 339 JRT_LEAF(int, SharedRuntime::unordered_dcmplt(double x, double y))
 340   return (x < y) ? 1 : ((g_isnan(x) || g_isnan(y)) ? 1 : 0);
 341 JRT_END
 342 
 343 JRT_LEAF(int, SharedRuntime::unordered_fcmple(float x, float y))
 344   return (x <= y) ? 1 : ((g_isnan(x) || g_isnan(y)) ? 1 : 0);
 345 JRT_END
 346 
 347 JRT_LEAF(int, SharedRuntime::unordered_dcmple(double x, double y))
 348   return (x <= y) ? 1 : ((g_isnan(x) || g_isnan(y)) ? 1 : 0);
 349 JRT_END
 350 
 351 JRT_LEAF(int, SharedRuntime::unordered_fcmpge(float x, float y))
 352   return (x >= y) ? 1 : ((g_isnan(x) || g_isnan(y)) ? 1 : 0);
 353 JRT_END
 354 
 355 JRT_LEAF(int, SharedRuntime::unordered_dcmpge(double x, double y))
 356   return (x >= y) ? 1 : ((g_isnan(x) || g_isnan(y)) ? 1 : 0);
 357 JRT_END
 358 
 359 JRT_LEAF(int, SharedRuntime::unordered_fcmpgt(float x, float y))
 360   return (x > y) ? 1 : ((g_isnan(x) || g_isnan(y)) ? 1 : 0);
 361 JRT_END
 362 
 363 JRT_LEAF(int, SharedRuntime::unordered_dcmpgt(double x, double y))
 364   return (x > y) ? 1 : ((g_isnan(x) || g_isnan(y)) ? 1 : 0);
 365 JRT_END
 366 
 367 // Intrinsics make gcc generate code for these.
 368 float  SharedRuntime::fneg(float f)   {
 369   return -f;
 370 }
 371 
 372 double SharedRuntime::dneg(double f)  {
 373   return -f;
 374 }
 375 
 376 #endif // __SOFTFP__
 377 
 378 #if defined(__SOFTFP__) || defined(E500V2)
 379 // Intrinsics make gcc generate code for these.
 380 double SharedRuntime::dabs(double f)  {
 381   return (f <= (double)0.0) ? (double)0.0 - f : f;
 382 }
 383 
 384 #endif
 385 
 386 #if defined(__SOFTFP__) || defined(PPC)
 387 double SharedRuntime::dsqrt(double f) {
 388   return sqrt(f);
 389 }
 390 #endif
 391 
 392 JRT_LEAF(jint, SharedRuntime::f2i(jfloat  x))
 393   if (g_isnan(x))
 394     return 0;
 395   if (x >= (jfloat) max_jint)
 396     return max_jint;
 397   if (x <= (jfloat) min_jint)
 398     return min_jint;
 399   return (jint) x;
 400 JRT_END
 401 
 402 
 403 JRT_LEAF(jlong, SharedRuntime::f2l(jfloat  x))
 404   if (g_isnan(x))
 405     return 0;
 406   if (x >= (jfloat) max_jlong)
 407     return max_jlong;
 408   if (x <= (jfloat) min_jlong)
 409     return min_jlong;
 410   return (jlong) x;
 411 JRT_END
 412 
 413 
 414 JRT_LEAF(jint, SharedRuntime::d2i(jdouble x))
 415   if (g_isnan(x))
 416     return 0;
 417   if (x >= (jdouble) max_jint)
 418     return max_jint;
 419   if (x <= (jdouble) min_jint)
 420     return min_jint;
 421   return (jint) x;
 422 JRT_END
 423 
 424 
 425 JRT_LEAF(jlong, SharedRuntime::d2l(jdouble x))
 426   if (g_isnan(x))
 427     return 0;
 428   if (x >= (jdouble) max_jlong)
 429     return max_jlong;
 430   if (x <= (jdouble) min_jlong)
 431     return min_jlong;
 432   return (jlong) x;
 433 JRT_END
 434 
 435 
 436 JRT_LEAF(jfloat, SharedRuntime::d2f(jdouble x))
 437   return (jfloat)x;
 438 JRT_END
 439 
 440 
 441 JRT_LEAF(jfloat, SharedRuntime::l2f(jlong x))
 442   return (jfloat)x;
 443 JRT_END
 444 
 445 
 446 JRT_LEAF(jdouble, SharedRuntime::l2d(jlong x))
 447   return (jdouble)x;
 448 JRT_END
 449 
 450 // Exception handling across interpreter/compiler boundaries
 451 //
 452 // exception_handler_for_return_address(...) returns the continuation address.
 453 // The continuation address is the entry point of the exception handler of the
 454 // previous frame depending on the return address.
 455 
 456 address SharedRuntime::raw_exception_handler_for_return_address(JavaThread* current, address return_address) {
 457   // Note: This is called when we have unwound the frame of the callee that did
 458   // throw an exception. So far, no check has been performed by the StackWatermarkSet.
 459   // Notably, the stack is not walkable at this point, and hence the check must
 460   // be deferred until later. Specifically, any of the handlers returned here in
 461   // this function, will get dispatched to, and call deferred checks to
 462   // StackWatermarkSet::after_unwind at a point where the stack is walkable.
 463   assert(frame::verify_return_pc(return_address), "must be a return address: " INTPTR_FORMAT, p2i(return_address));
 464   assert(current->frames_to_pop_failed_realloc() == 0 || Interpreter::contains(return_address), "missed frames to pop?");
 465 
 466   // Reset method handle flag.
 467   current->set_is_method_handle_return(false);
 468 
 469 #if INCLUDE_JVMCI
 470   // JVMCI's ExceptionHandlerStub expects the thread local exception PC to be clear
 471   // and other exception handler continuations do not read it
 472   current->set_exception_pc(NULL);
 473 #endif // INCLUDE_JVMCI
 474 
 475   // The fastest case first
 476   CodeBlob* blob = CodeCache::find_blob(return_address);
 477   CompiledMethod* nm = (blob != NULL) ? blob->as_compiled_method_or_null() : NULL;
 478   if (nm != NULL) {
 479     // Set flag if return address is a method handle call site.
 480     current->set_is_method_handle_return(nm->is_method_handle_return(return_address));
 481     // native nmethods don't have exception handlers
 482     assert(!nm->is_native_method(), "no exception handler");
 483     assert(nm->header_begin() != nm->exception_begin(), "no exception handler");
 484     if (nm->is_deopt_pc(return_address)) {
 485       // If we come here because of a stack overflow, the stack may be
 486       // unguarded. Reguard the stack otherwise if we return to the
 487       // deopt blob and the stack bang causes a stack overflow we
 488       // crash.
 489       StackOverflow* overflow_state = current->stack_overflow_state();
 490       bool guard_pages_enabled = overflow_state->reguard_stack_if_needed();
 491       if (overflow_state->reserved_stack_activation() != current->stack_base()) {
 492         overflow_state->set_reserved_stack_activation(current->stack_base());
 493       }
 494       assert(guard_pages_enabled, "stack banging in deopt blob may cause crash");
 495       // The deferred StackWatermarkSet::after_unwind check will be performed in
 496       // Deoptimization::fetch_unroll_info (with exec_mode == Unpack_exception)
 497       return SharedRuntime::deopt_blob()->unpack_with_exception();
 498     } else {
 499       // The deferred StackWatermarkSet::after_unwind check will be performed in
 500       // * OptoRuntime::rethrow_C for C2 code
 501       // * exception_handler_for_pc_helper via Runtime1::handle_exception_from_callee_id for C1 code
 502       return nm->exception_begin();
 503     }
 504   }
 505 
 506   // Entry code
 507   if (StubRoutines::returns_to_call_stub(return_address)) {
 508     // The deferred StackWatermarkSet::after_unwind check will be performed in
 509     // JavaCallWrapper::~JavaCallWrapper
 510     return StubRoutines::catch_exception_entry();
 511   }
 512   if (blob != NULL && blob->is_optimized_entry_blob()) {
 513     return ((OptimizedEntryBlob*)blob)->exception_handler();
 514   }
 515   // Interpreted code
 516   if (Interpreter::contains(return_address)) {
 517     // The deferred StackWatermarkSet::after_unwind check will be performed in
 518     // InterpreterRuntime::exception_handler_for_exception
 519     return Interpreter::rethrow_exception_entry();
 520   }
 521 
 522   guarantee(blob == NULL || !blob->is_runtime_stub(), "caller should have skipped stub");
 523   guarantee(!VtableStubs::contains(return_address), "NULL exceptions in vtables should have been handled already!");
 524 
 525 #ifndef PRODUCT
 526   { ResourceMark rm;
 527     tty->print_cr("No exception handler found for exception at " INTPTR_FORMAT " - potential problems:", p2i(return_address));
 528     tty->print_cr("a) exception happened in (new?) code stubs/buffers that is not handled here");
 529     tty->print_cr("b) other problem");
 530   }
 531 #endif // PRODUCT
 532 
 533   ShouldNotReachHere();
 534   return NULL;
 535 }
 536 
 537 
 538 JRT_LEAF(address, SharedRuntime::exception_handler_for_return_address(JavaThread* current, address return_address))
 539   return raw_exception_handler_for_return_address(current, return_address);
 540 JRT_END
 541 
 542 
 543 address SharedRuntime::get_poll_stub(address pc) {
 544   address stub;
 545   // Look up the code blob
 546   CodeBlob *cb = CodeCache::find_blob(pc);
 547 
 548   // Should be an nmethod
 549   guarantee(cb != NULL && cb->is_compiled(), "safepoint polling: pc must refer to an nmethod");
 550 
 551   // Look up the relocation information
 552   assert(((CompiledMethod*)cb)->is_at_poll_or_poll_return(pc),
 553     "safepoint polling: type must be poll");
 554 
 555 #ifdef ASSERT
 556   if (!((NativeInstruction*)pc)->is_safepoint_poll()) {
 557     tty->print_cr("bad pc: " PTR_FORMAT, p2i(pc));
 558     Disassembler::decode(cb);
 559     fatal("Only polling locations are used for safepoint");
 560   }
 561 #endif
 562 
 563   bool at_poll_return = ((CompiledMethod*)cb)->is_at_poll_return(pc);
 564   bool has_wide_vectors = ((CompiledMethod*)cb)->has_wide_vectors();
 565   if (at_poll_return) {
 566     assert(SharedRuntime::polling_page_return_handler_blob() != NULL,
 567            "polling page return stub not created yet");
 568     stub = SharedRuntime::polling_page_return_handler_blob()->entry_point();
 569   } else if (has_wide_vectors) {
 570     assert(SharedRuntime::polling_page_vectors_safepoint_handler_blob() != NULL,
 571            "polling page vectors safepoint stub not created yet");
 572     stub = SharedRuntime::polling_page_vectors_safepoint_handler_blob()->entry_point();
 573   } else {
 574     assert(SharedRuntime::polling_page_safepoint_handler_blob() != NULL,
 575            "polling page safepoint stub not created yet");
 576     stub = SharedRuntime::polling_page_safepoint_handler_blob()->entry_point();
 577   }
 578   log_debug(safepoint)("... found polling page %s exception at pc = "
 579                        INTPTR_FORMAT ", stub =" INTPTR_FORMAT,
 580                        at_poll_return ? "return" : "loop",
 581                        (intptr_t)pc, (intptr_t)stub);
 582   return stub;
 583 }
 584 
 585 
 586 oop SharedRuntime::retrieve_receiver( Symbol* sig, frame caller ) {
 587   assert(caller.is_interpreted_frame(), "");
 588   int args_size = ArgumentSizeComputer(sig).size() + 1;
 589   assert(args_size <= caller.interpreter_frame_expression_stack_size(), "receiver must be on interpreter stack");
 590   oop result = cast_to_oop(*caller.interpreter_frame_tos_at(args_size - 1));
 591   assert(Universe::heap()->is_in(result) && oopDesc::is_oop(result), "receiver must be an oop");
 592   return result;
 593 }
 594 
 595 
 596 void SharedRuntime::throw_and_post_jvmti_exception(JavaThread* current, Handle h_exception) {
 597   if (JvmtiExport::can_post_on_exceptions()) {
 598     vframeStream vfst(current, true);
 599     methodHandle method = methodHandle(current, vfst.method());
 600     address bcp = method()->bcp_from(vfst.bci());
 601     JvmtiExport::post_exception_throw(current, method(), bcp, h_exception());
 602   }
 603 
 604 #if INCLUDE_JVMCI
 605   if (EnableJVMCI && UseJVMCICompiler) {
 606     vframeStream vfst(current, true);
 607     methodHandle method = methodHandle(current, vfst.method());
 608     int bci = vfst.bci();
 609     MethodData* trap_mdo = method->method_data();
 610     if (trap_mdo != NULL) {
 611       // Set exception_seen if the exceptional bytecode is an invoke
 612       Bytecode_invoke call = Bytecode_invoke_check(method, bci);
 613       if (call.is_valid()) {
 614         ResourceMark rm(current);
 615         ProfileData* pdata = trap_mdo->allocate_bci_to_data(bci, NULL);
 616         if (pdata != NULL && pdata->is_BitData()) {
 617           BitData* bit_data = (BitData*) pdata;
 618           bit_data->set_exception_seen();
 619         }
 620       }
 621     }
 622   }
 623 #endif
 624 
 625   Exceptions::_throw(current, __FILE__, __LINE__, h_exception);
 626 }
 627 
 628 void SharedRuntime::throw_and_post_jvmti_exception(JavaThread* current, Symbol* name, const char *message) {
 629   Handle h_exception = Exceptions::new_exception(current, name, message);
 630   throw_and_post_jvmti_exception(current, h_exception);
 631 }
 632 
 633 // The interpreter code to call this tracing function is only
 634 // called/generated when UL is on for redefine, class and has the right level
 635 // and tags. Since obsolete methods are never compiled, we don't have
 636 // to modify the compilers to generate calls to this function.
 637 //
 638 JRT_LEAF(int, SharedRuntime::rc_trace_method_entry(
 639     JavaThread* thread, Method* method))
 640   if (method->is_obsolete()) {
 641     // We are calling an obsolete method, but this is not necessarily
 642     // an error. Our method could have been redefined just after we
 643     // fetched the Method* from the constant pool.
 644     ResourceMark rm;
 645     log_trace(redefine, class, obsolete)("calling obsolete method '%s'", method->name_and_sig_as_C_string());
 646   }
 647   return 0;
 648 JRT_END
 649 
 650 // ret_pc points into caller; we are returning caller's exception handler
 651 // for given exception
 652 address SharedRuntime::compute_compiled_exc_handler(CompiledMethod* cm, address ret_pc, Handle& exception,
 653                                                     bool force_unwind, bool top_frame_only, bool& recursive_exception_occurred) {
 654   assert(cm != NULL, "must exist");
 655   ResourceMark rm;
 656 
 657 #if INCLUDE_JVMCI
 658   if (cm->is_compiled_by_jvmci()) {
 659     // lookup exception handler for this pc
 660     int catch_pco = ret_pc - cm->code_begin();
 661     ExceptionHandlerTable table(cm);
 662     HandlerTableEntry *t = table.entry_for(catch_pco, -1, 0);
 663     if (t != NULL) {
 664       return cm->code_begin() + t->pco();
 665     } else {
 666       return Deoptimization::deoptimize_for_missing_exception_handler(cm);
 667     }
 668   }
 669 #endif // INCLUDE_JVMCI
 670 
 671   nmethod* nm = cm->as_nmethod();
 672   ScopeDesc* sd = nm->scope_desc_at(ret_pc);
 673   // determine handler bci, if any
 674   EXCEPTION_MARK;
 675 
 676   int handler_bci = -1;
 677   int scope_depth = 0;
 678   if (!force_unwind) {
 679     int bci = sd->bci();
 680     bool recursive_exception = false;
 681     do {
 682       bool skip_scope_increment = false;
 683       // exception handler lookup
 684       Klass* ek = exception->klass();
 685       methodHandle mh(THREAD, sd->method());
 686       handler_bci = Method::fast_exception_handler_bci_for(mh, ek, bci, THREAD);
 687       if (HAS_PENDING_EXCEPTION) {
 688         recursive_exception = true;
 689         // We threw an exception while trying to find the exception handler.
 690         // Transfer the new exception to the exception handle which will
 691         // be set into thread local storage, and do another lookup for an
 692         // exception handler for this exception, this time starting at the
 693         // BCI of the exception handler which caused the exception to be
 694         // thrown (bugs 4307310 and 4546590). Set "exception" reference
 695         // argument to ensure that the correct exception is thrown (4870175).
 696         recursive_exception_occurred = true;
 697         exception = Handle(THREAD, PENDING_EXCEPTION);
 698         CLEAR_PENDING_EXCEPTION;
 699         if (handler_bci >= 0) {
 700           bci = handler_bci;
 701           handler_bci = -1;
 702           skip_scope_increment = true;
 703         }
 704       }
 705       else {
 706         recursive_exception = false;
 707       }
 708       if (!top_frame_only && handler_bci < 0 && !skip_scope_increment) {
 709         sd = sd->sender();
 710         if (sd != NULL) {
 711           bci = sd->bci();
 712         }
 713         ++scope_depth;
 714       }
 715     } while (recursive_exception || (!top_frame_only && handler_bci < 0 && sd != NULL));
 716   }
 717 
 718   // found handling method => lookup exception handler
 719   int catch_pco = ret_pc - nm->code_begin();
 720 
 721   ExceptionHandlerTable table(nm);
 722   HandlerTableEntry *t = table.entry_for(catch_pco, handler_bci, scope_depth);
 723   if (t == NULL && (nm->is_compiled_by_c1() || handler_bci != -1)) {
 724     // Allow abbreviated catch tables.  The idea is to allow a method
 725     // to materialize its exceptions without committing to the exact
 726     // routing of exceptions.  In particular this is needed for adding
 727     // a synthetic handler to unlock monitors when inlining
 728     // synchronized methods since the unlock path isn't represented in
 729     // the bytecodes.
 730     t = table.entry_for(catch_pco, -1, 0);
 731   }
 732 
 733 #ifdef COMPILER1
 734   if (t == NULL && nm->is_compiled_by_c1()) {
 735     assert(nm->unwind_handler_begin() != NULL, "");
 736     return nm->unwind_handler_begin();
 737   }
 738 #endif
 739 
 740   if (t == NULL) {
 741     ttyLocker ttyl;
 742     tty->print_cr("MISSING EXCEPTION HANDLER for pc " INTPTR_FORMAT " and handler bci %d", p2i(ret_pc), handler_bci);
 743     tty->print_cr("   Exception:");
 744     exception->print();
 745     tty->cr();
 746     tty->print_cr(" Compiled exception table :");
 747     table.print();
 748     nm->print_code();
 749     guarantee(false, "missing exception handler");
 750     return NULL;
 751   }
 752 
 753   return nm->code_begin() + t->pco();
 754 }
 755 
 756 JRT_ENTRY(void, SharedRuntime::throw_AbstractMethodError(JavaThread* current))
 757   // These errors occur only at call sites
 758   throw_and_post_jvmti_exception(current, vmSymbols::java_lang_AbstractMethodError());
 759 JRT_END
 760 
 761 JRT_ENTRY(void, SharedRuntime::throw_IncompatibleClassChangeError(JavaThread* current))
 762   // These errors occur only at call sites
 763   throw_and_post_jvmti_exception(current, vmSymbols::java_lang_IncompatibleClassChangeError(), "vtable stub");
 764 JRT_END
 765 
 766 JRT_ENTRY(void, SharedRuntime::throw_ArithmeticException(JavaThread* current))
 767   throw_and_post_jvmti_exception(current, vmSymbols::java_lang_ArithmeticException(), "/ by zero");
 768 JRT_END
 769 
 770 JRT_ENTRY(void, SharedRuntime::throw_NullPointerException(JavaThread* current))
 771   throw_and_post_jvmti_exception(current, vmSymbols::java_lang_NullPointerException(), NULL);
 772 JRT_END
 773 
 774 JRT_ENTRY(void, SharedRuntime::throw_NullPointerException_at_call(JavaThread* current))
 775   // This entry point is effectively only used for NullPointerExceptions which occur at inline
 776   // cache sites (when the callee activation is not yet set up) so we are at a call site
 777   throw_and_post_jvmti_exception(current, vmSymbols::java_lang_NullPointerException(), NULL);
 778 JRT_END
 779 
 780 JRT_ENTRY(void, SharedRuntime::throw_StackOverflowError(JavaThread* current))
 781   throw_StackOverflowError_common(current, false);
 782 JRT_END
 783 
 784 JRT_ENTRY(void, SharedRuntime::throw_delayed_StackOverflowError(JavaThread* current))
 785   throw_StackOverflowError_common(current, true);
 786 JRT_END
 787 
 788 void SharedRuntime::throw_StackOverflowError_common(JavaThread* current, bool delayed) {
 789   // We avoid using the normal exception construction in this case because
 790   // it performs an upcall to Java, and we're already out of stack space.
 791   JavaThread* THREAD = current; // For exception macros.
 792   Klass* k = vmClasses::StackOverflowError_klass();
 793   oop exception_oop = InstanceKlass::cast(k)->allocate_instance(CHECK);
 794   if (delayed) {
 795     java_lang_Throwable::set_message(exception_oop,
 796                                      Universe::delayed_stack_overflow_error_message());
 797   }
 798   Handle exception (current, exception_oop);
 799   if (StackTraceInThrowable) {
 800     java_lang_Throwable::fill_in_stack_trace(exception);
 801   }
 802   // Increment counter for hs_err file reporting
 803   Atomic::inc(&Exceptions::_stack_overflow_errors);
 804   throw_and_post_jvmti_exception(current, exception);
 805 }
 806 
 807 address SharedRuntime::continuation_for_implicit_exception(JavaThread* current,
 808                                                            address pc,
 809                                                            ImplicitExceptionKind exception_kind)
 810 {
 811   address target_pc = NULL;
 812 
 813   if (Interpreter::contains(pc)) {
 814     switch (exception_kind) {
 815       case IMPLICIT_NULL:           return Interpreter::throw_NullPointerException_entry();
 816       case IMPLICIT_DIVIDE_BY_ZERO: return Interpreter::throw_ArithmeticException_entry();
 817       case STACK_OVERFLOW:          return Interpreter::throw_StackOverflowError_entry();
 818       default:                      ShouldNotReachHere();
 819     }
 820   } else {
 821     switch (exception_kind) {
 822       case STACK_OVERFLOW: {
 823         // Stack overflow only occurs upon frame setup; the callee is
 824         // going to be unwound. Dispatch to a shared runtime stub
 825         // which will cause the StackOverflowError to be fabricated
 826         // and processed.
 827         // Stack overflow should never occur during deoptimization:
 828         // the compiled method bangs the stack by as much as the
 829         // interpreter would need in case of a deoptimization. The
 830         // deoptimization blob and uncommon trap blob bang the stack
 831         // in a debug VM to verify the correctness of the compiled
 832         // method stack banging.
 833         assert(current->deopt_mark() == NULL, "no stack overflow from deopt blob/uncommon trap");
 834         Events::log_exception(current, "StackOverflowError at " INTPTR_FORMAT, p2i(pc));
 835         return StubRoutines::throw_StackOverflowError_entry();
 836       }
 837 
 838       case IMPLICIT_NULL: {
 839         if (VtableStubs::contains(pc)) {
 840           // We haven't yet entered the callee frame. Fabricate an
 841           // exception and begin dispatching it in the caller. Since
 842           // the caller was at a call site, it's safe to destroy all
 843           // caller-saved registers, as these entry points do.
 844           VtableStub* vt_stub = VtableStubs::stub_containing(pc);
 845 
 846           // If vt_stub is NULL, then return NULL to signal handler to report the SEGV error.
 847           if (vt_stub == NULL) return NULL;
 848 
 849           if (vt_stub->is_abstract_method_error(pc)) {
 850             assert(!vt_stub->is_vtable_stub(), "should never see AbstractMethodErrors from vtable-type VtableStubs");
 851             Events::log_exception(current, "AbstractMethodError at " INTPTR_FORMAT, p2i(pc));
 852             // Instead of throwing the abstract method error here directly, we re-resolve
 853             // and will throw the AbstractMethodError during resolve. As a result, we'll
 854             // get a more detailed error message.
 855             return SharedRuntime::get_handle_wrong_method_stub();
 856           } else {
 857             Events::log_exception(current, "NullPointerException at vtable entry " INTPTR_FORMAT, p2i(pc));
 858             // Assert that the signal comes from the expected location in stub code.
 859             assert(vt_stub->is_null_pointer_exception(pc),
 860                    "obtained signal from unexpected location in stub code");
 861             return StubRoutines::throw_NullPointerException_at_call_entry();
 862           }
 863         } else {
 864           CodeBlob* cb = CodeCache::find_blob(pc);
 865 
 866           // If code blob is NULL, then return NULL to signal handler to report the SEGV error.
 867           if (cb == NULL) return NULL;
 868 
 869           // Exception happened in CodeCache. Must be either:
 870           // 1. Inline-cache check in C2I handler blob,
 871           // 2. Inline-cache check in nmethod, or
 872           // 3. Implicit null exception in nmethod
 873 
 874           if (!cb->is_compiled()) {
 875             bool is_in_blob = cb->is_adapter_blob() || cb->is_method_handles_adapter_blob();
 876             if (!is_in_blob) {
 877               // Allow normal crash reporting to handle this
 878               return NULL;
 879             }
 880             Events::log_exception(current, "NullPointerException in code blob at " INTPTR_FORMAT, p2i(pc));
 881             // There is no handler here, so we will simply unwind.
 882             return StubRoutines::throw_NullPointerException_at_call_entry();
 883           }
 884 
 885           // Otherwise, it's a compiled method.  Consult its exception handlers.
 886           CompiledMethod* cm = (CompiledMethod*)cb;
 887           if (cm->inlinecache_check_contains(pc)) {
 888             // exception happened inside inline-cache check code
 889             // => the nmethod is not yet active (i.e., the frame
 890             // is not set up yet) => use return address pushed by
 891             // caller => don't push another return address
 892             Events::log_exception(current, "NullPointerException in IC check " INTPTR_FORMAT, p2i(pc));
 893             return StubRoutines::throw_NullPointerException_at_call_entry();
 894           }
 895 
 896           if (cm->method()->is_method_handle_intrinsic()) {
 897             // exception happened inside MH dispatch code, similar to a vtable stub
 898             Events::log_exception(current, "NullPointerException in MH adapter " INTPTR_FORMAT, p2i(pc));
 899             return StubRoutines::throw_NullPointerException_at_call_entry();
 900           }
 901 
 902 #ifndef PRODUCT
 903           _implicit_null_throws++;
 904 #endif
 905           target_pc = cm->continuation_for_implicit_null_exception(pc);
 906           // If there's an unexpected fault, target_pc might be NULL,
 907           // in which case we want to fall through into the normal
 908           // error handling code.
 909         }
 910 
 911         break; // fall through
 912       }
 913 
 914 
 915       case IMPLICIT_DIVIDE_BY_ZERO: {
 916         CompiledMethod* cm = CodeCache::find_compiled(pc);
 917         guarantee(cm != NULL, "must have containing compiled method for implicit division-by-zero exceptions");
 918 #ifndef PRODUCT
 919         _implicit_div0_throws++;
 920 #endif
 921         target_pc = cm->continuation_for_implicit_div0_exception(pc);
 922         // If there's an unexpected fault, target_pc might be NULL,
 923         // in which case we want to fall through into the normal
 924         // error handling code.
 925         break; // fall through
 926       }
 927 
 928       default: ShouldNotReachHere();
 929     }
 930 
 931     assert(exception_kind == IMPLICIT_NULL || exception_kind == IMPLICIT_DIVIDE_BY_ZERO, "wrong implicit exception kind");
 932 
 933     if (exception_kind == IMPLICIT_NULL) {
 934 #ifndef PRODUCT
 935       // for AbortVMOnException flag
 936       Exceptions::debug_check_abort("java.lang.NullPointerException");
 937 #endif //PRODUCT
 938       Events::log_exception(current, "Implicit null exception at " INTPTR_FORMAT " to " INTPTR_FORMAT, p2i(pc), p2i(target_pc));
 939     } else {
 940 #ifndef PRODUCT
 941       // for AbortVMOnException flag
 942       Exceptions::debug_check_abort("java.lang.ArithmeticException");
 943 #endif //PRODUCT
 944       Events::log_exception(current, "Implicit division by zero exception at " INTPTR_FORMAT " to " INTPTR_FORMAT, p2i(pc), p2i(target_pc));
 945     }
 946     return target_pc;
 947   }
 948 
 949   ShouldNotReachHere();
 950   return NULL;
 951 }
 952 
 953 
 954 /**
 955  * Throws an java/lang/UnsatisfiedLinkError.  The address of this method is
 956  * installed in the native function entry of all native Java methods before
 957  * they get linked to their actual native methods.
 958  *
 959  * \note
 960  * This method actually never gets called!  The reason is because
 961  * the interpreter's native entries call NativeLookup::lookup() which
 962  * throws the exception when the lookup fails.  The exception is then
 963  * caught and forwarded on the return from NativeLookup::lookup() call
 964  * before the call to the native function.  This might change in the future.
 965  */
 966 JNI_ENTRY(void*, throw_unsatisfied_link_error(JNIEnv* env, ...))
 967 {
 968   // We return a bad value here to make sure that the exception is
 969   // forwarded before we look at the return value.
 970   THROW_(vmSymbols::java_lang_UnsatisfiedLinkError(), (void*)badAddress);
 971 }
 972 JNI_END
 973 
 974 address SharedRuntime::native_method_throw_unsatisfied_link_error_entry() {
 975   return CAST_FROM_FN_PTR(address, &throw_unsatisfied_link_error);
 976 }
 977 
 978 JRT_ENTRY_NO_ASYNC(void, SharedRuntime::register_finalizer(JavaThread* current, oopDesc* obj))
 979 #if INCLUDE_JVMCI
 980   if (!obj->klass()->has_finalizer()) {
 981     return;
 982   }
 983 #endif // INCLUDE_JVMCI
 984   assert(oopDesc::is_oop(obj), "must be a valid oop");
 985   assert(obj->klass()->has_finalizer(), "shouldn't be here otherwise");
 986   InstanceKlass::register_finalizer(instanceOop(obj), CHECK);
 987 JRT_END
 988 

 989 jlong SharedRuntime::get_java_tid(Thread* thread) {
 990   if (thread != NULL) {
 991     if (thread->is_Java_thread()) {
 992       oop obj = JavaThread::cast(thread)->threadObj();
 993       return (obj == NULL) ? 0 : java_lang_Thread::thread_id(obj);
 994     }
 995   }
 996   return 0;
 997 }
 998 
 999 /**
1000  * This function ought to be a void function, but cannot be because
1001  * it gets turned into a tail-call on sparc, which runs into dtrace bug
1002  * 6254741.  Once that is fixed we can remove the dummy return value.
1003  */
1004 int SharedRuntime::dtrace_object_alloc(oopDesc* o, int size) {
1005   return dtrace_object_alloc_base(Thread::current(), o, size);
1006 }
1007 
1008 int SharedRuntime::dtrace_object_alloc_base(Thread* thread, oopDesc* o, int size) {
1009   assert(DTraceAllocProbes, "wrong call");
1010   Klass* klass = o->klass();
1011   Symbol* name = klass->name();
1012   HOTSPOT_OBJECT_ALLOC(
1013                    get_java_tid(thread),
1014                    (char *) name->bytes(), name->utf8_length(), size * HeapWordSize);
1015   return 0;
1016 }
1017 
1018 JRT_LEAF(int, SharedRuntime::dtrace_method_entry(
1019     JavaThread* current, Method* method))
1020   assert(DTraceMethodProbes, "wrong call");
1021   Symbol* kname = method->klass_name();
1022   Symbol* name = method->name();
1023   Symbol* sig = method->signature();
1024   HOTSPOT_METHOD_ENTRY(
1025       get_java_tid(current),
1026       (char *) kname->bytes(), kname->utf8_length(),
1027       (char *) name->bytes(), name->utf8_length(),
1028       (char *) sig->bytes(), sig->utf8_length());
1029   return 0;
1030 JRT_END
1031 
1032 JRT_LEAF(int, SharedRuntime::dtrace_method_exit(
1033     JavaThread* current, Method* method))
1034   assert(DTraceMethodProbes, "wrong call");
1035   Symbol* kname = method->klass_name();
1036   Symbol* name = method->name();
1037   Symbol* sig = method->signature();
1038   HOTSPOT_METHOD_RETURN(
1039       get_java_tid(current),
1040       (char *) kname->bytes(), kname->utf8_length(),
1041       (char *) name->bytes(), name->utf8_length(),
1042       (char *) sig->bytes(), sig->utf8_length());
1043   return 0;
1044 JRT_END
1045 
1046 
1047 // Finds receiver, CallInfo (i.e. receiver method), and calling bytecode)
1048 // for a call current in progress, i.e., arguments has been pushed on stack
1049 // put callee has not been invoked yet.  Used by: resolve virtual/static,
1050 // vtable updates, etc.  Caller frame must be compiled.
1051 Handle SharedRuntime::find_callee_info(Bytecodes::Code& bc, CallInfo& callinfo, TRAPS) {
1052   JavaThread* current = THREAD;
1053   ResourceMark rm(current);
1054 
1055   // last java frame on stack (which includes native call frames)
1056   vframeStream vfst(current, true);  // Do not skip and javaCalls
1057 
1058   return find_callee_info_helper(vfst, bc, callinfo, THREAD);
1059 }
1060 
1061 Method* SharedRuntime::extract_attached_method(vframeStream& vfst) {
1062   CompiledMethod* caller = vfst.nm();
1063 
1064   nmethodLocker caller_lock(caller);
1065 
1066   address pc = vfst.frame_pc();
1067   { // Get call instruction under lock because another thread may be busy patching it.
1068     CompiledICLocker ic_locker(caller);
1069     return caller->attached_method_before_pc(pc);
1070   }
1071   return NULL;
1072 }
1073 
1074 // Finds receiver, CallInfo (i.e. receiver method), and calling bytecode
1075 // for a call current in progress, i.e., arguments has been pushed on stack
1076 // but callee has not been invoked yet.  Caller frame must be compiled.
1077 Handle SharedRuntime::find_callee_info_helper(vframeStream& vfst, Bytecodes::Code& bc,
1078                                               CallInfo& callinfo, TRAPS) {
1079   Handle receiver;
1080   Handle nullHandle;  // create a handy null handle for exception returns
1081   JavaThread* current = THREAD;
1082 
1083   assert(!vfst.at_end(), "Java frame must exist");
1084 
1085   // Find caller and bci from vframe
1086   methodHandle caller(current, vfst.method());
1087   int          bci   = vfst.bci();
1088 















1089   Bytecode_invoke bytecode(caller, bci);
1090   int bytecode_index = bytecode.index();
1091   bc = bytecode.invoke_code();
1092 
1093   methodHandle attached_method(current, extract_attached_method(vfst));
1094   if (attached_method.not_null()) {
1095     Method* callee = bytecode.static_target(CHECK_NH);
1096     vmIntrinsics::ID id = callee->intrinsic_id();
1097     // When VM replaces MH.invokeBasic/linkTo* call with a direct/virtual call,
1098     // it attaches statically resolved method to the call site.
1099     if (MethodHandles::is_signature_polymorphic(id) &&
1100         MethodHandles::is_signature_polymorphic_intrinsic(id)) {
1101       bc = MethodHandles::signature_polymorphic_intrinsic_bytecode(id);
1102 
1103       // Adjust invocation mode according to the attached method.
1104       switch (bc) {
1105         case Bytecodes::_invokevirtual:
1106           if (attached_method->method_holder()->is_interface()) {
1107             bc = Bytecodes::_invokeinterface;
1108           }
1109           break;
1110         case Bytecodes::_invokeinterface:
1111           if (!attached_method->method_holder()->is_interface()) {
1112             bc = Bytecodes::_invokevirtual;
1113           }
1114           break;
1115         case Bytecodes::_invokehandle:
1116           if (!MethodHandles::is_signature_polymorphic_method(attached_method())) {
1117             bc = attached_method->is_static() ? Bytecodes::_invokestatic
1118                                               : Bytecodes::_invokevirtual;
1119           }
1120           break;
1121         default:
1122           break;
1123       }






1124     }
1125   }
1126 
1127   assert(bc != Bytecodes::_illegal, "not initialized");
1128 
1129   bool has_receiver = bc != Bytecodes::_invokestatic &&
1130                       bc != Bytecodes::_invokedynamic &&
1131                       bc != Bytecodes::_invokehandle;

1132 
1133   // Find receiver for non-static call
1134   if (has_receiver) {
1135     // This register map must be update since we need to find the receiver for
1136     // compiled frames. The receiver might be in a register.
1137     RegisterMap reg_map2(current);
1138     frame stubFrame   = current->last_frame();
1139     // Caller-frame is a compiled frame
1140     frame callerFrame = stubFrame.sender(&reg_map2);

1141 
1142     if (attached_method.is_null()) {
1143       Method* callee = bytecode.static_target(CHECK_NH);





1144       if (callee == NULL) {
1145         THROW_(vmSymbols::java_lang_NoSuchMethodException(), nullHandle);
1146       }
1147     }
1148 
1149     // Retrieve from a compiled argument list
1150     receiver = Handle(current, callerFrame.retrieve_receiver(&reg_map2));
1151 
1152     if (receiver.is_null()) {
1153       THROW_(vmSymbols::java_lang_NullPointerException(), nullHandle);









1154     }
1155   }
1156 
1157   // Resolve method
1158   if (attached_method.not_null()) {
1159     // Parameterized by attached method.
1160     LinkResolver::resolve_invoke(callinfo, receiver, attached_method, bc, CHECK_NH);
1161   } else {
1162     // Parameterized by bytecode.
1163     constantPoolHandle constants(current, caller->constants());
1164     LinkResolver::resolve_invoke(callinfo, receiver, constants, bytecode_index, bc, CHECK_NH);
1165   }
1166 
1167 #ifdef ASSERT
1168   // Check that the receiver klass is of the right subtype and that it is initialized for virtual calls
1169   if (has_receiver) {
1170     assert(receiver.not_null(), "should have thrown exception");
1171     Klass* receiver_klass = receiver->klass();
1172     Klass* rk = NULL;
1173     if (attached_method.not_null()) {
1174       // In case there's resolved method attached, use its holder during the check.
1175       rk = attached_method->method_holder();
1176     } else {
1177       // Klass is already loaded.
1178       constantPoolHandle constants(current, caller->constants());
1179       rk = constants->klass_ref_at(bytecode_index, CHECK_NH);
1180     }
1181     Klass* static_receiver_klass = rk;
1182     assert(receiver_klass->is_subtype_of(static_receiver_klass),
1183            "actual receiver must be subclass of static receiver klass");
1184     if (receiver_klass->is_instance_klass()) {
1185       if (InstanceKlass::cast(receiver_klass)->is_not_initialized()) {
1186         tty->print_cr("ERROR: Klass not yet initialized!!");
1187         receiver_klass->print();
1188       }
1189       assert(!InstanceKlass::cast(receiver_klass)->is_not_initialized(), "receiver_klass must be initialized");
1190     }
1191   }
1192 #endif
1193 
1194   return receiver;
1195 }
1196 
1197 methodHandle SharedRuntime::find_callee_method(TRAPS) {
1198   JavaThread* current = THREAD;
1199   ResourceMark rm(current);
1200   // We need first to check if any Java activations (compiled, interpreted)
1201   // exist on the stack since last JavaCall.  If not, we need
1202   // to get the target method from the JavaCall wrapper.
1203   vframeStream vfst(current, true);  // Do not skip any javaCalls
1204   methodHandle callee_method;
1205   if (vfst.at_end()) {
1206     // No Java frames were found on stack since we did the JavaCall.
1207     // Hence the stack can only contain an entry_frame.  We need to
1208     // find the target method from the stub frame.
1209     RegisterMap reg_map(current, false);
1210     frame fr = current->last_frame();
1211     assert(fr.is_runtime_frame(), "must be a runtimeStub");
1212     fr = fr.sender(&reg_map);
1213     assert(fr.is_entry_frame(), "must be");
1214     // fr is now pointing to the entry frame.
1215     callee_method = methodHandle(current, fr.entry_frame_call_wrapper()->callee_method());
1216   } else {
1217     Bytecodes::Code bc;
1218     CallInfo callinfo;
1219     find_callee_info_helper(vfst, bc, callinfo, CHECK_(methodHandle()));
1220     callee_method = methodHandle(current, callinfo.selected_method());
1221   }
1222   assert(callee_method()->is_method(), "must be");
1223   return callee_method;
1224 }
1225 
1226 // Resolves a call.
1227 methodHandle SharedRuntime::resolve_helper(bool is_virtual, bool is_optimized, TRAPS) {
1228   methodHandle callee_method;
1229   callee_method = resolve_sub_helper(is_virtual, is_optimized, THREAD);
1230   if (JvmtiExport::can_hotswap_or_post_breakpoint()) {
1231     int retry_count = 0;
1232     while (!HAS_PENDING_EXCEPTION && callee_method->is_old() &&
1233            callee_method->method_holder() != vmClasses::Object_klass()) {
1234       // If has a pending exception then there is no need to re-try to
1235       // resolve this method.
1236       // If the method has been redefined, we need to try again.
1237       // Hack: we have no way to update the vtables of arrays, so don't
1238       // require that java.lang.Object has been updated.
1239 
1240       // It is very unlikely that method is redefined more than 100 times
1241       // in the middle of resolve. If it is looping here more than 100 times
1242       // means then there could be a bug here.
1243       guarantee((retry_count++ < 100),
1244                 "Could not resolve to latest version of redefined method");
1245       // method is redefined in the middle of resolve so re-try.
1246       callee_method = resolve_sub_helper(is_virtual, is_optimized, THREAD);
1247     }
1248   }
1249   return callee_method;
1250 }
1251 
1252 // This fails if resolution required refilling of IC stubs
1253 bool SharedRuntime::resolve_sub_helper_internal(methodHandle callee_method, const frame& caller_frame,
1254                                                 CompiledMethod* caller_nm, bool is_virtual, bool is_optimized,
1255                                                 Handle receiver, CallInfo& call_info, Bytecodes::Code invoke_code, TRAPS) {
1256   StaticCallInfo static_call_info;
1257   CompiledICInfo virtual_call_info;
1258 
1259   // Make sure the callee nmethod does not get deoptimized and removed before
1260   // we are done patching the code.
1261   CompiledMethod* callee = callee_method->code();
1262 
1263   if (callee != NULL) {
1264     assert(callee->is_compiled(), "must be nmethod for patching");
1265   }
1266 
1267   if (callee != NULL && !callee->is_in_use()) {
1268     // Patch call site to C2I adapter if callee nmethod is deoptimized or unloaded.
1269     callee = NULL;
1270   }
1271   nmethodLocker nl_callee(callee);
1272 #ifdef ASSERT
1273   address dest_entry_point = callee == NULL ? 0 : callee->entry_point(); // used below
1274 #endif
1275 
1276   bool is_nmethod = caller_nm->is_nmethod();

1277 
1278   if (is_virtual) {
1279     assert(receiver.not_null() || invoke_code == Bytecodes::_invokehandle, "sanity check");








1280     bool static_bound = call_info.resolved_method()->can_be_statically_bound();
1281     Klass* klass = invoke_code == Bytecodes::_invokehandle ? NULL : receiver->klass();
1282     CompiledIC::compute_monomorphic_entry(callee_method, klass,
1283                      is_optimized, static_bound, is_nmethod, virtual_call_info,
1284                      CHECK_false);
1285   } else {
1286     // static call
1287     CompiledStaticCall::compute_entry(callee_method, is_nmethod, static_call_info);
1288   }
1289 
1290   // grab lock, check for deoptimization and potentially patch caller
1291   {
1292     CompiledICLocker ml(caller_nm);
1293 
1294     // Lock blocks for safepoint during which both nmethods can change state.
1295 
1296     // Now that we are ready to patch if the Method* was redefined then
1297     // don't update call site and let the caller retry.
1298     // Don't update call site if callee nmethod was unloaded or deoptimized.
1299     // Don't update call site if callee nmethod was replaced by an other nmethod
1300     // which may happen when multiply alive nmethod (tiered compilation)
1301     // will be supported.
1302     if (!callee_method->is_old() &&
1303         (callee == NULL || (callee->is_in_use() && callee_method->code() == callee))) {
1304       NoSafepointVerifier nsv;
1305 #ifdef ASSERT
1306       // We must not try to patch to jump to an already unloaded method.
1307       if (dest_entry_point != 0) {
1308         CodeBlob* cb = CodeCache::find_blob(dest_entry_point);
1309         assert((cb != NULL) && cb->is_compiled() && (((CompiledMethod*)cb) == callee),
1310                "should not call unloaded nmethod");
1311       }
1312 #endif
1313       if (is_virtual) {
1314         CompiledIC* inline_cache = CompiledIC_before(caller_nm, caller_frame.pc());
1315         if (inline_cache->is_clean()) {
1316           if (!inline_cache->set_to_monomorphic(virtual_call_info)) {
1317             return false;
1318           }
1319         }
1320       } else {
1321         if (VM_Version::supports_fast_class_init_checks() &&
1322             invoke_code == Bytecodes::_invokestatic &&
1323             callee_method->needs_clinit_barrier() &&
1324             callee != NULL && callee->is_compiled_by_jvmci()) {
1325           return true; // skip patching for JVMCI
1326         }
1327         CompiledStaticCall* ssc = caller_nm->compiledStaticCall_before(caller_frame.pc());
1328         if (ssc->is_clean()) ssc->set(static_call_info);
1329       }
1330     }
1331   } // unlock CompiledICLocker
1332   return true;
1333 }
1334 
1335 // Resolves a call.  The compilers generate code for calls that go here
1336 // and are patched with the real destination of the call.
1337 methodHandle SharedRuntime::resolve_sub_helper(bool is_virtual, bool is_optimized, TRAPS) {
1338   JavaThread* current = THREAD;
1339   ResourceMark rm(current);
1340   RegisterMap cbl_map(current, false);
1341   frame caller_frame = current->last_frame().sender(&cbl_map);
1342 
1343   CodeBlob* caller_cb = caller_frame.cb();
1344   guarantee(caller_cb != NULL && caller_cb->is_compiled(), "must be called from compiled method");
1345   CompiledMethod* caller_nm = caller_cb->as_compiled_method_or_null();

1346 
1347   // make sure caller is not getting deoptimized
1348   // and removed before we are done with it.
1349   // CLEANUP - with lazy deopt shouldn't need this lock
1350   nmethodLocker caller_lock(caller_nm);
1351 
1352   // determine call info & receiver
1353   // note: a) receiver is NULL for static calls
1354   //       b) an exception is thrown if receiver is NULL for non-static calls
1355   CallInfo call_info;
1356   Bytecodes::Code invoke_code = Bytecodes::_illegal;
1357   Handle receiver = find_callee_info(invoke_code, call_info, CHECK_(methodHandle()));
1358   methodHandle callee_method(current, call_info.selected_method());
1359 
1360   assert((!is_virtual && invoke_code == Bytecodes::_invokestatic ) ||
1361          (!is_virtual && invoke_code == Bytecodes::_invokespecial) ||
1362          (!is_virtual && invoke_code == Bytecodes::_invokehandle ) ||
1363          (!is_virtual && invoke_code == Bytecodes::_invokedynamic) ||
1364          ( is_virtual && invoke_code != Bytecodes::_invokestatic ), "inconsistent bytecode");
1365 
1366   assert(caller_nm->is_alive() && !caller_nm->is_unloading(), "It should be alive");
1367 
1368 #ifndef PRODUCT
1369   // tracing/debugging/statistics
1370   int *addr = (is_optimized) ? (&_resolve_opt_virtual_ctr) :
1371                 (is_virtual) ? (&_resolve_virtual_ctr) :
1372                                (&_resolve_static_ctr);
1373   Atomic::inc(addr);
1374 
1375   if (TraceCallFixup) {
1376     ResourceMark rm(current);
1377     tty->print("resolving %s%s (%s) call to",
1378                (is_optimized) ? "optimized " : "", (is_virtual) ? "virtual" : "static",
1379                Bytecodes::name(invoke_code));
1380     callee_method->print_short_name(tty);
1381     tty->print_cr(" at pc: " INTPTR_FORMAT " to code: " INTPTR_FORMAT,
1382                   p2i(caller_frame.pc()), p2i(callee_method->code()));
1383   }
1384 #endif
1385 
1386   if (invoke_code == Bytecodes::_invokestatic) {
1387     assert(callee_method->method_holder()->is_initialized() ||
1388            callee_method->method_holder()->is_reentrant_initialization(current),
1389            "invalid class initialization state for invoke_static");
1390     if (!VM_Version::supports_fast_class_init_checks() && callee_method->needs_clinit_barrier()) {
1391       // In order to keep class initialization check, do not patch call
1392       // site for static call when the class is not fully initialized.
1393       // Proper check is enforced by call site re-resolution on every invocation.
1394       //
1395       // When fast class initialization checks are supported (VM_Version::supports_fast_class_init_checks() == true),
1396       // explicit class initialization check is put in nmethod entry (VEP).
1397       assert(callee_method->method_holder()->is_linked(), "must be");
1398       return callee_method;
1399     }
1400   }
1401 
1402   // JSR 292 key invariant:
1403   // If the resolved method is a MethodHandle invoke target, the call
1404   // site must be a MethodHandle call site, because the lambda form might tail-call
1405   // leaving the stack in a state unknown to either caller or callee
1406   // TODO detune for now but we might need it again
1407 //  assert(!callee_method->is_compiled_lambda_form() ||
1408 //         caller_nm->is_method_handle_return(caller_frame.pc()), "must be MH call site");
1409 
1410   // Compute entry points. This might require generation of C2I converter
1411   // frames, so we cannot be holding any locks here. Furthermore, the
1412   // computation of the entry points is independent of patching the call.  We
1413   // always return the entry-point, but we only patch the stub if the call has
1414   // not been deoptimized.  Return values: For a virtual call this is an
1415   // (cached_oop, destination address) pair. For a static call/optimized
1416   // virtual this is just a destination address.
1417 
1418   // Patching IC caches may fail if we run out if transition stubs.
1419   // We refill the ic stubs then and try again.
1420   for (;;) {
1421     ICRefillVerifier ic_refill_verifier;
1422     bool successful = resolve_sub_helper_internal(callee_method, caller_frame, caller_nm,
1423                                                   is_virtual, is_optimized, receiver,
1424                                                   call_info, invoke_code, CHECK_(methodHandle()));
1425     if (successful) {
1426       return callee_method;
1427     } else {
1428       InlineCacheBuffer::refill_ic_stubs();
1429     }
1430   }
1431 
1432 }
1433 
1434 
1435 // Inline caches exist only in compiled code
1436 JRT_BLOCK_ENTRY(address, SharedRuntime::handle_wrong_method_ic_miss(JavaThread* current))
1437 #ifdef ASSERT
1438   RegisterMap reg_map(current, false);
1439   frame stub_frame = current->last_frame();
1440   assert(stub_frame.is_runtime_frame(), "sanity check");
1441   frame caller_frame = stub_frame.sender(&reg_map);
1442   assert(!caller_frame.is_interpreted_frame() && !caller_frame.is_entry_frame() && !caller_frame.is_optimized_entry_frame(), "unexpected frame");
1443 #endif /* ASSERT */
1444 
1445   methodHandle callee_method;


1446   JRT_BLOCK
1447     callee_method = SharedRuntime::handle_ic_miss_helper(CHECK_NULL);
1448     // Return Method* through TLS
1449     current->set_vm_result_2(callee_method());
1450   JRT_BLOCK_END
1451   // return compiled code entry point after potential safepoints
1452   assert(callee_method->verified_code_entry() != NULL, " Jump to zero!");
1453   return callee_method->verified_code_entry();
1454 JRT_END
1455 
1456 
1457 // Handle call site that has been made non-entrant
1458 JRT_BLOCK_ENTRY(address, SharedRuntime::handle_wrong_method(JavaThread* current))
1459   // 6243940 We might end up in here if the callee is deoptimized
1460   // as we race to call it.  We don't want to take a safepoint if
1461   // the caller was interpreted because the caller frame will look
1462   // interpreted to the stack walkers and arguments are now
1463   // "compiled" so it is much better to make this transition
1464   // invisible to the stack walking code. The i2c path will
1465   // place the callee method in the callee_target. It is stashed
1466   // there because if we try and find the callee by normal means a
1467   // safepoint is possible and have trouble gc'ing the compiled args.
1468   RegisterMap reg_map(current, false);
1469   frame stub_frame = current->last_frame();
1470   assert(stub_frame.is_runtime_frame(), "sanity check");
1471   frame caller_frame = stub_frame.sender(&reg_map);
1472 
1473   if (caller_frame.is_interpreted_frame() ||
1474       caller_frame.is_entry_frame() ||
1475       caller_frame.is_optimized_entry_frame()) {
1476     Method* callee = current->callee_target();
1477     guarantee(callee != NULL && callee->is_method(), "bad handshake");
1478     current->set_vm_result_2(callee);
1479     current->set_callee_target(NULL);
1480     if (caller_frame.is_entry_frame() && VM_Version::supports_fast_class_init_checks()) {
1481       // Bypass class initialization checks in c2i when caller is in native.
1482       // JNI calls to static methods don't have class initialization checks.
1483       // Fast class initialization checks are present in c2i adapters and call into
1484       // SharedRuntime::handle_wrong_method() on the slow path.
1485       //
1486       // JVM upcalls may land here as well, but there's a proper check present in
1487       // LinkResolver::resolve_static_call (called from JavaCalls::call_static),
1488       // so bypassing it in c2i adapter is benign.
1489       return callee->get_c2i_no_clinit_check_entry();
1490     } else {
1491       return callee->get_c2i_entry();
1492     }
1493   }
1494 
1495   // Must be compiled to compiled path which is safe to stackwalk
1496   methodHandle callee_method;



1497   JRT_BLOCK
1498     // Force resolving of caller (if we called from compiled frame)
1499     callee_method = SharedRuntime::reresolve_call_site(CHECK_NULL);
1500     current->set_vm_result_2(callee_method());
1501   JRT_BLOCK_END
1502   // return compiled code entry point after potential safepoints
1503   assert(callee_method->verified_code_entry() != NULL, " Jump to zero!");
1504   return callee_method->verified_code_entry();
1505 JRT_END
1506 
1507 // Handle abstract method call
1508 JRT_BLOCK_ENTRY(address, SharedRuntime::handle_wrong_method_abstract(JavaThread* current))
1509   // Verbose error message for AbstractMethodError.
1510   // Get the called method from the invoke bytecode.
1511   vframeStream vfst(current, true);
1512   assert(!vfst.at_end(), "Java frame must exist");
1513   methodHandle caller(current, vfst.method());
1514   Bytecode_invoke invoke(caller, vfst.bci());
1515   DEBUG_ONLY( invoke.verify(); )
1516 
1517   // Find the compiled caller frame.
1518   RegisterMap reg_map(current);
1519   frame stubFrame = current->last_frame();
1520   assert(stubFrame.is_runtime_frame(), "must be");
1521   frame callerFrame = stubFrame.sender(&reg_map);
1522   assert(callerFrame.is_compiled_frame(), "must be");
1523 
1524   // Install exception and return forward entry.
1525   address res = StubRoutines::throw_AbstractMethodError_entry();
1526   JRT_BLOCK
1527     methodHandle callee(current, invoke.static_target(current));
1528     if (!callee.is_null()) {
1529       oop recv = callerFrame.retrieve_receiver(&reg_map);
1530       Klass *recv_klass = (recv != NULL) ? recv->klass() : NULL;
1531       res = StubRoutines::forward_exception_entry();
1532       LinkResolver::throw_abstract_method_error(callee, recv_klass, CHECK_(res));
1533     }
1534   JRT_BLOCK_END
1535   return res;
1536 JRT_END
1537 
1538 
1539 // resolve a static call and patch code
1540 JRT_BLOCK_ENTRY(address, SharedRuntime::resolve_static_call_C(JavaThread* current ))
1541   methodHandle callee_method;

1542   JRT_BLOCK
1543     callee_method = SharedRuntime::resolve_helper(false, false, CHECK_NULL);
1544     current->set_vm_result_2(callee_method());
1545   JRT_BLOCK_END
1546   // return compiled code entry point after potential safepoints
1547   assert(callee_method->verified_code_entry() != NULL, " Jump to zero!");
1548   return callee_method->verified_code_entry();


1549 JRT_END
1550 
1551 
1552 // resolve virtual call and update inline cache to monomorphic
1553 JRT_BLOCK_ENTRY(address, SharedRuntime::resolve_virtual_call_C(JavaThread* current))
1554   methodHandle callee_method;

1555   JRT_BLOCK
1556     callee_method = SharedRuntime::resolve_helper(true, false, CHECK_NULL);
1557     current->set_vm_result_2(callee_method());
1558   JRT_BLOCK_END
1559   // return compiled code entry point after potential safepoints
1560   assert(callee_method->verified_code_entry() != NULL, " Jump to zero!");
1561   return callee_method->verified_code_entry();


1562 JRT_END
1563 
1564 
1565 // Resolve a virtual call that can be statically bound (e.g., always
1566 // monomorphic, so it has no inline cache).  Patch code to resolved target.
1567 JRT_BLOCK_ENTRY(address, SharedRuntime::resolve_opt_virtual_call_C(JavaThread* current))
1568   methodHandle callee_method;

1569   JRT_BLOCK
1570     callee_method = SharedRuntime::resolve_helper(true, true, CHECK_NULL);
1571     current->set_vm_result_2(callee_method());
1572   JRT_BLOCK_END
1573   // return compiled code entry point after potential safepoints
1574   assert(callee_method->verified_code_entry() != NULL, " Jump to zero!");
1575   return callee_method->verified_code_entry();


1576 JRT_END
1577 
1578 // The handle_ic_miss_helper_internal function returns false if it failed due
1579 // to either running out of vtable stubs or ic stubs due to IC transitions
1580 // to transitional states. The needs_ic_stub_refill value will be set if
1581 // the failure was due to running out of IC stubs, in which case handle_ic_miss_helper
1582 // refills the IC stubs and tries again.
1583 bool SharedRuntime::handle_ic_miss_helper_internal(Handle receiver, CompiledMethod* caller_nm,
1584                                                    const frame& caller_frame, methodHandle callee_method,
1585                                                    Bytecodes::Code bc, CallInfo& call_info,
1586                                                    bool& needs_ic_stub_refill, TRAPS) {
1587   CompiledICLocker ml(caller_nm);
1588   CompiledIC* inline_cache = CompiledIC_before(caller_nm, caller_frame.pc());
1589   bool should_be_mono = false;
1590   if (inline_cache->is_optimized()) {
1591     if (TraceCallFixup) {
1592       ResourceMark rm(THREAD);
1593       tty->print("OPTIMIZED IC miss (%s) call to", Bytecodes::name(bc));
1594       callee_method->print_short_name(tty);
1595       tty->print_cr(" code: " INTPTR_FORMAT, p2i(callee_method->code()));
1596     }

1597     should_be_mono = true;
1598   } else if (inline_cache->is_icholder_call()) {
1599     CompiledICHolder* ic_oop = inline_cache->cached_icholder();
1600     if (ic_oop != NULL) {
1601       if (!ic_oop->is_loader_alive()) {
1602         // Deferred IC cleaning due to concurrent class unloading
1603         if (!inline_cache->set_to_clean()) {
1604           needs_ic_stub_refill = true;
1605           return false;
1606         }
1607       } else if (receiver()->klass() == ic_oop->holder_klass()) {
1608         // This isn't a real miss. We must have seen that compiled code
1609         // is now available and we want the call site converted to a
1610         // monomorphic compiled call site.
1611         // We can't assert for callee_method->code() != NULL because it
1612         // could have been deoptimized in the meantime
1613         if (TraceCallFixup) {
1614           ResourceMark rm(THREAD);
1615           tty->print("FALSE IC miss (%s) converting to compiled call to", Bytecodes::name(bc));
1616           callee_method->print_short_name(tty);
1617           tty->print_cr(" code: " INTPTR_FORMAT, p2i(callee_method->code()));
1618         }
1619         should_be_mono = true;
1620       }
1621     }
1622   }
1623 
1624   if (should_be_mono) {
1625     // We have a path that was monomorphic but was going interpreted
1626     // and now we have (or had) a compiled entry. We correct the IC
1627     // by using a new icBuffer.
1628     CompiledICInfo info;
1629     Klass* receiver_klass = receiver()->klass();
1630     inline_cache->compute_monomorphic_entry(callee_method,
1631                                             receiver_klass,
1632                                             inline_cache->is_optimized(),
1633                                             false, caller_nm->is_nmethod(),

1634                                             info, CHECK_false);
1635     if (!inline_cache->set_to_monomorphic(info)) {
1636       needs_ic_stub_refill = true;
1637       return false;
1638     }
1639   } else if (!inline_cache->is_megamorphic() && !inline_cache->is_clean()) {
1640     // Potential change to megamorphic
1641 
1642     bool successful = inline_cache->set_to_megamorphic(&call_info, bc, needs_ic_stub_refill, CHECK_false);
1643     if (needs_ic_stub_refill) {
1644       return false;
1645     }
1646     if (!successful) {
1647       if (!inline_cache->set_to_clean()) {
1648         needs_ic_stub_refill = true;
1649         return false;
1650       }
1651     }
1652   } else {
1653     // Either clean or megamorphic
1654   }
1655   return true;
1656 }
1657 
1658 methodHandle SharedRuntime::handle_ic_miss_helper(TRAPS) {
1659   JavaThread* current = THREAD;
1660   ResourceMark rm(current);
1661   CallInfo call_info;
1662   Bytecodes::Code bc;
1663 
1664   // receiver is NULL for static calls. An exception is thrown for NULL
1665   // receivers for non-static calls
1666   Handle receiver = find_callee_info(bc, call_info, CHECK_(methodHandle()));
1667   // Compiler1 can produce virtual call sites that can actually be statically bound
1668   // If we fell thru to below we would think that the site was going megamorphic
1669   // when in fact the site can never miss. Worse because we'd think it was megamorphic
1670   // we'd try and do a vtable dispatch however methods that can be statically bound
1671   // don't have vtable entries (vtable_index < 0) and we'd blow up. So we force a
1672   // reresolution of the  call site (as if we did a handle_wrong_method and not an
1673   // plain ic_miss) and the site will be converted to an optimized virtual call site
1674   // never to miss again. I don't believe C2 will produce code like this but if it
1675   // did this would still be the correct thing to do for it too, hence no ifdef.
1676   //
1677   if (call_info.resolved_method()->can_be_statically_bound()) {
1678     methodHandle callee_method = SharedRuntime::reresolve_call_site(CHECK_(methodHandle()));


1679     if (TraceCallFixup) {
1680       RegisterMap reg_map(current, false);
1681       frame caller_frame = current->last_frame().sender(&reg_map);
1682       ResourceMark rm(current);
1683       tty->print("converting IC miss to reresolve (%s) call to", Bytecodes::name(bc));
1684       callee_method->print_short_name(tty);
1685       tty->print_cr(" from pc: " INTPTR_FORMAT, p2i(caller_frame.pc()));
1686       tty->print_cr(" code: " INTPTR_FORMAT, p2i(callee_method->code()));
1687     }
1688     return callee_method;
1689   }
1690 
1691   methodHandle callee_method(current, call_info.selected_method());
1692 
1693 #ifndef PRODUCT
1694   Atomic::inc(&_ic_miss_ctr);
1695 
1696   // Statistics & Tracing
1697   if (TraceCallFixup) {
1698     ResourceMark rm(current);
1699     tty->print("IC miss (%s) call to", Bytecodes::name(bc));
1700     callee_method->print_short_name(tty);
1701     tty->print_cr(" code: " INTPTR_FORMAT, p2i(callee_method->code()));
1702   }
1703 
1704   if (ICMissHistogram) {
1705     MutexLocker m(VMStatistic_lock);
1706     RegisterMap reg_map(current, false);
1707     frame f = current->last_frame().real_sender(&reg_map);// skip runtime stub
1708     // produce statistics under the lock
1709     trace_ic_miss(f.pc());
1710   }
1711 #endif
1712 
1713   // install an event collector so that when a vtable stub is created the
1714   // profiler can be notified via a DYNAMIC_CODE_GENERATED event. The
1715   // event can't be posted when the stub is created as locks are held
1716   // - instead the event will be deferred until the event collector goes
1717   // out of scope.
1718   JvmtiDynamicCodeEventCollector event_collector;
1719 
1720   // Update inline cache to megamorphic. Skip update if we are called from interpreted.
1721   // Transitioning IC caches may require transition stubs. If we run out
1722   // of transition stubs, we have to drop locks and perform a safepoint
1723   // that refills them.
1724   RegisterMap reg_map(current, false);
1725   frame caller_frame = current->last_frame().sender(&reg_map);
1726   CodeBlob* cb = caller_frame.cb();
1727   CompiledMethod* caller_nm = cb->as_compiled_method();

1728 
1729   for (;;) {
1730     ICRefillVerifier ic_refill_verifier;
1731     bool needs_ic_stub_refill = false;
1732     bool successful = handle_ic_miss_helper_internal(receiver, caller_nm, caller_frame, callee_method,
1733                                                      bc, call_info, needs_ic_stub_refill, CHECK_(methodHandle()));
1734     if (successful || !needs_ic_stub_refill) {
1735       return callee_method;
1736     } else {
1737       InlineCacheBuffer::refill_ic_stubs();
1738     }
1739   }
1740 }
1741 
1742 static bool clear_ic_at_addr(CompiledMethod* caller_nm, address call_addr, bool is_static_call) {
1743   CompiledICLocker ml(caller_nm);
1744   if (is_static_call) {
1745     CompiledStaticCall* ssc = caller_nm->compiledStaticCall_at(call_addr);
1746     if (!ssc->is_clean()) {
1747       return ssc->set_to_clean();
1748     }
1749   } else {
1750     // compiled, dispatched call (which used to call an interpreted method)
1751     CompiledIC* inline_cache = CompiledIC_at(caller_nm, call_addr);
1752     if (!inline_cache->is_clean()) {
1753       return inline_cache->set_to_clean();
1754     }
1755   }
1756   return true;
1757 }
1758 
1759 //
1760 // Resets a call-site in compiled code so it will get resolved again.
1761 // This routines handles both virtual call sites, optimized virtual call
1762 // sites, and static call sites. Typically used to change a call sites
1763 // destination from compiled to interpreted.
1764 //
1765 methodHandle SharedRuntime::reresolve_call_site(TRAPS) {
1766   JavaThread* current = THREAD;
1767   ResourceMark rm(current);
1768   RegisterMap reg_map(current, false);
1769   frame stub_frame = current->last_frame();
1770   assert(stub_frame.is_runtime_frame(), "must be a runtimeStub");
1771   frame caller = stub_frame.sender(&reg_map);
1772 
1773   // Do nothing if the frame isn't a live compiled frame.
1774   // nmethod could be deoptimized by the time we get here
1775   // so no update to the caller is needed.
1776 
1777   if (caller.is_compiled_frame() && !caller.is_deoptimized_frame()) {
1778 
1779     address pc = caller.pc();
1780 
1781     // Check for static or virtual call
1782     bool is_static_call = false;
1783     CompiledMethod* caller_nm = CodeCache::find_compiled(pc);

1784 
1785     // Default call_addr is the location of the "basic" call.
1786     // Determine the address of the call we a reresolving. With
1787     // Inline Caches we will always find a recognizable call.
1788     // With Inline Caches disabled we may or may not find a
1789     // recognizable call. We will always find a call for static
1790     // calls and for optimized virtual calls. For vanilla virtual
1791     // calls it depends on the state of the UseInlineCaches switch.
1792     //
1793     // With Inline Caches disabled we can get here for a virtual call
1794     // for two reasons:
1795     //   1 - calling an abstract method. The vtable for abstract methods
1796     //       will run us thru handle_wrong_method and we will eventually
1797     //       end up in the interpreter to throw the ame.
1798     //   2 - a racing deoptimization. We could be doing a vanilla vtable
1799     //       call and between the time we fetch the entry address and
1800     //       we jump to it the target gets deoptimized. Similar to 1
1801     //       we will wind up in the interprter (thru a c2i with c2).
1802     //
1803     address call_addr = NULL;
1804     {
1805       // Get call instruction under lock because another thread may be
1806       // busy patching it.
1807       CompiledICLocker ml(caller_nm);
1808       // Location of call instruction
1809       call_addr = caller_nm->call_instruction_address(pc);
1810     }
1811     // Make sure nmethod doesn't get deoptimized and removed until
1812     // this is done with it.
1813     // CLEANUP - with lazy deopt shouldn't need this lock
1814     nmethodLocker nmlock(caller_nm);
1815 
1816     if (call_addr != NULL) {
1817       RelocIterator iter(caller_nm, call_addr, call_addr+1);
1818       int ret = iter.next(); // Get item
1819       if (ret) {
1820         assert(iter.addr() == call_addr, "must find call");
1821         if (iter.type() == relocInfo::static_call_type) {
1822           is_static_call = true;
1823         } else {
1824           assert(iter.type() == relocInfo::virtual_call_type ||
1825                  iter.type() == relocInfo::opt_virtual_call_type
1826                 , "unexpected relocInfo. type");

1827         }
1828       } else {
1829         assert(!UseInlineCaches, "relocation info. must exist for this address");
1830       }
1831 
1832       // Cleaning the inline cache will force a new resolve. This is more robust
1833       // than directly setting it to the new destination, since resolving of calls
1834       // is always done through the same code path. (experience shows that it
1835       // leads to very hard to track down bugs, if an inline cache gets updated
1836       // to a wrong method). It should not be performance critical, since the
1837       // resolve is only done once.
1838 
1839       for (;;) {
1840         ICRefillVerifier ic_refill_verifier;
1841         if (!clear_ic_at_addr(caller_nm, call_addr, is_static_call)) {
1842           InlineCacheBuffer::refill_ic_stubs();
1843         } else {
1844           break;
1845         }
1846       }
1847     }
1848   }
1849 
1850   methodHandle callee_method = find_callee_method(CHECK_(methodHandle()));
1851 
1852 
1853 #ifndef PRODUCT
1854   Atomic::inc(&_wrong_method_ctr);
1855 
1856   if (TraceCallFixup) {
1857     ResourceMark rm(current);
1858     tty->print("handle_wrong_method reresolving call to");
1859     callee_method->print_short_name(tty);
1860     tty->print_cr(" code: " INTPTR_FORMAT, p2i(callee_method->code()));
1861   }
1862 #endif
1863 
1864   return callee_method;
1865 }
1866 
1867 address SharedRuntime::handle_unsafe_access(JavaThread* thread, address next_pc) {
1868   // The faulting unsafe accesses should be changed to throw the error
1869   // synchronously instead. Meanwhile the faulting instruction will be
1870   // skipped over (effectively turning it into a no-op) and an
1871   // asynchronous exception will be raised which the thread will
1872   // handle at a later point. If the instruction is a load it will
1873   // return garbage.
1874 
1875   // Request an async exception.
1876   thread->set_pending_unsafe_access_error();
1877 
1878   // Return address of next instruction to execute.
1879   return next_pc;
1880 }
1881 
1882 #ifdef ASSERT
1883 void SharedRuntime::check_member_name_argument_is_last_argument(const methodHandle& method,
1884                                                                 const BasicType* sig_bt,
1885                                                                 const VMRegPair* regs) {
1886   ResourceMark rm;
1887   const int total_args_passed = method->size_of_parameters();
1888   const VMRegPair*    regs_with_member_name = regs;
1889         VMRegPair* regs_without_member_name = NEW_RESOURCE_ARRAY(VMRegPair, total_args_passed - 1);
1890 
1891   const int member_arg_pos = total_args_passed - 1;
1892   assert(member_arg_pos >= 0 && member_arg_pos < total_args_passed, "oob");
1893   assert(sig_bt[member_arg_pos] == T_OBJECT, "dispatch argument must be an object");
1894 
1895   int comp_args_on_stack = java_calling_convention(sig_bt, regs_without_member_name, total_args_passed - 1);
1896 
1897   for (int i = 0; i < member_arg_pos; i++) {
1898     VMReg a =    regs_with_member_name[i].first();
1899     VMReg b = regs_without_member_name[i].first();
1900     assert(a->value() == b->value(), "register allocation mismatch: a=" INTX_FORMAT ", b=" INTX_FORMAT, a->value(), b->value());
1901   }
1902   assert(regs_with_member_name[member_arg_pos].first()->is_valid(), "bad member arg");
1903 }
1904 #endif
1905 
1906 bool SharedRuntime::should_fixup_call_destination(address destination, address entry_point, address caller_pc, Method* moop, CodeBlob* cb) {
1907   if (destination != entry_point) {
1908     CodeBlob* callee = CodeCache::find_blob(destination);
1909     // callee == cb seems weird. It means calling interpreter thru stub.
1910     if (callee != NULL && (callee == cb || callee->is_adapter_blob())) {
1911       // static call or optimized virtual
1912       if (TraceCallFixup) {
1913         tty->print("fixup callsite           at " INTPTR_FORMAT " to compiled code for", p2i(caller_pc));
1914         moop->print_short_name(tty);
1915         tty->print_cr(" to " INTPTR_FORMAT, p2i(entry_point));
1916       }
1917       return true;
1918     } else {
1919       if (TraceCallFixup) {
1920         tty->print("failed to fixup callsite at " INTPTR_FORMAT " to compiled code for", p2i(caller_pc));
1921         moop->print_short_name(tty);
1922         tty->print_cr(" to " INTPTR_FORMAT, p2i(entry_point));
1923       }
1924       // assert is too strong could also be resolve destinations.
1925       // assert(InlineCacheBuffer::contains(destination) || VtableStubs::contains(destination), "must be");
1926     }
1927   } else {
1928     if (TraceCallFixup) {
1929       tty->print("already patched callsite at " INTPTR_FORMAT " to compiled code for", p2i(caller_pc));
1930       moop->print_short_name(tty);
1931       tty->print_cr(" to " INTPTR_FORMAT, p2i(entry_point));
1932     }
1933   }
1934   return false;
1935 }
1936 
1937 // ---------------------------------------------------------------------------
1938 // We are calling the interpreter via a c2i. Normally this would mean that
1939 // we were called by a compiled method. However we could have lost a race
1940 // where we went int -> i2c -> c2i and so the caller could in fact be
1941 // interpreted. If the caller is compiled we attempt to patch the caller
1942 // so he no longer calls into the interpreter.
1943 JRT_LEAF(void, SharedRuntime::fixup_callers_callsite(Method* method, address caller_pc))
1944   Method* moop(method);
1945 
1946   address entry_point = moop->from_compiled_entry_no_trampoline();
1947 
1948   // It's possible that deoptimization can occur at a call site which hasn't
1949   // been resolved yet, in which case this function will be called from
1950   // an nmethod that has been patched for deopt and we can ignore the
1951   // request for a fixup.
1952   // Also it is possible that we lost a race in that from_compiled_entry
1953   // is now back to the i2c in that case we don't need to patch and if
1954   // we did we'd leap into space because the callsite needs to use
1955   // "to interpreter" stub in order to load up the Method*. Don't
1956   // ask me how I know this...
1957 
1958   CodeBlob* cb = CodeCache::find_blob(caller_pc);
1959   if (cb == NULL || !cb->is_compiled() || entry_point == moop->get_c2i_entry()) {




1960     return;
1961   }
1962 
1963   // The check above makes sure this is a nmethod.
1964   CompiledMethod* nm = cb->as_compiled_method_or_null();
1965   assert(nm, "must be");
1966 
1967   // Get the return PC for the passed caller PC.
1968   address return_pc = caller_pc + frame::pc_return_offset;
1969 
1970   // There is a benign race here. We could be attempting to patch to a compiled
1971   // entry point at the same time the callee is being deoptimized. If that is
1972   // the case then entry_point may in fact point to a c2i and we'd patch the
1973   // call site with the same old data. clear_code will set code() to NULL
1974   // at the end of it. If we happen to see that NULL then we can skip trying
1975   // to patch. If we hit the window where the callee has a c2i in the
1976   // from_compiled_entry and the NULL isn't present yet then we lose the race
1977   // and patch the code with the same old data. Asi es la vida.
1978 
1979   if (moop->code() == NULL) return;
1980 
1981   if (nm->is_in_use()) {
1982     // Expect to find a native call there (unless it was no-inline cache vtable dispatch)
1983     CompiledICLocker ic_locker(nm);
1984     if (NativeCall::is_call_before(return_pc)) {
1985       ResourceMark mark;
1986       NativeCallWrapper* call = nm->call_wrapper_before(return_pc);
1987       //
1988       // bug 6281185. We might get here after resolving a call site to a vanilla
1989       // virtual call. Because the resolvee uses the verified entry it may then
1990       // see compiled code and attempt to patch the site by calling us. This would
1991       // then incorrectly convert the call site to optimized and its downhill from
1992       // there. If you're lucky you'll get the assert in the bugid, if not you've
1993       // just made a call site that could be megamorphic into a monomorphic site
1994       // for the rest of its life! Just another racing bug in the life of
1995       // fixup_callers_callsite ...
1996       //
1997       RelocIterator iter(nm, call->instruction_address(), call->next_instruction_address());
1998       iter.next();
1999       assert(iter.has_current(), "must have a reloc at java call site");
2000       relocInfo::relocType typ = iter.reloc()->type();
2001       if (typ != relocInfo::static_call_type &&
2002            typ != relocInfo::opt_virtual_call_type &&
2003            typ != relocInfo::static_stub_type) {
2004         return;
2005       }
2006       address destination = call->destination();
2007       if (should_fixup_call_destination(destination, entry_point, caller_pc, moop, cb)) {
2008         call->set_destination_mt_safe(entry_point);
2009       }
2010     }
2011   }
2012 JRT_END
2013 
2014 
2015 // same as JVM_Arraycopy, but called directly from compiled code
2016 JRT_ENTRY(void, SharedRuntime::slow_arraycopy_C(oopDesc* src,  jint src_pos,
2017                                                 oopDesc* dest, jint dest_pos,
2018                                                 jint length,
2019                                                 JavaThread* current)) {
2020 #ifndef PRODUCT
2021   _slow_array_copy_ctr++;
2022 #endif
2023   // Check if we have null pointers
2024   if (src == NULL || dest == NULL) {
2025     THROW(vmSymbols::java_lang_NullPointerException());
2026   }
2027   // Do the copy.  The casts to arrayOop are necessary to the copy_array API,
2028   // even though the copy_array API also performs dynamic checks to ensure
2029   // that src and dest are truly arrays (and are conformable).
2030   // The copy_array mechanism is awkward and could be removed, but
2031   // the compilers don't call this function except as a last resort,
2032   // so it probably doesn't matter.
2033   src->klass()->copy_array((arrayOopDesc*)src, src_pos,
2034                                         (arrayOopDesc*)dest, dest_pos,
2035                                         length, current);
2036 }
2037 JRT_END
2038 
2039 // The caller of generate_class_cast_message() (or one of its callers)
2040 // must use a ResourceMark in order to correctly free the result.
2041 char* SharedRuntime::generate_class_cast_message(
2042     JavaThread* thread, Klass* caster_klass) {
2043 
2044   // Get target class name from the checkcast instruction
2045   vframeStream vfst(thread, true);
2046   assert(!vfst.at_end(), "Java frame must exist");
2047   Bytecode_checkcast cc(vfst.method(), vfst.method()->bcp_from(vfst.bci()));
2048   constantPoolHandle cpool(thread, vfst.method()->constants());
2049   Klass* target_klass = ConstantPool::klass_at_if_loaded(cpool, cc.index());
2050   Symbol* target_klass_name = NULL;
2051   if (target_klass == NULL) {
2052     // This klass should be resolved, but just in case, get the name in the klass slot.
2053     target_klass_name = cpool->klass_name_at(cc.index());
2054   }
2055   return generate_class_cast_message(caster_klass, target_klass, target_klass_name);
2056 }
2057 
2058 
2059 // The caller of generate_class_cast_message() (or one of its callers)
2060 // must use a ResourceMark in order to correctly free the result.
2061 char* SharedRuntime::generate_class_cast_message(
2062     Klass* caster_klass, Klass* target_klass, Symbol* target_klass_name) {
2063   const char* caster_name = caster_klass->external_name();
2064 
2065   assert(target_klass != NULL || target_klass_name != NULL, "one must be provided");
2066   const char* target_name = target_klass == NULL ? target_klass_name->as_klass_external_name() :
2067                                                    target_klass->external_name();
2068 
2069   size_t msglen = strlen(caster_name) + strlen("class ") + strlen(" cannot be cast to class ") + strlen(target_name) + 1;
2070 
2071   const char* caster_klass_description = "";
2072   const char* target_klass_description = "";
2073   const char* klass_separator = "";
2074   if (target_klass != NULL && caster_klass->module() == target_klass->module()) {
2075     caster_klass_description = caster_klass->joint_in_module_of_loader(target_klass);
2076   } else {
2077     caster_klass_description = caster_klass->class_in_module_of_loader();
2078     target_klass_description = (target_klass != NULL) ? target_klass->class_in_module_of_loader() : "";
2079     klass_separator = (target_klass != NULL) ? "; " : "";
2080   }
2081 
2082   // add 3 for parenthesis and preceeding space
2083   msglen += strlen(caster_klass_description) + strlen(target_klass_description) + strlen(klass_separator) + 3;
2084 
2085   char* message = NEW_RESOURCE_ARRAY_RETURN_NULL(char, msglen);
2086   if (message == NULL) {
2087     // Shouldn't happen, but don't cause even more problems if it does
2088     message = const_cast<char*>(caster_klass->external_name());
2089   } else {
2090     jio_snprintf(message,
2091                  msglen,
2092                  "class %s cannot be cast to class %s (%s%s%s)",
2093                  caster_name,
2094                  target_name,
2095                  caster_klass_description,
2096                  klass_separator,
2097                  target_klass_description
2098                  );
2099   }
2100   return message;
2101 }
2102 
2103 JRT_LEAF(void, SharedRuntime::reguard_yellow_pages())
2104   (void) JavaThread::current()->stack_overflow_state()->reguard_stack();
2105 JRT_END
2106 
2107 void SharedRuntime::monitor_enter_helper(oopDesc* obj, BasicLock* lock, JavaThread* current) {
2108   if (!SafepointSynchronize::is_synchronizing()) {
2109     // Only try quick_enter() if we're not trying to reach a safepoint
2110     // so that the calling thread reaches the safepoint more quickly.
2111     if (ObjectSynchronizer::quick_enter(obj, current, lock)) return;
2112   }
2113   // NO_ASYNC required because an async exception on the state transition destructor
2114   // would leave you with the lock held and it would never be released.
2115   // The normal monitorenter NullPointerException is thrown without acquiring a lock
2116   // and the model is that an exception implies the method failed.
2117   JRT_BLOCK_NO_ASYNC
2118   Handle h_obj(THREAD, obj);
2119   ObjectSynchronizer::enter(h_obj, lock, current);
2120   assert(!HAS_PENDING_EXCEPTION, "Should have no exception here");
2121   JRT_BLOCK_END
2122 }
2123 
2124 // Handles the uncommon case in locking, i.e., contention or an inflated lock.
2125 JRT_BLOCK_ENTRY(void, SharedRuntime::complete_monitor_locking_C(oopDesc* obj, BasicLock* lock, JavaThread* current))
2126   SharedRuntime::monitor_enter_helper(obj, lock, current);
2127 JRT_END
2128 
2129 void SharedRuntime::monitor_exit_helper(oopDesc* obj, BasicLock* lock, JavaThread* current) {
2130   assert(JavaThread::current() == current, "invariant");
2131   // Exit must be non-blocking, and therefore no exceptions can be thrown.
2132   ExceptionMark em(current);
2133   // The object could become unlocked through a JNI call, which we have no other checks for.
2134   // Give a fatal message if CheckJNICalls. Otherwise we ignore it.
2135   if (obj->is_unlocked()) {
2136     if (CheckJNICalls) {
2137       fatal("Object has been unlocked by JNI");
2138     }
2139     return;
2140   }
2141   ObjectSynchronizer::exit(obj, lock, current);
2142 }
2143 
2144 // Handles the uncommon cases of monitor unlocking in compiled code
2145 JRT_LEAF(void, SharedRuntime::complete_monitor_unlocking_C(oopDesc* obj, BasicLock* lock, JavaThread* current))
2146   SharedRuntime::monitor_exit_helper(obj, lock, current);
2147 JRT_END
2148 
2149 #ifndef PRODUCT
2150 
2151 void SharedRuntime::print_statistics() {
2152   ttyLocker ttyl;
2153   if (xtty != NULL)  xtty->head("statistics type='SharedRuntime'");
2154 
2155   SharedRuntime::print_ic_miss_histogram();
2156 
2157   // Dump the JRT_ENTRY counters
2158   if (_new_instance_ctr) tty->print_cr("%5d new instance requires GC", _new_instance_ctr);
2159   if (_new_array_ctr) tty->print_cr("%5d new array requires GC", _new_array_ctr);
2160   if (_multi2_ctr) tty->print_cr("%5d multianewarray 2 dim", _multi2_ctr);
2161   if (_multi3_ctr) tty->print_cr("%5d multianewarray 3 dim", _multi3_ctr);
2162   if (_multi4_ctr) tty->print_cr("%5d multianewarray 4 dim", _multi4_ctr);
2163   if (_multi5_ctr) tty->print_cr("%5d multianewarray 5 dim", _multi5_ctr);
2164 
2165   tty->print_cr("%5d inline cache miss in compiled", _ic_miss_ctr);
2166   tty->print_cr("%5d wrong method", _wrong_method_ctr);
2167   tty->print_cr("%5d unresolved static call site", _resolve_static_ctr);
2168   tty->print_cr("%5d unresolved virtual call site", _resolve_virtual_ctr);
2169   tty->print_cr("%5d unresolved opt virtual call site", _resolve_opt_virtual_ctr);
2170 
2171   if (_mon_enter_stub_ctr) tty->print_cr("%5d monitor enter stub", _mon_enter_stub_ctr);
2172   if (_mon_exit_stub_ctr) tty->print_cr("%5d monitor exit stub", _mon_exit_stub_ctr);
2173   if (_mon_enter_ctr) tty->print_cr("%5d monitor enter slow", _mon_enter_ctr);
2174   if (_mon_exit_ctr) tty->print_cr("%5d monitor exit slow", _mon_exit_ctr);
2175   if (_partial_subtype_ctr) tty->print_cr("%5d slow partial subtype", _partial_subtype_ctr);
2176   if (_jbyte_array_copy_ctr) tty->print_cr("%5d byte array copies", _jbyte_array_copy_ctr);
2177   if (_jshort_array_copy_ctr) tty->print_cr("%5d short array copies", _jshort_array_copy_ctr);
2178   if (_jint_array_copy_ctr) tty->print_cr("%5d int array copies", _jint_array_copy_ctr);
2179   if (_jlong_array_copy_ctr) tty->print_cr("%5d long array copies", _jlong_array_copy_ctr);
2180   if (_oop_array_copy_ctr) tty->print_cr("%5d oop array copies", _oop_array_copy_ctr);
2181   if (_checkcast_array_copy_ctr) tty->print_cr("%5d checkcast array copies", _checkcast_array_copy_ctr);
2182   if (_unsafe_array_copy_ctr) tty->print_cr("%5d unsafe array copies", _unsafe_array_copy_ctr);
2183   if (_generic_array_copy_ctr) tty->print_cr("%5d generic array copies", _generic_array_copy_ctr);
2184   if (_slow_array_copy_ctr) tty->print_cr("%5d slow array copies", _slow_array_copy_ctr);
2185   if (_find_handler_ctr) tty->print_cr("%5d find exception handler", _find_handler_ctr);
2186   if (_rethrow_ctr) tty->print_cr("%5d rethrow handler", _rethrow_ctr);
2187 
2188   AdapterHandlerLibrary::print_statistics();
2189 
2190   if (xtty != NULL)  xtty->tail("statistics");
2191 }
2192 
2193 inline double percent(int x, int y) {
2194   return 100.0 * x / MAX2(y, 1);
2195 }
2196 
2197 inline double percent(int64_t x, int64_t y) {
2198   return 100.0 * x / MAX2(y, (int64_t)1);
2199 }
2200 
2201 class MethodArityHistogram {
2202  public:
2203   enum { MAX_ARITY = 256 };
2204  private:
2205   static uint64_t _arity_histogram[MAX_ARITY]; // histogram of #args
2206   static uint64_t _size_histogram[MAX_ARITY];  // histogram of arg size in words
2207   static uint64_t _total_compiled_calls;
2208   static uint64_t _max_compiled_calls_per_method;
2209   static int _max_arity;                       // max. arity seen
2210   static int _max_size;                        // max. arg size seen
2211 
2212   static void add_method_to_histogram(nmethod* nm) {
2213     Method* method = (nm == NULL) ? NULL : nm->method();
2214     if ((method != NULL) && nm->is_alive()) {
2215       ArgumentCount args(method->signature());
2216       int arity   = args.size() + (method->is_static() ? 0 : 1);
2217       int argsize = method->size_of_parameters();
2218       arity   = MIN2(arity, MAX_ARITY-1);
2219       argsize = MIN2(argsize, MAX_ARITY-1);
2220       uint64_t count = (uint64_t)method->compiled_invocation_count();
2221       _max_compiled_calls_per_method = count > _max_compiled_calls_per_method ? count : _max_compiled_calls_per_method;
2222       _total_compiled_calls    += count;
2223       _arity_histogram[arity]  += count;
2224       _size_histogram[argsize] += count;
2225       _max_arity = MAX2(_max_arity, arity);
2226       _max_size  = MAX2(_max_size, argsize);
2227     }
2228   }
2229 
2230   void print_histogram_helper(int n, uint64_t* histo, const char* name) {
2231     const int N = MIN2(9, n);
2232     double sum = 0;
2233     double weighted_sum = 0;
2234     for (int i = 0; i <= n; i++) { sum += histo[i]; weighted_sum += i*histo[i]; }
2235     if (sum >= 1.0) { // prevent divide by zero or divide overflow
2236       double rest = sum;
2237       double percent = sum / 100;
2238       for (int i = 0; i <= N; i++) {
2239         rest -= histo[i];
2240         tty->print_cr("%4d: " UINT64_FORMAT_W(12) " (%5.1f%%)", i, histo[i], histo[i] / percent);
2241       }
2242       tty->print_cr("rest: " INT64_FORMAT_W(12) " (%5.1f%%)", (int64_t)rest, rest / percent);
2243       tty->print_cr("(avg. %s = %3.1f, max = %d)", name, weighted_sum / sum, n);
2244       tty->print_cr("(total # of compiled calls = " INT64_FORMAT_W(14) ")", _total_compiled_calls);
2245       tty->print_cr("(max # of compiled calls   = " INT64_FORMAT_W(14) ")", _max_compiled_calls_per_method);
2246     } else {
2247       tty->print_cr("Histogram generation failed for %s. n = %d, sum = %7.5f", name, n, sum);
2248     }
2249   }
2250 
2251   void print_histogram() {
2252     tty->print_cr("\nHistogram of call arity (incl. rcvr, calls to compiled methods only):");
2253     print_histogram_helper(_max_arity, _arity_histogram, "arity");
2254     tty->print_cr("\nHistogram of parameter block size (in words, incl. rcvr):");
2255     print_histogram_helper(_max_size, _size_histogram, "size");
2256     tty->cr();
2257   }
2258 
2259  public:
2260   MethodArityHistogram() {
2261     // Take the Compile_lock to protect against changes in the CodeBlob structures
2262     MutexLocker mu1(Compile_lock, Mutex::_safepoint_check_flag);
2263     // Take the CodeCache_lock to protect against changes in the CodeHeap structure
2264     MutexLocker mu2(CodeCache_lock, Mutex::_no_safepoint_check_flag);
2265     _max_arity = _max_size = 0;
2266     _total_compiled_calls = 0;
2267     _max_compiled_calls_per_method = 0;
2268     for (int i = 0; i < MAX_ARITY; i++) _arity_histogram[i] = _size_histogram[i] = 0;
2269     CodeCache::nmethods_do(add_method_to_histogram);
2270     print_histogram();
2271   }
2272 };
2273 
2274 uint64_t MethodArityHistogram::_arity_histogram[MethodArityHistogram::MAX_ARITY];
2275 uint64_t MethodArityHistogram::_size_histogram[MethodArityHistogram::MAX_ARITY];
2276 uint64_t MethodArityHistogram::_total_compiled_calls;
2277 uint64_t MethodArityHistogram::_max_compiled_calls_per_method;
2278 int MethodArityHistogram::_max_arity;
2279 int MethodArityHistogram::_max_size;
2280 
2281 void SharedRuntime::print_call_statistics(uint64_t comp_total) {
2282   tty->print_cr("Calls from compiled code:");
2283   int64_t total  = _nof_normal_calls + _nof_interface_calls + _nof_static_calls;
2284   int64_t mono_c = _nof_normal_calls - _nof_optimized_calls - _nof_megamorphic_calls;
2285   int64_t mono_i = _nof_interface_calls - _nof_optimized_interface_calls - _nof_megamorphic_interface_calls;
2286   tty->print_cr("\t" INT64_FORMAT_W(12) " (100%%)  total non-inlined   ", total);
2287   tty->print_cr("\t" INT64_FORMAT_W(12) " (%4.1f%%) |- virtual calls       ", _nof_normal_calls, percent(_nof_normal_calls, total));
2288   tty->print_cr("\t" INT64_FORMAT_W(12) " (%4.0f%%) |  |- inlined          ", _nof_inlined_calls, percent(_nof_inlined_calls, _nof_normal_calls));
2289   tty->print_cr("\t" INT64_FORMAT_W(12) " (%4.0f%%) |  |- optimized        ", _nof_optimized_calls, percent(_nof_optimized_calls, _nof_normal_calls));
2290   tty->print_cr("\t" INT64_FORMAT_W(12) " (%4.0f%%) |  |- monomorphic      ", mono_c, percent(mono_c, _nof_normal_calls));
2291   tty->print_cr("\t" INT64_FORMAT_W(12) " (%4.0f%%) |  |- megamorphic      ", _nof_megamorphic_calls, percent(_nof_megamorphic_calls, _nof_normal_calls));
2292   tty->print_cr("\t" INT64_FORMAT_W(12) " (%4.1f%%) |- interface calls     ", _nof_interface_calls, percent(_nof_interface_calls, total));
2293   tty->print_cr("\t" INT64_FORMAT_W(12) " (%4.0f%%) |  |- inlined          ", _nof_inlined_interface_calls, percent(_nof_inlined_interface_calls, _nof_interface_calls));
2294   tty->print_cr("\t" INT64_FORMAT_W(12) " (%4.0f%%) |  |- optimized        ", _nof_optimized_interface_calls, percent(_nof_optimized_interface_calls, _nof_interface_calls));
2295   tty->print_cr("\t" INT64_FORMAT_W(12) " (%4.0f%%) |  |- monomorphic      ", mono_i, percent(mono_i, _nof_interface_calls));
2296   tty->print_cr("\t" INT64_FORMAT_W(12) " (%4.0f%%) |  |- megamorphic      ", _nof_megamorphic_interface_calls, percent(_nof_megamorphic_interface_calls, _nof_interface_calls));
2297   tty->print_cr("\t" INT64_FORMAT_W(12) " (%4.1f%%) |- static/special calls", _nof_static_calls, percent(_nof_static_calls, total));
2298   tty->print_cr("\t" INT64_FORMAT_W(12) " (%4.0f%%) |  |- inlined          ", _nof_inlined_static_calls, percent(_nof_inlined_static_calls, _nof_static_calls));
2299   tty->cr();
2300   tty->print_cr("Note 1: counter updates are not MT-safe.");
2301   tty->print_cr("Note 2: %% in major categories are relative to total non-inlined calls;");
2302   tty->print_cr("        %% in nested categories are relative to their category");
2303   tty->print_cr("        (and thus add up to more than 100%% with inlining)");
2304   tty->cr();
2305 
2306   MethodArityHistogram h;
2307 }
2308 #endif
2309 
2310 
2311 // A simple wrapper class around the calling convention information
2312 // that allows sharing of adapters for the same calling convention.
2313 class AdapterFingerPrint : public CHeapObj<mtCode> {
2314  private:
2315   enum {
2316     _basic_type_bits = 4,
2317     _basic_type_mask = right_n_bits(_basic_type_bits),
2318     _basic_types_per_int = BitsPerInt / _basic_type_bits,
2319     _compact_int_count = 3
2320   };
2321   // TO DO:  Consider integrating this with a more global scheme for compressing signatures.
2322   // For now, 4 bits per components (plus T_VOID gaps after double/long) is not excessive.
2323 
2324   union {
2325     int  _compact[_compact_int_count];
2326     int* _fingerprint;
2327   } _value;
2328   int _length; // A negative length indicates the fingerprint is in the compact form,
2329                // Otherwise _value._fingerprint is the array.
2330 
2331   // Remap BasicTypes that are handled equivalently by the adapters.
2332   // These are correct for the current system but someday it might be
2333   // necessary to make this mapping platform dependent.
2334   static int adapter_encoding(BasicType in) {
2335     switch (in) {
2336       case T_BOOLEAN:
2337       case T_BYTE:
2338       case T_SHORT:
2339       case T_CHAR:
2340         // There are all promoted to T_INT in the calling convention
2341         return T_INT;
2342 
2343       case T_OBJECT:
2344       case T_ARRAY:
2345         // In other words, we assume that any register good enough for
2346         // an int or long is good enough for a managed pointer.
2347 #ifdef _LP64
2348         return T_LONG;
2349 #else
2350         return T_INT;
2351 #endif
2352 
2353       case T_INT:
2354       case T_LONG:
2355       case T_FLOAT:
2356       case T_DOUBLE:
2357       case T_VOID:
2358         return in;
2359 
2360       default:
2361         ShouldNotReachHere();
2362         return T_CONFLICT;
2363     }
2364   }
2365 
2366  public:
2367   AdapterFingerPrint(int total_args_passed, BasicType* sig_bt) {
2368     // The fingerprint is based on the BasicType signature encoded
2369     // into an array of ints with eight entries per int.

2370     int* ptr;
2371     int len = (total_args_passed + (_basic_types_per_int-1)) / _basic_types_per_int;
2372     if (len <= _compact_int_count) {
2373       assert(_compact_int_count == 3, "else change next line");
2374       _value._compact[0] = _value._compact[1] = _value._compact[2] = 0;
2375       // Storing the signature encoded as signed chars hits about 98%
2376       // of the time.
2377       _length = -len;
2378       ptr = _value._compact;
2379     } else {
2380       _length = len;
2381       _value._fingerprint = NEW_C_HEAP_ARRAY(int, _length, mtCode);
2382       ptr = _value._fingerprint;
2383     }
2384 
2385     // Now pack the BasicTypes with 8 per int
2386     int sig_index = 0;


2387     for (int index = 0; index < len; index++) {
2388       int value = 0;
2389       for (int byte = 0; sig_index < total_args_passed && byte < _basic_types_per_int; byte++) {
2390         int bt = adapter_encoding(sig_bt[sig_index++]);
2391         assert((bt & _basic_type_mask) == bt, "must fit in 4 bits");
2392         value = (value << _basic_type_bits) | bt;























2393       }
2394       ptr[index] = value;
2395     }

2396   }
2397 
2398   ~AdapterFingerPrint() {
2399     if (_length > 0) {
2400       FREE_C_HEAP_ARRAY(int, _value._fingerprint);
2401     }
2402   }
2403 
2404   int value(int index) {
2405     if (_length < 0) {
2406       return _value._compact[index];
2407     }
2408     return _value._fingerprint[index];
2409   }
2410   int length() {
2411     if (_length < 0) return -_length;
2412     return _length;
2413   }
2414 
2415   bool is_compact() {
2416     return _length <= 0;
2417   }
2418 
2419   unsigned int compute_hash() {
2420     int hash = 0;
2421     for (int i = 0; i < length(); i++) {
2422       int v = value(i);
2423       hash = (hash << 8) ^ v ^ (hash >> 5);
2424     }
2425     return (unsigned int)hash;
2426   }
2427 
2428   const char* as_string() {
2429     stringStream st;
2430     st.print("0x");
2431     for (int i = 0; i < length(); i++) {
2432       st.print("%x", value(i));
2433     }
2434     return st.as_string();
2435   }
2436 
2437 #ifndef PRODUCT
2438   // Reconstitutes the basic type arguments from the fingerprint,
2439   // producing strings like LIJDF
2440   const char* as_basic_args_string() {
2441     stringStream st;
2442     bool long_prev = false;
2443     for (int i = 0; i < length(); i++) {
2444       unsigned val = (unsigned)value(i);
2445       // args are packed so that first/lower arguments are in the highest
2446       // bits of each int value, so iterate from highest to the lowest
2447       for (int j = 32 - _basic_type_bits; j >= 0; j -= _basic_type_bits) {
2448         unsigned v = (val >> j) & _basic_type_mask;
2449         if (v == 0) {
2450           assert(i == length() - 1, "Only expect zeroes in the last word");
2451           continue;
2452         }
2453         if (long_prev) {
2454           long_prev = false;
2455           if (v == T_VOID) {
2456             st.print("J");
2457           } else {
2458             st.print("L");
2459           }
2460         }
2461         switch (v) {
2462           case T_INT:    st.print("I");    break;
2463           case T_LONG:   long_prev = true; break;
2464           case T_FLOAT:  st.print("F");    break;
2465           case T_DOUBLE: st.print("D");    break;
2466           case T_VOID:   break;
2467           default: ShouldNotReachHere();
2468         }
2469       }
2470     }
2471     if (long_prev) {
2472       st.print("L");
2473     }
2474     return st.as_string();
2475   }
2476 #endif // !product
2477 
2478   bool equals(AdapterFingerPrint* other) {
2479     if (other->_length != _length) {
2480       return false;
2481     }
2482     if (_length < 0) {
2483       assert(_compact_int_count == 3, "else change next line");
2484       return _value._compact[0] == other->_value._compact[0] &&
2485              _value._compact[1] == other->_value._compact[1] &&
2486              _value._compact[2] == other->_value._compact[2];
2487     } else {
2488       for (int i = 0; i < _length; i++) {
2489         if (_value._fingerprint[i] != other->_value._fingerprint[i]) {
2490           return false;
2491         }
2492       }
2493     }
2494     return true;
2495   }
2496 };
2497 
2498 
2499 // A hashtable mapping from AdapterFingerPrints to AdapterHandlerEntries
2500 class AdapterHandlerTable : public BasicHashtable<mtCode> {
2501   friend class AdapterHandlerTableIterator;
2502 
2503  private:
2504 
2505 #ifndef PRODUCT
2506   static int _lookups; // number of calls to lookup
2507   static int _buckets; // number of buckets checked
2508   static int _equals;  // number of buckets checked with matching hash
2509   static int _hits;    // number of successful lookups
2510   static int _compact; // number of equals calls with compact signature
2511 #endif
2512 
2513   AdapterHandlerEntry* bucket(int i) {
2514     return (AdapterHandlerEntry*)BasicHashtable<mtCode>::bucket(i);
2515   }
2516 
2517  public:
2518   AdapterHandlerTable()
2519     : BasicHashtable<mtCode>(293, (sizeof(AdapterHandlerEntry))) { }
2520 
2521   // Create a new entry suitable for insertion in the table
2522   AdapterHandlerEntry* new_entry(AdapterFingerPrint* fingerprint, address i2c_entry, address c2i_entry, address c2i_unverified_entry, address c2i_no_clinit_check_entry) {


2523     AdapterHandlerEntry* entry = (AdapterHandlerEntry*)BasicHashtable<mtCode>::new_entry(fingerprint->compute_hash());
2524     entry->init(fingerprint, i2c_entry, c2i_entry, c2i_unverified_entry, c2i_no_clinit_check_entry);

2525     return entry;
2526   }
2527 
2528   // Insert an entry into the table
2529   void add(AdapterHandlerEntry* entry) {
2530     int index = hash_to_index(entry->hash());
2531     add_entry(index, entry);
2532   }
2533 
2534   void free_entry(AdapterHandlerEntry* entry) {
2535     entry->deallocate();
2536     BasicHashtable<mtCode>::free_entry(entry);
2537   }
2538 
2539   // Find a entry with the same fingerprint if it exists
2540   AdapterHandlerEntry* lookup(int total_args_passed, BasicType* sig_bt) {
2541     NOT_PRODUCT(_lookups++);
2542     AdapterFingerPrint fp(total_args_passed, sig_bt);
2543     unsigned int hash = fp.compute_hash();
2544     int index = hash_to_index(hash);
2545     for (AdapterHandlerEntry* e = bucket(index); e != NULL; e = e->next()) {
2546       NOT_PRODUCT(_buckets++);
2547       if (e->hash() == hash) {
2548         NOT_PRODUCT(_equals++);
2549         if (fp.equals(e->fingerprint())) {
2550 #ifndef PRODUCT
2551           if (fp.is_compact()) _compact++;
2552           _hits++;
2553 #endif
2554           return e;
2555         }
2556       }
2557     }
2558     return NULL;
2559   }
2560 
2561 #ifndef PRODUCT
2562   void print_statistics() {
2563     ResourceMark rm;
2564     int longest = 0;
2565     int empty = 0;
2566     int total = 0;
2567     int nonempty = 0;
2568     for (int index = 0; index < table_size(); index++) {
2569       int count = 0;
2570       for (AdapterHandlerEntry* e = bucket(index); e != NULL; e = e->next()) {
2571         count++;
2572       }
2573       if (count != 0) nonempty++;
2574       if (count == 0) empty++;
2575       if (count > longest) longest = count;
2576       total += count;
2577     }
2578     tty->print_cr("AdapterHandlerTable: empty %d longest %d total %d average %f",
2579                   empty, longest, total, total / (double)nonempty);
2580     tty->print_cr("AdapterHandlerTable: lookups %d buckets %d equals %d hits %d compact %d",
2581                   _lookups, _buckets, _equals, _hits, _compact);
2582   }
2583 #endif
2584 };
2585 
2586 
2587 #ifndef PRODUCT
2588 
2589 int AdapterHandlerTable::_lookups;
2590 int AdapterHandlerTable::_buckets;
2591 int AdapterHandlerTable::_equals;
2592 int AdapterHandlerTable::_hits;
2593 int AdapterHandlerTable::_compact;
2594 
2595 #endif
2596 
2597 class AdapterHandlerTableIterator : public StackObj {
2598  private:
2599   AdapterHandlerTable* _table;
2600   int _index;
2601   AdapterHandlerEntry* _current;
2602 
2603   void scan() {
2604     while (_index < _table->table_size()) {
2605       AdapterHandlerEntry* a = _table->bucket(_index);
2606       _index++;
2607       if (a != NULL) {
2608         _current = a;
2609         return;
2610       }
2611     }
2612   }
2613 
2614  public:
2615   AdapterHandlerTableIterator(AdapterHandlerTable* table): _table(table), _index(0), _current(NULL) {
2616     scan();
2617   }
2618   bool has_next() {
2619     return _current != NULL;
2620   }
2621   AdapterHandlerEntry* next() {
2622     if (_current != NULL) {
2623       AdapterHandlerEntry* result = _current;
2624       _current = _current->next();
2625       if (_current == NULL) scan();
2626       return result;
2627     } else {
2628       return NULL;
2629     }
2630   }
2631 };
2632 
2633 
2634 // ---------------------------------------------------------------------------
2635 // Implementation of AdapterHandlerLibrary
2636 AdapterHandlerTable* AdapterHandlerLibrary::_adapters = NULL;
2637 AdapterHandlerEntry* AdapterHandlerLibrary::_abstract_method_handler = NULL;
2638 AdapterHandlerEntry* AdapterHandlerLibrary::_no_arg_handler = NULL;
2639 AdapterHandlerEntry* AdapterHandlerLibrary::_int_arg_handler = NULL;
2640 AdapterHandlerEntry* AdapterHandlerLibrary::_obj_arg_handler = NULL;
2641 AdapterHandlerEntry* AdapterHandlerLibrary::_obj_int_arg_handler = NULL;
2642 AdapterHandlerEntry* AdapterHandlerLibrary::_obj_obj_arg_handler = NULL;
2643 const int AdapterHandlerLibrary_size = 16*K;
2644 BufferBlob* AdapterHandlerLibrary::_buffer = NULL;
2645 
2646 BufferBlob* AdapterHandlerLibrary::buffer_blob() {
2647   return _buffer;
2648 }
2649 
2650 extern "C" void unexpected_adapter_call() {
2651   ShouldNotCallThis();
2652 }
2653 
2654 static void post_adapter_creation(const AdapterBlob* new_adapter, const AdapterHandlerEntry* entry) {
2655   char blob_id[256];
2656   jio_snprintf(blob_id,
2657                 sizeof(blob_id),
2658                 "%s(%s)",
2659                 new_adapter->name(),
2660                 entry->fingerprint()->as_string());
2661   Forte::register_stub(blob_id, new_adapter->content_begin(), new_adapter->content_end());
2662 
2663   if (JvmtiExport::should_post_dynamic_code_generated()) {
2664     JvmtiExport::post_dynamic_code_generated(blob_id, new_adapter->content_begin(), new_adapter->content_end());
2665   }
2666 }
2667 
2668 void AdapterHandlerLibrary::initialize() {
2669   ResourceMark rm;
2670   AdapterBlob* no_arg_blob = NULL;
2671   AdapterBlob* int_arg_blob = NULL;
2672   AdapterBlob* obj_arg_blob = NULL;
2673   AdapterBlob* obj_int_arg_blob = NULL;
2674   AdapterBlob* obj_obj_arg_blob = NULL;
2675   {
2676     MutexLocker mu(AdapterHandlerLibrary_lock);
2677     assert(_adapters == NULL, "Initializing more than once");
2678 
2679     _adapters = new AdapterHandlerTable();
2680 
2681     // Create a special handler for abstract methods.  Abstract methods
2682     // are never compiled so an i2c entry is somewhat meaningless, but
2683     // throw AbstractMethodError just in case.
2684     // Pass wrong_method_abstract for the c2i transitions to return
2685     // AbstractMethodError for invalid invocations.
2686     address wrong_method_abstract = SharedRuntime::get_handle_wrong_method_abstract_stub();
2687     _abstract_method_handler = AdapterHandlerLibrary::new_entry(new AdapterFingerPrint(0, NULL),
2688                                                                 StubRoutines::throw_AbstractMethodError_entry(),

2689                                                                 wrong_method_abstract, wrong_method_abstract);
2690 
2691     _buffer = BufferBlob::create("adapters", AdapterHandlerLibrary_size);
2692 
2693     _no_arg_handler = create_adapter(no_arg_blob, 0, NULL, true);


2694 
2695     BasicType obj_args[] = { T_OBJECT };
2696     _obj_arg_handler = create_adapter(obj_arg_blob, 1, obj_args, true);


2697 
2698     BasicType int_args[] = { T_INT };
2699     _int_arg_handler = create_adapter(int_arg_blob, 1, int_args, true);


2700 
2701     BasicType obj_int_args[] = { T_OBJECT, T_INT };
2702     _obj_int_arg_handler = create_adapter(obj_int_arg_blob, 2, obj_int_args, true);



2703 
2704     BasicType obj_obj_args[] = { T_OBJECT, T_OBJECT };
2705     _obj_obj_arg_handler = create_adapter(obj_obj_arg_blob, 2, obj_obj_args, true);



2706 
2707     assert(no_arg_blob != NULL &&
2708           obj_arg_blob != NULL &&
2709           int_arg_blob != NULL &&
2710           obj_int_arg_blob != NULL &&
2711           obj_obj_arg_blob != NULL, "Initial adapters must be properly created");
2712   }

2713 
2714   // Outside of the lock
2715   post_adapter_creation(no_arg_blob, _no_arg_handler);
2716   post_adapter_creation(obj_arg_blob, _obj_arg_handler);
2717   post_adapter_creation(int_arg_blob, _int_arg_handler);
2718   post_adapter_creation(obj_int_arg_blob, _obj_int_arg_handler);
2719   post_adapter_creation(obj_obj_arg_blob, _obj_obj_arg_handler);
2720 }
2721 
2722 AdapterHandlerEntry* AdapterHandlerLibrary::new_entry(AdapterFingerPrint* fingerprint,
2723                                                       address i2c_entry,
2724                                                       address c2i_entry,


2725                                                       address c2i_unverified_entry,

2726                                                       address c2i_no_clinit_check_entry) {
2727   return _adapters->new_entry(fingerprint, i2c_entry, c2i_entry, c2i_unverified_entry, c2i_no_clinit_check_entry);

2728 }
2729 
2730 AdapterHandlerEntry* AdapterHandlerLibrary::get_simple_adapter(const methodHandle& method) {
2731   if (method->is_abstract()) {
2732     return _abstract_method_handler;
2733   }
2734   int total_args_passed = method->size_of_parameters(); // All args on stack
2735   if (total_args_passed == 0) {
2736     return _no_arg_handler;
2737   } else if (total_args_passed == 1) {
2738     if (!method->is_static()) {
2739       return _obj_arg_handler;
2740     }
2741     switch (method->signature()->char_at(1)) {
2742       case JVM_SIGNATURE_CLASS:
2743       case JVM_SIGNATURE_ARRAY:
2744         return _obj_arg_handler;
2745       case JVM_SIGNATURE_INT:
2746       case JVM_SIGNATURE_BOOLEAN:
2747       case JVM_SIGNATURE_CHAR:
2748       case JVM_SIGNATURE_BYTE:
2749       case JVM_SIGNATURE_SHORT:
2750         return _int_arg_handler;
2751     }
2752   } else if (total_args_passed == 2 &&
2753              !method->is_static()) {
2754     switch (method->signature()->char_at(1)) {
2755       case JVM_SIGNATURE_CLASS:
2756       case JVM_SIGNATURE_ARRAY:
2757         return _obj_obj_arg_handler;
2758       case JVM_SIGNATURE_INT:
2759       case JVM_SIGNATURE_BOOLEAN:
2760       case JVM_SIGNATURE_CHAR:
2761       case JVM_SIGNATURE_BYTE:
2762       case JVM_SIGNATURE_SHORT:
2763         return _obj_int_arg_handler;
2764     }
2765   }
2766   return NULL;
2767 }
2768 
2769 class AdapterSignatureIterator : public SignatureIterator {
2770  private:
2771   BasicType stack_sig_bt[16];
2772   BasicType* sig_bt;
2773   int index;




2774 
2775  public:
2776   AdapterSignatureIterator(Symbol* signature,
2777                            fingerprint_t fingerprint,
2778                            bool is_static,
2779                            int total_args_passed) :
2780     SignatureIterator(signature, fingerprint),
2781     index(0)
2782   {
2783     sig_bt = (total_args_passed <= 16) ? stack_sig_bt : NEW_RESOURCE_ARRAY(BasicType, total_args_passed);
2784     if (!is_static) { // Pass in receiver first
2785       sig_bt[index++] = T_OBJECT;
2786     }
2787     do_parameters_on(this);
2788   }















2789 
2790   BasicType* basic_types() {
2791     return sig_bt;








2792   }
2793 
2794 #ifdef ASSERT
2795   int slots() {
2796     return index;










2797   }
2798 #endif
2799 
2800  private:



































2801 
2802   friend class SignatureIterator;  // so do_parameters_on can call do_type
2803   void do_type(BasicType type) {
2804     sig_bt[index++] = type;
2805     if (type == T_LONG || type == T_DOUBLE) {
2806       sig_bt[index++] = T_VOID; // Longs & doubles take 2 Java slots






























2807     }
2808   }
2809 };
2810 
2811 AdapterHandlerEntry* AdapterHandlerLibrary::get_adapter(const methodHandle& method) {
2812   // Use customized signature handler.  Need to lock around updates to
2813   // the AdapterHandlerTable (it is not safe for concurrent readers
2814   // and a single writer: this could be fixed if it becomes a
2815   // problem).
2816   assert(_adapters != NULL, "Uninitialized");
2817 
2818   // Fast-path for trivial adapters
2819   AdapterHandlerEntry* entry = get_simple_adapter(method);
2820   if (entry != NULL) {
2821     return entry;
2822   }
2823 
2824   ResourceMark rm;
2825   AdapterBlob* new_adapter = NULL;
2826 
2827   // Fill in the signature array, for the calling-convention call.
2828   int total_args_passed = method->size_of_parameters(); // All args on stack







2829 
2830   AdapterSignatureIterator si(method->signature(), method->constMethod()->fingerprint(),
2831                               method->is_static(), total_args_passed);
2832   assert(si.slots() == total_args_passed, "");
2833   BasicType* sig_bt = si.basic_types();
2834   {
2835     MutexLocker mu(AdapterHandlerLibrary_lock);
2836 













2837     // Lookup method signature's fingerprint
2838     entry = _adapters->lookup(total_args_passed, sig_bt);
2839 
2840     if (entry != NULL) {
2841 #ifdef ASSERT
2842       if (VerifyAdapterSharing) {
2843         AdapterBlob* comparison_blob = NULL;
2844         AdapterHandlerEntry* comparison_entry = create_adapter(comparison_blob, total_args_passed, sig_bt, false);
2845         assert(comparison_blob == NULL, "no blob should be created when creating an adapter for comparison");
2846         assert(comparison_entry->compare_code(entry), "code must match");
2847         // Release the one just created and return the original
2848         _adapters->free_entry(comparison_entry);
2849       }
2850 #endif
2851       return entry;
2852     }
2853 
2854     entry = create_adapter(new_adapter, total_args_passed, sig_bt, /* allocate_code_blob */ true);
2855   }
2856 
2857   // Outside of the lock
2858   if (new_adapter != NULL) {
2859     post_adapter_creation(new_adapter, entry);
2860   }
2861   return entry;
2862 }
2863 
2864 AdapterHandlerEntry* AdapterHandlerLibrary::create_adapter(AdapterBlob*& new_adapter,
2865                                                            int total_args_passed,
2866                                                            BasicType* sig_bt,
2867                                                            bool allocate_code_blob) {
2868 
2869   // StubRoutines::code2() is initialized after this function can be called. As a result,
2870   // VerifyAdapterCalls and VerifyAdapterSharing can fail if we re-use code that generated
2871   // prior to StubRoutines::code2() being set. Checks refer to checks generated in an I2C
2872   // stub that ensure that an I2C stub is called from an interpreter frame.
2873   bool contains_all_checks = StubRoutines::code2() != NULL;
2874 
2875   VMRegPair stack_regs[16];
2876   VMRegPair* regs = (total_args_passed <= 16) ? stack_regs : NEW_RESOURCE_ARRAY(VMRegPair, total_args_passed);
2877 
2878   // Get a description of the compiled java calling convention and the largest used (VMReg) stack slot usage
2879   int comp_args_on_stack = SharedRuntime::java_calling_convention(sig_bt, regs, total_args_passed);
2880   BufferBlob* buf = buffer_blob(); // the temporary code buffer in CodeCache
2881   CodeBuffer buffer(buf);
2882   short buffer_locs[20];
2883   buffer.insts()->initialize_shared_locs((relocInfo*)buffer_locs,
2884                                           sizeof(buffer_locs)/sizeof(relocInfo));
2885 
2886   // Make a C heap allocated version of the fingerprint to store in the adapter
2887   AdapterFingerPrint* fingerprint = new AdapterFingerPrint(total_args_passed, sig_bt);
2888   MacroAssembler _masm(&buffer);
2889   AdapterHandlerEntry* entry = SharedRuntime::generate_i2c2i_adapters(&_masm,
2890                                                 total_args_passed,
2891                                                 comp_args_on_stack,
2892                                                 sig_bt,
2893                                                 regs,
2894                                                 fingerprint);












2895 
2896 #ifdef ASSERT
2897   if (VerifyAdapterSharing) {
2898     entry->save_code(buf->code_begin(), buffer.insts_size());
2899     if (!allocate_code_blob) {
2900       return entry;
2901     }
2902   }
2903 #endif
2904 
2905   new_adapter = AdapterBlob::create(&buffer);
2906   NOT_PRODUCT(int insts_size = buffer.insts_size());
2907   if (new_adapter == NULL) {
2908     // CodeCache is full, disable compilation
2909     // Ought to log this but compile log is only per compile thread
2910     // and we're some non descript Java thread.
2911     return NULL;
2912   }
2913   entry->relocate(new_adapter->content_begin());
2914 #ifndef PRODUCT
2915   // debugging suppport
2916   if (PrintAdapterHandlers || PrintStubCode) {
2917     ttyLocker ttyl;
2918     entry->print_adapter_on(tty);
2919     tty->print_cr("i2c argument handler #%d for: %s %s (%d bytes generated)",
2920                   _adapters->number_of_entries(), fingerprint->as_basic_args_string(),
2921                   fingerprint->as_string(), insts_size);
2922     tty->print_cr("c2i argument handler starts at %p", entry->get_c2i_entry());
2923     if (Verbose || PrintStubCode) {
2924       address first_pc = entry->base_address();
2925       if (first_pc != NULL) {
2926         Disassembler::decode(first_pc, first_pc + insts_size, tty
2927                              NOT_PRODUCT(COMMA &new_adapter->asm_remarks()));
2928         tty->cr();
2929       }
2930     }
2931   }
2932 #endif
2933 
2934   // Add the entry only if the entry contains all required checks (see sharedRuntime_xxx.cpp)
2935   // The checks are inserted only if -XX:+VerifyAdapterCalls is specified.
2936   if (contains_all_checks || !VerifyAdapterCalls) {
2937     _adapters->add(entry);
2938   }
2939   return entry;
2940 }
2941 
2942 address AdapterHandlerEntry::base_address() {
2943   address base = _i2c_entry;
2944   if (base == NULL)  base = _c2i_entry;
2945   assert(base <= _c2i_entry || _c2i_entry == NULL, "");


2946   assert(base <= _c2i_unverified_entry || _c2i_unverified_entry == NULL, "");

2947   assert(base <= _c2i_no_clinit_check_entry || _c2i_no_clinit_check_entry == NULL, "");
2948   return base;
2949 }
2950 
2951 void AdapterHandlerEntry::relocate(address new_base) {
2952   address old_base = base_address();
2953   assert(old_base != NULL, "");
2954   ptrdiff_t delta = new_base - old_base;
2955   if (_i2c_entry != NULL)
2956     _i2c_entry += delta;
2957   if (_c2i_entry != NULL)
2958     _c2i_entry += delta;




2959   if (_c2i_unverified_entry != NULL)
2960     _c2i_unverified_entry += delta;


2961   if (_c2i_no_clinit_check_entry != NULL)
2962     _c2i_no_clinit_check_entry += delta;
2963   assert(base_address() == new_base, "");
2964 }
2965 
2966 
2967 void AdapterHandlerEntry::deallocate() {
2968   delete _fingerprint;



2969 #ifdef ASSERT
2970   FREE_C_HEAP_ARRAY(unsigned char, _saved_code);
2971 #endif
2972 }
2973 
2974 
2975 #ifdef ASSERT
2976 // Capture the code before relocation so that it can be compared
2977 // against other versions.  If the code is captured after relocation
2978 // then relative instructions won't be equivalent.
2979 void AdapterHandlerEntry::save_code(unsigned char* buffer, int length) {
2980   _saved_code = NEW_C_HEAP_ARRAY(unsigned char, length, mtCode);
2981   _saved_code_length = length;
2982   memcpy(_saved_code, buffer, length);
2983 }
2984 
2985 
2986 bool AdapterHandlerEntry::compare_code(AdapterHandlerEntry* other) {
2987   assert(_saved_code != NULL && other->_saved_code != NULL, "code not saved");
2988 
2989   if (other->_saved_code_length != _saved_code_length) {
2990     return false;
2991   }
2992 
2993   return memcmp(other->_saved_code, _saved_code, _saved_code_length) == 0;
2994 }
2995 #endif
2996 
2997 
2998 /**
2999  * Create a native wrapper for this native method.  The wrapper converts the
3000  * Java-compiled calling convention to the native convention, handles
3001  * arguments, and transitions to native.  On return from the native we transition
3002  * back to java blocking if a safepoint is in progress.
3003  */
3004 void AdapterHandlerLibrary::create_native_wrapper(const methodHandle& method) {
3005   ResourceMark rm;
3006   nmethod* nm = NULL;
3007   address critical_entry = NULL;
3008 
3009   assert(method->is_native(), "must be native");
3010   assert(method->is_method_handle_intrinsic() ||
3011          method->has_native_function(), "must have something valid to call!");
3012 
3013   if (CriticalJNINatives && !method->is_method_handle_intrinsic()) {
3014     // We perform the I/O with transition to native before acquiring AdapterHandlerLibrary_lock.
3015     critical_entry = NativeLookup::lookup_critical_entry(method);
3016   }
3017 
3018   {
3019     // Perform the work while holding the lock, but perform any printing outside the lock
3020     MutexLocker mu(AdapterHandlerLibrary_lock);
3021     // See if somebody beat us to it
3022     if (method->code() != NULL) {
3023       return;
3024     }
3025 
3026     const int compile_id = CompileBroker::assign_compile_id(method, CompileBroker::standard_entry_bci);
3027     assert(compile_id > 0, "Must generate native wrapper");
3028 
3029 
3030     ResourceMark rm;
3031     BufferBlob*  buf = buffer_blob(); // the temporary code buffer in CodeCache
3032     if (buf != NULL) {
3033       CodeBuffer buffer(buf);
3034       struct { double data[20]; } locs_buf;
3035       buffer.insts()->initialize_shared_locs((relocInfo*)&locs_buf, sizeof(locs_buf) / sizeof(relocInfo));
3036 #if defined(AARCH64)
3037       // On AArch64 with ZGC and nmethod entry barriers, we need all oops to be
3038       // in the constant pool to ensure ordering between the barrier and oops
3039       // accesses. For native_wrappers we need a constant.
3040       buffer.initialize_consts_size(8);
3041 #endif
3042       MacroAssembler _masm(&buffer);
3043 
3044       // Fill in the signature array, for the calling-convention call.
3045       const int total_args_passed = method->size_of_parameters();
3046 

3047       VMRegPair stack_regs[16];

3048       VMRegPair* regs = (total_args_passed <= 16) ? stack_regs : NEW_RESOURCE_ARRAY(VMRegPair, total_args_passed);
3049 
3050       AdapterSignatureIterator si(method->signature(), method->constMethod()->fingerprint(),
3051                               method->is_static(), total_args_passed);
3052       BasicType* sig_bt = si.basic_types();
3053       assert(si.slots() == total_args_passed, "");
3054       BasicType ret_type = si.return_type();








3055 
3056       // Now get the compiled-Java arguments layout.
3057       int comp_args_on_stack = SharedRuntime::java_calling_convention(sig_bt, regs, total_args_passed);
3058 
3059       // Generate the compiled-to-native wrapper code
3060       nm = SharedRuntime::generate_native_wrapper(&_masm, method, compile_id, sig_bt, regs, ret_type, critical_entry);
3061 
3062       if (nm != NULL) {
3063         {
3064           MutexLocker pl(CompiledMethod_lock, Mutex::_no_safepoint_check_flag);
3065           if (nm->make_in_use()) {
3066             method->set_code(method, nm);
3067           }
3068         }
3069 
3070         DirectiveSet* directive = DirectivesStack::getDefaultDirective(CompileBroker::compiler(CompLevel_simple));
3071         if (directive->PrintAssemblyOption) {
3072           nm->print_code();
3073         }
3074         DirectivesStack::release(directive);
3075       }
3076     }
3077   } // Unlock AdapterHandlerLibrary_lock
3078 
3079 
3080   // Install the generated code.
3081   if (nm != NULL) {
3082     const char *msg = method->is_static() ? "(static)" : "";
3083     CompileTask::print_ul(nm, msg);
3084     if (PrintCompilation) {
3085       ttyLocker ttyl;
3086       CompileTask::print(tty, nm, msg);
3087     }
3088     nm->post_compiled_method_load_event();
3089   }
3090 }
3091 
3092 // -------------------------------------------------------------------------
3093 // Java-Java calling convention
3094 // (what you use when Java calls Java)
3095 
3096 //------------------------------name_for_receiver----------------------------------
3097 // For a given signature, return the VMReg for parameter 0.
3098 VMReg SharedRuntime::name_for_receiver() {
3099   VMRegPair regs;
3100   BasicType sig_bt = T_OBJECT;
3101   (void) java_calling_convention(&sig_bt, &regs, 1);
3102   // Return argument 0 register.  In the LP64 build pointers
3103   // take 2 registers, but the VM wants only the 'main' name.
3104   return regs.first();
3105 }
3106 
3107 VMRegPair *SharedRuntime::find_callee_arguments(Symbol* sig, bool has_receiver, bool has_appendix, int* arg_size) {
3108   // This method is returning a data structure allocating as a
3109   // ResourceObject, so do not put any ResourceMarks in here.
3110 
3111   BasicType *sig_bt = NEW_RESOURCE_ARRAY(BasicType, 256);
3112   VMRegPair *regs = NEW_RESOURCE_ARRAY(VMRegPair, 256);
3113   int cnt = 0;
3114   if (has_receiver) {
3115     sig_bt[cnt++] = T_OBJECT; // Receiver is argument 0; not in signature
3116   }
3117 
3118   for (SignatureStream ss(sig); !ss.at_return_type(); ss.next()) {
3119     BasicType type = ss.type();
3120     sig_bt[cnt++] = type;
3121     if (is_double_word_type(type))
3122       sig_bt[cnt++] = T_VOID;
3123   }
3124 
3125   if (has_appendix) {
3126     sig_bt[cnt++] = T_OBJECT;
3127   }
3128 
3129   assert(cnt < 256, "grow table size");
3130 
3131   int comp_args_on_stack;
3132   comp_args_on_stack = java_calling_convention(sig_bt, regs, cnt);
3133 
3134   // the calling convention doesn't count out_preserve_stack_slots so
3135   // we must add that in to get "true" stack offsets.
3136 
3137   if (comp_args_on_stack) {
3138     for (int i = 0; i < cnt; i++) {
3139       VMReg reg1 = regs[i].first();
3140       if (reg1->is_stack()) {
3141         // Yuck
3142         reg1 = reg1->bias(out_preserve_stack_slots());
3143       }
3144       VMReg reg2 = regs[i].second();
3145       if (reg2->is_stack()) {
3146         // Yuck
3147         reg2 = reg2->bias(out_preserve_stack_slots());
3148       }
3149       regs[i].set_pair(reg2, reg1);
3150     }
3151   }
3152 
3153   // results
3154   *arg_size = cnt;
3155   return regs;
3156 }
3157 
3158 // OSR Migration Code
3159 //
3160 // This code is used convert interpreter frames into compiled frames.  It is
3161 // called from very start of a compiled OSR nmethod.  A temp array is
3162 // allocated to hold the interesting bits of the interpreter frame.  All
3163 // active locks are inflated to allow them to move.  The displaced headers and
3164 // active interpreter locals are copied into the temp buffer.  Then we return
3165 // back to the compiled code.  The compiled code then pops the current
3166 // interpreter frame off the stack and pushes a new compiled frame.  Then it
3167 // copies the interpreter locals and displaced headers where it wants.
3168 // Finally it calls back to free the temp buffer.
3169 //
3170 // All of this is done NOT at any Safepoint, nor is any safepoint or GC allowed.
3171 
3172 JRT_LEAF(intptr_t*, SharedRuntime::OSR_migration_begin( JavaThread *current) )
3173   // During OSR migration, we unwind the interpreted frame and replace it with a compiled
3174   // frame. The stack watermark code below ensures that the interpreted frame is processed
3175   // before it gets unwound. This is helpful as the size of the compiled frame could be
3176   // larger than the interpreted frame, which could result in the new frame not being
3177   // processed correctly.
3178   StackWatermarkSet::before_unwind(current);
3179 
3180   //
3181   // This code is dependent on the memory layout of the interpreter local
3182   // array and the monitors. On all of our platforms the layout is identical
3183   // so this code is shared. If some platform lays the their arrays out
3184   // differently then this code could move to platform specific code or
3185   // the code here could be modified to copy items one at a time using
3186   // frame accessor methods and be platform independent.
3187 
3188   frame fr = current->last_frame();
3189   assert(fr.is_interpreted_frame(), "");
3190   assert(fr.interpreter_frame_expression_stack_size()==0, "only handle empty stacks");
3191 
3192   // Figure out how many monitors are active.
3193   int active_monitor_count = 0;
3194   for (BasicObjectLock *kptr = fr.interpreter_frame_monitor_end();
3195        kptr < fr.interpreter_frame_monitor_begin();
3196        kptr = fr.next_monitor_in_interpreter_frame(kptr) ) {
3197     if (kptr->obj() != NULL) active_monitor_count++;
3198   }
3199 
3200   // QQQ we could place number of active monitors in the array so that compiled code
3201   // could double check it.
3202 
3203   Method* moop = fr.interpreter_frame_method();
3204   int max_locals = moop->max_locals();
3205   // Allocate temp buffer, 1 word per local & 2 per active monitor
3206   int buf_size_words = max_locals + active_monitor_count * BasicObjectLock::size();
3207   intptr_t *buf = NEW_C_HEAP_ARRAY(intptr_t,buf_size_words, mtCode);
3208 
3209   // Copy the locals.  Order is preserved so that loading of longs works.
3210   // Since there's no GC I can copy the oops blindly.
3211   assert(sizeof(HeapWord)==sizeof(intptr_t), "fix this code");
3212   Copy::disjoint_words((HeapWord*)fr.interpreter_frame_local_at(max_locals-1),
3213                        (HeapWord*)&buf[0],
3214                        max_locals);
3215 
3216   // Inflate locks.  Copy the displaced headers.  Be careful, there can be holes.
3217   int i = max_locals;
3218   for (BasicObjectLock *kptr2 = fr.interpreter_frame_monitor_end();
3219        kptr2 < fr.interpreter_frame_monitor_begin();
3220        kptr2 = fr.next_monitor_in_interpreter_frame(kptr2) ) {
3221     if (kptr2->obj() != NULL) {         // Avoid 'holes' in the monitor array
3222       BasicLock *lock = kptr2->lock();
3223       // Inflate so the object's header no longer refers to the BasicLock.
3224       if (lock->displaced_header().is_unlocked()) {
3225         // The object is locked and the resulting ObjectMonitor* will also be
3226         // locked so it can't be async deflated until ownership is dropped.
3227         // See the big comment in basicLock.cpp: BasicLock::move_to().
3228         ObjectSynchronizer::inflate_helper(kptr2->obj());
3229       }
3230       // Now the displaced header is free to move because the
3231       // object's header no longer refers to it.
3232       buf[i++] = (intptr_t)lock->displaced_header().value();
3233       buf[i++] = cast_from_oop<intptr_t>(kptr2->obj());
3234     }
3235   }
3236   assert(i - max_locals == active_monitor_count*2, "found the expected number of monitors");
3237 
3238   return buf;
3239 JRT_END
3240 
3241 JRT_LEAF(void, SharedRuntime::OSR_migration_end( intptr_t* buf) )
3242   FREE_C_HEAP_ARRAY(intptr_t, buf);
3243 JRT_END
3244 
3245 bool AdapterHandlerLibrary::contains(const CodeBlob* b) {
3246   AdapterHandlerTableIterator iter(_adapters);
3247   while (iter.has_next()) {
3248     AdapterHandlerEntry* a = iter.next();
3249     if (b == CodeCache::find_blob(a->get_i2c_entry())) return true;
3250   }
3251   return false;
3252 }
3253 
3254 void AdapterHandlerLibrary::print_handler_on(outputStream* st, const CodeBlob* b) {
3255   AdapterHandlerTableIterator iter(_adapters);
3256   while (iter.has_next()) {
3257     AdapterHandlerEntry* a = iter.next();
3258     if (b == CodeCache::find_blob(a->get_i2c_entry())) {
3259       st->print("Adapter for signature: ");
3260       a->print_adapter_on(tty);
3261       return;
3262     }
3263   }
3264   assert(false, "Should have found handler");
3265 }
3266 
3267 void AdapterHandlerEntry::print_adapter_on(outputStream* st) const {
3268   st->print("AHE@" INTPTR_FORMAT ": %s", p2i(this), fingerprint()->as_string());
3269   if (get_i2c_entry() != NULL) {
3270     st->print(" i2c: " INTPTR_FORMAT, p2i(get_i2c_entry()));
3271   }
3272   if (get_c2i_entry() != NULL) {
3273     st->print(" c2i: " INTPTR_FORMAT, p2i(get_c2i_entry()));
3274   }









3275   if (get_c2i_unverified_entry() != NULL) {
3276     st->print(" c2iUV: " INTPTR_FORMAT, p2i(get_c2i_unverified_entry()));
3277   }
3278   if (get_c2i_no_clinit_check_entry() != NULL) {
3279     st->print(" c2iNCI: " INTPTR_FORMAT, p2i(get_c2i_no_clinit_check_entry()));
3280   }
3281   st->cr();
3282 }
3283 
3284 #ifndef PRODUCT
3285 
3286 void AdapterHandlerLibrary::print_statistics() {
3287   _adapters->print_statistics();
3288 }
3289 
3290 #endif /* PRODUCT */
3291 
3292 JRT_LEAF(void, SharedRuntime::enable_stack_reserved_zone(JavaThread* current))
3293   StackOverflow* overflow_state = current->stack_overflow_state();
3294   overflow_state->enable_stack_reserved_zone(/*check_if_disabled*/true);
3295   overflow_state->set_reserved_stack_activation(current->stack_base());
3296 JRT_END
3297 
3298 frame SharedRuntime::look_for_reserved_stack_annotated_method(JavaThread* current, frame fr) {
3299   ResourceMark rm(current);
3300   frame activation;
3301   CompiledMethod* nm = NULL;
3302   int count = 1;
3303 
3304   assert(fr.is_java_frame(), "Must start on Java frame");
3305 
3306   while (true) {
3307     Method* method = NULL;
3308     bool found = false;
3309     if (fr.is_interpreted_frame()) {
3310       method = fr.interpreter_frame_method();
3311       if (method != NULL && method->has_reserved_stack_access()) {
3312         found = true;
3313       }
3314     } else {
3315       CodeBlob* cb = fr.cb();
3316       if (cb != NULL && cb->is_compiled()) {
3317         nm = cb->as_compiled_method();
3318         method = nm->method();
3319         // scope_desc_near() must be used, instead of scope_desc_at() because on
3320         // SPARC, the pcDesc can be on the delay slot after the call instruction.
3321         for (ScopeDesc *sd = nm->scope_desc_near(fr.pc()); sd != NULL; sd = sd->sender()) {
3322           method = sd->method();
3323           if (method != NULL && method->has_reserved_stack_access()) {
3324             found = true;
3325       }
3326     }
3327       }
3328     }
3329     if (found) {
3330       activation = fr;
3331       warning("Potentially dangerous stack overflow in "
3332               "ReservedStackAccess annotated method %s [%d]",
3333               method->name_and_sig_as_C_string(), count++);
3334       EventReservedStackActivation event;
3335       if (event.should_commit()) {
3336         event.set_method(method);
3337         event.commit();
3338       }
3339     }
3340     if (fr.is_first_java_frame()) {
3341       break;
3342     } else {
3343       fr = fr.java_sender();
3344     }
3345   }
3346   return activation;
3347 }
3348 
3349 void SharedRuntime::on_slowpath_allocation_exit(JavaThread* current) {
3350   // After any safepoint, just before going back to compiled code,
3351   // we inform the GC that we will be doing initializing writes to
3352   // this object in the future without emitting card-marks, so
3353   // GC may take any compensating steps.
3354 
3355   oop new_obj = current->vm_result();
3356   if (new_obj == NULL) return;
3357 
3358   BarrierSet *bs = BarrierSet::barrier_set();
3359   bs->on_slowpath_allocation_exit(current, new_obj);
3360 }





















































































































































































--- EOF ---