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