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