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