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