1 /*
   2  * Copyright (c) 2003, 2021, Oracle and/or its affiliates. All rights reserved.
   3  * Copyright (c) 2014, 2021, Red Hat Inc. All rights reserved.
   4  * Copyright (c) 2021, Azul Systems, Inc. All rights reserved.
   5  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   6  *
   7  * This code is free software; you can redistribute it and/or modify it
   8  * under the terms of the GNU General Public License version 2 only, as
   9  * published by the Free Software Foundation.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  *
  25  */
  26 
  27 #include "precompiled.hpp"
  28 #include "asm/macroAssembler.hpp"
  29 #include "asm/macroAssembler.inline.hpp"
  30 #include "code/codeCache.hpp"
  31 #include "code/debugInfoRec.hpp"
  32 #include "code/icBuffer.hpp"
  33 #include "code/vtableStubs.hpp"
  34 #include "compiler/oopMap.hpp"
  35 #include "gc/shared/barrierSetAssembler.hpp"
  36 #include "interpreter/interpreter.hpp"
  37 #include "interpreter/interp_masm.hpp"
  38 #include "logging/log.hpp"
  39 #include "memory/resourceArea.hpp"
  40 #include "nativeInst_aarch64.hpp"
  41 #include "oops/compiledICHolder.hpp"
  42 #include "oops/klass.inline.hpp"
  43 #include "prims/methodHandles.hpp"
  44 #include "runtime/jniHandles.hpp"
  45 #include "runtime/safepointMechanism.hpp"
  46 #include "runtime/sharedRuntime.hpp"
  47 #include "runtime/signature.hpp"
  48 #include "runtime/stubRoutines.hpp"
  49 #include "runtime/vframeArray.hpp"
  50 #include "utilities/align.hpp"
  51 #include "utilities/formatBuffer.hpp"
  52 #include "vmreg_aarch64.inline.hpp"
  53 #ifdef COMPILER1
  54 #include "c1/c1_Runtime1.hpp"
  55 #endif
  56 #ifdef COMPILER2
  57 #include "adfiles/ad_aarch64.hpp"
  58 #include "opto/runtime.hpp"
  59 #endif
  60 #if INCLUDE_JVMCI
  61 #include "jvmci/jvmciJavaClasses.hpp"
  62 #endif
  63 
  64 #define __ masm->
  65 
  66 const int StackAlignmentInSlots = StackAlignmentInBytes / VMRegImpl::stack_slot_size;
  67 
  68 class SimpleRuntimeFrame {
  69 
  70   public:
  71 
  72   // Most of the runtime stubs have this simple frame layout.
  73   // This class exists to make the layout shared in one place.
  74   // Offsets are for compiler stack slots, which are jints.
  75   enum layout {
  76     // The frame sender code expects that rbp will be in the "natural" place and
  77     // will override any oopMap setting for it. We must therefore force the layout
  78     // so that it agrees with the frame sender code.
  79     // we don't expect any arg reg save area so aarch64 asserts that
  80     // frame::arg_reg_save_area_bytes == 0
  81     rbp_off = 0,
  82     rbp_off2,
  83     return_off, return_off2,
  84     framesize
  85   };
  86 };
  87 
  88 // FIXME -- this is used by C1
  89 class RegisterSaver {
  90   const bool _save_vectors;
  91  public:
  92   RegisterSaver(bool save_vectors) : _save_vectors(save_vectors) {}
  93 
  94   OopMap* save_live_registers(MacroAssembler* masm, int additional_frame_words, int* total_frame_words);
  95   void restore_live_registers(MacroAssembler* masm);
  96 
  97   // Offsets into the register save area
  98   // Used by deoptimization when it is managing result register
  99   // values on its own
 100 
 101   int reg_offset_in_bytes(Register r);
 102   int r0_offset_in_bytes()    { return reg_offset_in_bytes(r0); }
 103   int rscratch1_offset_in_bytes()    { return reg_offset_in_bytes(rscratch1); }
 104   int v0_offset_in_bytes();
 105 
 106   // Total stack size in bytes for saving sve predicate registers.
 107   int total_sve_predicate_in_bytes();
 108 
 109   // Capture info about frame layout
 110   // Note this is only correct when not saving full vectors.
 111   enum layout {
 112                 fpu_state_off = 0,
 113                 fpu_state_end = fpu_state_off + FPUStateSizeInWords - 1,
 114                 // The frame sender code expects that rfp will be in
 115                 // the "natural" place and will override any oopMap
 116                 // setting for it. We must therefore force the layout
 117                 // so that it agrees with the frame sender code.
 118                 r0_off = fpu_state_off + FPUStateSizeInWords,
 119                 rfp_off = r0_off + (RegisterImpl::number_of_registers - 2) * RegisterImpl::max_slots_per_register,
 120                 return_off = rfp_off + RegisterImpl::max_slots_per_register,      // slot for return address
 121                 reg_save_size = return_off + RegisterImpl::max_slots_per_register};
 122 
 123 };
 124 
 125 int RegisterSaver::reg_offset_in_bytes(Register r) {
 126   // The integer registers are located above the floating point
 127   // registers in the stack frame pushed by save_live_registers() so the
 128   // offset depends on whether we are saving full vectors, and whether
 129   // those vectors are NEON or SVE.
 130 
 131   int slots_per_vect = FloatRegisterImpl::save_slots_per_register;
 132 
 133 #if COMPILER2_OR_JVMCI
 134   if (_save_vectors) {
 135     slots_per_vect = FloatRegisterImpl::slots_per_neon_register;
 136 
 137 #ifdef COMPILER2
 138     if (Matcher::supports_scalable_vector()) {
 139       slots_per_vect = Matcher::scalable_vector_reg_size(T_FLOAT);
 140     }
 141 #endif
 142   }
 143 #endif
 144 
 145   int r0_offset = v0_offset_in_bytes() + (slots_per_vect * FloatRegisterImpl::number_of_registers) * BytesPerInt;
 146   return r0_offset + r->encoding() * wordSize;
 147 }
 148 
 149 int RegisterSaver::v0_offset_in_bytes() {
 150   // The floating point registers are located above the predicate registers if
 151   // they are present in the stack frame pushed by save_live_registers(). So the
 152   // offset depends on the saved total predicate vectors in the stack frame.
 153   return (total_sve_predicate_in_bytes() / VMRegImpl::stack_slot_size) * BytesPerInt;
 154 }
 155 
 156 int RegisterSaver::total_sve_predicate_in_bytes() {
 157 #ifdef COMPILER2
 158   if (_save_vectors && Matcher::supports_scalable_vector()) {
 159     // The number of total predicate bytes is unlikely to be a multiple
 160     // of 16 bytes so we manually align it up.
 161     return align_up(Matcher::scalable_predicate_reg_slots() *
 162                     VMRegImpl::stack_slot_size *
 163                     PRegisterImpl::number_of_saved_registers, 16);
 164   }
 165 #endif
 166   return 0;
 167 }
 168 
 169 OopMap* RegisterSaver::save_live_registers(MacroAssembler* masm, int additional_frame_words, int* total_frame_words) {
 170   bool use_sve = false;
 171   int sve_vector_size_in_bytes = 0;
 172   int sve_vector_size_in_slots = 0;
 173   int sve_predicate_size_in_slots = 0;
 174   int total_predicate_in_bytes = total_sve_predicate_in_bytes();
 175   int total_predicate_in_slots = total_predicate_in_bytes / VMRegImpl::stack_slot_size;
 176 
 177 #ifdef COMPILER2
 178   use_sve = Matcher::supports_scalable_vector();
 179   if (use_sve) {
 180     sve_vector_size_in_bytes = Matcher::scalable_vector_reg_size(T_BYTE);
 181     sve_vector_size_in_slots = Matcher::scalable_vector_reg_size(T_FLOAT);
 182     sve_predicate_size_in_slots = Matcher::scalable_predicate_reg_slots();
 183   }
 184 #endif
 185 
 186 #if COMPILER2_OR_JVMCI
 187   if (_save_vectors) {
 188     int extra_save_slots_per_register = 0;
 189     // Save upper half of vector registers
 190     if (use_sve) {
 191       extra_save_slots_per_register = sve_vector_size_in_slots - FloatRegisterImpl::save_slots_per_register;
 192     } else {
 193       extra_save_slots_per_register = FloatRegisterImpl::extra_save_slots_per_neon_register;
 194     }
 195     int extra_vector_bytes = extra_save_slots_per_register *
 196                              VMRegImpl::stack_slot_size *
 197                              FloatRegisterImpl::number_of_registers;
 198     additional_frame_words += ((extra_vector_bytes + total_predicate_in_bytes) / wordSize);
 199   }
 200 #else
 201   assert(!_save_vectors, "vectors are generated only by C2 and JVMCI");
 202 #endif
 203 
 204   int frame_size_in_bytes = align_up(additional_frame_words * wordSize +
 205                                      reg_save_size * BytesPerInt, 16);
 206   // OopMap frame size is in compiler stack slots (jint's) not bytes or words
 207   int frame_size_in_slots = frame_size_in_bytes / BytesPerInt;
 208   // The caller will allocate additional_frame_words
 209   int additional_frame_slots = additional_frame_words * wordSize / BytesPerInt;
 210   // CodeBlob frame size is in words.
 211   int frame_size_in_words = frame_size_in_bytes / wordSize;
 212   *total_frame_words = frame_size_in_words;
 213 
 214   // Save Integer and Float registers.
 215   __ enter();
 216   __ push_CPU_state(_save_vectors, use_sve, sve_vector_size_in_bytes, total_predicate_in_bytes);
 217 
 218   // Set an oopmap for the call site.  This oopmap will map all
 219   // oop-registers and debug-info registers as callee-saved.  This
 220   // will allow deoptimization at this safepoint to find all possible
 221   // debug-info recordings, as well as let GC find all oops.
 222 
 223   OopMapSet *oop_maps = new OopMapSet();
 224   OopMap* oop_map = new OopMap(frame_size_in_slots, 0);
 225 
 226   for (int i = 0; i < RegisterImpl::number_of_registers; i++) {
 227     Register r = as_Register(i);
 228     if (r <= rfp && r != rscratch1 && r != rscratch2) {
 229       // SP offsets are in 4-byte words.
 230       // Register slots are 8 bytes wide, 32 floating-point registers.
 231       int sp_offset = RegisterImpl::max_slots_per_register * i +
 232                       FloatRegisterImpl::save_slots_per_register * FloatRegisterImpl::number_of_registers;
 233       oop_map->set_callee_saved(VMRegImpl::stack2reg(sp_offset + additional_frame_slots), r->as_VMReg());
 234     }
 235   }
 236 
 237   for (int i = 0; i < FloatRegisterImpl::number_of_registers; i++) {
 238     FloatRegister r = as_FloatRegister(i);
 239     int sp_offset = 0;
 240     if (_save_vectors) {
 241       sp_offset = use_sve ? (total_predicate_in_slots + sve_vector_size_in_slots * i) :
 242                             (FloatRegisterImpl::slots_per_neon_register * i);
 243     } else {
 244       sp_offset = FloatRegisterImpl::save_slots_per_register * i;
 245     }
 246     oop_map->set_callee_saved(VMRegImpl::stack2reg(sp_offset), r->as_VMReg());
 247   }
 248 
 249   if (_save_vectors && use_sve) {
 250     for (int i = 0; i < PRegisterImpl::number_of_saved_registers; i++) {
 251       PRegister r = as_PRegister(i);
 252       int sp_offset = sve_predicate_size_in_slots * i;
 253       oop_map->set_callee_saved(VMRegImpl::stack2reg(sp_offset), r->as_VMReg());
 254     }
 255   }
 256 
 257   return oop_map;
 258 }
 259 
 260 void RegisterSaver::restore_live_registers(MacroAssembler* masm) {
 261 #ifdef COMPILER2
 262   __ pop_CPU_state(_save_vectors, Matcher::supports_scalable_vector(),
 263                    Matcher::scalable_vector_reg_size(T_BYTE), total_sve_predicate_in_bytes());
 264 #else
 265 #if !INCLUDE_JVMCI
 266   assert(!_save_vectors, "vectors are generated only by C2 and JVMCI");
 267 #endif
 268   __ pop_CPU_state(_save_vectors);
 269 #endif
 270   __ leave();
 271 
 272 }
 273 
 274 // Is vector's size (in bytes) bigger than a size saved by default?
 275 // 8 bytes vector registers are saved by default on AArch64.
 276 // The SVE supported min vector size is 8 bytes and we need to save
 277 // predicate registers when the vector size is 8 bytes as well.
 278 bool SharedRuntime::is_wide_vector(int size) {
 279   return size > 8 || (UseSVE > 0 && size >= 8);
 280 }
 281 
 282 // 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   __ lea(rscratch1, RuntimeAddress(CAST_FROM_FN_PTR(address, SharedRuntime::fixup_callers_callsite)));
 414   __ blr(rscratch1);
 415 
 416   // Explicit isb required because fixup_callers_callsite may change the code
 417   // stream.
 418   __ safepoint_isb();
 419 
 420   __ pop_CPU_state();
 421   // restore sp
 422   __ leave();
 423   __ bind(L);
 424 }
 425 
 426 static void gen_c2i_adapter(MacroAssembler *masm,
 427                             int total_args_passed,
 428                             int comp_args_on_stack,
 429                             const BasicType *sig_bt,
 430                             const VMRegPair *regs,
 431                             Label& skip_fixup) {
 432   // Before we get into the guts of the C2I adapter, see if we should be here
 433   // at all.  We've come from compiled code and are attempting to jump to the
 434   // interpreter, which means the caller made a static call to get here
 435   // (vcalls always get a compiled target if there is one).  Check for a
 436   // compiled target.  If there is one, we need to patch the caller's call.
 437   patch_callers_callsite(masm);
 438 
 439   __ bind(skip_fixup);
 440 
 441   int words_pushed = 0;
 442 
 443   // Since all args are passed on the stack, total_args_passed *
 444   // Interpreter::stackElementSize is the space we need.
 445 
 446   int extraspace = total_args_passed * Interpreter::stackElementSize;
 447 
 448   __ mov(r13, sp);
 449 
 450   // stack is aligned, keep it that way
 451   extraspace = align_up(extraspace, 2*wordSize);
 452 
 453   if (extraspace)
 454     __ sub(sp, sp, extraspace);
 455 
 456   // Now write the args into the outgoing interpreter space
 457   for (int i = 0; i < total_args_passed; i++) {
 458     if (sig_bt[i] == T_VOID) {
 459       assert(i > 0 && (sig_bt[i-1] == T_LONG || sig_bt[i-1] == T_DOUBLE), "missing half");
 460       continue;
 461     }
 462 
 463     // offset to start parameters
 464     int st_off   = (total_args_passed - i - 1) * Interpreter::stackElementSize;
 465     int next_off = st_off - Interpreter::stackElementSize;
 466 
 467     // Say 4 args:
 468     // i   st_off
 469     // 0   32 T_LONG
 470     // 1   24 T_VOID
 471     // 2   16 T_OBJECT
 472     // 3    8 T_BOOL
 473     // -    0 return address
 474     //
 475     // However to make thing extra confusing. Because we can fit a Java long/double in
 476     // a single slot on a 64 bt vm and it would be silly to break them up, the interpreter
 477     // leaves one slot empty and only stores to a single slot. In this case the
 478     // slot that is occupied is the T_VOID slot. See I said it was confusing.
 479 
 480     VMReg r_1 = regs[i].first();
 481     VMReg r_2 = regs[i].second();
 482     if (!r_1->is_valid()) {
 483       assert(!r_2->is_valid(), "");
 484       continue;
 485     }
 486     if (r_1->is_stack()) {
 487       // memory to memory use rscratch1
 488       int ld_off = (r_1->reg2stack() * VMRegImpl::stack_slot_size
 489                     + extraspace
 490                     + words_pushed * wordSize);
 491       if (!r_2->is_valid()) {
 492         // sign extend??
 493         __ ldrw(rscratch1, Address(sp, ld_off));
 494         __ str(rscratch1, Address(sp, st_off));
 495 
 496       } else {
 497 
 498         __ ldr(rscratch1, Address(sp, ld_off));
 499 
 500         // Two VMREgs|OptoRegs can be T_OBJECT, T_ADDRESS, T_DOUBLE, T_LONG
 501         // T_DOUBLE and T_LONG use two slots in the interpreter
 502         if ( sig_bt[i] == T_LONG || sig_bt[i] == T_DOUBLE) {
 503           // ld_off == LSW, ld_off+wordSize == MSW
 504           // st_off == MSW, next_off == LSW
 505           __ str(rscratch1, Address(sp, next_off));
 506 #ifdef ASSERT
 507           // Overwrite the unused slot with known junk
 508           __ mov(rscratch1, (uint64_t)0xdeadffffdeadaaaaull);
 509           __ str(rscratch1, Address(sp, st_off));
 510 #endif /* ASSERT */
 511         } else {
 512           __ str(rscratch1, Address(sp, st_off));
 513         }
 514       }
 515     } else if (r_1->is_Register()) {
 516       Register r = r_1->as_Register();
 517       if (!r_2->is_valid()) {
 518         // must be only an int (or less ) so move only 32bits to slot
 519         // why not sign extend??
 520         __ str(r, Address(sp, st_off));
 521       } else {
 522         // Two VMREgs|OptoRegs can be T_OBJECT, T_ADDRESS, T_DOUBLE, T_LONG
 523         // T_DOUBLE and T_LONG use two slots in the interpreter
 524         if ( sig_bt[i] == T_LONG || sig_bt[i] == T_DOUBLE) {
 525           // jlong/double in gpr
 526 #ifdef ASSERT
 527           // Overwrite the unused slot with known junk
 528           __ mov(rscratch1, (uint64_t)0xdeadffffdeadaaabull);
 529           __ str(rscratch1, Address(sp, st_off));
 530 #endif /* ASSERT */
 531           __ str(r, Address(sp, next_off));
 532         } else {
 533           __ str(r, Address(sp, st_off));
 534         }
 535       }
 536     } else {
 537       assert(r_1->is_FloatRegister(), "");
 538       if (!r_2->is_valid()) {
 539         // only a float use just part of the slot
 540         __ strs(r_1->as_FloatRegister(), Address(sp, st_off));
 541       } else {
 542 #ifdef ASSERT
 543         // Overwrite the unused slot with known junk
 544         __ mov(rscratch1, (uint64_t)0xdeadffffdeadaaacull);
 545         __ str(rscratch1, Address(sp, st_off));
 546 #endif /* ASSERT */
 547         __ strd(r_1->as_FloatRegister(), Address(sp, next_off));
 548       }
 549     }
 550   }
 551 
 552   __ mov(esp, sp); // Interp expects args on caller's expression stack
 553 
 554   __ ldr(rscratch1, Address(rmethod, in_bytes(Method::interpreter_entry_offset())));
 555   __ br(rscratch1);
 556 }
 557 
 558 
 559 void SharedRuntime::gen_i2c_adapter(MacroAssembler *masm,
 560                                     int total_args_passed,
 561                                     int comp_args_on_stack,
 562                                     const BasicType *sig_bt,
 563                                     const VMRegPair *regs) {
 564 
 565   // Note: r13 contains the senderSP on entry. We must preserve it since
 566   // we may do a i2c -> c2i transition if we lose a race where compiled
 567   // code goes non-entrant while we get args ready.
 568 
 569   // In addition we use r13 to locate all the interpreter args because
 570   // we must align the stack to 16 bytes.
 571 
 572   // Adapters are frameless.
 573 
 574   // An i2c adapter is frameless because the *caller* frame, which is
 575   // interpreted, routinely repairs its own esp (from
 576   // interpreter_frame_last_sp), even if a callee has modified the
 577   // stack pointer.  It also recalculates and aligns sp.
 578 
 579   // A c2i adapter is frameless because the *callee* frame, which is
 580   // interpreted, routinely repairs its caller's sp (from sender_sp,
 581   // which is set up via the senderSP register).
 582 
 583   // In other words, if *either* the caller or callee is interpreted, we can
 584   // get the stack pointer repaired after a call.
 585 
 586   // This is why c2i and i2c adapters cannot be indefinitely composed.
 587   // In particular, if a c2i adapter were to somehow call an i2c adapter,
 588   // both caller and callee would be compiled methods, and neither would
 589   // clean up the stack pointer changes performed by the two adapters.
 590   // If this happens, control eventually transfers back to the compiled
 591   // caller, but with an uncorrected stack, causing delayed havoc.
 592 
 593   if (VerifyAdapterCalls &&
 594       (Interpreter::code() != NULL || StubRoutines::code1() != NULL)) {
 595 #if 0
 596     // So, let's test for cascading c2i/i2c adapters right now.
 597     //  assert(Interpreter::contains($return_addr) ||
 598     //         StubRoutines::contains($return_addr),
 599     //         "i2c adapter must return to an interpreter frame");
 600     __ block_comment("verify_i2c { ");
 601     Label L_ok;
 602     if (Interpreter::code() != NULL)
 603       range_check(masm, rax, r11,
 604                   Interpreter::code()->code_start(), Interpreter::code()->code_end(),
 605                   L_ok);
 606     if (StubRoutines::code1() != NULL)
 607       range_check(masm, rax, r11,
 608                   StubRoutines::code1()->code_begin(), StubRoutines::code1()->code_end(),
 609                   L_ok);
 610     if (StubRoutines::code2() != NULL)
 611       range_check(masm, rax, r11,
 612                   StubRoutines::code2()->code_begin(), StubRoutines::code2()->code_end(),
 613                   L_ok);
 614     const char* msg = "i2c adapter must return to an interpreter frame";
 615     __ block_comment(msg);
 616     __ stop(msg);
 617     __ bind(L_ok);
 618     __ block_comment("} verify_i2ce ");
 619 #endif
 620   }
 621 
 622   // Cut-out for having no stack args.
 623   int comp_words_on_stack = align_up(comp_args_on_stack*VMRegImpl::stack_slot_size, wordSize)>>LogBytesPerWord;
 624   if (comp_args_on_stack) {
 625     __ sub(rscratch1, sp, comp_words_on_stack * wordSize);
 626     __ andr(sp, rscratch1, -16);
 627   }
 628 
 629   // Will jump to the compiled code just as if compiled code was doing it.
 630   // Pre-load the register-jump target early, to schedule it better.
 631   __ ldr(rscratch1, Address(rmethod, in_bytes(Method::from_compiled_offset())));
 632 
 633 #if INCLUDE_JVMCI
 634   if (EnableJVMCI) {
 635     // check if this call should be routed towards a specific entry point
 636     __ ldr(rscratch2, Address(rthread, in_bytes(JavaThread::jvmci_alternate_call_target_offset())));
 637     Label no_alternative_target;
 638     __ cbz(rscratch2, no_alternative_target);
 639     __ mov(rscratch1, rscratch2);
 640     __ str(zr, Address(rthread, in_bytes(JavaThread::jvmci_alternate_call_target_offset())));
 641     __ bind(no_alternative_target);
 642   }
 643 #endif // INCLUDE_JVMCI
 644 
 645   // Now generate the shuffle code.
 646   for (int i = 0; i < total_args_passed; i++) {
 647     if (sig_bt[i] == T_VOID) {
 648       assert(i > 0 && (sig_bt[i-1] == T_LONG || sig_bt[i-1] == T_DOUBLE), "missing half");
 649       continue;
 650     }
 651 
 652     // Pick up 0, 1 or 2 words from SP+offset.
 653 
 654     assert(!regs[i].second()->is_valid() || regs[i].first()->next() == regs[i].second(),
 655             "scrambled load targets?");
 656     // Load in argument order going down.
 657     int ld_off = (total_args_passed - i - 1)*Interpreter::stackElementSize;
 658     // Point to interpreter value (vs. tag)
 659     int next_off = ld_off - Interpreter::stackElementSize;
 660     //
 661     //
 662     //
 663     VMReg r_1 = regs[i].first();
 664     VMReg r_2 = regs[i].second();
 665     if (!r_1->is_valid()) {
 666       assert(!r_2->is_valid(), "");
 667       continue;
 668     }
 669     if (r_1->is_stack()) {
 670       // Convert stack slot to an SP offset (+ wordSize to account for return address )
 671       int st_off = regs[i].first()->reg2stack()*VMRegImpl::stack_slot_size;
 672       if (!r_2->is_valid()) {
 673         // sign extend???
 674         __ ldrsw(rscratch2, Address(esp, ld_off));
 675         __ str(rscratch2, Address(sp, st_off));
 676       } else {
 677         //
 678         // We are using two optoregs. This can be either T_OBJECT,
 679         // T_ADDRESS, T_LONG, or T_DOUBLE the interpreter allocates
 680         // two slots but only uses one for thr T_LONG or T_DOUBLE case
 681         // So we must adjust where to pick up the data to match the
 682         // interpreter.
 683         //
 684         // Interpreter local[n] == MSW, local[n+1] == LSW however locals
 685         // are accessed as negative so LSW is at LOW address
 686 
 687         // ld_off is MSW so get LSW
 688         const int offset = (sig_bt[i]==T_LONG||sig_bt[i]==T_DOUBLE)?
 689                            next_off : ld_off;
 690         __ ldr(rscratch2, Address(esp, offset));
 691         // st_off is LSW (i.e. reg.first())
 692         __ str(rscratch2, Address(sp, st_off));
 693       }
 694     } else if (r_1->is_Register()) {  // Register argument
 695       Register r = r_1->as_Register();
 696       if (r_2->is_valid()) {
 697         //
 698         // We are using two VMRegs. This can be either T_OBJECT,
 699         // T_ADDRESS, T_LONG, or T_DOUBLE the interpreter allocates
 700         // two slots but only uses one for thr T_LONG or T_DOUBLE case
 701         // So we must adjust where to pick up the data to match the
 702         // interpreter.
 703 
 704         const int offset = (sig_bt[i]==T_LONG||sig_bt[i]==T_DOUBLE)?
 705                            next_off : ld_off;
 706 
 707         // this can be a misaligned move
 708         __ ldr(r, Address(esp, offset));
 709       } else {
 710         // sign extend and use a full word?
 711         __ ldrw(r, Address(esp, ld_off));
 712       }
 713     } else {
 714       if (!r_2->is_valid()) {
 715         __ ldrs(r_1->as_FloatRegister(), Address(esp, ld_off));
 716       } else {
 717         __ ldrd(r_1->as_FloatRegister(), Address(esp, next_off));
 718       }
 719     }
 720   }
 721 
 722   // 6243940 We might end up in handle_wrong_method if
 723   // the callee is deoptimized as we race thru here. If that
 724   // happens we don't want to take a safepoint because the
 725   // caller frame will look interpreted and arguments are now
 726   // "compiled" so it is much better to make this transition
 727   // invisible to the stack walking code. Unfortunately if
 728   // we try and find the callee by normal means a safepoint
 729   // is possible. So we stash the desired callee in the thread
 730   // and the vm will find there should this case occur.
 731 
 732   __ str(rmethod, Address(rthread, JavaThread::callee_target_offset()));
 733 
 734   __ br(rscratch1);
 735 }
 736 
 737 // ---------------------------------------------------------------
 738 AdapterHandlerEntry* SharedRuntime::generate_i2c2i_adapters(MacroAssembler *masm,
 739                                                             int total_args_passed,
 740                                                             int comp_args_on_stack,
 741                                                             const BasicType *sig_bt,
 742                                                             const VMRegPair *regs,
 743                                                             AdapterFingerPrint* fingerprint) {
 744   address i2c_entry = __ pc();
 745 
 746   gen_i2c_adapter(masm, total_args_passed, comp_args_on_stack, sig_bt, regs);
 747 
 748   address c2i_unverified_entry = __ pc();
 749   Label skip_fixup;
 750 
 751   Label ok;
 752 
 753   Register holder = rscratch2;
 754   Register receiver = j_rarg0;
 755   Register tmp = r10;  // A call-clobbered register not used for arg passing
 756 
 757   // -------------------------------------------------------------------------
 758   // Generate a C2I adapter.  On entry we know rmethod holds the Method* during calls
 759   // to the interpreter.  The args start out packed in the compiled layout.  They
 760   // need to be unpacked into the interpreter layout.  This will almost always
 761   // require some stack space.  We grow the current (compiled) stack, then repack
 762   // the args.  We  finally end in a jump to the generic interpreter entry point.
 763   // On exit from the interpreter, the interpreter will restore our SP (lest the
 764   // compiled code, which relys solely on SP and not FP, get sick).
 765 
 766   {
 767     __ block_comment("c2i_unverified_entry {");
 768     __ load_klass(rscratch1, receiver);
 769     __ ldr(tmp, Address(holder, CompiledICHolder::holder_klass_offset()));
 770     __ cmp(rscratch1, tmp);
 771     __ ldr(rmethod, Address(holder, CompiledICHolder::holder_metadata_offset()));
 772     __ br(Assembler::EQ, ok);
 773     __ far_jump(RuntimeAddress(SharedRuntime::get_ic_miss_stub()));
 774 
 775     __ bind(ok);
 776     // Method might have been compiled since the call site was patched to
 777     // interpreted; if that is the case treat it as a miss so we can get
 778     // the call site corrected.
 779     __ ldr(rscratch1, Address(rmethod, in_bytes(Method::code_offset())));
 780     __ cbz(rscratch1, skip_fixup);
 781     __ far_jump(RuntimeAddress(SharedRuntime::get_ic_miss_stub()));
 782     __ block_comment("} c2i_unverified_entry");
 783   }
 784 
 785   address c2i_entry = __ pc();
 786 
 787   // Class initialization barrier for static methods
 788   address c2i_no_clinit_check_entry = NULL;
 789   if (VM_Version::supports_fast_class_init_checks()) {
 790     Label L_skip_barrier;
 791 
 792     { // Bypass the barrier for non-static methods
 793       __ ldrw(rscratch1, Address(rmethod, Method::access_flags_offset()));
 794       __ andsw(zr, rscratch1, JVM_ACC_STATIC);
 795       __ br(Assembler::EQ, L_skip_barrier); // non-static
 796     }
 797 
 798     __ load_method_holder(rscratch2, rmethod);
 799     __ clinit_barrier(rscratch2, rscratch1, &L_skip_barrier);
 800     __ far_jump(RuntimeAddress(SharedRuntime::get_handle_wrong_method_stub()));
 801 
 802     __ bind(L_skip_barrier);
 803     c2i_no_clinit_check_entry = __ pc();
 804   }
 805 
 806   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
 807   bs->c2i_entry_barrier(masm);
 808 
 809   gen_c2i_adapter(masm, total_args_passed, comp_args_on_stack, sig_bt, regs, skip_fixup);
 810 
 811   __ flush();
 812   return AdapterHandlerLibrary::new_entry(fingerprint, i2c_entry, c2i_entry, c2i_unverified_entry, c2i_no_clinit_check_entry);
 813 }
 814 
 815 static int c_calling_convention_priv(const BasicType *sig_bt,
 816                                          VMRegPair *regs,
 817                                          VMRegPair *regs2,
 818                                          int total_args_passed) {
 819   assert(regs2 == NULL, "not needed on AArch64");
 820 
 821 // We return the amount of VMRegImpl stack slots we need to reserve for all
 822 // the arguments NOT counting out_preserve_stack_slots.
 823 
 824     static const Register INT_ArgReg[Argument::n_int_register_parameters_c] = {
 825       c_rarg0, c_rarg1, c_rarg2, c_rarg3, c_rarg4, c_rarg5,  c_rarg6,  c_rarg7
 826     };
 827     static const FloatRegister FP_ArgReg[Argument::n_float_register_parameters_c] = {
 828       c_farg0, c_farg1, c_farg2, c_farg3,
 829       c_farg4, c_farg5, c_farg6, c_farg7
 830     };
 831 
 832     uint int_args = 0;
 833     uint fp_args = 0;
 834     uint stk_args = 0; // inc by 2 each time
 835 
 836     for (int i = 0; i < total_args_passed; i++) {
 837       switch (sig_bt[i]) {
 838       case T_BOOLEAN:
 839       case T_CHAR:
 840       case T_BYTE:
 841       case T_SHORT:
 842       case T_INT:
 843         if (int_args < Argument::n_int_register_parameters_c) {
 844           regs[i].set1(INT_ArgReg[int_args++]->as_VMReg());
 845         } else {
 846 #ifdef __APPLE__
 847           // Less-than word types are stored one after another.
 848           // The code is unable to handle this so bailout.
 849           return -1;
 850 #endif
 851           regs[i].set1(VMRegImpl::stack2reg(stk_args));
 852           stk_args += 2;
 853         }
 854         break;
 855       case T_LONG:
 856         assert((i + 1) < total_args_passed && sig_bt[i + 1] == T_VOID, "expecting half");
 857         // fall through
 858       case T_OBJECT:
 859       case T_ARRAY:
 860       case T_ADDRESS:
 861       case T_METADATA:
 862         if (int_args < Argument::n_int_register_parameters_c) {
 863           regs[i].set2(INT_ArgReg[int_args++]->as_VMReg());
 864         } else {
 865           regs[i].set2(VMRegImpl::stack2reg(stk_args));
 866           stk_args += 2;
 867         }
 868         break;
 869       case T_FLOAT:
 870         if (fp_args < Argument::n_float_register_parameters_c) {
 871           regs[i].set1(FP_ArgReg[fp_args++]->as_VMReg());
 872         } else {
 873 #ifdef __APPLE__
 874           // Less-than word types are stored one after another.
 875           // The code is unable to handle this so bailout.
 876           return -1;
 877 #endif
 878           regs[i].set1(VMRegImpl::stack2reg(stk_args));
 879           stk_args += 2;
 880         }
 881         break;
 882       case T_DOUBLE:
 883         assert((i + 1) < total_args_passed && sig_bt[i + 1] == T_VOID, "expecting half");
 884         if (fp_args < Argument::n_float_register_parameters_c) {
 885           regs[i].set2(FP_ArgReg[fp_args++]->as_VMReg());
 886         } else {
 887           regs[i].set2(VMRegImpl::stack2reg(stk_args));
 888           stk_args += 2;
 889         }
 890         break;
 891       case T_VOID: // Halves of longs and doubles
 892         assert(i != 0 && (sig_bt[i - 1] == T_LONG || sig_bt[i - 1] == T_DOUBLE), "expecting half");
 893         regs[i].set_bad();
 894         break;
 895       default:
 896         ShouldNotReachHere();
 897         break;
 898       }
 899     }
 900 
 901   return stk_args;
 902 }
 903 
 904 int SharedRuntime::vector_calling_convention(VMRegPair *regs,
 905                                              uint num_bits,
 906                                              uint total_args_passed) {
 907   Unimplemented();
 908   return 0;
 909 }
 910 
 911 int SharedRuntime::c_calling_convention(const BasicType *sig_bt,
 912                                          VMRegPair *regs,
 913                                          VMRegPair *regs2,
 914                                          int total_args_passed)
 915 {
 916   int result = c_calling_convention_priv(sig_bt, regs, regs2, total_args_passed);
 917   guarantee(result >= 0, "Unsupported arguments configuration");
 918   return result;
 919 }
 920 
 921 // On 64 bit we will store integer like items to the stack as
 922 // 64 bits items (Aarch64 abi) even though java would only store
 923 // 32bits for a parameter. On 32bit it will simply be 32 bits
 924 // So this routine will do 32->32 on 32bit and 32->64 on 64bit
 925 static void move32_64(MacroAssembler* masm, VMRegPair src, VMRegPair dst) {
 926   if (src.first()->is_stack()) {
 927     if (dst.first()->is_stack()) {
 928       // stack to stack
 929       __ ldr(rscratch1, Address(rfp, reg2offset_in(src.first())));
 930       __ str(rscratch1, Address(sp, reg2offset_out(dst.first())));
 931     } else {
 932       // stack to reg
 933       __ ldrsw(dst.first()->as_Register(), Address(rfp, reg2offset_in(src.first())));
 934     }
 935   } else if (dst.first()->is_stack()) {
 936     // reg to stack
 937     // Do we really have to sign extend???
 938     // __ movslq(src.first()->as_Register(), src.first()->as_Register());
 939     __ str(src.first()->as_Register(), Address(sp, reg2offset_out(dst.first())));
 940   } else {
 941     if (dst.first() != src.first()) {
 942       __ sxtw(dst.first()->as_Register(), src.first()->as_Register());
 943     }
 944   }
 945 }
 946 
 947 // An oop arg. Must pass a handle not the oop itself
 948 static void object_move(MacroAssembler* masm,
 949                         OopMap* map,
 950                         int oop_handle_offset,
 951                         int framesize_in_slots,
 952                         VMRegPair src,
 953                         VMRegPair dst,
 954                         bool is_receiver,
 955                         int* receiver_offset) {
 956 
 957   // must pass a handle. First figure out the location we use as a handle
 958 
 959   Register rHandle = dst.first()->is_stack() ? rscratch2 : dst.first()->as_Register();
 960 
 961   // See if oop is NULL if it is we need no handle
 962 
 963   if (src.first()->is_stack()) {
 964 
 965     // Oop is already on the stack as an argument
 966     int offset_in_older_frame = src.first()->reg2stack() + SharedRuntime::out_preserve_stack_slots();
 967     map->set_oop(VMRegImpl::stack2reg(offset_in_older_frame + framesize_in_slots));
 968     if (is_receiver) {
 969       *receiver_offset = (offset_in_older_frame + framesize_in_slots) * VMRegImpl::stack_slot_size;
 970     }
 971 
 972     __ ldr(rscratch1, Address(rfp, reg2offset_in(src.first())));
 973     __ lea(rHandle, Address(rfp, reg2offset_in(src.first())));
 974     // conditionally move a NULL
 975     __ cmp(rscratch1, zr);
 976     __ csel(rHandle, zr, rHandle, Assembler::EQ);
 977   } else {
 978 
 979     // Oop is in an a register we must store it to the space we reserve
 980     // on the stack for oop_handles and pass a handle if oop is non-NULL
 981 
 982     const Register rOop = src.first()->as_Register();
 983     int oop_slot;
 984     if (rOop == j_rarg0)
 985       oop_slot = 0;
 986     else if (rOop == j_rarg1)
 987       oop_slot = 1;
 988     else if (rOop == j_rarg2)
 989       oop_slot = 2;
 990     else if (rOop == j_rarg3)
 991       oop_slot = 3;
 992     else if (rOop == j_rarg4)
 993       oop_slot = 4;
 994     else if (rOop == j_rarg5)
 995       oop_slot = 5;
 996     else if (rOop == j_rarg6)
 997       oop_slot = 6;
 998     else {
 999       assert(rOop == j_rarg7, "wrong register");
1000       oop_slot = 7;
1001     }
1002 
1003     oop_slot = oop_slot * VMRegImpl::slots_per_word + oop_handle_offset;
1004     int offset = oop_slot*VMRegImpl::stack_slot_size;
1005 
1006     map->set_oop(VMRegImpl::stack2reg(oop_slot));
1007     // Store oop in handle area, may be NULL
1008     __ str(rOop, Address(sp, offset));
1009     if (is_receiver) {
1010       *receiver_offset = offset;
1011     }
1012 
1013     __ cmp(rOop, zr);
1014     __ lea(rHandle, Address(sp, offset));
1015     // conditionally move a NULL
1016     __ csel(rHandle, zr, rHandle, Assembler::EQ);
1017   }
1018 
1019   // If arg is on the stack then place it otherwise it is already in correct reg.
1020   if (dst.first()->is_stack()) {
1021     __ str(rHandle, Address(sp, reg2offset_out(dst.first())));
1022   }
1023 }
1024 
1025 // A float arg may have to do float reg int reg conversion
1026 static void float_move(MacroAssembler* masm, VMRegPair src, VMRegPair dst) {
1027   assert(src.first()->is_stack() && dst.first()->is_stack() ||
1028          src.first()->is_reg() && dst.first()->is_reg(), "Unexpected error");
1029   if (src.first()->is_stack()) {
1030     if (dst.first()->is_stack()) {
1031       __ ldrw(rscratch1, Address(rfp, reg2offset_in(src.first())));
1032       __ strw(rscratch1, Address(sp, reg2offset_out(dst.first())));
1033     } else {
1034       ShouldNotReachHere();
1035     }
1036   } else if (src.first() != dst.first()) {
1037     if (src.is_single_phys_reg() && dst.is_single_phys_reg())
1038       __ fmovs(dst.first()->as_FloatRegister(), src.first()->as_FloatRegister());
1039     else
1040       ShouldNotReachHere();
1041   }
1042 }
1043 
1044 // A long move
1045 static void long_move(MacroAssembler* masm, VMRegPair src, VMRegPair dst) {
1046   if (src.first()->is_stack()) {
1047     if (dst.first()->is_stack()) {
1048       // stack to stack
1049       __ ldr(rscratch1, Address(rfp, reg2offset_in(src.first())));
1050       __ str(rscratch1, Address(sp, reg2offset_out(dst.first())));
1051     } else {
1052       // stack to reg
1053       __ ldr(dst.first()->as_Register(), Address(rfp, reg2offset_in(src.first())));
1054     }
1055   } else if (dst.first()->is_stack()) {
1056     // reg to stack
1057     // Do we really have to sign extend???
1058     // __ movslq(src.first()->as_Register(), src.first()->as_Register());
1059     __ str(src.first()->as_Register(), Address(sp, reg2offset_out(dst.first())));
1060   } else {
1061     if (dst.first() != src.first()) {
1062       __ mov(dst.first()->as_Register(), src.first()->as_Register());
1063     }
1064   }
1065 }
1066 
1067 
1068 // A double move
1069 static void double_move(MacroAssembler* masm, VMRegPair src, VMRegPair dst) {
1070   assert(src.first()->is_stack() && dst.first()->is_stack() ||
1071          src.first()->is_reg() && dst.first()->is_reg(), "Unexpected error");
1072   if (src.first()->is_stack()) {
1073     if (dst.first()->is_stack()) {
1074       __ ldr(rscratch1, Address(rfp, reg2offset_in(src.first())));
1075       __ str(rscratch1, Address(sp, reg2offset_out(dst.first())));
1076     } else {
1077       ShouldNotReachHere();
1078     }
1079   } else if (src.first() != dst.first()) {
1080     if (src.is_single_phys_reg() && dst.is_single_phys_reg())
1081       __ fmovd(dst.first()->as_FloatRegister(), src.first()->as_FloatRegister());
1082     else
1083       ShouldNotReachHere();
1084   }
1085 }
1086 
1087 
1088 void SharedRuntime::save_native_result(MacroAssembler *masm, BasicType ret_type, int frame_slots) {
1089   // We always ignore the frame_slots arg and just use the space just below frame pointer
1090   // which by this time is free to use
1091   switch (ret_type) {
1092   case T_FLOAT:
1093     __ strs(v0, Address(rfp, -wordSize));
1094     break;
1095   case T_DOUBLE:
1096     __ strd(v0, Address(rfp, -wordSize));
1097     break;
1098   case T_VOID:  break;
1099   default: {
1100     __ str(r0, Address(rfp, -wordSize));
1101     }
1102   }
1103 }
1104 
1105 void SharedRuntime::restore_native_result(MacroAssembler *masm, BasicType ret_type, int frame_slots) {
1106   // We always ignore the frame_slots arg and just use the space just below frame pointer
1107   // which by this time is free to use
1108   switch (ret_type) {
1109   case T_FLOAT:
1110     __ ldrs(v0, Address(rfp, -wordSize));
1111     break;
1112   case T_DOUBLE:
1113     __ ldrd(v0, Address(rfp, -wordSize));
1114     break;
1115   case T_VOID:  break;
1116   default: {
1117     __ ldr(r0, Address(rfp, -wordSize));
1118     }
1119   }
1120 }
1121 static void save_args(MacroAssembler *masm, int arg_count, int first_arg, VMRegPair *args) {
1122   RegSet x;
1123   for ( int i = first_arg ; i < arg_count ; i++ ) {
1124     if (args[i].first()->is_Register()) {
1125       x = x + args[i].first()->as_Register();
1126     } else if (args[i].first()->is_FloatRegister()) {
1127       __ strd(args[i].first()->as_FloatRegister(), Address(__ pre(sp, -2 * wordSize)));
1128     }
1129   }
1130   __ push(x, sp);
1131 }
1132 
1133 static void restore_args(MacroAssembler *masm, int arg_count, int first_arg, VMRegPair *args) {
1134   RegSet x;
1135   for ( int i = first_arg ; i < arg_count ; i++ ) {
1136     if (args[i].first()->is_Register()) {
1137       x = x + args[i].first()->as_Register();
1138     } else {
1139       ;
1140     }
1141   }
1142   __ pop(x, sp);
1143   for ( int i = arg_count - 1 ; i >= first_arg ; i-- ) {
1144     if (args[i].first()->is_Register()) {
1145       ;
1146     } else if (args[i].first()->is_FloatRegister()) {
1147       __ ldrd(args[i].first()->as_FloatRegister(), Address(__ post(sp, 2 * wordSize)));
1148     }
1149   }
1150 }
1151 
1152 static void rt_call(MacroAssembler* masm, address dest) {
1153   CodeBlob *cb = CodeCache::find_blob(dest);
1154   if (cb) {
1155     __ far_call(RuntimeAddress(dest));
1156   } else {
1157     __ lea(rscratch1, RuntimeAddress(dest));
1158     __ blr(rscratch1);
1159   }
1160 }
1161 
1162 static void verify_oop_args(MacroAssembler* masm,
1163                             const methodHandle& method,
1164                             const BasicType* sig_bt,
1165                             const VMRegPair* regs) {
1166   Register temp_reg = r19;  // not part of any compiled calling seq
1167   if (VerifyOops) {
1168     for (int i = 0; i < method->size_of_parameters(); i++) {
1169       if (sig_bt[i] == T_OBJECT ||
1170           sig_bt[i] == T_ARRAY) {
1171         VMReg r = regs[i].first();
1172         assert(r->is_valid(), "bad oop arg");
1173         if (r->is_stack()) {
1174           __ ldr(temp_reg, Address(sp, r->reg2stack() * VMRegImpl::stack_slot_size));
1175           __ verify_oop(temp_reg);
1176         } else {
1177           __ verify_oop(r->as_Register());
1178         }
1179       }
1180     }
1181   }
1182 }
1183 
1184 static void gen_special_dispatch(MacroAssembler* masm,
1185                                  const methodHandle& method,
1186                                  const BasicType* sig_bt,
1187                                  const VMRegPair* regs) {
1188   verify_oop_args(masm, method, sig_bt, regs);
1189   vmIntrinsics::ID iid = method->intrinsic_id();
1190 
1191   // Now write the args into the outgoing interpreter space
1192   bool     has_receiver   = false;
1193   Register receiver_reg   = noreg;
1194   int      member_arg_pos = -1;
1195   Register member_reg     = noreg;
1196   int      ref_kind       = MethodHandles::signature_polymorphic_intrinsic_ref_kind(iid);
1197   if (ref_kind != 0) {
1198     member_arg_pos = method->size_of_parameters() - 1;  // trailing MemberName argument
1199     member_reg = r19;  // known to be free at this point
1200     has_receiver = MethodHandles::ref_kind_has_receiver(ref_kind);
1201   } else if (iid == vmIntrinsics::_invokeBasic || iid == vmIntrinsics::_linkToNative) {
1202     has_receiver = true;



1203   } else {
1204     fatal("unexpected intrinsic id %d", vmIntrinsics::as_int(iid));
1205   }
1206 
1207   if (member_reg != noreg) {
1208     // Load the member_arg into register, if necessary.
1209     SharedRuntime::check_member_name_argument_is_last_argument(method, sig_bt, regs);
1210     VMReg r = regs[member_arg_pos].first();
1211     if (r->is_stack()) {
1212       __ ldr(member_reg, Address(sp, r->reg2stack() * VMRegImpl::stack_slot_size));
1213     } else {
1214       // no data motion is needed
1215       member_reg = r->as_Register();
1216     }
1217   }
1218 
1219   if (has_receiver) {
1220     // Make sure the receiver is loaded into a register.
1221     assert(method->size_of_parameters() > 0, "oob");
1222     assert(sig_bt[0] == T_OBJECT, "receiver argument must be an object");
1223     VMReg r = regs[0].first();
1224     assert(r->is_valid(), "bad receiver arg");
1225     if (r->is_stack()) {
1226       // Porting note:  This assumes that compiled calling conventions always
1227       // pass the receiver oop in a register.  If this is not true on some
1228       // platform, pick a temp and load the receiver from stack.
1229       fatal("receiver always in a register");
1230       receiver_reg = r2;  // known to be free at this point
1231       __ ldr(receiver_reg, Address(sp, r->reg2stack() * VMRegImpl::stack_slot_size));
1232     } else {
1233       // no data motion is needed
1234       receiver_reg = r->as_Register();
1235     }
1236   }
1237 
1238   // Figure out which address we are really jumping to:
1239   MethodHandles::generate_method_handle_dispatch(masm, iid,
1240                                                  receiver_reg, member_reg, /*for_compiler_entry:*/ true);
1241 }
1242 
1243 // ---------------------------------------------------------------------------
1244 // Generate a native wrapper for a given method.  The method takes arguments
1245 // in the Java compiled code convention, marshals them to the native
1246 // convention (handlizes oops, etc), transitions to native, makes the call,
1247 // returns to java state (possibly blocking), unhandlizes any result and
1248 // returns.
1249 //
1250 // Critical native functions are a shorthand for the use of
1251 // GetPrimtiveArrayCritical and disallow the use of any other JNI
1252 // functions.  The wrapper is expected to unpack the arguments before
1253 // passing them to the callee. Critical native functions leave the state _in_Java,
1254 // since they block out GC.
1255 // Some other parts of JNI setup are skipped like the tear down of the JNI handle
1256 // block and the check for pending exceptions it's impossible for them
1257 // to be thrown.
1258 //
1259 nmethod* SharedRuntime::generate_native_wrapper(MacroAssembler* masm,
1260                                                 const methodHandle& method,
1261                                                 int compile_id,
1262                                                 BasicType* in_sig_bt,
1263                                                 VMRegPair* in_regs,
1264                                                 BasicType ret_type) {
1265   if (method->is_method_handle_intrinsic()) {
1266     vmIntrinsics::ID iid = method->intrinsic_id();
1267     intptr_t start = (intptr_t)__ pc();
1268     int vep_offset = ((intptr_t)__ pc()) - start;
1269 
1270     // First instruction must be a nop as it may need to be patched on deoptimisation
1271     __ nop();
1272     gen_special_dispatch(masm,
1273                          method,
1274                          in_sig_bt,
1275                          in_regs);
1276     int frame_complete = ((intptr_t)__ pc()) - start;  // not complete, period
1277     __ flush();
1278     int stack_slots = SharedRuntime::out_preserve_stack_slots();  // no out slots at all, actually
1279     return nmethod::new_native_nmethod(method,
1280                                        compile_id,
1281                                        masm->code(),
1282                                        vep_offset,
1283                                        frame_complete,
1284                                        stack_slots / VMRegImpl::slots_per_word,
1285                                        in_ByteSize(-1),
1286                                        in_ByteSize(-1),
1287                                        (OopMapSet*)NULL);
1288   }
1289   address native_func = method->native_function();
1290   assert(native_func != NULL, "must have function");
1291 
1292   // An OopMap for lock (and class if static)
1293   OopMapSet *oop_maps = new OopMapSet();
1294   intptr_t start = (intptr_t)__ pc();
1295 
1296   // We have received a description of where all the java arg are located
1297   // on entry to the wrapper. We need to convert these args to where
1298   // the jni function will expect them. To figure out where they go
1299   // we convert the java signature to a C signature by inserting
1300   // the hidden arguments as arg[0] and possibly arg[1] (static method)
1301 
1302   const int total_in_args = method->size_of_parameters();
1303   int total_c_args = total_in_args + (method->is_static() ? 2 : 1);
1304 
1305   BasicType* out_sig_bt = NEW_RESOURCE_ARRAY(BasicType, total_c_args);
1306   VMRegPair* out_regs   = NEW_RESOURCE_ARRAY(VMRegPair, total_c_args);
1307   BasicType* in_elem_bt = NULL;
1308 
1309   int argc = 0;
1310   out_sig_bt[argc++] = T_ADDRESS;
1311   if (method->is_static()) {
1312     out_sig_bt[argc++] = T_OBJECT;
1313   }
1314 
1315   for (int i = 0; i < total_in_args ; i++ ) {
1316     out_sig_bt[argc++] = in_sig_bt[i];
1317   }
1318 
1319   // Now figure out where the args must be stored and how much stack space
1320   // they require.
1321   int out_arg_slots;
1322   out_arg_slots = c_calling_convention_priv(out_sig_bt, out_regs, NULL, total_c_args);
1323 
1324   if (out_arg_slots < 0) {
1325     return NULL;
1326   }
1327 
1328   // Compute framesize for the wrapper.  We need to handlize all oops in
1329   // incoming registers
1330 
1331   // Calculate the total number of stack slots we will need.
1332 
1333   // First count the abi requirement plus all of the outgoing args
1334   int stack_slots = SharedRuntime::out_preserve_stack_slots() + out_arg_slots;
1335 
1336   // Now the space for the inbound oop handle area
1337   int total_save_slots = 8 * VMRegImpl::slots_per_word;  // 8 arguments passed in registers
1338 
1339   int oop_handle_offset = stack_slots;
1340   stack_slots += total_save_slots;
1341 
1342   // Now any space we need for handlizing a klass if static method
1343 
1344   int klass_slot_offset = 0;
1345   int klass_offset = -1;
1346   int lock_slot_offset = 0;
1347   bool is_static = false;
1348 
1349   if (method->is_static()) {
1350     klass_slot_offset = stack_slots;
1351     stack_slots += VMRegImpl::slots_per_word;
1352     klass_offset = klass_slot_offset * VMRegImpl::stack_slot_size;
1353     is_static = true;
1354   }
1355 
1356   // Plus a lock if needed
1357 
1358   if (method->is_synchronized()) {
1359     lock_slot_offset = stack_slots;
1360     stack_slots += VMRegImpl::slots_per_word;
1361   }
1362 
1363   // Now a place (+2) to save return values or temp during shuffling
1364   // + 4 for return address (which we own) and saved rfp
1365   stack_slots += 6;
1366 
1367   // Ok The space we have allocated will look like:
1368   //
1369   //
1370   // FP-> |                     |
1371   //      |---------------------|
1372   //      | 2 slots for moves   |
1373   //      |---------------------|
1374   //      | lock box (if sync)  |
1375   //      |---------------------| <- lock_slot_offset
1376   //      | klass (if static)   |
1377   //      |---------------------| <- klass_slot_offset
1378   //      | oopHandle area      |
1379   //      |---------------------| <- oop_handle_offset (8 java arg registers)
1380   //      | outbound memory     |
1381   //      | based arguments     |
1382   //      |                     |
1383   //      |---------------------|
1384   //      |                     |
1385   // SP-> | out_preserved_slots |
1386   //
1387   //
1388 
1389 
1390   // Now compute actual number of stack words we need rounding to make
1391   // stack properly aligned.
1392   stack_slots = align_up(stack_slots, StackAlignmentInSlots);
1393 
1394   int stack_size = stack_slots * VMRegImpl::stack_slot_size;
1395 
1396   // First thing make an ic check to see if we should even be here
1397 
1398   // We are free to use all registers as temps without saving them and
1399   // restoring them except rfp. rfp is the only callee save register
1400   // as far as the interpreter and the compiler(s) are concerned.
1401 
1402 
1403   const Register ic_reg = rscratch2;
1404   const Register receiver = j_rarg0;
1405 
1406   Label hit;
1407   Label exception_pending;
1408 
1409   assert_different_registers(ic_reg, receiver, rscratch1);
1410   __ verify_oop(receiver);
1411   __ cmp_klass(receiver, ic_reg, rscratch1);
1412   __ br(Assembler::EQ, hit);
1413 
1414   __ far_jump(RuntimeAddress(SharedRuntime::get_ic_miss_stub()));
1415 
1416   // Verified entry point must be aligned
1417   __ align(8);
1418 
1419   __ bind(hit);
1420 
1421   int vep_offset = ((intptr_t)__ pc()) - start;
1422 
1423   // If we have to make this method not-entrant we'll overwrite its
1424   // first instruction with a jump.  For this action to be legal we
1425   // must ensure that this first instruction is a B, BL, NOP, BKPT,
1426   // SVC, HVC, or SMC.  Make it a NOP.
1427   __ nop();
1428 
1429   if (VM_Version::supports_fast_class_init_checks() && method->needs_clinit_barrier()) {
1430     Label L_skip_barrier;
1431     __ mov_metadata(rscratch2, method->method_holder()); // InstanceKlass*
1432     __ clinit_barrier(rscratch2, rscratch1, &L_skip_barrier);
1433     __ far_jump(RuntimeAddress(SharedRuntime::get_handle_wrong_method_stub()));
1434 
1435     __ bind(L_skip_barrier);
1436   }
1437 
1438   // Generate stack overflow check
1439   __ bang_stack_with_offset(checked_cast<int>(StackOverflow::stack_shadow_zone_size()));
1440 
1441   // Generate a new frame for the wrapper.
1442   __ enter();
1443   // -2 because return address is already present and so is saved rfp
1444   __ sub(sp, sp, stack_size - 2*wordSize);
1445 
1446   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
1447   bs->nmethod_entry_barrier(masm);
1448 
1449   // Frame is now completed as far as size and linkage.
1450   int frame_complete = ((intptr_t)__ pc()) - start;
1451 
1452   // We use r20 as the oop handle for the receiver/klass
1453   // It is callee save so it survives the call to native
1454 
1455   const Register oop_handle_reg = r20;
1456 
1457   //
1458   // We immediately shuffle the arguments so that any vm call we have to
1459   // make from here on out (sync slow path, jvmti, etc.) we will have
1460   // captured the oops from our caller and have a valid oopMap for
1461   // them.
1462 
1463   // -----------------
1464   // The Grand Shuffle
1465 
1466   // The Java calling convention is either equal (linux) or denser (win64) than the
1467   // c calling convention. However the because of the jni_env argument the c calling
1468   // convention always has at least one more (and two for static) arguments than Java.
1469   // Therefore if we move the args from java -> c backwards then we will never have
1470   // a register->register conflict and we don't have to build a dependency graph
1471   // and figure out how to break any cycles.
1472   //
1473 
1474   // Record esp-based slot for receiver on stack for non-static methods
1475   int receiver_offset = -1;
1476 
1477   // This is a trick. We double the stack slots so we can claim
1478   // the oops in the caller's frame. Since we are sure to have
1479   // more args than the caller doubling is enough to make
1480   // sure we can capture all the incoming oop args from the
1481   // caller.
1482   //
1483   OopMap* map = new OopMap(stack_slots * 2, 0 /* arg_slots*/);
1484 
1485   // Mark location of rfp (someday)
1486   // map->set_callee_saved(VMRegImpl::stack2reg( stack_slots - 2), stack_slots * 2, 0, vmreg(rfp));
1487 
1488 
1489   int float_args = 0;
1490   int int_args = 0;
1491 
1492 #ifdef ASSERT
1493   bool reg_destroyed[RegisterImpl::number_of_registers];
1494   bool freg_destroyed[FloatRegisterImpl::number_of_registers];
1495   for ( int r = 0 ; r < RegisterImpl::number_of_registers ; r++ ) {
1496     reg_destroyed[r] = false;
1497   }
1498   for ( int f = 0 ; f < FloatRegisterImpl::number_of_registers ; f++ ) {
1499     freg_destroyed[f] = false;
1500   }
1501 
1502 #endif /* ASSERT */
1503 
1504   // For JNI natives the incoming and outgoing registers are offset upwards.
1505   GrowableArray<int> arg_order(2 * total_in_args);
1506   VMRegPair tmp_vmreg;
1507   tmp_vmreg.set2(r19->as_VMReg());
1508 
1509   for (int i = total_in_args - 1, c_arg = total_c_args - 1; i >= 0; i--, c_arg--) {
1510     arg_order.push(i);
1511     arg_order.push(c_arg);
1512   }
1513 
1514   int temploc = -1;
1515   for (int ai = 0; ai < arg_order.length(); ai += 2) {
1516     int i = arg_order.at(ai);
1517     int c_arg = arg_order.at(ai + 1);
1518     __ block_comment(err_msg("move %d -> %d", i, c_arg));
1519     assert(c_arg != -1 && i != -1, "wrong order");
1520 #ifdef ASSERT
1521     if (in_regs[i].first()->is_Register()) {
1522       assert(!reg_destroyed[in_regs[i].first()->as_Register()->encoding()], "destroyed reg!");
1523     } else if (in_regs[i].first()->is_FloatRegister()) {
1524       assert(!freg_destroyed[in_regs[i].first()->as_FloatRegister()->encoding()], "destroyed reg!");
1525     }
1526     if (out_regs[c_arg].first()->is_Register()) {
1527       reg_destroyed[out_regs[c_arg].first()->as_Register()->encoding()] = true;
1528     } else if (out_regs[c_arg].first()->is_FloatRegister()) {
1529       freg_destroyed[out_regs[c_arg].first()->as_FloatRegister()->encoding()] = true;
1530     }
1531 #endif /* ASSERT */
1532     switch (in_sig_bt[i]) {
1533       case T_ARRAY:
1534       case T_OBJECT:
1535         object_move(masm, map, oop_handle_offset, stack_slots, in_regs[i], out_regs[c_arg],
1536                     ((i == 0) && (!is_static)),
1537                     &receiver_offset);
1538         int_args++;
1539         break;
1540       case T_VOID:
1541         break;
1542 
1543       case T_FLOAT:
1544         float_move(masm, in_regs[i], out_regs[c_arg]);
1545         float_args++;
1546         break;
1547 
1548       case T_DOUBLE:
1549         assert( i + 1 < total_in_args &&
1550                 in_sig_bt[i + 1] == T_VOID &&
1551                 out_sig_bt[c_arg+1] == T_VOID, "bad arg list");
1552         double_move(masm, in_regs[i], out_regs[c_arg]);
1553         float_args++;
1554         break;
1555 
1556       case T_LONG :
1557         long_move(masm, in_regs[i], out_regs[c_arg]);
1558         int_args++;
1559         break;
1560 
1561       case T_ADDRESS: assert(false, "found T_ADDRESS in java args");
1562 
1563       default:
1564         move32_64(masm, in_regs[i], out_regs[c_arg]);
1565         int_args++;
1566     }
1567   }
1568 
1569   // point c_arg at the first arg that is already loaded in case we
1570   // need to spill before we call out
1571   int c_arg = total_c_args - total_in_args;
1572 
1573   // Pre-load a static method's oop into c_rarg1.
1574   if (method->is_static()) {
1575 
1576     //  load oop into a register
1577     __ movoop(c_rarg1,
1578               JNIHandles::make_local(method->method_holder()->java_mirror()),
1579               /*immediate*/true);
1580 
1581     // Now handlize the static class mirror it's known not-null.
1582     __ str(c_rarg1, Address(sp, klass_offset));
1583     map->set_oop(VMRegImpl::stack2reg(klass_slot_offset));
1584 
1585     // Now get the handle
1586     __ lea(c_rarg1, Address(sp, klass_offset));
1587     // and protect the arg if we must spill
1588     c_arg--;
1589   }
1590 
1591   // Change state to native (we save the return address in the thread, since it might not
1592   // be pushed on the stack when we do a stack traversal).
1593   // We use the same pc/oopMap repeatedly when we call out
1594 
1595   Label native_return;
1596   __ set_last_Java_frame(sp, noreg, native_return, rscratch1);
1597 
1598   Label dtrace_method_entry, dtrace_method_entry_done;
1599   {
1600     uint64_t offset;
1601     __ adrp(rscratch1, ExternalAddress((address)&DTraceMethodProbes), offset);
1602     __ ldrb(rscratch1, Address(rscratch1, offset));
1603     __ cbnzw(rscratch1, dtrace_method_entry);
1604     __ bind(dtrace_method_entry_done);
1605   }
1606 
1607   // RedefineClasses() tracing support for obsolete method entry
1608   if (log_is_enabled(Trace, redefine, class, obsolete)) {
1609     // protect the args we've loaded
1610     save_args(masm, total_c_args, c_arg, out_regs);
1611     __ mov_metadata(c_rarg1, method());
1612     __ call_VM_leaf(
1613       CAST_FROM_FN_PTR(address, SharedRuntime::rc_trace_method_entry),
1614       rthread, c_rarg1);
1615     restore_args(masm, total_c_args, c_arg, out_regs);
1616   }
1617 
1618   // Lock a synchronized method
1619 
1620   // Register definitions used by locking and unlocking
1621 
1622   const Register swap_reg = r0;
1623   const Register obj_reg  = r19;  // Will contain the oop
1624   const Register lock_reg = r13;  // Address of compiler lock object (BasicLock)
1625   const Register old_hdr  = r13;  // value of old header at unlock time
1626   const Register tmp = lr;
1627 
1628   Label slow_path_lock;
1629   Label lock_done;
1630 
1631   if (method->is_synchronized()) {
1632 
1633     const int mark_word_offset = BasicLock::displaced_header_offset_in_bytes();
1634 
1635     // Get the handle (the 2nd argument)
1636     __ mov(oop_handle_reg, c_rarg1);
1637 
1638     // Get address of the box
1639 
1640     __ lea(lock_reg, Address(sp, lock_slot_offset * VMRegImpl::stack_slot_size));
1641 
1642     // Load the oop from the handle
1643     __ ldr(obj_reg, Address(oop_handle_reg, 0));
1644 
1645     if (!UseHeavyMonitors) {
1646       // Load (object->mark() | 1) into swap_reg %r0
1647       __ ldr(rscratch1, Address(obj_reg, oopDesc::mark_offset_in_bytes()));
1648       __ orr(swap_reg, rscratch1, 1);
1649 
1650       // Save (object->mark() | 1) into BasicLock's displaced header
1651       __ str(swap_reg, Address(lock_reg, mark_word_offset));
1652 
1653       // src -> dest iff dest == r0 else r0 <- dest
1654       { Label here;
1655         __ cmpxchg_obj_header(r0, lock_reg, obj_reg, rscratch1, lock_done, /*fallthrough*/NULL);
1656       }
1657 
1658       // Hmm should this move to the slow path code area???
1659 
1660       // Test if the oopMark is an obvious stack pointer, i.e.,
1661       //  1) (mark & 3) == 0, and
1662       //  2) sp <= mark < mark + os::pagesize()
1663       // These 3 tests can be done by evaluating the following
1664       // expression: ((mark - sp) & (3 - os::vm_page_size())),
1665       // assuming both stack pointer and pagesize have their
1666       // least significant 2 bits clear.
1667       // NOTE: the oopMark is in swap_reg %r0 as the result of cmpxchg
1668 
1669       __ sub(swap_reg, sp, swap_reg);
1670       __ neg(swap_reg, swap_reg);
1671       __ ands(swap_reg, swap_reg, 3 - os::vm_page_size());
1672 
1673       // Save the test result, for recursive case, the result is zero
1674       __ str(swap_reg, Address(lock_reg, mark_word_offset));
1675       __ br(Assembler::NE, slow_path_lock);
1676     } else {
1677       __ b(slow_path_lock);
1678     }
1679 
1680     // Slow path will re-enter here
1681     __ bind(lock_done);
1682   }
1683 
1684 
1685   // Finally just about ready to make the JNI call
1686 
1687   // get JNIEnv* which is first argument to native
1688   __ lea(c_rarg0, Address(rthread, in_bytes(JavaThread::jni_environment_offset())));
1689 
1690   // Now set thread in native
1691   __ mov(rscratch1, _thread_in_native);
1692   __ lea(rscratch2, Address(rthread, JavaThread::thread_state_offset()));
1693   __ stlrw(rscratch1, rscratch2);
1694 
1695   rt_call(masm, native_func);
1696 
1697   __ bind(native_return);
1698 
1699   intptr_t return_pc = (intptr_t) __ pc();
1700   oop_maps->add_gc_map(return_pc - start, map);
1701 
1702   // Unpack native results.
1703   switch (ret_type) {
1704   case T_BOOLEAN: __ c2bool(r0);                     break;
1705   case T_CHAR   : __ ubfx(r0, r0, 0, 16);            break;
1706   case T_BYTE   : __ sbfx(r0, r0, 0, 8);             break;
1707   case T_SHORT  : __ sbfx(r0, r0, 0, 16);            break;
1708   case T_INT    : __ sbfx(r0, r0, 0, 32);            break;
1709   case T_DOUBLE :
1710   case T_FLOAT  :
1711     // Result is in v0 we'll save as needed
1712     break;
1713   case T_ARRAY:                 // Really a handle
1714   case T_OBJECT:                // Really a handle
1715       break; // can't de-handlize until after safepoint check
1716   case T_VOID: break;
1717   case T_LONG: break;
1718   default       : ShouldNotReachHere();
1719   }
1720 
1721   Label safepoint_in_progress, safepoint_in_progress_done;
1722   Label after_transition;
1723 
1724   // Switch thread to "native transition" state before reading the synchronization state.
1725   // This additional state is necessary because reading and testing the synchronization
1726   // state is not atomic w.r.t. GC, as this scenario demonstrates:
1727   //     Java thread A, in _thread_in_native state, loads _not_synchronized and is preempted.
1728   //     VM thread changes sync state to synchronizing and suspends threads for GC.
1729   //     Thread A is resumed to finish this native method, but doesn't block here since it
1730   //     didn't see any synchronization is progress, and escapes.
1731   __ mov(rscratch1, _thread_in_native_trans);
1732 
1733   __ strw(rscratch1, Address(rthread, JavaThread::thread_state_offset()));
1734 
1735   // Force this write out before the read below
1736   __ dmb(Assembler::ISH);
1737 
1738   __ verify_sve_vector_length();
1739 
1740   // Check for safepoint operation in progress and/or pending suspend requests.
1741   {
1742     // We need an acquire here to ensure that any subsequent load of the
1743     // global SafepointSynchronize::_state flag is ordered after this load
1744     // of the thread-local polling word.  We don't want this poll to
1745     // return false (i.e. not safepointing) and a later poll of the global
1746     // SafepointSynchronize::_state spuriously to return true.
1747     //
1748     // This is to avoid a race when we're in a native->Java transition
1749     // racing the code which wakes up from a safepoint.
1750 
1751     __ safepoint_poll(safepoint_in_progress, true /* at_return */, true /* acquire */, false /* in_nmethod */);
1752     __ ldrw(rscratch1, Address(rthread, JavaThread::suspend_flags_offset()));
1753     __ cbnzw(rscratch1, safepoint_in_progress);
1754     __ bind(safepoint_in_progress_done);
1755   }
1756 
1757   // change thread state
1758   __ mov(rscratch1, _thread_in_Java);
1759   __ lea(rscratch2, Address(rthread, JavaThread::thread_state_offset()));
1760   __ stlrw(rscratch1, rscratch2);
1761   __ bind(after_transition);
1762 
1763   Label reguard;
1764   Label reguard_done;
1765   __ ldrb(rscratch1, Address(rthread, JavaThread::stack_guard_state_offset()));
1766   __ cmpw(rscratch1, StackOverflow::stack_guard_yellow_reserved_disabled);
1767   __ br(Assembler::EQ, reguard);
1768   __ bind(reguard_done);
1769 
1770   // native result if any is live
1771 
1772   // Unlock
1773   Label unlock_done;
1774   Label slow_path_unlock;
1775   if (method->is_synchronized()) {
1776 
1777     // Get locked oop from the handle we passed to jni
1778     __ ldr(obj_reg, Address(oop_handle_reg, 0));
1779 
1780     Label done;
1781 
1782     if (!UseHeavyMonitors) {
1783       // Simple recursive lock?
1784       __ ldr(rscratch1, Address(sp, lock_slot_offset * VMRegImpl::stack_slot_size));
1785       __ cbz(rscratch1, done);
1786     }
1787 
1788     // Must save r0 if if it is live now because cmpxchg must use it
1789     if (ret_type != T_FLOAT && ret_type != T_DOUBLE && ret_type != T_VOID) {
1790       save_native_result(masm, ret_type, stack_slots);
1791     }
1792 
1793     if (!UseHeavyMonitors) {
1794       // get address of the stack lock
1795       __ lea(r0, Address(sp, lock_slot_offset * VMRegImpl::stack_slot_size));
1796       //  get old displaced header
1797       __ ldr(old_hdr, Address(r0, 0));
1798 
1799       // Atomic swap old header if oop still contains the stack lock
1800       Label succeed;
1801       __ cmpxchg_obj_header(r0, old_hdr, obj_reg, rscratch1, succeed, &slow_path_unlock);
1802       __ bind(succeed);
1803     } else {
1804       __ b(slow_path_unlock);
1805     }
1806 
1807     // slow path re-enters here
1808     __ bind(unlock_done);
1809     if (ret_type != T_FLOAT && ret_type != T_DOUBLE && ret_type != T_VOID) {
1810       restore_native_result(masm, ret_type, stack_slots);
1811     }
1812 
1813     __ bind(done);
1814   }
1815 
1816   Label dtrace_method_exit, dtrace_method_exit_done;
1817   {
1818     uint64_t offset;
1819     __ adrp(rscratch1, ExternalAddress((address)&DTraceMethodProbes), offset);
1820     __ ldrb(rscratch1, Address(rscratch1, offset));
1821     __ cbnzw(rscratch1, dtrace_method_exit);
1822     __ bind(dtrace_method_exit_done);
1823   }
1824 
1825   __ reset_last_Java_frame(false);
1826 
1827   // Unbox oop result, e.g. JNIHandles::resolve result.
1828   if (is_reference_type(ret_type)) {
1829     __ resolve_jobject(r0, rthread, rscratch2);
1830   }
1831 
1832   if (CheckJNICalls) {
1833     // clear_pending_jni_exception_check
1834     __ str(zr, Address(rthread, JavaThread::pending_jni_exception_check_fn_offset()));
1835   }
1836 
1837   // reset handle block
1838   __ ldr(r2, Address(rthread, JavaThread::active_handles_offset()));
1839   __ str(zr, Address(r2, JNIHandleBlock::top_offset_in_bytes()));
1840 
1841   __ leave();
1842 
1843   // Any exception pending?
1844   __ ldr(rscratch1, Address(rthread, in_bytes(Thread::pending_exception_offset())));
1845   __ cbnz(rscratch1, exception_pending);
1846 
1847   // We're done
1848   __ ret(lr);
1849 
1850   // Unexpected paths are out of line and go here
1851 
1852   // forward the exception
1853   __ bind(exception_pending);
1854 
1855   // and forward the exception
1856   __ far_jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
1857 
1858   // Slow path locking & unlocking
1859   if (method->is_synchronized()) {
1860 
1861     __ block_comment("Slow path lock {");
1862     __ bind(slow_path_lock);
1863 
1864     // has last_Java_frame setup. No exceptions so do vanilla call not call_VM
1865     // args are (oop obj, BasicLock* lock, JavaThread* thread)
1866 
1867     // protect the args we've loaded
1868     save_args(masm, total_c_args, c_arg, out_regs);
1869 
1870     __ mov(c_rarg0, obj_reg);
1871     __ mov(c_rarg1, lock_reg);
1872     __ mov(c_rarg2, rthread);
1873 
1874     // Not a leaf but we have last_Java_frame setup as we want
1875     __ call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::complete_monitor_locking_C), 3);
1876     restore_args(masm, total_c_args, c_arg, out_regs);
1877 
1878 #ifdef ASSERT
1879     { Label L;
1880       __ ldr(rscratch1, Address(rthread, in_bytes(Thread::pending_exception_offset())));
1881       __ cbz(rscratch1, L);
1882       __ stop("no pending exception allowed on exit from monitorenter");
1883       __ bind(L);
1884     }
1885 #endif
1886     __ b(lock_done);
1887 
1888     __ block_comment("} Slow path lock");
1889 
1890     __ block_comment("Slow path unlock {");
1891     __ bind(slow_path_unlock);
1892 
1893     // If we haven't already saved the native result we must save it now as xmm registers
1894     // are still exposed.
1895 
1896     if (ret_type == T_FLOAT || ret_type == T_DOUBLE ) {
1897       save_native_result(masm, ret_type, stack_slots);
1898     }
1899 
1900     __ mov(c_rarg2, rthread);
1901     __ lea(c_rarg1, Address(sp, lock_slot_offset * VMRegImpl::stack_slot_size));
1902     __ mov(c_rarg0, obj_reg);
1903 
1904     // Save pending exception around call to VM (which contains an EXCEPTION_MARK)
1905     // NOTE that obj_reg == r19 currently
1906     __ ldr(r19, Address(rthread, in_bytes(Thread::pending_exception_offset())));
1907     __ str(zr, Address(rthread, in_bytes(Thread::pending_exception_offset())));
1908 
1909     rt_call(masm, CAST_FROM_FN_PTR(address, SharedRuntime::complete_monitor_unlocking_C));
1910 
1911 #ifdef ASSERT
1912     {
1913       Label L;
1914       __ ldr(rscratch1, Address(rthread, in_bytes(Thread::pending_exception_offset())));
1915       __ cbz(rscratch1, L);
1916       __ stop("no pending exception allowed on exit complete_monitor_unlocking_C");
1917       __ bind(L);
1918     }
1919 #endif /* ASSERT */
1920 
1921     __ str(r19, Address(rthread, in_bytes(Thread::pending_exception_offset())));
1922 
1923     if (ret_type == T_FLOAT || ret_type == T_DOUBLE ) {
1924       restore_native_result(masm, ret_type, stack_slots);
1925     }
1926     __ b(unlock_done);
1927 
1928     __ block_comment("} Slow path unlock");
1929 
1930   } // synchronized
1931 
1932   // SLOW PATH Reguard the stack if needed
1933 
1934   __ bind(reguard);
1935   save_native_result(masm, ret_type, stack_slots);
1936   rt_call(masm, CAST_FROM_FN_PTR(address, SharedRuntime::reguard_yellow_pages));
1937   restore_native_result(masm, ret_type, stack_slots);
1938   // and continue
1939   __ b(reguard_done);
1940 
1941   // SLOW PATH safepoint
1942   {
1943     __ block_comment("safepoint {");
1944     __ bind(safepoint_in_progress);
1945 
1946     // Don't use call_VM as it will see a possible pending exception and forward it
1947     // and never return here preventing us from clearing _last_native_pc down below.
1948     //
1949     save_native_result(masm, ret_type, stack_slots);
1950     __ mov(c_rarg0, rthread);
1951 #ifndef PRODUCT
1952   assert(frame::arg_reg_save_area_bytes == 0, "not expecting frame reg save area");
1953 #endif
1954     __ lea(rscratch1, RuntimeAddress(CAST_FROM_FN_PTR(address, JavaThread::check_special_condition_for_native_trans)));
1955     __ blr(rscratch1);
1956 
1957     // Restore any method result value
1958     restore_native_result(masm, ret_type, stack_slots);
1959 
1960     __ b(safepoint_in_progress_done);
1961     __ block_comment("} safepoint");
1962   }
1963 
1964   // SLOW PATH dtrace support
1965   {
1966     __ block_comment("dtrace entry {");
1967     __ bind(dtrace_method_entry);
1968 
1969     // We have all of the arguments setup at this point. We must not touch any register
1970     // argument registers at this point (what if we save/restore them there are no oop?
1971 
1972     save_args(masm, total_c_args, c_arg, out_regs);
1973     __ mov_metadata(c_rarg1, method());
1974     __ call_VM_leaf(
1975       CAST_FROM_FN_PTR(address, SharedRuntime::dtrace_method_entry),
1976       rthread, c_rarg1);
1977     restore_args(masm, total_c_args, c_arg, out_regs);
1978     __ b(dtrace_method_entry_done);
1979     __ block_comment("} dtrace entry");
1980   }
1981 
1982   {
1983     __ block_comment("dtrace exit {");
1984     __ bind(dtrace_method_exit);
1985     save_native_result(masm, ret_type, stack_slots);
1986     __ mov_metadata(c_rarg1, method());
1987     __ call_VM_leaf(
1988          CAST_FROM_FN_PTR(address, SharedRuntime::dtrace_method_exit),
1989          rthread, c_rarg1);
1990     restore_native_result(masm, ret_type, stack_slots);
1991     __ b(dtrace_method_exit_done);
1992     __ block_comment("} dtrace exit");
1993   }
1994 
1995 
1996   __ flush();
1997 
1998   nmethod *nm = nmethod::new_native_nmethod(method,
1999                                             compile_id,
2000                                             masm->code(),
2001                                             vep_offset,
2002                                             frame_complete,
2003                                             stack_slots / VMRegImpl::slots_per_word,
2004                                             (is_static ? in_ByteSize(klass_offset) : in_ByteSize(receiver_offset)),
2005                                             in_ByteSize(lock_slot_offset*VMRegImpl::stack_slot_size),
2006                                             oop_maps);
2007 
2008   return nm;
2009 }
2010 
2011 // this function returns the adjust size (in number of words) to a c2i adapter
2012 // activation for use during deoptimization
2013 int Deoptimization::last_frame_adjust(int callee_parameters, int callee_locals) {
2014   assert(callee_locals >= callee_parameters,
2015           "test and remove; got more parms than locals");
2016   if (callee_locals < callee_parameters)
2017     return 0;                   // No adjustment for negative locals
2018   int diff = (callee_locals - callee_parameters) * Interpreter::stackElementWords;
2019   // diff is counted in stack words
2020   return align_up(diff, 2);
2021 }
2022 
2023 
2024 //------------------------------generate_deopt_blob----------------------------
2025 void SharedRuntime::generate_deopt_blob() {
2026   // Allocate space for the code
2027   ResourceMark rm;
2028   // Setup code generation tools
2029   int pad = 0;
2030 #if INCLUDE_JVMCI
2031   if (EnableJVMCI) {
2032     pad += 512; // Increase the buffer size when compiling for JVMCI
2033   }
2034 #endif
2035   CodeBuffer buffer("deopt_blob", 2048+pad, 1024);
2036   MacroAssembler* masm = new MacroAssembler(&buffer);
2037   int frame_size_in_words;
2038   OopMap* map = NULL;
2039   OopMapSet *oop_maps = new OopMapSet();
2040   RegisterSaver reg_save(COMPILER2_OR_JVMCI != 0);
2041 
2042   // -------------
2043   // This code enters when returning to a de-optimized nmethod.  A return
2044   // address has been pushed on the the stack, and return values are in
2045   // registers.
2046   // If we are doing a normal deopt then we were called from the patched
2047   // nmethod from the point we returned to the nmethod. So the return
2048   // address on the stack is wrong by NativeCall::instruction_size
2049   // We will adjust the value so it looks like we have the original return
2050   // address on the stack (like when we eagerly deoptimized).
2051   // In the case of an exception pending when deoptimizing, we enter
2052   // with a return address on the stack that points after the call we patched
2053   // into the exception handler. We have the following register state from,
2054   // e.g., the forward exception stub (see stubGenerator_x86_64.cpp).
2055   //    r0: exception oop
2056   //    r19: exception handler
2057   //    r3: throwing pc
2058   // So in this case we simply jam r3 into the useless return address and
2059   // the stack looks just like we want.
2060   //
2061   // At this point we need to de-opt.  We save the argument return
2062   // registers.  We call the first C routine, fetch_unroll_info().  This
2063   // routine captures the return values and returns a structure which
2064   // describes the current frame size and the sizes of all replacement frames.
2065   // The current frame is compiled code and may contain many inlined
2066   // functions, each with their own JVM state.  We pop the current frame, then
2067   // push all the new frames.  Then we call the C routine unpack_frames() to
2068   // populate these frames.  Finally unpack_frames() returns us the new target
2069   // address.  Notice that callee-save registers are BLOWN here; they have
2070   // already been captured in the vframeArray at the time the return PC was
2071   // patched.
2072   address start = __ pc();
2073   Label cont;
2074 
2075   // Prolog for non exception case!
2076 
2077   // Save everything in sight.
2078   map = reg_save.save_live_registers(masm, 0, &frame_size_in_words);
2079 
2080   // Normal deoptimization.  Save exec mode for unpack_frames.
2081   __ movw(rcpool, Deoptimization::Unpack_deopt); // callee-saved
2082   __ b(cont);
2083 
2084   int reexecute_offset = __ pc() - start;
2085 #if INCLUDE_JVMCI && !defined(COMPILER1)
2086   if (EnableJVMCI && UseJVMCICompiler) {
2087     // JVMCI does not use this kind of deoptimization
2088     __ should_not_reach_here();
2089   }
2090 #endif
2091 
2092   // Reexecute case
2093   // return address is the pc describes what bci to do re-execute at
2094 
2095   // No need to update map as each call to save_live_registers will produce identical oopmap
2096   (void) reg_save.save_live_registers(masm, 0, &frame_size_in_words);
2097 
2098   __ movw(rcpool, Deoptimization::Unpack_reexecute); // callee-saved
2099   __ b(cont);
2100 
2101 #if INCLUDE_JVMCI
2102   Label after_fetch_unroll_info_call;
2103   int implicit_exception_uncommon_trap_offset = 0;
2104   int uncommon_trap_offset = 0;
2105 
2106   if (EnableJVMCI) {
2107     implicit_exception_uncommon_trap_offset = __ pc() - start;
2108 
2109     __ ldr(lr, Address(rthread, in_bytes(JavaThread::jvmci_implicit_exception_pc_offset())));
2110     __ str(zr, Address(rthread, in_bytes(JavaThread::jvmci_implicit_exception_pc_offset())));
2111 
2112     uncommon_trap_offset = __ pc() - start;
2113 
2114     // Save everything in sight.
2115     reg_save.save_live_registers(masm, 0, &frame_size_in_words);
2116     // fetch_unroll_info needs to call last_java_frame()
2117     Label retaddr;
2118     __ set_last_Java_frame(sp, noreg, retaddr, rscratch1);
2119 
2120     __ ldrw(c_rarg1, Address(rthread, in_bytes(JavaThread::pending_deoptimization_offset())));
2121     __ movw(rscratch1, -1);
2122     __ strw(rscratch1, Address(rthread, in_bytes(JavaThread::pending_deoptimization_offset())));
2123 
2124     __ movw(rcpool, (int32_t)Deoptimization::Unpack_reexecute);
2125     __ mov(c_rarg0, rthread);
2126     __ movw(c_rarg2, rcpool); // exec mode
2127     __ lea(rscratch1,
2128            RuntimeAddress(CAST_FROM_FN_PTR(address,
2129                                            Deoptimization::uncommon_trap)));
2130     __ blr(rscratch1);
2131     __ bind(retaddr);
2132     oop_maps->add_gc_map( __ pc()-start, map->deep_copy());
2133 
2134     __ reset_last_Java_frame(false);
2135 
2136     __ b(after_fetch_unroll_info_call);
2137   } // EnableJVMCI
2138 #endif // INCLUDE_JVMCI
2139 
2140   int exception_offset = __ pc() - start;
2141 
2142   // Prolog for exception case
2143 
2144   // all registers are dead at this entry point, except for r0, and
2145   // r3 which contain the exception oop and exception pc
2146   // respectively.  Set them in TLS and fall thru to the
2147   // unpack_with_exception_in_tls entry point.
2148 
2149   __ str(r3, Address(rthread, JavaThread::exception_pc_offset()));
2150   __ str(r0, Address(rthread, JavaThread::exception_oop_offset()));
2151 
2152   int exception_in_tls_offset = __ pc() - start;
2153 
2154   // new implementation because exception oop is now passed in JavaThread
2155 
2156   // Prolog for exception case
2157   // All registers must be preserved because they might be used by LinearScan
2158   // Exceptiop oop and throwing PC are passed in JavaThread
2159   // tos: stack at point of call to method that threw the exception (i.e. only
2160   // args are on the stack, no return address)
2161 
2162   // The return address pushed by save_live_registers will be patched
2163   // later with the throwing pc. The correct value is not available
2164   // now because loading it from memory would destroy registers.
2165 
2166   // NB: The SP at this point must be the SP of the method that is
2167   // being deoptimized.  Deoptimization assumes that the frame created
2168   // here by save_live_registers is immediately below the method's SP.
2169   // This is a somewhat fragile mechanism.
2170 
2171   // Save everything in sight.
2172   map = reg_save.save_live_registers(masm, 0, &frame_size_in_words);
2173 
2174   // Now it is safe to overwrite any register
2175 
2176   // Deopt during an exception.  Save exec mode for unpack_frames.
2177   __ mov(rcpool, Deoptimization::Unpack_exception); // callee-saved
2178 
2179   // load throwing pc from JavaThread and patch it as the return address
2180   // of the current frame. Then clear the field in JavaThread
2181 
2182   __ ldr(r3, Address(rthread, JavaThread::exception_pc_offset()));
2183   __ str(r3, Address(rfp, wordSize));
2184   __ str(zr, Address(rthread, JavaThread::exception_pc_offset()));
2185 
2186 #ifdef ASSERT
2187   // verify that there is really an exception oop in JavaThread
2188   __ ldr(r0, Address(rthread, JavaThread::exception_oop_offset()));
2189   __ verify_oop(r0);
2190 
2191   // verify that there is no pending exception
2192   Label no_pending_exception;
2193   __ ldr(rscratch1, Address(rthread, Thread::pending_exception_offset()));
2194   __ cbz(rscratch1, no_pending_exception);
2195   __ stop("must not have pending exception here");
2196   __ bind(no_pending_exception);
2197 #endif
2198 
2199   __ bind(cont);
2200 
2201   // Call C code.  Need thread and this frame, but NOT official VM entry
2202   // crud.  We cannot block on this call, no GC can happen.
2203   //
2204   // UnrollBlock* fetch_unroll_info(JavaThread* thread)
2205 
2206   // fetch_unroll_info needs to call last_java_frame().
2207 
2208   Label retaddr;
2209   __ set_last_Java_frame(sp, noreg, retaddr, rscratch1);
2210 #ifdef ASSERT0
2211   { Label L;
2212     __ ldr(rscratch1, Address(rthread,
2213                               JavaThread::last_Java_fp_offset()));
2214     __ cbz(rscratch1, L);
2215     __ stop("SharedRuntime::generate_deopt_blob: last_Java_fp not cleared");
2216     __ bind(L);
2217   }
2218 #endif // ASSERT
2219   __ mov(c_rarg0, rthread);
2220   __ mov(c_rarg1, rcpool);
2221   __ lea(rscratch1, RuntimeAddress(CAST_FROM_FN_PTR(address, Deoptimization::fetch_unroll_info)));
2222   __ blr(rscratch1);
2223   __ bind(retaddr);
2224 
2225   // Need to have an oopmap that tells fetch_unroll_info where to
2226   // find any register it might need.
2227   oop_maps->add_gc_map(__ pc() - start, map);
2228 
2229   __ reset_last_Java_frame(false);
2230 
2231 #if INCLUDE_JVMCI
2232   if (EnableJVMCI) {
2233     __ bind(after_fetch_unroll_info_call);
2234   }
2235 #endif
2236 
2237   // Load UnrollBlock* into r5
2238   __ mov(r5, r0);
2239 
2240   __ ldrw(rcpool, Address(r5, Deoptimization::UnrollBlock::unpack_kind_offset_in_bytes()));
2241    Label noException;
2242   __ cmpw(rcpool, Deoptimization::Unpack_exception);   // Was exception pending?
2243   __ br(Assembler::NE, noException);
2244   __ ldr(r0, Address(rthread, JavaThread::exception_oop_offset()));
2245   // QQQ this is useless it was NULL above
2246   __ ldr(r3, Address(rthread, JavaThread::exception_pc_offset()));
2247   __ str(zr, Address(rthread, JavaThread::exception_oop_offset()));
2248   __ str(zr, Address(rthread, JavaThread::exception_pc_offset()));
2249 
2250   __ verify_oop(r0);
2251 
2252   // Overwrite the result registers with the exception results.
2253   __ str(r0, Address(sp, reg_save.r0_offset_in_bytes()));
2254   // I think this is useless
2255   // __ str(r3, Address(sp, RegisterSaver::r3_offset_in_bytes()));
2256 
2257   __ bind(noException);
2258 
2259   // Only register save data is on the stack.
2260   // Now restore the result registers.  Everything else is either dead
2261   // or captured in the vframeArray.
2262 
2263   // Restore fp result register
2264   __ ldrd(v0, Address(sp, reg_save.v0_offset_in_bytes()));
2265   // Restore integer result register
2266   __ ldr(r0, Address(sp, reg_save.r0_offset_in_bytes()));
2267 
2268   // Pop all of the register save area off the stack
2269   __ add(sp, sp, frame_size_in_words * wordSize);
2270 
2271   // All of the register save area has been popped of the stack. Only the
2272   // return address remains.
2273 
2274   // Pop all the frames we must move/replace.
2275   //
2276   // Frame picture (youngest to oldest)
2277   // 1: self-frame (no frame link)
2278   // 2: deopting frame  (no frame link)
2279   // 3: caller of deopting frame (could be compiled/interpreted).
2280   //
2281   // Note: by leaving the return address of self-frame on the stack
2282   // and using the size of frame 2 to adjust the stack
2283   // when we are done the return to frame 3 will still be on the stack.
2284 
2285   // Pop deoptimized frame
2286   __ ldrw(r2, Address(r5, Deoptimization::UnrollBlock::size_of_deoptimized_frame_offset_in_bytes()));
2287   __ sub(r2, r2, 2 * wordSize);
2288   __ add(sp, sp, r2);
2289   __ ldp(rfp, lr, __ post(sp, 2 * wordSize));
2290   // LR should now be the return address to the caller (3)
2291 
2292 #ifdef ASSERT
2293   // Compilers generate code that bang the stack by as much as the
2294   // interpreter would need. So this stack banging should never
2295   // trigger a fault. Verify that it does not on non product builds.
2296   __ ldrw(r19, Address(r5, Deoptimization::UnrollBlock::total_frame_sizes_offset_in_bytes()));
2297   __ bang_stack_size(r19, r2);
2298 #endif
2299   // Load address of array of frame pcs into r2
2300   __ ldr(r2, Address(r5, Deoptimization::UnrollBlock::frame_pcs_offset_in_bytes()));
2301 
2302   // Trash the old pc
2303   // __ addptr(sp, wordSize);  FIXME ????
2304 
2305   // Load address of array of frame sizes into r4
2306   __ ldr(r4, Address(r5, Deoptimization::UnrollBlock::frame_sizes_offset_in_bytes()));
2307 
2308   // Load counter into r3
2309   __ ldrw(r3, Address(r5, Deoptimization::UnrollBlock::number_of_frames_offset_in_bytes()));
2310 
2311   // Now adjust the caller's stack to make up for the extra locals
2312   // but record the original sp so that we can save it in the skeletal interpreter
2313   // frame and the stack walking of interpreter_sender will get the unextended sp
2314   // value and not the "real" sp value.
2315 
2316   const Register sender_sp = r6;
2317 
2318   __ mov(sender_sp, sp);
2319   __ ldrw(r19, Address(r5,
2320                        Deoptimization::UnrollBlock::
2321                        caller_adjustment_offset_in_bytes()));
2322   __ sub(sp, sp, r19);
2323 
2324   // Push interpreter frames in a loop
2325   __ mov(rscratch1, (uint64_t)0xDEADDEAD);        // Make a recognizable pattern
2326   __ mov(rscratch2, rscratch1);
2327   Label loop;
2328   __ bind(loop);
2329   __ ldr(r19, Address(__ post(r4, wordSize)));          // Load frame size
2330   __ sub(r19, r19, 2*wordSize);           // We'll push pc and fp by hand
2331   __ ldr(lr, Address(__ post(r2, wordSize)));  // Load pc
2332   __ enter();                           // Save old & set new fp
2333   __ sub(sp, sp, r19);                  // Prolog
2334   // This value is corrected by layout_activation_impl
2335   __ str(zr, Address(rfp, frame::interpreter_frame_last_sp_offset * wordSize));
2336   __ str(sender_sp, Address(rfp, frame::interpreter_frame_sender_sp_offset * wordSize)); // Make it walkable
2337   __ mov(sender_sp, sp);               // Pass sender_sp to next frame
2338   __ sub(r3, r3, 1);                   // Decrement counter
2339   __ cbnz(r3, loop);
2340 
2341     // Re-push self-frame
2342   __ ldr(lr, Address(r2));
2343   __ enter();
2344 
2345   // Allocate a full sized register save area.  We subtract 2 because
2346   // enter() just pushed 2 words
2347   __ sub(sp, sp, (frame_size_in_words - 2) * wordSize);
2348 
2349   // Restore frame locals after moving the frame
2350   __ strd(v0, Address(sp, reg_save.v0_offset_in_bytes()));
2351   __ str(r0, Address(sp, reg_save.r0_offset_in_bytes()));
2352 
2353   // Call C code.  Need thread but NOT official VM entry
2354   // crud.  We cannot block on this call, no GC can happen.  Call should
2355   // restore return values to their stack-slots with the new SP.
2356   //
2357   // void Deoptimization::unpack_frames(JavaThread* thread, int exec_mode)
2358 
2359   // Use rfp because the frames look interpreted now
2360   // Don't need the precise return PC here, just precise enough to point into this code blob.
2361   address the_pc = __ pc();
2362   __ set_last_Java_frame(sp, rfp, the_pc, rscratch1);
2363 
2364   __ mov(c_rarg0, rthread);
2365   __ movw(c_rarg1, rcpool); // second arg: exec_mode
2366   __ lea(rscratch1, RuntimeAddress(CAST_FROM_FN_PTR(address, Deoptimization::unpack_frames)));
2367   __ blr(rscratch1);
2368 
2369   // Set an oopmap for the call site
2370   // Use the same PC we used for the last java frame
2371   oop_maps->add_gc_map(the_pc - start,
2372                        new OopMap( frame_size_in_words, 0 ));
2373 
2374   // Clear fp AND pc
2375   __ reset_last_Java_frame(true);
2376 
2377   // Collect return values
2378   __ ldrd(v0, Address(sp, reg_save.v0_offset_in_bytes()));
2379   __ ldr(r0, Address(sp, reg_save.r0_offset_in_bytes()));
2380   // I think this is useless (throwing pc?)
2381   // __ ldr(r3, Address(sp, RegisterSaver::r3_offset_in_bytes()));
2382 
2383   // Pop self-frame.
2384   __ leave();                           // Epilog
2385 
2386   // Jump to interpreter
2387   __ ret(lr);
2388 
2389   // Make sure all code is generated
2390   masm->flush();
2391 
2392   _deopt_blob = DeoptimizationBlob::create(&buffer, oop_maps, 0, exception_offset, reexecute_offset, frame_size_in_words);
2393   _deopt_blob->set_unpack_with_exception_in_tls_offset(exception_in_tls_offset);
2394 #if INCLUDE_JVMCI
2395   if (EnableJVMCI) {
2396     _deopt_blob->set_uncommon_trap_offset(uncommon_trap_offset);
2397     _deopt_blob->set_implicit_exception_uncommon_trap_offset(implicit_exception_uncommon_trap_offset);
2398   }
2399 #endif
2400 }
2401 
2402 // Number of stack slots between incoming argument block and the start of
2403 // a new frame.  The PROLOG must add this many slots to the stack.  The
2404 // EPILOG must remove this many slots. aarch64 needs two slots for
2405 // return address and fp.
2406 // TODO think this is correct but check
2407 uint SharedRuntime::in_preserve_stack_slots() {
2408   return 4;
2409 }
2410 
2411 uint SharedRuntime::out_preserve_stack_slots() {
2412   return 0;
2413 }
2414 
2415 #ifdef COMPILER2
2416 //------------------------------generate_uncommon_trap_blob--------------------
2417 void SharedRuntime::generate_uncommon_trap_blob() {
2418   // Allocate space for the code
2419   ResourceMark rm;
2420   // Setup code generation tools
2421   CodeBuffer buffer("uncommon_trap_blob", 2048, 1024);
2422   MacroAssembler* masm = new MacroAssembler(&buffer);
2423 
2424   assert(SimpleRuntimeFrame::framesize % 4 == 0, "sp not 16-byte aligned");
2425 
2426   address start = __ pc();
2427 
2428   // Push self-frame.  We get here with a return address in LR
2429   // and sp should be 16 byte aligned
2430   // push rfp and retaddr by hand
2431   __ stp(rfp, lr, Address(__ pre(sp, -2 * wordSize)));
2432   // we don't expect an arg reg save area
2433 #ifndef PRODUCT
2434   assert(frame::arg_reg_save_area_bytes == 0, "not expecting frame reg save area");
2435 #endif
2436   // compiler left unloaded_class_index in j_rarg0 move to where the
2437   // runtime expects it.
2438   if (c_rarg1 != j_rarg0) {
2439     __ movw(c_rarg1, j_rarg0);
2440   }
2441 
2442   // we need to set the past SP to the stack pointer of the stub frame
2443   // and the pc to the address where this runtime call will return
2444   // although actually any pc in this code blob will do).
2445   Label retaddr;
2446   __ set_last_Java_frame(sp, noreg, retaddr, rscratch1);
2447 
2448   // Call C code.  Need thread but NOT official VM entry
2449   // crud.  We cannot block on this call, no GC can happen.  Call should
2450   // capture callee-saved registers as well as return values.
2451   // Thread is in rdi already.
2452   //
2453   // UnrollBlock* uncommon_trap(JavaThread* thread, jint unloaded_class_index);
2454   //
2455   // n.b. 2 gp args, 0 fp args, integral return type
2456 
2457   __ mov(c_rarg0, rthread);
2458   __ movw(c_rarg2, (unsigned)Deoptimization::Unpack_uncommon_trap);
2459   __ lea(rscratch1,
2460          RuntimeAddress(CAST_FROM_FN_PTR(address,
2461                                          Deoptimization::uncommon_trap)));
2462   __ blr(rscratch1);
2463   __ bind(retaddr);
2464 
2465   // Set an oopmap for the call site
2466   OopMapSet* oop_maps = new OopMapSet();
2467   OopMap* map = new OopMap(SimpleRuntimeFrame::framesize, 0);
2468 
2469   // location of rfp is known implicitly by the frame sender code
2470 
2471   oop_maps->add_gc_map(__ pc() - start, map);
2472 
2473   __ reset_last_Java_frame(false);
2474 
2475   // move UnrollBlock* into r4
2476   __ mov(r4, r0);
2477 
2478 #ifdef ASSERT
2479   { Label L;
2480     __ ldrw(rscratch1, Address(r4, Deoptimization::UnrollBlock::unpack_kind_offset_in_bytes()));
2481     __ cmpw(rscratch1, (unsigned)Deoptimization::Unpack_uncommon_trap);
2482     __ br(Assembler::EQ, L);
2483     __ stop("SharedRuntime::generate_deopt_blob: last_Java_fp not cleared");
2484     __ bind(L);
2485   }
2486 #endif
2487 
2488   // Pop all the frames we must move/replace.
2489   //
2490   // Frame picture (youngest to oldest)
2491   // 1: self-frame (no frame link)
2492   // 2: deopting frame  (no frame link)
2493   // 3: caller of deopting frame (could be compiled/interpreted).
2494 
2495   // Pop self-frame.  We have no frame, and must rely only on r0 and sp.
2496   __ add(sp, sp, (SimpleRuntimeFrame::framesize) << LogBytesPerInt); // Epilog!
2497 
2498   // Pop deoptimized frame (int)
2499   __ ldrw(r2, Address(r4,
2500                       Deoptimization::UnrollBlock::
2501                       size_of_deoptimized_frame_offset_in_bytes()));
2502   __ sub(r2, r2, 2 * wordSize);
2503   __ add(sp, sp, r2);
2504   __ ldp(rfp, lr, __ post(sp, 2 * wordSize));
2505   // LR should now be the return address to the caller (3) frame
2506 
2507 #ifdef ASSERT
2508   // Compilers generate code that bang the stack by as much as the
2509   // interpreter would need. So this stack banging should never
2510   // trigger a fault. Verify that it does not on non product builds.
2511   __ ldrw(r1, Address(r4,
2512                       Deoptimization::UnrollBlock::
2513                       total_frame_sizes_offset_in_bytes()));
2514   __ bang_stack_size(r1, r2);
2515 #endif
2516 
2517   // Load address of array of frame pcs into r2 (address*)
2518   __ ldr(r2, Address(r4,
2519                      Deoptimization::UnrollBlock::frame_pcs_offset_in_bytes()));
2520 
2521   // Load address of array of frame sizes into r5 (intptr_t*)
2522   __ ldr(r5, Address(r4,
2523                      Deoptimization::UnrollBlock::
2524                      frame_sizes_offset_in_bytes()));
2525 
2526   // Counter
2527   __ ldrw(r3, Address(r4,
2528                       Deoptimization::UnrollBlock::
2529                       number_of_frames_offset_in_bytes())); // (int)
2530 
2531   // Now adjust the caller's stack to make up for the extra locals but
2532   // record the original sp so that we can save it in the skeletal
2533   // interpreter frame and the stack walking of interpreter_sender
2534   // will get the unextended sp value and not the "real" sp value.
2535 
2536   const Register sender_sp = r8;
2537 
2538   __ mov(sender_sp, sp);
2539   __ ldrw(r1, Address(r4,
2540                       Deoptimization::UnrollBlock::
2541                       caller_adjustment_offset_in_bytes())); // (int)
2542   __ sub(sp, sp, r1);
2543 
2544   // Push interpreter frames in a loop
2545   Label loop;
2546   __ bind(loop);
2547   __ ldr(r1, Address(r5, 0));       // Load frame size
2548   __ sub(r1, r1, 2 * wordSize);     // We'll push pc and rfp by hand
2549   __ ldr(lr, Address(r2, 0));       // Save return address
2550   __ enter();                       // and old rfp & set new rfp
2551   __ sub(sp, sp, r1);               // Prolog
2552   __ str(sender_sp, Address(rfp, frame::interpreter_frame_sender_sp_offset * wordSize)); // Make it walkable
2553   // This value is corrected by layout_activation_impl
2554   __ str(zr, Address(rfp, frame::interpreter_frame_last_sp_offset * wordSize));
2555   __ mov(sender_sp, sp);          // Pass sender_sp to next frame
2556   __ add(r5, r5, wordSize);       // Bump array pointer (sizes)
2557   __ add(r2, r2, wordSize);       // Bump array pointer (pcs)
2558   __ subsw(r3, r3, 1);            // Decrement counter
2559   __ br(Assembler::GT, loop);
2560   __ ldr(lr, Address(r2, 0));     // save final return address
2561   // Re-push self-frame
2562   __ enter();                     // & old rfp & set new rfp
2563 
2564   // Use rfp because the frames look interpreted now
2565   // Save "the_pc" since it cannot easily be retrieved using the last_java_SP after we aligned SP.
2566   // Don't need the precise return PC here, just precise enough to point into this code blob.
2567   address the_pc = __ pc();
2568   __ set_last_Java_frame(sp, rfp, the_pc, rscratch1);
2569 
2570   // Call C code.  Need thread but NOT official VM entry
2571   // crud.  We cannot block on this call, no GC can happen.  Call should
2572   // restore return values to their stack-slots with the new SP.
2573   // Thread is in rdi already.
2574   //
2575   // BasicType unpack_frames(JavaThread* thread, int exec_mode);
2576   //
2577   // n.b. 2 gp args, 0 fp args, integral return type
2578 
2579   // sp should already be aligned
2580   __ mov(c_rarg0, rthread);
2581   __ movw(c_rarg1, (unsigned)Deoptimization::Unpack_uncommon_trap);
2582   __ lea(rscratch1, RuntimeAddress(CAST_FROM_FN_PTR(address, Deoptimization::unpack_frames)));
2583   __ blr(rscratch1);
2584 
2585   // Set an oopmap for the call site
2586   // Use the same PC we used for the last java frame
2587   oop_maps->add_gc_map(the_pc - start, new OopMap(SimpleRuntimeFrame::framesize, 0));
2588 
2589   // Clear fp AND pc
2590   __ reset_last_Java_frame(true);
2591 
2592   // Pop self-frame.
2593   __ leave();                 // Epilog
2594 
2595   // Jump to interpreter
2596   __ ret(lr);
2597 
2598   // Make sure all code is generated
2599   masm->flush();
2600 
2601   _uncommon_trap_blob =  UncommonTrapBlob::create(&buffer, oop_maps,
2602                                                  SimpleRuntimeFrame::framesize >> 1);
2603 }
2604 #endif // COMPILER2
2605 
2606 
2607 //------------------------------generate_handler_blob------
2608 //
2609 // Generate a special Compile2Runtime blob that saves all registers,
2610 // and setup oopmap.
2611 //
2612 SafepointBlob* SharedRuntime::generate_handler_blob(address call_ptr, int poll_type) {
2613   ResourceMark rm;
2614   OopMapSet *oop_maps = new OopMapSet();
2615   OopMap* map;
2616 
2617   // Allocate space for the code.  Setup code generation tools.
2618   CodeBuffer buffer("handler_blob", 2048, 1024);
2619   MacroAssembler* masm = new MacroAssembler(&buffer);
2620 
2621   address start   = __ pc();
2622   address call_pc = NULL;
2623   int frame_size_in_words;
2624   bool cause_return = (poll_type == POLL_AT_RETURN);
2625   RegisterSaver reg_save(poll_type == POLL_AT_VECTOR_LOOP /* save_vectors */);
2626 
2627   // Save Integer and Float registers.
2628   map = reg_save.save_live_registers(masm, 0, &frame_size_in_words);
2629 
2630   // The following is basically a call_VM.  However, we need the precise
2631   // address of the call in order to generate an oopmap. Hence, we do all the
2632   // work outselves.
2633 
2634   Label retaddr;
2635   __ set_last_Java_frame(sp, noreg, retaddr, rscratch1);
2636 
2637   // The return address must always be correct so that frame constructor never
2638   // sees an invalid pc.
2639 
2640   if (!cause_return) {
2641     // overwrite the return address pushed by save_live_registers
2642     // Additionally, r20 is a callee-saved register so we can look at
2643     // it later to determine if someone changed the return address for
2644     // us!
2645     __ ldr(r20, Address(rthread, JavaThread::saved_exception_pc_offset()));
2646     __ str(r20, Address(rfp, wordSize));
2647   }
2648 
2649   // Do the call
2650   __ mov(c_rarg0, rthread);
2651   __ lea(rscratch1, RuntimeAddress(call_ptr));
2652   __ blr(rscratch1);
2653   __ bind(retaddr);
2654 
2655   // Set an oopmap for the call site.  This oopmap will map all
2656   // oop-registers and debug-info registers as callee-saved.  This
2657   // will allow deoptimization at this safepoint to find all possible
2658   // debug-info recordings, as well as let GC find all oops.
2659 
2660   oop_maps->add_gc_map( __ pc() - start, map);
2661 
2662   Label noException;
2663 
2664   __ reset_last_Java_frame(false);
2665 
2666   __ membar(Assembler::LoadLoad | Assembler::LoadStore);
2667 
2668   __ ldr(rscratch1, Address(rthread, Thread::pending_exception_offset()));
2669   __ cbz(rscratch1, noException);
2670 
2671   // Exception pending
2672 
2673   reg_save.restore_live_registers(masm);
2674 
2675   __ far_jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
2676 
2677   // No exception case
2678   __ bind(noException);
2679 
2680   Label no_adjust, bail;
2681   if (!cause_return) {
2682     // If our stashed return pc was modified by the runtime we avoid touching it
2683     __ ldr(rscratch1, Address(rfp, wordSize));
2684     __ cmp(r20, rscratch1);
2685     __ br(Assembler::NE, no_adjust);
2686 
2687 #ifdef ASSERT
2688     // Verify the correct encoding of the poll we're about to skip.
2689     // See NativeInstruction::is_ldrw_to_zr()
2690     __ ldrw(rscratch1, Address(r20));
2691     __ ubfx(rscratch2, rscratch1, 22, 10);
2692     __ cmpw(rscratch2, 0b1011100101);
2693     __ br(Assembler::NE, bail);
2694     __ ubfx(rscratch2, rscratch1, 0, 5);
2695     __ cmpw(rscratch2, 0b11111);
2696     __ br(Assembler::NE, bail);
2697 #endif
2698     // Adjust return pc forward to step over the safepoint poll instruction
2699     __ add(r20, r20, NativeInstruction::instruction_size);
2700     __ str(r20, Address(rfp, wordSize));
2701   }
2702 
2703   __ bind(no_adjust);
2704   // Normal exit, restore registers and exit.
2705   reg_save.restore_live_registers(masm);
2706 
2707   __ ret(lr);
2708 
2709 #ifdef ASSERT
2710   __ bind(bail);
2711   __ stop("Attempting to adjust pc to skip safepoint poll but the return point is not what we expected");
2712 #endif
2713 
2714   // Make sure all code is generated
2715   masm->flush();
2716 
2717   // Fill-out other meta info
2718   return SafepointBlob::create(&buffer, oop_maps, frame_size_in_words);
2719 }
2720 
2721 //
2722 // generate_resolve_blob - call resolution (static/virtual/opt-virtual/ic-miss
2723 //
2724 // Generate a stub that calls into vm to find out the proper destination
2725 // of a java call. All the argument registers are live at this point
2726 // but since this is generic code we don't know what they are and the caller
2727 // must do any gc of the args.
2728 //
2729 RuntimeStub* SharedRuntime::generate_resolve_blob(address destination, const char* name) {
2730   assert (StubRoutines::forward_exception_entry() != NULL, "must be generated before");
2731 
2732   // allocate space for the code
2733   ResourceMark rm;
2734 
2735   CodeBuffer buffer(name, 1000, 512);
2736   MacroAssembler* masm                = new MacroAssembler(&buffer);
2737 
2738   int frame_size_in_words;
2739   RegisterSaver reg_save(false /* save_vectors */);
2740 
2741   OopMapSet *oop_maps = new OopMapSet();
2742   OopMap* map = NULL;
2743 
2744   int start = __ offset();
2745 
2746   map = reg_save.save_live_registers(masm, 0, &frame_size_in_words);
2747 
2748   int frame_complete = __ offset();
2749 
2750   {
2751     Label retaddr;
2752     __ set_last_Java_frame(sp, noreg, retaddr, rscratch1);
2753 
2754     __ mov(c_rarg0, rthread);
2755     __ lea(rscratch1, RuntimeAddress(destination));
2756 
2757     __ blr(rscratch1);
2758     __ bind(retaddr);
2759   }
2760 
2761   // Set an oopmap for the call site.
2762   // We need this not only for callee-saved registers, but also for volatile
2763   // registers that the compiler might be keeping live across a safepoint.
2764 
2765   oop_maps->add_gc_map( __ offset() - start, map);
2766 
2767   // r0 contains the address we are going to jump to assuming no exception got installed
2768 
2769   // clear last_Java_sp
2770   __ reset_last_Java_frame(false);
2771   // check for pending exceptions
2772   Label pending;
2773   __ ldr(rscratch1, Address(rthread, Thread::pending_exception_offset()));
2774   __ cbnz(rscratch1, pending);
2775 
2776   // get the returned Method*
2777   __ get_vm_result_2(rmethod, rthread);
2778   __ str(rmethod, Address(sp, reg_save.reg_offset_in_bytes(rmethod)));
2779 
2780   // r0 is where we want to jump, overwrite rscratch1 which is saved and scratch
2781   __ str(r0, Address(sp, reg_save.rscratch1_offset_in_bytes()));
2782   reg_save.restore_live_registers(masm);
2783 
2784   // We are back the the original state on entry and ready to go.
2785 
2786   __ br(rscratch1);
2787 
2788   // Pending exception after the safepoint
2789 
2790   __ bind(pending);
2791 
2792   reg_save.restore_live_registers(masm);
2793 
2794   // exception pending => remove activation and forward to exception handler
2795 
2796   __ str(zr, Address(rthread, JavaThread::vm_result_offset()));
2797 
2798   __ ldr(r0, Address(rthread, Thread::pending_exception_offset()));
2799   __ far_jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
2800 
2801   // -------------
2802   // make sure all code is generated
2803   masm->flush();
2804 
2805   // return the  blob
2806   // frame_size_words or bytes??
2807   return RuntimeStub::new_runtime_stub(name, &buffer, frame_complete, frame_size_in_words, oop_maps, true);
2808 }
2809 
2810 #ifdef COMPILER2
2811 // This is here instead of runtime_x86_64.cpp because it uses SimpleRuntimeFrame
2812 //
2813 //------------------------------generate_exception_blob---------------------------
2814 // creates exception blob at the end
2815 // Using exception blob, this code is jumped from a compiled method.
2816 // (see emit_exception_handler in x86_64.ad file)
2817 //
2818 // Given an exception pc at a call we call into the runtime for the
2819 // handler in this method. This handler might merely restore state
2820 // (i.e. callee save registers) unwind the frame and jump to the
2821 // exception handler for the nmethod if there is no Java level handler
2822 // for the nmethod.
2823 //
2824 // This code is entered with a jmp.
2825 //
2826 // Arguments:
2827 //   r0: exception oop
2828 //   r3: exception pc
2829 //
2830 // Results:
2831 //   r0: exception oop
2832 //   r3: exception pc in caller or ???
2833 //   destination: exception handler of caller
2834 //
2835 // Note: the exception pc MUST be at a call (precise debug information)
2836 //       Registers r0, r3, r2, r4, r5, r8-r11 are not callee saved.
2837 //
2838 
2839 void OptoRuntime::generate_exception_blob() {
2840   assert(!OptoRuntime::is_callee_saved_register(R3_num), "");
2841   assert(!OptoRuntime::is_callee_saved_register(R0_num), "");
2842   assert(!OptoRuntime::is_callee_saved_register(R2_num), "");
2843 
2844   assert(SimpleRuntimeFrame::framesize % 4 == 0, "sp not 16-byte aligned");
2845 
2846   // Allocate space for the code
2847   ResourceMark rm;
2848   // Setup code generation tools
2849   CodeBuffer buffer("exception_blob", 2048, 1024);
2850   MacroAssembler* masm = new MacroAssembler(&buffer);
2851 
2852   // TODO check various assumptions made here
2853   //
2854   // make sure we do so before running this
2855 
2856   address start = __ pc();
2857 
2858   // push rfp and retaddr by hand
2859   // Exception pc is 'return address' for stack walker
2860   __ stp(rfp, lr, Address(__ pre(sp, -2 * wordSize)));
2861   // there are no callee save registers and we don't expect an
2862   // arg reg save area
2863 #ifndef PRODUCT
2864   assert(frame::arg_reg_save_area_bytes == 0, "not expecting frame reg save area");
2865 #endif
2866   // Store exception in Thread object. We cannot pass any arguments to the
2867   // handle_exception call, since we do not want to make any assumption
2868   // about the size of the frame where the exception happened in.
2869   __ str(r0, Address(rthread, JavaThread::exception_oop_offset()));
2870   __ str(r3, Address(rthread, JavaThread::exception_pc_offset()));
2871 
2872   // This call does all the hard work.  It checks if an exception handler
2873   // exists in the method.
2874   // If so, it returns the handler address.
2875   // If not, it prepares for stack-unwinding, restoring the callee-save
2876   // registers of the frame being removed.
2877   //
2878   // address OptoRuntime::handle_exception_C(JavaThread* thread)
2879   //
2880   // n.b. 1 gp arg, 0 fp args, integral return type
2881 
2882   // the stack should always be aligned
2883   address the_pc = __ pc();
2884   __ set_last_Java_frame(sp, noreg, the_pc, rscratch1);
2885   __ mov(c_rarg0, rthread);
2886   __ lea(rscratch1, RuntimeAddress(CAST_FROM_FN_PTR(address, OptoRuntime::handle_exception_C)));
2887   __ blr(rscratch1);
2888   // handle_exception_C is a special VM call which does not require an explicit
2889   // instruction sync afterwards.
2890 
2891   // May jump to SVE compiled code
2892   __ reinitialize_ptrue();
2893 
2894   // Set an oopmap for the call site.  This oopmap will only be used if we
2895   // are unwinding the stack.  Hence, all locations will be dead.
2896   // Callee-saved registers will be the same as the frame above (i.e.,
2897   // handle_exception_stub), since they were restored when we got the
2898   // exception.
2899 
2900   OopMapSet* oop_maps = new OopMapSet();
2901 
2902   oop_maps->add_gc_map(the_pc - start, new OopMap(SimpleRuntimeFrame::framesize, 0));
2903 
2904   __ reset_last_Java_frame(false);
2905 
2906   // Restore callee-saved registers
2907 
2908   // rfp is an implicitly saved callee saved register (i.e. the calling
2909   // convention will save restore it in prolog/epilog) Other than that
2910   // there are no callee save registers now that adapter frames are gone.
2911   // and we dont' expect an arg reg save area
2912   __ ldp(rfp, r3, Address(__ post(sp, 2 * wordSize)));
2913 
2914   // r0: exception handler
2915 
2916   // We have a handler in r0 (could be deopt blob).
2917   __ mov(r8, r0);
2918 
2919   // Get the exception oop
2920   __ ldr(r0, Address(rthread, JavaThread::exception_oop_offset()));
2921   // Get the exception pc in case we are deoptimized
2922   __ ldr(r4, Address(rthread, JavaThread::exception_pc_offset()));
2923 #ifdef ASSERT
2924   __ str(zr, Address(rthread, JavaThread::exception_handler_pc_offset()));
2925   __ str(zr, Address(rthread, JavaThread::exception_pc_offset()));
2926 #endif
2927   // Clear the exception oop so GC no longer processes it as a root.
2928   __ str(zr, Address(rthread, JavaThread::exception_oop_offset()));
2929 
2930   // r0: exception oop
2931   // r8:  exception handler
2932   // r4: exception pc
2933   // Jump to handler
2934 
2935   __ br(r8);
2936 
2937   // Make sure all code is generated
2938   masm->flush();
2939 
2940   // Set exception blob
2941   _exception_blob =  ExceptionBlob::create(&buffer, oop_maps, SimpleRuntimeFrame::framesize >> 1);
2942 }
2943 
2944 // ---------------------------------------------------------------
2945 
2946 class NativeInvokerGenerator : public StubCodeGenerator {
2947   address _call_target;
2948   int _shadow_space_bytes;
2949 
2950   const GrowableArray<VMReg>& _input_registers;
2951   const GrowableArray<VMReg>& _output_registers;
2952 
2953   int _frame_complete;
2954   int _framesize;
2955   OopMapSet* _oop_maps;
2956 public:
2957   NativeInvokerGenerator(CodeBuffer* buffer,
2958                          address call_target,
2959                          int shadow_space_bytes,
2960                          const GrowableArray<VMReg>& input_registers,
2961                          const GrowableArray<VMReg>& output_registers)
2962    : StubCodeGenerator(buffer, PrintMethodHandleStubs),
2963      _call_target(call_target),
2964      _shadow_space_bytes(shadow_space_bytes),
2965      _input_registers(input_registers),
2966      _output_registers(output_registers),
2967      _frame_complete(0),
2968      _framesize(0),
2969      _oop_maps(NULL) {
2970     assert(_output_registers.length() <= 1
2971            || (_output_registers.length() == 2 && !_output_registers.at(1)->is_valid()), "no multi-reg returns");
2972   }
2973 
2974   void generate();
2975 
2976   int spill_size_in_bytes() const {
2977     if (_output_registers.length() == 0) {
2978       return 0;
2979     }
2980     VMReg reg = _output_registers.at(0);
2981     assert(reg->is_reg(), "must be a register");
2982     if (reg->is_Register()) {
2983       return 8;
2984     } else if (reg->is_FloatRegister()) {
2985       bool use_sve = Matcher::supports_scalable_vector();
2986       if (use_sve) {
2987         return Matcher::scalable_vector_reg_size(T_BYTE);
2988       }
2989       return 16;
2990     } else {
2991       ShouldNotReachHere();
2992     }
2993     return 0;
2994   }
2995 
2996   void spill_output_registers() {
2997     if (_output_registers.length() == 0) {
2998       return;
2999     }
3000     VMReg reg = _output_registers.at(0);
3001     assert(reg->is_reg(), "must be a register");
3002     MacroAssembler* masm = _masm;
3003     if (reg->is_Register()) {
3004       __ spill(reg->as_Register(), true, 0);
3005     } else if (reg->is_FloatRegister()) {
3006       bool use_sve = Matcher::supports_scalable_vector();
3007       if (use_sve) {
3008         __ spill_sve_vector(reg->as_FloatRegister(), 0, Matcher::scalable_vector_reg_size(T_BYTE));
3009       } else {
3010         __ spill(reg->as_FloatRegister(), __ Q, 0);
3011       }
3012     } else {
3013       ShouldNotReachHere();
3014     }
3015   }
3016 
3017   void fill_output_registers() {
3018     if (_output_registers.length() == 0) {
3019       return;
3020     }
3021     VMReg reg = _output_registers.at(0);
3022     assert(reg->is_reg(), "must be a register");
3023     MacroAssembler* masm = _masm;
3024     if (reg->is_Register()) {
3025       __ unspill(reg->as_Register(), true, 0);
3026     } else if (reg->is_FloatRegister()) {
3027       bool use_sve = Matcher::supports_scalable_vector();
3028       if (use_sve) {
3029         __ unspill_sve_vector(reg->as_FloatRegister(), 0, Matcher::scalable_vector_reg_size(T_BYTE));
3030       } else {
3031         __ unspill(reg->as_FloatRegister(), __ Q, 0);
3032       }
3033     } else {
3034       ShouldNotReachHere();
3035     }
3036   }
3037 
3038   int frame_complete() const {
3039     return _frame_complete;
3040   }
3041 
3042   int framesize() const {
3043     return (_framesize >> (LogBytesPerWord - LogBytesPerInt));
3044   }
3045 
3046   OopMapSet* oop_maps() const {
3047     return _oop_maps;
3048   }
3049 
3050 private:
3051 #ifdef ASSERT
3052   bool target_uses_register(VMReg reg) {
3053     return _input_registers.contains(reg) || _output_registers.contains(reg);
3054   }
3055 #endif
3056 };
3057 
3058 static const int native_invoker_code_size = 1024;
3059 
3060 RuntimeStub* SharedRuntime::make_native_invoker(address call_target,
3061                                                 int shadow_space_bytes,
3062                                                 const GrowableArray<VMReg>& input_registers,
3063                                                 const GrowableArray<VMReg>& output_registers) {
3064   int locs_size  = 64;
3065   CodeBuffer code("nep_invoker_blob", native_invoker_code_size, locs_size);
3066   NativeInvokerGenerator g(&code, call_target, shadow_space_bytes, input_registers, output_registers);
3067   g.generate();
3068   code.log_section_sizes("nep_invoker_blob");
3069 
3070   RuntimeStub* stub =
3071     RuntimeStub::new_runtime_stub("nep_invoker_blob",
3072                                   &code,
3073                                   g.frame_complete(),
3074                                   g.framesize(),
3075                                   g.oop_maps(), false);
3076   return stub;
3077 }
3078 
3079 void NativeInvokerGenerator::generate() {
3080   assert(!(target_uses_register(rscratch1->as_VMReg())
3081            || target_uses_register(rscratch2->as_VMReg())
3082            || target_uses_register(rthread->as_VMReg())),
3083          "Register conflict");
3084 
3085   enum layout {
3086     rbp_off,
3087     rbp_off2,
3088     return_off,
3089     return_off2,
3090     framesize // inclusive of return address
3091   };
3092 
3093   assert(_shadow_space_bytes == 0, "not expecting shadow space on AArch64");
3094   _framesize = align_up(framesize + (spill_size_in_bytes() >> LogBytesPerInt), 4);
3095   assert(is_even(_framesize/2), "sp not 16-byte aligned");
3096 
3097   _oop_maps  = new OopMapSet();
3098   MacroAssembler* masm = _masm;
3099 
3100   address start = __ pc();
3101 
3102   __ enter();
3103 
3104   // lr and fp are already in place
3105   __ sub(sp, rfp, ((unsigned)_framesize-4) << LogBytesPerInt); // prolog
3106 
3107   _frame_complete = __ pc() - start;
3108 
3109   address the_pc = __ pc();
3110   __ set_last_Java_frame(sp, rfp, the_pc, rscratch1);
3111   OopMap* map = new OopMap(_framesize, 0);
3112   _oop_maps->add_gc_map(the_pc - start, map);
3113 
3114   // State transition
3115   __ mov(rscratch1, _thread_in_native);
3116   __ lea(rscratch2, Address(rthread, JavaThread::thread_state_offset()));
3117   __ stlrw(rscratch1, rscratch2);
3118 
3119   rt_call(masm, _call_target);
3120 
3121   __ mov(rscratch1, _thread_in_native_trans);
3122   __ strw(rscratch1, Address(rthread, JavaThread::thread_state_offset()));
3123 
3124   // Force this write out before the read below
3125   __ membar(Assembler::LoadLoad | Assembler::LoadStore |
3126             Assembler::StoreLoad | Assembler::StoreStore);
3127 
3128   __ verify_sve_vector_length();
3129 
3130   Label L_after_safepoint_poll;
3131   Label L_safepoint_poll_slow_path;
3132 
3133   __ safepoint_poll(L_safepoint_poll_slow_path, true /* at_return */, true /* acquire */, false /* in_nmethod */);
3134 
3135   __ ldrw(rscratch1, Address(rthread, JavaThread::suspend_flags_offset()));
3136   __ cbnzw(rscratch1, L_safepoint_poll_slow_path);
3137 
3138   __ bind(L_after_safepoint_poll);
3139 
3140   // change thread state
3141   __ mov(rscratch1, _thread_in_Java);
3142   __ lea(rscratch2, Address(rthread, JavaThread::thread_state_offset()));
3143   __ stlrw(rscratch1, rscratch2);
3144 
3145   __ block_comment("reguard stack check");
3146   Label L_reguard;
3147   Label L_after_reguard;
3148   __ ldrb(rscratch1, Address(rthread, JavaThread::stack_guard_state_offset()));
3149   __ cmpw(rscratch1, StackOverflow::stack_guard_yellow_reserved_disabled);
3150   __ br(Assembler::EQ, L_reguard);
3151   __ bind(L_after_reguard);
3152 
3153   __ reset_last_Java_frame(true);
3154 
3155   __ leave(); // required for proper stackwalking of RuntimeStub frame
3156   __ ret(lr);
3157 
3158   //////////////////////////////////////////////////////////////////////////////
3159 
3160   __ block_comment("{ L_safepoint_poll_slow_path");
3161   __ bind(L_safepoint_poll_slow_path);
3162 
3163   // Need to save the native result registers around any runtime calls.
3164   spill_output_registers();
3165 
3166   __ mov(c_rarg0, rthread);
3167   assert(frame::arg_reg_save_area_bytes == 0, "not expecting frame reg save area");
3168   __ lea(rscratch1, RuntimeAddress(CAST_FROM_FN_PTR(address, JavaThread::check_special_condition_for_native_trans)));
3169   __ blr(rscratch1);
3170 
3171   fill_output_registers();
3172 
3173   __ b(L_after_safepoint_poll);
3174   __ block_comment("} L_safepoint_poll_slow_path");
3175 
3176   //////////////////////////////////////////////////////////////////////////////
3177 
3178   __ block_comment("{ L_reguard");
3179   __ bind(L_reguard);
3180 
3181   spill_output_registers();
3182 
3183   rt_call(masm, CAST_FROM_FN_PTR(address, SharedRuntime::reguard_yellow_pages));
3184 
3185   fill_output_registers();
3186 
3187   __ b(L_after_reguard);
3188 
3189   __ block_comment("} L_reguard");
3190 
3191   //////////////////////////////////////////////////////////////////////////////
3192 
3193   __ flush();
3194 }
3195 #endif // COMPILER2

--- EOF ---