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