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