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