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