Skip to main content

rucc_codegen/
lower.rs

1//! The selector: an IR function becomes a machine IR function.
2//!
3//! Design: `spec/10-backend.md` sections 10.2 and 10.3.
4//!
5//! What the matcher in [`crate::select`] does is answer one question about one term. What this
6//! does is ask it: walk a function, decide which terms are worth asking about, and build machine
7//! instructions out of what comes back. Nothing here decides what an IR term lowers to. That is
8//! in `rules/x86-64.rules` and it is proved before it is used, which is the whole point of the
9//! arrangement and the reason this file is short.
10//!
11//! # What it does with an instruction
12//!
13//! It tries the ways the instruction can be shown to the matcher, in order, and takes the first
14//! that a rule fires on. [`crate::term`] is what a way of showing one is, and the order is the
15//! most specific first: an operand that is a constant is offered as a constant before it is
16//! offered as a register, and an operand computed by an instruction of its own is offered as
17//! that instruction before it is offered as a register. A rule that wants an immediate too wide
18//! for the machine has a guard that turns it down, and the search carries on to the way of
19//! showing it that puts the constant in a register, which is the right answer and is one nobody
20//! had to write down.
21//!
22//! A constant is not lowered where it is written. It is materialized where a register for it is
23//! first wanted, which is what keeps a constant that every use folded into an immediate from
24//! leaving a dead instruction behind, and it also gives the value the shortest live range it
25//! could have. The instruction that materializes it comes from the rule set like everything else.
26//!
27//! # What it does not do yet
28//!
29//! Everything is in the general purpose registers, because every rule in the set is about an
30//! integer, so a call that passes a `double` and a function that returns one are both reported
31//! rather than lowered. So is an argument that travels on the stack, on either side of a call,
32//! and so is a call through an address rather than to a name.
33//!
34//! # A call
35//!
36//! Not a rule, because a rule pattern sees one term and what a call's operands are is whatever
37//! the signature made them. [`crate::abi`] builds one instead, out of the same description of the
38//! convention the arguments come from: the values it passes are reads constrained to the
39//! registers the convention places them in, what comes back is a write constrained to the
40//! register it comes back in, and every other register the callee is free to destroy is a write
41//! of that register and nothing else, which is all the allocator needs to keep a value out of it.
42//!
43//! What that costs the frame is an argument area, and nothing after selection could work out how
44//! big, so the size of the widest call is given back with the function. A function that makes no
45//! call at all is a leaf, and a leaf is the function that may use the red zone.
46//!
47//! # Where a block goes
48//!
49//! On the block, which is what machine IR does with an edge and is why the branches need no more
50//! rule language than the arithmetic did. A rule never names a block, so an unconditional jump
51//! has no rule at all and a conditional branch has one that is about its condition and nothing
52//! else. The arms are copied across after the block is filled, arguments and all, because an
53//! argument that is a constant is materialized where a register for it is first wanted and the
54//! end of the block is where an edge wants it.
55//!
56//! What this leaves behind is a function whose blocks are in the order the IR held them and whose
57//! branches are still branches on a register. Turning one into a `test` and a `jcc` is the block
58//! layout's, since which of the two arms falls through is the layout's answer, and [`crate::split`]
59//! has to run before allocation so that every edge carrying a value has somewhere to put it.
60//!
61//! A store and a return are the two things here that write no register. A store is emitted like
62//! everything else and the only difference is that there is no result to put anywhere, so the
63//! operands the target describes are all reads. A return is the same, and what it is for is its
64//! one operand: the target constrains it to the register the caller reads the value out of, and
65//! the allocator is what gets it there. The instruction that leaves is not chosen here at all,
66//! because the epilogue has to give the frame back first and [`crate::finish`] writes that after
67//! allocation, so a return of nothing is lowered to nothing.
68//!
69//! The entry block is the one block whose parameters are not block parameters here. They are the
70//! function's arguments, they are already somewhere when it starts, and [`crate::abi`] is what
71//! says where. An argument that arrives on the stack is reported rather than read, because where
72//! the stack put it is a distance into a frame and no frame exists until after allocation.
73//!
74//! Blocks are walked in the order the function holds them and a value is expected to be defined
75//! before it is used, which is true of the IR this is given because every pass before it keeps
76//! definitions ahead of uses.
77
78use std::fmt;
79
80use rucc_base::Interner;
81use rucc_diag::Span;
82use rucc_ir::{
83    Abi, AsmOperands, Block, Def, Extra, FloatPred, Func, Inst, Linkage, MemOrder, Opcode, Param,
84    RmwOp, Type, Value, Visibility,
85};
86use rucc_mir as mir;
87use rucc_target::x86_64;
88use rucc_target::{CallRegs, Constraint, RegClass};
89
90use crate::abi::{self, Missing, Refused};
91use crate::coverage::Fired;
92use crate::elsewhere::Elsewhere;
93use crate::frame::{Layout, Local};
94use crate::select::{Match, Piece, Rule, Table};
95use crate::term::{MAX_ARGS, PLAIN, Plan, Shown, Term, Terms};
96use crate::varargs;
97
98/// The prefix a rule file puts in front of a machine term, which says which target it belongs
99/// to and is not part of the opcode.
100pub(crate) const PREFIX: &str = "x64.";
101
102/// The instruction a global offset table slot is read with.
103///
104/// Not in [`x86_64::FRAME`] with the other opcodes this file names, because a frame has no use for
105/// it. It is spelled out here because the relocation it takes is only legal on a `mov` with a REX
106/// prefix, so the width is part of the requirement rather than a choice.
107const GOT_LOAD: &str = "mov_rm_64";
108
109/// How wide an address is on this target, which is the width a cast between a pointer and an
110/// integer has to be at for the cast to be nothing.
111const ADDRESS_BITS: u32 = 64;
112
113/// How many bytes a `long double` takes in memory, and what it is aligned to, which are the same
114/// number and are both more than the ten bytes that mean anything.
115///
116/// The psABI's answer rather than a choice here. `sizeof (long double)` is sixteen on this
117/// machine, so an array of them is laid out this way whatever a slot holding one does, and a slot
118/// that agreed with the array is one fewer thing to get wrong.
119const X87_BYTES: u32 = 16;
120
121/// How many values the x87 stack holds at once.
122///
123/// Eight, which is the machine's number rather than a choice here, and it matters in one place:
124/// the parameters of a block are copied through the stack so that they all move at once, and a
125/// block with more of them than this has nowhere to put the ninth.
126const X87_DEPTH: usize = 8;
127
128/// How many bytes a value passes through on its way between a register and the x87 stack.
129///
130/// Eight, because the widest thing that crosses is a `double` or a sixty four bit integer, and
131/// nothing crosses at eighty bits: a value that wide is already in the frame and the stack reaches
132/// it where it is.
133const X87_CROSSING: u32 = 8;
134
135/// Where the rounding field of the x87 control word is and what it has to be set to for the unit
136/// to cut towards zero, which is the one rounding C asks for that the unit does not do by default.
137///
138/// Both bits on is truncate. The field is ORed into the word that was already there rather than
139/// written over it, so the precision control and the exception masks somebody else set stay set.
140const X87_TRUNCATE: i64 = 0x0c00;
141
142/// Whether a type is the one this machine has no register for.
143///
144/// Only the eighty bit float is, and that is a fact about x86-64 rather than about floats: every
145/// other scalar the front end produces is in a general purpose register or a vector one, and this
146/// one is on the x87 stack while it is being worked on and in memory the rest of the time. So it
147/// has no place in [`Lowering::class_of`] and no name in [`crate::term`], and every instruction
148/// that touches one is written out by hand in this file.
149fn on_x87(ty: Type) -> bool {
150    ty.is_scalar() && ty.is_float() && ty.bits() == 80
151}
152
153/// Why a function could not be lowered.
154///
155/// One reason and then nothing. A function with no rule for something in it is a function this
156/// cannot finish, and the second thing it could not lower is not news.
157#[derive(Debug, Clone, PartialEq, Eq)]
158pub enum Unsupported {
159    /// An instruction no rule fires on.
160    Inst {
161        /// The instruction that stopped it.
162        inst: Inst,
163        /// What the rule file would call it, or nothing if the rule language has no name for it
164        /// at all, which is what an instruction at a width nothing is written about looks like.
165        term: Option<&'static str>,
166        /// The opcode, which is what gets named when the rule language has no word for it.
167        ///
168        /// An opcode the rule language has no word for is exactly the opcode no rule lowers, so
169        /// without this the message would be empty in every case where somebody needs it.
170        opcode: Opcode,
171        /// What it produces, or nothing for an instruction that is only an effect.
172        ty: Option<Type>,
173    },
174    /// A parameter that does not arrive somewhere this can bring it in from.
175    ///
176    /// Not an instruction, which is why it is a separate arm: it is a fact about the signature
177    /// and there is nothing in the body of the function to point at.
178    Argument {
179        /// Its position in the signature.
180        index: usize,
181        /// What is wrong with where it arrives.
182        missing: Missing,
183    },
184    /// A call that passes or gives back a value this cannot put where the convention wants it.
185    Call {
186        /// The call.
187        inst: Inst,
188        /// Which value, and what is wrong with where it travels.
189        refused: Refused,
190    },
191    /// A `return` this cannot put where the convention wants it.
192    ///
193    /// A separate arm from [`Unsupported::Inst`] because it is not an instruction no rule fires
194    /// on. A return of more than one value is built from the convention rather than matched, the
195    /// same way a call is, so what goes wrong with one is what goes wrong with a call and not the
196    /// absence of a rule.
197    Returned {
198        /// The `return`.
199        inst: Inst,
200        /// What is wrong with where one of the values travels.
201        missing: Missing,
202    },
203    /// A stack slot whose size is not known until the function runs, which is what a variable
204    /// length array is.
205    ///
206    /// Not an instruction no rule covers. Growing the stack where the declaration stands is
207    /// arithmetic on the stack pointer, and everything else in the frame then has to be reached
208    /// through a frame pointer instead, and neither of those is a term a rule could be written
209    /// about or a thing the frame here knows how to lay out.
210    Dynamic {
211        /// The `alloca`.
212        inst: Inst,
213    },
214    /// More parameters of a type that travels on the x87 stack than the stack is deep.
215    ///
216    /// Not an instruction either, for the reason a function's parameter is not one: it is a fact
217    /// about the block and there is nothing in the block to point at. What crosses an edge for one
218    /// of these is the address of where the value is, and the block copies the bytes into a slot
219    /// of its own, all of them through the stack at once so that a block carrying two of them
220    /// swapped is copied in an order that is right. Eight is as many as the stack holds, and a
221    /// ninth would have to be copied before or after the rest, which is the order that could be
222    /// wrong.
223    Phi {
224        /// Which block it arrives at.
225        block: Block,
226        /// How many of them arrive there, which is the whole of what is wrong.
227        count: usize,
228        /// What they are.
229        ty: Type,
230    },
231    /// An `asm` statement this cannot build.
232    ///
233    /// Not an instruction no rule fires on, for the reason a call is not one: what it stands for is
234    /// whatever its template says, and no pattern over terms can read a string.
235    Assembly {
236        /// The `inline_asm`.
237        inst: Inst,
238        /// What about it is not built here yet.
239        refused: Written,
240    },
241}
242
243/// What about an `asm` statement is not built yet.
244#[derive(Debug, Clone, Copy, PartialEq, Eq)]
245pub enum Written {
246    /// A template with instructions in it.
247    Template,
248    /// An `asm goto`, whose labels make the statement a terminator.
249    Goto,
250    /// An operand this cannot put where the constraint says it goes.
251    Operand,
252}
253
254impl Written {
255    /// The rest of the sentence that starts with the statement.
256    #[must_use]
257    pub fn why(self) -> &'static str {
258        match self {
259            // The template is the assembler's to read and there is no assembler here yet, so a
260            // template with anything in it is a string nothing can turn into bytes. An empty one is
261            // no instructions, and no instructions is something this can write.
262            Written::Template => "has instructions in its template, which nothing here assembles",
263            Written::Goto => "jumps to a label, which nothing here builds an edge for",
264            Written::Operand => "has an operand this cannot place",
265        }
266    }
267}
268
269impl Unsupported {
270    /// The instruction it is about, or nothing for the one arm that is about a signature.
271    ///
272    /// What a caller wants this for is the span. The function knows where every instruction in
273    /// it came from, so a caller holding both can point a message at the line somebody wrote
274    /// rather than at the file as a whole, and nothing here has to carry a span of its own.
275    pub fn inst(&self) -> Option<Inst> {
276        match *self {
277            Unsupported::Inst { inst, .. }
278            | Unsupported::Call { inst, .. }
279            | Unsupported::Returned { inst, .. }
280            | Unsupported::Dynamic { inst, .. }
281            | Unsupported::Assembly { inst, .. } => Some(inst),
282            Unsupported::Argument { .. } | Unsupported::Phi { .. } => None,
283        }
284    }
285}
286
287impl fmt::Display for Unsupported {
288    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
289        match *self {
290            Unsupported::Inst { term: Some(term), .. } => write!(f, "no rule lowers `{term}`"),
291            Unsupported::Inst { term: None, opcode, ty: Some(ty), .. } => {
292                write!(f, "no rule lowers a `{opcode}` producing a `{ty}`")
293            }
294            Unsupported::Inst { term: None, opcode, ty: None, .. } => {
295                write!(f, "no rule lowers a `{opcode}`")
296            }
297            Unsupported::Argument { index, missing } => {
298                write!(f, "parameter {index} {}", missing.why())
299            }
300            Unsupported::Call { refused: Refused { argument: Some(index), missing }, .. } => {
301                write!(f, "argument {index} of this call {}", missing.why())
302            }
303            Unsupported::Call { refused: Refused { argument: None, missing }, .. } => {
304                write!(f, "what this call gives back {}", missing.why())
305            }
306            Unsupported::Returned { missing, .. } => {
307                write!(f, "what this function gives back {}", missing.why())
308            }
309            Unsupported::Dynamic { .. } => {
310                f.write_str("nothing here grows the stack for a variable length array")
311            }
312            Unsupported::Phi { block, count, ty } => {
313                let block = block.index();
314                write!(
315                    f,
316                    "block{block} takes {count} parameters of type `{ty}` and only {X87_DEPTH} can cross an edge at once"
317                )
318            }
319            Unsupported::Assembly { refused, .. } => write!(f, "this `asm` {}", refused.why()),
320        }
321    }
322}
323
324impl std::error::Error for Unsupported {}
325
326/// A lowered function, and what the frame needs that the machine IR does not hold.
327#[derive(Debug)]
328pub struct Lowered {
329    /// The function, in machine instructions.
330    pub func: mir::Func,
331    /// What it wants its stack to look like, which is separate from the function so that the two
332    /// can be read and written at the same time.
333    pub stack: Stack,
334    /// Which rules of the table lowered it, which is what `-Zrule-coverage` asks for and what
335    /// `crate::coverage` writes down.
336    pub fired: Fired,
337}
338
339/// What a function's stack has to hold, as far as selection is able to say.
340///
341/// All of it is answered here because selection is where a call is built and where an `alloca`
342/// is read, and nothing after it could tell what either of them needed.
343#[derive(Debug, Default)]
344pub struct Stack {
345    /// How many bytes the widest call in the function needs below the stack pointer for the
346    /// arguments it passes there, or `None` for a function that makes no call at all.
347    ///
348    /// `None` is a leaf, which is the function that may use the red zone and the one whose stack
349    /// pointer does not have to be left aligned for anybody.
350    pub calls: Option<u32>,
351    /// The memory the function asked for itself, one entry for every `alloca` in it, in the order
352    /// the walk reached them.
353    pub locals: Vec<Local>,
354    /// Which instruction computes the address of which of those locals.
355    ///
356    /// An address in the frame is a distance from the stack pointer, and there is no frame until
357    /// after allocation, so the instruction is written here with nothing in its displacement and
358    /// [`crate::finish`] writes the number in once [`crate::frame::Frame`] knows it.
359    pub addresses: Vec<(mir::Inst, usize)>,
360    /// Which instruction reads which of the arguments the caller passed on the stack, as how far up
361    /// the caller's argument area it reads.
362    ///
363    /// Waiting on [`crate::finish`] for the same reason the addresses above are, and on one thing
364    /// more: where the caller's argument area is from inside this function depends on whether the
365    /// prologue had to force the stack pointer's alignment, so which register the load reads
366    /// through is not settled here either.
367    pub arguments: Vec<(mir::Inst, u32)>,
368}
369
370impl Stack {
371    /// The layout given, with the three fields only the lowering knows the answer to filled in.
372    ///
373    /// Everything else in a layout comes from the flags the function is compiled under or from the
374    /// allocation, so this takes one and returns it rather than building one.
375    #[must_use]
376    pub fn layout<'a>(&'a self, base: Layout<'a>) -> Layout<'a> {
377        Layout {
378            leaf: self.calls.is_none(),
379            outgoing: self.calls.unwrap_or(0),
380            locals: &self.locals,
381            ..base
382        }
383    }
384}
385
386/// The x86-64 machine IR for that function.
387///
388/// # Errors
389///
390/// The first instruction no rule fires on, which today is anything at a width the rule set is not
391/// written at, a parameter that does not arrive in a register this can read, or a call that
392/// passes something this cannot put where the convention wants it.
393pub fn func(
394    source: &Func,
395    names: &mut Interner,
396    conv: &'static CallRegs,
397    elsewhere: &Elsewhere,
398) -> Result<Lowered, Unsupported> {
399    Lowering::new(source, names, conv, elsewhere).run()
400}
401
402/// One function being lowered.
403struct Lowering<'a> {
404    source: &'a Func,
405    names: &'a mut Interner,
406    out: mir::Func,
407    /// The machine register each IR value is in, once it has one.
408    regs: Vec<Option<mir::Reg>>,
409    /// For a constant that has been written into a register, the block it was written into,
410    /// which is the only block that register is any good in.
411    written: Vec<Option<mir::Block>>,
412    /// How many times each IR value is read, which is what says whether an instruction may be
413    /// folded into the one that reads it.
414    uses: Vec<u32>,
415    /// The block being filled.
416    at: Option<mir::Block>,
417    /// The machine IR block each IR block became.
418    blocks: Vec<Option<mir::Block>>,
419    /// The class an address is in, which is the general purpose one and is not a question: every
420    /// register an addressing mode names holds part of an address, and there is no machine here
421    /// that computes an address anywhere but in this file. Which class a *value* is in is
422    /// [`Lowering::class_of`], and it is a question, because a float is in the other one.
423    gpr: RegClass,
424    /// Where the convention this function is compiled for puts things, which is read for the
425    /// arguments and for the calls.
426    conv: &'static CallRegs,
427    /// Which names this function may not work an address out for itself, which is a fact about the
428    /// module and so is worked out before any of this and handed in.
429    elsewhere: &'a Elsewhere,
430    /// What the function wants its stack to look like, filled in as the walk finds out.
431    stack: Stack,
432    /// What a `va_start` in this function has to write, or nothing for a function that takes no
433    /// arguments its signature does not name.
434    ///
435    /// Worked out once, when the entry block binds the parameters, because every number in it is
436    /// about where those parameters left the walk over the argument registers and there is nowhere
437    /// else that knows.
438    varargs: Option<Varargs>,
439    /// Which of the function's stack objects each eighty bit value lives in, once it has asked
440    /// for one.
441    ///
442    /// One slot per value and it is never given back, which is what makes an eighty bit value
443    /// behave like every other one: it is written once and read wherever it is read, and no two
444    /// of them share a slot the way two of them would share a register. What is in a register is
445    /// the address, and that is worked out again at every use rather than kept, so nothing here
446    /// holds a general purpose register open across a whole function.
447    slots: Vec<Option<usize>>,
448    /// The eight bytes a value passes through between a register and the x87 stack, once
449    /// something has wanted them.
450    ///
451    /// One for the whole function, because every group that uses it is a handful of instructions
452    /// with nothing in between: the bytes are written, read straight back and never looked at
453    /// again, so a second slot would be a second slot holding the same nothing.
454    crossing: Option<usize>,
455    /// The four bytes the control word is saved in and the changed copy written to, once
456    /// something has wanted them.
457    ///
458    /// One for the whole function for the reason above, and four rather than two because it is
459    /// two words: the one the unit had and the one with the rounding field turned to truncate.
460    control: Option<usize>,
461    /// Which rules have fired so far.
462    fired: Fired,
463}
464
465/// What a `va_start` in a variadic function writes into the list it is given.
466///
467/// Three of the four are settled here and the fourth is not a number at all yet: where the save
468/// area is and where the caller's argument area is are both distances into a frame that does not
469/// exist until after allocation, so both are `lea` instructions [`crate::finish`] fills in.
470#[derive(Debug, Clone, Copy, PartialEq, Eq)]
471struct Varargs {
472    /// Which of the function's stack objects is the register save area.
473    save: usize,
474    /// How far up the caller's argument area the first argument the signature does not name is,
475    /// which is the whole of that area the named ones did not take.
476    incoming: u32,
477    /// What `gp_offset` starts at, which is past the general purpose registers the named arguments
478    /// took.
479    integers: u32,
480    /// What `fp_offset` starts at, which is past the vector ones.
481    floats: u32,
482}
483
484/// How far a function's name reaches, narrowed from the linkage the IR gave it.
485///
486/// The IR has five and an object file says three, and the two the linker cannot tell apart are
487/// the two weak ones: which of them a symbol had is a fact the optimizer reads and the linker has
488/// no way to record. A function is never `Common`, since that is what a tentative definition of an
489/// object is and there is no tentative definition of a function, and it is written here rather
490/// than left out so that a linkage added later has to come past this.
491const fn binding(linkage: Linkage) -> mir::Binding {
492    match linkage {
493        Linkage::Internal => mir::Binding::Local,
494        Linkage::Weak | Linkage::LinkOnce => mir::Binding::Weak,
495        Linkage::External | Linkage::Common => mir::Binding::Global,
496    }
497}
498
499/// How far a function's name reaches outside a shared library, carried across unchanged.
500///
501/// Nothing is narrowed here the way [`binding`] narrows the linkage, because ELF records all
502/// three of these and the two enumerations are the same three answers written twice: once in a
503/// crate that is not allowed to know what an object file is and once in one that is.
504const fn visibility(visibility: Visibility) -> mir::Visibility {
505    match visibility {
506        Visibility::Default => mir::Visibility::Default,
507        Visibility::Hidden => mir::Visibility::Hidden,
508        Visibility::Protected => mir::Visibility::Protected,
509    }
510}
511
512impl<'a> Lowering<'a> {
513    fn new(
514        source: &'a Func,
515        names: &'a mut Interner,
516        conv: &'static CallRegs,
517        elsewhere: &'a Elsewhere,
518    ) -> Self {
519        let counts = source.counts();
520        let name = source.name;
521        let mut uses = vec![0; counts.values];
522        for block in source.blocks() {
523            for inst in source.insts(block) {
524                for &arg in &source[source[inst].args] {
525                    uses[arg.index()] += 1;
526                }
527                for call in source.successors(inst) {
528                    for &arg in &source[call.args] {
529                        uses[arg.index()] += 1;
530                    }
531                }
532            }
533        }
534        let mut out = mir::Func::new(name);
535        out.align = source.align;
536        out.binding = binding(source.linkage);
537        out.visibility = visibility(source.visibility);
538        Self {
539            source,
540            names,
541            out,
542            regs: vec![None; counts.values],
543            written: vec![None; counts.values],
544            blocks: vec![None; counts.blocks],
545            uses,
546            at: None,
547            gpr: x86_64::GPR,
548            conv,
549            elsewhere,
550            stack: Stack::default(),
551            varargs: None,
552            slots: vec![None; counts.values],
553            crossing: None,
554            control: None,
555            fired: Fired::new(),
556        }
557    }
558
559    fn run(mut self) -> Result<Lowered, Unsupported> {
560        // Every block before any of them is filled, because a block that jumps forward has to
561        // name the block it jumps to and a machine IR block is named by a handle rather than by
562        // the IR block it came from.
563        for block in self.source.blocks() {
564            let out = self.out.create_block();
565            self.blocks[block.index()] = Some(out);
566        }
567        for block in self.order() {
568            self.block(block)?;
569        }
570        Ok(Lowered { func: self.out, stack: self.stack, fired: self.fired })
571    }
572
573    /// The order the blocks are filled in, which is not the order they are written in.
574    ///
575    /// Reverse postorder, because a value is written in a block that dominates every block that
576    /// reads it and a block in reverse postorder comes before every block it dominates. The order
577    /// the blocks are written in does not have that property: a block written early can read a
578    /// value a block below it writes, and reading a value with no register yet mints one, so the
579    /// register the definition writes later is not the register the read named. Nothing writes the
580    /// one the read named, and what comes out is a function that loads a stack slot no store ever
581    /// reached. It is the order this walk goes in rather than the order the blocks come out in,
582    /// which is what the loop above fixes, so the machine function is still written the way the IR
583    /// function was.
584    ///
585    /// Blocks the entry does not reach come last, in the order they are written in. Nothing runs
586    /// them and nothing they name is read by anything that does, but they still have to be filled,
587    /// because a machine block with no terminator is not one the passes below can read.
588    fn order(&self) -> Vec<Block> {
589        let Some(entry) = self.source.entry() else { return self.source.blocks().collect() };
590        let count = self.blocks.len();
591        let mut succs: Vec<Vec<Block>> = vec![Vec::new(); count];
592        for block in self.source.blocks() {
593            let Some(term) = self.source.terminator(block) else { continue };
594            succs[block.index()] = self.source.successors(term).map(|call| call.block).collect();
595        }
596        // An explicit stack, because the depth of the walk is the number of blocks and a function
597        // built by a generator has as many of those as it likes.
598        let mut seen = vec![false; count];
599        let mut order = Vec::with_capacity(count);
600        let mut stack = vec![(entry, 0usize)];
601        seen[entry.index()] = true;
602        while let Some((block, at)) = stack.pop() {
603            let Some(&next) = succs[block.index()].get(at) else {
604                order.push(block);
605                continue;
606            };
607            stack.push((block, at + 1));
608            if !seen[next.index()] {
609                seen[next.index()] = true;
610                stack.push((next, 0));
611            }
612        }
613        order.reverse();
614        order.extend(self.source.blocks().filter(|block| !seen[block.index()]));
615        order
616    }
617
618    /// One block: its parameters, then every instruction in it that is not folded into another.
619    fn block(&mut self, block: Block) -> Result<(), Unsupported> {
620        let out = self.out_block(block);
621        self.at = Some(out);
622        if self.source.entry() == Some(block) {
623            self.arrive(block, out)?;
624        } else {
625            let mut arriving = Vec::new();
626            for &param in &self.source[block].params {
627                // A value with no register to arrive in, which the class would not say, since
628                // `class_of` puts one of these in the general purpose file on purpose and what it
629                // means by that is that nothing there can hold it. What crosses the edge for one
630                // of those is the address of where the value already is, so the parameter is a
631                // pointer here and the bytes it points at are copied below.
632                let ty = self.source[param].ty;
633                let reg = self.out.append_param(out, self.class_of(ty));
634                self.regs[param.index()] = Some(reg);
635                if on_x87(ty) {
636                    arriving.push((param, reg));
637                }
638            }
639            self.settle(block, &arriving)?;
640        }
641
642        // What each instruction matched, and which instructions were folded into another. The
643        // instruction that is folded comes before the one that folds it, so the decision has to
644        // be made for the whole block before any of it is written, and it is made backwards: an
645        // instruction that has been folded into a later one does not get to fold anything into
646        // itself, because the rule that took it only reached one level down.
647        let insts: Vec<Inst> = self.source.insts(block).collect();
648        let mut found: Vec<Option<Match<Term>>> = (0..insts.len()).map(|_| None).collect();
649        let mut folded: Vec<Inst> = Vec::new();
650        for (index, &inst) in insts.iter().enumerate().rev() {
651            if folded.contains(&inst) {
652                continue;
653            }
654            if let Some((plan, matched)) = self.select(inst) {
655                folded.extend(self.folds(inst, plan));
656                found[index] = Some(matched);
657            }
658        }
659
660        for (&inst, matched) in insts.iter().zip(found) {
661            if folded.contains(&inst) || self.writes_nothing(inst) {
662                continue;
663            }
664            // A call is built from the convention rather than matched, which is why it is the one
665            // opcode looked at by name here. Through an address it is a different instruction and
666            // the same convention, so the two arrive at the same place and differ in one line of
667            // it.
668            match self.source[inst].opcode {
669                Opcode::Call | Opcode::CallIndirect => {
670                    self.called(inst)?;
671                    continue;
672                }
673                // Built from the frame rather than matched, for the same shape of reason a call
674                // is built from the convention: what a rule replaces a term with is instructions,
675                // and what an `alloca` needs first is bytes, which the rule language has no way
676                // to ask for.
677                Opcode::Alloca => {
678                    self.reserve(inst)?;
679                    continue;
680                }
681                // The address of a name, built here for the same reason an `alloca` is: what a
682                // rule replaces a term with is instructions over values, and the operand of this
683                // one is a symbol, which is a thing the rule language has no way to bind and the
684                // solver has no way to say anything about. There is nothing in `lea sym(%rip)` a
685                // proof over bitvectors could discharge, because what makes it the right answer
686                // is the relocation and what the linker does with it.
687                Opcode::GlobalAddr => {
688                    self.address_of(inst)?;
689                    continue;
690                }
691                // Built from the frame for the reason an `alloca` is, and from the convention for
692                // the reason a call is: three of the four fields it writes are distances that do
693                // not exist until the frame does, and the fourth is where the walk over the
694                // argument registers stopped. A function that is not variadic has no such walk to
695                // report, so it has nothing here and is refused below, which is the right answer
696                // for a `va_start` in one.
697                Opcode::VaStart if self.varargs.is_some() => {
698                    self.va_start(inst)?;
699                    continue;
700                }
701                // A return of more than one value, which is a structure small enough to come
702                // back in a pair of registers. Built from the convention for the reason a call
703                // is: which register each half goes in depends on the halves in front of it,
704                // because the two register files are walked separately, and a pattern over a term
705                // cannot see them. A return of one value is a term with a name and a rule, and it
706                // stays one.
707                //
708                // A return of none in a function whose answer went through memory is here too,
709                // and for a different reason: what it gives back is not written in the IR at all.
710                // The convention says the address the caller handed over comes back, and only the
711                // signature says this function was handed one.
712                //
713                // And a return of one eighty bit value, for a third reason: what a rule would
714                // write is an instruction leaving the value in a register, and this one is left on
715                // the x87 stack instead. A rule could not name that stack any more than any other
716                // rule about this type could.
717                Opcode::Return
718                    if self.source[self.source[inst].args].len() > 1
719                        || self.sret().is_some()
720                        || self.gives_back_x87(inst) =>
721                {
722                    self.returned(inst)?;
723                    continue;
724                }
725                // A cast between a pointer and an integer of the same width, which on this
726                // machine is every one the front end writes. No instruction at all, so no rule
727                // could name one.
728                Opcode::PtrToInt | Opcode::IntToPtr => {
729                    self.rename(inst)?;
730                    continue;
731                }
732                // A barrier, which is one instruction or none depending on the ordering. Written
733                // by name because there is nothing about it a rule could be proved against, the
734                // way there is nothing to prove about the address of a symbol.
735                Opcode::Fence => {
736                    self.barrier(inst)?;
737                    continue;
738                }
739                // A compare and exchange, which is written by name because it produces two values
740                // and a rule produces one. The replacement of a rule is one term, a term names the
741                // value an instruction computes, and there is no way in that language to say that
742                // an instruction leaves an answer in one place and a yes or no in another.
743                Opcode::Cmpxchg => {
744                    self.exchange(inst)?;
745                    continue;
746                }
747                // A read modify write, which is written by name for a different reason: it produces
748                // one value, so a rule could name it, and what it does is not in the head a rule
749                // matches on. Every one of the thirteen operations is the same opcode at the same
750                // type and differs only in what is carried beside it, so one pattern would be all
751                // thirteen patterns. Of the thirteen only the three with an instruction reach here,
752                // since `crate::retry` turned the rest into loops a long way above this.
753                Opcode::AtomicRmw => {
754                    self.modify(inst)?;
755                    continue;
756                }
757                // An `asm` statement, whose lowering is its template and there is no term for a
758                // string. Written by name for the reason a barrier is, and before the x87 arm
759                // below so that an `asm` holding a `long double` is refused as the `asm` it is
760                // rather than as an instruction nothing computes.
761                Opcode::InlineAsm => {
762                    self.assembly(inst)?;
763                    continue;
764                }
765                // Anything at all with an eighty bit float in it, which is the one arm here
766                // chosen by a type rather than by an opcode, because what makes these different
767                // is not what they do but where the value is. A `long double` has no register,
768                // so it has no name in `crate::term` and no rule could bind one: every one of
769                // these is a group of instructions over a frame slot, written out below.
770                //
771                // Last of the arms, so that a call and a return with one of these in them reach
772                // the convention first and are refused by it, which is the truer answer: what is
773                // wrong there is where the value has to travel and not that nothing can compute
774                // it.
775                _ if self.touches_x87(inst) => {
776                    self.x87(inst)?;
777                    continue;
778                }
779                _ => {}
780            }
781            let matched = matched.ok_or_else(|| self.unsupported(inst))?;
782            self.emit(inst, &matched)?;
783            // After it is built rather than when it matched, so that what is recorded is the rules
784            // this function was lowered by and not the rules something was tried with.
785            self.fired.mark(matched.rule);
786        }
787        self.edges(block, out)
788    }
789
790    /// One call, which is built from the convention rather than matched against the table for the
791    /// same reason the arguments of the function itself are.
792    ///
793    /// The arguments are read before the call is built, which is what materializes a constant
794    /// argument into a register, since no call passes an immediate.
795    ///
796    /// A call to a name and a call through an address are both here, and what tells them apart is
797    /// the opcode rather than whether a callee was recorded, which is the same thing the verifier
798    /// reads. Through an address the first operand is the address and the arguments are the ones
799    /// behind it, and everything after that is the same: where each argument goes, where the value
800    /// comes back and which registers are gone across it are the convention's answers and the
801    /// convention does not ask what is being called.
802    fn called(&mut self, inst: Inst) -> Result<(), Unsupported> {
803        let data = &self.source[inst];
804        let Extra::Call(info) = data.extra else { return Err(self.unsupported(inst)) };
805        let info = self.source[info];
806        let indirect = data.opcode == Opcode::CallIndirect;
807
808        let values: Vec<Value> = self.source[data.args].to_vec();
809        let callee = if indirect {
810            let &address = values.first().ok_or_else(|| self.unsupported(inst))?;
811            abi::Callee::Through(self.reg_of(address)?)
812        } else {
813            abi::Callee::Named(info.callee.ok_or_else(|| self.unsupported(inst))?)
814        };
815
816        // What the ABI asks of each argument, read out before any of them is, because reading one
817        // borrows the function this is a table in. The ones the signature names are the signature's
818        // answer and the ones behind them are the call's, which is where a structure passed to a
819        // variadic callee by value says that its bytes travel: there is no parameter to say it on.
820        let signature = &self.source[info.signature];
821        let variadic = signature.variadic;
822        let named: Vec<Abi> = signature.params.iter().map(|param| param.abi).collect();
823        let beyond: Vec<Abi> = self.source[info.varargs].to_vec();
824        // Every value that comes back and not only the first. A structure small enough to travel
825        // in registers comes back in up to two of them, and which register each half is in is the
826        // convention's answer, which is why the whole list goes to the same place the arguments do
827        // rather than to a rule.
828        let returns: Vec<Type> = signature.return_types().collect();
829
830        let mut args = Vec::with_capacity(values.len());
831        for (index, value) in values.into_iter().skip(usize::from(indirect)).enumerate() {
832            let abi = named.get(index).or_else(|| beyond.get(index - named.len()));
833            let abi = abi.copied().unwrap_or_default();
834            let ty = self.source[value].ty;
835            // What travels for an eighty bit value is its bytes, so what the call is handed is
836            // where they are rather than a register they are in, and there is no register they
837            // could be in. Everything else about it is a sixteen byte object passed by value and
838            // is built by the same code.
839            let reg =
840                if abi::on_the_stack(ty) { self.x87_slot(value) } else { self.reg_of(value)? };
841            args.push(abi::Passing { ty, reg, abi });
842        }
843        let block = self.at.expect("a block is being filled");
844        let what = abi::Calling { callee, args: &args, returns: &returns, variadic };
845        let made = abi::call(&mut self.out, block, &what, self.conv, self.names)
846            .map_err(|refused| Unsupported::Call { inst, refused })?;
847        let calls = &mut self.stack.calls;
848        *calls = Some(calls.unwrap_or(0).max(made.outgoing));
849        // An eighty bit value came back on the x87 stack, and the one thing that has to happen
850        // before anything else touches that stack is taking it off. So the `fstp` goes here, in
851        // front of everything the block does next, and after it the value is in its slot and is
852        // read the way every other one is.
853        let results: Vec<Value> = self.source[inst].results().collect();
854        if let [result] = results[..] {
855            if abi::on_the_stack(self.source[result].ty) {
856                let span = self.source.span(inst);
857                let into = self.x87_slot(result);
858                let into = self.through(into);
859                self.x87_at("fstp_t", span, into);
860                return Ok(());
861            }
862        }
863        for (result, &reg) in results.into_iter().zip(&made.results) {
864            self.regs[result.index()] = Some(reg);
865        }
866        Ok(())
867    }
868
869    /// The pointer a function returning through memory was handed, or nothing in a function that
870    /// was not.
871    ///
872    /// It is the first parameter and the signature is what says so, since in the IR it is an
873    /// ordinary pointer and reads like one everywhere in the body. A function with a signature
874    /// like that and no entry block has nothing to give back and no body to give it back from.
875    fn sret(&self) -> Option<Value> {
876        let first = self.source.signature().params.first()?;
877        if !matches!(first.abi, Abi::Sret { .. }) {
878            return None;
879        }
880        self.source[self.source.entry()?].params.first().copied()
881    }
882
883    /// One `return` the convention has to write, as the place each value has to be in by the end.
884    ///
885    /// One pseudo per value, each a read constrained to a return register, which is what a return
886    /// of one value already is and is the whole of what either does. The `ret` itself comes from
887    /// the epilogue for both, long after this, because the frame has to be given back first.
888    ///
889    /// The two register files are counted separately, so a structure of a `double` and a `long`
890    /// leaves the `double` in the first vector register and the `long` in the first integer one
891    /// rather than in the second of either. That is the same walk `rucc_codegen::abi` makes on
892    /// the other side of the call, which is what makes the two ends agree.
893    ///
894    /// A function whose answer went through memory gives back the address it was handed, in front
895    /// of nothing else, because a signature that returns that way returns nothing else. That the
896    /// caller already knows the address is not enough: it is allowed to read the register instead,
897    /// and a caller that does gets whatever the allocator last left there. In a leaf function that
898    /// is usually the right answer by accident, and one call in the body is enough to make it a
899    /// wild pointer, which is why this is written rather than left to luck.
900    ///
901    /// Where everything goes is worked out before anything is written, so a return this cannot
902    /// make leaves no half of one behind.
903    /// Whether what a `return` gives back is the one value that goes back on the x87 stack.
904    fn gives_back_x87(&self, inst: Inst) -> bool {
905        let [value] = self.source[self.source[inst].args] else { return false };
906        abi::on_the_stack(self.source[value].ty)
907    }
908
909    fn returned(&mut self, inst: Inst) -> Result<(), Unsupported> {
910        let values: Vec<Value> = self.source[self.source[inst].args].to_vec();
911        let (mut ints, mut floats) = (0usize, 0usize);
912        let mut parts = Vec::with_capacity(values.len() + 1);
913        // An eighty bit value goes back on the x87 stack, which is where the convention says it is
914        // and is the one place a value is left rather than put in a register. So the whole of the
915        // return is an `fld` of its slot, and the stack it leaves the value on is not empty at the
916        // `ret`, which is the one time in this file that is true and is what the convention asks
917        // for. What comes after is the epilogue, which gives the frame back and touches nothing in
918        // the unit.
919        if let [value] = values[..] {
920            let ty = self.source[value].ty;
921            if abi::on_the_stack(ty) && self.sret().is_none() {
922                let span = self.source.span(inst);
923                let from = self.x87_slot(value);
924                let from = self.through(from);
925                self.x87_at("fld_t", span, from);
926                return Ok(());
927            }
928        }
929        for value in self.sret().into_iter().chain(values) {
930            let ty = self.source[value].ty;
931            let at = if crate::term::float_slot(ty).is_some() { &mut floats } else { &mut ints };
932            // Why it cannot come back, and not only that it cannot. A type that travels nowhere
933            // says so itself, and a type that travels perfectly well ran out of registers.
934            let missing = abi::refuses(ty).unwrap_or(Missing::NoRoom);
935            let name = abi::ret_of(ty, *at).ok_or(Unsupported::Returned { inst, missing })?;
936            *at += 1;
937            // The register is the target's answer and not one worked out here, the same as it is
938            // for a return of one value, so that both halves of a pair and every rule that writes
939            // half of one are reading the same table.
940            let opcode = name.strip_prefix(PREFIX).expect("a machine instruction of this target");
941            let form = x86_64::form(opcode).ok_or_else(|| self.unsupported(inst))?;
942            let [desc] = form.operands() else { return Err(self.unsupported(inst)) };
943            parts.push((self.names.intern(name), self.reg_of(value)?, *desc));
944        }
945
946        let block = self.at.expect("a block is being filled");
947        let span = self.source.span(inst);
948        for (opcode, reg, desc) in parts {
949            let operand = mir::Operand {
950                reg,
951                class: desc.class,
952                role: desc.role,
953                constraint: desc.constraint,
954            };
955            self.out.build(block, mir::Opcode::new(opcode)).at(span).operand(operand).finish();
956        }
957        Ok(())
958    }
959
960    /// One `alloca`: the bytes it asks for go on the list the frame is laid out from, and the
961    /// address of them is one instruction.
962    ///
963    /// The instruction is a `lea` off the stack pointer, which is the one register that reaches
964    /// the frame in every function, and its displacement is left at nothing because there is no
965    /// frame yet. Which instruction is waiting for which local is remembered, and
966    /// [`crate::finish`] fills the numbers in after [`crate::frame::Frame`] has placed them.
967    ///
968    /// There is deliberately no rule for `alloca` and no name for one in [`crate::term`], and
969    /// that is what stops it being folded into something else. An operand shown as the
970    /// instruction that computed it is offered to the matcher by its name, so an `alloca` with no
971    /// name is one no pattern can reach past, and the address it computes is always in a register
972    /// by the time anything reads it.
973    fn reserve(&mut self, inst: Inst) -> Result<(), Unsupported> {
974        let data = &self.source[inst];
975        // A variable length array carries the size it wants as an operand rather than in the
976        // instruction, which is the whole of what tells the two apart here.
977        if !self.source[data.args].is_empty() {
978            return Err(Unsupported::Dynamic { inst });
979        }
980        let Extra::Mem(mem) = data.extra else { return Err(self.unsupported(inst)) };
981        let info = self.source[mem];
982        let size = u32::try_from(info.size).map_err(|_| Unsupported::Dynamic { inst })?;
983        let result = data.first_result.ok_or_else(|| self.unsupported(inst))?;
984
985        // At least one, because the frame divides by the alignment and an object with no
986        // alignment at all is one the front end had nothing to say about rather than one that may
987        // go anywhere.
988        let index = self.stack.locals.len();
989        self.stack.locals.push(Local { size, align: info.align.max(1) });
990
991        let block = self.at.expect("a block is being filled");
992        let reg = self.new_reg(result);
993        let span = self.source.span(inst);
994        let lea = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{}", x86_64::FRAME.lea)));
995        let sp = mir::Operand::read(mir::Reg::physical(self.conv.stack_pointer), self.gpr);
996        let made =
997            self.out.build(block, lea).at(span).def(reg, self.gpr).mem(mir::Mem::at(sp)).finish();
998        self.stack.addresses.push((made, index));
999        Ok(())
1000    }
1001
1002    /// Whether an instruction has an eighty bit float anywhere in it.
1003    ///
1004    /// Producing one and reading one are the same question here, because what makes one of these
1005    /// different from every other instruction is not the operation but where the value is. A
1006    /// `long double` is on the x87 stack while it is being worked on and in a frame slot the rest
1007    /// of the time, and neither of those is somewhere the operand of a rule could point.
1008    fn touches_x87(&self, inst: Inst) -> bool {
1009        let data = &self.source[inst];
1010        data.results().any(|value| on_x87(self.source[value].ty))
1011            || self.source[data.args].iter().any(|&arg| on_x87(self.source[arg].ty))
1012    }
1013
1014    /// Everything that happens to an eighty bit float, as the group of instructions it is.
1015    ///
1016    /// The first six move one, and every one of those is a load, a store, or a load and a store at
1017    /// two different formats, because that is the whole of what this machine converts with: the
1018    /// x87 has no instruction that turns one thing on its stack into another, so a widening is
1019    /// `fld` of the narrow format and a narrowing is `fstp` of it.
1020    ///
1021    /// The rest work on one, and they are here rather than in a rule for the same reason the six
1022    /// are. An add is a push, a push, the add and a pop, and what passes between those four is the
1023    /// top of a stack nothing allocates from, so there is no value in the middle of the group for
1024    /// a pattern to bind or a replacement to name. The comparison is the same shape with its last
1025    /// two instructions folded into one opcode, which is where the byte it produces comes from.
1026    ///
1027    /// Every group leaves the stack as empty as it found it, which is what `spec/10-backend.md`
1028    /// section 10.8 asks of one and is why nothing in this file has to track a depth: each push
1029    /// below is answered by a pop a line or two later, so no two groups can ever be looking at
1030    /// the same eight registers.
1031    fn x87(&mut self, inst: Inst) -> Result<(), Unsupported> {
1032        match self.source[inst].opcode {
1033            Opcode::Load => self.x87_load(inst),
1034            Opcode::Store => self.x87_store(inst),
1035            Opcode::FPExt => self.x87_widen(inst),
1036            Opcode::FPTrunc => self.x87_narrow(inst),
1037            Opcode::SIToFP => self.x87_from_signed(inst),
1038            Opcode::FPToSI => self.x87_to_signed(inst),
1039            Opcode::FAdd => self.x87_arith(inst, "fadd_p"),
1040            Opcode::FSub => self.x87_arith(inst, "fsubr_p"),
1041            Opcode::FMul => self.x87_arith(inst, "fmul_p"),
1042            Opcode::FDiv => self.x87_arith(inst, "fdivr_p"),
1043            Opcode::FNeg => self.x87_flip(inst),
1044            Opcode::FCmp => self.x87_compare(inst),
1045            Opcode::FConst => self.x87_const(inst),
1046            _ => Err(self.unsupported(inst)),
1047        }
1048    }
1049
1050    /// The eighty bit parameters of a block, copied out of the addresses an edge handed over and
1051    /// into slots of the block's own.
1052    ///
1053    /// What crosses an edge for a value of this type is an address, because the value is sixteen
1054    /// bytes of the frame and no register holds any of it. The block cannot keep that address: a
1055    /// second edge into the same block hands over a second one, and a read after the block would
1056    /// then be a read of whichever edge was taken rather than of one place. So the block has a
1057    /// slot per parameter and the bytes are copied into it here, which is the move on an edge that
1058    /// every other type gets from the allocator.
1059    ///
1060    /// Every load runs before every store and the stores run backwards, so all of the values are
1061    /// on the x87 stack at once and nothing reads a slot another one has already written. That
1062    /// costs nothing in the ordinary case of one parameter and is what makes the back edge of a
1063    /// loop that swaps two of these work. It is also the reason for the limit: the stack is eight
1064    /// deep, and a block with more of these than that is refused rather than copied in an order
1065    /// that could be wrong.
1066    fn settle(&mut self, block: Block, arriving: &[(Value, mir::Reg)]) -> Result<(), Unsupported> {
1067        let Some(&(first, _)) = arriving.first() else { return Ok(()) };
1068        if arriving.len() > X87_DEPTH {
1069            let ty = self.source[first].ty;
1070            return Err(Unsupported::Phi { block, count: arriving.len(), ty });
1071        }
1072        // A block parameter comes from no instruction, so what this points at is the first thing
1073        // in the block, which is where a reader looking for the copy would look.
1074        let first_inst = self.source.insts(block).next();
1075        let span = first_inst.map_or(Span::DUMMY, |it| self.source.span(it));
1076        for &(_, reg) in arriving {
1077            let from = self.through(reg);
1078            self.x87_at("fld_t", span, from);
1079        }
1080        for &(param, _) in arriving.iter().rev() {
1081            let into = self.x87_slot(param);
1082            let into = self.through(into);
1083            self.x87_at("fstp_t", span, into);
1084        }
1085        Ok(())
1086    }
1087
1088    /// The frame slot an eighty bit value lives in, as its address in a fresh register.
1089    ///
1090    /// The slot is the value's for the whole function and is taken the first time somebody asks.
1091    /// The address is worked out again every time, which is a `lea` per use and is deliberate: one
1092    /// address kept in a register from the definition to the last use would hold a general purpose
1093    /// register open across everything in between, and a function with a handful of these in it
1094    /// would spend its registers on addresses of things rather than on things.
1095    fn x87_slot(&mut self, value: Value) -> mir::Reg {
1096        // An argument of the function has a slot already and it is the caller's. The convention
1097        // puts the bytes in the argument area and hands over where they are, so the address that
1098        // arrived is the answer and no second copy of the value is made. Nothing ever writes to a
1099        // value of this type once it exists, so nothing writes to the caller's copy either. A
1100        // parameter of any other block is not this: what arrived there is an address a predecessor
1101        // chose, [`Lowering::settle`] has already copied the bytes out of it, and the slot those
1102        // bytes landed in is the one below.
1103        let entry = self.source.entry();
1104        if let (Def::Param { block, .. }, Some(reg)) =
1105            (self.source[value].def, self.regs[value.index()])
1106        {
1107            if entry == Some(block) {
1108                return reg;
1109            }
1110        }
1111        let index = match self.slots[value.index()] {
1112            Some(index) => index,
1113            None => {
1114                let index = self.stack.locals.len();
1115                self.stack.locals.push(Local { size: X87_BYTES, align: X87_BYTES });
1116                self.slots[value.index()] = Some(index);
1117                index
1118            }
1119        };
1120        let block = self.at.expect("a block is being filled");
1121        self.frame_address(block, index)
1122    }
1123
1124    /// The bytes a value crosses between a register and the x87 stack through, as their address
1125    /// in a fresh register.
1126    fn x87_crossing(&mut self) -> mir::Reg {
1127        let index = match self.crossing {
1128            Some(index) => index,
1129            None => {
1130                let index = self.stack.locals.len();
1131                self.stack.locals.push(Local { size: X87_CROSSING, align: X87_CROSSING });
1132                self.crossing = Some(index);
1133                index
1134            }
1135        };
1136        let block = self.at.expect("a block is being filled");
1137        self.frame_address(block, index)
1138    }
1139
1140    /// The two control words, as the address of the first of them in a fresh register.
1141    fn x87_control(&mut self) -> mir::Reg {
1142        let index = match self.control {
1143            Some(index) => index,
1144            None => {
1145                let index = self.stack.locals.len();
1146                self.stack.locals.push(Local { size: 4, align: 4 });
1147                self.control = Some(index);
1148                index
1149            }
1150        };
1151        let block = self.at.expect("a block is being filled");
1152        self.frame_address(block, index)
1153    }
1154
1155    /// An address held in a register, as the addressing mode that reaches it.
1156    fn through(&self, reg: mir::Reg) -> mir::Mem {
1157        mir::Mem::at(mir::Operand::read(reg, self.gpr))
1158    }
1159
1160    /// One instruction of a group, which names an address and nothing else.
1161    ///
1162    /// Every x87 instruction that moves a value is one of these. What it does to the stack is in
1163    /// the mnemonic rather than in an operand, so there is no register to write down and no
1164    /// register the allocator gets a say in.
1165    fn x87_at(&mut self, name: &str, span: Span, at: mir::Mem) {
1166        let block = self.at.expect("a block is being filled");
1167        let opcode = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{name}")));
1168        self.out.build(block, opcode).at(span).mem(at).finish();
1169    }
1170
1171    /// One instruction of a group that names nothing at all.
1172    ///
1173    /// The arithmetic is these. Both of an add's operands are already on the stack when it runs
1174    /// and so is where the answer goes, and the stack is not somewhere an instruction says, so
1175    /// `faddp` has an argument in the assembler's syntax and nothing here for the argument to come
1176    /// from. What it works on is which two pushes came before it, which is a fact about the order
1177    /// of the group and is why the group is written in one place.
1178    fn x87_only(&mut self, name: &str, span: Span) {
1179        let block = self.at.expect("a block is being filled");
1180        let opcode = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{name}")));
1181        self.out.build(block, opcode).at(span).finish();
1182    }
1183
1184    /// A `load` of a `long double`: onto the stack from where it was, and off it into the slot.
1185    ///
1186    /// Two instructions rather than the two general purpose moves the same sixteen bytes would
1187    /// take, because `fld` and `fstp` at this format neither convert nor look: the value goes on
1188    /// in the format it was already in and comes back off in it, so a signalling NaN stays one
1189    /// and nothing is raised. Which is what makes this a copy at all.
1190    fn x87_load(&mut self, inst: Inst) -> Result<(), Unsupported> {
1191        let (args, result) = self.ends(inst)?;
1192        let &address = args.first().ok_or_else(|| self.unsupported(inst))?;
1193        let span = self.source.span(inst);
1194        let from = self.reg_of(address)?;
1195        let from = self.through(from);
1196        let into = self.x87_slot(result);
1197        let into = self.through(into);
1198        self.x87_at("fld_t", span, from);
1199        self.x87_at("fstp_t", span, into);
1200        Ok(())
1201    }
1202
1203    /// A `store` of a `long double`: the same pair the other way round.
1204    fn x87_store(&mut self, inst: Inst) -> Result<(), Unsupported> {
1205        let args = self.source[self.source[inst].args].to_vec();
1206        let [value, address] = args[..] else { return Err(self.unsupported(inst)) };
1207        let span = self.source.span(inst);
1208        let from = self.x87_slot(value);
1209        let from = self.through(from);
1210        let into = self.reg_of(address)?;
1211        let into = self.through(into);
1212        self.x87_at("fld_t", span, from);
1213        self.x87_at("fstp_t", span, into);
1214        Ok(())
1215    }
1216
1217    /// A `float`, a `double` or an integer becoming a `long double`.
1218    ///
1219    /// Through memory, because the x87 reads memory and nothing else: the value is in a register
1220    /// the machine has and the unit has no way to be handed one, so it is written to the crossing
1221    /// bytes and loaded back at the format that widens it. Every one of these is exact. Sixty four
1222    /// bits of significand and fifteen of exponent hold every `float`, every `double` and every
1223    /// sixty four bit integer outright, so none of the four can round and none can raise.
1224    fn x87_across(
1225        &mut self,
1226        inst: Inst,
1227        put: &'static str,
1228        class: RegClass,
1229        get: &'static str,
1230    ) -> Result<(), Unsupported> {
1231        let (args, result) = self.ends(inst)?;
1232        let &source = args.first().ok_or_else(|| self.unsupported(inst))?;
1233        let span = self.source.span(inst);
1234        let value = self.reg_of(source)?;
1235        let across = self.x87_crossing();
1236        let across = self.through(across);
1237        let into = self.x87_slot(result);
1238        let into = self.through(into);
1239
1240        let block = self.at.expect("a block is being filled");
1241        let store = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{put}")));
1242        self.out.build(block, store).at(span).uses(value, class).mem(across).finish();
1243        self.x87_at(get, span, across);
1244        self.x87_at("fstp_t", span, into);
1245        Ok(())
1246    }
1247
1248    /// A `long double` becoming a `float`, a `double` or an integer.
1249    ///
1250    /// Through memory for the reason above and in the same three instructions backwards. The two
1251    /// that go to a float round to nearest, which is what the control word says unless somebody
1252    /// has changed it and is what C wants. The two that go to an integer do not, which is why they
1253    /// do not come here.
1254    fn x87_back(
1255        &mut self,
1256        inst: Inst,
1257        put: &'static str,
1258        get: &'static str,
1259        class: RegClass,
1260    ) -> Result<(), Unsupported> {
1261        let (args, result) = self.ends(inst)?;
1262        let &source = args.first().ok_or_else(|| self.unsupported(inst))?;
1263        let span = self.source.span(inst);
1264        let from = self.x87_slot(source);
1265        let from = self.through(from);
1266        let across = self.x87_crossing();
1267        let across = self.through(across);
1268
1269        self.x87_at("fld_t", span, from);
1270        self.x87_at(put, span, across);
1271        let block = self.at.expect("a block is being filled");
1272        let reg = self.new_reg(result);
1273        let load = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{get}")));
1274        self.out.build(block, load).at(span).def(reg, class).mem(across).finish();
1275        Ok(())
1276    }
1277
1278    /// An `fpext` up to a `long double`, which is the only direction this machine has one in.
1279    fn x87_widen(&mut self, inst: Inst) -> Result<(), Unsupported> {
1280        let sse = self.conv.sse_class;
1281        match self.source[self.narrow(inst)?].ty.bits() {
1282            32 => self.x87_across(inst, "movss_mr", sse, "fld_s"),
1283            64 => self.x87_across(inst, "movsd_mr", sse, "fld_l"),
1284            _ => Err(self.unsupported(inst)),
1285        }
1286    }
1287
1288    /// An `fptrunc` down from a `long double`, which is the other direction of the same.
1289    fn x87_narrow(&mut self, inst: Inst) -> Result<(), Unsupported> {
1290        let sse = self.conv.sse_class;
1291        let result = self.source[inst].first_result.ok_or_else(|| self.unsupported(inst))?;
1292        match self.source[result].ty.bits() {
1293            32 => self.x87_back(inst, "fstp_s", "movss_rm", sse),
1294            64 => self.x87_back(inst, "fstp_l", "movsd_rm", sse),
1295            _ => Err(self.unsupported(inst)),
1296        }
1297    }
1298
1299    /// A `sitofp` up to a `long double`.
1300    ///
1301    /// Thirty two bits and sixty four, and nothing narrower, because C widens an integer to `int`
1302    /// before it converts one and the front end writes that widening down. An unsigned integer is
1303    /// not here at all: `fild` reads its operand as signed, so a value above the signed range
1304    /// comes back short by two to the sixty fourth and has to be added back, which is arithmetic
1305    /// rather than a move and waits with the rest of it.
1306    fn x87_from_signed(&mut self, inst: Inst) -> Result<(), Unsupported> {
1307        let gpr = self.gpr;
1308        match self.source[self.narrow(inst)?].ty.bits() {
1309            32 => self.x87_across(inst, "mov_mr_32", gpr, "fild_l"),
1310            64 => self.x87_across(inst, "mov_mr_64", gpr, "fild_ll"),
1311            _ => Err(self.unsupported(inst)),
1312        }
1313    }
1314
1315    /// An `fptosi` down from a `long double`, which is the one conversion here with no single
1316    /// instruction behind it.
1317    ///
1318    /// C cuts towards zero and the unit rounds the way its control word says, so the store that
1319    /// takes the value off the stack is wrapped in the control word being saved, changed and put
1320    /// back. Five instructions around the one that does the work, and three more moving the word
1321    /// through a register, because this machine has no way to OR a constant into memory at this
1322    /// width. The unit has a shorter answer in `fisttp`, and `spec/10-backend.md` section 10.8
1323    /// says why it is not used: it is SSE3, the x86-64 baseline is not, and there is nothing here
1324    /// that can gate an instruction on a feature yet.
1325    fn x87_to_signed(&mut self, inst: Inst) -> Result<(), Unsupported> {
1326        let (args, result) = self.ends(inst)?;
1327        let &source = args.first().ok_or_else(|| self.unsupported(inst))?;
1328        let (put, get) = match self.source[result].ty.bits() {
1329            32 => ("fistp_l", "mov_rm_32"),
1330            64 => ("fistp_ll", "mov_rm_64"),
1331            _ => return Err(self.unsupported(inst)),
1332        };
1333        let span = self.source.span(inst);
1334        let gpr = self.gpr;
1335        let from = self.x87_slot(source);
1336        let from = self.through(from);
1337        let across = self.x87_crossing();
1338        let across = self.through(across);
1339        let control = self.x87_control();
1340        let saved = self.through(control).plus(0);
1341        let cut = self.through(control).plus(2);
1342
1343        // The word the unit has now, into the first of the two slots and into a register, with the
1344        // rounding field turned to truncate on the way to the second.
1345        self.x87_at("fnstcw", span, saved);
1346        let block = self.at.expect("a block is being filled");
1347        let was = self.out.new_vreg(gpr);
1348        let read = mir::Opcode::new(self.names.intern("x64.mov_rm_16"));
1349        self.out.build(block, read).at(span).def(was, gpr).mem(saved).finish();
1350        let now = self.out.new_vreg(gpr);
1351        let set = mir::Opcode::new(self.names.intern("x64.or_ri_16"));
1352        // Two address, which is written out here rather than taken from the two shorthands
1353        // because the shorthands leave an operand unconstrained: this machine ORs into the
1354        // register it read, so the two have to be the same one and only the constraint says so.
1355        self.out
1356            .build(block, set)
1357            .at(span)
1358            .operand(mir::Operand::write(now, gpr).with(Constraint::Reuse(1)))
1359            .operand(mir::Operand::read(was, gpr))
1360            .imm(X87_TRUNCATE)
1361            .finish();
1362        let write = mir::Opcode::new(self.names.intern("x64.mov_mr_16"));
1363        self.out.build(block, write).at(span).uses(now, gpr).mem(cut).finish();
1364
1365        // The conversion itself, under the changed word, and then the word the unit had put back
1366        // before anything else runs.
1367        self.x87_at("fldcw", span, cut);
1368        self.x87_at("fld_t", span, from);
1369        self.x87_at(put, span, across);
1370        self.x87_at("fldcw", span, saved);
1371
1372        let block = self.at.expect("a block is being filled");
1373        let reg = self.new_reg(result);
1374        let load = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{get}")));
1375        self.out.build(block, load).at(span).def(reg, gpr).mem(across).finish();
1376        Ok(())
1377    }
1378
1379    /// A constant of this type, as the bits of it written into its slot.
1380    ///
1381    /// No x87 instruction at all, which is the surprise here. A slot holding an eighty bit value is
1382    /// the value, so a constant is ten bytes put where the value lives, and the unit never has to
1383    /// see it: whatever reads it will `fld` it out of the slot the way it reads any other one.
1384    ///
1385    /// Ten bytes in two goes, because the machine stores eight at a time and there is no store of
1386    /// an immediate to memory, so each half is put in a register first. The six bytes above the ten
1387    /// are left alone, since nothing reads them: they are the padding that makes the type sixteen
1388    /// wide and they are unspecified in the psABI rather than zero.
1389    ///
1390    /// The other way is a constant pool, an `fldt` of a symbol, and a relocation, which is what a
1391    /// compiler with somewhere to put a literal does. This back end has nowhere to put one yet, and
1392    /// four instructions in the frame is what that costs until it does.
1393    fn x87_const(&mut self, inst: Inst) -> Result<(), Unsupported> {
1394        let Extra::Imm(imm) = self.source[inst].extra else { return Err(self.unsupported(inst)) };
1395        let result = self.source[inst].first_result.ok_or_else(|| self.unsupported(inst))?;
1396        let bits = self.source[imm].bits();
1397        let span = self.source.span(inst);
1398        let gpr = self.gpr;
1399        let slot = self.x87_slot(result);
1400        let low = self.through(slot).plus(0);
1401        let high = self.through(slot).plus(8);
1402
1403        let block = self.at.expect("a block is being filled");
1404        for (bytes, at, into) in
1405            [(bits as u64 as i64, low, "64"), (((bits >> 64) & 0xffff) as i64, high, "16")]
1406        {
1407            let held = self.out.new_vreg(gpr);
1408            let put = mir::Opcode::new(self.names.intern(&format!("{PREFIX}mov_ri_{into}")));
1409            self.out.build(block, put).at(span).def(held, gpr).imm(bytes).finish();
1410            let store = mir::Opcode::new(self.names.intern(&format!("{PREFIX}mov_mr_{into}")));
1411            self.out.build(block, store).at(span).uses(held, gpr).mem(at).finish();
1412        }
1413        Ok(())
1414    }
1415
1416    /// One arithmetic instruction on two eighty bit values, as the four it takes.
1417    ///
1418    /// The left operand is pushed first and the right one on top of it, so the left ends up
1419    /// underneath and the answer wanted is the one below against the top in that order. Which of
1420    /// the two mnemonics computes that is a question about the spelling rather than about the
1421    /// machine, and the two spellings disagree. Intel's `FSUBP ST(i), ST(0)` is `ST(i) - ST(0)`
1422    /// and is `DE E8+i`, and AT&T's `fsubp` is `DE E0+i`, which is the other subtraction. This
1423    /// compiler writes AT&T and encodes what gas encodes, so what it asks for here is `fsubr_p`
1424    /// and `fdivr_p`, and the `r` is not a reversal of anything the code generator decided.
1425    ///
1426    /// An addition and a multiplication have one form each and do not care, which is why a test
1427    /// that reads the mnemonic back would not have caught this and one that computes a subtraction
1428    /// and checks the answer does.
1429    ///
1430    /// The answer is left where the deeper of the two was and the shallower is gone, which is what
1431    /// the `p` on the mnemonic means, so one push has already been paid back by the time the
1432    /// `fstp` runs and the stack is level again after it.
1433    ///
1434    /// Nothing here is folded and nothing is reused. Two values that are the same value get two
1435    /// pushes of the same slot, and an operand that was just computed is read back out of the slot
1436    /// it was written to rather than left on the stack, which costs a store and a load per
1437    /// instruction in an expression. Keeping a partial result on the stack across the next
1438    /// instruction's operands means knowing how deep the stack is at every point in the block, and
1439    /// that is a different thing from writing a group.
1440    fn x87_arith(&mut self, inst: Inst, with: &'static str) -> Result<(), Unsupported> {
1441        let (args, result) = self.ends(inst)?;
1442        let [left, right] = args[..] else { return Err(self.unsupported(inst)) };
1443        let span = self.source.span(inst);
1444        let left = self.x87_slot(left);
1445        let left = self.through(left);
1446        let right = self.x87_slot(right);
1447        let right = self.through(right);
1448        let into = self.x87_slot(result);
1449        let into = self.through(into);
1450        self.x87_at("fld_t", span, left);
1451        self.x87_at("fld_t", span, right);
1452        self.x87_only(with, span);
1453        self.x87_at("fstp_t", span, into);
1454        Ok(())
1455    }
1456
1457    /// A negation, which is a push, the sign bit turned over and a pop.
1458    ///
1459    /// `fchs` does not read the value as a number, so this is right for a zero, for an infinity
1460    /// and for a NaN, and it raises nothing on any of them. Which is what C asks of a negation and
1461    /// is not what subtracting from zero would give: `0.0L - x` is a different answer at a
1462    /// negative zero and a signalling one at a NaN.
1463    fn x87_flip(&mut self, inst: Inst) -> Result<(), Unsupported> {
1464        let (args, result) = self.ends(inst)?;
1465        let &source = args.first().ok_or_else(|| self.unsupported(inst))?;
1466        let span = self.source.span(inst);
1467        let from = self.x87_slot(source);
1468        let from = self.through(from);
1469        let into = self.x87_slot(result);
1470        let into = self.through(into);
1471        self.x87_at("fld_t", span, from);
1472        self.x87_only("fchs", span);
1473        self.x87_at("fstp_t", span, into);
1474        Ok(())
1475    }
1476
1477    /// A comparison of two eighty bit values, as the two pushes and the one opcode that reads them.
1478    ///
1479    /// The right operand is pushed first and the left one on top of it, which is the other way
1480    /// round from the arithmetic and is because `fucomip` asks about the top against what is under
1481    /// it: the comparison this machine can do is the top's, so the value the predicate is about
1482    /// has to be the top. The pop that gets the loser off the stack and the byte that reads the
1483    /// flags are both inside the opcode, since what passes between those and the comparison is the
1484    /// flags and the flags are not something anything here can name.
1485    ///
1486    /// Which of the ten opcodes, and which way round, is the same table the vector comparisons
1487    /// match against in `rules/x86-64.rules`, and it has to stay the same table: a predicate that
1488    /// picked a different condition here than there would be a `long double` comparison that
1489    /// disagreed with the `double` comparison of the same two numbers, which is the one thing a
1490    /// wider format is not allowed to do.
1491    ///
1492    /// The always false and the always true are refused rather than folded into a constant,
1493    /// because a comparison this machine never has to do is one the optimizer should have removed
1494    /// and an instruction here that quietly agreed with it would hide that it did not.
1495    fn x87_compare(&mut self, inst: Inst) -> Result<(), Unsupported> {
1496        let Extra::FloatPred(pred) = self.source[inst].extra else {
1497            return Err(self.unsupported(inst));
1498        };
1499        let (args, result) = self.ends(inst)?;
1500        let [left, right] = args[..] else { return Err(self.unsupported(inst)) };
1501        // Two of the fourteen need a second byte and an instruction to put the two together,
1502        // because they are two conditions at once: an ordered equal is equal and not unordered,
1503        // and an unordered not equal is either. The opcode carries all of that and says here only
1504        // that it writes somewhere else as well.
1505        let (name, reversed, both) = match pred {
1506            FloatPred::Ogt => ("fucomip_set_a", false, false),
1507            FloatPred::Oge => ("fucomip_set_ae", false, false),
1508            FloatPred::Olt => ("fucomip_set_a", true, false),
1509            FloatPred::Ole => ("fucomip_set_ae", true, false),
1510            FloatPred::One => ("fucomip_set_ne", false, false),
1511            FloatPred::Ord => ("fucomip_set_np", false, false),
1512            FloatPred::Uno => ("fucomip_set_p", false, false),
1513            FloatPred::Ueq => ("fucomip_set_e", false, false),
1514            FloatPred::Ult => ("fucomip_set_b", false, false),
1515            FloatPred::Ule => ("fucomip_set_be", false, false),
1516            FloatPred::Ugt => ("fucomip_set_b", true, false),
1517            FloatPred::Uge => ("fucomip_set_be", true, false),
1518            FloatPred::Oeq => ("fucomip_set_e_and_np", false, true),
1519            FloatPred::Une => ("fucomip_set_ne_or_p", false, true),
1520            FloatPred::False | FloatPred::True => return Err(self.unsupported(inst)),
1521        };
1522        let (top, under) = if reversed { (right, left) } else { (left, right) };
1523
1524        let span = self.source.span(inst);
1525        let gpr = self.gpr;
1526        let under = self.x87_slot(under);
1527        let under = self.through(under);
1528        let top = self.x87_slot(top);
1529        let top = self.through(top);
1530        self.x87_at("fld_t", span, under);
1531        self.x87_at("fld_t", span, top);
1532
1533        let block = self.at.expect("a block is being filled");
1534        let reg = self.new_reg(result);
1535        // Taken before the instruction is started rather than inside it, since both come from the
1536        // same function being built and only one thing at a time may be adding to it.
1537        let spare = both.then(|| self.out.new_vreg(gpr));
1538        let opcode = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{name}")));
1539        let mut build = self.out.build(block, opcode).at(span).def(reg, gpr);
1540        if let Some(spare) = spare {
1541            build = build.def(spare, gpr);
1542        }
1543        build.finish();
1544        Ok(())
1545    }
1546
1547    /// The operands and the one result of an instruction that has exactly one.
1548    fn ends(&self, inst: Inst) -> Result<(&'a [Value], Value), Unsupported> {
1549        let data = &self.source[inst];
1550        let result = data.first_result.ok_or_else(|| self.unsupported(inst))?;
1551        Ok((&self.source[data.args], result))
1552    }
1553
1554    /// The operand of a conversion, which is the end of it that is not the `long double`.
1555    fn narrow(&self, inst: Inst) -> Result<Value, Unsupported> {
1556        let args = &self.source[self.source[inst].args];
1557        args.first().copied().ok_or_else(|| self.unsupported(inst))
1558    }
1559
1560    /// One `va_start`, as the four fields of the list it was handed.
1561    ///
1562    /// Two of them are numbers this already knows, and each costs an instruction to put in a
1563    /// register before it can be stored, because the machine here has no store of an immediate to
1564    /// memory. The other two are addresses in the frame, and each is a `lea` [`crate::finish`]
1565    /// finishes: the save area is one of the function's own stack objects, and the caller's
1566    /// argument area is where the parameters that had no register came from, which is the same
1567    /// place and the same fixup a parameter past the sixth already uses.
1568    ///
1569    /// What is written is exactly the four fields [`crate::varargs`] describes, in the order they
1570    /// are laid out, so that reading this beside that table is the whole of the check.
1571    fn va_start(&mut self, inst: Inst) -> Result<(), Unsupported> {
1572        let Some(&list) = self.source[self.source[inst].args].first() else {
1573            return Err(self.unsupported(inst));
1574        };
1575        let started = self.varargs.ok_or_else(|| self.unsupported(inst))?;
1576        let list = self.reg_of(list)?;
1577        let block = self.at.expect("a block is being filled");
1578        let span = self.source.span(inst);
1579
1580        for (at, count) in
1581            [(varargs::GP_OFFSET, started.integers), (varargs::FP_OFFSET, started.floats)]
1582        {
1583            let held = self.out.new_vreg(self.gpr);
1584            let load = mir::Opcode::new(self.names.intern("x64.mov_ri_32"));
1585            self.out.build(block, load).at(span).def(held, self.gpr).imm(i64::from(count)).finish();
1586
1587            let store = mir::Opcode::new(self.names.intern("x64.mov_mr_32"));
1588            let mem = self.field(list, at);
1589            self.out.build(block, store).at(span).uses(held, self.gpr).mem(mem).finish();
1590        }
1591
1592        // The first argument the signature did not name, which is as far up the caller's argument
1593        // area as the ones it did name reached. Nothing here knows where that area is, so the
1594        // distance is recorded the way a parameter read out of it is and finished with it.
1595        let overflow = self.out.new_vreg(self.gpr);
1596        let lea = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{}", x86_64::FRAME.lea)));
1597        let sp = mir::Operand::read(mir::Reg::physical(self.conv.stack_pointer), self.gpr);
1598        let made = self
1599            .out
1600            .build(block, lea)
1601            .at(span)
1602            .def(overflow, self.gpr)
1603            .mem(mir::Mem::at(sp))
1604            .finish();
1605        self.stack.arguments.push((made, started.incoming));
1606
1607        let save = self.frame_address(block, started.save);
1608        for (at, held) in [(varargs::OVERFLOW, overflow), (varargs::SAVE_AREA, save)] {
1609            let store = mir::Opcode::new(self.names.intern("x64.mov_mr_64"));
1610            let mem = self.field(list, at);
1611            self.out.build(block, store).at(span).uses(held, self.gpr).mem(mem).finish();
1612        }
1613        Ok(())
1614    }
1615
1616    /// One field of a list, as the addressing mode that reaches it.
1617    fn field(&self, list: mir::Reg, at: i64) -> mir::Mem {
1618        let base = mir::Operand::read(list, self.gpr);
1619        mir::Mem::at(base).plus(i32::try_from(at).expect("a field of a list is a small offset"))
1620    }
1621
1622    /// The address of a name: one `lea` off the instruction pointer, with the name on it.
1623    ///
1624    /// The same instruction an `alloca` gets and for a related reason. An address that is not in
1625    /// the program is a `lea` of an addressing mode that names no register, and the mode carries
1626    /// the symbol so that [`rucc_asm`] can write it relative to `%rip` and leave the relocation
1627    /// for the assembler. Both halves of that already existed: the printer writes `sym(%rip)` and
1628    /// the encoder emits the relocation, because a call to a name the file does not define needed
1629    /// them first.
1630    ///
1631    /// One `mov` and not one `lea` when the name is one [`Elsewhere`] holds, because the distance
1632    /// the `lea` adds to the instruction pointer is a number only a link that puts the name in
1633    /// this program can work out, and the address of a function this file merely declares is not
1634    /// such a number. The load reads the address out of the slot the linker fills in instead. The
1635    /// linker turns it back into the `lea` when the name turns out to have been here all along,
1636    /// so this is not slower in the case that was already right.
1637    ///
1638    /// There is deliberately no name for this in [`crate::term`], which is what stops the address
1639    /// being folded into the instruction that reads it. Folding it is the right thing to do and
1640    /// is what turns a load of a global from two instructions into one, but it is a separate
1641    /// question about addressing modes and issue #282 is it. Until then the address is in a
1642    /// register before anything uses it, which is correct and one instruction longer.
1643    ///
1644    /// What this does not do is give the name anything to refer to. A module carries its globals
1645    /// and nothing writes them out, so a file that defines the variable it reads compiles to a
1646    /// reference the linker cannot resolve. Issue #293 is the other half.
1647    fn address_of(&mut self, inst: Inst) -> Result<(), Unsupported> {
1648        let data = &self.source[inst];
1649        let Extra::Symbol(symbol) = data.extra else { return Err(self.unsupported(inst)) };
1650        let result = data.first_result.ok_or_else(|| self.unsupported(inst))?;
1651
1652        let block = self.at.expect("a block is being filled");
1653        let reg = self.new_reg(result);
1654        let span = self.source.span(inst);
1655        let (mnemonic, mem) = if self.elsewhere.holds(symbol) {
1656            (GOT_LOAD, mir::Mem::got(symbol))
1657        } else {
1658            (x86_64::FRAME.lea, mir::Mem::of(symbol))
1659        };
1660        let opcode = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{mnemonic}")));
1661        self.out.build(block, opcode).at(span).def(reg, self.gpr).mem(mem).finish();
1662        Ok(())
1663    }
1664
1665    /// A conversion that converts nothing: the result is the operand under another type.
1666    ///
1667    /// `ptrtoint` and `inttoptr` at one width are the whole of this. An address on this machine is
1668    /// an integer as wide as the machine addresses, so a cast between the two changes what the
1669    /// type system calls the value and changes nothing about the value, and the register holding
1670    /// it is the register that already held it. The front end never writes either of them at any
1671    /// other width, because it widens or narrows around the cast rather than through it, so the
1672    /// two widths disagreeing here means the IR came from somewhere else and is refused rather
1673    /// than guessed at.
1674    ///
1675    /// Reading the operand first is what materializes it when it is a constant, which is the case
1676    /// that matters: a null pointer is an `inttoptr` of zero, and that zero has to reach a
1677    /// register before anything can call it an address.
1678    fn rename(&mut self, inst: Inst) -> Result<(), Unsupported> {
1679        let data = &self.source[inst];
1680        let [arg] = self.source[data.args] else { return Err(self.unsupported(inst)) };
1681        let result = data.first_result.ok_or_else(|| self.unsupported(inst))?;
1682        if !self.is_address_width(self.source[arg].ty)
1683            || !self.is_address_width(self.source[result].ty)
1684        {
1685            return Err(self.unsupported(inst));
1686        }
1687        let reg = self.reg_of(arg)?;
1688        self.regs[result.index()] = Some(reg);
1689        Ok(())
1690    }
1691
1692    /// One barrier, which on this machine is one instruction at the strongest ordering and no
1693    /// instruction at all at every other one.
1694    ///
1695    /// x86-64 is total store order, so the only reordering the machine does is a store followed by
1696    /// a load of a different address, and the only ordering that forbids that is sequential
1697    /// consistency. An acquire, a release and an acquire release fence are therefore already true
1698    /// of every program running here, and what a program wanted from writing one is that the
1699    /// compiler not move memory accesses across it. The optimizer has finished by the time this
1700    /// runs and nothing below reorders one access past another, so the constraint is already
1701    /// discharged and there is nothing to write.
1702    ///
1703    /// The strongest one is `mfence`, which is what gcc 16.2.0 writes for
1704    /// `__atomic_thread_fence(__ATOMIC_SEQ_CST)` and for `__sync_synchronize`. A locked instruction
1705    /// on the stack is faster on most parts and is what some compilers write instead; it is also a
1706    /// write to memory the program did not ask for, and the plain barrier is the one that says what
1707    /// it means.
1708    ///
1709    /// Written here by name rather than by a rule, for the same reason a `lea` of a symbol is:
1710    /// there is nothing in a barrier that a proof over bitvectors could discharge. It computes
1711    /// nothing, so there is no equality to state, and what makes it the right answer is the memory
1712    /// model, which the rule language cannot talk about.
1713    fn barrier(&mut self, inst: Inst) -> Result<(), Unsupported> {
1714        let Extra::Order(order) = self.source[inst].extra else {
1715            return Err(self.unsupported(inst));
1716        };
1717        if order != MemOrder::SeqCst {
1718            return Ok(());
1719        }
1720        let block = self.at.expect("a block is being filled");
1721        let span = self.source.span(inst);
1722        let fence = mir::Opcode::new(self.names.intern("x64.mfence"));
1723        self.out.build(block, fence).at(span).finish();
1724        Ok(())
1725    }
1726
1727    /// One compare and exchange, which is the instruction every other atomic on this machine is
1728    /// built out of.
1729    ///
1730    /// What the IR asks for is: read what is at an address, compare it against a value the program
1731    /// expected, put a second value there if the two were equal, and say both what was read and
1732    /// whether the exchange happened. The machine has exactly that instruction, and the `lock` in
1733    /// front of it is what makes the whole of it one step as far as every other processor is
1734    /// concerned.
1735    ///
1736    /// The ordering is not read here, and that is the memory model rather than an omission. A
1737    /// locked instruction on x86-64 is a full barrier whatever the program asked for, so a relaxed
1738    /// compare and exchange and a sequentially consistent one are the same instruction, and there
1739    /// is nothing weaker to emit for the weaker orderings. The failure ordering is not read for the
1740    /// same reason.
1741    ///
1742    /// The two values it produces are why this is written by name. The one the program compares
1743    /// against and the one it gets back are both `rax`, which the instruction reads and writes
1744    /// without being told, and the table says so with a fixed constraint at each end rather than
1745    /// leaving the allocator to find out. The second value is the byte behind it, which is the zero
1746    /// flag read out by a `sete`, and it is a definition of the same instruction so that the
1747    /// allocator knows the two are live together and never gives the byte the register the answer
1748    /// is in.
1749    fn exchange(&mut self, inst: Inst) -> Result<(), Unsupported> {
1750        let args: Vec<Value> = self.source[self.source[inst].args].to_vec();
1751        let results: Vec<Value> = self.source[inst].results().collect();
1752        let [addr, expected, desired] = args[..] else { return Err(self.unsupported(inst)) };
1753        let [old, exchanged] = results[..] else { return Err(self.unsupported(inst)) };
1754
1755        // A value the machine can compare in one instruction, which is an integer or an address at
1756        // one of the four widths it has a compare and exchange for. Anything else is a type this
1757        // has no instruction for rather than a program that is wrong, and the front end refuses it
1758        // before ever getting here.
1759        let ty = self.source[old].ty;
1760        let bits = if ty.is_ptr() { ADDRESS_BITS } else { ty.bits() };
1761        if (!ty.is_int() && !ty.is_ptr()) || !matches!(bits, 8 | 16 | 32 | 64) {
1762            return Err(self.unsupported(inst));
1763        }
1764
1765        let base = self.reg_of(addr)?;
1766        let want = self.reg_of(expected)?;
1767        let put = self.reg_of(desired)?;
1768        let got = self.new_reg(old);
1769        let flag = self.new_reg(exchanged);
1770
1771        let name = format!("cmpxchg_{bits}");
1772        let form = x86_64::form(&name).ok_or_else(|| self.unsupported(inst))?;
1773        let block = self.at.expect("a block is being filled");
1774        let opcode = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{name}")));
1775        let mut build = self.out.build(block, opcode).at(self.source.span(inst));
1776        for (desc, reg) in form.operands().iter().zip([got, flag, want, put]) {
1777            let operand = mir::Operand {
1778                reg,
1779                class: desc.class,
1780                role: desc.role,
1781                constraint: desc.constraint,
1782            };
1783            build = build.operand(operand);
1784        }
1785        build.mem(mir::Mem::at(mir::Operand::read(base, self.gpr))).finish();
1786        Ok(())
1787    }
1788
1789    /// One read modify write, for the three operations this machine does in a single instruction.
1790    ///
1791    /// What the IR asks for is: read what is at an address, do something to it, put the answer back,
1792    /// say what was there before, and let nothing get between the three steps. The machine has
1793    /// `xchg` for putting a value there and `lock xadd` for adding one, and both leave what they
1794    /// found in the register the operand arrived in, which is why the value that comes back and the
1795    /// value that went in are one register here.
1796    ///
1797    /// A subtraction is the add over the negated operand, which is right at every width because the
1798    /// machine's arithmetic wraps and negating then adding is subtracting in two's complement
1799    /// whatever the operands were. The negate is a separate instruction in front, over a register of
1800    /// its own, so that the value the program handed over is not the one written on: an operand may
1801    /// be live after this and a program that read it again would read the negation.
1802    ///
1803    /// The ordering is not read, for the reason the compare and exchange beside this does not read
1804    /// it. `xchg` with memory locks the bus whether it is asked to or not and `lock xadd` is asked
1805    /// to, so both are full barriers on this machine and there is nothing weaker to fall to.
1806    ///
1807    /// Eight of the other ten never arrive, because `crate::retry` turned each of them into a loop
1808    /// around a compare and exchange before anything here saw it. The two that do arrive are the
1809    /// ones on floating values, and they are refused: a compare and exchange of a float wants the
1810    /// value carried through an integer of the same width, and an eighty bit float has no such
1811    /// width. Neither family of builtins can write one yet either, so a program that reaches this
1812    /// refusal is a program that reached an unimplemented builtin first.
1813    fn modify(&mut self, inst: Inst) -> Result<(), Unsupported> {
1814        let Extra::Rmw(op, _) = self.source[inst].extra else {
1815            return Err(self.unsupported(inst));
1816        };
1817        let args: Vec<Value> = self.source[self.source[inst].args].to_vec();
1818        let [addr, operand] = args[..] else { return Err(self.unsupported(inst)) };
1819        let old = self.source[inst].first_result.ok_or_else(|| self.unsupported(inst))?;
1820
1821        // A value the machine can exchange in one instruction, which is an integer at one of the
1822        // four widths it has these for. A pointer arrives as an address, so it is an integer by the
1823        // time it is here, and anything else is a type this has no instruction for.
1824        let ty = self.source[old].ty;
1825        if !ty.is_int() || !matches!(ty.bits(), 8 | 16 | 32 | 64) {
1826            return Err(self.unsupported(inst));
1827        }
1828        let name = match op {
1829            RmwOp::Xchg => format!("xchg_{}", ty.bits()),
1830            RmwOp::Add | RmwOp::Sub => format!("xadd_{}", ty.bits()),
1831            _ => return Err(self.unsupported(inst)),
1832        };
1833
1834        let base = self.reg_of(addr)?;
1835        let mut put = self.reg_of(operand)?;
1836        let block = self.at.expect("a block is being filled");
1837        let span = self.source.span(inst);
1838        if op == RmwOp::Sub {
1839            let negated = self.out.new_vreg(self.gpr);
1840            let negate =
1841                mir::Opcode::new(self.names.intern(&format!("{PREFIX}neg_r_{}", ty.bits())));
1842            let form = x86_64::form(&format!("neg_r_{}", ty.bits()))
1843                .ok_or_else(|| self.unsupported(inst))?;
1844            let mut build = self.out.build(block, negate).at(span);
1845            for (desc, reg) in form.operands().iter().zip([negated, put]) {
1846                build = build.operand(mir::Operand {
1847                    reg,
1848                    class: desc.class,
1849                    role: desc.role,
1850                    constraint: desc.constraint,
1851                });
1852            }
1853            build.finish();
1854            put = negated;
1855        }
1856
1857        let got = self.new_reg(old);
1858        let form = x86_64::form(&name).ok_or_else(|| self.unsupported(inst))?;
1859        let opcode = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{name}")));
1860        let mut build = self.out.build(block, opcode).at(span);
1861        for (desc, reg) in form.operands().iter().zip([got, put]) {
1862            build = build.operand(mir::Operand {
1863                reg,
1864                class: desc.class,
1865                role: desc.role,
1866                constraint: desc.constraint,
1867            });
1868        }
1869        build.mem(mir::Mem::at(mir::Operand::read(base, self.gpr))).finish();
1870        Ok(())
1871    }
1872
1873    /// One `asm` statement, for as long as its template has no instructions in it.
1874    ///
1875    /// An empty template is most of the inline assembly in a test suite, and it is not a corner
1876    /// case somebody wrote by accident. A program that wants a value computed where it stands, or a
1877    /// loop the optimizer must not touch, writes `asm volatile ("" : : : "memory")`, and forty
1878    /// years of bug reports about optimizers are full of them. What such a statement asks for is
1879    /// the barrier and the operand places, and no instructions at all.
1880    ///
1881    /// So the instructions are the easy half here and there are none of them. The half that is
1882    /// real is the operands: a constraint says where a value has to be, and where it has to be is
1883    /// still true when the template between them is empty.
1884    ///
1885    /// What the constraints ask for, on an empty template, is only ever that two operands share a
1886    /// place. Nothing reads a register no text names, so `"r"` on its own asks for a register and
1887    /// no particular one, and any register at all answers it. A matching constraint is different,
1888    /// because it says the output the assembly leaves is the place the input arrived in, and with
1889    /// no instructions between them that is the input unchanged. So it is a rename and not a move:
1890    /// the value is already in a register and the result is that register.
1891    ///
1892    /// An output nothing is tied to is whatever the assembly left there, which for a template that
1893    /// writes nothing is whatever was in the register. That is a value the program is not entitled
1894    /// to, and this writes a zero rather than reading one, because the allocator has to be given a
1895    /// definition before a use whatever the program is entitled to.
1896    ///
1897    /// The clobber list is not read, and on an empty template that is right rather than an
1898    /// omission. A clobber says the assembly ruins a register, and a template with no instructions
1899    /// in it ruins nothing.
1900    fn assembly(&mut self, inst: Inst) -> Result<(), Unsupported> {
1901        let data = &self.source[inst];
1902        let Extra::Asm(asm) = data.extra else { return Err(self.unsupported(inst)) };
1903        let info = self.source[asm];
1904        if !self.source[info.targets].is_empty() {
1905            return Err(Unsupported::Assembly { inst, refused: Written::Goto });
1906        }
1907        if !self.names.resolve(info.template).trim().is_empty() {
1908            return Err(Unsupported::Assembly { inst, refused: Written::Template });
1909        }
1910
1911        let constraints = self.names.resolve(info.constraints).to_string();
1912        let results: Vec<Value> = data.results().collect();
1913        let operands = AsmOperands::read(&constraints, &results, &self.source[data.args])
1914            .ok_or(Unsupported::Assembly { inst, refused: Written::Operand })?;
1915
1916        for (index, operand) in operands.iter().copied().enumerate().collect::<Vec<_>>() {
1917            let Some(result) = operand.result else { continue };
1918            let ty = self.source[result].ty;
1919            if on_x87(ty) {
1920                return Err(Unsupported::Assembly { inst, refused: Written::Operand });
1921            }
1922            match operands.tied_to(index) {
1923                // The place the input arrived in, which the assembly wrote nothing over.
1924                Some(from) => {
1925                    if self.class_of(self.source[from].ty) != self.class_of(ty) {
1926                        return Err(Unsupported::Assembly { inst, refused: Written::Operand });
1927                    }
1928                    let reg = self.reg_of(from)?;
1929                    self.regs[result.index()] = Some(reg);
1930                }
1931                None => self.undefined(inst, result)?,
1932            }
1933        }
1934        Ok(())
1935    }
1936
1937    /// A register holding a value the program has no claim on, written as a zero.
1938    ///
1939    /// Every other way of saying it costs the same instruction or needs a word the machine IR does
1940    /// not have, and a zero is the one that reads the same on every run.
1941    fn undefined(&mut self, inst: Inst, result: Value) -> Result<(), Unsupported> {
1942        let ty = self.source[result].ty;
1943        let refused = Unsupported::Assembly { inst, refused: Written::Operand };
1944        if self.class_of(ty) != self.gpr || !matches!(ty.bits(), 8 | 16 | 32 | 64) {
1945            return Err(refused);
1946        }
1947        let block = self.at.expect("a block is being filled");
1948        let span = self.source.span(inst);
1949        let reg = self.new_reg(result);
1950        let put = mir::Opcode::new(self.names.intern(&format!("{PREFIX}mov_ri_{}", ty.bits())));
1951        self.out.build(block, put).at(span).def(reg, self.gpr).imm(0).finish();
1952        Ok(())
1953    }
1954
1955    /// Whether a type is the width an address is, which is what makes a cast to or from one free.
1956    fn is_address_width(&self, ty: Type) -> bool {
1957        ty.is_ptr() || (ty.is_int() && ty.bits() == ADDRESS_BITS)
1958    }
1959
1960    /// Where a block goes, which in machine IR is on the block rather than on its terminator.
1961    ///
1962    /// That is why no rule ever names a block: a branch is selected for what it reads and the
1963    /// edges are copied across here, arguments and all. The arguments are read last, after every
1964    /// instruction of the block is written, because an argument that is a constant is
1965    /// materialized where it is first wanted and the end of the block is where an edge wants it.
1966    ///
1967    /// Which is not quite the end. A block that leaves two ways has the branch as its last
1968    /// instruction, and anything appended after a branch is something the branch has already
1969    /// jumped past, so a constant materialized here would be a register the block below reads and
1970    /// nothing ever writes. The branch is put back on the end when that happened, which is the
1971    /// only reordering anything in this crate does and is why the branch is remembered before a
1972    /// single argument is read.
1973    fn edges(&mut self, block: Block, out: mir::Block) -> Result<(), Unsupported> {
1974        let Some(term) = self.source.terminator(block) else { return Ok(()) };
1975        let branch =
1976            if self.source[term].opcode == Opcode::BrIf { self.out.terminator(out) } else { None };
1977
1978        let calls: Vec<rucc_ir::BlockCall> = self.source.successors(term).collect();
1979        let mut succs = Vec::with_capacity(calls.len());
1980        for call in calls {
1981            let args: Vec<Value> = self.source[call.args].to_vec();
1982            let mut regs = Vec::with_capacity(args.len());
1983            for value in args {
1984                // The address of where the value is rather than the value, for the one type a
1985                // register holds none of. The block on the other side copies the bytes out of it
1986                // into a slot of its own, which is what makes a second edge into the same block
1987                // safe.
1988                let reg = if on_x87(self.source[value].ty) {
1989                    self.x87_slot(value)
1990                } else {
1991                    self.reg_of(value)?
1992                };
1993                regs.push(reg);
1994            }
1995            succs.push(mir::BlockCall { block: self.out_block(call.block), args: regs });
1996        }
1997        if let Some(branch) = branch {
1998            if self.out.terminator(out) != Some(branch) {
1999                self.out.remove_inst(branch);
2000                self.out.append_inst(out, branch);
2001            }
2002        }
2003        *self.out.succs_mut(out) = succs;
2004        Ok(())
2005    }
2006
2007    /// The machine IR block an IR block became.
2008    fn out_block(&self, block: Block) -> mir::Block {
2009        self.blocks[block.index()].expect("every block was created before any was filled")
2010    }
2011
2012    /// The parameters of the entry block, which are the function's arguments.
2013    ///
2014    /// They are not block parameters in the machine IR and they cannot be. A block parameter is
2015    /// given its value by a move on the edge into the block, and there is no edge into an entry
2016    /// block, so what arrives in a function is the convention's to say. [`crate::abi`] is what
2017    /// says it.
2018    ///
2019    /// The ones past the last register arrived in the caller's memory and are read out of it, and
2020    /// the loads that read them come back here so that the frame can finish them the way it
2021    /// finishes an `alloca`.
2022    fn arrive(&mut self, block: Block, out: mir::Block) -> Result<(), Unsupported> {
2023        let params = self.source[block].params.clone();
2024        // The type of each is the block's answer and what the ABI asks of it is the signature's,
2025        // and the two lists are the same list: a parameter the classification turned into a
2026        // pointer is a pointer in the block too. A block with more parameters than the signature
2027        // names is not one the front end writes, and each of those is taken as a plain value.
2028        let asked: Vec<Abi> = self.source.signature().params.iter().map(|it| it.abi).collect();
2029        let types: Vec<Param> = params
2030            .iter()
2031            .enumerate()
2032            .map(|(index, &value)| {
2033                let abi = asked.get(index).copied().unwrap_or_default();
2034                Param { ty: self.source[value].ty, abi }
2035            })
2036            .collect();
2037        // A save area for a function that takes arguments its signature does not name, on a
2038        // convention whose list is the four field one. Windows is the other kind and has no area at
2039        // all, so a `va_start` in one is refused rather than built wrong.
2040        let variadic = self.source.signature().variadic && !self.conv.shared_positions;
2041        let area = variadic.then(|| varargs::Area::of(self.conv));
2042        let arrived = abi::entry(&mut self.out, out, &types, self.conv, self.names, area)
2043            .map_err(|(index, missing)| Unsupported::Argument { index, missing })?;
2044        for (&param, reg) in params.iter().zip(&arrived.regs) {
2045            self.regs[param.index()] = Some(*reg);
2046        }
2047        if let Some(area) = area {
2048            self.save_area(out, &arrived, area);
2049        }
2050        self.stack.arguments.extend(arrived.stack);
2051        Ok(())
2052    }
2053
2054    /// The prologue of a variadic function, which is every argument register it was handed written
2055    /// into the frame.
2056    ///
2057    /// Every one the signature did not name, that is. Which of those hold anything is a thing only
2058    /// the caller knew and there is nothing here to ask, so all of them are written, and the ones a
2059    /// named parameter took are not, because `va_start` sets the two offsets past them and nothing
2060    /// ever reads their slots.
2061    ///
2062    /// What that costs is up to fourteen stores in the prologue of a function that may read none of
2063    /// them, and the convention's answer to that is the count of vector registers in `%al`, which
2064    /// lets a callee skip the eight vector stores when the call passed no floats. Skipping them is a
2065    /// branch in a prologue, and a prologue is written long after this by [`crate::finish`], which
2066    /// has no blocks to branch between. So they are all written every time, which is correct and is
2067    /// what `-O0` costs. Issue #323 is the branch.
2068    ///
2069    /// A vector register is written eight bytes at a time and not sixteen, for the reason
2070    /// [`crate::varargs`] gives: the upper half of a slot is not something any reader of a list
2071    /// looks at.
2072    ///
2073    /// The address is computed once into a register rather than written as a displacement off the
2074    /// stack pointer, because a displacement into a frame is not known until after allocation and
2075    /// one `lea` costs less than a fixup list for a dozen stores. It is the same `lea` an `alloca`
2076    /// gets and [`crate::finish`] fills it in the same way.
2077    fn save_area(&mut self, out: mir::Block, arrived: &abi::Arrived, area: varargs::Area) {
2078        let save = self.stack.locals.len();
2079        self.stack.locals.push(Local { size: area.size, align: varargs::VECTOR_SLOT });
2080        self.varargs = Some(Varargs {
2081            save,
2082            incoming: arrived.used,
2083            integers: u32::try_from(arrived.took.0).unwrap_or(0) * area.stride(false),
2084            floats: area.starts_at(true)
2085                + u32::try_from(arrived.took.1).unwrap_or(0) * area.stride(true),
2086        });
2087
2088        let base = self.frame_address(out, save);
2089        for &(reg, class, at) in &arrived.spare {
2090            let name = if class == self.gpr { "x64.mov_mr_64" } else { "x64.movsd_mr" };
2091            let store = mir::Opcode::new(self.names.intern(name));
2092            let up = i32::try_from(at).expect("a register save area under two gigabytes");
2093            let mem = mir::Mem::at(mir::Operand::read(base, self.gpr)).plus(up);
2094            self.out.build(out, store).uses(reg, class).mem(mem).finish();
2095        }
2096    }
2097
2098    /// The address of one of the function's stack objects, in a fresh register.
2099    ///
2100    /// Written with nothing in its displacement, because where an object is in a frame is not known
2101    /// until after allocation, and given to [`crate::finish`] to fill in the way an `alloca` is.
2102    fn frame_address(&mut self, out: mir::Block, local: usize) -> mir::Reg {
2103        let reg = self.out.new_vreg(self.gpr);
2104        let lea = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{}", x86_64::FRAME.lea)));
2105        let sp = mir::Operand::read(mir::Reg::physical(self.conv.stack_pointer), self.gpr);
2106        let made = self.out.build(out, lea).def(reg, self.gpr).mem(mir::Mem::at(sp)).finish();
2107        self.stack.addresses.push((made, local));
2108        reg
2109    }
2110
2111    /// Whether an instruction is one no machine instruction is written for where it stands.
2112    ///
2113    /// Four of them, and none is a lowering decision, which is why none is a rule. A constant is
2114    /// written where a register for it is first wanted rather than where the IR put it, and every
2115    /// reader of one may have folded it into an immediate, in which case nowhere is the right
2116    /// place. A return of nothing has nothing to put anywhere: the epilogue gives the frame back
2117    /// and leaves, and it is appended to every block with no successors long after this has
2118    /// finished, so a return with a value is one instruction here and a return without one is
2119    /// none. Unless the value went back through memory, in which case there is something to put
2120    /// somewhere after all and the IR does not carry it: the address the caller handed over has
2121    /// to be in `rax` on the way out, and [`Lowering::returned`] is what writes that.
2122    ///
2123    /// An unconditional jump is the third, and there is even less of it: the edge is on the
2124    /// block, and whether the block it goes to is the next one and needs no jump at all is the
2125    /// block layout's answer rather than this one's.
2126    ///
2127    /// The fourth is a point control does not arrive at, in both of the forms the IR has for it:
2128    /// the `unreachable` terminator the front end puts at the end of a function whose body can run
2129    /// off the bottom, and the `unreachable_hint` a call to `__builtin_unreachable` becomes. What
2130    /// to write for a place nothing reaches is a question with no wrong answer, and nothing is the
2131    /// smallest one and the one gcc 16.2.0 gives at `-O0`. The terminator leaves the block with no
2132    /// successors, so the epilogue lands at the end of it the way it does on any other block that
2133    /// goes nowhere, and the function cannot fall out of its own last instruction into whatever
2134    /// the assembler puts next.
2135    fn writes_nothing(&self, inst: Inst) -> bool {
2136        let data = &self.source[inst];
2137        match data.opcode {
2138            Opcode::IConst | Opcode::Jump | Opcode::Unreachable | Opcode::UnreachableHint => true,
2139            Opcode::Return => self.source[data.args].is_empty() && self.sret().is_none(),
2140            _ => false,
2141        }
2142    }
2143
2144    /// The rule that fires on an instruction, and what it bound.
2145    ///
2146    /// The plans are tried in order and the first that matches wins, which is the maximal munch
2147    /// `spec/10-backend.md` asks for: a plan that offers more to the matcher is tried before one
2148    /// that offers less.
2149    fn select(&self, inst: Inst) -> Option<(Plan, Match<Term>)> {
2150        for plan in self.plans(inst) {
2151            let terms = Terms::new(self.source, inst, plan);
2152            if let Some(matched) = TABLE.find(&terms, Term::Root) {
2153                return Some((plan, matched));
2154            }
2155        }
2156        None
2157    }
2158
2159    /// Every way this instruction can be shown to the matcher, most offered first.
2160    fn plans(&self, inst: Inst) -> Vec<Plan> {
2161        let args = &self.source[self.source[inst].args];
2162        let mut plans = vec![PLAIN];
2163        for (index, &arg) in args.iter().enumerate().take(MAX_ARGS) {
2164            let mut ways = Vec::new();
2165            if self.foldable(inst, arg) {
2166                ways.push(Shown::Expand);
2167            }
2168            if Terms::new(self.source, inst, PLAIN).constant(arg).is_some() {
2169                ways.push(Shown::Const);
2170            }
2171            ways.push(Shown::Reg);
2172            plans = plans
2173                .into_iter()
2174                .flat_map(|plan| {
2175                    ways.iter().map(move |&way| {
2176                        let mut next = plan;
2177                        next[index] = way;
2178                        next
2179                    })
2180                })
2181                .collect();
2182        }
2183        plans
2184    }
2185
2186    /// Whether an operand may be shown as the instruction that computed it.
2187    ///
2188    /// It has to be in the same block, because a rule that folds one instruction into another
2189    /// moves the work to where the second one is. It has to be read only by this instruction,
2190    /// because folding it does not delete it for anybody else and doing the work twice is not a
2191    /// saving. And it has to be something rather than a block parameter, and not a constant,
2192    /// which is shown as a constant instead.
2193    fn foldable(&self, into: Inst, value: Value) -> bool {
2194        let Def::Result { inst, .. } = self.source[value].def else { return false };
2195        if self.source[inst].opcode == Opcode::IConst || self.uses[value.index()] != 1 {
2196            return false;
2197        }
2198        self.source.block_of(inst).is_some()
2199            && self.source.block_of(inst) == self.source.block_of(into)
2200    }
2201
2202    /// The instructions a match folded into the one it matched.
2203    ///
2204    /// The plan is what says this, not the bindings: a binding is a register or a number either
2205    /// way, and an operand shown as the instruction that computed it is one no rule could have
2206    /// matched without taking that instruction, because the plan offered the matcher nothing
2207    /// else to call it.
2208    fn folds(&self, inst: Inst, plan: Plan) -> Vec<Inst> {
2209        let args = &self.source[self.source[inst].args];
2210        args.iter()
2211            .take(MAX_ARGS)
2212            .enumerate()
2213            .filter(|&(index, _)| plan[index] == Shown::Expand)
2214            .filter_map(|(_, &arg)| match self.source[arg].def {
2215                Def::Result { inst, .. } => Some(inst),
2216                Def::Param { .. } => None,
2217            })
2218            .collect()
2219    }
2220
2221    /// Build the machine instruction a match calls for.
2222    fn emit(&mut self, inst: Inst, matched: &Match<Term>) -> Result<(), Unsupported> {
2223        let rule: &Rule = TABLE.rule(matched);
2224        let pieces = rule.replacement;
2225        let Some(Piece::App { head, arity }) = pieces.first() else {
2226            return Err(self.unsupported(inst));
2227        };
2228        let opcode = head.strip_prefix(PREFIX).ok_or_else(|| self.unsupported(inst))?;
2229        let form = x86_64::form(opcode).ok_or_else(|| self.unsupported(inst))?;
2230
2231        let mut read = Read::default();
2232        let mut at = 1;
2233        for _ in 0..*arity {
2234            at = self.read(inst, pieces, at, &matched.bindings, &mut read)?;
2235        }
2236
2237        let descs = form.operands();
2238        let writes = descs.iter().take_while(|desc| desc.role.is_def()).count();
2239        if descs.len() - writes != read.regs.len() {
2240            return Err(self.unsupported(inst));
2241        }
2242
2243        // The first thing the instruction writes is what it computes, and any others are
2244        // registers the machine destroys on the way, which are fresh because nothing else is in
2245        // them and nothing reads them. An instruction that writes nothing at all is one whose
2246        // whole purpose is its effect, which is what a store is, and there is no result to put
2247        // anywhere.
2248        let mut regs = Vec::new();
2249        if writes > 0 {
2250            let result = self.source[inst].first_result.ok_or_else(|| self.unsupported(inst))?;
2251            regs.push(self.new_reg(result));
2252            // The rest are the registers the machine destroys on the way, and the class each is in
2253            // is the one the instruction's description gives it rather than a guess, so that an
2254            // instruction that wrecks a register in the other file says so.
2255            regs.extend(descs[1..writes].iter().map(|desc| self.out.new_vreg(desc.class)));
2256        } else if self.source[inst].first_result.is_some() {
2257            // A rule that throws away a value the IR gave a name to would leave every reader of
2258            // that name with nothing to read, so it is a rule this and the target disagree about.
2259            return Err(self.unsupported(inst));
2260        }
2261        regs.extend(read.regs.iter().copied());
2262
2263        let block = self.at.expect("a block is being filled");
2264        let opcode = mir::Opcode::new(self.names.intern(head));
2265        let mut build = self.out.build(block, opcode).at(self.source.span(inst));
2266        for (desc, reg) in descs.iter().zip(regs) {
2267            let operand = mir::Operand {
2268                reg,
2269                class: desc.class,
2270                role: desc.role,
2271                constraint: desc.constraint,
2272            };
2273            build = build.operand(operand);
2274        }
2275        if let Some(mem) = read.mem {
2276            build = build.mem(mem);
2277        }
2278        if let Some(imm) = read.imm {
2279            build = build.imm(imm);
2280        }
2281        build.finish();
2282        Ok(())
2283    }
2284
2285    /// Read one argument of a replacement, which is a register, a number or an address.
2286    ///
2287    /// Gives back the position after it, because a replacement is flat and an address takes
2288    /// arguments of its own.
2289    fn read(
2290        &mut self,
2291        inst: Inst,
2292        pieces: &'static [Piece],
2293        at: usize,
2294        bindings: &[Term],
2295        out: &mut Read,
2296    ) -> Result<usize, Unsupported> {
2297        match pieces.get(at) {
2298            Some(Piece::Int(value)) => {
2299                out.imm = i64::try_from(*value).ok();
2300                Ok(at + 1)
2301            }
2302            Some(Piece::Var { index, .. }) => {
2303                match bindings.get(*index) {
2304                    Some(&Term::Reg(value)) => {
2305                        let reg = self.reg_of(value)?;
2306                        out.regs.push(reg);
2307                    }
2308                    Some(&Term::Num(value)) => out.imm = i64::try_from(value).ok(),
2309                    // A pattern binds a register or a number and nothing else, so this is a
2310                    // rule the matcher and this file disagree about.
2311                    _ => return Err(self.unsupported(inst)),
2312                }
2313                Ok(at + 1)
2314            }
2315            Some(Piece::App { head, arity }) => {
2316                let kind = x86_64::address(head).ok_or_else(|| self.unsupported(inst))?;
2317                let mut inner = Read::default();
2318                let mut next = at + 1;
2319                for _ in 0..*arity {
2320                    next = self.read(inst, pieces, next, bindings, &mut inner)?;
2321                }
2322                let mem = address(kind, &inner, self.gpr).ok_or_else(|| self.unsupported(inst))?;
2323                out.mem = Some(mem);
2324                Ok(next)
2325            }
2326            None => Err(self.unsupported(inst)),
2327        }
2328    }
2329
2330    /// The register a value is in, materializing it if it is a constant that has not been put in
2331    /// one yet.
2332    ///
2333    /// A constant is written where it is wanted rather than where the IR defined it, and where it
2334    /// is wanted is a block that need not be the one the IR defined it in. So the register holding
2335    /// one is only good inside the block it was written into, and a second block that wants the
2336    /// same constant gets its own. Anything else is a register read where nothing wrote it: the
2337    /// IR guarantees a definition dominates its uses, and this moved the definition.
2338    ///
2339    /// Writing the number again is also the right answer and not merely the safe one. It is one
2340    /// instruction that reads nothing, which is cheaper than holding a register live across a
2341    /// branch for it, and it is what a rematerializing allocator would do with the value anyway.
2342    fn reg_of(&mut self, value: Value) -> Result<mir::Reg, Unsupported> {
2343        let constant = match self.source[value].def {
2344            Def::Result { inst, .. } => {
2345                (self.source[inst].opcode == Opcode::IConst).then_some(inst)
2346            }
2347            Def::Param { .. } => None,
2348        };
2349        let here = self.at.expect("a block is being filled");
2350        if let Some(reg) = self.regs[value.index()] {
2351            if constant.is_none() || self.written[value.index()] == Some(here) {
2352                return Ok(reg);
2353            }
2354        }
2355        if let Some(inst) = constant {
2356            // Cleared so that the register the constant is written into is a new one rather than
2357            // the one the block above wrote, which is still being read up there.
2358            self.regs[value.index()] = None;
2359            let matched = self
2360                .select(inst)
2361                .map(|(_, matched)| matched)
2362                .ok_or_else(|| self.unsupported(inst))?;
2363            self.emit(inst, &matched)?;
2364            // The same mark the loop over the instructions makes, and it has to be made here as
2365            // well because this is the only place a constant is ever selected: the loop skips one
2366            // where the IR wrote it, so a rule that lowers a constant fires from nowhere else and
2367            // would be reported as a rule nothing reaches.
2368            self.fired.mark(matched.rule);
2369            self.written[value.index()] = Some(here);
2370            return Ok(self.regs[value.index()].expect("a constant is written into a register"));
2371        }
2372        Ok(self.new_reg(value))
2373    }
2374
2375    /// Which register file a value of that type lives in.
2376    ///
2377    /// The vector one for the two float widths the machine has scalar instructions for, and the
2378    /// general purpose one for everything else. A `long double` is in neither, and it is here
2379    /// rather than in the vector class on purpose: it would be put in a register that cannot hold
2380    /// it, and there is no rule that names one, so the instruction computing it is reported. The
2381    /// wrong class would make that a wrong program instead of a refused one.
2382    fn class_of(&self, ty: Type) -> RegClass {
2383        match crate::term::float_slot(ty) {
2384            Some(_) => self.conv.sse_class,
2385            None => self.gpr,
2386        }
2387    }
2388
2389    /// A fresh register for a value, which is what the instruction computing it writes.
2390    fn new_reg(&mut self, value: Value) -> mir::Reg {
2391        if let Some(reg) = self.regs[value.index()] {
2392            return reg;
2393        }
2394        let reg = self.out.new_vreg(self.class_of(self.source[value].ty));
2395        self.regs[value.index()] = Some(reg);
2396        reg
2397    }
2398
2399    fn unsupported(&self, inst: Inst) -> Unsupported {
2400        let data = &self.source[inst];
2401        Unsupported::Inst {
2402            inst,
2403            term: Terms::new(self.source, inst, PLAIN).name(inst),
2404            opcode: data.opcode,
2405            ty: data.first_result.map(|result| self.source[result].ty),
2406        }
2407    }
2408}
2409
2410/// What the arguments of one replacement came to.
2411#[derive(Debug, Default)]
2412struct Read {
2413    regs: Vec<mir::Reg>,
2414    imm: Option<i64>,
2415    mem: Option<mir::Mem>,
2416}
2417
2418/// The addressing mode an address constructor's arguments make.
2419///
2420/// One arm per constructor rather than a question asked of the kind, because what the arguments
2421/// mean is the whole of what tells the four apart: the same register is a base in one and an
2422/// index in another, and the same constant is a scale in one and a displacement in another.
2423fn address(kind: x86_64::Address, read: &Read, gpr: RegClass) -> Option<mir::Mem> {
2424    let mut regs = read.regs.iter().copied().map(|reg| mir::Operand::read(reg, gpr));
2425    match kind {
2426        x86_64::Address::BaseIndexScale => {
2427            let base = regs.next()?;
2428            let index = regs.next()?;
2429            Some(mir::Mem::at(base).indexed(index, u8::try_from(read.imm?).ok()?))
2430        }
2431        x86_64::Address::IndexScale => Some(mir::Mem {
2432            base: None,
2433            index: Some(regs.next()?),
2434            scale: u8::try_from(read.imm?).ok()?,
2435            disp: 0,
2436            symbol: None,
2437            got: false,
2438            segment: None,
2439        }),
2440        x86_64::Address::Base => Some(mir::Mem::at(regs.next()?)),
2441        // The rule that writes this has a guard saying the constant fits, so a displacement that
2442        // does not is a rule and a target that disagree rather than a program this cannot compile.
2443        x86_64::Address::BaseOffset => {
2444            Some(mir::Mem { disp: i32::try_from(read.imm?).ok()?, ..mir::Mem::at(regs.next()?) })
2445        }
2446    }
2447}
2448
2449/// The table this selector matches with.
2450///
2451/// One target for now, because one target has a rule file. Which table to use becomes a question
2452/// the moment a second one does, and the answer will be the target the session was given rather
2453/// than a constant here.
2454static TABLE: &Table = &crate::select::x86_64::TABLE;
2455
2456#[cfg(test)]
2457mod tests {
2458    use rucc_ir::{
2459        AsmInfo, Builder, CallInfo, Flags, InstData, MemInfo, MemOrder, Restrict, Signature, Type,
2460    };
2461    use rucc_regalloc::assign::Env;
2462    use rucc_target::x86_64::{FRAME, REGS, SYSV};
2463
2464    use super::*;
2465    use crate::finish::{Convention, finish};
2466    use crate::frame::{Frame, Incoming, Layout};
2467
2468    /// A function of as many 64 bit parameters as the test wants, and the block they are in.
2469    fn blank(params: &[Type]) -> (Interner, Func, Block, Vec<Value>) {
2470        let mut names = Interner::new();
2471        let mut func = Func::new(names.intern("f"), Signature::new());
2472        let block = func.create_block();
2473        let values = params.iter().map(|&ty| func.append_param(block, ty)).collect();
2474        (names, func, block, values)
2475    }
2476
2477    /// An ordinary access: not atomic, and aligned enough that nothing here has an opinion.
2478    /// Neither field reaches selection, which is the point of saying it once here.
2479    fn plain() -> MemInfo {
2480        MemInfo {
2481            size: 0,
2482            align: 1,
2483            order: MemOrder::NotAtomic,
2484            tbaa: None,
2485            restrict: Restrict::NONE,
2486        }
2487    }
2488
2489    /// What the allocator is given: every integer register the convention offers except two, held
2490    /// back so that a move on an edge has somewhere to break a cycle and a spilled value has
2491    /// somewhere to be read into. Which two does not matter, and holding back the last two the
2492    /// convention would reach for leaves every expectation below unchanged.
2493    fn env() -> Env {
2494        const SCRATCH: [rucc_target::PhysReg; 2] = [x86_64::R10, x86_64::R11];
2495        let order: Vec<rucc_target::PhysReg> =
2496            SYSV.int_order.iter().copied().filter(|reg| !SCRATCH.contains(reg)).collect();
2497        Env::new().with(x86_64::GPR, &order, &SCRATCH)
2498    }
2499
2500    /// The machine IR text a function lowers to.
2501    fn lower(names: &mut Interner, source: &Func) -> String {
2502        let out = func(source, names, &SYSV, &Elsewhere::default())
2503            .expect("every instruction has a rule");
2504        mir::print_func(&out.func, names, &REGS)
2505    }
2506
2507    #[test]
2508    fn an_addition_of_two_registers_is_one_instruction() {
2509        let i32 = Type::int(32);
2510        let (mut names, mut func, block, args) = blank(&[i32, i32]);
2511        let mut build = Builder::new(&mut func, block);
2512        build.binary(Opcode::Add, args[0], args[1], Flags::default());
2513
2514        assert_eq!(
2515            lower(&mut names, &func),
2516            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_32\n    \
2517             %1:gpr($rsi) = x64.arg_val_32\n    %2:gpr(reuse 1) = x64.add_rr_32 %0, %1\n}\n"
2518        );
2519    }
2520
2521    #[test]
2522    fn a_constant_operand_becomes_an_immediate() {
2523        let i32 = Type::int(32);
2524        let (mut names, mut func, block, args) = blank(&[i32]);
2525        let mut build = Builder::new(&mut func, block);
2526        let seven = build.iconst(i32, 7);
2527        build.binary(Opcode::Add, args[0], seven, Flags::default());
2528
2529        // The constant is in the instruction and nothing was written to hold it, which is what
2530        // materializing one where a register for it is wanted buys.
2531        assert_eq!(
2532            lower(&mut names, &func),
2533            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_32\n    \
2534             %1:gpr(reuse 1) = x64.add_ri_32 %0, 7\n}\n"
2535        );
2536    }
2537
2538    #[test]
2539    fn a_constant_too_wide_for_an_immediate_goes_into_a_register() {
2540        let i64 = Type::int(64);
2541        let (mut names, mut func, block, args) = blank(&[i64]);
2542        let mut build = Builder::new(&mut func, block);
2543        let big = build.iconst(i64, i128::from(i32::MAX) + 1);
2544        build.binary(Opcode::Add, args[0], big, Flags::default());
2545
2546        // Nobody wrote this fallback down. The rule that takes an immediate has a guard that
2547        // turns a number this wide down, so it does not fire, and the next way of showing the
2548        // operand puts it in a register.
2549        assert_eq!(
2550            lower(&mut names, &func),
2551            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_64\n    \
2552             %1:gpr = x64.mov_ri_64 2147483648\n    %2:gpr(reuse 1) = x64.add_rr_64 %0, %1\n}\n"
2553        );
2554    }
2555
2556    #[test]
2557    fn an_index_calculation_folds_into_an_address() {
2558        let i64 = Type::int(64);
2559        let (mut names, mut func, block, args) = blank(&[i64, i64]);
2560        let mut build = Builder::new(&mut func, block);
2561        let four = build.iconst(i64, 4);
2562        let scaled = build.binary(Opcode::Mul, args[1], four, Flags::default());
2563        build.binary(Opcode::Add, args[0], scaled, Flags::default());
2564
2565        // Three IR instructions and one machine instruction. The multiply is gone because the
2566        // rule that matched reached down and took it.
2567        assert_eq!(
2568            lower(&mut names, &func),
2569            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_64\n    \
2570             %1:gpr($rsi) = x64.arg_val_64\n    %2:gpr = x64.lea_64 [%0 + %1*4]\n}\n"
2571        );
2572    }
2573
2574    #[test]
2575    fn an_instruction_read_twice_is_not_folded_into_either_reader() {
2576        let i64 = Type::int(64);
2577        let (mut names, mut func, block, args) = blank(&[i64, i64]);
2578        let mut build = Builder::new(&mut func, block);
2579        let four = build.iconst(i64, 4);
2580        let scaled = build.binary(Opcode::Mul, args[1], four, Flags::default());
2581        let first = build.binary(Opcode::Add, args[0], scaled, Flags::default());
2582        build.binary(Opcode::Add, first, scaled, Flags::default());
2583
2584        // Folding it into both would compute it twice, which is not a saving, so it stays where
2585        // it is and both readers read the register it wrote.
2586        let text = lower(&mut names, &func);
2587        assert!(text.contains("x64.lea_64 [%1*4]"), "{text}");
2588        assert_eq!(text.matches("x64.add_rr_64").count(), 2, "{text}");
2589    }
2590
2591    #[test]
2592    fn a_shift_by_a_register_asks_for_it_in_cl() {
2593        let i32 = Type::int(32);
2594        let (mut names, mut func, block, args) = blank(&[i32, i32]);
2595        let mut build = Builder::new(&mut func, block);
2596        build.binary(Opcode::Shl, args[0], args[1], Flags::default());
2597
2598        // The fixed register is not in the rule. It is what the target says the instruction does
2599        // with its operands, and the allocator is what will act on it.
2600        let text = lower(&mut names, &func);
2601        assert!(text.contains("x64.shl_rcl_32 %0, %1($rcx)"), "{text}");
2602    }
2603
2604    #[test]
2605    fn a_division_names_the_registers_and_the_register_it_destroys() {
2606        let i32 = Type::int(32);
2607        let (mut names, mut func, block, args) = blank(&[i32, i32]);
2608        let mut build = Builder::new(&mut func, block);
2609        build.binary(Opcode::SDiv, args[0], args[1], Flags::default());
2610
2611        // Two definitions, because a division writes the remainder whether anybody wanted it or
2612        // not, and the second one is early because it is destroyed before the operands are read.
2613        let text = lower(&mut names, &func);
2614        assert!(
2615            text.contains("%2:gpr($rax), early %3:gpr($rdx) = x64.idiv_quo_32 %0($rax), %1"),
2616            "{text}"
2617        );
2618    }
2619
2620    #[test]
2621    fn a_load_reads_through_the_register_the_address_is_in() {
2622        let i64 = Type::int(64);
2623        let (mut names, mut func, block, args) = blank(&[i64]);
2624        let mut build = Builder::new(&mut func, block);
2625        build.load(Type::int(32), args[0], plain(), Flags::default());
2626
2627        assert_eq!(
2628            lower(&mut names, &func),
2629            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_64\n    \
2630             %1:gpr = x64.mov_rm_32 [%0]\n}\n"
2631        );
2632    }
2633
2634    #[test]
2635    fn a_store_writes_no_register_and_the_value_it_writes_is_the_one_the_ir_gave_it() {
2636        let (mut names, mut func, block, args) = blank(&[Type::int(32), Type::int(64)]);
2637        let mut build = Builder::new(&mut func, block);
2638        build.store(args[0], args[1], plain(), Flags::default());
2639
2640        // The value is the first parameter and the address is the second, and the instruction
2641        // takes them the other way round. Getting that backwards would compile to a store of the
2642        // address into the value, which is a program that runs and does the wrong thing.
2643        assert_eq!(
2644            lower(&mut names, &func),
2645            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_32\n    \
2646             %1:gpr($rsi) = x64.arg_val_64\n    x64.mov_mr_32 %0, [%1]\n}\n"
2647        );
2648    }
2649
2650    #[test]
2651    fn an_address_with_a_constant_added_folds_into_the_access() {
2652        let i64 = Type::int(64);
2653        let (mut names, mut func, block, args) = blank(&[i64]);
2654        let mut build = Builder::new(&mut func, block);
2655        let twelve = build.iconst(i64, 12);
2656        let field = build.binary(Opcode::Add, args[0], twelve, Flags::default());
2657        build.load(Type::int(64), field, plain(), Flags::default());
2658
2659        // Two IR instructions and one machine instruction, which is what every read of a field
2660        // of a structure comes to.
2661        assert_eq!(
2662            lower(&mut names, &func),
2663            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_64\n    \
2664             %1:gpr = x64.mov_rm_64 [%0 + 12]\n}\n"
2665        );
2666    }
2667
2668    #[test]
2669    fn a_displacement_too_wide_to_encode_leaves_the_addition_where_it_is() {
2670        let i64 = Type::int(64);
2671        let (mut names, mut func, block, args) = blank(&[i64]);
2672        let mut build = Builder::new(&mut func, block);
2673        let big = build.iconst(i64, i128::from(i32::MAX) + 1);
2674        let far = build.binary(Opcode::Add, args[0], big, Flags::default());
2675        build.load(Type::int(32), far, plain(), Flags::default());
2676
2677        // A displacement is signed and 32 bits. The rule that folds one has a guard that turns
2678        // this down, so the addition stays and the load reads through what it produced. Nobody
2679        // wrote that fallback: it is the next way of showing the operand.
2680        let text = lower(&mut names, &func);
2681        assert!(text.contains("x64.mov_rm_32 [%2]"), "{text}");
2682        assert!(text.contains("x64.add_rr_64"), "{text}");
2683    }
2684
2685    #[test]
2686    fn a_store_of_a_value_that_was_loaded_is_two_instructions_and_no_arithmetic() {
2687        let i64 = Type::int(64);
2688        let (mut names, mut func, block, args) = blank(&[i64, i64]);
2689        let mut build = Builder::new(&mut func, block);
2690        let got = build.load(Type::int(8), args[0], plain(), Flags::default());
2691        build.store(got, args[1], plain(), Flags::default());
2692
2693        // A load feeding a store is the one place folding would be wrong: an x86-64 `mov` has at
2694        // most one memory operand, and there is no rule that takes two, so the load is left where
2695        // it is and the store reads the register it wrote.
2696        assert_eq!(
2697            lower(&mut names, &func),
2698            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_64\n    \
2699             %1:gpr($rsi) = x64.arg_val_64\n    %2:gpr = x64.mov_rm_8 [%0]\n    \
2700             x64.mov_mr_8 %2, [%1]\n}\n"
2701        );
2702    }
2703
2704    #[test]
2705    fn an_access_at_a_width_no_rule_is_written_at_is_reported() {
2706        let i64 = Type::int(64);
2707        let (mut names, mut source, block, args) = blank(&[i64]);
2708        let mut build = Builder::new(&mut source, block);
2709        build.load(Type::int(128), args[0], plain(), Flags::default());
2710
2711        // The width is the whole of what is wrong here, so the width is in the message: `load`
2712        // on its own is written about at every other width and would send a reader looking in
2713        // the wrong place.
2714        let failed = func(&source, &mut names, &SYSV, &Elsewhere::default())
2715            .expect_err("nothing loads 128 bits");
2716        assert_eq!(failed.to_string(), "no rule lowers a `load` producing a `i128`");
2717    }
2718
2719    #[test]
2720    fn a_return_asks_for_the_value_in_the_register_the_caller_reads() {
2721        let (mut names, mut func, block, args) = blank(&[Type::int(32)]);
2722        let mut build = Builder::new(&mut func, block);
2723        build.ret(&[args[0]]);
2724
2725        // The register is not in the rule, the same way `cl` is not in the rule for a shift. It
2726        // is what the target says the instruction does with its operand, and the allocator is
2727        // what will act on it. There is no `ret` here, because giving the frame back has to
2728        // happen between this and leaving and the frame is not worked out yet.
2729        assert_eq!(
2730            lower(&mut names, &func),
2731            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_32\n    \
2732             x64.ret_val_32 %0($rax)\n}\n"
2733        );
2734    }
2735
2736    #[test]
2737    fn a_return_of_two_values_asks_for_the_second_register_as_well() {
2738        let i64 = Type::int(64);
2739        let (mut names, mut func, block, args) = blank(&[i64, i64]);
2740        let mut build = Builder::new(&mut func, block);
2741        build.ret(&[args[0], args[1]]);
2742
2743        // `struct { long a, b; } f(long a, long b)`, after the front end has classified it. Both
2744        // halves are integers, so the second is in the second integer return register, and both
2745        // pseudos say so the same way the one for a single value does.
2746        assert_eq!(
2747            lower(&mut names, &func),
2748            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_64\n    \
2749             %1:gpr($rsi) = x64.arg_val_64\n    x64.ret_val_64 %0($rax)\n    \
2750             x64.ret_val2_64 %1($rdx)\n}\n"
2751        );
2752    }
2753
2754    #[test]
2755    fn two_values_back_in_different_files_are_both_the_first_of_their_own() {
2756        let f64 = Type::float(rucc_ir::Float::F64);
2757        let (mut names, mut func, block, args) = blank(&[f64, Type::int(64)]);
2758        let mut build = Builder::new(&mut func, block);
2759        build.ret(&[args[0], args[1]]);
2760
2761        // `struct { double a; long b; } f(double a, long b)`. The two files are counted apart, so
2762        // neither half is the second of anything and the `double` is in `xmm0` rather than in the
2763        // register a second `double` would have been in. Getting this wrong is not a crash: the
2764        // caller reads a register nobody wrote, and this is where that is ruled out.
2765        assert_eq!(
2766            lower(&mut names, &func),
2767            "mfunc @f {\nblock0:\n    %0:xmm($xmm0) = x64.arg_val_f64\n    \
2768             %1:gpr($rdi) = x64.arg_val_64\n    x64.ret_val_f64 %0($xmm0)\n    \
2769             x64.ret_val_64 %1($rax)\n}\n"
2770        );
2771    }
2772
2773    #[test]
2774    fn two_of_the_same_file_back_take_the_first_two_of_it() {
2775        let f64 = Type::float(rucc_ir::Float::F64);
2776        let (mut names, mut func, block, args) = blank(&[f64, f64]);
2777        let mut build = Builder::new(&mut func, block);
2778        build.ret(&[args[0], args[1]]);
2779
2780        // `struct { double x, y; } f(double x, double y)`, which is the vector half of the pair
2781        // above and counts in its own file the same way.
2782        assert_eq!(
2783            lower(&mut names, &func),
2784            "mfunc @f {\nblock0:\n    %0:xmm($xmm0) = x64.arg_val_f64\n    \
2785             %1:xmm($xmm1) = x64.arg_val_f64\n    x64.ret_val_f64 %0($xmm0)\n    \
2786             x64.ret_val2_f64 %1($xmm1)\n}\n"
2787        );
2788    }
2789
2790    /// A function whose answer goes back through memory, with the pointer to the space for it in
2791    /// front of whatever else it takes. Only the signature says it is one.
2792    fn returning_through_memory(params: &[Type]) -> (Interner, Func, Block, Vec<Value>) {
2793        let mut names = Interner::new();
2794        let sret = Abi::Sret { size: 32, align: 8 };
2795        let mut signature = Signature::new().and_param(Param::with_abi(Type::PTR, sret));
2796        signature.params.extend(params.iter().copied().map(Param::new));
2797        let mut func = Func::new(names.intern("f"), signature);
2798        let block = func.create_block();
2799        let space = func.append_param(block, Type::PTR);
2800        let values = std::iter::once(space)
2801            .chain(params.iter().map(|&ty| func.append_param(block, ty)))
2802            .collect();
2803        (names, func, block, values)
2804    }
2805
2806    #[test]
2807    fn the_space_a_return_through_memory_was_given_goes_back_in_the_first_return_register() {
2808        let (mut names, mut func, block, _) = returning_through_memory(&[]);
2809        Builder::new(&mut func, block).ret(&[]);
2810
2811        // `struct big f(void)`, where `big` is too large to come back in registers. The `return`
2812        // carries nothing, because the value went into the space the caller handed over, and the
2813        // document still says that address comes back in `rax`. Nothing in the IR says it, so the
2814        // convention says it, and the pseudo is the one any other pointer return would use.
2815        assert_eq!(
2816            lower(&mut names, &func),
2817            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_64\n    \
2818             x64.ret_val_64 %0($rax)\n}\n"
2819        );
2820    }
2821
2822    #[test]
2823    fn what_the_function_did_in_between_does_not_take_the_register_off_it() {
2824        let (mut names, mut func, block, args) = returning_through_memory(&[Type::int(32)]);
2825        let mut build = Builder::new(&mut func, block);
2826        build.store(args[1], args[0], plain(), Flags::default());
2827        build.ret(&[]);
2828
2829        // The register is a read at the end and not a move at the start, so it is live across
2830        // everything between the two and the allocator has to keep it somewhere. In a function
2831        // with a call in it that somewhere is a callee saved register, and the address comes back
2832        // into `rax` here rather than whatever the last instruction happened to leave there. That
2833        // is issue #333, and a store is enough to show the value outlives the entry block.
2834        let text = lower(&mut names, &func);
2835        assert!(text.contains("x64.mov_mr_32 %1, [%0]"), "{text}");
2836        assert!(text.ends_with("    x64.ret_val_64 %0($rax)\n}\n"), "{text}");
2837    }
2838
2839    #[test]
2840    fn a_pointer_that_is_only_a_pointer_is_not_given_back() {
2841        let (mut names, mut func, block, args) = blank(&[Type::PTR]);
2842        let mut build = Builder::new(&mut func, block);
2843        build.store(args[0], args[0], plain(), Flags::default());
2844        build.ret(&[]);
2845
2846        // `void f(void **p)`. It takes a pointer first and returns nothing, which is the shape of
2847        // the one above and none of its meaning, and what tells them apart is the signature. A
2848        // `void` function leaves `rax` alone.
2849        assert!(!lower(&mut names, &func).contains("ret_val"));
2850    }
2851
2852    #[test]
2853    fn a_return_of_a_constant_puts_it_in_a_register_first() {
2854        let (mut names, mut func, block, _) = blank(&[]);
2855        let mut build = Builder::new(&mut func, block);
2856        let zero = build.iconst(Type::int(32), 0);
2857        build.ret(&[zero]);
2858
2859        // No rule returns an immediate, so the plan that offers one is turned down and the next
2860        // one materializes it. That is `int main(void) { return 0; }` in full, once the epilogue
2861        // is appended to it.
2862        assert_eq!(
2863            lower(&mut names, &func),
2864            "mfunc @f {\nblock0:\n    %0:gpr = x64.mov_ri_32 0\n    x64.ret_val_32 %0($rax)\n}\n"
2865        );
2866    }
2867
2868    #[test]
2869    fn the_rule_that_writes_a_constant_down_is_recorded_as_a_rule_that_fired() {
2870        let (mut names, mut func, block, _) = blank(&[]);
2871        let mut build = Builder::new(&mut func, block);
2872        let zero = build.iconst(Type::int(32), 0);
2873        build.ret(&[zero]);
2874
2875        // The loop over the instructions passes a constant by, because a constant is written where
2876        // a register for it is first wanted rather than where the IR put it. So the only place a
2877        // rule about one is ever selected is the materialization, and a mark made in the loop
2878        // alone would report every rule about a constant as a rule nothing reaches.
2879        let out = super::func(&func, &mut names, &SYSV, &Elsewhere::default())
2880            .expect("every instruction has a rule");
2881        let rules = &crate::select::x86_64::TABLE.rules;
2882        let fired: Vec<&str> = rules
2883            .iter()
2884            .enumerate()
2885            .filter(|(index, _)| out.fired.has(*index))
2886            .map(|(_, rule)| rule.pattern)
2887            .collect();
2888        assert!(fired.contains(&"(iconst.i32 k)"), "{fired:?}");
2889    }
2890
2891    #[test]
2892    fn a_return_of_nothing_is_no_instruction_at_all() {
2893        let (mut names, mut func, block, _) = blank(&[]);
2894        let mut build = Builder::new(&mut func, block);
2895        build.ret(&[]);
2896
2897        // Every part of leaving a function that returns nothing is the epilogue's, and the
2898        // epilogue goes in after allocation. A block with nothing in it is the right answer here
2899        // rather than a function that could not be lowered.
2900        assert_eq!(lower(&mut names, &func), "mfunc @f {\nblock0:\n}\n");
2901    }
2902
2903    #[test]
2904    fn the_allocator_is_what_moves_the_answer_into_the_return_register() {
2905        let (mut names, mut source, block, _) = blank(&[]);
2906        let mut build = Builder::new(&mut source, block);
2907        let zero = build.iconst(Type::int(32), 0);
2908        build.ret(&[zero]);
2909
2910        let mut out = func(&source, &mut names, &SYSV, &Elsewhere::default())
2911            .expect("every instruction has a rule")
2912            .func;
2913        let env = env();
2914        let allocation = rucc_regalloc::run(&mut out, &env, "test");
2915        let frame = Frame::of(&out, &allocation, &Layout::new(&SYSV, REGS));
2916        finish(
2917            &mut out,
2918            &allocation,
2919            &frame,
2920            &Stack::default(),
2921            Convention::new(&SYSV, &FRAME),
2922            &mut names,
2923        );
2924
2925        // `int main(void) { return 0; }` end to end. Nothing here asked for `rax`: the rule said
2926        // the value goes back, the target said where, and the allocator is what made it true. The
2927        // epilogue is what leaves, and this function needs no frame, so it is the return alone.
2928        //
2929        // Two instructions and no copy, which is what a hint buys. The return insists on `rax`,
2930        // so `rax` is the register the allocator tries first for the value the return reads, and
2931        // the constant is written straight into it.
2932        assert_eq!(
2933            mir::print_func(&out, &names, &REGS),
2934            "mfunc @f {\nblock0:\n    $rax = x64.mov_ri_32 0\n    \
2935             x64.ret_val_32 $rax($rax)\n    x64.ret\n}\n"
2936        );
2937    }
2938
2939    #[test]
2940    fn a_function_of_two_arguments_is_a_whole_function_now() {
2941        let i32 = Type::int(32);
2942        let (mut names, mut source, block, args) = blank(&[i32, i32]);
2943        let mut build = Builder::new(&mut source, block);
2944        let sum = build.binary(Opcode::Add, args[0], args[1], Flags::default());
2945        build.ret(&[sum]);
2946
2947        let mut out = func(&source, &mut names, &SYSV, &Elsewhere::default())
2948            .expect("every instruction has a rule")
2949            .func;
2950        let env = env();
2951        let allocation = rucc_regalloc::run(&mut out, &env, "test");
2952        let frame = Frame::of(&out, &allocation, &Layout::new(&SYSV, REGS));
2953        finish(
2954            &mut out,
2955            &allocation,
2956            &frame,
2957            &Stack::default(),
2958            Convention::new(&SYSV, &FRAME),
2959            &mut names,
2960        );
2961
2962        // `int f(int a, int b) { return a + b; }` end to end, and this is the test the argument
2963        // side exists for. Before it there was no way to write one: the allocator refuses a
2964        // function whose entry block takes parameters, because there is no edge into an entry
2965        // block for the moves that give a block parameter its value to go on.
2966        //
2967        // One move, and it is the one the machine's addition needs rather than one the allocator
2968        // owes anybody. Each argument stays in the register it arrived in, because the pseudo
2969        // that defines it insists on that register and the allocator now tries it first, and the
2970        // sum stays in the register the addition wrote it to until the return reads it out. The
2971        // copy in front of a two address instruction is what makes its destination one of the
2972        // registers it reads, and the source operand keeps its own name because the destination
2973        // is what the encoder writes.
2974        assert_eq!(
2975            mir::print_func(&out, &names, &REGS),
2976            "mfunc @f {\nblock0:\n    $rdi($rdi) = x64.arg_val_32\n    \
2977             $rsi($rsi) = x64.arg_val_32\n    \
2978             $rdi(reuse 1) = x64.add_rr_32 $rdi, $rsi\n    $rax = x64.mov_rr_64 $rdi\n    \
2979             x64.ret_val_32 $rax($rax)\n    x64.ret\n}\n"
2980        );
2981    }
2982
2983    #[test]
2984    fn an_argument_with_no_register_left_for_it_is_read_out_of_the_caller_s_stack() {
2985        let i64 = Type::int(64);
2986        let (mut names, mut source, block, args) = blank(&[i64; 7]);
2987        let mut build = Builder::new(&mut source, block);
2988        build.ret(&[args[6]]);
2989
2990        let lowered = func(&source, &mut names, &SYSV, &Elsewhere::default())
2991            .expect("the seventh is read from memory");
2992
2993        // SysV passes six integers in registers and the seventh in the caller's memory, so six of
2994        // these are pseudos that encode to nothing and the seventh is a load that encodes to real
2995        // bytes. Its displacement is nothing here for the reason a local's is: there is no frame
2996        // yet. What the walk hands on is which instruction is waiting, and for how far up the
2997        // caller's argument area, which is the bottom of it because it is the first one there.
2998        assert_eq!(lowered.stack.arguments.len(), 1);
2999        assert_eq!(lowered.stack.arguments[0].1, 0);
3000        let text = mir::print_func(&lowered.func, &names, &REGS);
3001        assert!(text.contains("%6:gpr = x64.mov_rm_64 [$rsp]"), "{text}");
3002        assert_eq!(text.matches("x64.arg_val_64").count(), 6, "{text}");
3003    }
3004
3005    #[test]
3006    fn the_frame_is_what_says_how_far_up_the_caller_s_stack_an_argument_is() {
3007        let i64 = Type::int(64);
3008        let (mut names, mut source, block, args) = blank(&[i64; 8]);
3009        let mut build = Builder::new(&mut source, block);
3010        let sum = build.binary(Opcode::Add, args[6], args[7], Flags::default());
3011        build.ret(&[sum]);
3012
3013        let lowered = func(&source, &mut names, &SYSV, &Elsewhere::default())
3014            .expect("both are read from memory");
3015        let stack = lowered.stack;
3016        let mut out = lowered.func;
3017        let env = env();
3018        let allocation = rucc_regalloc::run(&mut out, &env, "test");
3019        let layout = stack.layout(Layout::new(&SYSV, REGS));
3020        let frame = Frame::of(&out, &allocation, &layout);
3021        finish(&mut out, &allocation, &frame, &stack, Convention::new(&SYSV, &FRAME), &mut names);
3022
3023        // A leaf that takes no frame, so the stack pointer never moves and the only thing between
3024        // it and the caller's arguments is the return address the call pushed. The seventh
3025        // parameter is at the bottom of the caller's argument area and the eighth is one word
3026        // further up, which is the eight bytes between the two offsets.
3027        let text = mir::print_func(&out, &names, &REGS);
3028        assert_eq!(frame.size(), 0);
3029        assert_eq!(frame.incoming(), Incoming::from_stack(8));
3030        assert!(text.contains("x64.mov_rm_64 [$rsp + 8]"), "{text}");
3031        assert!(text.contains("x64.mov_rm_64 [$rsp + 16]"), "{text}");
3032    }
3033
3034    #[test]
3035    fn a_realigned_frame_reaches_the_caller_s_arguments_through_the_frame_pointer() {
3036        let i64 = Type::int(64);
3037        let (mut names, mut source, block, args) = blank(&[i64; 7]);
3038        let wide = slot(&mut source, block, 64, 32);
3039        let mut build = Builder::new(&mut source, block);
3040        build.store(args[6], wide, plain(), Flags::default());
3041        build.ret(&[args[6]]);
3042
3043        let lowered = func(&source, &mut names, &SYSV, &Elsewhere::default())
3044            .expect("every instruction has a rule");
3045        let stack = lowered.stack;
3046        let mut out = lowered.func;
3047        let env = env();
3048        let allocation = rucc_regalloc::run(&mut out, &env, "test");
3049        let layout = stack.layout(Layout::new(&SYSV, REGS));
3050        let frame = Frame::of(&out, &allocation, &layout);
3051        finish(&mut out, &allocation, &frame, &stack, Convention::new(&SYSV, &FRAME), &mut names);
3052
3053        // A local wanting thirty two byte alignment makes the prologue force the stack pointer,
3054        // which throws away how far the caller's stack was. So the load the lowering wrote off the
3055        // stack pointer is rewritten to read through the frame pointer, at the one distance that
3056        // survives: the word the prologue pushed the frame pointer into, and the return address
3057        // above it.
3058        let text = mir::print_func(&out, &names, &REGS);
3059        assert_eq!(frame.realign(), Some(32));
3060        assert_eq!(frame.incoming(), Incoming::from_frame(16));
3061        assert!(text.contains("x64.mov_rm_64 [$rbp + 16]"), "{text}");
3062        assert!(!text.contains("x64.mov_rm_64 [$rsp"), "{text}");
3063    }
3064
3065    #[test]
3066    fn a_jump_is_the_edge_and_nothing_else() {
3067        let i32 = Type::int(32);
3068        let (mut names, mut source, entry, args) = blank(&[i32]);
3069        let next = source.create_block();
3070        let got = source.append_param(next, i32);
3071        Builder::new(&mut source, entry).jump(next, &[args[0]]);
3072        Builder::new(&mut source, next).ret(&[got]);
3073
3074        // Two blocks and two instructions, and the jump is neither of them. What it was is the
3075        // arm on the first block, and what the arm carries is the argument it was called with.
3076        assert_eq!(
3077            lower(&mut names, &source),
3078            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_32 block1(%0)\n\n\
3079             block1(%1:gpr):\n    x64.ret_val_32 %1($rax)\n}\n"
3080        );
3081    }
3082
3083    /// A block that reads what a block below it writes is filled after it, not before it.
3084    ///
3085    /// The blocks are written entry, `early`, `late`, `exit`, and the entry jumps straight past
3086    /// `early` to `late`, so `late` dominates `early` while sitting below it in the function.
3087    /// Filling them in the order they are written reaches the read in `early` first, and reading
3088    /// a value with no register yet mints one. The cast in `late` is no instruction at all, so
3089    /// what it does is give its answer the register its operand is already in, and that is not
3090    /// the register the read minted. Nothing writes the register the read minted. The printer
3091    /// says `%?` for a register nothing defines, which is what this looks for, and what came out
3092    /// of the real bug was SQLite loading a stack slot no store ever reached.
3093    #[test]
3094    fn a_block_that_reads_what_a_block_below_it_writes_is_filled_after_it() {
3095        let i64 = Type::int(64);
3096        let (mut names, mut source, entry, args) = blank(&[i64, i64]);
3097        let early = source.create_block();
3098        let late = source.create_block();
3099        let exit = source.create_block();
3100
3101        Builder::new(&mut source, entry).jump(late, &[]);
3102        let ptr = cast(&mut source, late, Opcode::IntToPtr, args[0], Type::PTR);
3103        Builder::new(&mut source, early).ret(&[ptr]);
3104        let mut build = Builder::new(&mut source, late);
3105        let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
3106        build.br_if(cond, early, &[], exit, &[]);
3107        Builder::new(&mut source, exit).ret(&[args[1]]);
3108
3109        let text = lower(&mut names, &source);
3110        assert!(!text.contains("%?"), "every register has something that writes it: {text}");
3111    }
3112
3113    /// A constant is written where it is wanted rather than where the IR defined it, and two
3114    /// blocks wanting the same one is two places. Writing it once and reading it in both is a
3115    /// register read where nothing wrote it, unless the block it was written in happens to
3116    /// dominate the other, which nothing here checks and which the second arm of a branch never
3117    /// does. Each block gets its own copy of the number instead.
3118    #[test]
3119    fn a_constant_two_blocks_want_is_written_in_both_of_them() {
3120        let i32 = Type::int(32);
3121        let (mut names, mut source, entry, args) = blank(&[i32, i32]);
3122        let then = source.create_block();
3123        let other = source.create_block();
3124        let join = source.create_block();
3125        let got = source.append_param(join, i32);
3126
3127        let mut build = Builder::new(&mut source, entry);
3128        let seven = build.iconst(i32, 7);
3129        let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
3130        build.br_if(cond, then, &[], other, &[]);
3131        // Both arms want the seven in a register, because a block argument is never an immediate,
3132        // and neither arm dominates the other.
3133        Builder::new(&mut source, then).jump(join, &[seven]);
3134        Builder::new(&mut source, other).jump(join, &[seven]);
3135        Builder::new(&mut source, join).ret(&[got]);
3136
3137        let text = lower(&mut names, &source);
3138        assert_eq!(text.matches("x64.mov_ri_32 7").count(), 2, "one seven per block: {text}");
3139    }
3140
3141    /// An argument on an edge out of a block that leaves two ways is read after every instruction
3142    /// of the block is written, and reading one can write an instruction, which would land after
3143    /// the branch that has already jumped past it. The branch goes back on the end.
3144    #[test]
3145    fn a_constant_an_edge_wants_is_written_before_the_branch_and_not_after_it() {
3146        let i32 = Type::int(32);
3147        let (mut names, mut source, entry, args) = blank(&[i32, i32]);
3148        let then = source.create_block();
3149        let join = source.create_block();
3150        let got = source.append_param(join, i32);
3151
3152        let mut build = Builder::new(&mut source, entry);
3153        let nine = build.iconst(i32, 9);
3154        let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
3155        build.br_if(cond, then, &[], join, &[nine]);
3156        Builder::new(&mut source, then).jump(join, &[args[0]]);
3157        Builder::new(&mut source, join).ret(&[got]);
3158
3159        let out = func(&source, &mut names, &SYSV, &Elsewhere::default())
3160            .expect("every instruction has a rule")
3161            .func;
3162        let entry = out.entry().expect("an entry block");
3163        let last = out.terminator(entry).expect("a block that leaves two ways has a branch");
3164        let branch = names.intern("x64.br_cond_8");
3165        assert_eq!(
3166            out[last].opcode,
3167            mir::Opcode::new(branch),
3168            "the branch is last: {}",
3169            mir::print_func(&out, &names, &REGS)
3170        );
3171    }
3172
3173    #[test]
3174    fn a_conditional_branch_is_lowered_to_the_condition_and_nothing_about_where_it_goes() {
3175        let i32 = Type::int(32);
3176        let (mut names, mut source, entry, args) = blank(&[i32, i32]);
3177        let then = source.create_block();
3178        let other = source.create_block();
3179        let mut build = Builder::new(&mut source, entry);
3180        let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
3181        build.br_if(cond, then, &[], other, &[]);
3182        Builder::new(&mut source, then).ret(&[args[0]]);
3183        Builder::new(&mut source, other).ret(&[args[1]]);
3184
3185        // The comparison writes a byte and the branch reads it, and neither says a block. Both
3186        // arms are on the entry block, in the order the branch took them, so the arm that runs
3187        // when the condition holds is the first.
3188        assert_eq!(
3189            lower(&mut names, &source),
3190            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_32\n    \
3191             %1:gpr($rsi) = x64.arg_val_32\n    %2:gpr = x64.cmp_set_l_32 %0, %1\n    \
3192             x64.br_cond_8 %2, block1, block2\n\n\
3193             block1:\n    x64.ret_val_32 %0($rax)\n\n\
3194             block2:\n    x64.ret_val_32 %1($rax)\n}\n"
3195        );
3196    }
3197
3198    /// A choice between two values, which is one instruction and no blocks at all.
3199    ///
3200    /// The arms come out the other way round from the IR, because a conditional move overwrites its
3201    /// destination and the destination is the arm taken when the condition does not hold. The
3202    /// condition arrives last for the same reason: it is read by the test in front of the move
3203    /// rather than by the move.
3204    #[test]
3205    fn a_select_is_lowered_to_a_test_and_a_conditional_move() {
3206        let i32 = Type::int(32);
3207        let (mut names, mut source, entry, args) = blank(&[i32, i32]);
3208        let mut build = Builder::new(&mut source, entry);
3209        let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
3210        let picked = build.select(cond, args[0], args[1]);
3211        build.ret(&[picked]);
3212
3213        assert_eq!(
3214            lower(&mut names, &source),
3215            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_32\n    \
3216             %1:gpr($rsi) = x64.arg_val_32\n    %2:gpr = x64.cmp_set_l_32 %0, %1\n    \
3217             %3:gpr(reuse 1) = x64.test_cmov_ne_32 %1, %0, %2\n    \
3218             x64.ret_val_32 %3($rax)\n}\n"
3219        );
3220    }
3221
3222    #[test]
3223    fn a_branch_over_a_block_is_a_whole_function_now() {
3224        let i32 = Type::int(32);
3225        let (mut names, mut source, entry, args) = blank(&[i32, i32]);
3226        let then = source.create_block();
3227        let other = source.create_block();
3228        let join = source.create_block();
3229        let got = source.append_param(join, i32);
3230        let mut build = Builder::new(&mut source, entry);
3231        let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
3232        build.br_if(cond, then, &[], other, &[]);
3233        let mut build = Builder::new(&mut source, then);
3234        let sum = build.binary(Opcode::Add, args[0], args[1], Flags::default());
3235        build.jump(join, &[sum]);
3236        Builder::new(&mut source, other).jump(join, &[args[1]]);
3237        Builder::new(&mut source, join).ret(&[got]);
3238
3239        // `int f(int a, int b) { if (a < b) return a + b; else return b; }` end to end, written
3240        // the way a front end writes it: both arms of the branch are blocks of their own and the
3241        // return is the block they meet at. No edge here is critical, because the two arms out of
3242        // the entry carry nothing and the two arms into the join each leave a block that goes
3243        // nowhere else, so each has its own end to put its move at.
3244        let mut out = func(&source, &mut names, &SYSV, &Elsewhere::default())
3245            .expect("every instruction has a rule")
3246            .func;
3247        assert_eq!(crate::split::critical(&mut out), 0, "no edge here is critical");
3248        let env = env();
3249        let allocation = rucc_regalloc::run(&mut out, &env, "test");
3250        let frame = Frame::of(&out, &allocation, &Layout::new(&SYSV, REGS));
3251        finish(
3252            &mut out,
3253            &allocation,
3254            &frame,
3255            &Stack::default(),
3256            Convention::new(&SYSV, &FRAME),
3257            &mut names,
3258        );
3259
3260        // One epilogue, on the join, which is the one block the function leaves from, and the
3261        // moves that give the join its parameter are at the end of each arm. Every register is
3262        // physical and the branch is still a branch on a register, because turning it into a
3263        // `test` and a `jcc` is the block layout's and there is no block layout yet.
3264        let text = mir::print_func(&out, &names, &REGS);
3265        assert_eq!(text.matches("x64.ret\n").count(), 1, "{text}");
3266        assert!(text.contains("x64.br_cond_8"), "{text}");
3267        assert!(text.contains("x64.add_rr_32"), "{text}");
3268        assert!(!text.contains('%'), "{text}");
3269    }
3270
3271    #[test]
3272    fn a_critical_edge_is_split_before_the_allocator_ever_sees_it() {
3273        let i32 = Type::int(32);
3274        let (mut names, mut source, entry, args) = blank(&[i32, i32]);
3275        let then = source.create_block();
3276        let join = source.create_block();
3277        let got = source.append_param(join, i32);
3278        let mut build = Builder::new(&mut source, entry);
3279        let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
3280        build.br_if(cond, then, &[], join, &[args[1]]);
3281        Builder::new(&mut source, then).jump(join, &[args[0]]);
3282        let mut build = Builder::new(&mut source, join);
3283        let twice = build.binary(Opcode::Add, got, got, Flags::default());
3284        build.ret(&[twice]);
3285
3286        // The else arm is critical: the entry block leaves two ways and the join is arrived at
3287        // two ways, and the arm carries a value. Without splitting it the allocator asserts,
3288        // because the move that gives the join its parameter would have to run at the end of a
3289        // block that also goes to the other arm.
3290        let mut out = func(&source, &mut names, &SYSV, &Elsewhere::default())
3291            .expect("every instruction has a rule")
3292            .func;
3293        assert_eq!(crate::split::critical(&mut out), 1);
3294        let env = env();
3295        let allocation = rucc_regalloc::run(&mut out, &env, "test");
3296        let frame = Frame::of(&out, &allocation, &Layout::new(&SYSV, REGS));
3297        finish(
3298            &mut out,
3299            &allocation,
3300            &frame,
3301            &Stack::default(),
3302            Convention::new(&SYSV, &FRAME),
3303            &mut names,
3304        );
3305
3306        // The block the split added is where the move went, and it is the whole of that block.
3307        let text = mir::print_func(&out, &names, &REGS);
3308        assert_eq!(out.block_count(), 4, "{text}");
3309        assert_eq!(text.matches("x64.ret\n").count(), 1, "{text}");
3310    }
3311
3312    #[test]
3313    fn a_call_passes_what_the_convention_says_and_takes_back_what_it_says() {
3314        let i32 = Type::int(32);
3315        let (mut names, mut source, block, args) = blank(&[i32, i32]);
3316        let sig =
3317            source.add_signature(Signature::new().with_params(&[i32, i32]).with_returns(&[i32]));
3318        let callee = names.intern("g");
3319        let call = Builder::new(&mut source, block).call(callee, sig, &[args[0], args[1]]);
3320        let got = source[call].first_result.expect("an integer comes back");
3321        Builder::new(&mut source, block).ret(&[got]);
3322
3323        // `int f(int a, int b) { return g(a, b); }`. The arguments arrived where the call wants
3324        // them, so what the call reads is what arrived, and the whole of the convention is in the
3325        // constraints rather than in a move.
3326        let text = lower(&mut names, &source);
3327        assert!(text.contains("= x64.call %0($rdi), %1($rsi), @g"), "{text}");
3328        assert!(text.contains("x64.ret_val_32 %2($rax)"), "{text}");
3329        // What the call writes is the value that comes back and then every register the callee is
3330        // free to destroy, in both classes, which is the whole of what stops the allocator from
3331        // leaving something in one of them.
3332        assert!(text.contains("%2:gpr($rax), $rcx, $rdx, $r8, $r9, $r10, $r11, $xmm0,"), "{text}");
3333        assert!(text.contains("$xmm15 = x64.call"), "{text}");
3334    }
3335
3336    #[test]
3337    fn what_the_frame_owes_a_call_comes_back_with_the_function() {
3338        let i32 = Type::int(32);
3339        let sig = |source: &mut Func| source.add_signature(Signature::new().with_params(&[i32]));
3340
3341        let (mut names, mut source, block, args) = blank(&[i32]);
3342        let sig = sig(&mut source);
3343        let callee = names.intern("g");
3344        Builder::new(&mut source, block).call(callee, sig, &[args[0]]);
3345        let out = func(&source, &mut names, &SYSV, &Elsewhere::default())
3346            .expect("every instruction has a rule");
3347
3348        // Nothing on the stack, so nothing owed, but not a leaf either: a function that calls
3349        // owes the callee an aligned stack pointer and may not use the red zone.
3350        assert_eq!(out.stack.calls, Some(0));
3351        let layout = out.stack.layout(Layout::new(&SYSV, REGS));
3352        assert!(!layout.leaf);
3353        assert_eq!(layout.outgoing, 0);
3354
3355        // The same call under the other convention owes thirty two bytes for the callee to spill
3356        // its register arguments into, which is a fact about the convention and not about the call.
3357        let out = func(&source, &mut names, &x86_64::WIN64, &Elsewhere::default())
3358            .expect("every instruction has a rule");
3359        assert_eq!(out.stack.calls, Some(32));
3360
3361        // And a function that calls nothing is a leaf, which is what says it may use the red zone.
3362        let (mut names, mut source, block, args) = blank(&[i32]);
3363        Builder::new(&mut source, block).ret(&[args[0]]);
3364        let out = func(&source, &mut names, &SYSV, &Elsewhere::default())
3365            .expect("every instruction has a rule");
3366        assert_eq!(out.stack.calls, None);
3367        assert!(out.stack.layout(Layout::new(&SYSV, REGS)).leaf);
3368    }
3369
3370    #[test]
3371    fn a_value_that_outlives_a_call_is_not_left_where_the_call_destroys_it() {
3372        let i32 = Type::int(32);
3373        let (mut names, mut source, block, args) = blank(&[i32]);
3374        let sig = source.add_signature(Signature::new().with_params(&[i32]).with_returns(&[i32]));
3375        let callee = names.intern("g");
3376        let call = Builder::new(&mut source, block).call(callee, sig, &[args[0]]);
3377        let got = source[call].first_result.expect("an integer comes back");
3378        let mut build = Builder::new(&mut source, block);
3379        let sum = build.binary(Opcode::Add, got, args[0], Flags::default());
3380        build.ret(&[sum]);
3381
3382        // `int f(int a) { return g(a) + a; }`, which is the smallest program that asks the
3383        // question: `a` is read after the call and `rdi` is a register the call destroys.
3384        let lowered = func(&source, &mut names, &SYSV, &Elsewhere::default())
3385            .expect("every instruction has a rule");
3386        let layout = lowered.stack.layout(Layout::new(&SYSV, REGS));
3387        let mut out = lowered.func;
3388        let env = env();
3389        let allocation = rucc_regalloc::run(&mut out, &env, "test");
3390        let frame = Frame::of(&out, &allocation, &layout);
3391        finish(
3392            &mut out,
3393            &allocation,
3394            &frame,
3395            &Stack::default(),
3396            Convention::new(&SYSV, &FRAME),
3397            &mut names,
3398        );
3399
3400        // It went to a register the callee has to put back, and the prologue and epilogue are what
3401        // put it back, which is the whole bargain the two halves of a convention make.
3402        let text = mir::print_func(&out, &names, &REGS);
3403        assert!(text.contains("$rbx"), "{text}");
3404        assert!(!text.contains('%'), "{text}");
3405        assert_eq!(text.matches("x64.call").count(), 1, "{text}");
3406    }
3407
3408    #[test]
3409    fn a_call_with_more_arguments_than_registers_writes_the_rest_into_the_outgoing_area() {
3410        let i64 = Type::int(64);
3411        let (mut names, mut source, block, args) = blank(&[i64]);
3412        let seven = vec![i64; 7];
3413        let sig = source.add_signature(Signature::new().with_params(&seven));
3414        let callee = names.intern("g");
3415        let passed = vec![args[0]; 7];
3416        Builder::new(&mut source, block).call(callee, sig, &passed);
3417
3418        let lowered = func(&source, &mut names, &SYSV, &Elsewhere::default())
3419            .expect("the seventh goes to memory");
3420        // The bytes the call needs are on the layout the frame is worked out from, so that the
3421        // frame reserves as many as the widest call in the function asked for.
3422        assert_eq!(lowered.stack.calls, Some(8));
3423        let text = mir::print_func(&lowered.func, &names, &REGS);
3424        assert!(text.contains("x64.mov_mr_64 %0, [$rsp]\n"), "{text}");
3425    }
3426
3427    #[test]
3428    fn a_call_this_cannot_make_is_reported_rather_than_made() {
3429        let (mut names, mut source, block, _) = blank(&[]);
3430        let returns = [Type::float(rucc_ir::Float::F80), Type::int(64)];
3431        let sig = source.add_signature(Signature::new().with_returns(&returns));
3432        let callee = names.intern("g");
3433        Builder::new(&mut source, block).call(callee, sig, &[]);
3434        let failed = func(&source, &mut names, &SYSV, &Elsewhere::default())
3435            .expect_err("a long double is on the x87");
3436        assert_eq!(failed.to_string(), "what this call gives back is on the x87 stack");
3437    }
3438
3439    /// A `long double` on its own is a different answer, because on its own it comes back on the
3440    /// x87 stack rather than in a register, which is somewhere the call cannot be said to write.
3441    ///
3442    /// So the call gives back nothing at all and the value is taken off the stack by the `fstp`
3443    /// straight after it. That instruction has to be straight after it: the stack is one place and
3444    /// anything else that touched it before this ran would be looking at the value still on it.
3445    #[test]
3446    fn a_call_that_gives_back_a_long_double_takes_it_off_the_stack_at_once() {
3447        let (mut names, mut source, block, _) = blank(&[]);
3448        let long_double = Type::float(rucc_ir::Float::F80);
3449        let sig = source.add_signature(Signature::new().with_returns(&[long_double]));
3450        let callee = names.intern("g");
3451        Builder::new(&mut source, block).call(callee, sig, &[]);
3452
3453        let lowered = func(&source, &mut names, &SYSV, &Elsewhere::default())
3454            .expect("the value comes back in st0");
3455        let text = mir::print_func(&lowered.func, &names, &REGS);
3456        let after: Vec<&str> =
3457            text.lines().skip_while(|line| !line.contains("x64.call")).skip(1).collect();
3458        assert_eq!(after[0].trim(), "%0:gpr = x64.lea_64 [$rsp]", "{text}");
3459        assert_eq!(after[1].trim(), "x64.fstp_t [%0]", "{text}");
3460        // And the slot it went into is the sixteen bytes the type takes, like every other one.
3461        assert_eq!(lowered.stack.locals.len(), 1, "{text}");
3462        assert_eq!(lowered.stack.locals[0].size, X87_BYTES);
3463    }
3464
3465    #[test]
3466    fn a_call_through_an_address_goes_through_the_register_the_address_is_in() {
3467        let i32 = Type::int(32);
3468        let (mut names, mut source, block, args) = blank(&[Type::PTR, i32]);
3469        let sig = source.add_signature(Signature::new().with_params(&[i32]).with_returns(&[i32]));
3470        let varargs = source.push_abis(&[]);
3471        let info = source.add_call(CallInfo { callee: None, signature: sig, varargs });
3472        let mut build = Builder::new(&mut source, block);
3473        let inst = InstData {
3474            args: build.func().push_values(&[args[0], args[1]]),
3475            extra: Extra::Call(info),
3476            ..InstData::new(Opcode::CallIndirect)
3477        };
3478        let called = build.inst(inst, &[i32]);
3479        let got = source[called].first_result.expect("an integer comes back");
3480        Builder::new(&mut source, block).ret(&[got]);
3481
3482        // `int f(int (*g)(int), int a) { return g(a); }`. The first operand is the address and
3483        // the arguments are the ones behind it, and everything else about the call is what a call
3484        // to a name would have been.
3485        let text = lower(&mut names, &source);
3486        assert!(text.contains("= x64.call_reg %0, %1($rdi)"), "{text}");
3487        assert!(text.contains("x64.ret_val_32 %2($rax)"), "{text}");
3488        assert!(!text.contains("@g"), "a call through an address names nobody: {text}");
3489    }
3490
3491    #[test]
3492    fn an_instruction_no_rule_covers_is_reported() {
3493        let (mut names, mut source, block, args) = blank(&[Type::PTR]);
3494        let mut build = Builder::new(&mut source, block);
3495        let operands = build.func().push_values(&[args[0]]);
3496        build.inst(InstData { args: operands, ..InstData::new(Opcode::Prefetch) }, &[]);
3497
3498        // A hint about an address, which nothing writes an instruction for yet. Nothing about it
3499        // is a width or a register, so there is nothing for the message to add beyond the name.
3500        let failed = func(&source, &mut names, &SYSV, &Elsewhere::default())
3501            .expect_err("no rule writes a prefetch");
3502        assert_eq!(failed.to_string(), "no rule lowers a `prefetch`");
3503
3504        // A `prefetch` produces nothing, so there is no type in the message and nothing invents
3505        // one, and the instruction comes back so a caller can ask the function where it was.
3506        let inst = failed.inst().expect("the instruction it is about");
3507        assert_eq!(source[inst].opcode, Opcode::Prefetch);
3508    }
3509
3510    /// A barrier is written by name here, and what it is depends on the ordering and on nothing
3511    /// else. `crate::expand` is where the reasoning about this machine's memory model lives.
3512    #[test]
3513    fn a_barrier_is_one_instruction_at_the_strongest_ordering_and_none_below_it() {
3514        for order in MemOrder::all().filter(|&order| order != MemOrder::NotAtomic) {
3515            let (mut names, mut source, block, _) = blank(&[]);
3516            let mut build = Builder::new(&mut source, block);
3517            build
3518                .inst(InstData { extra: Extra::Order(order), ..InstData::new(Opcode::Fence) }, &[]);
3519
3520            let text = lower(&mut names, &source);
3521            assert_eq!(text.contains("x64.mfence"), order == MemOrder::SeqCst, "{order:?}: {text}");
3522        }
3523    }
3524
3525    /// A compare and exchange is written by name too, and at the width of the value rather than at
3526    /// the width of the address, which is the mistake worth pinning: everything here is a pointer
3527    /// and only the value says how many bytes the instruction touches.
3528    #[test]
3529    fn a_compare_and_exchange_is_one_instruction_at_the_width_of_the_value() {
3530        for bits in [8, 16, 32, 64] {
3531            let ty = Type::int(bits);
3532            let (mut names, mut source, block, args) = blank(&[Type::PTR, ty, ty]);
3533            let mut build = Builder::new(&mut source, block);
3534            let mem = build.func().add_mem(MemInfo {
3535                size: u64::from(bits / 8),
3536                align: bits / 8,
3537                order: MemOrder::SeqCst,
3538                ..plain()
3539            });
3540            let operands = build.func().push_values(&[args[0], args[1], args[2]]);
3541            build.inst(
3542                InstData {
3543                    args: operands,
3544                    extra: Extra::Mem(mem),
3545                    ..InstData::new(Opcode::Cmpxchg)
3546                },
3547                &[ty, Type::I1],
3548            );
3549
3550            // Two values out of one instruction, the first of them in the register the machine
3551            // reads the expected value out of, the second free for the allocator to place. The
3552            // address is the memory operand and neither of the two values is.
3553            let text = lower(&mut names, &source);
3554            let written = format!("%3:gpr($rax), %4:gpr = x64.cmpxchg_{bits} %1($rax), %2, [%0]");
3555            assert!(text.contains(&written), "{bits}: {text}");
3556        }
3557    }
3558
3559    #[test]
3560    fn more_values_back_than_the_convention_has_registers_for_is_reported() {
3561        let i64 = Type::int(64);
3562        let (mut names, mut source, block, args) = blank(&[i64, i64, i64]);
3563        let mut build = Builder::new(&mut source, block);
3564        build.ret(&[args[0], args[1], args[2]]);
3565
3566        // Two integers come back in `rax` and `rdx` and a third has nowhere to go, which is not a
3567        // gap in the rules but the convention saying no. The front end classifies before it gets
3568        // here, so this is the shape that would mean the classification went wrong.
3569        let failed = func(&source, &mut names, &SYSV, &Elsewhere::default())
3570            .expect_err("only two come back");
3571        assert_eq!(
3572            failed.to_string(),
3573            "what this function gives back takes more registers than this convention has for it"
3574        );
3575
3576        let inst = failed.inst().expect("the instruction it is about");
3577        assert_eq!(source[inst].opcode, Opcode::Return);
3578    }
3579
3580    /// A refusal about a signature has no instruction, which is what makes it the one arm apart.
3581    ///
3582    /// Everything else is about something written somewhere in the body and hands it back so a
3583    /// caller can ask the function where it came from. A parameter arrives before the first
3584    /// instruction runs, so there is nothing in the body to point at and the message is about
3585    /// the function.
3586    #[test]
3587    fn a_refusal_about_a_parameter_has_no_instruction_to_point_at() {
3588        let missing = Unsupported::Argument { index: 0, missing: Missing::OnX87 };
3589        assert_eq!(missing.inst(), None);
3590    }
3591
3592    /// An `alloca` of a fixed size, which is what every local whose address is taken becomes.
3593    fn slot(source: &mut Func, block: Block, size: u64, align: u32) -> Value {
3594        let info = MemInfo { size, align, ..plain() };
3595        let mut build = Builder::new(source, block);
3596        let mem = build.func().add_mem(info);
3597        build.value(InstData { extra: Extra::Mem(mem), ..InstData::new(Opcode::Alloca) }, Type::PTR)
3598    }
3599
3600    #[test]
3601    fn a_local_is_memory_in_the_frame_and_one_instruction_that_says_where() {
3602        let (mut names, mut source, block, _) = blank(&[]);
3603        let slot = slot(&mut source, block, 4, 4);
3604        let mut build = Builder::new(&mut source, block);
3605        let nine = build.iconst(Type::int(32), 9);
3606        build.store(nine, slot, plain(), Flags::default());
3607        let loaded = build.load(Type::int(32), slot, plain(), Flags::default());
3608        build.ret(&[loaded]);
3609
3610        let lowered = func(&source, &mut names, &SYSV, &Elsewhere::default())
3611            .expect("every instruction has a rule");
3612
3613        // Four bytes on the list the frame is laid out from, and the one instruction that reads
3614        // where they went. Its displacement is nothing here because there is no frame yet, and
3615        // which instruction is waiting for which local is what `finish` is handed.
3616        assert_eq!(lowered.stack.locals, vec![Local { size: 4, align: 4 }]);
3617        assert_eq!(lowered.stack.addresses.len(), 1);
3618        assert_eq!(lowered.stack.addresses[0].1, 0);
3619        assert_eq!(
3620            mir::print_func(&lowered.func, &names, &REGS),
3621            "mfunc @f {\nblock0:\n    %0:gpr = x64.lea_64 [$rsp]\n    \
3622             %1:gpr = x64.mov_ri_32 9\n    x64.mov_mr_32 %1, [%0]\n    \
3623             %2:gpr = x64.mov_rm_32 [%0]\n    x64.ret_val_32 %2($rax)\n}\n"
3624        );
3625    }
3626
3627    #[test]
3628    fn the_frame_is_what_fills_the_address_of_a_local_in() {
3629        let (mut names, mut source, block, _) = blank(&[]);
3630        let slot = slot(&mut source, block, 4, 4);
3631        let mut build = Builder::new(&mut source, block);
3632        let nine = build.iconst(Type::int(32), 9);
3633        build.store(nine, slot, plain(), Flags::default());
3634        let loaded = build.load(Type::int(32), slot, plain(), Flags::default());
3635        build.ret(&[loaded]);
3636
3637        let lowered = func(&source, &mut names, &SYSV, &Elsewhere::default())
3638            .expect("every instruction has a rule");
3639        let stack = lowered.stack;
3640        let mut out = lowered.func;
3641        let env = env();
3642        let allocation = rucc_regalloc::run(&mut out, &env, "test");
3643        let layout = stack.layout(Layout::new(&SYSV, REGS));
3644        let frame = Frame::of(&out, &allocation, &layout);
3645        finish(&mut out, &allocation, &frame, &stack, Convention::new(&SYSV, &FRAME), &mut names);
3646
3647        // `int f(void) { int x; x = 9; return x; }` with the address of `x` taken, end to end.
3648        // A leaf small enough to live in the red zone takes no frame at all, so the stack pointer
3649        // never moves and the four bytes are below it, which is what the negative offset is. The
3650        // instruction the lowering left with nothing in its displacement now has the answer in it.
3651        let text = mir::print_func(&out, &names, &REGS);
3652        assert!(text.contains("$rax = x64.lea_64 [$rsp - 8]"), "{text}");
3653        assert!(!text.contains("x64.sub_ri_64"), "{text}");
3654        assert_eq!(frame.size(), 0);
3655        assert_eq!(frame.local(0), Some(-8));
3656    }
3657
3658    #[test]
3659    fn a_stack_slot_whose_size_is_not_known_until_it_runs_is_reported() {
3660        let i64 = Type::int(64);
3661        let (mut names, mut source, block, args) = blank(&[i64]);
3662        let info = MemInfo { size: 0, align: 16, ..plain() };
3663        let mut build = Builder::new(&mut source, block);
3664        let mem = build.func().add_mem(info);
3665        let size = build.func().push_values(&[args[0]]);
3666        let slot = build.value(
3667            InstData { args: size, extra: Extra::Mem(mem), ..InstData::new(Opcode::Alloca) },
3668            Type::PTR,
3669        );
3670        Builder::new(&mut source, block).ret(&[slot]);
3671
3672        // A variable length array. Growing the stack where the declaration stands means moving the
3673        // stack pointer in the middle of the function and reaching everything else through a
3674        // frame pointer afterwards, and the frame here lays out neither.
3675        let failed = func(&source, &mut names, &SYSV, &Elsewhere::default())
3676            .expect_err("nothing grows the stack");
3677        assert_eq!(failed.to_string(), "nothing here grows the stack for a variable length array");
3678    }
3679
3680    #[test]
3681    fn an_address_is_read_written_and_added_to_like_the_integer_it_is() {
3682        let (mut names, mut source, block, args) = blank(&[Type::PTR, Type::int(64)]);
3683        let mut build = Builder::new(&mut source, block);
3684        let stepped = build.func().push_values(&[args[0], args[1]]);
3685        let next =
3686            build.value(InstData { args: stepped, ..InstData::new(Opcode::PtrAdd) }, Type::PTR);
3687        let loaded = build.load(Type::int(32), next, plain(), Flags::default());
3688        build.ret(&[loaded]);
3689
3690        // `int f(int *p, long i) { return *(int *)((char *)p + i); }`. Nothing about this is new
3691        // in the rule set, which is the point: the two addresses arrive in registers because an
3692        // address is an integer as wide as one, and the arithmetic on them is the add it always
3693        // was, so every rule written about an add reaches it.
3694        //
3695        // The add stays its own instruction rather than folding into the address the load reads
3696        // from. Two registers with no scale on either is the one addressing mode the rules have no
3697        // load through, because the folds that exist are the displacement one and the scaled ones,
3698        // and this is neither. That is a peephole worth having and not a thing this changes.
3699        assert_eq!(
3700            lower(&mut names, &source),
3701            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_64\n    \
3702             %1:gpr($rsi) = x64.arg_val_64\n    %2:gpr(reuse 1) = x64.add_rr_64 %0, %1\n    \
3703             %3:gpr = x64.mov_rm_32 [%2]\n    x64.ret_val_32 %3($rax)\n}\n"
3704        );
3705    }
3706
3707    /// The address of a file scope name, which is what every use of a global and every string
3708    /// literal starts from.
3709    fn address_of(source: &mut Func, block: Block, names: &mut Interner, name: &str) -> Value {
3710        let symbol = names.intern(name);
3711        let mut build = Builder::new(source, block);
3712        build.value(
3713            InstData { extra: Extra::Symbol(symbol), ..InstData::new(Opcode::GlobalAddr) },
3714            Type::PTR,
3715        )
3716    }
3717
3718    #[test]
3719    fn the_address_of_a_name_is_one_instruction_carrying_the_name() {
3720        let (mut names, mut source, block, _) = blank(&[]);
3721        let counter = address_of(&mut source, block, &mut names, "counter");
3722        let mut build = Builder::new(&mut source, block);
3723        let loaded = build.load(Type::int(32), counter, plain(), Flags::default());
3724        build.ret(&[loaded]);
3725
3726        // `extern int counter; int f(void) { return counter; }`. The address is an addressing mode
3727        // that names no register and carries the symbol, which is what the assembler writes
3728        // relative to `%rip` and what the object writer leaves a relocation for.
3729        assert_eq!(
3730            lower(&mut names, &source),
3731            "mfunc @f {\nblock0:\n    %0:gpr = x64.lea_64 [@counter]\n    \
3732             %1:gpr = x64.mov_rm_32 [%0]\n    x64.ret_val_32 %1($rax)\n}\n"
3733        );
3734    }
3735
3736    #[test]
3737    fn the_address_of_a_name_outside_the_file_is_read_out_of_the_offset_table() {
3738        let (mut names, mut source, block, _) = blank(&[]);
3739        let away = address_of(&mut source, block, &mut names, "away");
3740        Builder::new(&mut source, block).ret(&[away]);
3741        let elsewhere: Elsewhere = [names.intern("away")].into_iter().collect();
3742
3743        // `extern void away(void); void *f(void) { return away; }`. A load and not an address
3744        // computation, because the distance from here to a name a shared library may be the one
3745        // that defines is not a number any link can work out, and the slot the linker fills in is
3746        // in this program and so is a distance it has.
3747        let out =
3748            func(&source, &mut names, &SYSV, &elsewhere).expect("every instruction has a rule");
3749        assert_eq!(
3750            mir::print_func(&out.func, &names, &REGS),
3751            "mfunc @f {\nblock0:\n    %0:gpr = x64.mov_rm_64 [got @away]\n    \
3752             x64.ret_val_64 %0($rax)\n}\n"
3753        );
3754    }
3755
3756    /// One `asm` statement, with its template and its constraint list written as a program does.
3757    fn assembly(
3758        source: &mut Func,
3759        block: Block,
3760        names: &mut Interner,
3761        template: &str,
3762        constraints: &str,
3763        args: &[Value],
3764        results: &[Type],
3765    ) -> Inst {
3766        let info = AsmInfo {
3767            template: names.intern(template),
3768            constraints: names.intern(constraints),
3769            clobbers: names.intern("memory"),
3770            targets: rucc_ir::BlockCallList::EMPTY,
3771        };
3772        Builder::new(source, block).inline_asm(info, args, results, Flags::VOLATILE)
3773    }
3774
3775    #[test]
3776    fn an_asm_with_an_empty_template_and_no_operands_is_no_instructions() {
3777        let (mut names, mut source, block, _) = blank(&[]);
3778        assembly(&mut source, block, &mut names, "", "", &[], &[]);
3779        Builder::new(&mut source, block).ret(&[]);
3780
3781        // `asm volatile ("" : : : "memory")`, which is a barrier and nothing else. The barrier was
3782        // spent on the optimizer, which has finished by now, so what is left is nothing.
3783        assert_eq!(lower(&mut names, &source), "mfunc @f {\nblock0:\n}\n");
3784    }
3785
3786    #[test]
3787    fn an_output_an_input_is_tied_to_is_the_register_that_input_arrived_in() {
3788        let i32 = Type::int(32);
3789        let (mut names, mut source, block, args) = blank(&[i32]);
3790        let out = assembly(&mut source, block, &mut names, "", "=r,0", &args, &[i32]);
3791        let produced = source[out].results().next().expect("one result");
3792        Builder::new(&mut source, block).ret(&[produced]);
3793
3794        // `asm ("" : "=r" (x) : "0" (x))`, which is how a program stops the optimizer following a
3795        // value without changing it. The two share a place and the template writes nothing over
3796        // it, so the value comes back out of the register it went in.
3797        assert_eq!(
3798            lower(&mut names, &source),
3799            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_32\n    \
3800             x64.ret_val_32 %0($rax)\n}\n"
3801        );
3802    }
3803
3804    #[test]
3805    fn an_output_written_plus_is_the_same_rename() {
3806        let i32 = Type::int(32);
3807        let (mut names, mut source, block, args) = blank(&[i32]);
3808        let out = assembly(&mut source, block, &mut names, "", "+r", &args, &[i32]);
3809        let produced = source[out].results().next().expect("one result");
3810        Builder::new(&mut source, block).ret(&[produced]);
3811
3812        // `asm ("" : "+r" (x))`, which says the same thing in one operand instead of two.
3813        assert_eq!(
3814            lower(&mut names, &source),
3815            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_32\n    \
3816             x64.ret_val_32 %0($rax)\n}\n"
3817        );
3818    }
3819
3820    #[test]
3821    fn an_output_nothing_is_tied_to_is_a_zero() {
3822        let i32 = Type::int(32);
3823        let (mut names, mut source, block, _) = blank(&[]);
3824        let out = assembly(&mut source, block, &mut names, "", "=r", &[], &[i32]);
3825        let produced = source[out].results().next().expect("one result");
3826        Builder::new(&mut source, block).ret(&[produced]);
3827
3828        // `asm ("" : "=r" (y))`, whose answer is whatever the assembly left in the register, and
3829        // an empty template leaves nothing. A definite value rather than a register nothing wrote,
3830        // because the allocator is owed a definition before the use however little the program is.
3831        assert_eq!(
3832            lower(&mut names, &source),
3833            "mfunc @f {\nblock0:\n    %0:gpr = x64.mov_ri_32 0\n    x64.ret_val_32 %0($rax)\n}\n"
3834        );
3835    }
3836
3837    #[test]
3838    fn an_asm_with_instructions_in_its_template_is_refused_as_an_asm() {
3839        let (mut names, mut source, block, _) = blank(&[]);
3840        assembly(&mut source, block, &mut names, "nop", "", &[], &[]);
3841        Builder::new(&mut source, block).ret(&[]);
3842
3843        let failed = func(&source, &mut names, &SYSV, &Elsewhere::default())
3844            .expect_err("nothing here assembles a template");
3845        assert_eq!(
3846            failed.to_string(),
3847            "this `asm` has instructions in its template, which nothing here assembles"
3848        );
3849    }
3850
3851    #[test]
3852    fn a_constraint_list_that_does_not_describe_the_operands_is_refused() {
3853        let i32 = Type::int(32);
3854        let (mut names, mut source, block, args) = blank(&[i32]);
3855        assembly(&mut source, block, &mut names, "", "=r", &args, &[]);
3856        Builder::new(&mut source, block).ret(&[]);
3857
3858        // An output with no result to be, which is what the front end never writes and what a
3859        // hand written module can. Refused rather than placed by a guess.
3860        let failed = func(&source, &mut names, &SYSV, &Elsewhere::default())
3861            .expect_err("the list and the instruction disagree");
3862        assert_eq!(failed.to_string(), "this `asm` has an operand this cannot place");
3863    }
3864
3865    /// A cast between a pointer and an integer, at whatever width the result is asked for.
3866    fn cast(source: &mut Func, block: Block, opcode: Opcode, from: Value, to: Type) -> Value {
3867        let mut build = Builder::new(source, block);
3868        let args = build.func().push_values(&[from]);
3869        build.value(InstData { args, ..InstData::new(opcode) }, to)
3870    }
3871
3872    #[test]
3873    fn a_cast_between_a_pointer_and_an_integer_as_wide_is_no_instruction_at_all() {
3874        let (mut names, mut source, block, args) = blank(&[Type::PTR]);
3875        let number = cast(&mut source, block, Opcode::PtrToInt, args[0], Type::int(64));
3876        Builder::new(&mut source, block).ret(&[number]);
3877
3878        // `long f(void *p) { return (long)p; }`. An address on this machine is an integer as wide
3879        // as the machine addresses, so the cast changes what the type system calls the value and
3880        // changes nothing about the value, and the register holding it is the one that held it.
3881        assert_eq!(
3882            lower(&mut names, &source),
3883            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_64\n    \
3884             x64.ret_val_64 %0($rax)\n}\n"
3885        );
3886    }
3887
3888    #[test]
3889    fn a_null_pointer_is_a_constant_that_reaches_a_register_before_anything_reads_it() {
3890        let (mut names, mut source, block, _) = blank(&[]);
3891        let mut build = Builder::new(&mut source, block);
3892        let zero = build.iconst(Type::int(64), 0);
3893        let null = cast(&mut source, block, Opcode::IntToPtr, zero, Type::PTR);
3894        Builder::new(&mut source, block).ret(&[null]);
3895
3896        // `void *f(void) { return 0; }`. The cast is nothing, and reading its operand is what
3897        // writes the zero down: a constant is materialized where it is wanted rather than where
3898        // the IR defined it, and without the read there would be no instruction at all.
3899        assert_eq!(
3900            lower(&mut names, &source),
3901            "mfunc @f {\nblock0:\n    %0:gpr = x64.mov_ri_64 0\n    x64.ret_val_64 %0($rax)\n}\n"
3902        );
3903    }
3904
3905    #[test]
3906    fn the_five_linkages_the_ir_has_narrow_to_the_three_an_object_file_can_say() {
3907        let readings = [
3908            (Linkage::External, mir::Binding::Global),
3909            (Linkage::Common, mir::Binding::Global),
3910            (Linkage::Internal, mir::Binding::Local),
3911            (Linkage::Weak, mir::Binding::Weak),
3912            (Linkage::LinkOnce, mir::Binding::Weak),
3913        ];
3914        for (linkage, wanted) in readings {
3915            let (mut names, mut source, block, _) = blank(&[]);
3916            source.linkage = linkage;
3917            Builder::new(&mut source, block).ret(&[]);
3918            let out = func(&source, &mut names, &SYSV, &Elsewhere::default()).expect("a return");
3919            // The narrowing is done here rather than where the object is written, because a
3920            // machine function is all the assembler and the writer are ever handed.
3921            assert_eq!(out.func.binding, wanted, "{linkage:?}");
3922        }
3923    }
3924
3925    /// The visibility makes the same trip and is not narrowed on the way, because ELF says all
3926    /// three of them.
3927    ///
3928    /// Here for the reason the linkage above is here. A machine function is the whole of what the
3929    /// assembler and the object writer are handed, so a fact about the symbol that does not get
3930    /// onto one is a fact that is gone by the time anything could write it down, and the way that
3931    /// shows up is a shared library exporting the wrong set of names with nothing said anywhere.
3932    #[test]
3933    fn the_visibility_survives_the_trip_from_the_ir_to_a_machine_function() {
3934        let readings = [
3935            (Visibility::Default, mir::Visibility::Default),
3936            (Visibility::Hidden, mir::Visibility::Hidden),
3937            (Visibility::Protected, mir::Visibility::Protected),
3938        ];
3939        for (visibility, wanted) in readings {
3940            let (mut names, mut source, block, _) = blank(&[]);
3941            source.visibility = visibility;
3942            Builder::new(&mut source, block).ret(&[]);
3943            let out = func(&source, &mut names, &SYSV, &Elsewhere::default()).expect("a return");
3944            assert_eq!(out.func.visibility, wanted, "{visibility:?}");
3945        }
3946    }
3947
3948    #[test]
3949    fn a_cast_between_a_pointer_and_a_narrower_integer_is_reported() {
3950        let (mut names, mut source, block, args) = blank(&[Type::PTR]);
3951        let number = cast(&mut source, block, Opcode::PtrToInt, args[0], Type::int(32));
3952        Builder::new(&mut source, block).ret(&[number]);
3953
3954        // The front end never writes one: it casts at the address width and truncates or extends
3955        // around it, so both of those are the rules they always were. IR from somewhere else that
3956        // does write one is refused rather than compiled to a move that keeps the high half.
3957        let failed = func(&source, &mut names, &SYSV, &Elsewhere::default())
3958            .expect_err("no rule narrows an address");
3959        assert_eq!(failed.to_string(), "no rule lowers a `ptrtoint` producing a `i32`");
3960    }
3961
3962    /// The type this machine has no register for.
3963    fn long_double() -> Type {
3964        Type::float(rucc_ir::Float::F80)
3965    }
3966
3967    #[test]
3968    fn a_double_widened_and_narrowed_again_goes_out_through_the_frame_and_back() {
3969        let f64 = Type::float(rucc_ir::Float::F64);
3970        let (mut names, mut source, block, args) = blank(&[f64]);
3971        let wide = cast(&mut source, block, Opcode::FPExt, args[0], long_double());
3972        let back = cast(&mut source, block, Opcode::FPTrunc, wide, f64);
3973        Builder::new(&mut source, block).ret(&[back]);
3974
3975        // `double f(double d) { long double x = d; return x; }`. The x87 reads memory and nothing
3976        // else, so the value is written to the crossing slot, loaded at the format that widens it
3977        // and put in the slot the eighty bit value lives in. Coming back is the same three the
3978        // other way. Both slots are addressed by a `lea` with nothing in it yet, which is what
3979        // every address in a frame looks like here until `finish` has the numbers.
3980        assert_eq!(
3981            lower(&mut names, &source),
3982            "mfunc @f {\nblock0:\n    \
3983             %0:xmm($xmm0) = x64.arg_val_f64\n    \
3984             %1:gpr = x64.lea_64 [$rsp]\n    \
3985             %2:gpr = x64.lea_64 [$rsp]\n    \
3986             x64.movsd_mr %0, [%1]\n    \
3987             x64.fld_l [%1]\n    \
3988             x64.fstp_t [%2]\n    \
3989             %3:gpr = x64.lea_64 [$rsp]\n    \
3990             %4:gpr = x64.lea_64 [$rsp]\n    \
3991             x64.fld_t [%3]\n    \
3992             x64.fstp_l [%4]\n    \
3993             %5:xmm = x64.movsd_rm [%4]\n    \
3994             x64.ret_val_f64 %5($xmm0)\n}\n"
3995        );
3996    }
3997
3998    #[test]
3999    fn a_long_double_has_sixteen_bytes_of_its_own_and_keeps_them() {
4000        let f64 = Type::float(rucc_ir::Float::F64);
4001        let (mut names, mut source, block, args) = blank(&[f64]);
4002        let wide = cast(&mut source, block, Opcode::FPExt, args[0], long_double());
4003        let once = cast(&mut source, block, Opcode::FPTrunc, wide, f64);
4004        let twice = cast(&mut source, block, Opcode::FPTrunc, wide, f64);
4005        let mut build = Builder::new(&mut source, block);
4006        let sum = build.binary(Opcode::FAdd, once, twice, Flags::default());
4007        build.ret(&[sum]);
4008
4009        let out = func(&source, &mut names, &SYSV, &Elsewhere::default())
4010            .expect("every instruction is written");
4011
4012        // Two slots and not four: sixteen bytes for the one eighty bit value, which is what the
4013        // psABI says one takes and is aligned to, and eight for the crossing, which every group
4014        // in the function shares because nothing is ever left in it. The value's slot is its own
4015        // for the whole function, so reading it twice reads the same sixteen bytes.
4016        assert_eq!(
4017            out.stack.locals,
4018            vec![Local { size: 8, align: 8 }, Local { size: 16, align: 16 }]
4019        );
4020    }
4021
4022    #[test]
4023    fn an_integer_becomes_a_long_double_by_being_loaded_as_one() {
4024        let (mut names, mut source, block, args) = blank(&[Type::int(64)]);
4025        let wide = cast(&mut source, block, Opcode::SIToFP, args[0], long_double());
4026        let back =
4027            cast(&mut source, block, Opcode::FPTrunc, wide, Type::float(rucc_ir::Float::F64));
4028        Builder::new(&mut source, block).ret(&[back]);
4029
4030        // `double f(long n) { long double x = n; return x; }`. `fild` is the same push at another
4031        // format, so the conversion is the load and there is no instruction that converts.
4032        let text = lower(&mut names, &source);
4033        assert!(text.contains("x64.mov_mr_64 %0, [%1]"), "{text}");
4034        assert!(text.contains("x64.fild_ll [%1]"), "{text}");
4035    }
4036
4037    #[test]
4038    fn a_long_double_becoming_an_integer_cuts_towards_zero_with_the_control_word() {
4039        let (mut names, mut source, block, args) = blank(&[Type::float(rucc_ir::Float::F64)]);
4040        let wide = cast(&mut source, block, Opcode::FPExt, args[0], long_double());
4041        let whole = cast(&mut source, block, Opcode::FPToSI, wide, Type::int(32));
4042        Builder::new(&mut source, block).ret(&[whole]);
4043
4044        // The one conversion here with no single instruction behind it. C cuts towards zero and
4045        // the unit rounds the way its control word says, so the word is saved, ORed with the two
4046        // bits that mean truncate, loaded, used and put back. Nine instructions for what `fisttp`
4047        // does in one, and `spec/10-backend.md` section 10.8 says why that one is not used.
4048        let text = lower(&mut names, &source);
4049        let group: Vec<&str> = text
4050            .lines()
4051            .map(str::trim)
4052            .filter(|line| line.starts_with("x64.f") || line.contains("_16"))
4053            .collect();
4054        assert_eq!(
4055            group,
4056            [
4057                "x64.fld_l [%1]",
4058                "x64.fstp_t [%2]",
4059                "x64.fnstcw [%5]",
4060                "%6:gpr = x64.mov_rm_16 [%5]",
4061                "%7:gpr(reuse 1) = x64.or_ri_16 %6, 3072",
4062                "x64.mov_mr_16 %7, [%5 + 2]",
4063                "x64.fldcw [%5 + 2]",
4064                "x64.fld_t [%3]",
4065                "x64.fistp_l [%4]",
4066                "x64.fldcw [%5]",
4067            ],
4068            "{text}"
4069        );
4070    }
4071
4072    #[test]
4073    fn a_long_double_is_read_and_written_as_the_bits_it_already_is() {
4074        let (mut names, mut source, block, args) = blank(&[Type::PTR, Type::PTR]);
4075        let mut build = Builder::new(&mut source, block);
4076        let value = build.load(long_double(), args[0], plain(), Flags::default());
4077        build.store(value, args[1], plain(), Flags::default());
4078        build.ret(&[]);
4079
4080        // `void f(long double *a, long double *b) { *b = *a; }`. A copy is a push and a pop at the
4081        // format the value is already in, which neither converts nor looks: a signalling NaN stays
4082        // one and nothing is raised, which is the whole of what makes it a copy.
4083        let text = lower(&mut names, &source);
4084        let group: Vec<&str> =
4085            text.lines().map(str::trim).filter(|line| line.starts_with("x64.f")).collect();
4086        assert_eq!(
4087            group,
4088            ["x64.fld_t [%0]", "x64.fstp_t [%2]", "x64.fld_t [%3]", "x64.fstp_t [%1]"],
4089            "{text}"
4090        );
4091    }
4092
4093    /// Two `long double` values, from two `double` parameters, and the instructions that made
4094    /// them, which every test below this one throws away.
4095    fn two_long_doubles(source: &mut Func, block: Block, args: &[Value]) -> (Value, Value) {
4096        let left = cast(source, block, Opcode::FPExt, args[0], long_double());
4097        let right = cast(source, block, Opcode::FPExt, args[1], long_double());
4098        (left, right)
4099    }
4100
4101    /// The x87 instructions of a function, in order, with everything else dropped.
4102    fn stack_only(text: &str) -> Vec<&str> {
4103        text.lines().map(str::trim).filter(|line| line.contains("x64.f")).collect()
4104    }
4105
4106    /// The two frame slots the last two addresses of a function were taken of, which in a
4107    /// comparison are the two operands in the order they go on the stack.
4108    fn pushed(out: &Lowered) -> Vec<usize> {
4109        let taken: Vec<usize> = out.stack.addresses.iter().map(|&(_, local)| local).collect();
4110        taken[taken.len() - 2..].to_vec()
4111    }
4112
4113    #[test]
4114    fn adding_two_long_doubles_pushes_both_and_leaves_the_answer_in_a_slot() {
4115        let f64 = Type::float(rucc_ir::Float::F64);
4116        let (mut names, mut source, block, args) = blank(&[f64, f64]);
4117        let (left, right) = two_long_doubles(&mut source, block, &args);
4118        let sum =
4119            Builder::new(&mut source, block).binary(Opcode::FAdd, left, right, Flags::default());
4120        let back = cast(&mut source, block, Opcode::FPTrunc, sum, f64);
4121        Builder::new(&mut source, block).ret(&[back]);
4122
4123        // `double f(double a, double b) { return (long double) a + (long double) b; }`. The last
4124        // four lines are the add: both operands pushed, the instruction that names neither of
4125        // them because they are the top two of a stack, and the answer taken off into its slot.
4126        let text = lower(&mut names, &source);
4127        assert_eq!(
4128            stack_only(&text),
4129            [
4130                "x64.fld_l [%2]",
4131                "x64.fstp_t [%3]",
4132                "x64.fld_l [%4]",
4133                "x64.fstp_t [%5]",
4134                "x64.fld_t [%6]",
4135                "x64.fld_t [%7]",
4136                "x64.fadd_p",
4137                "x64.fstp_t [%8]",
4138                "x64.fld_t [%9]",
4139                "x64.fstp_l [%10]",
4140            ],
4141            "{text}"
4142        );
4143    }
4144
4145    #[test]
4146    fn a_subtraction_pushes_the_left_operand_first_and_asks_for_the_att_spelling() {
4147        let f64 = Type::float(rucc_ir::Float::F64);
4148        let (mut names, mut source, block, args) = blank(&[f64, f64]);
4149        let (left, right) = two_long_doubles(&mut source, block, &args);
4150        let less =
4151            Builder::new(&mut source, block).binary(Opcode::FSub, left, right, Flags::default());
4152        let back = cast(&mut source, block, Opcode::FPTrunc, less, f64);
4153        Builder::new(&mut source, block).ret(&[back]);
4154
4155        // The left one goes on first, so it ends up under the right one, and the answer wanted is
4156        // the one below minus the top. In AT&T that is `fsubrp`, since `fsubp` there is `DE E0+i`
4157        // and computes the other one. The `r` says which spelling this is and not which order the
4158        // pushes were in. `crates/rucc/tests/x87.rs` is what says the answer is right, because a
4159        // name is what got this wrong the first time.
4160        let text = lower(&mut names, &source);
4161        assert_eq!(
4162            &stack_only(&text)[4..8],
4163            ["x64.fld_t [%6]", "x64.fld_t [%7]", "x64.fsubr_p", "x64.fstp_t [%8]"],
4164            "{text}"
4165        );
4166    }
4167
4168    #[test]
4169    fn negating_a_long_double_turns_the_sign_over_and_reads_nothing() {
4170        let f64 = Type::float(rucc_ir::Float::F64);
4171        let (mut names, mut source, block, args) = blank(&[f64]);
4172        let wide = cast(&mut source, block, Opcode::FPExt, args[0], long_double());
4173        let flipped = Builder::new(&mut source, block).unary(Opcode::FNeg, wide, long_double());
4174        let back = cast(&mut source, block, Opcode::FPTrunc, flipped, f64);
4175        Builder::new(&mut source, block).ret(&[back]);
4176
4177        // `fchs` and not a subtraction from zero, which would give a different answer at a negative
4178        // zero and would signal at a NaN. It does not read the value as a number at all.
4179        let text = lower(&mut names, &source);
4180        assert_eq!(
4181            &stack_only(&text)[2..5],
4182            ["x64.fld_t [%3]", "x64.fchs", "x64.fstp_t [%4]"],
4183            "{text}"
4184        );
4185    }
4186
4187    #[test]
4188    fn comparing_two_long_doubles_puts_the_left_one_on_top() {
4189        let f64 = Type::float(rucc_ir::Float::F64);
4190        let (mut names, mut source, block, args) = blank(&[f64, f64]);
4191        let (left, right) = two_long_doubles(&mut source, block, &args);
4192        let mut build = Builder::new(&mut source, block);
4193        build.fcmp(FloatPred::Ogt, left, right, Flags::default());
4194        build.ret(&[]);
4195
4196        // `a > b`. `fucomip` asks about the top of the stack against what is under it, so the
4197        // operand the predicate is about has to go on last, which is the other way round from the
4198        // arithmetic above. The pop that clears the loser and the byte that reads the flags are
4199        // both inside the one opcode.
4200        let out = func(&source, &mut names, &SYSV, &Elsewhere::default())
4201            .expect("every instruction is written");
4202        let slots = pushed(&out);
4203        assert_eq!(slots, [2, 1], "the right operand goes on first and the left one on top");
4204        let text = mir::print_func(&out.func, &names, &REGS);
4205        assert_eq!(
4206            &stack_only(&text)[4..],
4207            ["x64.fld_t [%6]", "x64.fld_t [%7]", "%8:gpr = x64.fucomip_set_a"],
4208            "{text}"
4209        );
4210    }
4211
4212    #[test]
4213    fn a_comparison_that_the_machine_has_backwards_swaps_the_two_pushes() {
4214        let f64 = Type::float(rucc_ir::Float::F64);
4215        let (mut names, mut source, block, args) = blank(&[f64, f64]);
4216        let (left, right) = two_long_doubles(&mut source, block, &args);
4217        let mut build = Builder::new(&mut source, block);
4218        build.fcmp(FloatPred::Olt, left, right, Flags::default());
4219        build.ret(&[]);
4220
4221        // `a < b` is `b > a` and this machine has the one condition, so the same opcode runs with
4222        // the operands the other way round. The same trade the vector rules make, and it has to
4223        // be the same one: a `long double` comparison that picked a different condition from the
4224        // `double` comparison of the same two numbers would be wrong at exactly the unordered
4225        // cases the two conditions differ on.
4226        //
4227        // Which slot each push names is the whole of the difference from the test above, and the
4228        // text does not show it, since an address in a frame is a `lea` with nothing in it until
4229        // `finish` has the numbers. So the slots are what is read here.
4230        let out = func(&source, &mut names, &SYSV, &Elsewhere::default())
4231            .expect("every instruction is written");
4232        let slots = pushed(&out);
4233        assert_eq!(slots, [1, 2], "the left operand goes on first and the right one on top");
4234        let text = mir::print_func(&out.func, &names, &REGS);
4235        assert_eq!(
4236            &stack_only(&text)[4..],
4237            ["x64.fld_t [%6]", "x64.fld_t [%7]", "%8:gpr = x64.fucomip_set_a"],
4238            "{text}"
4239        );
4240    }
4241
4242    #[test]
4243    fn an_ordered_equal_needs_a_second_byte_to_put_the_two_conditions_together() {
4244        let f64 = Type::float(rucc_ir::Float::F64);
4245        let (mut names, mut source, block, args) = blank(&[f64, f64]);
4246        let (left, right) = two_long_doubles(&mut source, block, &args);
4247        let mut build = Builder::new(&mut source, block);
4248        build.fcmp(FloatPred::Oeq, left, right, Flags::default());
4249        build.ret(&[]);
4250
4251        // Equal and ordered are two conditions and the flags carry both, so the opcode writes a
4252        // second register as well as the one the value is in and ANDs them together. Said here by
4253        // handing it a spare, since an instruction that wrote a register nothing knew about would
4254        // be an instruction the allocator could put a live value in the way of.
4255        let text = lower(&mut names, &source);
4256        assert!(text.contains("%8:gpr, %9:gpr = x64.fucomip_set_e_and_np"), "{text}");
4257    }
4258
4259    #[test]
4260    fn a_comparison_that_is_never_asked_is_reported() {
4261        let f64 = Type::float(rucc_ir::Float::F64);
4262        let (mut names, mut source, block, args) = blank(&[f64, f64]);
4263        let (left, right) = two_long_doubles(&mut source, block, &args);
4264        let mut build = Builder::new(&mut source, block);
4265        build.fcmp(FloatPred::False, left, right, Flags::default());
4266        build.ret(&[]);
4267
4268        // Always false is a constant and not a comparison, so there is no condition to pick and
4269        // nothing here folds it into one: an instruction that quietly agreed with it would hide
4270        // that the optimizer left a comparison in that it should have taken out.
4271        let failed = func(&source, &mut names, &SYSV, &Elsewhere::default())
4272            .expect_err("no condition is always false");
4273        assert_eq!(failed.to_string(), "no rule lowers a `fcmp` producing a `i1`");
4274    }
4275
4276    #[test]
4277    fn a_long_double_constant_is_the_bits_of_it_put_where_the_value_lives() {
4278        let (mut names, mut source, block, args) = blank(&[Type::PTR]);
4279        let mut build = Builder::new(&mut source, block);
4280        // `1.5L`, which is the leading bit and one more of significand, and an exponent of zero.
4281        let one_and_a_half = build.fconst(long_double(), 0x3fff_c000_0000_0000_0000);
4282        build.store(one_and_a_half, args[0], plain(), Flags::default());
4283        build.ret(&[]);
4284
4285        // No x87 instruction at all. A slot holding one of these is the value, so a constant is
4286        // its ten bytes written where the value lives, and whatever reads it does the `fld`.
4287        let text = lower(&mut names, &source);
4288        assert!(text.contains("x64.mov_ri_64 -4611686018427387904"), "{text}");
4289        assert!(text.contains("x64.mov_ri_16 16383"), "{text}");
4290        assert!(text.contains("x64.mov_mr_16 %3, [%1 + 8]"), "{text}");
4291        // The six bytes above the ten are the padding that makes the type sixteen wide, and they
4292        // are unspecified rather than zero, so nothing writes them.
4293        assert_eq!(text.matches("x64.mov_mr").count(), 2, "{text}");
4294    }
4295
4296    #[test]
4297    fn a_negative_long_double_constant_keeps_the_bit_above_its_exponent() {
4298        let (mut names, mut source, block, args) = blank(&[Type::PTR]);
4299        let mut build = Builder::new(&mut source, block);
4300        let minus = build.fconst(long_double(), 0xbfff_c000_0000_0000_0000);
4301        build.store(minus, args[0], plain(), Flags::default());
4302        build.ret(&[]);
4303
4304        // `-1.5L`. The sign is the top bit of the two byte half, so the immediate that half is put
4305        // in a register with is above the signed range of sixteen bits and has to stay there: read
4306        // as a number it would be negative, and it is not a number, it is two bytes.
4307        let text = lower(&mut names, &source);
4308        assert!(text.contains("x64.mov_ri_16 49151"), "{text}");
4309    }
4310
4311    #[test]
4312    fn a_long_double_crosses_an_edge_as_an_address_and_is_copied_where_it_lands() {
4313        let (mut names, mut source, block, args) = blank(&[Type::float(rucc_ir::Float::F64)]);
4314        let wide = cast(&mut source, block, Opcode::FPExt, args[0], long_double());
4315        let next = source.create_block();
4316        let param = source.append_param(next, long_double());
4317        Builder::new(&mut source, block).jump(next, &[wide]);
4318        Builder::new(&mut source, next).ret(&[param]);
4319
4320        // What the edge carries is the address of the slot the value is already in, which is an
4321        // ordinary register the allocator has an opinion about. The block on the other side copies
4322        // the sixteen bytes into a slot of its own before anything reads them, so a second edge
4323        // handing over a second address would still leave one place for a reader to look.
4324        let text = lower(&mut names, &source);
4325        let second: Vec<&str> = text
4326            .lines()
4327            .skip_while(|line| !line.starts_with("block1"))
4328            .skip(1)
4329            .take(3)
4330            .map(str::trim)
4331            .collect();
4332        assert_eq!(
4333            second,
4334            ["x64.fld_t [%4]", "%5:gpr = x64.lea_64 [$rsp]", "x64.fstp_t [%5]"],
4335            "{text}"
4336        );
4337    }
4338
4339    #[test]
4340    fn more_long_doubles_at_a_block_than_the_stack_is_deep_are_reported() {
4341        let f64 = Type::float(rucc_ir::Float::F64);
4342        let (mut names, mut source, block, args) = blank(&[f64]);
4343        let wide = cast(&mut source, block, Opcode::FPExt, args[0], long_double());
4344        let next = source.create_block();
4345        let params: Vec<Value> =
4346            (0..=X87_DEPTH).map(|_| source.append_param(next, long_double())).collect();
4347        let carried: Vec<Value> = params.iter().map(|_| wide).collect();
4348        Builder::new(&mut source, block).jump(next, &carried);
4349        Builder::new(&mut source, next).ret(&[params[0]]);
4350
4351        // The copies go through the x87 stack so that every one of them is read before any of them
4352        // is written, which is what makes a block that swaps two of these right. Nine of them do
4353        // not fit on the stack, and copying the ninth before or after the rest is the order that
4354        // could be wrong, so it is refused instead.
4355        let failed = func(&source, &mut names, &SYSV, &Elsewhere::default())
4356            .expect_err("nine do not fit on the stack");
4357        assert_eq!(
4358            failed.to_string(),
4359            "block1 takes 9 parameters of type `f80` and only 8 can cross an edge at once"
4360        );
4361        assert_eq!(failed.inst(), None);
4362    }
4363}