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