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