1 /*
   2  * Copyright (c) 2003, 2021, Oracle and/or its affiliates. All rights reserved.
   3  * Copyright (c) 2014, 2021, Red Hat Inc. All rights reserved.
   4  * Copyright (c) 2021, Azul Systems, Inc. All rights reserved.
   5  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   6  *
   7  * This code is free software; you can redistribute it and/or modify it
   8  * under the terms of the GNU General Public License version 2 only, as
   9  * published by the Free Software Foundation.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  *
  25  */
  26 
  27 #include "precompiled.hpp"
  28 #include "asm/macroAssembler.hpp"
  29 #include "asm/macroAssembler.inline.hpp"
  30 #include "code/codeCache.hpp"
  31 #include "code/debugInfoRec.hpp"
  32 #include "code/icBuffer.hpp"
  33 #include "code/vtableStubs.hpp"
  34 #include "compiler/oopMap.hpp"
  35 #include "gc/shared/barrierSetAssembler.hpp"
  36 #include "interpreter/interpreter.hpp"
  37 #include "interpreter/interp_masm.hpp"
  38 #include "logging/log.hpp"
  39 #include "memory/resourceArea.hpp"
  40 #include "nativeInst_aarch64.hpp"
  41 #include "oops/compiledICHolder.hpp"
  42 #include "oops/klass.inline.hpp"
  43 #include "prims/methodHandles.hpp"
  44 #include "runtime/jniHandles.hpp"
  45 #include "runtime/safepointMechanism.hpp"
  46 #include "runtime/sharedRuntime.hpp"
  47 #include "runtime/signature.hpp"
  48 #include "runtime/stubRoutines.hpp"
  49 #include "runtime/vframeArray.hpp"
  50 #include "utilities/align.hpp"
  51 #include "utilities/formatBuffer.hpp"
  52 #include "vmreg_aarch64.inline.hpp"
  53 #ifdef COMPILER1
  54 #include "c1/c1_Runtime1.hpp"
  55 #endif
  56 #ifdef COMPILER2
  57 #include "adfiles/ad_aarch64.hpp"
  58 #include "opto/runtime.hpp"
  59 #endif
  60 #if INCLUDE_JVMCI
  61 #include "jvmci/jvmciJavaClasses.hpp"
  62 #endif
  63 
  64 #define __ masm->
  65 
  66 const int StackAlignmentInSlots = StackAlignmentInBytes / VMRegImpl::stack_slot_size;
  67 
  68 class SimpleRuntimeFrame {
  69 
  70   public:
  71 
  72   // Most of the runtime stubs have this simple frame layout.
  73   // This class exists to make the layout shared in one place.
  74   // Offsets are for compiler stack slots, which are jints.
  75   enum layout {
  76     // The frame sender code expects that rbp will be in the "natural" place and
  77     // will override any oopMap setting for it. We must therefore force the layout
  78     // so that it agrees with the frame sender code.
  79     // we don't expect any arg reg save area so aarch64 asserts that
  80     // frame::arg_reg_save_area_bytes == 0
  81     rbp_off = 0,
  82     rbp_off2,
  83     return_off, return_off2,
  84     framesize
  85   };
  86 };
  87 
  88 // FIXME -- this is used by C1
  89 class RegisterSaver {
  90   const bool _save_vectors;
  91  public:
  92   RegisterSaver(bool save_vectors) : _save_vectors(save_vectors) {}
  93 
  94   OopMap* save_live_registers(MacroAssembler* masm, int additional_frame_words, int* total_frame_words);
  95   void restore_live_registers(MacroAssembler* masm);
  96 
  97   // Offsets into the register save area
  98   // Used by deoptimization when it is managing result register
  99   // values on its own
 100 
 101   int reg_offset_in_bytes(Register r);
 102   int r0_offset_in_bytes()    { return reg_offset_in_bytes(r0); }
 103   int rscratch1_offset_in_bytes()    { return reg_offset_in_bytes(rscratch1); }
 104   int v0_offset_in_bytes();
 105 
 106   // Total stack size in bytes for saving sve predicate registers.
 107   int total_sve_predicate_in_bytes();
 108 
 109   // Capture info about frame layout
 110   // Note this is only correct when not saving full vectors.
 111   enum layout {
 112                 fpu_state_off = 0,
 113                 fpu_state_end = fpu_state_off + FPUStateSizeInWords - 1,
 114                 // The frame sender code expects that rfp will be in
 115                 // the "natural" place and will override any oopMap
 116                 // setting for it. We must therefore force the layout
 117                 // so that it agrees with the frame sender code.
 118                 r0_off = fpu_state_off + FPUStateSizeInWords,
 119                 rfp_off = r0_off + (RegisterImpl::number_of_registers - 2) * RegisterImpl::max_slots_per_register,
 120                 return_off = rfp_off + RegisterImpl::max_slots_per_register,      // slot for return address
 121                 reg_save_size = return_off + RegisterImpl::max_slots_per_register};
 122 
 123 };
 124 
 125 int RegisterSaver::reg_offset_in_bytes(Register r) {
 126   // The integer registers are located above the floating point
 127   // registers in the stack frame pushed by save_live_registers() so the
 128   // offset depends on whether we are saving full vectors, and whether
 129   // those vectors are NEON or SVE.
 130 
 131   int slots_per_vect = FloatRegisterImpl::save_slots_per_register;
 132 
 133 #if COMPILER2_OR_JVMCI
 134   if (_save_vectors) {
 135     slots_per_vect = FloatRegisterImpl::slots_per_neon_register;
 136 
 137 #ifdef COMPILER2
 138     if (Matcher::supports_scalable_vector()) {
 139       slots_per_vect = Matcher::scalable_vector_reg_size(T_FLOAT);
 140     }
 141 #endif
 142   }
 143 #endif
 144 
 145   int r0_offset = v0_offset_in_bytes() + (slots_per_vect * FloatRegisterImpl::number_of_registers) * BytesPerInt;
 146   return r0_offset + r->encoding() * wordSize;
 147 }
 148 
 149 int RegisterSaver::v0_offset_in_bytes() {
 150   // The floating point registers are located above the predicate registers if
 151   // they are present in the stack frame pushed by save_live_registers(). So the
 152   // offset depends on the saved total predicate vectors in the stack frame.
 153   return (total_sve_predicate_in_bytes() / VMRegImpl::stack_slot_size) * BytesPerInt;
 154 }
 155 
 156 int RegisterSaver::total_sve_predicate_in_bytes() {
 157 #ifdef COMPILER2
 158   if (_save_vectors && Matcher::supports_scalable_vector()) {
 159     // The number of total predicate bytes is unlikely to be a multiple
 160     // of 16 bytes so we manually align it up.
 161     return align_up(Matcher::scalable_predicate_reg_slots() *
 162                     VMRegImpl::stack_slot_size *
 163                     PRegisterImpl::number_of_saved_registers, 16);
 164   }
 165 #endif
 166   return 0;
 167 }
 168 
 169 OopMap* RegisterSaver::save_live_registers(MacroAssembler* masm, int additional_frame_words, int* total_frame_words) {
 170   bool use_sve = false;
 171   int sve_vector_size_in_bytes = 0;
 172   int sve_vector_size_in_slots = 0;
 173   int sve_predicate_size_in_slots = 0;
 174   int total_predicate_in_bytes = total_sve_predicate_in_bytes();
 175   int total_predicate_in_slots = total_predicate_in_bytes / VMRegImpl::stack_slot_size;
 176 
 177 #ifdef COMPILER2
 178   use_sve = Matcher::supports_scalable_vector();
 179   if (use_sve) {
 180     sve_vector_size_in_bytes = Matcher::scalable_vector_reg_size(T_BYTE);
 181     sve_vector_size_in_slots = Matcher::scalable_vector_reg_size(T_FLOAT);
 182     sve_predicate_size_in_slots = Matcher::scalable_predicate_reg_slots();
 183   }
 184 #endif
 185 
 186 #if COMPILER2_OR_JVMCI
 187   if (_save_vectors) {
 188     int extra_save_slots_per_register = 0;
 189     // Save upper half of vector registers
 190     if (use_sve) {
 191       extra_save_slots_per_register = sve_vector_size_in_slots - FloatRegisterImpl::save_slots_per_register;
 192     } else {
 193       extra_save_slots_per_register = FloatRegisterImpl::extra_save_slots_per_neon_register;
 194     }
 195     int extra_vector_bytes = extra_save_slots_per_register *
 196                              VMRegImpl::stack_slot_size *
 197                              FloatRegisterImpl::number_of_registers;
 198     additional_frame_words += ((extra_vector_bytes + total_predicate_in_bytes) / wordSize);
 199   }
 200 #else
 201   assert(!_save_vectors, "vectors are generated only by C2 and JVMCI");
 202 #endif
 203 
 204   int frame_size_in_bytes = align_up(additional_frame_words * wordSize +
 205                                      reg_save_size * BytesPerInt, 16);
 206   // OopMap frame size is in compiler stack slots (jint's) not bytes or words
 207   int frame_size_in_slots = frame_size_in_bytes / BytesPerInt;
 208   // The caller will allocate additional_frame_words
 209   int additional_frame_slots = additional_frame_words * wordSize / BytesPerInt;
 210   // CodeBlob frame size is in words.
 211   int frame_size_in_words = frame_size_in_bytes / wordSize;
 212   *total_frame_words = frame_size_in_words;
 213 
 214   // Save Integer and Float registers.
 215   __ enter();
 216   __ push_CPU_state(_save_vectors, use_sve, sve_vector_size_in_bytes, total_predicate_in_bytes);
 217 
 218   // Set an oopmap for the call site.  This oopmap will map all
 219   // oop-registers and debug-info registers as callee-saved.  This
 220   // will allow deoptimization at this safepoint to find all possible
 221   // debug-info recordings, as well as let GC find all oops.
 222 
 223   OopMapSet *oop_maps = new OopMapSet();
 224   OopMap* oop_map = new OopMap(frame_size_in_slots, 0);
 225 
 226   for (int i = 0; i < RegisterImpl::number_of_registers; i++) {
 227     Register r = as_Register(i);
 228     if (r <= rfp && r != rscratch1 && r != rscratch2) {
 229       // SP offsets are in 4-byte words.
 230       // Register slots are 8 bytes wide, 32 floating-point registers.
 231       int sp_offset = RegisterImpl::max_slots_per_register * i +
 232                       FloatRegisterImpl::save_slots_per_register * FloatRegisterImpl::number_of_registers;
 233       oop_map->set_callee_saved(VMRegImpl::stack2reg(sp_offset + additional_frame_slots), r->as_VMReg());
 234     }
 235   }
 236 
 237   for (int i = 0; i < FloatRegisterImpl::number_of_registers; i++) {
 238     FloatRegister r = as_FloatRegister(i);
 239     int sp_offset = 0;
 240     if (_save_vectors) {
 241       sp_offset = use_sve ? (total_predicate_in_slots + sve_vector_size_in_slots * i) :
 242                             (FloatRegisterImpl::slots_per_neon_register * i);
 243     } else {
 244       sp_offset = FloatRegisterImpl::save_slots_per_register * i;
 245     }
 246     oop_map->set_callee_saved(VMRegImpl::stack2reg(sp_offset), r->as_VMReg());
 247   }
 248 
 249   if (_save_vectors && use_sve) {
 250     for (int i = 0; i < PRegisterImpl::number_of_saved_registers; i++) {
 251       PRegister r = as_PRegister(i);
 252       int sp_offset = sve_predicate_size_in_slots * i;
 253       oop_map->set_callee_saved(VMRegImpl::stack2reg(sp_offset), r->as_VMReg());
 254     }
 255   }
 256 
 257   return oop_map;
 258 }
 259 
 260 void RegisterSaver::restore_live_registers(MacroAssembler* masm) {
 261 #ifdef COMPILER2
 262   __ pop_CPU_state(_save_vectors, Matcher::supports_scalable_vector(),
 263                    Matcher::scalable_vector_reg_size(T_BYTE), total_sve_predicate_in_bytes());
 264 #else
 265 #if !INCLUDE_JVMCI
 266   assert(!_save_vectors, "vectors are generated only by C2 and JVMCI");
 267 #endif
 268   __ pop_CPU_state(_save_vectors);
 269 #endif
 270   __ leave();
 271 
 272 }
 273 
 274 // Is vector's size (in bytes) bigger than a size saved by default?
 275 // 8 bytes vector registers are saved by default on AArch64.
 276 // The SVE supported min vector size is 8 bytes and we need to save
 277 // predicate registers when the vector size is 8 bytes as well.
 278 bool SharedRuntime::is_wide_vector(int size) {
 279   return size > 8 || (UseSVE > 0 && size >= 8);
 280 }
 281 














 282 // ---------------------------------------------------------------------------
 283 // Read the array of BasicTypes from a signature, and compute where the
 284 // arguments should go.  Values in the VMRegPair regs array refer to 4-byte
 285 // quantities.  Values less than VMRegImpl::stack0 are registers, those above
 286 // refer to 4-byte stack slots.  All stack slots are based off of the stack pointer
 287 // as framesizes are fixed.
 288 // VMRegImpl::stack0 refers to the first slot 0(sp).
 289 // and VMRegImpl::stack0+1 refers to the memory word 4-byes higher.  Register
 290 // up to RegisterImpl::number_of_registers) are the 64-bit
 291 // integer registers.
 292 
 293 // Note: the INPUTS in sig_bt are in units of Java argument words,
 294 // which are 64-bit.  The OUTPUTS are in 32-bit units.
 295 
 296 // The Java calling convention is a "shifted" version of the C ABI.
 297 // By skipping the first C ABI register we can call non-static jni
 298 // methods with small numbers of arguments without having to shuffle
 299 // the arguments at all. Since we control the java ABI we ought to at
 300 // least get some advantage out of it.
 301 
 302 int SharedRuntime::java_calling_convention(const BasicType *sig_bt,
 303                                            VMRegPair *regs,
 304                                            int total_args_passed) {
 305 
 306   // Create the mapping between argument positions and
 307   // registers.
 308   static const Register INT_ArgReg[Argument::n_int_register_parameters_j] = {
 309     j_rarg0, j_rarg1, j_rarg2, j_rarg3, j_rarg4, j_rarg5, j_rarg6, j_rarg7
 310   };
 311   static const FloatRegister FP_ArgReg[Argument::n_float_register_parameters_j] = {
 312     j_farg0, j_farg1, j_farg2, j_farg3,
 313     j_farg4, j_farg5, j_farg6, j_farg7
 314   };
 315 
 316 
 317   uint int_args = 0;
 318   uint fp_args = 0;
 319   uint stk_args = 0; // inc by 2 each time
 320 
 321   for (int i = 0; i < total_args_passed; i++) {
 322     switch (sig_bt[i]) {
 323     case T_BOOLEAN:
 324     case T_CHAR:
 325     case T_BYTE:
 326     case T_SHORT:
 327     case T_INT:
 328       if (int_args < Argument::n_int_register_parameters_j) {
 329         regs[i].set1(INT_ArgReg[int_args++]->as_VMReg());
 330       } else {
 331         regs[i].set1(VMRegImpl::stack2reg(stk_args));
 332         stk_args += 2;
 333       }
 334       break;
 335     case T_VOID:
 336       // halves of T_LONG or T_DOUBLE
 337       assert(i != 0 && (sig_bt[i - 1] == T_LONG || sig_bt[i - 1] == T_DOUBLE), "expecting half");
 338       regs[i].set_bad();
 339       break;
 340     case T_LONG:
 341       assert((i + 1) < total_args_passed && sig_bt[i + 1] == T_VOID, "expecting half");
 342       // fall through
 343     case T_OBJECT:
 344     case T_ARRAY:
 345     case T_ADDRESS:
 346       if (int_args < Argument::n_int_register_parameters_j) {
 347         regs[i].set2(INT_ArgReg[int_args++]->as_VMReg());
 348       } else {
 349         regs[i].set2(VMRegImpl::stack2reg(stk_args));
 350         stk_args += 2;
 351       }
 352       break;
 353     case T_FLOAT:
 354       if (fp_args < Argument::n_float_register_parameters_j) {
 355         regs[i].set1(FP_ArgReg[fp_args++]->as_VMReg());
 356       } else {
 357         regs[i].set1(VMRegImpl::stack2reg(stk_args));
 358         stk_args += 2;
 359       }
 360       break;
 361     case T_DOUBLE:
 362       assert((i + 1) < total_args_passed && sig_bt[i + 1] == T_VOID, "expecting half");
 363       if (fp_args < Argument::n_float_register_parameters_j) {
 364         regs[i].set2(FP_ArgReg[fp_args++]->as_VMReg());
 365       } else {
 366         regs[i].set2(VMRegImpl::stack2reg(stk_args));
 367         stk_args += 2;
 368       }
 369       break;
 370     default:
 371       ShouldNotReachHere();
 372       break;
 373     }
 374   }
 375 
 376   return align_up(stk_args, 2);
 377 }
 378 
 379 // Patch the callers callsite with entry to compiled code if it exists.
 380 static void patch_callers_callsite(MacroAssembler *masm) {
 381   Label L;
 382   __ ldr(rscratch1, Address(rmethod, in_bytes(Method::code_offset())));
 383   __ cbz(rscratch1, L);
 384 
 385   __ enter();
 386   __ push_CPU_state();
 387 
 388   // VM needs caller's callsite
 389   // VM needs target method
 390   // This needs to be a long call since we will relocate this adapter to
 391   // the codeBuffer and it may not reach
 392 
 393 #ifndef PRODUCT
 394   assert(frame::arg_reg_save_area_bytes == 0, "not expecting frame reg save area");
 395 #endif
 396 
 397   __ mov(c_rarg0, rmethod);
 398   __ mov(c_rarg1, lr);
 399   __ lea(rscratch1, RuntimeAddress(CAST_FROM_FN_PTR(address, SharedRuntime::fixup_callers_callsite)));
 400   __ blr(rscratch1);
 401 
 402   // Explicit isb required because fixup_callers_callsite may change the code
 403   // stream.
 404   __ safepoint_isb();
 405 
 406   __ pop_CPU_state();
 407   // restore sp
 408   __ leave();
 409   __ bind(L);
 410 }
 411 
 412 static void gen_c2i_adapter(MacroAssembler *masm,
 413                             int total_args_passed,
 414                             int comp_args_on_stack,
 415                             const BasicType *sig_bt,
 416                             const VMRegPair *regs,
 417                             Label& skip_fixup) {
 418   // Before we get into the guts of the C2I adapter, see if we should be here
 419   // at all.  We've come from compiled code and are attempting to jump to the
 420   // interpreter, which means the caller made a static call to get here
 421   // (vcalls always get a compiled target if there is one).  Check for a
 422   // compiled target.  If there is one, we need to patch the caller's call.
 423   patch_callers_callsite(masm);
 424 
 425   __ bind(skip_fixup);
 426 
 427   int words_pushed = 0;
 428 
 429   // Since all args are passed on the stack, total_args_passed *
 430   // Interpreter::stackElementSize is the space we need.
 431 
 432   int extraspace = total_args_passed * Interpreter::stackElementSize;
 433 
 434   __ mov(r13, sp);
 435 
 436   // stack is aligned, keep it that way
 437   extraspace = align_up(extraspace, 2*wordSize);
 438 
 439   if (extraspace)
 440     __ sub(sp, sp, extraspace);
 441 
 442   // Now write the args into the outgoing interpreter space
 443   for (int i = 0; i < total_args_passed; i++) {
 444     if (sig_bt[i] == T_VOID) {
 445       assert(i > 0 && (sig_bt[i-1] == T_LONG || sig_bt[i-1] == T_DOUBLE), "missing half");
 446       continue;
 447     }
 448 
 449     // offset to start parameters
 450     int st_off   = (total_args_passed - i - 1) * Interpreter::stackElementSize;
 451     int next_off = st_off - Interpreter::stackElementSize;
 452 
 453     // Say 4 args:
 454     // i   st_off
 455     // 0   32 T_LONG
 456     // 1   24 T_VOID
 457     // 2   16 T_OBJECT
 458     // 3    8 T_BOOL
 459     // -    0 return address
 460     //
 461     // However to make thing extra confusing. Because we can fit a Java long/double in
 462     // a single slot on a 64 bt vm and it would be silly to break them up, the interpreter
 463     // leaves one slot empty and only stores to a single slot. In this case the
 464     // slot that is occupied is the T_VOID slot. See I said it was confusing.
 465 
 466     VMReg r_1 = regs[i].first();
 467     VMReg r_2 = regs[i].second();
 468     if (!r_1->is_valid()) {
 469       assert(!r_2->is_valid(), "");
 470       continue;
 471     }
 472     if (r_1->is_stack()) {
 473       // memory to memory use rscratch1
 474       int ld_off = (r_1->reg2stack() * VMRegImpl::stack_slot_size
 475                     + extraspace
 476                     + words_pushed * wordSize);
 477       if (!r_2->is_valid()) {
 478         // sign extend??
 479         __ ldrw(rscratch1, Address(sp, ld_off));
 480         __ str(rscratch1, Address(sp, st_off));
 481 
 482       } else {
 483 
 484         __ ldr(rscratch1, Address(sp, ld_off));
 485 
 486         // Two VMREgs|OptoRegs can be T_OBJECT, T_ADDRESS, T_DOUBLE, T_LONG
 487         // T_DOUBLE and T_LONG use two slots in the interpreter
 488         if ( sig_bt[i] == T_LONG || sig_bt[i] == T_DOUBLE) {
 489           // ld_off == LSW, ld_off+wordSize == MSW
 490           // st_off == MSW, next_off == LSW
 491           __ str(rscratch1, Address(sp, next_off));
 492 #ifdef ASSERT
 493           // Overwrite the unused slot with known junk
 494           __ mov(rscratch1, (uint64_t)0xdeadffffdeadaaaaull);
 495           __ str(rscratch1, Address(sp, st_off));
 496 #endif /* ASSERT */
 497         } else {
 498           __ str(rscratch1, Address(sp, st_off));
 499         }
 500       }
 501     } else if (r_1->is_Register()) {
 502       Register r = r_1->as_Register();
 503       if (!r_2->is_valid()) {
 504         // must be only an int (or less ) so move only 32bits to slot
 505         // why not sign extend??
 506         __ str(r, Address(sp, st_off));
 507       } else {
 508         // Two VMREgs|OptoRegs can be T_OBJECT, T_ADDRESS, T_DOUBLE, T_LONG
 509         // T_DOUBLE and T_LONG use two slots in the interpreter
 510         if ( sig_bt[i] == T_LONG || sig_bt[i] == T_DOUBLE) {
 511           // jlong/double in gpr
 512 #ifdef ASSERT
 513           // Overwrite the unused slot with known junk
 514           __ mov(rscratch1, (uint64_t)0xdeadffffdeadaaabull);
 515           __ str(rscratch1, Address(sp, st_off));
 516 #endif /* ASSERT */
 517           __ str(r, Address(sp, next_off));
 518         } else {
 519           __ str(r, Address(sp, st_off));
 520         }
 521       }
 522     } else {
 523       assert(r_1->is_FloatRegister(), "");
 524       if (!r_2->is_valid()) {
 525         // only a float use just part of the slot
 526         __ strs(r_1->as_FloatRegister(), Address(sp, st_off));
 527       } else {
 528 #ifdef ASSERT
 529         // Overwrite the unused slot with known junk
 530         __ mov(rscratch1, (uint64_t)0xdeadffffdeadaaacull);
 531         __ str(rscratch1, Address(sp, st_off));
 532 #endif /* ASSERT */
 533         __ strd(r_1->as_FloatRegister(), Address(sp, next_off));
 534       }
 535     }
 536   }
 537 
 538   __ mov(esp, sp); // Interp expects args on caller's expression stack
 539 
 540   __ ldr(rscratch1, Address(rmethod, in_bytes(Method::interpreter_entry_offset())));
 541   __ br(rscratch1);
 542 }
 543 
 544 
 545 void SharedRuntime::gen_i2c_adapter(MacroAssembler *masm,
 546                                     int total_args_passed,
 547                                     int comp_args_on_stack,
 548                                     const BasicType *sig_bt,
 549                                     const VMRegPair *regs) {
 550 
 551   // Note: r13 contains the senderSP on entry. We must preserve it since
 552   // we may do a i2c -> c2i transition if we lose a race where compiled
 553   // code goes non-entrant while we get args ready.
 554 
 555   // In addition we use r13 to locate all the interpreter args because
 556   // we must align the stack to 16 bytes.
 557 
 558   // Adapters are frameless.
 559 
 560   // An i2c adapter is frameless because the *caller* frame, which is
 561   // interpreted, routinely repairs its own esp (from
 562   // interpreter_frame_last_sp), even if a callee has modified the
 563   // stack pointer.  It also recalculates and aligns sp.
 564 
 565   // A c2i adapter is frameless because the *callee* frame, which is
 566   // interpreted, routinely repairs its caller's sp (from sender_sp,
 567   // which is set up via the senderSP register).
 568 
 569   // In other words, if *either* the caller or callee is interpreted, we can
 570   // get the stack pointer repaired after a call.
 571 
 572   // This is why c2i and i2c adapters cannot be indefinitely composed.
 573   // In particular, if a c2i adapter were to somehow call an i2c adapter,
 574   // both caller and callee would be compiled methods, and neither would
 575   // clean up the stack pointer changes performed by the two adapters.
 576   // If this happens, control eventually transfers back to the compiled
 577   // caller, but with an uncorrected stack, causing delayed havoc.
 578 
 579   if (VerifyAdapterCalls &&
 580       (Interpreter::code() != NULL || StubRoutines::code1() != NULL)) {
 581 #if 0
 582     // So, let's test for cascading c2i/i2c adapters right now.
 583     //  assert(Interpreter::contains($return_addr) ||
 584     //         StubRoutines::contains($return_addr),
 585     //         "i2c adapter must return to an interpreter frame");
 586     __ block_comment("verify_i2c { ");
 587     Label L_ok;
 588     if (Interpreter::code() != NULL)
 589       range_check(masm, rax, r11,
 590                   Interpreter::code()->code_start(), Interpreter::code()->code_end(),
 591                   L_ok);
 592     if (StubRoutines::code1() != NULL)
 593       range_check(masm, rax, r11,
 594                   StubRoutines::code1()->code_begin(), StubRoutines::code1()->code_end(),
 595                   L_ok);
 596     if (StubRoutines::code2() != NULL)
 597       range_check(masm, rax, r11,
 598                   StubRoutines::code2()->code_begin(), StubRoutines::code2()->code_end(),
 599                   L_ok);
 600     const char* msg = "i2c adapter must return to an interpreter frame";
 601     __ block_comment(msg);
 602     __ stop(msg);
 603     __ bind(L_ok);
 604     __ block_comment("} verify_i2ce ");
 605 #endif
 606   }
 607 
 608   // Cut-out for having no stack args.
 609   int comp_words_on_stack = align_up(comp_args_on_stack*VMRegImpl::stack_slot_size, wordSize)>>LogBytesPerWord;
 610   if (comp_args_on_stack) {
 611     __ sub(rscratch1, sp, comp_words_on_stack * wordSize);
 612     __ andr(sp, rscratch1, -16);
 613   }
 614 
 615   // Will jump to the compiled code just as if compiled code was doing it.
 616   // Pre-load the register-jump target early, to schedule it better.
 617   __ ldr(rscratch1, Address(rmethod, in_bytes(Method::from_compiled_offset())));
 618 
 619 #if INCLUDE_JVMCI
 620   if (EnableJVMCI) {
 621     // check if this call should be routed towards a specific entry point
 622     __ ldr(rscratch2, Address(rthread, in_bytes(JavaThread::jvmci_alternate_call_target_offset())));
 623     Label no_alternative_target;
 624     __ cbz(rscratch2, no_alternative_target);
 625     __ mov(rscratch1, rscratch2);
 626     __ str(zr, Address(rthread, in_bytes(JavaThread::jvmci_alternate_call_target_offset())));
 627     __ bind(no_alternative_target);
 628   }
 629 #endif // INCLUDE_JVMCI
 630 
 631   // Now generate the shuffle code.
 632   for (int i = 0; i < total_args_passed; i++) {
 633     if (sig_bt[i] == T_VOID) {
 634       assert(i > 0 && (sig_bt[i-1] == T_LONG || sig_bt[i-1] == T_DOUBLE), "missing half");
 635       continue;
 636     }
 637 
 638     // Pick up 0, 1 or 2 words from SP+offset.
 639 
 640     assert(!regs[i].second()->is_valid() || regs[i].first()->next() == regs[i].second(),
 641             "scrambled load targets?");
 642     // Load in argument order going down.
 643     int ld_off = (total_args_passed - i - 1)*Interpreter::stackElementSize;
 644     // Point to interpreter value (vs. tag)
 645     int next_off = ld_off - Interpreter::stackElementSize;
 646     //
 647     //
 648     //
 649     VMReg r_1 = regs[i].first();
 650     VMReg r_2 = regs[i].second();
 651     if (!r_1->is_valid()) {
 652       assert(!r_2->is_valid(), "");
 653       continue;
 654     }
 655     if (r_1->is_stack()) {
 656       // Convert stack slot to an SP offset (+ wordSize to account for return address )
 657       int st_off = regs[i].first()->reg2stack()*VMRegImpl::stack_slot_size;
 658       if (!r_2->is_valid()) {
 659         // sign extend???
 660         __ ldrsw(rscratch2, Address(esp, ld_off));
 661         __ str(rscratch2, Address(sp, st_off));
 662       } else {
 663         //
 664         // We are using two optoregs. This can be either T_OBJECT,
 665         // T_ADDRESS, T_LONG, or T_DOUBLE the interpreter allocates
 666         // two slots but only uses one for thr T_LONG or T_DOUBLE case
 667         // So we must adjust where to pick up the data to match the
 668         // interpreter.
 669         //
 670         // Interpreter local[n] == MSW, local[n+1] == LSW however locals
 671         // are accessed as negative so LSW is at LOW address
 672 
 673         // ld_off is MSW so get LSW
 674         const int offset = (sig_bt[i]==T_LONG||sig_bt[i]==T_DOUBLE)?
 675                            next_off : ld_off;
 676         __ ldr(rscratch2, Address(esp, offset));
 677         // st_off is LSW (i.e. reg.first())
 678         __ str(rscratch2, Address(sp, st_off));
 679       }
 680     } else if (r_1->is_Register()) {  // Register argument
 681       Register r = r_1->as_Register();
 682       if (r_2->is_valid()) {
 683         //
 684         // We are using two VMRegs. This can be either T_OBJECT,
 685         // T_ADDRESS, T_LONG, or T_DOUBLE the interpreter allocates
 686         // two slots but only uses one for thr T_LONG or T_DOUBLE case
 687         // So we must adjust where to pick up the data to match the
 688         // interpreter.
 689 
 690         const int offset = (sig_bt[i]==T_LONG||sig_bt[i]==T_DOUBLE)?
 691                            next_off : ld_off;
 692 
 693         // this can be a misaligned move
 694         __ ldr(r, Address(esp, offset));
 695       } else {
 696         // sign extend and use a full word?
 697         __ ldrw(r, Address(esp, ld_off));
 698       }
 699     } else {
 700       if (!r_2->is_valid()) {
 701         __ ldrs(r_1->as_FloatRegister(), Address(esp, ld_off));
 702       } else {
 703         __ ldrd(r_1->as_FloatRegister(), Address(esp, next_off));
 704       }
 705     }
 706   }
 707 
 708   // 6243940 We might end up in handle_wrong_method if
 709   // the callee is deoptimized as we race thru here. If that
 710   // happens we don't want to take a safepoint because the
 711   // caller frame will look interpreted and arguments are now
 712   // "compiled" so it is much better to make this transition
 713   // invisible to the stack walking code. Unfortunately if
 714   // we try and find the callee by normal means a safepoint
 715   // is possible. So we stash the desired callee in the thread
 716   // and the vm will find there should this case occur.
 717 
 718   __ str(rmethod, Address(rthread, JavaThread::callee_target_offset()));
 719 
 720   __ br(rscratch1);
 721 }
 722 
 723 // ---------------------------------------------------------------
 724 AdapterHandlerEntry* SharedRuntime::generate_i2c2i_adapters(MacroAssembler *masm,
 725                                                             int total_args_passed,
 726                                                             int comp_args_on_stack,
 727                                                             const BasicType *sig_bt,
 728                                                             const VMRegPair *regs,
 729                                                             AdapterFingerPrint* fingerprint) {
 730   address i2c_entry = __ pc();
 731 
 732   gen_i2c_adapter(masm, total_args_passed, comp_args_on_stack, sig_bt, regs);
 733 
 734   address c2i_unverified_entry = __ pc();
 735   Label skip_fixup;
 736 
 737   Label ok;
 738 
 739   Register holder = rscratch2;
 740   Register receiver = j_rarg0;
 741   Register tmp = r10;  // A call-clobbered register not used for arg passing
 742 
 743   // -------------------------------------------------------------------------
 744   // Generate a C2I adapter.  On entry we know rmethod holds the Method* during calls
 745   // to the interpreter.  The args start out packed in the compiled layout.  They
 746   // need to be unpacked into the interpreter layout.  This will almost always
 747   // require some stack space.  We grow the current (compiled) stack, then repack
 748   // the args.  We  finally end in a jump to the generic interpreter entry point.
 749   // On exit from the interpreter, the interpreter will restore our SP (lest the
 750   // compiled code, which relys solely on SP and not FP, get sick).
 751 
 752   {
 753     __ block_comment("c2i_unverified_entry {");
 754     __ load_klass(rscratch1, receiver);
 755     __ ldr(tmp, Address(holder, CompiledICHolder::holder_klass_offset()));
 756     __ cmp(rscratch1, tmp);
 757     __ ldr(rmethod, Address(holder, CompiledICHolder::holder_metadata_offset()));
 758     __ br(Assembler::EQ, ok);
 759     __ far_jump(RuntimeAddress(SharedRuntime::get_ic_miss_stub()));
 760 
 761     __ bind(ok);
 762     // Method might have been compiled since the call site was patched to
 763     // interpreted; if that is the case treat it as a miss so we can get
 764     // the call site corrected.
 765     __ ldr(rscratch1, Address(rmethod, in_bytes(Method::code_offset())));
 766     __ cbz(rscratch1, skip_fixup);
 767     __ far_jump(RuntimeAddress(SharedRuntime::get_ic_miss_stub()));
 768     __ block_comment("} c2i_unverified_entry");
 769   }
 770 
 771   address c2i_entry = __ pc();
 772 
 773   // Class initialization barrier for static methods
 774   address c2i_no_clinit_check_entry = NULL;
 775   if (VM_Version::supports_fast_class_init_checks()) {
 776     Label L_skip_barrier;
 777 
 778     { // Bypass the barrier for non-static methods
 779       __ ldrw(rscratch1, Address(rmethod, Method::access_flags_offset()));
 780       __ andsw(zr, rscratch1, JVM_ACC_STATIC);
 781       __ br(Assembler::EQ, L_skip_barrier); // non-static
 782     }
 783 
 784     __ load_method_holder(rscratch2, rmethod);
 785     __ clinit_barrier(rscratch2, rscratch1, &L_skip_barrier);
 786     __ far_jump(RuntimeAddress(SharedRuntime::get_handle_wrong_method_stub()));
 787 
 788     __ bind(L_skip_barrier);
 789     c2i_no_clinit_check_entry = __ pc();
 790   }
 791 
 792   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
 793   bs->c2i_entry_barrier(masm);
 794 
 795   gen_c2i_adapter(masm, total_args_passed, comp_args_on_stack, sig_bt, regs, skip_fixup);
 796 
 797   __ flush();
 798   return AdapterHandlerLibrary::new_entry(fingerprint, i2c_entry, c2i_entry, c2i_unverified_entry, c2i_no_clinit_check_entry);
 799 }
 800 
 801 static int c_calling_convention_priv(const BasicType *sig_bt,
 802                                          VMRegPair *regs,
 803                                          VMRegPair *regs2,
 804                                          int total_args_passed) {
 805   assert(regs2 == NULL, "not needed on AArch64");
 806 
 807 // We return the amount of VMRegImpl stack slots we need to reserve for all
 808 // the arguments NOT counting out_preserve_stack_slots.
 809 
 810     static const Register INT_ArgReg[Argument::n_int_register_parameters_c] = {
 811       c_rarg0, c_rarg1, c_rarg2, c_rarg3, c_rarg4, c_rarg5,  c_rarg6,  c_rarg7
 812     };
 813     static const FloatRegister FP_ArgReg[Argument::n_float_register_parameters_c] = {
 814       c_farg0, c_farg1, c_farg2, c_farg3,
 815       c_farg4, c_farg5, c_farg6, c_farg7
 816     };
 817 
 818     uint int_args = 0;
 819     uint fp_args = 0;
 820     uint stk_args = 0; // inc by 2 each time
 821 
 822     for (int i = 0; i < total_args_passed; i++) {
 823       switch (sig_bt[i]) {
 824       case T_BOOLEAN:
 825       case T_CHAR:
 826       case T_BYTE:
 827       case T_SHORT:
 828       case T_INT:
 829         if (int_args < Argument::n_int_register_parameters_c) {
 830           regs[i].set1(INT_ArgReg[int_args++]->as_VMReg());
 831         } else {
 832 #ifdef __APPLE__
 833           // Less-than word types are stored one after another.
 834           // The code is unable to handle this so bailout.
 835           return -1;
 836 #endif
 837           regs[i].set1(VMRegImpl::stack2reg(stk_args));
 838           stk_args += 2;
 839         }
 840         break;
 841       case T_LONG:
 842         assert((i + 1) < total_args_passed && sig_bt[i + 1] == T_VOID, "expecting half");
 843         // fall through
 844       case T_OBJECT:
 845       case T_ARRAY:
 846       case T_ADDRESS:
 847       case T_METADATA:
 848         if (int_args < Argument::n_int_register_parameters_c) {
 849           regs[i].set2(INT_ArgReg[int_args++]->as_VMReg());
 850         } else {
 851           regs[i].set2(VMRegImpl::stack2reg(stk_args));
 852           stk_args += 2;
 853         }
 854         break;
 855       case T_FLOAT:
 856         if (fp_args < Argument::n_float_register_parameters_c) {
 857           regs[i].set1(FP_ArgReg[fp_args++]->as_VMReg());
 858         } else {
 859 #ifdef __APPLE__
 860           // Less-than word types are stored one after another.
 861           // The code is unable to handle this so bailout.
 862           return -1;
 863 #endif
 864           regs[i].set1(VMRegImpl::stack2reg(stk_args));
 865           stk_args += 2;
 866         }
 867         break;
 868       case T_DOUBLE:
 869         assert((i + 1) < total_args_passed && sig_bt[i + 1] == T_VOID, "expecting half");
 870         if (fp_args < Argument::n_float_register_parameters_c) {
 871           regs[i].set2(FP_ArgReg[fp_args++]->as_VMReg());
 872         } else {
 873           regs[i].set2(VMRegImpl::stack2reg(stk_args));
 874           stk_args += 2;
 875         }
 876         break;
 877       case T_VOID: // Halves of longs and doubles
 878         assert(i != 0 && (sig_bt[i - 1] == T_LONG || sig_bt[i - 1] == T_DOUBLE), "expecting half");
 879         regs[i].set_bad();
 880         break;
 881       default:
 882         ShouldNotReachHere();
 883         break;
 884       }
 885     }
 886 
 887   return stk_args;
 888 }
 889 
 890 int SharedRuntime::vector_calling_convention(VMRegPair *regs,
 891                                              uint num_bits,
 892                                              uint total_args_passed) {
 893   Unimplemented();
 894   return 0;
 895 }
 896 
 897 int SharedRuntime::c_calling_convention(const BasicType *sig_bt,
 898                                          VMRegPair *regs,
 899                                          VMRegPair *regs2,
 900                                          int total_args_passed)
 901 {
 902   int result = c_calling_convention_priv(sig_bt, regs, regs2, total_args_passed);
 903   guarantee(result >= 0, "Unsupported arguments configuration");
 904   return result;
 905 }
 906 






































































































































































 907 
 908 void SharedRuntime::save_native_result(MacroAssembler *masm, BasicType ret_type, int frame_slots) {
 909   // We always ignore the frame_slots arg and just use the space just below frame pointer
 910   // which by this time is free to use
 911   switch (ret_type) {
 912   case T_FLOAT:
 913     __ strs(v0, Address(rfp, -wordSize));
 914     break;
 915   case T_DOUBLE:
 916     __ strd(v0, Address(rfp, -wordSize));
 917     break;
 918   case T_VOID:  break;
 919   default: {
 920     __ str(r0, Address(rfp, -wordSize));
 921     }
 922   }
 923 }
 924 
 925 void SharedRuntime::restore_native_result(MacroAssembler *masm, BasicType ret_type, int frame_slots) {
 926   // We always ignore the frame_slots arg and just use the space just below frame pointer
 927   // which by this time is free to use
 928   switch (ret_type) {
 929   case T_FLOAT:
 930     __ ldrs(v0, Address(rfp, -wordSize));
 931     break;
 932   case T_DOUBLE:
 933     __ ldrd(v0, Address(rfp, -wordSize));
 934     break;
 935   case T_VOID:  break;
 936   default: {
 937     __ ldr(r0, Address(rfp, -wordSize));
 938     }
 939   }
 940 }
 941 static void save_args(MacroAssembler *masm, int arg_count, int first_arg, VMRegPair *args) {
 942   RegSet x;
 943   for ( int i = first_arg ; i < arg_count ; i++ ) {
 944     if (args[i].first()->is_Register()) {
 945       x = x + args[i].first()->as_Register();
 946     } else if (args[i].first()->is_FloatRegister()) {
 947       __ strd(args[i].first()->as_FloatRegister(), Address(__ pre(sp, -2 * wordSize)));
 948     }
 949   }
 950   __ push(x, sp);
 951 }
 952 
 953 static void restore_args(MacroAssembler *masm, int arg_count, int first_arg, VMRegPair *args) {
 954   RegSet x;
 955   for ( int i = first_arg ; i < arg_count ; i++ ) {
 956     if (args[i].first()->is_Register()) {
 957       x = x + args[i].first()->as_Register();
 958     } else {
 959       ;
 960     }
 961   }
 962   __ pop(x, sp);
 963   for ( int i = arg_count - 1 ; i >= first_arg ; i-- ) {
 964     if (args[i].first()->is_Register()) {
 965       ;
 966     } else if (args[i].first()->is_FloatRegister()) {
 967       __ ldrd(args[i].first()->as_FloatRegister(), Address(__ post(sp, 2 * wordSize)));
 968     }
 969   }
 970 }
 971 










 972 static void verify_oop_args(MacroAssembler* masm,
 973                             const methodHandle& method,
 974                             const BasicType* sig_bt,
 975                             const VMRegPair* regs) {
 976   Register temp_reg = r19;  // not part of any compiled calling seq
 977   if (VerifyOops) {
 978     for (int i = 0; i < method->size_of_parameters(); i++) {
 979       if (sig_bt[i] == T_OBJECT ||
 980           sig_bt[i] == T_ARRAY) {
 981         VMReg r = regs[i].first();
 982         assert(r->is_valid(), "bad oop arg");
 983         if (r->is_stack()) {
 984           __ ldr(temp_reg, Address(sp, r->reg2stack() * VMRegImpl::stack_slot_size));
 985           __ verify_oop(temp_reg);
 986         } else {
 987           __ verify_oop(r->as_Register());
 988         }
 989       }
 990     }
 991   }
 992 }
 993 
 994 static void gen_special_dispatch(MacroAssembler* masm,
 995                                  const methodHandle& method,
 996                                  const BasicType* sig_bt,
 997                                  const VMRegPair* regs) {
 998   verify_oop_args(masm, method, sig_bt, regs);
 999   vmIntrinsics::ID iid = method->intrinsic_id();
1000 
1001   // Now write the args into the outgoing interpreter space
1002   bool     has_receiver   = false;
1003   Register receiver_reg   = noreg;
1004   int      member_arg_pos = -1;
1005   Register member_reg     = noreg;
1006   int      ref_kind       = MethodHandles::signature_polymorphic_intrinsic_ref_kind(iid);
1007   if (ref_kind != 0) {
1008     member_arg_pos = method->size_of_parameters() - 1;  // trailing MemberName argument
1009     member_reg = r19;  // known to be free at this point
1010     has_receiver = MethodHandles::ref_kind_has_receiver(ref_kind);
1011   } else if (iid == vmIntrinsics::_invokeBasic) {
1012     has_receiver = true;
1013   } else if (iid == vmIntrinsics::_linkToNative) {
1014     member_arg_pos = method->size_of_parameters() - 1;  // trailing NativeEntryPoint argument
1015     member_reg = r19;  // known to be free at this point
1016   } else {
1017     fatal("unexpected intrinsic id %d", vmIntrinsics::as_int(iid));
1018   }
1019 
1020   if (member_reg != noreg) {
1021     // Load the member_arg into register, if necessary.
1022     SharedRuntime::check_member_name_argument_is_last_argument(method, sig_bt, regs);
1023     VMReg r = regs[member_arg_pos].first();
1024     if (r->is_stack()) {
1025       __ ldr(member_reg, Address(sp, r->reg2stack() * VMRegImpl::stack_slot_size));
1026     } else {
1027       // no data motion is needed
1028       member_reg = r->as_Register();
1029     }
1030   }
1031 
1032   if (has_receiver) {
1033     // Make sure the receiver is loaded into a register.
1034     assert(method->size_of_parameters() > 0, "oob");
1035     assert(sig_bt[0] == T_OBJECT, "receiver argument must be an object");
1036     VMReg r = regs[0].first();
1037     assert(r->is_valid(), "bad receiver arg");
1038     if (r->is_stack()) {
1039       // Porting note:  This assumes that compiled calling conventions always
1040       // pass the receiver oop in a register.  If this is not true on some
1041       // platform, pick a temp and load the receiver from stack.
1042       fatal("receiver always in a register");
1043       receiver_reg = r2;  // known to be free at this point
1044       __ ldr(receiver_reg, Address(sp, r->reg2stack() * VMRegImpl::stack_slot_size));
1045     } else {
1046       // no data motion is needed
1047       receiver_reg = r->as_Register();
1048     }
1049   }
1050 
1051   // Figure out which address we are really jumping to:
1052   MethodHandles::generate_method_handle_dispatch(masm, iid,
1053                                                  receiver_reg, member_reg, /*for_compiler_entry:*/ true);
1054 }
1055 
1056 // ---------------------------------------------------------------------------
1057 // Generate a native wrapper for a given method.  The method takes arguments
1058 // in the Java compiled code convention, marshals them to the native
1059 // convention (handlizes oops, etc), transitions to native, makes the call,
1060 // returns to java state (possibly blocking), unhandlizes any result and
1061 // returns.
1062 //
1063 // Critical native functions are a shorthand for the use of
1064 // GetPrimtiveArrayCritical and disallow the use of any other JNI
1065 // functions.  The wrapper is expected to unpack the arguments before
1066 // passing them to the callee. Critical native functions leave the state _in_Java,
1067 // since they block out GC.
1068 // Some other parts of JNI setup are skipped like the tear down of the JNI handle
1069 // block and the check for pending exceptions it's impossible for them
1070 // to be thrown.
1071 //
1072 nmethod* SharedRuntime::generate_native_wrapper(MacroAssembler* masm,
1073                                                 const methodHandle& method,
1074                                                 int compile_id,
1075                                                 BasicType* in_sig_bt,
1076                                                 VMRegPair* in_regs,
1077                                                 BasicType ret_type) {
1078   if (method->is_method_handle_intrinsic()) {
1079     vmIntrinsics::ID iid = method->intrinsic_id();
1080     intptr_t start = (intptr_t)__ pc();
1081     int vep_offset = ((intptr_t)__ pc()) - start;
1082 
1083     // First instruction must be a nop as it may need to be patched on deoptimisation
1084     __ nop();
1085     gen_special_dispatch(masm,
1086                          method,
1087                          in_sig_bt,
1088                          in_regs);
1089     int frame_complete = ((intptr_t)__ pc()) - start;  // not complete, period
1090     __ flush();
1091     int stack_slots = SharedRuntime::out_preserve_stack_slots();  // no out slots at all, actually
1092     return nmethod::new_native_nmethod(method,
1093                                        compile_id,
1094                                        masm->code(),
1095                                        vep_offset,
1096                                        frame_complete,
1097                                        stack_slots / VMRegImpl::slots_per_word,
1098                                        in_ByteSize(-1),
1099                                        in_ByteSize(-1),
1100                                        (OopMapSet*)NULL);
1101   }
1102   address native_func = method->native_function();
1103   assert(native_func != NULL, "must have function");
1104 
1105   // An OopMap for lock (and class if static)
1106   OopMapSet *oop_maps = new OopMapSet();
1107   intptr_t start = (intptr_t)__ pc();
1108 
1109   // We have received a description of where all the java arg are located
1110   // on entry to the wrapper. We need to convert these args to where
1111   // the jni function will expect them. To figure out where they go
1112   // we convert the java signature to a C signature by inserting
1113   // the hidden arguments as arg[0] and possibly arg[1] (static method)
1114 
1115   const int total_in_args = method->size_of_parameters();
1116   int total_c_args = total_in_args + (method->is_static() ? 2 : 1);
1117 
1118   BasicType* out_sig_bt = NEW_RESOURCE_ARRAY(BasicType, total_c_args);
1119   VMRegPair* out_regs   = NEW_RESOURCE_ARRAY(VMRegPair, total_c_args);
1120   BasicType* in_elem_bt = NULL;
1121 
1122   int argc = 0;
1123   out_sig_bt[argc++] = T_ADDRESS;
1124   if (method->is_static()) {
1125     out_sig_bt[argc++] = T_OBJECT;
1126   }
1127 
1128   for (int i = 0; i < total_in_args ; i++ ) {
1129     out_sig_bt[argc++] = in_sig_bt[i];
1130   }
1131 
1132   // Now figure out where the args must be stored and how much stack space
1133   // they require.
1134   int out_arg_slots;
1135   out_arg_slots = c_calling_convention_priv(out_sig_bt, out_regs, NULL, total_c_args);
1136 
1137   if (out_arg_slots < 0) {
1138     return NULL;
1139   }
1140 
1141   // Compute framesize for the wrapper.  We need to handlize all oops in
1142   // incoming registers
1143 
1144   // Calculate the total number of stack slots we will need.
1145 
1146   // First count the abi requirement plus all of the outgoing args
1147   int stack_slots = SharedRuntime::out_preserve_stack_slots() + out_arg_slots;
1148 
1149   // Now the space for the inbound oop handle area
1150   int total_save_slots = 8 * VMRegImpl::slots_per_word;  // 8 arguments passed in registers
1151 
1152   int oop_handle_offset = stack_slots;
1153   stack_slots += total_save_slots;
1154 
1155   // Now any space we need for handlizing a klass if static method
1156 
1157   int klass_slot_offset = 0;
1158   int klass_offset = -1;
1159   int lock_slot_offset = 0;
1160   bool is_static = false;
1161 
1162   if (method->is_static()) {
1163     klass_slot_offset = stack_slots;
1164     stack_slots += VMRegImpl::slots_per_word;
1165     klass_offset = klass_slot_offset * VMRegImpl::stack_slot_size;
1166     is_static = true;
1167   }
1168 
1169   // Plus a lock if needed
1170 
1171   if (method->is_synchronized()) {
1172     lock_slot_offset = stack_slots;
1173     stack_slots += VMRegImpl::slots_per_word;
1174   }
1175 
1176   // Now a place (+2) to save return values or temp during shuffling
1177   // + 4 for return address (which we own) and saved rfp
1178   stack_slots += 6;
1179 
1180   // Ok The space we have allocated will look like:
1181   //
1182   //
1183   // FP-> |                     |
1184   //      |---------------------|
1185   //      | 2 slots for moves   |
1186   //      |---------------------|
1187   //      | lock box (if sync)  |
1188   //      |---------------------| <- lock_slot_offset
1189   //      | klass (if static)   |
1190   //      |---------------------| <- klass_slot_offset
1191   //      | oopHandle area      |
1192   //      |---------------------| <- oop_handle_offset (8 java arg registers)
1193   //      | outbound memory     |
1194   //      | based arguments     |
1195   //      |                     |
1196   //      |---------------------|
1197   //      |                     |
1198   // SP-> | out_preserved_slots |
1199   //
1200   //
1201 
1202 
1203   // Now compute actual number of stack words we need rounding to make
1204   // stack properly aligned.
1205   stack_slots = align_up(stack_slots, StackAlignmentInSlots);
1206 
1207   int stack_size = stack_slots * VMRegImpl::stack_slot_size;
1208 
1209   // First thing make an ic check to see if we should even be here
1210 
1211   // We are free to use all registers as temps without saving them and
1212   // restoring them except rfp. rfp is the only callee save register
1213   // as far as the interpreter and the compiler(s) are concerned.
1214 
1215 
1216   const Register ic_reg = rscratch2;
1217   const Register receiver = j_rarg0;
1218 
1219   Label hit;
1220   Label exception_pending;
1221 
1222   assert_different_registers(ic_reg, receiver, rscratch1);
1223   __ verify_oop(receiver);
1224   __ cmp_klass(receiver, ic_reg, rscratch1);
1225   __ br(Assembler::EQ, hit);
1226 
1227   __ far_jump(RuntimeAddress(SharedRuntime::get_ic_miss_stub()));
1228 
1229   // Verified entry point must be aligned
1230   __ align(8);
1231 
1232   __ bind(hit);
1233 
1234   int vep_offset = ((intptr_t)__ pc()) - start;
1235 
1236   // If we have to make this method not-entrant we'll overwrite its
1237   // first instruction with a jump.  For this action to be legal we
1238   // must ensure that this first instruction is a B, BL, NOP, BKPT,
1239   // SVC, HVC, or SMC.  Make it a NOP.
1240   __ nop();
1241 
1242   if (VM_Version::supports_fast_class_init_checks() && method->needs_clinit_barrier()) {
1243     Label L_skip_barrier;
1244     __ mov_metadata(rscratch2, method->method_holder()); // InstanceKlass*
1245     __ clinit_barrier(rscratch2, rscratch1, &L_skip_barrier);
1246     __ far_jump(RuntimeAddress(SharedRuntime::get_handle_wrong_method_stub()));
1247 
1248     __ bind(L_skip_barrier);
1249   }
1250 
1251   // Generate stack overflow check
1252   __ bang_stack_with_offset(checked_cast<int>(StackOverflow::stack_shadow_zone_size()));
1253 
1254   // Generate a new frame for the wrapper.
1255   __ enter();
1256   // -2 because return address is already present and so is saved rfp
1257   __ sub(sp, sp, stack_size - 2*wordSize);
1258 
1259   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
1260   bs->nmethod_entry_barrier(masm);
1261 
1262   // Frame is now completed as far as size and linkage.
1263   int frame_complete = ((intptr_t)__ pc()) - start;
1264 
1265   // We use r20 as the oop handle for the receiver/klass
1266   // It is callee save so it survives the call to native
1267 
1268   const Register oop_handle_reg = r20;
1269 
1270   //
1271   // We immediately shuffle the arguments so that any vm call we have to
1272   // make from here on out (sync slow path, jvmti, etc.) we will have
1273   // captured the oops from our caller and have a valid oopMap for
1274   // them.
1275 
1276   // -----------------
1277   // The Grand Shuffle
1278 
1279   // The Java calling convention is either equal (linux) or denser (win64) than the
1280   // c calling convention. However the because of the jni_env argument the c calling
1281   // convention always has at least one more (and two for static) arguments than Java.
1282   // Therefore if we move the args from java -> c backwards then we will never have
1283   // a register->register conflict and we don't have to build a dependency graph
1284   // and figure out how to break any cycles.
1285   //
1286 
1287   // Record esp-based slot for receiver on stack for non-static methods
1288   int receiver_offset = -1;
1289 
1290   // This is a trick. We double the stack slots so we can claim
1291   // the oops in the caller's frame. Since we are sure to have
1292   // more args than the caller doubling is enough to make
1293   // sure we can capture all the incoming oop args from the
1294   // caller.
1295   //
1296   OopMap* map = new OopMap(stack_slots * 2, 0 /* arg_slots*/);
1297 
1298   // Mark location of rfp (someday)
1299   // map->set_callee_saved(VMRegImpl::stack2reg( stack_slots - 2), stack_slots * 2, 0, vmreg(rfp));
1300 
1301 
1302   int float_args = 0;
1303   int int_args = 0;
1304 
1305 #ifdef ASSERT
1306   bool reg_destroyed[RegisterImpl::number_of_registers];
1307   bool freg_destroyed[FloatRegisterImpl::number_of_registers];
1308   for ( int r = 0 ; r < RegisterImpl::number_of_registers ; r++ ) {
1309     reg_destroyed[r] = false;
1310   }
1311   for ( int f = 0 ; f < FloatRegisterImpl::number_of_registers ; f++ ) {
1312     freg_destroyed[f] = false;
1313   }
1314 
1315 #endif /* ASSERT */
1316 
1317   // For JNI natives the incoming and outgoing registers are offset upwards.
1318   GrowableArray<int> arg_order(2 * total_in_args);
1319   VMRegPair tmp_vmreg;
1320   tmp_vmreg.set2(r19->as_VMReg());
1321 
1322   for (int i = total_in_args - 1, c_arg = total_c_args - 1; i >= 0; i--, c_arg--) {
1323     arg_order.push(i);
1324     arg_order.push(c_arg);
1325   }
1326 
1327   int temploc = -1;
1328   for (int ai = 0; ai < arg_order.length(); ai += 2) {
1329     int i = arg_order.at(ai);
1330     int c_arg = arg_order.at(ai + 1);
1331     __ block_comment(err_msg("move %d -> %d", i, c_arg));
1332     assert(c_arg != -1 && i != -1, "wrong order");
1333 #ifdef ASSERT
1334     if (in_regs[i].first()->is_Register()) {
1335       assert(!reg_destroyed[in_regs[i].first()->as_Register()->encoding()], "destroyed reg!");
1336     } else if (in_regs[i].first()->is_FloatRegister()) {
1337       assert(!freg_destroyed[in_regs[i].first()->as_FloatRegister()->encoding()], "destroyed reg!");
1338     }
1339     if (out_regs[c_arg].first()->is_Register()) {
1340       reg_destroyed[out_regs[c_arg].first()->as_Register()->encoding()] = true;
1341     } else if (out_regs[c_arg].first()->is_FloatRegister()) {
1342       freg_destroyed[out_regs[c_arg].first()->as_FloatRegister()->encoding()] = true;
1343     }
1344 #endif /* ASSERT */
1345     switch (in_sig_bt[i]) {
1346       case T_ARRAY:
1347       case T_OBJECT:
1348         __ object_move(map, oop_handle_offset, stack_slots, in_regs[i], out_regs[c_arg],
1349                        ((i == 0) && (!is_static)),
1350                        &receiver_offset);
1351         int_args++;
1352         break;
1353       case T_VOID:
1354         break;
1355 
1356       case T_FLOAT:
1357         __ float_move(in_regs[i], out_regs[c_arg]);
1358         float_args++;
1359         break;
1360 
1361       case T_DOUBLE:
1362         assert( i + 1 < total_in_args &&
1363                 in_sig_bt[i + 1] == T_VOID &&
1364                 out_sig_bt[c_arg+1] == T_VOID, "bad arg list");
1365         __ double_move(in_regs[i], out_regs[c_arg]);
1366         float_args++;
1367         break;
1368 
1369       case T_LONG :
1370         __ long_move(in_regs[i], out_regs[c_arg]);
1371         int_args++;
1372         break;
1373 
1374       case T_ADDRESS: assert(false, "found T_ADDRESS in java args");
1375 
1376       default:
1377         __ move32_64(in_regs[i], out_regs[c_arg]);
1378         int_args++;
1379     }
1380   }
1381 
1382   // point c_arg at the first arg that is already loaded in case we
1383   // need to spill before we call out
1384   int c_arg = total_c_args - total_in_args;
1385 
1386   // Pre-load a static method's oop into c_rarg1.
1387   if (method->is_static()) {
1388 
1389     //  load oop into a register
1390     __ movoop(c_rarg1,
1391               JNIHandles::make_local(method->method_holder()->java_mirror()),
1392               /*immediate*/true);
1393 
1394     // Now handlize the static class mirror it's known not-null.
1395     __ str(c_rarg1, Address(sp, klass_offset));
1396     map->set_oop(VMRegImpl::stack2reg(klass_slot_offset));
1397 
1398     // Now get the handle
1399     __ lea(c_rarg1, Address(sp, klass_offset));
1400     // and protect the arg if we must spill
1401     c_arg--;
1402   }
1403 
1404   // Change state to native (we save the return address in the thread, since it might not
1405   // be pushed on the stack when we do a stack traversal).
1406   // We use the same pc/oopMap repeatedly when we call out
1407 
1408   Label native_return;
1409   __ set_last_Java_frame(sp, noreg, native_return, rscratch1);
1410 
1411   Label dtrace_method_entry, dtrace_method_entry_done;
1412   {
1413     uint64_t offset;
1414     __ adrp(rscratch1, ExternalAddress((address)&DTraceMethodProbes), offset);
1415     __ ldrb(rscratch1, Address(rscratch1, offset));
1416     __ cbnzw(rscratch1, dtrace_method_entry);
1417     __ bind(dtrace_method_entry_done);
1418   }
1419 
1420   // RedefineClasses() tracing support for obsolete method entry
1421   if (log_is_enabled(Trace, redefine, class, obsolete)) {
1422     // protect the args we've loaded
1423     save_args(masm, total_c_args, c_arg, out_regs);
1424     __ mov_metadata(c_rarg1, method());
1425     __ call_VM_leaf(
1426       CAST_FROM_FN_PTR(address, SharedRuntime::rc_trace_method_entry),
1427       rthread, c_rarg1);
1428     restore_args(masm, total_c_args, c_arg, out_regs);
1429   }
1430 
1431   // Lock a synchronized method
1432 
1433   // Register definitions used by locking and unlocking
1434 
1435   const Register swap_reg = r0;
1436   const Register obj_reg  = r19;  // Will contain the oop
1437   const Register lock_reg = r13;  // Address of compiler lock object (BasicLock)
1438   const Register old_hdr  = r13;  // value of old header at unlock time
1439   const Register tmp = lr;
1440 
1441   Label slow_path_lock;
1442   Label lock_done;
1443 
1444   if (method->is_synchronized()) {
1445 
1446     const int mark_word_offset = BasicLock::displaced_header_offset_in_bytes();
1447 
1448     // Get the handle (the 2nd argument)
1449     __ mov(oop_handle_reg, c_rarg1);
1450 
1451     // Get address of the box
1452 
1453     __ lea(lock_reg, Address(sp, lock_slot_offset * VMRegImpl::stack_slot_size));
1454 
1455     // Load the oop from the handle
1456     __ ldr(obj_reg, Address(oop_handle_reg, 0));
1457 
1458     if (!UseHeavyMonitors) {
1459       // Load (object->mark() | 1) into swap_reg %r0
1460       __ ldr(rscratch1, Address(obj_reg, oopDesc::mark_offset_in_bytes()));
1461       __ orr(swap_reg, rscratch1, 1);
1462 
1463       // Save (object->mark() | 1) into BasicLock's displaced header
1464       __ str(swap_reg, Address(lock_reg, mark_word_offset));
1465 
1466       // src -> dest iff dest == r0 else r0 <- dest
1467       { Label here;
1468         __ cmpxchg_obj_header(r0, lock_reg, obj_reg, rscratch1, lock_done, /*fallthrough*/NULL);
1469       }
1470 
1471       // Hmm should this move to the slow path code area???
1472 
1473       // Test if the oopMark is an obvious stack pointer, i.e.,
1474       //  1) (mark & 3) == 0, and
1475       //  2) sp <= mark < mark + os::pagesize()
1476       // These 3 tests can be done by evaluating the following
1477       // expression: ((mark - sp) & (3 - os::vm_page_size())),
1478       // assuming both stack pointer and pagesize have their
1479       // least significant 2 bits clear.
1480       // NOTE: the oopMark is in swap_reg %r0 as the result of cmpxchg
1481 
1482       __ sub(swap_reg, sp, swap_reg);
1483       __ neg(swap_reg, swap_reg);
1484       __ ands(swap_reg, swap_reg, 3 - os::vm_page_size());
1485 
1486       // Save the test result, for recursive case, the result is zero
1487       __ str(swap_reg, Address(lock_reg, mark_word_offset));
1488       __ br(Assembler::NE, slow_path_lock);
1489     } else {
1490       __ b(slow_path_lock);
1491     }
1492 
1493     // Slow path will re-enter here
1494     __ bind(lock_done);
1495   }
1496 
1497 
1498   // Finally just about ready to make the JNI call
1499 
1500   // get JNIEnv* which is first argument to native
1501   __ lea(c_rarg0, Address(rthread, in_bytes(JavaThread::jni_environment_offset())));
1502 
1503   // Now set thread in native
1504   __ mov(rscratch1, _thread_in_native);
1505   __ lea(rscratch2, Address(rthread, JavaThread::thread_state_offset()));
1506   __ stlrw(rscratch1, rscratch2);
1507 
1508   __ rt_call(native_func);
1509 
1510   __ bind(native_return);
1511 
1512   intptr_t return_pc = (intptr_t) __ pc();
1513   oop_maps->add_gc_map(return_pc - start, map);
1514 
1515   // Unpack native results.
1516   switch (ret_type) {
1517   case T_BOOLEAN: __ c2bool(r0);                     break;
1518   case T_CHAR   : __ ubfx(r0, r0, 0, 16);            break;
1519   case T_BYTE   : __ sbfx(r0, r0, 0, 8);             break;
1520   case T_SHORT  : __ sbfx(r0, r0, 0, 16);            break;
1521   case T_INT    : __ sbfx(r0, r0, 0, 32);            break;
1522   case T_DOUBLE :
1523   case T_FLOAT  :
1524     // Result is in v0 we'll save as needed
1525     break;
1526   case T_ARRAY:                 // Really a handle
1527   case T_OBJECT:                // Really a handle
1528       break; // can't de-handlize until after safepoint check
1529   case T_VOID: break;
1530   case T_LONG: break;
1531   default       : ShouldNotReachHere();
1532   }
1533 
1534   Label safepoint_in_progress, safepoint_in_progress_done;
1535   Label after_transition;
1536 
1537   // Switch thread to "native transition" state before reading the synchronization state.
1538   // This additional state is necessary because reading and testing the synchronization
1539   // state is not atomic w.r.t. GC, as this scenario demonstrates:
1540   //     Java thread A, in _thread_in_native state, loads _not_synchronized and is preempted.
1541   //     VM thread changes sync state to synchronizing and suspends threads for GC.
1542   //     Thread A is resumed to finish this native method, but doesn't block here since it
1543   //     didn't see any synchronization is progress, and escapes.
1544   __ mov(rscratch1, _thread_in_native_trans);
1545 
1546   __ strw(rscratch1, Address(rthread, JavaThread::thread_state_offset()));
1547 
1548   // Force this write out before the read below
1549   __ dmb(Assembler::ISH);
1550 
1551   __ verify_sve_vector_length();
1552 
1553   // Check for safepoint operation in progress and/or pending suspend requests.
1554   {
1555     // We need an acquire here to ensure that any subsequent load of the
1556     // global SafepointSynchronize::_state flag is ordered after this load
1557     // of the thread-local polling word.  We don't want this poll to
1558     // return false (i.e. not safepointing) and a later poll of the global
1559     // SafepointSynchronize::_state spuriously to return true.
1560     //
1561     // This is to avoid a race when we're in a native->Java transition
1562     // racing the code which wakes up from a safepoint.
1563 
1564     __ safepoint_poll(safepoint_in_progress, true /* at_return */, true /* acquire */, false /* in_nmethod */);
1565     __ ldrw(rscratch1, Address(rthread, JavaThread::suspend_flags_offset()));
1566     __ cbnzw(rscratch1, safepoint_in_progress);
1567     __ bind(safepoint_in_progress_done);
1568   }
1569 
1570   // change thread state
1571   __ mov(rscratch1, _thread_in_Java);
1572   __ lea(rscratch2, Address(rthread, JavaThread::thread_state_offset()));
1573   __ stlrw(rscratch1, rscratch2);
1574   __ bind(after_transition);
1575 
1576   Label reguard;
1577   Label reguard_done;
1578   __ ldrb(rscratch1, Address(rthread, JavaThread::stack_guard_state_offset()));
1579   __ cmpw(rscratch1, StackOverflow::stack_guard_yellow_reserved_disabled);
1580   __ br(Assembler::EQ, reguard);
1581   __ bind(reguard_done);
1582 
1583   // native result if any is live
1584 
1585   // Unlock
1586   Label unlock_done;
1587   Label slow_path_unlock;
1588   if (method->is_synchronized()) {
1589 
1590     // Get locked oop from the handle we passed to jni
1591     __ ldr(obj_reg, Address(oop_handle_reg, 0));
1592 
1593     Label done;
1594 
1595     if (!UseHeavyMonitors) {
1596       // Simple recursive lock?
1597       __ ldr(rscratch1, Address(sp, lock_slot_offset * VMRegImpl::stack_slot_size));
1598       __ cbz(rscratch1, done);
1599     }
1600 
1601     // Must save r0 if if it is live now because cmpxchg must use it
1602     if (ret_type != T_FLOAT && ret_type != T_DOUBLE && ret_type != T_VOID) {
1603       save_native_result(masm, ret_type, stack_slots);
1604     }
1605 
1606     if (!UseHeavyMonitors) {
1607       // get address of the stack lock
1608       __ lea(r0, Address(sp, lock_slot_offset * VMRegImpl::stack_slot_size));
1609       //  get old displaced header
1610       __ ldr(old_hdr, Address(r0, 0));
1611 
1612       // Atomic swap old header if oop still contains the stack lock
1613       Label succeed;
1614       __ cmpxchg_obj_header(r0, old_hdr, obj_reg, rscratch1, succeed, &slow_path_unlock);
1615       __ bind(succeed);
1616     } else {
1617       __ b(slow_path_unlock);
1618     }
1619 
1620     // slow path re-enters here
1621     __ bind(unlock_done);
1622     if (ret_type != T_FLOAT && ret_type != T_DOUBLE && ret_type != T_VOID) {
1623       restore_native_result(masm, ret_type, stack_slots);
1624     }
1625 
1626     __ bind(done);
1627   }
1628 
1629   Label dtrace_method_exit, dtrace_method_exit_done;
1630   {
1631     uint64_t offset;
1632     __ adrp(rscratch1, ExternalAddress((address)&DTraceMethodProbes), offset);
1633     __ ldrb(rscratch1, Address(rscratch1, offset));
1634     __ cbnzw(rscratch1, dtrace_method_exit);
1635     __ bind(dtrace_method_exit_done);
1636   }
1637 
1638   __ reset_last_Java_frame(false);
1639 
1640   // Unbox oop result, e.g. JNIHandles::resolve result.
1641   if (is_reference_type(ret_type)) {
1642     __ resolve_jobject(r0, rthread, rscratch2);
1643   }
1644 
1645   if (CheckJNICalls) {
1646     // clear_pending_jni_exception_check
1647     __ str(zr, Address(rthread, JavaThread::pending_jni_exception_check_fn_offset()));
1648   }
1649 
1650   // reset handle block
1651   __ ldr(r2, Address(rthread, JavaThread::active_handles_offset()));
1652   __ str(zr, Address(r2, JNIHandleBlock::top_offset_in_bytes()));
1653 
1654   __ leave();
1655 
1656   // Any exception pending?
1657   __ ldr(rscratch1, Address(rthread, in_bytes(Thread::pending_exception_offset())));
1658   __ cbnz(rscratch1, exception_pending);
1659 
1660   // We're done
1661   __ ret(lr);
1662 
1663   // Unexpected paths are out of line and go here
1664 
1665   // forward the exception
1666   __ bind(exception_pending);
1667 
1668   // and forward the exception
1669   __ far_jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
1670 
1671   // Slow path locking & unlocking
1672   if (method->is_synchronized()) {
1673 
1674     __ block_comment("Slow path lock {");
1675     __ bind(slow_path_lock);
1676 
1677     // has last_Java_frame setup. No exceptions so do vanilla call not call_VM
1678     // args are (oop obj, BasicLock* lock, JavaThread* thread)
1679 
1680     // protect the args we've loaded
1681     save_args(masm, total_c_args, c_arg, out_regs);
1682 
1683     __ mov(c_rarg0, obj_reg);
1684     __ mov(c_rarg1, lock_reg);
1685     __ mov(c_rarg2, rthread);
1686 
1687     // Not a leaf but we have last_Java_frame setup as we want
1688     __ call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::complete_monitor_locking_C), 3);
1689     restore_args(masm, total_c_args, c_arg, out_regs);
1690 
1691 #ifdef ASSERT
1692     { Label L;
1693       __ ldr(rscratch1, Address(rthread, in_bytes(Thread::pending_exception_offset())));
1694       __ cbz(rscratch1, L);
1695       __ stop("no pending exception allowed on exit from monitorenter");
1696       __ bind(L);
1697     }
1698 #endif
1699     __ b(lock_done);
1700 
1701     __ block_comment("} Slow path lock");
1702 
1703     __ block_comment("Slow path unlock {");
1704     __ bind(slow_path_unlock);
1705 
1706     // If we haven't already saved the native result we must save it now as xmm registers
1707     // are still exposed.
1708 
1709     if (ret_type == T_FLOAT || ret_type == T_DOUBLE ) {
1710       save_native_result(masm, ret_type, stack_slots);
1711     }
1712 
1713     __ mov(c_rarg2, rthread);
1714     __ lea(c_rarg1, Address(sp, lock_slot_offset * VMRegImpl::stack_slot_size));
1715     __ mov(c_rarg0, obj_reg);
1716 
1717     // Save pending exception around call to VM (which contains an EXCEPTION_MARK)
1718     // NOTE that obj_reg == r19 currently
1719     __ ldr(r19, Address(rthread, in_bytes(Thread::pending_exception_offset())));
1720     __ str(zr, Address(rthread, in_bytes(Thread::pending_exception_offset())));
1721 
1722     __ rt_call(CAST_FROM_FN_PTR(address, SharedRuntime::complete_monitor_unlocking_C));
1723 
1724 #ifdef ASSERT
1725     {
1726       Label L;
1727       __ ldr(rscratch1, Address(rthread, in_bytes(Thread::pending_exception_offset())));
1728       __ cbz(rscratch1, L);
1729       __ stop("no pending exception allowed on exit complete_monitor_unlocking_C");
1730       __ bind(L);
1731     }
1732 #endif /* ASSERT */
1733 
1734     __ str(r19, Address(rthread, in_bytes(Thread::pending_exception_offset())));
1735 
1736     if (ret_type == T_FLOAT || ret_type == T_DOUBLE ) {
1737       restore_native_result(masm, ret_type, stack_slots);
1738     }
1739     __ b(unlock_done);
1740 
1741     __ block_comment("} Slow path unlock");
1742 
1743   } // synchronized
1744 
1745   // SLOW PATH Reguard the stack if needed
1746 
1747   __ bind(reguard);
1748   save_native_result(masm, ret_type, stack_slots);
1749   __ rt_call(CAST_FROM_FN_PTR(address, SharedRuntime::reguard_yellow_pages));
1750   restore_native_result(masm, ret_type, stack_slots);
1751   // and continue
1752   __ b(reguard_done);
1753 
1754   // SLOW PATH safepoint
1755   {
1756     __ block_comment("safepoint {");
1757     __ bind(safepoint_in_progress);
1758 
1759     // Don't use call_VM as it will see a possible pending exception and forward it
1760     // and never return here preventing us from clearing _last_native_pc down below.
1761     //
1762     save_native_result(masm, ret_type, stack_slots);
1763     __ mov(c_rarg0, rthread);
1764 #ifndef PRODUCT
1765   assert(frame::arg_reg_save_area_bytes == 0, "not expecting frame reg save area");
1766 #endif
1767     __ lea(rscratch1, RuntimeAddress(CAST_FROM_FN_PTR(address, JavaThread::check_special_condition_for_native_trans)));
1768     __ blr(rscratch1);
1769 
1770     // Restore any method result value
1771     restore_native_result(masm, ret_type, stack_slots);
1772 
1773     __ b(safepoint_in_progress_done);
1774     __ block_comment("} safepoint");
1775   }
1776 
1777   // SLOW PATH dtrace support
1778   {
1779     __ block_comment("dtrace entry {");
1780     __ bind(dtrace_method_entry);
1781 
1782     // We have all of the arguments setup at this point. We must not touch any register
1783     // argument registers at this point (what if we save/restore them there are no oop?
1784 
1785     save_args(masm, total_c_args, c_arg, out_regs);
1786     __ mov_metadata(c_rarg1, method());
1787     __ call_VM_leaf(
1788       CAST_FROM_FN_PTR(address, SharedRuntime::dtrace_method_entry),
1789       rthread, c_rarg1);
1790     restore_args(masm, total_c_args, c_arg, out_regs);
1791     __ b(dtrace_method_entry_done);
1792     __ block_comment("} dtrace entry");
1793   }
1794 
1795   {
1796     __ block_comment("dtrace exit {");
1797     __ bind(dtrace_method_exit);
1798     save_native_result(masm, ret_type, stack_slots);
1799     __ mov_metadata(c_rarg1, method());
1800     __ call_VM_leaf(
1801          CAST_FROM_FN_PTR(address, SharedRuntime::dtrace_method_exit),
1802          rthread, c_rarg1);
1803     restore_native_result(masm, ret_type, stack_slots);
1804     __ b(dtrace_method_exit_done);
1805     __ block_comment("} dtrace exit");
1806   }
1807 
1808 
1809   __ flush();
1810 
1811   nmethod *nm = nmethod::new_native_nmethod(method,
1812                                             compile_id,
1813                                             masm->code(),
1814                                             vep_offset,
1815                                             frame_complete,
1816                                             stack_slots / VMRegImpl::slots_per_word,
1817                                             (is_static ? in_ByteSize(klass_offset) : in_ByteSize(receiver_offset)),
1818                                             in_ByteSize(lock_slot_offset*VMRegImpl::stack_slot_size),
1819                                             oop_maps);
1820 
1821   return nm;
1822 }
1823 
1824 // this function returns the adjust size (in number of words) to a c2i adapter
1825 // activation for use during deoptimization
1826 int Deoptimization::last_frame_adjust(int callee_parameters, int callee_locals) {
1827   assert(callee_locals >= callee_parameters,
1828           "test and remove; got more parms than locals");
1829   if (callee_locals < callee_parameters)
1830     return 0;                   // No adjustment for negative locals
1831   int diff = (callee_locals - callee_parameters) * Interpreter::stackElementWords;
1832   // diff is counted in stack words
1833   return align_up(diff, 2);
1834 }
1835 
1836 
1837 //------------------------------generate_deopt_blob----------------------------
1838 void SharedRuntime::generate_deopt_blob() {
1839   // Allocate space for the code
1840   ResourceMark rm;
1841   // Setup code generation tools
1842   int pad = 0;
1843 #if INCLUDE_JVMCI
1844   if (EnableJVMCI) {
1845     pad += 512; // Increase the buffer size when compiling for JVMCI
1846   }
1847 #endif
1848   CodeBuffer buffer("deopt_blob", 2048+pad, 1024);
1849   MacroAssembler* masm = new MacroAssembler(&buffer);
1850   int frame_size_in_words;
1851   OopMap* map = NULL;
1852   OopMapSet *oop_maps = new OopMapSet();
1853   RegisterSaver reg_save(COMPILER2_OR_JVMCI != 0);
1854 
1855   // -------------
1856   // This code enters when returning to a de-optimized nmethod.  A return
1857   // address has been pushed on the the stack, and return values are in
1858   // registers.
1859   // If we are doing a normal deopt then we were called from the patched
1860   // nmethod from the point we returned to the nmethod. So the return
1861   // address on the stack is wrong by NativeCall::instruction_size
1862   // We will adjust the value so it looks like we have the original return
1863   // address on the stack (like when we eagerly deoptimized).
1864   // In the case of an exception pending when deoptimizing, we enter
1865   // with a return address on the stack that points after the call we patched
1866   // into the exception handler. We have the following register state from,
1867   // e.g., the forward exception stub (see stubGenerator_x86_64.cpp).
1868   //    r0: exception oop
1869   //    r19: exception handler
1870   //    r3: throwing pc
1871   // So in this case we simply jam r3 into the useless return address and
1872   // the stack looks just like we want.
1873   //
1874   // At this point we need to de-opt.  We save the argument return
1875   // registers.  We call the first C routine, fetch_unroll_info().  This
1876   // routine captures the return values and returns a structure which
1877   // describes the current frame size and the sizes of all replacement frames.
1878   // The current frame is compiled code and may contain many inlined
1879   // functions, each with their own JVM state.  We pop the current frame, then
1880   // push all the new frames.  Then we call the C routine unpack_frames() to
1881   // populate these frames.  Finally unpack_frames() returns us the new target
1882   // address.  Notice that callee-save registers are BLOWN here; they have
1883   // already been captured in the vframeArray at the time the return PC was
1884   // patched.
1885   address start = __ pc();
1886   Label cont;
1887 
1888   // Prolog for non exception case!
1889 
1890   // Save everything in sight.
1891   map = reg_save.save_live_registers(masm, 0, &frame_size_in_words);
1892 
1893   // Normal deoptimization.  Save exec mode for unpack_frames.
1894   __ movw(rcpool, Deoptimization::Unpack_deopt); // callee-saved
1895   __ b(cont);
1896 
1897   int reexecute_offset = __ pc() - start;
1898 #if INCLUDE_JVMCI && !defined(COMPILER1)
1899   if (EnableJVMCI && UseJVMCICompiler) {
1900     // JVMCI does not use this kind of deoptimization
1901     __ should_not_reach_here();
1902   }
1903 #endif
1904 
1905   // Reexecute case
1906   // return address is the pc describes what bci to do re-execute at
1907 
1908   // No need to update map as each call to save_live_registers will produce identical oopmap
1909   (void) reg_save.save_live_registers(masm, 0, &frame_size_in_words);
1910 
1911   __ movw(rcpool, Deoptimization::Unpack_reexecute); // callee-saved
1912   __ b(cont);
1913 
1914 #if INCLUDE_JVMCI
1915   Label after_fetch_unroll_info_call;
1916   int implicit_exception_uncommon_trap_offset = 0;
1917   int uncommon_trap_offset = 0;
1918 
1919   if (EnableJVMCI) {
1920     implicit_exception_uncommon_trap_offset = __ pc() - start;
1921 
1922     __ ldr(lr, Address(rthread, in_bytes(JavaThread::jvmci_implicit_exception_pc_offset())));
1923     __ str(zr, Address(rthread, in_bytes(JavaThread::jvmci_implicit_exception_pc_offset())));
1924 
1925     uncommon_trap_offset = __ pc() - start;
1926 
1927     // Save everything in sight.
1928     reg_save.save_live_registers(masm, 0, &frame_size_in_words);
1929     // fetch_unroll_info needs to call last_java_frame()
1930     Label retaddr;
1931     __ set_last_Java_frame(sp, noreg, retaddr, rscratch1);
1932 
1933     __ ldrw(c_rarg1, Address(rthread, in_bytes(JavaThread::pending_deoptimization_offset())));
1934     __ movw(rscratch1, -1);
1935     __ strw(rscratch1, Address(rthread, in_bytes(JavaThread::pending_deoptimization_offset())));
1936 
1937     __ movw(rcpool, (int32_t)Deoptimization::Unpack_reexecute);
1938     __ mov(c_rarg0, rthread);
1939     __ movw(c_rarg2, rcpool); // exec mode
1940     __ lea(rscratch1,
1941            RuntimeAddress(CAST_FROM_FN_PTR(address,
1942                                            Deoptimization::uncommon_trap)));
1943     __ blr(rscratch1);
1944     __ bind(retaddr);
1945     oop_maps->add_gc_map( __ pc()-start, map->deep_copy());
1946 
1947     __ reset_last_Java_frame(false);
1948 
1949     __ b(after_fetch_unroll_info_call);
1950   } // EnableJVMCI
1951 #endif // INCLUDE_JVMCI
1952 
1953   int exception_offset = __ pc() - start;
1954 
1955   // Prolog for exception case
1956 
1957   // all registers are dead at this entry point, except for r0, and
1958   // r3 which contain the exception oop and exception pc
1959   // respectively.  Set them in TLS and fall thru to the
1960   // unpack_with_exception_in_tls entry point.
1961 
1962   __ str(r3, Address(rthread, JavaThread::exception_pc_offset()));
1963   __ str(r0, Address(rthread, JavaThread::exception_oop_offset()));
1964 
1965   int exception_in_tls_offset = __ pc() - start;
1966 
1967   // new implementation because exception oop is now passed in JavaThread
1968 
1969   // Prolog for exception case
1970   // All registers must be preserved because they might be used by LinearScan
1971   // Exceptiop oop and throwing PC are passed in JavaThread
1972   // tos: stack at point of call to method that threw the exception (i.e. only
1973   // args are on the stack, no return address)
1974 
1975   // The return address pushed by save_live_registers will be patched
1976   // later with the throwing pc. The correct value is not available
1977   // now because loading it from memory would destroy registers.
1978 
1979   // NB: The SP at this point must be the SP of the method that is
1980   // being deoptimized.  Deoptimization assumes that the frame created
1981   // here by save_live_registers is immediately below the method's SP.
1982   // This is a somewhat fragile mechanism.
1983 
1984   // Save everything in sight.
1985   map = reg_save.save_live_registers(masm, 0, &frame_size_in_words);
1986 
1987   // Now it is safe to overwrite any register
1988 
1989   // Deopt during an exception.  Save exec mode for unpack_frames.
1990   __ mov(rcpool, Deoptimization::Unpack_exception); // callee-saved
1991 
1992   // load throwing pc from JavaThread and patch it as the return address
1993   // of the current frame. Then clear the field in JavaThread
1994 
1995   __ ldr(r3, Address(rthread, JavaThread::exception_pc_offset()));
1996   __ str(r3, Address(rfp, wordSize));
1997   __ str(zr, Address(rthread, JavaThread::exception_pc_offset()));
1998 
1999 #ifdef ASSERT
2000   // verify that there is really an exception oop in JavaThread
2001   __ ldr(r0, Address(rthread, JavaThread::exception_oop_offset()));
2002   __ verify_oop(r0);
2003 
2004   // verify that there is no pending exception
2005   Label no_pending_exception;
2006   __ ldr(rscratch1, Address(rthread, Thread::pending_exception_offset()));
2007   __ cbz(rscratch1, no_pending_exception);
2008   __ stop("must not have pending exception here");
2009   __ bind(no_pending_exception);
2010 #endif
2011 
2012   __ bind(cont);
2013 
2014   // Call C code.  Need thread and this frame, but NOT official VM entry
2015   // crud.  We cannot block on this call, no GC can happen.
2016   //
2017   // UnrollBlock* fetch_unroll_info(JavaThread* thread)
2018 
2019   // fetch_unroll_info needs to call last_java_frame().
2020 
2021   Label retaddr;
2022   __ set_last_Java_frame(sp, noreg, retaddr, rscratch1);
2023 #ifdef ASSERT0
2024   { Label L;
2025     __ ldr(rscratch1, Address(rthread,
2026                               JavaThread::last_Java_fp_offset()));
2027     __ cbz(rscratch1, L);
2028     __ stop("SharedRuntime::generate_deopt_blob: last_Java_fp not cleared");
2029     __ bind(L);
2030   }
2031 #endif // ASSERT
2032   __ mov(c_rarg0, rthread);
2033   __ mov(c_rarg1, rcpool);
2034   __ lea(rscratch1, RuntimeAddress(CAST_FROM_FN_PTR(address, Deoptimization::fetch_unroll_info)));
2035   __ blr(rscratch1);
2036   __ bind(retaddr);
2037 
2038   // Need to have an oopmap that tells fetch_unroll_info where to
2039   // find any register it might need.
2040   oop_maps->add_gc_map(__ pc() - start, map);
2041 
2042   __ reset_last_Java_frame(false);
2043 
2044 #if INCLUDE_JVMCI
2045   if (EnableJVMCI) {
2046     __ bind(after_fetch_unroll_info_call);
2047   }
2048 #endif
2049 
2050   // Load UnrollBlock* into r5
2051   __ mov(r5, r0);
2052 
2053   __ ldrw(rcpool, Address(r5, Deoptimization::UnrollBlock::unpack_kind_offset_in_bytes()));
2054    Label noException;
2055   __ cmpw(rcpool, Deoptimization::Unpack_exception);   // Was exception pending?
2056   __ br(Assembler::NE, noException);
2057   __ ldr(r0, Address(rthread, JavaThread::exception_oop_offset()));
2058   // QQQ this is useless it was NULL above
2059   __ ldr(r3, Address(rthread, JavaThread::exception_pc_offset()));
2060   __ str(zr, Address(rthread, JavaThread::exception_oop_offset()));
2061   __ str(zr, Address(rthread, JavaThread::exception_pc_offset()));
2062 
2063   __ verify_oop(r0);
2064 
2065   // Overwrite the result registers with the exception results.
2066   __ str(r0, Address(sp, reg_save.r0_offset_in_bytes()));
2067   // I think this is useless
2068   // __ str(r3, Address(sp, RegisterSaver::r3_offset_in_bytes()));
2069 
2070   __ bind(noException);
2071 
2072   // Only register save data is on the stack.
2073   // Now restore the result registers.  Everything else is either dead
2074   // or captured in the vframeArray.
2075 
2076   // Restore fp result register
2077   __ ldrd(v0, Address(sp, reg_save.v0_offset_in_bytes()));
2078   // Restore integer result register
2079   __ ldr(r0, Address(sp, reg_save.r0_offset_in_bytes()));
2080 
2081   // Pop all of the register save area off the stack
2082   __ add(sp, sp, frame_size_in_words * wordSize);
2083 
2084   // All of the register save area has been popped of the stack. Only the
2085   // return address remains.
2086 
2087   // Pop all the frames we must move/replace.
2088   //
2089   // Frame picture (youngest to oldest)
2090   // 1: self-frame (no frame link)
2091   // 2: deopting frame  (no frame link)
2092   // 3: caller of deopting frame (could be compiled/interpreted).
2093   //
2094   // Note: by leaving the return address of self-frame on the stack
2095   // and using the size of frame 2 to adjust the stack
2096   // when we are done the return to frame 3 will still be on the stack.
2097 
2098   // Pop deoptimized frame
2099   __ ldrw(r2, Address(r5, Deoptimization::UnrollBlock::size_of_deoptimized_frame_offset_in_bytes()));
2100   __ sub(r2, r2, 2 * wordSize);
2101   __ add(sp, sp, r2);
2102   __ ldp(rfp, lr, __ post(sp, 2 * wordSize));
2103   // LR should now be the return address to the caller (3)
2104 
2105 #ifdef ASSERT
2106   // Compilers generate code that bang the stack by as much as the
2107   // interpreter would need. So this stack banging should never
2108   // trigger a fault. Verify that it does not on non product builds.
2109   __ ldrw(r19, Address(r5, Deoptimization::UnrollBlock::total_frame_sizes_offset_in_bytes()));
2110   __ bang_stack_size(r19, r2);
2111 #endif
2112   // Load address of array of frame pcs into r2
2113   __ ldr(r2, Address(r5, Deoptimization::UnrollBlock::frame_pcs_offset_in_bytes()));
2114 
2115   // Trash the old pc
2116   // __ addptr(sp, wordSize);  FIXME ????
2117 
2118   // Load address of array of frame sizes into r4
2119   __ ldr(r4, Address(r5, Deoptimization::UnrollBlock::frame_sizes_offset_in_bytes()));
2120 
2121   // Load counter into r3
2122   __ ldrw(r3, Address(r5, Deoptimization::UnrollBlock::number_of_frames_offset_in_bytes()));
2123 
2124   // Now adjust the caller's stack to make up for the extra locals
2125   // but record the original sp so that we can save it in the skeletal interpreter
2126   // frame and the stack walking of interpreter_sender will get the unextended sp
2127   // value and not the "real" sp value.
2128 
2129   const Register sender_sp = r6;
2130 
2131   __ mov(sender_sp, sp);
2132   __ ldrw(r19, Address(r5,
2133                        Deoptimization::UnrollBlock::
2134                        caller_adjustment_offset_in_bytes()));
2135   __ sub(sp, sp, r19);
2136 
2137   // Push interpreter frames in a loop
2138   __ mov(rscratch1, (uint64_t)0xDEADDEAD);        // Make a recognizable pattern
2139   __ mov(rscratch2, rscratch1);
2140   Label loop;
2141   __ bind(loop);
2142   __ ldr(r19, Address(__ post(r4, wordSize)));          // Load frame size
2143   __ sub(r19, r19, 2*wordSize);           // We'll push pc and fp by hand
2144   __ ldr(lr, Address(__ post(r2, wordSize)));  // Load pc
2145   __ enter();                           // Save old & set new fp
2146   __ sub(sp, sp, r19);                  // Prolog
2147   // This value is corrected by layout_activation_impl
2148   __ str(zr, Address(rfp, frame::interpreter_frame_last_sp_offset * wordSize));
2149   __ str(sender_sp, Address(rfp, frame::interpreter_frame_sender_sp_offset * wordSize)); // Make it walkable
2150   __ mov(sender_sp, sp);               // Pass sender_sp to next frame
2151   __ sub(r3, r3, 1);                   // Decrement counter
2152   __ cbnz(r3, loop);
2153 
2154     // Re-push self-frame
2155   __ ldr(lr, Address(r2));
2156   __ enter();
2157 
2158   // Allocate a full sized register save area.  We subtract 2 because
2159   // enter() just pushed 2 words
2160   __ sub(sp, sp, (frame_size_in_words - 2) * wordSize);
2161 
2162   // Restore frame locals after moving the frame
2163   __ strd(v0, Address(sp, reg_save.v0_offset_in_bytes()));
2164   __ str(r0, Address(sp, reg_save.r0_offset_in_bytes()));
2165 
2166   // Call C code.  Need thread but NOT official VM entry
2167   // crud.  We cannot block on this call, no GC can happen.  Call should
2168   // restore return values to their stack-slots with the new SP.
2169   //
2170   // void Deoptimization::unpack_frames(JavaThread* thread, int exec_mode)
2171 
2172   // Use rfp because the frames look interpreted now
2173   // Don't need the precise return PC here, just precise enough to point into this code blob.
2174   address the_pc = __ pc();
2175   __ set_last_Java_frame(sp, rfp, the_pc, rscratch1);
2176 
2177   __ mov(c_rarg0, rthread);
2178   __ movw(c_rarg1, rcpool); // second arg: exec_mode
2179   __ lea(rscratch1, RuntimeAddress(CAST_FROM_FN_PTR(address, Deoptimization::unpack_frames)));
2180   __ blr(rscratch1);
2181 
2182   // Set an oopmap for the call site
2183   // Use the same PC we used for the last java frame
2184   oop_maps->add_gc_map(the_pc - start,
2185                        new OopMap( frame_size_in_words, 0 ));
2186 
2187   // Clear fp AND pc
2188   __ reset_last_Java_frame(true);
2189 
2190   // Collect return values
2191   __ ldrd(v0, Address(sp, reg_save.v0_offset_in_bytes()));
2192   __ ldr(r0, Address(sp, reg_save.r0_offset_in_bytes()));
2193   // I think this is useless (throwing pc?)
2194   // __ ldr(r3, Address(sp, RegisterSaver::r3_offset_in_bytes()));
2195 
2196   // Pop self-frame.
2197   __ leave();                           // Epilog
2198 
2199   // Jump to interpreter
2200   __ ret(lr);
2201 
2202   // Make sure all code is generated
2203   masm->flush();
2204 
2205   _deopt_blob = DeoptimizationBlob::create(&buffer, oop_maps, 0, exception_offset, reexecute_offset, frame_size_in_words);
2206   _deopt_blob->set_unpack_with_exception_in_tls_offset(exception_in_tls_offset);
2207 #if INCLUDE_JVMCI
2208   if (EnableJVMCI) {
2209     _deopt_blob->set_uncommon_trap_offset(uncommon_trap_offset);
2210     _deopt_blob->set_implicit_exception_uncommon_trap_offset(implicit_exception_uncommon_trap_offset);
2211   }
2212 #endif
2213 }
2214 
2215 // Number of stack slots between incoming argument block and the start of
2216 // a new frame.  The PROLOG must add this many slots to the stack.  The
2217 // EPILOG must remove this many slots. aarch64 needs two slots for
2218 // return address and fp.
2219 // TODO think this is correct but check
2220 uint SharedRuntime::in_preserve_stack_slots() {
2221   return 4;
2222 }
2223 
2224 uint SharedRuntime::out_preserve_stack_slots() {
2225   return 0;
2226 }
2227 
2228 #ifdef COMPILER2
2229 //------------------------------generate_uncommon_trap_blob--------------------
2230 void SharedRuntime::generate_uncommon_trap_blob() {
2231   // Allocate space for the code
2232   ResourceMark rm;
2233   // Setup code generation tools
2234   CodeBuffer buffer("uncommon_trap_blob", 2048, 1024);
2235   MacroAssembler* masm = new MacroAssembler(&buffer);
2236 
2237   assert(SimpleRuntimeFrame::framesize % 4 == 0, "sp not 16-byte aligned");
2238 
2239   address start = __ pc();
2240 
2241   // Push self-frame.  We get here with a return address in LR
2242   // and sp should be 16 byte aligned
2243   // push rfp and retaddr by hand
2244   __ stp(rfp, lr, Address(__ pre(sp, -2 * wordSize)));
2245   // we don't expect an arg reg save area
2246 #ifndef PRODUCT
2247   assert(frame::arg_reg_save_area_bytes == 0, "not expecting frame reg save area");
2248 #endif
2249   // compiler left unloaded_class_index in j_rarg0 move to where the
2250   // runtime expects it.
2251   if (c_rarg1 != j_rarg0) {
2252     __ movw(c_rarg1, j_rarg0);
2253   }
2254 
2255   // we need to set the past SP to the stack pointer of the stub frame
2256   // and the pc to the address where this runtime call will return
2257   // although actually any pc in this code blob will do).
2258   Label retaddr;
2259   __ set_last_Java_frame(sp, noreg, retaddr, rscratch1);
2260 
2261   // Call C code.  Need thread but NOT official VM entry
2262   // crud.  We cannot block on this call, no GC can happen.  Call should
2263   // capture callee-saved registers as well as return values.
2264   // Thread is in rdi already.
2265   //
2266   // UnrollBlock* uncommon_trap(JavaThread* thread, jint unloaded_class_index);
2267   //
2268   // n.b. 2 gp args, 0 fp args, integral return type
2269 
2270   __ mov(c_rarg0, rthread);
2271   __ movw(c_rarg2, (unsigned)Deoptimization::Unpack_uncommon_trap);
2272   __ lea(rscratch1,
2273          RuntimeAddress(CAST_FROM_FN_PTR(address,
2274                                          Deoptimization::uncommon_trap)));
2275   __ blr(rscratch1);
2276   __ bind(retaddr);
2277 
2278   // Set an oopmap for the call site
2279   OopMapSet* oop_maps = new OopMapSet();
2280   OopMap* map = new OopMap(SimpleRuntimeFrame::framesize, 0);
2281 
2282   // location of rfp is known implicitly by the frame sender code
2283 
2284   oop_maps->add_gc_map(__ pc() - start, map);
2285 
2286   __ reset_last_Java_frame(false);
2287 
2288   // move UnrollBlock* into r4
2289   __ mov(r4, r0);
2290 
2291 #ifdef ASSERT
2292   { Label L;
2293     __ ldrw(rscratch1, Address(r4, Deoptimization::UnrollBlock::unpack_kind_offset_in_bytes()));
2294     __ cmpw(rscratch1, (unsigned)Deoptimization::Unpack_uncommon_trap);
2295     __ br(Assembler::EQ, L);
2296     __ stop("SharedRuntime::generate_deopt_blob: last_Java_fp not cleared");
2297     __ bind(L);
2298   }
2299 #endif
2300 
2301   // Pop all the frames we must move/replace.
2302   //
2303   // Frame picture (youngest to oldest)
2304   // 1: self-frame (no frame link)
2305   // 2: deopting frame  (no frame link)
2306   // 3: caller of deopting frame (could be compiled/interpreted).
2307 
2308   // Pop self-frame.  We have no frame, and must rely only on r0 and sp.
2309   __ add(sp, sp, (SimpleRuntimeFrame::framesize) << LogBytesPerInt); // Epilog!
2310 
2311   // Pop deoptimized frame (int)
2312   __ ldrw(r2, Address(r4,
2313                       Deoptimization::UnrollBlock::
2314                       size_of_deoptimized_frame_offset_in_bytes()));
2315   __ sub(r2, r2, 2 * wordSize);
2316   __ add(sp, sp, r2);
2317   __ ldp(rfp, lr, __ post(sp, 2 * wordSize));
2318   // LR should now be the return address to the caller (3) frame
2319 
2320 #ifdef ASSERT
2321   // Compilers generate code that bang the stack by as much as the
2322   // interpreter would need. So this stack banging should never
2323   // trigger a fault. Verify that it does not on non product builds.
2324   __ ldrw(r1, Address(r4,
2325                       Deoptimization::UnrollBlock::
2326                       total_frame_sizes_offset_in_bytes()));
2327   __ bang_stack_size(r1, r2);
2328 #endif
2329 
2330   // Load address of array of frame pcs into r2 (address*)
2331   __ ldr(r2, Address(r4,
2332                      Deoptimization::UnrollBlock::frame_pcs_offset_in_bytes()));
2333 
2334   // Load address of array of frame sizes into r5 (intptr_t*)
2335   __ ldr(r5, Address(r4,
2336                      Deoptimization::UnrollBlock::
2337                      frame_sizes_offset_in_bytes()));
2338 
2339   // Counter
2340   __ ldrw(r3, Address(r4,
2341                       Deoptimization::UnrollBlock::
2342                       number_of_frames_offset_in_bytes())); // (int)
2343 
2344   // Now adjust the caller's stack to make up for the extra locals but
2345   // record the original sp so that we can save it in the skeletal
2346   // interpreter frame and the stack walking of interpreter_sender
2347   // will get the unextended sp value and not the "real" sp value.
2348 
2349   const Register sender_sp = r8;
2350 
2351   __ mov(sender_sp, sp);
2352   __ ldrw(r1, Address(r4,
2353                       Deoptimization::UnrollBlock::
2354                       caller_adjustment_offset_in_bytes())); // (int)
2355   __ sub(sp, sp, r1);
2356 
2357   // Push interpreter frames in a loop
2358   Label loop;
2359   __ bind(loop);
2360   __ ldr(r1, Address(r5, 0));       // Load frame size
2361   __ sub(r1, r1, 2 * wordSize);     // We'll push pc and rfp by hand
2362   __ ldr(lr, Address(r2, 0));       // Save return address
2363   __ enter();                       // and old rfp & set new rfp
2364   __ sub(sp, sp, r1);               // Prolog
2365   __ str(sender_sp, Address(rfp, frame::interpreter_frame_sender_sp_offset * wordSize)); // Make it walkable
2366   // This value is corrected by layout_activation_impl
2367   __ str(zr, Address(rfp, frame::interpreter_frame_last_sp_offset * wordSize));
2368   __ mov(sender_sp, sp);          // Pass sender_sp to next frame
2369   __ add(r5, r5, wordSize);       // Bump array pointer (sizes)
2370   __ add(r2, r2, wordSize);       // Bump array pointer (pcs)
2371   __ subsw(r3, r3, 1);            // Decrement counter
2372   __ br(Assembler::GT, loop);
2373   __ ldr(lr, Address(r2, 0));     // save final return address
2374   // Re-push self-frame
2375   __ enter();                     // & old rfp & set new rfp
2376 
2377   // Use rfp because the frames look interpreted now
2378   // Save "the_pc" since it cannot easily be retrieved using the last_java_SP after we aligned SP.
2379   // Don't need the precise return PC here, just precise enough to point into this code blob.
2380   address the_pc = __ pc();
2381   __ set_last_Java_frame(sp, rfp, the_pc, rscratch1);
2382 
2383   // Call C code.  Need thread but NOT official VM entry
2384   // crud.  We cannot block on this call, no GC can happen.  Call should
2385   // restore return values to their stack-slots with the new SP.
2386   // Thread is in rdi already.
2387   //
2388   // BasicType unpack_frames(JavaThread* thread, int exec_mode);
2389   //
2390   // n.b. 2 gp args, 0 fp args, integral return type
2391 
2392   // sp should already be aligned
2393   __ mov(c_rarg0, rthread);
2394   __ movw(c_rarg1, (unsigned)Deoptimization::Unpack_uncommon_trap);
2395   __ lea(rscratch1, RuntimeAddress(CAST_FROM_FN_PTR(address, Deoptimization::unpack_frames)));
2396   __ blr(rscratch1);
2397 
2398   // Set an oopmap for the call site
2399   // Use the same PC we used for the last java frame
2400   oop_maps->add_gc_map(the_pc - start, new OopMap(SimpleRuntimeFrame::framesize, 0));
2401 
2402   // Clear fp AND pc
2403   __ reset_last_Java_frame(true);
2404 
2405   // Pop self-frame.
2406   __ leave();                 // Epilog
2407 
2408   // Jump to interpreter
2409   __ ret(lr);
2410 
2411   // Make sure all code is generated
2412   masm->flush();
2413 
2414   _uncommon_trap_blob =  UncommonTrapBlob::create(&buffer, oop_maps,
2415                                                  SimpleRuntimeFrame::framesize >> 1);
2416 }
2417 #endif // COMPILER2
2418 
2419 
2420 //------------------------------generate_handler_blob------
2421 //
2422 // Generate a special Compile2Runtime blob that saves all registers,
2423 // and setup oopmap.
2424 //
2425 SafepointBlob* SharedRuntime::generate_handler_blob(address call_ptr, int poll_type) {
2426   ResourceMark rm;
2427   OopMapSet *oop_maps = new OopMapSet();
2428   OopMap* map;
2429 
2430   // Allocate space for the code.  Setup code generation tools.
2431   CodeBuffer buffer("handler_blob", 2048, 1024);
2432   MacroAssembler* masm = new MacroAssembler(&buffer);
2433 
2434   address start   = __ pc();
2435   address call_pc = NULL;
2436   int frame_size_in_words;
2437   bool cause_return = (poll_type == POLL_AT_RETURN);
2438   RegisterSaver reg_save(poll_type == POLL_AT_VECTOR_LOOP /* save_vectors */);
2439 
2440   // Save Integer and Float registers.
2441   map = reg_save.save_live_registers(masm, 0, &frame_size_in_words);
2442 
2443   // The following is basically a call_VM.  However, we need the precise
2444   // address of the call in order to generate an oopmap. Hence, we do all the
2445   // work outselves.
2446 
2447   Label retaddr;
2448   __ set_last_Java_frame(sp, noreg, retaddr, rscratch1);
2449 
2450   // The return address must always be correct so that frame constructor never
2451   // sees an invalid pc.
2452 
2453   if (!cause_return) {
2454     // overwrite the return address pushed by save_live_registers
2455     // Additionally, r20 is a callee-saved register so we can look at
2456     // it later to determine if someone changed the return address for
2457     // us!
2458     __ ldr(r20, Address(rthread, JavaThread::saved_exception_pc_offset()));
2459     __ str(r20, Address(rfp, wordSize));
2460   }
2461 
2462   // Do the call
2463   __ mov(c_rarg0, rthread);
2464   __ lea(rscratch1, RuntimeAddress(call_ptr));
2465   __ blr(rscratch1);
2466   __ bind(retaddr);
2467 
2468   // Set an oopmap for the call site.  This oopmap will map all
2469   // oop-registers and debug-info registers as callee-saved.  This
2470   // will allow deoptimization at this safepoint to find all possible
2471   // debug-info recordings, as well as let GC find all oops.
2472 
2473   oop_maps->add_gc_map( __ pc() - start, map);
2474 
2475   Label noException;
2476 
2477   __ reset_last_Java_frame(false);
2478 
2479   __ membar(Assembler::LoadLoad | Assembler::LoadStore);
2480 
2481   __ ldr(rscratch1, Address(rthread, Thread::pending_exception_offset()));
2482   __ cbz(rscratch1, noException);
2483 
2484   // Exception pending
2485 
2486   reg_save.restore_live_registers(masm);
2487 
2488   __ far_jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
2489 
2490   // No exception case
2491   __ bind(noException);
2492 
2493   Label no_adjust, bail;
2494   if (!cause_return) {
2495     // If our stashed return pc was modified by the runtime we avoid touching it
2496     __ ldr(rscratch1, Address(rfp, wordSize));
2497     __ cmp(r20, rscratch1);
2498     __ br(Assembler::NE, no_adjust);
2499 
2500 #ifdef ASSERT
2501     // Verify the correct encoding of the poll we're about to skip.
2502     // See NativeInstruction::is_ldrw_to_zr()
2503     __ ldrw(rscratch1, Address(r20));
2504     __ ubfx(rscratch2, rscratch1, 22, 10);
2505     __ cmpw(rscratch2, 0b1011100101);
2506     __ br(Assembler::NE, bail);
2507     __ ubfx(rscratch2, rscratch1, 0, 5);
2508     __ cmpw(rscratch2, 0b11111);
2509     __ br(Assembler::NE, bail);
2510 #endif
2511     // Adjust return pc forward to step over the safepoint poll instruction
2512     __ add(r20, r20, NativeInstruction::instruction_size);
2513     __ str(r20, Address(rfp, wordSize));
2514   }
2515 
2516   __ bind(no_adjust);
2517   // Normal exit, restore registers and exit.
2518   reg_save.restore_live_registers(masm);
2519 
2520   __ ret(lr);
2521 
2522 #ifdef ASSERT
2523   __ bind(bail);
2524   __ stop("Attempting to adjust pc to skip safepoint poll but the return point is not what we expected");
2525 #endif
2526 
2527   // Make sure all code is generated
2528   masm->flush();
2529 
2530   // Fill-out other meta info
2531   return SafepointBlob::create(&buffer, oop_maps, frame_size_in_words);
2532 }
2533 
2534 //
2535 // generate_resolve_blob - call resolution (static/virtual/opt-virtual/ic-miss
2536 //
2537 // Generate a stub that calls into vm to find out the proper destination
2538 // of a java call. All the argument registers are live at this point
2539 // but since this is generic code we don't know what they are and the caller
2540 // must do any gc of the args.
2541 //
2542 RuntimeStub* SharedRuntime::generate_resolve_blob(address destination, const char* name) {
2543   assert (StubRoutines::forward_exception_entry() != NULL, "must be generated before");
2544 
2545   // allocate space for the code
2546   ResourceMark rm;
2547 
2548   CodeBuffer buffer(name, 1000, 512);
2549   MacroAssembler* masm                = new MacroAssembler(&buffer);
2550 
2551   int frame_size_in_words;
2552   RegisterSaver reg_save(false /* save_vectors */);
2553 
2554   OopMapSet *oop_maps = new OopMapSet();
2555   OopMap* map = NULL;
2556 
2557   int start = __ offset();
2558 
2559   map = reg_save.save_live_registers(masm, 0, &frame_size_in_words);
2560 
2561   int frame_complete = __ offset();
2562 
2563   {
2564     Label retaddr;
2565     __ set_last_Java_frame(sp, noreg, retaddr, rscratch1);
2566 
2567     __ mov(c_rarg0, rthread);
2568     __ lea(rscratch1, RuntimeAddress(destination));
2569 
2570     __ blr(rscratch1);
2571     __ bind(retaddr);
2572   }
2573 
2574   // Set an oopmap for the call site.
2575   // We need this not only for callee-saved registers, but also for volatile
2576   // registers that the compiler might be keeping live across a safepoint.
2577 
2578   oop_maps->add_gc_map( __ offset() - start, map);
2579 
2580   // r0 contains the address we are going to jump to assuming no exception got installed
2581 
2582   // clear last_Java_sp
2583   __ reset_last_Java_frame(false);
2584   // check for pending exceptions
2585   Label pending;
2586   __ ldr(rscratch1, Address(rthread, Thread::pending_exception_offset()));
2587   __ cbnz(rscratch1, pending);
2588 
2589   // get the returned Method*
2590   __ get_vm_result_2(rmethod, rthread);
2591   __ str(rmethod, Address(sp, reg_save.reg_offset_in_bytes(rmethod)));
2592 
2593   // r0 is where we want to jump, overwrite rscratch1 which is saved and scratch
2594   __ str(r0, Address(sp, reg_save.rscratch1_offset_in_bytes()));
2595   reg_save.restore_live_registers(masm);
2596 
2597   // We are back the the original state on entry and ready to go.
2598 
2599   __ br(rscratch1);
2600 
2601   // Pending exception after the safepoint
2602 
2603   __ bind(pending);
2604 
2605   reg_save.restore_live_registers(masm);
2606 
2607   // exception pending => remove activation and forward to exception handler
2608 
2609   __ str(zr, Address(rthread, JavaThread::vm_result_offset()));
2610 
2611   __ ldr(r0, Address(rthread, Thread::pending_exception_offset()));
2612   __ far_jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
2613 
2614   // -------------
2615   // make sure all code is generated
2616   masm->flush();
2617 
2618   // return the  blob
2619   // frame_size_words or bytes??
2620   return RuntimeStub::new_runtime_stub(name, &buffer, frame_complete, frame_size_in_words, oop_maps, true);
2621 }
2622 
2623 #ifdef COMPILER2
2624 // This is here instead of runtime_x86_64.cpp because it uses SimpleRuntimeFrame
2625 //
2626 //------------------------------generate_exception_blob---------------------------
2627 // creates exception blob at the end
2628 // Using exception blob, this code is jumped from a compiled method.
2629 // (see emit_exception_handler in x86_64.ad file)
2630 //
2631 // Given an exception pc at a call we call into the runtime for the
2632 // handler in this method. This handler might merely restore state
2633 // (i.e. callee save registers) unwind the frame and jump to the
2634 // exception handler for the nmethod if there is no Java level handler
2635 // for the nmethod.
2636 //
2637 // This code is entered with a jmp.
2638 //
2639 // Arguments:
2640 //   r0: exception oop
2641 //   r3: exception pc
2642 //
2643 // Results:
2644 //   r0: exception oop
2645 //   r3: exception pc in caller or ???
2646 //   destination: exception handler of caller
2647 //
2648 // Note: the exception pc MUST be at a call (precise debug information)
2649 //       Registers r0, r3, r2, r4, r5, r8-r11 are not callee saved.
2650 //
2651 
2652 void OptoRuntime::generate_exception_blob() {
2653   assert(!OptoRuntime::is_callee_saved_register(R3_num), "");
2654   assert(!OptoRuntime::is_callee_saved_register(R0_num), "");
2655   assert(!OptoRuntime::is_callee_saved_register(R2_num), "");
2656 
2657   assert(SimpleRuntimeFrame::framesize % 4 == 0, "sp not 16-byte aligned");
2658 
2659   // Allocate space for the code
2660   ResourceMark rm;
2661   // Setup code generation tools
2662   CodeBuffer buffer("exception_blob", 2048, 1024);
2663   MacroAssembler* masm = new MacroAssembler(&buffer);
2664 
2665   // TODO check various assumptions made here
2666   //
2667   // make sure we do so before running this
2668 
2669   address start = __ pc();
2670 
2671   // push rfp and retaddr by hand
2672   // Exception pc is 'return address' for stack walker
2673   __ stp(rfp, lr, Address(__ pre(sp, -2 * wordSize)));
2674   // there are no callee save registers and we don't expect an
2675   // arg reg save area
2676 #ifndef PRODUCT
2677   assert(frame::arg_reg_save_area_bytes == 0, "not expecting frame reg save area");
2678 #endif
2679   // Store exception in Thread object. We cannot pass any arguments to the
2680   // handle_exception call, since we do not want to make any assumption
2681   // about the size of the frame where the exception happened in.
2682   __ str(r0, Address(rthread, JavaThread::exception_oop_offset()));
2683   __ str(r3, Address(rthread, JavaThread::exception_pc_offset()));
2684 
2685   // This call does all the hard work.  It checks if an exception handler
2686   // exists in the method.
2687   // If so, it returns the handler address.
2688   // If not, it prepares for stack-unwinding, restoring the callee-save
2689   // registers of the frame being removed.
2690   //
2691   // address OptoRuntime::handle_exception_C(JavaThread* thread)
2692   //
2693   // n.b. 1 gp arg, 0 fp args, integral return type
2694 
2695   // the stack should always be aligned
2696   address the_pc = __ pc();
2697   __ set_last_Java_frame(sp, noreg, the_pc, rscratch1);
2698   __ mov(c_rarg0, rthread);
2699   __ lea(rscratch1, RuntimeAddress(CAST_FROM_FN_PTR(address, OptoRuntime::handle_exception_C)));
2700   __ blr(rscratch1);
2701   // handle_exception_C is a special VM call which does not require an explicit
2702   // instruction sync afterwards.
2703 
2704   // May jump to SVE compiled code
2705   __ reinitialize_ptrue();
2706 
2707   // Set an oopmap for the call site.  This oopmap will only be used if we
2708   // are unwinding the stack.  Hence, all locations will be dead.
2709   // Callee-saved registers will be the same as the frame above (i.e.,
2710   // handle_exception_stub), since they were restored when we got the
2711   // exception.
2712 
2713   OopMapSet* oop_maps = new OopMapSet();
2714 
2715   oop_maps->add_gc_map(the_pc - start, new OopMap(SimpleRuntimeFrame::framesize, 0));
2716 
2717   __ reset_last_Java_frame(false);
2718 
2719   // Restore callee-saved registers
2720 
2721   // rfp is an implicitly saved callee saved register (i.e. the calling
2722   // convention will save restore it in prolog/epilog) Other than that
2723   // there are no callee save registers now that adapter frames are gone.
2724   // and we dont' expect an arg reg save area
2725   __ ldp(rfp, r3, Address(__ post(sp, 2 * wordSize)));
2726 
2727   // r0: exception handler
2728 
2729   // We have a handler in r0 (could be deopt blob).
2730   __ mov(r8, r0);
2731 
2732   // Get the exception oop
2733   __ ldr(r0, Address(rthread, JavaThread::exception_oop_offset()));
2734   // Get the exception pc in case we are deoptimized
2735   __ ldr(r4, Address(rthread, JavaThread::exception_pc_offset()));
2736 #ifdef ASSERT
2737   __ str(zr, Address(rthread, JavaThread::exception_handler_pc_offset()));
2738   __ str(zr, Address(rthread, JavaThread::exception_pc_offset()));
2739 #endif
2740   // Clear the exception oop so GC no longer processes it as a root.
2741   __ str(zr, Address(rthread, JavaThread::exception_oop_offset()));
2742 
2743   // r0: exception oop
2744   // r8:  exception handler
2745   // r4: exception pc
2746   // Jump to handler
2747 
2748   __ br(r8);
2749 
2750   // Make sure all code is generated
2751   masm->flush();
2752 
2753   // Set exception blob
2754   _exception_blob =  ExceptionBlob::create(&buffer, oop_maps, SimpleRuntimeFrame::framesize >> 1);
2755 }
2756 



























































































































































































































































2757 #endif // COMPILER2
2758 
--- EOF ---