cranelift_codegen/machinst/abi.rs
1//! Implementation of a vanilla ABI, shared between several machines. The
2//! implementation here assumes that arguments will be passed in registers
3//! first, then additional args on the stack; that the stack grows downward,
4//! contains a standard frame (return address and frame pointer), and the
5//! compiler is otherwise free to allocate space below that with its choice of
6//! layout; and that the machine has some notion of caller- and callee-save
7//! registers. Most modern machines, e.g. x86-64 and AArch64, should fit this
8//! mold and thus both of these backends use this shared implementation.
9//!
10//! See the documentation in specific machine backends for the "instantiation"
11//! of this generic ABI, i.e., which registers are caller/callee-save, arguments
12//! and return values, and any other special requirements.
13//!
14//! For now the implementation here assumes a 64-bit machine, but we intend to
15//! make this 32/64-bit-generic shortly.
16//!
17//! # Vanilla ABI
18//!
19//! First, arguments and return values are passed in registers up to a certain
20//! fixed count, after which they overflow onto the stack. Multiple return
21//! values either fit in registers, or are returned in a separate return-value
22//! area on the stack, given by a hidden extra parameter.
23//!
24//! Note that the exact stack layout is up to us. We settled on the
25//! below design based on several requirements. In particular, we need
26//! to be able to generate instructions (or instruction sequences) to
27//! access arguments, stack slots, and spill slots before we know how
28//! many spill slots or clobber-saves there will be, because of our
29//! pass structure. We also prefer positive offsets to negative
30//! offsets because of an asymmetry in some machines' addressing modes
31//! (e.g., on AArch64, positive offsets have a larger possible range
32//! without a long-form sequence to synthesize an arbitrary
33//! offset). We also need clobber-save registers to be "near" the
34//! frame pointer: Windows unwind information requires it to be within
35//! 240 bytes of RBP. Finally, it is not allowed to access memory
36//! below the current SP value.
37//!
38//! We assume that a prologue first pushes the frame pointer (and
39//! return address above that, if the machine does not do that in
40//! hardware). We set FP to point to this two-word frame record. We
41//! store all other frame slots below this two-word frame record, as
42//! well as enough space for arguments to the largest possible
43//! function call. The stack pointer then remains at this position
44//! for the duration of the function, allowing us to address all
45//! frame storage at positive offsets from SP.
46//!
47//! Note that if we ever support dynamic stack-space allocation (for
48//! `alloca`), we will need a way to reference spill slots and stack
49//! slots relative to a dynamic SP, because we will no longer be able
50//! to know a static offset from SP to the slots at any particular
51//! program point. Probably the best solution at that point will be to
52//! revert to using the frame pointer as the reference for all slots,
53//! to allow generating spill/reload and stackslot accesses before we
54//! know how large the clobber-saves will be.
55//!
56//! # Stack Layout
57//!
58//! The stack looks like:
59//!
60//! ```plain
61//! (high address)
62//! | ... |
63//! | caller frames |
64//! | ... |
65//! +===========================+
66//! | ... |
67//! | stack args |
68//! Canonical Frame Address --> | (accessed via FP) |
69//! +---------------------------+
70//! SP at function entry -----> | return address |
71//! +---------------------------+
72//! FP after prologue --------> | FP (pushed by prologue) |
73//! +---------------------------+ -----
74//! | ... | |
75//! | clobbered callee-saves | |
76//! unwind-frame base --------> | (pushed by prologue) | |
77//! +---------------------------+ ----- |
78//! | ... | | |
79//! | spill slots | | |
80//! | (accessed via SP) | fixed active
81//! | ... | frame size
82//! | stack slots | storage |
83//! | (accessed via SP) | size |
84//! | (alloc'd by prologue) | | |
85//! +---------------------------+ ----- |
86//! | [alignment as needed] | |
87//! | ... | |
88//! | args for largest call | |
89//! SP -----------------------> | (alloc'd by prologue) | |
90//! +===========================+ -----
91//!
92//! (low address)
93//! ```
94//!
95//! # Multi-value Returns
96//!
97//! We support multi-value returns by using multiple return-value
98//! registers. In some cases this is an extension of the base system
99//! ABI. See each platform's `abi.rs` implementation for details.
100
101use crate::CodegenError;
102use crate::FxHashMap;
103use crate::HashMap;
104use crate::entity::SecondaryMap;
105use crate::ir::{ArgumentExtension, ArgumentPurpose, ExceptionTag, Signature};
106use crate::ir::{StackSlotKey, types::*};
107use crate::isa::TargetIsa;
108use crate::settings::ProbestackStrategy;
109use crate::{ir, isa};
110use crate::{machinst::*, trace};
111use alloc::boxed::Box;
112use core::marker::PhantomData;
113use regalloc2::{MachineEnv, PReg, PRegSet};
114use smallvec::smallvec;
115
116/// A small vector of instructions (with some reasonable size); appropriate for
117/// a small fixed sequence implementing one operation.
118pub type SmallInstVec<I> = SmallVec<[I; 4]>;
119
120/// A type used by backends to track argument-binding info in the "args"
121/// pseudoinst. The pseudoinst holds a vec of `ArgPair` structs.
122#[derive(Clone, Debug)]
123pub struct ArgPair {
124 /// The vreg that is defined by this args pseudoinst.
125 pub vreg: Writable<Reg>,
126 /// The preg that the arg arrives in; this constrains the vreg's
127 /// placement at the pseudoinst.
128 pub preg: Reg,
129}
130
131/// A type used by backends to track return register binding info in the "ret"
132/// pseudoinst. The pseudoinst holds a vec of `RetPair` structs.
133#[derive(Clone, Debug)]
134pub struct RetPair {
135 /// The vreg that is returned by this pseudionst.
136 pub vreg: Reg,
137 /// The preg that the arg is returned through; this constrains the vreg's
138 /// placement at the pseudoinst.
139 pub preg: Reg,
140}
141
142/// A location for (part of) an argument or return value. These "storage slots"
143/// are specified for each register-sized part of an argument.
144#[derive(Clone, Copy, Debug, PartialEq, Eq)]
145pub enum ABIArgSlot {
146 /// In a real register.
147 Reg {
148 /// Register that holds this arg.
149 reg: RealReg,
150 /// Value type of this arg.
151 ty: ir::Type,
152 /// Should this arg be zero- or sign-extended?
153 extension: ir::ArgumentExtension,
154 },
155 /// Arguments only: on stack, at given offset from SP at entry.
156 Stack {
157 /// Offset of this arg relative to the base of stack args.
158 offset: i64,
159 /// Value type of this arg.
160 ty: ir::Type,
161 /// Should this arg be zero- or sign-extended?
162 extension: ir::ArgumentExtension,
163 },
164}
165
166impl ABIArgSlot {
167 /// The type of the value that will be stored in this slot.
168 pub fn get_type(&self) -> ir::Type {
169 match self {
170 ABIArgSlot::Reg { ty, .. } => *ty,
171 ABIArgSlot::Stack { ty, .. } => *ty,
172 }
173 }
174}
175
176/// A vector of `ABIArgSlot`s. Inline capacity for one element because basically
177/// 100% of values use one slot. Only `i128`s need multiple slots, and they are
178/// super rare (and never happen with Wasm).
179pub type ABIArgSlotVec = SmallVec<[ABIArgSlot; 1]>;
180
181/// An ABIArg is composed of one or more parts. This allows for a CLIF-level
182/// Value to be passed with its parts in more than one location at the ABI
183/// level. For example, a 128-bit integer may be passed in two 64-bit registers,
184/// or even a 64-bit register and a 64-bit stack slot, on a 64-bit machine. The
185/// number of "parts" should correspond to the number of registers used to store
186/// this type according to the machine backend.
187///
188/// As an invariant, the `purpose` for every part must match. As a further
189/// invariant, a `StructArg` part cannot appear with any other part.
190#[derive(Clone, Debug)]
191pub enum ABIArg {
192 /// Storage slots (registers or stack locations) for each part of the
193 /// argument value. The number of slots must equal the number of register
194 /// parts used to store a value of this type.
195 Slots {
196 /// Slots, one per register part.
197 slots: ABIArgSlotVec,
198 /// Purpose of this arg.
199 purpose: ir::ArgumentPurpose,
200 },
201 /// Structure argument. We reserve stack space for it, but the CLIF-level
202 /// semantics are a little weird: the value passed to the call instruction,
203 /// and received in the corresponding block param, is a *pointer*. On the
204 /// caller side, we memcpy the data from the passed-in pointer to the stack
205 /// area; on the callee side, we compute a pointer to this stack area and
206 /// provide that as the argument's value.
207 StructArg {
208 /// Offset of this arg relative to base of stack args.
209 offset: i64,
210 /// Size of this arg on the stack.
211 size: u64,
212 /// Purpose of this arg.
213 purpose: ir::ArgumentPurpose,
214 },
215 /// Implicit argument. Similar to a StructArg, except that we have the
216 /// target type, not a pointer type, at the CLIF-level. This argument is
217 /// still being passed via reference implicitly.
218 ImplicitPtrArg {
219 /// Register or stack slot holding a pointer to the buffer.
220 pointer: ABIArgSlot,
221 /// Offset of the argument buffer.
222 offset: i64,
223 /// Type of the implicit argument.
224 ty: Type,
225 /// Purpose of this arg.
226 purpose: ir::ArgumentPurpose,
227 },
228}
229
230impl ABIArg {
231 /// Create an ABIArg from one register.
232 pub fn reg(
233 reg: RealReg,
234 ty: ir::Type,
235 extension: ir::ArgumentExtension,
236 purpose: ir::ArgumentPurpose,
237 ) -> ABIArg {
238 ABIArg::Slots {
239 slots: smallvec![ABIArgSlot::Reg { reg, ty, extension }],
240 purpose,
241 }
242 }
243
244 /// Create an ABIArg from one stack slot.
245 pub fn stack(
246 offset: i64,
247 ty: ir::Type,
248 extension: ir::ArgumentExtension,
249 purpose: ir::ArgumentPurpose,
250 ) -> ABIArg {
251 ABIArg::Slots {
252 slots: smallvec![ABIArgSlot::Stack {
253 offset,
254 ty,
255 extension,
256 }],
257 purpose,
258 }
259 }
260}
261
262/// Are we computing information about arguments or return values? Much of the
263/// handling is factored out into common routines; this enum allows us to
264/// distinguish which case we're handling.
265#[derive(Clone, Copy, Debug, PartialEq, Eq)]
266pub enum ArgsOrRets {
267 /// Arguments.
268 Args,
269 /// Return values.
270 Rets,
271}
272
273/// Abstract location for a machine-specific ABI impl to translate into the
274/// appropriate addressing mode.
275#[derive(Clone, Copy, Debug, PartialEq, Eq)]
276pub enum StackAMode {
277 /// Offset into the current frame's argument area.
278 IncomingArg(i64, u32),
279 /// Offset within the stack slots in the current frame.
280 Slot(i64),
281 /// Offset into the callee frame's argument area.
282 OutgoingArg(i64),
283}
284
285impl StackAMode {
286 fn offset_by(&self, offset: u32) -> Self {
287 match self {
288 StackAMode::IncomingArg(off, size) => {
289 StackAMode::IncomingArg(off.checked_add(i64::from(offset)).unwrap(), *size)
290 }
291 StackAMode::Slot(off) => StackAMode::Slot(off.checked_add(i64::from(offset)).unwrap()),
292 StackAMode::OutgoingArg(off) => {
293 StackAMode::OutgoingArg(off.checked_add(i64::from(offset)).unwrap())
294 }
295 }
296 }
297}
298
299/// Trait implemented by machine-specific backend to represent ISA flags.
300pub trait IsaFlags: Clone {
301 /// Get a flag indicating whether forward-edge CFI is enabled.
302 fn is_forward_edge_cfi_enabled(&self) -> bool {
303 false
304 }
305}
306
307/// Used as an out-parameter to accumulate a sequence of `ABIArg`s in
308/// `ABIMachineSpec::compute_arg_locs`. Wraps the shared allocation for all
309/// `ABIArg`s in `SigSet` and exposes just the args for the current
310/// `compute_arg_locs` call.
311pub struct ArgsAccumulator<'a> {
312 sig_set_abi_args: &'a mut Vec<ABIArg>,
313 start: usize,
314 non_formal_flag: bool,
315}
316
317impl<'a> ArgsAccumulator<'a> {
318 fn new(sig_set_abi_args: &'a mut Vec<ABIArg>) -> Self {
319 let start = sig_set_abi_args.len();
320 ArgsAccumulator {
321 sig_set_abi_args,
322 start,
323 non_formal_flag: false,
324 }
325 }
326
327 #[inline]
328 pub fn push(&mut self, arg: ABIArg) {
329 debug_assert!(!self.non_formal_flag);
330 self.sig_set_abi_args.push(arg)
331 }
332
333 #[inline]
334 pub fn push_non_formal(&mut self, arg: ABIArg) {
335 self.non_formal_flag = true;
336 self.sig_set_abi_args.push(arg)
337 }
338
339 #[inline]
340 pub fn args(&self) -> &[ABIArg] {
341 &self.sig_set_abi_args[self.start..]
342 }
343
344 #[inline]
345 pub fn args_mut(&mut self) -> &mut [ABIArg] {
346 &mut self.sig_set_abi_args[self.start..]
347 }
348}
349
350/// Trait implemented by machine-specific backend to provide information about
351/// register assignments and to allow generating the specific instructions for
352/// stack loads/saves, prologues/epilogues, etc.
353pub trait ABIMachineSpec {
354 /// The instruction type.
355 type I: VCodeInst;
356
357 /// The ISA flags type.
358 type F: IsaFlags;
359
360 /// This is the limit for the size of argument and return-value areas on the
361 /// stack. We place a reasonable limit here to avoid integer overflow issues
362 /// with 32-bit arithmetic.
363 const STACK_ARG_RET_SIZE_LIMIT: u32;
364
365 /// Returns the number of bits in a word, that is 32/64 for 32/64-bit architecture.
366 fn word_bits() -> u32;
367
368 /// Returns the number of bytes in a word.
369 fn word_bytes() -> u32 {
370 return Self::word_bits() / 8;
371 }
372
373 /// Returns word-size integer type.
374 fn word_type() -> Type {
375 match Self::word_bits() {
376 32 => I32,
377 64 => I64,
378 _ => unreachable!(),
379 }
380 }
381
382 /// Returns word register class.
383 fn word_reg_class() -> RegClass {
384 RegClass::Int
385 }
386
387 /// Returns required stack alignment in bytes.
388 fn stack_align(call_conv: isa::CallConv) -> u32;
389
390 /// Process a list of parameters or return values and allocate them to registers
391 /// and stack slots.
392 ///
393 /// The argument locations should be pushed onto the given `ArgsAccumulator`
394 /// in order. Any extra arguments added (such as return area pointers)
395 /// should come at the end of the list so that the first N lowered
396 /// parameters align with the N clif parameters.
397 ///
398 /// Returns the stack-space used (rounded up to as alignment requires), and
399 /// if `add_ret_area_ptr` was passed, the index of the extra synthetic arg
400 /// that was added.
401 fn compute_arg_locs(
402 call_conv: isa::CallConv,
403 flags: &settings::Flags,
404 params: &[ir::AbiParam],
405 args_or_rets: ArgsOrRets,
406 add_ret_area_ptr: bool,
407 args: ArgsAccumulator,
408 ) -> CodegenResult<(u32, Option<usize>)>;
409
410 /// Generate a load from the stack.
411 fn gen_load_stack(mem: StackAMode, into_reg: Writable<Reg>, ty: Type) -> Self::I;
412
413 /// Generate a store to the stack.
414 fn gen_store_stack(mem: StackAMode, from_reg: Reg, ty: Type) -> Self::I;
415
416 /// Generate a move.
417 fn gen_move(to_reg: Writable<Reg>, from_reg: Reg, ty: Type) -> Self::I;
418
419 /// Generate an integer-extend operation.
420 fn gen_extend(
421 to_reg: Writable<Reg>,
422 from_reg: Reg,
423 is_signed: bool,
424 from_bits: u8,
425 to_bits: u8,
426 ) -> Self::I;
427
428 /// Generate an "args" pseudo-instruction to capture input args in
429 /// registers.
430 fn gen_args(args: Vec<ArgPair>) -> Self::I;
431
432 /// Generate a "rets" pseudo-instruction that moves vregs to return
433 /// registers.
434 fn gen_rets(rets: Vec<RetPair>) -> Self::I;
435
436 /// Generate an add-with-immediate. Note that even if this uses a scratch
437 /// register, it must satisfy two requirements:
438 ///
439 /// - The add-imm sequence must only clobber caller-save registers that are
440 /// not used for arguments, because it will be placed in the prologue
441 /// before the clobbered callee-save registers are saved.
442 ///
443 /// - The add-imm sequence must work correctly when `from_reg` and/or
444 /// `into_reg` are the register returned by `get_stacklimit_reg()`.
445 fn gen_add_imm(
446 call_conv: isa::CallConv,
447 into_reg: Writable<Reg>,
448 from_reg: Reg,
449 imm: u32,
450 ) -> SmallInstVec<Self::I>;
451
452 /// Generate a sequence that traps with a `TrapCode::StackOverflow` code if
453 /// the stack pointer is less than the given limit register (assuming the
454 /// stack grows downward).
455 fn gen_stack_lower_bound_trap(limit_reg: Reg) -> SmallInstVec<Self::I>;
456
457 /// Generate an instruction to compute an address of a stack slot (FP- or
458 /// SP-based offset).
459 fn gen_get_stack_addr(mem: StackAMode, into_reg: Writable<Reg>) -> Self::I;
460
461 /// Get a fixed register to use to compute a stack limit. This is needed for
462 /// certain sequences generated after the register allocator has already
463 /// run. This must satisfy two requirements:
464 ///
465 /// - It must be a caller-save register that is not used for arguments,
466 /// because it will be clobbered in the prologue before the clobbered
467 /// callee-save registers are saved.
468 ///
469 /// - It must be safe to pass as an argument and/or destination to
470 /// `gen_add_imm()`. This is relevant when an addition with a large
471 /// immediate needs its own temporary; it cannot use the same fixed
472 /// temporary as this one.
473 fn get_stacklimit_reg(call_conv: isa::CallConv) -> Reg;
474
475 /// Generate a load to the given [base+offset] address.
476 fn gen_load_base_offset(into_reg: Writable<Reg>, base: Reg, offset: i32, ty: Type) -> Self::I;
477
478 /// Generate a store from the given [base+offset] address.
479 fn gen_store_base_offset(base: Reg, offset: i32, from_reg: Reg, ty: Type) -> Self::I;
480
481 /// Adjust the stack pointer up or down.
482 fn gen_sp_reg_adjust(amount: i32) -> SmallInstVec<Self::I>;
483
484 /// Compute a FrameLayout structure containing a sorted list of all clobbered
485 /// registers that are callee-saved according to the ABI, as well as the sizes
486 /// of all parts of the stack frame. The result is used to emit the prologue
487 /// and epilogue routines.
488 fn compute_frame_layout(
489 call_conv: isa::CallConv,
490 flags: &settings::Flags,
491 sig: &Signature,
492 regs: &[Writable<RealReg>],
493 function_calls: FunctionCalls,
494 incoming_args_size: u32,
495 tail_args_size: u32,
496 stackslots_size: u32,
497 fixed_frame_storage_size: u32,
498 outgoing_args_size: u32,
499 ) -> FrameLayout;
500
501 /// Defaults to a conservative 1GiB
502 /// across all backends.
503 fn maximum_frame_size() -> u32 {
504 1 << 30 // 1 GiB
505 }
506
507 /// Generate the usual frame-setup sequence for this architecture: e.g.,
508 /// `push rbp / mov rbp, rsp` on x86-64, or `stp fp, lr, [sp, #-16]!` on
509 /// AArch64.
510 fn gen_prologue_frame_setup(
511 call_conv: isa::CallConv,
512 flags: &settings::Flags,
513 isa_flags: &Self::F,
514 frame_layout: &FrameLayout,
515 ) -> SmallInstVec<Self::I>;
516
517 /// Generate the usual frame-restore sequence for this architecture.
518 fn gen_epilogue_frame_restore(
519 call_conv: isa::CallConv,
520 flags: &settings::Flags,
521 isa_flags: &Self::F,
522 frame_layout: &FrameLayout,
523 ) -> SmallInstVec<Self::I>;
524
525 /// Generate a return instruction.
526 fn gen_return(
527 call_conv: isa::CallConv,
528 isa_flags: &Self::F,
529 frame_layout: &FrameLayout,
530 ) -> SmallInstVec<Self::I>;
531
532 /// Generate a probestack call.
533 fn gen_probestack(insts: &mut SmallInstVec<Self::I>, frame_size: u32);
534
535 /// Generate a inline stack probe.
536 fn gen_inline_probestack(
537 insts: &mut SmallInstVec<Self::I>,
538 call_conv: isa::CallConv,
539 frame_size: u32,
540 guard_size: u32,
541 );
542
543 /// Generate a clobber-save sequence. The implementation here should return
544 /// a sequence of instructions that "push" or otherwise save to the stack all
545 /// registers written/modified by the function body that are callee-saved.
546 /// The sequence of instructions should adjust the stack pointer downward,
547 /// and should align as necessary according to ABI requirements.
548 fn gen_clobber_save(
549 call_conv: isa::CallConv,
550 flags: &settings::Flags,
551 frame_layout: &FrameLayout,
552 ) -> SmallVec<[Self::I; 16]>;
553
554 /// Generate a clobber-restore sequence. This sequence should perform the
555 /// opposite of the clobber-save sequence generated above, assuming that SP
556 /// going into the sequence is at the same point that it was left when the
557 /// clobber-save sequence finished.
558 fn gen_clobber_restore(
559 call_conv: isa::CallConv,
560 flags: &settings::Flags,
561 frame_layout: &FrameLayout,
562 ) -> SmallVec<[Self::I; 16]>;
563
564 /// Generate a memcpy invocation. Used to set up struct
565 /// args. Takes `src`, `dst` as read-only inputs and passes a temporary
566 /// allocator.
567 fn gen_memcpy<F: FnMut(Type) -> Writable<Reg>>(
568 call_conv: isa::CallConv,
569 dst: Reg,
570 src: Reg,
571 size: usize,
572 alloc_tmp: F,
573 ) -> SmallVec<[Self::I; 8]>;
574
575 /// Get the number of spillslots required for the given register-class.
576 fn get_number_of_spillslots_for_value(
577 rc: RegClass,
578 target_vector_bytes: u32,
579 isa_flags: &Self::F,
580 ) -> u32;
581
582 /// Get the ABI-dependent MachineEnv for managing register allocation.
583 fn get_machine_env(flags: &settings::Flags, call_conv: isa::CallConv) -> &MachineEnv;
584
585 /// Get all caller-save registers, that is, registers that we expect
586 /// not to be saved across a call to a callee with the given ABI.
587 fn get_regs_clobbered_by_call(
588 call_conv_of_callee: isa::CallConv,
589 is_exception: bool,
590 ) -> PRegSet;
591
592 /// Get the needed extension mode, given the mode attached to the argument
593 /// in the signature and the calling convention. The input (the attribute in
594 /// the signature) specifies what extension type should be done *if* the ABI
595 /// requires extension to the full register; this method's return value
596 /// indicates whether the extension actually *will* be done.
597 fn get_ext_mode(
598 call_conv: isa::CallConv,
599 specified: ir::ArgumentExtension,
600 ) -> ir::ArgumentExtension;
601
602 /// Get a temporary register that is available to use after a call
603 /// completes and that does not interfere with register-carried
604 /// return values. This is used to move stack-carried return
605 /// values directly into spillslots if needed.
606 fn retval_temp_reg(call_conv_of_callee: isa::CallConv) -> Writable<Reg>;
607
608 /// Get the exception payload registers, if any, for a calling
609 /// convention.
610 ///
611 /// Note that the argument here is the calling convention of the *callee*.
612 /// This might differ from the caller but the exceptional payloads that are
613 /// available are defined by the callee, not the caller.
614 fn exception_payload_regs(callee_conv: isa::CallConv) -> &'static [Reg] {
615 let _ = callee_conv;
616 &[]
617 }
618}
619
620/// Out-of-line data for calls, to keep the size of `Inst` down.
621#[derive(Clone, Debug)]
622pub struct CallInfo<T> {
623 /// Receiver of this call
624 pub dest: T,
625 /// Register uses of this call.
626 pub uses: CallArgList,
627 /// Register defs of this call.
628 pub defs: CallRetList,
629 /// Registers clobbered by this call, as per its calling convention.
630 pub clobbers: PRegSet,
631 /// The calling convention of the callee.
632 pub callee_conv: isa::CallConv,
633 /// The calling convention of the caller.
634 pub caller_conv: isa::CallConv,
635 /// The number of bytes that the callee will pop from the stack for the
636 /// caller, if any. (Used for popping stack arguments with the `tail`
637 /// calling convention.)
638 pub callee_pop_size: u32,
639 /// Information for a try-call, if this is one. We combine
640 /// handling of calls and try-calls as much as possible to share
641 /// argument/return logic; they mostly differ in the metadata that
642 /// they emit, which this information feeds into.
643 pub try_call_info: Option<TryCallInfo>,
644 /// Whether this call is patchable.
645 pub patchable: bool,
646}
647
648/// Out-of-line information present on `try_call` instructions only:
649/// information that is used to generate exception-handling tables and
650/// link up to destination blocks properly.
651#[derive(Clone, Debug)]
652pub struct TryCallInfo {
653 /// The target to jump to on a normal returhn.
654 pub continuation: MachLabel,
655 /// Exception tags to catch and corresponding destination labels.
656 pub exception_handlers: Box<[TryCallHandler]>,
657}
658
659/// Information about an individual handler at a try-call site.
660#[derive(Clone, Debug)]
661pub enum TryCallHandler {
662 /// If the tag matches (given the current context), recover at the
663 /// label.
664 Tag(ExceptionTag, MachLabel),
665 /// Recover at the label unconditionally.
666 Default(MachLabel),
667 /// Set the dynamic context for interpreting tags at this point in
668 /// the handler list.
669 Context(Reg),
670}
671
672impl<T> CallInfo<T> {
673 /// Creates an empty set of info with no clobbers/uses/etc with the
674 /// specified ABI
675 pub fn empty(dest: T, call_conv: isa::CallConv) -> CallInfo<T> {
676 CallInfo {
677 dest,
678 uses: smallvec![],
679 defs: smallvec![],
680 clobbers: PRegSet::empty(),
681 caller_conv: call_conv,
682 callee_conv: call_conv,
683 callee_pop_size: 0,
684 try_call_info: None,
685 patchable: false,
686 }
687 }
688}
689
690/// The id of an ABI signature within the `SigSet`.
691#[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
692pub struct Sig(u32);
693cranelift_entity::entity_impl!(Sig);
694
695impl Sig {
696 fn prev(self) -> Option<Sig> {
697 self.0.checked_sub(1).map(Sig)
698 }
699}
700
701/// ABI information shared between body (callee) and caller.
702#[derive(Clone, Debug)]
703pub struct SigData {
704 /// Currently both return values and arguments are stored in a continuous space vector
705 /// in `SigSet::abi_args`.
706 ///
707 /// ```plain
708 /// +----------------------------------------------+
709 /// | return values |
710 /// | ... |
711 /// rets_end --> +----------------------------------------------+
712 /// | arguments |
713 /// | ... |
714 /// args_end --> +----------------------------------------------+
715 ///
716 /// ```
717 ///
718 /// Note we only store two offsets as rets_end == args_start, and rets_start == prev.args_end.
719 ///
720 /// Argument location ending offset (regs or stack slots). Stack offsets are relative to
721 /// SP on entry to function.
722 ///
723 /// This is a index into the `SigSet::abi_args`.
724 args_end: u32,
725
726 /// Return-value location ending offset. Stack offsets are relative to the return-area
727 /// pointer.
728 ///
729 /// This is a index into the `SigSet::abi_args`.
730 rets_end: u32,
731
732 /// Space on stack used to store arguments. We're storing the size in u32 to
733 /// reduce the size of the struct.
734 sized_stack_arg_space: u32,
735
736 /// Space on stack used to store return values. We're storing the size in u32 to
737 /// reduce the size of the struct.
738 sized_stack_ret_space: u32,
739
740 /// Index in `args` of the stack-return-value-area argument.
741 stack_ret_arg: Option<u16>,
742
743 /// Calling convention used.
744 call_conv: isa::CallConv,
745}
746
747impl SigData {
748 /// Get total stack space required for arguments.
749 pub fn sized_stack_arg_space(&self) -> u32 {
750 self.sized_stack_arg_space
751 }
752
753 /// Get total stack space required for return values.
754 pub fn sized_stack_ret_space(&self) -> u32 {
755 self.sized_stack_ret_space
756 }
757
758 /// Get calling convention used.
759 pub fn call_conv(&self) -> isa::CallConv {
760 self.call_conv
761 }
762
763 /// The index of the stack-return-value-area argument, if any.
764 pub fn stack_ret_arg(&self) -> Option<u16> {
765 self.stack_ret_arg
766 }
767}
768
769/// A (mostly) deduplicated set of ABI signatures.
770///
771/// We say "mostly" because we do not dedupe between signatures interned via
772/// `ir::SigRef` (direct and indirect calls; the vast majority of signatures in
773/// this set) vs via `ir::Signature` (the callee itself and libcalls). Doing
774/// this final bit of deduplication would require filling out the
775/// `ir_signature_to_abi_sig`, which is a bunch of allocations (not just the
776/// hash map itself but params and returns vecs in each signature) that we want
777/// to avoid.
778///
779/// In general, prefer using the `ir::SigRef`-taking methods to the
780/// `ir::Signature`-taking methods when you can get away with it, as they don't
781/// require cloning non-copy types that will trigger heap allocations.
782///
783/// This type can be indexed by `Sig` to access its associated `SigData`.
784pub struct SigSet {
785 /// Interned `ir::Signature`s that we already have an ABI signature for.
786 ir_signature_to_abi_sig: FxHashMap<ir::Signature, Sig>,
787
788 /// Interned `ir::SigRef`s that we already have an ABI signature for.
789 ir_sig_ref_to_abi_sig: SecondaryMap<ir::SigRef, Option<Sig>>,
790
791 /// A single, shared allocation for all `ABIArg`s used by all
792 /// `SigData`s. Each `SigData` references its args/rets via indices into
793 /// this allocation.
794 abi_args: Vec<ABIArg>,
795
796 /// The actual ABI signatures, keyed by `Sig`.
797 sigs: PrimaryMap<Sig, SigData>,
798}
799
800impl SigSet {
801 /// Construct a new `SigSet`, interning all of the signatures used by the
802 /// given function.
803 pub fn new<M>(func: &ir::Function, flags: &settings::Flags) -> CodegenResult<Self>
804 where
805 M: ABIMachineSpec,
806 {
807 let arg_estimate = func.dfg.signatures.len() * 6;
808
809 let mut sigs = SigSet {
810 ir_signature_to_abi_sig: FxHashMap::default(),
811 ir_sig_ref_to_abi_sig: SecondaryMap::with_capacity(func.dfg.signatures.len()),
812 abi_args: Vec::with_capacity(arg_estimate),
813 sigs: PrimaryMap::with_capacity(1 + func.dfg.signatures.len()),
814 };
815
816 sigs.make_abi_sig_from_ir_signature::<M>(func.signature.clone(), flags)?;
817 for sig_ref in func.dfg.signatures.keys() {
818 sigs.make_abi_sig_from_ir_sig_ref::<M>(sig_ref, &func.dfg, flags)?;
819 }
820
821 Ok(sigs)
822 }
823
824 /// Have we already interned an ABI signature for the given `ir::Signature`?
825 pub fn have_abi_sig_for_signature(&self, signature: &ir::Signature) -> bool {
826 self.ir_signature_to_abi_sig.contains_key(signature)
827 }
828
829 /// Construct and intern an ABI signature for the given `ir::Signature`.
830 pub fn make_abi_sig_from_ir_signature<M>(
831 &mut self,
832 signature: ir::Signature,
833 flags: &settings::Flags,
834 ) -> CodegenResult<Sig>
835 where
836 M: ABIMachineSpec,
837 {
838 // Because the `HashMap` entry API requires taking ownership of the
839 // lookup key -- and we want to avoid unnecessary clones of
840 // `ir::Signature`s, even at the cost of duplicate lookups -- we can't
841 // have a single, get-or-create-style method for interning
842 // `ir::Signature`s into ABI signatures. So at least (debug) assert that
843 // we aren't creating duplicate ABI signatures for the same
844 // `ir::Signature`.
845 debug_assert!(!self.have_abi_sig_for_signature(&signature));
846
847 let sig_data = self.from_func_sig::<M>(&signature, flags)?;
848 let sig = self.sigs.push(sig_data);
849 self.ir_signature_to_abi_sig.insert(signature, sig);
850 Ok(sig)
851 }
852
853 fn make_abi_sig_from_ir_sig_ref<M>(
854 &mut self,
855 sig_ref: ir::SigRef,
856 dfg: &ir::DataFlowGraph,
857 flags: &settings::Flags,
858 ) -> CodegenResult<Sig>
859 where
860 M: ABIMachineSpec,
861 {
862 if let Some(sig) = self.ir_sig_ref_to_abi_sig[sig_ref] {
863 return Ok(sig);
864 }
865 let signature = &dfg.signatures[sig_ref];
866 let sig_data = self.from_func_sig::<M>(signature, flags)?;
867 let sig = self.sigs.push(sig_data);
868 self.ir_sig_ref_to_abi_sig[sig_ref] = Some(sig);
869 Ok(sig)
870 }
871
872 /// Get the already-interned ABI signature id for the given `ir::SigRef`.
873 pub fn abi_sig_for_sig_ref(&self, sig_ref: ir::SigRef) -> Sig {
874 self.ir_sig_ref_to_abi_sig[sig_ref]
875 .expect("must call `make_abi_sig_from_ir_sig_ref` before `get_abi_sig_for_sig_ref`")
876 }
877
878 /// Get the already-interned ABI signature id for the given `ir::Signature`.
879 pub fn abi_sig_for_signature(&self, signature: &ir::Signature) -> Sig {
880 self.ir_signature_to_abi_sig
881 .get(signature)
882 .copied()
883 .expect("must call `make_abi_sig_from_ir_signature` before `get_abi_sig_for_signature`")
884 }
885
886 pub fn from_func_sig<M: ABIMachineSpec>(
887 &mut self,
888 sig: &ir::Signature,
889 flags: &settings::Flags,
890 ) -> CodegenResult<SigData> {
891 // Keep in sync with ensure_struct_return_ptr_is_returned
892 if sig.uses_special_return(ArgumentPurpose::StructReturn) {
893 panic!("Explicit StructReturn return value not allowed: {sig:?}")
894 }
895 let tmp;
896 let returns = if let Some(struct_ret_index) =
897 sig.special_param_index(ArgumentPurpose::StructReturn)
898 {
899 if !sig.returns.is_empty() {
900 panic!("No return values are allowed when using StructReturn: {sig:?}");
901 }
902 tmp = [sig.params[struct_ret_index]];
903 &tmp
904 } else {
905 sig.returns.as_slice()
906 };
907
908 // Compute args and retvals from signature. Handle retvals first,
909 // because we may need to add a return-area arg to the args.
910
911 // NOTE: We rely on the order of the args (rets -> args) inserted to compute the offsets in
912 // `SigSet::args()` and `SigSet::rets()`. Therefore, we cannot change the two
913 // compute_arg_locs order.
914 let (sized_stack_ret_space, _) = M::compute_arg_locs(
915 sig.call_conv,
916 flags,
917 &returns,
918 ArgsOrRets::Rets,
919 /* extra ret-area ptr = */ false,
920 ArgsAccumulator::new(&mut self.abi_args),
921 )?;
922 if !flags.enable_multi_ret_implicit_sret() {
923 assert_eq!(sized_stack_ret_space, 0);
924 }
925 let rets_end = u32::try_from(self.abi_args.len()).unwrap();
926
927 // To avoid overflow issues, limit the return size to something reasonable.
928 if sized_stack_ret_space > M::STACK_ARG_RET_SIZE_LIMIT {
929 return Err(CodegenError::ImplLimitExceeded);
930 }
931
932 let need_stack_return_area = sized_stack_ret_space > 0;
933 if need_stack_return_area {
934 assert!(!sig.uses_special_param(ir::ArgumentPurpose::StructReturn));
935 }
936
937 let (sized_stack_arg_space, stack_ret_arg) = M::compute_arg_locs(
938 sig.call_conv,
939 flags,
940 &sig.params,
941 ArgsOrRets::Args,
942 need_stack_return_area,
943 ArgsAccumulator::new(&mut self.abi_args),
944 )?;
945 let args_end = u32::try_from(self.abi_args.len()).unwrap();
946
947 // To avoid overflow issues, limit the arg size to something reasonable.
948 if sized_stack_arg_space > M::STACK_ARG_RET_SIZE_LIMIT {
949 return Err(CodegenError::ImplLimitExceeded);
950 }
951
952 trace!(
953 "ABISig: sig {:?} => args end = {} rets end = {}
954 arg stack = {} ret stack = {} stack_ret_arg = {:?}",
955 sig,
956 args_end,
957 rets_end,
958 sized_stack_arg_space,
959 sized_stack_ret_space,
960 need_stack_return_area,
961 );
962
963 let stack_ret_arg = stack_ret_arg.map(|s| u16::try_from(s).unwrap());
964 Ok(SigData {
965 args_end,
966 rets_end,
967 sized_stack_arg_space,
968 sized_stack_ret_space,
969 stack_ret_arg,
970 call_conv: sig.call_conv,
971 })
972 }
973
974 /// Get this signature's ABI arguments.
975 pub fn args(&self, sig: Sig) -> &[ABIArg] {
976 let sig_data = &self.sigs[sig];
977 // Please see comments in `SigSet::from_func_sig` of how we store the offsets.
978 let start = usize::try_from(sig_data.rets_end).unwrap();
979 let end = usize::try_from(sig_data.args_end).unwrap();
980 &self.abi_args[start..end]
981 }
982
983 /// Get information specifying how to pass the implicit pointer
984 /// to the return-value area on the stack, if required.
985 pub fn get_ret_arg(&self, sig: Sig) -> Option<ABIArg> {
986 let sig_data = &self.sigs[sig];
987 if let Some(i) = sig_data.stack_ret_arg {
988 Some(self.args(sig)[usize::from(i)].clone())
989 } else {
990 None
991 }
992 }
993
994 /// Get information specifying how to pass one argument.
995 pub fn get_arg(&self, sig: Sig, idx: usize) -> ABIArg {
996 self.args(sig)[idx].clone()
997 }
998
999 /// Get this signature's ABI returns.
1000 pub fn rets(&self, sig: Sig) -> &[ABIArg] {
1001 let sig_data = &self.sigs[sig];
1002 // Please see comments in `SigSet::from_func_sig` of how we store the offsets.
1003 let start = usize::try_from(sig.prev().map_or(0, |prev| self.sigs[prev].args_end)).unwrap();
1004 let end = usize::try_from(sig_data.rets_end).unwrap();
1005 &self.abi_args[start..end]
1006 }
1007
1008 /// Get information specifying how to pass one return value.
1009 pub fn get_ret(&self, sig: Sig, idx: usize) -> ABIArg {
1010 self.rets(sig)[idx].clone()
1011 }
1012
1013 /// Get the number of arguments expected.
1014 pub fn num_args(&self, sig: Sig) -> usize {
1015 let len = self.args(sig).len();
1016 if self.sigs[sig].stack_ret_arg.is_some() {
1017 len - 1
1018 } else {
1019 len
1020 }
1021 }
1022
1023 /// Get the number of return values expected.
1024 pub fn num_rets(&self, sig: Sig) -> usize {
1025 self.rets(sig).len()
1026 }
1027}
1028
1029// NB: we do _not_ implement `IndexMut` because these signatures are
1030// deduplicated and shared!
1031impl core::ops::Index<Sig> for SigSet {
1032 type Output = SigData;
1033
1034 fn index(&self, sig: Sig) -> &Self::Output {
1035 &self.sigs[sig]
1036 }
1037}
1038
1039/// Structure describing the layout of a function's stack frame.
1040#[derive(Clone, Debug, Default)]
1041pub struct FrameLayout {
1042 /// Word size in bytes, so this struct can be
1043 /// monomorphic/independent of `ABIMachineSpec`.
1044 pub word_bytes: u32,
1045
1046 /// N.B. The areas whose sizes are given in this structure fully
1047 /// cover the current function's stack frame, from high to low
1048 /// stack addresses in the sequence below. Each size contains
1049 /// any alignment padding that may be required by the ABI.
1050
1051 /// Size of incoming arguments on the stack. This is not technically
1052 /// part of this function's frame, but code in the function will still
1053 /// need to access it. Depending on the ABI, we may need to set up a
1054 /// frame pointer to do so; we also may need to pop this area from the
1055 /// stack upon return.
1056 pub incoming_args_size: u32,
1057
1058 /// The size of the incoming argument area, taking into account any
1059 /// potential increase in size required for tail calls present in the
1060 /// function. In the case that no tail calls are present, this value
1061 /// will be the same as [`Self::incoming_args_size`].
1062 pub tail_args_size: u32,
1063
1064 /// Size of the "setup area", typically holding the return address
1065 /// and/or the saved frame pointer. This may be written either during
1066 /// the call itself (e.g. a pushed return address) or by code emitted
1067 /// from gen_prologue_frame_setup. In any case, after that code has
1068 /// completed execution, the stack pointer is expected to point to the
1069 /// bottom of this area. The same holds at the start of code emitted
1070 /// by gen_epilogue_frame_restore.
1071 pub setup_area_size: u32,
1072
1073 /// Size of the area used to save callee-saved clobbered registers.
1074 /// This area is accessed by code emitted from gen_clobber_save and
1075 /// gen_clobber_restore.
1076 pub clobber_size: u32,
1077
1078 /// Storage allocated for the fixed part of the stack frame.
1079 /// This contains stack slots and spill slots.
1080 pub fixed_frame_storage_size: u32,
1081
1082 /// The size of all stackslots.
1083 pub stackslots_size: u32,
1084
1085 /// Stack size to be reserved for outgoing arguments, if used by
1086 /// the current ABI, or 0 otherwise. After gen_clobber_save and
1087 /// before gen_clobber_restore, the stack pointer points to the
1088 /// bottom of this area.
1089 pub outgoing_args_size: u32,
1090
1091 /// Sorted list of callee-saved registers that are clobbered
1092 /// according to the ABI. These registers will be saved and
1093 /// restored by gen_clobber_save and gen_clobber_restore.
1094 pub clobbered_callee_saves: Vec<Writable<RealReg>>,
1095
1096 /// The function's call pattern classification.
1097 pub function_calls: FunctionCalls,
1098}
1099
1100impl FrameLayout {
1101 /// Split the clobbered callee-save registers into integer-class and
1102 /// float-class groups.
1103 ///
1104 /// This method does not currently support vector-class callee-save
1105 /// registers because no current backend has them.
1106 pub fn clobbered_callee_saves_by_class(&self) -> (&[Writable<RealReg>], &[Writable<RealReg>]) {
1107 let (ints, floats) = self.clobbered_callee_saves.split_at(
1108 self.clobbered_callee_saves
1109 .partition_point(|r| r.to_reg().class() == RegClass::Int),
1110 );
1111 debug_assert!(floats.iter().all(|r| r.to_reg().class() == RegClass::Float));
1112 (ints, floats)
1113 }
1114
1115 /// The size of FP to SP while the frame is active (not during prologue
1116 /// setup or epilogue tear down).
1117 pub fn active_size(&self) -> u32 {
1118 self.outgoing_args_size + self.fixed_frame_storage_size + self.clobber_size
1119 }
1120
1121 /// Get the offset from the SP to the sized stack slots area.
1122 pub fn sp_to_sized_stack_slots(&self) -> u32 {
1123 self.outgoing_args_size
1124 }
1125
1126 /// Get the offset of a spill slot from SP.
1127 pub fn spillslot_offset(&self, spillslot: SpillSlot) -> i64 {
1128 // Offset from beginning of spillslot area.
1129 let islot = spillslot.index() as i64;
1130 let spill_off = islot * self.word_bytes as i64;
1131 let sp_off = self.stackslots_size as i64 + spill_off;
1132
1133 sp_off
1134 }
1135
1136 /// Get the offset from SP up to FP.
1137 pub fn sp_to_fp(&self) -> u32 {
1138 self.outgoing_args_size + self.fixed_frame_storage_size + self.clobber_size
1139 }
1140}
1141
1142/// ABI object for a function body.
1143pub struct Callee<M: ABIMachineSpec> {
1144 /// CLIF-level signature, possibly normalized.
1145 ir_sig: ir::Signature,
1146 /// Signature: arg and retval regs.
1147 sig: Sig,
1148 /// Defined dynamic types.
1149 dynamic_type_sizes: HashMap<Type, u32>,
1150 /// Offsets to each dynamic stackslot.
1151 dynamic_stackslots: PrimaryMap<DynamicStackSlot, u32>,
1152 /// Offsets to each sized stackslot.
1153 sized_stackslots: PrimaryMap<StackSlot, u32>,
1154 /// Descriptors for sized stackslots.
1155 sized_stackslot_keys: SecondaryMap<StackSlot, Option<StackSlotKey>>,
1156 /// Total stack size of all stackslots
1157 stackslots_size: u32,
1158 /// Stack size to be reserved for outgoing arguments.
1159 outgoing_args_size: u32,
1160 /// Initially the number of bytes originating in the callers frame where stack arguments will
1161 /// live. After lowering this number may be larger than the size expected by the function being
1162 /// compiled, as tail calls potentially require more space for stack arguments.
1163 tail_args_size: u32,
1164 /// Register-argument defs, to be provided to the `args`
1165 /// pseudo-inst, and pregs to constrain them to.
1166 reg_args: Vec<ArgPair>,
1167 /// Finalized frame layout for this function.
1168 frame_layout: Option<FrameLayout>,
1169 /// The register holding the return-area pointer, if needed.
1170 ret_area_ptr: Option<Reg>,
1171 /// Calling convention this function expects.
1172 call_conv: isa::CallConv,
1173 /// The settings controlling this function's compilation.
1174 flags: settings::Flags,
1175 /// The ISA-specific flag values controlling this function's compilation.
1176 isa_flags: M::F,
1177 /// If this function has a stack limit specified, then `Reg` is where the
1178 /// stack limit will be located after the instructions specified have been
1179 /// executed.
1180 ///
1181 /// Note that this is intended for insertion into the prologue, if
1182 /// present. Also note that because the instructions here execute in the
1183 /// prologue this happens after legalization/register allocation/etc so we
1184 /// need to be extremely careful with each instruction. The instructions are
1185 /// manually register-allocated and carefully only use caller-saved
1186 /// registers and keep nothing live after this sequence of instructions.
1187 stack_limit: Option<(Reg, SmallInstVec<M::I>)>,
1188
1189 _mach: PhantomData<M>,
1190}
1191
1192fn get_special_purpose_param_register(
1193 f: &ir::Function,
1194 sigs: &SigSet,
1195 sig: Sig,
1196 purpose: ir::ArgumentPurpose,
1197) -> Option<Reg> {
1198 let idx = f.signature.special_param_index(purpose)?;
1199 match &sigs.args(sig)[idx] {
1200 &ABIArg::Slots { ref slots, .. } => match &slots[0] {
1201 &ABIArgSlot::Reg { reg, .. } => Some(reg.into()),
1202 _ => None,
1203 },
1204 _ => None,
1205 }
1206}
1207
1208fn checked_round_up(val: u32, mask: u32) -> Option<u32> {
1209 Some(val.checked_add(mask)? & !mask)
1210}
1211
1212impl<M: ABIMachineSpec> Callee<M> {
1213 /// Create a new body ABI instance.
1214 pub fn new(
1215 f: &ir::Function,
1216 isa: &dyn TargetIsa,
1217 isa_flags: &M::F,
1218 sigs: &SigSet,
1219 ) -> CodegenResult<Self> {
1220 trace!("ABI: func signature {:?}", f.signature);
1221
1222 let flags = isa.flags().clone();
1223 let sig = sigs.abi_sig_for_signature(&f.signature);
1224
1225 let call_conv = f.signature.call_conv;
1226 // Only these calling conventions are supported.
1227 debug_assert!(
1228 call_conv == isa::CallConv::SystemV
1229 || call_conv == isa::CallConv::Tail
1230 || call_conv == isa::CallConv::Fast
1231 || call_conv == isa::CallConv::WindowsFastcall
1232 || call_conv == isa::CallConv::AppleAarch64
1233 || call_conv == isa::CallConv::Winch
1234 || call_conv == isa::CallConv::PreserveAll,
1235 "Unsupported calling convention: {call_conv:?}"
1236 );
1237
1238 // Compute sized stackslot locations and total stackslot size.
1239 let mut end_offset: u32 = 0;
1240 let mut sized_stackslots = PrimaryMap::new();
1241 let mut sized_stackslot_keys = SecondaryMap::new();
1242
1243 for (stackslot, data) in f.sized_stack_slots.iter() {
1244 // We start our computation possibly unaligned where the previous
1245 // stackslot left off.
1246 let unaligned_start_offset = end_offset;
1247
1248 // The start of the stackslot must be aligned.
1249 //
1250 // We always at least machine-word-align slots, but also
1251 // satisfy the user's requested alignment.
1252 debug_assert!(data.align_shift < 32);
1253 let align = core::cmp::max(M::word_bytes(), 1u32 << data.align_shift);
1254 let mask = align - 1;
1255 let start_offset = checked_round_up(unaligned_start_offset, mask)
1256 .ok_or(CodegenError::ImplLimitExceeded)?;
1257
1258 // The end offset is the start offset increased by the size
1259 end_offset = start_offset
1260 .checked_add(data.size)
1261 .ok_or(CodegenError::ImplLimitExceeded)?;
1262
1263 debug_assert_eq!(stackslot.as_u32() as usize, sized_stackslots.len());
1264 sized_stackslots.push(start_offset);
1265 sized_stackslot_keys[stackslot] = data.key;
1266 }
1267
1268 // Compute dynamic stackslot locations and total stackslot size.
1269 let mut dynamic_stackslots = PrimaryMap::new();
1270 for (stackslot, data) in f.dynamic_stack_slots.iter() {
1271 debug_assert_eq!(stackslot.as_u32() as usize, dynamic_stackslots.len());
1272
1273 // This computation is similar to the stackslots above
1274 let unaligned_start_offset = end_offset;
1275
1276 let mask = M::word_bytes() - 1;
1277 let start_offset = checked_round_up(unaligned_start_offset, mask)
1278 .ok_or(CodegenError::ImplLimitExceeded)?;
1279
1280 let ty = f.get_concrete_dynamic_ty(data.dyn_ty).ok_or_else(|| {
1281 CodegenError::Unsupported(format!("invalid dynamic vector type: {}", data.dyn_ty))
1282 })?;
1283
1284 end_offset = start_offset
1285 .checked_add(isa.dynamic_vector_bytes(ty))
1286 .ok_or(CodegenError::ImplLimitExceeded)?;
1287
1288 dynamic_stackslots.push(start_offset);
1289 }
1290
1291 // The size of the stackslots needs to be word aligned
1292 let stackslots_size = checked_round_up(end_offset, M::word_bytes() - 1)
1293 .ok_or(CodegenError::ImplLimitExceeded)?;
1294
1295 let mut dynamic_type_sizes = HashMap::with_capacity(f.dfg.dynamic_types.len());
1296 for (dyn_ty, _data) in f.dfg.dynamic_types.iter() {
1297 let ty = f
1298 .get_concrete_dynamic_ty(dyn_ty)
1299 .unwrap_or_else(|| panic!("invalid dynamic vector type: {dyn_ty}"));
1300 let size = isa.dynamic_vector_bytes(ty);
1301 dynamic_type_sizes.insert(ty, size);
1302 }
1303
1304 // Figure out what instructions, if any, will be needed to check the
1305 // stack limit. This can either be specified as a special-purpose
1306 // argument or as a global value which often calculates the stack limit
1307 // from the arguments.
1308 let stack_limit = f
1309 .stack_limit
1310 .map(|gv| gen_stack_limit::<M>(f, sigs, sig, gv));
1311
1312 let tail_args_size = sigs[sig].sized_stack_arg_space;
1313
1314 Ok(Self {
1315 ir_sig: ensure_struct_return_ptr_is_returned(&f.signature),
1316 sig,
1317 dynamic_stackslots,
1318 dynamic_type_sizes,
1319 sized_stackslots,
1320 sized_stackslot_keys,
1321 stackslots_size,
1322 outgoing_args_size: 0,
1323 tail_args_size,
1324 reg_args: vec![],
1325 frame_layout: None,
1326 ret_area_ptr: None,
1327 call_conv,
1328 flags,
1329 isa_flags: isa_flags.clone(),
1330 stack_limit,
1331 _mach: PhantomData,
1332 })
1333 }
1334
1335 /// Inserts instructions necessary for checking the stack limit into the
1336 /// prologue.
1337 ///
1338 /// This function will generate instructions necessary for perform a stack
1339 /// check at the header of a function. The stack check is intended to trap
1340 /// if the stack pointer goes below a particular threshold, preventing stack
1341 /// overflow in wasm or other code. The `stack_limit` argument here is the
1342 /// register which holds the threshold below which we're supposed to trap.
1343 /// This function is known to allocate `stack_size` bytes and we'll push
1344 /// instructions onto `insts`.
1345 ///
1346 /// Note that the instructions generated here are special because this is
1347 /// happening so late in the pipeline (e.g. after register allocation). This
1348 /// means that we need to do manual register allocation here and also be
1349 /// careful to not clobber any callee-saved or argument registers. For now
1350 /// this routine makes do with the `spilltmp_reg` as one temporary
1351 /// register, and a second register of `tmp2` which is caller-saved. This
1352 /// should be fine for us since no spills should happen in this sequence of
1353 /// instructions, so our register won't get accidentally clobbered.
1354 ///
1355 /// No values can be live after the prologue, but in this case that's ok
1356 /// because we just need to perform a stack check before progressing with
1357 /// the rest of the function.
1358 fn insert_stack_check(
1359 &self,
1360 stack_limit: Reg,
1361 stack_size: u32,
1362 insts: &mut SmallInstVec<M::I>,
1363 ) {
1364 // With no explicit stack allocated we can just emit the simple check of
1365 // the stack registers against the stack limit register, and trap if
1366 // it's out of bounds.
1367 if stack_size == 0 {
1368 insts.extend(M::gen_stack_lower_bound_trap(stack_limit));
1369 return;
1370 }
1371
1372 // Note that the 32k stack size here is pretty special. See the
1373 // documentation in x86/abi.rs for why this is here. The general idea is
1374 // that we're protecting against overflow in the addition that happens
1375 // below.
1376 if stack_size >= 32 * 1024 {
1377 insts.extend(M::gen_stack_lower_bound_trap(stack_limit));
1378 }
1379
1380 // Add the `stack_size` to `stack_limit`, placing the result in
1381 // `scratch`.
1382 //
1383 // Note though that `stack_limit`'s register may be the same as
1384 // `scratch`. If our stack size doesn't fit into an immediate this
1385 // means we need a second scratch register for loading the stack size
1386 // into a register.
1387 let scratch = Writable::from_reg(M::get_stacklimit_reg(self.call_conv));
1388 insts.extend(M::gen_add_imm(
1389 self.call_conv,
1390 scratch,
1391 stack_limit,
1392 stack_size,
1393 ));
1394 insts.extend(M::gen_stack_lower_bound_trap(scratch.to_reg()));
1395 }
1396}
1397
1398/// Generates the instructions necessary for the `gv` to be materialized into a
1399/// register.
1400///
1401/// This function will return a register that will contain the result of
1402/// evaluating `gv`. It will also return any instructions necessary to calculate
1403/// the value of the register.
1404///
1405/// Note that global values are typically lowered to instructions via the
1406/// standard legalization pass. Unfortunately though prologue generation happens
1407/// so late in the pipeline that we can't use these legalization passes to
1408/// generate the instructions for `gv`. As a result we duplicate some lowering
1409/// of `gv` here and support only some global values. This is similar to what
1410/// the x86 backend does for now, and hopefully this can be somewhat cleaned up
1411/// in the future too!
1412///
1413/// Also note that this function will make use of `writable_spilltmp_reg()` as a
1414/// temporary register to store values in if necessary. Currently after we write
1415/// to this register there's guaranteed to be no spilled values between where
1416/// it's used, because we're not participating in register allocation anyway!
1417fn gen_stack_limit<M: ABIMachineSpec>(
1418 f: &ir::Function,
1419 sigs: &SigSet,
1420 sig: Sig,
1421 gv: ir::GlobalValue,
1422) -> (Reg, SmallInstVec<M::I>) {
1423 let mut insts = smallvec![];
1424 let reg = generate_gv::<M>(f, sigs, sig, gv, &mut insts);
1425 return (reg, insts);
1426}
1427
1428fn generate_gv<M: ABIMachineSpec>(
1429 f: &ir::Function,
1430 sigs: &SigSet,
1431 sig: Sig,
1432 gv: ir::GlobalValue,
1433 insts: &mut SmallInstVec<M::I>,
1434) -> Reg {
1435 match f.global_values[gv] {
1436 // Return the direct register the vmcontext is in
1437 ir::GlobalValueData::VMContext => {
1438 get_special_purpose_param_register(f, sigs, sig, ir::ArgumentPurpose::VMContext)
1439 .expect("no vmcontext parameter found")
1440 }
1441 // Load our base value into a register, then load from that register
1442 // in to a temporary register.
1443 ir::GlobalValueData::Load {
1444 base,
1445 offset,
1446 global_type: _,
1447 flags: _,
1448 } => {
1449 let base = generate_gv::<M>(f, sigs, sig, base, insts);
1450 let into_reg = Writable::from_reg(M::get_stacklimit_reg(f.stencil.signature.call_conv));
1451 insts.push(M::gen_load_base_offset(
1452 into_reg,
1453 base,
1454 offset.into(),
1455 M::word_type(),
1456 ));
1457 return into_reg.to_reg();
1458 }
1459 ref other => panic!("global value for stack limit not supported: {other}"),
1460 }
1461}
1462
1463/// Returns true if the signature needs to be legalized.
1464fn missing_struct_return(sig: &ir::Signature) -> bool {
1465 sig.uses_special_param(ArgumentPurpose::StructReturn)
1466 && !sig.uses_special_return(ArgumentPurpose::StructReturn)
1467}
1468
1469fn ensure_struct_return_ptr_is_returned(sig: &ir::Signature) -> ir::Signature {
1470 // Keep in sync with Callee::new
1471 let mut sig = sig.clone();
1472 if sig.uses_special_return(ArgumentPurpose::StructReturn) {
1473 panic!("Explicit StructReturn return value not allowed: {sig:?}")
1474 }
1475 if let Some(struct_ret_index) = sig.special_param_index(ArgumentPurpose::StructReturn) {
1476 if !sig.returns.is_empty() {
1477 panic!("No return values are allowed when using StructReturn: {sig:?}");
1478 }
1479 sig.returns.insert(0, sig.params[struct_ret_index]);
1480 }
1481 sig
1482}
1483
1484/// ### Pre-Regalloc Functions
1485///
1486/// These methods of `Callee` may only be called before regalloc.
1487impl<M: ABIMachineSpec> Callee<M> {
1488 /// Access the (possibly legalized) signature.
1489 pub fn signature(&self) -> &ir::Signature {
1490 debug_assert!(
1491 !missing_struct_return(&self.ir_sig),
1492 "`Callee::ir_sig` is always legalized"
1493 );
1494 &self.ir_sig
1495 }
1496
1497 /// Initialize. This is called after the Callee is constructed because it
1498 /// may allocate a temp vreg, which can only be allocated once the lowering
1499 /// context exists.
1500 pub fn init_retval_area(
1501 &mut self,
1502 sigs: &SigSet,
1503 vregs: &mut VRegAllocator<M::I>,
1504 ) -> CodegenResult<()> {
1505 if sigs[self.sig].stack_ret_arg.is_some() {
1506 let ret_area_ptr = vregs.alloc(M::word_type())?;
1507 self.ret_area_ptr = Some(ret_area_ptr.only_reg().unwrap());
1508 }
1509 Ok(())
1510 }
1511
1512 /// Get the return area pointer register, if any.
1513 pub fn ret_area_ptr(&self) -> Option<Reg> {
1514 self.ret_area_ptr
1515 }
1516
1517 /// Accumulate outgoing arguments.
1518 ///
1519 /// This ensures that at least `size` bytes are allocated in the prologue to
1520 /// be available for use in function calls to hold arguments and/or return
1521 /// values. If this function is called multiple times, the maximum of all
1522 /// `size` values will be available.
1523 pub fn accumulate_outgoing_args_size(&mut self, size: u32) {
1524 if size > self.outgoing_args_size {
1525 self.outgoing_args_size = size;
1526 }
1527 }
1528
1529 /// Accumulate the incoming argument area size requirements for a tail call,
1530 /// as it could be larger than the incoming arguments of the function
1531 /// currently being compiled.
1532 pub fn accumulate_tail_args_size(&mut self, size: u32) {
1533 if size > self.tail_args_size {
1534 self.tail_args_size = size;
1535 }
1536 }
1537
1538 pub fn is_forward_edge_cfi_enabled(&self) -> bool {
1539 self.isa_flags.is_forward_edge_cfi_enabled()
1540 }
1541
1542 /// Get the calling convention implemented by this ABI object.
1543 pub fn call_conv(&self) -> isa::CallConv {
1544 self.call_conv
1545 }
1546
1547 /// Get the ABI-dependent MachineEnv for managing register allocation.
1548 pub fn machine_env(&self) -> &MachineEnv {
1549 M::get_machine_env(&self.flags, self.call_conv)
1550 }
1551
1552 /// The offsets of all sized stack slots (not spill slots) for debuginfo purposes.
1553 pub fn sized_stackslot_offsets(&self) -> &PrimaryMap<StackSlot, u32> {
1554 &self.sized_stackslots
1555 }
1556
1557 /// The offsets of all dynamic stack slots (not spill slots) for debuginfo purposes.
1558 pub fn dynamic_stackslot_offsets(&self) -> &PrimaryMap<DynamicStackSlot, u32> {
1559 &self.dynamic_stackslots
1560 }
1561
1562 /// Generate an instruction which copies an argument to a destination
1563 /// register.
1564 pub fn gen_copy_arg_to_regs(
1565 &mut self,
1566 sigs: &SigSet,
1567 idx: usize,
1568 into_regs: ValueRegs<Writable<Reg>>,
1569 vregs: &mut VRegAllocator<M::I>,
1570 ) -> SmallInstVec<M::I> {
1571 let mut insts = smallvec![];
1572 let mut copy_arg_slot_to_reg = |slot: &ABIArgSlot, into_reg: &Writable<Reg>| {
1573 match slot {
1574 &ABIArgSlot::Reg { reg, .. } => {
1575 // Add a preg -> def pair to the eventual `args`
1576 // instruction. Extension mode doesn't matter
1577 // (we're copying out, not in; we ignore high bits
1578 // by convention).
1579 let arg = ArgPair {
1580 vreg: *into_reg,
1581 preg: reg.into(),
1582 };
1583 self.reg_args.push(arg);
1584 }
1585 &ABIArgSlot::Stack {
1586 offset,
1587 ty,
1588 extension,
1589 ..
1590 } => {
1591 // However, we have to respect the extension mode for stack
1592 // slots, or else we grab the wrong bytes on big-endian.
1593 let ext = M::get_ext_mode(sigs[self.sig].call_conv, extension);
1594 let ty =
1595 if ext != ArgumentExtension::None && M::word_bits() > ty_bits(ty) as u32 {
1596 M::word_type()
1597 } else {
1598 ty
1599 };
1600 insts.push(M::gen_load_stack(
1601 StackAMode::IncomingArg(offset, sigs[self.sig].sized_stack_arg_space),
1602 *into_reg,
1603 ty,
1604 ));
1605 }
1606 }
1607 };
1608
1609 match &sigs.args(self.sig)[idx] {
1610 &ABIArg::Slots { ref slots, .. } => {
1611 assert_eq!(into_regs.len(), slots.len());
1612 for (slot, into_reg) in slots.iter().zip(into_regs.regs().iter()) {
1613 copy_arg_slot_to_reg(&slot, &into_reg);
1614 }
1615 }
1616 &ABIArg::StructArg { offset, .. } => {
1617 let into_reg = into_regs.only_reg().unwrap();
1618 // Buffer address is implicitly defined by the ABI.
1619 insts.push(M::gen_get_stack_addr(
1620 StackAMode::IncomingArg(offset, sigs[self.sig].sized_stack_arg_space),
1621 into_reg,
1622 ));
1623 }
1624 &ABIArg::ImplicitPtrArg { pointer, ty, .. } => {
1625 let into_reg = into_regs.only_reg().unwrap();
1626 // We need to dereference the pointer.
1627 let base = match &pointer {
1628 &ABIArgSlot::Reg { reg, ty, .. } => {
1629 let tmp = vregs.alloc_with_deferred_error(ty).only_reg().unwrap();
1630 self.reg_args.push(ArgPair {
1631 vreg: Writable::from_reg(tmp),
1632 preg: reg.into(),
1633 });
1634 tmp
1635 }
1636 &ABIArgSlot::Stack { offset, ty, .. } => {
1637 let addr_reg = writable_value_regs(vregs.alloc_with_deferred_error(ty))
1638 .only_reg()
1639 .unwrap();
1640 insts.push(M::gen_load_stack(
1641 StackAMode::IncomingArg(offset, sigs[self.sig].sized_stack_arg_space),
1642 addr_reg,
1643 ty,
1644 ));
1645 addr_reg.to_reg()
1646 }
1647 };
1648 insts.push(M::gen_load_base_offset(into_reg, base, 0, ty));
1649 }
1650 }
1651 insts
1652 }
1653
1654 /// Generate an instruction which copies a source register to a return value slot.
1655 pub fn gen_copy_regs_to_retval(
1656 &self,
1657 sigs: &SigSet,
1658 idx: usize,
1659 from_regs: ValueRegs<Reg>,
1660 vregs: &mut VRegAllocator<M::I>,
1661 ) -> (SmallVec<[RetPair; 2]>, SmallInstVec<M::I>) {
1662 let mut reg_pairs = smallvec![];
1663 let mut ret = smallvec![];
1664 let word_bits = M::word_bits() as u8;
1665 match &sigs.rets(self.sig)[idx] {
1666 &ABIArg::Slots { ref slots, .. } => {
1667 assert_eq!(from_regs.len(), slots.len());
1668 for (slot, &from_reg) in slots.iter().zip(from_regs.regs().iter()) {
1669 match slot {
1670 &ABIArgSlot::Reg {
1671 reg, ty, extension, ..
1672 } => {
1673 let from_bits = ty_bits(ty) as u8;
1674 let ext = M::get_ext_mode(sigs[self.sig].call_conv, extension);
1675 let vreg = match (ext, from_bits) {
1676 (ir::ArgumentExtension::Uext, n)
1677 | (ir::ArgumentExtension::Sext, n)
1678 if n < word_bits =>
1679 {
1680 let signed = ext == ir::ArgumentExtension::Sext;
1681 let dst =
1682 writable_value_regs(vregs.alloc_with_deferred_error(ty))
1683 .only_reg()
1684 .unwrap();
1685 ret.push(M::gen_extend(
1686 dst, from_reg, signed, from_bits,
1687 /* to_bits = */ word_bits,
1688 ));
1689 dst.to_reg()
1690 }
1691 _ => {
1692 // No move needed, regalloc2 will emit it using the constraint
1693 // added by the RetPair.
1694 from_reg
1695 }
1696 };
1697 reg_pairs.push(RetPair {
1698 vreg,
1699 preg: Reg::from(reg),
1700 });
1701 }
1702 &ABIArgSlot::Stack {
1703 offset,
1704 ty,
1705 extension,
1706 ..
1707 } => {
1708 let mut ty = ty;
1709 let from_bits = ty_bits(ty) as u8;
1710 // A machine ABI implementation should ensure that stack frames
1711 // have "reasonable" size. All current ABIs for machinst
1712 // backends (aarch64 and x64) enforce a 128MB limit.
1713 let off = i32::try_from(offset).expect(
1714 "Argument stack offset greater than 2GB; should hit impl limit first",
1715 );
1716 let ext = M::get_ext_mode(sigs[self.sig].call_conv, extension);
1717 // Trash the from_reg; it should be its last use.
1718 match (ext, from_bits) {
1719 (ir::ArgumentExtension::Uext, n)
1720 | (ir::ArgumentExtension::Sext, n)
1721 if n < word_bits =>
1722 {
1723 assert_eq!(M::word_reg_class(), from_reg.class());
1724 let signed = ext == ir::ArgumentExtension::Sext;
1725 let dst =
1726 writable_value_regs(vregs.alloc_with_deferred_error(ty))
1727 .only_reg()
1728 .unwrap();
1729 ret.push(M::gen_extend(
1730 dst, from_reg, signed, from_bits,
1731 /* to_bits = */ word_bits,
1732 ));
1733 // Store the extended version.
1734 ty = M::word_type();
1735 }
1736 _ => {}
1737 };
1738 ret.push(M::gen_store_base_offset(
1739 self.ret_area_ptr.unwrap(),
1740 off,
1741 from_reg,
1742 ty,
1743 ));
1744 }
1745 }
1746 }
1747 }
1748 ABIArg::StructArg { .. } => {
1749 panic!("StructArg in return position is unsupported");
1750 }
1751 ABIArg::ImplicitPtrArg { .. } => {
1752 panic!("ImplicitPtrArg in return position is unsupported");
1753 }
1754 }
1755 (reg_pairs, ret)
1756 }
1757
1758 /// Generate any setup instruction needed to save values to the
1759 /// return-value area. This is usually used when were are multiple return
1760 /// values or an otherwise large return value that must be passed on the
1761 /// stack; typically the ABI specifies an extra hidden argument that is a
1762 /// pointer to that memory.
1763 pub fn gen_retval_area_setup(
1764 &mut self,
1765 sigs: &SigSet,
1766 vregs: &mut VRegAllocator<M::I>,
1767 ) -> Option<M::I> {
1768 if let Some(i) = sigs[self.sig].stack_ret_arg {
1769 let ret_area_ptr = Writable::from_reg(self.ret_area_ptr.unwrap());
1770 let insts =
1771 self.gen_copy_arg_to_regs(sigs, i.into(), ValueRegs::one(ret_area_ptr), vregs);
1772 insts.into_iter().next().map(|inst| {
1773 trace!(
1774 "gen_retval_area_setup: inst {:?}; ptr reg is {:?}",
1775 inst,
1776 ret_area_ptr.to_reg()
1777 );
1778 inst
1779 })
1780 } else {
1781 trace!("gen_retval_area_setup: not needed");
1782 None
1783 }
1784 }
1785
1786 /// Generate a return instruction.
1787 pub fn gen_rets(&self, rets: Vec<RetPair>) -> M::I {
1788 M::gen_rets(rets)
1789 }
1790
1791 /// Set up arguments values `args` for a call with signature `sig`.
1792 /// This will return a series of instructions to be emitted to set
1793 /// up all arguments, as well as a `CallArgList` list representing
1794 /// the arguments passed in registers. The latter need to be added
1795 /// as constraints to the actual call instruction.
1796 pub fn gen_call_args(
1797 &self,
1798 sigs: &SigSet,
1799 sig: Sig,
1800 args: &[ValueRegs<Reg>],
1801 is_tail_call: bool,
1802 flags: &settings::Flags,
1803 vregs: &mut VRegAllocator<M::I>,
1804 ) -> (CallArgList, SmallInstVec<M::I>) {
1805 let mut uses: CallArgList = smallvec![];
1806 let mut insts = smallvec![];
1807
1808 assert_eq!(args.len(), sigs.num_args(sig));
1809
1810 let call_conv = sigs[sig].call_conv;
1811 let stack_arg_space = sigs[sig].sized_stack_arg_space;
1812 let stack_arg = |offset| {
1813 if is_tail_call {
1814 StackAMode::IncomingArg(offset, stack_arg_space)
1815 } else {
1816 StackAMode::OutgoingArg(offset)
1817 }
1818 };
1819
1820 let word_ty = M::word_type();
1821 let word_rc = M::word_reg_class();
1822 let word_bits = M::word_bits() as usize;
1823
1824 if is_tail_call {
1825 debug_assert_eq!(
1826 self.call_conv,
1827 isa::CallConv::Tail,
1828 "Can only do `return_call`s from within a `tail` calling convention function"
1829 );
1830 }
1831
1832 // Helper to process a single argument slot (register or stack slot).
1833 // This will either add the register to the `uses` list or write the
1834 // value to the stack slot in the outgoing argument area (or for tail
1835 // calls, the incoming argument area).
1836 let mut process_arg_slot = |insts: &mut SmallInstVec<M::I>, slot, vreg, ty| {
1837 match &slot {
1838 &ABIArgSlot::Reg { reg, .. } => {
1839 uses.push(CallArgPair {
1840 vreg,
1841 preg: reg.into(),
1842 });
1843 }
1844 &ABIArgSlot::Stack { offset, .. } => {
1845 insts.push(M::gen_store_stack(stack_arg(offset), vreg, ty));
1846 }
1847 };
1848 };
1849
1850 // First pass: Handle `StructArg` arguments. These need to be copied
1851 // into their associated stack buffers. This should happen before any
1852 // of the other arguments are processed, as the `memcpy` call might
1853 // clobber registers used by other arguments.
1854 for (idx, from_regs) in args.iter().enumerate() {
1855 match &sigs.args(sig)[idx] {
1856 &ABIArg::Slots { .. } | &ABIArg::ImplicitPtrArg { .. } => {}
1857 &ABIArg::StructArg { offset, size, .. } => {
1858 let tmp = vregs.alloc_with_deferred_error(word_ty).only_reg().unwrap();
1859 insts.push(M::gen_get_stack_addr(
1860 stack_arg(offset),
1861 Writable::from_reg(tmp),
1862 ));
1863 insts.extend(M::gen_memcpy(
1864 isa::CallConv::for_libcall(flags, call_conv),
1865 tmp,
1866 from_regs.only_reg().unwrap(),
1867 size as usize,
1868 |ty| {
1869 Writable::from_reg(
1870 vregs.alloc_with_deferred_error(ty).only_reg().unwrap(),
1871 )
1872 },
1873 ));
1874 }
1875 }
1876 }
1877
1878 // Second pass: Handle everything except `StructArg` arguments.
1879 for (idx, from_regs) in args.iter().enumerate() {
1880 match sigs.args(sig)[idx] {
1881 ABIArg::Slots { ref slots, .. } => {
1882 assert_eq!(from_regs.len(), slots.len());
1883 for (slot, from_reg) in slots.iter().zip(from_regs.regs().iter()) {
1884 // Load argument slot value from `from_reg`, and perform any zero-
1885 // or sign-extension that is required by the ABI.
1886 let (ty, extension) = match *slot {
1887 ABIArgSlot::Reg { ty, extension, .. } => (ty, extension),
1888 ABIArgSlot::Stack { ty, extension, .. } => (ty, extension),
1889 };
1890 let ext = M::get_ext_mode(call_conv, extension);
1891 let (vreg, ty) = if ext != ir::ArgumentExtension::None
1892 && ty_bits(ty) < word_bits
1893 {
1894 assert_eq!(word_rc, from_reg.class());
1895 let signed = match ext {
1896 ir::ArgumentExtension::Uext => false,
1897 ir::ArgumentExtension::Sext => true,
1898 _ => unreachable!(),
1899 };
1900 let tmp = vregs.alloc_with_deferred_error(word_ty).only_reg().unwrap();
1901 insts.push(M::gen_extend(
1902 Writable::from_reg(tmp),
1903 *from_reg,
1904 signed,
1905 ty_bits(ty) as u8,
1906 word_bits as u8,
1907 ));
1908 (tmp, word_ty)
1909 } else {
1910 (*from_reg, ty)
1911 };
1912 process_arg_slot(&mut insts, *slot, vreg, ty);
1913 }
1914 }
1915 ABIArg::ImplicitPtrArg {
1916 offset,
1917 pointer,
1918 ty,
1919 ..
1920 } => {
1921 let vreg = from_regs.only_reg().unwrap();
1922 let tmp = vregs.alloc_with_deferred_error(word_ty).only_reg().unwrap();
1923 insts.push(M::gen_get_stack_addr(
1924 stack_arg(offset),
1925 Writable::from_reg(tmp),
1926 ));
1927 insts.push(M::gen_store_base_offset(tmp, 0, vreg, ty));
1928 process_arg_slot(&mut insts, pointer, tmp, word_ty);
1929 }
1930 ABIArg::StructArg { .. } => {}
1931 }
1932 }
1933
1934 // Finally, set the stack-return pointer to the return argument area.
1935 // For tail calls, this means forwarding the incoming stack-return pointer.
1936 if let Some(ret_arg) = sigs.get_ret_arg(sig) {
1937 let ret_area = if is_tail_call {
1938 self.ret_area_ptr.expect(
1939 "if the tail callee has a return pointer, then the tail caller must as well",
1940 )
1941 } else {
1942 let tmp = vregs.alloc_with_deferred_error(word_ty).only_reg().unwrap();
1943 let amode = StackAMode::OutgoingArg(stack_arg_space.into());
1944 insts.push(M::gen_get_stack_addr(amode, Writable::from_reg(tmp)));
1945 tmp
1946 };
1947 match ret_arg {
1948 // The return pointer must occupy a single slot.
1949 ABIArg::Slots { slots, .. } => {
1950 assert_eq!(slots.len(), 1);
1951 process_arg_slot(&mut insts, slots[0], ret_area, word_ty);
1952 }
1953 _ => unreachable!(),
1954 }
1955 }
1956
1957 (uses, insts)
1958 }
1959
1960 /// Set up return values `outputs` for a call with signature `sig`.
1961 /// This does not emit (or return) any instructions, but returns a
1962 /// `CallRetList` representing the return value constraints. This
1963 /// needs to be added to the actual call instruction.
1964 ///
1965 /// If `try_call_payloads` is non-zero, it is expected to hold
1966 /// exception payload registers for try_call instructions. These
1967 /// will be added as needed to the `CallRetList` as well.
1968 pub fn gen_call_rets(
1969 &self,
1970 sigs: &SigSet,
1971 sig: Sig,
1972 outputs: &[ValueRegs<Reg>],
1973 try_call_payloads: Option<&[Writable<Reg>]>,
1974 vregs: &mut VRegAllocator<M::I>,
1975 ) -> CallRetList {
1976 let callee_conv = sigs[sig].call_conv;
1977 let stack_arg_space = sigs[sig].sized_stack_arg_space;
1978
1979 let word_ty = M::word_type();
1980 let word_bits = M::word_bits() as usize;
1981
1982 let mut defs: CallRetList = smallvec![];
1983 let mut outputs = outputs.into_iter();
1984 let num_rets = sigs.num_rets(sig);
1985 for idx in 0..num_rets {
1986 let ret = sigs.rets(sig)[idx].clone();
1987 match ret {
1988 ABIArg::Slots {
1989 ref slots, purpose, ..
1990 } => {
1991 // We do not use the returned copy of the return buffer pointer,
1992 // so skip any StructReturn returns that may be present.
1993 if purpose == ArgumentPurpose::StructReturn {
1994 continue;
1995 }
1996 let retval_regs = outputs.next().unwrap();
1997 assert_eq!(retval_regs.len(), slots.len());
1998 for (slot, retval_reg) in slots.iter().zip(retval_regs.regs().iter()) {
1999 // We do not perform any extension because we're copying out, not in,
2000 // and we ignore high bits in our own registers by convention. However,
2001 // we still need to use the proper extended type to access stack slots
2002 // (this is critical on big-endian systems).
2003 let (ty, extension) = match *slot {
2004 ABIArgSlot::Reg { ty, extension, .. } => (ty, extension),
2005 ABIArgSlot::Stack { ty, extension, .. } => (ty, extension),
2006 };
2007 let ext = M::get_ext_mode(callee_conv, extension);
2008 let ty = if ext != ir::ArgumentExtension::None && ty_bits(ty) < word_bits {
2009 word_ty
2010 } else {
2011 ty
2012 };
2013
2014 match slot {
2015 &ABIArgSlot::Reg { reg, .. } => {
2016 defs.push(CallRetPair {
2017 vreg: Writable::from_reg(*retval_reg),
2018 location: RetLocation::Reg(reg.into(), ty),
2019 });
2020 }
2021 &ABIArgSlot::Stack { offset, .. } => {
2022 let amode =
2023 StackAMode::OutgoingArg(offset + i64::from(stack_arg_space));
2024 defs.push(CallRetPair {
2025 vreg: Writable::from_reg(*retval_reg),
2026 location: RetLocation::Stack(amode, ty),
2027 });
2028 }
2029 }
2030 }
2031 }
2032 ABIArg::StructArg { .. } => {
2033 panic!("StructArg not supported in return position");
2034 }
2035 ABIArg::ImplicitPtrArg { .. } => {
2036 panic!("ImplicitPtrArg not supported in return position");
2037 }
2038 }
2039 }
2040 assert!(outputs.next().is_none());
2041
2042 if let Some(try_call_payloads) = try_call_payloads {
2043 // Let `M` say where the payload values are going to end up and then
2044 // double-check it's the same size as the calling convention's
2045 // reported number of exception types.
2046 let pregs = M::exception_payload_regs(callee_conv);
2047 assert_eq!(
2048 callee_conv.exception_payload_types(M::word_type()).len(),
2049 pregs.len()
2050 );
2051
2052 // We need to update `defs` to contain the exception
2053 // payload regs as well. We have two sources of info that
2054 // we join:
2055 //
2056 // - The machine-specific ABI implementation `M`, which
2057 // tells us the particular registers that payload values
2058 // must be in
2059 // - The passed-in lowering context, which gives us the
2060 // vregs we must define.
2061 //
2062 // Note that payload values may need to end up in the same
2063 // physical registers as ordinary return values; this is
2064 // not a conflict, because we either get one or the
2065 // other. For regalloc's purposes, we define both starting
2066 // here at the callsite, but we can share one def in the
2067 // `defs` list and alias one vreg to another. Thus we
2068 // handle the two cases below for each payload register:
2069 // overlaps a return value (and we alias to it) or not
2070 // (and we add a def).
2071 for (i, &preg) in pregs.iter().enumerate() {
2072 let vreg = try_call_payloads[i];
2073 if let Some(existing) = defs.iter().find(|def| match def.location {
2074 RetLocation::Reg(r, _) => r == preg,
2075 _ => false,
2076 }) {
2077 vregs.set_vreg_alias(vreg.to_reg(), existing.vreg.to_reg());
2078 } else {
2079 defs.push(CallRetPair {
2080 vreg,
2081 location: RetLocation::Reg(preg, word_ty),
2082 });
2083 }
2084 }
2085 }
2086
2087 defs
2088 }
2089
2090 /// Populate a `CallInfo` for a call with signature `sig`.
2091 ///
2092 /// `dest` is the target-specific call destination value
2093 /// `uses` is the `CallArgList` describing argument constraints
2094 /// `defs` is the `CallRetList` describing return constraints
2095 /// `try_call_info` describes exception targets for try_call instructions
2096 /// `patchable` describes whether this callsite should emit metadata
2097 /// for patching to enable/disable it.
2098 ///
2099 /// The clobber list is computed here from the above data.
2100 pub fn gen_call_info<T>(
2101 &self,
2102 sigs: &SigSet,
2103 sig: Sig,
2104 dest: T,
2105 uses: CallArgList,
2106 defs: CallRetList,
2107 try_call_info: Option<TryCallInfo>,
2108 patchable: bool,
2109 ) -> CallInfo<T> {
2110 let caller_conv = self.call_conv;
2111 let callee_conv = sigs[sig].call_conv;
2112 let stack_arg_space = sigs[sig].sized_stack_arg_space;
2113
2114 let clobbers = {
2115 // Get clobbers: all caller-saves. These may include return value
2116 // regs, which we will remove from the clobber set below.
2117 let mut clobbers =
2118 <M>::get_regs_clobbered_by_call(callee_conv, try_call_info.is_some());
2119
2120 // Remove retval regs from clobbers.
2121 for def in &defs {
2122 if let RetLocation::Reg(preg, _) = def.location {
2123 clobbers.remove(PReg::from(preg.to_real_reg().unwrap()));
2124 }
2125 }
2126
2127 clobbers
2128 };
2129
2130 // Any adjustment to SP to account for required outgoing arguments/stack return values must
2131 // be done inside of the call pseudo-op, to ensure that SP is always in a consistent
2132 // state for all other instructions. For example, if a tail-call abi function is called
2133 // here, the reclamation of the outgoing argument area must be done inside of the call
2134 // pseudo-op's emission to ensure that SP is consistent at all other points in the lowered
2135 // function. (Except the prologue and epilogue, but those are fairly special parts of the
2136 // function that establish the SP invariants that are relied on elsewhere and are generated
2137 // after the register allocator has run and thus cannot have register allocator-inserted
2138 // references to SP offsets.)
2139
2140 let callee_pop_size = if callee_conv == isa::CallConv::Tail {
2141 // The tail calling convention has callees pop stack arguments.
2142 stack_arg_space
2143 } else {
2144 0
2145 };
2146
2147 CallInfo {
2148 dest,
2149 uses,
2150 defs,
2151 clobbers,
2152 callee_conv,
2153 caller_conv,
2154 callee_pop_size,
2155 try_call_info,
2156 patchable,
2157 }
2158 }
2159
2160 /// Get the raw offset of a sized stackslot in the slot region.
2161 pub fn sized_stackslot_offset(&self, slot: StackSlot) -> u32 {
2162 self.sized_stackslots[slot]
2163 }
2164
2165 /// Produce an instruction that computes a sized stackslot address.
2166 pub fn sized_stackslot_addr(
2167 &self,
2168 slot: StackSlot,
2169 offset: u32,
2170 into_reg: Writable<Reg>,
2171 ) -> M::I {
2172 // Offset from beginning of stackslot area.
2173 let stack_off = self.sized_stackslots[slot] as i64;
2174 let sp_off: i64 = stack_off + (offset as i64);
2175 M::gen_get_stack_addr(StackAMode::Slot(sp_off), into_reg)
2176 }
2177
2178 /// Produce an instruction that computes a dynamic stackslot address.
2179 pub fn dynamic_stackslot_addr(&self, slot: DynamicStackSlot, into_reg: Writable<Reg>) -> M::I {
2180 let stack_off = self.dynamic_stackslots[slot] as i64;
2181 M::gen_get_stack_addr(StackAMode::Slot(stack_off), into_reg)
2182 }
2183
2184 /// Get an `args` pseudo-inst, if any, that should appear at the
2185 /// very top of the function body prior to regalloc.
2186 pub fn take_args(&mut self) -> Option<M::I> {
2187 if self.reg_args.len() > 0 {
2188 // Very first instruction is an `args` pseudo-inst that
2189 // establishes live-ranges for in-register arguments and
2190 // constrains them at the start of the function to the
2191 // locations defined by the ABI.
2192 Some(M::gen_args(core::mem::take(&mut self.reg_args)))
2193 } else {
2194 None
2195 }
2196 }
2197}
2198
2199/// ### Post-Regalloc Functions
2200///
2201/// These methods of `Callee` may only be called after
2202/// regalloc.
2203impl<M: ABIMachineSpec> Callee<M> {
2204 /// Compute the final frame layout, post-regalloc.
2205 ///
2206 /// This must be called before gen_prologue or gen_epilogue.
2207 pub fn compute_frame_layout(
2208 &mut self,
2209 sigs: &SigSet,
2210 spillslots: usize,
2211 clobbered: Vec<Writable<RealReg>>,
2212 function_calls: FunctionCalls,
2213 ) -> CodegenResult<()> {
2214 let bytes = M::word_bytes();
2215 let total_stacksize = self.stackslots_size + bytes * spillslots as u32;
2216 let mask = M::stack_align(self.call_conv) - 1;
2217 let total_stacksize = (total_stacksize + mask) & !mask; // 16-align the stack.
2218 let frame_layout = M::compute_frame_layout(
2219 self.call_conv,
2220 &self.flags,
2221 self.signature(),
2222 &clobbered,
2223 function_calls,
2224 self.stack_args_size(sigs),
2225 self.tail_args_size,
2226 self.stackslots_size,
2227 total_stacksize,
2228 self.outgoing_args_size,
2229 );
2230
2231 if Self::frame_layout_exceeds_limit(&frame_layout, M::maximum_frame_size()) {
2232 return Err(CodegenError::ImplLimitExceeded);
2233 }
2234
2235 self.frame_layout = Some(frame_layout);
2236 Ok(())
2237 }
2238
2239 /// Pulled out so that it can be used directly in tests without constructing a full `Callee`.
2240 pub(crate) fn frame_layout_exceeds_limit(
2241 frame_layout: &FrameLayout,
2242 max_frame_size: u32,
2243 ) -> bool {
2244 let total: u64 = frame_layout.incoming_args_size as u64
2245 + frame_layout.tail_args_size as u64
2246 + frame_layout.setup_area_size as u64
2247 + frame_layout.clobber_size as u64
2248 + frame_layout.fixed_frame_storage_size as u64
2249 + frame_layout.outgoing_args_size as u64;
2250 total > max_frame_size as u64
2251 }
2252
2253 /// Generate a prologue, post-regalloc.
2254 ///
2255 /// This should include any stack frame or other setup necessary to use the
2256 /// other methods (`load_arg`, `store_retval`, and spillslot accesses.)
2257 pub fn gen_prologue(&self) -> SmallInstVec<M::I> {
2258 let frame_layout = self.frame_layout();
2259 let mut insts = smallvec![];
2260
2261 // Set up frame.
2262 insts.extend(M::gen_prologue_frame_setup(
2263 self.call_conv,
2264 &self.flags,
2265 &self.isa_flags,
2266 &frame_layout,
2267 ));
2268
2269 // The stack limit check needs to cover all the stack adjustments we
2270 // might make, up to the next stack limit check in any function we
2271 // call. Since this happens after frame setup, the current function's
2272 // setup area needs to be accounted for in the caller's stack limit
2273 // check, but we need to account for any setup area that our callees
2274 // might need. Note that s390x may also use the outgoing args area for
2275 // backtrace support even in leaf functions, so that should be accounted
2276 // for unconditionally.
2277 let total_stacksize = (frame_layout.tail_args_size - frame_layout.incoming_args_size)
2278 + frame_layout.clobber_size
2279 + frame_layout.fixed_frame_storage_size
2280 + frame_layout.outgoing_args_size
2281 + if frame_layout.function_calls == FunctionCalls::None {
2282 0
2283 } else {
2284 frame_layout.setup_area_size
2285 };
2286
2287 // Leaf functions with zero stack don't need a stack check if one's
2288 // specified, otherwise always insert the stack check.
2289 if total_stacksize > 0 || frame_layout.function_calls != FunctionCalls::None {
2290 if let Some((reg, stack_limit_load)) = &self.stack_limit {
2291 insts.extend(stack_limit_load.clone());
2292 self.insert_stack_check(*reg, total_stacksize, &mut insts);
2293 }
2294
2295 if self.flags.enable_probestack() {
2296 let guard_size = 1 << self.flags.probestack_size_log2();
2297 match self.flags.probestack_strategy() {
2298 ProbestackStrategy::Inline => M::gen_inline_probestack(
2299 &mut insts,
2300 self.call_conv,
2301 total_stacksize,
2302 guard_size,
2303 ),
2304 ProbestackStrategy::Outline => {
2305 if total_stacksize >= guard_size {
2306 M::gen_probestack(&mut insts, total_stacksize);
2307 }
2308 }
2309 }
2310 }
2311 }
2312
2313 // Save clobbered registers.
2314 insts.extend(M::gen_clobber_save(
2315 self.call_conv,
2316 &self.flags,
2317 &frame_layout,
2318 ));
2319
2320 insts
2321 }
2322
2323 /// Generate an epilogue, post-regalloc.
2324 ///
2325 /// Note that this must generate the actual return instruction (rather than
2326 /// emitting this in the lowering logic), because the epilogue code comes
2327 /// before the return and the two are likely closely related.
2328 pub fn gen_epilogue(&self) -> SmallInstVec<M::I> {
2329 let frame_layout = self.frame_layout();
2330 let mut insts = smallvec![];
2331
2332 // Restore clobbered registers.
2333 insts.extend(M::gen_clobber_restore(
2334 self.call_conv,
2335 &self.flags,
2336 &frame_layout,
2337 ));
2338
2339 // Tear down frame.
2340 insts.extend(M::gen_epilogue_frame_restore(
2341 self.call_conv,
2342 &self.flags,
2343 &self.isa_flags,
2344 &frame_layout,
2345 ));
2346
2347 // And return.
2348 insts.extend(M::gen_return(
2349 self.call_conv,
2350 &self.isa_flags,
2351 &frame_layout,
2352 ));
2353
2354 trace!("Epilogue: {:?}", insts);
2355 insts
2356 }
2357
2358 /// Return a reference to the computed frame layout information. This
2359 /// function will panic if it's called before [`Self::compute_frame_layout`].
2360 pub fn frame_layout(&self) -> &FrameLayout {
2361 self.frame_layout
2362 .as_ref()
2363 .expect("frame layout not computed before prologue generation")
2364 }
2365
2366 /// Returns the offset from SP to FP for the given function, after
2367 /// the prologue has set up the frame. This comprises the spill
2368 /// slots and stack-storage slots as well as storage for clobbered
2369 /// callee-save registers and outgoing arguments at callsites
2370 /// (space for which is reserved during frame setup).
2371 pub fn sp_to_fp_offset(&self) -> u32 {
2372 let frame_layout = self.frame_layout();
2373 frame_layout.clobber_size
2374 + frame_layout.fixed_frame_storage_size
2375 + frame_layout.outgoing_args_size
2376 }
2377
2378 /// Returns offset from the slot base in the current frame to the caller's SP.
2379 pub fn slot_base_to_caller_sp_offset(&self) -> u32 {
2380 // Note: this looks very similar to `frame_size()` above, but
2381 // it differs in both endpoints: it measures from the bottom
2382 // of stackslots, excluding outgoing args; and it includes the
2383 // setup area (FP/LR) size and any extra tail-args space.
2384 let frame_layout = self.frame_layout();
2385 frame_layout.clobber_size
2386 + frame_layout.fixed_frame_storage_size
2387 + frame_layout.setup_area_size
2388 + (frame_layout.tail_args_size - frame_layout.incoming_args_size)
2389 }
2390
2391 /// Returns the size of arguments expected on the stack.
2392 pub fn stack_args_size(&self, sigs: &SigSet) -> u32 {
2393 sigs[self.sig].sized_stack_arg_space
2394 }
2395
2396 /// Get the spill-slot size.
2397 pub fn get_spillslot_size(&self, rc: RegClass) -> u32 {
2398 let max = if self.dynamic_type_sizes.len() == 0 {
2399 16
2400 } else {
2401 *self
2402 .dynamic_type_sizes
2403 .iter()
2404 .max_by(|x, y| x.1.cmp(&y.1))
2405 .map(|(_k, v)| v)
2406 .unwrap()
2407 };
2408 M::get_number_of_spillslots_for_value(rc, max, &self.isa_flags)
2409 }
2410
2411 /// Get the spill slot offset relative to the fixed allocation area start.
2412 pub fn get_spillslot_offset(&self, slot: SpillSlot) -> i64 {
2413 self.frame_layout().spillslot_offset(slot)
2414 }
2415
2416 /// Generate a spill.
2417 pub fn gen_spill(&self, to_slot: SpillSlot, from_reg: RealReg) -> M::I {
2418 let ty = M::I::canonical_type_for_rc(from_reg.class());
2419 debug_assert_eq!(<M>::I::rc_for_type(ty).unwrap().1, &[ty]);
2420
2421 let sp_off = self.get_spillslot_offset(to_slot);
2422 trace!("gen_spill: {from_reg:?} into slot {to_slot:?} at offset {sp_off}");
2423
2424 let from = StackAMode::Slot(sp_off);
2425 <M>::gen_store_stack(from, Reg::from(from_reg), ty)
2426 }
2427
2428 /// Generate a reload (fill).
2429 pub fn gen_reload(&self, to_reg: Writable<RealReg>, from_slot: SpillSlot) -> M::I {
2430 let ty = M::I::canonical_type_for_rc(to_reg.to_reg().class());
2431 debug_assert_eq!(<M>::I::rc_for_type(ty).unwrap().1, &[ty]);
2432
2433 let sp_off = self.get_spillslot_offset(from_slot);
2434 trace!("gen_reload: {to_reg:?} from slot {from_slot:?} at offset {sp_off}");
2435
2436 let from = StackAMode::Slot(sp_off);
2437 <M>::gen_load_stack(from, to_reg.map(Reg::from), ty)
2438 }
2439
2440 /// Provide metadata to be emitted alongside machine code.
2441 ///
2442 /// This metadata describes the frame layout sufficiently to find
2443 /// stack slots, so that runtimes and unwinders can observe state
2444 /// set up by compiled code in stackslots allocated for that
2445 /// purpose.
2446 pub fn frame_slot_metadata(&self) -> MachBufferFrameLayout {
2447 let frame_to_fp_offset = self.sp_to_fp_offset();
2448 let mut stackslots = SecondaryMap::with_capacity(self.sized_stackslots.len());
2449 let storage_area_base = self.frame_layout().outgoing_args_size;
2450 for (slot, storage_area_offset) in &self.sized_stackslots {
2451 stackslots[slot] = MachBufferStackSlot {
2452 offset: storage_area_base.checked_add(*storage_area_offset).unwrap(),
2453 key: self.sized_stackslot_keys[slot],
2454 };
2455 }
2456 MachBufferFrameLayout {
2457 frame_to_fp_offset,
2458 stackslots,
2459 }
2460 }
2461}
2462
2463/// An input argument to a call instruction: the vreg that is used,
2464/// and the preg it is constrained to (per the ABI).
2465#[derive(Clone, Debug)]
2466pub struct CallArgPair {
2467 /// The virtual register to use for the argument.
2468 pub vreg: Reg,
2469 /// The real register into which the arg goes.
2470 pub preg: Reg,
2471}
2472
2473/// An output return value from a call instruction: the vreg that is
2474/// defined, and the preg or stack location it is constrained to (per
2475/// the ABI).
2476#[derive(Clone, Debug)]
2477pub struct CallRetPair {
2478 /// The virtual register to define from this return value.
2479 pub vreg: Writable<Reg>,
2480 /// The real register from which the return value is read.
2481 pub location: RetLocation,
2482}
2483
2484/// A location to load a return-value from after a call completes.
2485#[derive(Clone, Debug, PartialEq, Eq)]
2486pub enum RetLocation {
2487 /// A physical register.
2488 Reg(Reg, Type),
2489 /// A stack location, identified by a `StackAMode`.
2490 Stack(StackAMode, Type),
2491}
2492
2493pub type CallArgList = SmallVec<[CallArgPair; 8]>;
2494pub type CallRetList = SmallVec<[CallRetPair; 8]>;
2495
2496impl<T> CallInfo<T> {
2497 /// Emit loads for any stack-carried return values using the call
2498 /// info and allocations.
2499 pub fn emit_retval_loads<
2500 M: ABIMachineSpec,
2501 EmitFn: FnMut(M::I),
2502 IslandFn: Fn(u32) -> Option<M::I>,
2503 >(
2504 &self,
2505 stackslots_size: u32,
2506 mut emit: EmitFn,
2507 emit_island: IslandFn,
2508 ) {
2509 // Count stack-ret locations and emit an island to account for
2510 // this space usage.
2511 let mut space_needed = 0;
2512 for CallRetPair { location, .. } in &self.defs {
2513 if let RetLocation::Stack(..) = location {
2514 // Assume up to ten instructions, semi-arbitrarily:
2515 // load from stack, store to spillslot, codegen of
2516 // large offsets on RISC ISAs.
2517 space_needed += 10 * M::I::worst_case_size();
2518 }
2519 }
2520 if space_needed > 0 {
2521 if let Some(island_inst) = emit_island(space_needed) {
2522 emit(island_inst);
2523 }
2524 }
2525
2526 let temp = M::retval_temp_reg(self.callee_conv);
2527 // The temporary must be noted as clobbered unless there are
2528 // no returns (hence it isn't needed). The latter can only be
2529 // the case statically for an ABI when the ABI doesn't allow
2530 // any returns at all (e.g., preserve-all ABI).
2531 debug_assert!(
2532 self.defs.is_empty()
2533 || M::get_regs_clobbered_by_call(self.callee_conv, self.try_call_info.is_some())
2534 .contains(PReg::from(temp.to_reg().to_real_reg().unwrap()))
2535 );
2536
2537 for CallRetPair { vreg, location } in &self.defs {
2538 match location {
2539 RetLocation::Reg(preg, ..) => {
2540 // The temporary must not also be an actual return
2541 // value register.
2542 debug_assert!(*preg != temp.to_reg());
2543 }
2544 RetLocation::Stack(amode, ty) => {
2545 if let Some(spillslot) = vreg.to_reg().to_spillslot() {
2546 // `temp` is an integer register of machine word
2547 // width, but `ty` may be floating-point/vector,
2548 // which (i) may not be loadable directly into an
2549 // int reg, and (ii) may be wider than a machine
2550 // word. For simplicity, and because there are not
2551 // always easy choices for volatile float/vec regs
2552 // (see e.g. x86-64, where fastcall clobbers only
2553 // xmm0-xmm5, but tail uses xmm0-xmm7 for
2554 // returns), we use the integer temp register in
2555 // steps.
2556 let parts = (ty.bytes() + M::word_bytes() - 1) / M::word_bytes();
2557 let one_part_load_ty =
2558 Type::int_with_byte_size(M::word_bytes().min(ty.bytes()) as u16)
2559 .unwrap();
2560 for part in 0..parts {
2561 emit(M::gen_load_stack(
2562 amode.offset_by(part * M::word_bytes()),
2563 temp,
2564 one_part_load_ty,
2565 ));
2566 emit(M::gen_store_stack(
2567 StackAMode::Slot(
2568 i64::from(stackslots_size)
2569 + i64::from(M::word_bytes())
2570 * ((spillslot.index() as i64) + (part as i64)),
2571 ),
2572 temp.to_reg(),
2573 M::word_type(),
2574 ));
2575 }
2576 } else {
2577 assert_ne!(*vreg, temp);
2578 emit(M::gen_load_stack(*amode, *vreg, *ty));
2579 }
2580 }
2581 }
2582 }
2583 }
2584}
2585
2586impl TryCallInfo {
2587 pub(crate) fn exception_handlers(
2588 &self,
2589 layout: &FrameLayout,
2590 ) -> impl Iterator<Item = MachExceptionHandler> {
2591 self.exception_handlers.iter().map(|handler| match handler {
2592 TryCallHandler::Tag(tag, label) => MachExceptionHandler::Tag(*tag, *label),
2593 TryCallHandler::Default(label) => MachExceptionHandler::Default(*label),
2594 TryCallHandler::Context(reg) => {
2595 let loc = if let Some(spillslot) = reg.to_spillslot() {
2596 // The spillslot offset is relative to the "fixed
2597 // storage area", which comes after outgoing args.
2598 let offset = layout.spillslot_offset(spillslot) + i64::from(layout.outgoing_args_size);
2599 ExceptionContextLoc::SPOffset(u32::try_from(offset).expect("SP offset cannot be negative or larger than 4GiB"))
2600 } else if let Some(realreg) = reg.to_real_reg() {
2601 ExceptionContextLoc::GPR(realreg.hw_enc())
2602 } else {
2603 panic!("Virtual register present in try-call handler clause after register allocation");
2604 };
2605 MachExceptionHandler::Context(loc)
2606 }
2607 })
2608 }
2609
2610 pub(crate) fn pretty_print_dests(&self) -> String {
2611 self.exception_handlers
2612 .iter()
2613 .map(|handler| match handler {
2614 TryCallHandler::Tag(tag, label) => format!("{tag:?}: {label:?}"),
2615 TryCallHandler::Default(label) => format!("default: {label:?}"),
2616 TryCallHandler::Context(loc) => format!("context {loc:?}"),
2617 })
2618 .collect::<Vec<_>>()
2619 .join(", ")
2620 }
2621
2622 pub(crate) fn collect_operands(&mut self, collector: &mut impl OperandVisitor) {
2623 for handler in &mut self.exception_handlers {
2624 match handler {
2625 TryCallHandler::Context(ctx) => {
2626 collector.any_late_use(ctx);
2627 }
2628 TryCallHandler::Tag(_, _) | TryCallHandler::Default(_) => {}
2629 }
2630 }
2631 }
2632}
2633
2634#[cfg(test)]
2635mod tests {
2636 use super::SigData;
2637
2638 #[test]
2639 fn sig_data_size() {
2640 // The size of `SigData` is performance sensitive, so make sure
2641 // we don't regress it unintentionally.
2642 assert_eq!(core::mem::size_of::<SigData>(), 24);
2643 }
2644}