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