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 // On 64 bit we will store integer like items to the stack as
 825 // 64 bits items (sparc abi) even though java would only store
 826 // 32bits for a parameter. On 32bit it will simply be 32 bits
 827 // So this routine will do 32->32 on 32bit and 32->64 on 64bit
 828 static void move32_64(MacroAssembler* masm, VMRegPair src, VMRegPair dst) {
 829   if (src.first()->is_stack()) {
 830     if (dst.first()->is_stack()) {
 831       // stack to stack
 832       __ ldr(rscratch1, Address(rfp, reg2offset_in(src.first())));
 833       __ str(rscratch1, Address(sp, reg2offset_out(dst.first())));
 834     } else {
 835       // stack to reg
 836       __ ldrsw(dst.first()->as_Register(), Address(rfp, reg2offset_in(src.first())));
 837     }
 838   } else if (dst.first()->is_stack()) {
 839     // reg to stack
 840     // Do we really have to sign extend???
 841     // __ movslq(src.first()->as_Register(), src.first()->as_Register());
 842     __ str(src.first()->as_Register(), Address(sp, reg2offset_out(dst.first())));
 843   } else {
 844     if (dst.first() != src.first()) {
 845       __ sxtw(dst.first()->as_Register(), src.first()->as_Register());
 846     }
 847   }
 848 }
 849 
 850 // An oop arg. Must pass a handle not the oop itself
 851 static void object_move(MacroAssembler* masm,
 852                         OopMap* map,
 853                         int oop_handle_offset,
 854                         int framesize_in_slots,
 855                         VMRegPair src,
 856                         VMRegPair dst,
 857                         bool is_receiver,
 858                         int* receiver_offset) {
 859 
 860   // must pass a handle. First figure out the location we use as a handle
 861 
 862   Register rHandle = dst.first()->is_stack() ? rscratch2 : dst.first()->as_Register();
 863 
 864   // See if oop is NULL if it is we need no handle
 865 
 866   if (src.first()->is_stack()) {
 867 
 868     // Oop is already on the stack as an argument
 869     int offset_in_older_frame = src.first()->reg2stack() + SharedRuntime::out_preserve_stack_slots();
 870     map->set_oop(VMRegImpl::stack2reg(offset_in_older_frame + framesize_in_slots));
 871     if (is_receiver) {
 872       *receiver_offset = (offset_in_older_frame + framesize_in_slots) * VMRegImpl::stack_slot_size;
 873     }
 874 
 875     __ ldr(rscratch1, Address(rfp, reg2offset_in(src.first())));
 876     __ lea(rHandle, Address(rfp, reg2offset_in(src.first())));
 877     // conditionally move a NULL
 878     __ cmp(rscratch1, zr);
 879     __ csel(rHandle, zr, rHandle, Assembler::EQ);
 880   } else {
 881 
 882     // Oop is in an a register we must store it to the space we reserve
 883     // on the stack for oop_handles and pass a handle if oop is non-NULL
 884 
 885     const Register rOop = src.first()->as_Register();
 886     int oop_slot;
 887     if (rOop == j_rarg0)
 888       oop_slot = 0;
 889     else if (rOop == j_rarg1)
 890       oop_slot = 1;
 891     else if (rOop == j_rarg2)
 892       oop_slot = 2;
 893     else if (rOop == j_rarg3)
 894       oop_slot = 3;
 895     else if (rOop == j_rarg4)
 896       oop_slot = 4;
 897     else if (rOop == j_rarg5)
 898       oop_slot = 5;
 899     else if (rOop == j_rarg6)
 900       oop_slot = 6;
 901     else {
 902       assert(rOop == j_rarg7, "wrong register");
 903       oop_slot = 7;
 904     }
 905 
 906     oop_slot = oop_slot * VMRegImpl::slots_per_word + oop_handle_offset;
 907     int offset = oop_slot*VMRegImpl::stack_slot_size;
 908 
 909     map->set_oop(VMRegImpl::stack2reg(oop_slot));
 910     // Store oop in handle area, may be NULL
 911     __ str(rOop, Address(sp, offset));
 912     if (is_receiver) {
 913       *receiver_offset = offset;
 914     }
 915 
 916     __ cmp(rOop, zr);
 917     __ lea(rHandle, Address(sp, offset));
 918     // conditionally move a NULL
 919     __ csel(rHandle, zr, rHandle, Assembler::EQ);
 920   }
 921 
 922   // If arg is on the stack then place it otherwise it is already in correct reg.
 923   if (dst.first()->is_stack()) {
 924     __ str(rHandle, Address(sp, reg2offset_out(dst.first())));
 925   }
 926 }
 927 
 928 // A float arg may have to do float reg int reg conversion
 929 static void float_move(MacroAssembler* masm, VMRegPair src, VMRegPair dst) {
 930   assert(src.first()->is_stack() && dst.first()->is_stack() ||
 931          src.first()->is_reg() && dst.first()->is_reg(), "Unexpected error");
 932   if (src.first()->is_stack()) {
 933     if (dst.first()->is_stack()) {
 934       __ ldrw(rscratch1, Address(rfp, reg2offset_in(src.first())));
 935       __ strw(rscratch1, Address(sp, reg2offset_out(dst.first())));
 936     } else {
 937       ShouldNotReachHere();
 938     }
 939   } else if (src.first() != dst.first()) {
 940     if (src.is_single_phys_reg() && dst.is_single_phys_reg())
 941       __ fmovs(dst.first()->as_FloatRegister(), src.first()->as_FloatRegister());
 942     else
 943       ShouldNotReachHere();
 944   }
 945 }
 946 
 947 // A long move
 948 static void long_move(MacroAssembler* masm, VMRegPair src, VMRegPair dst) {
 949   if (src.first()->is_stack()) {
 950     if (dst.first()->is_stack()) {
 951       // stack to stack
 952       __ ldr(rscratch1, Address(rfp, reg2offset_in(src.first())));
 953       __ str(rscratch1, Address(sp, reg2offset_out(dst.first())));
 954     } else {
 955       // stack to reg
 956       __ ldr(dst.first()->as_Register(), Address(rfp, reg2offset_in(src.first())));
 957     }
 958   } else if (dst.first()->is_stack()) {
 959     // reg to stack
 960     // Do we really have to sign extend???
 961     // __ movslq(src.first()->as_Register(), src.first()->as_Register());
 962     __ str(src.first()->as_Register(), Address(sp, reg2offset_out(dst.first())));
 963   } else {
 964     if (dst.first() != src.first()) {
 965       __ mov(dst.first()->as_Register(), src.first()->as_Register());
 966     }
 967   }
 968 }
 969 
 970 
 971 // A double move
 972 static void double_move(MacroAssembler* masm, VMRegPair src, VMRegPair dst) {
 973   assert(src.first()->is_stack() && dst.first()->is_stack() ||
 974          src.first()->is_reg() && dst.first()->is_reg(), "Unexpected error");
 975   if (src.first()->is_stack()) {
 976     if (dst.first()->is_stack()) {
 977       __ ldr(rscratch1, Address(rfp, reg2offset_in(src.first())));
 978       __ str(rscratch1, Address(sp, reg2offset_out(dst.first())));
 979     } else {
 980       ShouldNotReachHere();
 981     }
 982   } else if (src.first() != dst.first()) {
 983     if (src.is_single_phys_reg() && dst.is_single_phys_reg())
 984       __ fmovd(dst.first()->as_FloatRegister(), src.first()->as_FloatRegister());
 985     else
 986       ShouldNotReachHere();
 987   }
 988 }
 989 
 990 
 991 void SharedRuntime::save_native_result(MacroAssembler *masm, BasicType ret_type, int frame_slots) {
 992   // We always ignore the frame_slots arg and just use the space just below frame pointer
 993   // which by this time is free to use
 994   switch (ret_type) {
 995   case T_FLOAT:
 996     __ strs(v0, Address(rfp, -wordSize));
 997     break;
 998   case T_DOUBLE:
 999     __ strd(v0, Address(rfp, -wordSize));
1000     break;
1001   case T_VOID:  break;
1002   default: {
1003     __ str(r0, Address(rfp, -wordSize));
1004     }
1005   }
1006 }
1007 
1008 void SharedRuntime::restore_native_result(MacroAssembler *masm, BasicType ret_type, int frame_slots) {
1009   // We always ignore the frame_slots arg and just use the space just below frame pointer
1010   // which by this time is free to use
1011   switch (ret_type) {
1012   case T_FLOAT:
1013     __ ldrs(v0, Address(rfp, -wordSize));
1014     break;
1015   case T_DOUBLE:
1016     __ ldrd(v0, Address(rfp, -wordSize));
1017     break;
1018   case T_VOID:  break;
1019   default: {
1020     __ ldr(r0, Address(rfp, -wordSize));
1021     }
1022   }
1023 }
1024 static void save_args(MacroAssembler *masm, int arg_count, int first_arg, VMRegPair *args) {
1025   RegSet x;
1026   for ( int i = first_arg ; i < arg_count ; i++ ) {
1027     if (args[i].first()->is_Register()) {
1028       x = x + args[i].first()->as_Register();
1029     } else if (args[i].first()->is_FloatRegister()) {
1030       __ strd(args[i].first()->as_FloatRegister(), Address(__ pre(sp, -2 * wordSize)));
1031     }
1032   }
1033   __ push(x, sp);
1034 }
1035 
1036 static void restore_args(MacroAssembler *masm, int arg_count, int first_arg, VMRegPair *args) {
1037   RegSet x;
1038   for ( int i = first_arg ; i < arg_count ; i++ ) {
1039     if (args[i].first()->is_Register()) {
1040       x = x + args[i].first()->as_Register();
1041     } else {
1042       ;
1043     }
1044   }
1045   __ pop(x, sp);
1046   for ( int i = arg_count - 1 ; i >= first_arg ; i-- ) {
1047     if (args[i].first()->is_Register()) {
1048       ;
1049     } else if (args[i].first()->is_FloatRegister()) {
1050       __ ldrd(args[i].first()->as_FloatRegister(), Address(__ post(sp, 2 * wordSize)));
1051     }
1052   }
1053 }
1054 
1055 
1056 // Check GCLocker::needs_gc and enter the runtime if it's true.  This
1057 // keeps a new JNI critical region from starting until a GC has been
1058 // forced.  Save down any oops in registers and describe them in an
1059 // OopMap.
1060 static void check_needs_gc_for_critical_native(MacroAssembler* masm,
1061                                                int stack_slots,
1062                                                int total_c_args,
1063                                                int total_in_args,
1064                                                int arg_save_area,
1065                                                OopMapSet* oop_maps,
1066                                                VMRegPair* in_regs,
1067                                                BasicType* in_sig_bt) { Unimplemented(); }
1068 
1069 // Unpack an array argument into a pointer to the body and the length
1070 // if the array is non-null, otherwise pass 0 for both.
1071 static void unpack_array_argument(MacroAssembler* masm, VMRegPair reg, BasicType in_elem_type, VMRegPair body_arg, VMRegPair length_arg) { Unimplemented(); }
1072 
1073 
1074 class ComputeMoveOrder: public StackObj {
1075   class MoveOperation: public ResourceObj {
1076     friend class ComputeMoveOrder;
1077    private:
1078     VMRegPair        _src;
1079     VMRegPair        _dst;
1080     int              _src_index;
1081     int              _dst_index;
1082     bool             _processed;
1083     MoveOperation*  _next;
1084     MoveOperation*  _prev;
1085 
1086     static int get_id(VMRegPair r) { Unimplemented(); return 0; }
1087 
1088    public:
1089     MoveOperation(int src_index, VMRegPair src, int dst_index, VMRegPair dst):
1090       _src(src)
1091     , _dst(dst)
1092     , _src_index(src_index)
1093     , _dst_index(dst_index)
1094     , _processed(false)
1095     , _next(NULL)
1096     , _prev(NULL) { Unimplemented(); }
1097 
1098     VMRegPair src() const              { Unimplemented(); return _src; }
1099     int src_id() const                 { Unimplemented(); return 0; }
1100     int src_index() const              { Unimplemented(); return 0; }
1101     VMRegPair dst() const              { Unimplemented(); return _src; }
1102     void set_dst(int i, VMRegPair dst) { Unimplemented(); }
1103     int dst_index() const              { Unimplemented(); return 0; }
1104     int dst_id() const                 { Unimplemented(); return 0; }
1105     MoveOperation* next() const        { Unimplemented(); return 0; }
1106     MoveOperation* prev() const        { Unimplemented(); return 0; }
1107     void set_processed()               { Unimplemented(); }
1108     bool is_processed() const          { Unimplemented(); return 0; }
1109 
1110     // insert
1111     void break_cycle(VMRegPair temp_register) { Unimplemented(); }
1112 
1113     void link(GrowableArray<MoveOperation*>& killer) { Unimplemented(); }
1114   };
1115 
1116  private:
1117   GrowableArray<MoveOperation*> edges;
1118 
1119  public:
1120   ComputeMoveOrder(int total_in_args, VMRegPair* in_regs, int total_c_args, VMRegPair* out_regs,
1121                     BasicType* in_sig_bt, GrowableArray<int>& arg_order, VMRegPair tmp_vmreg) { Unimplemented(); }
1122 
1123   // Collected all the move operations
1124   void add_edge(int src_index, VMRegPair src, int dst_index, VMRegPair dst) { Unimplemented(); }
1125 
1126   // Walk the edges breaking cycles between moves.  The result list
1127   // can be walked in order to produce the proper set of loads
1128   GrowableArray<MoveOperation*>* get_store_order(VMRegPair temp_register) { Unimplemented(); return 0; }
1129 };
1130 
1131 
1132 static void rt_call(MacroAssembler* masm, address dest) {
1133   CodeBlob *cb = CodeCache::find_blob(dest);
1134   if (cb) {
1135     __ far_call(RuntimeAddress(dest));
1136   } else {
1137     __ lea(rscratch1, RuntimeAddress(dest));
1138     __ blr(rscratch1);
1139     __ maybe_isb();
1140   }
1141 }
1142 
1143 static void verify_oop_args(MacroAssembler* masm,
1144                             const methodHandle& method,
1145                             const BasicType* sig_bt,
1146                             const VMRegPair* regs) {
1147   Register temp_reg = r19;  // not part of any compiled calling seq
1148   if (VerifyOops) {
1149     for (int i = 0; i < method->size_of_parameters(); i++) {
1150       if (sig_bt[i] == T_OBJECT ||
1151           sig_bt[i] == T_ARRAY) {
1152         VMReg r = regs[i].first();
1153         assert(r->is_valid(), "bad oop arg");
1154         if (r->is_stack()) {
1155           __ ldr(temp_reg, Address(sp, r->reg2stack() * VMRegImpl::stack_slot_size));
1156           __ verify_oop(temp_reg);
1157         } else {
1158           __ verify_oop(r->as_Register());
1159         }
1160       }
1161     }
1162   }
1163 }
1164 
1165 static void gen_special_dispatch(MacroAssembler* masm,
1166                                  const methodHandle& method,
1167                                  const BasicType* sig_bt,
1168                                  const VMRegPair* regs) {
1169   verify_oop_args(masm, method, sig_bt, regs);
1170   vmIntrinsics::ID iid = method->intrinsic_id();
1171 
1172   // Now write the args into the outgoing interpreter space
1173   bool     has_receiver   = false;
1174   Register receiver_reg   = noreg;
1175   int      member_arg_pos = -1;
1176   Register member_reg     = noreg;
1177   int      ref_kind       = MethodHandles::signature_polymorphic_intrinsic_ref_kind(iid);
1178   if (ref_kind != 0) {
1179     member_arg_pos = method->size_of_parameters() - 1;  // trailing MemberName argument
1180     member_reg = r19;  // known to be free at this point
1181     has_receiver = MethodHandles::ref_kind_has_receiver(ref_kind);
1182   } else if (iid == vmIntrinsics::_invokeBasic) {
1183     has_receiver = true;
1184   } else {
1185     fatal("unexpected intrinsic id %d", iid);
1186   }
1187 
1188   if (member_reg != noreg) {
1189     // Load the member_arg into register, if necessary.
1190     SharedRuntime::check_member_name_argument_is_last_argument(method, sig_bt, regs);
1191     VMReg r = regs[member_arg_pos].first();
1192     if (r->is_stack()) {
1193       __ ldr(member_reg, Address(sp, r->reg2stack() * VMRegImpl::stack_slot_size));
1194     } else {
1195       // no data motion is needed
1196       member_reg = r->as_Register();
1197     }
1198   }
1199 
1200   if (has_receiver) {
1201     // Make sure the receiver is loaded into a register.
1202     assert(method->size_of_parameters() > 0, "oob");
1203     assert(sig_bt[0] == T_OBJECT, "receiver argument must be an object");
1204     VMReg r = regs[0].first();
1205     assert(r->is_valid(), "bad receiver arg");
1206     if (r->is_stack()) {
1207       // Porting note:  This assumes that compiled calling conventions always
1208       // pass the receiver oop in a register.  If this is not true on some
1209       // platform, pick a temp and load the receiver from stack.
1210       fatal("receiver always in a register");
1211       receiver_reg = r2;  // known to be free at this point
1212       __ ldr(receiver_reg, Address(sp, r->reg2stack() * VMRegImpl::stack_slot_size));
1213     } else {
1214       // no data motion is needed
1215       receiver_reg = r->as_Register();
1216     }
1217   }
1218 
1219   // Figure out which address we are really jumping to:
1220   MethodHandles::generate_method_handle_dispatch(masm, iid,
1221                                                  receiver_reg, member_reg, /*for_compiler_entry:*/ true);
1222 }
1223 
1224 // ---------------------------------------------------------------------------
1225 // Generate a native wrapper for a given method.  The method takes arguments
1226 // in the Java compiled code convention, marshals them to the native
1227 // convention (handlizes oops, etc), transitions to native, makes the call,
1228 // returns to java state (possibly blocking), unhandlizes any result and
1229 // returns.
1230 //
1231 // Critical native functions are a shorthand for the use of
1232 // GetPrimtiveArrayCritical and disallow the use of any other JNI
1233 // functions.  The wrapper is expected to unpack the arguments before
1234 // passing them to the callee and perform checks before and after the
1235 // native call to ensure that they GCLocker
1236 // lock_critical/unlock_critical semantics are followed.  Some other
1237 // parts of JNI setup are skipped like the tear down of the JNI handle
1238 // block and the check for pending exceptions it's impossible for them
1239 // to be thrown.
1240 //
1241 // They are roughly structured like this:
1242 //    if (GCLocker::needs_gc())
1243 //      SharedRuntime::block_for_jni_critical();
1244 //    tranistion to thread_in_native
1245 //    unpack arrray arguments and call native entry point
1246 //    check for safepoint in progress
1247 //    check if any thread suspend flags are set
1248 //      call into JVM and possible unlock the JNI critical
1249 //      if a GC was suppressed while in the critical native.
1250 //    transition back to thread_in_Java
1251 //    return to caller
1252 //
1253 nmethod* SharedRuntime::generate_native_wrapper(MacroAssembler* masm,
1254                                                 const methodHandle& method,
1255                                                 int compile_id,
1256                                                 BasicType* in_sig_bt,
1257                                                 VMRegPair* in_regs,
1258                                                 BasicType ret_type,
1259                                                 address critical_entry) {
1260   if (method->is_method_handle_intrinsic()) {
1261     vmIntrinsics::ID iid = method->intrinsic_id();
1262     intptr_t start = (intptr_t)__ pc();
1263     int vep_offset = ((intptr_t)__ pc()) - start;
1264 
1265     // First instruction must be a nop as it may need to be patched on deoptimisation
1266     __ nop();
1267     gen_special_dispatch(masm,
1268                          method,
1269                          in_sig_bt,
1270                          in_regs);
1271     int frame_complete = ((intptr_t)__ pc()) - start;  // not complete, period
1272     __ flush();
1273     int stack_slots = SharedRuntime::out_preserve_stack_slots();  // no out slots at all, actually
1274     return nmethod::new_native_nmethod(method,
1275                                        compile_id,
1276                                        masm->code(),
1277                                        vep_offset,
1278                                        frame_complete,
1279                                        stack_slots / VMRegImpl::slots_per_word,
1280                                        in_ByteSize(-1),
1281                                        in_ByteSize(-1),
1282                                        (OopMapSet*)NULL);
1283   }
1284   bool is_critical_native = true;
1285   address native_func = critical_entry;
1286   if (native_func == NULL) {
1287     native_func = method->native_function();
1288     is_critical_native = false;
1289   }
1290   assert(native_func != NULL, "must have function");
1291 
1292   // An OopMap for lock (and class if static)
1293   OopMapSet *oop_maps = new OopMapSet();
1294   intptr_t start = (intptr_t)__ pc();
1295 
1296   // We have received a description of where all the java arg are located
1297   // on entry to the wrapper. We need to convert these args to where
1298   // the jni function will expect them. To figure out where they go
1299   // we convert the java signature to a C signature by inserting
1300   // the hidden arguments as arg[0] and possibly arg[1] (static method)
1301 
1302   const int total_in_args = method->size_of_parameters();
1303   int total_c_args = total_in_args;
1304   if (!is_critical_native) {
1305     total_c_args += 1;
1306     if (method->is_static()) {
1307       total_c_args++;
1308     }
1309   } else {
1310     for (int i = 0; i < total_in_args; i++) {
1311       if (in_sig_bt[i] == T_ARRAY) {
1312         total_c_args++;
1313       }
1314     }
1315   }
1316 
1317   BasicType* out_sig_bt = NEW_RESOURCE_ARRAY(BasicType, total_c_args);
1318   VMRegPair* out_regs   = NEW_RESOURCE_ARRAY(VMRegPair, total_c_args);
1319   BasicType* in_elem_bt = NULL;
1320 
1321   int argc = 0;
1322   if (!is_critical_native) {
1323     out_sig_bt[argc++] = T_ADDRESS;
1324     if (method->is_static()) {
1325       out_sig_bt[argc++] = T_OBJECT;
1326     }
1327 
1328     for (int i = 0; i < total_in_args ; i++ ) {
1329       out_sig_bt[argc++] = in_sig_bt[i];
1330     }
1331   } else {
1332     in_elem_bt = NEW_RESOURCE_ARRAY(BasicType, total_in_args);
1333     SignatureStream ss(method->signature());
1334     for (int i = 0; i < total_in_args ; i++ ) {
1335       if (in_sig_bt[i] == T_ARRAY) {
1336         // Arrays are passed as int, elem* pair
1337         out_sig_bt[argc++] = T_INT;
1338         out_sig_bt[argc++] = T_ADDRESS;
1339         ss.skip_array_prefix(1);  // skip one '['
1340         assert(ss.is_primitive(), "primitive type expected");
1341         in_elem_bt[i] = ss.type();
1342       } else {
1343         out_sig_bt[argc++] = in_sig_bt[i];
1344         in_elem_bt[i] = T_VOID;
1345       }
1346       if (in_sig_bt[i] != T_VOID) {
1347         assert(in_sig_bt[i] == ss.type() ||
1348                in_sig_bt[i] == T_ARRAY, "must match");
1349         ss.next();
1350       }
1351     }
1352   }
1353 
1354   // Now figure out where the args must be stored and how much stack space
1355   // they require.
1356   int out_arg_slots;
1357   out_arg_slots = c_calling_convention(out_sig_bt, out_regs, NULL, total_c_args);
1358 
1359   // Compute framesize for the wrapper.  We need to handlize all oops in
1360   // incoming registers
1361 
1362   // Calculate the total number of stack slots we will need.
1363 
1364   // First count the abi requirement plus all of the outgoing args
1365   int stack_slots = SharedRuntime::out_preserve_stack_slots() + out_arg_slots;
1366 
1367   // Now the space for the inbound oop handle area
1368   int total_save_slots = 8 * VMRegImpl::slots_per_word;  // 8 arguments passed in registers
1369   if (is_critical_native) {
1370     // Critical natives may have to call out so they need a save area
1371     // for register arguments.
1372     int double_slots = 0;
1373     int single_slots = 0;
1374     for ( int i = 0; i < total_in_args; i++) {
1375       if (in_regs[i].first()->is_Register()) {
1376         const Register reg = in_regs[i].first()->as_Register();
1377         switch (in_sig_bt[i]) {
1378           case T_BOOLEAN:
1379           case T_BYTE:
1380           case T_SHORT:
1381           case T_CHAR:
1382           case T_INT:  single_slots++; break;
1383           case T_ARRAY:  // specific to LP64 (7145024)
1384           case T_LONG: double_slots++; break;
1385           default:  ShouldNotReachHere();
1386         }
1387       } else if (in_regs[i].first()->is_FloatRegister()) {
1388         ShouldNotReachHere();
1389       }
1390     }
1391     total_save_slots = double_slots * 2 + single_slots;
1392     // align the save area
1393     if (double_slots != 0) {
1394       stack_slots = align_up(stack_slots, 2);
1395     }
1396   }
1397 
1398   int oop_handle_offset = stack_slots;
1399   stack_slots += total_save_slots;
1400 
1401   // Now any space we need for handlizing a klass if static method
1402 
1403   int klass_slot_offset = 0;
1404   int klass_offset = -1;
1405   int lock_slot_offset = 0;
1406   bool is_static = false;
1407 
1408   if (method->is_static()) {
1409     klass_slot_offset = stack_slots;
1410     stack_slots += VMRegImpl::slots_per_word;
1411     klass_offset = klass_slot_offset * VMRegImpl::stack_slot_size;
1412     is_static = true;
1413   }
1414 
1415   // Plus a lock if needed
1416 
1417   if (method->is_synchronized()) {
1418     lock_slot_offset = stack_slots;
1419     stack_slots += VMRegImpl::slots_per_word;
1420   }
1421 
1422   // Now a place (+2) to save return values or temp during shuffling
1423   // + 4 for return address (which we own) and saved rfp
1424   stack_slots += 6;
1425 
1426   // Ok The space we have allocated will look like:
1427   //
1428   //
1429   // FP-> |                     |
1430   //      |---------------------|
1431   //      | 2 slots for moves   |
1432   //      |---------------------|
1433   //      | lock box (if sync)  |
1434   //      |---------------------| <- lock_slot_offset
1435   //      | klass (if static)   |
1436   //      |---------------------| <- klass_slot_offset
1437   //      | oopHandle area      |
1438   //      |---------------------| <- oop_handle_offset (8 java arg registers)
1439   //      | outbound memory     |
1440   //      | based arguments     |
1441   //      |                     |
1442   //      |---------------------|
1443   //      |                     |
1444   // SP-> | out_preserved_slots |
1445   //
1446   //
1447 
1448 
1449   // Now compute actual number of stack words we need rounding to make
1450   // stack properly aligned.
1451   stack_slots = align_up(stack_slots, StackAlignmentInSlots);
1452 
1453   int stack_size = stack_slots * VMRegImpl::stack_slot_size;
1454 
1455   // First thing make an ic check to see if we should even be here
1456 
1457   // We are free to use all registers as temps without saving them and
1458   // restoring them except rfp. rfp is the only callee save register
1459   // as far as the interpreter and the compiler(s) are concerned.
1460 
1461 
1462   const Register ic_reg = rscratch2;
1463   const Register receiver = j_rarg0;
1464 
1465   Label hit;
1466   Label exception_pending;
1467 
1468   assert_different_registers(ic_reg, receiver, rscratch1);
1469   __ verify_oop(receiver);
1470   __ cmp_klass(receiver, ic_reg, rscratch1);
1471   __ br(Assembler::EQ, hit);
1472 
1473   __ far_jump(RuntimeAddress(SharedRuntime::get_ic_miss_stub()));
1474 
1475   // Verified entry point must be aligned
1476   __ align(8);
1477 
1478   __ bind(hit);
1479 
1480   int vep_offset = ((intptr_t)__ pc()) - start;
1481 
1482   // If we have to make this method not-entrant we'll overwrite its
1483   // first instruction with a jump.  For this action to be legal we
1484   // must ensure that this first instruction is a B, BL, NOP, BKPT,
1485   // SVC, HVC, or SMC.  Make it a NOP.
1486   __ nop();
1487 
1488   if (VM_Version::supports_fast_class_init_checks() && method->needs_clinit_barrier()) {
1489     Label L_skip_barrier;
1490     __ mov_metadata(rscratch2, method->method_holder()); // InstanceKlass*
1491     __ clinit_barrier(rscratch2, rscratch1, &L_skip_barrier);
1492     __ far_jump(RuntimeAddress(SharedRuntime::get_handle_wrong_method_stub()));
1493 
1494     __ bind(L_skip_barrier);
1495   }
1496 
1497   // Generate stack overflow check
1498   if (UseStackBanging) {
1499     __ bang_stack_with_offset(JavaThread::stack_shadow_zone_size());
1500   } else {
1501     Unimplemented();
1502   }
1503 
1504   // Generate a new frame for the wrapper.
1505   __ enter();
1506   // -2 because return address is already present and so is saved rfp
1507   __ sub(sp, sp, stack_size - 2*wordSize);
1508 
1509   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
1510   bs->nmethod_entry_barrier(masm);
1511 
1512   // Frame is now completed as far as size and linkage.
1513   int frame_complete = ((intptr_t)__ pc()) - start;
1514 
1515   // We use r20 as the oop handle for the receiver/klass
1516   // It is callee save so it survives the call to native
1517 
1518   const Register oop_handle_reg = r20;
1519 
1520   if (is_critical_native) {
1521     check_needs_gc_for_critical_native(masm, stack_slots, total_c_args, total_in_args,
1522                                        oop_handle_offset, oop_maps, in_regs, in_sig_bt);
1523   }
1524 
1525   //
1526   // We immediately shuffle the arguments so that any vm call we have to
1527   // make from here on out (sync slow path, jvmti, etc.) we will have
1528   // captured the oops from our caller and have a valid oopMap for
1529   // them.
1530 
1531   // -----------------
1532   // The Grand Shuffle
1533 
1534   // The Java calling convention is either equal (linux) or denser (win64) than the
1535   // c calling convention. However the because of the jni_env argument the c calling
1536   // convention always has at least one more (and two for static) arguments than Java.
1537   // Therefore if we move the args from java -> c backwards then we will never have
1538   // a register->register conflict and we don't have to build a dependency graph
1539   // and figure out how to break any cycles.
1540   //
1541 
1542   // Record esp-based slot for receiver on stack for non-static methods
1543   int receiver_offset = -1;
1544 
1545   // This is a trick. We double the stack slots so we can claim
1546   // the oops in the caller's frame. Since we are sure to have
1547   // more args than the caller doubling is enough to make
1548   // sure we can capture all the incoming oop args from the
1549   // caller.
1550   //
1551   OopMap* map = new OopMap(stack_slots * 2, 0 /* arg_slots*/);
1552 
1553   // Mark location of rfp (someday)
1554   // map->set_callee_saved(VMRegImpl::stack2reg( stack_slots - 2), stack_slots * 2, 0, vmreg(rfp));
1555 
1556 
1557   int float_args = 0;
1558   int int_args = 0;
1559 
1560 #ifdef ASSERT
1561   bool reg_destroyed[RegisterImpl::number_of_registers];
1562   bool freg_destroyed[FloatRegisterImpl::number_of_registers];
1563   for ( int r = 0 ; r < RegisterImpl::number_of_registers ; r++ ) {
1564     reg_destroyed[r] = false;
1565   }
1566   for ( int f = 0 ; f < FloatRegisterImpl::number_of_registers ; f++ ) {
1567     freg_destroyed[f] = false;
1568   }
1569 
1570 #endif /* ASSERT */
1571 
1572   // This may iterate in two different directions depending on the
1573   // kind of native it is.  The reason is that for regular JNI natives
1574   // the incoming and outgoing registers are offset upwards and for
1575   // critical natives they are offset down.
1576   GrowableArray<int> arg_order(2 * total_in_args);
1577   VMRegPair tmp_vmreg;
1578   tmp_vmreg.set2(r19->as_VMReg());
1579 
1580   if (!is_critical_native) {
1581     for (int i = total_in_args - 1, c_arg = total_c_args - 1; i >= 0; i--, c_arg--) {
1582       arg_order.push(i);
1583       arg_order.push(c_arg);
1584     }
1585   } else {
1586     // Compute a valid move order, using tmp_vmreg to break any cycles
1587     ComputeMoveOrder cmo(total_in_args, in_regs, total_c_args, out_regs, in_sig_bt, arg_order, tmp_vmreg);
1588   }
1589 
1590   int temploc = -1;
1591   for (int ai = 0; ai < arg_order.length(); ai += 2) {
1592     int i = arg_order.at(ai);
1593     int c_arg = arg_order.at(ai + 1);
1594     __ block_comment(err_msg("move %d -> %d", i, c_arg));
1595     if (c_arg == -1) {
1596       assert(is_critical_native, "should only be required for critical natives");
1597       // This arg needs to be moved to a temporary
1598       __ mov(tmp_vmreg.first()->as_Register(), in_regs[i].first()->as_Register());
1599       in_regs[i] = tmp_vmreg;
1600       temploc = i;
1601       continue;
1602     } else if (i == -1) {
1603       assert(is_critical_native, "should only be required for critical natives");
1604       // Read from the temporary location
1605       assert(temploc != -1, "must be valid");
1606       i = temploc;
1607       temploc = -1;
1608     }
1609 #ifdef ASSERT
1610     if (in_regs[i].first()->is_Register()) {
1611       assert(!reg_destroyed[in_regs[i].first()->as_Register()->encoding()], "destroyed reg!");
1612     } else if (in_regs[i].first()->is_FloatRegister()) {
1613       assert(!freg_destroyed[in_regs[i].first()->as_FloatRegister()->encoding()], "destroyed reg!");
1614     }
1615     if (out_regs[c_arg].first()->is_Register()) {
1616       reg_destroyed[out_regs[c_arg].first()->as_Register()->encoding()] = true;
1617     } else if (out_regs[c_arg].first()->is_FloatRegister()) {
1618       freg_destroyed[out_regs[c_arg].first()->as_FloatRegister()->encoding()] = true;
1619     }
1620 #endif /* ASSERT */
1621     switch (in_sig_bt[i]) {
1622       case T_ARRAY:
1623         if (is_critical_native) {
1624           unpack_array_argument(masm, in_regs[i], in_elem_bt[i], out_regs[c_arg + 1], out_regs[c_arg]);
1625           c_arg++;
1626 #ifdef ASSERT
1627           if (out_regs[c_arg].first()->is_Register()) {
1628             reg_destroyed[out_regs[c_arg].first()->as_Register()->encoding()] = true;
1629           } else if (out_regs[c_arg].first()->is_FloatRegister()) {
1630             freg_destroyed[out_regs[c_arg].first()->as_FloatRegister()->encoding()] = true;
1631           }
1632 #endif
1633           int_args++;
1634           break;
1635         }
1636       case T_OBJECT:
1637         assert(!is_critical_native, "no oop arguments");
1638         object_move(masm, map, oop_handle_offset, stack_slots, in_regs[i], out_regs[c_arg],
1639                     ((i == 0) && (!is_static)),
1640                     &receiver_offset);
1641         int_args++;
1642         break;
1643       case T_VOID:
1644         break;
1645 
1646       case T_FLOAT:
1647         float_move(masm, in_regs[i], out_regs[c_arg]);
1648         float_args++;
1649         break;
1650 
1651       case T_DOUBLE:
1652         assert( i + 1 < total_in_args &&
1653                 in_sig_bt[i + 1] == T_VOID &&
1654                 out_sig_bt[c_arg+1] == T_VOID, "bad arg list");
1655         double_move(masm, in_regs[i], out_regs[c_arg]);
1656         float_args++;
1657         break;
1658 
1659       case T_LONG :
1660         long_move(masm, in_regs[i], out_regs[c_arg]);
1661         int_args++;
1662         break;
1663 
1664       case T_ADDRESS: assert(false, "found T_ADDRESS in java args");
1665 
1666       default:
1667         move32_64(masm, in_regs[i], out_regs[c_arg]);
1668         int_args++;
1669     }
1670   }
1671 
1672   // point c_arg at the first arg that is already loaded in case we
1673   // need to spill before we call out
1674   int c_arg = total_c_args - total_in_args;
1675 
1676   // Pre-load a static method's oop into c_rarg1.
1677   if (method->is_static() && !is_critical_native) {
1678 
1679     //  load oop into a register
1680     __ movoop(c_rarg1,
1681               JNIHandles::make_local(method->method_holder()->java_mirror()),
1682               /*immediate*/true);
1683 
1684     // Now handlize the static class mirror it's known not-null.
1685     __ str(c_rarg1, Address(sp, klass_offset));
1686     map->set_oop(VMRegImpl::stack2reg(klass_slot_offset));
1687 
1688     // Now get the handle
1689     __ lea(c_rarg1, Address(sp, klass_offset));
1690     // and protect the arg if we must spill
1691     c_arg--;
1692   }
1693 
1694   // Change state to native (we save the return address in the thread, since it might not
1695   // be pushed on the stack when we do a stack traversal).
1696   // We use the same pc/oopMap repeatedly when we call out
1697 
1698   Label native_return;
1699   __ set_last_Java_frame(sp, noreg, native_return, rscratch1);
1700 
1701   Label dtrace_method_entry, dtrace_method_entry_done;
1702   {
1703     uint64_t offset;
1704     __ adrp(rscratch1, ExternalAddress((address)&DTraceMethodProbes), offset);
1705     __ ldrb(rscratch1, Address(rscratch1, offset));
1706     __ cbnzw(rscratch1, dtrace_method_entry);
1707     __ bind(dtrace_method_entry_done);
1708   }
1709 
1710   // RedefineClasses() tracing support for obsolete method entry
1711   if (log_is_enabled(Trace, redefine, class, obsolete)) {
1712     // protect the args we've loaded
1713     save_args(masm, total_c_args, c_arg, out_regs);
1714     __ mov_metadata(c_rarg1, method());
1715     __ call_VM_leaf(
1716       CAST_FROM_FN_PTR(address, SharedRuntime::rc_trace_method_entry),
1717       rthread, c_rarg1);
1718     restore_args(masm, total_c_args, c_arg, out_regs);
1719   }
1720 
1721   // Lock a synchronized method
1722 
1723   // Register definitions used by locking and unlocking
1724 
1725   const Register swap_reg = r0;
1726   const Register obj_reg  = r19;  // Will contain the oop
1727   const Register lock_reg = r13;  // Address of compiler lock object (BasicLock)
1728   const Register old_hdr  = r13;  // value of old header at unlock time
1729   const Register tmp = lr;
1730 
1731   Label slow_path_lock;
1732   Label lock_done;
1733 
1734   if (method->is_synchronized()) {
1735     assert(!is_critical_native, "unhandled");
1736 
1737     const int mark_word_offset = BasicLock::displaced_header_offset_in_bytes();
1738 
1739     // Get the handle (the 2nd argument)
1740     __ mov(oop_handle_reg, c_rarg1);
1741 
1742     // Get address of the box
1743 
1744     __ lea(lock_reg, Address(sp, lock_slot_offset * VMRegImpl::stack_slot_size));
1745 
1746     // Load the oop from the handle
1747     __ ldr(obj_reg, Address(oop_handle_reg, 0));
1748 
1749     __ resolve(IS_NOT_NULL, obj_reg);
1750 
1751     if (UseBiasedLocking) {
1752       __ biased_locking_enter(lock_reg, obj_reg, swap_reg, tmp, false, lock_done, &slow_path_lock);
1753     }
1754 
1755     // Load (object->mark() | 1) into swap_reg %r0
1756     __ ldr(rscratch1, Address(obj_reg, oopDesc::mark_offset_in_bytes()));
1757     __ orr(swap_reg, rscratch1, 1);
1758 
1759     // Save (object->mark() | 1) into BasicLock's displaced header
1760     __ str(swap_reg, Address(lock_reg, mark_word_offset));
1761 
1762     // src -> dest iff dest == r0 else r0 <- dest
1763     { Label here;
1764       __ cmpxchg_obj_header(r0, lock_reg, obj_reg, rscratch1, lock_done, /*fallthrough*/NULL);
1765     }
1766 
1767     // Hmm should this move to the slow path code area???
1768 
1769     // Test if the oopMark is an obvious stack pointer, i.e.,
1770     //  1) (mark & 3) == 0, and
1771     //  2) sp <= mark < mark + os::pagesize()
1772     // These 3 tests can be done by evaluating the following
1773     // expression: ((mark - sp) & (3 - os::vm_page_size())),
1774     // assuming both stack pointer and pagesize have their
1775     // least significant 2 bits clear.
1776     // NOTE: the oopMark is in swap_reg %r0 as the result of cmpxchg
1777 
1778     __ sub(swap_reg, sp, swap_reg);
1779     __ neg(swap_reg, swap_reg);
1780     __ ands(swap_reg, swap_reg, 3 - os::vm_page_size());
1781 
1782     // Save the test result, for recursive case, the result is zero
1783     __ str(swap_reg, Address(lock_reg, mark_word_offset));
1784     __ br(Assembler::NE, slow_path_lock);
1785 
1786     // Slow path will re-enter here
1787 
1788     __ bind(lock_done);
1789   }
1790 
1791 
1792   // Finally just about ready to make the JNI call
1793 
1794   // get JNIEnv* which is first argument to native
1795   if (!is_critical_native) {
1796     __ lea(c_rarg0, Address(rthread, in_bytes(JavaThread::jni_environment_offset())));
1797   }
1798 
1799   // Now set thread in native
1800   __ mov(rscratch1, _thread_in_native);
1801   __ lea(rscratch2, Address(rthread, JavaThread::thread_state_offset()));
1802   __ stlrw(rscratch1, rscratch2);
1803 
1804   rt_call(masm, native_func);
1805 
1806   __ bind(native_return);
1807 
1808   intptr_t return_pc = (intptr_t) __ pc();
1809   oop_maps->add_gc_map(return_pc - start, map);
1810 
1811   // Unpack native results.
1812   switch (ret_type) {
1813   case T_BOOLEAN: __ c2bool(r0);                     break;
1814   case T_CHAR   : __ ubfx(r0, r0, 0, 16);            break;
1815   case T_BYTE   : __ sbfx(r0, r0, 0, 8);             break;
1816   case T_SHORT  : __ sbfx(r0, r0, 0, 16);            break;
1817   case T_INT    : __ sbfx(r0, r0, 0, 32);            break;
1818   case T_DOUBLE :
1819   case T_FLOAT  :
1820     // Result is in v0 we'll save as needed
1821     break;
1822   case T_ARRAY:                 // Really a handle
1823   case T_OBJECT:                // Really a handle
1824       break; // can't de-handlize until after safepoint check
1825   case T_VOID: break;
1826   case T_LONG: break;
1827   default       : ShouldNotReachHere();
1828   }
1829 
1830   // Switch thread to "native transition" state before reading the synchronization state.
1831   // This additional state is necessary because reading and testing the synchronization
1832   // state is not atomic w.r.t. GC, as this scenario demonstrates:
1833   //     Java thread A, in _thread_in_native state, loads _not_synchronized and is preempted.
1834   //     VM thread changes sync state to synchronizing and suspends threads for GC.
1835   //     Thread A is resumed to finish this native method, but doesn't block here since it
1836   //     didn't see any synchronization is progress, and escapes.
1837   __ mov(rscratch1, _thread_in_native_trans);
1838 
1839   __ strw(rscratch1, Address(rthread, JavaThread::thread_state_offset()));
1840 
1841   // Force this write out before the read below
1842   __ dmb(Assembler::ISH);
1843 
1844   // check for safepoint operation in progress and/or pending suspend requests
1845   Label safepoint_in_progress, safepoint_in_progress_done;
1846   {
1847     __ safepoint_poll_acquire(safepoint_in_progress);
1848     __ ldrw(rscratch1, Address(rthread, JavaThread::suspend_flags_offset()));
1849     __ cbnzw(rscratch1, safepoint_in_progress);
1850     __ bind(safepoint_in_progress_done);
1851   }
1852 
1853   // change thread state
1854   Label after_transition;
1855   __ mov(rscratch1, _thread_in_Java);
1856   __ lea(rscratch2, Address(rthread, JavaThread::thread_state_offset()));
1857   __ stlrw(rscratch1, rscratch2);
1858   __ bind(after_transition);
1859 
1860   Label reguard;
1861   Label reguard_done;
1862   __ ldrb(rscratch1, Address(rthread, JavaThread::stack_guard_state_offset()));
1863   __ cmpw(rscratch1, JavaThread::stack_guard_yellow_reserved_disabled);
1864   __ br(Assembler::EQ, reguard);
1865   __ bind(reguard_done);
1866 
1867   // native result if any is live
1868 
1869   // Unlock
1870   Label unlock_done;
1871   Label slow_path_unlock;
1872   if (method->is_synchronized()) {
1873 
1874     // Get locked oop from the handle we passed to jni
1875     __ ldr(obj_reg, Address(oop_handle_reg, 0));
1876 
1877     __ resolve(IS_NOT_NULL, obj_reg);
1878 
1879     Label done;
1880 
1881     if (UseBiasedLocking) {
1882       __ biased_locking_exit(obj_reg, old_hdr, done);
1883     }
1884 
1885     // Simple recursive lock?
1886 
1887     __ ldr(rscratch1, Address(sp, lock_slot_offset * VMRegImpl::stack_slot_size));
1888     __ cbz(rscratch1, done);
1889 
1890     // Must save r0 if if it is live now because cmpxchg must use it
1891     if (ret_type != T_FLOAT && ret_type != T_DOUBLE && ret_type != T_VOID) {
1892       save_native_result(masm, ret_type, stack_slots);
1893     }
1894 
1895 
1896     // get address of the stack lock
1897     __ lea(r0, Address(sp, lock_slot_offset * VMRegImpl::stack_slot_size));
1898     //  get old displaced header
1899     __ ldr(old_hdr, Address(r0, 0));
1900 
1901     // Atomic swap old header if oop still contains the stack lock
1902     Label succeed;
1903     __ cmpxchg_obj_header(r0, old_hdr, obj_reg, rscratch1, succeed, &slow_path_unlock);
1904     __ bind(succeed);
1905 
1906     // slow path re-enters here
1907     __ bind(unlock_done);
1908     if (ret_type != T_FLOAT && ret_type != T_DOUBLE && ret_type != T_VOID) {
1909       restore_native_result(masm, ret_type, stack_slots);
1910     }
1911 
1912     __ bind(done);
1913   }
1914 
1915   Label dtrace_method_exit, dtrace_method_exit_done;
1916   {
1917     uint64_t offset;
1918     __ adrp(rscratch1, ExternalAddress((address)&DTraceMethodProbes), offset);
1919     __ ldrb(rscratch1, Address(rscratch1, offset));
1920     __ cbnzw(rscratch1, dtrace_method_exit);
1921     __ bind(dtrace_method_exit_done);
1922   }
1923 
1924   __ reset_last_Java_frame(false);
1925 
1926   // Unbox oop result, e.g. JNIHandles::resolve result.
1927   if (is_reference_type(ret_type)) {
1928     __ resolve_jobject(r0, rthread, rscratch2);
1929   }
1930 
1931   if (CheckJNICalls) {
1932     // clear_pending_jni_exception_check
1933     __ str(zr, Address(rthread, JavaThread::pending_jni_exception_check_fn_offset()));
1934   }
1935 
1936   if (!is_critical_native) {
1937     // reset handle block
1938     __ ldr(r2, Address(rthread, JavaThread::active_handles_offset()));
1939     __ str(zr, Address(r2, JNIHandleBlock::top_offset_in_bytes()));
1940   }
1941 
1942   __ leave();
1943 
1944   if (!is_critical_native) {
1945     // Any exception pending?
1946     __ ldr(rscratch1, Address(rthread, in_bytes(Thread::pending_exception_offset())));
1947     __ cbnz(rscratch1, exception_pending);
1948   }
1949 
1950   // We're done
1951   __ ret(lr);
1952 
1953   // Unexpected paths are out of line and go here
1954 
1955   if (!is_critical_native) {
1956     // forward the exception
1957     __ bind(exception_pending);
1958 
1959     // and forward the exception
1960     __ far_jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
1961   }
1962 
1963   // Slow path locking & unlocking
1964   if (method->is_synchronized()) {
1965 
1966     __ block_comment("Slow path lock {");
1967     __ bind(slow_path_lock);
1968 
1969     // has last_Java_frame setup. No exceptions so do vanilla call not call_VM
1970     // args are (oop obj, BasicLock* lock, JavaThread* thread)
1971 
1972     // protect the args we've loaded
1973     save_args(masm, total_c_args, c_arg, out_regs);
1974 
1975     __ mov(c_rarg0, obj_reg);
1976     __ mov(c_rarg1, lock_reg);
1977     __ mov(c_rarg2, rthread);
1978 
1979     // Not a leaf but we have last_Java_frame setup as we want
1980     __ call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::complete_monitor_locking_C), 3);
1981     restore_args(masm, total_c_args, c_arg, out_regs);
1982 
1983 #ifdef ASSERT
1984     { Label L;
1985       __ ldr(rscratch1, Address(rthread, in_bytes(Thread::pending_exception_offset())));
1986       __ cbz(rscratch1, L);
1987       __ stop("no pending exception allowed on exit from monitorenter");
1988       __ bind(L);
1989     }
1990 #endif
1991     __ b(lock_done);
1992 
1993     __ block_comment("} Slow path lock");
1994 
1995     __ block_comment("Slow path unlock {");
1996     __ bind(slow_path_unlock);
1997 
1998     // If we haven't already saved the native result we must save it now as xmm registers
1999     // are still exposed.
2000 
2001     if (ret_type == T_FLOAT || ret_type == T_DOUBLE ) {
2002       save_native_result(masm, ret_type, stack_slots);
2003     }
2004 
2005     __ mov(c_rarg2, rthread);
2006     __ lea(c_rarg1, Address(sp, lock_slot_offset * VMRegImpl::stack_slot_size));
2007     __ mov(c_rarg0, obj_reg);
2008 
2009     // Save pending exception around call to VM (which contains an EXCEPTION_MARK)
2010     // NOTE that obj_reg == r19 currently
2011     __ ldr(r19, Address(rthread, in_bytes(Thread::pending_exception_offset())));
2012     __ str(zr, Address(rthread, in_bytes(Thread::pending_exception_offset())));
2013 
2014     rt_call(masm, CAST_FROM_FN_PTR(address, SharedRuntime::complete_monitor_unlocking_C));
2015 
2016 #ifdef ASSERT
2017     {
2018       Label L;
2019       __ ldr(rscratch1, Address(rthread, in_bytes(Thread::pending_exception_offset())));
2020       __ cbz(rscratch1, L);
2021       __ stop("no pending exception allowed on exit complete_monitor_unlocking_C");
2022       __ bind(L);
2023     }
2024 #endif /* ASSERT */
2025 
2026     __ str(r19, Address(rthread, in_bytes(Thread::pending_exception_offset())));
2027 
2028     if (ret_type == T_FLOAT || ret_type == T_DOUBLE ) {
2029       restore_native_result(masm, ret_type, stack_slots);
2030     }
2031     __ b(unlock_done);
2032 
2033     __ block_comment("} Slow path unlock");
2034 
2035   } // synchronized
2036 
2037   // SLOW PATH Reguard the stack if needed
2038 
2039   __ bind(reguard);
2040   save_native_result(masm, ret_type, stack_slots);
2041   rt_call(masm, CAST_FROM_FN_PTR(address, SharedRuntime::reguard_yellow_pages));
2042   restore_native_result(masm, ret_type, stack_slots);
2043   // and continue
2044   __ b(reguard_done);
2045 
2046   // SLOW PATH safepoint
2047   {
2048     __ block_comment("safepoint {");
2049     __ bind(safepoint_in_progress);
2050 
2051     // Don't use call_VM as it will see a possible pending exception and forward it
2052     // and never return here preventing us from clearing _last_native_pc down below.
2053     //
2054     save_native_result(masm, ret_type, stack_slots);
2055     __ mov(c_rarg0, rthread);
2056 #ifndef PRODUCT
2057   assert(frame::arg_reg_save_area_bytes == 0, "not expecting frame reg save area");
2058 #endif
2059     if (!is_critical_native) {
2060       __ lea(rscratch1, RuntimeAddress(CAST_FROM_FN_PTR(address, JavaThread::check_special_condition_for_native_trans)));
2061     } else {
2062       __ lea(rscratch1, RuntimeAddress(CAST_FROM_FN_PTR(address, JavaThread::check_special_condition_for_native_trans_and_transition)));
2063     }
2064     __ blr(rscratch1);
2065     __ maybe_isb();
2066     // Restore any method result value
2067     restore_native_result(masm, ret_type, stack_slots);
2068 
2069     if (is_critical_native) {
2070       // The call above performed the transition to thread_in_Java so
2071       // skip the transition logic above.
2072       __ b(after_transition);
2073     }
2074 
2075     __ b(safepoint_in_progress_done);
2076     __ block_comment("} safepoint");
2077   }
2078 
2079   // SLOW PATH dtrace support
2080   {
2081     __ block_comment("dtrace entry {");
2082     __ bind(dtrace_method_entry);
2083 
2084     // We have all of the arguments setup at this point. We must not touch any register
2085     // argument registers at this point (what if we save/restore them there are no oop?
2086 
2087     save_args(masm, total_c_args, c_arg, out_regs);
2088     __ mov_metadata(c_rarg1, method());
2089     __ call_VM_leaf(
2090       CAST_FROM_FN_PTR(address, SharedRuntime::dtrace_method_entry),
2091       rthread, c_rarg1);
2092     restore_args(masm, total_c_args, c_arg, out_regs);
2093     __ b(dtrace_method_entry_done);
2094     __ block_comment("} dtrace entry");
2095   }
2096 
2097   {
2098     __ block_comment("dtrace exit {");
2099     __ bind(dtrace_method_exit);
2100     save_native_result(masm, ret_type, stack_slots);
2101     __ mov_metadata(c_rarg1, method());
2102     __ call_VM_leaf(
2103          CAST_FROM_FN_PTR(address, SharedRuntime::dtrace_method_exit),
2104          rthread, c_rarg1);
2105     restore_native_result(masm, ret_type, stack_slots);
2106     __ b(dtrace_method_exit_done);
2107     __ block_comment("} dtrace exit");
2108   }
2109 
2110 
2111   __ flush();
2112 
2113   nmethod *nm = nmethod::new_native_nmethod(method,
2114                                             compile_id,
2115                                             masm->code(),
2116                                             vep_offset,
2117                                             frame_complete,
2118                                             stack_slots / VMRegImpl::slots_per_word,
2119                                             (is_static ? in_ByteSize(klass_offset) : in_ByteSize(receiver_offset)),
2120                                             in_ByteSize(lock_slot_offset*VMRegImpl::stack_slot_size),
2121                                             oop_maps);
2122 
2123   if (is_critical_native) {
2124     nm->set_lazy_critical_native(true);
2125   }
2126 
2127   return nm;
2128 
2129 }
2130 
2131 // this function returns the adjust size (in number of words) to a c2i adapter
2132 // activation for use during deoptimization
2133 int Deoptimization::last_frame_adjust(int callee_parameters, int callee_locals) {
2134   assert(callee_locals >= callee_parameters,
2135           "test and remove; got more parms than locals");
2136   if (callee_locals < callee_parameters)
2137     return 0;                   // No adjustment for negative locals
2138   int diff = (callee_locals - callee_parameters) * Interpreter::stackElementWords;
2139   // diff is counted in stack words
2140   return align_up(diff, 2);
2141 }
2142 
2143 
2144 //------------------------------generate_deopt_blob----------------------------
2145 void SharedRuntime::generate_deopt_blob() {
2146   // Allocate space for the code
2147   ResourceMark rm;
2148   // Setup code generation tools
2149   int pad = 0;
2150 #if INCLUDE_JVMCI
2151   if (EnableJVMCI || UseAOT) {
2152     pad += 512; // Increase the buffer size when compiling for JVMCI
2153   }
2154 #endif
2155   CodeBuffer buffer("deopt_blob", 2048+pad, 1024);
2156   MacroAssembler* masm = new MacroAssembler(&buffer);
2157   int frame_size_in_words;
2158   OopMap* map = NULL;
2159   OopMapSet *oop_maps = new OopMapSet();
2160 
2161   // -------------
2162   // This code enters when returning to a de-optimized nmethod.  A return
2163   // address has been pushed on the the stack, and return values are in
2164   // registers.
2165   // If we are doing a normal deopt then we were called from the patched
2166   // nmethod from the point we returned to the nmethod. So the return
2167   // address on the stack is wrong by NativeCall::instruction_size
2168   // We will adjust the value so it looks like we have the original return
2169   // address on the stack (like when we eagerly deoptimized).
2170   // In the case of an exception pending when deoptimizing, we enter
2171   // with a return address on the stack that points after the call we patched
2172   // into the exception handler. We have the following register state from,
2173   // e.g., the forward exception stub (see stubGenerator_x86_64.cpp).
2174   //    r0: exception oop
2175   //    r19: exception handler
2176   //    r3: throwing pc
2177   // So in this case we simply jam r3 into the useless return address and
2178   // the stack looks just like we want.
2179   //
2180   // At this point we need to de-opt.  We save the argument return
2181   // registers.  We call the first C routine, fetch_unroll_info().  This
2182   // routine captures the return values and returns a structure which
2183   // describes the current frame size and the sizes of all replacement frames.
2184   // The current frame is compiled code and may contain many inlined
2185   // functions, each with their own JVM state.  We pop the current frame, then
2186   // push all the new frames.  Then we call the C routine unpack_frames() to
2187   // populate these frames.  Finally unpack_frames() returns us the new target
2188   // address.  Notice that callee-save registers are BLOWN here; they have
2189   // already been captured in the vframeArray at the time the return PC was
2190   // patched.
2191   address start = __ pc();
2192   Label cont;
2193 
2194   // Prolog for non exception case!
2195 
2196   // Save everything in sight.
2197   map = RegisterSaver::save_live_registers(masm, 0, &frame_size_in_words);
2198 
2199   // Normal deoptimization.  Save exec mode for unpack_frames.
2200   __ movw(rcpool, Deoptimization::Unpack_deopt); // callee-saved
2201   __ b(cont);
2202 
2203   int reexecute_offset = __ pc() - start;
2204 #if INCLUDE_JVMCI && !defined(COMPILER1)
2205   if (EnableJVMCI && UseJVMCICompiler) {
2206     // JVMCI does not use this kind of deoptimization
2207     __ should_not_reach_here();
2208   }
2209 #endif
2210 
2211   // Reexecute case
2212   // return address is the pc describes what bci to do re-execute at
2213 
2214   // No need to update map as each call to save_live_registers will produce identical oopmap
2215   (void) RegisterSaver::save_live_registers(masm, 0, &frame_size_in_words);
2216 
2217   __ movw(rcpool, Deoptimization::Unpack_reexecute); // callee-saved
2218   __ b(cont);
2219 
2220 #if INCLUDE_JVMCI
2221   Label after_fetch_unroll_info_call;
2222   int implicit_exception_uncommon_trap_offset = 0;
2223   int uncommon_trap_offset = 0;
2224 
2225   if (EnableJVMCI || UseAOT) {
2226     implicit_exception_uncommon_trap_offset = __ pc() - start;
2227 
2228     __ ldr(lr, Address(rthread, in_bytes(JavaThread::jvmci_implicit_exception_pc_offset())));
2229     __ str(zr, Address(rthread, in_bytes(JavaThread::jvmci_implicit_exception_pc_offset())));
2230 
2231     uncommon_trap_offset = __ pc() - start;
2232 
2233     // Save everything in sight.
2234     RegisterSaver::save_live_registers(masm, 0, &frame_size_in_words);
2235     // fetch_unroll_info needs to call last_java_frame()
2236     Label retaddr;
2237     __ set_last_Java_frame(sp, noreg, retaddr, rscratch1);
2238 
2239     __ ldrw(c_rarg1, Address(rthread, in_bytes(JavaThread::pending_deoptimization_offset())));
2240     __ movw(rscratch1, -1);
2241     __ strw(rscratch1, Address(rthread, in_bytes(JavaThread::pending_deoptimization_offset())));
2242 
2243     __ movw(rcpool, (int32_t)Deoptimization::Unpack_reexecute);
2244     __ mov(c_rarg0, rthread);
2245     __ movw(c_rarg2, rcpool); // exec mode
2246     __ lea(rscratch1,
2247            RuntimeAddress(CAST_FROM_FN_PTR(address,
2248                                            Deoptimization::uncommon_trap)));
2249     __ blr(rscratch1);
2250     __ bind(retaddr);
2251     oop_maps->add_gc_map( __ pc()-start, map->deep_copy());
2252 
2253     __ reset_last_Java_frame(false);
2254 
2255     __ b(after_fetch_unroll_info_call);
2256   } // EnableJVMCI
2257 #endif // INCLUDE_JVMCI
2258 
2259   int exception_offset = __ pc() - start;
2260 
2261   // Prolog for exception case
2262 
2263   // all registers are dead at this entry point, except for r0, and
2264   // r3 which contain the exception oop and exception pc
2265   // respectively.  Set them in TLS and fall thru to the
2266   // unpack_with_exception_in_tls entry point.
2267 
2268   __ str(r3, Address(rthread, JavaThread::exception_pc_offset()));
2269   __ str(r0, Address(rthread, JavaThread::exception_oop_offset()));
2270 
2271   int exception_in_tls_offset = __ pc() - start;
2272 
2273   // new implementation because exception oop is now passed in JavaThread
2274 
2275   // Prolog for exception case
2276   // All registers must be preserved because they might be used by LinearScan
2277   // Exceptiop oop and throwing PC are passed in JavaThread
2278   // tos: stack at point of call to method that threw the exception (i.e. only
2279   // args are on the stack, no return address)
2280 
2281   // The return address pushed by save_live_registers will be patched
2282   // later with the throwing pc. The correct value is not available
2283   // now because loading it from memory would destroy registers.
2284 
2285   // NB: The SP at this point must be the SP of the method that is
2286   // being deoptimized.  Deoptimization assumes that the frame created
2287   // here by save_live_registers is immediately below the method's SP.
2288   // This is a somewhat fragile mechanism.
2289 
2290   // Save everything in sight.
2291   map = RegisterSaver::save_live_registers(masm, 0, &frame_size_in_words);
2292 
2293   // Now it is safe to overwrite any register
2294 
2295   // Deopt during an exception.  Save exec mode for unpack_frames.
2296   __ mov(rcpool, Deoptimization::Unpack_exception); // callee-saved
2297 
2298   // load throwing pc from JavaThread and patch it as the return address
2299   // of the current frame. Then clear the field in JavaThread
2300 
2301   __ ldr(r3, Address(rthread, JavaThread::exception_pc_offset()));
2302   __ str(r3, Address(rfp, wordSize));
2303   __ str(zr, Address(rthread, JavaThread::exception_pc_offset()));
2304 
2305 #ifdef ASSERT
2306   // verify that there is really an exception oop in JavaThread
2307   __ ldr(r0, Address(rthread, JavaThread::exception_oop_offset()));
2308   __ verify_oop(r0);
2309 
2310   // verify that there is no pending exception
2311   Label no_pending_exception;
2312   __ ldr(rscratch1, Address(rthread, Thread::pending_exception_offset()));
2313   __ cbz(rscratch1, no_pending_exception);
2314   __ stop("must not have pending exception here");
2315   __ bind(no_pending_exception);
2316 #endif
2317 
2318   __ bind(cont);
2319 
2320   // Call C code.  Need thread and this frame, but NOT official VM entry
2321   // crud.  We cannot block on this call, no GC can happen.
2322   //
2323   // UnrollBlock* fetch_unroll_info(JavaThread* thread)
2324 
2325   // fetch_unroll_info needs to call last_java_frame().
2326 
2327   Label retaddr;
2328   __ set_last_Java_frame(sp, noreg, retaddr, rscratch1);
2329 #ifdef ASSERT0
2330   { Label L;
2331     __ ldr(rscratch1, Address(rthread,
2332                               JavaThread::last_Java_fp_offset()));
2333     __ cbz(rscratch1, L);
2334     __ stop("SharedRuntime::generate_deopt_blob: last_Java_fp not cleared");
2335     __ bind(L);
2336   }
2337 #endif // ASSERT
2338   __ mov(c_rarg0, rthread);
2339   __ mov(c_rarg1, rcpool);
2340   __ lea(rscratch1, RuntimeAddress(CAST_FROM_FN_PTR(address, Deoptimization::fetch_unroll_info)));
2341   __ blr(rscratch1);
2342   __ bind(retaddr);
2343 
2344   // Need to have an oopmap that tells fetch_unroll_info where to
2345   // find any register it might need.
2346   oop_maps->add_gc_map(__ pc() - start, map);
2347 
2348   __ reset_last_Java_frame(false);
2349 
2350 #if INCLUDE_JVMCI
2351   if (EnableJVMCI || UseAOT) {
2352     __ bind(after_fetch_unroll_info_call);
2353   }
2354 #endif
2355 
2356   // Load UnrollBlock* into r5
2357   __ mov(r5, r0);
2358 
2359   __ ldrw(rcpool, Address(r5, Deoptimization::UnrollBlock::unpack_kind_offset_in_bytes()));
2360    Label noException;
2361   __ cmpw(rcpool, Deoptimization::Unpack_exception);   // Was exception pending?
2362   __ br(Assembler::NE, noException);
2363   __ ldr(r0, Address(rthread, JavaThread::exception_oop_offset()));
2364   // QQQ this is useless it was NULL above
2365   __ ldr(r3, Address(rthread, JavaThread::exception_pc_offset()));
2366   __ str(zr, Address(rthread, JavaThread::exception_oop_offset()));
2367   __ str(zr, Address(rthread, JavaThread::exception_pc_offset()));
2368 
2369   __ verify_oop(r0);
2370 
2371   // Overwrite the result registers with the exception results.
2372   __ str(r0, Address(sp, RegisterSaver::r0_offset_in_bytes()));
2373   // I think this is useless
2374   // __ str(r3, Address(sp, RegisterSaver::r3_offset_in_bytes()));
2375 
2376   __ bind(noException);
2377 
2378   // Only register save data is on the stack.
2379   // Now restore the result registers.  Everything else is either dead
2380   // or captured in the vframeArray.
2381   RegisterSaver::restore_result_registers(masm);
2382 
2383   // All of the register save area has been popped of the stack. Only the
2384   // return address remains.
2385 
2386   // Pop all the frames we must move/replace.
2387   //
2388   // Frame picture (youngest to oldest)
2389   // 1: self-frame (no frame link)
2390   // 2: deopting frame  (no frame link)
2391   // 3: caller of deopting frame (could be compiled/interpreted).
2392   //
2393   // Note: by leaving the return address of self-frame on the stack
2394   // and using the size of frame 2 to adjust the stack
2395   // when we are done the return to frame 3 will still be on the stack.
2396 
2397   // Pop deoptimized frame
2398   __ ldrw(r2, Address(r5, Deoptimization::UnrollBlock::size_of_deoptimized_frame_offset_in_bytes()));
2399   __ sub(r2, r2, 2 * wordSize);
2400   __ add(sp, sp, r2);
2401   __ ldp(rfp, lr, __ post(sp, 2 * wordSize));
2402   // LR should now be the return address to the caller (3)
2403 
2404 #ifdef ASSERT
2405   // Compilers generate code that bang the stack by as much as the
2406   // interpreter would need. So this stack banging should never
2407   // trigger a fault. Verify that it does not on non product builds.
2408   if (UseStackBanging) {
2409     __ ldrw(r19, Address(r5, Deoptimization::UnrollBlock::total_frame_sizes_offset_in_bytes()));
2410     __ bang_stack_size(r19, r2);
2411   }
2412 #endif
2413   // Load address of array of frame pcs into r2
2414   __ ldr(r2, Address(r5, Deoptimization::UnrollBlock::frame_pcs_offset_in_bytes()));
2415 
2416   // Trash the old pc
2417   // __ addptr(sp, wordSize);  FIXME ????
2418 
2419   // Load address of array of frame sizes into r4
2420   __ ldr(r4, Address(r5, Deoptimization::UnrollBlock::frame_sizes_offset_in_bytes()));
2421 
2422   // Load counter into r3
2423   __ ldrw(r3, Address(r5, Deoptimization::UnrollBlock::number_of_frames_offset_in_bytes()));
2424 
2425   // Now adjust the caller's stack to make up for the extra locals
2426   // but record the original sp so that we can save it in the skeletal interpreter
2427   // frame and the stack walking of interpreter_sender will get the unextended sp
2428   // value and not the "real" sp value.
2429 
2430   const Register sender_sp = r6;
2431 
2432   __ mov(sender_sp, sp);
2433   __ ldrw(r19, Address(r5,
2434                        Deoptimization::UnrollBlock::
2435                        caller_adjustment_offset_in_bytes()));
2436   __ sub(sp, sp, r19);
2437 
2438   // Push interpreter frames in a loop
2439   __ mov(rscratch1, (address)0xDEADDEAD);        // Make a recognizable pattern
2440   __ mov(rscratch2, rscratch1);
2441   Label loop;
2442   __ bind(loop);
2443   __ ldr(r19, Address(__ post(r4, wordSize)));          // Load frame size
2444   __ sub(r19, r19, 2*wordSize);           // We'll push pc and fp by hand
2445   __ ldr(lr, Address(__ post(r2, wordSize)));  // Load pc
2446   __ enter();                           // Save old & set new fp
2447   __ sub(sp, sp, r19);                  // Prolog
2448   // This value is corrected by layout_activation_impl
2449   __ str(zr, Address(rfp, frame::interpreter_frame_last_sp_offset * wordSize));
2450   __ str(sender_sp, Address(rfp, frame::interpreter_frame_sender_sp_offset * wordSize)); // Make it walkable
2451   __ mov(sender_sp, sp);               // Pass sender_sp to next frame
2452   __ sub(r3, r3, 1);                   // Decrement counter
2453   __ cbnz(r3, loop);
2454 
2455     // Re-push self-frame
2456   __ ldr(lr, Address(r2));
2457   __ enter();
2458 
2459   // Allocate a full sized register save area.  We subtract 2 because
2460   // enter() just pushed 2 words
2461   __ sub(sp, sp, (frame_size_in_words - 2) * wordSize);
2462 
2463   // Restore frame locals after moving the frame
2464   __ strd(v0, Address(sp, RegisterSaver::v0_offset_in_bytes()));
2465   __ str(r0, Address(sp, RegisterSaver::r0_offset_in_bytes()));
2466 
2467   // Call C code.  Need thread but NOT official VM entry
2468   // crud.  We cannot block on this call, no GC can happen.  Call should
2469   // restore return values to their stack-slots with the new SP.
2470   //
2471   // void Deoptimization::unpack_frames(JavaThread* thread, int exec_mode)
2472 
2473   // Use rfp because the frames look interpreted now
2474   // Don't need the precise return PC here, just precise enough to point into this code blob.
2475   address the_pc = __ pc();
2476   __ set_last_Java_frame(sp, rfp, the_pc, rscratch1);
2477 
2478   __ mov(c_rarg0, rthread);
2479   __ movw(c_rarg1, rcpool); // second arg: exec_mode
2480   __ lea(rscratch1, RuntimeAddress(CAST_FROM_FN_PTR(address, Deoptimization::unpack_frames)));
2481   __ blr(rscratch1);
2482 
2483   // Set an oopmap for the call site
2484   // Use the same PC we used for the last java frame
2485   oop_maps->add_gc_map(the_pc - start,
2486                        new OopMap( frame_size_in_words, 0 ));
2487 
2488   // Clear fp AND pc
2489   __ reset_last_Java_frame(true);
2490 
2491   // Collect return values
2492   __ ldrd(v0, Address(sp, RegisterSaver::v0_offset_in_bytes()));
2493   __ ldr(r0, Address(sp, RegisterSaver::r0_offset_in_bytes()));
2494   // I think this is useless (throwing pc?)
2495   // __ ldr(r3, Address(sp, RegisterSaver::r3_offset_in_bytes()));
2496 
2497   // Pop self-frame.
2498   __ leave();                           // Epilog
2499 
2500   // Jump to interpreter
2501   __ ret(lr);
2502 
2503   // Make sure all code is generated
2504   masm->flush();
2505 
2506   _deopt_blob = DeoptimizationBlob::create(&buffer, oop_maps, 0, exception_offset, reexecute_offset, frame_size_in_words);
2507   _deopt_blob->set_unpack_with_exception_in_tls_offset(exception_in_tls_offset);
2508 #if INCLUDE_JVMCI
2509   if (EnableJVMCI || UseAOT) {
2510     _deopt_blob->set_uncommon_trap_offset(uncommon_trap_offset);
2511     _deopt_blob->set_implicit_exception_uncommon_trap_offset(implicit_exception_uncommon_trap_offset);
2512   }
2513 #endif
2514 }
2515 
2516 uint SharedRuntime::out_preserve_stack_slots() {
2517   return 0;
2518 }
2519 
2520 #ifdef COMPILER2
2521 //------------------------------generate_uncommon_trap_blob--------------------
2522 void SharedRuntime::generate_uncommon_trap_blob() {
2523   // Allocate space for the code
2524   ResourceMark rm;
2525   // Setup code generation tools
2526   CodeBuffer buffer("uncommon_trap_blob", 2048, 1024);
2527   MacroAssembler* masm = new MacroAssembler(&buffer);
2528 
2529   assert(SimpleRuntimeFrame::framesize % 4 == 0, "sp not 16-byte aligned");
2530 
2531   address start = __ pc();
2532 
2533   // Push self-frame.  We get here with a return address in LR
2534   // and sp should be 16 byte aligned
2535   // push rfp and retaddr by hand
2536   __ stp(rfp, lr, Address(__ pre(sp, -2 * wordSize)));
2537   // we don't expect an arg reg save area
2538 #ifndef PRODUCT
2539   assert(frame::arg_reg_save_area_bytes == 0, "not expecting frame reg save area");
2540 #endif
2541   // compiler left unloaded_class_index in j_rarg0 move to where the
2542   // runtime expects it.
2543   if (c_rarg1 != j_rarg0) {
2544     __ movw(c_rarg1, j_rarg0);
2545   }
2546 
2547   // we need to set the past SP to the stack pointer of the stub frame
2548   // and the pc to the address where this runtime call will return
2549   // although actually any pc in this code blob will do).
2550   Label retaddr;
2551   __ set_last_Java_frame(sp, noreg, retaddr, rscratch1);
2552 
2553   // Call C code.  Need thread but NOT official VM entry
2554   // crud.  We cannot block on this call, no GC can happen.  Call should
2555   // capture callee-saved registers as well as return values.
2556   // Thread is in rdi already.
2557   //
2558   // UnrollBlock* uncommon_trap(JavaThread* thread, jint unloaded_class_index);
2559   //
2560   // n.b. 2 gp args, 0 fp args, integral return type
2561 
2562   __ mov(c_rarg0, rthread);
2563   __ movw(c_rarg2, (unsigned)Deoptimization::Unpack_uncommon_trap);
2564   __ lea(rscratch1,
2565          RuntimeAddress(CAST_FROM_FN_PTR(address,
2566                                          Deoptimization::uncommon_trap)));
2567   __ blr(rscratch1);
2568   __ bind(retaddr);
2569 
2570   // Set an oopmap for the call site
2571   OopMapSet* oop_maps = new OopMapSet();
2572   OopMap* map = new OopMap(SimpleRuntimeFrame::framesize, 0);
2573 
2574   // location of rfp is known implicitly by the frame sender code
2575 
2576   oop_maps->add_gc_map(__ pc() - start, map);
2577 
2578   __ reset_last_Java_frame(false);
2579 
2580   // move UnrollBlock* into r4
2581   __ mov(r4, r0);
2582 
2583 #ifdef ASSERT
2584   { Label L;
2585     __ ldrw(rscratch1, Address(r4, Deoptimization::UnrollBlock::unpack_kind_offset_in_bytes()));
2586     __ cmpw(rscratch1, (unsigned)Deoptimization::Unpack_uncommon_trap);
2587     __ br(Assembler::EQ, L);
2588     __ stop("SharedRuntime::generate_deopt_blob: last_Java_fp not cleared");
2589     __ bind(L);
2590   }
2591 #endif
2592 
2593   // Pop all the frames we must move/replace.
2594   //
2595   // Frame picture (youngest to oldest)
2596   // 1: self-frame (no frame link)
2597   // 2: deopting frame  (no frame link)
2598   // 3: caller of deopting frame (could be compiled/interpreted).
2599 
2600   // Pop self-frame.  We have no frame, and must rely only on r0 and sp.
2601   __ add(sp, sp, (SimpleRuntimeFrame::framesize) << LogBytesPerInt); // Epilog!
2602 
2603   // Pop deoptimized frame (int)
2604   __ ldrw(r2, Address(r4,
2605                       Deoptimization::UnrollBlock::
2606                       size_of_deoptimized_frame_offset_in_bytes()));
2607   __ sub(r2, r2, 2 * wordSize);
2608   __ add(sp, sp, r2);
2609   __ ldp(rfp, lr, __ post(sp, 2 * wordSize));
2610   // LR should now be the return address to the caller (3) frame
2611 
2612 #ifdef ASSERT
2613   // Compilers generate code that bang the stack by as much as the
2614   // interpreter would need. So this stack banging should never
2615   // trigger a fault. Verify that it does not on non product builds.
2616   if (UseStackBanging) {
2617     __ ldrw(r1, Address(r4,
2618                         Deoptimization::UnrollBlock::
2619                         total_frame_sizes_offset_in_bytes()));
2620     __ bang_stack_size(r1, r2);
2621   }
2622 #endif
2623 
2624   // Load address of array of frame pcs into r2 (address*)
2625   __ ldr(r2, Address(r4,
2626                      Deoptimization::UnrollBlock::frame_pcs_offset_in_bytes()));
2627 
2628   // Load address of array of frame sizes into r5 (intptr_t*)
2629   __ ldr(r5, Address(r4,
2630                      Deoptimization::UnrollBlock::
2631                      frame_sizes_offset_in_bytes()));
2632 
2633   // Counter
2634   __ ldrw(r3, Address(r4,
2635                       Deoptimization::UnrollBlock::
2636                       number_of_frames_offset_in_bytes())); // (int)
2637 
2638   // Now adjust the caller's stack to make up for the extra locals but
2639   // record the original sp so that we can save it in the skeletal
2640   // interpreter frame and the stack walking of interpreter_sender
2641   // will get the unextended sp value and not the "real" sp value.
2642 
2643   const Register sender_sp = r8;
2644 
2645   __ mov(sender_sp, sp);
2646   __ ldrw(r1, Address(r4,
2647                       Deoptimization::UnrollBlock::
2648                       caller_adjustment_offset_in_bytes())); // (int)
2649   __ sub(sp, sp, r1);
2650 
2651   // Push interpreter frames in a loop
2652   Label loop;
2653   __ bind(loop);
2654   __ ldr(r1, Address(r5, 0));       // Load frame size
2655   __ sub(r1, r1, 2 * wordSize);     // We'll push pc and rfp by hand
2656   __ ldr(lr, Address(r2, 0));       // Save return address
2657   __ enter();                       // and old rfp & set new rfp
2658   __ sub(sp, sp, r1);               // Prolog
2659   __ str(sender_sp, Address(rfp, frame::interpreter_frame_sender_sp_offset * wordSize)); // Make it walkable
2660   // This value is corrected by layout_activation_impl
2661   __ str(zr, Address(rfp, frame::interpreter_frame_last_sp_offset * wordSize));
2662   __ mov(sender_sp, sp);          // Pass sender_sp to next frame
2663   __ add(r5, r5, wordSize);       // Bump array pointer (sizes)
2664   __ add(r2, r2, wordSize);       // Bump array pointer (pcs)
2665   __ subsw(r3, r3, 1);            // Decrement counter
2666   __ br(Assembler::GT, loop);
2667   __ ldr(lr, Address(r2, 0));     // save final return address
2668   // Re-push self-frame
2669   __ enter();                     // & old rfp & set new rfp
2670 
2671   // Use rfp because the frames look interpreted now
2672   // Save "the_pc" since it cannot easily be retrieved using the last_java_SP after we aligned SP.
2673   // Don't need the precise return PC here, just precise enough to point into this code blob.
2674   address the_pc = __ pc();
2675   __ set_last_Java_frame(sp, rfp, the_pc, rscratch1);
2676 
2677   // Call C code.  Need thread but NOT official VM entry
2678   // crud.  We cannot block on this call, no GC can happen.  Call should
2679   // restore return values to their stack-slots with the new SP.
2680   // Thread is in rdi already.
2681   //
2682   // BasicType unpack_frames(JavaThread* thread, int exec_mode);
2683   //
2684   // n.b. 2 gp args, 0 fp args, integral return type
2685 
2686   // sp should already be aligned
2687   __ mov(c_rarg0, rthread);
2688   __ movw(c_rarg1, (unsigned)Deoptimization::Unpack_uncommon_trap);
2689   __ lea(rscratch1, RuntimeAddress(CAST_FROM_FN_PTR(address, Deoptimization::unpack_frames)));
2690   __ blr(rscratch1);
2691 
2692   // Set an oopmap for the call site
2693   // Use the same PC we used for the last java frame
2694   oop_maps->add_gc_map(the_pc - start, new OopMap(SimpleRuntimeFrame::framesize, 0));
2695 
2696   // Clear fp AND pc
2697   __ reset_last_Java_frame(true);
2698 
2699   // Pop self-frame.
2700   __ leave();                 // Epilog
2701 
2702   // Jump to interpreter
2703   __ ret(lr);
2704 
2705   // Make sure all code is generated
2706   masm->flush();
2707 
2708   _uncommon_trap_blob =  UncommonTrapBlob::create(&buffer, oop_maps,
2709                                                  SimpleRuntimeFrame::framesize >> 1);
2710 }
2711 #endif // COMPILER2
2712 
2713 
2714 //------------------------------generate_handler_blob------
2715 //
2716 // Generate a special Compile2Runtime blob that saves all registers,
2717 // and setup oopmap.
2718 //
2719 SafepointBlob* SharedRuntime::generate_handler_blob(address call_ptr, int poll_type) {
2720   ResourceMark rm;
2721   OopMapSet *oop_maps = new OopMapSet();
2722   OopMap* map;
2723 
2724   // Allocate space for the code.  Setup code generation tools.
2725   CodeBuffer buffer("handler_blob", 2048, 1024);
2726   MacroAssembler* masm = new MacroAssembler(&buffer);
2727 
2728   address start   = __ pc();
2729   address call_pc = NULL;
2730   int frame_size_in_words;
2731   bool cause_return = (poll_type == POLL_AT_RETURN);
2732   bool save_vectors = (poll_type == POLL_AT_VECTOR_LOOP);
2733 
2734   // Save Integer and Float registers.
2735   map = RegisterSaver::save_live_registers(masm, 0, &frame_size_in_words, save_vectors);
2736 
2737   // The following is basically a call_VM.  However, we need the precise
2738   // address of the call in order to generate an oopmap. Hence, we do all the
2739   // work outselves.
2740 
2741   Label retaddr;
2742   __ set_last_Java_frame(sp, noreg, retaddr, rscratch1);
2743 
2744   // The return address must always be correct so that frame constructor never
2745   // sees an invalid pc.
2746 
2747   if (!cause_return) {
2748     // overwrite the return address pushed by save_live_registers
2749     // Additionally, r20 is a callee-saved register so we can look at
2750     // it later to determine if someone changed the return address for
2751     // us!
2752     __ ldr(r20, Address(rthread, JavaThread::saved_exception_pc_offset()));
2753     __ str(r20, Address(rfp, wordSize));
2754   }
2755 
2756   // Do the call
2757   __ mov(c_rarg0, rthread);
2758   __ lea(rscratch1, RuntimeAddress(call_ptr));
2759   __ blr(rscratch1);
2760   __ bind(retaddr);
2761 
2762   // Set an oopmap for the call site.  This oopmap will map all
2763   // oop-registers and debug-info registers as callee-saved.  This
2764   // will allow deoptimization at this safepoint to find all possible
2765   // debug-info recordings, as well as let GC find all oops.
2766 
2767   oop_maps->add_gc_map( __ pc() - start, map);
2768 
2769   Label noException;
2770 
2771   __ reset_last_Java_frame(false);
2772 
2773   __ maybe_isb();
2774   __ membar(Assembler::LoadLoad | Assembler::LoadStore);
2775 
2776   __ ldr(rscratch1, Address(rthread, Thread::pending_exception_offset()));
2777   __ cbz(rscratch1, noException);
2778 
2779   // Exception pending
2780 
2781   RegisterSaver::restore_live_registers(masm, save_vectors);
2782 
2783   __ far_jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
2784 
2785   // No exception case
2786   __ bind(noException);
2787 
2788   Label no_adjust, bail;
2789   if (!cause_return) {
2790     // If our stashed return pc was modified by the runtime we avoid touching it
2791     __ ldr(rscratch1, Address(rfp, wordSize));
2792     __ cmp(r20, rscratch1);
2793     __ br(Assembler::NE, no_adjust);
2794 
2795 #ifdef ASSERT
2796     // Verify the correct encoding of the poll we're about to skip.
2797     // See NativeInstruction::is_ldrw_to_zr()
2798     __ ldrw(rscratch1, Address(r20));
2799     __ ubfx(rscratch2, rscratch1, 22, 10);
2800     __ cmpw(rscratch2, 0b1011100101);
2801     __ br(Assembler::NE, bail);
2802     __ ubfx(rscratch2, rscratch1, 0, 5);
2803     __ cmpw(rscratch2, 0b11111);
2804     __ br(Assembler::NE, bail);
2805 #endif
2806     // Adjust return pc forward to step over the safepoint poll instruction
2807     __ add(r20, r20, NativeInstruction::instruction_size);
2808     __ str(r20, Address(rfp, wordSize));
2809   }
2810 
2811   __ bind(no_adjust);
2812   // Normal exit, restore registers and exit.
2813   RegisterSaver::restore_live_registers(masm, save_vectors);
2814 
2815   __ ret(lr);
2816 
2817 #ifdef ASSERT
2818   __ bind(bail);
2819   __ stop("Attempting to adjust pc to skip safepoint poll but the return point is not what we expected");
2820 #endif
2821 
2822   // Make sure all code is generated
2823   masm->flush();
2824 
2825   // Fill-out other meta info
2826   return SafepointBlob::create(&buffer, oop_maps, frame_size_in_words);
2827 }
2828 
2829 //
2830 // generate_resolve_blob - call resolution (static/virtual/opt-virtual/ic-miss
2831 //
2832 // Generate a stub that calls into vm to find out the proper destination
2833 // of a java call. All the argument registers are live at this point
2834 // but since this is generic code we don't know what they are and the caller
2835 // must do any gc of the args.
2836 //
2837 RuntimeStub* SharedRuntime::generate_resolve_blob(address destination, const char* name) {
2838   assert (StubRoutines::forward_exception_entry() != NULL, "must be generated before");
2839 
2840   // allocate space for the code
2841   ResourceMark rm;
2842 
2843   CodeBuffer buffer(name, 1000, 512);
2844   MacroAssembler* masm                = new MacroAssembler(&buffer);
2845 
2846   int frame_size_in_words;
2847 
2848   OopMapSet *oop_maps = new OopMapSet();
2849   OopMap* map = NULL;
2850 
2851   int start = __ offset();
2852 
2853   map = RegisterSaver::save_live_registers(masm, 0, &frame_size_in_words);
2854 
2855   int frame_complete = __ offset();
2856 
2857   {
2858     Label retaddr;
2859     __ set_last_Java_frame(sp, noreg, retaddr, rscratch1);
2860 
2861     __ mov(c_rarg0, rthread);
2862     __ lea(rscratch1, RuntimeAddress(destination));
2863 
2864     __ blr(rscratch1);
2865     __ bind(retaddr);
2866   }
2867 
2868   // Set an oopmap for the call site.
2869   // We need this not only for callee-saved registers, but also for volatile
2870   // registers that the compiler might be keeping live across a safepoint.
2871 
2872   oop_maps->add_gc_map( __ offset() - start, map);
2873 
2874   __ maybe_isb();
2875 
2876   // r0 contains the address we are going to jump to assuming no exception got installed
2877 
2878   // clear last_Java_sp
2879   __ reset_last_Java_frame(false);
2880   // check for pending exceptions
2881   Label pending;
2882   __ ldr(rscratch1, Address(rthread, Thread::pending_exception_offset()));
2883   __ cbnz(rscratch1, pending);
2884 
2885   // get the returned Method*
2886   __ get_vm_result_2(rmethod, rthread);
2887   __ str(rmethod, Address(sp, RegisterSaver::reg_offset_in_bytes(rmethod)));
2888 
2889   // r0 is where we want to jump, overwrite rscratch1 which is saved and scratch
2890   __ str(r0, Address(sp, RegisterSaver::rscratch1_offset_in_bytes()));
2891   RegisterSaver::restore_live_registers(masm);
2892 
2893   // We are back the the original state on entry and ready to go.
2894 
2895   __ br(rscratch1);
2896 
2897   // Pending exception after the safepoint
2898 
2899   __ bind(pending);
2900 
2901   RegisterSaver::restore_live_registers(masm);
2902 
2903   // exception pending => remove activation and forward to exception handler
2904 
2905   __ str(zr, Address(rthread, JavaThread::vm_result_offset()));
2906 
2907   __ ldr(r0, Address(rthread, Thread::pending_exception_offset()));
2908   __ far_jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
2909 
2910   // -------------
2911   // make sure all code is generated
2912   masm->flush();
2913 
2914   // return the  blob
2915   // frame_size_words or bytes??
2916   return RuntimeStub::new_runtime_stub(name, &buffer, frame_complete, frame_size_in_words, oop_maps, true);
2917 }
2918 
2919 #ifdef COMPILER2
2920 // This is here instead of runtime_x86_64.cpp because it uses SimpleRuntimeFrame
2921 //
2922 //------------------------------generate_exception_blob---------------------------
2923 // creates exception blob at the end
2924 // Using exception blob, this code is jumped from a compiled method.
2925 // (see emit_exception_handler in x86_64.ad file)
2926 //
2927 // Given an exception pc at a call we call into the runtime for the
2928 // handler in this method. This handler might merely restore state
2929 // (i.e. callee save registers) unwind the frame and jump to the
2930 // exception handler for the nmethod if there is no Java level handler
2931 // for the nmethod.
2932 //
2933 // This code is entered with a jmp.
2934 //
2935 // Arguments:
2936 //   r0: exception oop
2937 //   r3: exception pc
2938 //
2939 // Results:
2940 //   r0: exception oop
2941 //   r3: exception pc in caller or ???
2942 //   destination: exception handler of caller
2943 //
2944 // Note: the exception pc MUST be at a call (precise debug information)
2945 //       Registers r0, r3, r2, r4, r5, r8-r11 are not callee saved.
2946 //
2947 
2948 void OptoRuntime::generate_exception_blob() {
2949   assert(!OptoRuntime::is_callee_saved_register(R3_num), "");
2950   assert(!OptoRuntime::is_callee_saved_register(R0_num), "");
2951   assert(!OptoRuntime::is_callee_saved_register(R2_num), "");
2952 
2953   assert(SimpleRuntimeFrame::framesize % 4 == 0, "sp not 16-byte aligned");
2954 
2955   // Allocate space for the code
2956   ResourceMark rm;
2957   // Setup code generation tools
2958   CodeBuffer buffer("exception_blob", 2048, 1024);
2959   MacroAssembler* masm = new MacroAssembler(&buffer);
2960 
2961   // TODO check various assumptions made here
2962   //
2963   // make sure we do so before running this
2964 
2965   address start = __ pc();
2966 
2967   // push rfp and retaddr by hand
2968   // Exception pc is 'return address' for stack walker
2969   __ stp(rfp, lr, Address(__ pre(sp, -2 * wordSize)));
2970   // there are no callee save registers and we don't expect an
2971   // arg reg save area
2972 #ifndef PRODUCT
2973   assert(frame::arg_reg_save_area_bytes == 0, "not expecting frame reg save area");
2974 #endif
2975   // Store exception in Thread object. We cannot pass any arguments to the
2976   // handle_exception call, since we do not want to make any assumption
2977   // about the size of the frame where the exception happened in.
2978   __ str(r0, Address(rthread, JavaThread::exception_oop_offset()));
2979   __ str(r3, Address(rthread, JavaThread::exception_pc_offset()));
2980 
2981   // This call does all the hard work.  It checks if an exception handler
2982   // exists in the method.
2983   // If so, it returns the handler address.
2984   // If not, it prepares for stack-unwinding, restoring the callee-save
2985   // registers of the frame being removed.
2986   //
2987   // address OptoRuntime::handle_exception_C(JavaThread* thread)
2988   //
2989   // n.b. 1 gp arg, 0 fp args, integral return type
2990 
2991   // the stack should always be aligned
2992   address the_pc = __ pc();
2993   __ set_last_Java_frame(sp, noreg, the_pc, rscratch1);
2994   __ mov(c_rarg0, rthread);
2995   __ lea(rscratch1, RuntimeAddress(CAST_FROM_FN_PTR(address, OptoRuntime::handle_exception_C)));
2996   __ blr(rscratch1);
2997   __ maybe_isb();
2998 
2999   // Set an oopmap for the call site.  This oopmap will only be used if we
3000   // are unwinding the stack.  Hence, all locations will be dead.
3001   // Callee-saved registers will be the same as the frame above (i.e.,
3002   // handle_exception_stub), since they were restored when we got the
3003   // exception.
3004 
3005   OopMapSet* oop_maps = new OopMapSet();
3006 
3007   oop_maps->add_gc_map(the_pc - start, new OopMap(SimpleRuntimeFrame::framesize, 0));
3008 
3009   __ reset_last_Java_frame(false);
3010 
3011   // Restore callee-saved registers
3012 
3013   // rfp is an implicitly saved callee saved register (i.e. the calling
3014   // convention will save restore it in prolog/epilog) Other than that
3015   // there are no callee save registers now that adapter frames are gone.
3016   // and we dont' expect an arg reg save area
3017   __ ldp(rfp, r3, Address(__ post(sp, 2 * wordSize)));
3018 
3019   // r0: exception handler
3020 
3021   // We have a handler in r0 (could be deopt blob).
3022   __ mov(r8, r0);
3023 
3024   // Get the exception oop
3025   __ ldr(r0, Address(rthread, JavaThread::exception_oop_offset()));
3026   // Get the exception pc in case we are deoptimized
3027   __ ldr(r4, Address(rthread, JavaThread::exception_pc_offset()));
3028 #ifdef ASSERT
3029   __ str(zr, Address(rthread, JavaThread::exception_handler_pc_offset()));
3030   __ str(zr, Address(rthread, JavaThread::exception_pc_offset()));
3031 #endif
3032   // Clear the exception oop so GC no longer processes it as a root.
3033   __ str(zr, Address(rthread, JavaThread::exception_oop_offset()));
3034 
3035   // r0: exception oop
3036   // r8:  exception handler
3037   // r4: exception pc
3038   // Jump to handler
3039 
3040   __ br(r8);
3041 
3042   // Make sure all code is generated
3043   masm->flush();
3044 
3045   // Set exception blob
3046   _exception_blob =  ExceptionBlob::create(&buffer, oop_maps, SimpleRuntimeFrame::framesize >> 1);
3047 }
3048 #endif // COMPILER2