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