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