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