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