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