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