1 /*
   2  * Copyright (c) 1997, 2026, 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 "cds/aotCompressedPointers.hpp"
  26 #include "cds/archiveBuilder.hpp"
  27 #include "cds/archiveUtils.inline.hpp"
  28 #include "classfile/classLoader.hpp"
  29 #include "classfile/compactHashtable.hpp"
  30 #include "classfile/javaClasses.inline.hpp"
  31 #include "classfile/stringTable.hpp"
  32 #include "classfile/vmClasses.hpp"
  33 #include "classfile/vmSymbols.hpp"
  34 #include "code/aotCodeCache.hpp"
  35 #include "code/codeCache.hpp"
  36 #include "code/compiledIC.hpp"
  37 #include "code/nmethod.inline.hpp"
  38 #include "code/scopeDesc.hpp"
  39 #include "code/vtableStubs.hpp"
  40 #include "compiler/abstractCompiler.hpp"
  41 #include "compiler/compileBroker.hpp"
  42 #include "compiler/disassembler.hpp"
  43 #include "gc/shared/barrierSet.hpp"
  44 #include "gc/shared/collectedHeap.hpp"
  45 #include "interpreter/interpreter.hpp"
  46 #include "interpreter/interpreterRuntime.hpp"
  47 #include "jfr/jfrEvents.hpp"
  48 #include "jvm.h"
  49 #include "logging/log.hpp"
  50 #include "memory/resourceArea.hpp"
  51 #include "memory/universe.hpp"
  52 #include "metaprogramming/primitiveConversions.hpp"
  53 #include "oops/klass.hpp"
  54 #include "oops/method.inline.hpp"
  55 #include "oops/objArrayKlass.hpp"
  56 #include "oops/oop.inline.hpp"
  57 #include "prims/forte.hpp"
  58 #include "prims/jvmtiExport.hpp"
  59 #include "prims/jvmtiThreadState.hpp"
  60 #include "prims/methodHandles.hpp"
  61 #include "prims/nativeLookup.hpp"
  62 #include "runtime/arguments.hpp"
  63 #include "runtime/atomicAccess.hpp"
  64 #include "runtime/basicLock.inline.hpp"
  65 #include "runtime/frame.inline.hpp"
  66 #include "runtime/handles.inline.hpp"
  67 #include "runtime/init.hpp"
  68 #include "runtime/interfaceSupport.inline.hpp"
  69 #include "runtime/java.hpp"
  70 #include "runtime/javaCalls.hpp"
  71 #include "runtime/jniHandles.inline.hpp"
  72 #include "runtime/osThread.hpp"
  73 #include "runtime/perfData.inline.hpp"
  74 #include "runtime/sharedRuntime.hpp"
  75 #include "runtime/stackWatermarkSet.hpp"
  76 #include "runtime/stubRoutines.hpp"
  77 #include "runtime/synchronizer.hpp"
  78 #include "runtime/timerTrace.hpp"
  79 #include "runtime/vframe.inline.hpp"
  80 #include "runtime/vframeArray.hpp"
  81 #include "runtime/vm_version.hpp"
  82 #include "services/management.hpp"
  83 #include "utilities/copy.hpp"
  84 #include "utilities/dtrace.hpp"
  85 #include "utilities/events.hpp"
  86 #include "utilities/exceptions.hpp"
  87 #include "utilities/globalDefinitions.hpp"
  88 #include "utilities/hashTable.hpp"
  89 #include "utilities/macros.hpp"
  90 #include "utilities/xmlstream.hpp"
  91 #ifdef COMPILER1
  92 #include "c1/c1_Runtime1.hpp"
  93 #endif
  94 #ifdef COMPILER2
  95 #include "opto/runtime.hpp"
  96 #endif
  97 #if INCLUDE_JFR
  98 #include "jfr/jfr.inline.hpp"
  99 #endif
 100 
 101 // Shared runtime stub routines reside in their own unique blob with a
 102 // single entry point
 103 
 104 
 105 #define SHARED_STUB_FIELD_DEFINE(name, type) \
 106   type*       SharedRuntime::BLOB_FIELD_NAME(name);
 107   SHARED_STUBS_DO(SHARED_STUB_FIELD_DEFINE)
 108 #undef SHARED_STUB_FIELD_DEFINE
 109 
 110 nmethod*            SharedRuntime::_cont_doYield_stub;
 111 
 112 PerfTickCounters* SharedRuntime::_perf_resolve_opt_virtual_total_time = nullptr;
 113 PerfTickCounters* SharedRuntime::_perf_resolve_virtual_total_time     = nullptr;
 114 PerfTickCounters* SharedRuntime::_perf_resolve_static_total_time      = nullptr;
 115 PerfTickCounters* SharedRuntime::_perf_handle_wrong_method_total_time = nullptr;
 116 PerfTickCounters* SharedRuntime::_perf_ic_miss_total_time             = nullptr;
 117 
 118 #if 0
 119 // TODO tweak global stub name generation to match this
 120 #define SHARED_STUB_NAME_DECLARE(name, type) "Shared Runtime " # name "_blob",
 121 const char *SharedRuntime::_stub_names[] = {
 122   SHARED_STUBS_DO(SHARED_STUB_NAME_DECLARE)
 123 };
 124 #endif
 125 
 126 //----------------------------generate_stubs-----------------------------------
 127 void SharedRuntime::generate_initial_stubs() {
 128   // Build this early so it's available for the interpreter.
 129   _throw_StackOverflowError_blob =
 130     generate_throw_exception(StubId::shared_throw_StackOverflowError_id,
 131                              CAST_FROM_FN_PTR(address, SharedRuntime::throw_StackOverflowError));
 132 }
 133 
 134 void SharedRuntime::generate_stubs() {
 135   _wrong_method_blob =
 136     generate_resolve_blob(StubId::shared_wrong_method_id,
 137                           CAST_FROM_FN_PTR(address, SharedRuntime::handle_wrong_method));
 138   _wrong_method_abstract_blob =
 139     generate_resolve_blob(StubId::shared_wrong_method_abstract_id,
 140                           CAST_FROM_FN_PTR(address, SharedRuntime::handle_wrong_method_abstract));
 141   _ic_miss_blob =
 142     generate_resolve_blob(StubId::shared_ic_miss_id,
 143                           CAST_FROM_FN_PTR(address, SharedRuntime::handle_wrong_method_ic_miss));
 144   _resolve_opt_virtual_call_blob =
 145     generate_resolve_blob(StubId::shared_resolve_opt_virtual_call_id,
 146                           CAST_FROM_FN_PTR(address, SharedRuntime::resolve_opt_virtual_call_C));
 147   _resolve_virtual_call_blob =
 148     generate_resolve_blob(StubId::shared_resolve_virtual_call_id,
 149                           CAST_FROM_FN_PTR(address, SharedRuntime::resolve_virtual_call_C));
 150   _resolve_static_call_blob =
 151     generate_resolve_blob(StubId::shared_resolve_static_call_id,
 152                           CAST_FROM_FN_PTR(address, SharedRuntime::resolve_static_call_C));
 153 
 154   _throw_delayed_StackOverflowError_blob =
 155     generate_throw_exception(StubId::shared_throw_delayed_StackOverflowError_id,
 156                              CAST_FROM_FN_PTR(address, SharedRuntime::throw_delayed_StackOverflowError));
 157 
 158   _throw_AbstractMethodError_blob =
 159     generate_throw_exception(StubId::shared_throw_AbstractMethodError_id,
 160                              CAST_FROM_FN_PTR(address, SharedRuntime::throw_AbstractMethodError));
 161 
 162   _throw_IncompatibleClassChangeError_blob =
 163     generate_throw_exception(StubId::shared_throw_IncompatibleClassChangeError_id,
 164                              CAST_FROM_FN_PTR(address, SharedRuntime::throw_IncompatibleClassChangeError));
 165 
 166   _throw_NullPointerException_at_call_blob =
 167     generate_throw_exception(StubId::shared_throw_NullPointerException_at_call_id,
 168                              CAST_FROM_FN_PTR(address, SharedRuntime::throw_NullPointerException_at_call));
 169 
 170 #if COMPILER2_OR_JVMCI
 171   // Vectors are generated only by C2 and JVMCI.
 172   bool support_wide = is_wide_vector(MaxVectorSize);
 173   if (support_wide) {
 174     _polling_page_vectors_safepoint_handler_blob =
 175       generate_handler_blob(StubId::shared_polling_page_vectors_safepoint_handler_id,
 176                             CAST_FROM_FN_PTR(address, SafepointSynchronize::handle_polling_page_exception));
 177   }
 178 #endif // COMPILER2_OR_JVMCI
 179   _polling_page_safepoint_handler_blob =
 180     generate_handler_blob(StubId::shared_polling_page_safepoint_handler_id,
 181                           CAST_FROM_FN_PTR(address, SafepointSynchronize::handle_polling_page_exception));
 182   _polling_page_return_handler_blob =
 183     generate_handler_blob(StubId::shared_polling_page_return_handler_id,
 184                           CAST_FROM_FN_PTR(address, SafepointSynchronize::handle_polling_page_exception));
 185 
 186   generate_deopt_blob();
 187 
 188   if (UsePerfData) {
 189     EXCEPTION_MARK;
 190     NEWPERFTICKCOUNTERS(_perf_resolve_opt_virtual_total_time, SUN_CI, "resovle_opt_virtual_call");
 191     NEWPERFTICKCOUNTERS(_perf_resolve_virtual_total_time,     SUN_CI, "resovle_virtual_call");
 192     NEWPERFTICKCOUNTERS(_perf_resolve_static_total_time,      SUN_CI, "resovle_static_call");
 193     NEWPERFTICKCOUNTERS(_perf_handle_wrong_method_total_time, SUN_CI, "handle_wrong_method");
 194     NEWPERFTICKCOUNTERS(_perf_ic_miss_total_time ,            SUN_CI, "ic_miss");
 195     if (HAS_PENDING_EXCEPTION) {
 196       vm_exit_during_initialization("SharedRuntime::generate_stubs() failed unexpectedly");
 197     }
 198   }
 199 }
 200 
 201 void SharedRuntime::init_adapter_library() {
 202   AdapterHandlerLibrary::initialize();
 203 }
 204 
 205 static void print_counter_on(outputStream* st, const char* name, PerfTickCounters* counter, uint cnt) {
 206   st->print("  %-28s " JLONG_FORMAT_W(6) "us", name, counter->elapsed_counter_value_us());
 207   if (TraceThreadTime) {
 208     st->print(" (elapsed) " JLONG_FORMAT_W(6) "us (thread)", counter->thread_counter_value_us());
 209   }
 210   st->print(" / %5d events", cnt);
 211   st->cr();
 212 }
 213 
 214 void SharedRuntime::print_counters_on(outputStream* st) {
 215   st->print_cr("SharedRuntime:");
 216   if (UsePerfData) {
 217     print_counter_on(st, "resolve_opt_virtual_call:", _perf_resolve_opt_virtual_total_time, _resolve_opt_virtual_ctr);
 218     print_counter_on(st, "resolve_virtual_call:",     _perf_resolve_virtual_total_time,     _resolve_virtual_ctr);
 219     print_counter_on(st, "resolve_static_call:",      _perf_resolve_static_total_time,      _resolve_static_ctr);
 220     print_counter_on(st, "handle_wrong_method:",      _perf_handle_wrong_method_total_time, _wrong_method_ctr);
 221     print_counter_on(st, "ic_miss:",                  _perf_ic_miss_total_time,             _ic_miss_ctr);
 222 
 223     jlong total_elapsed_time_us = Management::ticks_to_us(_perf_resolve_opt_virtual_total_time->elapsed_counter_value() +
 224                                                           _perf_resolve_virtual_total_time->elapsed_counter_value() +
 225                                                           _perf_resolve_static_total_time->elapsed_counter_value() +
 226                                                           _perf_handle_wrong_method_total_time->elapsed_counter_value() +
 227                                                           _perf_ic_miss_total_time->elapsed_counter_value());
 228     st->print("Total:                      " JLONG_FORMAT_W(5) "us", total_elapsed_time_us);
 229     if (TraceThreadTime) {
 230       jlong total_thread_time_us = Management::ticks_to_us(_perf_resolve_opt_virtual_total_time->thread_counter_value() +
 231                                                            _perf_resolve_virtual_total_time->thread_counter_value() +
 232                                                            _perf_resolve_static_total_time->thread_counter_value() +
 233                                                            _perf_handle_wrong_method_total_time->thread_counter_value() +
 234                                                            _perf_ic_miss_total_time->thread_counter_value());
 235       st->print(" (elapsed) " JLONG_FORMAT_W(5) "us (thread)", total_thread_time_us);
 236 
 237     }
 238     st->cr();
 239   } else {
 240     st->print_cr("  no data (UsePerfData is turned off)");
 241   }
 242 }
 243 
 244 #if INCLUDE_JFR
 245 //------------------------------generate jfr runtime stubs ------
 246 void SharedRuntime::generate_jfr_stubs() {
 247   ResourceMark rm;
 248   const char* timer_msg = "SharedRuntime generate_jfr_stubs";
 249   TraceTime timer(timer_msg, TRACETIME_LOG(Info, startuptime));
 250 
 251   _jfr_write_checkpoint_blob = generate_jfr_write_checkpoint();
 252   _jfr_return_lease_blob = generate_jfr_return_lease();
 253 }
 254 
 255 #endif // INCLUDE_JFR
 256 
 257 #include <math.h>
 258 
 259 // Implementation of SharedRuntime
 260 

 261 // For statistics
 262 uint SharedRuntime::_ic_miss_ctr = 0;
 263 uint SharedRuntime::_wrong_method_ctr = 0;
 264 uint SharedRuntime::_resolve_static_ctr = 0;
 265 uint SharedRuntime::_resolve_virtual_ctr = 0;
 266 uint SharedRuntime::_resolve_opt_virtual_ctr = 0;
 267 
 268 #ifndef PRODUCT
 269 uint SharedRuntime::_implicit_null_throws = 0;
 270 uint SharedRuntime::_implicit_div0_throws = 0;
 271 
 272 int64_t SharedRuntime::_nof_normal_calls = 0;
 273 int64_t SharedRuntime::_nof_inlined_calls = 0;
 274 int64_t SharedRuntime::_nof_megamorphic_calls = 0;
 275 int64_t SharedRuntime::_nof_static_calls = 0;
 276 int64_t SharedRuntime::_nof_inlined_static_calls = 0;
 277 int64_t SharedRuntime::_nof_interface_calls = 0;
 278 int64_t SharedRuntime::_nof_inlined_interface_calls = 0;
 279 
 280 uint SharedRuntime::_new_instance_ctr=0;
 281 uint SharedRuntime::_new_array_ctr=0;
 282 uint SharedRuntime::_multi2_ctr=0;
 283 uint SharedRuntime::_multi3_ctr=0;
 284 uint SharedRuntime::_multi4_ctr=0;
 285 uint SharedRuntime::_multi5_ctr=0;
 286 uint SharedRuntime::_mon_enter_stub_ctr=0;
 287 uint SharedRuntime::_mon_exit_stub_ctr=0;
 288 uint SharedRuntime::_mon_enter_ctr=0;
 289 uint SharedRuntime::_mon_exit_ctr=0;
 290 uint SharedRuntime::_partial_subtype_ctr=0;
 291 uint SharedRuntime::_jbyte_array_copy_ctr=0;
 292 uint SharedRuntime::_jshort_array_copy_ctr=0;
 293 uint SharedRuntime::_jint_array_copy_ctr=0;
 294 uint SharedRuntime::_jlong_array_copy_ctr=0;
 295 uint SharedRuntime::_oop_array_copy_ctr=0;
 296 uint SharedRuntime::_checkcast_array_copy_ctr=0;
 297 uint SharedRuntime::_unsafe_array_copy_ctr=0;
 298 uint SharedRuntime::_generic_array_copy_ctr=0;
 299 uint SharedRuntime::_slow_array_copy_ctr=0;
 300 uint SharedRuntime::_find_handler_ctr=0;
 301 uint SharedRuntime::_rethrow_ctr=0;
 302 uint SharedRuntime::_unsafe_set_memory_ctr=0;
 303 
 304 int     SharedRuntime::_ICmiss_index                    = 0;
 305 int     SharedRuntime::_ICmiss_count[SharedRuntime::maxICmiss_count];
 306 address SharedRuntime::_ICmiss_at[SharedRuntime::maxICmiss_count];
 307 
 308 
 309 void SharedRuntime::trace_ic_miss(address at) {
 310   for (int i = 0; i < _ICmiss_index; i++) {
 311     if (_ICmiss_at[i] == at) {
 312       _ICmiss_count[i]++;
 313       return;
 314     }
 315   }
 316   int index = _ICmiss_index++;
 317   if (_ICmiss_index >= maxICmiss_count) _ICmiss_index = maxICmiss_count - 1;
 318   _ICmiss_at[index] = at;
 319   _ICmiss_count[index] = 1;
 320 }
 321 
 322 void SharedRuntime::print_ic_miss_histogram_on(outputStream* st) {
 323   if (ICMissHistogram) {
 324     st->print_cr("IC Miss Histogram:");
 325     int tot_misses = 0;
 326     for (int i = 0; i < _ICmiss_index; i++) {
 327       st->print_cr("  at: " INTPTR_FORMAT "  nof: %d", p2i(_ICmiss_at[i]), _ICmiss_count[i]);
 328       tot_misses += _ICmiss_count[i];
 329     }
 330     st->print_cr("Total IC misses: %7d", tot_misses);
 331   }
 332 }
 333 
 334 #ifdef COMPILER2
 335 // Runtime methods for printf-style debug nodes (same printing format as fieldDescriptor::print_on_for)
 336 void SharedRuntime::debug_print_value(jboolean x) {
 337   tty->print_cr("boolean %d", x);
 338 }
 339 
 340 void SharedRuntime::debug_print_value(jbyte x) {
 341   tty->print_cr("byte %d", x);
 342 }
 343 
 344 void SharedRuntime::debug_print_value(jshort x) {
 345   tty->print_cr("short %d", x);
 346 }
 347 
 348 void SharedRuntime::debug_print_value(jchar x) {
 349   tty->print_cr("char %c %d", isprint(x) ? x : ' ', x);
 350 }
 351 
 352 void SharedRuntime::debug_print_value(jint x) {
 353   tty->print_cr("int %d", x);
 354 }
 355 
 356 void SharedRuntime::debug_print_value(jlong x) {
 357   tty->print_cr("long " JLONG_FORMAT, x);
 358 }
 359 
 360 void SharedRuntime::debug_print_value(jfloat x) {
 361   tty->print_cr("float %f", x);
 362 }
 363 
 364 void SharedRuntime::debug_print_value(jdouble x) {
 365   tty->print_cr("double %lf", x);
 366 }
 367 
 368 void SharedRuntime::debug_print_value(oopDesc* x) {
 369   x->print();
 370 }
 371 #endif // COMPILER2
 372 
 373 #endif // PRODUCT
 374 
 375 
 376 JRT_LEAF(jlong, SharedRuntime::lmul(jlong y, jlong x))
 377   return x * y;
 378 JRT_END
 379 
 380 
 381 JRT_LEAF(jlong, SharedRuntime::ldiv(jlong y, jlong x))
 382   if (x == min_jlong && y == CONST64(-1)) {
 383     return x;
 384   } else {
 385     return x / y;
 386   }
 387 JRT_END
 388 
 389 
 390 JRT_LEAF(jlong, SharedRuntime::lrem(jlong y, jlong x))
 391   if (x == min_jlong && y == CONST64(-1)) {
 392     return 0;
 393   } else {
 394     return x % y;
 395   }
 396 JRT_END
 397 
 398 
 399 #ifdef _WIN64
 400 const juint  float_sign_mask  = 0x7FFFFFFF;
 401 const juint  float_infinity   = 0x7F800000;
 402 const julong double_sign_mask = CONST64(0x7FFFFFFFFFFFFFFF);
 403 const julong double_infinity  = CONST64(0x7FF0000000000000);
 404 #endif
 405 
 406 #if !defined(X86)
 407 JRT_LEAF(jfloat, SharedRuntime::frem(jfloat x, jfloat y))
 408 #ifdef _WIN64
 409   // 64-bit Windows on amd64 returns the wrong values for
 410   // infinity operands.
 411   juint xbits = PrimitiveConversions::cast<juint>(x);
 412   juint ybits = PrimitiveConversions::cast<juint>(y);
 413   // x Mod Infinity == x unless x is infinity
 414   if (((xbits & float_sign_mask) != float_infinity) &&
 415        ((ybits & float_sign_mask) == float_infinity) ) {
 416     return x;
 417   }
 418   return ((jfloat)fmod_winx64((double)x, (double)y));
 419 #else
 420   return ((jfloat)fmod((double)x,(double)y));
 421 #endif
 422 JRT_END
 423 
 424 JRT_LEAF(jdouble, SharedRuntime::drem(jdouble x, jdouble y))
 425 #ifdef _WIN64
 426   julong xbits = PrimitiveConversions::cast<julong>(x);
 427   julong ybits = PrimitiveConversions::cast<julong>(y);
 428   // x Mod Infinity == x unless x is infinity
 429   if (((xbits & double_sign_mask) != double_infinity) &&
 430        ((ybits & double_sign_mask) == double_infinity) ) {
 431     return x;
 432   }
 433   return ((jdouble)fmod_winx64((double)x, (double)y));
 434 #else
 435   return ((jdouble)fmod((double)x,(double)y));
 436 #endif
 437 JRT_END
 438 #endif // !X86
 439 
 440 JRT_LEAF(jfloat, SharedRuntime::i2f(jint x))
 441   return (jfloat)x;
 442 JRT_END
 443 
 444 #ifdef __SOFTFP__
 445 JRT_LEAF(jfloat, SharedRuntime::fadd(jfloat x, jfloat y))
 446   return x + y;
 447 JRT_END
 448 
 449 JRT_LEAF(jfloat, SharedRuntime::fsub(jfloat x, jfloat y))
 450   return x - y;
 451 JRT_END
 452 
 453 JRT_LEAF(jfloat, SharedRuntime::fmul(jfloat x, jfloat y))
 454   return x * y;
 455 JRT_END
 456 
 457 JRT_LEAF(jfloat, SharedRuntime::fdiv(jfloat x, jfloat y))
 458   return x / y;
 459 JRT_END
 460 
 461 JRT_LEAF(jdouble, SharedRuntime::dadd(jdouble x, jdouble y))
 462   return x + y;
 463 JRT_END
 464 
 465 JRT_LEAF(jdouble, SharedRuntime::dsub(jdouble x, jdouble y))
 466   return x - y;
 467 JRT_END
 468 
 469 JRT_LEAF(jdouble, SharedRuntime::dmul(jdouble x, jdouble y))
 470   return x * y;
 471 JRT_END
 472 
 473 JRT_LEAF(jdouble, SharedRuntime::ddiv(jdouble x, jdouble y))
 474   return x / y;
 475 JRT_END
 476 
 477 JRT_LEAF(jdouble, SharedRuntime::i2d(jint x))
 478   return (jdouble)x;
 479 JRT_END
 480 
 481 JRT_LEAF(jdouble, SharedRuntime::f2d(jfloat x))
 482   return (jdouble)x;
 483 JRT_END
 484 
 485 JRT_LEAF(int,  SharedRuntime::fcmpl(float x, float y))
 486   return x>y ? 1 : (x==y ? 0 : -1);  /* x<y or is_nan*/
 487 JRT_END
 488 
 489 JRT_LEAF(int,  SharedRuntime::fcmpg(float x, float y))
 490   return x<y ? -1 : (x==y ? 0 : 1);  /* x>y or is_nan */
 491 JRT_END
 492 
 493 JRT_LEAF(int,  SharedRuntime::dcmpl(double x, double y))
 494   return x>y ? 1 : (x==y ? 0 : -1); /* x<y or is_nan */
 495 JRT_END
 496 
 497 JRT_LEAF(int,  SharedRuntime::dcmpg(double x, double y))
 498   return x<y ? -1 : (x==y ? 0 : 1);  /* x>y or is_nan */
 499 JRT_END
 500 
 501 // Functions to return the opposite of the aeabi functions for nan.
 502 JRT_LEAF(int, SharedRuntime::unordered_fcmplt(float x, float y))
 503   return (x < y) ? 1 : ((g_isnan(x) || g_isnan(y)) ? 1 : 0);
 504 JRT_END
 505 
 506 JRT_LEAF(int, SharedRuntime::unordered_dcmplt(double x, double y))
 507   return (x < y) ? 1 : ((g_isnan(x) || g_isnan(y)) ? 1 : 0);
 508 JRT_END
 509 
 510 JRT_LEAF(int, SharedRuntime::unordered_fcmple(float x, float y))
 511   return (x <= y) ? 1 : ((g_isnan(x) || g_isnan(y)) ? 1 : 0);
 512 JRT_END
 513 
 514 JRT_LEAF(int, SharedRuntime::unordered_dcmple(double x, double y))
 515   return (x <= y) ? 1 : ((g_isnan(x) || g_isnan(y)) ? 1 : 0);
 516 JRT_END
 517 
 518 JRT_LEAF(int, SharedRuntime::unordered_fcmpge(float x, float y))
 519   return (x >= y) ? 1 : ((g_isnan(x) || g_isnan(y)) ? 1 : 0);
 520 JRT_END
 521 
 522 JRT_LEAF(int, SharedRuntime::unordered_dcmpge(double x, double y))
 523   return (x >= y) ? 1 : ((g_isnan(x) || g_isnan(y)) ? 1 : 0);
 524 JRT_END
 525 
 526 JRT_LEAF(int, SharedRuntime::unordered_fcmpgt(float x, float y))
 527   return (x > y) ? 1 : ((g_isnan(x) || g_isnan(y)) ? 1 : 0);
 528 JRT_END
 529 
 530 JRT_LEAF(int, SharedRuntime::unordered_dcmpgt(double x, double y))
 531   return (x > y) ? 1 : ((g_isnan(x) || g_isnan(y)) ? 1 : 0);
 532 JRT_END
 533 
 534 // Intrinsics make gcc generate code for these.
 535 float  SharedRuntime::fneg(float f)   {
 536   return -f;
 537 }
 538 
 539 double SharedRuntime::dneg(double f)  {
 540   return -f;
 541 }
 542 
 543 #endif // __SOFTFP__
 544 
 545 #if defined(__SOFTFP__) || defined(E500V2)
 546 // Intrinsics make gcc generate code for these.
 547 double SharedRuntime::dabs(double f)  {
 548   return (f <= (double)0.0) ? (double)0.0 - f : f;
 549 }
 550 
 551 #endif
 552 
 553 #if defined(__SOFTFP__)
 554 double SharedRuntime::dsqrt(double f) {
 555   return sqrt(f);
 556 }
 557 #endif
 558 
 559 JRT_LEAF(jint, SharedRuntime::f2i(jfloat  x))
 560   if (g_isnan(x))
 561     return 0;
 562   if (x >= (jfloat) max_jint)
 563     return max_jint;
 564   if (x <= (jfloat) min_jint)
 565     return min_jint;
 566   return (jint) x;
 567 JRT_END
 568 
 569 
 570 JRT_LEAF(jlong, SharedRuntime::f2l(jfloat  x))
 571   if (g_isnan(x))
 572     return 0;
 573   if (x >= (jfloat) max_jlong)
 574     return max_jlong;
 575   if (x <= (jfloat) min_jlong)
 576     return min_jlong;
 577   return (jlong) x;
 578 JRT_END
 579 
 580 
 581 JRT_LEAF(jint, SharedRuntime::d2i(jdouble x))
 582   if (g_isnan(x))
 583     return 0;
 584   if (x >= (jdouble) max_jint)
 585     return max_jint;
 586   if (x <= (jdouble) min_jint)
 587     return min_jint;
 588   return (jint) x;
 589 JRT_END
 590 
 591 
 592 JRT_LEAF(jlong, SharedRuntime::d2l(jdouble x))
 593   if (g_isnan(x))
 594     return 0;
 595   if (x >= (jdouble) max_jlong)
 596     return max_jlong;
 597   if (x <= (jdouble) min_jlong)
 598     return min_jlong;
 599   return (jlong) x;
 600 JRT_END
 601 
 602 
 603 JRT_LEAF(jfloat, SharedRuntime::d2f(jdouble x))
 604   return (jfloat)x;
 605 JRT_END
 606 
 607 
 608 JRT_LEAF(jfloat, SharedRuntime::l2f(jlong x))
 609   return (jfloat)x;
 610 JRT_END
 611 
 612 
 613 JRT_LEAF(jdouble, SharedRuntime::l2d(jlong x))
 614   return (jdouble)x;
 615 JRT_END
 616 
 617 
 618 // Exception handling across interpreter/compiler boundaries
 619 //
 620 // exception_handler_for_return_address(...) returns the continuation address.
 621 // The continuation address is the entry point of the exception handler of the
 622 // previous frame depending on the return address.
 623 
 624 address SharedRuntime::raw_exception_handler_for_return_address(JavaThread* current, address return_address) {
 625   // Note: This is called when we have unwound the frame of the callee that did
 626   // throw an exception. So far, no check has been performed by the StackWatermarkSet.
 627   // Notably, the stack is not walkable at this point, and hence the check must
 628   // be deferred until later. Specifically, any of the handlers returned here in
 629   // this function, will get dispatched to, and call deferred checks to
 630   // StackWatermarkSet::after_unwind at a point where the stack is walkable.
 631   assert(frame::verify_return_pc(return_address), "must be a return address: " INTPTR_FORMAT, p2i(return_address));
 632   assert(current->frames_to_pop_failed_realloc() == 0 || Interpreter::contains(return_address), "missed frames to pop?");
 633 
 634 #if INCLUDE_JVMCI
 635   // JVMCI's ExceptionHandlerStub expects the thread local exception PC to be clear
 636   // and other exception handler continuations do not read it
 637   current->set_exception_pc(nullptr);
 638 #endif // INCLUDE_JVMCI
 639 
 640   if (Continuation::is_return_barrier_entry(return_address)) {
 641     return StubRoutines::cont_returnBarrierExc();
 642   }
 643 
 644   // The fastest case first
 645   CodeBlob* blob = CodeCache::find_blob(return_address);
 646   nmethod* nm = (blob != nullptr) ? blob->as_nmethod_or_null() : nullptr;
 647   if (nm != nullptr) {
 648     // native nmethods don't have exception handlers
 649     assert(!nm->is_native_method() || nm->method()->is_continuation_enter_intrinsic(), "no exception handler");
 650     assert(nm->header_begin() != nm->exception_begin(), "no exception handler");
 651     if (nm->is_deopt_pc(return_address)) {
 652       // If we come here because of a stack overflow, the stack may be
 653       // unguarded. Reguard the stack otherwise if we return to the
 654       // deopt blob and the stack bang causes a stack overflow we
 655       // crash.
 656       StackOverflow* overflow_state = current->stack_overflow_state();
 657       bool guard_pages_enabled = overflow_state->reguard_stack_if_needed();
 658       if (overflow_state->reserved_stack_activation() != current->stack_base()) {
 659         overflow_state->set_reserved_stack_activation(current->stack_base());
 660       }
 661       assert(guard_pages_enabled, "stack banging in deopt blob may cause crash");
 662       // The deferred StackWatermarkSet::after_unwind check will be performed in
 663       // Deoptimization::fetch_unroll_info (with exec_mode == Unpack_exception)
 664       return SharedRuntime::deopt_blob()->unpack_with_exception();
 665     } else {
 666       // The deferred StackWatermarkSet::after_unwind check will be performed in
 667       // * OptoRuntime::handle_exception_C_helper for C2 code
 668       // * exception_handler_for_pc_helper via Runtime1::handle_exception_from_callee_id for C1 code
 669 #ifdef COMPILER2
 670       if (nm->compiler_type() == compiler_c2) {
 671         return OptoRuntime::exception_blob()->entry_point();
 672       }
 673 #endif // COMPILER2
 674       return nm->exception_begin();
 675     }
 676   }
 677 
 678   // Entry code
 679   if (StubRoutines::returns_to_call_stub(return_address)) {
 680     // The deferred StackWatermarkSet::after_unwind check will be performed in
 681     // JavaCallWrapper::~JavaCallWrapper
 682     assert (StubRoutines::catch_exception_entry() != nullptr, "must be generated before");
 683     return StubRoutines::catch_exception_entry();
 684   }
 685   if (blob != nullptr && blob->is_upcall_stub()) {
 686     return StubRoutines::upcall_stub_exception_handler();
 687   }
 688   // Interpreted code
 689   if (Interpreter::contains(return_address)) {
 690     // The deferred StackWatermarkSet::after_unwind check will be performed in
 691     // InterpreterRuntime::exception_handler_for_exception
 692     return Interpreter::rethrow_exception_entry();
 693   }
 694 
 695   guarantee(blob == nullptr || !blob->is_runtime_stub(), "caller should have skipped stub");
 696   guarantee(!VtableStubs::contains(return_address), "null exceptions in vtables should have been handled already!");
 697 
 698 #ifndef PRODUCT
 699   { ResourceMark rm;
 700     tty->print_cr("No exception handler found for exception at " INTPTR_FORMAT " - potential problems:", p2i(return_address));
 701     os::print_location(tty, (intptr_t)return_address);
 702     tty->print_cr("a) exception happened in (new?) code stubs/buffers that is not handled here");
 703     tty->print_cr("b) other problem");
 704   }
 705 #endif // PRODUCT
 706   ShouldNotReachHere();
 707   return nullptr;
 708 }
 709 
 710 
 711 JRT_LEAF(address, SharedRuntime::exception_handler_for_return_address(JavaThread* current, address return_address))
 712   return raw_exception_handler_for_return_address(current, return_address);
 713 JRT_END
 714 
 715 
 716 address SharedRuntime::get_poll_stub(address pc) {
 717   address stub;
 718   // Look up the code blob
 719   CodeBlob *cb = CodeCache::find_blob(pc);
 720 
 721   // Should be an nmethod
 722   guarantee(cb != nullptr && cb->is_nmethod(), "safepoint polling: pc must refer to an nmethod");
 723 
 724   // Look up the relocation information
 725   assert(cb->as_nmethod()->is_at_poll_or_poll_return(pc),
 726       "safepoint polling: type must be poll at pc " INTPTR_FORMAT, p2i(pc));
 727 
 728 #ifdef ASSERT
 729   if (!((NativeInstruction*)pc)->is_safepoint_poll()) {
 730     tty->print_cr("bad pc: " PTR_FORMAT, p2i(pc));
 731     Disassembler::decode(cb);
 732     fatal("Only polling locations are used for safepoint");
 733   }
 734 #endif
 735 
 736   bool at_poll_return = cb->as_nmethod()->is_at_poll_return(pc);
 737   bool has_wide_vectors = cb->as_nmethod()->has_wide_vectors();
 738   if (at_poll_return) {
 739     assert(SharedRuntime::polling_page_return_handler_blob() != nullptr,
 740            "polling page return stub not created yet");
 741     stub = SharedRuntime::polling_page_return_handler_blob()->entry_point();
 742   } else if (has_wide_vectors) {
 743     assert(SharedRuntime::polling_page_vectors_safepoint_handler_blob() != nullptr,
 744            "polling page vectors safepoint stub not created yet");
 745     stub = SharedRuntime::polling_page_vectors_safepoint_handler_blob()->entry_point();
 746   } else {
 747     assert(SharedRuntime::polling_page_safepoint_handler_blob() != nullptr,
 748            "polling page safepoint stub not created yet");
 749     stub = SharedRuntime::polling_page_safepoint_handler_blob()->entry_point();
 750   }
 751   log_trace(safepoint)("Polling page exception: thread = " INTPTR_FORMAT " [%d], pc = "
 752                        INTPTR_FORMAT " (%s), stub = " INTPTR_FORMAT,
 753                        p2i(Thread::current()),
 754                        Thread::current()->osthread()->thread_id(),
 755                        p2i(pc),
 756                        at_poll_return ? "return" : "loop",
 757                        p2i(stub));
 758   return stub;
 759 }
 760 
 761 void SharedRuntime::throw_and_post_jvmti_exception(JavaThread* current, Handle h_exception) {
 762   if (JvmtiExport::can_post_on_exceptions()) {
 763     vframeStream vfst(current, true);
 764     methodHandle method = methodHandle(current, vfst.method());
 765     address bcp = method()->bcp_from(vfst.bci());
 766     JvmtiExport::post_exception_throw(current, method(), bcp, h_exception());
 767   }
 768 
 769 #if INCLUDE_JVMCI
 770   if (EnableJVMCI) {
 771     vframeStream vfst(current, true);
 772     methodHandle method = methodHandle(current, vfst.method());
 773     int bci = vfst.bci();
 774     MethodData* trap_mdo = method->method_data();
 775     if (trap_mdo != nullptr) {
 776       // Set exception_seen if the exceptional bytecode is an invoke
 777       Bytecode_invoke call = Bytecode_invoke_check(method, bci);
 778       if (call.is_valid()) {
 779         ResourceMark rm(current);
 780 
 781         // Lock to read ProfileData, and ensure lock is not broken by a safepoint
 782         MutexLocker ml(trap_mdo->extra_data_lock(), Mutex::_no_safepoint_check_flag);
 783 
 784         ProfileData* pdata = trap_mdo->allocate_bci_to_data(bci, nullptr);
 785         if (pdata != nullptr && pdata->is_BitData()) {
 786           BitData* bit_data = (BitData*) pdata;
 787           bit_data->set_exception_seen();
 788         }
 789       }
 790     }
 791   }
 792 #endif
 793 
 794   Exceptions::_throw(current, __FILE__, __LINE__, h_exception);
 795 }
 796 
 797 void SharedRuntime::throw_and_post_jvmti_exception(JavaThread* current, Symbol* name, const char *message) {
 798   Handle h_exception = Exceptions::new_exception(current, name, message);
 799   throw_and_post_jvmti_exception(current, h_exception);
 800 }
 801 
 802 // The interpreter code to call this tracing function is only
 803 // called/generated when UL is on for redefine, class and has the right level
 804 // and tags. Since obsolete methods are never compiled, we don't have
 805 // to modify the compilers to generate calls to this function.
 806 //
 807 JRT_LEAF(int, SharedRuntime::rc_trace_method_entry(
 808     JavaThread* thread, Method* method))
 809   if (method->is_obsolete()) {
 810     // We are calling an obsolete method, but this is not necessarily
 811     // an error. Our method could have been redefined just after we
 812     // fetched the Method* from the constant pool.
 813     ResourceMark rm;
 814     log_trace(redefine, class, obsolete)("calling obsolete method '%s'", method->name_and_sig_as_C_string());
 815   }
 816 
 817   LogStreamHandle(Trace, interpreter, bytecode) log;
 818   if (log.is_enabled()) {
 819     ResourceMark rm;
 820     log.print("method entry: " INTPTR_FORMAT " %s %s%s%s%s",
 821               p2i(thread),
 822               (method->is_static() ? "static" : "virtual"),
 823               method->name_and_sig_as_C_string(),
 824               (method->is_native() ? " native" : ""),
 825               (thread->class_being_initialized() != nullptr ? " clinit" : ""),
 826               (method->method_holder()->is_initialized() ? "" : " being_initialized"));
 827   }
 828   return 0;
 829 JRT_END
 830 
 831 // ret_pc points into caller; we are returning caller's exception handler
 832 // for given exception
 833 // Note that the implementation of this method assumes it's only called when an exception has actually occured
 834 address SharedRuntime::compute_compiled_exc_handler(nmethod* nm, address ret_pc, Handle& exception,
 835                                                     bool force_unwind, bool top_frame_only, bool& recursive_exception_occurred) {
 836   assert(nm != nullptr, "must exist");
 837   ResourceMark rm;
 838 
 839 #if INCLUDE_JVMCI
 840   if (nm->is_compiled_by_jvmci()) {
 841     // lookup exception handler for this pc
 842     int catch_pco = pointer_delta_as_int(ret_pc, nm->code_begin());
 843     ExceptionHandlerTable table(nm);
 844     HandlerTableEntry *t = table.entry_for(catch_pco, -1, 0);
 845     if (t != nullptr) {
 846       return nm->code_begin() + t->pco();
 847     } else {
 848       bool make_not_entrant = true;
 849       return Deoptimization::deoptimize_for_missing_exception_handler(nm, make_not_entrant);
 850     }
 851   }
 852 #endif // INCLUDE_JVMCI
 853 
 854   ScopeDesc* sd = nm->scope_desc_at(ret_pc);
 855   // determine handler bci, if any
 856   EXCEPTION_MARK;
 857 
 858   Handle orig_exception(THREAD, exception());
 859 
 860   int handler_bci = -1;
 861   int scope_depth = 0;
 862   if (!force_unwind) {
 863     int bci = sd->bci();
 864     bool recursive_exception = false;
 865     do {
 866       bool skip_scope_increment = false;
 867       // exception handler lookup
 868       Klass* ek = exception->klass();
 869       methodHandle mh(THREAD, sd->method());
 870       handler_bci = Method::fast_exception_handler_bci_for(mh, ek, bci, THREAD);
 871       if (HAS_PENDING_EXCEPTION) {
 872         recursive_exception = true;
 873         // We threw an exception while trying to find the exception handler.
 874         // Transfer the new exception to the exception handle which will
 875         // be set into thread local storage, and do another lookup for an
 876         // exception handler for this exception, this time starting at the
 877         // BCI of the exception handler which caused the exception to be
 878         // thrown (bugs 4307310 and 4546590). Set "exception" reference
 879         // argument to ensure that the correct exception is thrown (4870175).
 880         recursive_exception_occurred = true;
 881         exception.replace(PENDING_EXCEPTION);
 882         CLEAR_PENDING_EXCEPTION;
 883         if (handler_bci >= 0) {
 884           bci = handler_bci;
 885           handler_bci = -1;
 886           skip_scope_increment = true;
 887         }
 888       }
 889       else {
 890         recursive_exception = false;
 891       }
 892       if (!top_frame_only && handler_bci < 0 && !skip_scope_increment) {
 893         sd = sd->sender();
 894         if (sd != nullptr) {
 895           bci = sd->bci();
 896         }
 897         ++scope_depth;
 898       }
 899     } while (recursive_exception || (!top_frame_only && handler_bci < 0 && sd != nullptr));
 900   }
 901 
 902   // found handling method => lookup exception handler
 903   int catch_pco = pointer_delta_as_int(ret_pc, nm->code_begin());
 904 
 905   ExceptionHandlerTable table(nm);
 906   HandlerTableEntry *t = table.entry_for(catch_pco, handler_bci, scope_depth);
 907 
 908   // If the compiler did not anticipate a recursive exception, resulting in an exception
 909   // thrown from the catch bci, then the compiled exception handler might be missing.
 910   // This is rare.  Just deoptimize and let the interpreter rethrow the original
 911   // exception at the original bci.
 912   if (t == nullptr && recursive_exception_occurred) {
 913     exception.replace(orig_exception()); // restore original exception
 914     bool make_not_entrant = false;
 915     return Deoptimization::deoptimize_for_missing_exception_handler(nm, make_not_entrant);
 916   }
 917 
 918   if (t == nullptr && (nm->is_compiled_by_c1() || handler_bci != -1)) {
 919     // Allow abbreviated catch tables.  The idea is to allow a method
 920     // to materialize its exceptions without committing to the exact
 921     // routing of exceptions.  In particular this is needed for adding
 922     // a synthetic handler to unlock monitors when inlining
 923     // synchronized methods since the unlock path isn't represented in
 924     // the bytecodes.
 925     t = table.entry_for(catch_pco, -1, 0);
 926   }
 927 
 928 #ifdef COMPILER1
 929   if (t == nullptr && nm->is_compiled_by_c1()) {
 930     assert(nm->unwind_handler_begin() != nullptr, "");
 931     return nm->unwind_handler_begin();
 932   }
 933 #endif
 934 
 935   if (t == nullptr) {
 936     ttyLocker ttyl;
 937     tty->print_cr("MISSING EXCEPTION HANDLER for pc " INTPTR_FORMAT " and handler bci %d, catch_pco: %d", p2i(ret_pc), handler_bci, catch_pco);
 938     tty->print_cr("   Exception:");
 939     exception->print();
 940     tty->cr();
 941     tty->print_cr(" Compiled exception table :");
 942     table.print();
 943     nm->print();
 944     nm->print_code();
 945     guarantee(false, "missing exception handler");
 946     return nullptr;
 947   }
 948 
 949   if (handler_bci != -1) { // did we find a handler in this method?
 950     sd->method()->set_exception_handler_entered(handler_bci); // profile
 951   }
 952   return nm->code_begin() + t->pco();
 953 }
 954 
 955 JRT_ENTRY(void, SharedRuntime::throw_AbstractMethodError(JavaThread* current))
 956   // These errors occur only at call sites
 957   throw_and_post_jvmti_exception(current, vmSymbols::java_lang_AbstractMethodError());
 958 JRT_END
 959 
 960 JRT_ENTRY(void, SharedRuntime::throw_IncompatibleClassChangeError(JavaThread* current))
 961   // These errors occur only at call sites
 962   throw_and_post_jvmti_exception(current, vmSymbols::java_lang_IncompatibleClassChangeError(), "vtable stub");
 963 JRT_END
 964 
 965 JRT_ENTRY(void, SharedRuntime::throw_ArithmeticException(JavaThread* current))
 966   throw_and_post_jvmti_exception(current, vmSymbols::java_lang_ArithmeticException(), "/ by zero");
 967 JRT_END
 968 
 969 JRT_ENTRY(void, SharedRuntime::throw_NullPointerException(JavaThread* current))
 970   throw_and_post_jvmti_exception(current, vmSymbols::java_lang_NullPointerException(), nullptr);
 971 JRT_END
 972 
 973 JRT_ENTRY(void, SharedRuntime::throw_NullPointerException_at_call(JavaThread* current))
 974   // This entry point is effectively only used for NullPointerExceptions which occur at inline
 975   // cache sites (when the callee activation is not yet set up) so we are at a call site
 976   throw_and_post_jvmti_exception(current, vmSymbols::java_lang_NullPointerException(), nullptr);
 977 JRT_END
 978 
 979 JRT_ENTRY(void, SharedRuntime::throw_StackOverflowError(JavaThread* current))
 980   throw_StackOverflowError_common(current, false);
 981 JRT_END
 982 
 983 JRT_ENTRY(void, SharedRuntime::throw_delayed_StackOverflowError(JavaThread* current))
 984   throw_StackOverflowError_common(current, true);
 985 JRT_END
 986 
 987 void SharedRuntime::throw_StackOverflowError_common(JavaThread* current, bool delayed) {
 988   // We avoid using the normal exception construction in this case because
 989   // it performs an upcall to Java, and we're already out of stack space.
 990   JavaThread* THREAD = current; // For exception macros.
 991   InstanceKlass* k = vmClasses::StackOverflowError_klass();
 992   oop exception_oop = k->allocate_instance(CHECK);
 993   if (delayed) {
 994     java_lang_Throwable::set_message(exception_oop,
 995                                      Universe::delayed_stack_overflow_error_message());
 996   }
 997   Handle exception (current, exception_oop);
 998   if (StackTraceInThrowable) {
 999     java_lang_Throwable::fill_in_stack_trace(exception);
1000   }
1001   // Remove the ScopedValue bindings in case we got a
1002   // StackOverflowError while we were trying to remove ScopedValue
1003   // bindings.
1004   current->clear_scopedValueBindings();
1005   // Increment counter for hs_err file reporting
1006   Exceptions::increment_stack_overflow_errors();
1007   throw_and_post_jvmti_exception(current, exception);
1008 }
1009 
1010 address SharedRuntime::continuation_for_implicit_exception(JavaThread* current,
1011                                                            address pc,
1012                                                            ImplicitExceptionKind exception_kind)
1013 {
1014   address target_pc = nullptr;
1015 
1016   if (Interpreter::contains(pc)) {
1017     switch (exception_kind) {
1018       case IMPLICIT_NULL:           return Interpreter::throw_NullPointerException_entry();
1019       case IMPLICIT_DIVIDE_BY_ZERO: return Interpreter::throw_ArithmeticException_entry();
1020       case STACK_OVERFLOW:          return Interpreter::throw_StackOverflowError_entry();
1021       default:                      ShouldNotReachHere();
1022     }
1023   } else {
1024     switch (exception_kind) {
1025       case STACK_OVERFLOW: {
1026         // Stack overflow only occurs upon frame setup; the callee is
1027         // going to be unwound. Dispatch to a shared runtime stub
1028         // which will cause the StackOverflowError to be fabricated
1029         // and processed.
1030         // Stack overflow should never occur during deoptimization:
1031         // the compiled method bangs the stack by as much as the
1032         // interpreter would need in case of a deoptimization. The
1033         // deoptimization blob and uncommon trap blob bang the stack
1034         // in a debug VM to verify the correctness of the compiled
1035         // method stack banging.
1036         assert(current->deopt_mark() == nullptr, "no stack overflow from deopt blob/uncommon trap");
1037         Events::log_exception(current, "StackOverflowError at " INTPTR_FORMAT, p2i(pc));
1038         return SharedRuntime::throw_StackOverflowError_entry();
1039       }
1040 
1041       case IMPLICIT_NULL: {
1042         if (VtableStubs::contains(pc)) {
1043           // We haven't yet entered the callee frame. Fabricate an
1044           // exception and begin dispatching it in the caller. Since
1045           // the caller was at a call site, it's safe to destroy all
1046           // caller-saved registers, as these entry points do.
1047           VtableStub* vt_stub = VtableStubs::stub_containing(pc);
1048 
1049           // If vt_stub is null, then return null to signal handler to report the SEGV error.
1050           if (vt_stub == nullptr) return nullptr;
1051 
1052           if (vt_stub->is_abstract_method_error(pc)) {
1053             assert(!vt_stub->is_vtable_stub(), "should never see AbstractMethodErrors from vtable-type VtableStubs");
1054             Events::log_exception(current, "AbstractMethodError at " INTPTR_FORMAT, p2i(pc));
1055             // Instead of throwing the abstract method error here directly, we re-resolve
1056             // and will throw the AbstractMethodError during resolve. As a result, we'll
1057             // get a more detailed error message.
1058             return SharedRuntime::get_handle_wrong_method_stub();
1059           } else {
1060             Events::log_exception(current, "NullPointerException at vtable entry " INTPTR_FORMAT, p2i(pc));
1061             // Assert that the signal comes from the expected location in stub code.
1062             assert(vt_stub->is_null_pointer_exception(pc),
1063                    "obtained signal from unexpected location in stub code");
1064             return SharedRuntime::throw_NullPointerException_at_call_entry();
1065           }
1066         } else {
1067           CodeBlob* cb = CodeCache::find_blob(pc);
1068 
1069           // If code blob is null, then return null to signal handler to report the SEGV error.
1070           if (cb == nullptr) return nullptr;
1071 
1072           // Exception happened in CodeCache. Must be either:
1073           // 1. Inline-cache check in C2I handler blob,
1074           // 2. Inline-cache check in nmethod, or
1075           // 3. Implicit null exception in nmethod
1076 
1077           if (!cb->is_nmethod()) {
1078             bool is_in_blob = cb->is_adapter_blob() || cb->is_method_handles_adapter_blob();
1079             if (!is_in_blob) {
1080               // Allow normal crash reporting to handle this
1081               return nullptr;
1082             }
1083             Events::log_exception(current, "NullPointerException in code blob at " INTPTR_FORMAT, p2i(pc));
1084             // There is no handler here, so we will simply unwind.
1085             return SharedRuntime::throw_NullPointerException_at_call_entry();
1086           }
1087 
1088           // Otherwise, it's a compiled method.  Consult its exception handlers.
1089           nmethod* nm = cb->as_nmethod();
1090           if (nm->inlinecache_check_contains(pc)) {
1091             // exception happened inside inline-cache check code
1092             // => the nmethod is not yet active (i.e., the frame
1093             // is not set up yet) => use return address pushed by
1094             // caller => don't push another return address
1095             Events::log_exception(current, "NullPointerException in IC check " INTPTR_FORMAT, p2i(pc));
1096             return SharedRuntime::throw_NullPointerException_at_call_entry();
1097           }
1098 
1099           if (nm->method()->is_method_handle_intrinsic()) {
1100             // exception happened inside MH dispatch code, similar to a vtable stub
1101             Events::log_exception(current, "NullPointerException in MH adapter " INTPTR_FORMAT, p2i(pc));
1102             return SharedRuntime::throw_NullPointerException_at_call_entry();
1103           }
1104 
1105 #ifndef PRODUCT
1106           _implicit_null_throws++;
1107 #endif
1108           target_pc = nm->continuation_for_implicit_null_exception(pc);
1109           // If there's an unexpected fault, target_pc might be null,
1110           // in which case we want to fall through into the normal
1111           // error handling code.
1112         }
1113 
1114         break; // fall through
1115       }
1116 
1117 
1118       case IMPLICIT_DIVIDE_BY_ZERO: {
1119         nmethod* nm = CodeCache::find_nmethod(pc);
1120         guarantee(nm != nullptr, "must have containing compiled method for implicit division-by-zero exceptions");
1121 #ifndef PRODUCT
1122         _implicit_div0_throws++;
1123 #endif
1124         target_pc = nm->continuation_for_implicit_div0_exception(pc);
1125         // If there's an unexpected fault, target_pc might be null,
1126         // in which case we want to fall through into the normal
1127         // error handling code.
1128         break; // fall through
1129       }
1130 
1131       default: ShouldNotReachHere();
1132     }
1133 
1134     assert(exception_kind == IMPLICIT_NULL || exception_kind == IMPLICIT_DIVIDE_BY_ZERO, "wrong implicit exception kind");
1135 
1136     if (exception_kind == IMPLICIT_NULL) {
1137 #ifndef PRODUCT
1138       // for AbortVMOnException flag
1139       Exceptions::debug_check_abort("java.lang.NullPointerException");
1140 #endif //PRODUCT
1141       Events::log_exception(current, "Implicit null exception at " INTPTR_FORMAT " to " INTPTR_FORMAT, p2i(pc), p2i(target_pc));
1142     } else {
1143 #ifndef PRODUCT
1144       // for AbortVMOnException flag
1145       Exceptions::debug_check_abort("java.lang.ArithmeticException");
1146 #endif //PRODUCT
1147       Events::log_exception(current, "Implicit division by zero exception at " INTPTR_FORMAT " to " INTPTR_FORMAT, p2i(pc), p2i(target_pc));
1148     }
1149     return target_pc;
1150   }
1151 
1152   ShouldNotReachHere();
1153   return nullptr;
1154 }
1155 
1156 
1157 /**
1158  * Throws an java/lang/UnsatisfiedLinkError.  The address of this method is
1159  * installed in the native function entry of all native Java methods before
1160  * they get linked to their actual native methods.
1161  *
1162  * \note
1163  * This method actually never gets called!  The reason is because
1164  * the interpreter's native entries call NativeLookup::lookup() which
1165  * throws the exception when the lookup fails.  The exception is then
1166  * caught and forwarded on the return from NativeLookup::lookup() call
1167  * before the call to the native function.  This might change in the future.
1168  */
1169 JNI_ENTRY(void*, throw_unsatisfied_link_error(JNIEnv* env, ...))
1170 {
1171   // We return a bad value here to make sure that the exception is
1172   // forwarded before we look at the return value.
1173   THROW_(vmSymbols::java_lang_UnsatisfiedLinkError(), (void*)badAddress);
1174 }
1175 JNI_END
1176 
1177 address SharedRuntime::native_method_throw_unsatisfied_link_error_entry() {
1178   return CAST_FROM_FN_PTR(address, &throw_unsatisfied_link_error);
1179 }
1180 
1181 JRT_ENTRY_NO_ASYNC(void, SharedRuntime::register_finalizer(JavaThread* current, oopDesc* obj))
1182 #if INCLUDE_JVMCI
1183   if (!obj->klass()->has_finalizer()) {
1184     return;
1185   }
1186 #endif // INCLUDE_JVMCI
1187   assert(oopDesc::is_oop(obj), "must be a valid oop");
1188   assert(obj->klass()->has_finalizer(), "shouldn't be here otherwise");
1189   InstanceKlass::register_finalizer(instanceOop(obj), CHECK);
1190 JRT_END
1191 
1192 jlong SharedRuntime::get_java_tid(JavaThread* thread) {
1193   assert(thread != nullptr, "No thread");
1194   if (thread == nullptr) {
1195     return 0;
1196   }
1197   guarantee(Thread::current() != thread || thread->is_oop_safe(),
1198             "current cannot touch oops after its GC barrier is detached.");
1199   oop obj = thread->threadObj();
1200   return (obj == nullptr) ? 0 : java_lang_Thread::thread_id(obj);
1201 }
1202 
1203 /**
1204  * This function ought to be a void function, but cannot be because
1205  * it gets turned into a tail-call on sparc, which runs into dtrace bug
1206  * 6254741.  Once that is fixed we can remove the dummy return value.
1207  */
1208 int SharedRuntime::dtrace_object_alloc(oopDesc* o) {
1209   return dtrace_object_alloc(JavaThread::current(), o, o->size());
1210 }
1211 
1212 int SharedRuntime::dtrace_object_alloc(JavaThread* thread, oopDesc* o) {
1213   return dtrace_object_alloc(thread, o, o->size());
1214 }
1215 
1216 int SharedRuntime::dtrace_object_alloc(JavaThread* thread, oopDesc* o, size_t size) {
1217   assert(DTraceAllocProbes, "wrong call");
1218   Klass* klass = o->klass();
1219   Symbol* name = klass->name();
1220   HOTSPOT_OBJECT_ALLOC(
1221                    get_java_tid(thread),
1222                    (char *) name->bytes(), name->utf8_length(), size * HeapWordSize);
1223   return 0;
1224 }
1225 
1226 JRT_LEAF(int, SharedRuntime::dtrace_method_entry(
1227     JavaThread* current, Method* method))
1228   assert(current == JavaThread::current(), "pre-condition");
1229 
1230   assert(DTraceMethodProbes, "wrong call");
1231   Symbol* kname = method->klass_name();
1232   Symbol* name = method->name();
1233   Symbol* sig = method->signature();
1234   HOTSPOT_METHOD_ENTRY(
1235       get_java_tid(current),
1236       (char *) kname->bytes(), kname->utf8_length(),
1237       (char *) name->bytes(), name->utf8_length(),
1238       (char *) sig->bytes(), sig->utf8_length());
1239   return 0;
1240 JRT_END
1241 
1242 JRT_LEAF(int, SharedRuntime::dtrace_method_exit(
1243     JavaThread* current, Method* method))
1244   assert(current == JavaThread::current(), "pre-condition");
1245   assert(DTraceMethodProbes, "wrong call");
1246   Symbol* kname = method->klass_name();
1247   Symbol* name = method->name();
1248   Symbol* sig = method->signature();
1249   HOTSPOT_METHOD_RETURN(
1250       get_java_tid(current),
1251       (char *) kname->bytes(), kname->utf8_length(),
1252       (char *) name->bytes(), name->utf8_length(),
1253       (char *) sig->bytes(), sig->utf8_length());
1254   return 0;
1255 JRT_END
1256 
1257 
1258 // Finds receiver, CallInfo (i.e. receiver method), and calling bytecode)
1259 // for a call current in progress, i.e., arguments has been pushed on stack
1260 // put callee has not been invoked yet.  Used by: resolve virtual/static,
1261 // vtable updates, etc.  Caller frame must be compiled.
1262 Handle SharedRuntime::find_callee_info(Bytecodes::Code& bc, CallInfo& callinfo, TRAPS) {
1263   JavaThread* current = THREAD;
1264   ResourceMark rm(current);
1265 
1266   // last java frame on stack (which includes native call frames)
1267   vframeStream vfst(current, true);  // Do not skip and javaCalls
1268 
1269   return find_callee_info_helper(vfst, bc, callinfo, THREAD);
1270 }
1271 
1272 Method* SharedRuntime::extract_attached_method(vframeStream& vfst) {
1273   nmethod* caller = vfst.nm();
1274 
1275   address pc = vfst.frame_pc();
1276   { // Get call instruction under lock because another thread may be busy patching it.
1277     CompiledICLocker ic_locker(caller);
1278     return caller->attached_method_before_pc(pc);
1279   }
1280   return nullptr;
1281 }
1282 
1283 // Finds receiver, CallInfo (i.e. receiver method), and calling bytecode
1284 // for a call current in progress, i.e., arguments has been pushed on stack
1285 // but callee has not been invoked yet.  Caller frame must be compiled.
1286 Handle SharedRuntime::find_callee_info_helper(vframeStream& vfst, Bytecodes::Code& bc,
1287                                               CallInfo& callinfo, TRAPS) {
1288   Handle receiver;
1289   Handle nullHandle;  // create a handy null handle for exception returns
1290   JavaThread* current = THREAD;
1291 
1292   assert(!vfst.at_end(), "Java frame must exist");
1293 
1294   // Find caller and bci from vframe
1295   methodHandle caller(current, vfst.method());
1296   int          bci   = vfst.bci();
1297 
1298   if (caller->is_continuation_enter_intrinsic()) {
1299     bc = Bytecodes::_invokestatic;
1300     LinkResolver::resolve_continuation_enter(callinfo, CHECK_NH);
1301     return receiver;
1302   }
1303 
1304   Bytecode_invoke bytecode(caller, bci);
1305   int bytecode_index = bytecode.index();
1306   bc = bytecode.invoke_code();
1307 
1308   methodHandle attached_method(current, extract_attached_method(vfst));
1309   if (attached_method.not_null()) {
1310     Method* callee = bytecode.static_target(CHECK_NH);
1311     vmIntrinsics::ID id = callee->intrinsic_id();
1312     // When VM replaces MH.invokeBasic/linkTo* call with a direct/virtual call,
1313     // it attaches statically resolved method to the call site.
1314     if (MethodHandles::is_signature_polymorphic(id) &&
1315         MethodHandles::is_signature_polymorphic_intrinsic(id)) {
1316       bc = MethodHandles::signature_polymorphic_intrinsic_bytecode(id);
1317 
1318       // Adjust invocation mode according to the attached method.
1319       switch (bc) {
1320         case Bytecodes::_invokevirtual:
1321           if (attached_method->method_holder()->is_interface()) {
1322             bc = Bytecodes::_invokeinterface;
1323           }
1324           break;
1325         case Bytecodes::_invokeinterface:
1326           if (!attached_method->method_holder()->is_interface()) {
1327             bc = Bytecodes::_invokevirtual;
1328           }
1329           break;
1330         case Bytecodes::_invokehandle:
1331           if (!MethodHandles::is_signature_polymorphic_method(attached_method())) {
1332             bc = attached_method->is_static() ? Bytecodes::_invokestatic
1333                                               : Bytecodes::_invokevirtual;
1334           }
1335           break;
1336         default:
1337           break;
1338       }
1339     }
1340   }
1341 
1342   assert(bc != Bytecodes::_illegal, "not initialized");
1343 
1344   bool has_receiver = bc != Bytecodes::_invokestatic &&
1345                       bc != Bytecodes::_invokedynamic &&
1346                       bc != Bytecodes::_invokehandle;
1347 
1348   // Find receiver for non-static call
1349   if (has_receiver) {
1350     // This register map must be update since we need to find the receiver for
1351     // compiled frames. The receiver might be in a register.
1352     RegisterMap reg_map2(current,
1353                          RegisterMap::UpdateMap::include,
1354                          RegisterMap::ProcessFrames::include,
1355                          RegisterMap::WalkContinuation::skip);
1356     frame stubFrame   = current->last_frame();
1357     // Caller-frame is a compiled frame
1358     frame callerFrame = stubFrame.sender(&reg_map2);
1359 
1360     if (attached_method.is_null()) {
1361       Method* callee = bytecode.static_target(CHECK_NH);
1362       if (callee == nullptr) {
1363         THROW_(vmSymbols::java_lang_NoSuchMethodException(), nullHandle);
1364       }
1365     }
1366 
1367     // Retrieve from a compiled argument list
1368     receiver = Handle(current, callerFrame.retrieve_receiver(&reg_map2));
1369     assert(oopDesc::is_oop_or_null(receiver()), "");
1370 
1371     if (receiver.is_null()) {
1372       THROW_(vmSymbols::java_lang_NullPointerException(), nullHandle);
1373     }
1374   }
1375 
1376   // Resolve method
1377   if (attached_method.not_null()) {
1378     // Parameterized by attached method.
1379     LinkResolver::resolve_invoke(callinfo, receiver, attached_method, bc, CHECK_NH);
1380   } else {
1381     // Parameterized by bytecode.
1382     constantPoolHandle constants(current, caller->constants());
1383     LinkResolver::resolve_invoke(callinfo, receiver, constants, bytecode_index, bc, CHECK_NH);
1384   }
1385 
1386 #ifdef ASSERT
1387   // Check that the receiver klass is of the right subtype and that it is initialized for virtual calls
1388   if (has_receiver) {
1389     assert(receiver.not_null(), "should have thrown exception");
1390     Klass* receiver_klass = receiver->klass();
1391     Klass* rk = nullptr;
1392     if (attached_method.not_null()) {
1393       // In case there's resolved method attached, use its holder during the check.
1394       rk = attached_method->method_holder();
1395     } else {
1396       // Klass is already loaded.
1397       constantPoolHandle constants(current, caller->constants());
1398       rk = constants->klass_ref_at(bytecode_index, bc, CHECK_NH);
1399     }
1400     Klass* static_receiver_klass = rk;
1401     assert(receiver_klass->is_subtype_of(static_receiver_klass),
1402            "actual receiver must be subclass of static receiver klass");
1403     if (receiver_klass->is_instance_klass()) {
1404       if (InstanceKlass::cast(receiver_klass)->is_not_initialized()) {
1405         tty->print_cr("ERROR: Klass not yet initialized!!");
1406         receiver_klass->print();
1407       }
1408       assert(!InstanceKlass::cast(receiver_klass)->is_not_initialized(), "receiver_klass must be initialized");
1409     }
1410   }
1411 #endif
1412 
1413   return receiver;
1414 }
1415 
1416 methodHandle SharedRuntime::find_callee_method(TRAPS) {
1417   JavaThread* current = THREAD;
1418   ResourceMark rm(current);
1419   // We need first to check if any Java activations (compiled, interpreted)
1420   // exist on the stack since last JavaCall.  If not, we need
1421   // to get the target method from the JavaCall wrapper.
1422   vframeStream vfst(current, true);  // Do not skip any javaCalls
1423   methodHandle callee_method;
1424   if (vfst.at_end()) {
1425     // No Java frames were found on stack since we did the JavaCall.
1426     // Hence the stack can only contain an entry_frame.  We need to
1427     // find the target method from the stub frame.
1428     RegisterMap reg_map(current,
1429                         RegisterMap::UpdateMap::skip,
1430                         RegisterMap::ProcessFrames::include,
1431                         RegisterMap::WalkContinuation::skip);
1432     frame fr = current->last_frame();
1433     assert(fr.is_runtime_frame(), "must be a runtimeStub");
1434     fr = fr.sender(&reg_map);
1435     assert(fr.is_entry_frame(), "must be");
1436     // fr is now pointing to the entry frame.
1437     callee_method = methodHandle(current, fr.entry_frame_call_wrapper()->callee_method());
1438   } else {
1439     Bytecodes::Code bc;
1440     CallInfo callinfo;
1441     find_callee_info_helper(vfst, bc, callinfo, CHECK_(methodHandle()));
1442     callee_method = methodHandle(current, callinfo.selected_method());
1443   }
1444   assert(callee_method()->is_method(), "must be");
1445   return callee_method;
1446 }
1447 
1448 // Resolves a call.
1449 methodHandle SharedRuntime::resolve_helper(bool is_virtual, bool is_optimized, TRAPS) {
1450   JavaThread* current = THREAD;
1451   ResourceMark rm(current);
1452   RegisterMap cbl_map(current,
1453                       RegisterMap::UpdateMap::skip,
1454                       RegisterMap::ProcessFrames::include,
1455                       RegisterMap::WalkContinuation::skip);
1456   frame caller_frame = current->last_frame().sender(&cbl_map);
1457 
1458   CodeBlob* caller_cb = caller_frame.cb();
1459   guarantee(caller_cb != nullptr && caller_cb->is_nmethod(), "must be called from compiled method");
1460   nmethod* caller_nm = caller_cb->as_nmethod();
1461 
1462   // determine call info & receiver
1463   // note: a) receiver is null for static calls
1464   //       b) an exception is thrown if receiver is null for non-static calls
1465   CallInfo call_info;
1466   Bytecodes::Code invoke_code = Bytecodes::_illegal;
1467   Handle receiver = find_callee_info(invoke_code, call_info, CHECK_(methodHandle()));
1468 
1469   NoSafepointVerifier nsv;
1470 
1471   methodHandle callee_method(current, call_info.selected_method());
1472 
1473   assert((!is_virtual && invoke_code == Bytecodes::_invokestatic ) ||
1474          (!is_virtual && invoke_code == Bytecodes::_invokespecial) ||
1475          (!is_virtual && invoke_code == Bytecodes::_invokehandle ) ||
1476          (!is_virtual && invoke_code == Bytecodes::_invokedynamic) ||
1477          ( is_virtual && invoke_code != Bytecodes::_invokestatic ), "inconsistent bytecode");
1478 
1479   assert(!caller_nm->is_unloading(), "It should not be unloading");
1480 

1481   // tracing/debugging/statistics
1482   uint *addr = (is_optimized) ? (&_resolve_opt_virtual_ctr) :
1483                  (is_virtual) ? (&_resolve_virtual_ctr) :
1484                                 (&_resolve_static_ctr);
1485   AtomicAccess::inc(addr);
1486 
1487 #ifndef PRODUCT
1488   if (TraceCallFixup) {
1489     ResourceMark rm(current);
1490     tty->print("resolving %s%s (%s) call to",
1491                (is_optimized) ? "optimized " : "", (is_virtual) ? "virtual" : "static",
1492                Bytecodes::name(invoke_code));
1493     callee_method->print_short_name(tty);
1494     tty->print_cr(" at pc: " INTPTR_FORMAT " to code: " INTPTR_FORMAT,
1495                   p2i(caller_frame.pc()), p2i(callee_method->code()));
1496   }
1497 #endif
1498 
1499   if (invoke_code == Bytecodes::_invokestatic) {
1500     assert(callee_method->method_holder()->is_initialized() ||
1501            callee_method->method_holder()->is_reentrant_initialization(current),
1502            "invalid class initialization state for invoke_static");
1503     if (!VM_Version::supports_fast_class_init_checks() && callee_method->needs_clinit_barrier()) {
1504       // In order to keep class initialization check, do not patch call
1505       // site for static call when the class is not fully initialized.
1506       // Proper check is enforced by call site re-resolution on every invocation.
1507       //
1508       // When fast class initialization checks are supported (VM_Version::supports_fast_class_init_checks() == true),
1509       // explicit class initialization check is put in nmethod entry (VEP).
1510       assert(callee_method->method_holder()->is_linked(), "must be");
1511       return callee_method;
1512     }
1513   }
1514 
1515 
1516   // JSR 292 key invariant:
1517   // If the resolved method is a MethodHandle invoke target, the call
1518   // site must be a MethodHandle call site, because the lambda form might tail-call
1519   // leaving the stack in a state unknown to either caller or callee
1520 
1521   // Compute entry points. The computation of the entry points is independent of
1522   // patching the call.
1523 
1524   // Make sure the callee nmethod does not get deoptimized and removed before
1525   // we are done patching the code.
1526 
1527 
1528   CompiledICLocker ml(caller_nm);
1529   if (is_virtual && !is_optimized) {
1530     CompiledIC* inline_cache = CompiledIC_before(caller_nm, caller_frame.pc());
1531     inline_cache->update(&call_info, receiver->klass());
1532   } else {
1533     // Callsite is a direct call - set it to the destination method
1534     CompiledDirectCall* callsite = CompiledDirectCall::before(caller_frame.pc());
1535     callsite->set(callee_method);
1536   }
1537 
1538   return callee_method;
1539 }
1540 
1541 // Inline caches exist only in compiled code
1542 JRT_BLOCK_ENTRY(address, SharedRuntime::handle_wrong_method_ic_miss(JavaThread* current))
1543   PerfTraceTime timer(_perf_ic_miss_total_time);
1544 
1545 #ifdef ASSERT
1546   RegisterMap reg_map(current,
1547                       RegisterMap::UpdateMap::skip,
1548                       RegisterMap::ProcessFrames::include,
1549                       RegisterMap::WalkContinuation::skip);
1550   frame stub_frame = current->last_frame();
1551   assert(stub_frame.is_runtime_frame(), "sanity check");
1552   frame caller_frame = stub_frame.sender(&reg_map);
1553   assert(!caller_frame.is_interpreted_frame() && !caller_frame.is_entry_frame() && !caller_frame.is_upcall_stub_frame(), "unexpected frame");
1554 #endif /* ASSERT */
1555 
1556   methodHandle callee_method;
1557   JRT_BLOCK
1558     callee_method = SharedRuntime::handle_ic_miss_helper(CHECK_NULL);
1559     // Return Method* through TLS
1560     current->set_vm_result_metadata(callee_method());
1561   JRT_BLOCK_END
1562   // return compiled code entry point after potential safepoints
1563   return get_resolved_entry(current, callee_method);
1564 JRT_END
1565 
1566 
1567 // Handle call site that has been made non-entrant
1568 JRT_BLOCK_ENTRY(address, SharedRuntime::handle_wrong_method(JavaThread* current))
1569   PerfTraceTime timer(_perf_handle_wrong_method_total_time);
1570 
1571   // 6243940 We might end up in here if the callee is deoptimized
1572   // as we race to call it.  We don't want to take a safepoint if
1573   // the caller was interpreted because the caller frame will look
1574   // interpreted to the stack walkers and arguments are now
1575   // "compiled" so it is much better to make this transition
1576   // invisible to the stack walking code. The i2c path will
1577   // place the callee method in the callee_target. It is stashed
1578   // there because if we try and find the callee by normal means a
1579   // safepoint is possible and have trouble gc'ing the compiled args.
1580   RegisterMap reg_map(current,
1581                       RegisterMap::UpdateMap::skip,
1582                       RegisterMap::ProcessFrames::include,
1583                       RegisterMap::WalkContinuation::skip);
1584   frame stub_frame = current->last_frame();
1585   assert(stub_frame.is_runtime_frame(), "sanity check");
1586   frame caller_frame = stub_frame.sender(&reg_map);
1587 
1588   if (caller_frame.is_interpreted_frame() ||
1589       caller_frame.is_entry_frame() ||
1590       caller_frame.is_upcall_stub_frame()) {
1591     Method* callee = current->callee_target();
1592     guarantee(callee != nullptr && callee->is_method(), "bad handshake");
1593     current->set_vm_result_metadata(callee);
1594     current->set_callee_target(nullptr);
1595     if (caller_frame.is_entry_frame() && VM_Version::supports_fast_class_init_checks()) {
1596       // Bypass class initialization checks in c2i when caller is in native.
1597       // JNI calls to static methods don't have class initialization checks.
1598       // Fast class initialization checks are present in c2i adapters and call into
1599       // SharedRuntime::handle_wrong_method() on the slow path.
1600       //
1601       // JVM upcalls may land here as well, but there's a proper check present in
1602       // LinkResolver::resolve_static_call (called from JavaCalls::call_static),
1603       // so bypassing it in c2i adapter is benign.
1604       return callee->get_c2i_no_clinit_check_entry();
1605     } else {
1606       return callee->get_c2i_entry();
1607     }
1608   }
1609 
1610   // Must be compiled to compiled path which is safe to stackwalk
1611   methodHandle callee_method;
1612   JRT_BLOCK
1613     // Force resolving of caller (if we called from compiled frame)
1614     callee_method = SharedRuntime::reresolve_call_site(CHECK_NULL);
1615     current->set_vm_result_metadata(callee_method());
1616   JRT_BLOCK_END
1617   // return compiled code entry point after potential safepoints
1618   return get_resolved_entry(current, callee_method);
1619 JRT_END
1620 
1621 // Handle abstract method call
1622 JRT_BLOCK_ENTRY(address, SharedRuntime::handle_wrong_method_abstract(JavaThread* current))
1623   PerfTraceTime timer(_perf_handle_wrong_method_total_time);
1624 
1625   // Verbose error message for AbstractMethodError.
1626   // Get the called method from the invoke bytecode.
1627   vframeStream vfst(current, true);
1628   assert(!vfst.at_end(), "Java frame must exist");
1629   methodHandle caller(current, vfst.method());
1630   Bytecode_invoke invoke(caller, vfst.bci());
1631   DEBUG_ONLY( invoke.verify(); )
1632 
1633   // Find the compiled caller frame.
1634   RegisterMap reg_map(current,
1635                       RegisterMap::UpdateMap::include,
1636                       RegisterMap::ProcessFrames::include,
1637                       RegisterMap::WalkContinuation::skip);
1638   frame stubFrame = current->last_frame();
1639   assert(stubFrame.is_runtime_frame(), "must be");
1640   frame callerFrame = stubFrame.sender(&reg_map);
1641   assert(callerFrame.is_compiled_frame(), "must be");
1642 
1643   // Install exception and return forward entry.
1644   address res = SharedRuntime::throw_AbstractMethodError_entry();
1645   JRT_BLOCK
1646     methodHandle callee(current, invoke.static_target(current));
1647     if (!callee.is_null()) {
1648       oop recv = callerFrame.retrieve_receiver(&reg_map);
1649       Klass *recv_klass = (recv != nullptr) ? recv->klass() : nullptr;
1650       res = StubRoutines::forward_exception_entry();
1651       LinkResolver::throw_abstract_method_error(callee, recv_klass, CHECK_(res));
1652     }
1653   JRT_BLOCK_END
1654   return res;
1655 JRT_END
1656 
1657 // return verified_code_entry if interp_only_mode is not set for the current thread;
1658 // otherwise return c2i entry.
1659 address SharedRuntime::get_resolved_entry(JavaThread* current, methodHandle callee_method) {
1660   if (current->is_interp_only_mode() && !callee_method->is_special_native_intrinsic()) {
1661     // In interp_only_mode we need to go to the interpreted entry
1662     // The c2i won't patch in this mode -- see fixup_callers_callsite
1663     return callee_method->get_c2i_entry();
1664   }
1665   assert(callee_method->verified_code_entry() != nullptr, " Jump to zero!");
1666   return callee_method->verified_code_entry();
1667 }
1668 
1669 // resolve a static call and patch code
1670 JRT_BLOCK_ENTRY(address, SharedRuntime::resolve_static_call_C(JavaThread* current ))
1671   PerfTraceTime timer(_perf_resolve_static_total_time);
1672 
1673   methodHandle callee_method;
1674   bool enter_special = false;
1675   JRT_BLOCK
1676     callee_method = SharedRuntime::resolve_helper(false, false, CHECK_NULL);
1677     current->set_vm_result_metadata(callee_method());
1678   JRT_BLOCK_END
1679   // return compiled code entry point after potential safepoints
1680   return get_resolved_entry(current, callee_method);
1681 JRT_END
1682 
1683 // resolve virtual call and update inline cache to monomorphic
1684 JRT_BLOCK_ENTRY(address, SharedRuntime::resolve_virtual_call_C(JavaThread* current))
1685   PerfTraceTime timer(_perf_resolve_virtual_total_time);
1686 
1687   methodHandle callee_method;
1688   JRT_BLOCK
1689     callee_method = SharedRuntime::resolve_helper(true, false, CHECK_NULL);
1690     current->set_vm_result_metadata(callee_method());
1691   JRT_BLOCK_END
1692   // return compiled code entry point after potential safepoints
1693   return get_resolved_entry(current, callee_method);
1694 JRT_END
1695 
1696 
1697 // Resolve a virtual call that can be statically bound (e.g., always
1698 // monomorphic, so it has no inline cache).  Patch code to resolved target.
1699 JRT_BLOCK_ENTRY(address, SharedRuntime::resolve_opt_virtual_call_C(JavaThread* current))
1700   PerfTraceTime timer(_perf_resolve_opt_virtual_total_time);
1701 
1702   methodHandle callee_method;
1703   JRT_BLOCK
1704     callee_method = SharedRuntime::resolve_helper(true, true, CHECK_NULL);
1705     current->set_vm_result_metadata(callee_method());
1706   JRT_BLOCK_END
1707   // return compiled code entry point after potential safepoints
1708   return get_resolved_entry(current, callee_method);
1709 JRT_END
1710 
1711 methodHandle SharedRuntime::handle_ic_miss_helper(TRAPS) {
1712   JavaThread* current = THREAD;
1713   ResourceMark rm(current);
1714   CallInfo call_info;
1715   Bytecodes::Code bc;
1716 
1717   // receiver is null for static calls. An exception is thrown for null
1718   // receivers for non-static calls
1719   Handle receiver = find_callee_info(bc, call_info, CHECK_(methodHandle()));
1720 
1721   methodHandle callee_method(current, call_info.selected_method());
1722 

1723   AtomicAccess::inc(&_ic_miss_ctr);
1724 
1725 #ifndef PRODUCT
1726   // Statistics & Tracing
1727   if (TraceCallFixup) {
1728     ResourceMark rm(current);
1729     tty->print("IC miss (%s) call to", Bytecodes::name(bc));
1730     callee_method->print_short_name(tty);
1731     tty->print_cr(" code: " INTPTR_FORMAT, p2i(callee_method->code()));
1732   }
1733 
1734   if (ICMissHistogram) {
1735     MutexLocker m(VMStatistic_lock);
1736     RegisterMap reg_map(current,
1737                         RegisterMap::UpdateMap::skip,
1738                         RegisterMap::ProcessFrames::include,
1739                         RegisterMap::WalkContinuation::skip);
1740     frame f = current->last_frame().real_sender(&reg_map);// skip runtime stub
1741     // produce statistics under the lock
1742     trace_ic_miss(f.pc());
1743   }
1744 #endif
1745 
1746   // install an event collector so that when a vtable stub is created the
1747   // profiler can be notified via a DYNAMIC_CODE_GENERATED event. The
1748   // event can't be posted when the stub is created as locks are held
1749   // - instead the event will be deferred until the event collector goes
1750   // out of scope.
1751   JvmtiDynamicCodeEventCollector event_collector;
1752 
1753   // Update inline cache to megamorphic. Skip update if we are called from interpreted.
1754   RegisterMap reg_map(current,
1755                       RegisterMap::UpdateMap::skip,
1756                       RegisterMap::ProcessFrames::include,
1757                       RegisterMap::WalkContinuation::skip);
1758   frame caller_frame = current->last_frame().sender(&reg_map);
1759   CodeBlob* cb = caller_frame.cb();
1760   nmethod* caller_nm = cb->as_nmethod();
1761 
1762   CompiledICLocker ml(caller_nm);
1763   CompiledIC* inline_cache = CompiledIC_before(caller_nm, caller_frame.pc());
1764   inline_cache->update(&call_info, receiver()->klass());
1765 
1766   return callee_method;
1767 }
1768 
1769 //
1770 // Resets a call-site in compiled code so it will get resolved again.
1771 // This routines handles both virtual call sites, optimized virtual call
1772 // sites, and static call sites. Typically used to change a call sites
1773 // destination from compiled to interpreted.
1774 //
1775 methodHandle SharedRuntime::reresolve_call_site(TRAPS) {
1776   JavaThread* current = THREAD;
1777   ResourceMark rm(current);
1778   RegisterMap reg_map(current,
1779                       RegisterMap::UpdateMap::skip,
1780                       RegisterMap::ProcessFrames::include,
1781                       RegisterMap::WalkContinuation::skip);
1782   frame stub_frame = current->last_frame();
1783   assert(stub_frame.is_runtime_frame(), "must be a runtimeStub");
1784   frame caller = stub_frame.sender(&reg_map);
1785 
1786   // Do nothing if the frame isn't a live compiled frame.
1787   // nmethod could be deoptimized by the time we get here
1788   // so no update to the caller is needed.
1789 
1790   if ((caller.is_compiled_frame() && !caller.is_deoptimized_frame()) ||
1791       (caller.is_native_frame() && caller.cb()->as_nmethod()->method()->is_continuation_enter_intrinsic())) {
1792 
1793     address pc = caller.pc();
1794 
1795     nmethod* caller_nm = CodeCache::find_nmethod(pc);
1796     assert(caller_nm != nullptr, "did not find caller nmethod");
1797 
1798     // Default call_addr is the location of the "basic" call.
1799     // Determine the address of the call we a reresolving. With
1800     // Inline Caches we will always find a recognizable call.
1801     // With Inline Caches disabled we may or may not find a
1802     // recognizable call. We will always find a call for static
1803     // calls and for optimized virtual calls. For vanilla virtual
1804     // calls it depends on the state of the UseInlineCaches switch.
1805     //
1806     // With Inline Caches disabled we can get here for a virtual call
1807     // for two reasons:
1808     //   1 - calling an abstract method. The vtable for abstract methods
1809     //       will run us thru handle_wrong_method and we will eventually
1810     //       end up in the interpreter to throw the ame.
1811     //   2 - a racing deoptimization. We could be doing a vanilla vtable
1812     //       call and between the time we fetch the entry address and
1813     //       we jump to it the target gets deoptimized. Similar to 1
1814     //       we will wind up in the interprter (thru a c2i with c2).
1815     //
1816     CompiledICLocker ml(caller_nm);
1817     address call_addr = caller_nm->call_instruction_address(pc);
1818 
1819     if (call_addr != nullptr) {
1820       // On x86 the logic for finding a call instruction is blindly checking for a call opcode 5
1821       // bytes back in the instruction stream so we must also check for reloc info.
1822       RelocIterator iter(caller_nm, call_addr, call_addr+1);
1823       bool ret = iter.next(); // Get item
1824       if (ret) {
1825         switch (iter.type()) {
1826           case relocInfo::static_call_type:
1827           case relocInfo::opt_virtual_call_type: {
1828             CompiledDirectCall* cdc = CompiledDirectCall::at(call_addr);
1829             cdc->set_to_clean();
1830             break;
1831           }
1832 
1833           case relocInfo::virtual_call_type: {
1834             // compiled, dispatched call (which used to call an interpreted method)
1835             CompiledIC* inline_cache = CompiledIC_at(caller_nm, call_addr);
1836             inline_cache->set_to_clean();
1837             break;
1838           }
1839           default:
1840             break;
1841         }
1842       }
1843     }
1844   }
1845 
1846   methodHandle callee_method = find_callee_method(CHECK_(methodHandle()));
1847 


1848   AtomicAccess::inc(&_wrong_method_ctr);
1849 
1850 #ifndef PRODUCT
1851   if (TraceCallFixup) {
1852     ResourceMark rm(current);
1853     tty->print("handle_wrong_method reresolving call to");
1854     callee_method->print_short_name(tty);
1855     tty->print_cr(" code: " INTPTR_FORMAT, p2i(callee_method->code()));
1856   }
1857 #endif
1858 
1859   return callee_method;
1860 }
1861 
1862 address SharedRuntime::handle_unsafe_access(JavaThread* thread, address next_pc) {
1863   // The faulting unsafe accesses should be changed to throw the error
1864   // synchronously instead. Meanwhile the faulting instruction will be
1865   // skipped over (effectively turning it into a no-op) and an
1866   // asynchronous exception will be raised which the thread will
1867   // handle at a later point. If the instruction is a load it will
1868   // return garbage.
1869 
1870   // Request an async exception.
1871   thread->set_pending_unsafe_access_error();
1872 
1873   // Return address of next instruction to execute.
1874   return next_pc;
1875 }
1876 
1877 #ifdef ASSERT
1878 void SharedRuntime::check_member_name_argument_is_last_argument(const methodHandle& method,
1879                                                                 const BasicType* sig_bt,
1880                                                                 const VMRegPair* regs) {
1881   ResourceMark rm;
1882   const int total_args_passed = method->size_of_parameters();
1883   const VMRegPair*    regs_with_member_name = regs;
1884         VMRegPair* regs_without_member_name = NEW_RESOURCE_ARRAY(VMRegPair, total_args_passed - 1);
1885 
1886   const int member_arg_pos = total_args_passed - 1;
1887   assert(member_arg_pos >= 0 && member_arg_pos < total_args_passed, "oob");
1888   assert(sig_bt[member_arg_pos] == T_OBJECT, "dispatch argument must be an object");
1889 
1890   java_calling_convention(sig_bt, regs_without_member_name, total_args_passed - 1);
1891 
1892   for (int i = 0; i < member_arg_pos; i++) {
1893     VMReg a =    regs_with_member_name[i].first();
1894     VMReg b = regs_without_member_name[i].first();
1895     assert(a->value() == b->value(), "register allocation mismatch: a= %d, b= %d", a->value(), b->value());
1896   }
1897   assert(regs_with_member_name[member_arg_pos].first()->is_valid(), "bad member arg");
1898 }
1899 #endif
1900 
1901 // ---------------------------------------------------------------------------
1902 // We are calling the interpreter via a c2i. Normally this would mean that
1903 // we were called by a compiled method. However we could have lost a race
1904 // where we went int -> i2c -> c2i and so the caller could in fact be
1905 // interpreted. If the caller is compiled we attempt to patch the caller
1906 // so he no longer calls into the interpreter.
1907 JRT_LEAF(void, SharedRuntime::fixup_callers_callsite(Method* method, address caller_pc))
1908   AARCH64_PORT_ONLY(assert(pauth_ptr_is_raw(caller_pc), "should be raw"));
1909 
1910   // It's possible that deoptimization can occur at a call site which hasn't
1911   // been resolved yet, in which case this function will be called from
1912   // an nmethod that has been patched for deopt and we can ignore the
1913   // request for a fixup.
1914   // Also it is possible that we lost a race in that from_compiled_entry
1915   // is now back to the i2c in that case we don't need to patch and if
1916   // we did we'd leap into space because the callsite needs to use
1917   // "to interpreter" stub in order to load up the Method*. Don't
1918   // ask me how I know this...
1919 
1920   // Result from nmethod::is_unloading is not stable across safepoints.
1921   NoSafepointVerifier nsv;
1922 
1923   nmethod* callee = method->code();
1924   if (callee == nullptr) {
1925     return;
1926   }
1927 
1928   // write lock needed because we might patch call site by set_to_clean()
1929   // and is_unloading() can modify nmethod's state
1930   MACOS_AARCH64_ONLY(ThreadWXEnable __wx(WXWrite, JavaThread::current()));
1931 
1932   CodeBlob* cb = CodeCache::find_blob(caller_pc);
1933   if (cb == nullptr || !cb->is_nmethod() || !callee->is_in_use() || callee->is_unloading()) {
1934     return;
1935   }
1936 
1937   // The check above makes sure this is an nmethod.
1938   nmethod* caller = cb->as_nmethod();
1939 
1940   // Get the return PC for the passed caller PC.
1941   address return_pc = caller_pc + frame::pc_return_offset;
1942 
1943   if (!caller->is_in_use() || !NativeCall::is_call_before(return_pc)) {
1944     return;
1945   }
1946 
1947   // Expect to find a native call there (unless it was no-inline cache vtable dispatch)
1948   CompiledICLocker ic_locker(caller);
1949   ResourceMark rm;
1950 
1951   // If we got here through a static call or opt_virtual call, then we know where the
1952   // call address would be; let's peek at it
1953   address callsite_addr = (address)nativeCall_before(return_pc);
1954   RelocIterator iter(caller, callsite_addr, callsite_addr + 1);
1955   if (!iter.next()) {
1956     // No reloc entry found; not a static or optimized virtual call
1957     return;
1958   }
1959 
1960   relocInfo::relocType type = iter.reloc()->type();
1961   if (type != relocInfo::static_call_type &&
1962       type != relocInfo::opt_virtual_call_type) {
1963     return;
1964   }
1965 
1966   CompiledDirectCall* callsite = CompiledDirectCall::before(return_pc);
1967   callsite->set_to_clean();
1968 JRT_END
1969 
1970 
1971 // same as JVM_Arraycopy, but called directly from compiled code
1972 JRT_ENTRY(void, SharedRuntime::slow_arraycopy_C(oopDesc* src,  jint src_pos,
1973                                                 oopDesc* dest, jint dest_pos,
1974                                                 jint length,
1975                                                 JavaThread* current)) {
1976 #ifndef PRODUCT
1977   _slow_array_copy_ctr++;
1978 #endif
1979   // Check if we have null pointers
1980   if (src == nullptr || dest == nullptr) {
1981     THROW(vmSymbols::java_lang_NullPointerException());
1982   }
1983   // Do the copy.  The casts to arrayOop are necessary to the copy_array API,
1984   // even though the copy_array API also performs dynamic checks to ensure
1985   // that src and dest are truly arrays (and are conformable).
1986   // The copy_array mechanism is awkward and could be removed, but
1987   // the compilers don't call this function except as a last resort,
1988   // so it probably doesn't matter.
1989   src->klass()->copy_array((arrayOopDesc*)src, src_pos,
1990                                         (arrayOopDesc*)dest, dest_pos,
1991                                         length, current);
1992 }
1993 JRT_END
1994 
1995 // The caller of generate_class_cast_message() (or one of its callers)
1996 // must use a ResourceMark in order to correctly free the result.
1997 char* SharedRuntime::generate_class_cast_message(
1998     JavaThread* thread, Klass* caster_klass) {
1999 
2000   // Get target class name from the checkcast instruction
2001   vframeStream vfst(thread, true);
2002   assert(!vfst.at_end(), "Java frame must exist");
2003   Bytecode_checkcast cc(vfst.method(), vfst.method()->bcp_from(vfst.bci()));
2004   constantPoolHandle cpool(thread, vfst.method()->constants());
2005   Klass* target_klass = ConstantPool::klass_at_if_loaded(cpool, cc.index());
2006   Symbol* target_klass_name = nullptr;
2007   if (target_klass == nullptr) {
2008     // This klass should be resolved, but just in case, get the name in the klass slot.
2009     target_klass_name = cpool->klass_name_at(cc.index());
2010   }
2011   return generate_class_cast_message(caster_klass, target_klass, target_klass_name);
2012 }
2013 
2014 
2015 // The caller of generate_class_cast_message() (or one of its callers)
2016 // must use a ResourceMark in order to correctly free the result.
2017 char* SharedRuntime::generate_class_cast_message(
2018     Klass* caster_klass, Klass* target_klass, Symbol* target_klass_name) {
2019   const char* caster_name = caster_klass->external_name();
2020 
2021   assert(target_klass != nullptr || target_klass_name != nullptr, "one must be provided");
2022   const char* target_name = target_klass == nullptr ? target_klass_name->as_klass_external_name() :
2023                                                    target_klass->external_name();
2024 
2025   size_t msglen = strlen(caster_name) + strlen("class ") + strlen(" cannot be cast to class ") + strlen(target_name) + 1;
2026 
2027   const char* caster_klass_description = "";
2028   const char* target_klass_description = "";
2029   const char* klass_separator = "";
2030   if (target_klass != nullptr && caster_klass->module() == target_klass->module()) {
2031     caster_klass_description = caster_klass->joint_in_module_of_loader(target_klass);
2032   } else {
2033     caster_klass_description = caster_klass->class_in_module_of_loader();
2034     target_klass_description = (target_klass != nullptr) ? target_klass->class_in_module_of_loader() : "";
2035     klass_separator = (target_klass != nullptr) ? "; " : "";
2036   }
2037 
2038   // add 3 for parenthesis and preceding space
2039   msglen += strlen(caster_klass_description) + strlen(target_klass_description) + strlen(klass_separator) + 3;
2040 
2041   char* message = NEW_RESOURCE_ARRAY_RETURN_NULL(char, msglen);
2042   if (message == nullptr) {
2043     // Shouldn't happen, but don't cause even more problems if it does
2044     message = const_cast<char*>(caster_klass->external_name());
2045   } else {
2046     jio_snprintf(message,
2047                  msglen,
2048                  "class %s cannot be cast to class %s (%s%s%s)",
2049                  caster_name,
2050                  target_name,
2051                  caster_klass_description,
2052                  klass_separator,
2053                  target_klass_description
2054                  );
2055   }
2056   return message;
2057 }
2058 
2059 JRT_LEAF(void, SharedRuntime::reguard_yellow_pages())
2060   (void) JavaThread::current()->stack_overflow_state()->reguard_stack();
2061 JRT_END
2062 
2063 void SharedRuntime::monitor_enter_helper(oopDesc* obj, BasicLock* lock, JavaThread* current) {
2064   if (!SafepointSynchronize::is_synchronizing()) {
2065     // Only try quick_enter() if we're not trying to reach a safepoint
2066     // so that the calling thread reaches the safepoint more quickly.
2067     if (ObjectSynchronizer::quick_enter(obj, lock, current)) {
2068       return;
2069     }
2070   }
2071   // NO_ASYNC required because an async exception on the state transition destructor
2072   // would leave you with the lock held and it would never be released.
2073   // The normal monitorenter NullPointerException is thrown without acquiring a lock
2074   // and the model is that an exception implies the method failed.
2075   JRT_BLOCK_NO_ASYNC
2076   Handle h_obj(THREAD, obj);
2077   ObjectSynchronizer::enter(h_obj, lock, current);
2078   assert(!HAS_PENDING_EXCEPTION, "Should have no exception here");
2079   JRT_BLOCK_END
2080 }
2081 
2082 // Handles the uncommon case in locking, i.e., contention or an inflated lock.
2083 JRT_BLOCK_ENTRY(void, SharedRuntime::complete_monitor_locking_C(oopDesc* obj, BasicLock* lock, JavaThread* current))
2084   SharedRuntime::monitor_enter_helper(obj, lock, current);
2085 JRT_END
2086 
2087 void SharedRuntime::monitor_exit_helper(oopDesc* obj, BasicLock* lock, JavaThread* current) {
2088   assert(JavaThread::current() == current, "invariant");
2089   // Exit must be non-blocking, and therefore no exceptions can be thrown.
2090   ExceptionMark em(current);
2091 
2092   // Check if C2_MacroAssembler::fast_unlock() or
2093   // C2_MacroAssembler::fast_unlock() unlocked an inflated
2094   // monitor before going slow path.  Since there is no safepoint
2095   // polling when calling into the VM, we can be sure that the monitor
2096   // hasn't been deallocated.
2097   ObjectMonitor* m = current->unlocked_inflated_monitor();
2098   if (m != nullptr) {
2099     assert(!m->has_owner(current), "must be");
2100     current->clear_unlocked_inflated_monitor();
2101 
2102     // We need to reacquire the lock before we can call ObjectSynchronizer::exit().
2103     if (!m->try_enter(current, /*check_for_recursion*/ false)) {
2104       // Some other thread acquired the lock (or the monitor was
2105       // deflated). Either way we are done.
2106       return;
2107     }
2108   }
2109 
2110   // The object could become unlocked through a JNI call, which we have no other checks for.
2111   // Give a fatal message if CheckJNICalls. Otherwise we ignore it.
2112   if (obj->is_unlocked()) {
2113     if (CheckJNICalls) {
2114       fatal("Object has been unlocked by JNI");
2115     }
2116     return;
2117   }
2118   ObjectSynchronizer::exit(obj, lock, current);
2119 }
2120 
2121 // Handles the uncommon cases of monitor unlocking in compiled code
2122 JRT_LEAF(void, SharedRuntime::complete_monitor_unlocking_C(oopDesc* obj, BasicLock* lock, JavaThread* current))
2123   assert(current == JavaThread::current(), "pre-condition");
2124   SharedRuntime::monitor_exit_helper(obj, lock, current);
2125 JRT_END
2126 
2127 #ifndef PRODUCT
2128 
2129 void SharedRuntime::print_statistics() {
2130   ttyLocker ttyl;
2131   if (xtty != nullptr)  xtty->head("statistics type='SharedRuntime'");
2132 
2133   SharedRuntime::print_ic_miss_histogram_on(tty);
2134   SharedRuntime::print_counters_on(tty);
2135   AdapterHandlerLibrary::print_statistics_on(tty);
































2136 
2137   if (xtty != nullptr)  xtty->tail("statistics");
2138 }
2139 
2140 //void SharedRuntime::print_counters_on(outputStream* st) {
2141 //  // Dump the JRT_ENTRY counters
2142 //  if (_new_instance_ctr) st->print_cr("%5u new instance requires GC", _new_instance_ctr);
2143 //  if (_new_array_ctr)    st->print_cr("%5u new array requires GC", _new_array_ctr);
2144 //  if (_multi2_ctr)       st->print_cr("%5u multianewarray 2 dim", _multi2_ctr);
2145 //  if (_multi3_ctr)       st->print_cr("%5u multianewarray 3 dim", _multi3_ctr);
2146 //  if (_multi4_ctr)       st->print_cr("%5u multianewarray 4 dim", _multi4_ctr);
2147 //  if (_multi5_ctr)       st->print_cr("%5u multianewarray 5 dim", _multi5_ctr);
2148 //
2149 //  st->print_cr("%5u inline cache miss in compiled", _ic_miss_ctr);
2150 //  st->print_cr("%5u wrong method", _wrong_method_ctr);
2151 //  st->print_cr("%5u unresolved static call site", _resolve_static_ctr);
2152 //  st->print_cr("%5u unresolved virtual call site", _resolve_virtual_ctr);
2153 //  st->print_cr("%5u unresolved opt virtual call site", _resolve_opt_virtual_ctr);
2154 //
2155 //  if (_mon_enter_stub_ctr)       st->print_cr("%5u monitor enter stub", _mon_enter_stub_ctr);
2156 //  if (_mon_exit_stub_ctr)        st->print_cr("%5u monitor exit stub", _mon_exit_stub_ctr);
2157 //  if (_mon_enter_ctr)            st->print_cr("%5u monitor enter slow", _mon_enter_ctr);
2158 //  if (_mon_exit_ctr)             st->print_cr("%5u monitor exit slow", _mon_exit_ctr);
2159 //  if (_partial_subtype_ctr)      st->print_cr("%5u slow partial subtype", _partial_subtype_ctr);
2160 //  if (_jbyte_array_copy_ctr)     st->print_cr("%5u byte array copies", _jbyte_array_copy_ctr);
2161 //  if (_jshort_array_copy_ctr)    st->print_cr("%5u short array copies", _jshort_array_copy_ctr);
2162 //  if (_jint_array_copy_ctr)      st->print_cr("%5u int array copies", _jint_array_copy_ctr);
2163 //  if (_jlong_array_copy_ctr)     st->print_cr("%5u long array copies", _jlong_array_copy_ctr);
2164 //  if (_oop_array_copy_ctr)       st->print_cr("%5u oop array copies", _oop_array_copy_ctr);
2165 //  if (_checkcast_array_copy_ctr) st->print_cr("%5u checkcast array copies", _checkcast_array_copy_ctr);
2166 //  if (_unsafe_array_copy_ctr)    st->print_cr("%5u unsafe array copies", _unsafe_array_copy_ctr);
2167 //  if (_generic_array_copy_ctr)   st->print_cr("%5u generic array copies", _generic_array_copy_ctr);
2168 //  if (_slow_array_copy_ctr)      st->print_cr("%5u slow array copies", _slow_array_copy_ctr);
2169 //  if (_find_handler_ctr)         st->print_cr("%5u find exception handler", _find_handler_ctr);
2170 //  if (_rethrow_ctr)              st->print_cr("%5u rethrow handler", _rethrow_ctr);
2171 //  if (_unsafe_set_memory_ctr) tty->print_cr("%5u unsafe set memorys", _unsafe_set_memory_ctr);
2172 //}
2173 
2174 inline double percent(int64_t x, int64_t y) {
2175   return 100.0 * (double)x / (double)MAX2(y, (int64_t)1);
2176 }
2177 
2178 class MethodArityHistogram {
2179  public:
2180   enum { MAX_ARITY = 256 };
2181  private:
2182   static uint64_t _arity_histogram[MAX_ARITY]; // histogram of #args
2183   static uint64_t _size_histogram[MAX_ARITY];  // histogram of arg size in words
2184   static uint64_t _total_compiled_calls;
2185   static uint64_t _max_compiled_calls_per_method;
2186   static int _max_arity;                       // max. arity seen
2187   static int _max_size;                        // max. arg size seen
2188 
2189   static void add_method_to_histogram(nmethod* nm) {
2190     Method* method = (nm == nullptr) ? nullptr : nm->method();
2191     if (method != nullptr) {
2192       ArgumentCount args(method->signature());
2193       int arity   = args.size() + (method->is_static() ? 0 : 1);
2194       int argsize = method->size_of_parameters();
2195       arity   = MIN2(arity, MAX_ARITY-1);
2196       argsize = MIN2(argsize, MAX_ARITY-1);
2197       uint64_t count = (uint64_t)method->compiled_invocation_count();
2198       _max_compiled_calls_per_method = count > _max_compiled_calls_per_method ? count : _max_compiled_calls_per_method;
2199       _total_compiled_calls    += count;
2200       _arity_histogram[arity]  += count;
2201       _size_histogram[argsize] += count;
2202       _max_arity = MAX2(_max_arity, arity);
2203       _max_size  = MAX2(_max_size, argsize);
2204     }
2205   }
2206 
2207   void print_histogram_helper(int n, uint64_t* histo, const char* name) {
2208     const int N = MIN2(9, n);
2209     double sum = 0;
2210     double weighted_sum = 0;
2211     for (int i = 0; i <= n; i++) { sum += (double)histo[i]; weighted_sum += (double)(i*histo[i]); }
2212     if (sum >= 1) { // prevent divide by zero or divide overflow
2213       double rest = sum;
2214       double percent = sum / 100;
2215       for (int i = 0; i <= N; i++) {
2216         rest -= (double)histo[i];
2217         tty->print_cr("%4d: " UINT64_FORMAT_W(12) " (%5.1f%%)", i, histo[i], (double)histo[i] / percent);
2218       }
2219       tty->print_cr("rest: " INT64_FORMAT_W(12) " (%5.1f%%)", (int64_t)rest, rest / percent);
2220       tty->print_cr("(avg. %s = %3.1f, max = %d)", name, weighted_sum / sum, n);
2221       tty->print_cr("(total # of compiled calls = " INT64_FORMAT_W(14) ")", _total_compiled_calls);
2222       tty->print_cr("(max # of compiled calls   = " INT64_FORMAT_W(14) ")", _max_compiled_calls_per_method);
2223     } else {
2224       tty->print_cr("Histogram generation failed for %s. n = %d, sum = %7.5f", name, n, sum);
2225     }
2226   }
2227 
2228   void print_histogram() {
2229     tty->print_cr("\nHistogram of call arity (incl. rcvr, calls to compiled methods only):");
2230     print_histogram_helper(_max_arity, _arity_histogram, "arity");
2231     tty->print_cr("\nHistogram of parameter block size (in words, incl. rcvr):");
2232     print_histogram_helper(_max_size, _size_histogram, "size");
2233     tty->cr();
2234   }
2235 
2236  public:
2237   MethodArityHistogram() {
2238     // Take the Compile_lock to protect against changes in the CodeBlob structures
2239     MutexLocker mu1(Compile_lock, Mutex::_safepoint_check_flag);
2240     // Take the CodeCache_lock to protect against changes in the CodeHeap structure
2241     MutexLocker mu2(CodeCache_lock, Mutex::_no_safepoint_check_flag);
2242     _max_arity = _max_size = 0;
2243     _total_compiled_calls = 0;
2244     _max_compiled_calls_per_method = 0;
2245     for (int i = 0; i < MAX_ARITY; i++) _arity_histogram[i] = _size_histogram[i] = 0;
2246     CodeCache::nmethods_do(add_method_to_histogram);
2247     print_histogram();
2248   }
2249 };
2250 
2251 uint64_t MethodArityHistogram::_arity_histogram[MethodArityHistogram::MAX_ARITY];
2252 uint64_t MethodArityHistogram::_size_histogram[MethodArityHistogram::MAX_ARITY];
2253 uint64_t MethodArityHistogram::_total_compiled_calls;
2254 uint64_t MethodArityHistogram::_max_compiled_calls_per_method;
2255 int MethodArityHistogram::_max_arity;
2256 int MethodArityHistogram::_max_size;
2257 
2258 void SharedRuntime::print_call_statistics_on(outputStream* st) {
2259   tty->print_cr("Calls from compiled code:");
2260   int64_t total  = _nof_normal_calls + _nof_interface_calls + _nof_static_calls;
2261   int64_t mono_c = _nof_normal_calls - _nof_megamorphic_calls;
2262   int64_t mono_i = _nof_interface_calls;
2263   tty->print_cr("\t" INT64_FORMAT_W(12) " (100%%)  total non-inlined   ", total);
2264   tty->print_cr("\t" INT64_FORMAT_W(12) " (%4.1f%%) |- virtual calls       ", _nof_normal_calls, percent(_nof_normal_calls, total));
2265   tty->print_cr("\t" INT64_FORMAT_W(12) " (%4.0f%%) |  |- inlined          ", _nof_inlined_calls, percent(_nof_inlined_calls, _nof_normal_calls));
2266   tty->print_cr("\t" INT64_FORMAT_W(12) " (%4.0f%%) |  |- monomorphic      ", mono_c, percent(mono_c, _nof_normal_calls));
2267   tty->print_cr("\t" INT64_FORMAT_W(12) " (%4.0f%%) |  |- megamorphic      ", _nof_megamorphic_calls, percent(_nof_megamorphic_calls, _nof_normal_calls));
2268   tty->print_cr("\t" INT64_FORMAT_W(12) " (%4.1f%%) |- interface calls     ", _nof_interface_calls, percent(_nof_interface_calls, total));
2269   tty->print_cr("\t" INT64_FORMAT_W(12) " (%4.0f%%) |  |- inlined          ", _nof_inlined_interface_calls, percent(_nof_inlined_interface_calls, _nof_interface_calls));
2270   tty->print_cr("\t" INT64_FORMAT_W(12) " (%4.0f%%) |  |- monomorphic      ", mono_i, percent(mono_i, _nof_interface_calls));
2271   tty->print_cr("\t" INT64_FORMAT_W(12) " (%4.1f%%) |- static/special calls", _nof_static_calls, percent(_nof_static_calls, total));
2272   tty->print_cr("\t" INT64_FORMAT_W(12) " (%4.0f%%) |  |- inlined          ", _nof_inlined_static_calls, percent(_nof_inlined_static_calls, _nof_static_calls));
2273   tty->cr();
2274   tty->print_cr("Note 1: counter updates are not MT-safe.");
2275   tty->print_cr("Note 2: %% in major categories are relative to total non-inlined calls;");
2276   tty->print_cr("        %% in nested categories are relative to their category");
2277   tty->print_cr("        (and thus add up to more than 100%% with inlining)");
2278   tty->cr();
2279 
2280   MethodArityHistogram h;
2281 }
2282 #endif
2283 
2284 #ifndef PRODUCT
2285 static int _lookups; // number of calls to lookup
2286 static int _equals;  // number of buckets checked with matching hash
2287 static int _archived_hits; // number of successful lookups in archived table
2288 static int _runtime_hits;  // number of successful lookups in runtime table
2289 #endif
2290 
2291 // A simple wrapper class around the calling convention information
2292 // that allows sharing of adapters for the same calling convention.
2293 class AdapterFingerPrint : public MetaspaceObj {
2294  private:
2295   enum {
2296     _basic_type_bits = 4,
2297     _basic_type_mask = right_n_bits(_basic_type_bits),
2298     _basic_types_per_int = BitsPerInt / _basic_type_bits,
2299   };
2300   // TO DO:  Consider integrating this with a more global scheme for compressing signatures.
2301   // For now, 4 bits per components (plus T_VOID gaps after double/long) is not excessive.
2302 
2303   int _length;
2304 
2305   static int data_offset() { return sizeof(AdapterFingerPrint); }
2306   int* data_pointer() {
2307     return (int*)((address)this + data_offset());
2308   }
2309 
2310   // Private construtor. Use allocate() to get an instance.
2311   AdapterFingerPrint(int total_args_passed, BasicType* sig_bt, int len) {
2312     int* data = data_pointer();
2313     // Pack the BasicTypes with 8 per int
2314     assert(len == length(total_args_passed), "sanity");
2315     _length = len;
2316     int sig_index = 0;
2317     for (int index = 0; index < _length; index++) {
2318       int value = 0;
2319       for (int byte = 0; sig_index < total_args_passed && byte < _basic_types_per_int; byte++) {
2320         int bt = adapter_encoding(sig_bt[sig_index++]);
2321         assert((bt & _basic_type_mask) == bt, "must fit in 4 bits");
2322         value = (value << _basic_type_bits) | bt;
2323       }
2324       data[index] = value;
2325     }
2326   }
2327 
2328   // Call deallocate instead
2329   ~AdapterFingerPrint() {
2330     ShouldNotCallThis();
2331   }
2332 
2333   static int length(int total_args) {
2334     return (total_args + (_basic_types_per_int-1)) / _basic_types_per_int;
2335   }
2336 
2337   static int compute_size_in_words(int len) {
2338     return (int)heap_word_size(sizeof(AdapterFingerPrint) + (len * sizeof(int)));
2339   }
2340 
2341   // Remap BasicTypes that are handled equivalently by the adapters.
2342   // These are correct for the current system but someday it might be
2343   // necessary to make this mapping platform dependent.
2344   static int adapter_encoding(BasicType in) {
2345     switch (in) {
2346       case T_BOOLEAN:
2347       case T_BYTE:
2348       case T_SHORT:
2349       case T_CHAR:
2350         // There are all promoted to T_INT in the calling convention
2351         return T_INT;
2352 
2353       case T_OBJECT:
2354       case T_ARRAY:
2355         // In other words, we assume that any register good enough for
2356         // an int or long is good enough for a managed pointer.
2357 #ifdef _LP64
2358         return T_LONG;
2359 #else
2360         return T_INT;
2361 #endif
2362 
2363       case T_INT:
2364       case T_LONG:
2365       case T_FLOAT:
2366       case T_DOUBLE:
2367       case T_VOID:
2368         return in;
2369 
2370       default:
2371         ShouldNotReachHere();
2372         return T_CONFLICT;
2373     }
2374   }
2375 
2376   void* operator new(size_t size, size_t fp_size) throw() {
2377     assert(fp_size >= size, "sanity check");
2378     void* p = AllocateHeap(fp_size, mtCode);
2379     memset(p, 0, fp_size);
2380     return p;
2381   }
2382 
2383   template<typename Function>
2384   void iterate_args(Function function) {
2385     for (int i = 0; i < length(); i++) {
2386       unsigned val = (unsigned)value(i);
2387       // args are packed so that first/lower arguments are in the highest
2388       // bits of each int value, so iterate from highest to the lowest
2389       for (int j = 32 - _basic_type_bits; j >= 0; j -= _basic_type_bits) {
2390         unsigned v = (val >> j) & _basic_type_mask;
2391         if (v == 0) {
2392           continue;
2393         }
2394         function(v);
2395       }
2396     }
2397   }
2398 
2399  public:
2400   static AdapterFingerPrint* allocate(int total_args_passed, BasicType* sig_bt) {
2401     int len = length(total_args_passed);
2402     int size_in_bytes = BytesPerWord * compute_size_in_words(len);
2403     AdapterFingerPrint* afp = new (size_in_bytes) AdapterFingerPrint(total_args_passed, sig_bt, len);
2404     assert((afp->size() * BytesPerWord) == size_in_bytes, "should match");
2405     return afp;
2406   }
2407 
2408   static void deallocate(AdapterFingerPrint* fp) {
2409     FreeHeap(fp);
2410   }
2411 
2412   int value(int index) {
2413     int* data = data_pointer();
2414     return data[index];
2415   }
2416 
2417   int length() {
2418     return _length;
2419   }
2420 
2421   unsigned int compute_hash() {
2422     int hash = 0;
2423     for (int i = 0; i < length(); i++) {
2424       int v = value(i);
2425       //Add arithmetic operation to the hash, like +3 to improve hashing
2426       hash = ((hash << 8) ^ v ^ (hash >> 5)) + 3;
2427     }
2428     return (unsigned int)hash;
2429   }
2430 
2431   const char* as_string() {
2432     stringStream st;
2433     st.print("0x");
2434     for (int i = 0; i < length(); i++) {
2435       st.print("%x", value(i));
2436     }
2437     return st.as_string();
2438   }
2439 
2440   const char* as_basic_args_string() {
2441     stringStream st;
2442     bool long_prev = false;
2443     iterate_args([&] (int arg) {
2444       if (long_prev) {
2445         long_prev = false;
2446         if (arg == T_VOID) {
2447           st.print("J");
2448         } else {
2449           st.print("L");
2450         }
2451       }
2452       switch (arg) {
2453         case T_INT:    st.print("I");    break;
2454         case T_LONG:   long_prev = true; break;
2455         case T_FLOAT:  st.print("F");    break;
2456         case T_DOUBLE: st.print("D");    break;
2457         case T_VOID:   break;
2458         default: ShouldNotReachHere();
2459       }
2460     });
2461     if (long_prev) {
2462       st.print("L");
2463     }
2464     return st.as_string();
2465   }
2466 
2467   BasicType* as_basic_type(int& nargs) {
2468     nargs = 0;
2469     GrowableArray<BasicType> btarray;
2470     bool long_prev = false;
2471 
2472     iterate_args([&] (int arg) {
2473       if (long_prev) {
2474         long_prev = false;
2475         if (arg == T_VOID) {
2476           btarray.append(T_LONG);
2477         } else {
2478           btarray.append(T_OBJECT); // it could be T_ARRAY; it shouldn't matter
2479         }
2480       }
2481       switch (arg) {
2482         case T_INT: // fallthrough
2483         case T_FLOAT: // fallthrough
2484         case T_DOUBLE:
2485         case T_VOID:
2486           btarray.append((BasicType)arg);
2487           break;
2488         case T_LONG:
2489           long_prev = true;
2490           break;
2491         default: ShouldNotReachHere();
2492       }
2493     });
2494 
2495     if (long_prev) {
2496       btarray.append(T_OBJECT);
2497     }
2498 
2499     nargs = btarray.length();
2500     BasicType* sig_bt = NEW_RESOURCE_ARRAY(BasicType, nargs);
2501     int index = 0;
2502     GrowableArrayIterator<BasicType> iter = btarray.begin();
2503     while (iter != btarray.end()) {
2504       sig_bt[index++] = *iter;
2505       ++iter;
2506     }
2507     assert(index == btarray.length(), "sanity check");
2508 #ifdef ASSERT
2509     {
2510       AdapterFingerPrint* compare_fp = AdapterFingerPrint::allocate(nargs, sig_bt);
2511       assert(this->equals(compare_fp), "sanity check");
2512       AdapterFingerPrint::deallocate(compare_fp);
2513     }
2514 #endif
2515     return sig_bt;
2516   }
2517 
2518   bool equals(AdapterFingerPrint* other) {
2519     if (other->_length != _length) {
2520       return false;
2521     } else {
2522       for (int i = 0; i < _length; i++) {
2523         if (value(i) != other->value(i)) {
2524           return false;
2525         }
2526       }
2527     }
2528     return true;
2529   }
2530 
2531   // methods required by virtue of being a MetaspaceObj
2532   void metaspace_pointers_do(MetaspaceClosure* it) { return; /* nothing to do here */ }
2533   int size() const { return compute_size_in_words(_length); }
2534   MetaspaceObj::Type type() const { return AdapterFingerPrintType; }
2535 
2536   static bool equals(AdapterFingerPrint* const& fp1, AdapterFingerPrint* const& fp2) {
2537     NOT_PRODUCT(_equals++);
2538     return fp1->equals(fp2);
2539   }
2540 
2541   static unsigned int compute_hash(AdapterFingerPrint* const& fp) {
2542     return fp->compute_hash();
2543   }
2544 };
2545 
2546 #if INCLUDE_CDS
2547 static inline bool adapter_fp_equals_compact_hashtable_entry(AdapterHandlerEntry* entry, AdapterFingerPrint* fp, int len_unused) {
2548   return AdapterFingerPrint::equals(entry->fingerprint(), fp);
2549 }
2550 
2551 class ArchivedAdapterTable : public OffsetCompactHashtable<
2552   AdapterFingerPrint*,
2553   AdapterHandlerEntry*,
2554   adapter_fp_equals_compact_hashtable_entry> {};
2555 #endif // INCLUDE_CDS
2556 
2557 // A hashtable mapping from AdapterFingerPrints to AdapterHandlerEntries
2558 using AdapterHandlerTable = HashTable<AdapterFingerPrint*, AdapterHandlerEntry*, 293,
2559                   AnyObj::C_HEAP, mtCode,
2560                   AdapterFingerPrint::compute_hash,
2561                   AdapterFingerPrint::equals>;
2562 static AdapterHandlerTable* _adapter_handler_table;
2563 static GrowableArray<AdapterHandlerEntry*>* _adapter_handler_list = nullptr;
2564 
2565 // Find a entry with the same fingerprint if it exists
2566 AdapterHandlerEntry* AdapterHandlerLibrary::lookup(int total_args_passed, BasicType* sig_bt) {
2567   NOT_PRODUCT(_lookups++);
2568   assert_lock_strong(AdapterHandlerLibrary_lock);
2569   AdapterFingerPrint* fp = AdapterFingerPrint::allocate(total_args_passed, sig_bt);
2570   AdapterHandlerEntry* entry = nullptr;
2571 #if INCLUDE_CDS
2572   // if we are building the archive then the archived adapter table is
2573   // not valid and we need to use the ones added to the runtime table
2574   if (AOTCodeCache::is_using_adapter()) {
2575     // Search archived table first. It is read-only table so can be searched without lock
2576     entry = _aot_adapter_handler_table.lookup(fp, fp->compute_hash(), 0 /* unused */);
2577 #ifndef PRODUCT
2578     if (entry != nullptr) {
2579       _archived_hits++;
2580     }
2581 #endif
2582   }
2583 #endif // INCLUDE_CDS
2584   if (entry == nullptr) {
2585     assert_lock_strong(AdapterHandlerLibrary_lock);
2586     AdapterHandlerEntry** entry_p = _adapter_handler_table->get(fp);
2587     if (entry_p != nullptr) {
2588       entry = *entry_p;
2589       assert(entry->fingerprint()->equals(fp), "fingerprint mismatch key fp %s %s (hash=%d) != found fp %s %s (hash=%d)",
2590              entry->fingerprint()->as_basic_args_string(), entry->fingerprint()->as_string(), entry->fingerprint()->compute_hash(),
2591              fp->as_basic_args_string(), fp->as_string(), fp->compute_hash());
2592   #ifndef PRODUCT
2593       _runtime_hits++;
2594   #endif
2595     }
2596   }
2597   AdapterFingerPrint::deallocate(fp);
2598   return entry;
2599 }
2600 
2601 #ifndef PRODUCT
2602 void AdapterHandlerLibrary::print_statistics_on(outputStream* st) {
2603   auto size = [&] (AdapterFingerPrint* key, AdapterHandlerEntry* a) {
2604     return sizeof(*key) + sizeof(*a);
2605   };
2606   TableStatistics ts = _adapter_handler_table->statistics_calculate(size);
2607   ts.print(st, "AdapterHandlerTable");
2608   st->print_cr("AdapterHandlerTable (table_size=%d, entries=%d)",
2609                _adapter_handler_table->table_size(), _adapter_handler_table->number_of_entries());
2610   int total_hits = _archived_hits + _runtime_hits;
2611   st->print_cr("AdapterHandlerTable: lookups %d equals %d hits %d (archived=%d+runtime=%d)",
2612                _lookups, _equals, total_hits, _archived_hits, _runtime_hits);
2613 }
2614 #endif // !PRODUCT
2615 
2616 // ---------------------------------------------------------------------------
2617 // Implementation of AdapterHandlerLibrary
2618 AdapterHandlerEntry* AdapterHandlerLibrary::_no_arg_handler = nullptr;
2619 AdapterHandlerEntry* AdapterHandlerLibrary::_int_arg_handler = nullptr;
2620 AdapterHandlerEntry* AdapterHandlerLibrary::_obj_arg_handler = nullptr;
2621 AdapterHandlerEntry* AdapterHandlerLibrary::_obj_int_arg_handler = nullptr;
2622 AdapterHandlerEntry* AdapterHandlerLibrary::_obj_obj_arg_handler = nullptr;
2623 #if INCLUDE_CDS
2624 ArchivedAdapterTable AdapterHandlerLibrary::_aot_adapter_handler_table;
2625 #endif // INCLUDE_CDS
2626 static const int AdapterHandlerLibrary_size = 16*K;
2627 BufferBlob* AdapterHandlerLibrary::_buffer = nullptr;
2628 volatile uint AdapterHandlerLibrary::_id_counter = 0;
2629 
2630 BufferBlob* AdapterHandlerLibrary::buffer_blob() {
2631   assert(_buffer != nullptr, "should be initialized");
2632   return _buffer;
2633 }
2634 
2635 static void post_adapter_creation(const AdapterHandlerEntry* entry) {
2636   if (Forte::is_enabled() || JvmtiExport::should_post_dynamic_code_generated()) {
2637     AdapterBlob* adapter_blob = entry->adapter_blob();
2638     char blob_id[256];
2639     jio_snprintf(blob_id,
2640                  sizeof(blob_id),
2641                  "%s(%s)",
2642                  adapter_blob->name(),
2643                  entry->fingerprint()->as_string());
2644     if (Forte::is_enabled()) {
2645       Forte::register_stub(blob_id, adapter_blob->content_begin(), adapter_blob->content_end());
2646     }
2647 
2648     if (JvmtiExport::should_post_dynamic_code_generated()) {
2649       JvmtiExport::post_dynamic_code_generated(blob_id, adapter_blob->content_begin(), adapter_blob->content_end());
2650     }
2651   }
2652 }
2653 
2654 void AdapterHandlerLibrary::initialize() {
2655   {
2656     ResourceMark rm;
2657     _adapter_handler_table = new (mtCode) AdapterHandlerTable();
2658     _buffer = BufferBlob::create("adapters", AdapterHandlerLibrary_size);
2659   }
2660 
2661 #if INCLUDE_CDS
2662   // Link adapters in AOT Cache to their code in AOT Code Cache
2663   if (AOTCodeCache::is_using_adapter() && !_aot_adapter_handler_table.empty()) {
2664     link_aot_adapters();
2665     lookup_simple_adapters();
2666     return;
2667   }
2668 #endif // INCLUDE_CDS
2669 
2670   ResourceMark rm;
2671   {
2672     MutexLocker mu(AdapterHandlerLibrary_lock);
2673 
2674     _no_arg_handler = create_adapter(0, nullptr);
2675 
2676     BasicType obj_args[] = { T_OBJECT };
2677     _obj_arg_handler = create_adapter(1, obj_args);
2678 
2679     BasicType int_args[] = { T_INT };
2680     _int_arg_handler = create_adapter(1, int_args);
2681 
2682     BasicType obj_int_args[] = { T_OBJECT, T_INT };
2683     _obj_int_arg_handler = create_adapter(2, obj_int_args);
2684 
2685     BasicType obj_obj_args[] = { T_OBJECT, T_OBJECT };
2686     _obj_obj_arg_handler = create_adapter(2, obj_obj_args);
2687 
2688     // we should always get an entry back but we don't have any
2689     // associated blob on Zero
2690     assert(_no_arg_handler != nullptr &&
2691            _obj_arg_handler != nullptr &&
2692            _int_arg_handler != nullptr &&
2693            _obj_int_arg_handler != nullptr &&
2694            _obj_obj_arg_handler != nullptr, "Initial adapter handlers must be properly created");
2695   }
2696 
2697   // Outside of the lock
2698 #ifndef ZERO
2699   // no blobs to register when we are on Zero
2700   post_adapter_creation(_no_arg_handler);
2701   post_adapter_creation(_obj_arg_handler);
2702   post_adapter_creation(_int_arg_handler);
2703   post_adapter_creation(_obj_int_arg_handler);
2704   post_adapter_creation(_obj_obj_arg_handler);
2705 #endif // ZERO
2706 }
2707 
2708 AdapterHandlerEntry* AdapterHandlerLibrary::new_entry(AdapterFingerPrint* fingerprint) {
2709   uint id = (uint)AtomicAccess::add((int*)&_id_counter, 1);
2710   assert(id > 0, "we can never overflow because AOT cache cannot contain more than 2^32 methods");
2711   return AdapterHandlerEntry::allocate(id, fingerprint);
2712 }
2713 
2714 AdapterHandlerEntry* AdapterHandlerLibrary::get_simple_adapter(const methodHandle& method) {
2715   int total_args_passed = method->size_of_parameters(); // All args on stack
2716   if (total_args_passed == 0) {
2717     return _no_arg_handler;
2718   } else if (total_args_passed == 1) {
2719     if (!method->is_static()) {
2720       return _obj_arg_handler;
2721     }
2722     switch (method->signature()->char_at(1)) {
2723       case JVM_SIGNATURE_CLASS:
2724       case JVM_SIGNATURE_ARRAY:
2725         return _obj_arg_handler;
2726       case JVM_SIGNATURE_INT:
2727       case JVM_SIGNATURE_BOOLEAN:
2728       case JVM_SIGNATURE_CHAR:
2729       case JVM_SIGNATURE_BYTE:
2730       case JVM_SIGNATURE_SHORT:
2731         return _int_arg_handler;
2732     }
2733   } else if (total_args_passed == 2 &&
2734              !method->is_static()) {
2735     switch (method->signature()->char_at(1)) {
2736       case JVM_SIGNATURE_CLASS:
2737       case JVM_SIGNATURE_ARRAY:
2738         return _obj_obj_arg_handler;
2739       case JVM_SIGNATURE_INT:
2740       case JVM_SIGNATURE_BOOLEAN:
2741       case JVM_SIGNATURE_CHAR:
2742       case JVM_SIGNATURE_BYTE:
2743       case JVM_SIGNATURE_SHORT:
2744         return _obj_int_arg_handler;
2745     }
2746   }
2747   return nullptr;
2748 }
2749 
2750 class AdapterSignatureIterator : public SignatureIterator {
2751  private:
2752   BasicType stack_sig_bt[16];
2753   BasicType* sig_bt;
2754   int index;
2755 
2756  public:
2757   AdapterSignatureIterator(Symbol* signature,
2758                            fingerprint_t fingerprint,
2759                            bool is_static,
2760                            int total_args_passed) :
2761     SignatureIterator(signature, fingerprint),
2762     index(0)
2763   {
2764     sig_bt = (total_args_passed <= 16) ? stack_sig_bt : NEW_RESOURCE_ARRAY(BasicType, total_args_passed);
2765     if (!is_static) { // Pass in receiver first
2766       sig_bt[index++] = T_OBJECT;
2767     }
2768     do_parameters_on(this);
2769   }
2770 
2771   BasicType* basic_types() {
2772     return sig_bt;
2773   }
2774 
2775 #ifdef ASSERT
2776   int slots() {
2777     return index;
2778   }
2779 #endif
2780 
2781  private:
2782 
2783   friend class SignatureIterator;  // so do_parameters_on can call do_type
2784   void do_type(BasicType type) {
2785     sig_bt[index++] = type;
2786     if (type == T_LONG || type == T_DOUBLE) {
2787       sig_bt[index++] = T_VOID; // Longs & doubles take 2 Java slots
2788     }
2789   }
2790 };
2791 
2792 
2793 const char* AdapterHandlerEntry::_entry_names[] = {
2794   "i2c", "c2i", "c2i_unverified", "c2i_no_clinit_check"
2795 };
2796 
2797 #ifdef ASSERT
2798 void AdapterHandlerLibrary::verify_adapter_sharing(int total_args_passed, BasicType* sig_bt, AdapterHandlerEntry* cached_entry) {
2799   // we can only check for the same code if there is any
2800 #ifndef ZERO
2801   AdapterHandlerEntry* comparison_entry = create_adapter(total_args_passed, sig_bt, true);
2802   assert(comparison_entry->adapter_blob() == nullptr, "no blob should be created when creating an adapter for comparison");
2803   assert(comparison_entry->compare_code(cached_entry), "code must match");
2804   // Release the one just created
2805   AdapterHandlerEntry::deallocate(comparison_entry);
2806 # endif // ZERO
2807 }
2808 #endif /* ASSERT*/
2809 
2810 AdapterHandlerEntry* AdapterHandlerLibrary::get_adapter(const methodHandle& method) {
2811   assert(!method->is_abstract(), "abstract methods do not have adapters");
2812   // Use customized signature handler.  Need to lock around updates to
2813   // the _adapter_handler_table (it is not safe for concurrent readers
2814   // and a single writer: this could be fixed if it becomes a
2815   // problem).
2816 
2817   // Fast-path for trivial adapters
2818   AdapterHandlerEntry* entry = get_simple_adapter(method);
2819   if (entry != nullptr) {
2820     return entry;
2821   }
2822 
2823   ResourceMark rm;
2824   bool new_entry = false;
2825 
2826   // Fill in the signature array, for the calling-convention call.
2827   int total_args_passed = method->size_of_parameters(); // All args on stack
2828 
2829   AdapterSignatureIterator si(method->signature(), method->constMethod()->fingerprint(),
2830                               method->is_static(), total_args_passed);
2831   assert(si.slots() == total_args_passed, "");
2832   BasicType* sig_bt = si.basic_types();
2833   {
2834     MutexLocker mu(AdapterHandlerLibrary_lock);
2835 
2836     // Lookup method signature's fingerprint
2837     entry = lookup(total_args_passed, sig_bt);
2838 
2839     if (entry != nullptr) {
2840 #ifndef ZERO
2841       assert(entry->is_linked(), "AdapterHandlerEntry must have been linked");
2842 #endif
2843 #ifdef ASSERT
2844       if (!entry->in_aot_cache() && VerifyAdapterSharing) {
2845         verify_adapter_sharing(total_args_passed, sig_bt, entry);
2846       }
2847 #endif
2848     } else {
2849       entry = create_adapter(total_args_passed, sig_bt);
2850       if (entry != nullptr) {
2851         new_entry = true;
2852       }
2853     }
2854   }
2855 
2856   // Outside of the lock
2857   if (new_entry) {
2858     post_adapter_creation(entry);
2859   }
2860   return entry;
2861 }
2862 
2863 void AdapterHandlerLibrary::lookup_aot_cache(AdapterHandlerEntry* handler) {
2864   ResourceMark rm;
2865   const char* name = AdapterHandlerLibrary::name(handler);
2866   const uint32_t id = AdapterHandlerLibrary::id(handler);
2867 
2868   CodeBlob* blob = AOTCodeCache::load_code_blob(AOTCodeEntry::Adapter, id, name);
2869   if (blob != nullptr) {
2870     handler->set_adapter_blob(blob->as_adapter_blob());
2871   }
2872 }
2873 
2874 #ifndef PRODUCT
2875 void AdapterHandlerLibrary::print_adapter_handler_info(outputStream* st, AdapterHandlerEntry* handler) {
2876   ttyLocker ttyl;
2877   ResourceMark rm;
2878   int insts_size;
2879   // on Zero the blob may be null
2880   handler->print_adapter_on(tty);
2881   AdapterBlob* adapter_blob = handler->adapter_blob();
2882   if (adapter_blob == nullptr) {
2883     return;
2884   }
2885   insts_size = adapter_blob->code_size();
2886   st->print_cr("i2c argument handler for: %s %s (%d bytes generated)",
2887                 handler->fingerprint()->as_basic_args_string(),
2888                 handler->fingerprint()->as_string(), insts_size);
2889   st->print_cr("c2i argument handler starts at " INTPTR_FORMAT, p2i(handler->get_c2i_entry()));
2890   if (Verbose || PrintStubCode) {
2891     address first_pc = adapter_blob->content_begin();
2892     if (first_pc != nullptr) {
2893       Disassembler::decode(first_pc, first_pc + insts_size, st, &adapter_blob->asm_remarks());
2894       st->cr();
2895     }
2896   }
2897 }
2898 #endif // PRODUCT
2899 
2900 void AdapterHandlerLibrary::address_to_offset(address entry_address[AdapterBlob::ENTRY_COUNT],
2901                                               int entry_offset[AdapterBlob::ENTRY_COUNT]) {
2902   entry_offset[AdapterBlob::I2C] = 0;
2903   entry_offset[AdapterBlob::C2I] = entry_address[AdapterBlob::C2I] - entry_address[AdapterBlob::I2C];
2904   entry_offset[AdapterBlob::C2I_Unverified] = entry_address[AdapterBlob::C2I_Unverified] - entry_address[AdapterBlob::I2C];
2905   if (entry_address[AdapterBlob::C2I_No_Clinit_Check] == nullptr) {
2906     entry_offset[AdapterBlob::C2I_No_Clinit_Check] = -1;
2907   } else {
2908     entry_offset[AdapterBlob::C2I_No_Clinit_Check] = entry_address[AdapterBlob::C2I_No_Clinit_Check] - entry_address[AdapterBlob::I2C];
2909   }
2910 }
2911 
2912 bool AdapterHandlerLibrary::generate_adapter_code(AdapterHandlerEntry* handler,
2913                                                   int total_args_passed,
2914                                                   BasicType* sig_bt,
2915                                                   bool is_transient) {
2916   if (log_is_enabled(Info, perf, class, link)) {
2917     ClassLoader::perf_method_adapters_count()->inc();
2918   }
2919 
2920 #ifndef ZERO
2921   BufferBlob* buf = buffer_blob(); // the temporary code buffer in CodeCache
2922   CodeBuffer buffer(buf);
2923   short buffer_locs[20];
2924   buffer.insts()->initialize_shared_locs((relocInfo*)buffer_locs,
2925                                          sizeof(buffer_locs)/sizeof(relocInfo));
2926   MacroAssembler masm(&buffer);
2927   VMRegPair stack_regs[16];
2928   VMRegPair* regs = (total_args_passed <= 16) ? stack_regs : NEW_RESOURCE_ARRAY(VMRegPair, total_args_passed);
2929 
2930   // Get a description of the compiled java calling convention and the largest used (VMReg) stack slot usage
2931   int comp_args_on_stack = SharedRuntime::java_calling_convention(sig_bt, regs, total_args_passed);
2932   address entry_address[AdapterBlob::ENTRY_COUNT];
2933   SharedRuntime::generate_i2c2i_adapters(&masm,
2934                                          total_args_passed,
2935                                          comp_args_on_stack,
2936                                          sig_bt,
2937                                          regs,
2938                                          entry_address);
2939   // On zero there is no code to save and no need to create a blob and
2940   // or relocate the handler.
2941   int entry_offset[AdapterBlob::ENTRY_COUNT];
2942   address_to_offset(entry_address, entry_offset);
2943 #ifdef ASSERT
2944   if (VerifyAdapterSharing) {
2945     handler->save_code(buf->code_begin(), buffer.insts_size());
2946     if (is_transient) {
2947       return true;
2948     }
2949   }
2950 #endif
2951   AdapterBlob* adapter_blob = AdapterBlob::create(&buffer, entry_offset);
2952   if (adapter_blob == nullptr) {
2953     // CodeCache is full, disable compilation
2954     // Ought to log this but compile log is only per compile thread
2955     // and we're some non descript Java thread.
2956     return false;
2957   }
2958   handler->set_adapter_blob(adapter_blob);
2959   if (!is_transient && AOTCodeCache::is_dumping_adapter()) {
2960     // try to save generated code
2961     const char* name = AdapterHandlerLibrary::name(handler);
2962     const uint32_t id = AdapterHandlerLibrary::id(handler);
2963     bool success = AOTCodeCache::store_code_blob(*adapter_blob, AOTCodeEntry::Adapter, id, name);
2964     assert(success || !AOTCodeCache::is_dumping_adapter(), "caching of adapter must be disabled");
2965   }
2966 #endif // ZERO
2967 
2968 #ifndef PRODUCT
2969   // debugging support
2970   if (PrintAdapterHandlers || PrintStubCode) {
2971     print_adapter_handler_info(tty, handler);
2972   }
2973 #endif
2974 
2975   return true;
2976 }
2977 
2978 AdapterHandlerEntry* AdapterHandlerLibrary::create_adapter(int total_args_passed,
2979                                                            BasicType* sig_bt,
2980                                                            bool is_transient) {
2981   AdapterFingerPrint* fp = AdapterFingerPrint::allocate(total_args_passed, sig_bt);
2982   AdapterHandlerEntry* handler = AdapterHandlerLibrary::new_entry(fp);
2983   if (!generate_adapter_code(handler, total_args_passed, sig_bt, is_transient)) {
2984     AdapterHandlerEntry::deallocate(handler);
2985     return nullptr;
2986   }
2987   if (!is_transient) {
2988     assert_lock_strong(AdapterHandlerLibrary_lock);
2989     _adapter_handler_table->put(fp, handler);
2990   }
2991   return handler;
2992 }
2993 
2994 #if INCLUDE_CDS
2995 void AdapterHandlerEntry::remove_unshareable_info() {
2996 #ifdef ASSERT
2997    _saved_code = nullptr;
2998    _saved_code_length = 0;
2999 #endif // ASSERT
3000    _adapter_blob = nullptr;
3001    _linked = false;
3002 }
3003 
3004 class CopyAdapterTableToArchive : StackObj {
3005 private:
3006   CompactHashtableWriter* _writer;
3007   ArchiveBuilder* _builder;
3008 public:
3009   CopyAdapterTableToArchive(CompactHashtableWriter* writer) : _writer(writer),
3010                                                              _builder(ArchiveBuilder::current())
3011   {}
3012 
3013   bool do_entry(AdapterFingerPrint* fp, AdapterHandlerEntry* entry) {
3014     LogStreamHandle(Trace, aot) lsh;
3015     if (ArchiveBuilder::current()->has_been_archived((address)entry)) {
3016       assert(ArchiveBuilder::current()->has_been_archived((address)fp), "must be");
3017       AdapterFingerPrint* buffered_fp = ArchiveBuilder::current()->get_buffered_addr(fp);
3018       assert(buffered_fp != nullptr,"sanity check");
3019       AdapterHandlerEntry* buffered_entry = ArchiveBuilder::current()->get_buffered_addr(entry);
3020       assert(buffered_entry != nullptr,"sanity check");
3021 
3022       uint hash = fp->compute_hash();
3023       _writer->add(hash, AOTCompressedPointers::encode_not_null(buffered_entry));
3024       if (lsh.is_enabled()) {
3025         address fp_runtime_addr = (address)buffered_fp + ArchiveBuilder::current()->buffer_to_requested_delta();
3026         address entry_runtime_addr = (address)buffered_entry + ArchiveBuilder::current()->buffer_to_requested_delta();
3027         log_trace(aot)("Added fp=%p (%s), entry=%p to the archived adater table", buffered_fp, buffered_fp->as_basic_args_string(), buffered_entry);
3028       }
3029     } else {
3030       if (lsh.is_enabled()) {
3031         log_trace(aot)("Skipping adapter handler %p (fp=%s) as it is not archived", entry, fp->as_basic_args_string());
3032       }
3033     }
3034     return true;
3035   }
3036 };
3037 
3038 void AdapterHandlerLibrary::dump_aot_adapter_table() {
3039   CompactHashtableStats stats;
3040   CompactHashtableWriter writer(_adapter_handler_table->number_of_entries(), &stats);
3041   CopyAdapterTableToArchive copy(&writer);
3042   _adapter_handler_table->iterate(&copy);
3043   writer.dump(&_aot_adapter_handler_table, "archived adapter table");
3044 }
3045 
3046 void AdapterHandlerLibrary::serialize_shared_table_header(SerializeClosure* soc) {
3047   _aot_adapter_handler_table.serialize_header(soc);
3048 }
3049 
3050 void AdapterHandlerLibrary::link_aot_adapter_handler(AdapterHandlerEntry* handler) {
3051 #ifdef ASSERT
3052   if (TestAOTAdapterLinkFailure) {
3053     return;
3054   }
3055 #endif
3056   lookup_aot_cache(handler);
3057 #ifndef PRODUCT
3058   // debugging support
3059   if (PrintAdapterHandlers || PrintStubCode) {
3060     print_adapter_handler_info(tty, handler);
3061   }
3062 #endif
3063 }
3064 
3065 // This method is used during production run to link archived adapters (stored in AOT Cache)
3066 // to their code in AOT Code Cache
3067 void AdapterHandlerEntry::link() {
3068   ResourceMark rm;
3069   assert(_fingerprint != nullptr, "_fingerprint must not be null");
3070   bool generate_code = false;
3071   // Generate code only if AOTCodeCache is not available, or
3072   // caching adapters is disabled, or we fail to link
3073   // the AdapterHandlerEntry to its code in the AOTCodeCache
3074   if (AOTCodeCache::is_using_adapter()) {
3075     AdapterHandlerLibrary::link_aot_adapter_handler(this);
3076     // If link_aot_adapter_handler() succeeds, _adapter_blob will be non-null
3077     if (_adapter_blob == nullptr) {
3078       log_warning(aot)("Failed to link AdapterHandlerEntry (fp=%s) to its code in the AOT code cache", _fingerprint->as_basic_args_string());
3079       generate_code = true;
3080     }
3081   } else {
3082     generate_code = true;
3083   }
3084   if (generate_code) {
3085     int nargs;
3086     BasicType* bt = _fingerprint->as_basic_type(nargs);
3087     if (!AdapterHandlerLibrary::generate_adapter_code(this, nargs, bt, /* is_transient */ false)) {
3088       // Don't throw exceptions during VM initialization because java.lang.* classes
3089       // might not have been initialized, causing problems when constructing the
3090       // Java exception object.
3091       vm_exit_during_initialization("Out of space in CodeCache for adapters");
3092     }
3093   }
3094   if (_adapter_blob != nullptr) {
3095     post_adapter_creation(this);
3096   }
3097   assert(_linked, "AdapterHandlerEntry must now be linked");
3098 }
3099 
3100 void AdapterHandlerLibrary::link_aot_adapters() {
3101   uint max_id = 0;
3102   assert(AOTCodeCache::is_using_adapter(), "AOT adapters code should be available");
3103   /* It is possible that some adapters generated in assembly phase are not stored in the cache.
3104    * That implies adapter ids of the adapters in the cache may not be contiguous.
3105    * If the size of the _aot_adapter_handler_table is used to initialize _id_counter, then it may
3106    * result in collision of adapter ids between AOT stored handlers and runtime generated handlers.
3107    * To avoid such situation, initialize the _id_counter with the largest adapter id among the AOT stored handlers.
3108    */
3109   _aot_adapter_handler_table.iterate_all([&](AdapterHandlerEntry* entry) {
3110     assert(!entry->is_linked(), "AdapterHandlerEntry is already linked!");
3111     entry->link();
3112     max_id = MAX2(max_id, entry->id());
3113   });
3114   // Set adapter id to the maximum id found in the AOTCache
3115   assert(_id_counter == 0, "Did not expect new AdapterHandlerEntry to be created at this stage");
3116   _id_counter = max_id;
3117 }
3118 
3119 // This method is called during production run to lookup simple adapters
3120 // in the archived adapter handler table
3121 void AdapterHandlerLibrary::lookup_simple_adapters() {
3122   assert(!_aot_adapter_handler_table.empty(), "archived adapter handler table is empty");
3123 
3124   MutexLocker mu(AdapterHandlerLibrary_lock);
3125   _no_arg_handler = lookup(0, nullptr);
3126 
3127   BasicType obj_args[] = { T_OBJECT };
3128   _obj_arg_handler = lookup(1, obj_args);
3129 
3130   BasicType int_args[] = { T_INT };
3131   _int_arg_handler = lookup(1, int_args);
3132 
3133   BasicType obj_int_args[] = { T_OBJECT, T_INT };
3134   _obj_int_arg_handler = lookup(2, obj_int_args);
3135 
3136   BasicType obj_obj_args[] = { T_OBJECT, T_OBJECT };
3137   _obj_obj_arg_handler = lookup(2, obj_obj_args);
3138 
3139   assert(_no_arg_handler != nullptr &&
3140          _obj_arg_handler != nullptr &&
3141          _int_arg_handler != nullptr &&
3142          _obj_int_arg_handler != nullptr &&
3143          _obj_obj_arg_handler != nullptr, "Initial adapters not found in archived adapter handler table");
3144   assert(_no_arg_handler->is_linked() &&
3145          _obj_arg_handler->is_linked() &&
3146          _int_arg_handler->is_linked() &&
3147          _obj_int_arg_handler->is_linked() &&
3148          _obj_obj_arg_handler->is_linked(), "Initial adapters not in linked state");
3149 }
3150 #endif // INCLUDE_CDS
3151 
3152 void AdapterHandlerEntry::metaspace_pointers_do(MetaspaceClosure* it) {
3153   LogStreamHandle(Trace, aot) lsh;
3154   if (lsh.is_enabled()) {
3155     lsh.print("Iter(AdapterHandlerEntry): %p(%s)", this, _fingerprint->as_basic_args_string());
3156     lsh.cr();
3157   }
3158   it->push(&_fingerprint);
3159 }
3160 
3161 AdapterHandlerEntry::~AdapterHandlerEntry() {
3162   if (_fingerprint != nullptr) {
3163     AdapterFingerPrint::deallocate(_fingerprint);
3164     _fingerprint = nullptr;
3165   }
3166 #ifdef ASSERT
3167   FREE_C_HEAP_ARRAY(unsigned char, _saved_code);
3168 #endif
3169   FreeHeap(this);
3170 }
3171 
3172 
3173 #ifdef ASSERT
3174 // Capture the code before relocation so that it can be compared
3175 // against other versions.  If the code is captured after relocation
3176 // then relative instructions won't be equivalent.
3177 void AdapterHandlerEntry::save_code(unsigned char* buffer, int length) {
3178   _saved_code = NEW_C_HEAP_ARRAY(unsigned char, length, mtCode);
3179   _saved_code_length = length;
3180   memcpy(_saved_code, buffer, length);
3181 }
3182 
3183 
3184 bool AdapterHandlerEntry::compare_code(AdapterHandlerEntry* other) {
3185   assert(_saved_code != nullptr && other->_saved_code != nullptr, "code not saved");
3186 
3187   if (other->_saved_code_length != _saved_code_length) {
3188     return false;
3189   }
3190 
3191   return memcmp(other->_saved_code, _saved_code, _saved_code_length) == 0;
3192 }
3193 #endif
3194 
3195 
3196 /**
3197  * Create a native wrapper for this native method.  The wrapper converts the
3198  * Java-compiled calling convention to the native convention, handles
3199  * arguments, and transitions to native.  On return from the native we transition
3200  * back to java blocking if a safepoint is in progress.
3201  */
3202 void AdapterHandlerLibrary::create_native_wrapper(const methodHandle& method) {
3203   ResourceMark rm;
3204   nmethod* nm = nullptr;
3205 
3206   // Check if memory should be freed before allocation
3207   CodeCache::gc_on_allocation();
3208 
3209   assert(method->is_native(), "must be native");
3210   assert(method->is_special_native_intrinsic() ||
3211          method->has_native_function(), "must have something valid to call!");
3212 
3213   {
3214     // Perform the work while holding the lock, but perform any printing outside the lock
3215     MutexLocker mu(AdapterHandlerLibrary_lock);
3216     // See if somebody beat us to it
3217     if (method->code() != nullptr) {
3218       return;
3219     }
3220 
3221     const int compile_id = CompileBroker::assign_compile_id(method, CompileBroker::standard_entry_bci);
3222     assert(compile_id > 0, "Must generate native wrapper");
3223 
3224 
3225     ResourceMark rm;
3226     BufferBlob*  buf = buffer_blob(); // the temporary code buffer in CodeCache
3227     if (buf != nullptr) {
3228       CodeBuffer buffer(buf);
3229 
3230       if (method->is_continuation_enter_intrinsic()) {
3231         buffer.initialize_stubs_size(192);
3232       }
3233 
3234       struct { double data[20]; } locs_buf;
3235       struct { double data[20]; } stubs_locs_buf;
3236       buffer.insts()->initialize_shared_locs((relocInfo*)&locs_buf, sizeof(locs_buf) / sizeof(relocInfo));
3237 #if defined(AARCH64) || defined(PPC64)
3238       // On AArch64 with ZGC and nmethod entry barriers, we need all oops to be
3239       // in the constant pool to ensure ordering between the barrier and oops
3240       // accesses. For native_wrappers we need a constant.
3241       // On PPC64 the continuation enter intrinsic needs the constant pool for the compiled
3242       // static java call that is resolved in the runtime.
3243       if (PPC64_ONLY(method->is_continuation_enter_intrinsic() &&) true) {
3244         buffer.initialize_consts_size(8 PPC64_ONLY(+ 24));
3245       }
3246 #endif
3247       buffer.stubs()->initialize_shared_locs((relocInfo*)&stubs_locs_buf, sizeof(stubs_locs_buf) / sizeof(relocInfo));
3248       MacroAssembler _masm(&buffer);
3249 
3250       // Fill in the signature array, for the calling-convention call.
3251       const int total_args_passed = method->size_of_parameters();
3252 
3253       VMRegPair stack_regs[16];
3254       VMRegPair* regs = (total_args_passed <= 16) ? stack_regs : NEW_RESOURCE_ARRAY(VMRegPair, total_args_passed);
3255 
3256       AdapterSignatureIterator si(method->signature(), method->constMethod()->fingerprint(),
3257                               method->is_static(), total_args_passed);
3258       BasicType* sig_bt = si.basic_types();
3259       assert(si.slots() == total_args_passed, "");
3260       BasicType ret_type = si.return_type();
3261 
3262       // Now get the compiled-Java arguments layout.
3263       SharedRuntime::java_calling_convention(sig_bt, regs, total_args_passed);
3264 
3265       // Generate the compiled-to-native wrapper code
3266       nm = SharedRuntime::generate_native_wrapper(&_masm, method, compile_id, sig_bt, regs, ret_type);
3267 
3268       if (nm != nullptr) {
3269         {
3270           MutexLocker pl(NMethodState_lock, Mutex::_no_safepoint_check_flag);
3271           if (nm->make_in_use()) {
3272             method->set_code(method, nm);
3273           }
3274         }
3275 
3276         DirectiveSet* directive = DirectivesStack::getMatchingDirective(method, CompileBroker::compiler(CompLevel_simple));
3277         if (directive->PrintAssemblyOption) {
3278           nm->print_code();
3279         }
3280         DirectivesStack::release(directive);
3281       }
3282     }
3283   } // Unlock AdapterHandlerLibrary_lock
3284 
3285 
3286   // Install the generated code.
3287   if (nm != nullptr) {
3288     const char *msg = method->is_static() ? "(static)" : "";
3289     CompileTask::print_ul(nm, msg);
3290     if (PrintCompilation) {
3291       ttyLocker ttyl;
3292       CompileTask::print(tty, nm, msg);
3293     }
3294     nm->post_compiled_method_load_event();
3295   }
3296 }
3297 
3298 // -------------------------------------------------------------------------
3299 // Java-Java calling convention
3300 // (what you use when Java calls Java)
3301 
3302 //------------------------------name_for_receiver----------------------------------
3303 // For a given signature, return the VMReg for parameter 0.
3304 VMReg SharedRuntime::name_for_receiver() {
3305   VMRegPair regs;
3306   BasicType sig_bt = T_OBJECT;
3307   (void) java_calling_convention(&sig_bt, &regs, 1);
3308   // Return argument 0 register.  In the LP64 build pointers
3309   // take 2 registers, but the VM wants only the 'main' name.
3310   return regs.first();
3311 }
3312 
3313 VMRegPair *SharedRuntime::find_callee_arguments(Symbol* sig, bool has_receiver, bool has_appendix, int* arg_size) {
3314   // This method is returning a data structure allocating as a
3315   // ResourceObject, so do not put any ResourceMarks in here.
3316 
3317   BasicType *sig_bt = NEW_RESOURCE_ARRAY(BasicType, 256);
3318   VMRegPair *regs = NEW_RESOURCE_ARRAY(VMRegPair, 256);
3319   int cnt = 0;
3320   if (has_receiver) {
3321     sig_bt[cnt++] = T_OBJECT; // Receiver is argument 0; not in signature
3322   }
3323 
3324   for (SignatureStream ss(sig); !ss.at_return_type(); ss.next()) {
3325     BasicType type = ss.type();
3326     sig_bt[cnt++] = type;
3327     if (is_double_word_type(type))
3328       sig_bt[cnt++] = T_VOID;
3329   }
3330 
3331   if (has_appendix) {
3332     sig_bt[cnt++] = T_OBJECT;
3333   }
3334 
3335   assert(cnt < 256, "grow table size");
3336 
3337   int comp_args_on_stack;
3338   comp_args_on_stack = java_calling_convention(sig_bt, regs, cnt);
3339 
3340   // the calling convention doesn't count out_preserve_stack_slots so
3341   // we must add that in to get "true" stack offsets.
3342 
3343   if (comp_args_on_stack) {
3344     for (int i = 0; i < cnt; i++) {
3345       VMReg reg1 = regs[i].first();
3346       if (reg1->is_stack()) {
3347         // Yuck
3348         reg1 = reg1->bias(out_preserve_stack_slots());
3349       }
3350       VMReg reg2 = regs[i].second();
3351       if (reg2->is_stack()) {
3352         // Yuck
3353         reg2 = reg2->bias(out_preserve_stack_slots());
3354       }
3355       regs[i].set_pair(reg2, reg1);
3356     }
3357   }
3358 
3359   // results
3360   *arg_size = cnt;
3361   return regs;
3362 }
3363 
3364 // OSR Migration Code
3365 //
3366 // This code is used convert interpreter frames into compiled frames.  It is
3367 // called from very start of a compiled OSR nmethod.  A temp array is
3368 // allocated to hold the interesting bits of the interpreter frame.  All
3369 // active locks are inflated to allow them to move.  The displaced headers and
3370 // active interpreter locals are copied into the temp buffer.  Then we return
3371 // back to the compiled code.  The compiled code then pops the current
3372 // interpreter frame off the stack and pushes a new compiled frame.  Then it
3373 // copies the interpreter locals and displaced headers where it wants.
3374 // Finally it calls back to free the temp buffer.
3375 //
3376 // All of this is done NOT at any Safepoint, nor is any safepoint or GC allowed.
3377 
3378 JRT_LEAF(intptr_t*, SharedRuntime::OSR_migration_begin( JavaThread *current) )
3379   assert(current == JavaThread::current(), "pre-condition");
3380   JFR_ONLY(Jfr::check_and_process_sample_request(current);)
3381   // During OSR migration, we unwind the interpreted frame and replace it with a compiled
3382   // frame. The stack watermark code below ensures that the interpreted frame is processed
3383   // before it gets unwound. This is helpful as the size of the compiled frame could be
3384   // larger than the interpreted frame, which could result in the new frame not being
3385   // processed correctly.
3386   StackWatermarkSet::before_unwind(current);
3387 
3388   //
3389   // This code is dependent on the memory layout of the interpreter local
3390   // array and the monitors. On all of our platforms the layout is identical
3391   // so this code is shared. If some platform lays the their arrays out
3392   // differently then this code could move to platform specific code or
3393   // the code here could be modified to copy items one at a time using
3394   // frame accessor methods and be platform independent.
3395 
3396   frame fr = current->last_frame();
3397   assert(fr.is_interpreted_frame(), "");
3398   assert(fr.interpreter_frame_expression_stack_size()==0, "only handle empty stacks");
3399 
3400   // Figure out how many monitors are active.
3401   int active_monitor_count = 0;
3402   for (BasicObjectLock *kptr = fr.interpreter_frame_monitor_end();
3403        kptr < fr.interpreter_frame_monitor_begin();
3404        kptr = fr.next_monitor_in_interpreter_frame(kptr) ) {
3405     if (kptr->obj() != nullptr) active_monitor_count++;
3406   }
3407 
3408   // QQQ we could place number of active monitors in the array so that compiled code
3409   // could double check it.
3410 
3411   Method* moop = fr.interpreter_frame_method();
3412   int max_locals = moop->max_locals();
3413   // Allocate temp buffer, 1 word per local & 2 per active monitor
3414   int buf_size_words = max_locals + active_monitor_count * BasicObjectLock::size();
3415   intptr_t *buf = NEW_C_HEAP_ARRAY(intptr_t,buf_size_words, mtCode);
3416 
3417   // Copy the locals.  Order is preserved so that loading of longs works.
3418   // Since there's no GC I can copy the oops blindly.
3419   assert(sizeof(HeapWord)==sizeof(intptr_t), "fix this code");
3420   Copy::disjoint_words((HeapWord*)fr.interpreter_frame_local_at(max_locals-1),
3421                        (HeapWord*)&buf[0],
3422                        max_locals);
3423 
3424   // Inflate locks.  Copy the displaced headers.  Be careful, there can be holes.
3425   int i = max_locals;
3426   for (BasicObjectLock *kptr2 = fr.interpreter_frame_monitor_end();
3427        kptr2 < fr.interpreter_frame_monitor_begin();
3428        kptr2 = fr.next_monitor_in_interpreter_frame(kptr2) ) {
3429     if (kptr2->obj() != nullptr) {         // Avoid 'holes' in the monitor array
3430       BasicLock *lock = kptr2->lock();
3431       if (UseObjectMonitorTable) {
3432         buf[i] = (intptr_t)lock->object_monitor_cache();
3433       }
3434 #ifdef ASSERT
3435       else {
3436         buf[i] = badDispHeaderOSR;
3437       }
3438 #endif
3439       i++;
3440       buf[i++] = cast_from_oop<intptr_t>(kptr2->obj());
3441     }
3442   }
3443   assert(i - max_locals == active_monitor_count*2, "found the expected number of monitors");
3444 
3445   RegisterMap map(current,
3446                   RegisterMap::UpdateMap::skip,
3447                   RegisterMap::ProcessFrames::include,
3448                   RegisterMap::WalkContinuation::skip);
3449   frame sender = fr.sender(&map);
3450   if (sender.is_interpreted_frame()) {
3451     current->push_cont_fastpath(sender.unextended_sp());
3452   }
3453 
3454   return buf;
3455 JRT_END
3456 
3457 JRT_LEAF(void, SharedRuntime::OSR_migration_end( intptr_t* buf) )
3458   FREE_C_HEAP_ARRAY(intptr_t, buf);
3459 JRT_END
3460 
3461 const char* AdapterHandlerLibrary::name(AdapterHandlerEntry* handler) {
3462   return handler->fingerprint()->as_basic_args_string();
3463 }
3464 
3465 uint32_t AdapterHandlerLibrary::id(AdapterHandlerEntry* handler) {
3466   return handler->id();
3467 }
3468 
3469 void AdapterHandlerLibrary::print_handler_on(outputStream* st, const CodeBlob* b) {
3470   bool found = false;
3471 #if INCLUDE_CDS
3472   if (AOTCodeCache::is_using_adapter()) {
3473     auto findblob_archived_table = [&] (AdapterHandlerEntry* handler) {
3474       if (b == handler->adapter_blob()) {
3475         found = true;
3476         st->print("Adapter for signature: ");
3477         handler->print_adapter_on(st);
3478         return false; // abort iteration
3479       } else {
3480         return true; // keep looking
3481       }
3482     };
3483     _aot_adapter_handler_table.iterate(findblob_archived_table);
3484   }
3485 #endif // INCLUDE_CDS
3486   if (!found) {
3487     auto findblob_runtime_table = [&] (AdapterFingerPrint* key, AdapterHandlerEntry* handler) {
3488       if (b == handler->adapter_blob()) {
3489         found = true;
3490         st->print("Adapter for signature: ");
3491         handler->print_adapter_on(st);
3492         return false; // abort iteration
3493       } else {
3494         return true; // keep looking
3495       }
3496     };
3497     assert_locked_or_safepoint(AdapterHandlerLibrary_lock);
3498     _adapter_handler_table->iterate(findblob_runtime_table);
3499   }
3500   assert(found, "Should have found handler");
3501 }
3502 
3503 void AdapterHandlerEntry::print_adapter_on(outputStream* st) const {
3504   st->print("AHE@" INTPTR_FORMAT ": %s", p2i(this), fingerprint()->as_string());
3505   if (adapter_blob() != nullptr) {
3506     st->print(" i2c: " INTPTR_FORMAT, p2i(get_i2c_entry()));
3507     st->print(" c2i: " INTPTR_FORMAT, p2i(get_c2i_entry()));
3508     st->print(" c2iUV: " INTPTR_FORMAT, p2i(get_c2i_unverified_entry()));
3509     if (get_c2i_no_clinit_check_entry() != nullptr) {
3510       st->print(" c2iNCI: " INTPTR_FORMAT, p2i(get_c2i_no_clinit_check_entry()));
3511     }
3512   }
3513   st->cr();
3514 }
3515 








3516 JRT_LEAF(void, SharedRuntime::enable_stack_reserved_zone(JavaThread* current))
3517   assert(current == JavaThread::current(), "pre-condition");
3518   StackOverflow* overflow_state = current->stack_overflow_state();
3519   overflow_state->enable_stack_reserved_zone(/*check_if_disabled*/true);
3520   overflow_state->set_reserved_stack_activation(current->stack_base());
3521 JRT_END
3522 
3523 frame SharedRuntime::look_for_reserved_stack_annotated_method(JavaThread* current, frame fr) {
3524   ResourceMark rm(current);
3525   frame activation;
3526   nmethod* nm = nullptr;
3527   int count = 1;
3528 
3529   assert(fr.is_java_frame(), "Must start on Java frame");
3530 
3531   RegisterMap map(JavaThread::current(),
3532                   RegisterMap::UpdateMap::skip,
3533                   RegisterMap::ProcessFrames::skip,
3534                   RegisterMap::WalkContinuation::skip); // don't walk continuations
3535   for (; !fr.is_first_frame(); fr = fr.sender(&map)) {
3536     if (!fr.is_java_frame()) {
3537       continue;
3538     }
3539 
3540     Method* method = nullptr;
3541     bool found = false;
3542     if (fr.is_interpreted_frame()) {
3543       method = fr.interpreter_frame_method();
3544       if (method != nullptr && method->has_reserved_stack_access()) {
3545         found = true;
3546       }
3547     } else {
3548       CodeBlob* cb = fr.cb();
3549       if (cb != nullptr && cb->is_nmethod()) {
3550         nm = cb->as_nmethod();
3551         method = nm->method();
3552         for (ScopeDesc *sd = nm->scope_desc_near(fr.pc()); sd != nullptr; sd = sd->sender()) {
3553           method = sd->method();
3554           if (method != nullptr && method->has_reserved_stack_access()) {
3555             found = true;
3556           }
3557         }
3558       }
3559     }
3560     if (found) {
3561       activation = fr;
3562       warning("Potentially dangerous stack overflow in "
3563               "ReservedStackAccess annotated method %s [%d]",
3564               method->name_and_sig_as_C_string(), count++);
3565       EventReservedStackActivation event;
3566       if (event.should_commit()) {
3567         event.set_method(method);
3568         event.commit();
3569       }
3570     }
3571   }
3572   return activation;
3573 }
3574 
3575 void SharedRuntime::on_slowpath_allocation_exit(JavaThread* current) {
3576   // After any safepoint, just before going back to compiled code,
3577   // we inform the GC that we will be doing initializing writes to
3578   // this object in the future without emitting card-marks, so
3579   // GC may take any compensating steps.
3580 
3581   oop new_obj = current->vm_result_oop();
3582   if (new_obj == nullptr) return;
3583 
3584   BarrierSet *bs = BarrierSet::barrier_set();
3585   bs->on_slowpath_allocation_exit(current, new_obj);
3586 }
--- EOF ---