1 /*
   2  * Copyright (c) 2003, 2025, Oracle and/or its affiliates. All rights reserved.
   3  * Copyright (c) 2014, 2021, Red Hat Inc. All rights reserved.
   4  * Copyright (c) 2021, Azul Systems, Inc. All rights reserved.
   5  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   6  *
   7  * This code is free software; you can redistribute it and/or modify it
   8  * under the terms of the GNU General Public License version 2 only, as
   9  * published by the Free Software Foundation.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  *
  25  */
  26 
  27 #include "asm/macroAssembler.hpp"
  28 #include "asm/macroAssembler.inline.hpp"
  29 #include "classfile/symbolTable.hpp"
  30 #include "code/aotCodeCache.hpp"
  31 #include "code/codeCache.hpp"
  32 #include "code/compiledIC.hpp"
  33 #include "code/debugInfoRec.hpp"
  34 #include "code/vtableStubs.hpp"
  35 #include "compiler/oopMap.hpp"
  36 #include "gc/shared/barrierSetAssembler.hpp"
  37 #include "interpreter/interpreter.hpp"
  38 #include "interpreter/interp_masm.hpp"
  39 #include "logging/log.hpp"
  40 #include "memory/resourceArea.hpp"
  41 #include "nativeInst_aarch64.hpp"
  42 #include "oops/klass.inline.hpp"
  43 #include "oops/method.inline.hpp"
  44 #include "prims/methodHandles.hpp"
  45 #include "runtime/continuation.hpp"
  46 #include "runtime/continuationEntry.inline.hpp"
  47 #include "runtime/globals.hpp"
  48 #include "runtime/jniHandles.hpp"
  49 #include "runtime/safepointMechanism.hpp"
  50 #include "runtime/sharedRuntime.hpp"
  51 #include "runtime/signature.hpp"
  52 #include "runtime/stubRoutines.hpp"
  53 #include "runtime/timerTrace.hpp"
  54 #include "runtime/vframeArray.hpp"
  55 #include "utilities/align.hpp"
  56 #include "utilities/formatBuffer.hpp"
  57 #include "vmreg_aarch64.inline.hpp"
  58 #ifdef COMPILER1
  59 #include "c1/c1_Runtime1.hpp"
  60 #endif
  61 #ifdef COMPILER2
  62 #include "adfiles/ad_aarch64.hpp"
  63 #include "opto/runtime.hpp"
  64 #endif
  65 #if INCLUDE_JVMCI
  66 #include "jvmci/jvmciJavaClasses.hpp"
  67 #endif
  68 
  69 #define __ masm->
  70 
  71 #ifdef PRODUCT
  72 #define BLOCK_COMMENT(str) /* nothing */
  73 #else
  74 #define BLOCK_COMMENT(str) __ block_comment(str)
  75 #endif
  76 
  77 const int StackAlignmentInSlots = StackAlignmentInBytes / VMRegImpl::stack_slot_size;
  78 
  79 // FIXME -- this is used by C1
  80 class RegisterSaver {
  81   const bool _save_vectors;
  82  public:
  83   RegisterSaver(bool save_vectors) : _save_vectors(save_vectors) {}
  84 
  85   OopMap* save_live_registers(MacroAssembler* masm, int additional_frame_words, int* total_frame_words);
  86   void restore_live_registers(MacroAssembler* masm);
  87 
  88   // Offsets into the register save area
  89   // Used by deoptimization when it is managing result register
  90   // values on its own
  91 
  92   int reg_offset_in_bytes(Register r);
  93   int r0_offset_in_bytes()    { return reg_offset_in_bytes(r0); }
  94   int rscratch1_offset_in_bytes()    { return reg_offset_in_bytes(rscratch1); }
  95   int v0_offset_in_bytes();
  96 
  97   // Total stack size in bytes for saving sve predicate registers.
  98   int total_sve_predicate_in_bytes();
  99 
 100   // Capture info about frame layout
 101   // Note this is only correct when not saving full vectors.
 102   enum layout {
 103                 fpu_state_off = 0,
 104                 fpu_state_end = fpu_state_off + FPUStateSizeInWords - 1,
 105                 // The frame sender code expects that rfp will be in
 106                 // the "natural" place and will override any oopMap
 107                 // setting for it. We must therefore force the layout
 108                 // so that it agrees with the frame sender code.
 109                 r0_off = fpu_state_off + FPUStateSizeInWords,
 110                 rfp_off = r0_off + (Register::number_of_registers - 2) * Register::max_slots_per_register,
 111                 return_off = rfp_off + Register::max_slots_per_register,      // slot for return address
 112                 reg_save_size = return_off + Register::max_slots_per_register};
 113 
 114 };
 115 
 116 int RegisterSaver::reg_offset_in_bytes(Register r) {
 117   // The integer registers are located above the floating point
 118   // registers in the stack frame pushed by save_live_registers() so the
 119   // offset depends on whether we are saving full vectors, and whether
 120   // those vectors are NEON or SVE.
 121 
 122   int slots_per_vect = FloatRegister::save_slots_per_register;
 123 
 124 #if COMPILER2_OR_JVMCI
 125   if (_save_vectors) {
 126     slots_per_vect = FloatRegister::slots_per_neon_register;
 127 
 128 #ifdef COMPILER2
 129     if (Matcher::supports_scalable_vector()) {
 130       slots_per_vect = Matcher::scalable_vector_reg_size(T_FLOAT);
 131     }
 132 #endif
 133   }
 134 #endif
 135 
 136   int r0_offset = v0_offset_in_bytes() + (slots_per_vect * FloatRegister::number_of_registers) * BytesPerInt;
 137   return r0_offset + r->encoding() * wordSize;
 138 }
 139 
 140 int RegisterSaver::v0_offset_in_bytes() {
 141   // The floating point registers are located above the predicate registers if
 142   // they are present in the stack frame pushed by save_live_registers(). So the
 143   // offset depends on the saved total predicate vectors in the stack frame.
 144   return (total_sve_predicate_in_bytes() / VMRegImpl::stack_slot_size) * BytesPerInt;
 145 }
 146 
 147 int RegisterSaver::total_sve_predicate_in_bytes() {
 148 #ifdef COMPILER2
 149   if (_save_vectors && Matcher::supports_scalable_vector()) {
 150     return (Matcher::scalable_vector_reg_size(T_BYTE) >> LogBitsPerByte) *
 151            PRegister::number_of_registers;
 152   }
 153 #endif
 154   return 0;
 155 }
 156 
 157 OopMap* RegisterSaver::save_live_registers(MacroAssembler* masm, int additional_frame_words, int* total_frame_words) {
 158   bool use_sve = false;
 159   int sve_vector_size_in_bytes = 0;
 160   int sve_vector_size_in_slots = 0;
 161   int sve_predicate_size_in_slots = 0;
 162   int total_predicate_in_bytes = total_sve_predicate_in_bytes();
 163   int total_predicate_in_slots = total_predicate_in_bytes / VMRegImpl::stack_slot_size;
 164 
 165 #ifdef COMPILER2
 166   use_sve = Matcher::supports_scalable_vector();
 167   if (use_sve) {
 168     sve_vector_size_in_bytes = Matcher::scalable_vector_reg_size(T_BYTE);
 169     sve_vector_size_in_slots = Matcher::scalable_vector_reg_size(T_FLOAT);
 170     sve_predicate_size_in_slots = Matcher::scalable_predicate_reg_slots();
 171   }
 172 #endif
 173 
 174 #if COMPILER2_OR_JVMCI
 175   if (_save_vectors) {
 176     int extra_save_slots_per_register = 0;
 177     // Save upper half of vector registers
 178     if (use_sve) {
 179       extra_save_slots_per_register = sve_vector_size_in_slots - FloatRegister::save_slots_per_register;
 180     } else {
 181       extra_save_slots_per_register = FloatRegister::extra_save_slots_per_neon_register;
 182     }
 183     int extra_vector_bytes = extra_save_slots_per_register *
 184                              VMRegImpl::stack_slot_size *
 185                              FloatRegister::number_of_registers;
 186     additional_frame_words += ((extra_vector_bytes + total_predicate_in_bytes) / wordSize);
 187   }
 188 #else
 189   assert(!_save_vectors, "vectors are generated only by C2 and JVMCI");
 190 #endif
 191 
 192   int frame_size_in_bytes = align_up(additional_frame_words * wordSize +
 193                                      reg_save_size * BytesPerInt, 16);
 194   // OopMap frame size is in compiler stack slots (jint's) not bytes or words
 195   int frame_size_in_slots = frame_size_in_bytes / BytesPerInt;
 196   // The caller will allocate additional_frame_words
 197   int additional_frame_slots = additional_frame_words * wordSize / BytesPerInt;
 198   // CodeBlob frame size is in words.
 199   int frame_size_in_words = frame_size_in_bytes / wordSize;
 200   *total_frame_words = frame_size_in_words;
 201 
 202   // Save Integer and Float registers.
 203   __ enter();
 204   __ push_CPU_state(_save_vectors, use_sve, sve_vector_size_in_bytes, total_predicate_in_bytes);
 205 
 206   // Set an oopmap for the call site.  This oopmap will map all
 207   // oop-registers and debug-info registers as callee-saved.  This
 208   // will allow deoptimization at this safepoint to find all possible
 209   // debug-info recordings, as well as let GC find all oops.
 210 
 211   OopMapSet *oop_maps = new OopMapSet();
 212   OopMap* oop_map = new OopMap(frame_size_in_slots, 0);
 213 
 214   for (int i = 0; i < Register::number_of_registers; i++) {
 215     Register r = as_Register(i);
 216     if (i <= rfp->encoding() && r != rscratch1 && r != rscratch2) {
 217       // SP offsets are in 4-byte words.
 218       // Register slots are 8 bytes wide, 32 floating-point registers.
 219       int sp_offset = Register::max_slots_per_register * i +
 220                       FloatRegister::save_slots_per_register * FloatRegister::number_of_registers;
 221       oop_map->set_callee_saved(VMRegImpl::stack2reg(sp_offset + additional_frame_slots), r->as_VMReg());
 222     }
 223   }
 224 
 225   for (int i = 0; i < FloatRegister::number_of_registers; i++) {
 226     FloatRegister r = as_FloatRegister(i);
 227     int sp_offset = 0;
 228     if (_save_vectors) {
 229       sp_offset = use_sve ? (total_predicate_in_slots + sve_vector_size_in_slots * i) :
 230                             (FloatRegister::slots_per_neon_register * i);
 231     } else {
 232       sp_offset = FloatRegister::save_slots_per_register * i;
 233     }
 234     oop_map->set_callee_saved(VMRegImpl::stack2reg(sp_offset), r->as_VMReg());
 235   }
 236 
 237   return oop_map;
 238 }
 239 
 240 void RegisterSaver::restore_live_registers(MacroAssembler* masm) {
 241 #ifdef COMPILER2
 242   __ pop_CPU_state(_save_vectors, Matcher::supports_scalable_vector(),
 243                    Matcher::scalable_vector_reg_size(T_BYTE), total_sve_predicate_in_bytes());
 244 #else
 245 #if !INCLUDE_JVMCI
 246   assert(!_save_vectors, "vectors are generated only by C2 and JVMCI");
 247 #endif
 248   __ pop_CPU_state(_save_vectors);
 249 #endif
 250   __ ldp(rfp, lr, Address(__ post(sp, 2 * wordSize)));
 251   __ authenticate_return_address();
 252 }
 253 
 254 // Is vector's size (in bytes) bigger than a size saved by default?
 255 // 8 bytes vector registers are saved by default on AArch64.
 256 // The SVE supported min vector size is 8 bytes and we need to save
 257 // predicate registers when the vector size is 8 bytes as well.
 258 bool SharedRuntime::is_wide_vector(int size) {
 259   return size > 8 || (UseSVE > 0 && size >= 8);
 260 }
 261 
 262 // ---------------------------------------------------------------------------
 263 // Read the array of BasicTypes from a signature, and compute where the
 264 // arguments should go.  Values in the VMRegPair regs array refer to 4-byte
 265 // quantities.  Values less than VMRegImpl::stack0 are registers, those above
 266 // refer to 4-byte stack slots.  All stack slots are based off of the stack pointer
 267 // as framesizes are fixed.
 268 // VMRegImpl::stack0 refers to the first slot 0(sp).
 269 // and VMRegImpl::stack0+1 refers to the memory word 4-byes higher.
 270 // Register up to Register::number_of_registers are the 64-bit
 271 // integer registers.
 272 
 273 // Note: the INPUTS in sig_bt are in units of Java argument words,
 274 // which are 64-bit.  The OUTPUTS are in 32-bit units.
 275 
 276 // The Java calling convention is a "shifted" version of the C ABI.
 277 // By skipping the first C ABI register we can call non-static jni
 278 // methods with small numbers of arguments without having to shuffle
 279 // the arguments at all. Since we control the java ABI we ought to at
 280 // least get some advantage out of it.
 281 
 282 int SharedRuntime::java_calling_convention(const BasicType *sig_bt,
 283                                            VMRegPair *regs,
 284                                            int total_args_passed) {
 285 
 286   // Create the mapping between argument positions and
 287   // registers.
 288   static const Register INT_ArgReg[Argument::n_int_register_parameters_j] = {
 289     j_rarg0, j_rarg1, j_rarg2, j_rarg3, j_rarg4, j_rarg5, j_rarg6, j_rarg7
 290   };
 291   static const FloatRegister FP_ArgReg[Argument::n_float_register_parameters_j] = {
 292     j_farg0, j_farg1, j_farg2, j_farg3,
 293     j_farg4, j_farg5, j_farg6, j_farg7
 294   };
 295 
 296 
 297   uint int_args = 0;
 298   uint fp_args = 0;
 299   uint stk_args = 0;
 300 
 301   for (int i = 0; i < total_args_passed; i++) {
 302     switch (sig_bt[i]) {
 303     case T_BOOLEAN:
 304     case T_CHAR:
 305     case T_BYTE:
 306     case T_SHORT:
 307     case T_INT:
 308       if (int_args < Argument::n_int_register_parameters_j) {
 309         regs[i].set1(INT_ArgReg[int_args++]->as_VMReg());
 310       } else {
 311         stk_args = align_up(stk_args, 2);
 312         regs[i].set1(VMRegImpl::stack2reg(stk_args));
 313         stk_args += 1;
 314       }
 315       break;
 316     case T_VOID:
 317       // halves of T_LONG or T_DOUBLE
 318       assert(i != 0 && (sig_bt[i - 1] == T_LONG || sig_bt[i - 1] == T_DOUBLE), "expecting half");
 319       regs[i].set_bad();
 320       break;
 321     case T_LONG:
 322       assert((i + 1) < total_args_passed && sig_bt[i + 1] == T_VOID, "expecting half");
 323       // fall through
 324     case T_OBJECT:
 325     case T_ARRAY:
 326     case T_ADDRESS:
 327       if (int_args < Argument::n_int_register_parameters_j) {
 328         regs[i].set2(INT_ArgReg[int_args++]->as_VMReg());
 329       } else {
 330         stk_args = align_up(stk_args, 2);
 331         regs[i].set2(VMRegImpl::stack2reg(stk_args));
 332         stk_args += 2;
 333       }
 334       break;
 335     case T_FLOAT:
 336       if (fp_args < Argument::n_float_register_parameters_j) {
 337         regs[i].set1(FP_ArgReg[fp_args++]->as_VMReg());
 338       } else {
 339         stk_args = align_up(stk_args, 2);
 340         regs[i].set1(VMRegImpl::stack2reg(stk_args));
 341         stk_args += 1;
 342       }
 343       break;
 344     case T_DOUBLE:
 345       assert((i + 1) < total_args_passed && sig_bt[i + 1] == T_VOID, "expecting half");
 346       if (fp_args < Argument::n_float_register_parameters_j) {
 347         regs[i].set2(FP_ArgReg[fp_args++]->as_VMReg());
 348       } else {
 349         stk_args = align_up(stk_args, 2);
 350         regs[i].set2(VMRegImpl::stack2reg(stk_args));
 351         stk_args += 2;
 352       }
 353       break;
 354     default:
 355       ShouldNotReachHere();
 356       break;
 357     }
 358   }
 359 
 360   return stk_args;
 361 }
 362 
 363 
 364 const uint SharedRuntime::java_return_convention_max_int = Argument::n_int_register_parameters_j;
 365 const uint SharedRuntime::java_return_convention_max_float = Argument::n_float_register_parameters_j;
 366 
 367 int SharedRuntime::java_return_convention(const BasicType *sig_bt, VMRegPair *regs, int total_args_passed) {
 368 
 369   // Create the mapping between argument positions and registers.
 370 
 371   static const Register INT_ArgReg[java_return_convention_max_int] = {
 372     r0 /* j_rarg7 */, j_rarg6, j_rarg5, j_rarg4, j_rarg3, j_rarg2, j_rarg1, j_rarg0
 373   };
 374 
 375   static const FloatRegister FP_ArgReg[java_return_convention_max_float] = {
 376     j_farg0, j_farg1, j_farg2, j_farg3, j_farg4, j_farg5, j_farg6, j_farg7
 377   };
 378 
 379   uint int_args = 0;
 380   uint fp_args = 0;
 381 
 382   for (int i = 0; i < total_args_passed; i++) {
 383     switch (sig_bt[i]) {
 384     case T_BOOLEAN:
 385     case T_CHAR:
 386     case T_BYTE:
 387     case T_SHORT:
 388     case T_INT:
 389       if (int_args < SharedRuntime::java_return_convention_max_int) {
 390         regs[i].set1(INT_ArgReg[int_args]->as_VMReg());
 391         int_args ++;
 392       } else {
 393         return -1;
 394       }
 395       break;
 396     case T_VOID:
 397       // halves of T_LONG or T_DOUBLE
 398       assert(i != 0 && (sig_bt[i - 1] == T_LONG || sig_bt[i - 1] == T_DOUBLE), "expecting half");
 399       regs[i].set_bad();
 400       break;
 401     case T_LONG:
 402       assert((i + 1) < total_args_passed && sig_bt[i + 1] == T_VOID, "expecting half");
 403       // fall through
 404     case T_OBJECT:
 405     case T_ARRAY:
 406     case T_ADDRESS:
 407       // Should T_METADATA be added to java_calling_convention as well ?
 408     case T_METADATA:
 409       if (int_args < SharedRuntime::java_return_convention_max_int) {
 410         regs[i].set2(INT_ArgReg[int_args]->as_VMReg());
 411         int_args ++;
 412       } else {
 413         return -1;
 414       }
 415       break;
 416     case T_FLOAT:
 417       if (fp_args < SharedRuntime::java_return_convention_max_float) {
 418         regs[i].set1(FP_ArgReg[fp_args]->as_VMReg());
 419         fp_args ++;
 420       } else {
 421         return -1;
 422       }
 423       break;
 424     case T_DOUBLE:
 425       assert((i + 1) < total_args_passed && sig_bt[i + 1] == T_VOID, "expecting half");
 426       if (fp_args < SharedRuntime::java_return_convention_max_float) {
 427         regs[i].set2(FP_ArgReg[fp_args]->as_VMReg());
 428         fp_args ++;
 429       } else {
 430         return -1;
 431       }
 432       break;
 433     default:
 434       ShouldNotReachHere();
 435       break;
 436     }
 437   }
 438 
 439   return int_args + fp_args;
 440 }
 441 
 442 // Patch the callers callsite with entry to compiled code if it exists.
 443 static void patch_callers_callsite(MacroAssembler *masm) {
 444   Label L;
 445   __ ldr(rscratch1, Address(rmethod, in_bytes(Method::code_offset())));
 446   __ cbz(rscratch1, L);
 447 
 448   __ enter();
 449   __ push_CPU_state();
 450 
 451   // VM needs caller's callsite
 452   // VM needs target method
 453   // This needs to be a long call since we will relocate this adapter to
 454   // the codeBuffer and it may not reach
 455 
 456 #ifndef PRODUCT
 457   assert(frame::arg_reg_save_area_bytes == 0, "not expecting frame reg save area");
 458 #endif
 459 
 460   __ mov(c_rarg0, rmethod);
 461   __ mov(c_rarg1, lr);
 462   __ authenticate_return_address(c_rarg1);
 463   __ lea(rscratch1, RuntimeAddress(CAST_FROM_FN_PTR(address, SharedRuntime::fixup_callers_callsite)));
 464   __ blr(rscratch1);
 465 
 466   // Explicit isb required because fixup_callers_callsite may change the code
 467   // stream.
 468   __ safepoint_isb();
 469 
 470   __ pop_CPU_state();
 471   // restore sp
 472   __ leave();
 473   __ bind(L);
 474 }
 475 
 476 // For each inline type argument, sig includes the list of fields of
 477 // the inline type. This utility function computes the number of
 478 // arguments for the call if inline types are passed by reference (the
 479 // calling convention the interpreter expects).
 480 static int compute_total_args_passed_int(const GrowableArray<SigEntry>* sig_extended) {
 481   int total_args_passed = 0;
 482   if (InlineTypePassFieldsAsArgs) {
 483     for (int i = 0; i < sig_extended->length(); i++) {
 484       BasicType bt = sig_extended->at(i)._bt;
 485       if (bt == T_METADATA) {
 486         // In sig_extended, an inline type argument starts with:
 487         // T_METADATA, followed by the types of the fields of the
 488         // inline type and T_VOID to mark the end of the value
 489         // type. Inline types are flattened so, for instance, in the
 490         // case of an inline type with an int field and an inline type
 491         // field that itself has 2 fields, an int and a long:
 492         // T_METADATA T_INT T_METADATA T_INT T_LONG T_VOID (second
 493         // slot for the T_LONG) T_VOID (inner inline type) T_VOID
 494         // (outer inline type)
 495         total_args_passed++;
 496         int vt = 1;
 497         do {
 498           i++;
 499           BasicType bt = sig_extended->at(i)._bt;
 500           BasicType prev_bt = sig_extended->at(i-1)._bt;
 501           if (bt == T_METADATA) {
 502             vt++;
 503           } else if (bt == T_VOID &&
 504                      prev_bt != T_LONG &&
 505                      prev_bt != T_DOUBLE) {
 506             vt--;
 507           }
 508         } while (vt != 0);
 509       } else {
 510         total_args_passed++;
 511       }
 512     }
 513   } else {
 514     total_args_passed = sig_extended->length();
 515   }
 516   return total_args_passed;
 517 }
 518 
 519 
 520 static void gen_c2i_adapter_helper(MacroAssembler* masm,
 521                                    BasicType bt,
 522                                    BasicType prev_bt,
 523                                    size_t size_in_bytes,
 524                                    const VMRegPair& reg_pair,
 525                                    const Address& to,
 526                                    Register tmp1,
 527                                    Register tmp2,
 528                                    Register tmp3,
 529                                    int extraspace,
 530                                    bool is_oop) {
 531   if (bt == T_VOID) {
 532     assert(prev_bt == T_LONG || prev_bt == T_DOUBLE, "missing half");
 533     return;
 534   }
 535 
 536   // Say 4 args:
 537   // i   st_off
 538   // 0   32 T_LONG
 539   // 1   24 T_VOID
 540   // 2   16 T_OBJECT
 541   // 3    8 T_BOOL
 542   // -    0 return address
 543   //
 544   // However to make thing extra confusing. Because we can fit a Java long/double in
 545   // a single slot on a 64 bt vm and it would be silly to break them up, the interpreter
 546   // leaves one slot empty and only stores to a single slot. In this case the
 547   // slot that is occupied is the T_VOID slot. See I said it was confusing.
 548 
 549   bool wide = (size_in_bytes == wordSize);
 550   VMReg r_1 = reg_pair.first();
 551   VMReg r_2 = reg_pair.second();
 552   assert(r_2->is_valid() == wide, "invalid size");
 553   if (!r_1->is_valid()) {
 554     assert(!r_2->is_valid(), "");
 555     return;
 556   }
 557 
 558   if (!r_1->is_FloatRegister()) {
 559     Register val = r25;
 560     if (r_1->is_stack()) {
 561       // memory to memory use r25 (scratch registers is used by store_heap_oop)
 562       int ld_off = r_1->reg2stack() * VMRegImpl::stack_slot_size + extraspace;
 563       __ load_sized_value(val, Address(sp, ld_off), size_in_bytes, /* is_signed */ false);
 564     } else {
 565       val = r_1->as_Register();
 566     }
 567     assert_different_registers(to.base(), val, tmp1, tmp2, tmp3);
 568     if (is_oop) {
 569       __ store_heap_oop(to, val, tmp1, tmp2, tmp3, IN_HEAP | ACCESS_WRITE | IS_DEST_UNINITIALIZED);
 570     } else {
 571       __ store_sized_value(to, val, size_in_bytes);
 572     }
 573   } else {
 574     if (wide) {
 575       __ strd(r_1->as_FloatRegister(), to);
 576     } else {
 577       // only a float use just part of the slot
 578       __ strs(r_1->as_FloatRegister(), to);
 579     }
 580   }
 581 }
 582 
 583 static void gen_c2i_adapter(MacroAssembler *masm,
 584                             const GrowableArray<SigEntry>* sig_extended,
 585                             const VMRegPair *regs,
 586                             bool requires_clinit_barrier,
 587                             address& c2i_no_clinit_check_entry,
 588                             Label& skip_fixup,
 589                             address start,
 590                             OopMapSet* oop_maps,
 591                             int& frame_complete,
 592                             int& frame_size_in_words,
 593                             bool alloc_inline_receiver) {
 594   if (requires_clinit_barrier && VM_Version::supports_fast_class_init_checks()) {
 595     Label L_skip_barrier;
 596 
 597     { // Bypass the barrier for non-static methods
 598       __ ldrh(rscratch1, Address(rmethod, Method::access_flags_offset()));
 599       __ andsw(zr, rscratch1, JVM_ACC_STATIC);
 600       __ br(Assembler::EQ, L_skip_barrier); // non-static
 601     }
 602 
 603     __ load_method_holder(rscratch2, rmethod);
 604     __ clinit_barrier(rscratch2, rscratch1, &L_skip_barrier);
 605     __ far_jump(RuntimeAddress(SharedRuntime::get_handle_wrong_method_stub()));
 606 
 607     __ bind(L_skip_barrier);
 608     c2i_no_clinit_check_entry = __ pc();
 609   }
 610 
 611   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
 612   bs->c2i_entry_barrier(masm);
 613 
 614   // Before we get into the guts of the C2I adapter, see if we should be here
 615   // at all.  We've come from compiled code and are attempting to jump to the
 616   // interpreter, which means the caller made a static call to get here
 617   // (vcalls always get a compiled target if there is one).  Check for a
 618   // compiled target.  If there is one, we need to patch the caller's call.
 619   patch_callers_callsite(masm);
 620 
 621   __ bind(skip_fixup);
 622 
 623   // TODO 8366717 Is the comment about r13 correct? Isn't that r19_sender_sp?
 624   // Name some registers to be used in the following code. We can use
 625   // anything except r0-r7 which are arguments in the Java calling
 626   // convention, rmethod (r12), and r13 which holds the outgoing sender
 627   // SP for the interpreter.
 628   // TODO 8366717 We need to make sure that buf_array, buf_oop (and potentially other long-life regs) are kept live in slowpath runtime calls in GC barriers
 629   Register buf_array = r10;   // Array of buffered inline types
 630   Register buf_oop = r11;     // Buffered inline type oop
 631   Register tmp1 = r15;
 632   Register tmp2 = r16;
 633   Register tmp3 = r17;
 634 
 635   if (InlineTypePassFieldsAsArgs) {
 636     // Is there an inline type argument?
 637     bool has_inline_argument = false;
 638     for (int i = 0; i < sig_extended->length() && !has_inline_argument; i++) {
 639       has_inline_argument = (sig_extended->at(i)._bt == T_METADATA);
 640     }
 641     if (has_inline_argument) {
 642       // There is at least an inline type argument: we're coming from
 643       // compiled code so we have no buffers to back the inline types
 644       // Allocate the buffers here with a runtime call.
 645       // TODO 8366717 Do we need to save vectors here? They could be used as arg registers, right? Same on x64.
 646       RegisterSaver reg_save(true /* save_vectors */);
 647       OopMap* map = reg_save.save_live_registers(masm, 0, &frame_size_in_words);
 648 
 649       frame_complete = __ offset();
 650       address the_pc = __ pc();
 651 
 652       Label retaddr;
 653       __ set_last_Java_frame(sp, noreg, retaddr, rscratch1);
 654 
 655       __ mov(c_rarg0, rthread);
 656       __ mov(c_rarg1, rmethod);
 657       __ mov(c_rarg2, (int64_t)alloc_inline_receiver);
 658 
 659       __ lea(rscratch1, RuntimeAddress(CAST_FROM_FN_PTR(address, SharedRuntime::allocate_inline_types)));
 660       __ blr(rscratch1);
 661       __ bind(retaddr);
 662 
 663       oop_maps->add_gc_map(__ pc() - start, map);
 664       __ reset_last_Java_frame(false);
 665 
 666       reg_save.restore_live_registers(masm);
 667 
 668       Label no_exception;
 669       __ ldr(rscratch1, Address(rthread, Thread::pending_exception_offset()));
 670       __ cbz(rscratch1, no_exception);
 671 
 672       __ str(zr, Address(rthread, JavaThread::vm_result_oop_offset()));
 673       __ ldr(r0, Address(rthread, Thread::pending_exception_offset()));
 674       __ far_jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
 675 
 676       __ bind(no_exception);
 677 
 678       // We get an array of objects from the runtime call
 679       __ get_vm_result_oop(buf_array, rthread);
 680       __ get_vm_result_metadata(rmethod, rthread); // TODO: required to keep the callee Method live?
 681     }
 682   }
 683 
 684   // Since all args are passed on the stack, total_args_passed *
 685   // Interpreter::stackElementSize is the space we need.
 686 
 687   int total_args_passed = compute_total_args_passed_int(sig_extended);
 688   int extraspace = total_args_passed * Interpreter::stackElementSize;
 689 
 690   // stack is aligned, keep it that way
 691   extraspace = align_up(extraspace, StackAlignmentInBytes);
 692 
 693   // set senderSP value
 694   __ mov(r19_sender_sp, sp);
 695 
 696   __ sub(sp, sp, extraspace);
 697 
 698   // Now write the args into the outgoing interpreter space
 699 
 700   // next_arg_comp is the next argument from the compiler point of
 701   // view (inline type fields are passed in registers/on the stack). In
 702   // sig_extended, an inline type argument starts with: T_METADATA,
 703   // followed by the types of the fields of the inline type and T_VOID
 704   // to mark the end of the inline type. ignored counts the number of
 705   // T_METADATA/T_VOID. next_vt_arg is the next inline type argument:
 706   // used to get the buffer for that argument from the pool of buffers
 707   // we allocated above and want to pass to the
 708   // interpreter. next_arg_int is the next argument from the
 709   // interpreter point of view (inline types are passed by reference).
 710   for (int next_arg_comp = 0, ignored = 0, next_vt_arg = 0, next_arg_int = 0;
 711        next_arg_comp < sig_extended->length(); next_arg_comp++) {
 712     assert(ignored <= next_arg_comp, "shouldn't skip over more slots than there are arguments");
 713     assert(next_arg_int <= total_args_passed, "more arguments for the interpreter than expected?");
 714     BasicType bt = sig_extended->at(next_arg_comp)._bt;
 715     int st_off = (total_args_passed - next_arg_int - 1) * Interpreter::stackElementSize;
 716     if (!InlineTypePassFieldsAsArgs || bt != T_METADATA) {
 717       int next_off = st_off - Interpreter::stackElementSize;
 718       const int offset = (bt == T_LONG || bt == T_DOUBLE) ? next_off : st_off;
 719       const VMRegPair reg_pair = regs[next_arg_comp-ignored];
 720       size_t size_in_bytes = reg_pair.second()->is_valid() ? 8 : 4;
 721       gen_c2i_adapter_helper(masm, bt, next_arg_comp > 0 ? sig_extended->at(next_arg_comp-1)._bt : T_ILLEGAL,
 722                              size_in_bytes, reg_pair, Address(sp, offset), tmp1, tmp2, tmp3, extraspace, false);
 723       next_arg_int++;
 724 #ifdef ASSERT
 725       if (bt == T_LONG || bt == T_DOUBLE) {
 726         // Overwrite the unused slot with known junk
 727         __ mov(rscratch1, CONST64(0xdeadffffdeadaaaa));
 728         __ str(rscratch1, Address(sp, st_off));
 729       }
 730 #endif /* ASSERT */
 731     } else {
 732       ignored++;
 733       // get the buffer from the just allocated pool of buffers
 734       int index = arrayOopDesc::base_offset_in_bytes(T_OBJECT) + next_vt_arg * type2aelembytes(T_OBJECT);
 735       __ load_heap_oop(buf_oop, Address(buf_array, index), tmp1, tmp2);
 736       next_vt_arg++; next_arg_int++;
 737       int vt = 1;
 738       // write fields we get from compiled code in registers/stack
 739       // slots to the buffer: we know we are done with that inline type
 740       // argument when we hit the T_VOID that acts as an end of inline
 741       // type delimiter for this inline type. Inline types are flattened
 742       // so we might encounter embedded inline types. Each entry in
 743       // sig_extended contains a field offset in the buffer.
 744       Label L_null;
 745       do {
 746         next_arg_comp++;
 747         BasicType bt = sig_extended->at(next_arg_comp)._bt;
 748         BasicType prev_bt = sig_extended->at(next_arg_comp - 1)._bt;
 749         if (bt == T_METADATA) {
 750           vt++;
 751           ignored++;
 752         } else if (bt == T_VOID && prev_bt != T_LONG && prev_bt != T_DOUBLE) {
 753           vt--;
 754           ignored++;
 755         } else {
 756           int off = sig_extended->at(next_arg_comp)._offset;
 757           if (off == -1) {
 758             // Nullable inline type argument, emit null check
 759             VMReg reg = regs[next_arg_comp-ignored].first();
 760             Label L_notNull;
 761             if (reg->is_stack()) {
 762               int ld_off = reg->reg2stack() * VMRegImpl::stack_slot_size + extraspace;
 763               __ ldrb(tmp1, Address(sp, ld_off));
 764               __ cbnz(tmp1, L_notNull);
 765             } else {
 766               __ cbnz(reg->as_Register(), L_notNull);
 767             }
 768             __ str(zr, Address(sp, st_off));
 769             __ b(L_null);
 770             __ bind(L_notNull);
 771             continue;
 772           }
 773           assert(off > 0, "offset in object should be positive");
 774           size_t size_in_bytes = is_java_primitive(bt) ? type2aelembytes(bt) : wordSize;
 775           bool is_oop = is_reference_type(bt);
 776           gen_c2i_adapter_helper(masm, bt, next_arg_comp > 0 ? sig_extended->at(next_arg_comp-1)._bt : T_ILLEGAL,
 777                                  size_in_bytes, regs[next_arg_comp-ignored], Address(buf_oop, off), tmp1, tmp2, tmp3, extraspace, is_oop);
 778         }
 779       } while (vt != 0);
 780       // pass the buffer to the interpreter
 781       __ str(buf_oop, Address(sp, st_off));
 782       __ bind(L_null);
 783     }
 784   }
 785 
 786   __ mov(esp, sp); // Interp expects args on caller's expression stack
 787 
 788   __ ldr(rscratch1, Address(rmethod, in_bytes(Method::interpreter_entry_offset())));
 789   __ br(rscratch1);
 790 }
 791 
 792 void SharedRuntime::gen_i2c_adapter(MacroAssembler *masm, int comp_args_on_stack, const GrowableArray<SigEntry>* sig, const VMRegPair *regs) {
 793 
 794 
 795   // Note: r19_sender_sp contains the senderSP on entry. We must
 796   // preserve it since we may do a i2c -> c2i transition if we lose a
 797   // race where compiled code goes non-entrant while we get args
 798   // ready.
 799 
 800   // Adapters are frameless.
 801 
 802   // An i2c adapter is frameless because the *caller* frame, which is
 803   // interpreted, routinely repairs its own esp (from
 804   // interpreter_frame_last_sp), even if a callee has modified the
 805   // stack pointer.  It also recalculates and aligns sp.
 806 
 807   // A c2i adapter is frameless because the *callee* frame, which is
 808   // interpreted, routinely repairs its caller's sp (from sender_sp,
 809   // which is set up via the senderSP register).
 810 
 811   // In other words, if *either* the caller or callee is interpreted, we can
 812   // get the stack pointer repaired after a call.
 813 
 814   // This is why c2i and i2c adapters cannot be indefinitely composed.
 815   // In particular, if a c2i adapter were to somehow call an i2c adapter,
 816   // both caller and callee would be compiled methods, and neither would
 817   // clean up the stack pointer changes performed by the two adapters.
 818   // If this happens, control eventually transfers back to the compiled
 819   // caller, but with an uncorrected stack, causing delayed havoc.
 820 
 821   // Cut-out for having no stack args.
 822   int comp_words_on_stack = 0;
 823   if (comp_args_on_stack) {
 824      comp_words_on_stack = align_up(comp_args_on_stack * VMRegImpl::stack_slot_size, wordSize) >> LogBytesPerWord;
 825      __ sub(rscratch1, sp, comp_words_on_stack * wordSize);
 826      __ andr(sp, rscratch1, -16);
 827   }
 828 
 829   // Will jump to the compiled code just as if compiled code was doing it.
 830   // Pre-load the register-jump target early, to schedule it better.
 831   __ ldr(rscratch1, Address(rmethod, in_bytes(Method::from_compiled_inline_offset())));
 832 
 833 #if INCLUDE_JVMCI
 834   if (EnableJVMCI) {
 835     // check if this call should be routed towards a specific entry point
 836     __ ldr(rscratch2, Address(rthread, in_bytes(JavaThread::jvmci_alternate_call_target_offset())));
 837     Label no_alternative_target;
 838     __ cbz(rscratch2, no_alternative_target);
 839     __ mov(rscratch1, rscratch2);
 840     __ str(zr, Address(rthread, in_bytes(JavaThread::jvmci_alternate_call_target_offset())));
 841     __ bind(no_alternative_target);
 842   }
 843 #endif // INCLUDE_JVMCI
 844 
 845   int total_args_passed = sig->length();
 846 
 847   // Now generate the shuffle code.
 848   for (int i = 0; i < total_args_passed; i++) {
 849     BasicType bt = sig->at(i)._bt;
 850     if (bt == T_VOID) {
 851       assert(i > 0 && (sig->at(i - 1)._bt == T_LONG || sig->at(i - 1)._bt == T_DOUBLE), "missing half");
 852       continue;
 853     }
 854 
 855     // Pick up 0, 1 or 2 words from SP+offset.
 856     assert(!regs[i].second()->is_valid() || regs[i].first()->next() == regs[i].second(), "scrambled load targets?");
 857 
 858     // Load in argument order going down.
 859     int ld_off = (total_args_passed - i - 1) * Interpreter::stackElementSize;
 860     // Point to interpreter value (vs. tag)
 861     int next_off = ld_off - Interpreter::stackElementSize;
 862     //
 863     //
 864     //
 865     VMReg r_1 = regs[i].first();
 866     VMReg r_2 = regs[i].second();
 867     if (!r_1->is_valid()) {
 868       assert(!r_2->is_valid(), "");
 869       continue;
 870     }
 871     if (r_1->is_stack()) {
 872       // Convert stack slot to an SP offset (+ wordSize to account for return address )
 873       int st_off = regs[i].first()->reg2stack() * VMRegImpl::stack_slot_size;
 874       if (!r_2->is_valid()) {
 875         // sign extend???
 876         __ ldrsw(rscratch2, Address(esp, ld_off));
 877         __ str(rscratch2, Address(sp, st_off));
 878       } else {
 879         //
 880         // We are using two optoregs. This can be either T_OBJECT,
 881         // T_ADDRESS, T_LONG, or T_DOUBLE the interpreter allocates
 882         // two slots but only uses one for thr T_LONG or T_DOUBLE case
 883         // So we must adjust where to pick up the data to match the
 884         // interpreter.
 885         //
 886         // Interpreter local[n] == MSW, local[n+1] == LSW however locals
 887         // are accessed as negative so LSW is at LOW address
 888 
 889         // ld_off is MSW so get LSW
 890         const int offset = (bt == T_LONG || bt == T_DOUBLE) ? next_off : ld_off;
 891         __ ldr(rscratch2, Address(esp, offset));
 892         // st_off is LSW (i.e. reg.first())
 893          __ str(rscratch2, Address(sp, st_off));
 894        }
 895      } else if (r_1->is_Register()) {  // Register argument
 896        Register r = r_1->as_Register();
 897        if (r_2->is_valid()) {
 898          //
 899          // We are using two VMRegs. This can be either T_OBJECT,
 900          // T_ADDRESS, T_LONG, or T_DOUBLE the interpreter allocates
 901          // two slots but only uses one for thr T_LONG or T_DOUBLE case
 902          // So we must adjust where to pick up the data to match the
 903          // interpreter.
 904 
 905         const int offset = (bt == T_LONG || bt == T_DOUBLE) ? next_off : ld_off;
 906 
 907          // this can be a misaligned move
 908          __ ldr(r, Address(esp, offset));
 909        } else {
 910          // sign extend and use a full word?
 911          __ ldrw(r, Address(esp, ld_off));
 912        }
 913      } else {
 914        if (!r_2->is_valid()) {
 915          __ ldrs(r_1->as_FloatRegister(), Address(esp, ld_off));
 916        } else {
 917          __ ldrd(r_1->as_FloatRegister(), Address(esp, next_off));
 918        }
 919      }
 920    }
 921 
 922 
 923   __ mov(rscratch2, rscratch1);
 924   __ push_cont_fastpath(rthread); // Set JavaThread::_cont_fastpath to the sp of the oldest interpreted frame we know about; kills rscratch1
 925   __ mov(rscratch1, rscratch2);
 926 
 927   // 6243940 We might end up in handle_wrong_method if
 928   // the callee is deoptimized as we race thru here. If that
 929   // happens we don't want to take a safepoint because the
 930   // caller frame will look interpreted and arguments are now
 931   // "compiled" so it is much better to make this transition
 932   // invisible to the stack walking code. Unfortunately if
 933   // we try and find the callee by normal means a safepoint
 934   // is possible. So we stash the desired callee in the thread
 935   // and the vm will find there should this case occur.
 936 
 937   __ str(rmethod, Address(rthread, JavaThread::callee_target_offset()));
 938   __ br(rscratch1);
 939 }
 940 
 941 static void gen_inline_cache_check(MacroAssembler *masm, Label& skip_fixup) {
 942   Register data = rscratch2;
 943   __ ic_check(1 /* end_alignment */);
 944   __ ldr(rmethod, Address(data, CompiledICData::speculated_method_offset()));
 945 
 946   // Method might have been compiled since the call site was patched to
 947   // interpreted; if that is the case treat it as a miss so we can get
 948   // the call site corrected.
 949   __ ldr(rscratch1, Address(rmethod, in_bytes(Method::code_offset())));
 950   __ cbz(rscratch1, skip_fixup);
 951   __ far_jump(RuntimeAddress(SharedRuntime::get_ic_miss_stub()));
 952 }
 953 
 954 // ---------------------------------------------------------------
 955 void SharedRuntime::generate_i2c2i_adapters(MacroAssembler* masm,
 956                                             int comp_args_on_stack,
 957                                             const GrowableArray<SigEntry>* sig,
 958                                             const VMRegPair* regs,
 959                                             const GrowableArray<SigEntry>* sig_cc,
 960                                             const VMRegPair* regs_cc,
 961                                             const GrowableArray<SigEntry>* sig_cc_ro,
 962                                             const VMRegPair* regs_cc_ro,
 963                                             AdapterHandlerEntry* handler,
 964                                             AdapterBlob*& new_adapter,
 965                                             bool allocate_code_blob) {
 966   address i2c_entry = __ pc();
 967   gen_i2c_adapter(masm, comp_args_on_stack, sig, regs);
 968 
 969   // -------------------------------------------------------------------------
 970   // Generate a C2I adapter.  On entry we know rmethod holds the Method* during calls
 971   // to the interpreter.  The args start out packed in the compiled layout.  They
 972   // need to be unpacked into the interpreter layout.  This will almost always
 973   // require some stack space.  We grow the current (compiled) stack, then repack
 974   // the args.  We  finally end in a jump to the generic interpreter entry point.
 975   // On exit from the interpreter, the interpreter will restore our SP (lest the
 976   // compiled code, which relies solely on SP and not FP, get sick).
 977 
 978   address c2i_unverified_entry        = __ pc();
 979   address c2i_unverified_inline_entry = __ pc();
 980   Label skip_fixup;
 981 
 982   gen_inline_cache_check(masm, skip_fixup);
 983 
 984   OopMapSet* oop_maps = new OopMapSet();
 985   int frame_complete = CodeOffsets::frame_never_safe;
 986   int frame_size_in_words = 0;
 987 
 988   // Scalarized c2i adapter with non-scalarized receiver (i.e., don't pack receiver)
 989   address c2i_no_clinit_check_entry = nullptr;
 990   address c2i_inline_ro_entry = __ pc();
 991   if (regs_cc != regs_cc_ro) {
 992     // No class init barrier needed because method is guaranteed to be non-static
 993     gen_c2i_adapter(masm, sig_cc_ro, regs_cc_ro, /* requires_clinit_barrier = */ false, c2i_no_clinit_check_entry,
 994                     skip_fixup, i2c_entry, oop_maps, frame_complete, frame_size_in_words, /* alloc_inline_receiver = */ false);
 995     skip_fixup.reset();
 996   }
 997 
 998   // Scalarized c2i adapter
 999   address c2i_entry        = __ pc();
1000   address c2i_inline_entry = __ pc();
1001   gen_c2i_adapter(masm, sig_cc, regs_cc, /* requires_clinit_barrier = */ true, c2i_no_clinit_check_entry,
1002                   skip_fixup, i2c_entry, oop_maps, frame_complete, frame_size_in_words, /* alloc_inline_receiver = */ true);
1003 
1004   // Non-scalarized c2i adapter
1005   if (regs != regs_cc) {
1006     c2i_unverified_inline_entry = __ pc();
1007     Label inline_entry_skip_fixup;
1008     gen_inline_cache_check(masm, inline_entry_skip_fixup);
1009 
1010     c2i_inline_entry = __ pc();
1011     gen_c2i_adapter(masm, sig, regs, /* requires_clinit_barrier = */ true, c2i_no_clinit_check_entry,
1012                     inline_entry_skip_fixup, i2c_entry, oop_maps, frame_complete, frame_size_in_words, /* alloc_inline_receiver = */ false);
1013   }
1014 
1015   // The c2i adapters might safepoint and trigger a GC. The caller must make sure that
1016   // the GC knows about the location of oop argument locations passed to the c2i adapter.
1017   if (allocate_code_blob) {
1018     bool caller_must_gc_arguments = (regs != regs_cc);
1019     int entry_offset[AdapterHandlerEntry::ENTRIES_COUNT];
1020     assert(AdapterHandlerEntry::ENTRIES_COUNT == 7, "sanity");
1021     entry_offset[0] = 0; // i2c_entry offset
1022     entry_offset[1] = c2i_entry - i2c_entry;
1023     entry_offset[2] = c2i_inline_entry - i2c_entry;
1024     entry_offset[3] = c2i_inline_ro_entry - i2c_entry;
1025     entry_offset[4] = c2i_unverified_entry - i2c_entry;
1026     entry_offset[5] = c2i_unverified_inline_entry - i2c_entry;
1027     entry_offset[6] = c2i_no_clinit_check_entry - i2c_entry;
1028     new_adapter = AdapterBlob::create(masm->code(), entry_offset, frame_complete, frame_size_in_words, oop_maps, caller_must_gc_arguments);
1029   }
1030 
1031   handler->set_entry_points(i2c_entry, c2i_entry, c2i_inline_entry, c2i_inline_ro_entry, c2i_unverified_entry,
1032                             c2i_unverified_inline_entry, c2i_no_clinit_check_entry);
1033 }
1034 
1035 static int c_calling_convention_priv(const BasicType *sig_bt,
1036                                          VMRegPair *regs,
1037                                          int total_args_passed) {
1038 
1039 // We return the amount of VMRegImpl stack slots we need to reserve for all
1040 // the arguments NOT counting out_preserve_stack_slots.
1041 
1042     static const Register INT_ArgReg[Argument::n_int_register_parameters_c] = {
1043       c_rarg0, c_rarg1, c_rarg2, c_rarg3, c_rarg4, c_rarg5,  c_rarg6,  c_rarg7
1044     };
1045     static const FloatRegister FP_ArgReg[Argument::n_float_register_parameters_c] = {
1046       c_farg0, c_farg1, c_farg2, c_farg3,
1047       c_farg4, c_farg5, c_farg6, c_farg7
1048     };
1049 
1050     uint int_args = 0;
1051     uint fp_args = 0;
1052     uint stk_args = 0; // inc by 2 each time
1053 
1054     for (int i = 0; i < total_args_passed; i++) {
1055       switch (sig_bt[i]) {
1056       case T_BOOLEAN:
1057       case T_CHAR:
1058       case T_BYTE:
1059       case T_SHORT:
1060       case T_INT:
1061         if (int_args < Argument::n_int_register_parameters_c) {
1062           regs[i].set1(INT_ArgReg[int_args++]->as_VMReg());
1063         } else {
1064 #ifdef __APPLE__
1065           // Less-than word types are stored one after another.
1066           // The code is unable to handle this so bailout.
1067           return -1;
1068 #endif
1069           regs[i].set1(VMRegImpl::stack2reg(stk_args));
1070           stk_args += 2;
1071         }
1072         break;
1073       case T_LONG:
1074         assert((i + 1) < total_args_passed && sig_bt[i + 1] == T_VOID, "expecting half");
1075         // fall through
1076       case T_OBJECT:
1077       case T_ARRAY:
1078       case T_ADDRESS:
1079       case T_METADATA:
1080         if (int_args < Argument::n_int_register_parameters_c) {
1081           regs[i].set2(INT_ArgReg[int_args++]->as_VMReg());
1082         } else {
1083           regs[i].set2(VMRegImpl::stack2reg(stk_args));
1084           stk_args += 2;
1085         }
1086         break;
1087       case T_FLOAT:
1088         if (fp_args < Argument::n_float_register_parameters_c) {
1089           regs[i].set1(FP_ArgReg[fp_args++]->as_VMReg());
1090         } else {
1091 #ifdef __APPLE__
1092           // Less-than word types are stored one after another.
1093           // The code is unable to handle this so bailout.
1094           return -1;
1095 #endif
1096           regs[i].set1(VMRegImpl::stack2reg(stk_args));
1097           stk_args += 2;
1098         }
1099         break;
1100       case T_DOUBLE:
1101         assert((i + 1) < total_args_passed && sig_bt[i + 1] == T_VOID, "expecting half");
1102         if (fp_args < Argument::n_float_register_parameters_c) {
1103           regs[i].set2(FP_ArgReg[fp_args++]->as_VMReg());
1104         } else {
1105           regs[i].set2(VMRegImpl::stack2reg(stk_args));
1106           stk_args += 2;
1107         }
1108         break;
1109       case T_VOID: // Halves of longs and doubles
1110         assert(i != 0 && (sig_bt[i - 1] == T_LONG || sig_bt[i - 1] == T_DOUBLE), "expecting half");
1111         regs[i].set_bad();
1112         break;
1113       default:
1114         ShouldNotReachHere();
1115         break;
1116       }
1117     }
1118 
1119   return stk_args;
1120 }
1121 
1122 int SharedRuntime::vector_calling_convention(VMRegPair *regs,
1123                                              uint num_bits,
1124                                              uint total_args_passed) {
1125   // More than 8 argument inputs are not supported now.
1126   assert(total_args_passed <= Argument::n_float_register_parameters_c, "unsupported");
1127   assert(num_bits >= 64 && num_bits <= 2048 && is_power_of_2(num_bits), "unsupported");
1128 
1129   static const FloatRegister VEC_ArgReg[Argument::n_float_register_parameters_c] = {
1130     v0, v1, v2, v3, v4, v5, v6, v7
1131   };
1132 
1133   // On SVE, we use the same vector registers with 128-bit vector registers on NEON.
1134   int next_reg_val = num_bits == 64 ? 1 : 3;
1135   for (uint i = 0; i < total_args_passed; i++) {
1136     VMReg vmreg = VEC_ArgReg[i]->as_VMReg();
1137     regs[i].set_pair(vmreg->next(next_reg_val), vmreg);
1138   }
1139   return 0;
1140 }
1141 
1142 int SharedRuntime::c_calling_convention(const BasicType *sig_bt,
1143                                          VMRegPair *regs,
1144                                          int total_args_passed)
1145 {
1146   int result = c_calling_convention_priv(sig_bt, regs, total_args_passed);
1147   guarantee(result >= 0, "Unsupported arguments configuration");
1148   return result;
1149 }
1150 
1151 
1152 void SharedRuntime::save_native_result(MacroAssembler *masm, BasicType ret_type, int frame_slots) {
1153   // We always ignore the frame_slots arg and just use the space just below frame pointer
1154   // which by this time is free to use
1155   switch (ret_type) {
1156   case T_FLOAT:
1157     __ strs(v0, Address(rfp, -wordSize));
1158     break;
1159   case T_DOUBLE:
1160     __ strd(v0, Address(rfp, -wordSize));
1161     break;
1162   case T_VOID:  break;
1163   default: {
1164     __ str(r0, Address(rfp, -wordSize));
1165     }
1166   }
1167 }
1168 
1169 void SharedRuntime::restore_native_result(MacroAssembler *masm, BasicType ret_type, int frame_slots) {
1170   // We always ignore the frame_slots arg and just use the space just below frame pointer
1171   // which by this time is free to use
1172   switch (ret_type) {
1173   case T_FLOAT:
1174     __ ldrs(v0, Address(rfp, -wordSize));
1175     break;
1176   case T_DOUBLE:
1177     __ ldrd(v0, Address(rfp, -wordSize));
1178     break;
1179   case T_VOID:  break;
1180   default: {
1181     __ ldr(r0, Address(rfp, -wordSize));
1182     }
1183   }
1184 }
1185 static void save_args(MacroAssembler *masm, int arg_count, int first_arg, VMRegPair *args) {
1186   RegSet x;
1187   for ( int i = first_arg ; i < arg_count ; i++ ) {
1188     if (args[i].first()->is_Register()) {
1189       x = x + args[i].first()->as_Register();
1190     } else if (args[i].first()->is_FloatRegister()) {
1191       __ strd(args[i].first()->as_FloatRegister(), Address(__ pre(sp, -2 * wordSize)));
1192     }
1193   }
1194   __ push(x, sp);
1195 }
1196 
1197 static void restore_args(MacroAssembler *masm, int arg_count, int first_arg, VMRegPair *args) {
1198   RegSet x;
1199   for ( int i = first_arg ; i < arg_count ; i++ ) {
1200     if (args[i].first()->is_Register()) {
1201       x = x + args[i].first()->as_Register();
1202     } else {
1203       ;
1204     }
1205   }
1206   __ pop(x, sp);
1207   for ( int i = arg_count - 1 ; i >= first_arg ; i-- ) {
1208     if (args[i].first()->is_Register()) {
1209       ;
1210     } else if (args[i].first()->is_FloatRegister()) {
1211       __ ldrd(args[i].first()->as_FloatRegister(), Address(__ post(sp, 2 * wordSize)));
1212     }
1213   }
1214 }
1215 
1216 static void verify_oop_args(MacroAssembler* masm,
1217                             const methodHandle& method,
1218                             const BasicType* sig_bt,
1219                             const VMRegPair* regs) {
1220   Register temp_reg = r19;  // not part of any compiled calling seq
1221   if (VerifyOops) {
1222     for (int i = 0; i < method->size_of_parameters(); i++) {
1223       if (sig_bt[i] == T_OBJECT ||
1224           sig_bt[i] == T_ARRAY) {
1225         VMReg r = regs[i].first();
1226         assert(r->is_valid(), "bad oop arg");
1227         if (r->is_stack()) {
1228           __ ldr(temp_reg, Address(sp, r->reg2stack() * VMRegImpl::stack_slot_size));
1229           __ verify_oop(temp_reg);
1230         } else {
1231           __ verify_oop(r->as_Register());
1232         }
1233       }
1234     }
1235   }
1236 }
1237 
1238 // on exit, sp points to the ContinuationEntry
1239 static OopMap* continuation_enter_setup(MacroAssembler* masm, int& stack_slots) {
1240   assert(ContinuationEntry::size() % VMRegImpl::stack_slot_size == 0, "");
1241   assert(in_bytes(ContinuationEntry::cont_offset())  % VMRegImpl::stack_slot_size == 0, "");
1242   assert(in_bytes(ContinuationEntry::chunk_offset()) % VMRegImpl::stack_slot_size == 0, "");
1243 
1244   stack_slots += (int)ContinuationEntry::size()/wordSize;
1245   __ sub(sp, sp, (int)ContinuationEntry::size()); // place Continuation metadata
1246 
1247   OopMap* map = new OopMap(((int)ContinuationEntry::size() + wordSize)/ VMRegImpl::stack_slot_size, 0 /* arg_slots*/);
1248 
1249   __ ldr(rscratch1, Address(rthread, JavaThread::cont_entry_offset()));
1250   __ str(rscratch1, Address(sp, ContinuationEntry::parent_offset()));
1251   __ mov(rscratch1, sp); // we can't use sp as the source in str
1252   __ str(rscratch1, Address(rthread, JavaThread::cont_entry_offset()));
1253 
1254   return map;
1255 }
1256 
1257 // on entry c_rarg1 points to the continuation
1258 //          sp points to ContinuationEntry
1259 //          c_rarg3 -- isVirtualThread
1260 static void fill_continuation_entry(MacroAssembler* masm) {
1261 #ifdef ASSERT
1262   __ movw(rscratch1, ContinuationEntry::cookie_value());
1263   __ strw(rscratch1, Address(sp, ContinuationEntry::cookie_offset()));
1264 #endif
1265 
1266   __ str (c_rarg1, Address(sp, ContinuationEntry::cont_offset()));
1267   __ strw(c_rarg3, Address(sp, ContinuationEntry::flags_offset()));
1268   __ str (zr,      Address(sp, ContinuationEntry::chunk_offset()));
1269   __ strw(zr,      Address(sp, ContinuationEntry::argsize_offset()));
1270   __ strw(zr,      Address(sp, ContinuationEntry::pin_count_offset()));
1271 
1272   __ ldr(rscratch1, Address(rthread, JavaThread::cont_fastpath_offset()));
1273   __ str(rscratch1, Address(sp, ContinuationEntry::parent_cont_fastpath_offset()));
1274   __ ldr(rscratch1, Address(rthread, JavaThread::held_monitor_count_offset()));
1275   __ str(rscratch1, Address(sp, ContinuationEntry::parent_held_monitor_count_offset()));
1276 
1277   __ str(zr, Address(rthread, JavaThread::cont_fastpath_offset()));
1278   __ str(zr, Address(rthread, JavaThread::held_monitor_count_offset()));
1279 }
1280 
1281 // on entry, sp points to the ContinuationEntry
1282 // on exit, rfp points to the spilled rfp in the entry frame
1283 static void continuation_enter_cleanup(MacroAssembler* masm) {
1284 #ifndef PRODUCT
1285   Label OK;
1286   __ ldr(rscratch1, Address(rthread, JavaThread::cont_entry_offset()));
1287   __ cmp(sp, rscratch1);
1288   __ br(Assembler::EQ, OK);
1289   __ stop("incorrect sp1");
1290   __ bind(OK);
1291 #endif
1292   __ ldr(rscratch1, Address(sp, ContinuationEntry::parent_cont_fastpath_offset()));
1293   __ str(rscratch1, Address(rthread, JavaThread::cont_fastpath_offset()));
1294 
1295   if (CheckJNICalls) {
1296     // Check if this is a virtual thread continuation
1297     Label L_skip_vthread_code;
1298     __ ldrw(rscratch1, Address(sp, ContinuationEntry::flags_offset()));
1299     __ cbzw(rscratch1, L_skip_vthread_code);
1300 
1301     // If the held monitor count is > 0 and this vthread is terminating then
1302     // it failed to release a JNI monitor. So we issue the same log message
1303     // that JavaThread::exit does.
1304     __ ldr(rscratch1, Address(rthread, JavaThread::jni_monitor_count_offset()));
1305     __ cbz(rscratch1, L_skip_vthread_code);
1306 
1307     // Save return value potentially containing the exception oop in callee-saved R19.
1308     __ mov(r19, r0);
1309     __ call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::log_jni_monitor_still_held));
1310     // Restore potential return value.
1311     __ mov(r0, r19);
1312 
1313     // For vthreads we have to explicitly zero the JNI monitor count of the carrier
1314     // on termination. The held count is implicitly zeroed below when we restore from
1315     // the parent held count (which has to be zero).
1316     __ str(zr, Address(rthread, JavaThread::jni_monitor_count_offset()));
1317 
1318     __ bind(L_skip_vthread_code);
1319   }
1320 #ifdef ASSERT
1321   else {
1322     // Check if this is a virtual thread continuation
1323     Label L_skip_vthread_code;
1324     __ ldrw(rscratch1, Address(sp, ContinuationEntry::flags_offset()));
1325     __ cbzw(rscratch1, L_skip_vthread_code);
1326 
1327     // See comment just above. If not checking JNI calls the JNI count is only
1328     // needed for assertion checking.
1329     __ str(zr, Address(rthread, JavaThread::jni_monitor_count_offset()));
1330 
1331     __ bind(L_skip_vthread_code);
1332   }
1333 #endif
1334 
1335   __ ldr(rscratch1, Address(sp, ContinuationEntry::parent_held_monitor_count_offset()));
1336   __ str(rscratch1, Address(rthread, JavaThread::held_monitor_count_offset()));
1337 
1338   __ ldr(rscratch2, Address(sp, ContinuationEntry::parent_offset()));
1339   __ str(rscratch2, Address(rthread, JavaThread::cont_entry_offset()));
1340   __ add(rfp, sp, (int)ContinuationEntry::size());
1341 }
1342 
1343 // enterSpecial(Continuation c, boolean isContinue, boolean isVirtualThread)
1344 // On entry: c_rarg1 -- the continuation object
1345 //           c_rarg2 -- isContinue
1346 //           c_rarg3 -- isVirtualThread
1347 static void gen_continuation_enter(MacroAssembler* masm,
1348                                  const methodHandle& method,
1349                                  const BasicType* sig_bt,
1350                                  const VMRegPair* regs,
1351                                  int& exception_offset,
1352                                  OopMapSet*oop_maps,
1353                                  int& frame_complete,
1354                                  int& stack_slots,
1355                                  int& interpreted_entry_offset,
1356                                  int& compiled_entry_offset) {
1357   //verify_oop_args(masm, method, sig_bt, regs);
1358   Address resolve(SharedRuntime::get_resolve_static_call_stub(), relocInfo::static_call_type);
1359 
1360   address start = __ pc();
1361 
1362   Label call_thaw, exit;
1363 
1364   // i2i entry used at interp_only_mode only
1365   interpreted_entry_offset = __ pc() - start;
1366   {
1367 
1368 #ifdef ASSERT
1369     Label is_interp_only;
1370     __ ldrw(rscratch1, Address(rthread, JavaThread::interp_only_mode_offset()));
1371     __ cbnzw(rscratch1, is_interp_only);
1372     __ stop("enterSpecial interpreter entry called when not in interp_only_mode");
1373     __ bind(is_interp_only);
1374 #endif
1375 
1376     // Read interpreter arguments into registers (this is an ad-hoc i2c adapter)
1377     __ ldr(c_rarg1, Address(esp, Interpreter::stackElementSize*2));
1378     __ ldr(c_rarg2, Address(esp, Interpreter::stackElementSize*1));
1379     __ ldr(c_rarg3, Address(esp, Interpreter::stackElementSize*0));
1380     __ push_cont_fastpath(rthread);
1381 
1382     __ enter();
1383     stack_slots = 2; // will be adjusted in setup
1384     OopMap* map = continuation_enter_setup(masm, stack_slots);
1385     // The frame is complete here, but we only record it for the compiled entry, so the frame would appear unsafe,
1386     // but that's okay because at the very worst we'll miss an async sample, but we're in interp_only_mode anyway.
1387 
1388     fill_continuation_entry(masm);
1389 
1390     __ cbnz(c_rarg2, call_thaw);
1391 
1392     const address tr_call = __ trampoline_call(resolve);
1393     if (tr_call == nullptr) {
1394       fatal("CodeCache is full at gen_continuation_enter");
1395     }
1396 
1397     oop_maps->add_gc_map(__ pc() - start, map);
1398     __ post_call_nop();
1399 
1400     __ b(exit);
1401 
1402     address stub = CompiledDirectCall::emit_to_interp_stub(masm, tr_call);
1403     if (stub == nullptr) {
1404       fatal("CodeCache is full at gen_continuation_enter");
1405     }
1406   }
1407 
1408   // compiled entry
1409   __ align(CodeEntryAlignment);
1410   compiled_entry_offset = __ pc() - start;
1411 
1412   __ enter();
1413   stack_slots = 2; // will be adjusted in setup
1414   OopMap* map = continuation_enter_setup(masm, stack_slots);
1415   frame_complete = __ pc() - start;
1416 
1417   fill_continuation_entry(masm);
1418 
1419   __ cbnz(c_rarg2, call_thaw);
1420 
1421   const address tr_call = __ trampoline_call(resolve);
1422   if (tr_call == nullptr) {
1423     fatal("CodeCache is full at gen_continuation_enter");
1424   }
1425 
1426   oop_maps->add_gc_map(__ pc() - start, map);
1427   __ post_call_nop();
1428 
1429   __ b(exit);
1430 
1431   __ bind(call_thaw);
1432 
1433   ContinuationEntry::_thaw_call_pc_offset = __ pc() - start;
1434   __ rt_call(CAST_FROM_FN_PTR(address, StubRoutines::cont_thaw()));
1435   oop_maps->add_gc_map(__ pc() - start, map->deep_copy());
1436   ContinuationEntry::_return_pc_offset = __ pc() - start;
1437   __ post_call_nop();
1438 
1439   __ bind(exit);
1440   ContinuationEntry::_cleanup_offset = __ pc() - start;
1441   continuation_enter_cleanup(masm);
1442   __ leave();
1443   __ ret(lr);
1444 
1445   /// exception handling
1446 
1447   exception_offset = __ pc() - start;
1448   {
1449       __ mov(r19, r0); // save return value contaning the exception oop in callee-saved R19
1450 
1451       continuation_enter_cleanup(masm);
1452 
1453       __ ldr(c_rarg1, Address(rfp, wordSize)); // return address
1454       __ authenticate_return_address(c_rarg1);
1455       __ call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::exception_handler_for_return_address), rthread, c_rarg1);
1456 
1457       // see OptoRuntime::generate_exception_blob: r0 -- exception oop, r3 -- exception pc
1458 
1459       __ mov(r1, r0); // the exception handler
1460       __ mov(r0, r19); // restore return value contaning the exception oop
1461       __ verify_oop(r0);
1462 
1463       __ leave();
1464       __ mov(r3, lr);
1465       __ br(r1); // the exception handler
1466   }
1467 
1468   address stub = CompiledDirectCall::emit_to_interp_stub(masm, tr_call);
1469   if (stub == nullptr) {
1470     fatal("CodeCache is full at gen_continuation_enter");
1471   }
1472 }
1473 
1474 static void gen_continuation_yield(MacroAssembler* masm,
1475                                    const methodHandle& method,
1476                                    const BasicType* sig_bt,
1477                                    const VMRegPair* regs,
1478                                    OopMapSet* oop_maps,
1479                                    int& frame_complete,
1480                                    int& stack_slots,
1481                                    int& compiled_entry_offset) {
1482     enum layout {
1483       rfp_off1,
1484       rfp_off2,
1485       lr_off,
1486       lr_off2,
1487       framesize // inclusive of return address
1488     };
1489     // assert(is_even(framesize/2), "sp not 16-byte aligned");
1490     stack_slots = framesize /  VMRegImpl::slots_per_word;
1491     assert(stack_slots == 2, "recheck layout");
1492 
1493     address start = __ pc();
1494 
1495     compiled_entry_offset = __ pc() - start;
1496     __ enter();
1497 
1498     __ mov(c_rarg1, sp);
1499 
1500     frame_complete = __ pc() - start;
1501     address the_pc = __ pc();
1502 
1503     __ post_call_nop(); // this must be exactly after the pc value that is pushed into the frame info, we use this nop for fast CodeBlob lookup
1504 
1505     __ mov(c_rarg0, rthread);
1506     __ set_last_Java_frame(sp, rfp, the_pc, rscratch1);
1507     __ call_VM_leaf(Continuation::freeze_entry(), 2);
1508     __ reset_last_Java_frame(true);
1509 
1510     Label pinned;
1511 
1512     __ cbnz(r0, pinned);
1513 
1514     // We've succeeded, set sp to the ContinuationEntry
1515     __ ldr(rscratch1, Address(rthread, JavaThread::cont_entry_offset()));
1516     __ mov(sp, rscratch1);
1517     continuation_enter_cleanup(masm);
1518 
1519     __ bind(pinned); // pinned -- return to caller
1520 
1521     // handle pending exception thrown by freeze
1522     __ ldr(rscratch1, Address(rthread, in_bytes(Thread::pending_exception_offset())));
1523     Label ok;
1524     __ cbz(rscratch1, ok);
1525     __ leave();
1526     __ lea(rscratch1, RuntimeAddress(StubRoutines::forward_exception_entry()));
1527     __ br(rscratch1);
1528     __ bind(ok);
1529 
1530     __ leave();
1531     __ ret(lr);
1532 
1533     OopMap* map = new OopMap(framesize, 1);
1534     oop_maps->add_gc_map(the_pc - start, map);
1535 }
1536 
1537 void SharedRuntime::continuation_enter_cleanup(MacroAssembler* masm) {
1538   ::continuation_enter_cleanup(masm);
1539 }
1540 
1541 static void gen_special_dispatch(MacroAssembler* masm,
1542                                  const methodHandle& method,
1543                                  const BasicType* sig_bt,
1544                                  const VMRegPair* regs) {
1545   verify_oop_args(masm, method, sig_bt, regs);
1546   vmIntrinsics::ID iid = method->intrinsic_id();
1547 
1548   // Now write the args into the outgoing interpreter space
1549   bool     has_receiver   = false;
1550   Register receiver_reg   = noreg;
1551   int      member_arg_pos = -1;
1552   Register member_reg     = noreg;
1553   int      ref_kind       = MethodHandles::signature_polymorphic_intrinsic_ref_kind(iid);
1554   if (ref_kind != 0) {
1555     member_arg_pos = method->size_of_parameters() - 1;  // trailing MemberName argument
1556     member_reg = r19;  // known to be free at this point
1557     has_receiver = MethodHandles::ref_kind_has_receiver(ref_kind);
1558   } else if (iid == vmIntrinsics::_invokeBasic) {
1559     has_receiver = true;
1560   } else if (iid == vmIntrinsics::_linkToNative) {
1561     member_arg_pos = method->size_of_parameters() - 1;  // trailing NativeEntryPoint argument
1562     member_reg = r19;  // known to be free at this point
1563   } else {
1564     fatal("unexpected intrinsic id %d", vmIntrinsics::as_int(iid));
1565   }
1566 
1567   if (member_reg != noreg) {
1568     // Load the member_arg into register, if necessary.
1569     SharedRuntime::check_member_name_argument_is_last_argument(method, sig_bt, regs);
1570     VMReg r = regs[member_arg_pos].first();
1571     if (r->is_stack()) {
1572       __ ldr(member_reg, Address(sp, r->reg2stack() * VMRegImpl::stack_slot_size));
1573     } else {
1574       // no data motion is needed
1575       member_reg = r->as_Register();
1576     }
1577   }
1578 
1579   if (has_receiver) {
1580     // Make sure the receiver is loaded into a register.
1581     assert(method->size_of_parameters() > 0, "oob");
1582     assert(sig_bt[0] == T_OBJECT, "receiver argument must be an object");
1583     VMReg r = regs[0].first();
1584     assert(r->is_valid(), "bad receiver arg");
1585     if (r->is_stack()) {
1586       // Porting note:  This assumes that compiled calling conventions always
1587       // pass the receiver oop in a register.  If this is not true on some
1588       // platform, pick a temp and load the receiver from stack.
1589       fatal("receiver always in a register");
1590       receiver_reg = r2;  // known to be free at this point
1591       __ ldr(receiver_reg, Address(sp, r->reg2stack() * VMRegImpl::stack_slot_size));
1592     } else {
1593       // no data motion is needed
1594       receiver_reg = r->as_Register();
1595     }
1596   }
1597 
1598   // Figure out which address we are really jumping to:
1599   MethodHandles::generate_method_handle_dispatch(masm, iid,
1600                                                  receiver_reg, member_reg, /*for_compiler_entry:*/ true);
1601 }
1602 
1603 // ---------------------------------------------------------------------------
1604 // Generate a native wrapper for a given method.  The method takes arguments
1605 // in the Java compiled code convention, marshals them to the native
1606 // convention (handlizes oops, etc), transitions to native, makes the call,
1607 // returns to java state (possibly blocking), unhandlizes any result and
1608 // returns.
1609 //
1610 // Critical native functions are a shorthand for the use of
1611 // GetPrimtiveArrayCritical and disallow the use of any other JNI
1612 // functions.  The wrapper is expected to unpack the arguments before
1613 // passing them to the callee. Critical native functions leave the state _in_Java,
1614 // since they block out GC.
1615 // Some other parts of JNI setup are skipped like the tear down of the JNI handle
1616 // block and the check for pending exceptions it's impossible for them
1617 // to be thrown.
1618 //
1619 nmethod* SharedRuntime::generate_native_wrapper(MacroAssembler* masm,
1620                                                 const methodHandle& method,
1621                                                 int compile_id,
1622                                                 BasicType* in_sig_bt,
1623                                                 VMRegPair* in_regs,
1624                                                 BasicType ret_type) {
1625   if (method->is_continuation_native_intrinsic()) {
1626     int exception_offset = -1;
1627     OopMapSet* oop_maps = new OopMapSet();
1628     int frame_complete = -1;
1629     int stack_slots = -1;
1630     int interpreted_entry_offset = -1;
1631     int vep_offset = -1;
1632     if (method->is_continuation_enter_intrinsic()) {
1633       gen_continuation_enter(masm,
1634                              method,
1635                              in_sig_bt,
1636                              in_regs,
1637                              exception_offset,
1638                              oop_maps,
1639                              frame_complete,
1640                              stack_slots,
1641                              interpreted_entry_offset,
1642                              vep_offset);
1643     } else if (method->is_continuation_yield_intrinsic()) {
1644       gen_continuation_yield(masm,
1645                              method,
1646                              in_sig_bt,
1647                              in_regs,
1648                              oop_maps,
1649                              frame_complete,
1650                              stack_slots,
1651                              vep_offset);
1652     } else {
1653       guarantee(false, "Unknown Continuation native intrinsic");
1654     }
1655 
1656 #ifdef ASSERT
1657     if (method->is_continuation_enter_intrinsic()) {
1658       assert(interpreted_entry_offset != -1, "Must be set");
1659       assert(exception_offset != -1,         "Must be set");
1660     } else {
1661       assert(interpreted_entry_offset == -1, "Must be unset");
1662       assert(exception_offset == -1,         "Must be unset");
1663     }
1664     assert(frame_complete != -1,    "Must be set");
1665     assert(stack_slots != -1,       "Must be set");
1666     assert(vep_offset != -1,        "Must be set");
1667 #endif
1668 
1669     __ flush();
1670     nmethod* nm = nmethod::new_native_nmethod(method,
1671                                               compile_id,
1672                                               masm->code(),
1673                                               vep_offset,
1674                                               frame_complete,
1675                                               stack_slots,
1676                                               in_ByteSize(-1),
1677                                               in_ByteSize(-1),
1678                                               oop_maps,
1679                                               exception_offset);
1680     if (nm == nullptr) return nm;
1681     if (method->is_continuation_enter_intrinsic()) {
1682       ContinuationEntry::set_enter_code(nm, interpreted_entry_offset);
1683     } else if (method->is_continuation_yield_intrinsic()) {
1684       _cont_doYield_stub = nm;
1685     } else {
1686       guarantee(false, "Unknown Continuation native intrinsic");
1687     }
1688     return nm;
1689   }
1690 
1691   if (method->is_method_handle_intrinsic()) {
1692     vmIntrinsics::ID iid = method->intrinsic_id();
1693     intptr_t start = (intptr_t)__ pc();
1694     int vep_offset = ((intptr_t)__ pc()) - start;
1695 
1696     // First instruction must be a nop as it may need to be patched on deoptimisation
1697     __ nop();
1698     gen_special_dispatch(masm,
1699                          method,
1700                          in_sig_bt,
1701                          in_regs);
1702     int frame_complete = ((intptr_t)__ pc()) - start;  // not complete, period
1703     __ flush();
1704     int stack_slots = SharedRuntime::out_preserve_stack_slots();  // no out slots at all, actually
1705     return nmethod::new_native_nmethod(method,
1706                                        compile_id,
1707                                        masm->code(),
1708                                        vep_offset,
1709                                        frame_complete,
1710                                        stack_slots / VMRegImpl::slots_per_word,
1711                                        in_ByteSize(-1),
1712                                        in_ByteSize(-1),
1713                                        nullptr);
1714   }
1715   address native_func = method->native_function();
1716   assert(native_func != nullptr, "must have function");
1717 
1718   // An OopMap for lock (and class if static)
1719   OopMapSet *oop_maps = new OopMapSet();
1720   intptr_t start = (intptr_t)__ pc();
1721 
1722   // We have received a description of where all the java arg are located
1723   // on entry to the wrapper. We need to convert these args to where
1724   // the jni function will expect them. To figure out where they go
1725   // we convert the java signature to a C signature by inserting
1726   // the hidden arguments as arg[0] and possibly arg[1] (static method)
1727 
1728   const int total_in_args = method->size_of_parameters();
1729   int total_c_args = total_in_args + (method->is_static() ? 2 : 1);
1730 
1731   BasicType* out_sig_bt = NEW_RESOURCE_ARRAY(BasicType, total_c_args);
1732   VMRegPair* out_regs   = NEW_RESOURCE_ARRAY(VMRegPair, total_c_args);
1733 
1734   int argc = 0;
1735   out_sig_bt[argc++] = T_ADDRESS;
1736   if (method->is_static()) {
1737     out_sig_bt[argc++] = T_OBJECT;
1738   }
1739 
1740   for (int i = 0; i < total_in_args ; i++ ) {
1741     out_sig_bt[argc++] = in_sig_bt[i];
1742   }
1743 
1744   // Now figure out where the args must be stored and how much stack space
1745   // they require.
1746   int out_arg_slots;
1747   out_arg_slots = c_calling_convention_priv(out_sig_bt, out_regs, total_c_args);
1748 
1749   if (out_arg_slots < 0) {
1750     return nullptr;
1751   }
1752 
1753   // Compute framesize for the wrapper.  We need to handlize all oops in
1754   // incoming registers
1755 
1756   // Calculate the total number of stack slots we will need.
1757 
1758   // First count the abi requirement plus all of the outgoing args
1759   int stack_slots = SharedRuntime::out_preserve_stack_slots() + out_arg_slots;
1760 
1761   // Now the space for the inbound oop handle area
1762   int total_save_slots = 8 * VMRegImpl::slots_per_word;  // 8 arguments passed in registers
1763 
1764   int oop_handle_offset = stack_slots;
1765   stack_slots += total_save_slots;
1766 
1767   // Now any space we need for handlizing a klass if static method
1768 
1769   int klass_slot_offset = 0;
1770   int klass_offset = -1;
1771   int lock_slot_offset = 0;
1772   bool is_static = false;
1773 
1774   if (method->is_static()) {
1775     klass_slot_offset = stack_slots;
1776     stack_slots += VMRegImpl::slots_per_word;
1777     klass_offset = klass_slot_offset * VMRegImpl::stack_slot_size;
1778     is_static = true;
1779   }
1780 
1781   // Plus a lock if needed
1782 
1783   if (method->is_synchronized()) {
1784     lock_slot_offset = stack_slots;
1785     stack_slots += VMRegImpl::slots_per_word;
1786   }
1787 
1788   // Now a place (+2) to save return values or temp during shuffling
1789   // + 4 for return address (which we own) and saved rfp
1790   stack_slots += 6;
1791 
1792   // Ok The space we have allocated will look like:
1793   //
1794   //
1795   // FP-> |                     |
1796   //      |---------------------|
1797   //      | 2 slots for moves   |
1798   //      |---------------------|
1799   //      | lock box (if sync)  |
1800   //      |---------------------| <- lock_slot_offset
1801   //      | klass (if static)   |
1802   //      |---------------------| <- klass_slot_offset
1803   //      | oopHandle area      |
1804   //      |---------------------| <- oop_handle_offset (8 java arg registers)
1805   //      | outbound memory     |
1806   //      | based arguments     |
1807   //      |                     |
1808   //      |---------------------|
1809   //      |                     |
1810   // SP-> | out_preserved_slots |
1811   //
1812   //
1813 
1814 
1815   // Now compute actual number of stack words we need rounding to make
1816   // stack properly aligned.
1817   stack_slots = align_up(stack_slots, StackAlignmentInSlots);
1818 
1819   int stack_size = stack_slots * VMRegImpl::stack_slot_size;
1820 
1821   // First thing make an ic check to see if we should even be here
1822 
1823   // We are free to use all registers as temps without saving them and
1824   // restoring them except rfp. rfp is the only callee save register
1825   // as far as the interpreter and the compiler(s) are concerned.
1826 
1827   const Register receiver = j_rarg0;
1828 
1829   Label exception_pending;
1830 
1831   assert_different_registers(receiver, rscratch1);
1832   __ verify_oop(receiver);
1833   __ ic_check(8 /* end_alignment */);
1834 
1835   // Verified entry point must be aligned
1836   int vep_offset = ((intptr_t)__ pc()) - start;
1837 
1838   // If we have to make this method not-entrant we'll overwrite its
1839   // first instruction with a jump.  For this action to be legal we
1840   // must ensure that this first instruction is a B, BL, NOP, BKPT,
1841   // SVC, HVC, or SMC.  Make it a NOP.
1842   __ nop();
1843 
1844   if (VM_Version::supports_fast_class_init_checks() && method->needs_clinit_barrier()) {
1845     Label L_skip_barrier;
1846     __ mov_metadata(rscratch2, method->method_holder()); // InstanceKlass*
1847     __ clinit_barrier(rscratch2, rscratch1, &L_skip_barrier);
1848     __ far_jump(RuntimeAddress(SharedRuntime::get_handle_wrong_method_stub()));
1849 
1850     __ bind(L_skip_barrier);
1851   }
1852 
1853   // Generate stack overflow check
1854   __ bang_stack_with_offset(checked_cast<int>(StackOverflow::stack_shadow_zone_size()));
1855 
1856   // Generate a new frame for the wrapper.
1857   __ enter();
1858   // -2 because return address is already present and so is saved rfp
1859   __ sub(sp, sp, stack_size - 2*wordSize);
1860 
1861   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
1862   bs->nmethod_entry_barrier(masm, nullptr /* slow_path */, nullptr /* continuation */, nullptr /* guard */);
1863 
1864   // Frame is now completed as far as size and linkage.
1865   int frame_complete = ((intptr_t)__ pc()) - start;
1866 
1867   // We use r20 as the oop handle for the receiver/klass
1868   // It is callee save so it survives the call to native
1869 
1870   const Register oop_handle_reg = r20;
1871 
1872   //
1873   // We immediately shuffle the arguments so that any vm call we have to
1874   // make from here on out (sync slow path, jvmti, etc.) we will have
1875   // captured the oops from our caller and have a valid oopMap for
1876   // them.
1877 
1878   // -----------------
1879   // The Grand Shuffle
1880 
1881   // The Java calling convention is either equal (linux) or denser (win64) than the
1882   // c calling convention. However the because of the jni_env argument the c calling
1883   // convention always has at least one more (and two for static) arguments than Java.
1884   // Therefore if we move the args from java -> c backwards then we will never have
1885   // a register->register conflict and we don't have to build a dependency graph
1886   // and figure out how to break any cycles.
1887   //
1888 
1889   // Record esp-based slot for receiver on stack for non-static methods
1890   int receiver_offset = -1;
1891 
1892   // This is a trick. We double the stack slots so we can claim
1893   // the oops in the caller's frame. Since we are sure to have
1894   // more args than the caller doubling is enough to make
1895   // sure we can capture all the incoming oop args from the
1896   // caller.
1897   //
1898   OopMap* map = new OopMap(stack_slots * 2, 0 /* arg_slots*/);
1899 
1900   // Mark location of rfp (someday)
1901   // map->set_callee_saved(VMRegImpl::stack2reg( stack_slots - 2), stack_slots * 2, 0, vmreg(rfp));
1902 
1903 
1904   int float_args = 0;
1905   int int_args = 0;
1906 
1907 #ifdef ASSERT
1908   bool reg_destroyed[Register::number_of_registers];
1909   bool freg_destroyed[FloatRegister::number_of_registers];
1910   for ( int r = 0 ; r < Register::number_of_registers ; r++ ) {
1911     reg_destroyed[r] = false;
1912   }
1913   for ( int f = 0 ; f < FloatRegister::number_of_registers ; f++ ) {
1914     freg_destroyed[f] = false;
1915   }
1916 
1917 #endif /* ASSERT */
1918 
1919   // For JNI natives the incoming and outgoing registers are offset upwards.
1920   GrowableArray<int> arg_order(2 * total_in_args);
1921 
1922   for (int i = total_in_args - 1, c_arg = total_c_args - 1; i >= 0; i--, c_arg--) {
1923     arg_order.push(i);
1924     arg_order.push(c_arg);
1925   }
1926 
1927   for (int ai = 0; ai < arg_order.length(); ai += 2) {
1928     int i = arg_order.at(ai);
1929     int c_arg = arg_order.at(ai + 1);
1930     __ block_comment(err_msg("move %d -> %d", i, c_arg));
1931     assert(c_arg != -1 && i != -1, "wrong order");
1932 #ifdef ASSERT
1933     if (in_regs[i].first()->is_Register()) {
1934       assert(!reg_destroyed[in_regs[i].first()->as_Register()->encoding()], "destroyed reg!");
1935     } else if (in_regs[i].first()->is_FloatRegister()) {
1936       assert(!freg_destroyed[in_regs[i].first()->as_FloatRegister()->encoding()], "destroyed reg!");
1937     }
1938     if (out_regs[c_arg].first()->is_Register()) {
1939       reg_destroyed[out_regs[c_arg].first()->as_Register()->encoding()] = true;
1940     } else if (out_regs[c_arg].first()->is_FloatRegister()) {
1941       freg_destroyed[out_regs[c_arg].first()->as_FloatRegister()->encoding()] = true;
1942     }
1943 #endif /* ASSERT */
1944     switch (in_sig_bt[i]) {
1945       case T_ARRAY:
1946       case T_OBJECT:
1947         __ object_move(map, oop_handle_offset, stack_slots, in_regs[i], out_regs[c_arg],
1948                        ((i == 0) && (!is_static)),
1949                        &receiver_offset);
1950         int_args++;
1951         break;
1952       case T_VOID:
1953         break;
1954 
1955       case T_FLOAT:
1956         __ float_move(in_regs[i], out_regs[c_arg]);
1957         float_args++;
1958         break;
1959 
1960       case T_DOUBLE:
1961         assert( i + 1 < total_in_args &&
1962                 in_sig_bt[i + 1] == T_VOID &&
1963                 out_sig_bt[c_arg+1] == T_VOID, "bad arg list");
1964         __ double_move(in_regs[i], out_regs[c_arg]);
1965         float_args++;
1966         break;
1967 
1968       case T_LONG :
1969         __ long_move(in_regs[i], out_regs[c_arg]);
1970         int_args++;
1971         break;
1972 
1973       case T_ADDRESS: assert(false, "found T_ADDRESS in java args");
1974 
1975       default:
1976         __ move32_64(in_regs[i], out_regs[c_arg]);
1977         int_args++;
1978     }
1979   }
1980 
1981   // point c_arg at the first arg that is already loaded in case we
1982   // need to spill before we call out
1983   int c_arg = total_c_args - total_in_args;
1984 
1985   // Pre-load a static method's oop into c_rarg1.
1986   if (method->is_static()) {
1987 
1988     //  load oop into a register
1989     __ movoop(c_rarg1,
1990               JNIHandles::make_local(method->method_holder()->java_mirror()));
1991 
1992     // Now handlize the static class mirror it's known not-null.
1993     __ str(c_rarg1, Address(sp, klass_offset));
1994     map->set_oop(VMRegImpl::stack2reg(klass_slot_offset));
1995 
1996     // Now get the handle
1997     __ lea(c_rarg1, Address(sp, klass_offset));
1998     // and protect the arg if we must spill
1999     c_arg--;
2000   }
2001 
2002   // Change state to native (we save the return address in the thread, since it might not
2003   // be pushed on the stack when we do a stack traversal). It is enough that the pc()
2004   // points into the right code segment. It does not have to be the correct return pc.
2005   // We use the same pc/oopMap repeatedly when we call out.
2006 
2007   Label native_return;
2008   if (method->is_object_wait0()) {
2009     // For convenience we use the pc we want to resume to in case of preemption on Object.wait.
2010     __ set_last_Java_frame(sp, noreg, native_return, rscratch1);
2011   } else {
2012     intptr_t the_pc = (intptr_t) __ pc();
2013     oop_maps->add_gc_map(the_pc - start, map);
2014 
2015     __ set_last_Java_frame(sp, noreg, __ pc(), rscratch1);
2016   }
2017 
2018   Label dtrace_method_entry, dtrace_method_entry_done;
2019   if (DTraceMethodProbes) {
2020     __ b(dtrace_method_entry);
2021     __ bind(dtrace_method_entry_done);
2022   }
2023 
2024   // RedefineClasses() tracing support for obsolete method entry
2025   if (log_is_enabled(Trace, redefine, class, obsolete)) {
2026     // protect the args we've loaded
2027     save_args(masm, total_c_args, c_arg, out_regs);
2028     __ mov_metadata(c_rarg1, method());
2029     __ call_VM_leaf(
2030       CAST_FROM_FN_PTR(address, SharedRuntime::rc_trace_method_entry),
2031       rthread, c_rarg1);
2032     restore_args(masm, total_c_args, c_arg, out_regs);
2033   }
2034 
2035   // Lock a synchronized method
2036 
2037   // Register definitions used by locking and unlocking
2038 
2039   const Register swap_reg = r0;
2040   const Register obj_reg  = r19;  // Will contain the oop
2041   const Register lock_reg = r13;  // Address of compiler lock object (BasicLock)
2042   const Register old_hdr  = r13;  // value of old header at unlock time
2043   const Register lock_tmp = r14;  // Temporary used by lightweight_lock/unlock
2044   const Register tmp = lr;
2045 
2046   Label slow_path_lock;
2047   Label lock_done;
2048 
2049   if (method->is_synchronized()) {
2050     Label count;
2051     const int mark_word_offset = BasicLock::displaced_header_offset_in_bytes();
2052 
2053     // Get the handle (the 2nd argument)
2054     __ mov(oop_handle_reg, c_rarg1);
2055 
2056     // Get address of the box
2057 
2058     __ lea(lock_reg, Address(sp, lock_slot_offset * VMRegImpl::stack_slot_size));
2059 
2060     // Load the oop from the handle
2061     __ ldr(obj_reg, Address(oop_handle_reg, 0));
2062 
2063     __ lightweight_lock(lock_reg, obj_reg, swap_reg, tmp, lock_tmp, slow_path_lock);
2064 
2065     // Slow path will re-enter here
2066     __ bind(lock_done);
2067   }
2068 
2069 
2070   // Finally just about ready to make the JNI call
2071 
2072   // get JNIEnv* which is first argument to native
2073   __ lea(c_rarg0, Address(rthread, in_bytes(JavaThread::jni_environment_offset())));
2074 
2075   // Now set thread in native
2076   __ mov(rscratch1, _thread_in_native);
2077   __ lea(rscratch2, Address(rthread, JavaThread::thread_state_offset()));
2078   __ stlrw(rscratch1, rscratch2);
2079 
2080   __ rt_call(native_func);
2081 
2082   // Verify or restore cpu control state after JNI call
2083   __ restore_cpu_control_state_after_jni(rscratch1, rscratch2);
2084 
2085   // Unpack native results.
2086   switch (ret_type) {
2087   case T_BOOLEAN: __ c2bool(r0);                     break;
2088   case T_CHAR   : __ ubfx(r0, r0, 0, 16);            break;
2089   case T_BYTE   : __ sbfx(r0, r0, 0, 8);             break;
2090   case T_SHORT  : __ sbfx(r0, r0, 0, 16);            break;
2091   case T_INT    : __ sbfx(r0, r0, 0, 32);            break;
2092   case T_DOUBLE :
2093   case T_FLOAT  :
2094     // Result is in v0 we'll save as needed
2095     break;
2096   case T_ARRAY:                 // Really a handle
2097   case T_OBJECT:                // Really a handle
2098       break; // can't de-handlize until after safepoint check
2099   case T_VOID: break;
2100   case T_LONG: break;
2101   default       : ShouldNotReachHere();
2102   }
2103 
2104   Label safepoint_in_progress, safepoint_in_progress_done;
2105 
2106   // Switch thread to "native transition" state before reading the synchronization state.
2107   // This additional state is necessary because reading and testing the synchronization
2108   // state is not atomic w.r.t. GC, as this scenario demonstrates:
2109   //     Java thread A, in _thread_in_native state, loads _not_synchronized and is preempted.
2110   //     VM thread changes sync state to synchronizing and suspends threads for GC.
2111   //     Thread A is resumed to finish this native method, but doesn't block here since it
2112   //     didn't see any synchronization is progress, and escapes.
2113   __ mov(rscratch1, _thread_in_native_trans);
2114 
2115   __ strw(rscratch1, Address(rthread, JavaThread::thread_state_offset()));
2116 
2117   // Force this write out before the read below
2118   if (!UseSystemMemoryBarrier) {
2119     __ dmb(Assembler::ISH);
2120   }
2121 
2122   __ verify_sve_vector_length();
2123 
2124   // Check for safepoint operation in progress and/or pending suspend requests.
2125   {
2126     // No need for acquire as Java threads always disarm themselves.
2127     __ safepoint_poll(safepoint_in_progress, true /* at_return */, false /* in_nmethod */);
2128     __ ldrw(rscratch1, Address(rthread, JavaThread::suspend_flags_offset()));
2129     __ cbnzw(rscratch1, safepoint_in_progress);
2130     __ bind(safepoint_in_progress_done);
2131   }
2132 
2133   // change thread state
2134   __ mov(rscratch1, _thread_in_Java);
2135   __ lea(rscratch2, Address(rthread, JavaThread::thread_state_offset()));
2136   __ stlrw(rscratch1, rscratch2);
2137 
2138   if (method->is_object_wait0()) {
2139     // Check preemption for Object.wait()
2140     __ ldr(rscratch1, Address(rthread, JavaThread::preempt_alternate_return_offset()));
2141     __ cbz(rscratch1, native_return);
2142     __ str(zr, Address(rthread, JavaThread::preempt_alternate_return_offset()));
2143     __ br(rscratch1);
2144     __ bind(native_return);
2145 
2146     intptr_t the_pc = (intptr_t) __ pc();
2147     oop_maps->add_gc_map(the_pc - start, map);
2148   }
2149 
2150   Label reguard;
2151   Label reguard_done;
2152   __ ldrb(rscratch1, Address(rthread, JavaThread::stack_guard_state_offset()));
2153   __ cmpw(rscratch1, StackOverflow::stack_guard_yellow_reserved_disabled);
2154   __ br(Assembler::EQ, reguard);
2155   __ bind(reguard_done);
2156 
2157   // native result if any is live
2158 
2159   // Unlock
2160   Label unlock_done;
2161   Label slow_path_unlock;
2162   if (method->is_synchronized()) {
2163 
2164     // Get locked oop from the handle we passed to jni
2165     __ ldr(obj_reg, Address(oop_handle_reg, 0));
2166 
2167     // Must save r0 if if it is live now because cmpxchg must use it
2168     if (ret_type != T_FLOAT && ret_type != T_DOUBLE && ret_type != T_VOID) {
2169       save_native_result(masm, ret_type, stack_slots);
2170     }
2171 
2172     __ lightweight_unlock(obj_reg, old_hdr, swap_reg, lock_tmp, slow_path_unlock);
2173 
2174     // slow path re-enters here
2175     __ bind(unlock_done);
2176     if (ret_type != T_FLOAT && ret_type != T_DOUBLE && ret_type != T_VOID) {
2177       restore_native_result(masm, ret_type, stack_slots);
2178     }
2179   }
2180 
2181   Label dtrace_method_exit, dtrace_method_exit_done;
2182   if (DTraceMethodProbes) {
2183     __ b(dtrace_method_exit);
2184     __ bind(dtrace_method_exit_done);
2185   }
2186 
2187   __ reset_last_Java_frame(false);
2188 
2189   // Unbox oop result, e.g. JNIHandles::resolve result.
2190   if (is_reference_type(ret_type)) {
2191     __ resolve_jobject(r0, r1, r2);
2192   }
2193 
2194   if (CheckJNICalls) {
2195     // clear_pending_jni_exception_check
2196     __ str(zr, Address(rthread, JavaThread::pending_jni_exception_check_fn_offset()));
2197   }
2198 
2199   // reset handle block
2200   __ ldr(r2, Address(rthread, JavaThread::active_handles_offset()));
2201   __ str(zr, Address(r2, JNIHandleBlock::top_offset()));
2202 
2203   __ leave();
2204 
2205   #if INCLUDE_JFR
2206   // We need to do a poll test after unwind in case the sampler
2207   // managed to sample the native frame after returning to Java.
2208   Label L_return;
2209   __ ldr(rscratch1, Address(rthread, JavaThread::polling_word_offset()));
2210   address poll_test_pc = __ pc();
2211   __ relocate(relocInfo::poll_return_type);
2212   __ tbz(rscratch1, log2i_exact(SafepointMechanism::poll_bit()), L_return);
2213   assert(SharedRuntime::polling_page_return_handler_blob() != nullptr,
2214     "polling page return stub not created yet");
2215   address stub = SharedRuntime::polling_page_return_handler_blob()->entry_point();
2216   __ adr(rscratch1, InternalAddress(poll_test_pc));
2217   __ str(rscratch1, Address(rthread, JavaThread::saved_exception_pc_offset()));
2218   __ far_jump(RuntimeAddress(stub));
2219   __ bind(L_return);
2220 #endif // INCLUDE_JFR
2221 
2222   // Any exception pending?
2223   __ ldr(rscratch1, Address(rthread, in_bytes(Thread::pending_exception_offset())));
2224   __ cbnz(rscratch1, exception_pending);
2225 
2226   // We're done
2227   __ ret(lr);
2228 
2229   // Unexpected paths are out of line and go here
2230 
2231   // forward the exception
2232   __ bind(exception_pending);
2233 
2234   // and forward the exception
2235   __ far_jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
2236 
2237   // Slow path locking & unlocking
2238   if (method->is_synchronized()) {
2239 
2240     __ block_comment("Slow path lock {");
2241     __ bind(slow_path_lock);
2242 
2243     // has last_Java_frame setup. No exceptions so do vanilla call not call_VM
2244     // args are (oop obj, BasicLock* lock, JavaThread* thread)
2245 
2246     // protect the args we've loaded
2247     save_args(masm, total_c_args, c_arg, out_regs);
2248 
2249     __ mov(c_rarg0, obj_reg);
2250     __ mov(c_rarg1, lock_reg);
2251     __ mov(c_rarg2, rthread);
2252 
2253     // Not a leaf but we have last_Java_frame setup as we want.
2254     // We don't want to unmount in case of contention since that would complicate preserving
2255     // the arguments that had already been marshalled into the native convention. So we force
2256     // the freeze slow path to find this native wrapper frame (see recurse_freeze_native_frame())
2257     // and pin the vthread. Otherwise the fast path won't find it since we don't walk the stack.
2258     __ push_cont_fastpath();
2259     __ call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::complete_monitor_locking_C), 3);
2260     __ pop_cont_fastpath();
2261     restore_args(masm, total_c_args, c_arg, out_regs);
2262 
2263 #ifdef ASSERT
2264     { Label L;
2265       __ ldr(rscratch1, Address(rthread, in_bytes(Thread::pending_exception_offset())));
2266       __ cbz(rscratch1, L);
2267       __ stop("no pending exception allowed on exit from monitorenter");
2268       __ bind(L);
2269     }
2270 #endif
2271     __ b(lock_done);
2272 
2273     __ block_comment("} Slow path lock");
2274 
2275     __ block_comment("Slow path unlock {");
2276     __ bind(slow_path_unlock);
2277 
2278     // If we haven't already saved the native result we must save it now as xmm registers
2279     // are still exposed.
2280 
2281     if (ret_type == T_FLOAT || ret_type == T_DOUBLE ) {
2282       save_native_result(masm, ret_type, stack_slots);
2283     }
2284 
2285     __ mov(c_rarg2, rthread);
2286     __ lea(c_rarg1, Address(sp, lock_slot_offset * VMRegImpl::stack_slot_size));
2287     __ mov(c_rarg0, obj_reg);
2288 
2289     // Save pending exception around call to VM (which contains an EXCEPTION_MARK)
2290     // NOTE that obj_reg == r19 currently
2291     __ ldr(r19, Address(rthread, in_bytes(Thread::pending_exception_offset())));
2292     __ str(zr, Address(rthread, in_bytes(Thread::pending_exception_offset())));
2293 
2294     __ rt_call(CAST_FROM_FN_PTR(address, SharedRuntime::complete_monitor_unlocking_C));
2295 
2296 #ifdef ASSERT
2297     {
2298       Label L;
2299       __ ldr(rscratch1, Address(rthread, in_bytes(Thread::pending_exception_offset())));
2300       __ cbz(rscratch1, L);
2301       __ stop("no pending exception allowed on exit complete_monitor_unlocking_C");
2302       __ bind(L);
2303     }
2304 #endif /* ASSERT */
2305 
2306     __ str(r19, Address(rthread, in_bytes(Thread::pending_exception_offset())));
2307 
2308     if (ret_type == T_FLOAT || ret_type == T_DOUBLE ) {
2309       restore_native_result(masm, ret_type, stack_slots);
2310     }
2311     __ b(unlock_done);
2312 
2313     __ block_comment("} Slow path unlock");
2314 
2315   } // synchronized
2316 
2317   // SLOW PATH Reguard the stack if needed
2318 
2319   __ bind(reguard);
2320   save_native_result(masm, ret_type, stack_slots);
2321   __ rt_call(CAST_FROM_FN_PTR(address, SharedRuntime::reguard_yellow_pages));
2322   restore_native_result(masm, ret_type, stack_slots);
2323   // and continue
2324   __ b(reguard_done);
2325 
2326   // SLOW PATH safepoint
2327   {
2328     __ block_comment("safepoint {");
2329     __ bind(safepoint_in_progress);
2330 
2331     // Don't use call_VM as it will see a possible pending exception and forward it
2332     // and never return here preventing us from clearing _last_native_pc down below.
2333     //
2334     save_native_result(masm, ret_type, stack_slots);
2335     __ mov(c_rarg0, rthread);
2336 #ifndef PRODUCT
2337   assert(frame::arg_reg_save_area_bytes == 0, "not expecting frame reg save area");
2338 #endif
2339     __ lea(rscratch1, RuntimeAddress(CAST_FROM_FN_PTR(address, JavaThread::check_special_condition_for_native_trans)));
2340     __ blr(rscratch1);
2341 
2342     // Restore any method result value
2343     restore_native_result(masm, ret_type, stack_slots);
2344 
2345     __ b(safepoint_in_progress_done);
2346     __ block_comment("} safepoint");
2347   }
2348 
2349   // SLOW PATH dtrace support
2350   if (DTraceMethodProbes) {
2351     {
2352       __ block_comment("dtrace entry {");
2353       __ bind(dtrace_method_entry);
2354 
2355       // We have all of the arguments setup at this point. We must not touch any register
2356       // argument registers at this point (what if we save/restore them there are no oop?
2357 
2358       save_args(masm, total_c_args, c_arg, out_regs);
2359       __ mov_metadata(c_rarg1, method());
2360       __ call_VM_leaf(
2361         CAST_FROM_FN_PTR(address, SharedRuntime::dtrace_method_entry),
2362         rthread, c_rarg1);
2363       restore_args(masm, total_c_args, c_arg, out_regs);
2364       __ b(dtrace_method_entry_done);
2365       __ block_comment("} dtrace entry");
2366     }
2367 
2368     {
2369       __ block_comment("dtrace exit {");
2370       __ bind(dtrace_method_exit);
2371       save_native_result(masm, ret_type, stack_slots);
2372       __ mov_metadata(c_rarg1, method());
2373       __ call_VM_leaf(
2374         CAST_FROM_FN_PTR(address, SharedRuntime::dtrace_method_exit),
2375         rthread, c_rarg1);
2376       restore_native_result(masm, ret_type, stack_slots);
2377       __ b(dtrace_method_exit_done);
2378       __ block_comment("} dtrace exit");
2379     }
2380   }
2381 
2382   __ flush();
2383 
2384   nmethod *nm = nmethod::new_native_nmethod(method,
2385                                             compile_id,
2386                                             masm->code(),
2387                                             vep_offset,
2388                                             frame_complete,
2389                                             stack_slots / VMRegImpl::slots_per_word,
2390                                             (is_static ? in_ByteSize(klass_offset) : in_ByteSize(receiver_offset)),
2391                                             in_ByteSize(lock_slot_offset*VMRegImpl::stack_slot_size),
2392                                             oop_maps);
2393 
2394   return nm;
2395 }
2396 
2397 // this function returns the adjust size (in number of words) to a c2i adapter
2398 // activation for use during deoptimization
2399 int Deoptimization::last_frame_adjust(int callee_parameters, int callee_locals) {
2400   assert(callee_locals >= callee_parameters,
2401           "test and remove; got more parms than locals");
2402   if (callee_locals < callee_parameters)
2403     return 0;                   // No adjustment for negative locals
2404   int diff = (callee_locals - callee_parameters) * Interpreter::stackElementWords;
2405   // diff is counted in stack words
2406   return align_up(diff, 2);
2407 }
2408 
2409 
2410 //------------------------------generate_deopt_blob----------------------------
2411 void SharedRuntime::generate_deopt_blob() {
2412   // Allocate space for the code
2413   ResourceMark rm;
2414   // Setup code generation tools
2415   int pad = 0;
2416 #if INCLUDE_JVMCI
2417   if (EnableJVMCI) {
2418     pad += 512; // Increase the buffer size when compiling for JVMCI
2419   }
2420 #endif
2421   const char* name = SharedRuntime::stub_name(StubId::shared_deopt_id);
2422   CodeBlob* blob = AOTCodeCache::load_code_blob(AOTCodeEntry::SharedBlob, BlobId::shared_deopt_id);
2423   if (blob != nullptr) {
2424     _deopt_blob = blob->as_deoptimization_blob();
2425     return;
2426   }
2427 
2428   CodeBuffer buffer(name, 2048+pad, 1024);
2429   MacroAssembler* masm = new MacroAssembler(&buffer);
2430   int frame_size_in_words;
2431   OopMap* map = nullptr;
2432   OopMapSet *oop_maps = new OopMapSet();
2433   RegisterSaver reg_save(COMPILER2_OR_JVMCI != 0);
2434 
2435   // -------------
2436   // This code enters when returning to a de-optimized nmethod.  A return
2437   // address has been pushed on the stack, and return values are in
2438   // registers.
2439   // If we are doing a normal deopt then we were called from the patched
2440   // nmethod from the point we returned to the nmethod. So the return
2441   // address on the stack is wrong by NativeCall::instruction_size
2442   // We will adjust the value so it looks like we have the original return
2443   // address on the stack (like when we eagerly deoptimized).
2444   // In the case of an exception pending when deoptimizing, we enter
2445   // with a return address on the stack that points after the call we patched
2446   // into the exception handler. We have the following register state from,
2447   // e.g., the forward exception stub (see stubGenerator_x86_64.cpp).
2448   //    r0: exception oop
2449   //    r19: exception handler
2450   //    r3: throwing pc
2451   // So in this case we simply jam r3 into the useless return address and
2452   // the stack looks just like we want.
2453   //
2454   // At this point we need to de-opt.  We save the argument return
2455   // registers.  We call the first C routine, fetch_unroll_info().  This
2456   // routine captures the return values and returns a structure which
2457   // describes the current frame size and the sizes of all replacement frames.
2458   // The current frame is compiled code and may contain many inlined
2459   // functions, each with their own JVM state.  We pop the current frame, then
2460   // push all the new frames.  Then we call the C routine unpack_frames() to
2461   // populate these frames.  Finally unpack_frames() returns us the new target
2462   // address.  Notice that callee-save registers are BLOWN here; they have
2463   // already been captured in the vframeArray at the time the return PC was
2464   // patched.
2465   address start = __ pc();
2466   Label cont;
2467 
2468   // Prolog for non exception case!
2469 
2470   // Save everything in sight.
2471   map = reg_save.save_live_registers(masm, 0, &frame_size_in_words);
2472 
2473   // Normal deoptimization.  Save exec mode for unpack_frames.
2474   __ movw(rcpool, Deoptimization::Unpack_deopt); // callee-saved
2475   __ b(cont);
2476 
2477   int reexecute_offset = __ pc() - start;
2478 #if INCLUDE_JVMCI && !defined(COMPILER1)
2479   if (UseJVMCICompiler) {
2480     // JVMCI does not use this kind of deoptimization
2481     __ should_not_reach_here();
2482   }
2483 #endif
2484 
2485   // Reexecute case
2486   // return address is the pc describes what bci to do re-execute at
2487 
2488   // No need to update map as each call to save_live_registers will produce identical oopmap
2489   (void) reg_save.save_live_registers(masm, 0, &frame_size_in_words);
2490 
2491   __ movw(rcpool, Deoptimization::Unpack_reexecute); // callee-saved
2492   __ b(cont);
2493 
2494 #if INCLUDE_JVMCI
2495   Label after_fetch_unroll_info_call;
2496   int implicit_exception_uncommon_trap_offset = 0;
2497   int uncommon_trap_offset = 0;
2498 
2499   if (EnableJVMCI) {
2500     implicit_exception_uncommon_trap_offset = __ pc() - start;
2501 
2502     __ ldr(lr, Address(rthread, in_bytes(JavaThread::jvmci_implicit_exception_pc_offset())));
2503     __ str(zr, Address(rthread, in_bytes(JavaThread::jvmci_implicit_exception_pc_offset())));
2504 
2505     uncommon_trap_offset = __ pc() - start;
2506 
2507     // Save everything in sight.
2508     reg_save.save_live_registers(masm, 0, &frame_size_in_words);
2509     // fetch_unroll_info needs to call last_java_frame()
2510     Label retaddr;
2511     __ set_last_Java_frame(sp, noreg, retaddr, rscratch1);
2512 
2513     __ ldrw(c_rarg1, Address(rthread, in_bytes(JavaThread::pending_deoptimization_offset())));
2514     __ movw(rscratch1, -1);
2515     __ strw(rscratch1, Address(rthread, in_bytes(JavaThread::pending_deoptimization_offset())));
2516 
2517     __ movw(rcpool, (int32_t)Deoptimization::Unpack_reexecute);
2518     __ mov(c_rarg0, rthread);
2519     __ movw(c_rarg2, rcpool); // exec mode
2520     __ lea(rscratch1,
2521            RuntimeAddress(CAST_FROM_FN_PTR(address,
2522                                            Deoptimization::uncommon_trap)));
2523     __ blr(rscratch1);
2524     __ bind(retaddr);
2525     oop_maps->add_gc_map( __ pc()-start, map->deep_copy());
2526 
2527     __ reset_last_Java_frame(false);
2528 
2529     __ b(after_fetch_unroll_info_call);
2530   } // EnableJVMCI
2531 #endif // INCLUDE_JVMCI
2532 
2533   int exception_offset = __ pc() - start;
2534 
2535   // Prolog for exception case
2536 
2537   // all registers are dead at this entry point, except for r0, and
2538   // r3 which contain the exception oop and exception pc
2539   // respectively.  Set them in TLS and fall thru to the
2540   // unpack_with_exception_in_tls entry point.
2541 
2542   __ str(r3, Address(rthread, JavaThread::exception_pc_offset()));
2543   __ str(r0, Address(rthread, JavaThread::exception_oop_offset()));
2544 
2545   int exception_in_tls_offset = __ pc() - start;
2546 
2547   // new implementation because exception oop is now passed in JavaThread
2548 
2549   // Prolog for exception case
2550   // All registers must be preserved because they might be used by LinearScan
2551   // Exceptiop oop and throwing PC are passed in JavaThread
2552   // tos: stack at point of call to method that threw the exception (i.e. only
2553   // args are on the stack, no return address)
2554 
2555   // The return address pushed by save_live_registers will be patched
2556   // later with the throwing pc. The correct value is not available
2557   // now because loading it from memory would destroy registers.
2558 
2559   // NB: The SP at this point must be the SP of the method that is
2560   // being deoptimized.  Deoptimization assumes that the frame created
2561   // here by save_live_registers is immediately below the method's SP.
2562   // This is a somewhat fragile mechanism.
2563 
2564   // Save everything in sight.
2565   map = reg_save.save_live_registers(masm, 0, &frame_size_in_words);
2566 
2567   // Now it is safe to overwrite any register
2568 
2569   // Deopt during an exception.  Save exec mode for unpack_frames.
2570   __ mov(rcpool, Deoptimization::Unpack_exception); // callee-saved
2571 
2572   // load throwing pc from JavaThread and patch it as the return address
2573   // of the current frame. Then clear the field in JavaThread
2574   __ ldr(r3, Address(rthread, JavaThread::exception_pc_offset()));
2575   __ protect_return_address(r3);
2576   __ str(r3, Address(rfp, wordSize));
2577   __ str(zr, Address(rthread, JavaThread::exception_pc_offset()));
2578 
2579 #ifdef ASSERT
2580   // verify that there is really an exception oop in JavaThread
2581   __ ldr(r0, Address(rthread, JavaThread::exception_oop_offset()));
2582   __ verify_oop(r0);
2583 
2584   // verify that there is no pending exception
2585   Label no_pending_exception;
2586   __ ldr(rscratch1, Address(rthread, Thread::pending_exception_offset()));
2587   __ cbz(rscratch1, no_pending_exception);
2588   __ stop("must not have pending exception here");
2589   __ bind(no_pending_exception);
2590 #endif
2591 
2592   __ bind(cont);
2593 
2594   // Call C code.  Need thread and this frame, but NOT official VM entry
2595   // crud.  We cannot block on this call, no GC can happen.
2596   //
2597   // UnrollBlock* fetch_unroll_info(JavaThread* thread)
2598 
2599   // fetch_unroll_info needs to call last_java_frame().
2600 
2601   Label retaddr;
2602   __ set_last_Java_frame(sp, noreg, retaddr, rscratch1);
2603 #ifdef ASSERT
2604   { Label L;
2605     __ ldr(rscratch1, Address(rthread, JavaThread::last_Java_fp_offset()));
2606     __ cbz(rscratch1, L);
2607     __ stop("SharedRuntime::generate_deopt_blob: last_Java_fp not cleared");
2608     __ bind(L);
2609   }
2610 #endif // ASSERT
2611   __ mov(c_rarg0, rthread);
2612   __ mov(c_rarg1, rcpool);
2613   __ lea(rscratch1, RuntimeAddress(CAST_FROM_FN_PTR(address, Deoptimization::fetch_unroll_info)));
2614   __ blr(rscratch1);
2615   __ bind(retaddr);
2616 
2617   // Need to have an oopmap that tells fetch_unroll_info where to
2618   // find any register it might need.
2619   oop_maps->add_gc_map(__ pc() - start, map);
2620 
2621   __ reset_last_Java_frame(false);
2622 
2623 #if INCLUDE_JVMCI
2624   if (EnableJVMCI) {
2625     __ bind(after_fetch_unroll_info_call);
2626   }
2627 #endif
2628 
2629   // Load UnrollBlock* into r5
2630   __ mov(r5, r0);
2631 
2632   __ ldrw(rcpool, Address(r5, Deoptimization::UnrollBlock::unpack_kind_offset()));
2633    Label noException;
2634   __ cmpw(rcpool, Deoptimization::Unpack_exception);   // Was exception pending?
2635   __ br(Assembler::NE, noException);
2636   __ ldr(r0, Address(rthread, JavaThread::exception_oop_offset()));
2637   // QQQ this is useless it was null above
2638   __ ldr(r3, Address(rthread, JavaThread::exception_pc_offset()));
2639   __ str(zr, Address(rthread, JavaThread::exception_oop_offset()));
2640   __ str(zr, Address(rthread, JavaThread::exception_pc_offset()));
2641 
2642   __ verify_oop(r0);
2643 
2644   // Overwrite the result registers with the exception results.
2645   __ str(r0, Address(sp, reg_save.r0_offset_in_bytes()));
2646   // I think this is useless
2647   // __ str(r3, Address(sp, RegisterSaver::r3_offset_in_bytes()));
2648 
2649   __ bind(noException);
2650 
2651   // Only register save data is on the stack.
2652   // Now restore the result registers.  Everything else is either dead
2653   // or captured in the vframeArray.
2654 
2655   // Restore fp result register
2656   __ ldrd(v0, Address(sp, reg_save.v0_offset_in_bytes()));
2657   // Restore integer result register
2658   __ ldr(r0, Address(sp, reg_save.r0_offset_in_bytes()));
2659 
2660   // Pop all of the register save area off the stack
2661   __ add(sp, sp, frame_size_in_words * wordSize);
2662 
2663   // All of the register save area has been popped of the stack. Only the
2664   // return address remains.
2665 
2666   // Pop all the frames we must move/replace.
2667   //
2668   // Frame picture (youngest to oldest)
2669   // 1: self-frame (no frame link)
2670   // 2: deopting frame  (no frame link)
2671   // 3: caller of deopting frame (could be compiled/interpreted).
2672   //
2673   // Note: by leaving the return address of self-frame on the stack
2674   // and using the size of frame 2 to adjust the stack
2675   // when we are done the return to frame 3 will still be on the stack.
2676 
2677   // Pop deoptimized frame
2678   __ ldrw(r2, Address(r5, Deoptimization::UnrollBlock::size_of_deoptimized_frame_offset()));
2679   __ sub(r2, r2, 2 * wordSize);
2680   __ add(sp, sp, r2);
2681   __ ldp(rfp, zr, __ post(sp, 2 * wordSize));
2682 
2683 #ifdef ASSERT
2684   // Compilers generate code that bang the stack by as much as the
2685   // interpreter would need. So this stack banging should never
2686   // trigger a fault. Verify that it does not on non product builds.
2687   __ ldrw(r19, Address(r5, Deoptimization::UnrollBlock::total_frame_sizes_offset()));
2688   __ bang_stack_size(r19, r2);
2689 #endif
2690   // Load address of array of frame pcs into r2
2691   __ ldr(r2, Address(r5, Deoptimization::UnrollBlock::frame_pcs_offset()));
2692 
2693   // Trash the old pc
2694   // __ addptr(sp, wordSize);  FIXME ????
2695 
2696   // Load address of array of frame sizes into r4
2697   __ ldr(r4, Address(r5, Deoptimization::UnrollBlock::frame_sizes_offset()));
2698 
2699   // Load counter into r3
2700   __ ldrw(r3, Address(r5, Deoptimization::UnrollBlock::number_of_frames_offset()));
2701 
2702   // Now adjust the caller's stack to make up for the extra locals
2703   // but record the original sp so that we can save it in the skeletal interpreter
2704   // frame and the stack walking of interpreter_sender will get the unextended sp
2705   // value and not the "real" sp value.
2706 
2707   const Register sender_sp = r6;
2708 
2709   __ mov(sender_sp, sp);
2710   __ ldrw(r19, Address(r5,
2711                        Deoptimization::UnrollBlock::
2712                        caller_adjustment_offset()));
2713   __ sub(sp, sp, r19);
2714 
2715   // Push interpreter frames in a loop
2716   __ mov(rscratch1, (uint64_t)0xDEADDEAD);        // Make a recognizable pattern
2717   __ mov(rscratch2, rscratch1);
2718   Label loop;
2719   __ bind(loop);
2720   __ ldr(r19, Address(__ post(r4, wordSize)));          // Load frame size
2721   __ sub(r19, r19, 2*wordSize);           // We'll push pc and fp by hand
2722   __ ldr(lr, Address(__ post(r2, wordSize)));  // Load pc
2723   __ enter();                           // Save old & set new fp
2724   __ sub(sp, sp, r19);                  // Prolog
2725   // This value is corrected by layout_activation_impl
2726   __ str(zr, Address(rfp, frame::interpreter_frame_last_sp_offset * wordSize));
2727   __ str(sender_sp, Address(rfp, frame::interpreter_frame_sender_sp_offset * wordSize)); // Make it walkable
2728   __ mov(sender_sp, sp);               // Pass sender_sp to next frame
2729   __ sub(r3, r3, 1);                   // Decrement counter
2730   __ cbnz(r3, loop);
2731 
2732     // Re-push self-frame
2733   __ ldr(lr, Address(r2));
2734   __ enter();
2735 
2736   // Allocate a full sized register save area.  We subtract 2 because
2737   // enter() just pushed 2 words
2738   __ sub(sp, sp, (frame_size_in_words - 2) * wordSize);
2739 
2740   // Restore frame locals after moving the frame
2741   __ strd(v0, Address(sp, reg_save.v0_offset_in_bytes()));
2742   __ str(r0, Address(sp, reg_save.r0_offset_in_bytes()));
2743 
2744   // Call C code.  Need thread but NOT official VM entry
2745   // crud.  We cannot block on this call, no GC can happen.  Call should
2746   // restore return values to their stack-slots with the new SP.
2747   //
2748   // void Deoptimization::unpack_frames(JavaThread* thread, int exec_mode)
2749 
2750   // Use rfp because the frames look interpreted now
2751   // Don't need the precise return PC here, just precise enough to point into this code blob.
2752   address the_pc = __ pc();
2753   __ set_last_Java_frame(sp, rfp, the_pc, rscratch1);
2754 
2755   __ mov(c_rarg0, rthread);
2756   __ movw(c_rarg1, rcpool); // second arg: exec_mode
2757   __ lea(rscratch1, RuntimeAddress(CAST_FROM_FN_PTR(address, Deoptimization::unpack_frames)));
2758   __ blr(rscratch1);
2759 
2760   // Set an oopmap for the call site
2761   // Use the same PC we used for the last java frame
2762   oop_maps->add_gc_map(the_pc - start,
2763                        new OopMap( frame_size_in_words, 0 ));
2764 
2765   // Clear fp AND pc
2766   __ reset_last_Java_frame(true);
2767 
2768   // Collect return values
2769   __ ldrd(v0, Address(sp, reg_save.v0_offset_in_bytes()));
2770   __ ldr(r0, Address(sp, reg_save.r0_offset_in_bytes()));
2771   // I think this is useless (throwing pc?)
2772   // __ ldr(r3, Address(sp, RegisterSaver::r3_offset_in_bytes()));
2773 
2774   // Pop self-frame.
2775   __ leave();                           // Epilog
2776 
2777   // Jump to interpreter
2778   __ ret(lr);
2779 
2780   // Make sure all code is generated
2781   masm->flush();
2782 
2783   _deopt_blob = DeoptimizationBlob::create(&buffer, oop_maps, 0, exception_offset, reexecute_offset, frame_size_in_words);
2784   _deopt_blob->set_unpack_with_exception_in_tls_offset(exception_in_tls_offset);
2785 #if INCLUDE_JVMCI
2786   if (EnableJVMCI) {
2787     _deopt_blob->set_uncommon_trap_offset(uncommon_trap_offset);
2788     _deopt_blob->set_implicit_exception_uncommon_trap_offset(implicit_exception_uncommon_trap_offset);
2789   }
2790 #endif
2791 
2792   AOTCodeCache::store_code_blob(*_deopt_blob, AOTCodeEntry::SharedBlob, BlobId::shared_deopt_id);
2793 }
2794 
2795 // Number of stack slots between incoming argument block and the start of
2796 // a new frame.  The PROLOG must add this many slots to the stack.  The
2797 // EPILOG must remove this many slots. aarch64 needs two slots for
2798 // return address and fp.
2799 // TODO think this is correct but check
2800 uint SharedRuntime::in_preserve_stack_slots() {
2801   return 4;
2802 }
2803 
2804 uint SharedRuntime::out_preserve_stack_slots() {
2805   return 0;
2806 }
2807 
2808 
2809 VMReg SharedRuntime::thread_register() {
2810   return rthread->as_VMReg();
2811 }
2812 
2813 //------------------------------generate_handler_blob------
2814 //
2815 // Generate a special Compile2Runtime blob that saves all registers,
2816 // and setup oopmap.
2817 //
2818 SafepointBlob* SharedRuntime::generate_handler_blob(StubId id, address call_ptr) {
2819   assert(is_polling_page_id(id), "expected a polling page stub id");
2820 
2821   // Allocate space for the code.  Setup code generation tools.
2822   const char* name = SharedRuntime::stub_name(id);
2823   CodeBlob* blob = AOTCodeCache::load_code_blob(AOTCodeEntry::SharedBlob, StubInfo::blob(id));
2824   if (blob != nullptr) {
2825     return blob->as_safepoint_blob();
2826   }
2827 
2828   ResourceMark rm;
2829   OopMapSet *oop_maps = new OopMapSet();
2830   OopMap* map;
2831   CodeBuffer buffer(name, 2048, 1024);
2832   MacroAssembler* masm = new MacroAssembler(&buffer);
2833 
2834   address start   = __ pc();
2835   address call_pc = nullptr;
2836   int frame_size_in_words;
2837   bool cause_return = (id == StubId::shared_polling_page_return_handler_id);
2838   RegisterSaver reg_save(id == StubId::shared_polling_page_vectors_safepoint_handler_id /* save_vectors */);
2839 
2840   // When the signal occurred, the LR was either signed and stored on the stack (in which
2841   // case it will be restored from the stack before being used) or unsigned and not stored
2842   // on the stack. Stipping ensures we get the right value.
2843   __ strip_return_address();
2844 
2845   // Save Integer and Float registers.
2846   map = reg_save.save_live_registers(masm, 0, &frame_size_in_words);
2847 
2848   // The following is basically a call_VM.  However, we need the precise
2849   // address of the call in order to generate an oopmap. Hence, we do all the
2850   // work ourselves.
2851 
2852   Label retaddr;
2853   __ set_last_Java_frame(sp, noreg, retaddr, rscratch1);
2854 
2855   // The return address must always be correct so that frame constructor never
2856   // sees an invalid pc.
2857 
2858   if (!cause_return) {
2859     // overwrite the return address pushed by save_live_registers
2860     // Additionally, r20 is a callee-saved register so we can look at
2861     // it later to determine if someone changed the return address for
2862     // us!
2863     __ ldr(r20, Address(rthread, JavaThread::saved_exception_pc_offset()));
2864     __ protect_return_address(r20);
2865     __ str(r20, Address(rfp, wordSize));
2866   }
2867 
2868   // Do the call
2869   __ mov(c_rarg0, rthread);
2870   __ lea(rscratch1, RuntimeAddress(call_ptr));
2871   __ blr(rscratch1);
2872   __ bind(retaddr);
2873 
2874   // Set an oopmap for the call site.  This oopmap will map all
2875   // oop-registers and debug-info registers as callee-saved.  This
2876   // will allow deoptimization at this safepoint to find all possible
2877   // debug-info recordings, as well as let GC find all oops.
2878 
2879   oop_maps->add_gc_map( __ pc() - start, map);
2880 
2881   Label noException;
2882 
2883   __ reset_last_Java_frame(false);
2884 
2885   __ membar(Assembler::LoadLoad | Assembler::LoadStore);
2886 
2887   __ ldr(rscratch1, Address(rthread, Thread::pending_exception_offset()));
2888   __ cbz(rscratch1, noException);
2889 
2890   // Exception pending
2891 
2892   reg_save.restore_live_registers(masm);
2893 
2894   __ far_jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
2895 
2896   // No exception case
2897   __ bind(noException);
2898 
2899   Label no_adjust, bail;
2900   if (!cause_return) {
2901     // If our stashed return pc was modified by the runtime we avoid touching it
2902     __ ldr(rscratch1, Address(rfp, wordSize));
2903     __ cmp(r20, rscratch1);
2904     __ br(Assembler::NE, no_adjust);
2905     __ authenticate_return_address(r20);
2906 
2907 #ifdef ASSERT
2908     // Verify the correct encoding of the poll we're about to skip.
2909     // See NativeInstruction::is_ldrw_to_zr()
2910     __ ldrw(rscratch1, Address(r20));
2911     __ ubfx(rscratch2, rscratch1, 22, 10);
2912     __ cmpw(rscratch2, 0b1011100101);
2913     __ br(Assembler::NE, bail);
2914     __ ubfx(rscratch2, rscratch1, 0, 5);
2915     __ cmpw(rscratch2, 0b11111);
2916     __ br(Assembler::NE, bail);
2917 #endif
2918     // Adjust return pc forward to step over the safepoint poll instruction
2919     __ add(r20, r20, NativeInstruction::instruction_size);
2920     __ protect_return_address(r20);
2921     __ str(r20, Address(rfp, wordSize));
2922   }
2923 
2924   __ bind(no_adjust);
2925   // Normal exit, restore registers and exit.
2926   reg_save.restore_live_registers(masm);
2927 
2928   __ ret(lr);
2929 
2930 #ifdef ASSERT
2931   __ bind(bail);
2932   __ stop("Attempting to adjust pc to skip safepoint poll but the return point is not what we expected");
2933 #endif
2934 
2935   // Make sure all code is generated
2936   masm->flush();
2937 
2938   // Fill-out other meta info
2939   SafepointBlob* sp_blob = SafepointBlob::create(&buffer, oop_maps, frame_size_in_words);
2940 
2941   AOTCodeCache::store_code_blob(*sp_blob, AOTCodeEntry::SharedBlob, StubInfo::blob(id));
2942   return sp_blob;
2943 }
2944 
2945 //
2946 // generate_resolve_blob - call resolution (static/virtual/opt-virtual/ic-miss
2947 //
2948 // Generate a stub that calls into vm to find out the proper destination
2949 // of a java call. All the argument registers are live at this point
2950 // but since this is generic code we don't know what they are and the caller
2951 // must do any gc of the args.
2952 //
2953 RuntimeStub* SharedRuntime::generate_resolve_blob(StubId id, address destination) {
2954   assert (StubRoutines::forward_exception_entry() != nullptr, "must be generated before");
2955   assert(is_resolve_id(id), "expected a resolve stub id");
2956 
2957   const char* name = SharedRuntime::stub_name(id);
2958   CodeBlob* blob = AOTCodeCache::load_code_blob(AOTCodeEntry::SharedBlob, StubInfo::blob(id));
2959   if (blob != nullptr) {
2960     return blob->as_runtime_stub();
2961   }
2962 
2963   // allocate space for the code
2964   ResourceMark rm;
2965   CodeBuffer buffer(name, 1000, 512);
2966   MacroAssembler* masm                = new MacroAssembler(&buffer);
2967 
2968   int frame_size_in_words;
2969   RegisterSaver reg_save(false /* save_vectors */);
2970 
2971   OopMapSet *oop_maps = new OopMapSet();
2972   OopMap* map = nullptr;
2973 
2974   int start = __ offset();
2975 
2976   map = reg_save.save_live_registers(masm, 0, &frame_size_in_words);
2977 
2978   int frame_complete = __ offset();
2979 
2980   {
2981     Label retaddr;
2982     __ set_last_Java_frame(sp, noreg, retaddr, rscratch1);
2983 
2984     __ mov(c_rarg0, rthread);
2985     __ lea(rscratch1, RuntimeAddress(destination));
2986 
2987     __ blr(rscratch1);
2988     __ bind(retaddr);
2989   }
2990 
2991   // Set an oopmap for the call site.
2992   // We need this not only for callee-saved registers, but also for volatile
2993   // registers that the compiler might be keeping live across a safepoint.
2994 
2995   oop_maps->add_gc_map( __ offset() - start, map);
2996 
2997   // r0 contains the address we are going to jump to assuming no exception got installed
2998 
2999   // clear last_Java_sp
3000   __ reset_last_Java_frame(false);
3001   // check for pending exceptions
3002   Label pending;
3003   __ ldr(rscratch1, Address(rthread, Thread::pending_exception_offset()));
3004   __ cbnz(rscratch1, pending);
3005 
3006   // get the returned Method*
3007   __ get_vm_result_metadata(rmethod, rthread);
3008   __ str(rmethod, Address(sp, reg_save.reg_offset_in_bytes(rmethod)));
3009 
3010   // r0 is where we want to jump, overwrite rscratch1 which is saved and scratch
3011   __ str(r0, Address(sp, reg_save.rscratch1_offset_in_bytes()));
3012   reg_save.restore_live_registers(masm);
3013 
3014   // We are back to the original state on entry and ready to go.
3015 
3016   __ br(rscratch1);
3017 
3018   // Pending exception after the safepoint
3019 
3020   __ bind(pending);
3021 
3022   reg_save.restore_live_registers(masm);
3023 
3024   // exception pending => remove activation and forward to exception handler
3025 
3026   __ str(zr, Address(rthread, JavaThread::vm_result_oop_offset()));
3027 
3028   __ ldr(r0, Address(rthread, Thread::pending_exception_offset()));
3029   __ far_jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
3030 
3031   // -------------
3032   // make sure all code is generated
3033   masm->flush();
3034 
3035   // return the  blob
3036   // frame_size_words or bytes??
3037   RuntimeStub* rs_blob = RuntimeStub::new_runtime_stub(name, &buffer, frame_complete, frame_size_in_words, oop_maps, true);
3038 
3039   AOTCodeCache::store_code_blob(*rs_blob, AOTCodeEntry::SharedBlob, StubInfo::blob(id));
3040   return rs_blob;
3041 }
3042 
3043 BufferedInlineTypeBlob* SharedRuntime::generate_buffered_inline_type_adapter(const InlineKlass* vk) {
3044   BufferBlob* buf = BufferBlob::create("inline types pack/unpack", 16 * K);
3045   if (buf == nullptr) {
3046     return nullptr;
3047   }
3048   CodeBuffer buffer(buf);
3049   short buffer_locs[20];
3050   buffer.insts()->initialize_shared_locs((relocInfo*)buffer_locs,
3051                                          sizeof(buffer_locs)/sizeof(relocInfo));
3052 
3053   MacroAssembler _masm(&buffer);
3054   MacroAssembler* masm = &_masm;
3055 
3056   const Array<SigEntry>* sig_vk = vk->extended_sig();
3057   const Array<VMRegPair>* regs = vk->return_regs();
3058 
3059   int pack_fields_jobject_off = __ offset();
3060   // Resolve pre-allocated buffer from JNI handle.
3061   // We cannot do this in generate_call_stub() because it requires GC code to be initialized.
3062   Register Rresult = r14;  // See StubGenerator::generate_call_stub().
3063   __ ldr(r0, Address(Rresult));
3064   __ resolve_jobject(r0 /* value */,
3065                      rthread /* thread */,
3066                      r12 /* tmp */);
3067   __ str(r0, Address(Rresult));
3068 
3069   int pack_fields_off = __ offset();
3070 
3071   int j = 1;
3072   for (int i = 0; i < sig_vk->length(); i++) {
3073     BasicType bt = sig_vk->at(i)._bt;
3074     if (bt == T_METADATA) {
3075       continue;
3076     }
3077     if (bt == T_VOID) {
3078       if (sig_vk->at(i-1)._bt == T_LONG ||
3079           sig_vk->at(i-1)._bt == T_DOUBLE) {
3080         j++;
3081       }
3082       continue;
3083     }
3084     int off = sig_vk->at(i)._offset;
3085     VMRegPair pair = regs->at(j);
3086     VMReg r_1 = pair.first();
3087     VMReg r_2 = pair.second();
3088     Address to(r0, off);
3089     if (bt == T_FLOAT) {
3090       __ strs(r_1->as_FloatRegister(), to);
3091     } else if (bt == T_DOUBLE) {
3092       __ strd(r_1->as_FloatRegister(), to);
3093     } else {
3094       Register val = r_1->as_Register();
3095       assert_different_registers(to.base(), val, r15, r16, r17);
3096       if (is_reference_type(bt)) {
3097         __ store_heap_oop(to, val, r15, r16, r17, IN_HEAP | ACCESS_WRITE | IS_DEST_UNINITIALIZED);
3098       } else {
3099         __ store_sized_value(to, r_1->as_Register(), type2aelembytes(bt));
3100       }
3101     }
3102     j++;
3103   }
3104   assert(j == regs->length(), "missed a field?");
3105   if (vk->has_nullable_atomic_layout()) {
3106     // Zero the null marker (setting it to 1 would be better but would require an additional register)
3107     __ strb(zr, Address(r0, vk->null_marker_offset()));
3108   }
3109   __ ret(lr);
3110 
3111   int unpack_fields_off = __ offset();
3112 
3113   Label skip;
3114   Label not_null;
3115   __ cbnz(r0, not_null);
3116 
3117   // Return value is null. Zero oop registers to make the GC happy.
3118   j = 1;
3119   for (int i = 0; i < sig_vk->length(); i++) {
3120     BasicType bt = sig_vk->at(i)._bt;
3121     if (bt == T_METADATA) {
3122       continue;
3123     }
3124     if (bt == T_VOID) {
3125       if (sig_vk->at(i-1)._bt == T_LONG ||
3126           sig_vk->at(i-1)._bt == T_DOUBLE) {
3127         j++;
3128       }
3129       continue;
3130     }
3131     if (bt == T_OBJECT || bt == T_ARRAY) {
3132       VMRegPair pair = regs->at(j);
3133       VMReg r_1 = pair.first();
3134       __ mov(r_1->as_Register(), zr);
3135     }
3136     j++;
3137   }
3138   __ b(skip);
3139   __ bind(not_null);
3140 
3141   j = 1;
3142   for (int i = 0; i < sig_vk->length(); i++) {
3143     BasicType bt = sig_vk->at(i)._bt;
3144     if (bt == T_METADATA) {
3145       continue;
3146     }
3147     if (bt == T_VOID) {
3148       if (sig_vk->at(i-1)._bt == T_LONG ||
3149           sig_vk->at(i-1)._bt == T_DOUBLE) {
3150         j++;
3151       }
3152       continue;
3153     }
3154     int off = sig_vk->at(i)._offset;
3155     assert(off > 0, "offset in object should be positive");
3156     VMRegPair pair = regs->at(j);
3157     VMReg r_1 = pair.first();
3158     VMReg r_2 = pair.second();
3159     Address from(r0, off);
3160     if (bt == T_FLOAT) {
3161       __ ldrs(r_1->as_FloatRegister(), from);
3162     } else if (bt == T_DOUBLE) {
3163       __ ldrd(r_1->as_FloatRegister(), from);
3164     } else if (bt == T_OBJECT || bt == T_ARRAY) {
3165       assert_different_registers(r0, r_1->as_Register());
3166       __ load_heap_oop(r_1->as_Register(), from, rscratch1, rscratch2);
3167     } else {
3168       assert(is_java_primitive(bt), "unexpected basic type");
3169       assert_different_registers(r0, r_1->as_Register());
3170       size_t size_in_bytes = type2aelembytes(bt);
3171       __ load_sized_value(r_1->as_Register(), from, size_in_bytes, bt != T_CHAR && bt != T_BOOLEAN);
3172     }
3173     j++;
3174   }
3175   assert(j == regs->length(), "missed a field?");
3176 
3177   __ bind(skip);
3178 
3179   __ ret(lr);
3180 
3181   __ flush();
3182 
3183   return BufferedInlineTypeBlob::create(&buffer, pack_fields_off, pack_fields_jobject_off, unpack_fields_off);
3184 }
3185 
3186 // Continuation point for throwing of implicit exceptions that are
3187 // not handled in the current activation. Fabricates an exception
3188 // oop and initiates normal exception dispatching in this
3189 // frame. Since we need to preserve callee-saved values (currently
3190 // only for C2, but done for C1 as well) we need a callee-saved oop
3191 // map and therefore have to make these stubs into RuntimeStubs
3192 // rather than BufferBlobs.  If the compiler needs all registers to
3193 // be preserved between the fault point and the exception handler
3194 // then it must assume responsibility for that in
3195 // AbstractCompiler::continuation_for_implicit_null_exception or
3196 // continuation_for_implicit_division_by_zero_exception. All other
3197 // implicit exceptions (e.g., NullPointerException or
3198 // AbstractMethodError on entry) are either at call sites or
3199 // otherwise assume that stack unwinding will be initiated, so
3200 // caller saved registers were assumed volatile in the compiler.
3201 
3202 RuntimeStub* SharedRuntime::generate_throw_exception(StubId id, address runtime_entry) {
3203   assert(is_throw_id(id), "expected a throw stub id");
3204 
3205   const char* name = SharedRuntime::stub_name(id);
3206 
3207   // Information about frame layout at time of blocking runtime call.
3208   // Note that we only have to preserve callee-saved registers since
3209   // the compilers are responsible for supplying a continuation point
3210   // if they expect all registers to be preserved.
3211   // n.b. aarch64 asserts that frame::arg_reg_save_area_bytes == 0
3212   enum layout {
3213     rfp_off = 0,
3214     rfp_off2,
3215     return_off,
3216     return_off2,
3217     framesize // inclusive of return address
3218   };
3219 
3220   int insts_size = 512;
3221   int locs_size  = 64;
3222 
3223   const char* timer_msg = "SharedRuntime generate_throw_exception";
3224   TraceTime timer(timer_msg, TRACETIME_LOG(Info, startuptime));
3225 
3226   CodeBlob* blob = AOTCodeCache::load_code_blob(AOTCodeEntry::SharedBlob, StubInfo::blob(id));
3227   if (blob != nullptr) {
3228     return blob->as_runtime_stub();
3229   }
3230 
3231   ResourceMark rm;
3232   CodeBuffer code(name, insts_size, locs_size);
3233   OopMapSet* oop_maps  = new OopMapSet();
3234   MacroAssembler* masm = new MacroAssembler(&code);
3235 
3236   address start = __ pc();
3237 
3238   // This is an inlined and slightly modified version of call_VM
3239   // which has the ability to fetch the return PC out of
3240   // thread-local storage and also sets up last_Java_sp slightly
3241   // differently than the real call_VM
3242 
3243   __ enter(); // Save FP and LR before call
3244 
3245   assert(is_even(framesize/2), "sp not 16-byte aligned");
3246 
3247   // lr and fp are already in place
3248   __ sub(sp, rfp, ((uint64_t)framesize-4) << LogBytesPerInt); // prolog
3249 
3250   int frame_complete = __ pc() - start;
3251 
3252   // Set up last_Java_sp and last_Java_fp
3253   address the_pc = __ pc();
3254   __ set_last_Java_frame(sp, rfp, the_pc, rscratch1);
3255 
3256   __ mov(c_rarg0, rthread);
3257   BLOCK_COMMENT("call runtime_entry");
3258   __ lea(rscratch1, RuntimeAddress(runtime_entry));
3259   __ blr(rscratch1);
3260 
3261   // Generate oop map
3262   OopMap* map = new OopMap(framesize, 0);
3263 
3264   oop_maps->add_gc_map(the_pc - start, map);
3265 
3266   __ reset_last_Java_frame(true);
3267 
3268   // Reinitialize the ptrue predicate register, in case the external runtime
3269   // call clobbers ptrue reg, as we may return to SVE compiled code.
3270   __ reinitialize_ptrue();
3271 
3272   __ leave();
3273 
3274   // check for pending exceptions
3275 #ifdef ASSERT
3276   Label L;
3277   __ ldr(rscratch1, Address(rthread, Thread::pending_exception_offset()));
3278   __ cbnz(rscratch1, L);
3279   __ should_not_reach_here();
3280   __ bind(L);
3281 #endif // ASSERT
3282   __ far_jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
3283 
3284   // codeBlob framesize is in words (not VMRegImpl::slot_size)
3285   RuntimeStub* stub =
3286     RuntimeStub::new_runtime_stub(name,
3287                                   &code,
3288                                   frame_complete,
3289                                   (framesize >> (LogBytesPerWord - LogBytesPerInt)),
3290                                   oop_maps, false);
3291   AOTCodeCache::store_code_blob(*stub, AOTCodeEntry::SharedBlob, StubInfo::blob(id));
3292 
3293   return stub;
3294 }
3295 
3296 #if INCLUDE_JFR
3297 
3298 static void jfr_prologue(address the_pc, MacroAssembler* masm, Register thread) {
3299   __ set_last_Java_frame(sp, rfp, the_pc, rscratch1);
3300   __ mov(c_rarg0, thread);
3301 }
3302 
3303 // The handle is dereferenced through a load barrier.
3304 static void jfr_epilogue(MacroAssembler* masm) {
3305   __ reset_last_Java_frame(true);
3306 }
3307 
3308 // For c2: c_rarg0 is junk, call to runtime to write a checkpoint.
3309 // It returns a jobject handle to the event writer.
3310 // The handle is dereferenced and the return value is the event writer oop.
3311 RuntimeStub* SharedRuntime::generate_jfr_write_checkpoint() {
3312   enum layout {
3313     rbp_off,
3314     rbpH_off,
3315     return_off,
3316     return_off2,
3317     framesize // inclusive of return address
3318   };
3319 
3320   int insts_size = 1024;
3321   int locs_size = 64;
3322   const char* name = SharedRuntime::stub_name(StubId::shared_jfr_write_checkpoint_id);
3323   CodeBuffer code(name, insts_size, locs_size);
3324   OopMapSet* oop_maps = new OopMapSet();
3325   MacroAssembler* masm = new MacroAssembler(&code);
3326 
3327   address start = __ pc();
3328   __ enter();
3329   int frame_complete = __ pc() - start;
3330   address the_pc = __ pc();
3331   jfr_prologue(the_pc, masm, rthread);
3332   __ call_VM_leaf(CAST_FROM_FN_PTR(address, JfrIntrinsicSupport::write_checkpoint), 1);
3333   jfr_epilogue(masm);
3334   __ resolve_global_jobject(r0, rscratch1, rscratch2);
3335   __ leave();
3336   __ ret(lr);
3337 
3338   OopMap* map = new OopMap(framesize, 1); // rfp
3339   oop_maps->add_gc_map(the_pc - start, map);
3340 
3341   RuntimeStub* stub = // codeBlob framesize is in words (not VMRegImpl::slot_size)
3342     RuntimeStub::new_runtime_stub(name, &code, frame_complete,
3343                                   (framesize >> (LogBytesPerWord - LogBytesPerInt)),
3344                                   oop_maps, false);
3345   return stub;
3346 }
3347 
3348 // For c2: call to return a leased buffer.
3349 RuntimeStub* SharedRuntime::generate_jfr_return_lease() {
3350   enum layout {
3351     rbp_off,
3352     rbpH_off,
3353     return_off,
3354     return_off2,
3355     framesize // inclusive of return address
3356   };
3357 
3358   int insts_size = 1024;
3359   int locs_size = 64;
3360 
3361   const char* name = SharedRuntime::stub_name(StubId::shared_jfr_return_lease_id);
3362   CodeBuffer code(name, insts_size, locs_size);
3363   OopMapSet* oop_maps = new OopMapSet();
3364   MacroAssembler* masm = new MacroAssembler(&code);
3365 
3366   address start = __ pc();
3367   __ enter();
3368   int frame_complete = __ pc() - start;
3369   address the_pc = __ pc();
3370   jfr_prologue(the_pc, masm, rthread);
3371   __ call_VM_leaf(CAST_FROM_FN_PTR(address, JfrIntrinsicSupport::return_lease), 1);
3372   jfr_epilogue(masm);
3373 
3374   __ leave();
3375   __ ret(lr);
3376 
3377   OopMap* map = new OopMap(framesize, 1); // rfp
3378   oop_maps->add_gc_map(the_pc - start, map);
3379 
3380   RuntimeStub* stub = // codeBlob framesize is in words (not VMRegImpl::slot_size)
3381     RuntimeStub::new_runtime_stub(name, &code, frame_complete,
3382                                   (framesize >> (LogBytesPerWord - LogBytesPerInt)),
3383                                   oop_maps, false);
3384   return stub;
3385 }
3386 
3387 #endif // INCLUDE_JFR