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