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