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