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