Skip to main content

rucc_codegen/
pipeline.rs

1//! One IR function to one machine function, which is every pass in this crate in order.
2//!
3//! Design: `spec/10-backend.md` section 10.1, which is where the order comes from.
4//!
5//! Each pass here is written and tested on its own and each is useful on its own, but there is
6//! exactly one order they run in and until now that order lived in the tests. A caller outside
7//! this crate would have had to know that splitting critical edges comes after lowering and
8//! before allocation, that the frame is worked out after allocation because the spill slots are
9//! the largest thing in it, and that the prologue is written after the frame. None of that is a
10//! decision a driver should be making, so it is written down once, here.
11//!
12//! # What comes out
13//!
14//! A function whose every register is physical, whose every offset into the frame is a constant,
15//! and whose blocks are in the order they run in with the jumps that order needs. That is the
16//! point at which a function is one an encoder could read, and there is nothing left in it that
17//! is not an instruction of the machine it was compiled for.
18//!
19//! # What is still missing from the middle
20//!
21//! The optimizing path, all of it. What runs here is `spec/10-backend.md` section 10.3's fast
22//! path: one rule per term, a linear scan, and a block order from the shape of the CFG rather
23//! than from block frequency. No scheduling, and the redundant moves a coalescer would take out
24//! are still in the output.
25
26use rucc_base::Interner;
27use rucc_base::hash::Map;
28use rucc_cost::Goal;
29use rucc_ir as ir;
30use rucc_mir as mir;
31use rucc_regalloc::assign::Env;
32use rucc_target::{
33    BitInsts, BranchInsts, CallRegs, FlagInsts, FrameInsts, MachineInsts, PhysReg, RegFile,
34    ShortInsts, TargetInfo, TimingInsts, aarch64, x86_64,
35};
36use rucc_tuple::Arch;
37
38use crate::bits;
39use crate::choice;
40use crate::combine;
41use crate::compare;
42use crate::copies;
43use crate::coverage::Fired;
44use crate::elsewhere::Elsewhere;
45use crate::finish::{Convention, Padding, Probing, Protect, Tracing, far, finish};
46use crate::fold;
47use crate::frame::{self, Frame, Layout};
48use crate::kept;
49use crate::layout;
50use crate::lower::{self, Unsupported};
51use crate::lowering::{self, Lowerings};
52use crate::pressure::{Cost, Pressure};
53use crate::schedule;
54use crate::select::{self, Selector};
55use crate::shorten;
56use crate::slots::{self, Slots};
57use crate::split;
58use crate::tail;
59use crate::usage::{StackUsage, Usage};
60use crate::weights;
61pub use rucc_regalloc::Allocator;
62
63/// Everything about a machine that compiling a function for it needs.
64///
65/// The fields are different kinds of fact and they come from different places: where the
66/// convention puts things, what registers the machine has, which instructions build a frame,
67/// which instructions a branch becomes, and which registers the allocator may hand out. The last
68/// one is not a target fact on its own, because holding a register back as scratch is a decision
69/// about the allocator rather than about the machine, which is why it is built here rather than
70/// in [`rucc_target`].
71#[derive(Debug)]
72pub struct Machine {
73    /// Where the convention this function is compiled for puts things.
74    pub conv: &'static CallRegs,
75    /// The registers the machine has, which is what says how wide a spill slot of a class is.
76    pub file: RegFile,
77    /// The instructions that take a frame and give it back.
78    pub insts: &'static FrameInsts,
79    /// The instructions a branch becomes once the blocks are in an order.
80    pub branch: &'static BranchInsts,
81    /// How much of a register each of the machine's instructions reads and writes.
82    pub bits: &'static BitInsts,
83    /// What each of the machine's instructions leaves in the condition state.
84    pub flags: &'static FlagInsts,
85    /// What shape each of the machine's instructions is, which is what a pass proposing a new one
86    /// has its proposal held against.
87    pub shapes: &'static MachineInsts,
88    /// How long each of the machine's instructions takes, and what it takes it on.
89    pub timing: &'static TimingInsts,
90    /// Which of the machine's instructions have a shorter spelling of the same answer.
91    pub short: &'static ShortInsts,
92    /// What the selector asks of the machine, which is the rules and the instructions it writes
93    /// itself.
94    pub selector: &'static Selector,
95    /// What the allocator may hand out, and what it holds back.
96    pub env: Env,
97}
98
99/// The scratch registers held back from the allocator on x86-64.
100///
101/// Two, because a move on an edge may have to break a cycle and a spilled value has to be read
102/// into something, and those can want a register at the same instruction. Two is also what nearly
103/// every instruction wants, including the one that looks larger: an instruction that reads two
104/// spilled values and writes a third sends the answer back into a register an operand arrived in
105/// rather than asking for one of its own, and `rewrite` says why that is allowed.
106///
107/// It is not two because two was enough to start with and nobody looked again. There is no third
108/// to hold back. A scratch register has to be one the convention passes nothing in, since the
109/// rewriter puts moves in wherever it likes, and one the callee does not owe back, since the
110/// rewriter runs after the prologue has been decided and cannot ask for a register to be saved. On
111/// SysV that is `r10`, `r11` and `rax`, and `rax` is not one to take: it is the return value, so
112/// holding it back costs a move at every return in the program, which is a price paid everywhere
113/// for a shape that turns up almost nowhere.
114///
115/// An instruction that wants a third is the indexed store with its base, its index and its value
116/// all on the stack, which is tamnd/rucc#913. `rewrite` answers that one by borrowing a register
117/// and putting back what was in it, which costs two memory accesses at the instruction that wanted
118/// it and nothing anywhere else.
119pub(crate) const SCRATCH: [PhysReg; 2] = [x86_64::R10, x86_64::R11];
120
121/// The scratch registers held back from the allocator on AArch64. See [`Machine::aarch64`].
122pub(crate) const AARCH64_SCRATCH: [PhysReg; 2] = [aarch64::X16, aarch64::X17];
123
124/// How many of each class are held back.
125const SCRATCH_COUNT: usize = SCRATCH.len();
126
127/// The second register file's allocation order and the scratch registers taken out of it, which
128/// are the last two in the order that the convention does not preserve.
129fn held_back(conv: &CallRegs) -> (Vec<PhysReg>, Vec<PhysReg>) {
130    let free: Vec<PhysReg> =
131        conv.sse_order.iter().copied().filter(|&reg| !conv.preserves_sse(reg)).collect();
132    let at = free.len().saturating_sub(SCRATCH_COUNT);
133    let scratch: Vec<PhysReg> = free[at..].to_vec();
134    let order = conv.sse_order.iter().copied().filter(|reg| !scratch.contains(reg)).collect();
135    (order, scratch)
136}
137
138impl Machine {
139    /// The x86-64 machine under that convention.
140    ///
141    /// Both files are offered. A value the selector produces is in one or the other, which is
142    /// decided by its type: an integer and an address are general purpose and a `float` or a
143    /// `double` is in a vector register, and the allocator is given each file separately because
144    /// no move goes between them.
145    #[must_use]
146    pub fn x86_64(conv: &'static CallRegs) -> Self {
147        let order: Vec<PhysReg> =
148            conv.int_order.iter().copied().filter(|reg| !SCRATCH.contains(reg)).collect();
149        // The vector file wants its own two, for the same two jobs, and they have to be two the
150        // convention does not preserve: a scratch register is written by a move the rewriter puts
151        // in, which is after the prologue has already been decided, so one the callee owes back
152        // would be one nothing saved. That rules out the upper ten on Windows and nothing at all
153        // on SysV, and taking the last two that are left lands on `xmm14` and `xmm15` there and on
154        // `xmm4` and `xmm5` on Windows, neither of which any argument travels in.
155        let (sse_order, sse_scratch) = held_back(conv);
156        Self {
157            conv,
158            file: x86_64::REGS,
159            insts: &x86_64::FRAME,
160            branch: &x86_64::BRANCH,
161            bits: &x86_64::BITS,
162            flags: &x86_64::FLAGS,
163            shapes: &x86_64::MACHINE,
164            timing: &x86_64::TIMING,
165            short: &x86_64::SHORT,
166            selector: &select::x86_64::SELECTOR,
167            env: Env::new().with(x86_64::GPR, &order, &SCRATCH).with(
168                x86_64::XMM,
169                &sse_order,
170                &sse_scratch,
171            ),
172        }
173    }
174
175    /// The AArch64 machine under that convention.
176    ///
177    /// The scratch registers are `x16` and `x17`, which the convention already keeps out of the
178    /// allocation order because a linker's veneer may write them between a call and the function
179    /// it reaches. That is the property a scratch register wants: nothing lives in one across
180    /// anything the compiler did not write, so a move the rewriter puts in can have it. The vector
181    /// file's two are picked the way the x86 ones are, which lands on `v30` and `v31`.
182    #[must_use]
183    pub fn aarch64(conv: &'static CallRegs) -> Self {
184        let order: Vec<PhysReg> =
185            conv.int_order.iter().copied().filter(|reg| !AARCH64_SCRATCH.contains(reg)).collect();
186        let (fp_order, fp_scratch) = held_back(conv);
187        Self {
188            conv,
189            file: aarch64::REGS,
190            insts: &aarch64::FRAME,
191            branch: &aarch64::BRANCH,
192            bits: &aarch64::BITS,
193            flags: &aarch64::FLAGS,
194            shapes: &aarch64::MACHINE,
195            timing: &aarch64::TIMING,
196            short: &aarch64::SHORT,
197            selector: &select::aarch64::SELECTOR,
198            env: Env::new().with(aarch64::GPR, &order, &AARCH64_SCRATCH).with(
199                aarch64::FPR,
200                &fp_order,
201                &fp_scratch,
202            ),
203        }
204    }
205
206    /// The same machine for a function written in another calling convention, which is what an
207    /// `__attribute__((ms_abi))` function on Linux or an `__attribute__((sysv_abi))` one on
208    /// Windows is compiled against. `None` when the platform has no such convention.
209    ///
210    /// Only the convention changes. The allocator's order and the scratch registers are worked out
211    /// again from it, because which registers the function owes back is the thing that differs,
212    /// and a scratch register has to be one it does not owe.
213    #[must_use]
214    pub fn under(&self, convention: rucc_target::Convention) -> Option<Self> {
215        let conv = self.conv.under(convention)?;
216        if std::ptr::eq(self.selector, &select::aarch64::SELECTOR) {
217            Some(Self::aarch64(conv))
218        } else {
219            Some(Self::x86_64(conv))
220        }
221    }
222
223    /// The machine a target describes, or `None` when no backend in this crate covers it.
224    ///
225    /// [`TargetInfo`] already carries the convention, because the front end needs it to lay a
226    /// `va_list` out, so the only thing this decides is which architecture's frame instructions
227    /// and register file go with it. RISC-V is `None` until it has a rule file, and a caller that
228    /// gets one reports a target it cannot compile for rather than compiling wrongly.
229    #[must_use]
230    pub fn for_target(target: &TargetInfo) -> Option<Self> {
231        let conv = target.call_regs?;
232        match target.tuple.arch() {
233            Arch::X86_64 => Some(Self::x86_64(conv)),
234            Arch::Aarch64 => Some(Self::aarch64(conv)),
235            _ => None,
236        }
237    }
238}
239
240/// Whether every function calls a profiler on the way in, and where that call goes.
241///
242/// What `-pg` asks for, with `-mfentry` and `-mno-fentry` choosing between the last two. The choice
243/// has already been made against the target by the time this is built, which is why there is no
244/// answer here for a command line that named neither.
245#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
246pub enum Profile {
247    /// It does not, which is what nearly every command line asks for.
248    #[default]
249    No,
250    /// In front of the prologue, which is the hook a tracer can replace while the program runs.
251    Early,
252    /// Once the frame is taken, which is the hook that reads the frame pointer.
253    Late,
254}
255
256/// How much room every function opens with for something to be written over it later.
257///
258/// What `-fpatchable-function-entry=` asks for, as the two halves a prologue deals in rather than
259/// as the total and the part the flag is written in. The room can be on either side of the
260/// function's own label and the two sides are not the same thing: what is after the label is inside
261/// the function, which is what a patcher redirecting a call into it wants, and what is in front of
262/// it is outside, which is where a patcher that needs a whole instruction it can reach from the
263/// first one puts it.
264#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
265pub struct Room {
266    /// How many bytes go after the function's own label.
267    pub after: u32,
268    /// How many go in front of it.
269    pub before: u32,
270}
271
272impl Room {
273    /// Whether any room at all was asked for, which is what decides whether a function gets one.
274    ///
275    /// `=0` is a command line that asked for none, and gcc takes it and writes nothing, so the
276    /// question is about the numbers rather than about whether the flag was written.
277    #[must_use]
278    pub const fn any(self) -> bool {
279        self.after > 0 || self.before > 0
280    }
281}
282
283/// What the command line says, as opposed to what the machine says.
284///
285/// Most of it is about a frame, which is what this held to begin with, and the rest is passes being
286/// asked for or turned off by name. [`Flags::goal`] is neither: it is the one thing here that no
287/// flag names on its own and that every pass below selection may read.
288#[derive(Debug, Clone, Copy, PartialEq, Eq)]
289pub struct Flags {
290    /// Whether every function keeps a frame pointer, which `-fno-omit-frame-pointer` asks for.
291    pub frame_pointer: bool,
292    /// Whether the red zone may be used, which `-mno-red-zone` and every kernel turns off.
293    pub red_zone: bool,
294    /// Whether a frame is taken a page at a time, which `-fstack-clash-protection` asks for.
295    pub stack_clash: bool,
296    /// Whether every address an indirect branch may arrive at opens with a landing pad, which
297    /// `-fcf-protection=branch` asks for. That is every function, and every label of a function
298    /// whose address the program took.
299    pub landing: bool,
300    /// Whether every function calls a profiler on the way in, which `-pg` asks for.
301    pub profile: Profile,
302    /// How much room every function opens with for a patcher, which
303    /// `-fpatchable-function-entry=` asks for. See [`Room`].
304    pub patch: Room,
305    /// Whether the blocks are put in the order the weights say rather than in the order the
306    /// shape of the graph says, which `-freorder-blocks` asks for and every level above `-O0`
307    /// turns on. See [`crate::layout`].
308    pub reorder: bool,
309    /// Whether two locals that are never both wanted may be the same bytes, which
310    /// `-fstack-reuse=none` turns off and `-O0` does not ask for. Spill slots share whatever this
311    /// says, since a spill slot is not a variable and nothing can ask a debugger for one. See
312    /// [`crate::slots`].
313    pub reuse: bool,
314    /// Whether the instructions of a block are put in the order the machine finishes soonest,
315    /// which `-fschedule-insns2` asks for and every level from `-O2` turns on. See
316    /// [`crate::schedule`].
317    pub schedule: bool,
318    /// Whether the head of every hot loop is found, so that the loop can be padded to stay inside
319    /// one line, which `-falign-loops` asks for and no level turns on by itself yet. See
320    /// [`crate::layout::heads`].
321    pub align_loops: bool,
322    /// Whether the target's timing model is believed about the machine's units as well as about
323    /// its latencies, which `-Zcycle-accurate-model=` says and the model itself answers otherwise.
324    ///
325    /// `None` is a command line that did not say, which is nearly every one, and then the model's
326    /// own answer decides. It is here rather than only on the model because section 38.1 asks for
327    /// a way to say the model is better or worse than it claims without editing the model, and
328    /// because the measurement section 38.8 owes is the same corpus compiled both ways.
329    pub accurate: Option<bool>,
330    /// Whether the register allocator runs its own checks on a build that has assertions compiled
331    /// out, which `-Zverify-each` asks for. See [`rucc_regalloc::run`].
332    pub verify: bool,
333    /// Which register allocator decides where the values go, which `-Zregalloc=` says. See
334    /// [`rucc_regalloc::Allocator`].
335    pub allocator: Allocator,
336    /// Whether the level asked for small code or for fast code.
337    ///
338    /// The level itself lives in `rucc-session`, which is above this crate, so what arrives here is
339    /// the answer rather than the question. It is on the flags rather than on the [`Machine`]
340    /// because it is not a fact about a machine: the same machine compiles the same function both
341    /// ways, and which way is what the command line said.
342    ///
343    /// tamnd/rucc#741 is the issue about this not being here at all, and about `-Os` having been a
344    /// shorter list of middle end passes and nothing else. [`crate::shorten`] is the first pass
345    /// below selection to read it.
346    pub goal: Goal,
347    /// The shape `-Zswitch=` forces on every `switch`, which is `None` unless somebody is
348    /// measuring what each shape costs. See [`crate::switch::Force`].
349    pub switch: Option<crate::switch::Force>,
350    /// Whether a call in tail position becomes a jump, which `-foptimize-sibling-calls` asks for
351    /// and `-O2` and `-Os` turn on. See [`crate::tail`].
352    pub sibling: bool,
353    /// Whether the build writes debugging information, which `-g` asks for. Where each local is
354    /// over which instructions is worked out only then, since nothing else reads it. See
355    /// [`crate::kept`].
356    pub debug: bool,
357}
358
359impl Default for Flags {
360    /// No frame pointer, the red zone allowed, the frame taken in one subtraction, no landing pad,
361    /// no profiling, no room for a patcher, the blocks in the order the graph's shape gives,
362    /// nothing in the frame sharing with anything, no scheduling, no loop padded to a boundary and
363    /// code that is meant to be fast rather than small, with no debugging information, which is
364    /// what a convention that has a red zone says at `-O0` when nobody on the command line has said
365    /// otherwise.
366    fn default() -> Self {
367        Self {
368            frame_pointer: false,
369            red_zone: true,
370            stack_clash: false,
371            landing: false,
372            profile: Profile::No,
373            patch: Room::default(),
374            reorder: false,
375            reuse: false,
376            schedule: false,
377            align_loops: false,
378            accurate: None,
379            verify: false,
380            allocator: Allocator::Single,
381            goal: Goal::Speed,
382            switch: None,
383            sibling: false,
384            debug: false,
385        }
386    }
387}
388
389/// Compiles one function, from the IR the middle end produced to machine instructions.
390///
391/// The function is taken by reference that can be written through, because the first pass is an
392/// IR to IR rewrite: a construct whose lowering is a new shape of control flow cannot be a rule,
393/// since a rule replaces a term with a term and has nowhere to put a block. So the IR that reaches
394/// selection is not quite the IR the middle end produced, and this is the only place that is true.
395/// `--emit=ir` prints before any of this runs.
396///
397/// `elsewhere` is the one thing here that is a fact about the module rather than about the
398/// function, and it is passed in rather than looked up because this only ever sees the one
399/// function. What it decides is how the address of a name is come by, which is the difference
400/// between an address this file can measure to and one only the linker knows.
401///
402/// # Errors
403///
404/// The first thing in it this cannot lower, which is what [`lower::func`] reports, and one thing
405/// after it that is about the shape of the function rather than about an instruction, which is a
406/// frame that grows while it runs in a function whose flags say no frame may. Everything else after
407/// lowering works on machine instructions that exist, so it either runs or it is a bug in this
408/// crate.
409pub fn compile(
410    source: &mut ir::Func,
411    names: &mut Interner,
412    machine: &Machine,
413    elsewhere: &Elsewhere,
414    flags: Flags,
415) -> Result<mir::Func, Unsupported> {
416    let (mut fired, mut pressure, mut lowerings, mut stack) =
417        (Fired::new(), Pressure::new(), Lowerings::new(), StackUsage::new());
418    compile_recording(
419        source,
420        names,
421        machine,
422        elsewhere,
423        flags,
424        &mut Recording {
425            fired: &mut fired,
426            pressure: &mut pressure,
427            lowerings: &mut lowerings,
428            stack: &mut stack,
429        },
430    )
431}
432
433/// Somewhere to put what a compilation did along the way, for the flags that ask.
434///
435/// One of these rather than three parameters, because they are one thing: a caller either wants
436/// the measurements or does not, and a caller that does wants the same three to cover every
437/// function of every file on the command line.
438#[derive(Debug)]
439pub struct Recording<'a> {
440    /// Which lowering rules fired, for `-Zrule-coverage`.
441    pub fired: &'a mut Fired,
442    /// What the allocator had to put on the stack, for `-Zregister-pressure`.
443    pub pressure: &'a mut Pressure,
444    /// What the pre-selection lowering group did, for `-Zlowering`.
445    pub lowerings: &'a mut Lowerings,
446    /// How much stack each function takes, for `-fstack-usage`.
447    pub stack: &'a mut StackUsage,
448}
449
450/// The same compilation, with what it did along the way recorded.
451///
452/// Two functions rather than one that takes options, because a caller that does not want the
453/// numbers should not have to say so. What each field of the [`Recording`] is for is on the field,
454/// and all of them are added to rather than replaced, so a caller passes the same one for every
455/// function of a module and every module of a command line and gets the answer for all of them.
456///
457/// # Errors
458///
459/// The same as [`compile`]. A function that was refused contributes nothing to any of them, since
460/// a function that did not compile is not evidence about what a rule set or a frame would have
461/// done.
462pub fn compile_recording(
463    source: &mut ir::Func,
464    names: &mut Interner,
465    machine: &Machine,
466    elsewhere: &Elsewhere,
467    flags: Flags,
468    recording: &mut Recording<'_>,
469) -> Result<mir::Func, Unsupported> {
470    // A function the program wrote in the platform's other calling convention is compiled against
471    // that convention from the first pass to the last: its parameters arrive where it says, the
472    // registers it owes back are the ones it says, and its frame has the room it says. The calls
473    // it makes each name their own convention, so they are unaffected by this.
474    let foreign;
475    let machine = match source.signature().convention {
476        rucc_target::Convention::Target => machine,
477        convention => {
478            foreign = machine
479                .under(convention)
480                .ok_or(Unsupported::Unported { inst: None, what: lower::Unported::Convention })?;
481            &foreign
482        }
483    };
484    // Everything the machine has no rule for, rewritten into things it has, as one group rather
485    // than as a dozen lines here. What is in the group and what the order between its members is
486    // for are both in `crate::lowering`, which is where a new lowering is added.
487    let counting = recording.lowerings.wanted();
488    let ran = lowering::group(source, names, machine.conv, flags.goal, flags.switch, counting);
489    if !ran.switches.is_empty() {
490        let called = names.resolve(source.name).to_owned();
491        recording.lowerings.switched(&called, &ran.switches);
492    }
493    if counting {
494        let called = names.resolve(source.name).to_owned();
495        recording.lowerings.record(&called, ran);
496    }
497    // The function the program said it writes the whole of itself, which is what decides most of
498    // the frame below rather than being one more thing in it. Read here rather than beside the rest
499    // of the layout because the refusal a few lines down is the earliest thing that asks.
500    let naked = source.attrs.set.contains(ir::AttrSet::NAKED);
501    // Last thing before selection, because a `tail_call` ends its block and every lowering above
502    // is written against blocks that end the way the middle end left them. Only on a machine that
503    // can jump to a name, since the call stays a call on one that cannot.
504    if flags.sibling && machine.insts.away.is_some() {
505        tail::mark(source, names, elsewhere);
506    }
507    // Asked of the IR, where a call still says whom it calls. See [`tail::comes_back`].
508    let alone = tail::comes_back(source, names, elsewhere);
509    let lowered =
510        lower::func_for(source, names, machine.selector, machine.conv, elsewhere, flags.debug)?;
511    recording.fired.merge(&lowered.fired);
512    let lower::Lowered { mut func, mut stack, blocks, .. } = lowered;
513    // Straight after selection, because this is the last moment the machine blocks and the IR
514    // blocks still stand one for one, and the pass that reads the numbers is the very last one
515    // there is. See `crate::weights`.
516    if flags.reorder {
517        weights::carry(source, &blocks, &mut func);
518    }
519    // The one thing a frame that grows while it runs cannot be asked for, which is a refusal rather
520    // than wrong code.
521    if let Some(inst) = stack.grown_at {
522        // And the one thing a naked function cannot be asked for either, from the other side of the
523        // same fact. A frame that grows is reached from a frame pointer the prologue establishes,
524        // and there is no prologue here, so the address the array hands out would be counted from a
525        // register holding whatever the caller left in it.
526        if naked {
527            return Err(Unsupported::Dynamic { inst, growing: lower::Growing::Naked });
528        }
529        // The lowering refuses a variable length array that asks for more alignment than a call
530        // leaves the stack pointer on. A fixed local asking for it in the same function is the same
531        // refusal arrived at from the other side: the prologue would force the alignment, and
532        // forcing it and moving the stack pointer afterwards are two frames that each want the one
533        // register that still reaches the rest of the frame. See `Growing` in [`crate::frame`].
534        if stack.locals.iter().any(|local| local.align > machine.conv.stack_align) {
535            return Err(Unsupported::Dynamic { inst, growing: lower::Growing::Aligned });
536        }
537    }
538
539    // Before the fold below, which is the order section 37.6 puts the two in. A widening this takes
540    // out is one whose readers are sent to its source, and one of those readers may be an address
541    // computation, so asking which bits are read first means the fold sees the addresses as they
542    // will be rather than as they were.
543    bits::dead(&mut func, machine.bits, machine.shapes, names);
544
545    // After selection, because the address instruction and the one that reads it are both machine
546    // instructions only once selection has written them, and before allocation, because what makes
547    // the pair safe to put together is that a virtual register is written once. The addresses into
548    // the frame and into the caller's argument area go through it like anything else, and the two
549    // lists `finish` reads are rewritten as they do, so an address that ends up inside its reader
550    // is still an address the frame layout knows to write an offset into.
551    // A constant added to an index goes into the displacement first, so an address that took one
552    // is handed on to its readers with it already inside.
553    fold::offsets(&mut func, machine.insts, machine.shapes, names);
554    let mut pending = fold::Pending {
555        addresses: &mut stack.addresses,
556        arguments: &mut stack.arguments,
557        dynamic: &mut stack.dynamic,
558    };
559    fold::addresses(&mut func, machine.insts, machine.shapes, names, &mut pending);
560
561    // After that fold rather than before it, because what this puts inside an arithmetic
562    // instruction is a load's addressing mode and a load whose address is still a `lea` in front of
563    // it has nothing in its own mode worth carrying. Before allocation for the reason the fold is:
564    // a virtual register is written once, which is the whole of why the value the load produced
565    // cannot have changed between the two instructions this joins.
566    // The run that reads a place, computes on it and writes it back goes first, because it is three
567    // instructions the selector wrote and taking the load out of the middle one first would leave
568    // the same run written a second way.
569    combine::stores(&mut func, machine.shapes, machine.flags, names, &mut pending);
570    combine::loads(&mut func, machine.shapes, names, &mut pending);
571
572    // Whether this function carries a canary is the front end's answer, because what
573    // `-fstack-protector` asks about is the kind of local a function has and the types are gone by
574    // here. What the machine does about it is this crate's answer, and a target with nowhere to
575    // keep the word a canary is copied from does nothing, which is what the driver refuses a
576    // command line over before any of this runs.
577    // Not in a naked function, whatever the command line asked of every function. The canary is a
578    // word the prologue copies into the frame and the check at the end reads back, so a function
579    // with neither has nowhere to put it and nowhere to read it from. gcc leaves one out too.
580    let protect = source.attrs.set.contains(ir::AttrSet::STACK_PROTECT) && !naked;
581    let guard = protect.then_some(machine.conv.guard.as_ref()).flatten();
582    // Nothing at all on a target with no hook to call, which is the same answer the protector gives
583    // on a target with nowhere to keep its word, and the driver refuses the command line over it
584    // before any of this runs.
585    let profile = match machine.conv.trace {
586        Some(_) => flags.profile,
587        None => Profile::No,
588    };
589    let base = stack.layout(Layout::new(machine.conv, machine.file));
590    let layout = Layout {
591        // The later hook reads the frame pointer to find out who called this function, so a
592        // function that calls it is given one whether or not anything else asked. A function that
593        // asked where its own frame is has the same claim on one, and for a plainer reason: the
594        // register is the answer.
595        //
596        // And not at all in a naked function, whatever any of that says. Establishing one is two
597        // instructions of a prologue there is none of, and a function that saves the machine state
598        // by hand is usually saving the frame pointer among it, which is what micropython's
599        // `nlr_push` does on its third line.
600        frame_pointer: !naked
601            && (flags.frame_pointer
602                || profile == Profile::Late
603                || stack.walks_frames
604                || stack.saves_place),
605        // And not in a naked function either, which is not about what the red zone costs but about
606        // what the refusal below has to be able to see. A local small enough to live below the
607        // stack pointer takes no bytes off it, so the frame comes out empty and a function that
608        // wanted somewhere to keep something would be told it asked for nothing. Taking the red
609        // zone away makes every local show up as bytes, and bytes are what gets refused.
610        red_zone: flags.red_zone && !naked,
611        // Two registers to a push on a machine with an instruction for it, which is `stp` on
612        // AArch64, and one at a time on x86-64, which has none.
613        pairs: machine.insts.pair.is_some(),
614        protect: guard.is_some(),
615        naked,
616        // A protected function calls the one that does not come back, on the arm where the check
617        // failed, so it is not a leaf however few calls the program wrote in it. That is what
618        // takes the red zone away from it and what makes its frame leave the stack pointer where
619        // a call needs it. The later hook is a call in the same position and costs the same.
620        //
621        // The earlier one is not, and this is the one place the difference shows. It runs before
622        // the prologue has written anything, so the bytes below the stack pointer it uses are ones
623        // this function has not put anything in yet, and a leaf that keeps its locals down there
624        // stays a leaf. gcc leaves it alone too.
625        leaf: base.leaf && guard.is_none() && profile != Profile::Late,
626        ..base
627    };
628
629    // Before allocation as well, and asked here rather than where it is used because what it asks
630    // is whether anything but the branch reads the byte a comparison wrote. A virtual register is
631    // written once and a physical one is not, so after allocation that question no longer has an
632    // answer.
633    let fusable = layout::fusable(&func, machine.branch, names);
634    // The same question about the selects on a comparison's byte, asked here for the same reason.
635    let choosable = choice::fusable(&func, machine.branch, names);
636
637    // In front of the splitting below, because what it does is take the values off the edges out of
638    // a computed `goto` and the splitting has no answer for one of those: the block they leave ends
639    // in a jump already, so neither end of the edge is somewhere a move can go.
640    split::indirect(&mut func, machine.branch, machine.insts, names);
641
642    // And after it, because what it puts a pad at is the block an address names and the pass above
643    // is what settles which block that is. The pad the prologue opens with is written much later,
644    // with the rest of the prologue, since the address it answers for is the function's own.
645    //
646    // Nothing at all on a target with nothing that marks an address as one an indirect branch may
647    // arrive at, which is the same answer the stack protector gives on a target with nowhere to
648    // keep its word, and the driver refuses the command line over it before any of this runs.
649    let landing = flags.landing.then_some(machine.insts.landing).flatten();
650    split::pads(&mut func, machine.insts, landing, names);
651
652    // Before allocation, because an edge that carries values into a block arrived at more than
653    // one way, out of a block that leaves more than one way, has nowhere to put the moves those
654    // values turn into, and the allocator asserts rather than guessing.
655    split::critical(&mut func);
656
657    // Before allocation, because how far the address of a local gets is a question about values and
658    // a value is written once only until the allocator's rewrite has been through. What is done
659    // with the answer waits until afterwards, since the liveness it is read against is the
660    // allocator's. See [`crate::slots`].
661    //
662    // Only asked at all where the locals are allowed to share, since this is the whole of what says
663    // whether a local may. The spill slots are laid out either way and this says nothing about
664    // them.
665    let reach = (flags.reuse && !alone)
666        .then(|| slots::reach(&func, &stack.addresses, stack.locals.len(), machine.insts, names));
667
668    // The instructions as they are now, for the locals the front end kept in values. The
669    // allocator's liveness is counted along this order and the rewrite is about to put spills,
670    // reloads and edge moves in among them, so the list has to be taken before it runs. Only in a
671    // function that named something, since a function that named nothing has no use for it. See
672    // [`crate::kept`].
673    //
674    // Or where a local the program declared may share its bytes, which is only where there is a
675    // `reach`, since a local that shares is in the frame over part of the function and the part is
676    // asked about the same way.
677    //
678    // Only for a build that writes debugging information, since the stretches are read by nothing
679    // else.
680    let line = (flags.debug
681        && (!func.named.is_empty() || (reach.is_some() && !stack.declared.is_empty())))
682    .then(|| kept::before(&func));
683
684    // Which arithmetic reads its two sources either way round, so the allocator may write the
685    // answer over whichever of the two is finished with. Marked here rather than at selection
686    // because every pass in between that rewrites an instruction would have to carry the mark.
687    commuting(&mut func, machine.shapes, names);
688
689    // The single pass allocator in a function that can be come back into. A value live across the
690    // call that comes back has to be read by the second arrival from memory the first arm did not
691    // write, and the backtracking allocator is free to leave it in a register the first arm writes.
692    let allocator = if alone { Allocator::Single } else { flags.allocator };
693    let called = names.resolve(func.name).to_owned();
694    let allocation =
695        rucc_regalloc::run_with(&mut func, &machine.env, &called, flags.verify, allocator);
696    recording.pressure.record(&called, Cost::of(&allocation));
697
698    // After allocation, because the largest area in most frames is the spill slots and nothing
699    // knows how many of those there are until the allocator has finished running out of registers,
700    // and because a spill slot cannot be shared with a local until it is known there is one.
701    let widths = frame::widths(&layout, &allocation);
702    // Nothing shares in a function that can be come back into, since the second arrival reads
703    // bytes the liveness says nobody wants. See [`tail::comes_back`].
704    let share = if alone {
705        Slots::apart(&stack.locals, &widths)
706    } else {
707        Slots::share(&func, reach.as_ref(), &allocation, &stack.locals, &widths)
708    };
709    let mut layout = Layout { share: Some(&share), ..layout };
710    let mut frame = Frame::of(&func, &allocation, &layout);
711    // A frame bigger than a page is taken by calling the platform's routine for it, and on a
712    // machine whose call leaves the return address in a register that call writes over it. So such
713    // a function is not a leaf, whatever the program called, and has to save the register the way
714    // any other caller does. AArch64 Windows is the one, and clang saves x29 and x30 there too.
715    let page = machine.insts.probe.as_ref().map_or(u32::MAX, |probe| probe.interval);
716    if layout.leaf
717        && machine.conv.chkstk.is_some()
718        && machine.conv.link.is_some()
719        && frame.size() > page
720    {
721        layout = Layout { leaf: false, ..layout };
722        frame = Frame::of(&func, &allocation, &layout);
723    }
724    // The one thing a naked function cannot be given. Everything else the attribute asks for is
725    // something left out, and leaving something out always works; bytes are the one thing the body
726    // may want that only a prologue provides. A local, a spilled value and the arguments of a call
727    // are the three ways to want them, and the answer to all three is the same sentence.
728    if naked && frame.size() > 0 {
729        return Err(Unsupported::Naked { bytes: frame.size() });
730    }
731    // Here because the frame is settled and nothing after this changes how big it is. The name is
732    // the one the source spelled, since that is what gcc's report says and what a person reading
733    // it looks for, and a renamed function is the one place it differs from the symbol.
734    recording.stack.record(Usage {
735        name: names.resolve(source.spelled.unwrap_or(source.name)).to_owned(),
736        named: source.named,
737        declared: source.declared,
738        bytes: frame.usage(),
739        dynamic: frame.grows(),
740    });
741
742    // Here because this is where the two halves of the answer are both in hand: which local is
743    // which declaration came down from selection, and where a local is was settled a line ago.
744    // Nothing further on could work it out, since the frame is not carried past this function and
745    // an offset in a finished instruction says nothing about what the bytes it reaches are for.
746    //
747    // Whatever the command line said about debugging information, because the list is one entry
748    // per local the program named and a function has tens of those at most. Asking the flags would
749    // cost more to thread down here than the list costs to build.
750    //
751    // A local that went in beside something else is left off, because its bytes are its own only
752    // where it is wanted and an answer good at every address would have a debugger print whatever
753    // took its place. It gets stretches instead, at the end with the locals kept in values.
754    func.locals = stack
755        .declared
756        .iter()
757        .filter(|&&(local, _)| share.shared(local).is_none())
758        .filter_map(|&(local, decl)| Some((decl, frame.from_frame_base(local)?)))
759        .collect();
760    let framed: Vec<(u32, i32, &[rucc_regalloc::live::Range])> = stack
761        .declared
762        .iter()
763        .filter_map(|&(local, decl)| {
764            Some((decl, frame.from_frame_base(local)?, share.shared(local)?))
765        })
766        .collect();
767    func.sharing = framed.iter().map(|&(decl, _, _)| decl).collect();
768
769    let scratch = machine.env.scratch(machine.conv.int_class);
770    let protect = guard.map(|guard| Protect {
771        guard,
772        branch: machine.branch,
773        scratch: [scratch[0], scratch[1]],
774    });
775    // A target with no instruction that touches a page without changing it does nothing about the
776    // flag, which is the same answer the protector gives on a target with nowhere to keep its word.
777    // Every target this crate has a back end for has one.
778    //
779    // Or where the platform reaches the pages of every frame whatever the command line said, which
780    // is Windows. The prologue there calls a routine rather than walking, but a frame that grows
781    // while it runs is walked in the body either way: the routine takes its size in a register the
782    // allocator hands out and destroys two more, which is answerable in a prologue and not in the
783    // middle of a function, and the walk needs nothing but the two registers already held back.
784    let probe = (flags.stack_clash || machine.conv.chkstk.is_some())
785        .then_some(machine.insts.probe.as_ref())
786        .flatten()
787        .map(|probe| Probing { probe, branch: machine.branch, scratch: [scratch[0], scratch[1]] });
788    let trace = machine.conv.trace.and_then(|trace| match profile {
789        Profile::No => None,
790        Profile::Early => Some(Tracing { name: trace.early, early: true }),
791        Profile::Late => Some(Tracing { name: trace.late, early: false }),
792    });
793    // And once more for the room a patcher was promised, which is a run of the shortest
794    // instruction that does nothing and so needs the target to have one. Nothing is written on a
795    // target that does not, rather than a run of something longer: the flag counts bytes, and a
796    // patcher writing over the room starts at its front and wants every byte in it to be a place
797    // it could have started at.
798    let pad = flags.patch.any().then_some(machine.insts.pad).flatten().map(|name| Padding {
799        name,
800        before: flags.patch.before,
801        after: flags.patch.after,
802    });
803    let convention = Convention {
804        protect,
805        probe,
806        landing,
807        trace,
808        pad,
809        ..Convention::new(machine.conv, machine.insts)
810    };
811    let moves = finish(&mut func, &allocation, &frame, &stack, convention, names);
812
813    // After the moves are written, because a spill and the reload of it are written by different
814    // decisions of the allocator and what stands between the two is settled by the function they
815    // both went into. Before the layout, because the layout is where the instruction sequence
816    // stops being something a pass may edit.
817    copies::clean(&mut func, &moves, machine.shapes, machine.insts, machine.conv, names);
818
819    // After the moves are cleaned up, since that pass follows what the scratch registers hold, and
820    // before the schedule, which should see the extra `add` as the instruction it is.
821    far(&mut func, machine.insts, machine.conv, scratch, names);
822
823    // After the allocator's moves have been cleaned up, because a schedule chosen around a move
824    // that is about to be taken out is a schedule built around an instruction that is not in the
825    // output. Before the layout, because the layout is the freeze: it writes the jumps the block
826    // order needs and it puts a comparison and the branch that reads it together, and neither
827    // survives an instruction being moved in afterwards. That is section 38.6's placement, and the
828    // reason it is after allocation rather than before is in [`crate::schedule`].
829    if flags.schedule {
830        schedule::insts(
831            &mut func,
832            (machine.conv.stack_pointer, machine.conv.int_class),
833            machine.timing,
834            machine.shapes,
835            machine.flags,
836            names,
837            flags.accurate.unwrap_or(machine.timing.accurate),
838            &fusable,
839        );
840    }
841
842    // Last, because everything before this finds the blocks a function returns from by looking
843    // for the ones that go nowhere, and after this a block that falls through goes nowhere too.
844    layout::blocks(&mut func, machine.branch, names, &fusable, flags.reorder);
845
846    // After the layout for the reason the branches wait for it: a select that reads what a
847    // comparison left is a pair with nothing allowed between, and nothing past here puts anything
848    // there. Before the compare pass, since the comparison this keeps is one that pass may find
849    // was already made.
850    choice::moves(&mut func, machine.branch, machine.flags, machine.shapes, names, &choosable);
851
852    // After the layout rather than before it, which is the whole of what makes it safe. What a
853    // comparison leaves for the instruction behind it to read is not a register and nothing may
854    // come between the two, and the layout is the other pass that writes such a pair. Running
855    // here means there is nothing left that could put an instruction in the middle of one.
856    compare::redundant(&mut func, machine.flags, machine.shapes, names);
857
858    // After that rather than before it, because a comparison it takes out is a write of the
859    // condition state that is gone with it, and this pass is asking which writes of that state are
860    // read. Running in front would see writes the output does not have and turn down rewrites that
861    // are allowed. Nothing here moves an instruction or changes a block, so being behind the
862    // layout's freeze costs it nothing.
863    shorten::shorter(&mut func, machine.short, machine.flags, machine.shapes, names, flags.goal);
864
865    // Once the blocks will not move again, since a head is a block a jump runs backwards to and
866    // which way a jump runs is the layout's answer. Nothing below adds or takes out a block.
867    if flags.align_loops {
868        func.heads = layout::heads(&func);
869    }
870
871    // After everything that edits instructions, because a call is the one instruction all of them
872    // leave alone and a jump out of the function is one some of them would not know about. Nothing
873    // before this sees anything but a call, a return and an epilogue, which is right on its own.
874    tail::jumps(&mut func, &stack.tails, machine.insts, names);
875
876    // Last of all, because a stretch is named by the instructions at either end of it and every
877    // pass above is free to take an instruction out or move one. The frame is wanted here as well
878    // as above, since a value the allocator spilled is in the frame over its stretch rather than in
879    // a register, and it is the same distance from the call frame address the locals were given.
880    func.kept = match line {
881        Some(line) => kept::of(&func, &line, &allocation, &frame, &framed),
882        None => Vec::new(),
883    };
884    Ok(func)
885}
886
887/// Marks every instruction the machine says reads its two sources either way round.
888fn commuting(func: &mut mir::Func, shapes: &MachineInsts, names: &Interner) {
889    let insts: Vec<mir::Inst> = func.blocks().flat_map(|block| func.insts(block)).collect();
890    // Asked once per opcode rather than by name for every instruction. tamnd/rucc#2233.
891    let mut known: Map<mir::Opcode, bool> = Map::default();
892    for inst in insts {
893        let opcode = func[inst].opcode;
894        let commutes =
895            *known.entry(opcode).or_insert_with(|| shapes.commutes(names.resolve(opcode.name())));
896        if commutes {
897            func[inst].flags = func[inst].flags.with(mir::Flags::COMMUTES);
898        }
899    }
900}
901
902#[cfg(test)]
903mod tests {
904    use rucc_ir::{Builder, Flags as IrFlags, Func, Opcode, Restrict, Signature, Type};
905    use rucc_target::x86_64::{REGS, SYSV, WIN64};
906
907    use super::*;
908
909    /// A function of two integers, and the block to fill.
910    fn blank(params: &[Type]) -> (Interner, Func, ir::Block, Vec<ir::Value>) {
911        let mut names = Interner::new();
912        let mut func = Func::new(names.intern("f"), Signature::new());
913        let block = func.create_block();
914        let values = params.iter().map(|&ty| func.append_param(block, ty)).collect();
915        (names, func, block, values)
916    }
917
918    /// The AArch64 machine holds back the two registers a veneer may write and two vector
919    /// registers nothing is passed in, and hands out everything else the convention orders.
920    #[test]
921    fn the_aarch64_machine_holds_back_what_a_veneer_writes() {
922        use rucc_target::aarch64::{self, AAPCS64, FPR, GPR, v};
923        let machine = Machine::aarch64(&AAPCS64);
924        assert_eq!(machine.env.scratch(GPR), [aarch64::X16, aarch64::X17]);
925        assert_eq!(machine.env.scratch(FPR), [v(30), v(31)]);
926        assert_eq!(machine.env.order(GPR), AAPCS64.int_order);
927        assert_eq!(machine.env.order(FPR).len(), 30);
928        assert_eq!(machine.insts.prefix, "a64.");
929        assert_eq!(machine.timing.prefix, machine.shapes.prefix);
930    }
931
932    /// `int f(int a) { return g(a) + a; }` compiled for AArch64 and printed.
933    fn aarch64_call() -> String {
934        let i32 = Type::int(32);
935        let (mut names, mut source, block, args) = blank(&[i32]);
936        let sig = source.add_signature(Signature::new().with_params(&[i32]).with_returns(&[i32]));
937        let callee = names.intern("g");
938        let call = Builder::new(&mut source, block).call(callee, sig, &[args[0]]);
939        let got = source[call].first_result.expect("an integer comes back");
940        let mut build = Builder::new(&mut source, block);
941        let sum = build.binary(Opcode::Add, got, args[0], IrFlags::default());
942        build.ret(&[sum]);
943
944        let machine = Machine::aarch64(&aarch64::AAPCS64);
945        let out =
946            compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
947                .expect("every instruction has a rule");
948        mir::print_func(&out, &names, &aarch64::REGS)
949    }
950
951    #[test]
952    fn an_aarch64_function_that_calls_keeps_its_return_address_in_a_frame_record() {
953        let text = aarch64_call();
954        let lines: Vec<&str> = text.lines().map(str::trim).collect();
955        let first = |what: &str| lines.iter().position(|line| line.contains(what));
956        // The call writes over x30, so it goes on the stack with x29 before anything else, and the
957        // frame pointer is pointed at the pair.
958        let record = first("a64.push_pair_64 $x29, $x30").unwrap_or_else(|| panic!("{text}"));
959        let pointed = first("$x29 = a64.mov_rr_64 $sp").unwrap_or_else(|| panic!("{text}"));
960        let call = first("a64.bl").unwrap_or_else(|| panic!("{text}"));
961        let back = first("a64.pop_pair_64").unwrap_or_else(|| panic!("{text}"));
962        let ret =
963            lines.iter().position(|&line| line == "a64.ret").unwrap_or_else(|| panic!("{text}"));
964        assert!(record < pointed && pointed < call && call < back && back < ret, "{text}");
965        // Every push moves the stack pointer by sixteen, so whatever the frame takes on top of them
966        // is a multiple of sixteen too, and nothing is taken for the word x86 would have owed.
967        for line in &lines {
968            if let Some(rest) = line.split("a64.sub_ri_64 $sp, ").nth(1) {
969                let size: u32 = rest.parse().unwrap_or_else(|_| panic!("{text}"));
970                assert_eq!(size % 16, 0, "{text}");
971            }
972        }
973    }
974
975    #[test]
976    fn an_aarch64_leaf_keeps_no_frame_record() {
977        let i32 = Type::int(32);
978        let (mut names, mut source, block, args) = blank(&[i32, i32]);
979        let mut build = Builder::new(&mut source, block);
980        let sum = build.binary(Opcode::Add, args[0], args[1], IrFlags::default());
981        build.ret(&[sum]);
982
983        let machine = Machine::aarch64(&aarch64::AAPCS64);
984        let out =
985            compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
986                .expect("every instruction has a rule");
987        let text = mir::print_func(&out, &names, &aarch64::REGS);
988        assert!(!text.contains("push"), "{text}");
989        assert!(text.contains("a64.add_rr_32"), "{text}");
990    }
991
992    #[test]
993    fn a_function_comes_out_with_no_virtual_register_left_in_it() {
994        let i32 = Type::int(32);
995        let (mut names, mut source, block, args) = blank(&[i32, i32]);
996        let mut build = Builder::new(&mut source, block);
997        let sum = build.binary(Opcode::Add, args[0], args[1], IrFlags::default());
998        build.ret(&[sum]);
999
1000        let machine = Machine::x86_64(&SYSV);
1001        let out =
1002            compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
1003                .expect("every instruction has a rule");
1004
1005        // `int f(int a, int b) { return a + b; }` end to end. A leaf that spills nothing needs no
1006        // frame at all, so there is no prologue to see. The one move left is the one the machine's
1007        // addition needs, since the sum is written into the register one of the two operands was
1008        // read from and the return wants it in `rax`. The addition is marked as reading them
1009        // either way round, which is why the allocator was free to pick.
1010        assert_eq!(
1011            mir::print_func(&out, &names, &REGS),
1012            "mfunc @f {\n\
1013             block0:\n    \
1014             $rdi($rdi) = x64.arg_val_32\n    \
1015             $rsi($rsi) = x64.arg_val_32\n    \
1016             $rdi(reuse 1) = x64.add_rr_32 commutes $rdi, $rsi\n    \
1017             $rax = x64.mov_rr_64 $rdi\n    \
1018             x64.ret_val_32 $rax($rax)\n    \
1019             x64.ret\n\
1020             }\n"
1021        );
1022    }
1023
1024    #[test]
1025    fn a_declared_local_comes_out_saying_how_far_below_the_call_frame_address_it_is() {
1026        let i32 = Type::int(32);
1027        let (mut names, mut source, block, args) = blank(&[i32]);
1028        let mut build = Builder::new(&mut source, block);
1029        let info = rucc_ir::MemInfo {
1030            size: 4,
1031            align: 4,
1032            order: rucc_ir::MemOrder::NotAtomic,
1033            tbaa: None,
1034            owns: 0,
1035            restrict: Restrict::NONE,
1036        };
1037        let mem = build.func().add_mem(info);
1038        let slot = build.value(
1039            ir::InstData { extra: ir::Extra::Mem(mem), ..ir::InstData::new(Opcode::Alloca) },
1040            Type::PTR,
1041        );
1042        build.func().declare_mem(mem, 5);
1043        build.store(args[0], slot, info, IrFlags::default());
1044        let loaded = build.load(i32, slot, info, IrFlags::default());
1045        build.ret(&[loaded]);
1046
1047        let machine = Machine::x86_64(&SYSV);
1048        let out =
1049            compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
1050                .expect("every instruction has a rule");
1051
1052        // `int f(int a) { int x = a; return x; }` with the address of `x` taken, so it is four
1053        // bytes in the frame. A leaf this small lives in the red zone, so the stack pointer never
1054        // moves. What is below it is a whole word, since everything a frame holds is counted in
1055        // words whether or not it fills one, and the call frame address is one more word above the
1056        // stack pointer for the return address the call pushed.
1057        assert_eq!(out.locals, vec![(5, -16)]);
1058    }
1059
1060    #[test]
1061    fn a_local_kept_in_a_value_comes_out_saying_which_register_holds_it_and_over_what() {
1062        let i32 = Type::int(32);
1063        let (mut names, mut source, block, args) = blank(&[i32]);
1064        let mut build = Builder::new(&mut source, block);
1065        let sum = build.binary(Opcode::Add, args[0], args[0], IrFlags::default());
1066        build.func().declare_value(sum, 5);
1067        build.ret(&[sum]);
1068
1069        let machine = Machine::x86_64(&SYSV);
1070        let flags = Flags { debug: true, ..Flags::default() };
1071        let out = compile(&mut source, &mut names, &machine, &Elsewhere::default(), flags)
1072            .expect("every instruction has a rule");
1073
1074        // `int f(int a) { int x = a + a; return x; }` with nothing taking the address of `x`, so
1075        // it never reaches the frame and the only answer about it is a register. The sum is
1076        // written by the addition and read by the move that puts it where the return wants it, so
1077        // the stretch is one instruction long and it is the move rather than the addition.
1078        assert_eq!(out.kept.len(), 1, "one stretch: {:?}", out.kept);
1079        assert_eq!(out.kept[0].decl, 5);
1080        assert!(matches!(out.kept[0].at, mir::Where::Reg { .. }), "a register: {:?}", out.kept[0]);
1081        assert!(out.locals.is_empty(), "nothing in the frame: {:?}", out.locals);
1082    }
1083
1084    /// What `-Zlowering` is built out of, and the reason it is worth a test here rather than only
1085    /// in `crate::lowering`: the group has to be the thing this pipeline runs. A lowering added to
1086    /// a line of this function instead of to `Step::GROUP` would still work and would still be
1087    /// untested, and the record coming back with one entry per member is what catches it.
1088    #[test]
1089    fn every_member_of_the_lowering_group_is_run_by_the_compilation_and_says_what_it_did() {
1090        let i32 = Type::int(32);
1091        let (mut names, mut source, block, args) = blank(&[i32]);
1092        let mut build = Builder::new(&mut source, block);
1093        let swapped = build.unary(Opcode::Bswap, args[0], i32);
1094        build.ret(&[swapped]);
1095
1096        let mut lowerings = Lowerings::asked(true);
1097        compile_recording(
1098            &mut source,
1099            &mut names,
1100            &Machine::x86_64(&SYSV),
1101            &Elsewhere::default(),
1102            Flags::default(),
1103            &mut Recording {
1104                fired: &mut Fired::new(),
1105                pressure: &mut Pressure::new(),
1106                stack: &mut StackUsage::new(),
1107                lowerings: &mut lowerings,
1108            },
1109        )
1110        .expect("every instruction has a rule");
1111
1112        assert_eq!(lowerings.functions(), 1);
1113        let listing = lowerings.listing();
1114        assert!(listing.contains("lowering f\n"), "{listing}");
1115        for step in lowering::Step::GROUP {
1116            assert!(listing.contains(step.name()), "{} did not run: {listing}", step.name());
1117        }
1118        // The byte reversal went through the group rather than reaching the selector, which has no
1119        // rule for one.
1120        assert!(listing.contains("bytes"), "{listing}");
1121        assert!(!listing.contains("left 1"), "something the group answers for survived: {listing}");
1122    }
1123
1124    /// What `-Zrule-coverage` is built out of: the rules a compilation fired, recorded as it went.
1125    /// The second function adds to the first rather than replacing it, which is what makes one of
1126    /// these files the answer for a whole command line rather than for whichever function was last.
1127    #[test]
1128    fn which_rules_lowered_a_function_is_something_the_compilation_can_be_asked_for() {
1129        let i32 = Type::int(32);
1130        let (mut names, mut source, block, args) = blank(&[i32, i32]);
1131        let mut build = Builder::new(&mut source, block);
1132        let sum = build.binary(Opcode::Add, args[0], args[1], IrFlags::default());
1133        build.ret(&[sum]);
1134
1135        let machine = Machine::x86_64(&SYSV);
1136        let mut fired = Fired::new();
1137        compile_recording(
1138            &mut source,
1139            &mut names,
1140            &machine,
1141            &Elsewhere::default(),
1142            Flags::default(),
1143            &mut Recording {
1144                fired: &mut fired,
1145                pressure: &mut Pressure::new(),
1146                stack: &mut StackUsage::new(),
1147                lowerings: &mut Lowerings::asked(true),
1148            },
1149        )
1150        .expect("every instruction has a rule");
1151        let one = fired.count();
1152        assert!(one > 0, "an add and a return went through the table and nothing was recorded");
1153
1154        let listing = fired.listing(&select::x86_64::TABLE);
1155        assert_eq!(listing.lines().filter(|line| line.starts_with("fired ")).count(), one);
1156        assert!(
1157            listing.contains(&format!("{one} of ")),
1158            "{}",
1159            listing.lines().next().unwrap_or("")
1160        );
1161
1162        // The same rules again plus the ones a subtraction needs, into the same record.
1163        let (mut names, mut source, block, args) = blank(&[i32, i32]);
1164        let mut build = Builder::new(&mut source, block);
1165        let difference = build.binary(Opcode::Sub, args[0], args[1], IrFlags::default());
1166        build.ret(&[difference]);
1167        compile_recording(
1168            &mut source,
1169            &mut names,
1170            &machine,
1171            &Elsewhere::default(),
1172            Flags::default(),
1173            &mut Recording {
1174                fired: &mut fired,
1175                pressure: &mut Pressure::new(),
1176                stack: &mut StackUsage::new(),
1177                lowerings: &mut Lowerings::asked(true),
1178            },
1179        )
1180        .expect("every instruction has a rule");
1181        assert!(fired.count() > one, "a subtraction is not an addition");
1182    }
1183
1184    #[test]
1185    fn a_function_that_calls_takes_a_frame_and_gives_it_back() {
1186        let i32 = Type::int(32);
1187        let (mut names, mut source, block, args) = blank(&[i32]);
1188        let sig = source.add_signature(Signature::new().with_params(&[i32]).with_returns(&[i32]));
1189        let callee = names.intern("g");
1190        let call = Builder::new(&mut source, block).call(callee, sig, &[args[0]]);
1191        let got = source[call].first_result.expect("an integer comes back");
1192        let mut build = Builder::new(&mut source, block);
1193        let sum = build.binary(Opcode::Add, got, args[0], IrFlags::default());
1194        build.ret(&[sum]);
1195
1196        let machine = Machine::x86_64(&SYSV);
1197        let out =
1198            compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
1199                .expect("every instruction has a rule");
1200
1201        // `int f(int a) { return g(a) + a; }`. Not a leaf, so the stack pointer moves and the
1202        // register the value that outlives the call went to is one the prologue saves.
1203        let text = mir::print_func(&out, &names, &REGS);
1204        assert!(text.contains("x64.push_64 $rbx"), "{text}");
1205        assert!(text.contains("$rbx = x64.pop_64"), "{text}");
1206        assert!(text.contains("x64.call $rdi($rdi), @g"), "{text}");
1207        assert!(!text.contains('%'), "{text}");
1208    }
1209
1210    /// `int f(int a, ...) { return g(a, ...); }` with that many arguments, compiled with sibling
1211    /// calls on or off, as the machine code that comes out.
1212    fn tail(count: usize, sibling: bool) -> String {
1213        let i32 = Type::int(32);
1214        let params = vec![i32; count];
1215        let mut names = Interner::new();
1216        let signature = Signature::new().with_params(&params).with_returns(&[i32]);
1217        let mut source = Func::new(names.intern("f"), signature.clone());
1218        let block = source.create_block();
1219        let args: Vec<_> = params.iter().map(|&ty| source.append_param(block, ty)).collect();
1220        let sig = source.add_signature(signature);
1221        let callee = names.intern("g");
1222        let call = Builder::new(&mut source, block).call(callee, sig, &args);
1223        let got = source[call].first_result.expect("an integer comes back");
1224        Builder::new(&mut source, block).ret(&[got]);
1225
1226        let machine = Machine::x86_64(&SYSV);
1227        let flags = Flags { sibling, ..Flags::default() };
1228        let out = compile(&mut source, &mut names, &machine, &Elsewhere::default(), flags)
1229            .expect("every instruction has a rule");
1230        mir::print_func(&out, &names, &REGS)
1231    }
1232
1233    /// A call whose answer is the answer ends in a jump to it once the frame is given back, and
1234    /// only when the flag says so.
1235    #[test]
1236    fn a_call_in_tail_position_is_a_jump_when_asked_for() {
1237        let text = tail(2, true);
1238        assert!(text.contains("x64.jmp_away @g"), "{text}");
1239        assert!(!text.contains("x64.call"), "{text}");
1240        assert!(!text.contains("x64.ret"), "{text}");
1241
1242        let text = tail(2, false);
1243        assert!(text.contains("x64.call"), "{text}");
1244        assert!(text.contains("x64.ret"), "{text}");
1245    }
1246
1247    /// Eight arguments are two more than there are registers for, so two go in the argument area
1248    /// at the bottom of this frame, and the call has to be made while the frame is still there.
1249    #[test]
1250    fn a_call_that_needs_the_argument_area_stays_a_call() {
1251        let text = tail(8, true);
1252        assert!(text.contains("x64.call"), "{text}");
1253        assert!(!text.contains("x64.jmp_away"), "{text}");
1254    }
1255
1256    #[test]
1257    fn the_other_convention_is_the_same_function_somewhere_else() {
1258        let i32 = Type::int(32);
1259        let (mut names, mut source, block, args) = blank(&[i32, i32]);
1260        let mut build = Builder::new(&mut source, block);
1261        let sum = build.binary(Opcode::Add, args[0], args[1], IrFlags::default());
1262        build.ret(&[sum]);
1263
1264        let machine = Machine::x86_64(&WIN64);
1265        let out =
1266            compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
1267                .expect("every instruction has a rule");
1268
1269        // The arguments arrive in `rcx` and `rdx` here rather than in `rdi` and `rsi`, which is
1270        // the whole of what changed, and it changed because the convention was asked.
1271        let text = mir::print_func(&out, &names, &REGS);
1272        assert!(text.contains("$rcx($rcx) = x64.arg_val_32"), "{text}");
1273        assert!(text.contains("$rdx($rdx) = x64.arg_val_32"), "{text}");
1274        assert!(!text.contains("$rdi"), "{text}");
1275    }
1276
1277    #[test]
1278    fn a_function_with_a_branch_in_it_goes_through_every_pass() {
1279        let i32 = Type::int(32);
1280        let (mut names, mut source, entry, args) = blank(&[i32, i32]);
1281        let then = source.create_block();
1282        let join = source.create_block();
1283        let got = source.append_param(join, i32);
1284        let mut build = Builder::new(&mut source, entry);
1285        let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
1286        build.br_if(cond, then, &[], join, &[args[1]]);
1287        Builder::new(&mut source, then).jump(join, &[args[0]]);
1288        Builder::new(&mut source, join).ret(&[got]);
1289
1290        let machine = Machine::x86_64(&SYSV);
1291        let out =
1292            compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
1293                .expect("every instruction has a rule");
1294
1295        // The else arm is a critical edge carrying a value, so a block that nothing lowered is in
1296        // there, which is the pass between lowering and allocation doing its job. Without it the
1297        // allocator would have asserted rather than compiled this.
1298        assert_eq!(out.block_count(), 4);
1299
1300        // `int f(int a, int b) { return a < b ? a : b; }` end to end, and the last pass is what
1301        // this pins. The branch became a test and one jump, and it is the jump taken when the
1302        // condition failed, because the arm the condition is true for is the block laid out next
1303        // and a block falls into the block laid out next. The other arm is the empty block the
1304        // edge splitting left, which is where the move the edge carries ended up, and it falls
1305        // into the join as well. What is left is one jump in the whole function. Both arms write
1306        // the join's parameter straight into `rax`, because the return at the bottom insists on
1307        // that register and the moves the edges carry are free to name it.
1308        let text = mir::print_func(&out, &names, &REGS);
1309        assert_eq!(
1310            text,
1311            "mfunc @f {\n\
1312             block0:\n    \
1313             $rdi($rdi) = x64.arg_val_32\n    \
1314             $rsi($rsi) = x64.arg_val_32\n    \
1315             x64.cmp_rr_32 $rdi, $rsi\n    \
1316             x64.jcc_ge block2, block1\n\
1317             \nblock1:\n    \
1318             $rax = x64.mov_rr_64 $rdi\n    \
1319             x64.jmp block3\n\
1320             \nblock2:\n    \
1321             $rax = x64.mov_rr_64 $rsi, block3\n\
1322             \nblock3:\n    \
1323             x64.ret_val_32 $rax($rax)\n    \
1324             x64.ret\n\
1325             }\n"
1326        );
1327    }
1328
1329    /// A loop that swaps its two values round every time it goes, which is `gcd`, and which is
1330    /// the smallest program that caught two ways of losing a value. Both were found by running
1331    /// what came out rather than by reading it, and both are pinned here rather than only where
1332    /// they were fixed, because what is wrong with either of them is only visible in the whole
1333    /// function.
1334    #[test]
1335    fn a_loop_that_carries_its_values_round_keeps_all_of_them() {
1336        let i32 = Type::int(32);
1337        let (mut names, mut source, entry, args) = blank(&[i32, i32]);
1338        let head = source.create_block();
1339        let body = source.create_block();
1340        let exit = source.create_block();
1341        let left = source.append_param(head, i32);
1342        let right = source.append_param(head, i32);
1343        Builder::new(&mut source, entry).jump(head, &[args[0], args[1]]);
1344        let mut build = Builder::new(&mut source, head);
1345        let zero = build.iconst(i32, 0);
1346        let more = build.icmp(rucc_ir::IntPred::Ne, right, zero);
1347        build.br_if(more, body, &[], exit, &[left]);
1348        let mut build = Builder::new(&mut source, body);
1349        let rest = build.binary(Opcode::SRem, left, right, IrFlags::default());
1350        build.jump(head, &[right, rest]);
1351        let result = source.append_param(exit, i32);
1352        Builder::new(&mut source, exit).ret(&[result]);
1353
1354        let machine = Machine::x86_64(&SYSV);
1355        let out =
1356            compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
1357                .expect("every instruction has a rule");
1358
1359        // `int gcd(int a, int b) { while (b) { int t = a % b; a = b; b = t; } return a; }`. Two
1360        // things in here were wrong and each of them returned three from a program that gcc
1361        // returns forty two from.
1362        //
1363        // The first is in the entry block. The move the edge into the loop asks for writes `rsi`,
1364        // and the second argument has to be taken out of `rsi` before it does. An edit at the end
1365        // of a block used to go in front of the last instruction, on the reasoning that the last
1366        // instruction is the branch, and the block's jump is not an instruction until the layout
1367        // has run, so it went in front of the `arg_val` whose own move had not been made yet.
1368        //
1369        // The second is in the loop body. A division writes both a quotient and a remainder, and
1370        // only the remainder is wanted here, so the quotient is a value nothing reads. It used to
1371        // be given the same register as the remainder, because a value written early was live at
1372        // one point and that point was in front of where the remainder was written. The copy that
1373        // takes the quotient nowhere then landed on top of the remainder. The remainder is written
1374        // early as well now, which is a separate thing the target has to say and is why both
1375        // answers read `early` here: `rdx` is filled by the sign extension before the division
1376        // reads its divisor, so nothing else may be sitting in it at that point either.
1377        //
1378        // What asks whether the second argument is zero reads as a test rather than a comparison
1379        // because `crate::shorten` runs last and writes the shorter of the two, which asks the
1380        // machine the same thing and leaves the same condition state for the jump behind it.
1381        assert_eq!(
1382            mir::print_func(&out, &names, &REGS),
1383            "mfunc @f {\n\
1384             block0:\n    \
1385             $rdi($rdi) = x64.arg_val_32\n    \
1386             $rsi($rsi) = x64.arg_val_32\n    \
1387             $rcx = x64.mov_rr_64 $rdi, block1\n\
1388             \nblock1:\n    \
1389             x64.test_rr_32 $rsi\n    \
1390             x64.jcc_e block3, block2\n\
1391             \nblock2:\n    \
1392             $rax = x64.mov_rr_64 $rcx\n    \
1393             early $rdx($rdx), early $rax($rax) = x64.idiv_rem_32 $rax($rax), $rsi\n    \
1394             $rdi = x64.mov_rr_64 $rax\n    \
1395             $rcx = x64.mov_rr_64 $rsi\n    \
1396             $rsi = x64.mov_rr_64 $rdx\n    \
1397             x64.jmp block1\n\
1398             \nblock3:\n    \
1399             $rax = x64.mov_rr_64 $rcx\n    \
1400             x64.ret_val_32 $rax($rax)\n    \
1401             x64.ret\n\
1402             }\n"
1403        );
1404    }
1405
1406    /// `spec/10-backend.md` section 10.1 says `--emit=mir-final` round-trips, and a function with
1407    /// a branch in it is the one where that is worth checking: after the layout has run, where a
1408    /// jump goes is nowhere in the instruction, so the text has to carry it on the block and the
1409    /// parser has to put it back on the block it came off.
1410    #[test]
1411    fn a_function_that_has_been_laid_out_reads_back_as_the_same_function() {
1412        let i32 = Type::int(32);
1413        let (mut names, mut source, entry, args) = blank(&[i32, i32]);
1414        let then = source.create_block();
1415        let join = source.create_block();
1416        let got = source.append_param(join, i32);
1417        let mut build = Builder::new(&mut source, entry);
1418        let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
1419        build.br_if(cond, then, &[], join, &[args[1]]);
1420        Builder::new(&mut source, then).jump(join, &[args[0]]);
1421        Builder::new(&mut source, join).ret(&[got]);
1422
1423        let machine = Machine::x86_64(&SYSV);
1424        let out =
1425            compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
1426                .expect("every instruction has a rule");
1427
1428        let text = mir::print_func(&out, &names, &REGS);
1429        let read = rucc_mir::parse(&text, &mut names, &REGS).expect("what the printer wrote");
1430        assert_eq!(mir::print(&read, &names, &REGS), text);
1431    }
1432
1433    #[test]
1434    fn a_function_this_cannot_lower_is_reported_rather_than_compiled() {
1435        let f80 = Type::float(rucc_ir::Float::F80);
1436        let (mut names, mut source, block, args) = blank(&[f80, Type::int(64)]);
1437        Builder::new(&mut source, block).ret(&args);
1438
1439        // One of these comes back on the x87 stack and the other in a register, and the only pair
1440        // that stack holds is two `long double` halves of one complex value. So this is refused
1441        // rather than lowered, and it is the convention that refuses it rather than anything about
1442        // the instructions.
1443        let machine = Machine::x86_64(&SYSV);
1444        let failed =
1445            compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
1446                .expect_err("a long double cannot come back beside another value");
1447        assert_eq!(failed.to_string(), "what this function gives back is on the x87 stack");
1448    }
1449
1450    /// A `long double` in and a `long double` out, which is the whole of what the convention says
1451    /// about the type and is two different answers rather than one.
1452    ///
1453    /// It arrives in the caller's argument area, so what the parameter is is the address of the
1454    /// bytes and the function reads them where they are. It goes back on the x87 stack, so the
1455    /// return is an `fld` and nothing else, and the value is still on that stack when the function
1456    /// returns, which is the one time anything here leaves it that way.
1457    ///
1458    /// The addresses are gone from the instruction listing, which is [`crate::fold`]: an argument's
1459    /// address is a `lea` off the stack pointer and the `fld` that reads it has room for that
1460    /// address itself, so the offset the frame layout works out is written into the `fld`.
1461    #[test]
1462    fn a_long_double_arrives_in_memory_and_goes_back_on_the_x87_stack() {
1463        let f80 = Type::float(rucc_ir::Float::F80);
1464        let (mut names, mut source, block, args) = blank(&[f80, f80]);
1465        let mut build = Builder::new(&mut source, block);
1466        let sum = build.binary(Opcode::FAdd, args[0], args[1], IrFlags::default());
1467        build.ret(&[sum]);
1468
1469        let machine = Machine::x86_64(&SYSV);
1470        let out =
1471            compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
1472                .expect("every instruction has a rule");
1473
1474        let text = mir::print_func(&out, &names, &REGS);
1475        // The two parameters, sixteen bytes apart, read out of the caller's frame rather than out
1476        // of a register, and the answer left on the stack by the last instruction in the function.
1477        assert!(text.contains("x64.fld_t [$rsp + 32]"), "{text}");
1478        assert!(text.contains("x64.fld_t [$rsp + 48]"), "{text}");
1479        assert!(!text.contains("x64.lea_64"), "an address every reader took is gone: {text}");
1480        assert!(!text.contains("x64.ret_val"), "nothing comes back in a register: {text}");
1481        // What comes after the `fld` is the epilogue, which gives the frame back and touches
1482        // nothing in the unit, so the value is where the caller looks for it when the `ret` runs.
1483        let end: Vec<&str> = text.lines().rev().skip(1).take(3).map(str::trim).collect();
1484        assert_eq!(end, ["x64.ret", "$rsp = x64.add_ri_64 $rsp, 24", "x64.fld_t [$rsp]"], "{text}");
1485    }
1486
1487    /// A `_Complex long double` goes back on the x87 stack as two values, the real half on top.
1488    ///
1489    /// Each half arrives in memory like any `long double`, and the return loads the imaginary half
1490    /// first so that the real one is in `st(0)` above it, which is where the caller looks for each.
1491    /// A call to such a function takes both off again, the real half first, so the stack is empty
1492    /// by the time anything else touches it.
1493    #[test]
1494    fn a_complex_long_double_goes_back_on_the_x87_stack_as_a_pair() {
1495        let f80 = Type::float(rucc_ir::Float::F80);
1496        let (mut names, mut source, block, args) = blank(&[f80, f80]);
1497        Builder::new(&mut source, block).ret(&[args[1], args[0]]);
1498
1499        let machine = Machine::x86_64(&SYSV);
1500        let out =
1501            compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
1502                .expect("the pair is what the convention asks for");
1503        let text = mir::print_func(&out, &names, &REGS);
1504        // The second parameter is the real half here, so it is loaded last and ends up on top. There
1505        // is no frame, so the first parameter is right above the return address.
1506        let lines: Vec<&str> = text.lines().map(str::trim).collect();
1507        let imaginary = lines.iter().position(|&line| line == "x64.fld_t [$rsp + 8]");
1508        let real = lines.iter().position(|&line| line == "x64.fld_t [$rsp + 24]");
1509        assert!(imaginary.is_some() && real == imaginary.map(|at| at + 1), "{text}");
1510        assert!(!text.contains("x64.ret_val"), "nothing comes back in a register: {text}");
1511
1512        let (mut names, mut source, block, _) = blank(&[]);
1513        let sig = source.add_signature(Signature::new().with_returns(&[f80, f80]));
1514        let callee = names.intern("g");
1515        let call = Builder::new(&mut source, block).call(callee, sig, &[]);
1516        let halves: Vec<ir::Value> = source[call].results().collect();
1517        Builder::new(&mut source, block).ret(&[halves[1], halves[0]]);
1518        let out =
1519            compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
1520                .expect("a call can take the pair off");
1521        let text = mir::print_func(&out, &names, &REGS);
1522        assert_eq!(text.matches("x64.fstp_t").count(), 2, "{text}");
1523        assert_eq!(text.matches("x64.fld_t").count(), 2, "{text}");
1524    }
1525
1526    /// The whole of the second register class, end to end: two floats arrive in vector registers,
1527    /// the arithmetic happens in one, and the answer goes back in the register the convention
1528    /// names. Nothing here touches the general purpose file, which is the point.
1529    #[test]
1530    fn a_float_is_added_in_the_register_file_it_arrives_in() {
1531        let f32 = Type::float(rucc_ir::Float::F32);
1532        let (mut names, mut source, block, args) = blank(&[f32, f32]);
1533        let mut build = Builder::new(&mut source, block);
1534        let sum = build.binary(Opcode::FAdd, args[0], args[1], ir::Flags::default());
1535        build.ret(&[sum]);
1536
1537        let machine = Machine::x86_64(&SYSV);
1538        let out =
1539            compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
1540                .expect("every instruction has a rule");
1541
1542        let text = mir::print_func(&out, &names, &REGS);
1543        assert!(text.contains("x64.addss_rr"), "{text}");
1544        assert!(text.contains("$xmm0"), "{text}");
1545        assert!(!text.contains("$rax"), "{text}");
1546    }
1547
1548    /// A float moved between a register and memory, which is the instruction that decides which
1549    /// file the value is in and is a different one from the `mov` that moves the same four bytes.
1550    #[test]
1551    fn a_float_read_from_memory_and_written_back_uses_the_scalar_moves() {
1552        let f64 = Type::float(rucc_ir::Float::F64);
1553        let (mut names, mut source, block, args) = blank(&[Type::PTR, f64]);
1554        let mut build = Builder::new(&mut source, block);
1555        let info = rucc_ir::MemInfo {
1556            size: 8,
1557            align: 8,
1558            order: rucc_ir::MemOrder::NotAtomic,
1559            tbaa: None,
1560            owns: 0,
1561            restrict: Restrict::NONE,
1562        };
1563        let read = build.load(f64, args[0], info, ir::Flags::default());
1564        let sum = build.binary(Opcode::FAdd, read, args[1], ir::Flags::default());
1565        build.store(sum, args[0], info, ir::Flags::default());
1566        build.ret(&[sum]);
1567
1568        let machine = Machine::x86_64(&SYSV);
1569        let out =
1570            compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
1571                .expect("every instruction has a rule");
1572
1573        let text = mir::print_func(&out, &names, &REGS);
1574        assert!(text.contains("x64.movsd_rm"), "{text}");
1575        assert!(text.contains("x64.movsd_mr"), "{text}");
1576        // Not the aligned whole register move, which is what a spill uses and is the one
1577        // instruction here that would read and write more than the program asked for.
1578        assert!(!text.contains("x64.movaps_rm"), "{text}");
1579        assert!(!text.contains("x64.movaps_mr"), "{text}");
1580    }
1581
1582    /// The same journey at the format the machine only moves, which is the whole of what it can do
1583    /// with one: in from memory, back out to memory, in and out of a register, and back to the
1584    /// caller.
1585    ///
1586    /// No arithmetic, because there is no instruction for any and every one of them is a call to
1587    /// the runtime. What this says is that the value gets where a call would need it to be.
1588    #[test]
1589    fn a_quad_float_read_from_memory_and_written_back_uses_the_whole_register_move() {
1590        let quad = Type::float(rucc_ir::Float::F128);
1591        let (mut names, mut source, block, args) = blank(&[Type::PTR, quad]);
1592        let mut build = Builder::new(&mut source, block);
1593        let info = rucc_ir::MemInfo {
1594            size: 16,
1595            align: 16,
1596            order: rucc_ir::MemOrder::NotAtomic,
1597            tbaa: None,
1598            owns: 0,
1599            restrict: Restrict::NONE,
1600        };
1601        let read = build.load(quad, args[0], info, ir::Flags::default());
1602        build.store(args[1], args[0], info, ir::Flags::default());
1603        build.ret(&[read]);
1604
1605        let machine = Machine::x86_64(&SYSV);
1606        let out =
1607            compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
1608                .expect("every instruction has a rule");
1609
1610        let text = mir::print_func(&out, &names, &REGS);
1611        assert!(text.contains("x64.movaps_rm"), "{text}");
1612        assert!(text.contains("x64.movaps_mr"), "{text}");
1613        assert!(text.contains("x64.arg_val_f128"), "{text}");
1614        assert!(text.contains("x64.ret_val_f128"), "{text}");
1615        // In the vector file and not the general purpose one, which is where the two eightbytes
1616        // of this value would have gone if it had been classified as a pair of integers.
1617        assert!(text.contains("$xmm0"), "{text}");
1618        assert!(!text.contains("gpr($rax)"), "{text}");
1619    }
1620
1621    /// Both conversions between an unsigned word and a `long double`, all the way to instructions.
1622    ///
1623    /// What the rewrite writes and what the x87 group in [`crate::lower`] has are two lists put
1624    /// together in two different files, and this is where they meet. The rewrite is free to write
1625    /// any instruction it likes at any width, and at this width almost none of them can be
1626    /// lowered, so a correction written the way the narrower ones are written would pass its own
1627    /// tests next door and fail here.
1628    #[test]
1629    fn an_unsigned_word_and_a_long_double_convert_into_each_other() {
1630        let f80 = Type::float(rucc_ir::Float::F80);
1631        let (mut names, mut source, block, args) = blank(&[Type::PTR, Type::int(64)]);
1632        let mut build = Builder::new(&mut source, block);
1633        let info = rucc_ir::MemInfo {
1634            size: 16,
1635            align: 16,
1636            order: rucc_ir::MemOrder::NotAtomic,
1637            tbaa: None,
1638            owns: 0,
1639            restrict: Restrict::NONE,
1640        };
1641        let wide = build.unary(Opcode::UIToFP, args[1], f80);
1642        build.store(wide, args[0], info, ir::Flags::default());
1643        let read = build.load(f80, args[0], info, ir::Flags::default());
1644        let back = build.unary(Opcode::FPToUI, read, Type::int(64));
1645        build.ret(&[back]);
1646
1647        let machine = Machine::x86_64(&SYSV);
1648        let out =
1649            compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
1650                .expect("every instruction has a rule");
1651
1652        let text = mir::print_func(&out, &names, &REGS);
1653        // The signed conversions in both directions, the constants that correct them, and the
1654        // multiply that takes a correction or leaves it. Nothing here reaches a wide register.
1655        assert!(text.contains("x64.fild_ll"), "the integer goes in as a signed one: {text}");
1656        assert!(text.contains("x64.fistp_ll"), "and comes back out as one: {text}");
1657        assert!(text.contains("x64.fmul_p"), "the correction is taken or not: {text}");
1658        assert!(text.contains("x64.fadd_p"), "and applied one way: {text}");
1659        assert!(text.contains("x64.fsubr_p"), "and the other: {text}");
1660        assert!(!text.contains("xmm"), "no part of this is in a vector register: {text}");
1661    }
1662
1663    /// A value carried from one register file to the other, which is what a conversion is. The
1664    /// instruction reads one file and writes the other, and the allocator has to know that: a
1665    /// conversion whose operands were both said to be in one file would put the answer in a
1666    /// register the next instruction cannot reach.
1667    #[test]
1668    fn a_conversion_carries_the_value_into_the_other_register_file() {
1669        let f64 = Type::float(rucc_ir::Float::F64);
1670        let (mut names, mut source, block, args) = blank(&[f64]);
1671        let mut build = Builder::new(&mut source, block);
1672        let whole = build.unary(Opcode::FPToSI, args[0], Type::int(32));
1673        let back = build.unary(Opcode::SIToFP, whole, f64);
1674        build.ret(&[back]);
1675
1676        let machine = Machine::x86_64(&SYSV);
1677        let out =
1678            compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
1679                .expect("every instruction has a rule");
1680
1681        // The conversion that cuts towards zero rather than the one that rounds, which is what C
1682        // means by the cast, and the argument and the answer in the register the convention names.
1683        let text = mir::print_func(&out, &names, &REGS);
1684        assert!(text.contains("x64.cvttsd2si_32"), "{text}");
1685        assert!(text.contains("x64.cvtsi2sd_32"), "{text}");
1686        assert!(text.contains("$xmm0"), "{text}");
1687    }
1688
1689    /// The other way of putting a float and a number together, which keeps every bit rather than
1690    /// the value and is what a program reading the bits of a `double` asks for.
1691    #[test]
1692    fn a_bitcast_between_the_files_is_the_move_that_changes_no_bit() {
1693        let f64 = Type::float(rucc_ir::Float::F64);
1694        let (mut names, mut source, block, args) = blank(&[f64]);
1695        let mut build = Builder::new(&mut source, block);
1696        let bits = build.unary(Opcode::Bitcast, args[0], Type::int(64));
1697        build.ret(&[bits]);
1698
1699        let machine = Machine::x86_64(&SYSV);
1700        let out =
1701            compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
1702                .expect("every instruction has a rule");
1703
1704        let text = mir::print_func(&out, &names, &REGS);
1705        assert!(text.contains("x64.movq_from_xmm"), "{text}");
1706        assert!(!text.contains("cvt"), "{text}");
1707    }
1708
1709    /// A comparison whose answer the machine has a condition for, which is most of them.
1710    #[test]
1711    fn a_float_comparison_is_the_compare_and_the_byte_a_condition_sets() {
1712        let f64 = Type::float(rucc_ir::Float::F64);
1713        let (mut names, mut source, block, args) = blank(&[f64, f64]);
1714        let mut build = Builder::new(&mut source, block);
1715        let less = build.fcmp(rucc_ir::FloatPred::Olt, args[0], args[1], ir::Flags::default());
1716        let wide = build.unary(Opcode::ZExt, less, Type::int(32));
1717        build.ret(&[wide]);
1718
1719        let machine = Machine::x86_64(&SYSV);
1720        let out =
1721            compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
1722                .expect("every instruction has a rule");
1723
1724        // Less than is greater than with the operands the other way round, and the machine has no
1725        // condition for the first, so the rule that fires is the one that swaps them.
1726        let text = mir::print_func(&out, &names, &REGS);
1727        assert!(text.contains("x64.ucomisd_set_a"), "{text}");
1728    }
1729
1730    /// The two comparisons that are not one condition. An ordered equality is the flag that means
1731    /// equal or unordered and the flag that says it was ordered, so the instruction writes a
1732    /// second byte and reads it back, and what this is about is that the second byte gets a
1733    /// register of its own rather than the one the answer is in.
1734    #[test]
1735    fn an_equality_between_floats_gets_a_register_for_the_byte_it_needs_twice() {
1736        let f64 = Type::float(rucc_ir::Float::F64);
1737        let (mut names, mut source, block, args) = blank(&[f64, f64]);
1738        let mut build = Builder::new(&mut source, block);
1739        let same = build.fcmp(rucc_ir::FloatPred::Oeq, args[0], args[1], ir::Flags::default());
1740        let wide = build.unary(Opcode::ZExt, same, Type::int(32));
1741        build.ret(&[wide]);
1742
1743        let machine = Machine::x86_64(&SYSV);
1744        let out =
1745            compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
1746                .expect("every instruction has a rule");
1747
1748        let text = mir::print_func(&out, &names, &REGS);
1749        let line = text
1750            .lines()
1751            .find(|line| line.contains("x64.ucomisd_set_e_and_np"))
1752            .expect("the rule for an ordered equality fired");
1753        let written: Vec<&str> = line
1754            .split_once('=')
1755            .expect("the instruction writes something")
1756            .0
1757            .split(',')
1758            .map(str::trim)
1759            .collect();
1760        assert_eq!(written.len(), 2, "{line}");
1761        assert_ne!(written[0], written[1], "{line}");
1762    }
1763
1764    /// A float literal, which is the last float thing a C program writes that had no lowering.
1765    /// The rewrite that puts it in reach is in `expand`, and what this is about is that the two
1766    /// halves meet: the constant is spelled in a general purpose register and moved across.
1767    #[test]
1768    fn a_float_constant_is_the_bits_in_a_register_and_the_move_that_carries_them_over() {
1769        let f64 = Type::float(rucc_ir::Float::F64);
1770        let (mut names, mut source, block, _) = blank(&[]);
1771        let mut build = Builder::new(&mut source, block);
1772        let half = build.fconst(f64, 0x3fe0_0000_0000_0000);
1773        build.ret(&[half]);
1774
1775        let machine = Machine::x86_64(&SYSV);
1776        let out =
1777            compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
1778                .expect("every instruction has a rule");
1779
1780        let text = mir::print_func(&out, &names, &REGS);
1781        assert!(text.contains("x64.mov_ri_64"), "{text}");
1782        assert!(text.contains("x64.movq_to_xmm"), "{text}");
1783    }
1784
1785    /// A negation, which is the sign bit flipped and nothing else touched, so what the machine
1786    /// does is an exclusive or in a general purpose register rather than any float instruction.
1787    #[test]
1788    fn a_negation_is_the_sign_bit_flipped_and_no_float_instruction_at_all() {
1789        let f64 = Type::float(rucc_ir::Float::F64);
1790        let (mut names, mut source, block, args) = blank(&[f64]);
1791        let mut build = Builder::new(&mut source, block);
1792        let less = build.unary(Opcode::FNeg, args[0], f64);
1793        build.ret(&[less]);
1794
1795        let machine = Machine::x86_64(&SYSV);
1796        let out =
1797            compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
1798                .expect("every instruction has a rule");
1799
1800        let text = mir::print_func(&out, &names, &REGS);
1801        assert!(text.contains("x64.xor_rr_64"), "{text}");
1802        assert!(!text.contains("sub"), "a negation is not a subtraction: {text}");
1803    }
1804
1805    #[test]
1806    fn the_flags_reach_the_frame() {
1807        let i32 = Type::int(32);
1808        let (mut names, mut source, block, args) = blank(&[i32]);
1809        Builder::new(&mut source, block).ret(&[args[0]]);
1810
1811        let machine = Machine::x86_64(&SYSV);
1812        let flags = Flags { frame_pointer: true, profile: Profile::No, ..Flags::default() };
1813        let out = compile(&mut source, &mut names, &machine, &Elsewhere::default(), flags)
1814            .expect("every instruction has a rule");
1815
1816        // A function that keeps a frame pointer keeps it whether it needed one or not, which is
1817        // what `-fno-omit-frame-pointer` is for and is the only thing this test is about.
1818        let text = mir::print_func(&out, &names, &REGS);
1819        assert!(text.contains("x64.push_64 $rbp"), "{text}");
1820        assert!(text.contains("$rbp = x64.mov_rr_64 $rsp"), "{text}");
1821    }
1822
1823    /// A function written in the other convention gets a machine of the same kind under that
1824    /// convention, and one the platform does not have is `None` rather than the native one.
1825    #[test]
1826    fn a_function_of_the_other_convention_gets_the_other_machine() {
1827        use rucc_target::Convention;
1828        let triple = |text: &str| text.parse::<rucc_target::Triple>().expect("a triple");
1829        let info = TargetInfo::new(triple("x86_64-unknown-linux-gnu"));
1830        let machine = Machine::for_target(&info).expect("x86-64 is the target this crate covers");
1831        let ms = machine.under(Convention::Ms).expect("Linux has the Windows convention");
1832        assert!(std::ptr::eq(ms.conv, &x86_64::MS_ON_SYSV));
1833        assert!(machine.under(Convention::Sysv).is_none());
1834        // The Windows convention owes `xmm6` to `xmm15` back, so the vector scratch registers are
1835        // two it does not owe.
1836        assert!(!ms.env.scratch(ms.conv.sse_class).iter().any(|&reg| ms.conv.preserves_sse(reg)));
1837
1838        let info = TargetInfo::new(triple("x86_64-pc-windows-msvc"));
1839        let machine = Machine::for_target(&info).expect("x86-64 is the target this crate covers");
1840        let sysv = machine.under(Convention::Sysv).expect("Windows has the System V convention");
1841        assert!(std::ptr::eq(sysv.conv, &x86_64::SYSV_ON_WIN64));
1842        assert!(machine.under(Convention::Ms).is_none());
1843
1844        let info = TargetInfo::new(triple("aarch64-unknown-linux-gnu"));
1845        let machine = Machine::for_target(&info).expect("aarch64 has a back end");
1846        assert!(machine.under(Convention::Ms).is_none());
1847    }
1848
1849    #[test]
1850    fn a_target_says_which_machine_it_is_and_which_convention_it_uses() {
1851        let triple = |text: &str| text.parse::<rucc_target::Triple>().expect("a triple");
1852        let info = TargetInfo::new(triple("x86_64-unknown-linux-gnu"));
1853        let machine = Machine::for_target(&info).expect("x86-64 is the target this crate covers");
1854        assert!(std::ptr::eq(machine.conv, &SYSV));
1855
1856        let info = TargetInfo::new(triple("x86_64-pc-windows-msvc"));
1857        let machine = Machine::for_target(&info).expect("x86-64 is the target this crate covers");
1858        assert!(std::ptr::eq(machine.conv, &WIN64));
1859
1860        // The AArch64 machine, with its own selector, so nothing compiles x86-64 instructions for
1861        // an AArch64 program.
1862        let info = TargetInfo::new(triple("aarch64-unknown-linux-gnu"));
1863        let machine = Machine::for_target(&info).expect("aarch64 has a back end");
1864        assert!(std::ptr::eq(machine.conv, &aarch64::AAPCS64));
1865        assert!(std::ptr::eq(machine.selector, &select::aarch64::SELECTOR));
1866
1867        // Not a target this crate has a back end for, and saying so is the whole point.
1868        let info = TargetInfo::new(triple("riscv64-unknown-linux-gnu"));
1869        assert!(Machine::for_target(&info).is_none());
1870    }
1871}