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