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