1 /*
2 * Copyright (c) 2003, 2026, Oracle and/or its affiliates. All rights reserved.
3 * Copyright (c) 2014, 2021, Red Hat Inc. All rights reserved.
4 * Copyright (c) 2021, Azul Systems, Inc. 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 "classfile/symbolTable.hpp"
30 #include "code/aotCodeCache.hpp"
31 #include "code/codeCache.hpp"
32 #include "code/compiledIC.hpp"
33 #include "code/debugInfoRec.hpp"
34 #include "code/vtableStubs.hpp"
35 #include "compiler/oopMap.hpp"
36 #include "gc/shared/barrierSetAssembler.hpp"
37 #include "interpreter/interpreter.hpp"
38 #include "interpreter/interp_masm.hpp"
39 #include "logging/log.hpp"
40 #include "memory/resourceArea.hpp"
41 #include "nativeInst_aarch64.hpp"
42 #include "oops/klass.inline.hpp"
43 #include "oops/method.inline.hpp"
44 #include "prims/methodHandles.hpp"
45 #include "runtime/continuation.hpp"
46 #include "runtime/continuationEntry.inline.hpp"
47 #include "runtime/globals.hpp"
48 #include "runtime/jniHandles.hpp"
49 #include "runtime/safepointMechanism.hpp"
50 #include "runtime/sharedRuntime.hpp"
51 #include "runtime/signature.hpp"
52 #include "runtime/stubRoutines.hpp"
53 #include "runtime/timerTrace.hpp"
54 #include "runtime/vframeArray.hpp"
55 #include "utilities/align.hpp"
56 #include "utilities/formatBuffer.hpp"
57 #include "vmreg_aarch64.inline.hpp"
58 #ifdef COMPILER1
59 #include "c1/c1_Runtime1.hpp"
60 #endif
61 #ifdef COMPILER2
62 #include "adfiles/ad_aarch64.hpp"
63 #include "opto/runtime.hpp"
64 #endif
65 #if INCLUDE_JVMCI
66 #include "jvmci/jvmciJavaClasses.hpp"
67 #endif
68
69 #define __ masm->
70
71 #ifdef PRODUCT
72 #define BLOCK_COMMENT(str) /* nothing */
73 #else
74 #define BLOCK_COMMENT(str) __ block_comment(str)
75 #endif
76
77 const int StackAlignmentInSlots = StackAlignmentInBytes / VMRegImpl::stack_slot_size;
78
79 // FIXME -- this is used by C1
80 class RegisterSaver {
81 const bool _save_vectors;
82 public:
83 RegisterSaver(bool save_vectors) : _save_vectors(save_vectors) {}
84
85 OopMap* save_live_registers(MacroAssembler* masm, int additional_frame_words, int* total_frame_words);
86 void restore_live_registers(MacroAssembler* masm);
87
88 // Offsets into the register save area
89 // Used by deoptimization when it is managing result register
90 // values on its own
91
92 int reg_offset_in_bytes(Register r);
93 int r0_offset_in_bytes() { return reg_offset_in_bytes(r0); }
94 int rscratch1_offset_in_bytes() { return reg_offset_in_bytes(rscratch1); }
95 int v0_offset_in_bytes();
96
97 // Total stack size in bytes for saving sve predicate registers.
98 int total_sve_predicate_in_bytes();
99
100 // Capture info about frame layout
101 // Note this is only correct when not saving full vectors.
102 enum layout {
103 fpu_state_off = 0,
104 fpu_state_end = fpu_state_off + FPUStateSizeInWords - 1,
105 // The frame sender code expects that rfp will be in
106 // the "natural" place and will override any oopMap
107 // setting for it. We must therefore force the layout
108 // so that it agrees with the frame sender code.
109 r0_off = fpu_state_off + FPUStateSizeInWords,
110 rfp_off = r0_off + (Register::number_of_registers - 2) * Register::max_slots_per_register,
111 return_off = rfp_off + Register::max_slots_per_register, // slot for return address
112 reg_save_size = return_off + Register::max_slots_per_register};
113
114 };
115
116 int RegisterSaver::reg_offset_in_bytes(Register r) {
117 // The integer registers are located above the floating point
118 // registers in the stack frame pushed by save_live_registers() so the
119 // offset depends on whether we are saving full vectors, and whether
120 // those vectors are NEON or SVE.
121
122 int slots_per_vect = FloatRegister::save_slots_per_register;
123
124 #if COMPILER2_OR_JVMCI
125 if (_save_vectors) {
126 slots_per_vect = FloatRegister::slots_per_neon_register;
127
128 #ifdef COMPILER2
129 if (Matcher::supports_scalable_vector()) {
130 slots_per_vect = Matcher::scalable_vector_reg_size(T_FLOAT);
131 }
132 #endif
133 }
134 #endif
135
136 int r0_offset = v0_offset_in_bytes() + (slots_per_vect * FloatRegister::number_of_registers) * BytesPerInt;
137 return r0_offset + r->encoding() * wordSize;
138 }
139
140 int RegisterSaver::v0_offset_in_bytes() {
141 // The floating point registers are located above the predicate registers if
142 // they are present in the stack frame pushed by save_live_registers(). So the
143 // offset depends on the saved total predicate vectors in the stack frame.
144 return (total_sve_predicate_in_bytes() / VMRegImpl::stack_slot_size) * BytesPerInt;
145 }
146
147 int RegisterSaver::total_sve_predicate_in_bytes() {
148 #ifdef COMPILER2
149 if (_save_vectors && Matcher::supports_scalable_vector()) {
150 return (Matcher::scalable_vector_reg_size(T_BYTE) >> LogBitsPerByte) *
151 PRegister::number_of_registers;
152 }
153 #endif
154 return 0;
155 }
156
157 OopMap* RegisterSaver::save_live_registers(MacroAssembler* masm, int additional_frame_words, int* total_frame_words) {
158 bool use_sve = false;
159 int sve_vector_size_in_bytes = 0;
160 int sve_vector_size_in_slots = 0;
161 int sve_predicate_size_in_slots = 0;
162 int total_predicate_in_bytes = total_sve_predicate_in_bytes();
163 int total_predicate_in_slots = total_predicate_in_bytes / VMRegImpl::stack_slot_size;
164
165 #ifdef COMPILER2
166 use_sve = Matcher::supports_scalable_vector();
167 if (use_sve) {
168 sve_vector_size_in_bytes = Matcher::scalable_vector_reg_size(T_BYTE);
169 sve_vector_size_in_slots = Matcher::scalable_vector_reg_size(T_FLOAT);
170 sve_predicate_size_in_slots = Matcher::scalable_predicate_reg_slots();
171 }
172 #endif
173
174 #if COMPILER2_OR_JVMCI
175 if (_save_vectors) {
176 int extra_save_slots_per_register = 0;
177 // Save upper half of vector registers
178 if (use_sve) {
179 extra_save_slots_per_register = sve_vector_size_in_slots - FloatRegister::save_slots_per_register;
180 } else {
181 extra_save_slots_per_register = FloatRegister::extra_save_slots_per_neon_register;
182 }
183 int extra_vector_bytes = extra_save_slots_per_register *
184 VMRegImpl::stack_slot_size *
185 FloatRegister::number_of_registers;
186 additional_frame_words += ((extra_vector_bytes + total_predicate_in_bytes) / wordSize);
187 }
188 #else
189 assert(!_save_vectors, "vectors are generated only by C2 and JVMCI");
190 #endif
191
192 int frame_size_in_bytes = align_up(additional_frame_words * wordSize +
193 reg_save_size * BytesPerInt, 16);
194 // OopMap frame size is in compiler stack slots (jint's) not bytes or words
195 int frame_size_in_slots = frame_size_in_bytes / BytesPerInt;
196 // The caller will allocate additional_frame_words
197 int additional_frame_slots = additional_frame_words * wordSize / BytesPerInt;
198 // CodeBlob frame size is in words.
199 int frame_size_in_words = frame_size_in_bytes / wordSize;
200 *total_frame_words = frame_size_in_words;
201
202 // Save Integer and Float registers.
203 __ enter();
204 __ push_CPU_state(_save_vectors, use_sve, sve_vector_size_in_bytes, total_predicate_in_bytes);
205
206 // Set an oopmap for the call site. This oopmap will map all
207 // oop-registers and debug-info registers as callee-saved. This
208 // will allow deoptimization at this safepoint to find all possible
209 // debug-info recordings, as well as let GC find all oops.
210
211 OopMap* oop_map = new OopMap(frame_size_in_slots, 0);
212
213 for (int i = 0; i < Register::number_of_registers; i++) {
214 Register r = as_Register(i);
215 if (i <= rfp->encoding() && r != rscratch1 && r != rscratch2) {
216 // SP offsets are in 4-byte words.
217 // Register slots are 8 bytes wide, 32 floating-point registers.
218 int sp_offset = Register::max_slots_per_register * i +
219 FloatRegister::save_slots_per_register * FloatRegister::number_of_registers;
220 oop_map->set_callee_saved(VMRegImpl::stack2reg(sp_offset + additional_frame_slots), r->as_VMReg());
221 }
222 }
223
224 for (int i = 0; i < FloatRegister::number_of_registers; i++) {
225 FloatRegister r = as_FloatRegister(i);
226 int sp_offset = 0;
227 if (_save_vectors) {
228 sp_offset = use_sve ? (total_predicate_in_slots + sve_vector_size_in_slots * i) :
229 (FloatRegister::slots_per_neon_register * i);
230 } else {
231 sp_offset = FloatRegister::save_slots_per_register * i;
232 }
233 oop_map->set_callee_saved(VMRegImpl::stack2reg(sp_offset), r->as_VMReg());
234 }
235
236 return oop_map;
237 }
238
239 void RegisterSaver::restore_live_registers(MacroAssembler* masm) {
240 #ifdef COMPILER2
241 __ pop_CPU_state(_save_vectors, Matcher::supports_scalable_vector(),
242 Matcher::scalable_vector_reg_size(T_BYTE), total_sve_predicate_in_bytes());
243 #else
244 #if !INCLUDE_JVMCI
245 assert(!_save_vectors, "vectors are generated only by C2 and JVMCI");
246 #endif
247 __ pop_CPU_state(_save_vectors);
248 #endif
249 __ ldp(rfp, lr, Address(__ post(sp, 2 * wordSize)));
250 __ authenticate_return_address();
251 }
252
253 // Is vector's size (in bytes) bigger than a size saved by default?
254 // 8 bytes vector registers are saved by default on AArch64.
255 // The SVE supported min vector size is 8 bytes and we need to save
256 // predicate registers when the vector size is 8 bytes as well.
257 bool SharedRuntime::is_wide_vector(int size) {
258 return size > 8 || (UseSVE > 0 && size >= 8);
259 }
260
261 // ---------------------------------------------------------------------------
262 // Read the array of BasicTypes from a signature, and compute where the
263 // arguments should go. Values in the VMRegPair regs array refer to 4-byte
264 // quantities. Values less than VMRegImpl::stack0 are registers, those above
265 // refer to 4-byte stack slots. All stack slots are based off of the stack pointer
266 // as framesizes are fixed.
267 // VMRegImpl::stack0 refers to the first slot 0(sp).
268 // and VMRegImpl::stack0+1 refers to the memory word 4-byes higher.
269 // Register up to Register::number_of_registers are the 64-bit
270 // integer registers.
271
272 // Note: the INPUTS in sig_bt are in units of Java argument words,
273 // which are 64-bit. The OUTPUTS are in 32-bit units.
274
275 // The Java calling convention is a "shifted" version of the C ABI.
276 // By skipping the first C ABI register we can call non-static jni
277 // methods with small numbers of arguments without having to shuffle
278 // the arguments at all. Since we control the java ABI we ought to at
279 // least get some advantage out of it.
280
281 int SharedRuntime::java_calling_convention(const BasicType *sig_bt,
282 VMRegPair *regs,
283 int total_args_passed) {
284
285 // Create the mapping between argument positions and
286 // registers.
287 static const Register INT_ArgReg[Argument::n_int_register_parameters_j] = {
288 j_rarg0, j_rarg1, j_rarg2, j_rarg3, j_rarg4, j_rarg5, j_rarg6, j_rarg7
289 };
290 static const FloatRegister FP_ArgReg[Argument::n_float_register_parameters_j] = {
291 j_farg0, j_farg1, j_farg2, j_farg3,
292 j_farg4, j_farg5, j_farg6, j_farg7
293 };
294
295
296 uint int_args = 0;
297 uint fp_args = 0;
298 uint stk_args = 0;
299
300 for (int i = 0; i < total_args_passed; i++) {
301 switch (sig_bt[i]) {
302 case T_BOOLEAN:
303 case T_CHAR:
304 case T_BYTE:
305 case T_SHORT:
306 case T_INT:
307 if (int_args < Argument::n_int_register_parameters_j) {
308 regs[i].set1(INT_ArgReg[int_args++]->as_VMReg());
309 } else {
310 stk_args = align_up(stk_args, 2);
311 regs[i].set1(VMRegImpl::stack2reg(stk_args));
312 stk_args += 1;
313 }
314 break;
315 case T_VOID:
316 // halves of T_LONG or T_DOUBLE
317 assert(i != 0 && (sig_bt[i - 1] == T_LONG || sig_bt[i - 1] == T_DOUBLE), "expecting half");
318 regs[i].set_bad();
319 break;
320 case T_LONG:
321 assert((i + 1) < total_args_passed && sig_bt[i + 1] == T_VOID, "expecting half");
322 // fall through
323 case T_OBJECT:
324 case T_ARRAY:
325 case T_ADDRESS:
326 if (int_args < Argument::n_int_register_parameters_j) {
327 regs[i].set2(INT_ArgReg[int_args++]->as_VMReg());
328 } else {
329 stk_args = align_up(stk_args, 2);
330 regs[i].set2(VMRegImpl::stack2reg(stk_args));
331 stk_args += 2;
332 }
333 break;
334 case T_FLOAT:
335 if (fp_args < Argument::n_float_register_parameters_j) {
336 regs[i].set1(FP_ArgReg[fp_args++]->as_VMReg());
337 } else {
338 stk_args = align_up(stk_args, 2);
339 regs[i].set1(VMRegImpl::stack2reg(stk_args));
340 stk_args += 1;
341 }
342 break;
343 case T_DOUBLE:
344 assert((i + 1) < total_args_passed && sig_bt[i + 1] == T_VOID, "expecting half");
345 if (fp_args < Argument::n_float_register_parameters_j) {
346 regs[i].set2(FP_ArgReg[fp_args++]->as_VMReg());
347 } else {
348 stk_args = align_up(stk_args, 2);
349 regs[i].set2(VMRegImpl::stack2reg(stk_args));
350 stk_args += 2;
351 }
352 break;
353 default:
354 ShouldNotReachHere();
355 break;
356 }
357 }
358
359 return stk_args;
360 }
361
362
363 const uint SharedRuntime::java_return_convention_max_int = Argument::n_int_register_parameters_j;
364 const uint SharedRuntime::java_return_convention_max_float = Argument::n_float_register_parameters_j;
365
366 int SharedRuntime::java_return_convention(const BasicType *sig_bt, VMRegPair *regs, int total_args_passed) {
367
368 // Create the mapping between argument positions and registers.
369
370 static const Register INT_ArgReg[java_return_convention_max_int] = {
371 r0 /* j_rarg7 */, j_rarg6, j_rarg5, j_rarg4, j_rarg3, j_rarg2, j_rarg1, j_rarg0
372 };
373
374 static const FloatRegister FP_ArgReg[java_return_convention_max_float] = {
375 j_farg0, j_farg1, j_farg2, j_farg3, j_farg4, j_farg5, j_farg6, j_farg7
376 };
377
378 uint int_args = 0;
379 uint fp_args = 0;
380
381 for (int i = 0; i < total_args_passed; i++) {
382 switch (sig_bt[i]) {
383 case T_BOOLEAN:
384 case T_CHAR:
385 case T_BYTE:
386 case T_SHORT:
387 case T_INT:
388 if (int_args < SharedRuntime::java_return_convention_max_int) {
389 regs[i].set1(INT_ArgReg[int_args]->as_VMReg());
390 int_args ++;
391 } else {
392 return -1;
393 }
394 break;
395 case T_VOID:
396 // halves of T_LONG or T_DOUBLE
397 assert(i != 0 && (sig_bt[i - 1] == T_LONG || sig_bt[i - 1] == T_DOUBLE), "expecting half");
398 regs[i].set_bad();
399 break;
400 case T_LONG:
401 assert((i + 1) < total_args_passed && sig_bt[i + 1] == T_VOID, "expecting half");
402 // fall through
403 case T_OBJECT:
404 case T_ARRAY:
405 case T_ADDRESS:
406 // Should T_METADATA be added to java_calling_convention as well ?
407 case T_METADATA:
408 if (int_args < SharedRuntime::java_return_convention_max_int) {
409 regs[i].set2(INT_ArgReg[int_args]->as_VMReg());
410 int_args ++;
411 } else {
412 return -1;
413 }
414 break;
415 case T_FLOAT:
416 if (fp_args < SharedRuntime::java_return_convention_max_float) {
417 regs[i].set1(FP_ArgReg[fp_args]->as_VMReg());
418 fp_args ++;
419 } else {
420 return -1;
421 }
422 break;
423 case T_DOUBLE:
424 assert((i + 1) < total_args_passed && sig_bt[i + 1] == T_VOID, "expecting half");
425 if (fp_args < SharedRuntime::java_return_convention_max_float) {
426 regs[i].set2(FP_ArgReg[fp_args]->as_VMReg());
427 fp_args ++;
428 } else {
429 return -1;
430 }
431 break;
432 default:
433 ShouldNotReachHere();
434 break;
435 }
436 }
437
438 return int_args + fp_args;
439 }
440
441 // Patch the callers callsite with entry to compiled code if it exists.
442 static void patch_callers_callsite(MacroAssembler *masm) {
443 Label L;
444 __ ldr(rscratch1, Address(rmethod, in_bytes(Method::code_offset())));
445 __ cbz(rscratch1, L);
446
447 __ enter();
448 __ push_CPU_state();
449
450 // VM needs caller's callsite
451 // VM needs target method
452 // This needs to be a long call since we will relocate this adapter to
453 // the codeBuffer and it may not reach
454
455 #ifndef PRODUCT
456 assert(frame::arg_reg_save_area_bytes == 0, "not expecting frame reg save area");
457 #endif
458
459 __ mov(c_rarg0, rmethod);
460 __ mov(c_rarg1, lr);
461 __ authenticate_return_address(c_rarg1);
462 __ lea(rscratch1, RuntimeAddress(CAST_FROM_FN_PTR(address, SharedRuntime::fixup_callers_callsite)));
463 __ blr(rscratch1);
464
465 // Explicit isb required because fixup_callers_callsite may change the code
466 // stream.
467 __ safepoint_isb();
468
469 __ pop_CPU_state();
470 // restore sp
471 __ leave();
472 __ bind(L);
473 }
474
475 // For each inline type argument, sig includes the list of fields of
476 // the inline type. This utility function computes the number of
477 // arguments for the call if inline types are passed by reference (the
478 // calling convention the interpreter expects).
479 static int compute_total_args_passed_int(const GrowableArray<SigEntry>* sig_extended) {
480 int total_args_passed = 0;
481 if (InlineTypePassFieldsAsArgs) {
482 for (int i = 0; i < sig_extended->length(); i++) {
483 BasicType bt = sig_extended->at(i)._bt;
484 if (bt == T_METADATA) {
485 // In sig_extended, an inline type argument starts with:
486 // T_METADATA, followed by the types of the fields of the
487 // inline type and T_VOID to mark the end of the value
488 // type. Inline types are flattened so, for instance, in the
489 // case of an inline type with an int field and an inline type
490 // field that itself has 2 fields, an int and a long:
491 // T_METADATA T_INT T_METADATA T_INT T_LONG T_VOID (second
492 // slot for the T_LONG) T_VOID (inner inline type) T_VOID
493 // (outer inline type)
494 total_args_passed++;
495 int vt = 1;
496 do {
497 i++;
498 BasicType bt = sig_extended->at(i)._bt;
499 BasicType prev_bt = sig_extended->at(i-1)._bt;
500 if (bt == T_METADATA) {
501 vt++;
502 } else if (bt == T_VOID &&
503 prev_bt != T_LONG &&
504 prev_bt != T_DOUBLE) {
505 vt--;
506 }
507 } while (vt != 0);
508 } else {
509 total_args_passed++;
510 }
511 }
512 } else {
513 total_args_passed = sig_extended->length();
514 }
515 return total_args_passed;
516 }
517
518
519 static void gen_c2i_adapter_helper(MacroAssembler* masm,
520 BasicType bt,
521 BasicType prev_bt,
522 size_t size_in_bytes,
523 const VMRegPair& reg_pair,
524 const Address& to,
525 Register tmp1,
526 Register tmp2,
527 Register tmp3,
528 int extraspace,
529 bool is_oop) {
530 if (bt == T_VOID) {
531 assert(prev_bt == T_LONG || prev_bt == T_DOUBLE, "missing half");
532 return;
533 }
534
535 // Say 4 args:
536 // i st_off
537 // 0 32 T_LONG
538 // 1 24 T_VOID
539 // 2 16 T_OBJECT
540 // 3 8 T_BOOL
541 // - 0 return address
542 //
543 // However to make thing extra confusing. Because we can fit a Java long/double in
544 // a single slot on a 64 bt vm and it would be silly to break them up, the interpreter
545 // leaves one slot empty and only stores to a single slot. In this case the
546 // slot that is occupied is the T_VOID slot. See I said it was confusing.
547
548 bool wide = (size_in_bytes == wordSize);
549 VMReg r_1 = reg_pair.first();
550 VMReg r_2 = reg_pair.second();
551 assert(r_2->is_valid() == wide, "invalid size");
552 if (!r_1->is_valid()) {
553 assert(!r_2->is_valid(), "");
554 return;
555 }
556
557 if (!r_1->is_FloatRegister()) {
558 Register val = r25;
559 if (r_1->is_stack()) {
560 // memory to memory use r25 (scratch registers is used by store_heap_oop)
561 int ld_off = r_1->reg2stack() * VMRegImpl::stack_slot_size + extraspace;
562 __ load_sized_value(val, Address(sp, ld_off), size_in_bytes, /* is_signed */ false);
563 } else {
564 val = r_1->as_Register();
565 }
566 assert_different_registers(to.base(), val, tmp1, tmp2, tmp3);
567 if (is_oop) {
568 // store_heap_oop transitively calls oop_store_at which corrupts to.base(). We need to keep it valid.
569 __ push(to.base(), sp);
570 __ store_heap_oop(to, val, tmp1, tmp2, tmp3, IN_HEAP | ACCESS_WRITE | IS_DEST_UNINITIALIZED);
571 __ pop(to.base(), sp);
572 } else {
573 __ store_sized_value(to, val, size_in_bytes);
574 }
575 } else {
576 if (wide) {
577 __ strd(r_1->as_FloatRegister(), to);
578 } else {
579 // only a float use just part of the slot
580 __ strs(r_1->as_FloatRegister(), to);
581 }
582 }
583 }
584
585 static void gen_c2i_adapter(MacroAssembler *masm,
586 const GrowableArray<SigEntry>* sig_extended,
587 const VMRegPair *regs,
588 bool requires_clinit_barrier,
589 address& c2i_no_clinit_check_entry,
590 Label& skip_fixup,
591 address start,
592 OopMapSet* oop_maps,
593 int& frame_complete,
594 int& frame_size_in_words,
595 bool alloc_inline_receiver) {
596 if (requires_clinit_barrier) {
597 assert(VM_Version::supports_fast_class_init_checks(), "sanity");
598 Label L_skip_barrier;
599
600 { // Bypass the barrier for non-static methods
601 __ ldrh(rscratch1, Address(rmethod, Method::access_flags_offset()));
602 __ andsw(zr, rscratch1, JVM_ACC_STATIC);
603 __ br(Assembler::EQ, L_skip_barrier); // non-static
604 }
605
606 __ load_method_holder(rscratch2, rmethod);
607 __ clinit_barrier(rscratch2, rscratch1, &L_skip_barrier);
608 __ far_jump(RuntimeAddress(SharedRuntime::get_handle_wrong_method_stub()));
609
610 __ bind(L_skip_barrier);
611 c2i_no_clinit_check_entry = __ pc();
612 }
613
614 BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
615 bs->c2i_entry_barrier(masm);
616
617 // Before we get into the guts of the C2I adapter, see if we should be here
618 // at all. We've come from compiled code and are attempting to jump to the
619 // interpreter, which means the caller made a static call to get here
620 // (vcalls always get a compiled target if there is one). Check for a
621 // compiled target. If there is one, we need to patch the caller's call.
622 patch_callers_callsite(masm);
623
624 __ bind(skip_fixup);
625
626 // Name some registers to be used in the following code. We can use
627 // anything except r0-r7 which are arguments in the Java calling
628 // convention, rmethod (r12), and r19 which holds the outgoing sender
629 // SP for the interpreter.
630 Register buf_array = r10; // Array of buffered inline types
631 Register buf_oop = r11; // Buffered inline type oop
632 Register tmp1 = r15;
633 Register tmp2 = r16;
634 Register tmp3 = r17;
635
636 #ifndef ASSERT
637 RegSet clobbered_gp_regs = MacroAssembler::call_clobbered_gp_registers();
638 assert(clobbered_gp_regs.contains(buf_array), "buf_array must be saved explicitly if it's not a clobber");
639 assert(clobbered_gp_regs.contains(buf_oop), "buf_oop must be saved explicitly if it's not a clobber");
640 assert(clobbered_gp_regs.contains(tmp1), "tmp1 must be saved explicitly if it's not a clobber");
641 assert(clobbered_gp_regs.contains(tmp2), "tmp2 must be saved explicitly if it's not a clobber");
642 assert(clobbered_gp_regs.contains(tmp3), "tmp3 must be saved explicitly if it's not a clobber");
643 #endif
644
645 if (InlineTypePassFieldsAsArgs) {
646 // Is there an inline type argument?
647 bool has_inline_argument = false;
648 for (int i = 0; i < sig_extended->length() && !has_inline_argument; i++) {
649 has_inline_argument = (sig_extended->at(i)._bt == T_METADATA);
650 }
651 if (has_inline_argument) {
652 // There is at least an inline type argument: we're coming from
653 // compiled code so we have no buffers to back the inline types
654 // Allocate the buffers here with a runtime call.
655 RegisterSaver reg_save(true /* save_vectors */);
656 OopMap* map = reg_save.save_live_registers(masm, 0, &frame_size_in_words);
657
658 frame_complete = __ offset();
659 address the_pc = __ pc();
660
661 Label retaddr;
662 __ set_last_Java_frame(sp, noreg, retaddr, rscratch1);
663
664 __ mov(c_rarg0, rthread);
665 __ mov(c_rarg1, rmethod);
666 __ mov(c_rarg2, (int64_t)alloc_inline_receiver);
667
668 __ lea(rscratch1, RuntimeAddress(CAST_FROM_FN_PTR(address, SharedRuntime::allocate_inline_types)));
669 __ blr(rscratch1);
670 __ bind(retaddr);
671
672 oop_maps->add_gc_map(__ pc() - start, map);
673 __ reset_last_Java_frame(false);
674
675 reg_save.restore_live_registers(masm);
676
677 Label no_exception;
678 __ ldr(rscratch1, Address(rthread, Thread::pending_exception_offset()));
679 __ cbz(rscratch1, no_exception);
680
681 __ str(zr, Address(rthread, JavaThread::vm_result_oop_offset()));
682 __ ldr(r0, Address(rthread, Thread::pending_exception_offset()));
683 __ far_jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
684
685 __ bind(no_exception);
686
687 // We get an array of objects from the runtime call
688 __ get_vm_result_oop(buf_array, rthread);
689 __ get_vm_result_metadata(rmethod, rthread); // TODO: required to keep the callee Method live?
690 }
691 }
692
693 // Since all args are passed on the stack, total_args_passed *
694 // Interpreter::stackElementSize is the space we need.
695
696 int total_args_passed = compute_total_args_passed_int(sig_extended);
697 int extraspace = total_args_passed * Interpreter::stackElementSize;
698
699 // stack is aligned, keep it that way
700 extraspace = align_up(extraspace, StackAlignmentInBytes);
701
702 // set senderSP value
703 __ mov(r19_sender_sp, sp);
704
705 __ sub(sp, sp, extraspace);
706
707 // Now write the args into the outgoing interpreter space
708
709 // next_arg_comp is the next argument from the compiler point of
710 // view (inline type fields are passed in registers/on the stack). In
711 // sig_extended, an inline type argument starts with: T_METADATA,
712 // followed by the types of the fields of the inline type and T_VOID
713 // to mark the end of the inline type. ignored counts the number of
714 // T_METADATA/T_VOID. next_vt_arg is the next inline type argument:
715 // used to get the buffer for that argument from the pool of buffers
716 // we allocated above and want to pass to the
717 // interpreter. next_arg_int is the next argument from the
718 // interpreter point of view (inline types are passed by reference).
719 for (int next_arg_comp = 0, ignored = 0, next_vt_arg = 0, next_arg_int = 0;
720 next_arg_comp < sig_extended->length(); next_arg_comp++) {
721 assert(ignored <= next_arg_comp, "shouldn't skip over more slots than there are arguments");
722 assert(next_arg_int <= total_args_passed, "more arguments for the interpreter than expected?");
723 BasicType bt = sig_extended->at(next_arg_comp)._bt;
724 int st_off = (total_args_passed - next_arg_int - 1) * Interpreter::stackElementSize;
725 if (!InlineTypePassFieldsAsArgs || bt != T_METADATA) {
726 int next_off = st_off - Interpreter::stackElementSize;
727 const int offset = (bt == T_LONG || bt == T_DOUBLE) ? next_off : st_off;
728 const VMRegPair reg_pair = regs[next_arg_comp-ignored];
729 size_t size_in_bytes = reg_pair.second()->is_valid() ? 8 : 4;
730 gen_c2i_adapter_helper(masm, bt, next_arg_comp > 0 ? sig_extended->at(next_arg_comp-1)._bt : T_ILLEGAL,
731 size_in_bytes, reg_pair, Address(sp, offset), tmp1, tmp2, tmp3, extraspace, false);
732 next_arg_int++;
733 #ifdef ASSERT
734 if (bt == T_LONG || bt == T_DOUBLE) {
735 // Overwrite the unused slot with known junk
736 __ mov(rscratch1, CONST64(0xdeadffffdeadaaaa));
737 __ str(rscratch1, Address(sp, st_off));
738 }
739 #endif /* ASSERT */
740 } else {
741 ignored++;
742 // get the buffer from the just allocated pool of buffers
743 int index = arrayOopDesc::base_offset_in_bytes(T_OBJECT) + next_vt_arg * type2aelembytes(T_OBJECT);
744 __ load_heap_oop(buf_oop, Address(buf_array, index), tmp1, tmp2);
745 next_vt_arg++; next_arg_int++;
746 int vt = 1;
747 // write fields we get from compiled code in registers/stack
748 // slots to the buffer: we know we are done with that inline type
749 // argument when we hit the T_VOID that acts as an end of inline
750 // type delimiter for this inline type. Inline types are flattened
751 // so we might encounter embedded inline types. Each entry in
752 // sig_extended contains a field offset in the buffer.
753 Label L_null;
754 do {
755 next_arg_comp++;
756 BasicType bt = sig_extended->at(next_arg_comp)._bt;
757 BasicType prev_bt = sig_extended->at(next_arg_comp - 1)._bt;
758 if (bt == T_METADATA) {
759 vt++;
760 ignored++;
761 } else if (bt == T_VOID && prev_bt != T_LONG && prev_bt != T_DOUBLE) {
762 vt--;
763 ignored++;
764 } else {
765 int off = sig_extended->at(next_arg_comp)._offset;
766 if (off == -1) {
767 // Nullable inline type argument, emit null check
768 VMReg reg = regs[next_arg_comp-ignored].first();
769 Label L_notNull;
770 if (reg->is_stack()) {
771 int ld_off = reg->reg2stack() * VMRegImpl::stack_slot_size + extraspace;
772 __ ldrb(tmp1, Address(sp, ld_off));
773 __ cbnz(tmp1, L_notNull);
774 } else {
775 __ cbnz(reg->as_Register(), L_notNull);
776 }
777 __ str(zr, Address(sp, st_off));
778 __ b(L_null);
779 __ bind(L_notNull);
780 continue;
781 }
782 assert(off > 0, "offset in object should be positive");
783 size_t size_in_bytes = is_java_primitive(bt) ? type2aelembytes(bt) : wordSize;
784 bool is_oop = is_reference_type(bt);
785 gen_c2i_adapter_helper(masm, bt, next_arg_comp > 0 ? sig_extended->at(next_arg_comp-1)._bt : T_ILLEGAL,
786 size_in_bytes, regs[next_arg_comp-ignored], Address(buf_oop, off), tmp1, tmp2, tmp3, extraspace, is_oop);
787 }
788 } while (vt != 0);
789 // pass the buffer to the interpreter
790 __ str(buf_oop, Address(sp, st_off));
791 __ bind(L_null);
792 }
793 }
794
795 __ mov(esp, sp); // Interp expects args on caller's expression stack
796
797 __ ldr(rscratch1, Address(rmethod, in_bytes(Method::interpreter_entry_offset())));
798 __ br(rscratch1);
799 }
800
801 void SharedRuntime::gen_i2c_adapter(MacroAssembler *masm, int comp_args_on_stack, const GrowableArray<SigEntry>* sig, const VMRegPair *regs) {
802
803
804 // Note: r19_sender_sp contains the senderSP on entry. We must
805 // preserve it since we may do a i2c -> c2i transition if we lose a
806 // race where compiled code goes non-entrant while we get args
807 // ready.
808
809 // Adapters are frameless.
810
811 // An i2c adapter is frameless because the *caller* frame, which is
812 // interpreted, routinely repairs its own esp (from
813 // interpreter_frame_last_sp), even if a callee has modified the
814 // stack pointer. It also recalculates and aligns sp.
815
816 // A c2i adapter is frameless because the *callee* frame, which is
817 // interpreted, routinely repairs its caller's sp (from sender_sp,
818 // which is set up via the senderSP register).
819
820 // In other words, if *either* the caller or callee is interpreted, we can
821 // get the stack pointer repaired after a call.
822
823 // This is why c2i and i2c adapters cannot be indefinitely composed.
824 // In particular, if a c2i adapter were to somehow call an i2c adapter,
825 // both caller and callee would be compiled methods, and neither would
826 // clean up the stack pointer changes performed by the two adapters.
827 // If this happens, control eventually transfers back to the compiled
828 // caller, but with an uncorrected stack, causing delayed havoc.
829
830 // Cut-out for having no stack args.
831 int comp_words_on_stack = 0;
832 if (comp_args_on_stack) {
833 comp_words_on_stack = align_up(comp_args_on_stack * VMRegImpl::stack_slot_size, wordSize) >> LogBytesPerWord;
834 __ sub(rscratch1, sp, comp_words_on_stack * wordSize);
835 __ andr(sp, rscratch1, -16);
836 }
837
838 // Will jump to the compiled code just as if compiled code was doing it.
839 // Pre-load the register-jump target early, to schedule it better.
840 __ ldr(rscratch1, Address(rmethod, in_bytes(Method::from_compiled_inline_offset())));
841
842 #if INCLUDE_JVMCI
843 if (EnableJVMCI) {
844 // check if this call should be routed towards a specific entry point
845 __ ldr(rscratch2, Address(rthread, in_bytes(JavaThread::jvmci_alternate_call_target_offset())));
846 Label no_alternative_target;
847 __ cbz(rscratch2, no_alternative_target);
848 __ mov(rscratch1, rscratch2);
849 __ str(zr, Address(rthread, in_bytes(JavaThread::jvmci_alternate_call_target_offset())));
850 __ bind(no_alternative_target);
851 }
852 #endif // INCLUDE_JVMCI
853
854 int total_args_passed = sig->length();
855
856 // Now generate the shuffle code.
857 for (int i = 0; i < total_args_passed; i++) {
858 BasicType bt = sig->at(i)._bt;
859 if (bt == T_VOID) {
860 assert(i > 0 && (sig->at(i - 1)._bt == T_LONG || sig->at(i - 1)._bt == T_DOUBLE), "missing half");
861 continue;
862 }
863
864 // Pick up 0, 1 or 2 words from SP+offset.
865 assert(!regs[i].second()->is_valid() || regs[i].first()->next() == regs[i].second(), "scrambled load targets?");
866
867 // Load in argument order going down.
868 int ld_off = (total_args_passed - i - 1) * Interpreter::stackElementSize;
869 // Point to interpreter value (vs. tag)
870 int next_off = ld_off - Interpreter::stackElementSize;
871 //
872 //
873 //
874 VMReg r_1 = regs[i].first();
875 VMReg r_2 = regs[i].second();
876 if (!r_1->is_valid()) {
877 assert(!r_2->is_valid(), "");
878 continue;
879 }
880 if (r_1->is_stack()) {
881 // Convert stack slot to an SP offset (+ wordSize to account for return address )
882 int st_off = regs[i].first()->reg2stack() * VMRegImpl::stack_slot_size;
883 if (!r_2->is_valid()) {
884 // sign extend???
885 __ ldrsw(rscratch2, Address(esp, ld_off));
886 __ str(rscratch2, Address(sp, st_off));
887 } else {
888 //
889 // We are using two optoregs. This can be either T_OBJECT,
890 // T_ADDRESS, T_LONG, or T_DOUBLE the interpreter allocates
891 // two slots but only uses one for thr T_LONG or T_DOUBLE case
892 // So we must adjust where to pick up the data to match the
893 // interpreter.
894 //
895 // Interpreter local[n] == MSW, local[n+1] == LSW however locals
896 // are accessed as negative so LSW is at LOW address
897
898 // ld_off is MSW so get LSW
899 const int offset = (bt == T_LONG || bt == T_DOUBLE) ? next_off : ld_off;
900 __ ldr(rscratch2, Address(esp, offset));
901 // st_off is LSW (i.e. reg.first())
902 __ str(rscratch2, Address(sp, st_off));
903 }
904 } else if (r_1->is_Register()) { // Register argument
905 Register r = r_1->as_Register();
906 if (r_2->is_valid()) {
907 //
908 // We are using two VMRegs. This can be either T_OBJECT,
909 // T_ADDRESS, T_LONG, or T_DOUBLE the interpreter allocates
910 // two slots but only uses one for thr T_LONG or T_DOUBLE case
911 // So we must adjust where to pick up the data to match the
912 // interpreter.
913
914 const int offset = (bt == T_LONG || bt == T_DOUBLE) ? next_off : ld_off;
915
916 // this can be a misaligned move
917 __ ldr(r, Address(esp, offset));
918 } else {
919 // sign extend and use a full word?
920 __ ldrw(r, Address(esp, ld_off));
921 }
922 } else {
923 if (!r_2->is_valid()) {
924 __ ldrs(r_1->as_FloatRegister(), Address(esp, ld_off));
925 } else {
926 __ ldrd(r_1->as_FloatRegister(), Address(esp, next_off));
927 }
928 }
929 }
930
931
932 __ mov(rscratch2, rscratch1);
933 __ push_cont_fastpath(rthread); // Set JavaThread::_cont_fastpath to the sp of the oldest interpreted frame we know about; kills rscratch1
934 __ mov(rscratch1, rscratch2);
935
936 // 6243940 We might end up in handle_wrong_method if
937 // the callee is deoptimized as we race thru here. If that
938 // happens we don't want to take a safepoint because the
939 // caller frame will look interpreted and arguments are now
940 // "compiled" so it is much better to make this transition
941 // invisible to the stack walking code. Unfortunately if
942 // we try and find the callee by normal means a safepoint
943 // is possible. So we stash the desired callee in the thread
944 // and the vm will find there should this case occur.
945
946 __ str(rmethod, Address(rthread, JavaThread::callee_target_offset()));
947 __ br(rscratch1);
948 }
949
950 static void gen_inline_cache_check(MacroAssembler *masm, Label& skip_fixup) {
951 Register data = rscratch2;
952 __ ic_check(1 /* end_alignment */);
953 __ ldr(rmethod, Address(data, CompiledICData::speculated_method_offset()));
954
955 // Method might have been compiled since the call site was patched to
956 // interpreted; if that is the case treat it as a miss so we can get
957 // the call site corrected.
958 __ ldr(rscratch1, Address(rmethod, in_bytes(Method::code_offset())));
959 __ cbz(rscratch1, skip_fixup);
960 __ far_jump(RuntimeAddress(SharedRuntime::get_ic_miss_stub()));
961 }
962
963 // ---------------------------------------------------------------
964 void SharedRuntime::generate_i2c2i_adapters(MacroAssembler* masm,
965 int comp_args_on_stack,
966 const GrowableArray<SigEntry>* sig,
967 const VMRegPair* regs,
968 const GrowableArray<SigEntry>* sig_cc,
969 const VMRegPair* regs_cc,
970 const GrowableArray<SigEntry>* sig_cc_ro,
971 const VMRegPair* regs_cc_ro,
972 address entry_address[AdapterBlob::ENTRY_COUNT],
973 AdapterBlob*& new_adapter,
974 bool allocate_code_blob) {
975
976 entry_address[AdapterBlob::I2C] = __ pc();
977 gen_i2c_adapter(masm, comp_args_on_stack, sig, regs);
978
979 // -------------------------------------------------------------------------
980 // Generate a C2I adapter. On entry we know rmethod holds the Method* during calls
981 // to the interpreter. The args start out packed in the compiled layout. They
982 // need to be unpacked into the interpreter layout. This will almost always
983 // require some stack space. We grow the current (compiled) stack, then repack
984 // the args. We finally end in a jump to the generic interpreter entry point.
985 // On exit from the interpreter, the interpreter will restore our SP (lest the
986 // compiled code, which relies solely on SP and not FP, get sick).
987
988 entry_address[AdapterBlob::C2I_Unverified] = __ pc();
989 entry_address[AdapterBlob::C2I_Unverified_Inline] = __ pc();
990 Label skip_fixup;
991
992 gen_inline_cache_check(masm, skip_fixup);
993
994 OopMapSet* oop_maps = new OopMapSet();
995 int frame_complete = CodeOffsets::frame_never_safe;
996 int frame_size_in_words = 0;
997
998 // Scalarized c2i adapter with non-scalarized receiver (i.e., don't pack receiver)
999 entry_address[AdapterBlob::C2I_No_Clinit_Check] = nullptr;
1000 entry_address[AdapterBlob::C2I_Inline_RO] = __ pc();
1001 if (regs_cc != regs_cc_ro) {
1002 // No class init barrier needed because method is guaranteed to be non-static
1003 gen_c2i_adapter(masm, sig_cc_ro, regs_cc_ro, /* requires_clinit_barrier = */ false, entry_address[AdapterBlob::C2I_No_Clinit_Check],
1004 skip_fixup, entry_address[AdapterBlob::I2C], oop_maps, frame_complete, frame_size_in_words, /* alloc_inline_receiver = */ false);
1005 skip_fixup.reset();
1006 }
1007
1008 // Scalarized c2i adapter
1009 entry_address[AdapterBlob::C2I] = __ pc();
1010 entry_address[AdapterBlob::C2I_Inline] = __ pc();
1011 gen_c2i_adapter(masm, sig_cc, regs_cc, /* requires_clinit_barrier = */ true, entry_address[AdapterBlob::C2I_No_Clinit_Check],
1012 skip_fixup, entry_address[AdapterBlob::I2C], oop_maps, frame_complete, frame_size_in_words, /* alloc_inline_receiver = */ true);
1013
1014 // Non-scalarized c2i adapter
1015 if (regs != regs_cc) {
1016 entry_address[AdapterBlob::C2I_Unverified_Inline] = __ pc();
1017 Label inline_entry_skip_fixup;
1018 gen_inline_cache_check(masm, inline_entry_skip_fixup);
1019
1020 entry_address[AdapterBlob::C2I_Inline] = __ pc();
1021 gen_c2i_adapter(masm, sig, regs, /* requires_clinit_barrier = */ true, entry_address[AdapterBlob::C2I_No_Clinit_Check],
1022 inline_entry_skip_fixup, entry_address[AdapterBlob::I2C], oop_maps, frame_complete, frame_size_in_words, /* alloc_inline_receiver = */ false);
1023 }
1024
1025 // The c2i adapters might safepoint and trigger a GC. The caller must make sure that
1026 // the GC knows about the location of oop argument locations passed to the c2i adapter.
1027 if (allocate_code_blob) {
1028 bool caller_must_gc_arguments = (regs != regs_cc);
1029 int entry_offset[AdapterHandlerEntry::ENTRIES_COUNT];
1030 assert(AdapterHandlerEntry::ENTRIES_COUNT == 7, "sanity");
1031 AdapterHandlerLibrary::address_to_offset(entry_address, entry_offset);
1032 new_adapter = AdapterBlob::create(masm->code(), entry_offset, frame_complete, frame_size_in_words, oop_maps, caller_must_gc_arguments);
1033 }
1034 }
1035
1036 static int c_calling_convention_priv(const BasicType *sig_bt,
1037 VMRegPair *regs,
1038 int total_args_passed) {
1039
1040 // We return the amount of VMRegImpl stack slots we need to reserve for all
1041 // the arguments NOT counting out_preserve_stack_slots.
1042
1043 static const Register INT_ArgReg[Argument::n_int_register_parameters_c] = {
1044 c_rarg0, c_rarg1, c_rarg2, c_rarg3, c_rarg4, c_rarg5, c_rarg6, c_rarg7
1045 };
1046 static const FloatRegister FP_ArgReg[Argument::n_float_register_parameters_c] = {
1047 c_farg0, c_farg1, c_farg2, c_farg3,
1048 c_farg4, c_farg5, c_farg6, c_farg7
1049 };
1050
1051 uint int_args = 0;
1052 uint fp_args = 0;
1053 uint stk_args = 0; // inc by 2 each time
1054
1055 for (int i = 0; i < total_args_passed; i++) {
1056 switch (sig_bt[i]) {
1057 case T_BOOLEAN:
1058 case T_CHAR:
1059 case T_BYTE:
1060 case T_SHORT:
1061 case T_INT:
1062 if (int_args < Argument::n_int_register_parameters_c) {
1063 regs[i].set1(INT_ArgReg[int_args++]->as_VMReg());
1064 } else {
1065 #ifdef __APPLE__
1066 // Less-than word types are stored one after another.
1067 // The code is unable to handle this so bailout.
1068 return -1;
1069 #endif
1070 regs[i].set1(VMRegImpl::stack2reg(stk_args));
1071 stk_args += 2;
1072 }
1073 break;
1074 case T_LONG:
1075 assert((i + 1) < total_args_passed && sig_bt[i + 1] == T_VOID, "expecting half");
1076 // fall through
1077 case T_OBJECT:
1078 case T_ARRAY:
1079 case T_ADDRESS:
1080 case T_METADATA:
1081 if (int_args < Argument::n_int_register_parameters_c) {
1082 regs[i].set2(INT_ArgReg[int_args++]->as_VMReg());
1083 } else {
1084 regs[i].set2(VMRegImpl::stack2reg(stk_args));
1085 stk_args += 2;
1086 }
1087 break;
1088 case T_FLOAT:
1089 if (fp_args < Argument::n_float_register_parameters_c) {
1090 regs[i].set1(FP_ArgReg[fp_args++]->as_VMReg());
1091 } else {
1092 #ifdef __APPLE__
1093 // Less-than word types are stored one after another.
1094 // The code is unable to handle this so bailout.
1095 return -1;
1096 #endif
1097 regs[i].set1(VMRegImpl::stack2reg(stk_args));
1098 stk_args += 2;
1099 }
1100 break;
1101 case T_DOUBLE:
1102 assert((i + 1) < total_args_passed && sig_bt[i + 1] == T_VOID, "expecting half");
1103 if (fp_args < Argument::n_float_register_parameters_c) {
1104 regs[i].set2(FP_ArgReg[fp_args++]->as_VMReg());
1105 } else {
1106 regs[i].set2(VMRegImpl::stack2reg(stk_args));
1107 stk_args += 2;
1108 }
1109 break;
1110 case T_VOID: // Halves of longs and doubles
1111 assert(i != 0 && (sig_bt[i - 1] == T_LONG || sig_bt[i - 1] == T_DOUBLE), "expecting half");
1112 regs[i].set_bad();
1113 break;
1114 default:
1115 ShouldNotReachHere();
1116 break;
1117 }
1118 }
1119
1120 return stk_args;
1121 }
1122
1123 int SharedRuntime::vector_calling_convention(VMRegPair *regs,
1124 uint num_bits,
1125 uint total_args_passed) {
1126 // More than 8 argument inputs are not supported now.
1127 assert(total_args_passed <= Argument::n_float_register_parameters_c, "unsupported");
1128 assert(num_bits >= 64 && num_bits <= 2048 && is_power_of_2(num_bits), "unsupported");
1129
1130 static const FloatRegister VEC_ArgReg[Argument::n_float_register_parameters_c] = {
1131 v0, v1, v2, v3, v4, v5, v6, v7
1132 };
1133
1134 // On SVE, we use the same vector registers with 128-bit vector registers on NEON.
1135 int next_reg_val = num_bits == 64 ? 1 : 3;
1136 for (uint i = 0; i < total_args_passed; i++) {
1137 VMReg vmreg = VEC_ArgReg[i]->as_VMReg();
1138 regs[i].set_pair(vmreg->next(next_reg_val), vmreg);
1139 }
1140 return 0;
1141 }
1142
1143 int SharedRuntime::c_calling_convention(const BasicType *sig_bt,
1144 VMRegPair *regs,
1145 int total_args_passed)
1146 {
1147 int result = c_calling_convention_priv(sig_bt, regs, total_args_passed);
1148 guarantee(result >= 0, "Unsupported arguments configuration");
1149 return result;
1150 }
1151
1152
1153 void SharedRuntime::save_native_result(MacroAssembler *masm, BasicType ret_type, int frame_slots) {
1154 // We always ignore the frame_slots arg and just use the space just below frame pointer
1155 // which by this time is free to use
1156 switch (ret_type) {
1157 case T_FLOAT:
1158 __ strs(v0, Address(rfp, -wordSize));
1159 break;
1160 case T_DOUBLE:
1161 __ strd(v0, Address(rfp, -wordSize));
1162 break;
1163 case T_VOID: break;
1164 default: {
1165 __ str(r0, Address(rfp, -wordSize));
1166 }
1167 }
1168 }
1169
1170 void SharedRuntime::restore_native_result(MacroAssembler *masm, BasicType ret_type, int frame_slots) {
1171 // We always ignore the frame_slots arg and just use the space just below frame pointer
1172 // which by this time is free to use
1173 switch (ret_type) {
1174 case T_FLOAT:
1175 __ ldrs(v0, Address(rfp, -wordSize));
1176 break;
1177 case T_DOUBLE:
1178 __ ldrd(v0, Address(rfp, -wordSize));
1179 break;
1180 case T_VOID: break;
1181 default: {
1182 __ ldr(r0, Address(rfp, -wordSize));
1183 }
1184 }
1185 }
1186 static void save_args(MacroAssembler *masm, int arg_count, int first_arg, VMRegPair *args) {
1187 RegSet x;
1188 for ( int i = first_arg ; i < arg_count ; i++ ) {
1189 if (args[i].first()->is_Register()) {
1190 x = x + args[i].first()->as_Register();
1191 } else if (args[i].first()->is_FloatRegister()) {
1192 __ strd(args[i].first()->as_FloatRegister(), Address(__ pre(sp, -2 * wordSize)));
1193 }
1194 }
1195 __ push(x, sp);
1196 }
1197
1198 static void restore_args(MacroAssembler *masm, int arg_count, int first_arg, VMRegPair *args) {
1199 RegSet x;
1200 for ( int i = first_arg ; i < arg_count ; i++ ) {
1201 if (args[i].first()->is_Register()) {
1202 x = x + args[i].first()->as_Register();
1203 } else {
1204 ;
1205 }
1206 }
1207 __ pop(x, sp);
1208 for ( int i = arg_count - 1 ; i >= first_arg ; i-- ) {
1209 if (args[i].first()->is_Register()) {
1210 ;
1211 } else if (args[i].first()->is_FloatRegister()) {
1212 __ ldrd(args[i].first()->as_FloatRegister(), Address(__ post(sp, 2 * wordSize)));
1213 }
1214 }
1215 }
1216
1217 static void verify_oop_args(MacroAssembler* masm,
1218 const methodHandle& method,
1219 const BasicType* sig_bt,
1220 const VMRegPair* regs) {
1221 Register temp_reg = r19; // not part of any compiled calling seq
1222 if (VerifyOops) {
1223 for (int i = 0; i < method->size_of_parameters(); i++) {
1224 if (sig_bt[i] == T_OBJECT ||
1225 sig_bt[i] == T_ARRAY) {
1226 VMReg r = regs[i].first();
1227 assert(r->is_valid(), "bad oop arg");
1228 if (r->is_stack()) {
1229 __ ldr(temp_reg, Address(sp, r->reg2stack() * VMRegImpl::stack_slot_size));
1230 __ verify_oop(temp_reg);
1231 } else {
1232 __ verify_oop(r->as_Register());
1233 }
1234 }
1235 }
1236 }
1237 }
1238
1239 // on exit, sp points to the ContinuationEntry
1240 static OopMap* continuation_enter_setup(MacroAssembler* masm, int& stack_slots) {
1241 assert(ContinuationEntry::size() % VMRegImpl::stack_slot_size == 0, "");
1242 assert(in_bytes(ContinuationEntry::cont_offset()) % VMRegImpl::stack_slot_size == 0, "");
1243 assert(in_bytes(ContinuationEntry::chunk_offset()) % VMRegImpl::stack_slot_size == 0, "");
1244
1245 stack_slots += (int)ContinuationEntry::size()/wordSize;
1246 __ sub(sp, sp, (int)ContinuationEntry::size()); // place Continuation metadata
1247
1248 OopMap* map = new OopMap(((int)ContinuationEntry::size() + wordSize)/ VMRegImpl::stack_slot_size, 0 /* arg_slots*/);
1249
1250 __ ldr(rscratch1, Address(rthread, JavaThread::cont_entry_offset()));
1251 __ str(rscratch1, Address(sp, ContinuationEntry::parent_offset()));
1252 __ mov(rscratch1, sp); // we can't use sp as the source in str
1253 __ str(rscratch1, Address(rthread, JavaThread::cont_entry_offset()));
1254
1255 return map;
1256 }
1257
1258 // on entry c_rarg1 points to the continuation
1259 // sp points to ContinuationEntry
1260 // c_rarg3 -- isVirtualThread
1261 static void fill_continuation_entry(MacroAssembler* masm) {
1262 #ifdef ASSERT
1263 __ movw(rscratch1, ContinuationEntry::cookie_value());
1264 __ strw(rscratch1, Address(sp, ContinuationEntry::cookie_offset()));
1265 #endif
1266
1267 __ str (c_rarg1, Address(sp, ContinuationEntry::cont_offset()));
1268 __ strw(c_rarg3, Address(sp, ContinuationEntry::flags_offset()));
1269 __ str (zr, Address(sp, ContinuationEntry::chunk_offset()));
1270 __ strw(zr, Address(sp, ContinuationEntry::argsize_offset()));
1271 __ strw(zr, Address(sp, ContinuationEntry::pin_count_offset()));
1272
1273 __ ldr(rscratch1, Address(rthread, JavaThread::cont_fastpath_offset()));
1274 __ str(rscratch1, Address(sp, ContinuationEntry::parent_cont_fastpath_offset()));
1275
1276 __ str(zr, Address(rthread, JavaThread::cont_fastpath_offset()));
1277 }
1278
1279 // on entry, sp points to the ContinuationEntry
1280 // on exit, rfp points to the spilled rfp in the entry frame
1281 static void continuation_enter_cleanup(MacroAssembler* masm) {
1282 #ifndef PRODUCT
1283 Label OK;
1284 __ ldr(rscratch1, Address(rthread, JavaThread::cont_entry_offset()));
1285 __ cmp(sp, rscratch1);
1286 __ br(Assembler::EQ, OK);
1287 __ stop("incorrect sp1");
1288 __ bind(OK);
1289 #endif
1290 __ ldr(rscratch1, Address(sp, ContinuationEntry::parent_cont_fastpath_offset()));
1291 __ str(rscratch1, Address(rthread, JavaThread::cont_fastpath_offset()));
1292 __ ldr(rscratch2, Address(sp, ContinuationEntry::parent_offset()));
1293 __ str(rscratch2, Address(rthread, JavaThread::cont_entry_offset()));
1294 __ add(rfp, sp, (int)ContinuationEntry::size());
1295 }
1296
1297 // enterSpecial(Continuation c, boolean isContinue, boolean isVirtualThread)
1298 // On entry: c_rarg1 -- the continuation object
1299 // c_rarg2 -- isContinue
1300 // c_rarg3 -- isVirtualThread
1301 static void gen_continuation_enter(MacroAssembler* masm,
1302 const methodHandle& method,
1303 const BasicType* sig_bt,
1304 const VMRegPair* regs,
1305 int& exception_offset,
1306 OopMapSet*oop_maps,
1307 int& frame_complete,
1308 int& stack_slots,
1309 int& interpreted_entry_offset,
1310 int& compiled_entry_offset) {
1311 //verify_oop_args(masm, method, sig_bt, regs);
1312 Address resolve(SharedRuntime::get_resolve_static_call_stub(), relocInfo::static_call_type);
1313
1314 address start = __ pc();
1315
1316 Label call_thaw, exit;
1317
1318 // i2i entry used at interp_only_mode only
1319 interpreted_entry_offset = __ pc() - start;
1320 {
1321
1322 #ifdef ASSERT
1323 Label is_interp_only;
1324 __ ldrw(rscratch1, Address(rthread, JavaThread::interp_only_mode_offset()));
1325 __ cbnzw(rscratch1, is_interp_only);
1326 __ stop("enterSpecial interpreter entry called when not in interp_only_mode");
1327 __ bind(is_interp_only);
1328 #endif
1329
1330 // Read interpreter arguments into registers (this is an ad-hoc i2c adapter)
1331 __ ldr(c_rarg1, Address(esp, Interpreter::stackElementSize*2));
1332 __ ldr(c_rarg2, Address(esp, Interpreter::stackElementSize*1));
1333 __ ldr(c_rarg3, Address(esp, Interpreter::stackElementSize*0));
1334 __ push_cont_fastpath(rthread);
1335
1336 __ enter();
1337 stack_slots = 2; // will be adjusted in setup
1338 OopMap* map = continuation_enter_setup(masm, stack_slots);
1339 // The frame is complete here, but we only record it for the compiled entry, so the frame would appear unsafe,
1340 // but that's okay because at the very worst we'll miss an async sample, but we're in interp_only_mode anyway.
1341
1342 fill_continuation_entry(masm);
1343
1344 __ cbnz(c_rarg2, call_thaw);
1345
1346 const address tr_call = __ trampoline_call(resolve);
1347 if (tr_call == nullptr) {
1348 fatal("CodeCache is full at gen_continuation_enter");
1349 }
1350
1351 oop_maps->add_gc_map(__ pc() - start, map);
1352 __ post_call_nop();
1353
1354 __ b(exit);
1355
1356 address stub = CompiledDirectCall::emit_to_interp_stub(masm, tr_call);
1357 if (stub == nullptr) {
1358 fatal("CodeCache is full at gen_continuation_enter");
1359 }
1360 }
1361
1362 // compiled entry
1363 __ align(CodeEntryAlignment);
1364 compiled_entry_offset = __ pc() - start;
1365
1366 __ enter();
1367 stack_slots = 2; // will be adjusted in setup
1368 OopMap* map = continuation_enter_setup(masm, stack_slots);
1369 frame_complete = __ pc() - start;
1370
1371 fill_continuation_entry(masm);
1372
1373 __ cbnz(c_rarg2, call_thaw);
1374
1375 const address tr_call = __ trampoline_call(resolve);
1376 if (tr_call == nullptr) {
1377 fatal("CodeCache is full at gen_continuation_enter");
1378 }
1379
1380 oop_maps->add_gc_map(__ pc() - start, map);
1381 __ post_call_nop();
1382
1383 __ b(exit);
1384
1385 __ bind(call_thaw);
1386
1387 ContinuationEntry::_thaw_call_pc_offset = __ pc() - start;
1388 __ rt_call(CAST_FROM_FN_PTR(address, StubRoutines::cont_thaw()));
1389 oop_maps->add_gc_map(__ pc() - start, map->deep_copy());
1390 ContinuationEntry::_return_pc_offset = __ pc() - start;
1391 __ post_call_nop();
1392
1393 __ bind(exit);
1394 ContinuationEntry::_cleanup_offset = __ pc() - start;
1395 continuation_enter_cleanup(masm);
1396 __ leave();
1397 __ ret(lr);
1398
1399 /// exception handling
1400
1401 exception_offset = __ pc() - start;
1402 {
1403 __ mov(r19, r0); // save return value contaning the exception oop in callee-saved R19
1404
1405 continuation_enter_cleanup(masm);
1406
1407 __ ldr(c_rarg1, Address(rfp, wordSize)); // return address
1408 __ authenticate_return_address(c_rarg1);
1409 __ call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::exception_handler_for_return_address), rthread, c_rarg1);
1410
1411 // see OptoRuntime::generate_exception_blob: r0 -- exception oop, r3 -- exception pc
1412
1413 __ mov(r1, r0); // the exception handler
1414 __ mov(r0, r19); // restore return value contaning the exception oop
1415 __ verify_oop(r0);
1416
1417 __ leave();
1418 __ mov(r3, lr);
1419 __ br(r1); // the exception handler
1420 }
1421
1422 address stub = CompiledDirectCall::emit_to_interp_stub(masm, tr_call);
1423 if (stub == nullptr) {
1424 fatal("CodeCache is full at gen_continuation_enter");
1425 }
1426 }
1427
1428 static void gen_continuation_yield(MacroAssembler* masm,
1429 const methodHandle& method,
1430 const BasicType* sig_bt,
1431 const VMRegPair* regs,
1432 OopMapSet* oop_maps,
1433 int& frame_complete,
1434 int& stack_slots,
1435 int& compiled_entry_offset) {
1436 enum layout {
1437 rfp_off1,
1438 rfp_off2,
1439 lr_off,
1440 lr_off2,
1441 framesize // inclusive of return address
1442 };
1443 // assert(is_even(framesize/2), "sp not 16-byte aligned");
1444 stack_slots = framesize / VMRegImpl::slots_per_word;
1445 assert(stack_slots == 2, "recheck layout");
1446
1447 address start = __ pc();
1448
1449 compiled_entry_offset = __ pc() - start;
1450 __ enter();
1451
1452 __ mov(c_rarg1, sp);
1453
1454 frame_complete = __ pc() - start;
1455 address the_pc = __ pc();
1456
1457 __ 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
1458
1459 __ mov(c_rarg0, rthread);
1460 __ set_last_Java_frame(sp, rfp, the_pc, rscratch1);
1461 __ call_VM_leaf(Continuation::freeze_entry(), 2);
1462 __ reset_last_Java_frame(true);
1463
1464 Label pinned;
1465
1466 __ cbnz(r0, pinned);
1467
1468 // We've succeeded, set sp to the ContinuationEntry
1469 __ ldr(rscratch1, Address(rthread, JavaThread::cont_entry_offset()));
1470 __ mov(sp, rscratch1);
1471 continuation_enter_cleanup(masm);
1472
1473 __ bind(pinned); // pinned -- return to caller
1474
1475 // handle pending exception thrown by freeze
1476 __ ldr(rscratch1, Address(rthread, in_bytes(Thread::pending_exception_offset())));
1477 Label ok;
1478 __ cbz(rscratch1, ok);
1479 __ leave();
1480 __ lea(rscratch1, RuntimeAddress(StubRoutines::forward_exception_entry()));
1481 __ br(rscratch1);
1482 __ bind(ok);
1483
1484 __ leave();
1485 __ ret(lr);
1486
1487 OopMap* map = new OopMap(framesize, 1);
1488 oop_maps->add_gc_map(the_pc - start, map);
1489 }
1490
1491 void SharedRuntime::continuation_enter_cleanup(MacroAssembler* masm) {
1492 ::continuation_enter_cleanup(masm);
1493 }
1494
1495 static void gen_special_dispatch(MacroAssembler* masm,
1496 const methodHandle& method,
1497 const BasicType* sig_bt,
1498 const VMRegPair* regs) {
1499 verify_oop_args(masm, method, sig_bt, regs);
1500 vmIntrinsics::ID iid = method->intrinsic_id();
1501
1502 // Now write the args into the outgoing interpreter space
1503 bool has_receiver = false;
1504 Register receiver_reg = noreg;
1505 int member_arg_pos = -1;
1506 Register member_reg = noreg;
1507 int ref_kind = MethodHandles::signature_polymorphic_intrinsic_ref_kind(iid);
1508 if (ref_kind != 0) {
1509 member_arg_pos = method->size_of_parameters() - 1; // trailing MemberName argument
1510 member_reg = r19; // known to be free at this point
1511 has_receiver = MethodHandles::ref_kind_has_receiver(ref_kind);
1512 } else if (iid == vmIntrinsics::_invokeBasic) {
1513 has_receiver = true;
1514 } else if (iid == vmIntrinsics::_linkToNative) {
1515 member_arg_pos = method->size_of_parameters() - 1; // trailing NativeEntryPoint argument
1516 member_reg = r19; // known to be free at this point
1517 } else {
1518 fatal("unexpected intrinsic id %d", vmIntrinsics::as_int(iid));
1519 }
1520
1521 if (member_reg != noreg) {
1522 // Load the member_arg into register, if necessary.
1523 SharedRuntime::check_member_name_argument_is_last_argument(method, sig_bt, regs);
1524 VMReg r = regs[member_arg_pos].first();
1525 if (r->is_stack()) {
1526 __ ldr(member_reg, Address(sp, r->reg2stack() * VMRegImpl::stack_slot_size));
1527 } else {
1528 // no data motion is needed
1529 member_reg = r->as_Register();
1530 }
1531 }
1532
1533 if (has_receiver) {
1534 // Make sure the receiver is loaded into a register.
1535 assert(method->size_of_parameters() > 0, "oob");
1536 assert(sig_bt[0] == T_OBJECT, "receiver argument must be an object");
1537 VMReg r = regs[0].first();
1538 assert(r->is_valid(), "bad receiver arg");
1539 if (r->is_stack()) {
1540 // Porting note: This assumes that compiled calling conventions always
1541 // pass the receiver oop in a register. If this is not true on some
1542 // platform, pick a temp and load the receiver from stack.
1543 fatal("receiver always in a register");
1544 receiver_reg = r2; // known to be free at this point
1545 __ ldr(receiver_reg, Address(sp, r->reg2stack() * VMRegImpl::stack_slot_size));
1546 } else {
1547 // no data motion is needed
1548 receiver_reg = r->as_Register();
1549 }
1550 }
1551
1552 // Figure out which address we are really jumping to:
1553 MethodHandles::generate_method_handle_dispatch(masm, iid,
1554 receiver_reg, member_reg, /*for_compiler_entry:*/ true);
1555 }
1556
1557 // ---------------------------------------------------------------------------
1558 // Generate a native wrapper for a given method. The method takes arguments
1559 // in the Java compiled code convention, marshals them to the native
1560 // convention (handlizes oops, etc), transitions to native, makes the call,
1561 // returns to java state (possibly blocking), unhandlizes any result and
1562 // returns.
1563 //
1564 // Critical native functions are a shorthand for the use of
1565 // GetPrimtiveArrayCritical and disallow the use of any other JNI
1566 // functions. The wrapper is expected to unpack the arguments before
1567 // passing them to the callee. Critical native functions leave the state _in_Java,
1568 // since they block out GC.
1569 // Some other parts of JNI setup are skipped like the tear down of the JNI handle
1570 // block and the check for pending exceptions it's impossible for them
1571 // to be thrown.
1572 //
1573 nmethod* SharedRuntime::generate_native_wrapper(MacroAssembler* masm,
1574 const methodHandle& method,
1575 int compile_id,
1576 BasicType* in_sig_bt,
1577 VMRegPair* in_regs,
1578 BasicType ret_type) {
1579 if (method->is_continuation_native_intrinsic()) {
1580 int exception_offset = -1;
1581 OopMapSet* oop_maps = new OopMapSet();
1582 int frame_complete = -1;
1583 int stack_slots = -1;
1584 int interpreted_entry_offset = -1;
1585 int vep_offset = -1;
1586 if (method->is_continuation_enter_intrinsic()) {
1587 gen_continuation_enter(masm,
1588 method,
1589 in_sig_bt,
1590 in_regs,
1591 exception_offset,
1592 oop_maps,
1593 frame_complete,
1594 stack_slots,
1595 interpreted_entry_offset,
1596 vep_offset);
1597 } else if (method->is_continuation_yield_intrinsic()) {
1598 gen_continuation_yield(masm,
1599 method,
1600 in_sig_bt,
1601 in_regs,
1602 oop_maps,
1603 frame_complete,
1604 stack_slots,
1605 vep_offset);
1606 } else {
1607 guarantee(false, "Unknown Continuation native intrinsic");
1608 }
1609
1610 #ifdef ASSERT
1611 if (method->is_continuation_enter_intrinsic()) {
1612 assert(interpreted_entry_offset != -1, "Must be set");
1613 assert(exception_offset != -1, "Must be set");
1614 } else {
1615 assert(interpreted_entry_offset == -1, "Must be unset");
1616 assert(exception_offset == -1, "Must be unset");
1617 }
1618 assert(frame_complete != -1, "Must be set");
1619 assert(stack_slots != -1, "Must be set");
1620 assert(vep_offset != -1, "Must be set");
1621 #endif
1622
1623 __ flush();
1624 nmethod* nm = nmethod::new_native_nmethod(method,
1625 compile_id,
1626 masm->code(),
1627 vep_offset,
1628 frame_complete,
1629 stack_slots,
1630 in_ByteSize(-1),
1631 in_ByteSize(-1),
1632 oop_maps,
1633 exception_offset);
1634 if (nm == nullptr) return nm;
1635 if (method->is_continuation_enter_intrinsic()) {
1636 ContinuationEntry::set_enter_code(nm, interpreted_entry_offset);
1637 } else if (method->is_continuation_yield_intrinsic()) {
1638 _cont_doYield_stub = nm;
1639 } else {
1640 guarantee(false, "Unknown Continuation native intrinsic");
1641 }
1642 return nm;
1643 }
1644
1645 if (method->is_method_handle_intrinsic()) {
1646 vmIntrinsics::ID iid = method->intrinsic_id();
1647 intptr_t start = (intptr_t)__ pc();
1648 int vep_offset = ((intptr_t)__ pc()) - start;
1649
1650 // First instruction must be a nop as it may need to be patched on deoptimisation
1651 __ nop();
1652 gen_special_dispatch(masm,
1653 method,
1654 in_sig_bt,
1655 in_regs);
1656 int frame_complete = ((intptr_t)__ pc()) - start; // not complete, period
1657 __ flush();
1658 int stack_slots = SharedRuntime::out_preserve_stack_slots(); // no out slots at all, actually
1659 return nmethod::new_native_nmethod(method,
1660 compile_id,
1661 masm->code(),
1662 vep_offset,
1663 frame_complete,
1664 stack_slots / VMRegImpl::slots_per_word,
1665 in_ByteSize(-1),
1666 in_ByteSize(-1),
1667 nullptr);
1668 }
1669 address native_func = method->native_function();
1670 assert(native_func != nullptr, "must have function");
1671
1672 // An OopMap for lock (and class if static)
1673 OopMapSet *oop_maps = new OopMapSet();
1674 intptr_t start = (intptr_t)__ pc();
1675
1676 // We have received a description of where all the java arg are located
1677 // on entry to the wrapper. We need to convert these args to where
1678 // the jni function will expect them. To figure out where they go
1679 // we convert the java signature to a C signature by inserting
1680 // the hidden arguments as arg[0] and possibly arg[1] (static method)
1681
1682 const int total_in_args = method->size_of_parameters();
1683 int total_c_args = total_in_args + (method->is_static() ? 2 : 1);
1684
1685 BasicType* out_sig_bt = NEW_RESOURCE_ARRAY(BasicType, total_c_args);
1686 VMRegPair* out_regs = NEW_RESOURCE_ARRAY(VMRegPair, total_c_args);
1687
1688 int argc = 0;
1689 out_sig_bt[argc++] = T_ADDRESS;
1690 if (method->is_static()) {
1691 out_sig_bt[argc++] = T_OBJECT;
1692 }
1693
1694 for (int i = 0; i < total_in_args ; i++ ) {
1695 out_sig_bt[argc++] = in_sig_bt[i];
1696 }
1697
1698 // Now figure out where the args must be stored and how much stack space
1699 // they require.
1700 int out_arg_slots;
1701 out_arg_slots = c_calling_convention_priv(out_sig_bt, out_regs, total_c_args);
1702
1703 if (out_arg_slots < 0) {
1704 return nullptr;
1705 }
1706
1707 // Compute framesize for the wrapper. We need to handlize all oops in
1708 // incoming registers
1709
1710 // Calculate the total number of stack slots we will need.
1711
1712 // First count the abi requirement plus all of the outgoing args
1713 int stack_slots = SharedRuntime::out_preserve_stack_slots() + out_arg_slots;
1714
1715 // Now the space for the inbound oop handle area
1716 int total_save_slots = 8 * VMRegImpl::slots_per_word; // 8 arguments passed in registers
1717
1718 int oop_handle_offset = stack_slots;
1719 stack_slots += total_save_slots;
1720
1721 // Now any space we need for handlizing a klass if static method
1722
1723 int klass_slot_offset = 0;
1724 int klass_offset = -1;
1725 int lock_slot_offset = 0;
1726 bool is_static = false;
1727
1728 if (method->is_static()) {
1729 klass_slot_offset = stack_slots;
1730 stack_slots += VMRegImpl::slots_per_word;
1731 klass_offset = klass_slot_offset * VMRegImpl::stack_slot_size;
1732 is_static = true;
1733 }
1734
1735 // Plus a lock if needed
1736
1737 if (method->is_synchronized()) {
1738 lock_slot_offset = stack_slots;
1739 stack_slots += VMRegImpl::slots_per_word;
1740 }
1741
1742 // Now a place (+2) to save return values or temp during shuffling
1743 // + 4 for return address (which we own) and saved rfp
1744 stack_slots += 6;
1745
1746 // Ok The space we have allocated will look like:
1747 //
1748 //
1749 // FP-> | |
1750 // |---------------------|
1751 // | 2 slots for moves |
1752 // |---------------------|
1753 // | lock box (if sync) |
1754 // |---------------------| <- lock_slot_offset
1755 // | klass (if static) |
1756 // |---------------------| <- klass_slot_offset
1757 // | oopHandle area |
1758 // |---------------------| <- oop_handle_offset (8 java arg registers)
1759 // | outbound memory |
1760 // | based arguments |
1761 // | |
1762 // |---------------------|
1763 // | |
1764 // SP-> | out_preserved_slots |
1765 //
1766 //
1767
1768
1769 // Now compute actual number of stack words we need rounding to make
1770 // stack properly aligned.
1771 stack_slots = align_up(stack_slots, StackAlignmentInSlots);
1772
1773 int stack_size = stack_slots * VMRegImpl::stack_slot_size;
1774
1775 // First thing make an ic check to see if we should even be here
1776
1777 // We are free to use all registers as temps without saving them and
1778 // restoring them except rfp. rfp is the only callee save register
1779 // as far as the interpreter and the compiler(s) are concerned.
1780
1781 const Register receiver = j_rarg0;
1782
1783 Label exception_pending;
1784
1785 assert_different_registers(receiver, rscratch1);
1786 __ verify_oop(receiver);
1787 __ ic_check(8 /* end_alignment */);
1788
1789 // Verified entry point must be aligned
1790 int vep_offset = ((intptr_t)__ pc()) - start;
1791
1792 // If we have to make this method not-entrant we'll overwrite its
1793 // first instruction with a jump. For this action to be legal we
1794 // must ensure that this first instruction is a B, BL, NOP, BKPT,
1795 // SVC, HVC, or SMC. Make it a NOP.
1796 __ nop();
1797
1798 if (method->needs_clinit_barrier()) {
1799 assert(VM_Version::supports_fast_class_init_checks(), "sanity");
1800 Label L_skip_barrier;
1801 __ mov_metadata(rscratch2, method->method_holder()); // InstanceKlass*
1802 __ clinit_barrier(rscratch2, rscratch1, &L_skip_barrier);
1803 __ far_jump(RuntimeAddress(SharedRuntime::get_handle_wrong_method_stub()));
1804
1805 __ bind(L_skip_barrier);
1806 }
1807
1808 // Generate stack overflow check
1809 __ bang_stack_with_offset(checked_cast<int>(StackOverflow::stack_shadow_zone_size()));
1810
1811 // Generate a new frame for the wrapper.
1812 __ enter();
1813 // -2 because return address is already present and so is saved rfp
1814 __ sub(sp, sp, stack_size - 2*wordSize);
1815
1816 BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
1817 bs->nmethod_entry_barrier(masm, nullptr /* slow_path */, nullptr /* continuation */, nullptr /* guard */);
1818
1819 // Frame is now completed as far as size and linkage.
1820 int frame_complete = ((intptr_t)__ pc()) - start;
1821
1822 // We use r20 as the oop handle for the receiver/klass
1823 // It is callee save so it survives the call to native
1824
1825 const Register oop_handle_reg = r20;
1826
1827 //
1828 // We immediately shuffle the arguments so that any vm call we have to
1829 // make from here on out (sync slow path, jvmti, etc.) we will have
1830 // captured the oops from our caller and have a valid oopMap for
1831 // them.
1832
1833 // -----------------
1834 // The Grand Shuffle
1835
1836 // The Java calling convention is either equal (linux) or denser (win64) than the
1837 // c calling convention. However the because of the jni_env argument the c calling
1838 // convention always has at least one more (and two for static) arguments than Java.
1839 // Therefore if we move the args from java -> c backwards then we will never have
1840 // a register->register conflict and we don't have to build a dependency graph
1841 // and figure out how to break any cycles.
1842 //
1843
1844 // Record esp-based slot for receiver on stack for non-static methods
1845 int receiver_offset = -1;
1846
1847 // This is a trick. We double the stack slots so we can claim
1848 // the oops in the caller's frame. Since we are sure to have
1849 // more args than the caller doubling is enough to make
1850 // sure we can capture all the incoming oop args from the
1851 // caller.
1852 //
1853 OopMap* map = new OopMap(stack_slots * 2, 0 /* arg_slots*/);
1854
1855 // Mark location of rfp (someday)
1856 // map->set_callee_saved(VMRegImpl::stack2reg( stack_slots - 2), stack_slots * 2, 0, vmreg(rfp));
1857
1858
1859 int float_args = 0;
1860 int int_args = 0;
1861
1862 #ifdef ASSERT
1863 bool reg_destroyed[Register::number_of_registers];
1864 bool freg_destroyed[FloatRegister::number_of_registers];
1865 for ( int r = 0 ; r < Register::number_of_registers ; r++ ) {
1866 reg_destroyed[r] = false;
1867 }
1868 for ( int f = 0 ; f < FloatRegister::number_of_registers ; f++ ) {
1869 freg_destroyed[f] = false;
1870 }
1871
1872 #endif /* ASSERT */
1873
1874 // For JNI natives the incoming and outgoing registers are offset upwards.
1875 GrowableArray<int> arg_order(2 * total_in_args);
1876
1877 for (int i = total_in_args - 1, c_arg = total_c_args - 1; i >= 0; i--, c_arg--) {
1878 arg_order.push(i);
1879 arg_order.push(c_arg);
1880 }
1881
1882 for (int ai = 0; ai < arg_order.length(); ai += 2) {
1883 int i = arg_order.at(ai);
1884 int c_arg = arg_order.at(ai + 1);
1885 __ block_comment(err_msg("move %d -> %d", i, c_arg));
1886 assert(c_arg != -1 && i != -1, "wrong order");
1887 #ifdef ASSERT
1888 if (in_regs[i].first()->is_Register()) {
1889 assert(!reg_destroyed[in_regs[i].first()->as_Register()->encoding()], "destroyed reg!");
1890 } else if (in_regs[i].first()->is_FloatRegister()) {
1891 assert(!freg_destroyed[in_regs[i].first()->as_FloatRegister()->encoding()], "destroyed reg!");
1892 }
1893 if (out_regs[c_arg].first()->is_Register()) {
1894 reg_destroyed[out_regs[c_arg].first()->as_Register()->encoding()] = true;
1895 } else if (out_regs[c_arg].first()->is_FloatRegister()) {
1896 freg_destroyed[out_regs[c_arg].first()->as_FloatRegister()->encoding()] = true;
1897 }
1898 #endif /* ASSERT */
1899 switch (in_sig_bt[i]) {
1900 case T_ARRAY:
1901 case T_OBJECT:
1902 __ object_move(map, oop_handle_offset, stack_slots, in_regs[i], out_regs[c_arg],
1903 ((i == 0) && (!is_static)),
1904 &receiver_offset);
1905 int_args++;
1906 break;
1907 case T_VOID:
1908 break;
1909
1910 case T_FLOAT:
1911 __ float_move(in_regs[i], out_regs[c_arg]);
1912 float_args++;
1913 break;
1914
1915 case T_DOUBLE:
1916 assert( i + 1 < total_in_args &&
1917 in_sig_bt[i + 1] == T_VOID &&
1918 out_sig_bt[c_arg+1] == T_VOID, "bad arg list");
1919 __ double_move(in_regs[i], out_regs[c_arg]);
1920 float_args++;
1921 break;
1922
1923 case T_LONG :
1924 __ long_move(in_regs[i], out_regs[c_arg]);
1925 int_args++;
1926 break;
1927
1928 case T_ADDRESS: assert(false, "found T_ADDRESS in java args");
1929
1930 default:
1931 __ move32_64(in_regs[i], out_regs[c_arg]);
1932 int_args++;
1933 }
1934 }
1935
1936 // point c_arg at the first arg that is already loaded in case we
1937 // need to spill before we call out
1938 int c_arg = total_c_args - total_in_args;
1939
1940 // Pre-load a static method's oop into c_rarg1.
1941 if (method->is_static()) {
1942
1943 // load oop into a register
1944 __ movoop(c_rarg1,
1945 JNIHandles::make_local(method->method_holder()->java_mirror()));
1946
1947 // Now handlize the static class mirror it's known not-null.
1948 __ str(c_rarg1, Address(sp, klass_offset));
1949 map->set_oop(VMRegImpl::stack2reg(klass_slot_offset));
1950
1951 // Now get the handle
1952 __ lea(c_rarg1, Address(sp, klass_offset));
1953 // and protect the arg if we must spill
1954 c_arg--;
1955 }
1956
1957 // Change state to native (we save the return address in the thread, since it might not
1958 // be pushed on the stack when we do a stack traversal). It is enough that the pc()
1959 // points into the right code segment. It does not have to be the correct return pc.
1960 // We use the same pc/oopMap repeatedly when we call out.
1961
1962 Label native_return;
1963 if (method->is_object_wait0()) {
1964 // For convenience we use the pc we want to resume to in case of preemption on Object.wait.
1965 __ set_last_Java_frame(sp, noreg, native_return, rscratch1);
1966 } else {
1967 intptr_t the_pc = (intptr_t) __ pc();
1968 oop_maps->add_gc_map(the_pc - start, map);
1969
1970 __ set_last_Java_frame(sp, noreg, __ pc(), rscratch1);
1971 }
1972
1973 Label dtrace_method_entry, dtrace_method_entry_done;
1974 if (DTraceMethodProbes) {
1975 __ b(dtrace_method_entry);
1976 __ bind(dtrace_method_entry_done);
1977 }
1978
1979 // RedefineClasses() tracing support for obsolete method entry
1980 if (log_is_enabled(Trace, redefine, class, obsolete)) {
1981 // protect the args we've loaded
1982 save_args(masm, total_c_args, c_arg, out_regs);
1983 __ mov_metadata(c_rarg1, method());
1984 __ call_VM_leaf(
1985 CAST_FROM_FN_PTR(address, SharedRuntime::rc_trace_method_entry),
1986 rthread, c_rarg1);
1987 restore_args(masm, total_c_args, c_arg, out_regs);
1988 }
1989
1990 // Lock a synchronized method
1991
1992 // Register definitions used by locking and unlocking
1993
1994 const Register swap_reg = r0;
1995 const Register obj_reg = r19; // Will contain the oop
1996 const Register lock_reg = r13; // Address of compiler lock object (BasicLock)
1997 const Register old_hdr = r13; // value of old header at unlock time
1998 const Register lock_tmp = r14; // Temporary used by fast_lock/unlock
1999 const Register tmp = lr;
2000
2001 Label slow_path_lock;
2002 Label lock_done;
2003
2004 if (method->is_synchronized()) {
2005 // Get the handle (the 2nd argument)
2006 __ mov(oop_handle_reg, c_rarg1);
2007
2008 // Get address of the box
2009
2010 __ lea(lock_reg, Address(sp, lock_slot_offset * VMRegImpl::stack_slot_size));
2011
2012 // Load the oop from the handle
2013 __ ldr(obj_reg, Address(oop_handle_reg, 0));
2014
2015 __ fast_lock(lock_reg, obj_reg, swap_reg, tmp, lock_tmp, slow_path_lock);
2016
2017 // Slow path will re-enter here
2018 __ bind(lock_done);
2019 }
2020
2021
2022 // Finally just about ready to make the JNI call
2023
2024 // get JNIEnv* which is first argument to native
2025 __ lea(c_rarg0, Address(rthread, in_bytes(JavaThread::jni_environment_offset())));
2026
2027 // Now set thread in native
2028 __ mov(rscratch1, _thread_in_native);
2029 __ lea(rscratch2, Address(rthread, JavaThread::thread_state_offset()));
2030 __ stlrw(rscratch1, rscratch2);
2031
2032 __ rt_call(native_func);
2033
2034 // Verify or restore cpu control state after JNI call
2035 __ restore_cpu_control_state_after_jni(rscratch1, rscratch2);
2036
2037 // Unpack native results.
2038 switch (ret_type) {
2039 case T_BOOLEAN: __ c2bool(r0); break;
2040 case T_CHAR : __ ubfx(r0, r0, 0, 16); break;
2041 case T_BYTE : __ sbfx(r0, r0, 0, 8); break;
2042 case T_SHORT : __ sbfx(r0, r0, 0, 16); break;
2043 case T_INT : __ sbfx(r0, r0, 0, 32); break;
2044 case T_DOUBLE :
2045 case T_FLOAT :
2046 // Result is in v0 we'll save as needed
2047 break;
2048 case T_ARRAY: // Really a handle
2049 case T_OBJECT: // Really a handle
2050 break; // can't de-handlize until after safepoint check
2051 case T_VOID: break;
2052 case T_LONG: break;
2053 default : ShouldNotReachHere();
2054 }
2055
2056 Label safepoint_in_progress, safepoint_in_progress_done;
2057
2058 // Switch thread to "native transition" state before reading the synchronization state.
2059 // This additional state is necessary because reading and testing the synchronization
2060 // state is not atomic w.r.t. GC, as this scenario demonstrates:
2061 // Java thread A, in _thread_in_native state, loads _not_synchronized and is preempted.
2062 // VM thread changes sync state to synchronizing and suspends threads for GC.
2063 // Thread A is resumed to finish this native method, but doesn't block here since it
2064 // didn't see any synchronization is progress, and escapes.
2065 __ mov(rscratch1, _thread_in_native_trans);
2066
2067 __ strw(rscratch1, Address(rthread, JavaThread::thread_state_offset()));
2068
2069 // Force this write out before the read below
2070 if (!UseSystemMemoryBarrier) {
2071 __ dmb(Assembler::ISH);
2072 }
2073
2074 __ verify_sve_vector_length();
2075
2076 // Check for safepoint operation in progress and/or pending suspend requests.
2077 {
2078 // No need for acquire as Java threads always disarm themselves.
2079 __ safepoint_poll(safepoint_in_progress, true /* at_return */, false /* in_nmethod */);
2080 __ ldrw(rscratch1, Address(rthread, JavaThread::suspend_flags_offset()));
2081 __ cbnzw(rscratch1, safepoint_in_progress);
2082 __ bind(safepoint_in_progress_done);
2083 }
2084
2085 // change thread state
2086 __ mov(rscratch1, _thread_in_Java);
2087 __ lea(rscratch2, Address(rthread, JavaThread::thread_state_offset()));
2088 __ stlrw(rscratch1, rscratch2);
2089
2090 if (method->is_object_wait0()) {
2091 // Check preemption for Object.wait()
2092 __ ldr(rscratch1, Address(rthread, JavaThread::preempt_alternate_return_offset()));
2093 __ cbz(rscratch1, native_return);
2094 __ str(zr, Address(rthread, JavaThread::preempt_alternate_return_offset()));
2095 __ br(rscratch1);
2096 __ bind(native_return);
2097
2098 intptr_t the_pc = (intptr_t) __ pc();
2099 oop_maps->add_gc_map(the_pc - start, map);
2100 }
2101
2102 Label reguard;
2103 Label reguard_done;
2104 __ ldrb(rscratch1, Address(rthread, JavaThread::stack_guard_state_offset()));
2105 __ cmpw(rscratch1, StackOverflow::stack_guard_yellow_reserved_disabled);
2106 __ br(Assembler::EQ, reguard);
2107 __ bind(reguard_done);
2108
2109 // native result if any is live
2110
2111 // Unlock
2112 Label unlock_done;
2113 Label slow_path_unlock;
2114 if (method->is_synchronized()) {
2115
2116 // Get locked oop from the handle we passed to jni
2117 __ ldr(obj_reg, Address(oop_handle_reg, 0));
2118
2119 // Must save r0 if if it is live now because cmpxchg must use it
2120 if (ret_type != T_FLOAT && ret_type != T_DOUBLE && ret_type != T_VOID) {
2121 save_native_result(masm, ret_type, stack_slots);
2122 }
2123
2124 __ fast_unlock(obj_reg, old_hdr, swap_reg, lock_tmp, slow_path_unlock);
2125
2126 // slow path re-enters here
2127 __ bind(unlock_done);
2128 if (ret_type != T_FLOAT && ret_type != T_DOUBLE && ret_type != T_VOID) {
2129 restore_native_result(masm, ret_type, stack_slots);
2130 }
2131 }
2132
2133 Label dtrace_method_exit, dtrace_method_exit_done;
2134 if (DTraceMethodProbes) {
2135 __ b(dtrace_method_exit);
2136 __ bind(dtrace_method_exit_done);
2137 }
2138
2139 __ reset_last_Java_frame(false);
2140
2141 // Unbox oop result, e.g. JNIHandles::resolve result.
2142 if (is_reference_type(ret_type)) {
2143 __ resolve_jobject(r0, r1, r2);
2144 }
2145
2146 if (CheckJNICalls) {
2147 // clear_pending_jni_exception_check
2148 __ str(zr, Address(rthread, JavaThread::pending_jni_exception_check_fn_offset()));
2149 }
2150
2151 // reset handle block
2152 __ ldr(r2, Address(rthread, JavaThread::active_handles_offset()));
2153 __ str(zr, Address(r2, JNIHandleBlock::top_offset()));
2154
2155 __ leave();
2156
2157 #if INCLUDE_JFR
2158 // We need to do a poll test after unwind in case the sampler
2159 // managed to sample the native frame after returning to Java.
2160 Label L_return;
2161 __ ldr(rscratch1, Address(rthread, JavaThread::polling_word_offset()));
2162 address poll_test_pc = __ pc();
2163 __ relocate(relocInfo::poll_return_type);
2164 __ tbz(rscratch1, log2i_exact(SafepointMechanism::poll_bit()), L_return);
2165 assert(SharedRuntime::polling_page_return_handler_blob() != nullptr,
2166 "polling page return stub not created yet");
2167 address stub = SharedRuntime::polling_page_return_handler_blob()->entry_point();
2168 __ adr(rscratch1, InternalAddress(poll_test_pc));
2169 __ str(rscratch1, Address(rthread, JavaThread::saved_exception_pc_offset()));
2170 __ far_jump(RuntimeAddress(stub));
2171 __ bind(L_return);
2172 #endif // INCLUDE_JFR
2173
2174 // Any exception pending?
2175 __ ldr(rscratch1, Address(rthread, in_bytes(Thread::pending_exception_offset())));
2176 __ cbnz(rscratch1, exception_pending);
2177
2178 // We're done
2179 __ ret(lr);
2180
2181 // Unexpected paths are out of line and go here
2182
2183 // forward the exception
2184 __ bind(exception_pending);
2185
2186 // and forward the exception
2187 __ far_jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
2188
2189 // Slow path locking & unlocking
2190 if (method->is_synchronized()) {
2191
2192 __ block_comment("Slow path lock {");
2193 __ bind(slow_path_lock);
2194
2195 // has last_Java_frame setup. No exceptions so do vanilla call not call_VM
2196 // args are (oop obj, BasicLock* lock, JavaThread* thread)
2197
2198 // protect the args we've loaded
2199 save_args(masm, total_c_args, c_arg, out_regs);
2200
2201 __ mov(c_rarg0, obj_reg);
2202 __ mov(c_rarg1, lock_reg);
2203 __ mov(c_rarg2, rthread);
2204
2205 // Not a leaf but we have last_Java_frame setup as we want.
2206 // We don't want to unmount in case of contention since that would complicate preserving
2207 // the arguments that had already been marshalled into the native convention. So we force
2208 // the freeze slow path to find this native wrapper frame (see recurse_freeze_native_frame())
2209 // and pin the vthread. Otherwise the fast path won't find it since we don't walk the stack.
2210 __ push_cont_fastpath();
2211 __ call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::complete_monitor_locking_C), 3);
2212 __ pop_cont_fastpath();
2213 restore_args(masm, total_c_args, c_arg, out_regs);
2214
2215 #ifdef ASSERT
2216 { Label L;
2217 __ ldr(rscratch1, Address(rthread, in_bytes(Thread::pending_exception_offset())));
2218 __ cbz(rscratch1, L);
2219 __ stop("no pending exception allowed on exit from monitorenter");
2220 __ bind(L);
2221 }
2222 #endif
2223 __ b(lock_done);
2224
2225 __ block_comment("} Slow path lock");
2226
2227 __ block_comment("Slow path unlock {");
2228 __ bind(slow_path_unlock);
2229
2230 // If we haven't already saved the native result we must save it now as xmm registers
2231 // are still exposed.
2232
2233 if (ret_type == T_FLOAT || ret_type == T_DOUBLE ) {
2234 save_native_result(masm, ret_type, stack_slots);
2235 }
2236
2237 __ mov(c_rarg2, rthread);
2238 __ lea(c_rarg1, Address(sp, lock_slot_offset * VMRegImpl::stack_slot_size));
2239 __ mov(c_rarg0, obj_reg);
2240
2241 // Save pending exception around call to VM (which contains an EXCEPTION_MARK)
2242 // NOTE that obj_reg == r19 currently
2243 __ ldr(r19, Address(rthread, in_bytes(Thread::pending_exception_offset())));
2244 __ str(zr, Address(rthread, in_bytes(Thread::pending_exception_offset())));
2245
2246 __ rt_call(CAST_FROM_FN_PTR(address, SharedRuntime::complete_monitor_unlocking_C));
2247
2248 #ifdef ASSERT
2249 {
2250 Label L;
2251 __ ldr(rscratch1, Address(rthread, in_bytes(Thread::pending_exception_offset())));
2252 __ cbz(rscratch1, L);
2253 __ stop("no pending exception allowed on exit complete_monitor_unlocking_C");
2254 __ bind(L);
2255 }
2256 #endif /* ASSERT */
2257
2258 __ str(r19, Address(rthread, in_bytes(Thread::pending_exception_offset())));
2259
2260 if (ret_type == T_FLOAT || ret_type == T_DOUBLE ) {
2261 restore_native_result(masm, ret_type, stack_slots);
2262 }
2263 __ b(unlock_done);
2264
2265 __ block_comment("} Slow path unlock");
2266
2267 } // synchronized
2268
2269 // SLOW PATH Reguard the stack if needed
2270
2271 __ bind(reguard);
2272 save_native_result(masm, ret_type, stack_slots);
2273 __ rt_call(CAST_FROM_FN_PTR(address, SharedRuntime::reguard_yellow_pages));
2274 restore_native_result(masm, ret_type, stack_slots);
2275 // and continue
2276 __ b(reguard_done);
2277
2278 // SLOW PATH safepoint
2279 {
2280 __ block_comment("safepoint {");
2281 __ bind(safepoint_in_progress);
2282
2283 // Don't use call_VM as it will see a possible pending exception and forward it
2284 // and never return here preventing us from clearing _last_native_pc down below.
2285 //
2286 save_native_result(masm, ret_type, stack_slots);
2287 __ mov(c_rarg0, rthread);
2288 #ifndef PRODUCT
2289 assert(frame::arg_reg_save_area_bytes == 0, "not expecting frame reg save area");
2290 #endif
2291 __ lea(rscratch1, RuntimeAddress(CAST_FROM_FN_PTR(address, JavaThread::check_special_condition_for_native_trans)));
2292 __ blr(rscratch1);
2293
2294 // Restore any method result value
2295 restore_native_result(masm, ret_type, stack_slots);
2296
2297 __ b(safepoint_in_progress_done);
2298 __ block_comment("} safepoint");
2299 }
2300
2301 // SLOW PATH dtrace support
2302 if (DTraceMethodProbes) {
2303 {
2304 __ block_comment("dtrace entry {");
2305 __ bind(dtrace_method_entry);
2306
2307 // We have all of the arguments setup at this point. We must not touch any register
2308 // argument registers at this point (what if we save/restore them there are no oop?
2309
2310 save_args(masm, total_c_args, c_arg, out_regs);
2311 __ mov_metadata(c_rarg1, method());
2312 __ call_VM_leaf(
2313 CAST_FROM_FN_PTR(address, SharedRuntime::dtrace_method_entry),
2314 rthread, c_rarg1);
2315 restore_args(masm, total_c_args, c_arg, out_regs);
2316 __ b(dtrace_method_entry_done);
2317 __ block_comment("} dtrace entry");
2318 }
2319
2320 {
2321 __ block_comment("dtrace exit {");
2322 __ bind(dtrace_method_exit);
2323 save_native_result(masm, ret_type, stack_slots);
2324 __ mov_metadata(c_rarg1, method());
2325 __ call_VM_leaf(
2326 CAST_FROM_FN_PTR(address, SharedRuntime::dtrace_method_exit),
2327 rthread, c_rarg1);
2328 restore_native_result(masm, ret_type, stack_slots);
2329 __ b(dtrace_method_exit_done);
2330 __ block_comment("} dtrace exit");
2331 }
2332 }
2333
2334 __ flush();
2335
2336 nmethod *nm = nmethod::new_native_nmethod(method,
2337 compile_id,
2338 masm->code(),
2339 vep_offset,
2340 frame_complete,
2341 stack_slots / VMRegImpl::slots_per_word,
2342 (is_static ? in_ByteSize(klass_offset) : in_ByteSize(receiver_offset)),
2343 in_ByteSize(lock_slot_offset*VMRegImpl::stack_slot_size),
2344 oop_maps);
2345
2346 return nm;
2347 }
2348
2349 // this function returns the adjust size (in number of words) to a c2i adapter
2350 // activation for use during deoptimization
2351 int Deoptimization::last_frame_adjust(int callee_parameters, int callee_locals) {
2352 assert(callee_locals >= callee_parameters,
2353 "test and remove; got more parms than locals");
2354 if (callee_locals < callee_parameters)
2355 return 0; // No adjustment for negative locals
2356 int diff = (callee_locals - callee_parameters) * Interpreter::stackElementWords;
2357 // diff is counted in stack words
2358 return align_up(diff, 2);
2359 }
2360
2361
2362 //------------------------------generate_deopt_blob----------------------------
2363 void SharedRuntime::generate_deopt_blob() {
2364 // Allocate space for the code
2365 ResourceMark rm;
2366 // Setup code generation tools
2367 int pad = 0;
2368 #if INCLUDE_JVMCI
2369 if (EnableJVMCI) {
2370 pad += 512; // Increase the buffer size when compiling for JVMCI
2371 }
2372 #endif
2373 const char* name = SharedRuntime::stub_name(StubId::shared_deopt_id);
2374 CodeBlob* blob = AOTCodeCache::load_code_blob(AOTCodeEntry::SharedBlob, BlobId::shared_deopt_id);
2375 if (blob != nullptr) {
2376 _deopt_blob = blob->as_deoptimization_blob();
2377 return;
2378 }
2379
2380 CodeBuffer buffer(name, 2048+pad, 1024);
2381 MacroAssembler* masm = new MacroAssembler(&buffer);
2382 int frame_size_in_words;
2383 OopMap* map = nullptr;
2384 OopMapSet *oop_maps = new OopMapSet();
2385 RegisterSaver reg_save(COMPILER2_OR_JVMCI != 0);
2386
2387 // -------------
2388 // This code enters when returning to a de-optimized nmethod. A return
2389 // address has been pushed on the stack, and return values are in
2390 // registers.
2391 // If we are doing a normal deopt then we were called from the patched
2392 // nmethod from the point we returned to the nmethod. So the return
2393 // address on the stack is wrong by NativeCall::instruction_size
2394 // We will adjust the value so it looks like we have the original return
2395 // address on the stack (like when we eagerly deoptimized).
2396 // In the case of an exception pending when deoptimizing, we enter
2397 // with a return address on the stack that points after the call we patched
2398 // into the exception handler. We have the following register state from,
2399 // e.g., the forward exception stub (see stubGenerator_x86_64.cpp).
2400 // r0: exception oop
2401 // r19: exception handler
2402 // r3: throwing pc
2403 // So in this case we simply jam r3 into the useless return address and
2404 // the stack looks just like we want.
2405 //
2406 // At this point we need to de-opt. We save the argument return
2407 // registers. We call the first C routine, fetch_unroll_info(). This
2408 // routine captures the return values and returns a structure which
2409 // describes the current frame size and the sizes of all replacement frames.
2410 // The current frame is compiled code and may contain many inlined
2411 // functions, each with their own JVM state. We pop the current frame, then
2412 // push all the new frames. Then we call the C routine unpack_frames() to
2413 // populate these frames. Finally unpack_frames() returns us the new target
2414 // address. Notice that callee-save registers are BLOWN here; they have
2415 // already been captured in the vframeArray at the time the return PC was
2416 // patched.
2417 address start = __ pc();
2418 Label cont;
2419
2420 // Prolog for non exception case!
2421
2422 // Save everything in sight.
2423 map = reg_save.save_live_registers(masm, 0, &frame_size_in_words);
2424
2425 // Normal deoptimization. Save exec mode for unpack_frames.
2426 __ movw(rcpool, Deoptimization::Unpack_deopt); // callee-saved
2427 __ b(cont);
2428
2429 int reexecute_offset = __ pc() - start;
2430 #if INCLUDE_JVMCI && !defined(COMPILER1)
2431 if (UseJVMCICompiler) {
2432 // JVMCI does not use this kind of deoptimization
2433 __ should_not_reach_here();
2434 }
2435 #endif
2436
2437 // Reexecute case
2438 // return address is the pc describes what bci to do re-execute at
2439
2440 // No need to update map as each call to save_live_registers will produce identical oopmap
2441 (void) reg_save.save_live_registers(masm, 0, &frame_size_in_words);
2442
2443 __ movw(rcpool, Deoptimization::Unpack_reexecute); // callee-saved
2444 __ b(cont);
2445
2446 #if INCLUDE_JVMCI
2447 Label after_fetch_unroll_info_call;
2448 int implicit_exception_uncommon_trap_offset = 0;
2449 int uncommon_trap_offset = 0;
2450
2451 if (EnableJVMCI) {
2452 implicit_exception_uncommon_trap_offset = __ pc() - start;
2453
2454 __ ldr(lr, Address(rthread, in_bytes(JavaThread::jvmci_implicit_exception_pc_offset())));
2455 __ str(zr, Address(rthread, in_bytes(JavaThread::jvmci_implicit_exception_pc_offset())));
2456
2457 uncommon_trap_offset = __ pc() - start;
2458
2459 // Save everything in sight.
2460 reg_save.save_live_registers(masm, 0, &frame_size_in_words);
2461 // fetch_unroll_info needs to call last_java_frame()
2462 Label retaddr;
2463 __ set_last_Java_frame(sp, noreg, retaddr, rscratch1);
2464
2465 __ ldrw(c_rarg1, Address(rthread, in_bytes(JavaThread::pending_deoptimization_offset())));
2466 __ movw(rscratch1, -1);
2467 __ strw(rscratch1, Address(rthread, in_bytes(JavaThread::pending_deoptimization_offset())));
2468
2469 __ movw(rcpool, (int32_t)Deoptimization::Unpack_reexecute);
2470 __ mov(c_rarg0, rthread);
2471 __ movw(c_rarg2, rcpool); // exec mode
2472 __ lea(rscratch1,
2473 RuntimeAddress(CAST_FROM_FN_PTR(address,
2474 Deoptimization::uncommon_trap)));
2475 __ blr(rscratch1);
2476 __ bind(retaddr);
2477 oop_maps->add_gc_map( __ pc()-start, map->deep_copy());
2478
2479 __ reset_last_Java_frame(false);
2480
2481 __ b(after_fetch_unroll_info_call);
2482 } // EnableJVMCI
2483 #endif // INCLUDE_JVMCI
2484
2485 int exception_offset = __ pc() - start;
2486
2487 // Prolog for exception case
2488
2489 // all registers are dead at this entry point, except for r0, and
2490 // r3 which contain the exception oop and exception pc
2491 // respectively. Set them in TLS and fall thru to the
2492 // unpack_with_exception_in_tls entry point.
2493
2494 __ str(r3, Address(rthread, JavaThread::exception_pc_offset()));
2495 __ str(r0, Address(rthread, JavaThread::exception_oop_offset()));
2496
2497 int exception_in_tls_offset = __ pc() - start;
2498
2499 // new implementation because exception oop is now passed in JavaThread
2500
2501 // Prolog for exception case
2502 // All registers must be preserved because they might be used by LinearScan
2503 // Exceptiop oop and throwing PC are passed in JavaThread
2504 // tos: stack at point of call to method that threw the exception (i.e. only
2505 // args are on the stack, no return address)
2506
2507 // The return address pushed by save_live_registers will be patched
2508 // later with the throwing pc. The correct value is not available
2509 // now because loading it from memory would destroy registers.
2510
2511 // NB: The SP at this point must be the SP of the method that is
2512 // being deoptimized. Deoptimization assumes that the frame created
2513 // here by save_live_registers is immediately below the method's SP.
2514 // This is a somewhat fragile mechanism.
2515
2516 // Save everything in sight.
2517 map = reg_save.save_live_registers(masm, 0, &frame_size_in_words);
2518
2519 // Now it is safe to overwrite any register
2520
2521 // Deopt during an exception. Save exec mode for unpack_frames.
2522 __ mov(rcpool, Deoptimization::Unpack_exception); // callee-saved
2523
2524 // load throwing pc from JavaThread and patch it as the return address
2525 // of the current frame. Then clear the field in JavaThread
2526 __ ldr(r3, Address(rthread, JavaThread::exception_pc_offset()));
2527 __ protect_return_address(r3);
2528 __ str(r3, Address(rfp, wordSize));
2529 __ str(zr, Address(rthread, JavaThread::exception_pc_offset()));
2530
2531 #ifdef ASSERT
2532 // verify that there is really an exception oop in JavaThread
2533 __ ldr(r0, Address(rthread, JavaThread::exception_oop_offset()));
2534 __ verify_oop(r0);
2535
2536 // verify that there is no pending exception
2537 Label no_pending_exception;
2538 __ ldr(rscratch1, Address(rthread, Thread::pending_exception_offset()));
2539 __ cbz(rscratch1, no_pending_exception);
2540 __ stop("must not have pending exception here");
2541 __ bind(no_pending_exception);
2542 #endif
2543
2544 __ bind(cont);
2545
2546 // Call C code. Need thread and this frame, but NOT official VM entry
2547 // crud. We cannot block on this call, no GC can happen.
2548 //
2549 // UnrollBlock* fetch_unroll_info(JavaThread* thread)
2550
2551 // fetch_unroll_info needs to call last_java_frame().
2552
2553 Label retaddr;
2554 __ set_last_Java_frame(sp, noreg, retaddr, rscratch1);
2555 #ifdef ASSERT
2556 { Label L;
2557 __ ldr(rscratch1, Address(rthread, JavaThread::last_Java_fp_offset()));
2558 __ cbz(rscratch1, L);
2559 __ stop("SharedRuntime::generate_deopt_blob: last_Java_fp not cleared");
2560 __ bind(L);
2561 }
2562 #endif // ASSERT
2563 __ mov(c_rarg0, rthread);
2564 __ mov(c_rarg1, rcpool);
2565 __ lea(rscratch1, RuntimeAddress(CAST_FROM_FN_PTR(address, Deoptimization::fetch_unroll_info)));
2566 __ blr(rscratch1);
2567 __ bind(retaddr);
2568
2569 // Need to have an oopmap that tells fetch_unroll_info where to
2570 // find any register it might need.
2571 oop_maps->add_gc_map(__ pc() - start, map);
2572
2573 __ reset_last_Java_frame(false);
2574
2575 #if INCLUDE_JVMCI
2576 if (EnableJVMCI) {
2577 __ bind(after_fetch_unroll_info_call);
2578 }
2579 #endif
2580
2581 // Load UnrollBlock* into r5
2582 __ mov(r5, r0);
2583
2584 __ ldrw(rcpool, Address(r5, Deoptimization::UnrollBlock::unpack_kind_offset()));
2585 Label noException;
2586 __ cmpw(rcpool, Deoptimization::Unpack_exception); // Was exception pending?
2587 __ br(Assembler::NE, noException);
2588 __ ldr(r0, Address(rthread, JavaThread::exception_oop_offset()));
2589 // QQQ this is useless it was null above
2590 __ ldr(r3, Address(rthread, JavaThread::exception_pc_offset()));
2591 __ str(zr, Address(rthread, JavaThread::exception_oop_offset()));
2592 __ str(zr, Address(rthread, JavaThread::exception_pc_offset()));
2593
2594 __ verify_oop(r0);
2595
2596 // Overwrite the result registers with the exception results.
2597 __ str(r0, Address(sp, reg_save.r0_offset_in_bytes()));
2598 // I think this is useless
2599 // __ str(r3, Address(sp, RegisterSaver::r3_offset_in_bytes()));
2600
2601 __ bind(noException);
2602
2603 // Only register save data is on the stack.
2604 // Now restore the result registers. Everything else is either dead
2605 // or captured in the vframeArray.
2606
2607 // Restore fp result register
2608 __ ldrd(v0, Address(sp, reg_save.v0_offset_in_bytes()));
2609 // Restore integer result register
2610 __ ldr(r0, Address(sp, reg_save.r0_offset_in_bytes()));
2611
2612 // Pop all of the register save area off the stack
2613 __ add(sp, sp, frame_size_in_words * wordSize);
2614
2615 // All of the register save area has been popped of the stack. Only the
2616 // return address remains.
2617
2618 // Pop all the frames we must move/replace.
2619 //
2620 // Frame picture (youngest to oldest)
2621 // 1: self-frame (no frame link)
2622 // 2: deopting frame (no frame link)
2623 // 3: caller of deopting frame (could be compiled/interpreted).
2624 //
2625 // Note: by leaving the return address of self-frame on the stack
2626 // and using the size of frame 2 to adjust the stack
2627 // when we are done the return to frame 3 will still be on the stack.
2628
2629 // Pop deoptimized frame
2630 __ ldrw(r2, Address(r5, Deoptimization::UnrollBlock::size_of_deoptimized_frame_offset()));
2631 __ sub(r2, r2, 2 * wordSize);
2632 __ add(sp, sp, r2);
2633 __ ldp(rfp, zr, __ post(sp, 2 * wordSize));
2634
2635 #ifdef ASSERT
2636 // Compilers generate code that bang the stack by as much as the
2637 // interpreter would need. So this stack banging should never
2638 // trigger a fault. Verify that it does not on non product builds.
2639 __ ldrw(r19, Address(r5, Deoptimization::UnrollBlock::total_frame_sizes_offset()));
2640 __ bang_stack_size(r19, r2);
2641 #endif
2642 // Load address of array of frame pcs into r2
2643 __ ldr(r2, Address(r5, Deoptimization::UnrollBlock::frame_pcs_offset()));
2644
2645 // Trash the old pc
2646 // __ addptr(sp, wordSize); FIXME ????
2647
2648 // Load address of array of frame sizes into r4
2649 __ ldr(r4, Address(r5, Deoptimization::UnrollBlock::frame_sizes_offset()));
2650
2651 // Load counter into r3
2652 __ ldrw(r3, Address(r5, Deoptimization::UnrollBlock::number_of_frames_offset()));
2653
2654 // Now adjust the caller's stack to make up for the extra locals
2655 // but record the original sp so that we can save it in the skeletal interpreter
2656 // frame and the stack walking of interpreter_sender will get the unextended sp
2657 // value and not the "real" sp value.
2658
2659 const Register sender_sp = r6;
2660
2661 __ mov(sender_sp, sp);
2662 __ ldrw(r19, Address(r5,
2663 Deoptimization::UnrollBlock::
2664 caller_adjustment_offset()));
2665 __ sub(sp, sp, r19);
2666
2667 // Push interpreter frames in a loop
2668 __ mov(rscratch1, (uint64_t)0xDEADDEAD); // Make a recognizable pattern
2669 __ mov(rscratch2, rscratch1);
2670 Label loop;
2671 __ bind(loop);
2672 __ ldr(r19, Address(__ post(r4, wordSize))); // Load frame size
2673 __ sub(r19, r19, 2*wordSize); // We'll push pc and fp by hand
2674 __ ldr(lr, Address(__ post(r2, wordSize))); // Load pc
2675 __ enter(); // Save old & set new fp
2676 __ sub(sp, sp, r19); // Prolog
2677 // This value is corrected by layout_activation_impl
2678 __ str(zr, Address(rfp, frame::interpreter_frame_last_sp_offset * wordSize));
2679 __ str(sender_sp, Address(rfp, frame::interpreter_frame_sender_sp_offset * wordSize)); // Make it walkable
2680 __ mov(sender_sp, sp); // Pass sender_sp to next frame
2681 __ sub(r3, r3, 1); // Decrement counter
2682 __ cbnz(r3, loop);
2683
2684 // Re-push self-frame
2685 __ ldr(lr, Address(r2));
2686 __ enter();
2687
2688 // Allocate a full sized register save area. We subtract 2 because
2689 // enter() just pushed 2 words
2690 __ sub(sp, sp, (frame_size_in_words - 2) * wordSize);
2691
2692 // Restore frame locals after moving the frame
2693 __ strd(v0, Address(sp, reg_save.v0_offset_in_bytes()));
2694 __ str(r0, Address(sp, reg_save.r0_offset_in_bytes()));
2695
2696 // Call C code. Need thread but NOT official VM entry
2697 // crud. We cannot block on this call, no GC can happen. Call should
2698 // restore return values to their stack-slots with the new SP.
2699 //
2700 // void Deoptimization::unpack_frames(JavaThread* thread, int exec_mode)
2701
2702 // Use rfp because the frames look interpreted now
2703 // Don't need the precise return PC here, just precise enough to point into this code blob.
2704 address the_pc = __ pc();
2705 __ set_last_Java_frame(sp, rfp, the_pc, rscratch1);
2706
2707 __ mov(c_rarg0, rthread);
2708 __ movw(c_rarg1, rcpool); // second arg: exec_mode
2709 __ lea(rscratch1, RuntimeAddress(CAST_FROM_FN_PTR(address, Deoptimization::unpack_frames)));
2710 __ blr(rscratch1);
2711
2712 // Set an oopmap for the call site
2713 // Use the same PC we used for the last java frame
2714 oop_maps->add_gc_map(the_pc - start,
2715 new OopMap( frame_size_in_words, 0 ));
2716
2717 // Clear fp AND pc
2718 __ reset_last_Java_frame(true);
2719
2720 // Collect return values
2721 __ ldrd(v0, Address(sp, reg_save.v0_offset_in_bytes()));
2722 __ ldr(r0, Address(sp, reg_save.r0_offset_in_bytes()));
2723 // I think this is useless (throwing pc?)
2724 // __ ldr(r3, Address(sp, RegisterSaver::r3_offset_in_bytes()));
2725
2726 // Pop self-frame.
2727 __ leave(); // Epilog
2728
2729 // Jump to interpreter
2730 __ ret(lr);
2731
2732 // Make sure all code is generated
2733 masm->flush();
2734
2735 _deopt_blob = DeoptimizationBlob::create(&buffer, oop_maps, 0, exception_offset, reexecute_offset, frame_size_in_words);
2736 _deopt_blob->set_unpack_with_exception_in_tls_offset(exception_in_tls_offset);
2737 #if INCLUDE_JVMCI
2738 if (EnableJVMCI) {
2739 _deopt_blob->set_uncommon_trap_offset(uncommon_trap_offset);
2740 _deopt_blob->set_implicit_exception_uncommon_trap_offset(implicit_exception_uncommon_trap_offset);
2741 }
2742 #endif
2743
2744 AOTCodeCache::store_code_blob(*_deopt_blob, AOTCodeEntry::SharedBlob, BlobId::shared_deopt_id);
2745 }
2746
2747 // Number of stack slots between incoming argument block and the start of
2748 // a new frame. The PROLOG must add this many slots to the stack. The
2749 // EPILOG must remove this many slots. aarch64 needs two slots for
2750 // return address and fp.
2751 // TODO think this is correct but check
2752 uint SharedRuntime::in_preserve_stack_slots() {
2753 return 4;
2754 }
2755
2756 uint SharedRuntime::out_preserve_stack_slots() {
2757 return 0;
2758 }
2759
2760
2761 VMReg SharedRuntime::thread_register() {
2762 return rthread->as_VMReg();
2763 }
2764
2765 //------------------------------generate_handler_blob------
2766 //
2767 // Generate a special Compile2Runtime blob that saves all registers,
2768 // and setup oopmap.
2769 //
2770 SafepointBlob* SharedRuntime::generate_handler_blob(StubId id, address call_ptr) {
2771 assert(is_polling_page_id(id), "expected a polling page stub id");
2772
2773 // Allocate space for the code. Setup code generation tools.
2774 const char* name = SharedRuntime::stub_name(id);
2775 CodeBlob* blob = AOTCodeCache::load_code_blob(AOTCodeEntry::SharedBlob, StubInfo::blob(id));
2776 if (blob != nullptr) {
2777 return blob->as_safepoint_blob();
2778 }
2779
2780 ResourceMark rm;
2781 OopMapSet *oop_maps = new OopMapSet();
2782 OopMap* map;
2783 CodeBuffer buffer(name, 2048, 1024);
2784 MacroAssembler* masm = new MacroAssembler(&buffer);
2785
2786 address start = __ pc();
2787 address call_pc = nullptr;
2788 int frame_size_in_words;
2789 bool cause_return = (id == StubId::shared_polling_page_return_handler_id);
2790 RegisterSaver reg_save(id == StubId::shared_polling_page_vectors_safepoint_handler_id /* save_vectors */);
2791
2792 // When the signal occurred, the LR was either signed and stored on the stack (in which
2793 // case it will be restored from the stack before being used) or unsigned and not stored
2794 // on the stack. Stipping ensures we get the right value.
2795 __ strip_return_address();
2796
2797 // Save Integer and Float registers.
2798 map = reg_save.save_live_registers(masm, 0, &frame_size_in_words);
2799
2800 // The following is basically a call_VM. However, we need the precise
2801 // address of the call in order to generate an oopmap. Hence, we do all the
2802 // work ourselves.
2803
2804 Label retaddr;
2805 __ set_last_Java_frame(sp, noreg, retaddr, rscratch1);
2806
2807 // The return address must always be correct so that frame constructor never
2808 // sees an invalid pc.
2809
2810 if (!cause_return) {
2811 // overwrite the return address pushed by save_live_registers
2812 // Additionally, r20 is a callee-saved register so we can look at
2813 // it later to determine if someone changed the return address for
2814 // us!
2815 __ ldr(r20, Address(rthread, JavaThread::saved_exception_pc_offset()));
2816 __ protect_return_address(r20);
2817 __ str(r20, Address(rfp, wordSize));
2818 }
2819
2820 // Do the call
2821 __ mov(c_rarg0, rthread);
2822 __ lea(rscratch1, RuntimeAddress(call_ptr));
2823 __ blr(rscratch1);
2824 __ bind(retaddr);
2825
2826 // Set an oopmap for the call site. This oopmap will map all
2827 // oop-registers and debug-info registers as callee-saved. This
2828 // will allow deoptimization at this safepoint to find all possible
2829 // debug-info recordings, as well as let GC find all oops.
2830
2831 oop_maps->add_gc_map( __ pc() - start, map);
2832
2833 Label noException;
2834
2835 __ reset_last_Java_frame(false);
2836
2837 __ membar(Assembler::LoadLoad | Assembler::LoadStore);
2838
2839 __ ldr(rscratch1, Address(rthread, Thread::pending_exception_offset()));
2840 __ cbz(rscratch1, noException);
2841
2842 // Exception pending
2843
2844 reg_save.restore_live_registers(masm);
2845
2846 __ far_jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
2847
2848 // No exception case
2849 __ bind(noException);
2850
2851 Label no_adjust, bail;
2852 if (!cause_return) {
2853 // If our stashed return pc was modified by the runtime we avoid touching it
2854 __ ldr(rscratch1, Address(rfp, wordSize));
2855 __ cmp(r20, rscratch1);
2856 __ br(Assembler::NE, no_adjust);
2857 __ authenticate_return_address(r20);
2858
2859 #ifdef ASSERT
2860 // Verify the correct encoding of the poll we're about to skip.
2861 // See NativeInstruction::is_ldrw_to_zr()
2862 __ ldrw(rscratch1, Address(r20));
2863 __ ubfx(rscratch2, rscratch1, 22, 10);
2864 __ cmpw(rscratch2, 0b1011100101);
2865 __ br(Assembler::NE, bail);
2866 __ ubfx(rscratch2, rscratch1, 0, 5);
2867 __ cmpw(rscratch2, 0b11111);
2868 __ br(Assembler::NE, bail);
2869 #endif
2870 // Adjust return pc forward to step over the safepoint poll instruction
2871 __ add(r20, r20, NativeInstruction::instruction_size);
2872 __ protect_return_address(r20);
2873 __ str(r20, Address(rfp, wordSize));
2874 }
2875
2876 __ bind(no_adjust);
2877 // Normal exit, restore registers and exit.
2878 reg_save.restore_live_registers(masm);
2879
2880 __ ret(lr);
2881
2882 #ifdef ASSERT
2883 __ bind(bail);
2884 __ stop("Attempting to adjust pc to skip safepoint poll but the return point is not what we expected");
2885 #endif
2886
2887 // Make sure all code is generated
2888 masm->flush();
2889
2890 // Fill-out other meta info
2891 SafepointBlob* sp_blob = SafepointBlob::create(&buffer, oop_maps, frame_size_in_words);
2892
2893 AOTCodeCache::store_code_blob(*sp_blob, AOTCodeEntry::SharedBlob, StubInfo::blob(id));
2894 return sp_blob;
2895 }
2896
2897 //
2898 // generate_resolve_blob - call resolution (static/virtual/opt-virtual/ic-miss
2899 //
2900 // Generate a stub that calls into vm to find out the proper destination
2901 // of a java call. All the argument registers are live at this point
2902 // but since this is generic code we don't know what they are and the caller
2903 // must do any gc of the args.
2904 //
2905 RuntimeStub* SharedRuntime::generate_resolve_blob(StubId id, address destination) {
2906 assert (StubRoutines::forward_exception_entry() != nullptr, "must be generated before");
2907 assert(is_resolve_id(id), "expected a resolve stub id");
2908
2909 const char* name = SharedRuntime::stub_name(id);
2910 CodeBlob* blob = AOTCodeCache::load_code_blob(AOTCodeEntry::SharedBlob, StubInfo::blob(id));
2911 if (blob != nullptr) {
2912 return blob->as_runtime_stub();
2913 }
2914
2915 // allocate space for the code
2916 ResourceMark rm;
2917 CodeBuffer buffer(name, 1000, 512);
2918 MacroAssembler* masm = new MacroAssembler(&buffer);
2919
2920 int frame_size_in_words;
2921 RegisterSaver reg_save(false /* save_vectors */);
2922
2923 OopMapSet *oop_maps = new OopMapSet();
2924 OopMap* map = nullptr;
2925
2926 int start = __ offset();
2927
2928 map = reg_save.save_live_registers(masm, 0, &frame_size_in_words);
2929
2930 int frame_complete = __ offset();
2931
2932 {
2933 Label retaddr;
2934 __ set_last_Java_frame(sp, noreg, retaddr, rscratch1);
2935
2936 __ mov(c_rarg0, rthread);
2937 __ lea(rscratch1, RuntimeAddress(destination));
2938
2939 __ blr(rscratch1);
2940 __ bind(retaddr);
2941 }
2942
2943 // Set an oopmap for the call site.
2944 // We need this not only for callee-saved registers, but also for volatile
2945 // registers that the compiler might be keeping live across a safepoint.
2946
2947 oop_maps->add_gc_map( __ offset() - start, map);
2948
2949 // r0 contains the address we are going to jump to assuming no exception got installed
2950
2951 // clear last_Java_sp
2952 __ reset_last_Java_frame(false);
2953 // check for pending exceptions
2954 Label pending;
2955 __ ldr(rscratch1, Address(rthread, Thread::pending_exception_offset()));
2956 __ cbnz(rscratch1, pending);
2957
2958 // get the returned Method*
2959 __ get_vm_result_metadata(rmethod, rthread);
2960 __ str(rmethod, Address(sp, reg_save.reg_offset_in_bytes(rmethod)));
2961
2962 // r0 is where we want to jump, overwrite rscratch1 which is saved and scratch
2963 __ str(r0, Address(sp, reg_save.rscratch1_offset_in_bytes()));
2964 reg_save.restore_live_registers(masm);
2965
2966 // We are back to the original state on entry and ready to go.
2967
2968 __ br(rscratch1);
2969
2970 // Pending exception after the safepoint
2971
2972 __ bind(pending);
2973
2974 reg_save.restore_live_registers(masm);
2975
2976 // exception pending => remove activation and forward to exception handler
2977
2978 __ str(zr, Address(rthread, JavaThread::vm_result_oop_offset()));
2979
2980 __ ldr(r0, Address(rthread, Thread::pending_exception_offset()));
2981 __ far_jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
2982
2983 // -------------
2984 // make sure all code is generated
2985 masm->flush();
2986
2987 // return the blob
2988 // frame_size_words or bytes??
2989 RuntimeStub* rs_blob = RuntimeStub::new_runtime_stub(name, &buffer, frame_complete, frame_size_in_words, oop_maps, true);
2990
2991 AOTCodeCache::store_code_blob(*rs_blob, AOTCodeEntry::SharedBlob, StubInfo::blob(id));
2992 return rs_blob;
2993 }
2994
2995 BufferedInlineTypeBlob* SharedRuntime::generate_buffered_inline_type_adapter(const InlineKlass* vk) {
2996 BufferBlob* buf = BufferBlob::create("inline types pack/unpack", 16 * K);
2997 if (buf == nullptr) {
2998 return nullptr;
2999 }
3000 CodeBuffer buffer(buf);
3001 short buffer_locs[20];
3002 buffer.insts()->initialize_shared_locs((relocInfo*)buffer_locs,
3003 sizeof(buffer_locs)/sizeof(relocInfo));
3004
3005 MacroAssembler _masm(&buffer);
3006 MacroAssembler* masm = &_masm;
3007
3008 const Array<SigEntry>* sig_vk = vk->extended_sig();
3009 const Array<VMRegPair>* regs = vk->return_regs();
3010
3011 int pack_fields_jobject_off = __ offset();
3012 // Resolve pre-allocated buffer from JNI handle.
3013 // We cannot do this in generate_call_stub() because it requires GC code to be initialized.
3014 Register Rresult = r14; // See StubGenerator::generate_call_stub().
3015 __ ldr(r0, Address(Rresult));
3016 __ resolve_jobject(r0 /* value */,
3017 rthread /* thread */,
3018 r12 /* tmp */);
3019 __ str(r0, Address(Rresult));
3020
3021 int pack_fields_off = __ offset();
3022
3023 int j = 1;
3024 for (int i = 0; i < sig_vk->length(); i++) {
3025 BasicType bt = sig_vk->at(i)._bt;
3026 if (bt == T_METADATA) {
3027 continue;
3028 }
3029 if (bt == T_VOID) {
3030 if (sig_vk->at(i-1)._bt == T_LONG ||
3031 sig_vk->at(i-1)._bt == T_DOUBLE) {
3032 j++;
3033 }
3034 continue;
3035 }
3036 int off = sig_vk->at(i)._offset;
3037 VMRegPair pair = regs->at(j);
3038 VMReg r_1 = pair.first();
3039 VMReg r_2 = pair.second();
3040 Address to(r0, off);
3041 if (bt == T_FLOAT) {
3042 __ strs(r_1->as_FloatRegister(), to);
3043 } else if (bt == T_DOUBLE) {
3044 __ strd(r_1->as_FloatRegister(), to);
3045 } else {
3046 Register val = r_1->as_Register();
3047 assert_different_registers(to.base(), val, r15, r16, r17);
3048 if (is_reference_type(bt)) {
3049 // store_heap_oop transitively calls oop_store_at which corrupts to.base(). We need to keep r0 valid.
3050 __ mov(r17, r0);
3051 Address to_with_r17(r17, off);
3052 __ store_heap_oop(to_with_r17, val, r15, r16, r17, IN_HEAP | ACCESS_WRITE | IS_DEST_UNINITIALIZED);
3053 } else {
3054 __ store_sized_value(to, r_1->as_Register(), type2aelembytes(bt));
3055 }
3056 }
3057 j++;
3058 }
3059 assert(j == regs->length(), "missed a field?");
3060 if (vk->supports_nullable_layouts()) {
3061 // Zero the null marker (setting it to 1 would be better but would require an additional register)
3062 __ strb(zr, Address(r0, vk->null_marker_offset()));
3063 }
3064 __ ret(lr);
3065
3066 int unpack_fields_off = __ offset();
3067
3068 Label skip;
3069 Label not_null;
3070 __ cbnz(r0, not_null);
3071
3072 // Return value is null. Zero all registers because the runtime requires a canonical
3073 // representation of a flat null.
3074 j = 1;
3075 for (int i = 0; i < sig_vk->length(); i++) {
3076 BasicType bt = sig_vk->at(i)._bt;
3077 if (bt == T_METADATA) {
3078 continue;
3079 }
3080 if (bt == T_VOID) {
3081 if (sig_vk->at(i-1)._bt == T_LONG ||
3082 sig_vk->at(i-1)._bt == T_DOUBLE) {
3083 j++;
3084 }
3085 continue;
3086 }
3087
3088 VMRegPair pair = regs->at(j);
3089 VMReg r_1 = pair.first();
3090 if (r_1->is_FloatRegister()) {
3091 __ mov(r_1->as_FloatRegister(), Assembler::T2S, 0);
3092 } else {
3093 __ mov(r_1->as_Register(), zr);
3094 }
3095 j++;
3096 }
3097 __ b(skip);
3098 __ bind(not_null);
3099
3100 j = 1;
3101 for (int i = 0; i < sig_vk->length(); i++) {
3102 BasicType bt = sig_vk->at(i)._bt;
3103 if (bt == T_METADATA) {
3104 continue;
3105 }
3106 if (bt == T_VOID) {
3107 if (sig_vk->at(i-1)._bt == T_LONG ||
3108 sig_vk->at(i-1)._bt == T_DOUBLE) {
3109 j++;
3110 }
3111 continue;
3112 }
3113 int off = sig_vk->at(i)._offset;
3114 assert(off > 0, "offset in object should be positive");
3115 VMRegPair pair = regs->at(j);
3116 VMReg r_1 = pair.first();
3117 VMReg r_2 = pair.second();
3118 Address from(r0, off);
3119 if (bt == T_FLOAT) {
3120 __ ldrs(r_1->as_FloatRegister(), from);
3121 } else if (bt == T_DOUBLE) {
3122 __ ldrd(r_1->as_FloatRegister(), from);
3123 } else if (bt == T_OBJECT || bt == T_ARRAY) {
3124 assert_different_registers(r0, r_1->as_Register());
3125 __ load_heap_oop(r_1->as_Register(), from, rscratch1, rscratch2);
3126 } else {
3127 assert(is_java_primitive(bt), "unexpected basic type");
3128 assert_different_registers(r0, r_1->as_Register());
3129 size_t size_in_bytes = type2aelembytes(bt);
3130 __ load_sized_value(r_1->as_Register(), from, size_in_bytes, bt != T_CHAR && bt != T_BOOLEAN);
3131 }
3132 j++;
3133 }
3134 assert(j == regs->length(), "missed a field?");
3135
3136 __ bind(skip);
3137
3138 __ ret(lr);
3139
3140 __ flush();
3141
3142 return BufferedInlineTypeBlob::create(&buffer, pack_fields_off, pack_fields_jobject_off, unpack_fields_off);
3143 }
3144
3145 // Continuation point for throwing of implicit exceptions that are
3146 // not handled in the current activation. Fabricates an exception
3147 // oop and initiates normal exception dispatching in this
3148 // frame. Since we need to preserve callee-saved values (currently
3149 // only for C2, but done for C1 as well) we need a callee-saved oop
3150 // map and therefore have to make these stubs into RuntimeStubs
3151 // rather than BufferBlobs. If the compiler needs all registers to
3152 // be preserved between the fault point and the exception handler
3153 // then it must assume responsibility for that in
3154 // AbstractCompiler::continuation_for_implicit_null_exception or
3155 // continuation_for_implicit_division_by_zero_exception. All other
3156 // implicit exceptions (e.g., NullPointerException or
3157 // AbstractMethodError on entry) are either at call sites or
3158 // otherwise assume that stack unwinding will be initiated, so
3159 // caller saved registers were assumed volatile in the compiler.
3160
3161 RuntimeStub* SharedRuntime::generate_throw_exception(StubId id, address runtime_entry) {
3162 assert(is_throw_id(id), "expected a throw stub id");
3163
3164 const char* name = SharedRuntime::stub_name(id);
3165
3166 // Information about frame layout at time of blocking runtime call.
3167 // Note that we only have to preserve callee-saved registers since
3168 // the compilers are responsible for supplying a continuation point
3169 // if they expect all registers to be preserved.
3170 // n.b. aarch64 asserts that frame::arg_reg_save_area_bytes == 0
3171 enum layout {
3172 rfp_off = 0,
3173 rfp_off2,
3174 return_off,
3175 return_off2,
3176 framesize // inclusive of return address
3177 };
3178
3179 int insts_size = 512;
3180 int locs_size = 64;
3181
3182 const char* timer_msg = "SharedRuntime generate_throw_exception";
3183 TraceTime timer(timer_msg, TRACETIME_LOG(Info, startuptime));
3184
3185 CodeBlob* blob = AOTCodeCache::load_code_blob(AOTCodeEntry::SharedBlob, StubInfo::blob(id));
3186 if (blob != nullptr) {
3187 return blob->as_runtime_stub();
3188 }
3189
3190 ResourceMark rm;
3191 CodeBuffer code(name, insts_size, locs_size);
3192 OopMapSet* oop_maps = new OopMapSet();
3193 MacroAssembler* masm = new MacroAssembler(&code);
3194
3195 address start = __ pc();
3196
3197 // This is an inlined and slightly modified version of call_VM
3198 // which has the ability to fetch the return PC out of
3199 // thread-local storage and also sets up last_Java_sp slightly
3200 // differently than the real call_VM
3201
3202 __ enter(); // Save FP and LR before call
3203
3204 assert(is_even(framesize/2), "sp not 16-byte aligned");
3205
3206 // lr and fp are already in place
3207 __ sub(sp, rfp, ((uint64_t)framesize-4) << LogBytesPerInt); // prolog
3208
3209 int frame_complete = __ pc() - start;
3210
3211 // Set up last_Java_sp and last_Java_fp
3212 address the_pc = __ pc();
3213 __ set_last_Java_frame(sp, rfp, the_pc, rscratch1);
3214
3215 __ mov(c_rarg0, rthread);
3216 BLOCK_COMMENT("call runtime_entry");
3217 __ lea(rscratch1, RuntimeAddress(runtime_entry));
3218 __ blr(rscratch1);
3219
3220 // Generate oop map
3221 OopMap* map = new OopMap(framesize, 0);
3222
3223 oop_maps->add_gc_map(the_pc - start, map);
3224
3225 __ reset_last_Java_frame(true);
3226
3227 // Reinitialize the ptrue predicate register, in case the external runtime
3228 // call clobbers ptrue reg, as we may return to SVE compiled code.
3229 __ reinitialize_ptrue();
3230
3231 __ leave();
3232
3233 // check for pending exceptions
3234 #ifdef ASSERT
3235 Label L;
3236 __ ldr(rscratch1, Address(rthread, Thread::pending_exception_offset()));
3237 __ cbnz(rscratch1, L);
3238 __ should_not_reach_here();
3239 __ bind(L);
3240 #endif // ASSERT
3241 __ far_jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
3242
3243 // codeBlob framesize is in words (not VMRegImpl::slot_size)
3244 RuntimeStub* stub =
3245 RuntimeStub::new_runtime_stub(name,
3246 &code,
3247 frame_complete,
3248 (framesize >> (LogBytesPerWord - LogBytesPerInt)),
3249 oop_maps, false);
3250 AOTCodeCache::store_code_blob(*stub, AOTCodeEntry::SharedBlob, StubInfo::blob(id));
3251
3252 return stub;
3253 }
3254
3255 #if INCLUDE_JFR
3256
3257 static void jfr_prologue(address the_pc, MacroAssembler* masm, Register thread) {
3258 __ set_last_Java_frame(sp, rfp, the_pc, rscratch1);
3259 __ mov(c_rarg0, thread);
3260 }
3261
3262 // The handle is dereferenced through a load barrier.
3263 static void jfr_epilogue(MacroAssembler* masm) {
3264 __ reset_last_Java_frame(true);
3265 }
3266
3267 // For c2: c_rarg0 is junk, call to runtime to write a checkpoint.
3268 // It returns a jobject handle to the event writer.
3269 // The handle is dereferenced and the return value is the event writer oop.
3270 RuntimeStub* SharedRuntime::generate_jfr_write_checkpoint() {
3271 enum layout {
3272 rbp_off,
3273 rbpH_off,
3274 return_off,
3275 return_off2,
3276 framesize // inclusive of return address
3277 };
3278
3279 int insts_size = 1024;
3280 int locs_size = 64;
3281 const char* name = SharedRuntime::stub_name(StubId::shared_jfr_write_checkpoint_id);
3282 CodeBuffer code(name, insts_size, locs_size);
3283 OopMapSet* oop_maps = new OopMapSet();
3284 MacroAssembler* masm = new MacroAssembler(&code);
3285
3286 address start = __ pc();
3287 __ enter();
3288 int frame_complete = __ pc() - start;
3289 address the_pc = __ pc();
3290 jfr_prologue(the_pc, masm, rthread);
3291 __ call_VM_leaf(CAST_FROM_FN_PTR(address, JfrIntrinsicSupport::write_checkpoint), 1);
3292 jfr_epilogue(masm);
3293 __ resolve_global_jobject(r0, rscratch1, rscratch2);
3294 __ leave();
3295 __ ret(lr);
3296
3297 OopMap* map = new OopMap(framesize, 1); // rfp
3298 oop_maps->add_gc_map(the_pc - start, map);
3299
3300 RuntimeStub* stub = // codeBlob framesize is in words (not VMRegImpl::slot_size)
3301 RuntimeStub::new_runtime_stub(name, &code, frame_complete,
3302 (framesize >> (LogBytesPerWord - LogBytesPerInt)),
3303 oop_maps, false);
3304 return stub;
3305 }
3306
3307 // For c2: call to return a leased buffer.
3308 RuntimeStub* SharedRuntime::generate_jfr_return_lease() {
3309 enum layout {
3310 rbp_off,
3311 rbpH_off,
3312 return_off,
3313 return_off2,
3314 framesize // inclusive of return address
3315 };
3316
3317 int insts_size = 1024;
3318 int locs_size = 64;
3319
3320 const char* name = SharedRuntime::stub_name(StubId::shared_jfr_return_lease_id);
3321 CodeBuffer code(name, insts_size, locs_size);
3322 OopMapSet* oop_maps = new OopMapSet();
3323 MacroAssembler* masm = new MacroAssembler(&code);
3324
3325 address start = __ pc();
3326 __ enter();
3327 int frame_complete = __ pc() - start;
3328 address the_pc = __ pc();
3329 jfr_prologue(the_pc, masm, rthread);
3330 __ call_VM_leaf(CAST_FROM_FN_PTR(address, JfrIntrinsicSupport::return_lease), 1);
3331 jfr_epilogue(masm);
3332
3333 __ leave();
3334 __ ret(lr);
3335
3336 OopMap* map = new OopMap(framesize, 1); // rfp
3337 oop_maps->add_gc_map(the_pc - start, map);
3338
3339 RuntimeStub* stub = // codeBlob framesize is in words (not VMRegImpl::slot_size)
3340 RuntimeStub::new_runtime_stub(name, &code, frame_complete,
3341 (framesize >> (LogBytesPerWord - LogBytesPerInt)),
3342 oop_maps, false);
3343 return stub;
3344 }
3345
3346 #endif // INCLUDE_JFR