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