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 = first_arg ; i < arg_count ; 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     if (UseBiasedLocking) {
1843       __ biased_locking_enter(lock_reg, obj_reg, swap_reg, tmp, false, lock_done, &slow_path_lock);
1844     }
1845 
1846     // Load (object->mark() | 1) into swap_reg %r0
1847     __ ldr(rscratch1, Address(obj_reg, oopDesc::mark_offset_in_bytes()));
1848     __ orr(swap_reg, rscratch1, 1);
1849 
1850     // Save (object->mark() | 1) into BasicLock's displaced header
1851     __ str(swap_reg, Address(lock_reg, mark_word_offset));
1852 
1853     // src -> dest iff dest == r0 else r0 <- dest
1854     { Label here;
1855       __ cmpxchg_obj_header(r0, lock_reg, obj_reg, rscratch1, lock_done, /*fallthrough*/NULL);
1856     }
1857 
1858     // Hmm should this move to the slow path code area???
1859 
1860     // Test if the oopMark is an obvious stack pointer, i.e.,
1861     //  1) (mark & 3) == 0, and
1862     //  2) sp <= mark < mark + os::pagesize()
1863     // These 3 tests can be done by evaluating the following
1864     // expression: ((mark - sp) & (3 - os::vm_page_size())),
1865     // assuming both stack pointer and pagesize have their
1866     // least significant 2 bits clear.
1867     // NOTE: the oopMark is in swap_reg %r0 as the result of cmpxchg
1868 
1869     __ sub(swap_reg, sp, swap_reg);
1870     __ neg(swap_reg, swap_reg);
1871     __ ands(swap_reg, swap_reg, 3 - os::vm_page_size());
1872 
1873     // Save the test result, for recursive case, the result is zero
1874     __ str(swap_reg, Address(lock_reg, mark_word_offset));
1875     __ br(Assembler::NE, slow_path_lock);
1876 
1877     // Slow path will re-enter here
1878 
1879     __ bind(lock_done);
1880   }
1881 
1882 
1883   // Finally just about ready to make the JNI call
1884 
1885   // get JNIEnv* which is first argument to native
1886   if (!is_critical_native) {
1887     __ lea(c_rarg0, Address(rthread, in_bytes(JavaThread::jni_environment_offset())));
1888   }
1889 
1890   // Now set thread in native
1891   __ mov(rscratch1, _thread_in_native);
1892   __ lea(rscratch2, Address(rthread, JavaThread::thread_state_offset()));
1893   __ stlrw(rscratch1, rscratch2);
1894 
1895   {
1896     int return_type = 0;
1897     switch (ret_type) {
1898     case T_VOID: break;
1899       return_type = 0; break;
1900     case T_CHAR:
1901     case T_BYTE:
1902     case T_SHORT:
1903     case T_INT:
1904     case T_BOOLEAN:
1905     case T_LONG:
1906       return_type = 1; break;
1907     case T_ARRAY:
1908     case T_OBJECT:
1909       return_type = 1; break;
1910     case T_FLOAT:
1911       return_type = 2; break;
1912     case T_DOUBLE:
1913       return_type = 3; break;
1914     default:
1915       ShouldNotReachHere();
1916     }
1917     rt_call(masm, native_func,
1918             int_args + 2, // AArch64 passes up to 8 args in int registers
1919             float_args,   // and up to 8 float args
1920             return_type);
1921   }
1922 
1923   // Unpack native results.
1924   switch (ret_type) {
1925   case T_BOOLEAN: __ ubfx(r0, r0, 0, 8);             break;
1926   case T_CHAR   : __ ubfx(r0, r0, 0, 16);            break;
1927   case T_BYTE   : __ sbfx(r0, r0, 0, 8);             break;
1928   case T_SHORT  : __ sbfx(r0, r0, 0, 16);            break;
1929   case T_INT    : __ sbfx(r0, r0, 0, 32);            break;
1930   case T_DOUBLE :
1931   case T_FLOAT  :
1932     // Result is in v0 we'll save as needed
1933     break;
1934   case T_ARRAY:                 // Really a handle
1935   case T_OBJECT:                // Really a handle
1936       break; // can't de-handlize until after safepoint check
1937   case T_VOID: break;
1938   case T_LONG: break;
1939   default       : ShouldNotReachHere();
1940   }
1941 
1942   // Switch thread to "native transition" state before reading the synchronization state.
1943   // This additional state is necessary because reading and testing the synchronization
1944   // state is not atomic w.r.t. GC, as this scenario demonstrates:
1945   //     Java thread A, in _thread_in_native state, loads _not_synchronized and is preempted.
1946   //     VM thread changes sync state to synchronizing and suspends threads for GC.
1947   //     Thread A is resumed to finish this native method, but doesn't block here since it
1948   //     didn't see any synchronization is progress, and escapes.
1949   __ mov(rscratch1, _thread_in_native_trans);
1950 
1951   if(os::is_MP()) {
1952     if (UseMembar) {
1953       __ strw(rscratch1, Address(rthread, JavaThread::thread_state_offset()));
1954 
1955       // Force this write out before the read below
1956       __ dmb(Assembler::ISH);
1957     } else {
1958       __ lea(rscratch2, Address(rthread, JavaThread::thread_state_offset()));
1959       __ stlrw(rscratch1, rscratch2);
1960 
1961       // Write serialization page so VM thread can do a pseudo remote membar.
1962       // We use the current thread pointer to calculate a thread specific
1963       // offset to write to within the page. This minimizes bus traffic
1964       // due to cache line collision.
1965       __ serialize_memory(rthread, r2);
1966     }
1967   } else {
1968     __ strw(rscratch1, Address(rthread, JavaThread::thread_state_offset()));
1969   }
1970 
1971   // check for safepoint operation in progress and/or pending suspend requests
1972   Label safepoint_in_progress, safepoint_in_progress_done;
1973   {
1974     __ safepoint_poll_acquire(safepoint_in_progress);
1975     __ ldrw(rscratch1, Address(rthread, JavaThread::suspend_flags_offset()));
1976     __ cbnzw(rscratch1, safepoint_in_progress);
1977     __ bind(safepoint_in_progress_done);
1978   }
1979 
1980   // change thread state
1981   Label after_transition;
1982   __ mov(rscratch1, _thread_in_Java);
1983   __ lea(rscratch2, Address(rthread, JavaThread::thread_state_offset()));
1984   __ stlrw(rscratch1, rscratch2);
1985   __ bind(after_transition);
1986 
1987   Label reguard;
1988   Label reguard_done;
1989   __ ldrb(rscratch1, Address(rthread, JavaThread::stack_guard_state_offset()));
1990   __ cmpw(rscratch1, JavaThread::stack_guard_yellow_reserved_disabled);
1991   __ br(Assembler::EQ, reguard);
1992   __ bind(reguard_done);
1993 
1994   // native result if any is live
1995 
1996   // Unlock
1997   Label unlock_done;
1998   Label slow_path_unlock;
1999   if (method->is_synchronized()) {
2000 
2001     // Get locked oop from the handle we passed to jni
2002     __ ldr(obj_reg, Address(oop_handle_reg, 0));
2003 
2004     Label done;
2005 
2006     if (UseBiasedLocking) {
2007       __ biased_locking_exit(obj_reg, old_hdr, done);
2008     }
2009 
2010     // Simple recursive lock?
2011 
2012     __ ldr(rscratch1, Address(sp, lock_slot_offset * VMRegImpl::stack_slot_size));
2013     __ cbz(rscratch1, done);
2014 
2015     // Must save r0 if if it is live now because cmpxchg must use it
2016     if (ret_type != T_FLOAT && ret_type != T_DOUBLE && ret_type != T_VOID) {
2017       save_native_result(masm, ret_type, stack_slots);
2018     }
2019 
2020 
2021     // get address of the stack lock
2022     __ lea(r0, Address(sp, lock_slot_offset * VMRegImpl::stack_slot_size));
2023     //  get old displaced header
2024     __ ldr(old_hdr, Address(r0, 0));
2025 
2026     // Atomic swap old header if oop still contains the stack lock
2027     Label succeed;
2028     __ cmpxchg_obj_header(r0, old_hdr, obj_reg, rscratch1, succeed, &slow_path_unlock);
2029     __ bind(succeed);
2030 
2031     // slow path re-enters here
2032     __ bind(unlock_done);
2033     if (ret_type != T_FLOAT && ret_type != T_DOUBLE && ret_type != T_VOID) {
2034       restore_native_result(masm, ret_type, stack_slots);
2035     }
2036 
2037     __ bind(done);
2038   }
2039 
2040   Label dtrace_method_exit, dtrace_method_exit_done;
2041   {
2042     unsigned long offset;
2043     __ adrp(rscratch1, ExternalAddress((address)&DTraceMethodProbes), offset);
2044     __ ldrb(rscratch1, Address(rscratch1, offset));
2045     __ cbnzw(rscratch1, dtrace_method_exit);
2046     __ bind(dtrace_method_exit_done);
2047   }
2048 
2049   __ reset_last_Java_frame(false);
2050 
2051   // Unbox oop result, e.g. JNIHandles::resolve result.
2052   if (ret_type == T_OBJECT || ret_type == T_ARRAY) {
2053     __ resolve_jobject(r0, rthread, rscratch2);
2054   }
2055 
2056   if (CheckJNICalls) {
2057     // clear_pending_jni_exception_check
2058     __ str(zr, Address(rthread, JavaThread::pending_jni_exception_check_fn_offset()));
2059   }
2060 
2061   if (!is_critical_native) {
2062     // reset handle block
2063     __ ldr(r2, Address(rthread, JavaThread::active_handles_offset()));
2064     __ str(zr, Address(r2, JNIHandleBlock::top_offset_in_bytes()));
2065   }
2066 
2067   __ leave();
2068 
2069   if (!is_critical_native) {
2070     // Any exception pending?
2071     __ ldr(rscratch1, Address(rthread, in_bytes(Thread::pending_exception_offset())));
2072     __ cbnz(rscratch1, exception_pending);
2073   }
2074 
2075   // record exit from native wrapper code
2076   if (NotifySimulator) {
2077     __ notify(Assembler::method_reentry);
2078   }
2079 
2080   // We're done
2081   __ ret(lr);
2082 
2083   // Unexpected paths are out of line and go here
2084 
2085   if (!is_critical_native) {
2086     // forward the exception
2087     __ bind(exception_pending);
2088 
2089     // and forward the exception
2090     __ far_jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
2091   }
2092 
2093   // Slow path locking & unlocking
2094   if (method->is_synchronized()) {
2095 
2096     __ block_comment("Slow path lock {");
2097     __ bind(slow_path_lock);
2098 
2099     // has last_Java_frame setup. No exceptions so do vanilla call not call_VM
2100     // args are (oop obj, BasicLock* lock, JavaThread* thread)
2101 
2102     // protect the args we've loaded
2103     save_args(masm, total_c_args, c_arg, out_regs);
2104 
2105     __ mov(c_rarg0, obj_reg);
2106     __ mov(c_rarg1, lock_reg);
2107     __ mov(c_rarg2, rthread);
2108 
2109     // Not a leaf but we have last_Java_frame setup as we want
2110     __ call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::complete_monitor_locking_C), 3);
2111     restore_args(masm, total_c_args, c_arg, out_regs);
2112 
2113 #ifdef ASSERT
2114     { Label L;
2115       __ ldr(rscratch1, Address(rthread, in_bytes(Thread::pending_exception_offset())));
2116       __ cbz(rscratch1, L);
2117       __ stop("no pending exception allowed on exit from monitorenter");
2118       __ bind(L);
2119     }
2120 #endif
2121     __ b(lock_done);
2122 
2123     __ block_comment("} Slow path lock");
2124 
2125     __ block_comment("Slow path unlock {");
2126     __ bind(slow_path_unlock);
2127 
2128     // If we haven't already saved the native result we must save it now as xmm registers
2129     // are still exposed.
2130 
2131     if (ret_type == T_FLOAT || ret_type == T_DOUBLE ) {
2132       save_native_result(masm, ret_type, stack_slots);
2133     }
2134 
2135     __ mov(c_rarg2, rthread);
2136     __ lea(c_rarg1, Address(sp, lock_slot_offset * VMRegImpl::stack_slot_size));
2137     __ mov(c_rarg0, obj_reg);
2138 
2139     // Save pending exception around call to VM (which contains an EXCEPTION_MARK)
2140     // NOTE that obj_reg == r19 currently
2141     __ ldr(r19, Address(rthread, in_bytes(Thread::pending_exception_offset())));
2142     __ str(zr, Address(rthread, in_bytes(Thread::pending_exception_offset())));
2143 
2144     rt_call(masm, CAST_FROM_FN_PTR(address, SharedRuntime::complete_monitor_unlocking_C), 3, 0, 1);
2145 
2146 #ifdef ASSERT
2147     {
2148       Label L;
2149       __ ldr(rscratch1, Address(rthread, in_bytes(Thread::pending_exception_offset())));
2150       __ cbz(rscratch1, L);
2151       __ stop("no pending exception allowed on exit complete_monitor_unlocking_C");
2152       __ bind(L);
2153     }
2154 #endif /* ASSERT */
2155 
2156     __ str(r19, Address(rthread, in_bytes(Thread::pending_exception_offset())));
2157 
2158     if (ret_type == T_FLOAT || ret_type == T_DOUBLE ) {
2159       restore_native_result(masm, ret_type, stack_slots);
2160     }
2161     __ b(unlock_done);
2162 
2163     __ block_comment("} Slow path unlock");
2164 
2165   } // synchronized
2166 
2167   // SLOW PATH Reguard the stack if needed
2168 
2169   __ bind(reguard);
2170   save_native_result(masm, ret_type, stack_slots);
2171   rt_call(masm, CAST_FROM_FN_PTR(address, SharedRuntime::reguard_yellow_pages), 0, 0, 0);
2172   restore_native_result(masm, ret_type, stack_slots);
2173   // and continue
2174   __ b(reguard_done);
2175 
2176   // SLOW PATH safepoint
2177   {
2178     __ block_comment("safepoint {");
2179     __ bind(safepoint_in_progress);
2180 
2181     // Don't use call_VM as it will see a possible pending exception and forward it
2182     // and never return here preventing us from clearing _last_native_pc down below.
2183     //
2184     save_native_result(masm, ret_type, stack_slots);
2185     __ mov(c_rarg0, rthread);
2186 #ifndef PRODUCT
2187   assert(frame::arg_reg_save_area_bytes == 0, "not expecting frame reg save area");
2188 #endif
2189     if (!is_critical_native) {
2190       __ lea(rscratch1, RuntimeAddress(CAST_FROM_FN_PTR(address, JavaThread::check_special_condition_for_native_trans)));
2191     } else {
2192       __ lea(rscratch1, RuntimeAddress(CAST_FROM_FN_PTR(address, JavaThread::check_special_condition_for_native_trans_and_transition)));
2193     }
2194     __ blrt(rscratch1, 1, 0, 1);
2195     __ maybe_isb();
2196     // Restore any method result value
2197     restore_native_result(masm, ret_type, stack_slots);
2198 
2199     if (is_critical_native) {
2200       // The call above performed the transition to thread_in_Java so
2201       // skip the transition logic above.
2202       __ b(after_transition);
2203     }
2204 
2205     __ b(safepoint_in_progress_done);
2206     __ block_comment("} safepoint");
2207   }
2208 
2209   // SLOW PATH dtrace support
2210   {
2211     __ block_comment("dtrace entry {");
2212     __ bind(dtrace_method_entry);
2213 
2214     // We have all of the arguments setup at this point. We must not touch any register
2215     // argument registers at this point (what if we save/restore them there are no oop?
2216 
2217     save_args(masm, total_c_args, c_arg, out_regs);
2218     __ mov_metadata(c_rarg1, method());
2219     __ call_VM_leaf(
2220       CAST_FROM_FN_PTR(address, SharedRuntime::dtrace_method_entry),
2221       rthread, c_rarg1);
2222     restore_args(masm, total_c_args, c_arg, out_regs);
2223     __ b(dtrace_method_entry_done);
2224     __ block_comment("} dtrace entry");
2225   }
2226 
2227   {
2228     __ block_comment("dtrace exit {");
2229     __ bind(dtrace_method_exit);
2230     save_native_result(masm, ret_type, stack_slots);
2231     __ mov_metadata(c_rarg1, method());
2232     __ call_VM_leaf(
2233          CAST_FROM_FN_PTR(address, SharedRuntime::dtrace_method_exit),
2234          rthread, c_rarg1);
2235     restore_native_result(masm, ret_type, stack_slots);
2236     __ b(dtrace_method_exit_done);
2237     __ block_comment("} dtrace exit");
2238   }
2239 
2240 
2241   __ flush();
2242 
2243   nmethod *nm = nmethod::new_native_nmethod(method,
2244                                             compile_id,
2245                                             masm->code(),
2246                                             vep_offset,
2247                                             frame_complete,
2248                                             stack_slots / VMRegImpl::slots_per_word,
2249                                             (is_static ? in_ByteSize(klass_offset) : in_ByteSize(receiver_offset)),
2250                                             in_ByteSize(lock_slot_offset*VMRegImpl::stack_slot_size),
2251                                             oop_maps);
2252 
2253   if (is_critical_native) {
2254     nm->set_lazy_critical_native(true);
2255   }
2256 
2257   return nm;
2258 
2259 }
2260 
2261 // this function returns the adjust size (in number of words) to a c2i adapter
2262 // activation for use during deoptimization
2263 int Deoptimization::last_frame_adjust(int callee_parameters, int callee_locals) {
2264   assert(callee_locals >= callee_parameters,
2265           "test and remove; got more parms than locals");
2266   if (callee_locals < callee_parameters)
2267     return 0;                   // No adjustment for negative locals
2268   int diff = (callee_locals - callee_parameters) * Interpreter::stackElementWords;
2269   // diff is counted in stack words
2270   return align_up(diff, 2);
2271 }
2272 
2273 
2274 //------------------------------generate_deopt_blob----------------------------
2275 void SharedRuntime::generate_deopt_blob() {
2276   // Allocate space for the code
2277   ResourceMark rm;
2278   // Setup code generation tools
2279   int pad = 0;
2280 #if INCLUDE_JVMCI
2281   if (EnableJVMCI || UseAOT) {
2282     pad += 512; // Increase the buffer size when compiling for JVMCI
2283   }
2284 #endif
2285   CodeBuffer buffer("deopt_blob", 2048+pad, 1024);
2286   MacroAssembler* masm = new MacroAssembler(&buffer);
2287   int frame_size_in_words;
2288   OopMap* map = NULL;
2289   OopMapSet *oop_maps = new OopMapSet();
2290 
2291 #ifdef BUILTIN_SIM
2292   AArch64Simulator *simulator;
2293   if (NotifySimulator) {
2294     simulator = AArch64Simulator::get_current(UseSimulatorCache, DisableBCCheck);
2295     simulator->notifyCompile(const_cast<char*>("SharedRuntime::deopt_blob"), __ pc());
2296   }
2297 #endif
2298 
2299   // -------------
2300   // This code enters when returning to a de-optimized nmethod.  A return
2301   // address has been pushed on the the stack, and return values are in
2302   // registers.
2303   // If we are doing a normal deopt then we were called from the patched
2304   // nmethod from the point we returned to the nmethod. So the return
2305   // address on the stack is wrong by NativeCall::instruction_size
2306   // We will adjust the value so it looks like we have the original return
2307   // address on the stack (like when we eagerly deoptimized).
2308   // In the case of an exception pending when deoptimizing, we enter
2309   // with a return address on the stack that points after the call we patched
2310   // into the exception handler. We have the following register state from,
2311   // e.g., the forward exception stub (see stubGenerator_x86_64.cpp).
2312   //    r0: exception oop
2313   //    r19: exception handler
2314   //    r3: throwing pc
2315   // So in this case we simply jam r3 into the useless return address and
2316   // the stack looks just like we want.
2317   //
2318   // At this point we need to de-opt.  We save the argument return
2319   // registers.  We call the first C routine, fetch_unroll_info().  This
2320   // routine captures the return values and returns a structure which
2321   // describes the current frame size and the sizes of all replacement frames.
2322   // The current frame is compiled code and may contain many inlined
2323   // functions, each with their own JVM state.  We pop the current frame, then
2324   // push all the new frames.  Then we call the C routine unpack_frames() to
2325   // populate these frames.  Finally unpack_frames() returns us the new target
2326   // address.  Notice that callee-save registers are BLOWN here; they have
2327   // already been captured in the vframeArray at the time the return PC was
2328   // patched.
2329   address start = __ pc();
2330   Label cont;
2331 
2332   // Prolog for non exception case!
2333 
2334   // Save everything in sight.
2335   map = RegisterSaver::save_live_registers(masm, 0, &frame_size_in_words);
2336 
2337   // Normal deoptimization.  Save exec mode for unpack_frames.
2338   __ movw(rcpool, Deoptimization::Unpack_deopt); // callee-saved
2339   __ b(cont);
2340 
2341   int reexecute_offset = __ pc() - start;
2342 #if INCLUDE_JVMCI && !defined(COMPILER1)
2343   if (EnableJVMCI && UseJVMCICompiler) {
2344     // JVMCI does not use this kind of deoptimization
2345     __ should_not_reach_here();
2346   }
2347 #endif
2348 
2349   // Reexecute case
2350   // return address is the pc describes what bci to do re-execute at
2351 
2352   // No need to update map as each call to save_live_registers will produce identical oopmap
2353   (void) RegisterSaver::save_live_registers(masm, 0, &frame_size_in_words);
2354 
2355   __ movw(rcpool, Deoptimization::Unpack_reexecute); // callee-saved
2356   __ b(cont);
2357 
2358 #if INCLUDE_JVMCI
2359   Label after_fetch_unroll_info_call;
2360   int implicit_exception_uncommon_trap_offset = 0;
2361   int uncommon_trap_offset = 0;
2362 
2363   if (EnableJVMCI || UseAOT) {
2364     implicit_exception_uncommon_trap_offset = __ pc() - start;
2365 
2366     __ ldr(lr, Address(rthread, in_bytes(JavaThread::jvmci_implicit_exception_pc_offset())));
2367     __ str(zr, Address(rthread, in_bytes(JavaThread::jvmci_implicit_exception_pc_offset())));
2368 
2369     uncommon_trap_offset = __ pc() - start;
2370 
2371     // Save everything in sight.
2372     RegisterSaver::save_live_registers(masm, 0, &frame_size_in_words);
2373     // fetch_unroll_info needs to call last_java_frame()
2374     Label retaddr;
2375     __ set_last_Java_frame(sp, noreg, retaddr, rscratch1);
2376 
2377     __ ldrw(c_rarg1, Address(rthread, in_bytes(JavaThread::pending_deoptimization_offset())));
2378     __ movw(rscratch1, -1);
2379     __ strw(rscratch1, Address(rthread, in_bytes(JavaThread::pending_deoptimization_offset())));
2380 
2381     __ movw(rcpool, (int32_t)Deoptimization::Unpack_reexecute);
2382     __ mov(c_rarg0, rthread);
2383     __ movw(c_rarg2, rcpool); // exec mode
2384     __ lea(rscratch1,
2385            RuntimeAddress(CAST_FROM_FN_PTR(address,
2386                                            Deoptimization::uncommon_trap)));
2387     __ blrt(rscratch1, 2, 0, MacroAssembler::ret_type_integral);
2388     __ bind(retaddr);
2389     oop_maps->add_gc_map( __ pc()-start, map->deep_copy());
2390 
2391     __ reset_last_Java_frame(false);
2392 
2393     __ b(after_fetch_unroll_info_call);
2394   } // EnableJVMCI
2395 #endif // INCLUDE_JVMCI
2396 
2397   int exception_offset = __ pc() - start;
2398 
2399   // Prolog for exception case
2400 
2401   // all registers are dead at this entry point, except for r0, and
2402   // r3 which contain the exception oop and exception pc
2403   // respectively.  Set them in TLS and fall thru to the
2404   // unpack_with_exception_in_tls entry point.
2405 
2406   __ str(r3, Address(rthread, JavaThread::exception_pc_offset()));
2407   __ str(r0, Address(rthread, JavaThread::exception_oop_offset()));
2408 
2409   int exception_in_tls_offset = __ pc() - start;
2410 
2411   // new implementation because exception oop is now passed in JavaThread
2412 
2413   // Prolog for exception case
2414   // All registers must be preserved because they might be used by LinearScan
2415   // Exceptiop oop and throwing PC are passed in JavaThread
2416   // tos: stack at point of call to method that threw the exception (i.e. only
2417   // args are on the stack, no return address)
2418 
2419   // The return address pushed by save_live_registers will be patched
2420   // later with the throwing pc. The correct value is not available
2421   // now because loading it from memory would destroy registers.
2422 
2423   // NB: The SP at this point must be the SP of the method that is
2424   // being deoptimized.  Deoptimization assumes that the frame created
2425   // here by save_live_registers is immediately below the method's SP.
2426   // This is a somewhat fragile mechanism.
2427 
2428   // Save everything in sight.
2429   map = RegisterSaver::save_live_registers(masm, 0, &frame_size_in_words);
2430 
2431   // Now it is safe to overwrite any register
2432 
2433   // Deopt during an exception.  Save exec mode for unpack_frames.
2434   __ mov(rcpool, Deoptimization::Unpack_exception); // callee-saved
2435 
2436   // load throwing pc from JavaThread and patch it as the return address
2437   // of the current frame. Then clear the field in JavaThread
2438 
2439   __ ldr(r3, Address(rthread, JavaThread::exception_pc_offset()));
2440   __ str(r3, Address(rfp, wordSize));
2441   __ str(zr, Address(rthread, JavaThread::exception_pc_offset()));
2442 
2443 #ifdef ASSERT
2444   // verify that there is really an exception oop in JavaThread
2445   __ ldr(r0, Address(rthread, JavaThread::exception_oop_offset()));
2446   __ verify_oop(r0);
2447 
2448   // verify that there is no pending exception
2449   Label no_pending_exception;
2450   __ ldr(rscratch1, Address(rthread, Thread::pending_exception_offset()));
2451   __ cbz(rscratch1, no_pending_exception);
2452   __ stop("must not have pending exception here");
2453   __ bind(no_pending_exception);
2454 #endif
2455 
2456   __ bind(cont);
2457 
2458   // Call C code.  Need thread and this frame, but NOT official VM entry
2459   // crud.  We cannot block on this call, no GC can happen.
2460   //
2461   // UnrollBlock* fetch_unroll_info(JavaThread* thread)
2462 
2463   // fetch_unroll_info needs to call last_java_frame().
2464 
2465   Label retaddr;
2466   __ set_last_Java_frame(sp, noreg, retaddr, rscratch1);
2467 #ifdef ASSERT0
2468   { Label L;
2469     __ ldr(rscratch1, Address(rthread,
2470                               JavaThread::last_Java_fp_offset()));
2471     __ cbz(rscratch1, L);
2472     __ stop("SharedRuntime::generate_deopt_blob: last_Java_fp not cleared");
2473     __ bind(L);
2474   }
2475 #endif // ASSERT
2476   __ mov(c_rarg0, rthread);
2477   __ mov(c_rarg1, rcpool);
2478   __ lea(rscratch1, RuntimeAddress(CAST_FROM_FN_PTR(address, Deoptimization::fetch_unroll_info)));
2479   __ blrt(rscratch1, 1, 0, 1);
2480   __ bind(retaddr);
2481 
2482   // Need to have an oopmap that tells fetch_unroll_info where to
2483   // find any register it might need.
2484   oop_maps->add_gc_map(__ pc() - start, map);
2485 
2486   __ reset_last_Java_frame(false);
2487 
2488 #if INCLUDE_JVMCI
2489   if (EnableJVMCI || UseAOT) {
2490     __ bind(after_fetch_unroll_info_call);
2491   }
2492 #endif
2493 
2494   // Load UnrollBlock* into r5
2495   __ mov(r5, r0);
2496 
2497   __ ldrw(rcpool, Address(r5, Deoptimization::UnrollBlock::unpack_kind_offset_in_bytes()));
2498    Label noException;
2499   __ cmpw(rcpool, Deoptimization::Unpack_exception);   // Was exception pending?
2500   __ br(Assembler::NE, noException);
2501   __ ldr(r0, Address(rthread, JavaThread::exception_oop_offset()));
2502   // QQQ this is useless it was NULL above
2503   __ ldr(r3, Address(rthread, JavaThread::exception_pc_offset()));
2504   __ str(zr, Address(rthread, JavaThread::exception_oop_offset()));
2505   __ str(zr, Address(rthread, JavaThread::exception_pc_offset()));
2506 
2507   __ verify_oop(r0);
2508 
2509   // Overwrite the result registers with the exception results.
2510   __ str(r0, Address(sp, RegisterSaver::r0_offset_in_bytes()));
2511   // I think this is useless
2512   // __ str(r3, Address(sp, RegisterSaver::r3_offset_in_bytes()));
2513 
2514   __ bind(noException);
2515 
2516   // Only register save data is on the stack.
2517   // Now restore the result registers.  Everything else is either dead
2518   // or captured in the vframeArray.
2519   RegisterSaver::restore_result_registers(masm);
2520 
2521   // All of the register save area has been popped of the stack. Only the
2522   // return address remains.
2523 
2524   // Pop all the frames we must move/replace.
2525   //
2526   // Frame picture (youngest to oldest)
2527   // 1: self-frame (no frame link)
2528   // 2: deopting frame  (no frame link)
2529   // 3: caller of deopting frame (could be compiled/interpreted).
2530   //
2531   // Note: by leaving the return address of self-frame on the stack
2532   // and using the size of frame 2 to adjust the stack
2533   // when we are done the return to frame 3 will still be on the stack.
2534 
2535   // Pop deoptimized frame
2536   __ ldrw(r2, Address(r5, Deoptimization::UnrollBlock::size_of_deoptimized_frame_offset_in_bytes()));
2537   __ sub(r2, r2, 2 * wordSize);
2538   __ add(sp, sp, r2);
2539   __ ldp(rfp, lr, __ post(sp, 2 * wordSize));
2540   // LR should now be the return address to the caller (3)
2541 
2542 #ifdef ASSERT
2543   // Compilers generate code that bang the stack by as much as the
2544   // interpreter would need. So this stack banging should never
2545   // trigger a fault. Verify that it does not on non product builds.
2546   if (UseStackBanging) {
2547     __ ldrw(r19, Address(r5, Deoptimization::UnrollBlock::total_frame_sizes_offset_in_bytes()));
2548     __ bang_stack_size(r19, r2);
2549   }
2550 #endif
2551   // Load address of array of frame pcs into r2
2552   __ ldr(r2, Address(r5, Deoptimization::UnrollBlock::frame_pcs_offset_in_bytes()));
2553 
2554   // Trash the old pc
2555   // __ addptr(sp, wordSize);  FIXME ????
2556 
2557   // Load address of array of frame sizes into r4
2558   __ ldr(r4, Address(r5, Deoptimization::UnrollBlock::frame_sizes_offset_in_bytes()));
2559 
2560   // Load counter into r3
2561   __ ldrw(r3, Address(r5, Deoptimization::UnrollBlock::number_of_frames_offset_in_bytes()));
2562 
2563   // Now adjust the caller's stack to make up for the extra locals
2564   // but record the original sp so that we can save it in the skeletal interpreter
2565   // frame and the stack walking of interpreter_sender will get the unextended sp
2566   // value and not the "real" sp value.
2567 
2568   const Register sender_sp = r6;
2569 
2570   __ mov(sender_sp, sp);
2571   __ ldrw(r19, Address(r5,
2572                        Deoptimization::UnrollBlock::
2573                        caller_adjustment_offset_in_bytes()));
2574   __ sub(sp, sp, r19);
2575 
2576   // Push interpreter frames in a loop
2577   __ mov(rscratch1, (address)0xDEADDEAD);        // Make a recognizable pattern
2578   __ mov(rscratch2, rscratch1);
2579   Label loop;
2580   __ bind(loop);
2581   __ ldr(r19, Address(__ post(r4, wordSize)));          // Load frame size
2582   __ sub(r19, r19, 2*wordSize);           // We'll push pc and fp by hand
2583   __ ldr(lr, Address(__ post(r2, wordSize)));  // Load pc
2584   __ enter();                           // Save old & set new fp
2585   __ sub(sp, sp, r19);                  // Prolog
2586   // This value is corrected by layout_activation_impl
2587   __ str(zr, Address(rfp, frame::interpreter_frame_last_sp_offset * wordSize));
2588   __ str(sender_sp, Address(rfp, frame::interpreter_frame_sender_sp_offset * wordSize)); // Make it walkable
2589   __ mov(sender_sp, sp);               // Pass sender_sp to next frame
2590   __ sub(r3, r3, 1);                   // Decrement counter
2591   __ cbnz(r3, loop);
2592 
2593     // Re-push self-frame
2594   __ ldr(lr, Address(r2));
2595   __ enter();
2596 
2597   // Allocate a full sized register save area.  We subtract 2 because
2598   // enter() just pushed 2 words
2599   __ sub(sp, sp, (frame_size_in_words - 2) * wordSize);
2600 
2601   // Restore frame locals after moving the frame
2602   __ strd(v0, Address(sp, RegisterSaver::v0_offset_in_bytes()));
2603   __ str(r0, Address(sp, RegisterSaver::r0_offset_in_bytes()));
2604 
2605   // Call C code.  Need thread but NOT official VM entry
2606   // crud.  We cannot block on this call, no GC can happen.  Call should
2607   // restore return values to their stack-slots with the new SP.
2608   //
2609   // void Deoptimization::unpack_frames(JavaThread* thread, int exec_mode)
2610 
2611   // Use rfp because the frames look interpreted now
2612   // Don't need the precise return PC here, just precise enough to point into this code blob.
2613   address the_pc = __ pc();
2614   __ set_last_Java_frame(sp, rfp, the_pc, rscratch1);
2615 
2616   __ mov(c_rarg0, rthread);
2617   __ movw(c_rarg1, rcpool); // second arg: exec_mode
2618   __ lea(rscratch1, RuntimeAddress(CAST_FROM_FN_PTR(address, Deoptimization::unpack_frames)));
2619   __ blrt(rscratch1, 2, 0, 0);
2620 
2621   // Set an oopmap for the call site
2622   // Use the same PC we used for the last java frame
2623   oop_maps->add_gc_map(the_pc - start,
2624                        new OopMap( frame_size_in_words, 0 ));
2625 
2626   // Clear fp AND pc
2627   __ reset_last_Java_frame(true);
2628 
2629   // Collect return values
2630   __ ldrd(v0, Address(sp, RegisterSaver::v0_offset_in_bytes()));
2631   __ ldr(r0, Address(sp, RegisterSaver::r0_offset_in_bytes()));
2632   // I think this is useless (throwing pc?)
2633   // __ ldr(r3, Address(sp, RegisterSaver::r3_offset_in_bytes()));
2634 
2635   // Pop self-frame.
2636   __ leave();                           // Epilog
2637 
2638   // Jump to interpreter
2639   __ ret(lr);
2640 
2641   // Make sure all code is generated
2642   masm->flush();
2643 
2644   _deopt_blob = DeoptimizationBlob::create(&buffer, oop_maps, 0, exception_offset, reexecute_offset, frame_size_in_words);
2645   _deopt_blob->set_unpack_with_exception_in_tls_offset(exception_in_tls_offset);
2646 #if INCLUDE_JVMCI
2647   if (EnableJVMCI || UseAOT) {
2648     _deopt_blob->set_uncommon_trap_offset(uncommon_trap_offset);
2649     _deopt_blob->set_implicit_exception_uncommon_trap_offset(implicit_exception_uncommon_trap_offset);
2650   }
2651 #endif
2652 #ifdef BUILTIN_SIM
2653   if (NotifySimulator) {
2654     unsigned char *base = _deopt_blob->code_begin();
2655     simulator->notifyRelocate(start, base - start);
2656   }
2657 #endif
2658 }
2659 
2660 uint SharedRuntime::out_preserve_stack_slots() {
2661   return 0;
2662 }
2663 
2664 #if COMPILER2_OR_JVMCI
2665 //------------------------------generate_uncommon_trap_blob--------------------
2666 void SharedRuntime::generate_uncommon_trap_blob() {
2667   // Allocate space for the code
2668   ResourceMark rm;
2669   // Setup code generation tools
2670   CodeBuffer buffer("uncommon_trap_blob", 2048, 1024);
2671   MacroAssembler* masm = new MacroAssembler(&buffer);
2672 
2673 #ifdef BUILTIN_SIM
2674   AArch64Simulator *simulator;
2675   if (NotifySimulator) {
2676     simulator = AArch64Simulator::get_current(UseSimulatorCache, DisableBCCheck);
2677     simulator->notifyCompile(const_cast<char*>("SharedRuntime:uncommon_trap_blob"), __ pc());
2678   }
2679 #endif
2680 
2681   assert(SimpleRuntimeFrame::framesize % 4 == 0, "sp not 16-byte aligned");
2682 
2683   address start = __ pc();
2684 
2685   // Push self-frame.  We get here with a return address in LR
2686   // and sp should be 16 byte aligned
2687   // push rfp and retaddr by hand
2688   __ stp(rfp, lr, Address(__ pre(sp, -2 * wordSize)));
2689   // we don't expect an arg reg save area
2690 #ifndef PRODUCT
2691   assert(frame::arg_reg_save_area_bytes == 0, "not expecting frame reg save area");
2692 #endif
2693   // compiler left unloaded_class_index in j_rarg0 move to where the
2694   // runtime expects it.
2695   if (c_rarg1 != j_rarg0) {
2696     __ movw(c_rarg1, j_rarg0);
2697   }
2698 
2699   // we need to set the past SP to the stack pointer of the stub frame
2700   // and the pc to the address where this runtime call will return
2701   // although actually any pc in this code blob will do).
2702   Label retaddr;
2703   __ set_last_Java_frame(sp, noreg, retaddr, rscratch1);
2704 
2705   // Call C code.  Need thread but NOT official VM entry
2706   // crud.  We cannot block on this call, no GC can happen.  Call should
2707   // capture callee-saved registers as well as return values.
2708   // Thread is in rdi already.
2709   //
2710   // UnrollBlock* uncommon_trap(JavaThread* thread, jint unloaded_class_index);
2711   //
2712   // n.b. 2 gp args, 0 fp args, integral return type
2713 
2714   __ mov(c_rarg0, rthread);
2715   __ movw(c_rarg2, (unsigned)Deoptimization::Unpack_uncommon_trap);
2716   __ lea(rscratch1,
2717          RuntimeAddress(CAST_FROM_FN_PTR(address,
2718                                          Deoptimization::uncommon_trap)));
2719   __ blrt(rscratch1, 2, 0, MacroAssembler::ret_type_integral);
2720   __ bind(retaddr);
2721 
2722   // Set an oopmap for the call site
2723   OopMapSet* oop_maps = new OopMapSet();
2724   OopMap* map = new OopMap(SimpleRuntimeFrame::framesize, 0);
2725 
2726   // location of rfp is known implicitly by the frame sender code
2727 
2728   oop_maps->add_gc_map(__ pc() - start, map);
2729 
2730   __ reset_last_Java_frame(false);
2731 
2732   // move UnrollBlock* into r4
2733   __ mov(r4, r0);
2734 
2735 #ifdef ASSERT
2736   { Label L;
2737     __ ldrw(rscratch1, Address(r4, Deoptimization::UnrollBlock::unpack_kind_offset_in_bytes()));
2738     __ cmpw(rscratch1, (unsigned)Deoptimization::Unpack_uncommon_trap);
2739     __ br(Assembler::EQ, L);
2740     __ stop("SharedRuntime::generate_deopt_blob: last_Java_fp not cleared");
2741     __ bind(L);
2742   }
2743 #endif
2744 
2745   // Pop all the frames we must move/replace.
2746   //
2747   // Frame picture (youngest to oldest)
2748   // 1: self-frame (no frame link)
2749   // 2: deopting frame  (no frame link)
2750   // 3: caller of deopting frame (could be compiled/interpreted).
2751 
2752   // Pop self-frame.  We have no frame, and must rely only on r0 and sp.
2753   __ add(sp, sp, (SimpleRuntimeFrame::framesize) << LogBytesPerInt); // Epilog!
2754 
2755   // Pop deoptimized frame (int)
2756   __ ldrw(r2, Address(r4,
2757                       Deoptimization::UnrollBlock::
2758                       size_of_deoptimized_frame_offset_in_bytes()));
2759   __ sub(r2, r2, 2 * wordSize);
2760   __ add(sp, sp, r2);
2761   __ ldp(rfp, lr, __ post(sp, 2 * wordSize));
2762   // LR should now be the return address to the caller (3) frame
2763 
2764 #ifdef ASSERT
2765   // Compilers generate code that bang the stack by as much as the
2766   // interpreter would need. So this stack banging should never
2767   // trigger a fault. Verify that it does not on non product builds.
2768   if (UseStackBanging) {
2769     __ ldrw(r1, Address(r4,
2770                         Deoptimization::UnrollBlock::
2771                         total_frame_sizes_offset_in_bytes()));
2772     __ bang_stack_size(r1, r2);
2773   }
2774 #endif
2775 
2776   // Load address of array of frame pcs into r2 (address*)
2777   __ ldr(r2, Address(r4,
2778                      Deoptimization::UnrollBlock::frame_pcs_offset_in_bytes()));
2779 
2780   // Load address of array of frame sizes into r5 (intptr_t*)
2781   __ ldr(r5, Address(r4,
2782                      Deoptimization::UnrollBlock::
2783                      frame_sizes_offset_in_bytes()));
2784 
2785   // Counter
2786   __ ldrw(r3, Address(r4,
2787                       Deoptimization::UnrollBlock::
2788                       number_of_frames_offset_in_bytes())); // (int)
2789 
2790   // Now adjust the caller's stack to make up for the extra locals but
2791   // record the original sp so that we can save it in the skeletal
2792   // interpreter frame and the stack walking of interpreter_sender
2793   // will get the unextended sp value and not the "real" sp value.
2794 
2795   const Register sender_sp = r8;
2796 
2797   __ mov(sender_sp, sp);
2798   __ ldrw(r1, Address(r4,
2799                       Deoptimization::UnrollBlock::
2800                       caller_adjustment_offset_in_bytes())); // (int)
2801   __ sub(sp, sp, r1);
2802 
2803   // Push interpreter frames in a loop
2804   Label loop;
2805   __ bind(loop);
2806   __ ldr(r1, Address(r5, 0));       // Load frame size
2807   __ sub(r1, r1, 2 * wordSize);     // We'll push pc and rfp by hand
2808   __ ldr(lr, Address(r2, 0));       // Save return address
2809   __ enter();                       // and old rfp & set new rfp
2810   __ sub(sp, sp, r1);               // Prolog
2811   __ str(sender_sp, Address(rfp, frame::interpreter_frame_sender_sp_offset * wordSize)); // Make it walkable
2812   // This value is corrected by layout_activation_impl
2813   __ str(zr, Address(rfp, frame::interpreter_frame_last_sp_offset * wordSize));
2814   __ mov(sender_sp, sp);          // Pass sender_sp to next frame
2815   __ add(r5, r5, wordSize);       // Bump array pointer (sizes)
2816   __ add(r2, r2, wordSize);       // Bump array pointer (pcs)
2817   __ subsw(r3, r3, 1);            // Decrement counter
2818   __ br(Assembler::GT, loop);
2819   __ ldr(lr, Address(r2, 0));     // save final return address
2820   // Re-push self-frame
2821   __ enter();                     // & old rfp & set new rfp
2822 
2823   // Use rfp because the frames look interpreted now
2824   // Save "the_pc" since it cannot easily be retrieved using the last_java_SP after we aligned SP.
2825   // Don't need the precise return PC here, just precise enough to point into this code blob.
2826   address the_pc = __ pc();
2827   __ set_last_Java_frame(sp, rfp, the_pc, rscratch1);
2828 
2829   // Call C code.  Need thread but NOT official VM entry
2830   // crud.  We cannot block on this call, no GC can happen.  Call should
2831   // restore return values to their stack-slots with the new SP.
2832   // Thread is in rdi already.
2833   //
2834   // BasicType unpack_frames(JavaThread* thread, int exec_mode);
2835   //
2836   // n.b. 2 gp args, 0 fp args, integral return type
2837 
2838   // sp should already be aligned
2839   __ mov(c_rarg0, rthread);
2840   __ movw(c_rarg1, (unsigned)Deoptimization::Unpack_uncommon_trap);
2841   __ lea(rscratch1, RuntimeAddress(CAST_FROM_FN_PTR(address, Deoptimization::unpack_frames)));
2842   __ blrt(rscratch1, 2, 0, MacroAssembler::ret_type_integral);
2843 
2844   // Set an oopmap for the call site
2845   // Use the same PC we used for the last java frame
2846   oop_maps->add_gc_map(the_pc - start, new OopMap(SimpleRuntimeFrame::framesize, 0));
2847 
2848   // Clear fp AND pc
2849   __ reset_last_Java_frame(true);
2850 
2851   // Pop self-frame.
2852   __ leave();                 // Epilog
2853 
2854   // Jump to interpreter
2855   __ ret(lr);
2856 
2857   // Make sure all code is generated
2858   masm->flush();
2859 
2860   _uncommon_trap_blob =  UncommonTrapBlob::create(&buffer, oop_maps,
2861                                                  SimpleRuntimeFrame::framesize >> 1);
2862 
2863 #ifdef BUILTIN_SIM
2864   if (NotifySimulator) {
2865     unsigned char *base = _deopt_blob->code_begin();
2866     simulator->notifyRelocate(start, base - start);
2867   }
2868 #endif
2869 }
2870 #endif // COMPILER2_OR_JVMCI
2871 
2872 
2873 //------------------------------generate_handler_blob------
2874 //
2875 // Generate a special Compile2Runtime blob that saves all registers,
2876 // and setup oopmap.
2877 //
2878 SafepointBlob* SharedRuntime::generate_handler_blob(address call_ptr, int poll_type) {
2879   ResourceMark rm;
2880   OopMapSet *oop_maps = new OopMapSet();
2881   OopMap* map;
2882 
2883   // Allocate space for the code.  Setup code generation tools.
2884   CodeBuffer buffer("handler_blob", 2048, 1024);
2885   MacroAssembler* masm = new MacroAssembler(&buffer);
2886 
2887   address start   = __ pc();
2888   address call_pc = NULL;
2889   int frame_size_in_words;
2890   bool cause_return = (poll_type == POLL_AT_RETURN);
2891   bool save_vectors = (poll_type == POLL_AT_VECTOR_LOOP);
2892 
2893   // Save registers, fpu state, and flags
2894   map = RegisterSaver::save_live_registers(masm, 0, &frame_size_in_words, save_vectors);
2895 
2896   // The following is basically a call_VM.  However, we need the precise
2897   // address of the call in order to generate an oopmap. Hence, we do all the
2898   // work outselves.
2899 
2900   Label retaddr;
2901   __ set_last_Java_frame(sp, noreg, retaddr, rscratch1);
2902 
2903   // The return address must always be correct so that frame constructor never
2904   // sees an invalid pc.
2905 
2906   if (!cause_return) {
2907     // overwrite the return address pushed by save_live_registers
2908     // Additionally, r20 is a callee-saved register so we can look at
2909     // it later to determine if someone changed the return address for
2910     // us!
2911     __ ldr(r20, Address(rthread, JavaThread::saved_exception_pc_offset()));
2912     __ str(r20, Address(rfp, wordSize));
2913   }
2914 
2915   // Do the call
2916   __ mov(c_rarg0, rthread);
2917   __ lea(rscratch1, RuntimeAddress(call_ptr));
2918   __ blrt(rscratch1, 1, 0, 1);
2919   __ bind(retaddr);
2920 
2921   // Set an oopmap for the call site.  This oopmap will map all
2922   // oop-registers and debug-info registers as callee-saved.  This
2923   // will allow deoptimization at this safepoint to find all possible
2924   // debug-info recordings, as well as let GC find all oops.
2925 
2926   oop_maps->add_gc_map( __ pc() - start, map);
2927 
2928   Label noException;
2929 
2930   __ reset_last_Java_frame(false);
2931 
2932   __ maybe_isb();
2933   __ membar(Assembler::LoadLoad | Assembler::LoadStore);
2934 
2935   __ ldr(rscratch1, Address(rthread, Thread::pending_exception_offset()));
2936   __ cbz(rscratch1, noException);
2937 
2938   // Exception pending
2939 
2940   RegisterSaver::restore_live_registers(masm, save_vectors);
2941 
2942   __ far_jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
2943 
2944   // No exception case
2945   __ bind(noException);
2946 
2947   Label no_adjust, bail;
2948   if (SafepointMechanism::uses_thread_local_poll() && !cause_return) {
2949     // If our stashed return pc was modified by the runtime we avoid touching it
2950     __ ldr(rscratch1, Address(rfp, wordSize));
2951     __ cmp(r20, rscratch1);
2952     __ br(Assembler::NE, no_adjust);
2953 
2954 #ifdef ASSERT
2955     // Verify the correct encoding of the poll we're about to skip.
2956     // See NativeInstruction::is_ldrw_to_zr()
2957     __ ldrw(rscratch1, Address(r20));
2958     __ ubfx(rscratch2, rscratch1, 22, 10);
2959     __ cmpw(rscratch2, 0b1011100101);
2960     __ br(Assembler::NE, bail);
2961     __ ubfx(rscratch2, rscratch1, 0, 5);
2962     __ cmpw(rscratch2, 0b11111);
2963     __ br(Assembler::NE, bail);
2964 #endif
2965     // Adjust return pc forward to step over the safepoint poll instruction
2966     __ add(r20, r20, NativeInstruction::instruction_size);
2967     __ str(r20, Address(rfp, wordSize));
2968   }
2969 
2970   __ bind(no_adjust);
2971   // Normal exit, restore registers and exit.
2972   RegisterSaver::restore_live_registers(masm, save_vectors);
2973 
2974   __ ret(lr);
2975 
2976 #ifdef ASSERT
2977   __ bind(bail);
2978   __ stop("Attempting to adjust pc to skip safepoint poll but the return point is not what we expected");
2979 #endif
2980 
2981   // Make sure all code is generated
2982   masm->flush();
2983 
2984   // Fill-out other meta info
2985   return SafepointBlob::create(&buffer, oop_maps, frame_size_in_words);
2986 }
2987 
2988 //
2989 // generate_resolve_blob - call resolution (static/virtual/opt-virtual/ic-miss
2990 //
2991 // Generate a stub that calls into vm to find out the proper destination
2992 // of a java call. All the argument registers are live at this point
2993 // but since this is generic code we don't know what they are and the caller
2994 // must do any gc of the args.
2995 //
2996 RuntimeStub* SharedRuntime::generate_resolve_blob(address destination, const char* name) {
2997   assert (StubRoutines::forward_exception_entry() != NULL, "must be generated before");
2998 
2999   // allocate space for the code
3000   ResourceMark rm;
3001 
3002   CodeBuffer buffer(name, 1000, 512);
3003   MacroAssembler* masm                = new MacroAssembler(&buffer);
3004 
3005   int frame_size_in_words;
3006 
3007   OopMapSet *oop_maps = new OopMapSet();
3008   OopMap* map = NULL;
3009 
3010   int start = __ offset();
3011 
3012   map = RegisterSaver::save_live_registers(masm, 0, &frame_size_in_words);
3013 
3014   int frame_complete = __ offset();
3015 
3016   {
3017     Label retaddr;
3018     __ set_last_Java_frame(sp, noreg, retaddr, rscratch1);
3019 
3020     __ mov(c_rarg0, rthread);
3021     __ lea(rscratch1, RuntimeAddress(destination));
3022 
3023     __ blrt(rscratch1, 1, 0, 1);
3024     __ bind(retaddr);
3025   }
3026 
3027   // Set an oopmap for the call site.
3028   // We need this not only for callee-saved registers, but also for volatile
3029   // registers that the compiler might be keeping live across a safepoint.
3030 
3031   oop_maps->add_gc_map( __ offset() - start, map);
3032 
3033   __ maybe_isb();
3034 
3035   // r0 contains the address we are going to jump to assuming no exception got installed
3036 
3037   // clear last_Java_sp
3038   __ reset_last_Java_frame(false);
3039   // check for pending exceptions
3040   Label pending;
3041   __ ldr(rscratch1, Address(rthread, Thread::pending_exception_offset()));
3042   __ cbnz(rscratch1, pending);
3043 
3044   // get the returned Method*
3045   __ get_vm_result_2(rmethod, rthread);
3046   __ str(rmethod, Address(sp, RegisterSaver::reg_offset_in_bytes(rmethod)));
3047 
3048   // r0 is where we want to jump, overwrite rscratch1 which is saved and scratch
3049   __ str(r0, Address(sp, RegisterSaver::rscratch1_offset_in_bytes()));
3050   RegisterSaver::restore_live_registers(masm);
3051 
3052   // We are back the the original state on entry and ready to go.
3053 
3054   __ br(rscratch1);
3055 
3056   // Pending exception after the safepoint
3057 
3058   __ bind(pending);
3059 
3060   RegisterSaver::restore_live_registers(masm);
3061 
3062   // exception pending => remove activation and forward to exception handler
3063 
3064   __ str(zr, Address(rthread, JavaThread::vm_result_offset()));
3065 
3066   __ ldr(r0, Address(rthread, Thread::pending_exception_offset()));
3067   __ far_jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
3068 
3069   // -------------
3070   // make sure all code is generated
3071   masm->flush();
3072 
3073   // return the  blob
3074   // frame_size_words or bytes??
3075   return RuntimeStub::new_runtime_stub(name, &buffer, frame_complete, frame_size_in_words, oop_maps, true);
3076 }
3077 
3078 #if COMPILER2_OR_JVMCI
3079 // This is here instead of runtime_x86_64.cpp because it uses SimpleRuntimeFrame
3080 //
3081 //------------------------------generate_exception_blob---------------------------
3082 // creates exception blob at the end
3083 // Using exception blob, this code is jumped from a compiled method.
3084 // (see emit_exception_handler in x86_64.ad file)
3085 //
3086 // Given an exception pc at a call we call into the runtime for the
3087 // handler in this method. This handler might merely restore state
3088 // (i.e. callee save registers) unwind the frame and jump to the
3089 // exception handler for the nmethod if there is no Java level handler
3090 // for the nmethod.
3091 //
3092 // This code is entered with a jmp.
3093 //
3094 // Arguments:
3095 //   r0: exception oop
3096 //   r3: exception pc
3097 //
3098 // Results:
3099 //   r0: exception oop
3100 //   r3: exception pc in caller or ???
3101 //   destination: exception handler of caller
3102 //
3103 // Note: the exception pc MUST be at a call (precise debug information)
3104 //       Registers r0, r3, r2, r4, r5, r8-r11 are not callee saved.
3105 //
3106 
3107 void OptoRuntime::generate_exception_blob() {
3108   assert(!OptoRuntime::is_callee_saved_register(R3_num), "");
3109   assert(!OptoRuntime::is_callee_saved_register(R0_num), "");
3110   assert(!OptoRuntime::is_callee_saved_register(R2_num), "");
3111 
3112   assert(SimpleRuntimeFrame::framesize % 4 == 0, "sp not 16-byte aligned");
3113 
3114   // Allocate space for the code
3115   ResourceMark rm;
3116   // Setup code generation tools
3117   CodeBuffer buffer("exception_blob", 2048, 1024);
3118   MacroAssembler* masm = new MacroAssembler(&buffer);
3119 
3120   // TODO check various assumptions made here
3121   //
3122   // make sure we do so before running this
3123 
3124   address start = __ pc();
3125 
3126   // push rfp and retaddr by hand
3127   // Exception pc is 'return address' for stack walker
3128   __ stp(rfp, lr, Address(__ pre(sp, -2 * wordSize)));
3129   // there are no callee save registers and we don't expect an
3130   // arg reg save area
3131 #ifndef PRODUCT
3132   assert(frame::arg_reg_save_area_bytes == 0, "not expecting frame reg save area");
3133 #endif
3134   // Store exception in Thread object. We cannot pass any arguments to the
3135   // handle_exception call, since we do not want to make any assumption
3136   // about the size of the frame where the exception happened in.
3137   __ str(r0, Address(rthread, JavaThread::exception_oop_offset()));
3138   __ str(r3, Address(rthread, JavaThread::exception_pc_offset()));
3139 
3140   // This call does all the hard work.  It checks if an exception handler
3141   // exists in the method.
3142   // If so, it returns the handler address.
3143   // If not, it prepares for stack-unwinding, restoring the callee-save
3144   // registers of the frame being removed.
3145   //
3146   // address OptoRuntime::handle_exception_C(JavaThread* thread)
3147   //
3148   // n.b. 1 gp arg, 0 fp args, integral return type
3149 
3150   // the stack should always be aligned
3151   address the_pc = __ pc();
3152   __ set_last_Java_frame(sp, noreg, the_pc, rscratch1);
3153   __ mov(c_rarg0, rthread);
3154   __ lea(rscratch1, RuntimeAddress(CAST_FROM_FN_PTR(address, OptoRuntime::handle_exception_C)));
3155   __ blrt(rscratch1, 1, 0, MacroAssembler::ret_type_integral);
3156   __ maybe_isb();
3157 
3158   // Set an oopmap for the call site.  This oopmap will only be used if we
3159   // are unwinding the stack.  Hence, all locations will be dead.
3160   // Callee-saved registers will be the same as the frame above (i.e.,
3161   // handle_exception_stub), since they were restored when we got the
3162   // exception.
3163 
3164   OopMapSet* oop_maps = new OopMapSet();
3165 
3166   oop_maps->add_gc_map(the_pc - start, new OopMap(SimpleRuntimeFrame::framesize, 0));
3167 
3168   __ reset_last_Java_frame(false);
3169 
3170   // Restore callee-saved registers
3171 
3172   // rfp is an implicitly saved callee saved register (i.e. the calling
3173   // convention will save restore it in prolog/epilog) Other than that
3174   // there are no callee save registers now that adapter frames are gone.
3175   // and we dont' expect an arg reg save area
3176   __ ldp(rfp, r3, Address(__ post(sp, 2 * wordSize)));
3177 
3178   // r0: exception handler
3179 
3180   // We have a handler in r0 (could be deopt blob).
3181   __ mov(r8, r0);
3182 
3183   // Get the exception oop
3184   __ ldr(r0, Address(rthread, JavaThread::exception_oop_offset()));
3185   // Get the exception pc in case we are deoptimized
3186   __ ldr(r4, Address(rthread, JavaThread::exception_pc_offset()));
3187 #ifdef ASSERT
3188   __ str(zr, Address(rthread, JavaThread::exception_handler_pc_offset()));
3189   __ str(zr, Address(rthread, JavaThread::exception_pc_offset()));
3190 #endif
3191   // Clear the exception oop so GC no longer processes it as a root.
3192   __ str(zr, Address(rthread, JavaThread::exception_oop_offset()));
3193 
3194   // r0: exception oop
3195   // r8:  exception handler
3196   // r4: exception pc
3197   // Jump to handler
3198 
3199   __ br(r8);
3200 
3201   // Make sure all code is generated
3202   masm->flush();
3203 
3204   // Set exception blob
3205   _exception_blob =  ExceptionBlob::create(&buffer, oop_maps, SimpleRuntimeFrame::framesize >> 1);
3206 }
3207 #endif // COMPILER2_OR_JVMCI