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::collections::HashSet;
79use std::fmt;
80
81use rucc_base::{Interner, Symbol};
82use rucc_diag::Span;
83use rucc_ir::{
84    Abi, AsmOperand, AsmOperands, AttrSet, Block, Def, Extra, Flags, FloatPred, Func, Inst,
85    Linkage, MemOrder, Opcode, Param, PrefetchHint, RmwOp, Type, Value, Visibility,
86};
87use rucc_mir as mir;
88use rucc_target::x86_64;
89use rucc_target::{CallRegs, Constraint, OperandDesc, PhysReg, RegClass, Role, Segment};
90
91use crate::abi::{self, Missing, Refused};
92use crate::coverage::Fired;
93use crate::elsewhere::Elsewhere;
94use crate::frame::{Layout, Local};
95use crate::select::{Match, Piece, Rule, Table};
96use crate::term::{MAX_ARGS, PLAIN, Plan, Shown, Term, Terms};
97use crate::varargs;
98
99/// The prefix a rule file puts in front of a machine term, which says which target it belongs
100/// to and is not part of the opcode.
101pub(crate) const PREFIX: &str = "x64.";
102
103/// The instruction a global offset table slot is read with.
104///
105/// Not in [`x86_64::FRAME`] with the other opcodes this file names, because a frame has no use for
106/// it. It is spelled out here because the relocation it takes is only legal on a `mov` with a REX
107/// prefix, so the width is part of the requirement rather than a choice.
108const GOT_LOAD: &str = "mov_rm_64";
109
110/// The instruction a template's `jmp` to a name outside it becomes.
111///
112/// Named here for [`GOT_LOAD`]'s reason turned round: a frame never writes one, because the only
113/// function it appears in has no prologue and no epilogue for the frame to write anything into.
114/// See [`x86_64::Step::Away`].
115const AWAY: &str = "jmp_away";
116
117/// How wide an address is on this target, which is the width a cast between a pointer and an
118/// integer has to be at for the cast to be nothing.
119const ADDRESS_BITS: u32 = 64;
120
121/// How many bytes a `long double` takes in memory, and what it is aligned to, which are the same
122/// number and are both more than the ten bytes that mean anything.
123///
124/// The psABI's answer rather than a choice here. `sizeof (long double)` is sixteen on this
125/// machine, so an array of them is laid out this way whatever a slot holding one does, and a slot
126/// that agreed with the array is one fewer thing to get wrong.
127const X87_BYTES: u32 = 16;
128
129/// How many values the x87 stack holds at once.
130///
131/// Eight, which is the machine's number rather than a choice here, and it matters in one place:
132/// the parameters of a block are copied through the stack so that they all move at once, and a
133/// block with more of them than this has nowhere to put the ninth.
134const X87_DEPTH: usize = 8;
135
136/// How far into the buffer of a `__builtin_setjmp` each of the four words it writes is.
137///
138/// The first three are gcc's, measured against gcc 16.2.0 on x86-64 at `-O0`: the frame pointer,
139/// the address control comes back to, and the stack pointer, in that order. The fourth is this
140/// compiler's own. gcc has no word for the answer because it writes a second block that sets the
141/// answer to one and is arrived at from the restore, and this writes the answer through memory
142/// instead, for the reason [`Lowering::saves_place`] gives.
143///
144/// None of the four is an interface. The buffer is the program's memory and its five words are
145/// the front end's promise about how much of it there is, but nothing except the matching restore
146/// ever reads a word of it, and a buffer written by one compiler was never going to be one another
147/// compiler could come back through.
148const JUMP_FRAME: i32 = 0;
149
150/// Where the address control comes back to is. See [`JUMP_FRAME`].
151const JUMP_PC: i32 = 8;
152
153/// Where the stack pointer is. See [`JUMP_FRAME`].
154const JUMP_STACK: i32 = 16;
155
156/// Where the address of the word the answer arrives in is. See [`JUMP_FRAME`].
157const JUMP_ANSWER: i32 = 24;
158
159/// How many bytes the word a `__builtin_setjmp` answers with takes in the frame, and what it is
160/// aligned to, which are the same number because it is one machine word.
161const JUMP_WORD: u32 = 8;
162
163/// How many registers the restore needs to hold things in while it puts the frame back.
164///
165/// Four, and every one of them is a register nothing else in the function may be in, which is why
166/// they are counted here rather than asked for one at a time. See [`Lowering::comes_back`].
167const JUMP_REGS: usize = 4;
168
169/// How many bytes a value passes through on its way between a register and the x87 stack.
170///
171/// Eight, because the widest thing that crosses is a `double` or a sixty four bit integer, and
172/// nothing crosses at eighty bits: a value that wide is already in the frame and the stack reaches
173/// it where it is.
174const X87_CROSSING: u32 = 8;
175
176/// Where the rounding field of the x87 control word is and what it has to be set to for the unit
177/// to cut towards zero, which is the one rounding C asks for that the unit does not do by default.
178///
179/// Both bits on is truncate. The field is ORed into the word that was already there rather than
180/// written over it, so the precision control and the exception masks somebody else set stay set.
181const X87_TRUNCATE: i64 = 0x0c00;
182
183/// Whether a type is the one this machine has no register for.
184///
185/// Only the eighty bit float is, and that is a fact about x86-64 rather than about floats: every
186/// other scalar the front end produces is in a general purpose register or a vector one, and this
187/// one is on the x87 stack while it is being worked on and in memory the rest of the time. So it
188/// has no place in [`Lowering::class_of`] and no name in [`crate::term`], and every instruction
189/// that touches one is written out by hand in this file.
190fn on_x87(ty: Type) -> bool {
191    ty.is_scalar() && ty.is_float() && ty.bits() == 80
192}
193
194/// Where one operand of an assembly statement is, on each side of the assembly.
195///
196/// Two registers rather than one, because an operand written `+` is a value that arrives and a
197/// value that leaves and those are two values. The machine IR has one definition per register by
198/// construction, so an instruction of the template that reads the operand and writes it has to name
199/// a different register in each place, and what makes the two one register in the end is the
200/// [`Constraint::Reuse`] the instruction's description carries: the allocator reads it, gives both
201/// the same physical register, and copies the incoming value somewhere first when something else is
202/// still using it.
203///
204/// Most operands have one of the two. An input has only a place it is read from and an output
205/// written `=` has only a place it is written to, and asking either of them for the other is an
206/// operand read where the opcode writes or written where it reads, which [`Lowering::placed`]
207/// refuses.
208#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
209struct Place {
210    /// The register the value arrives in, for an operand something reads.
211    read: Option<mir::Reg>,
212    /// The register the value leaves in, for an operand something writes.
213    write: Option<mir::Reg>,
214}
215
216/// Whether that operand of the statement is one the assembly may read, and so where a read of it
217/// gets its value from.
218///
219/// [`bound`] asks this question of an operand a constraint letter named and this asks it of one the
220/// template numbered, which is the same question twice because a two-address instruction reaches
221/// its first source both ways. `mulq %3` reaches `rax` by the letter on the output and libgmp says
222/// what is in it with `"%0"` on an input. `addq %5,%q1` reaches its first source by numbering the
223/// output, and libgmp says what is in it with `"0"` on an input in the same way.
224///
225/// So an output written `=` has no value of its own and is still readable when an input is tied to
226/// it, and the value the read wants is that input's. An output written `+` carries its own value
227/// and answers with that. An output nothing is tied to answers `None`, which is a program that told
228/// the compiler the assembly only writes the operand while the instruction reads it before it
229/// writes it, and is refused where it is asked.
230fn read_as(list: &[AsmOperand<'_>], index: usize) -> Option<Value> {
231    let operand = list.get(index)?;
232    if operand.value.is_some() {
233        return operand.value;
234    }
235    operand.result?;
236    list.iter().find(|entry| entry.tied == Some(index)).and_then(|entry| entry.value)
237}
238
239/// Which of an assembly statement's operands is in that register, for an instruction that reaches
240/// the register without its text saying so.
241///
242/// The constraint is what says so, and it is the only thing in such a statement that could:
243/// `"=a"` is an output in `rax`, `"c"` is an input in `rcx`, an operand that is a local register
244/// variable is in the register its declaration named, and a register nothing names is a register
245/// nobody has said anything about. So a write looks among the outputs and a read among the inputs,
246/// and an output written `+` answers for either, since it is read before it is written. See
247/// [`pinned`], which is the one question asked of both ways of saying it.
248///
249/// The other way a read of such a register is said is a matching constraint. `"=a"` on an output
250/// and `"0"` on an input is the program saying that one register holds the input on the way in and
251/// the output on the way out, and it is how a statement fills a register the instruction reads and
252/// writes without writing the register down twice. The letter is on the output, which has no value
253/// to read, and the value is on the input, which has no letter, so neither of them answers this on
254/// its own and the answer is the input: what a read wants is the register the value arrived in, and
255/// that is the input's place.
256///
257/// `None` is a register the instruction uses and the statement put nothing in, which is the usual
258/// answer rather than an unusual one. `cpuid` writes four registers and a program that wanted one
259/// of them names one. See [`Lowering::spare`], which is where that one goes.
260fn bound(list: &[AsmOperand<'_>], reg: PhysReg, role: Role) -> Option<usize> {
261    let named = list.iter().position(|operand| {
262        pinned(operand) == Some(reg)
263            && if role.is_def() { operand.result.is_some() } else { operand.value.is_some() }
264    });
265    if named.is_some() || role.is_def() {
266        return named;
267    }
268    list.iter().position(|operand| {
269        operand.value.is_some()
270            && operand
271                .tied
272                .is_some_and(|at| list.get(at).is_some_and(|out| pinned(out) == Some(reg)))
273    })
274}
275
276/// The register one of an assembly statement's operands is in, whichever of the two ways said it.
277///
278/// A constraint letter is one way and is the only way a program can say one of the six registers
279/// that have a letter. A local register variable is the other, and it is the only way to say any
280/// of the rest: there is no letter for `r12`, which is the whole reason the extension exists, so
281/// the declaration says it and the front end wrote the name into the constraint. The name is read
282/// against this machine's table here, the same place the letter is read against it, and a name the
283/// machine has not got answers nothing, which leaves the operand where an operand nobody placed
284/// goes.
285///
286/// The sigil gcc allows in front of a name is taken off here, because what a name is written with
287/// is syntax and which register it means is this question.
288fn pinned(operand: &AsmOperand<'_>) -> Option<PhysReg> {
289    match operand.named {
290        Some(name) => {
291            let (reg, _) = x86_64::gpr_named(name.strip_prefix('%').unwrap_or(name))?;
292            Some(reg)
293        }
294        None => operand.fixed.and_then(x86_64::gpr_letter),
295    }
296}
297
298/// Why a function could not be lowered.
299///
300/// One reason and then nothing. A function with no rule for something in it is a function this
301/// cannot finish, and the second thing it could not lower is not news.
302#[derive(Debug, Clone, PartialEq, Eq)]
303pub enum Unsupported {
304    /// An instruction no rule fires on.
305    Inst {
306        /// The instruction that stopped it.
307        inst: Inst,
308        /// What the rule file would call it, or nothing if the rule language has no name for it
309        /// at all, which is what an instruction at a width nothing is written about looks like.
310        term: Option<&'static str>,
311        /// The opcode, which is what gets named when the rule language has no word for it.
312        ///
313        /// An opcode the rule language has no word for is exactly the opcode no rule lowers, so
314        /// without this the message would be empty in every case where somebody needs it.
315        opcode: Opcode,
316        /// What it produces, or nothing for an instruction that is only an effect.
317        ty: Option<Type>,
318    },
319    /// A parameter that does not arrive somewhere this can bring it in from.
320    ///
321    /// Not an instruction, which is why it is a separate arm: it is a fact about the signature
322    /// and there is nothing in the body of the function to point at.
323    Argument {
324        /// Its position in the signature.
325        index: usize,
326        /// What is wrong with where it arrives.
327        missing: Missing,
328    },
329    /// A call that passes or gives back a value this cannot put where the convention wants it.
330    Call {
331        /// The call.
332        inst: Inst,
333        /// Which value, and what is wrong with where it travels.
334        refused: Refused,
335    },
336    /// A `return` this cannot put where the convention wants it.
337    ///
338    /// A separate arm from [`Unsupported::Inst`] because it is not an instruction no rule fires
339    /// on. A return of more than one value is built from the convention rather than matched, the
340    /// same way a call is, so what goes wrong with one is what goes wrong with a call and not the
341    /// absence of a rule.
342    Returned {
343        /// The `return`.
344        inst: Inst,
345        /// What is wrong with where one of the values travels.
346        missing: Missing,
347    },
348    /// A stack slot the frame cannot give the bytes it asked for.
349    ///
350    /// Not an instruction no rule covers. An `alloca` is built here rather than matched, so what
351    /// goes wrong with one is what the frame can and cannot hold rather than what the rules spell.
352    Dynamic {
353        /// The `alloca`.
354        inst: Inst,
355        /// What the frame could not do about it.
356        growing: Growing,
357    },
358    /// More parameters of a type that travels on the x87 stack than the stack is deep.
359    ///
360    /// Not an instruction either, for the reason a function's parameter is not one: it is a fact
361    /// about the block and there is nothing in the block to point at. What crosses an edge for one
362    /// of these is the address of where the value is, and the block copies the bytes into a slot
363    /// of its own, all of them through the stack at once so that a block carrying two of them
364    /// swapped is copied in an order that is right. Eight is as many as the stack holds, and a
365    /// ninth would have to be copied before or after the rest, which is the order that could be
366    /// wrong.
367    Phi {
368        /// Which block it arrives at.
369        block: Block,
370        /// How many of them arrive there, which is the whole of what is wrong.
371        count: usize,
372        /// What they are.
373        ty: Type,
374    },
375    /// An `asm` statement this cannot build.
376    ///
377    /// Not an instruction no rule fires on, for the reason a call is not one: what it stands for is
378    /// whatever its template says, and no pattern over terms can read a string.
379    Assembly {
380        /// The `inline_asm`.
381        inst: Inst,
382        /// What about it is not built here yet.
383        refused: Written,
384    },
385    /// A `register long x asm ("...")` naming something this machine has not got.
386    ///
387    /// Not an instruction no rule fires on. There is a rule's worth of instruction here and what
388    /// is wrong is the string beside it, which is a name rather than a term, so the message says
389    /// the name. Which names a machine has is the machine's own question and this is where it is
390    /// asked, at the table a clobber list is read against.
391    Register {
392        /// The `register_value`.
393        inst: Inst,
394        /// The name the program wrote, as it wrote it.
395        name: String,
396    },
397    /// A naked function whose frame is not empty.
398    ///
399    /// Not an instruction no rule fires on, and there is nothing in the body to point at: the
400    /// function asked for no prologue and then wanted bytes only a prologue takes. Refused rather
401    /// than given the bytes anyway, because an offset into a frame nothing set up reaches into
402    /// whatever the caller left below its own stack pointer, which is wrong code that assembles.
403    /// See [`crate::frame::Layout::naked`].
404    Naked {
405        /// How many bytes it wanted, which is the whole of what is wrong.
406        bytes: u32,
407    },
408}
409
410/// What about an `asm` statement is not built yet.
411#[derive(Debug, Clone, Copy, PartialEq, Eq)]
412pub enum Written {
413    /// A template with instructions in it.
414    Template,
415    /// An `asm goto`, whose labels make the statement a terminator.
416    Goto,
417    /// An operand this cannot put where the constraint says it goes.
418    Operand,
419    /// A clobber list naming something this has no register for.
420    Clobber,
421    /// A `jmp` out of the function in a function that has an epilogue behind it.
422    Away,
423}
424
425impl Written {
426    /// The rest of the sentence that starts with the statement.
427    #[must_use]
428    pub fn why(self) -> &'static str {
429        match self {
430            // The template is the assembler's to read and there is no assembler here yet, so a
431            // template with anything in it is a string nothing can turn into bytes. An empty one is
432            // no instructions, and no instructions is something this can write.
433            Written::Template => "has instructions in its template, which nothing here assembles",
434            Written::Goto => "jumps to a label, which nothing here builds an edge for",
435            Written::Operand => "has an operand this cannot place",
436            Written::Clobber => "says it destroys a register this has no name for",
437            Written::Away => {
438                "jumps out of the function, which only a function that is `naked` may do, since \
439                 anywhere else there is an epilogue behind it to give the frame back"
440            }
441        }
442    }
443}
444
445/// What the frame could not do about a stack slot.
446#[derive(Debug, Clone, Copy, PartialEq, Eq)]
447pub enum Growing {
448    /// An object of a size the number a frame counts bytes in does not reach.
449    Huge,
450    /// A variable length array wanting more alignment than a call leaves the stack pointer with.
451    ///
452    /// Rounding the stack pointer down again after the bytes have been taken would put it
453    /// somewhere no constant reaches the rest of the frame from, so a frame like this needs a
454    /// second base register held for the whole of the function. Nothing here holds one.
455    ///
456    /// [`crate::expand::rounds`] takes the array away before this sees it, by asking for the
457    /// alignment in extra bytes and handing out an address inside them, so what is left of this
458    /// is IR that arrived without going through that pass and the fixed local in
459    /// [`crate::pipeline`] that wants the same thing from the other side.
460    Aligned,
461    /// A variable length array in a function written without a prologue.
462    ///
463    /// A frame that grows is reached from a frame pointer, and establishing one is the first two
464    /// instructions of a prologue that `__attribute__((naked))` asked there be none of. See
465    /// [`crate::frame::Layout::naked`].
466    Naked,
467}
468
469impl Growing {
470    /// The rest of the sentence that starts with the slot.
471    #[must_use]
472    pub fn why(self) -> &'static str {
473        match self {
474            Growing::Huge => "is more bytes than a frame counts",
475            Growing::Aligned => {
476                "wants more alignment than the stack pointer is left on, which needs a base \
477                 register nothing here keeps"
478            }
479            Growing::Naked => {
480                "is in a function that is `naked`, which has no prologue to point a frame pointer \
481                 at it with"
482            }
483        }
484    }
485}
486
487impl Unsupported {
488    /// The instruction it is about, or nothing for the one arm that is about a signature.
489    ///
490    /// What a caller wants this for is the span. The function knows where every instruction in
491    /// it came from, so a caller holding both can point a message at the line somebody wrote
492    /// rather than at the file as a whole, and nothing here has to carry a span of its own.
493    pub fn inst(&self) -> Option<Inst> {
494        match *self {
495            Unsupported::Inst { inst, .. }
496            | Unsupported::Call { inst, .. }
497            | Unsupported::Returned { inst, .. }
498            | Unsupported::Dynamic { inst, .. }
499            | Unsupported::Assembly { inst, .. }
500            | Unsupported::Register { inst, .. } => Some(inst),
501            Unsupported::Argument { .. } | Unsupported::Phi { .. } | Unsupported::Naked { .. } => {
502                None
503            }
504        }
505    }
506}
507
508impl fmt::Display for Unsupported {
509    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
510        match *self {
511            Unsupported::Inst { term: Some(term), .. } => write!(f, "no rule lowers `{term}`"),
512            Unsupported::Inst { term: None, opcode, ty: Some(ty), .. } => {
513                write!(f, "no rule lowers a `{opcode}` producing a `{ty}`")
514            }
515            Unsupported::Inst { term: None, opcode, ty: None, .. } => {
516                write!(f, "no rule lowers a `{opcode}`")
517            }
518            Unsupported::Argument { index, missing } => {
519                write!(f, "parameter {index} {}", missing.why())
520            }
521            Unsupported::Call { refused: Refused { argument: Some(index), missing }, .. } => {
522                write!(f, "argument {index} of this call {}", missing.why())
523            }
524            Unsupported::Call { refused: Refused { argument: None, missing }, .. } => {
525                write!(f, "what this call gives back {}", missing.why())
526            }
527            Unsupported::Returned { missing, .. } => {
528                write!(f, "what this function gives back {}", missing.why())
529            }
530            Unsupported::Dynamic { growing, .. } => {
531                write!(f, "this local {}", growing.why())
532            }
533            Unsupported::Phi { block, count, ty } => {
534                let block = block.index();
535                write!(
536                    f,
537                    "block{block} takes {count} parameters of type `{ty}` and only {X87_DEPTH} can cross an edge at once"
538                )
539            }
540            Unsupported::Assembly { refused, .. } => write!(f, "this `asm` {}", refused.why()),
541            Unsupported::Register { ref name, .. } => {
542                write!(
543                    f,
544                    "this object is kept in `{name}`, which is not a register this machine has"
545                )
546            }
547            Unsupported::Naked { bytes } => write!(
548                f,
549                "this function is `naked` and wants {bytes} bytes of frame, which there is no prologue to take"
550            ),
551        }
552    }
553}
554
555impl std::error::Error for Unsupported {}
556
557/// A lowered function, and what the frame needs that the machine IR does not hold.
558#[derive(Debug)]
559pub struct Lowered {
560    /// The function, in machine instructions.
561    pub func: mir::Func,
562    /// What it wants its stack to look like, which is separate from the function so that the two
563    /// can be read and written at the same time.
564    pub stack: Stack,
565    /// Which rules of the table lowered it, which is what `-Zrule-coverage` asks for and what
566    /// `crate::coverage` writes down.
567    pub fired: Fired,
568    /// Which machine IR block each IR block became, indexed by the IR block's own index, and
569    /// nothing for a block the walk never reached.
570    ///
571    /// Here because it is the only place the correspondence exists. Selection makes one block per
572    /// block, in the same order and with the arms in the same order, so anything the IR knows
573    /// about a block can be carried down through this and nothing else, and
574    /// [`crate::weights::carry`] is what does.
575    pub blocks: Vec<Option<mir::Block>>,
576}
577
578/// What a function's stack has to hold, as far as selection is able to say.
579///
580/// All of it is answered here because selection is where a call is built and where an `alloca`
581/// is read, and nothing after it could tell what either of them needed.
582#[derive(Debug, Default)]
583pub struct Stack {
584    /// How many bytes the widest call in the function needs below the stack pointer for the
585    /// arguments it passes there, or `None` for a function that makes no call at all.
586    ///
587    /// `None` is a leaf, which is the function that may use the red zone and the one whose stack
588    /// pointer does not have to be left aligned for anybody.
589    pub calls: Option<u32>,
590    /// The memory the function asked for itself, one entry for every `alloca` in it, in the order
591    /// the walk reached them.
592    pub locals: Vec<Local>,
593    /// Which instruction computes the address of which of those locals.
594    ///
595    /// An address in the frame is a distance from the stack pointer, and there is no frame until
596    /// after allocation, so the instruction is written here with nothing in its displacement and
597    /// [`crate::finish`] writes the number in once [`crate::frame::Frame`] knows it.
598    pub addresses: Vec<(mir::Inst, usize)>,
599    /// Which of those locals is which declaration in the source, for the ones the program declared.
600    ///
601    /// The number is the one the IR function carries and means nothing here. What it is for is the
602    /// debugging information, which has to say where a named local ended up and cannot ask the
603    /// frame directly: the frame knows a local by the order the `alloca` for it was lowered in and
604    /// by nothing else.
605    ///
606    /// Shorter than the list above rather than the same length, because most of what a function
607    /// keeps in its frame is memory an expression wanted somewhere to put.
608    pub declared: Vec<(usize, u32)>,
609    /// Which instruction computes the address of a piece of memory whose size the function works
610    /// out while it runs, which is what a variable length array is.
611    ///
612    /// Waiting on [`crate::finish`] for a different number from the one the addresses above are:
613    /// the bytes were taken off the stack pointer by the instruction in front of this one, so where
614    /// they start is however much of the bottom of the frame belongs to the arguments of a call,
615    /// and that is not known until the frame is.
616    pub dynamic: Vec<mir::Inst>,
617    /// Which instruction takes those bytes off the stack pointer, one for every one of them, in the
618    /// order the walk reached them.
619    ///
620    /// Read by [`crate::finish`] on a command line that asked for the stack to be touched a page at
621    /// a time, which is the one thing that has to find these again: the bytes are in a register by
622    /// then, so the walk down to them is a loop, and a loop is written around an instruction rather
623    /// than in front of a block. Nothing else looks at them, because everything else about a frame
624    /// that grows is answered by the address the instruction below this one computes.
625    pub grown: Vec<mir::Inst>,
626    /// Where the function first moves the stack pointer while it runs, if it does at all.
627    ///
628    /// Two things are read off this. One is whether at all, which is what [`crate::frame::Layout`]
629    /// wants, because a frame that moves its stack pointer has a different shape from one that does
630    /// not and the layout is built before the instructions are looked at again. See `Growing` in
631    /// [`crate::frame`]. The other is where, so that a caller that cannot accept such a frame has
632    /// somewhere to point when it says so.
633    pub grown_at: Option<Inst>,
634    /// Which instruction reads which of the arguments the caller passed on the stack, as how far up
635    /// the caller's argument area it reads.
636    ///
637    /// Waiting on [`crate::finish`] for the same reason the addresses above are, and on one thing
638    /// more: where the caller's argument area is from inside this function depends on whether the
639    /// prologue had to force the stack pointer's alignment, so which register the load reads
640    /// through is not settled here either.
641    pub arguments: Vec<(mir::Inst, u32)>,
642    /// Whether the function asked where its own frame is, which is what `__builtin_frame_address`
643    /// and `__builtin_return_address` both start from.
644    ///
645    /// A function like that keeps a frame pointer whatever the flags say, because the register is
646    /// the answer to the first of them and the start of the walk for every depth above zero. There
647    /// is no other way to reach it: the distance from the stack pointer to the frame is a number
648    /// the layout works out, and what a walk up the chain needs is the link the prologue saved.
649    pub walks_frames: bool,
650    /// Whether the function saved a place for a `__builtin_longjmp` to come back to, which is what
651    /// `__builtin_setjmp` does.
652    ///
653    /// A function like that keeps a frame pointer whatever the flags say as well, and for a reason
654    /// of the same shape: the two registers the restore puts back are the frame pointer and the
655    /// stack pointer, and a frame that did not keep the first of them has nothing in it saying
656    /// where the caller's frame is for the epilogue to find after control has come back.
657    pub saves_place: bool,
658}
659
660impl Stack {
661    /// The layout given, with the three fields only the lowering knows the answer to filled in.
662    ///
663    /// Everything else in a layout comes from the flags the function is compiled under or from the
664    /// allocation, so this takes one and returns it rather than building one.
665    ///
666    /// A function that saved a place is not a leaf whatever it called. What a leaf buys is the red
667    /// zone, which is the words below the stack pointer nothing else may write, and a function
668    /// control comes back into from a `__builtin_longjmp` has already had something else running
669    /// down there: whatever it called and whatever that called, or a signal handler on the same
670    /// stack. Every one of those has written over the red zone by the time control arrives, so a
671    /// value this function left there would not be there any more.
672    #[must_use]
673    pub fn layout<'a>(&'a self, base: Layout<'a>) -> Layout<'a> {
674        Layout {
675            leaf: self.calls.is_none() && !self.saves_place,
676            outgoing: self.calls.unwrap_or(0),
677            locals: &self.locals,
678            grows: self.grown_at.is_some(),
679            ..base
680        }
681    }
682}
683
684/// The x86-64 machine IR for that function.
685///
686/// # Errors
687///
688/// The first instruction no rule fires on, which today is anything at a width the rule set is not
689/// written at, a parameter that does not arrive in a register this can read, or a call that
690/// passes something this cannot put where the convention wants it.
691pub fn func(
692    source: &Func,
693    names: &mut Interner,
694    conv: &'static CallRegs,
695    elsewhere: &Elsewhere,
696) -> Result<Lowered, Unsupported> {
697    Lowering::new(source, names, conv, elsewhere).run()
698}
699
700/// What the matcher settled on for one block, indexed the way the block's instructions are.
701struct Decided {
702    /// What each instruction matched, and nothing for one that matched no rule or was folded
703    /// into a later one.
704    found: Vec<Option<Match<Term>>>,
705    /// How each instruction showed its operands to the matcher, which is what says what it took.
706    plans: Vec<Option<Plan>>,
707    /// The instructions some other instruction took, which are the ones with nothing to write.
708    folded: Vec<Inst>,
709}
710
711/// One function being lowered.
712struct Lowering<'a> {
713    source: &'a Func,
714    names: &'a mut Interner,
715    out: mir::Func,
716    /// The machine register each IR value is in, once it has one.
717    regs: Vec<Option<mir::Reg>>,
718    /// For a constant that has been written into a register, the block it was written into,
719    /// which is the only block that register is any good in.
720    written: Vec<Option<mir::Block>>,
721    /// How many times each IR value is read, which is what says whether an instruction may be
722    /// folded into the one that reads it.
723    uses: Vec<u32>,
724    /// The block being filled.
725    at: Option<mir::Block>,
726    /// The machine IR block each IR block became.
727    blocks: Vec<Option<mir::Block>>,
728    /// The class an address is in, which is the general purpose one and is not a question: every
729    /// register an addressing mode names holds part of an address, and there is no machine here
730    /// that computes an address anywhere but in this file. Which class a *value* is in is
731    /// [`Lowering::class_of`], and it is a question, because a float is in the other one.
732    gpr: RegClass,
733    /// Where the convention this function is compiled for puts things, which is read for the
734    /// arguments and for the calls.
735    conv: &'static CallRegs,
736    /// Which names this function may not work an address out for itself, which is a fact about the
737    /// module and so is worked out before any of this and handed in.
738    elsewhere: &'a Elsewhere,
739    /// What the function wants its stack to look like, filled in as the walk finds out.
740    stack: Stack,
741    /// What a `va_start` in this function has to write, or nothing for a function that takes no
742    /// arguments its signature does not name.
743    ///
744    /// Worked out once, when the entry block binds the parameters, because every number in it is
745    /// about where those parameters left the walk over the argument registers and there is nowhere
746    /// else that knows.
747    varargs: Option<Varargs>,
748    /// Which of the function's stack objects each eighty bit value lives in, once it has asked
749    /// for one.
750    ///
751    /// One slot per value and it is never given back, which is what makes an eighty bit value
752    /// behave like every other one: it is written once and read wherever it is read, and no two
753    /// of them share a slot the way two of them would share a register. What is in a register is
754    /// the address, and that is worked out again at every use rather than kept, so nothing here
755    /// holds a general purpose register open across a whole function.
756    slots: Vec<Option<usize>>,
757    /// The eight bytes a value passes through between a register and the x87 stack, once
758    /// something has wanted them.
759    ///
760    /// One for the whole function, because every group that uses it is a handful of instructions
761    /// with nothing in between: the bytes are written, read straight back and never looked at
762    /// again, so a second slot would be a second slot holding the same nothing.
763    crossing: Option<usize>,
764    /// The four bytes the control word is saved in and the changed copy written to, once
765    /// something has wanted them.
766    ///
767    /// One for the whole function for the reason above, and four rather than two because it is
768    /// two words: the one the unit had and the one with the rounding field turned to truncate.
769    control: Option<usize>,
770    /// The word a `__builtin_setjmp` in this function answers with, once one has asked for it.
771    ///
772    /// One for the whole function however many saves there are in it, because the word is written
773    /// and read back with nothing in between: the save writes a zero into it and the instruction
774    /// straight after reads it, and the only other thing that ever writes it is a restore arriving
775    /// between those two. Two saves sharing it is two pairs each doing that, and neither can be
776    /// inside the other.
777    answer: Option<usize>,
778    /// Which rules have fired so far.
779    fired: Fired,
780}
781
782/// What a `va_start` in a variadic function writes into the list it is given.
783///
784/// Two shapes, because two conventions describe a list two ways, and [`crate::varargs`] is where
785/// both are written down. Neither is a set of numbers on its own: where the save area is and where
786/// the caller's argument area is are distances into a frame that does not exist until after
787/// allocation, so each is a `lea` [`crate::finish`] fills in.
788#[derive(Debug, Clone, Copy, PartialEq, Eq)]
789enum Varargs {
790    /// The four field list, whose two offsets are settled here and whose two addresses are not.
791    Fields {
792        /// Which of the function's stack objects is the register save area.
793        save: usize,
794        /// How far up the caller's argument area the first argument the signature does not name is,
795        /// which is the whole of that area the named ones did not take.
796        incoming: u32,
797        /// What `gp_offset` starts at, which is past the general purpose registers the named
798        /// arguments took.
799        integers: u32,
800        /// What `fp_offset` starts at, which is past the vector ones.
801        floats: u32,
802    },
803    /// The list that is a pointer, which is the one address and nothing else.
804    Pointer {
805        /// How far up the caller's argument area the first argument the signature does not name is,
806        /// which on this convention is the word belonging to the position the named ones stopped
807        /// at.
808        incoming: u32,
809    },
810}
811
812/// How far a function's name reaches, narrowed from the linkage the IR gave it.
813///
814/// The IR has five and an object file says three, and the two the linker cannot tell apart are
815/// the two weak ones: which of them a symbol had is a fact the optimizer reads and the linker has
816/// no way to record. A function is never `Common`, since that is what a tentative definition of an
817/// object is and there is no tentative definition of a function, and it is written here rather
818/// than left out so that a linkage added later has to come past this.
819const fn binding(linkage: Linkage) -> mir::Binding {
820    match linkage {
821        Linkage::Internal => mir::Binding::Local,
822        Linkage::Weak | Linkage::LinkOnce => mir::Binding::Weak,
823        Linkage::External | Linkage::Common => mir::Binding::Global,
824    }
825}
826
827/// How far a function's name reaches outside a shared library, carried across unchanged.
828///
829/// Nothing is narrowed here the way [`binding`] narrows the linkage, because ELF records all
830/// three of these and the two enumerations are the same three answers written twice: once in a
831/// crate that is not allowed to know what an object file is and once in one that is.
832const fn visibility(visibility: Visibility) -> mir::Visibility {
833    match visibility {
834        Visibility::Default => mir::Visibility::Default,
835        Visibility::Hidden => mir::Visibility::Hidden,
836        Visibility::Protected => mir::Visibility::Protected,
837    }
838}
839
840impl<'a> Lowering<'a> {
841    fn new(
842        source: &'a Func,
843        names: &'a mut Interner,
844        conv: &'static CallRegs,
845        elsewhere: &'a Elsewhere,
846    ) -> Self {
847        let counts = source.counts();
848        let name = source.name;
849        let mut uses = vec![0; counts.values];
850        for block in source.blocks() {
851            for inst in source.insts(block) {
852                for &arg in &source[source[inst].args] {
853                    uses[arg.index()] += 1;
854                }
855                for call in source.successors(inst) {
856                    for &arg in &source[call.args] {
857                        uses[arg.index()] += 1;
858                    }
859                }
860            }
861        }
862        let mut out = mir::Func::new(name);
863        out.align = source.align;
864        // Carried rather than worked out here, because where a function was declared is a fact
865        // about the source and this is a long way past it. What wants it is the line table.
866        out.declared = source.declared;
867        out.binding = binding(source.linkage);
868        out.visibility = visibility(source.visibility);
869        Self {
870            source,
871            names,
872            out,
873            regs: vec![None; counts.values],
874            written: vec![None; counts.values],
875            blocks: vec![None; counts.blocks],
876            uses,
877            at: None,
878            gpr: x86_64::GPR,
879            conv,
880            elsewhere,
881            stack: Stack::default(),
882            varargs: None,
883            slots: vec![None; counts.values],
884            crossing: None,
885            control: None,
886            answer: None,
887            fired: Fired::new(),
888        }
889    }
890
891    fn run(mut self) -> Result<Lowered, Unsupported> {
892        // Every block before any of them is filled, because a block that jumps forward has to
893        // name the block it jumps to and a machine IR block is named by a handle rather than by
894        // the IR block it came from.
895        for block in self.source.blocks() {
896            let out = self.out.create_block();
897            self.blocks[block.index()] = Some(out);
898        }
899        for block in self.order() {
900            self.block(block)?;
901        }
902        // And the name each block an image holds the address of was given, which nothing in the
903        // walk above would ask for: the `lea` a label address is inside the function needs no
904        // symbol, and the one thing that does is a relocation in another section.
905        let named: Vec<(Block, Symbol)> = self.source.named_blocks().collect();
906        let labels: Vec<(mir::Block, Symbol)> =
907            named.into_iter().map(|(block, name)| (self.out_block(block), name)).collect();
908        self.out.labels = labels;
909        self.naming();
910        Ok(Lowered { func: self.out, stack: self.stack, fired: self.fired, blocks: self.blocks })
911    }
912
913    /// Which register each declaration the front end kept in a value ended up in, as far as this
914    /// walk can say, which is the other half of what [`Lowering::new_reg`] writes down as it goes.
915    ///
916    /// Two halves because there are two ways a value gets a register here. Most of them ask for a
917    /// fresh one and that is where `new_reg` catches them, and the rest are put in a register
918    /// something else chose: a parameter arrives in whichever one the convention handed it, a block
919    /// parameter in whichever one the edge agreed on, and a result of a rule that names its own
920    /// registers in the one the rule named. None of those goes past the mint, so this is the map at
921    /// the end read off the other side, and the two together are every value a declaration is
922    /// behind.
923    ///
924    /// The map on its own would not do, which is why `new_reg` writes down what it writes down: the
925    /// entry for a constant is cleared every time the walk leaves the block that wrote it, so a
926    /// local a constant holds is in the map for one block of the function and nowhere else.
927    fn naming(&mut self) {
928        let mut named = std::mem::take(&mut self.out.named);
929        for value in self.source.values() {
930            let Some(reg) = self.regs[value.index()] else { continue };
931            named.extend(self.source.value_decls(value).map(|decl| (decl, reg)));
932        }
933        named.sort_unstable();
934        named.dedup();
935        self.out.named = named;
936    }
937
938    /// The order the blocks are filled in, which is not the order they are written in.
939    ///
940    /// Reverse postorder, because a value is written in a block that dominates every block that
941    /// reads it and a block in reverse postorder comes before every block it dominates. The order
942    /// the blocks are written in does not have that property: a block written early can read a
943    /// value a block below it writes, and reading a value with no register yet mints one, so the
944    /// register the definition writes later is not the register the read named. Nothing writes the
945    /// one the read named, and what comes out is a function that loads a stack slot no store ever
946    /// reached. It is the order this walk goes in rather than the order the blocks come out in,
947    /// which is what the loop above fixes, so the machine function is still written the way the IR
948    /// function was.
949    ///
950    /// Blocks the entry does not reach come last, in the order they are written in. Nothing runs
951    /// them and nothing they name is read by anything that does, but they still have to be filled,
952    /// because a machine block with no terminator is not one the passes below can read.
953    fn order(&self) -> Vec<Block> {
954        let Some(entry) = self.source.entry() else { return self.source.blocks().collect() };
955        let count = self.blocks.len();
956        let mut succs: Vec<Vec<Block>> = vec![Vec::new(); count];
957        for block in self.source.blocks() {
958            let Some(term) = self.source.terminator(block) else { continue };
959            succs[block.index()] = self.source.successors(term).map(|call| call.block).collect();
960        }
961        // An explicit stack, because the depth of the walk is the number of blocks and a function
962        // built by a generator has as many of those as it likes.
963        let mut seen = vec![false; count];
964        let mut order = Vec::with_capacity(count);
965        let mut stack = vec![(entry, 0usize)];
966        seen[entry.index()] = true;
967        while let Some((block, at)) = stack.pop() {
968            let Some(&next) = succs[block.index()].get(at) else {
969                order.push(block);
970                continue;
971            };
972            stack.push((block, at + 1));
973            if !seen[next.index()] {
974                seen[next.index()] = true;
975                stack.push((next, 0));
976            }
977        }
978        order.reverse();
979        order.extend(self.source.blocks().filter(|block| !seen[block.index()]));
980        order
981    }
982
983    /// One block: its parameters, then every instruction in it that is not folded into another.
984    fn block(&mut self, block: Block) -> Result<(), Unsupported> {
985        let out = self.out_block(block);
986        self.at = Some(out);
987        if self.source.entry() == Some(block) {
988            self.arrive(block, out)?;
989        } else {
990            let mut arriving = Vec::new();
991            for &param in &self.source[block].params {
992                // A value with no register to arrive in, which the class would not say, since
993                // `class_of` puts one of these in the general purpose file on purpose and what it
994                // means by that is that nothing there can hold it. What crosses the edge for one
995                // of those is the address of where the value already is, so the parameter is a
996                // pointer here and the bytes it points at are copied below.
997                let ty = self.source[param].ty;
998                let reg = self.out.append_param(out, self.class_of(ty));
999                self.regs[param.index()] = Some(reg);
1000                if on_x87(ty) {
1001                    arriving.push((param, reg));
1002                }
1003            }
1004            self.settle(block, &arriving)?;
1005        }
1006
1007        // What each instruction matched, and which instructions were folded into another. The
1008        // decision is made for the whole block before any of it is written, and it is made more
1009        // than once: a value that only some of its readers took has to be put back in a register
1010        // for all of them, and taking it away from those readers changes what they match.
1011        let insts: Vec<Inst> = self.source.insts(block).collect();
1012        let mut refused: HashSet<Value> = HashSet::new();
1013        let mut decided = self.decide(&insts, &refused);
1014        while let Some(value) = self.left_alive(&insts, &decided.plans) {
1015            refused.insert(value);
1016            decided = self.decide(&insts, &refused);
1017        }
1018        let Decided { found, folded, .. } = decided;
1019
1020        for (&inst, matched) in insts.iter().zip(found) {
1021            if folded.contains(&inst) || self.writes_nothing(inst) {
1022                continue;
1023            }
1024            // A call is built from the convention rather than matched, which is why it is the one
1025            // opcode looked at by name here. Through an address it is a different instruction and
1026            // the same convention, so the two arrive at the same place and differ in one line of
1027            // it.
1028            match self.source[inst].opcode {
1029                Opcode::Call | Opcode::CallIndirect => {
1030                    self.called(inst)?;
1031                    continue;
1032                }
1033                // Built from the frame rather than matched, for the same shape of reason a call
1034                // is built from the convention: what a rule replaces a term with is instructions,
1035                // and what an `alloca` needs first is bytes, which the rule language has no way
1036                // to ask for.
1037                Opcode::Alloca => {
1038                    self.reserve(inst)?;
1039                    continue;
1040                }
1041                // Reading the stack pointer and writing it back, which are the two ends of a scope
1042                // holding a variable length array. Built here for the reason an `alloca` is: the
1043                // value is a register the rule language has no way to name, because what it holds
1044                // is not a value the program computed but where the machine's stack had got to.
1045                Opcode::StackSave => {
1046                    self.stack_pointer(inst, false)?;
1047                    continue;
1048                }
1049                Opcode::StackRestore => {
1050                    self.stack_pointer(inst, true)?;
1051                    continue;
1052                }
1053                // The address of a name, built here for the same reason an `alloca` is: what a
1054                // rule replaces a term with is instructions over values, and the operand of this
1055                // one is a symbol, which is a thing the rule language has no way to bind and the
1056                // solver has no way to say anything about. There is nothing in `lea sym(%rip)` a
1057                // proof over bitvectors could discharge, because what makes it the right answer
1058                // is the relocation and what the linker does with it.
1059                Opcode::GlobalAddr => {
1060                    self.address_of(inst)?;
1061                    continue;
1062                }
1063                // The address of a label and the branch that reads one, built here for the same
1064                // reason and for one more. The reason is the same: what the first of them names is
1065                // a block, which is not a value a rule pattern can bind, and there is nothing in
1066                // the distance between two places in one function that a proof over bitvectors
1067                // could discharge. The extra one is that the second is a terminator whose arms are
1068                // not two and not fixed, and a rule says what an instruction reads rather than
1069                // where a block goes.
1070                Opcode::BlockAddr => {
1071                    self.block_address(inst)?;
1072                    continue;
1073                }
1074                Opcode::IndirectBr => {
1075                    self.indirect_branch(inst)?;
1076                    continue;
1077                }
1078                // The pair that saves a place in this function and comes back to it. Built here
1079                // for the reason the address of a label is, and for two more. The reason is the
1080                // same: the first of them writes down where control comes back to, which is a
1081                // place in this function and not a value a rule pattern can bind. The extra ones
1082                // are that each of them is a group of instructions over a buffer the program owns
1083                // rather than one instruction, and that the first of them leaves the block it was
1084                // written in and carries on in a new one, which is a thing no rule can do.
1085                Opcode::SetjmpMarker => {
1086                    self.saves_place(inst)?;
1087                    continue;
1088                }
1089                Opcode::LongjmpMarker => {
1090                    self.comes_back(inst)?;
1091                    continue;
1092                }
1093                // Where this thread's own storage starts, built here for a reason of the same
1094                // shape: what it reads is `%fs`, which is not a register the rule language can
1095                // bind and not one a proof over bitvectors could say anything about, because what
1096                // makes the load the right answer is an agreement between the loader and the C
1097                // library rather than any arithmetic.
1098                Opcode::ThreadPointer => {
1099                    self.thread_pointer(inst)?;
1100                    continue;
1101                }
1102                // What a named machine register holds, built here for the reason above written
1103                // about any register rather than about one: which register it is is a string
1104                // beside the instruction, and a rule matches on an opcode and a type and could
1105                // not see it. There is nothing to prove either, since the answer is the register
1106                // and the instruction is the move that reads it.
1107                Opcode::RegisterValue => {
1108                    self.register_value(inst)?;
1109                    continue;
1110                }
1111                // Where a frame is and what it returns to, built here for the same reason and one
1112                // more. The reason is the same: what the walk starts from is the frame pointer,
1113                // which is not a register a rule pattern can bind, and there is nothing in reading
1114                // the link the prologue saved that a proof over bitvectors could discharge. The
1115                // extra one is that how long the walk is comes out of a number beside the
1116                // instruction, so one of these is not one instruction but however many the depth
1117                // says, and a rule replaces a term with a term.
1118                Opcode::FrameAddress | Opcode::ReturnAddress => {
1119                    self.frames(inst)?;
1120                    continue;
1121                }
1122                // Built from the frame for the reason an `alloca` is, and from the convention for
1123                // the reason a call is: three of the four fields it writes are distances that do
1124                // not exist until the frame does, and the fourth is where the walk over the
1125                // argument registers stopped. A function that is not variadic has no such walk to
1126                // report, so it has nothing here and is refused below, which is the right answer
1127                // for a `va_start` in one.
1128                Opcode::VaStart if self.varargs.is_some() => {
1129                    self.va_start(inst)?;
1130                    continue;
1131                }
1132                // A return of more than one value, which is a structure small enough to come
1133                // back in a pair of registers. Built from the convention for the reason a call
1134                // is: which register each half goes in depends on the halves in front of it,
1135                // because the two register files are walked separately, and a pattern over a term
1136                // cannot see them. A return of one value is a term with a name and a rule, and it
1137                // stays one.
1138                //
1139                // A return of none in a function whose answer went through memory is here too,
1140                // and for a different reason: what it gives back is not written in the IR at all.
1141                // The convention says the address the caller handed over comes back, and only the
1142                // signature says this function was handed one.
1143                //
1144                // And a return of one eighty bit value, for a third reason: what a rule would
1145                // write is an instruction leaving the value in a register, and this one is left on
1146                // the x87 stack instead. A rule could not name that stack any more than any other
1147                // rule about this type could.
1148                Opcode::Return
1149                    if self.source[self.source[inst].args].len() > 1
1150                        || self.sret().is_some()
1151                        || self.gives_back_x87(inst) =>
1152                {
1153                    self.returned(inst)?;
1154                    continue;
1155                }
1156                // A cast between a pointer and an integer of the same width, which on this
1157                // machine is every one the front end writes. No instruction at all, so no rule
1158                // could name one.
1159                Opcode::PtrToInt | Opcode::IntToPtr => {
1160                    self.rename(inst)?;
1161                    continue;
1162                }
1163                // A barrier, which is one instruction or none depending on the ordering. Written
1164                // by name because there is nothing about it a rule could be proved against, the
1165                // way there is nothing to prove about the address of a symbol.
1166                Opcode::Fence => {
1167                    self.barrier(inst)?;
1168                    continue;
1169                }
1170                // A hint, written by name for the reason a barrier is and one step further: not
1171                // only is there no equality for a proof to discharge, there is nothing about the
1172                // program around it either. Which of the four instructions it is comes out of the
1173                // number the builtin was given, which is beside the instruction rather than in it.
1174                Opcode::Prefetch => {
1175                    self.hint(inst)?;
1176                    continue;
1177                }
1178                // Stopping, written by name for the first half of the barrier's reason: it
1179                // computes nothing, so there is no term for a rule to replace, and what makes it
1180                // right is what the operating system does with the fault rather than anything a
1181                // proof over bitvectors could discharge.
1182                Opcode::Trap => {
1183                    self.trap(inst);
1184                    continue;
1185                }
1186                // A compare and exchange, which is written by name because it produces two values
1187                // and a rule produces one. The replacement of a rule is one term, a term names the
1188                // value an instruction computes, and there is no way in that language to say that
1189                // an instruction leaves an answer in one place and a yes or no in another.
1190                Opcode::Cmpxchg => {
1191                    self.exchange(inst)?;
1192                    continue;
1193                }
1194                // A read modify write, which is written by name for a different reason: it produces
1195                // one value, so a rule could name it, and what it does is not in the head a rule
1196                // matches on. Every one of the thirteen operations is the same opcode at the same
1197                // type and differs only in what is carried beside it, so one pattern would be all
1198                // thirteen patterns. Of the thirteen only the three with an instruction reach here,
1199                // since `crate::retry` turned the rest into loops a long way above this.
1200                Opcode::AtomicRmw => {
1201                    self.modify(inst)?;
1202                    continue;
1203                }
1204                // An `asm` statement, whose lowering is its template and there is no term for a
1205                // string. Written by name for the reason a barrier is, and before the x87 arm
1206                // below so that an `asm` holding a `long double` is refused as the `asm` it is
1207                // rather than as an instruction nothing computes.
1208                Opcode::InlineAsm => {
1209                    self.assembly(inst)?;
1210                    continue;
1211                }
1212                // Anything at all with an eighty bit float in it, which is the one arm here
1213                // chosen by a type rather than by an opcode, because what makes these different
1214                // is not what they do but where the value is. A `long double` has no register,
1215                // so it has no name in `crate::term` and no rule could bind one: every one of
1216                // these is a group of instructions over a frame slot, written out below.
1217                //
1218                // Last of the arms, so that a call and a return with one of these in them reach
1219                // the convention first and are refused by it, which is the truer answer: what is
1220                // wrong there is where the value has to travel and not that nothing can compute
1221                // it.
1222                _ if self.touches_x87(inst) => {
1223                    self.x87(inst)?;
1224                    continue;
1225                }
1226                _ => {}
1227            }
1228            let matched = matched.ok_or_else(|| self.unsupported(inst))?;
1229            self.emit(inst, &matched)?;
1230            // After it is built rather than when it matched, so that what is recorded is the rules
1231            // this function was lowered by and not the rules something was tried with.
1232            self.fired.mark(matched.rule);
1233        }
1234        // Whichever block the walk ended in rather than the one it started in. The two are the
1235        // same block for every function that does not save a place for a `__builtin_longjmp`, and
1236        // where they differ it is the last of them that the terminator and the arms belong to.
1237        // See [`Self::saves_place`].
1238        let last = self.at.expect("a block is being filled");
1239        self.edges(block, last)
1240    }
1241
1242    /// One call, which is built from the convention rather than matched against the table for the
1243    /// same reason the arguments of the function itself are.
1244    ///
1245    /// The arguments are read before the call is built, which is what materializes a constant
1246    /// argument into a register, since no call passes an immediate.
1247    ///
1248    /// A call to a name and a call through an address are both here, and what tells them apart is
1249    /// the opcode rather than whether a callee was recorded, which is the same thing the verifier
1250    /// reads. Through an address the first operand is the address and the arguments are the ones
1251    /// behind it, and everything after that is the same: where each argument goes, where the value
1252    /// comes back and which registers are gone across it are the convention's answers and the
1253    /// convention does not ask what is being called.
1254    fn called(&mut self, inst: Inst) -> Result<(), Unsupported> {
1255        let data = &self.source[inst];
1256        let Extra::Call(info) = data.extra else { return Err(self.unsupported(inst)) };
1257        let info = self.source[info];
1258        let indirect = data.opcode == Opcode::CallIndirect;
1259
1260        let values: Vec<Value> = self.source[data.args].to_vec();
1261        let callee = if indirect {
1262            let &address = values.first().ok_or_else(|| self.unsupported(inst))?;
1263            abi::Callee::Through(self.reg_of(address)?)
1264        } else {
1265            abi::Callee::Named(info.callee.ok_or_else(|| self.unsupported(inst))?)
1266        };
1267
1268        // What the ABI asks of each argument, read out before any of them is, because reading one
1269        // borrows the function this is a table in. The ones the signature names are the signature's
1270        // answer and the ones behind them are the call's, which is where a structure passed to a
1271        // variadic callee by value says that its bytes travel: there is no parameter to say it on.
1272        let signature = &self.source[info.signature];
1273        let variadic = signature.variadic;
1274        let named: Vec<Abi> = signature.params.iter().map(|param| param.abi).collect();
1275        let beyond: Vec<Abi> = self.source[info.varargs].to_vec();
1276        // Every value that comes back and not only the first. A structure small enough to travel
1277        // in registers comes back in up to two of them, and which register each half is in is the
1278        // convention's answer, which is why the whole list goes to the same place the arguments do
1279        // rather than to a rule.
1280        let returns: Vec<Type> = signature.return_types().collect();
1281
1282        let mut args = Vec::with_capacity(values.len());
1283        for (index, value) in values.into_iter().skip(usize::from(indirect)).enumerate() {
1284            let abi = named.get(index).or_else(|| beyond.get(index - named.len()));
1285            let abi = abi.copied().unwrap_or_default();
1286            let ty = self.source[value].ty;
1287            // What travels for an eighty bit value is its bytes, so what the call is handed is
1288            // where they are rather than a register they are in, and there is no register they
1289            // could be in. Everything else about it is a sixteen byte object passed by value and
1290            // is built by the same code.
1291            let reg =
1292                if abi::on_the_stack(ty) { self.x87_slot(value) } else { self.reg_of(value)? };
1293            args.push(abi::Passing { ty, reg, abi });
1294        }
1295        let block = self.at.expect("a block is being filled");
1296        let what = abi::Calling {
1297            callee,
1298            args: &args,
1299            returns: &returns,
1300            variadic,
1301            named: named.len(),
1302            at: self.source.span(inst),
1303        };
1304        let made = abi::call(&mut self.out, block, &what, self.conv, self.names)
1305            .map_err(|refused| Unsupported::Call { inst, refused })?;
1306        let calls = &mut self.stack.calls;
1307        *calls = Some(calls.unwrap_or(0).max(made.outgoing));
1308        // An eighty bit value came back on the x87 stack, and the one thing that has to happen
1309        // before anything else touches that stack is taking it off. So the `fstp` goes here, in
1310        // front of everything the block does next, and after it the value is in its slot and is
1311        // read the way every other one is.
1312        let results: Vec<Value> = self.source[inst].results().collect();
1313        if let [result] = results[..] {
1314            if abi::on_the_stack(self.source[result].ty) {
1315                let span = self.source.span(inst);
1316                let into = self.x87_slot(result);
1317                let into = self.through(into);
1318                self.x87_at("fstp_t", span, into);
1319                return Ok(());
1320            }
1321        }
1322        for (result, &reg) in results.into_iter().zip(&made.results) {
1323            self.regs[result.index()] = Some(reg);
1324        }
1325        Ok(())
1326    }
1327
1328    /// The pointer a function returning through memory was handed, or nothing in a function that
1329    /// was not.
1330    ///
1331    /// It is the first parameter and the signature is what says so, since in the IR it is an
1332    /// ordinary pointer and reads like one everywhere in the body. A function with a signature
1333    /// like that and no entry block has nothing to give back and no body to give it back from.
1334    fn sret(&self) -> Option<Value> {
1335        let first = self.source.signature().params.first()?;
1336        if !matches!(first.abi, Abi::Sret { .. }) {
1337            return None;
1338        }
1339        self.source[self.source.entry()?].params.first().copied()
1340    }
1341
1342    /// One `return` the convention has to write, as the place each value has to be in by the end.
1343    ///
1344    /// One pseudo per value, each a read constrained to a return register, which is what a return
1345    /// of one value already is and is the whole of what either does. The `ret` itself comes from
1346    /// the epilogue for both, long after this, because the frame has to be given back first.
1347    ///
1348    /// The two register files are counted separately, so a structure of a `double` and a `long`
1349    /// leaves the `double` in the first vector register and the `long` in the first integer one
1350    /// rather than in the second of either. That is the same walk `rucc_codegen::abi` makes on
1351    /// the other side of the call, which is what makes the two ends agree.
1352    ///
1353    /// A function whose answer went through memory gives back the address it was handed, in front
1354    /// of nothing else, because a signature that returns that way returns nothing else. That the
1355    /// caller already knows the address is not enough: it is allowed to read the register instead,
1356    /// and a caller that does gets whatever the allocator last left there. In a leaf function that
1357    /// is usually the right answer by accident, and one call in the body is enough to make it a
1358    /// wild pointer, which is why this is written rather than left to luck.
1359    ///
1360    /// Where everything goes is worked out before anything is written, so a return this cannot
1361    /// make leaves no half of one behind.
1362    /// Whether what a `return` gives back is the one value that goes back on the x87 stack.
1363    fn gives_back_x87(&self, inst: Inst) -> bool {
1364        let [value] = self.source[self.source[inst].args] else { return false };
1365        abi::on_the_stack(self.source[value].ty)
1366    }
1367
1368    fn returned(&mut self, inst: Inst) -> Result<(), Unsupported> {
1369        let values: Vec<Value> = self.source[self.source[inst].args].to_vec();
1370        let (mut ints, mut floats) = (0usize, 0usize);
1371        let mut parts = Vec::with_capacity(values.len() + 1);
1372        // An eighty bit value goes back on the x87 stack, which is where the convention says it is
1373        // and is the one place a value is left rather than put in a register. So the whole of the
1374        // return is an `fld` of its slot, and the stack it leaves the value on is not empty at the
1375        // `ret`, which is the one time in this file that is true and is what the convention asks
1376        // for. What comes after is the epilogue, which gives the frame back and touches nothing in
1377        // the unit.
1378        if let [value] = values[..] {
1379            let ty = self.source[value].ty;
1380            if abi::on_the_stack(ty) && self.sret().is_none() {
1381                let span = self.source.span(inst);
1382                let from = self.x87_slot(value);
1383                let from = self.through(from);
1384                self.x87_at("fld_t", span, from);
1385                return Ok(());
1386            }
1387        }
1388        for value in self.sret().into_iter().chain(values) {
1389            let ty = self.source[value].ty;
1390            let at = if crate::term::in_vector_file(ty) { &mut floats } else { &mut ints };
1391            // Why it cannot come back, and not only that it cannot. A type that travels nowhere
1392            // says so itself, and a type that travels perfectly well ran out of registers.
1393            let missing = abi::refuses(ty).unwrap_or(Missing::NoRoom);
1394            let name = abi::ret_of(ty, *at).ok_or(Unsupported::Returned { inst, missing })?;
1395            *at += 1;
1396            // The register is the target's answer and not one worked out here, the same as it is
1397            // for a return of one value, so that both halves of a pair and every rule that writes
1398            // half of one are reading the same table.
1399            let opcode = name.strip_prefix(PREFIX).expect("a machine instruction of this target");
1400            let form = x86_64::form(opcode).ok_or_else(|| self.unsupported(inst))?;
1401            let [desc] = form.operands() else { return Err(self.unsupported(inst)) };
1402            parts.push((self.names.intern(name), self.reg_of(value)?, *desc));
1403        }
1404
1405        let block = self.at.expect("a block is being filled");
1406        let span = self.source.span(inst);
1407        for (opcode, reg, desc) in parts {
1408            let operand = mir::Operand {
1409                reg,
1410                class: desc.class,
1411                role: desc.role,
1412                constraint: desc.constraint,
1413            };
1414            self.out.build(block, mir::Opcode::new(opcode)).at(span).operand(operand).finish();
1415        }
1416        Ok(())
1417    }
1418
1419    /// One `alloca`: the bytes it asks for go on the list the frame is laid out from, and the
1420    /// address of them is one instruction.
1421    ///
1422    /// The instruction is a `lea` off the stack pointer, which is the one register that reaches
1423    /// the frame in every function, and its displacement is left at nothing because there is no
1424    /// frame yet. Which instruction is waiting for which local is remembered, and
1425    /// [`crate::finish`] fills the numbers in after [`crate::frame::Frame`] has placed them.
1426    ///
1427    /// There is deliberately no rule for `alloca` and no name for one in [`crate::term`], and
1428    /// that is what stops it being folded into something else. An operand shown as the
1429    /// instruction that computed it is offered to the matcher by its name, so an `alloca` with no
1430    /// name is one no pattern can reach past, and the address it computes is always in a register
1431    /// by the time anything reads it.
1432    fn reserve(&mut self, inst: Inst) -> Result<(), Unsupported> {
1433        let data = &self.source[inst];
1434        // A variable length array carries the size it wants as an operand rather than in the
1435        // instruction, which is the whole of what tells the two apart here.
1436        if let Some(&size) = self.source[data.args].first() {
1437            return self.grow(inst, size);
1438        }
1439        let Extra::Mem(mem) = data.extra else { return Err(self.unsupported(inst)) };
1440        let info = self.source[mem];
1441        let size = u32::try_from(info.size)
1442            .map_err(|_| Unsupported::Dynamic { inst, growing: Growing::Huge })?;
1443        let result = data.first_result.ok_or_else(|| self.unsupported(inst))?;
1444
1445        // At least one, because the frame divides by the alignment and an object with no
1446        // alignment at all is one the front end had nothing to say about rather than one that may
1447        // go anywhere.
1448        let index = self.stack.locals.len();
1449        self.stack.locals.push(Local { size, align: info.align.max(1) });
1450        if let Some(decl) = self.source.mem_decl(mem) {
1451            self.stack.declared.push((index, decl));
1452        }
1453
1454        let block = self.at.expect("a block is being filled");
1455        let reg = self.new_reg(result);
1456        let span = self.source.span(inst);
1457        let lea = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{}", x86_64::FRAME.lea)));
1458        let sp = mir::Operand::read(mir::Reg::physical(self.conv.stack_pointer), self.gpr);
1459        let made =
1460            self.out.build(block, lea).at(span).def(reg, self.gpr).mem(mir::Mem::at(sp)).finish();
1461        self.stack.addresses.push((made, index));
1462        Ok(())
1463    }
1464
1465    /// The other kind of `alloca`: one whose size the function does not know until it runs, which
1466    /// is what a variable length array is.
1467    ///
1468    /// Nothing about it is a slot the frame laid out, because the frame is laid out once and this
1469    /// happens as often as control reaches the declaration. The bytes come off the stack pointer
1470    /// where the declaration stands, which is two instructions:
1471    ///
1472    /// ```text
1473    ///   sub sp, bytes     the stack pointer moves down over the memory, which is what takes it
1474    ///   lea reg, [sp+n]   where the memory starts, which is above the outgoing argument area
1475    /// ```
1476    ///
1477    /// The displacement is left at nothing for the reason the constant kind leaves its own at
1478    /// nothing, and for a different number: that area belongs to the arguments of whatever this
1479    /// function calls, it stays at the bottom of the frame wherever the bottom has moved to, and
1480    /// how big it is is not known until every call in the function has been seen.
1481    ///
1482    /// The bytes are already a multiple of the stack pointer's alignment by the time they arrive,
1483    /// because [`crate::expand::rounds`] rounded them up in the IR, so nothing here has to mask the
1484    /// stack pointer afterwards and the stack pointer stays somewhere a call can be made from.
1485    ///
1486    /// Two instructions here and not always two in the finished function. On a command line that
1487    /// asked for the stack to be touched a page at a time, the subtraction becomes a loop that
1488    /// walks the same distance a page at a time, which [`crate::finish`] writes. That is why the
1489    /// instruction is written down in [`Stack::grown`] as well as left where it is.
1490    ///
1491    /// An array wanting more alignment than the convention leaves the stack pointer with does not
1492    /// reach here asking for it: [`crate::expand::rounds`] gives it the alignment in extra bytes
1493    /// and turns the array into a `ptr_add` of the offset that lands inside them, so what arrives
1494    /// is a block asking for the convention's alignment like any other. The refusal below is what
1495    /// answers IR that came from somewhere other than that pass, since forcing the alignment here
1496    /// would be a second rounding of a register the frame already rounded, and after it no
1497    /// constant reaches the rest of the frame from anywhere. See `Growing` in [`crate::frame`].
1498    fn grow(&mut self, inst: Inst, size: Value) -> Result<(), Unsupported> {
1499        let data = &self.source[inst];
1500        let Extra::Mem(mem) = data.extra else { return Err(self.unsupported(inst)) };
1501        let info = self.source[mem];
1502        if info.align > self.conv.stack_align {
1503            return Err(Unsupported::Dynamic { inst, growing: Growing::Aligned });
1504        }
1505        let result = data.first_result.ok_or_else(|| self.unsupported(inst))?;
1506        let bytes = self.reg_of(size)?;
1507
1508        let block = self.at.expect("a block is being filled");
1509        let span = self.source.span(inst);
1510        let stack = mir::Reg::physical(self.conv.stack_pointer);
1511        let grow = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{}", x86_64::FRAME.grow)));
1512        let took = self
1513            .out
1514            .build(block, grow)
1515            .at(span)
1516            .operand(mir::Operand::write(stack, self.gpr))
1517            .operand(mir::Operand::read(stack, self.gpr))
1518            .operand(mir::Operand::read(bytes, self.gpr))
1519            .finish();
1520        self.stack.grown.push(took);
1521
1522        let reg = self.new_reg(result);
1523        let lea = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{}", x86_64::FRAME.lea)));
1524        let sp = mir::Operand::read(stack, self.gpr);
1525        let made =
1526            self.out.build(block, lea).at(span).def(reg, self.gpr).mem(mir::Mem::at(sp)).finish();
1527        self.stack.dynamic.push(made);
1528        self.stack.grown_at.get_or_insert(inst);
1529        Ok(())
1530    }
1531
1532    /// Where the stack pointer is, kept so that something later can put it back.
1533    ///
1534    /// One move out of the stack pointer and one move into it, which is the whole of what the two
1535    /// halves are. What makes them worth writing is where the front end puts them: a scope holding
1536    /// a variable length array saves the stack pointer as it opens and puts it back as it closes,
1537    /// so a loop declaring one takes its bytes once round rather than once per iteration, and a
1538    /// jump out of the scope gives the bytes back on the way out.
1539    ///
1540    /// The value travels in an ordinary register the allocator hands out, so it may be spilled like
1541    /// any other, and a spill slot in a frame that grows is reached through the frame pointer,
1542    /// which is exactly the register that still means something after the stack pointer has moved.
1543    fn stack_pointer(&mut self, inst: Inst, into: bool) -> Result<(), Unsupported> {
1544        let data = &self.source[inst];
1545        let block = self.at.expect("a block is being filled");
1546        let span = self.source.span(inst);
1547        let stack = mir::Reg::physical(self.conv.stack_pointer);
1548        let mov = x86_64::FRAME.moves(self.gpr).expect("a class the target says how to move").mov;
1549        let mov = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{mov}")));
1550        let (write, read) = if into {
1551            let &saved = self.source[data.args].first().ok_or_else(|| self.unsupported(inst))?;
1552            (stack, self.reg_of(saved)?)
1553        } else {
1554            let result = data.first_result.ok_or_else(|| self.unsupported(inst))?;
1555            (self.new_reg(result), stack)
1556        };
1557        self.out
1558            .build(block, mov)
1559            .at(span)
1560            .operand(mir::Operand::write(write, self.gpr))
1561            .operand(mir::Operand::read(read, self.gpr))
1562            .finish();
1563        // Only the write is a move of the stack pointer, and it is the one that makes the frame a
1564        // growing one. A read of it in a function that never writes it back is a function that
1565        // asked where the stack was and did nothing with the answer.
1566        if into {
1567            self.stack.grown_at.get_or_insert(inst);
1568        }
1569        Ok(())
1570    }
1571
1572    /// Whether an instruction has an eighty bit float anywhere in it.
1573    ///
1574    /// Producing one and reading one are the same question here, because what makes one of these
1575    /// different from every other instruction is not the operation but where the value is. A
1576    /// `long double` is on the x87 stack while it is being worked on and in a frame slot the rest
1577    /// of the time, and neither of those is somewhere the operand of a rule could point.
1578    fn touches_x87(&self, inst: Inst) -> bool {
1579        let data = &self.source[inst];
1580        data.results().any(|value| on_x87(self.source[value].ty))
1581            || self.source[data.args].iter().any(|&arg| on_x87(self.source[arg].ty))
1582    }
1583
1584    /// Everything that happens to an eighty bit float, as the group of instructions it is.
1585    ///
1586    /// The first six move one, and every one of those is a load, a store, or a load and a store at
1587    /// two different formats, because that is the whole of what this machine converts with: the
1588    /// x87 has no instruction that turns one thing on its stack into another, so a widening is
1589    /// `fld` of the narrow format and a narrowing is `fstp` of it.
1590    ///
1591    /// The rest work on one, and they are here rather than in a rule for the same reason the six
1592    /// are. An add is a push, a push, the add and a pop, and what passes between those four is the
1593    /// top of a stack nothing allocates from, so there is no value in the middle of the group for
1594    /// a pattern to bind or a replacement to name. The comparison is the same shape with its last
1595    /// two instructions folded into one opcode, which is where the byte it produces comes from.
1596    ///
1597    /// Every group leaves the stack as empty as it found it, which is what `spec/10-backend.md`
1598    /// section 10.8 asks of one and is why nothing in this file has to track a depth: each push
1599    /// below is answered by a pop a line or two later, so no two groups can ever be looking at
1600    /// the same eight registers.
1601    fn x87(&mut self, inst: Inst) -> Result<(), Unsupported> {
1602        match self.source[inst].opcode {
1603            Opcode::Load => self.x87_load(inst),
1604            Opcode::Store => self.x87_store(inst),
1605            Opcode::FPExt => self.x87_widen(inst),
1606            Opcode::FPTrunc => self.x87_narrow(inst),
1607            Opcode::SIToFP => self.x87_from_signed(inst),
1608            Opcode::FPToSI => self.x87_to_signed(inst),
1609            Opcode::FAdd => self.x87_arith(inst, "fadd_p"),
1610            Opcode::FSub => self.x87_arith(inst, "fsubr_p"),
1611            Opcode::FMul => self.x87_arith(inst, "fmul_p"),
1612            Opcode::FDiv => self.x87_arith(inst, "fdivr_p"),
1613            Opcode::FNeg => self.x87_flip(inst),
1614            Opcode::FCmp => self.x87_compare(inst),
1615            Opcode::FConst => self.x87_const(inst),
1616            _ => Err(self.unsupported(inst)),
1617        }
1618    }
1619
1620    /// The eighty bit parameters of a block, copied out of the addresses an edge handed over and
1621    /// into slots of the block's own.
1622    ///
1623    /// What crosses an edge for a value of this type is an address, because the value is sixteen
1624    /// bytes of the frame and no register holds any of it. The block cannot keep that address: a
1625    /// second edge into the same block hands over a second one, and a read after the block would
1626    /// then be a read of whichever edge was taken rather than of one place. So the block has a
1627    /// slot per parameter and the bytes are copied into it here, which is the move on an edge that
1628    /// every other type gets from the allocator.
1629    ///
1630    /// Every load runs before every store and the stores run backwards, so all of the values are
1631    /// on the x87 stack at once and nothing reads a slot another one has already written. That
1632    /// costs nothing in the ordinary case of one parameter and is what makes the back edge of a
1633    /// loop that swaps two of these work. It is also the reason for the limit: the stack is eight
1634    /// deep, and a block with more of these than that is refused rather than copied in an order
1635    /// that could be wrong.
1636    fn settle(&mut self, block: Block, arriving: &[(Value, mir::Reg)]) -> Result<(), Unsupported> {
1637        let Some(&(first, _)) = arriving.first() else { return Ok(()) };
1638        if arriving.len() > X87_DEPTH {
1639            let ty = self.source[first].ty;
1640            return Err(Unsupported::Phi { block, count: arriving.len(), ty });
1641        }
1642        // A block parameter comes from no instruction, so what this points at is the first thing
1643        // in the block, which is where a reader looking for the copy would look.
1644        let first_inst = self.source.insts(block).next();
1645        let span = first_inst.map_or(Span::DUMMY, |it| self.source.span(it));
1646        for &(_, reg) in arriving {
1647            let from = self.through(reg);
1648            self.x87_at("fld_t", span, from);
1649        }
1650        for &(param, _) in arriving.iter().rev() {
1651            let into = self.x87_slot(param);
1652            let into = self.through(into);
1653            self.x87_at("fstp_t", span, into);
1654        }
1655        Ok(())
1656    }
1657
1658    /// The frame slot an eighty bit value lives in, as its address in a fresh register.
1659    ///
1660    /// The slot is the value's for the whole function and is taken the first time somebody asks.
1661    /// The address is worked out again every time, which is a `lea` per use and is deliberate: one
1662    /// address kept in a register from the definition to the last use would hold a general purpose
1663    /// register open across everything in between, and a function with a handful of these in it
1664    /// would spend its registers on addresses of things rather than on things.
1665    fn x87_slot(&mut self, value: Value) -> mir::Reg {
1666        // An argument of the function has a slot already and it is the caller's. The convention
1667        // puts the bytes in the argument area and hands over where they are, so the address that
1668        // arrived is the answer and no second copy of the value is made. Nothing ever writes to a
1669        // value of this type once it exists, so nothing writes to the caller's copy either. A
1670        // parameter of any other block is not this: what arrived there is an address a predecessor
1671        // chose, [`Lowering::settle`] has already copied the bytes out of it, and the slot those
1672        // bytes landed in is the one below.
1673        let entry = self.source.entry();
1674        if let (Def::Param { block, .. }, Some(reg)) =
1675            (self.source[value].def, self.regs[value.index()])
1676        {
1677            if entry == Some(block) {
1678                return reg;
1679            }
1680        }
1681        let index = match self.slots[value.index()] {
1682            Some(index) => index,
1683            None => {
1684                let index = self.stack.locals.len();
1685                self.stack.locals.push(Local { size: X87_BYTES, align: X87_BYTES });
1686                self.slots[value.index()] = Some(index);
1687                index
1688            }
1689        };
1690        let block = self.at.expect("a block is being filled");
1691        self.frame_address(block, index)
1692    }
1693
1694    /// The bytes a value crosses between a register and the x87 stack through, as their address
1695    /// in a fresh register.
1696    fn x87_crossing(&mut self) -> mir::Reg {
1697        let index = match self.crossing {
1698            Some(index) => index,
1699            None => {
1700                let index = self.stack.locals.len();
1701                self.stack.locals.push(Local { size: X87_CROSSING, align: X87_CROSSING });
1702                self.crossing = Some(index);
1703                index
1704            }
1705        };
1706        let block = self.at.expect("a block is being filled");
1707        self.frame_address(block, index)
1708    }
1709
1710    /// The two control words, as the address of the first of them in a fresh register.
1711    fn x87_control(&mut self) -> mir::Reg {
1712        let index = match self.control {
1713            Some(index) => index,
1714            None => {
1715                let index = self.stack.locals.len();
1716                self.stack.locals.push(Local { size: 4, align: 4 });
1717                self.control = Some(index);
1718                index
1719            }
1720        };
1721        let block = self.at.expect("a block is being filled");
1722        self.frame_address(block, index)
1723    }
1724
1725    /// An address held in a register, as the addressing mode that reaches it.
1726    fn through(&self, reg: mir::Reg) -> mir::Mem {
1727        mir::Mem::at(mir::Operand::read(reg, self.gpr))
1728    }
1729
1730    /// One instruction of a group, which names an address and nothing else.
1731    ///
1732    /// Every x87 instruction that moves a value is one of these. What it does to the stack is in
1733    /// the mnemonic rather than in an operand, so there is no register to write down and no
1734    /// register the allocator gets a say in.
1735    fn x87_at(&mut self, name: &str, span: Span, at: mir::Mem) {
1736        let block = self.at.expect("a block is being filled");
1737        let opcode = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{name}")));
1738        self.out.build(block, opcode).at(span).mem(at).finish();
1739    }
1740
1741    /// The one instruction of a group that reaches the program's own memory.
1742    ///
1743    /// A `long double` moves in two instructions with a frame slot at one end of them, and the
1744    /// other end is the address the program wrote. That end is the access, so it is the one that
1745    /// carries what the program said about it, and the trip through the slot is this compiler's
1746    /// own business the way a spill is. See [`Self::carried`].
1747    fn x87_touching(&mut self, name: &str, inst: Inst, at: mir::Mem) {
1748        let block = self.at.expect("a block is being filled");
1749        let opcode = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{name}")));
1750        let (span, flags) = (self.source.span(inst), self.carried(inst));
1751        self.out.build(block, opcode).at(span).flags(flags).mem(at).finish();
1752    }
1753
1754    /// One instruction of a group that names nothing at all.
1755    ///
1756    /// The arithmetic is these. Both of an add's operands are already on the stack when it runs
1757    /// and so is where the answer goes, and the stack is not somewhere an instruction says, so
1758    /// `faddp` has an argument in the assembler's syntax and nothing here for the argument to come
1759    /// from. What it works on is which two pushes came before it, which is a fact about the order
1760    /// of the group and is why the group is written in one place.
1761    fn x87_only(&mut self, name: &str, span: Span) {
1762        let block = self.at.expect("a block is being filled");
1763        let opcode = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{name}")));
1764        self.out.build(block, opcode).at(span).finish();
1765    }
1766
1767    /// A `load` of a `long double`: onto the stack from where it was, and off it into the slot.
1768    ///
1769    /// Two instructions rather than the two general purpose moves the same sixteen bytes would
1770    /// take, because `fld` and `fstp` at this format neither convert nor look: the value goes on
1771    /// in the format it was already in and comes back off in it, so a signalling NaN stays one
1772    /// and nothing is raised. Which is what makes this a copy at all.
1773    fn x87_load(&mut self, inst: Inst) -> Result<(), Unsupported> {
1774        let (args, result) = self.ends(inst)?;
1775        let &address = args.first().ok_or_else(|| self.unsupported(inst))?;
1776        let span = self.source.span(inst);
1777        let from = self.reg_of(address)?;
1778        let from = self.through(from);
1779        let into = self.x87_slot(result);
1780        let into = self.through(into);
1781        self.x87_touching("fld_t", inst, from);
1782        self.x87_at("fstp_t", span, into);
1783        Ok(())
1784    }
1785
1786    /// A `store` of a `long double`: the same pair the other way round.
1787    fn x87_store(&mut self, inst: Inst) -> Result<(), Unsupported> {
1788        let args = self.source[self.source[inst].args].to_vec();
1789        let [value, address] = args[..] else { return Err(self.unsupported(inst)) };
1790        let span = self.source.span(inst);
1791        let from = self.x87_slot(value);
1792        let from = self.through(from);
1793        let into = self.reg_of(address)?;
1794        let into = self.through(into);
1795        self.x87_at("fld_t", span, from);
1796        self.x87_touching("fstp_t", inst, into);
1797        Ok(())
1798    }
1799
1800    /// A `float`, a `double` or an integer becoming a `long double`.
1801    ///
1802    /// Through memory, because the x87 reads memory and nothing else: the value is in a register
1803    /// the machine has and the unit has no way to be handed one, so it is written to the crossing
1804    /// bytes and loaded back at the format that widens it. Every one of these is exact. Sixty four
1805    /// bits of significand and fifteen of exponent hold every `float`, every `double` and every
1806    /// sixty four bit integer outright, so none of the four can round and none can raise.
1807    fn x87_across(
1808        &mut self,
1809        inst: Inst,
1810        put: &'static str,
1811        class: RegClass,
1812        get: &'static str,
1813    ) -> Result<(), Unsupported> {
1814        let (args, result) = self.ends(inst)?;
1815        let &source = args.first().ok_or_else(|| self.unsupported(inst))?;
1816        let span = self.source.span(inst);
1817        let value = self.reg_of(source)?;
1818        let across = self.x87_crossing();
1819        let across = self.through(across);
1820        let into = self.x87_slot(result);
1821        let into = self.through(into);
1822
1823        let block = self.at.expect("a block is being filled");
1824        let store = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{put}")));
1825        self.out.build(block, store).at(span).uses(value, class).mem(across).finish();
1826        self.x87_at(get, span, across);
1827        self.x87_at("fstp_t", span, into);
1828        Ok(())
1829    }
1830
1831    /// A `long double` becoming a `float`, a `double` or an integer.
1832    ///
1833    /// Through memory for the reason above and in the same three instructions backwards. The two
1834    /// that go to a float round to nearest, which is what the control word says unless somebody
1835    /// has changed it and is what C wants. The two that go to an integer do not, which is why they
1836    /// do not come here.
1837    fn x87_back(
1838        &mut self,
1839        inst: Inst,
1840        put: &'static str,
1841        get: &'static str,
1842        class: RegClass,
1843    ) -> Result<(), Unsupported> {
1844        let (args, result) = self.ends(inst)?;
1845        let &source = args.first().ok_or_else(|| self.unsupported(inst))?;
1846        let span = self.source.span(inst);
1847        let from = self.x87_slot(source);
1848        let from = self.through(from);
1849        let across = self.x87_crossing();
1850        let across = self.through(across);
1851
1852        self.x87_at("fld_t", span, from);
1853        self.x87_at(put, span, across);
1854        let block = self.at.expect("a block is being filled");
1855        let reg = self.new_reg(result);
1856        let load = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{get}")));
1857        self.out.build(block, load).at(span).def(reg, class).mem(across).finish();
1858        Ok(())
1859    }
1860
1861    /// An `fpext` up to a `long double`, which is the only direction this machine has one in.
1862    fn x87_widen(&mut self, inst: Inst) -> Result<(), Unsupported> {
1863        let sse = self.conv.sse_class;
1864        match self.source[self.narrow(inst)?].ty.bits() {
1865            32 => self.x87_across(inst, "movss_mr", sse, "fld_s"),
1866            64 => self.x87_across(inst, "movsd_mr", sse, "fld_l"),
1867            _ => Err(self.unsupported(inst)),
1868        }
1869    }
1870
1871    /// An `fptrunc` down from a `long double`, which is the other direction of the same.
1872    fn x87_narrow(&mut self, inst: Inst) -> Result<(), Unsupported> {
1873        let sse = self.conv.sse_class;
1874        let result = self.source[inst].first_result.ok_or_else(|| self.unsupported(inst))?;
1875        match self.source[result].ty.bits() {
1876            32 => self.x87_back(inst, "fstp_s", "movss_rm", sse),
1877            64 => self.x87_back(inst, "fstp_l", "movsd_rm", sse),
1878            _ => Err(self.unsupported(inst)),
1879        }
1880    }
1881
1882    /// A `sitofp` up to a `long double`.
1883    ///
1884    /// Thirty two bits and sixty four, and nothing narrower, because C widens an integer to `int`
1885    /// before it converts one and the front end writes that widening down. An unsigned integer is
1886    /// not here at all: `fild` reads its operand as signed, so a value above the signed range
1887    /// comes back short by two to the sixty fourth and has to be added back, which is arithmetic
1888    /// rather than a move and waits with the rest of it.
1889    fn x87_from_signed(&mut self, inst: Inst) -> Result<(), Unsupported> {
1890        let gpr = self.gpr;
1891        match self.source[self.narrow(inst)?].ty.bits() {
1892            32 => self.x87_across(inst, "mov_mr_32", gpr, "fild_l"),
1893            64 => self.x87_across(inst, "mov_mr_64", gpr, "fild_ll"),
1894            _ => Err(self.unsupported(inst)),
1895        }
1896    }
1897
1898    /// An `fptosi` down from a `long double`, which is the one conversion here with no single
1899    /// instruction behind it.
1900    ///
1901    /// C cuts towards zero and the unit rounds the way its control word says, so the store that
1902    /// takes the value off the stack is wrapped in the control word being saved, changed and put
1903    /// back. Five instructions around the one that does the work, and three more moving the word
1904    /// through a register, because this machine has no way to OR a constant into memory at this
1905    /// width. The unit has a shorter answer in `fisttp`, and `spec/10-backend.md` section 10.8
1906    /// says why it is not used: it is SSE3, the x86-64 baseline is not, and there is nothing here
1907    /// that can gate an instruction on a feature yet.
1908    fn x87_to_signed(&mut self, inst: Inst) -> Result<(), Unsupported> {
1909        let (args, result) = self.ends(inst)?;
1910        let &source = args.first().ok_or_else(|| self.unsupported(inst))?;
1911        let (put, get) = match self.source[result].ty.bits() {
1912            32 => ("fistp_l", "mov_rm_32"),
1913            64 => ("fistp_ll", "mov_rm_64"),
1914            _ => return Err(self.unsupported(inst)),
1915        };
1916        let span = self.source.span(inst);
1917        let gpr = self.gpr;
1918        let from = self.x87_slot(source);
1919        let from = self.through(from);
1920        let across = self.x87_crossing();
1921        let across = self.through(across);
1922        let control = self.x87_control();
1923        let saved = self.through(control).plus(0);
1924        let cut = self.through(control).plus(2);
1925
1926        // The word the unit has now, into the first of the two slots and into a register, with the
1927        // rounding field turned to truncate on the way to the second.
1928        self.x87_at("fnstcw", span, saved);
1929        let block = self.at.expect("a block is being filled");
1930        let was = self.out.new_vreg(gpr);
1931        let read = mir::Opcode::new(self.names.intern("x64.mov_rm_16"));
1932        self.out.build(block, read).at(span).def(was, gpr).mem(saved).finish();
1933        let now = self.out.new_vreg(gpr);
1934        let set = mir::Opcode::new(self.names.intern("x64.or_ri_16"));
1935        // Two address, which is written out here rather than taken from the two shorthands
1936        // because the shorthands leave an operand unconstrained: this machine ORs into the
1937        // register it read, so the two have to be the same one and only the constraint says so.
1938        self.out
1939            .build(block, set)
1940            .at(span)
1941            .operand(mir::Operand::write(now, gpr).with(Constraint::Reuse(1)))
1942            .operand(mir::Operand::read(was, gpr))
1943            .imm(X87_TRUNCATE)
1944            .finish();
1945        let write = mir::Opcode::new(self.names.intern("x64.mov_mr_16"));
1946        self.out.build(block, write).at(span).uses(now, gpr).mem(cut).finish();
1947
1948        // The conversion itself, under the changed word, and then the word the unit had put back
1949        // before anything else runs.
1950        self.x87_at("fldcw", span, cut);
1951        self.x87_at("fld_t", span, from);
1952        self.x87_at(put, span, across);
1953        self.x87_at("fldcw", span, saved);
1954
1955        let block = self.at.expect("a block is being filled");
1956        let reg = self.new_reg(result);
1957        let load = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{get}")));
1958        self.out.build(block, load).at(span).def(reg, gpr).mem(across).finish();
1959        Ok(())
1960    }
1961
1962    /// A constant of this type, as the bits of it written into its slot.
1963    ///
1964    /// No x87 instruction at all, which is the surprise here. A slot holding an eighty bit value is
1965    /// the value, so a constant is ten bytes put where the value lives, and the unit never has to
1966    /// see it: whatever reads it will `fld` it out of the slot the way it reads any other one.
1967    ///
1968    /// Ten bytes in two goes, because the machine stores eight at a time and there is no store of
1969    /// an immediate to memory, so each half is put in a register first. The six bytes above the ten
1970    /// are left alone, since nothing reads them: they are the padding that makes the type sixteen
1971    /// wide and they are unspecified in the psABI rather than zero.
1972    ///
1973    /// The other way is a constant pool, an `fldt` of a symbol, and a relocation, which is what a
1974    /// compiler with somewhere to put a literal does. This back end has nowhere to put one yet, and
1975    /// four instructions in the frame is what that costs until it does.
1976    fn x87_const(&mut self, inst: Inst) -> Result<(), Unsupported> {
1977        let Extra::Imm(imm) = self.source[inst].extra else { return Err(self.unsupported(inst)) };
1978        let result = self.source[inst].first_result.ok_or_else(|| self.unsupported(inst))?;
1979        let bits = self.source[imm].bits();
1980        let span = self.source.span(inst);
1981        let gpr = self.gpr;
1982        let slot = self.x87_slot(result);
1983        let low = self.through(slot).plus(0);
1984        let high = self.through(slot).plus(8);
1985
1986        let block = self.at.expect("a block is being filled");
1987        for (bytes, at, into) in
1988            [(bits as u64 as i64, low, "64"), (((bits >> 64) & 0xffff) as i64, high, "16")]
1989        {
1990            let held = self.out.new_vreg(gpr);
1991            let put = mir::Opcode::new(self.names.intern(&format!("{PREFIX}mov_ri_{into}")));
1992            self.out.build(block, put).at(span).def(held, gpr).imm(bytes).finish();
1993            let store = mir::Opcode::new(self.names.intern(&format!("{PREFIX}mov_mr_{into}")));
1994            self.out.build(block, store).at(span).uses(held, gpr).mem(at).finish();
1995        }
1996        Ok(())
1997    }
1998
1999    /// One arithmetic instruction on two eighty bit values, as the four it takes.
2000    ///
2001    /// The left operand is pushed first and the right one on top of it, so the left ends up
2002    /// underneath and the answer wanted is the one below against the top in that order. Which of
2003    /// the two mnemonics computes that is a question about the spelling rather than about the
2004    /// machine, and the two spellings disagree. Intel's `FSUBP ST(i), ST(0)` is `ST(i) - ST(0)`
2005    /// and is `DE E8+i`, and AT&T's `fsubp` is `DE E0+i`, which is the other subtraction. This
2006    /// compiler writes AT&T and encodes what gas encodes, so what it asks for here is `fsubr_p`
2007    /// and `fdivr_p`, and the `r` is not a reversal of anything the code generator decided.
2008    ///
2009    /// An addition and a multiplication have one form each and do not care, which is why a test
2010    /// that reads the mnemonic back would not have caught this and one that computes a subtraction
2011    /// and checks the answer does.
2012    ///
2013    /// The answer is left where the deeper of the two was and the shallower is gone, which is what
2014    /// the `p` on the mnemonic means, so one push has already been paid back by the time the
2015    /// `fstp` runs and the stack is level again after it.
2016    ///
2017    /// Nothing here is folded and nothing is reused. Two values that are the same value get two
2018    /// pushes of the same slot, and an operand that was just computed is read back out of the slot
2019    /// it was written to rather than left on the stack, which costs a store and a load per
2020    /// instruction in an expression. Keeping a partial result on the stack across the next
2021    /// instruction's operands means knowing how deep the stack is at every point in the block, and
2022    /// that is a different thing from writing a group.
2023    fn x87_arith(&mut self, inst: Inst, with: &'static str) -> Result<(), Unsupported> {
2024        let (args, result) = self.ends(inst)?;
2025        let [left, right] = args[..] else { return Err(self.unsupported(inst)) };
2026        let span = self.source.span(inst);
2027        let left = self.x87_slot(left);
2028        let left = self.through(left);
2029        let right = self.x87_slot(right);
2030        let right = self.through(right);
2031        let into = self.x87_slot(result);
2032        let into = self.through(into);
2033        self.x87_at("fld_t", span, left);
2034        self.x87_at("fld_t", span, right);
2035        self.x87_only(with, span);
2036        self.x87_at("fstp_t", span, into);
2037        Ok(())
2038    }
2039
2040    /// A negation, which is a push, the sign bit turned over and a pop.
2041    ///
2042    /// `fchs` does not read the value as a number, so this is right for a zero, for an infinity
2043    /// and for a NaN, and it raises nothing on any of them. Which is what C asks of a negation and
2044    /// is not what subtracting from zero would give: `0.0L - x` is a different answer at a
2045    /// negative zero and a signalling one at a NaN.
2046    fn x87_flip(&mut self, inst: Inst) -> Result<(), Unsupported> {
2047        let (args, result) = self.ends(inst)?;
2048        let &source = args.first().ok_or_else(|| self.unsupported(inst))?;
2049        let span = self.source.span(inst);
2050        let from = self.x87_slot(source);
2051        let from = self.through(from);
2052        let into = self.x87_slot(result);
2053        let into = self.through(into);
2054        self.x87_at("fld_t", span, from);
2055        self.x87_only("fchs", span);
2056        self.x87_at("fstp_t", span, into);
2057        Ok(())
2058    }
2059
2060    /// A comparison of two eighty bit values, as the two pushes and the one opcode that reads them.
2061    ///
2062    /// The right operand is pushed first and the left one on top of it, which is the other way
2063    /// round from the arithmetic and is because `fucomip` asks about the top against what is under
2064    /// it: the comparison this machine can do is the top's, so the value the predicate is about
2065    /// has to be the top. The pop that gets the loser off the stack and the byte that reads the
2066    /// flags are both inside the opcode, since what passes between those and the comparison is the
2067    /// flags and the flags are not something anything here can name.
2068    ///
2069    /// Which of the ten opcodes, and which way round, is the same table the vector comparisons
2070    /// match against in `rules/x86-64.rules`, and it has to stay the same table: a predicate that
2071    /// picked a different condition here than there would be a `long double` comparison that
2072    /// disagreed with the `double` comparison of the same two numbers, which is the one thing a
2073    /// wider format is not allowed to do.
2074    ///
2075    /// The always false and the always true are refused rather than folded into a constant,
2076    /// because a comparison this machine never has to do is one the optimizer should have removed
2077    /// and an instruction here that quietly agreed with it would hide that it did not.
2078    fn x87_compare(&mut self, inst: Inst) -> Result<(), Unsupported> {
2079        let Extra::FloatPred(pred) = self.source[inst].extra else {
2080            return Err(self.unsupported(inst));
2081        };
2082        let (args, result) = self.ends(inst)?;
2083        let [left, right] = args[..] else { return Err(self.unsupported(inst)) };
2084        // Two of the fourteen need a second byte and an instruction to put the two together,
2085        // because they are two conditions at once: an ordered equal is equal and not unordered,
2086        // and an unordered not equal is either. The opcode carries all of that and says here only
2087        // that it writes somewhere else as well.
2088        let (name, reversed, both) = match pred {
2089            FloatPred::Ogt => ("fucomip_set_a", false, false),
2090            FloatPred::Oge => ("fucomip_set_ae", false, false),
2091            FloatPred::Olt => ("fucomip_set_a", true, false),
2092            FloatPred::Ole => ("fucomip_set_ae", true, false),
2093            FloatPred::One => ("fucomip_set_ne", false, false),
2094            FloatPred::Ord => ("fucomip_set_np", false, false),
2095            FloatPred::Uno => ("fucomip_set_p", false, false),
2096            FloatPred::Ueq => ("fucomip_set_e", false, false),
2097            FloatPred::Ult => ("fucomip_set_b", false, false),
2098            FloatPred::Ule => ("fucomip_set_be", false, false),
2099            FloatPred::Ugt => ("fucomip_set_b", true, false),
2100            FloatPred::Uge => ("fucomip_set_be", true, false),
2101            FloatPred::Oeq => ("fucomip_set_e_and_np", false, true),
2102            FloatPred::Une => ("fucomip_set_ne_or_p", false, true),
2103            FloatPred::False | FloatPred::True => return Err(self.unsupported(inst)),
2104        };
2105        let (top, under) = if reversed { (right, left) } else { (left, right) };
2106
2107        let span = self.source.span(inst);
2108        let gpr = self.gpr;
2109        let under = self.x87_slot(under);
2110        let under = self.through(under);
2111        let top = self.x87_slot(top);
2112        let top = self.through(top);
2113        self.x87_at("fld_t", span, under);
2114        self.x87_at("fld_t", span, top);
2115
2116        let block = self.at.expect("a block is being filled");
2117        let reg = self.new_reg(result);
2118        // Taken before the instruction is started rather than inside it, since both come from the
2119        // same function being built and only one thing at a time may be adding to it.
2120        let spare = both.then(|| self.out.new_vreg(gpr));
2121        let opcode = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{name}")));
2122        let mut build = self.out.build(block, opcode).at(span).def(reg, gpr);
2123        if let Some(spare) = spare {
2124            build = build.def(spare, gpr);
2125        }
2126        build.finish();
2127        Ok(())
2128    }
2129
2130    /// The operands and the one result of an instruction that has exactly one.
2131    fn ends(&self, inst: Inst) -> Result<(&'a [Value], Value), Unsupported> {
2132        let data = &self.source[inst];
2133        let result = data.first_result.ok_or_else(|| self.unsupported(inst))?;
2134        Ok((&self.source[data.args], result))
2135    }
2136
2137    /// The operand of a conversion, which is the end of it that is not the `long double`.
2138    fn narrow(&self, inst: Inst) -> Result<Value, Unsupported> {
2139        let args = &self.source[self.source[inst].args];
2140        args.first().copied().ok_or_else(|| self.unsupported(inst))
2141    }
2142
2143    /// One `va_start`, as the fields of the list it was handed.
2144    ///
2145    /// On the four field list, two of them are numbers this already knows, and each costs an
2146    /// instruction to put in a register before it can be stored, because the machine here has no
2147    /// store of an immediate to memory. The other two are addresses in the frame, and each is a
2148    /// `lea` [`crate::finish`] finishes: the save area is one of the function's own stack objects,
2149    /// and the caller's argument area is where the parameters that had no register came from, which
2150    /// is the same place and the same fixup a parameter past the sixth already uses.
2151    ///
2152    /// On the list that is a pointer it is the second of those four and nothing else, since the
2153    /// whole of what that list says is where the walk is and the walk starts at the first argument
2154    /// the signature does not name. One `lea` and one store.
2155    ///
2156    /// What is written is exactly the fields [`crate::varargs`] describes, in the order they are
2157    /// laid out, so that reading this beside that table is the whole of the check.
2158    fn va_start(&mut self, inst: Inst) -> Result<(), Unsupported> {
2159        let Some(&list) = self.source[self.source[inst].args].first() else {
2160            return Err(self.unsupported(inst));
2161        };
2162        let started = self.varargs.ok_or_else(|| self.unsupported(inst))?;
2163        let list = self.reg_of(list)?;
2164        let block = self.at.expect("a block is being filled");
2165        let span = self.source.span(inst);
2166
2167        let (save, incoming) = match started {
2168            Varargs::Pointer { incoming } => (None, incoming),
2169            Varargs::Fields { save, incoming, integers, floats } => {
2170                for (at, count) in [(varargs::GP_OFFSET, integers), (varargs::FP_OFFSET, floats)] {
2171                    let held = self.out.new_vreg(self.gpr);
2172                    let load = mir::Opcode::new(self.names.intern("x64.mov_ri_32"));
2173                    let build = self.out.build(block, load).at(span);
2174                    build.def(held, self.gpr).imm(i64::from(count)).finish();
2175
2176                    let store = mir::Opcode::new(self.names.intern("x64.mov_mr_32"));
2177                    let mem = self.field(list, at);
2178                    self.out.build(block, store).at(span).uses(held, self.gpr).mem(mem).finish();
2179                }
2180                (Some(save), incoming)
2181            }
2182        };
2183
2184        // The first argument the signature did not name, which is as far up the caller's argument
2185        // area as the ones it did name reached. Nothing here knows where that area is, so the
2186        // distance is recorded the way a parameter read out of it is and finished with it.
2187        let overflow = self.out.new_vreg(self.gpr);
2188        let lea = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{}", x86_64::FRAME.lea)));
2189        let sp = mir::Operand::read(mir::Reg::physical(self.conv.stack_pointer), self.gpr);
2190        let made = self
2191            .out
2192            .build(block, lea)
2193            .at(span)
2194            .def(overflow, self.gpr)
2195            .mem(mir::Mem::at(sp))
2196            .finish();
2197        self.stack.arguments.push((made, incoming));
2198
2199        // At the front of the list when that address is the whole of it, and at the field the
2200        // layout gives it when there are four, with the save area behind it.
2201        let fields = match save {
2202            None => vec![(0, overflow)],
2203            Some(save) => {
2204                let save = self.frame_address(block, save);
2205                vec![(varargs::OVERFLOW, overflow), (varargs::SAVE_AREA, save)]
2206            }
2207        };
2208        for (at, held) in fields {
2209            let store = mir::Opcode::new(self.names.intern("x64.mov_mr_64"));
2210            let mem = self.field(list, at);
2211            self.out.build(block, store).at(span).uses(held, self.gpr).mem(mem).finish();
2212        }
2213        Ok(())
2214    }
2215
2216    /// One field of a list, as the addressing mode that reaches it.
2217    fn field(&self, list: mir::Reg, at: i64) -> mir::Mem {
2218        let base = mir::Operand::read(list, self.gpr);
2219        mir::Mem::at(base).plus(i32::try_from(at).expect("a field of a list is a small offset"))
2220    }
2221
2222    /// The address of a name: one `lea` off the instruction pointer, with the name on it.
2223    ///
2224    /// The same instruction an `alloca` gets and for a related reason. An address that is not in
2225    /// the program is a `lea` of an addressing mode that names no register, and the mode carries
2226    /// the symbol so that [`rucc_asm`] can write it relative to `%rip` and leave the relocation
2227    /// for the assembler. Both halves of that already existed: the printer writes `sym(%rip)` and
2228    /// the encoder emits the relocation, because a call to a name the file does not define needed
2229    /// them first.
2230    ///
2231    /// One `mov` and not one `lea` when the name is one [`Elsewhere`] holds, because the distance
2232    /// the `lea` adds to the instruction pointer is a number only a link that puts the name in
2233    /// this program can work out, and the address of a function this file merely declares is not
2234    /// such a number. The load reads the address out of the slot the linker fills in instead. The
2235    /// linker turns it back into the `lea` when the name turns out to have been here all along,
2236    /// so this is not slower in the case that was already right.
2237    ///
2238    /// There is deliberately no name for this in [`crate::term`], which is what stops the address
2239    /// being folded into the instruction that reads it. Folding it is the right thing to do and
2240    /// is what turns a load of a global from two instructions into one, but it is a separate
2241    /// question about addressing modes and issue #282 is it. Until then the address is in a
2242    /// register before anything uses it, which is correct and one instruction longer.
2243    ///
2244    /// What this does not do is give the name anything to refer to. A module carries its globals
2245    /// and nothing writes them out, so a file that defines the variable it reads compiles to a
2246    /// reference the linker cannot resolve. Issue #293 is the other half.
2247    ///
2248    /// A thread-local variable is neither of the two above and is [`Self::thread_address`].
2249    fn address_of(&mut self, inst: Inst) -> Result<(), Unsupported> {
2250        let data = &self.source[inst];
2251        let Extra::Symbol(symbol) = data.extra else { return Err(self.unsupported(inst)) };
2252        let result = data.first_result.ok_or_else(|| self.unsupported(inst))?;
2253        if self.elsewhere.thread(symbol) {
2254            return self.thread_address(inst, symbol, result);
2255        }
2256
2257        let block = self.at.expect("a block is being filled");
2258        let reg = self.new_reg(result);
2259        let span = self.source.span(inst);
2260        let (mnemonic, mem) = if self.elsewhere.holds(symbol) {
2261            (GOT_LOAD, mir::Mem::got(symbol))
2262        } else {
2263            (x86_64::FRAME.lea, mir::Mem::of(symbol))
2264        };
2265        let opcode = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{mnemonic}")));
2266        self.out.build(block, opcode).at(span).def(reg, self.gpr).mem(mem).finish();
2267        Ok(())
2268    }
2269
2270    /// The address of a thread-local variable, which is this thread's copy of it.
2271    ///
2272    /// Neither instruction the ordinary case writes would mean anything here. There is no distance
2273    /// to the variable for a `lea` to add, because there is no variable: there is one copy of it per
2274    /// thread and they are at different addresses, so a link asked for the distance to the name
2275    /// refuses rather than picking one. And there is no address for a table slot to hold either, for
2276    /// the same reason.
2277    ///
2278    /// What is the same in every thread is where the variable sits inside the block of storage a
2279    /// thread gets, so that offset is what the link writes down, and the address of the running
2280    /// thread's block is what turns it into an address. x86-64 keeps that address in `%fs`, at the
2281    /// front of the block, so the whole of this is three instructions:
2282    ///
2283    /// ```text
2284    /// movq  x@gottpoff(%rip), %off   # how far into the block x sits, which the link fills in
2285    /// movq  %fs:0, %tp               # where this thread's block is, which only the machine knows
2286    /// addq  %tp, %off                # this thread's copy of x
2287    /// ```
2288    ///
2289    /// That is the initial exec model. It is one instruction longer than what gcc writes at `-O2`
2290    /// in an executable, which folds the addition into the instruction that uses the address, and
2291    /// the difference is issue #282 rather than anything about threads: nothing here folds an
2292    /// address into its reader yet. The link relaxes the first instruction into an immediate when it
2293    /// is making an executable, since it lays the blocks out and therefore knows the number, so the
2294    /// table slot costs nothing in the case that is common.
2295    ///
2296    /// It is not the most general model. A library loaded by `dlopen` gets its storage after the
2297    /// program is already running, and the block this reaches was laid out before it started, so
2298    /// the loader has to find room in that block for the library's variables. glibc keeps a little
2299    /// spare room for exactly this and a library that fits in it loads and runs; one that does not
2300    /// fails to load, with a message saying so. The model with no such limit calls `__tls_get_addr`
2301    /// and is what gcc writes under `-fPIC` by default, and it is issue #1104.
2302    ///
2303    /// So this is the model gcc writes under `-ftls-model=initial-exec`: right for an executable,
2304    /// right for a library the program is linked against, and a load that either works or is
2305    /// refused out loud for a library something opens later. What it is never is quietly wrong.
2306    fn thread_address(
2307        &mut self,
2308        inst: Inst,
2309        symbol: Symbol,
2310        result: Value,
2311    ) -> Result<(), Unsupported> {
2312        let block = self.at.expect("a block is being filled");
2313        let span = self.source.span(inst);
2314        let gpr = self.gpr;
2315        let load = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{GOT_LOAD}")));
2316
2317        let offset = self.out.new_vreg(gpr);
2318        self.out
2319            .build(block, load)
2320            .at(span)
2321            .def(offset, gpr)
2322            .mem(mir::Mem::thread(symbol))
2323            .finish();
2324        // The front of the block, which is the one thing on this machine that no instruction can
2325        // work out: `%fs` is not a register a program can read, and what it points at is a word
2326        // holding its own address, so reading through it at zero is how the address is come by.
2327        let pointer = self.out.new_vreg(gpr);
2328        let at = mir::Mem::in_segment(Segment::Fs, 0);
2329        self.out.build(block, load).at(span).def(pointer, gpr).mem(at).finish();
2330
2331        // Two address, spelled out for the reason `x87_to_int` gives: this machine adds into the
2332        // register it read, and only the constraint says the two are the same one.
2333        let reg = self.new_reg(result);
2334        let add = mir::Opcode::new(self.names.intern(&format!("{PREFIX}add_rr_64")));
2335        self.out
2336            .build(block, add)
2337            .at(span)
2338            .operand(mir::Operand::write(reg, gpr).with(Constraint::Reuse(1)))
2339            .operand(mir::Operand::read(offset, gpr))
2340            .operand(mir::Operand::read(pointer, gpr))
2341            .finish();
2342        Ok(())
2343    }
2344
2345    /// `&&label`, GNU's address of a label, which is the same `lea` a global gets against a place
2346    /// in this same function.
2347    ///
2348    /// What the two have in common is the whole of the instruction: an address worked out from
2349    /// where the instruction is, which is what `(%rip)` means and is the only way this compiler
2350    /// reaches anything. What they do not have in common is what fills the four bytes in. A
2351    /// global is a name, so the number is a relocation and the linker writes it. A block is a
2352    /// place in this function, so both ends are in one section and the number is known as soon as
2353    /// the blocks have been laid out, which is why `rucc_asm` fills it in the way it fills in a
2354    /// jump rather than leaving a relocation behind.
2355    ///
2356    /// Nothing here says the block is one control can arrive at. That is said by the
2357    /// [`Opcode::IndirectBr`] that reads the address, which lists every block it can arrive at,
2358    /// and by nothing else: an address on its own is a number.
2359    fn block_address(&mut self, inst: Inst) -> Result<(), Unsupported> {
2360        let result = self.source[inst].first_result.ok_or_else(|| self.unsupported(inst))?;
2361        let Some(call) = self.source.successors(inst).next() else {
2362            return Err(self.unsupported(inst));
2363        };
2364        let block = self.at.expect("a block is being filled");
2365        let reg = self.new_reg(result);
2366        let span = self.source.span(inst);
2367        let opcode = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{}", x86_64::FRAME.lea)));
2368        let mem = mir::Mem::block(self.out_block(call.block));
2369        self.out.build(block, opcode).at(span).def(reg, self.gpr).mem(mem).finish();
2370        Ok(())
2371    }
2372
2373    /// `goto *p`, GNU's computed goto, which is a jump through a register.
2374    ///
2375    /// Where it goes is not written here and cannot be. Every block it can arrive at is on the
2376    /// block this ends, the way every other arm is, and which of them the address holds is decided
2377    /// while the program runs. So this is one instruction with one operand, and the arms are
2378    /// copied across by [`Self::edges`] like anybody else's.
2379    fn indirect_branch(&mut self, inst: Inst) -> Result<(), Unsupported> {
2380        let data = &self.source[inst];
2381        let &address = self.source[data.args].first().ok_or_else(|| self.unsupported(inst))?;
2382        let reg = self.reg_of(address)?;
2383        let block = self.at.expect("a block is being filled");
2384        let span = self.source.span(inst);
2385        let name = x86_64::BRANCH.indirect;
2386        let opcode = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{name}")));
2387        self.out.build(block, opcode).at(span).operand(mir::Operand::read(reg, self.gpr)).finish();
2388        Ok(())
2389    }
2390
2391    /// `__builtin_setjmp`, which writes down where the function is so that a `__builtin_longjmp`
2392    /// somewhere else can bring control back here, and answers zero on the way past.
2393    ///
2394    /// Four words of the buffer, the three gcc writes and one of this compiler's own, and then the
2395    /// block ends: everything after the save in the IR block is put into a new machine IR block,
2396    /// and the address of that block is what went into the buffer. That is the whole reason the
2397    /// block is split here. An address points at a label, a machine IR block is the only thing in
2398    /// this representation that has one, and a save is in the middle of a block rather than at the
2399    /// end of one.
2400    ///
2401    /// # How the answer gets back
2402    ///
2403    /// Through the frame rather than through a register. The save writes a zero into a word of its
2404    /// own frame, puts the address of that word in the buffer, and the new block reads the word
2405    /// back. The restore writes a one through the address it finds in the buffer before it goes.
2406    /// So one load answers zero on the way past and one on the way back, and neither path has to
2407    /// agree with the other about a register.
2408    ///
2409    /// gcc does it the other way round, with a second block that sets the answer to one and is
2410    /// what the restore arrives at. That block is one nothing in the function jumps to, and a
2411    /// machine IR whose blocks are walked from the entry has nowhere to put such a thing: the
2412    /// allocator lays a function out in the line it is going to be emitted in, and a block no edge
2413    /// reaches is not in that line. The word in the frame costs eight bytes of stack and one load,
2414    /// and it needs nothing said anywhere about a block arrived at from outside.
2415    ///
2416    /// # What the allocator is told
2417    ///
2418    /// That every register it hands out is gone at the end of the first block. That is what makes
2419    /// the rest of the function right on the way back: control arrives from a `__builtin_longjmp`
2420    /// in some other function, and the only two registers that puts back are the stack pointer and
2421    /// the frame pointer, so anything this function still wants has to be in the frame those two
2422    /// reach. It is said with a write of every one of those registers, which is the same thing a
2423    /// call says about the registers a callee may destroy, on an instruction with nothing else on
2424    /// it so that the stores above are not caught up in it.
2425    fn saves_place(&mut self, inst: Inst) -> Result<(), Unsupported> {
2426        let data = &self.source[inst];
2427        let result = data.first_result.ok_or_else(|| self.unsupported(inst))?;
2428        let &buffer = self.source[data.args].first().ok_or_else(|| self.unsupported(inst))?;
2429        let span = self.source.span(inst);
2430        let buf = self.reg_of(buffer)?;
2431        let at = self.at.expect("a block is being filled");
2432        let gpr = self.gpr;
2433        let moves = x86_64::FRAME.moves(gpr).expect("a class the target says how to move");
2434        let store = self.named(moves.store);
2435        let load = self.named(moves.load);
2436        let lea = self.named(x86_64::FRAME.lea);
2437        let put = self.named(x86_64::FRAME.imm);
2438        let nothing = x86_64::FRAME.pad.expect("a target with an instruction that does nothing");
2439        let nothing = self.named(nothing);
2440        self.stack.saves_place = true;
2441        let answer = self.answer_slot();
2442        let back = self.out.create_block();
2443
2444        // The zero this answers with, into the word a restore writes a one into.
2445        let zero = self.out.new_vreg(gpr);
2446        self.out.build(at, put).at(span).def(zero, gpr).imm(0).finish();
2447        let mem = self.frame_mem();
2448        let made = self.out.build(at, store).at(span).uses(zero, gpr).mem(mem).finish();
2449        self.stack.addresses.push((made, answer));
2450
2451        // The four words: where that word is, where control comes back to, and the two registers
2452        // the restore puts back.
2453        let found = self.frame_address(at, answer);
2454        self.write_word(at, span, store, found, buf, JUMP_ANSWER);
2455        let pc = self.out.new_vreg(gpr);
2456        self.out.build(at, lea).at(span).def(pc, gpr).mem(mir::Mem::block(back)).finish();
2457        self.write_word(at, span, store, pc, buf, JUMP_PC);
2458        let frame = mir::Reg::physical(self.conv.frame_pointer);
2459        self.write_word(at, span, store, frame, buf, JUMP_FRAME);
2460        let stack = mir::Reg::physical(self.conv.stack_pointer);
2461        self.write_word(at, span, store, stack, buf, JUMP_STACK);
2462
2463        // Nothing is in a register past this point, which is what the rest of the function is
2464        // allowed to assume about the way back in.
2465        let gone = self.across_jump();
2466        let mut build = self.out.build(at, nothing).at(span);
2467        for (reg, class) in gone {
2468            build = build.operand(mir::Operand::write(reg, class));
2469        }
2470        build.finish();
2471
2472        // And the rest of the block, which is the block the address above was of.
2473        *self.out.succs_mut(at) = vec![mir::BlockCall::to(back)];
2474        self.at = Some(back);
2475        let reg = self.new_reg(result);
2476        let mem = self.frame_mem();
2477        let made = self.out.build(back, load).at(span).def(reg, gpr).mem(mem).finish();
2478        self.stack.addresses.push((made, answer));
2479        Ok(())
2480    }
2481
2482    /// `__builtin_longjmp`, which reads a buffer a `__builtin_setjmp` filled in and goes there.
2483    ///
2484    /// Everything comes out of the buffer before anything is put back, and the four registers it
2485    /// comes out into are physical ones rather than values the allocator places. Both of those are
2486    /// about the same moment. The stack pointer is one of the things being put back, a value the
2487    /// allocator sent to the stack is reached through the stack pointer, and between the
2488    /// instruction that moves it and the jump there is no stack this function owns any more. A
2489    /// register named outright is a register nothing reloads into and nothing else is in, which is
2490    /// the only way to hold something across that moment.
2491    ///
2492    /// Four of them because that is how many things are in the air at once: where to go, the frame
2493    /// pointer to put back, the one the matching save is to answer with, and one register used
2494    /// twice, first for the address that one is written through and then for the stack pointer.
2495    ///
2496    /// Nothing after this in the block is reached. The marker is not a terminator, for the reason
2497    /// `spec/08-ir.md` gives, so the block goes on and whatever the front end wrote after it is
2498    /// written out and never run.
2499    fn comes_back(&mut self, inst: Inst) -> Result<(), Unsupported> {
2500        let data = &self.source[inst];
2501        let &buffer = self.source[data.args].first().ok_or_else(|| self.unsupported(inst))?;
2502        let span = self.source.span(inst);
2503        let buf = self.reg_of(buffer)?;
2504        let at = self.at.expect("a block is being filled");
2505        let gpr = self.gpr;
2506        let moves = x86_64::FRAME.moves(gpr).expect("a class the target says how to move");
2507        let load = self.named(moves.load);
2508        let store = self.named(moves.store);
2509        let mov = self.named(moves.mov);
2510        let put = self.named(x86_64::FRAME.imm);
2511        let jump = self.named(x86_64::BRANCH.indirect);
2512
2513        let held = self.jump_regs();
2514        if held.len() < JUMP_REGS {
2515            return Err(self.unsupported(inst));
2516        }
2517        let pc = mir::Reg::physical(held[0]);
2518        let frame = mir::Reg::physical(held[1]);
2519        let spare = mir::Reg::physical(held[2]);
2520        let one = mir::Reg::physical(held[3]);
2521
2522        self.read_word(at, span, load, pc, buf, JUMP_PC);
2523        self.read_word(at, span, load, frame, buf, JUMP_FRAME);
2524        self.read_word(at, span, load, spare, buf, JUMP_ANSWER);
2525
2526        // What the matching save answers with, written through the address that came out of the
2527        // buffer, because the word it goes in is in the other function's frame and this one has no
2528        // way of knowing where that is.
2529        self.out.build(at, put).at(span).def(one, gpr).imm(1).finish();
2530        let mem = mir::Mem::at(mir::Operand::read(spare, gpr));
2531        self.out.build(at, store).at(span).uses(one, gpr).mem(mem).finish();
2532
2533        // The stack last of the four, so that the register the buffer is reached through is done
2534        // with before the stack it may have been spilled to stops being this function's.
2535        self.read_word(at, span, load, spare, buf, JUMP_STACK);
2536        let stack = mir::Reg::physical(self.conv.stack_pointer);
2537        self.copy(at, span, mov, stack, spare);
2538        let base = mir::Reg::physical(self.conv.frame_pointer);
2539        self.copy(at, span, mov, base, frame);
2540
2541        // And the jump, which reads the two registers just put back as well as the address it
2542        // goes through. Neither of those is printed, because the target's spelling of an indirect
2543        // jump has one argument and it is the first one read. They are there because the code
2544        // control arrives at reaches its frame through them, and because without them the two
2545        // instructions above write registers nothing reads: a scheduler is then free to put the
2546        // jump in front of them, and at `-O2` it does.
2547        self.out
2548            .build(at, jump)
2549            .at(span)
2550            .operand(mir::Operand::read(pc, gpr))
2551            .operand(mir::Operand::read(stack, gpr))
2552            .operand(mir::Operand::read(base, gpr))
2553            .finish();
2554        Ok(())
2555    }
2556
2557    /// One word of the buffer of a `__builtin_setjmp`, written from a register.
2558    fn write_word(
2559        &mut self,
2560        at: mir::Block,
2561        span: Span,
2562        store: mir::Opcode,
2563        from: mir::Reg,
2564        buf: mir::Reg,
2565        word: i32,
2566    ) {
2567        let mem = mir::Mem::at(mir::Operand::read(buf, self.gpr)).plus(word);
2568        self.out.build(at, store).at(span).uses(from, self.gpr).mem(mem).finish();
2569    }
2570
2571    /// One word of that buffer, read back into a register.
2572    fn read_word(
2573        &mut self,
2574        at: mir::Block,
2575        span: Span,
2576        load: mir::Opcode,
2577        into: mir::Reg,
2578        buf: mir::Reg,
2579        word: i32,
2580    ) {
2581        let mem = mir::Mem::at(mir::Operand::read(buf, self.gpr)).plus(word);
2582        self.out.build(at, load).at(span).def(into, self.gpr).mem(mem).finish();
2583    }
2584
2585    /// One register into another, which is the one shape of instruction the builder has no word
2586    /// for because neither operand is a definition of a value or a read of memory.
2587    fn copy(
2588        &mut self,
2589        at: mir::Block,
2590        span: Span,
2591        mov: mir::Opcode,
2592        into: mir::Reg,
2593        from: mir::Reg,
2594    ) {
2595        self.out
2596            .build(at, mov)
2597            .at(span)
2598            .operand(mir::Operand::write(into, self.gpr))
2599            .operand(mir::Operand::read(from, self.gpr))
2600            .finish();
2601    }
2602
2603    /// The word a `__builtin_setjmp` in this function answers with, asked for once and kept.
2604    fn answer_slot(&mut self) -> usize {
2605        match self.answer {
2606            Some(index) => index,
2607            None => {
2608                let index = self.stack.locals.len();
2609                self.stack.locals.push(Local { size: JUMP_WORD, align: JUMP_WORD });
2610                self.answer = Some(index);
2611                index
2612            }
2613        }
2614    }
2615
2616    /// An address in this function's frame with nothing in its displacement, which is what an
2617    /// instruction reaching one of its stack objects is written with until [`crate::finish`] knows
2618    /// where the object is.
2619    fn frame_mem(&self) -> mir::Mem {
2620        mir::Mem::at(mir::Operand::read(mir::Reg::physical(self.conv.stack_pointer), self.gpr))
2621    }
2622
2623    /// Every register the allocator hands out, which is what a `__builtin_setjmp` destroys.
2624    ///
2625    /// Both files, since a `double` live across a save has the same problem an integer does. The
2626    /// two registers a frame is reached through are not here: the restore puts both of them back,
2627    /// which is the whole of what it puts back, and a function whose frame pointer was destroyed
2628    /// by its own save would have nothing left to find its caller with.
2629    fn across_jump(&self) -> Vec<(mir::Reg, RegClass)> {
2630        let mut gone = Vec::new();
2631        for &reg in self.conv.int_order {
2632            if reg == self.conv.stack_pointer || reg == self.conv.frame_pointer {
2633                continue;
2634            }
2635            gone.push((mir::Reg::physical(reg), self.gpr));
2636        }
2637        for &reg in self.conv.sse_order {
2638            gone.push((mir::Reg::physical(reg), self.conv.sse_class));
2639        }
2640        gone
2641    }
2642
2643    /// The registers a `__builtin_longjmp` may hold things in while it puts a frame back.
2644    ///
2645    /// The ones the allocator hands out, less the two a frame is reached through. The scratch
2646    /// registers are not among them on purpose: the rewriter writes a reload into one of those
2647    /// wherever it likes, and one of these has to survive from the load that fills it to the
2648    /// instruction that reads it however many instructions apart those are.
2649    fn jump_regs(&self) -> Vec<PhysReg> {
2650        self.conv
2651            .int_order
2652            .iter()
2653            .copied()
2654            .filter(|&reg| {
2655                reg != self.conv.stack_pointer
2656                    && reg != self.conv.frame_pointer
2657                    && !crate::pipeline::SCRATCH.contains(&reg)
2658            })
2659            .collect()
2660    }
2661
2662    /// A machine opcode of this target from the name the target gives it.
2663    fn named(&mut self, name: &str) -> mir::Opcode {
2664        mir::Opcode::new(self.names.intern(&format!("{PREFIX}{name}")))
2665    }
2666
2667    /// `__builtin_frame_address` and `__builtin_return_address`, which are a walk up the chain of
2668    /// saved frame pointers and then one thing read at the end of it.
2669    ///
2670    /// Every frame that kept a frame pointer holds the caller's at the address the register points
2671    /// at, and the address that frame returns to one word above that, which is where the call
2672    /// instruction put it and where the prologue's push left it. So the walk is a load through the
2673    /// register for each link, the frame address is wherever the walk stopped, and the return
2674    /// address is one more load from a word above it. gcc 16.2.0 writes exactly this, measured on
2675    /// x86-64 at `-O2` for depths zero to three of both builtins.
2676    ///
2677    /// The function is given a frame pointer because of this, which is what [`Stack::walks_frames`]
2678    /// carries out to the layout. A depth of zero needs it as the answer and every depth above zero
2679    /// needs it as the start, so there is no case here where it is not wanted.
2680    ///
2681    /// How far the chain actually reaches is the program's business and not this one's. A caller
2682    /// compiled without a frame pointer has no link in it for the walk to follow, so a depth above
2683    /// zero is a promise about how the whole program was built. That is why gcc documents a nonzero
2684    /// depth as unsafe rather than as an answer, and why the depth is refused above a limit in
2685    /// `check/builtin/frame.rs` rather than walked as far as it says.
2686    fn frames(&mut self, inst: Inst) -> Result<(), Unsupported> {
2687        let data = &self.source[inst];
2688        let Extra::Depth(depth) = data.extra else { return Err(self.unsupported(inst)) };
2689        let result = data.first_result.ok_or_else(|| self.unsupported(inst))?;
2690        let returning = data.opcode == Opcode::ReturnAddress;
2691        let block = self.at.expect("a block is being filled");
2692        let span = self.source.span(inst);
2693        let moves = x86_64::FRAME.moves(self.gpr).expect("a class the target says how to move");
2694        let load = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{}", moves.load)));
2695        self.stack.walks_frames = true;
2696
2697        // Where the walk is up to. The frame pointer to begin with, and the register the last load
2698        // wrote after that.
2699        let reg = self.new_reg(result);
2700        let mut base = mir::Reg::physical(self.conv.frame_pointer);
2701        for link in 0..depth {
2702            // The last load of a walk that is looking for a frame writes the answer itself, which
2703            // is what keeps a walk of so many links that many instructions and not one more.
2704            let ends_here = link + 1 == depth && !returning;
2705            let next = if ends_here { reg } else { self.out.new_vreg(self.gpr) };
2706            let at = mir::Mem::at(mir::Operand::read(base, self.gpr));
2707            self.out.build(block, load).at(span).def(next, self.gpr).mem(at).finish();
2708            base = next;
2709        }
2710
2711        if returning {
2712            let up = i32::try_from(self.conv.return_address).expect("a word above the frame");
2713            let at = mir::Mem::at(mir::Operand::read(base, self.gpr)).plus(up);
2714            self.out.build(block, load).at(span).def(reg, self.gpr).mem(at).finish();
2715        } else if depth == 0 {
2716            // The one case with no load in it at all: the frame this function is running in is the
2717            // register itself, and a physical register is not one the allocator hands out, so the
2718            // answer is a copy of it.
2719            let mov = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{}", moves.mov)));
2720            self.out
2721                .build(block, mov)
2722                .at(span)
2723                .operand(mir::Operand::write(reg, self.gpr))
2724                .operand(mir::Operand::read(base, self.gpr))
2725                .finish();
2726        }
2727        Ok(())
2728    }
2729
2730    /// `__builtin_thread_pointer`, which is the front of the block [`Self::thread_address`] adds
2731    /// an offset to.
2732    ///
2733    /// The same one instruction, on its own this time and with nothing to add to it. A program
2734    /// writes this when what it wants is a number that is different in every thread and cheap to
2735    /// come by, rather than a variable of its own in the block, so there is no relocation here and
2736    /// no name for the link to resolve.
2737    fn thread_pointer(&mut self, inst: Inst) -> Result<(), Unsupported> {
2738        let result = self.source[inst].first_result.ok_or_else(|| self.unsupported(inst))?;
2739        let block = self.at.expect("a block is being filled");
2740        let span = self.source.span(inst);
2741        let reg = self.new_reg(result);
2742        let load = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{GOT_LOAD}")));
2743        let at = mir::Mem::in_segment(Segment::Fs, 0);
2744        self.out.build(block, load).at(span).def(reg, self.gpr).mem(at).finish();
2745        Ok(())
2746    }
2747
2748    /// What a named machine register holds, which is `register long x asm ("rbx");`.
2749    ///
2750    /// One move out of that register, with the register named as itself the way a register a
2751    /// template wrote is named, which is [`Self::itself`] and is the thing #1653 built. What it
2752    /// buys here is what it buys there: the register is part of the instruction the allocator
2753    /// sees, so it is a use the allocator will not have written over first, and the value goes
2754    /// into an ordinary one of its own that everything downstream reads.
2755    ///
2756    /// The whole sixty four bits are moved whatever the type is, because the register is that
2757    /// wide and a narrower type reads the low end of the copy, which is the same low end. A type
2758    /// wider than the register is refused, since there is no register holding it to read.
2759    ///
2760    /// A name the machine has not got is refused too, and is the only thing that can be wrong
2761    /// with the string: which register a name means is this machine's question and this is where
2762    /// the question is asked, at the same table `asm` asks about clobbers at. The sigil gcc
2763    /// allows in front of it is taken off here, because what the name is written with is syntax.
2764    fn register_value(&mut self, inst: Inst) -> Result<(), Unsupported> {
2765        let Extra::Symbol(symbol) = self.source[inst].extra else {
2766            return Err(self.unsupported(inst));
2767        };
2768        let result = self.source[inst].first_result.ok_or_else(|| self.unsupported(inst))?;
2769        let ty = self.source[result].ty;
2770        let bits = if ty.is_ptr() { ADDRESS_BITS } else { ty.bits() };
2771        if bits > ADDRESS_BITS {
2772            return Err(self.unsupported(inst));
2773        }
2774        let spelled = self.names.resolve(symbol).to_owned();
2775        let named = x86_64::gpr_named(spelled.strip_prefix('%').unwrap_or(&spelled));
2776        let Some((held, _)) = named else {
2777            return Err(Unsupported::Register { inst, name: spelled });
2778        };
2779        let block = self.at.expect("a block is being filled");
2780        let span = self.source.span(inst);
2781        let mov = x86_64::FRAME.moves(self.gpr).expect("a class the target says how to move").mov;
2782        let mov = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{mov}")));
2783        let into = self.new_reg(result);
2784        self.out
2785            .build(block, mov)
2786            .at(span)
2787            .operand(mir::Operand::write(into, self.gpr))
2788            .operand(
2789                mir::Operand::read(mir::Reg::physical(held), self.gpr)
2790                    .with(Constraint::Fixed(held)),
2791            )
2792            .finish();
2793        Ok(())
2794    }
2795
2796    /// A conversion that converts nothing: the result is the operand under another type.
2797    ///
2798    /// `ptrtoint` and `inttoptr` at one width are the whole of this. An address on this machine is
2799    /// an integer as wide as the machine addresses, so a cast between the two changes what the
2800    /// type system calls the value and changes nothing about the value, and the register holding
2801    /// it is the register that already held it. The front end never writes either of them at any
2802    /// other width, because it widens or narrows around the cast rather than through it, so the
2803    /// two widths disagreeing here means the IR came from somewhere else and is refused rather
2804    /// than guessed at.
2805    ///
2806    /// Reading the operand first is what materializes it when it is a constant, which is the case
2807    /// that matters: a null pointer is an `inttoptr` of zero, and that zero has to reach a
2808    /// register before anything can call it an address.
2809    fn rename(&mut self, inst: Inst) -> Result<(), Unsupported> {
2810        let data = &self.source[inst];
2811        let [arg] = self.source[data.args] else { return Err(self.unsupported(inst)) };
2812        let result = data.first_result.ok_or_else(|| self.unsupported(inst))?;
2813        if !self.is_address_width(self.source[arg].ty)
2814            || !self.is_address_width(self.source[result].ty)
2815        {
2816            return Err(self.unsupported(inst));
2817        }
2818        let reg = self.reg_of(arg)?;
2819        self.regs[result.index()] = Some(reg);
2820        Ok(())
2821    }
2822
2823    /// One barrier, which on this machine is one instruction at the strongest ordering and no
2824    /// instruction at all at every other one.
2825    ///
2826    /// x86-64 is total store order, so the only reordering the machine does is a store followed by
2827    /// a load of a different address, and the only ordering that forbids that is sequential
2828    /// consistency. An acquire, a release and an acquire release fence are therefore already true
2829    /// of every program running here, and what a program wanted from writing one is that the
2830    /// compiler not move memory accesses across it. The optimizer has finished by the time this
2831    /// runs and nothing below reorders one access past another, so the constraint is already
2832    /// discharged and there is nothing to write.
2833    ///
2834    /// The strongest one is `mfence`, which is what gcc 16.2.0 writes for
2835    /// `__atomic_thread_fence(__ATOMIC_SEQ_CST)` and for `__sync_synchronize`. A locked instruction
2836    /// on the stack is faster on most parts and is what some compilers write instead; it is also a
2837    /// write to memory the program did not ask for, and the plain barrier is the one that says what
2838    /// it means.
2839    ///
2840    /// Written here by name rather than by a rule, for the same reason a `lea` of a symbol is:
2841    /// there is nothing in a barrier that a proof over bitvectors could discharge. It computes
2842    /// nothing, so there is no equality to state, and what makes it the right answer is the memory
2843    /// model, which the rule language cannot talk about.
2844    fn barrier(&mut self, inst: Inst) -> Result<(), Unsupported> {
2845        let Extra::Order(order) = self.source[inst].extra else {
2846            return Err(self.unsupported(inst));
2847        };
2848        if order != MemOrder::SeqCst {
2849            return Ok(());
2850        }
2851        let block = self.at.expect("a block is being filled");
2852        let span = self.source.span(inst);
2853        let fence = mir::Opcode::new(self.names.intern("x64.mfence"));
2854        self.out.build(block, fence).at(span).finish();
2855        Ok(())
2856    }
2857
2858    /// The instruction a program stops on, which is one byte pair and no operands.
2859    ///
2860    /// `ud2` is an opcode the manual promises will never be given a meaning, so a processor that
2861    /// reaches it raises the fault for an instruction it does not know, and on Linux that arrives
2862    /// at the program as `SIGILL`. That is what `__builtin_trap` is for: a stop that cannot be
2863    /// caught by anything the program installed for an ordinary error, cannot be returned from,
2864    /// and leaves the address of the fault in the core file.
2865    ///
2866    /// Why not a call to `abort`. It is two bytes against a call and a relocation, it needs no
2867    /// library, and it works in the places this one is written most, which are a kernel and a
2868    /// freestanding program that has no `abort` to call. gcc 16.2.0 writes `ud2` here too.
2869    fn trap(&mut self, inst: Inst) {
2870        let block = self.at.expect("a block is being filled");
2871        let span = self.source.span(inst);
2872        let stop = mir::Opcode::new(self.names.intern("x64.ud2"));
2873        self.out.build(block, stop).at(span).finish();
2874    }
2875
2876    /// One hint that an address is about to be used, which is one instruction and no promise.
2877    ///
2878    /// Four instructions on this machine and the locality picks between them, which is what the
2879    /// number means: how much of the data will still be wanted after the access. None of it wanted
2880    /// is `prefetchnta`, which brings the line in without keeping it, and all of it wanted is
2881    /// `prefetcht0`, which brings it as close as the machine can. The two in between are the levels
2882    /// between those. Measured against gcc 16.2.0 on x86-64 rather than read off the manual: zero
2883    /// gives `prefetchnta`, one `prefetcht2`, two `prefetcht1` and three `prefetcht0`.
2884    ///
2885    /// Whether the access will write is not read here, and that is this machine rather than an
2886    /// omission. The write hint is `prefetchw`, which is not in the base instruction set, and gcc
2887    /// writes it only when the command line said the part has it. So a prefetch for a write is the
2888    /// same instruction as a prefetch for a read, which is what gcc 16.2.0 writes without
2889    /// `-mprfchw`, and the difference is carried in the IR for a target that can use it.
2890    ///
2891    /// The address goes in the addressing mode rather than in an operand, the way a store's does.
2892    /// It is built here as the plainest one there is, a register and nothing else, because what
2893    /// arrives is a value and folding an addition into the mode is a rule's job and no rule reaches
2894    /// this instruction. An address the program computed is therefore one `lea` or one add in front
2895    /// of this, which is what it would have been for the load the hint is about anyway.
2896    fn hint(&mut self, inst: Inst) -> Result<(), Unsupported> {
2897        let Extra::Prefetch(hint) = self.source[inst].extra else {
2898            return Err(self.unsupported(inst));
2899        };
2900        let args: Vec<Value> = self.source[self.source[inst].args].to_vec();
2901        let [address] = args[..] else { return Err(self.unsupported(inst)) };
2902        let name = match hint.locality {
2903            0 => "prefetch_nta",
2904            1 => "prefetch_t2",
2905            2 => "prefetch_t1",
2906            PrefetchHint::MOST => "prefetch_t0",
2907            // Nothing else exists. The checker reads a locality outside the range as zero and the
2908            // verifier refuses one that got here another way, so this is a hint that was built
2909            // rather than checked, and the safe answer for a hint is to write no instruction.
2910            _ => return Err(self.unsupported(inst)),
2911        };
2912        let base = self.reg_of(address)?;
2913        let block = self.at.expect("a block is being filled");
2914        let opcode = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{name}")));
2915        self.out
2916            .build(block, opcode)
2917            .at(self.source.span(inst))
2918            .mem(mir::Mem::at(mir::Operand::read(base, self.gpr)))
2919            .finish();
2920        Ok(())
2921    }
2922
2923    /// One compare and exchange, which is the instruction every other atomic on this machine is
2924    /// built out of.
2925    ///
2926    /// What the IR asks for is: read what is at an address, compare it against a value the program
2927    /// expected, put a second value there if the two were equal, and say both what was read and
2928    /// whether the exchange happened. The machine has exactly that instruction, and the `lock` in
2929    /// front of it is what makes the whole of it one step as far as every other processor is
2930    /// concerned.
2931    ///
2932    /// The ordering is not read here, and that is the memory model rather than an omission. A
2933    /// locked instruction on x86-64 is a full barrier whatever the program asked for, so a relaxed
2934    /// compare and exchange and a sequentially consistent one are the same instruction, and there
2935    /// is nothing weaker to emit for the weaker orderings. The failure ordering is not read for the
2936    /// same reason.
2937    ///
2938    /// The two values it produces are why this is written by name. The one the program compares
2939    /// against and the one it gets back are both `rax`, which the instruction reads and writes
2940    /// without being told, and the table says so with a fixed constraint at each end rather than
2941    /// leaving the allocator to find out. The second value is the byte behind it, which is the zero
2942    /// flag read out by a `sete`, and it is a definition of the same instruction so that the
2943    /// allocator knows the two are live together and never gives the byte the register the answer
2944    /// is in.
2945    fn exchange(&mut self, inst: Inst) -> Result<(), Unsupported> {
2946        let args: Vec<Value> = self.source[self.source[inst].args].to_vec();
2947        let results: Vec<Value> = self.source[inst].results().collect();
2948        let [addr, expected, desired] = args[..] else { return Err(self.unsupported(inst)) };
2949        let [old, exchanged] = results[..] else { return Err(self.unsupported(inst)) };
2950
2951        // A value the machine can compare in one instruction, which is an integer or an address at
2952        // one of the four widths it has a compare and exchange for. Anything else is a type this
2953        // has no instruction for rather than a program that is wrong, and the front end refuses it
2954        // before ever getting here.
2955        let ty = self.source[old].ty;
2956        let bits = if ty.is_ptr() { ADDRESS_BITS } else { ty.bits() };
2957        if (!ty.is_int() && !ty.is_ptr()) || !matches!(bits, 8 | 16 | 32 | 64) {
2958            return Err(self.unsupported(inst));
2959        }
2960
2961        let base = self.reg_of(addr)?;
2962        let want = self.reg_of(expected)?;
2963        let put = self.reg_of(desired)?;
2964        let got = self.new_reg(old);
2965        let flag = self.new_reg(exchanged);
2966
2967        let name = format!("cmpxchg_{bits}");
2968        let form = x86_64::form(&name).ok_or_else(|| self.unsupported(inst))?;
2969        let block = self.at.expect("a block is being filled");
2970        let opcode = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{name}")));
2971        let (span, flags) = (self.source.span(inst), self.carried(inst));
2972        let mut build = self.out.build(block, opcode).at(span).flags(flags);
2973        for (desc, reg) in form.operands().iter().zip([got, flag, want, put]) {
2974            let operand = mir::Operand {
2975                reg,
2976                class: desc.class,
2977                role: desc.role,
2978                constraint: desc.constraint,
2979            };
2980            build = build.operand(operand);
2981        }
2982        build.mem(mir::Mem::at(mir::Operand::read(base, self.gpr))).finish();
2983        Ok(())
2984    }
2985
2986    /// One read modify write, for the three operations this machine does in a single instruction.
2987    ///
2988    /// What the IR asks for is: read what is at an address, do something to it, put the answer back,
2989    /// say what was there before, and let nothing get between the three steps. The machine has
2990    /// `xchg` for putting a value there and `lock xadd` for adding one, and both leave what they
2991    /// found in the register the operand arrived in, which is why the value that comes back and the
2992    /// value that went in are one register here.
2993    ///
2994    /// A subtraction is the add over the negated operand, which is right at every width because the
2995    /// machine's arithmetic wraps and negating then adding is subtracting in two's complement
2996    /// whatever the operands were. The negate is a separate instruction in front, over a register of
2997    /// its own, so that the value the program handed over is not the one written on: an operand may
2998    /// be live after this and a program that read it again would read the negation.
2999    ///
3000    /// The ordering is not read, for the reason the compare and exchange beside this does not read
3001    /// it. `xchg` with memory locks the bus whether it is asked to or not and `lock xadd` is asked
3002    /// to, so both are full barriers on this machine and there is nothing weaker to fall to.
3003    ///
3004    /// Eight of the other ten never arrive, because `crate::retry` turned each of them into a loop
3005    /// around a compare and exchange before anything here saw it. The two that do arrive are the
3006    /// ones on floating values, and they are refused: a compare and exchange of a float wants the
3007    /// value carried through an integer of the same width, and an eighty bit float has no such
3008    /// width. Neither family of builtins can write one yet either, so a program that reaches this
3009    /// refusal is a program that reached an unimplemented builtin first.
3010    fn modify(&mut self, inst: Inst) -> Result<(), Unsupported> {
3011        let Extra::Rmw(op, _) = self.source[inst].extra else {
3012            return Err(self.unsupported(inst));
3013        };
3014        let args: Vec<Value> = self.source[self.source[inst].args].to_vec();
3015        let [addr, operand] = args[..] else { return Err(self.unsupported(inst)) };
3016        let old = self.source[inst].first_result.ok_or_else(|| self.unsupported(inst))?;
3017
3018        // A value the machine can exchange in one instruction, which is an integer at one of the
3019        // four widths it has these for. A pointer arrives as an address, so it is an integer by the
3020        // time it is here, and anything else is a type this has no instruction for.
3021        let ty = self.source[old].ty;
3022        if !ty.is_int() || !matches!(ty.bits(), 8 | 16 | 32 | 64) {
3023            return Err(self.unsupported(inst));
3024        }
3025        let name = match op {
3026            RmwOp::Xchg => format!("xchg_{}", ty.bits()),
3027            RmwOp::Add | RmwOp::Sub => format!("xadd_{}", ty.bits()),
3028            _ => return Err(self.unsupported(inst)),
3029        };
3030
3031        let base = self.reg_of(addr)?;
3032        let mut put = self.reg_of(operand)?;
3033        let block = self.at.expect("a block is being filled");
3034        let span = self.source.span(inst);
3035        if op == RmwOp::Sub {
3036            let negated = self.out.new_vreg(self.gpr);
3037            let negate =
3038                mir::Opcode::new(self.names.intern(&format!("{PREFIX}neg_r_{}", ty.bits())));
3039            let form = x86_64::form(&format!("neg_r_{}", ty.bits()))
3040                .ok_or_else(|| self.unsupported(inst))?;
3041            let mut build = self.out.build(block, negate).at(span);
3042            for (desc, reg) in form.operands().iter().zip([negated, put]) {
3043                build = build.operand(mir::Operand {
3044                    reg,
3045                    class: desc.class,
3046                    role: desc.role,
3047                    constraint: desc.constraint,
3048                });
3049            }
3050            build.finish();
3051            put = negated;
3052        }
3053
3054        let got = self.new_reg(old);
3055        let form = x86_64::form(&name).ok_or_else(|| self.unsupported(inst))?;
3056        let opcode = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{name}")));
3057        let flags = self.carried(inst);
3058        let mut build = self.out.build(block, opcode).at(span).flags(flags);
3059        for (desc, reg) in form.operands().iter().zip([got, put]) {
3060            build = build.operand(mir::Operand {
3061                reg,
3062                class: desc.class,
3063                role: desc.role,
3064                constraint: desc.constraint,
3065            });
3066        }
3067        build.mem(mir::Mem::at(mir::Operand::read(base, self.gpr))).finish();
3068        Ok(())
3069    }
3070
3071    /// One `asm` statement.
3072    ///
3073    /// An empty template is most of the inline assembly in a test suite, and it is not a corner
3074    /// case somebody wrote by accident. A program that wants a value computed where it stands, or a
3075    /// loop the optimizer must not touch, writes `asm volatile ("" : : : "memory")`, and forty
3076    /// years of bug reports about optimizers are full of them. What such a statement asks for is
3077    /// the barrier and the operand places, and no instructions at all.
3078    ///
3079    /// So the operands are the half that is always real: a constraint says where a value has to be,
3080    /// and where it has to be is still true when the template between them is empty.
3081    ///
3082    /// What the constraints ask for, on an empty template, is only ever that two operands share a
3083    /// place. Nothing reads a register no text names, so `"r"` on its own asks for a register and
3084    /// no particular one, and any register at all answers it. A matching constraint is different,
3085    /// because it says the output the assembly leaves is the place the input arrived in, and with
3086    /// no instructions between them that is the input unchanged. So it is a rename and not a move:
3087    /// the value is already in a register and the result is that register.
3088    ///
3089    /// An output nothing is tied to and no instruction writes is whatever the assembly left there,
3090    /// which for a template that writes nothing is whatever was in the register. That is a value
3091    /// the program is not entitled to, and this writes a zero rather than reading one, because the
3092    /// allocator has to be given a definition before a use whatever the program is entitled to.
3093    ///
3094    /// # A template with instructions in it
3095    ///
3096    /// [`x86_64::read`] turns the text into the opcodes this backend already has, which is what
3097    /// `spec/11-asm-objects-debug.md` section 11.1 asks for: the machine is described once, and an
3098    /// instruction a program wrote is looked up in that description rather than copied through to
3099    /// an assembler that has one of its own. So nothing here assembles anything. What it does is
3100    /// put the statement's operands where the opcode holds them, and from there an `asm` statement
3101    /// is ordinary machine code: the allocator picks the registers, the listing and the object file
3102    /// are written from the same table as every other instruction, and a spill around one works
3103    /// because there is nothing left about it for a spill to get wrong.
3104    ///
3105    /// A register the template named in its own text is the one thing in there that is nobody's
3106    /// operand, and it is placed as itself. See [`Self::itself`] for why that is safer here than
3107    /// the thing gcc does, which is to copy the name out and leave the allocator none the wiser.
3108    ///
3109    /// Two things are refused, both for one reason, which is that placing them by a guess gives a
3110    /// program that assembles into something other than what it says.
3111    ///
3112    /// An output the template writes more than once, which is one place with two definitions in it,
3113    /// and the machine IR between here and the allocator has one definition per register by
3114    /// construction. An output tied to an input and written once is not that: it is two registers
3115    /// the description ties together, which is what [`Place`] is about.
3116    ///
3117    /// An operand read where the opcode writes, or written where it reads. An output that has not
3118    /// been written yet is not a value, and an input the assembly writes over is a value something
3119    /// else may still be using.
3120    ///
3121    /// # A register the instruction uses without being told
3122    ///
3123    /// An instruction may reach a register its text does not name, and `cpuid` is all of them at
3124    /// once: the leaf goes in `eax`, the subleaf in `ecx`, and the answer comes back in all four
3125    /// registers. The description holds every bit of that already, so what is left is to say which
3126    /// of the statement's operands is in each of those registers, and the constraint letter is the
3127    /// one thing in an assembly statement that says it. `"=a"` is an output in `rax` and `"c"` is
3128    /// an input in `rcx`, which is why a program writing `cpuid` writes its constraints that way
3129    /// and has no choice about it.
3130    ///
3131    /// A register no letter named is one the statement put nothing in, and that is the usual case
3132    /// rather than an unusual one, since an instruction that answers four questions is written by
3133    /// programs that asked one. A write of one is the register being destroyed and gets a register
3134    /// of its own, which is what tells the allocator to keep everything else out of it. A read of
3135    /// one is a register the instruction looks at and the program never filled, which gets a zero
3136    /// for the reason [`Self::undefined`] gives.
3137    ///
3138    /// # The clobber list
3139    ///
3140    /// Read now, as the registers it names being written by every instruction of the template. By
3141    /// every one rather than by one of them, because the list says the assembly as a whole leaves
3142    /// them ruined and nothing here knows which line did it. Every entry has to be a register this
3143    /// machine has a name for or the statement is refused, since a name nobody read is a register
3144    /// nobody is keeping out of.
3145    ///
3146    /// `memory` and `cc` are the two entries that are not registers and both are skipped. `memory`
3147    /// says the assembly touches storage, which is already true of every `asm` this writes and is
3148    /// nothing a register list could hold. `cc` says it ruins the condition flags, and the flag
3149    /// tracking already has that from the instructions the template was read into, since it takes
3150    /// every instruction it does not recognize as writing them and every instruction here is one
3151    /// this machine describes.
3152    ///
3153    /// A clobber the instruction already writes is left off it. `cpuid` writes all four registers
3154    /// by description, and a statement listing three of them as clobbers as well is saying the
3155    /// same thing twice, which the allocator would read as one register with two definitions.
3156    ///
3157    /// On a template with nothing in it the list is ignored, as it was before, since a template
3158    /// with no instructions ruins nothing whatever it said about what it ruins.
3159    fn assembly(&mut self, inst: Inst) -> Result<(), Unsupported> {
3160        let data = &self.source[inst];
3161        let Extra::Asm(asm) = data.extra else { return Err(self.unsupported(inst)) };
3162        let info = self.source[asm];
3163        if !self.source[info.targets].is_empty() {
3164            return Err(Unsupported::Assembly { inst, refused: Written::Goto });
3165        }
3166        let refused = || Unsupported::Assembly { inst, refused: Written::Operand };
3167
3168        let constraints = self.names.resolve(info.constraints).to_string();
3169        let results: Vec<Value> = data.results().collect();
3170        let operands = AsmOperands::read(&constraints, &results, &self.source[data.args])
3171            .ok_or_else(refused)?;
3172        let list: Vec<AsmOperand<'_>> = operands.iter().copied().collect();
3173
3174        // Read after the constraints and not before them, because a mnemonic whose suffix the
3175        // program left off is read at the width of the operands it names, and the operands are
3176        // what the constraints are a list of.
3177        let widths: Vec<Option<x86_64::Width>> = list
3178            .iter()
3179            .map(|operand| {
3180                let ty = self.source[operand.result.or(operand.value)?].ty;
3181                if !ty.is_scalar() {
3182                    return None;
3183                }
3184                x86_64::Width::of_bits(if ty.is_ptr() { ADDRESS_BITS } else { ty.bits() })
3185            })
3186            .collect();
3187        let template = self.names.resolve(info.template).to_string();
3188        let steps = if template.trim().is_empty() {
3189            Vec::new()
3190        } else {
3191            x86_64::read(&template, &widths)
3192                .ok_or(Unsupported::Assembly { inst, refused: Written::Template })?
3193        };
3194
3195        // Which operands the template writes, counted before anything is placed, because the answer
3196        // decides where each of the three below comes from and one instruction may name an operand
3197        // that a later one writes. Which of them any instruction puts in a register at all is
3198        // counted in the same walk, since an operand no instruction reaches that way is one nothing
3199        // has to put anywhere: a constant a template names only as the distance into an address is
3200        // written into the instruction, and a register holding a copy of it would be one nobody
3201        // reads. An operand the address is counted from is reached that way and is counted here for
3202        // that reason, because the walk below it is over the opcode's operands and an address is
3203        // not one of those.
3204        let mut writes = vec![0usize; list.len()];
3205        let mut reads = vec![false; list.len()];
3206        let mut held = vec![false; list.len()];
3207        for step in &steps {
3208            let x86_64::Step::Line(line) = step else { continue };
3209            match line.at.and_then(|at| at.base) {
3210                Some(x86_64::Piece::Operand { index, .. }) => {
3211                    *held.get_mut(index).ok_or_else(refused)? = true;
3212                }
3213                Some(x86_64::Piece::Reg { reg, .. }) => {
3214                    if let Some(index) = bound(&list, reg, Role::Use) {
3215                        *held.get_mut(index).ok_or_else(refused)? = true;
3216                    }
3217                }
3218                _ => {}
3219            }
3220            let form = x86_64::form(line.opcode).ok_or_else(refused)?;
3221            // Which registers the instruction reaches, asked the same way it is asked again when
3222            // the instruction is written. See [`Self::lettered`] for the one opcode whose answer
3223            // comes from the constraint letters rather than from the description.
3224            let lettered = (line.opcode == x86_64::LITERAL).then(|| self.lettered(&list));
3225            let (described, pieces) = match &lettered {
3226                Some((described, pieces)) => (described.as_slice(), pieces.as_slice()),
3227                None => (form.operands(), line.operands.as_slice()),
3228            };
3229            for (desc, piece) in described.iter().zip(pieces) {
3230                // An operand the instruction reaches without its text saying so is the statement's
3231                // only when a constraint letter put something there. One that is nobody's writes
3232                // nothing of the program's, so it is counted nowhere and is dealt with where it is
3233                // placed.
3234                let index = match *piece {
3235                    x86_64::Piece::Operand { index, .. } => index,
3236                    x86_64::Piece::Implicit { reg } => match bound(&list, reg, desc.role) {
3237                        Some(index) => index,
3238                        None => continue,
3239                    },
3240                    x86_64::Piece::Reg { reg, .. } => match bound(&list, reg, desc.role) {
3241                        Some(index) => index,
3242                        None => continue,
3243                    },
3244                };
3245                *held.get_mut(index).ok_or_else(refused)? = true;
3246                if matches!(desc.role, Role::Def | Role::EarlyDef) {
3247                    *writes.get_mut(index).ok_or_else(refused)? += 1;
3248                } else {
3249                    *reads.get_mut(index).ok_or_else(refused)? = true;
3250                }
3251            }
3252        }
3253
3254        // Where every operand is. Worked out in full before the first instruction is written, since
3255        // reading a value may be what puts it in a register in the first place, and that has to
3256        // happen in front of the assembly rather than in the middle of it.
3257        let mut places: Vec<Place> = vec![Place::default(); list.len()];
3258        for (index, operand) in list.iter().copied().enumerate() {
3259            let Some(result) = operand.result else {
3260                // An input, or an output the assembly was handed the address of, and both are a
3261                // value that arrives in a register and is read out of it, unless no instruction of
3262                // the template reads it out of one.
3263                let value = operand.value.ok_or_else(refused)?;
3264                if held[index] {
3265                    places[index].read = Some(self.reg_of(value)?);
3266                }
3267                continue;
3268            };
3269            let ty = self.source[result].ty;
3270            if on_x87(ty) || writes[index] > 1 {
3271                return Err(refused());
3272            }
3273            let tied = operands.tied_to(index);
3274            if let Some(from) = tied {
3275                if self.class_of(self.source[from].ty) != self.class_of(ty) {
3276                    return Err(refused());
3277                }
3278                places[index].read = Some(self.reg_of(from)?);
3279            }
3280            if writes[index] == 1 {
3281                places[index].write = Some(self.new_reg(result));
3282                continue;
3283            }
3284            match tied {
3285                // The place the input arrived in, which the assembly wrote nothing over. One
3286                // register, so this is a rename rather than a move.
3287                Some(_) => {
3288                    let reg = places[index].read.ok_or_else(refused)?;
3289                    self.regs[result.index()] = Some(reg);
3290                    places[index].write = Some(reg);
3291                }
3292                None => {
3293                    self.undefined(inst, result)?;
3294                    places[index].write = self.regs[result.index()];
3295                }
3296            }
3297        }
3298
3299        // An output an instruction of the template also reads, which the statement said nothing
3300        // about because an output is what a statement says the other thing about. What it holds
3301        // there is undefined, and a program writing one means it: `sbb %0, %0` in libgmp's
3302        // `add_mssaaaa` subtracts a register from itself and is asking for the borrow bit rather
3303        // than for the number, so whatever the register held, the answer is the same. Undefined is
3304        // not the same as absent though, since the allocator is owed a definition in front of every
3305        // use, so it gets the zero an output nothing wrote gets and for the same reason.
3306        for index in 0..list.len() {
3307            if !reads[index] || places[index].read.is_some() || places[index].write.is_none() {
3308                continue;
3309            }
3310            places[index].read = Some(self.seeded(inst, list[index])?);
3311        }
3312
3313        // Worked out once for the whole template, since the list is one list and every instruction
3314        // of the template gets it. Not worked out at all for a template with no instructions, which
3315        // is where there is nothing for it to go on.
3316        let clobbers = self.names.resolve(info.clobbers).to_string();
3317        let clobbered =
3318            if steps.is_empty() { Vec::new() } else { Self::clobbered(inst, &clobbers)? };
3319
3320        // A template with a label in it is not one run of instructions, and what it is instead is
3321        // in [`Self::woven`]. Every other template is what it has always been, which is every
3322        // instruction of it written into the block the statement stands in.
3323        if steps.iter().any(|step| !matches!(step, x86_64::Step::Line(_))) {
3324            return self.woven(inst, &steps, &mut places, &list, &clobbered, &writes);
3325        }
3326        for step in &steps {
3327            let x86_64::Step::Line(line) = step else { continue };
3328            self.instruction(inst, line, &places, &list, &clobbered)?;
3329        }
3330        Ok(())
3331    }
3332
3333    /// A register holding a zero, for an operand of a template that is read before anything filled
3334    /// it.
3335    ///
3336    /// Two things ask for this and they are the same thing twice. An output the template reads has
3337    /// nothing to be read out of until the instruction that writes it has run, and a loop carries
3338    /// an operand into a block before the instruction that fills it, so both are a use in front of
3339    /// every definition. What the program is owed there is nothing, since the value is undefined
3340    /// either way, and what the allocator is owed is a register something wrote.
3341    fn seeded(&mut self, inst: Inst, operand: AsmOperand<'_>) -> Result<mir::Reg, Unsupported> {
3342        let refused = || Unsupported::Assembly { inst, refused: Written::Operand };
3343        let value = operand.result.or(operand.value).ok_or_else(refused)?;
3344        let class = self.class_of(self.source[value].ty);
3345        if class != self.gpr {
3346            return Err(refused());
3347        }
3348        let block = self.at.expect("a block is being filled");
3349        let reg = self.out.new_vreg(class);
3350        let put = mir::Opcode::new(self.names.intern(&format!("{PREFIX}mov_ri_64")));
3351        self.out.build(block, put).at(self.source.span(inst)).def(reg, class).imm(0).finish();
3352        Ok(reg)
3353    }
3354
3355    /// A template with labels in it, as the blocks its jumps leave and arrive at.
3356    ///
3357    /// A statement is an instruction of the IR and stands inside one block, so a template that
3358    /// jumps has to stop being one thing. Each label becomes a block, each jump ends the block it
3359    /// stands in and gives it two arms, and whatever follows the statement goes into whichever
3360    /// block the walk finished in, which is what [`Self::block`] already reads off `self.at` and
3361    /// what [`Self::saves_place`] already does for the same reason.
3362    ///
3363    /// # What is carried between them
3364    ///
3365    /// The machine IR here is in the form where a register is written once, so an operand written
3366    /// inside a loop and read again at the top of it cannot be one register. What arrives at the
3367    /// top is a parameter of that block, and every jump to it carries whichever register held the
3368    /// operand where the jump stands. That is the whole of the bookkeeping: every block a label
3369    /// made takes one parameter for each operand that is in a register at all, in one order, so an
3370    /// arm's arguments and a block's parameters are the same list read twice.
3371    ///
3372    /// Which register an operand is in at each point is kept in the read half of its place, since
3373    /// that is what the instructions below read it out of. An instruction that writes an operand
3374    /// leaves it in the register it wrote, and a jump below carries that one. The block an
3375    /// untaken jump falls into is arrived at one way only and so takes no parameters, and nothing
3376    /// about where the operands are changes there.
3377    ///
3378    /// An operand written by the template and filled by nothing is written as a zero first, for
3379    /// the reason [`Self::undefined`] gives and one more: a jump may carry it before the
3380    /// instruction that fills it has run, and an argument has to be a register something wrote.
3381    ///
3382    /// # The condition state
3383    ///
3384    /// Nothing carries it and nothing has to. The instruction that sets it and the jump that reads
3385    /// it are both written here, next to each other in one block, and what the allocator may put
3386    /// between them is a move, which on this machine leaves the condition state alone. The edge
3387    /// into a block a loop goes back to is a critical edge and `crate::split` gives it a block of
3388    /// its own, so the moves an arm turns into land behind the jump rather than in front of it.
3389    fn woven(
3390        &mut self,
3391        inst: Inst,
3392        steps: &[x86_64::Step],
3393        places: &mut [Place],
3394        list: &[AsmOperand<'_>],
3395        clobbered: &[PhysReg],
3396        writes: &[usize],
3397    ) -> Result<(), Unsupported> {
3398        let refused = || Unsupported::Assembly { inst, refused: Written::Operand };
3399        let span = self.source.span(inst);
3400
3401        // Which operands are carried, which is every one that is in a register at all. An operand
3402        // the template never puts in one, such as a constant it names only as the distance into an
3403        // address, is in the instruction and has nowhere to be carried from.
3404        let mut carried: Vec<(usize, RegClass)> = Vec::new();
3405        for (index, operand) in list.iter().enumerate() {
3406            if places[index].read.is_none() && places[index].write.is_none() {
3407                continue;
3408            }
3409            let value = operand.result.or(operand.value).ok_or_else(refused)?;
3410            let ty = self.source[value].ty;
3411            if on_x87(ty) {
3412                return Err(refused());
3413            }
3414            carried.push((index, self.class_of(ty)));
3415        }
3416
3417        // What each of them holds where the template starts.
3418        for &(index, _) in &carried {
3419            if places[index].read.is_some() {
3420                continue;
3421            }
3422            if writes[index] == 0 {
3423                places[index].read = places[index].write;
3424                continue;
3425            }
3426            places[index].read = Some(self.seeded(inst, list[index])?);
3427        }
3428
3429        // The blocks, made before the walk because a jump forwards names a label the walk has not
3430        // reached yet.
3431        let mut labels: Vec<(&str, mir::Block, Vec<mir::Reg>)> = Vec::new();
3432        for step in steps {
3433            let x86_64::Step::Label(name) = step else { continue };
3434            let block = self.out.create_block();
3435            let mut params = Vec::with_capacity(carried.len());
3436            for &(_, class) in &carried {
3437                params.push(self.out.append_param(block, class));
3438            }
3439            labels.push((name.as_str(), block, params));
3440        }
3441
3442        for step in steps {
3443            match step {
3444                x86_64::Step::Label(name) => {
3445                    let (block, params) = Self::went(&labels, name).ok_or_else(refused)?;
3446                    let from = self.at.expect("a block is being filled");
3447                    let args = Self::held(places, &carried).ok_or_else(refused)?;
3448                    *self.out.succs_mut(from) = vec![mir::BlockCall::with(block, args)];
3449                    self.at = Some(block);
3450                    for (at, &(index, _)) in carried.iter().enumerate() {
3451                        places[index].read = params.get(at).copied();
3452                    }
3453                }
3454                x86_64::Step::Jump { opcode, to } => {
3455                    let (block, _) = Self::went(&labels, to).ok_or_else(refused)?;
3456                    let from = self.at.expect("a block is being filled");
3457                    let args = Self::held(places, &carried).ok_or_else(refused)?;
3458                    let opcode = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{opcode}")));
3459                    self.out.build(from, opcode).at(span).finish();
3460                    let next = self.out.create_block();
3461                    *self.out.succs_mut(from) =
3462                        vec![mir::BlockCall::with(block, args), mir::BlockCall::to(next)];
3463                    self.at = Some(next);
3464                }
3465                x86_64::Step::Away { symbol } => {
3466                    // Only in a function that is written without a prologue, which is the one
3467                    // place the jump means what it says. Anywhere else there is an epilogue behind
3468                    // the statement that puts the registers back and gives the frame up, and a
3469                    // jump over it goes to the next function with this function's frame still
3470                    // taken. The reader already made sure it is the last step of the template, so
3471                    // what is left to ask is about the function around it.
3472                    if !self.source.attrs.set.contains(AttrSet::NAKED) {
3473                        return Err(Unsupported::Assembly { inst, refused: Written::Away });
3474                    }
3475                    let from = self.at.expect("a block is being filled");
3476                    let opcode = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{AWAY}")));
3477                    let symbol = self.names.intern(symbol);
3478                    self.out.build(from, opcode).at(span).symbol(symbol).finish();
3479                    // Nowhere, which is what a jump out of the function leaves behind it and is
3480                    // the same list a `ret` leaves. The block after it is made for the walk above
3481                    // rather than for the program: the statement may be in the middle of a body
3482                    // that goes on being lowered, and what that lowering writes is reached by
3483                    // nothing and thrown away with the block.
3484                    *self.out.succs_mut(from) = Vec::new();
3485                    self.at = Some(self.out.create_block());
3486                }
3487                x86_64::Step::Line(line) => {
3488                    self.instruction(inst, line, places, list, clobbered)?;
3489                    let form = x86_64::form(line.opcode).ok_or_else(refused)?;
3490                    for (desc, piece) in form.operands().iter().zip(&line.operands) {
3491                        if !desc.role.is_def() {
3492                            continue;
3493                        }
3494                        let index = match *piece {
3495                            x86_64::Piece::Operand { index, .. } => index,
3496                            x86_64::Piece::Implicit { reg } => match bound(list, reg, desc.role) {
3497                                Some(index) => index,
3498                                None => continue,
3499                            },
3500                            x86_64::Piece::Reg { reg, .. } => match bound(list, reg, desc.role) {
3501                                Some(index) => index,
3502                                None => continue,
3503                            },
3504                        };
3505                        let place = places.get_mut(index).ok_or_else(refused)?;
3506                        if place.write.is_some() {
3507                            place.read = place.write;
3508                        }
3509                    }
3510                }
3511            }
3512        }
3513
3514        // Where the walk left each output, which is the parameter of the block a label made when
3515        // the template ends in one and the register an instruction wrote when it does not.
3516        for (index, operand) in list.iter().enumerate() {
3517            let Some(result) = operand.result else { continue };
3518            if let Some(reg) = places[index].read {
3519                self.regs[result.index()] = Some(reg);
3520            }
3521        }
3522        Ok(())
3523    }
3524
3525    /// The block one of the template's labels made, and the parameters it takes.
3526    fn went<'b>(
3527        labels: &'b [(&str, mir::Block, Vec<mir::Reg>)],
3528        name: &str,
3529    ) -> Option<(mir::Block, &'b [mir::Reg])> {
3530        labels
3531            .iter()
3532            .find(|(had, ..)| *had == name)
3533            .map(|(_, block, params)| (*block, params.as_slice()))
3534    }
3535
3536    /// The register each carried operand is in, which is what an arm to a label carries.
3537    fn held(places: &[Place], carried: &[(usize, RegClass)]) -> Option<Vec<mir::Reg>> {
3538        carried.iter().map(|&(index, _)| places.get(index)?.read).collect()
3539    }
3540
3541    /// The registers a clobber list names, in the order it named them.
3542    ///
3543    /// Nothing is dropped. A name this has no register for is refused, because the list is the
3544    /// program telling the compiler which registers it may not leave anything in, and an entry
3545    /// nobody read is a register something may still be left in. See [`Self::assembly`] for the
3546    /// two entries that are not registers and for why they are skipped rather than refused.
3547    fn clobbered(inst: Inst, clobbers: &str) -> Result<Vec<PhysReg>, Unsupported> {
3548        let refused = || Unsupported::Assembly { inst, refused: Written::Clobber };
3549        let mut named = Vec::new();
3550        for entry in clobbers.split(',') {
3551            let entry = entry.trim().trim_matches('"');
3552            // The sigil is optional in a clobber list and means nothing when it is there, unlike
3553            // in a template, where it is what tells a register from an operand.
3554            let entry = entry.strip_prefix('%').unwrap_or(entry);
3555            if entry.is_empty() || entry == "memory" || entry == "cc" {
3556                continue;
3557            }
3558            let (reg, _) = x86_64::gpr_named(entry).ok_or_else(refused)?;
3559            if !named.contains(&reg) {
3560                named.push(reg);
3561            }
3562        }
3563        Ok(named)
3564    }
3565
3566    /// One instruction of a template, as the machine instruction it was read back into.
3567    fn instruction(
3568        &mut self,
3569        inst: Inst,
3570        line: &x86_64::Line,
3571        places: &[Place],
3572        list: &[AsmOperand<'_>],
3573        clobbered: &[PhysReg],
3574    ) -> Result<(), Unsupported> {
3575        let refused = || Unsupported::Assembly { inst, refused: Written::Operand };
3576        let form = x86_64::form(line.opcode).ok_or_else(refused)?;
3577        // What the instruction reaches and what is in each of them. The description answers the
3578        // first for every opcode but one, and the pieces the template was read into answer the
3579        // second. Bytes a program wrote out itself are the one, since nothing in a number is a
3580        // register anybody could read, so the constraint letters answer both. See
3581        // [`Self::lettered`].
3582        let lettered = (line.opcode == x86_64::LITERAL).then(|| self.lettered(list));
3583        let (described, pieces) = match &lettered {
3584            Some((described, pieces)) => (described.as_slice(), pieces.as_slice()),
3585            None => (form.operands(), line.operands.as_slice()),
3586        };
3587        let mut built = Vec::with_capacity(pieces.len() + clobbered.len());
3588        for (desc, piece) in described.iter().zip(pieces) {
3589            built.push(self.placed(inst, *desc, *piece, places, list)?);
3590        }
3591        // The clobbers go in among the definitions rather than behind the reads, because an operand
3592        // vector in the machine IR is every definition and then every use and what counts them
3593        // reads that order rather than each operand's role.
3594        let defs = built.iter().take_while(|operand| operand.role.is_def()).count();
3595        let mut added = 0usize;
3596        for &reg in clobbered {
3597            if described.iter().any(|desc| desc.constraint == Constraint::Fixed(reg)) {
3598                continue;
3599            }
3600            built.insert(defs, mir::Operand::write(mir::Reg::physical(reg), self.gpr));
3601            added += 1;
3602        }
3603        // A constraint tying one operand to another names it by its place in this vector, and the
3604        // clobbers were put in the middle of the vector, so everything behind them moved. The
3605        // description is written against an instruction with no clobbers in it and cannot know
3606        // that, which makes this the one place the two numberings have to be reconciled.
3607        for operand in &mut built {
3608            if let Constraint::Reuse(at) = operand.constraint {
3609                if usize::from(at) >= defs {
3610                    let moved = usize::from(at) + added;
3611                    operand.constraint =
3612                        Constraint::Reuse(u8::try_from(moved).map_err(|_| refused())?);
3613                }
3614            }
3615        }
3616        let at = match line.at {
3617            Some(at) => Some(self.addressed(inst, at, places, list)?),
3618            None => None,
3619        };
3620
3621        let block = self.at.expect("a block is being filled");
3622        let span = self.source.span(inst);
3623        let opcode = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{}", line.opcode)));
3624        let mut build = self.out.build(block, opcode).at(span);
3625        for operand in built {
3626            build = build.operand(operand);
3627        }
3628        if let Some(value) = line.imm {
3629            build = build.imm(value);
3630        }
3631        if let Some(mem) = at {
3632            build = build.mem(mem);
3633        }
3634        build.finish();
3635        Ok(())
3636    }
3637
3638    /// The registers a run of bytes reaches, taken from the constraint letters rather than from the
3639    /// description of an opcode.
3640    ///
3641    /// Every other instruction of a template has a description saying which registers it reaches
3642    /// without naming them, and [`Self::assembly`] matches the letters against that. Bytes a program
3643    /// wrote out itself have no such description and could not have one: what the instruction is, is
3644    /// a number, and nothing in a number is a register anything could read. So the letters are the
3645    /// whole of what is known, and they are enough, because a program writing an instruction this
3646    /// way has to say where its operands go for exactly the reason a program writing `cpuid` does.
3647    ///
3648    /// Each register named by a letter gets one entry for the write and one for the read, the same
3649    /// two `cpuid` has, and only the half the statement asked for: a register no output names is not
3650    /// written here and one no input names is not read. The writes come first because that is the
3651    /// order an operand vector in the machine IR is counted in. A register named by nothing is left
3652    /// out rather than given a spare one, which is the difference from `cpuid` and is right for the
3653    /// same reason: `cpuid` writes four registers whatever the program said, and what these bytes
3654    /// touch is known only from what the program said.
3655    fn lettered(&self, list: &[AsmOperand<'_>]) -> (Vec<OperandDesc>, Vec<x86_64::Piece>) {
3656        let mut named: Vec<PhysReg> = Vec::new();
3657        for operand in list {
3658            if let Some(reg) = pinned(operand) {
3659                if !named.contains(&reg) {
3660                    named.push(reg);
3661                }
3662            }
3663        }
3664        let mut described = Vec::with_capacity(named.len() * 2);
3665        let mut pieces = Vec::with_capacity(named.len() * 2);
3666        for role in [Role::Def, Role::Use] {
3667            for &reg in &named {
3668                if bound(list, reg, role).is_none() {
3669                    continue;
3670                }
3671                let desc = if role.is_def() {
3672                    OperandDesc::write(self.gpr)
3673                } else {
3674                    OperandDesc::read(self.gpr)
3675                };
3676                described.push(desc.with(Constraint::Fixed(reg)));
3677                pieces.push(x86_64::Piece::Implicit { reg });
3678            }
3679        }
3680        (described, pieces)
3681    }
3682
3683    /// One operand of one instruction of a template, in the register the statement put it in.
3684    fn placed(
3685        &mut self,
3686        inst: Inst,
3687        desc: OperandDesc,
3688        piece: x86_64::Piece,
3689        places: &[Place],
3690        list: &[AsmOperand<'_>],
3691    ) -> Result<mir::Operand, Unsupported> {
3692        let refused = || Unsupported::Assembly { inst, refused: Written::Operand };
3693        // A register the instruction reaches without its text naming it belongs to whichever of the
3694        // statement's operands a constraint letter put there, and to nobody when no letter did.
3695        // There is no width to check in that case: the operand is the register the letter named and
3696        // the instruction does what it does to it, which is what a program writing `"=a"` asked for.
3697        let (index, spelled) = match piece {
3698            x86_64::Piece::Operand { index, width, stated } => (index, Some((width, stated))),
3699            x86_64::Piece::Implicit { reg } => match bound(list, reg, desc.role) {
3700                Some(index) => (index, None),
3701                None => return self.spare(inst, desc),
3702            },
3703            // A register the template named, which belongs to one of the statement's operands when
3704            // a constraint letter put that operand there and to nobody otherwise. Asked in that
3705            // order rather than placed straight away, because `"D" (p)` with `%rdi` in the text is
3706            // the program saying one thing twice, and answering it twice would hand the allocator
3707            // one register holding two values.
3708            x86_64::Piece::Reg { reg, .. } => match bound(list, reg, desc.role) {
3709                Some(index) => (index, None),
3710                None => return self.itself(inst, desc, reg),
3711            },
3712        };
3713        let operand = list.get(index).copied().ok_or_else(refused)?;
3714        // The two halves of an operand written `+`, which arrives in one register and leaves in
3715        // another with the allocator told to make them the same one. Everything else has one of
3716        // the two and asking for the other is the refusal below.
3717        let place = places.get(index).copied().ok_or_else(refused)?;
3718        let reg = match desc.role {
3719            Role::Use => place.read,
3720            Role::Def | Role::EarlyDef => place.write,
3721        }
3722        .ok_or_else(refused)?;
3723
3724        // Read where the opcode reads and written where it writes, which is what the first half of
3725        // this asks. An output has a result and an input has a value, an output written `+` has
3726        // both because it is read before it is written, and an output a matching constraint names
3727        // is read as the input that named it. See [`read_as`].
3728        // An output with neither is read as well, and what it holds there is undefined, which
3729        // [`Self::assembly`] says why and puts a zero in a register for.
3730        let placeable = match desc.role {
3731            Role::Use => read_as(list, index).is_some() || operand.result.is_some(),
3732            Role::Def | Role::EarlyDef => operand.result.is_some(),
3733        };
3734        let ty = match (operand.result, operand.value) {
3735            (Some(result), _) => self.source[result].ty,
3736            (None, Some(value)) => self.source[value].ty,
3737            (None, None) => return Err(refused()),
3738        };
3739        let bits = if ty.is_ptr() { ADDRESS_BITS } else { ty.bits() };
3740        if !placeable || self.class_of(ty) != desc.class {
3741            return Err(refused());
3742        }
3743        if let Some((width, stated)) = spelled {
3744            // An operand the template wrote a width on may be written by an instruction that fills
3745            // more of the register than the object in it does, and the object is then the low part
3746            // of what was written. That is what gmp asks for when it counts the low zero bits of a
3747            // limb into an `unsigned` and spells the count `%q0`: one quadword instruction writes
3748            // the whole register and the `unsigned` is the bottom of it, which is every bit of an
3749            // answer that cannot exceed sixty four anyway.
3750            //
3751            // Only written, and only wider. A read of more of a register than its type fills is a
3752            // program handing an instruction bits nothing ever put there. A write of less of one
3753            // leaves the top of the object holding whatever the register held before, which is the
3754            // same thing one instruction later. Both are refused, and an operand the template left
3755            // plain is refused either way, because what gets spelled for that one is the register
3756            // at the width of its type and no other instruction is the one written down.
3757            let widened = stated && desc.role.is_def() && width.bits() > bits;
3758            if bits != width.bits() && !widened {
3759                return Err(refused());
3760            }
3761        }
3762        // An operand the program pinned is in that register and nowhere else, whatever the opcode
3763        // would have allowed it. That is the whole of what a local register variable asks for, and
3764        // it is the same shape a division already has: the allocator is told the register, puts a
3765        // move in front or behind where it has to, and leaves it out where it does not.
3766        let constraint = match pinned(&operand) {
3767            Some(reg) => Constraint::Fixed(reg),
3768            None => desc.constraint,
3769        };
3770        Ok(mir::Operand { reg, class: desc.class, role: desc.role, constraint })
3771    }
3772
3773    /// A register the template named in its own text.
3774    ///
3775    /// Not one of the statement's operands and not something the allocator handed out. The program
3776    /// wrote `%rbx` in the middle of a template and meant that register, which is what code doing
3777    /// something the constraint letters cannot say is made of: micropython saves the callee-saved
3778    /// registers into a buffer by name because the whole point of the buffer is that those exact
3779    /// registers are in it, and there is no constraint letter for `%rsp`.
3780    ///
3781    /// So it is placed as itself, fixed to the register the template named. What that buys is the
3782    /// thing gcc does not do: the register becomes part of the instruction the allocator sees, so a
3783    /// write of one is a definition it knows about and will not leave anything of the program's
3784    /// across, and a read of one is a use it will not have put something else in first. gcc copies
3785    /// the text out and a register two things believe they own is a wrong program nothing reports.
3786    /// Here the allocator is told, and a program that also named the register in its clobber list
3787    /// says the same thing twice rather than something new.
3788    fn itself(
3789        &mut self,
3790        inst: Inst,
3791        desc: OperandDesc,
3792        reg: PhysReg,
3793    ) -> Result<mir::Operand, Unsupported> {
3794        let refused = Unsupported::Assembly { inst, refused: Written::Operand };
3795        if desc.class != self.gpr {
3796            return Err(refused);
3797        }
3798        Ok(mir::Operand {
3799            reg: mir::Reg::physical(reg),
3800            class: self.gpr,
3801            role: desc.role,
3802            constraint: Constraint::Fixed(reg),
3803        })
3804    }
3805
3806    /// A register an instruction of a template uses and the statement put nothing in.
3807    ///
3808    /// A write of one is the register being destroyed, which is what a clobber list is usually
3809    /// written to say and what an instruction with more answers than the program asked for does
3810    /// anyway: `cpuid` writes all four registers whether or not the statement wanted all four. A
3811    /// register of its own is the whole of what that needs, since a value nothing reads is one the
3812    /// allocator may put anywhere and is told about so that nothing else is put there.
3813    ///
3814    /// A read of one is a register the instruction looks at and the program never filled, which
3815    /// gcc leaves as whatever happened to be there. A zero is written instead, for the reason
3816    /// [`Self::undefined`] gives: the allocator has to be given a definition before a use, and a
3817    /// zero is the one answer that reads the same on every run.
3818    fn spare(&mut self, inst: Inst, desc: OperandDesc) -> Result<mir::Operand, Unsupported> {
3819        let refused = Unsupported::Assembly { inst, refused: Written::Operand };
3820        if desc.class != self.gpr {
3821            return Err(refused);
3822        }
3823        let reg = self.out.new_vreg(desc.class);
3824        if !desc.role.is_def() {
3825            let block = self.at.expect("a block is being filled");
3826            let span = self.source.span(inst);
3827            let put = mir::Opcode::new(self.names.intern(&format!("{PREFIX}mov_ri_64")));
3828            self.out.build(block, put).at(span).def(reg, desc.class).imm(0).finish();
3829        }
3830        Ok(mir::Operand { reg, class: desc.class, role: desc.role, constraint: desc.constraint })
3831    }
3832
3833    /// The address one instruction of a template reads or writes.
3834    fn addressed(
3835        &mut self,
3836        inst: Inst,
3837        at: x86_64::At,
3838        places: &[Place],
3839        list: &[AsmOperand<'_>],
3840    ) -> Result<mir::Mem, Unsupported> {
3841        let refused = || Unsupported::Assembly { inst, refused: Written::Operand };
3842        let base = match at.base {
3843            None => None,
3844            Some(x86_64::Piece::Operand { index, .. }) => {
3845                // The register an address is counted from is read and never written, whatever the
3846                // instruction does to what it finds there.
3847                let reg = places.get(index).and_then(|place| place.read).ok_or_else(refused)?;
3848                Some(mir::Operand::read(reg, self.gpr))
3849            }
3850            // A register the template named, counted from as itself. See [`Self::itself`], and note
3851            // that this is the half of it every one of these templates needs: `movq %rax, 16(%rdi)`
3852            // names one register as the thing being stored and another as where to store it. An
3853            // operand a constraint letter put in that register is that operand, for the reason
3854            // [`Self::placed`] gives.
3855            Some(x86_64::Piece::Reg { reg, .. }) => match bound(list, reg, Role::Use) {
3856                Some(index) => {
3857                    let reg = places.get(index).and_then(|place| place.read).ok_or_else(refused)?;
3858                    Some(mir::Operand::read(reg, self.gpr))
3859                }
3860                None => Some(
3861                    mir::Operand::read(mir::Reg::physical(reg), self.gpr)
3862                        .with(Constraint::Fixed(reg)),
3863                ),
3864            },
3865            // An address counted from a register the instruction reaches without being told is
3866            // not something this machine has: every addressing mode is written out in the text it
3867            // is part of, so a base that got here another way is a base nothing wrote down.
3868            Some(x86_64::Piece::Implicit { .. }) => return Err(refused()),
3869        };
3870        // A distance the template wrote, or the one in an operand the template pointed at, which is
3871        // the same distance said by something that knows how big a thing is. It has to be a number
3872        // the compiler can read at translation time, since it goes in the instruction rather than
3873        // in a register, and an operand holding anything else is refused rather than put somewhere.
3874        let disp = match at.disp {
3875            x86_64::Disp::Number(disp) => disp,
3876            x86_64::Disp::Operand(index) => {
3877                let value =
3878                    list.get(index).and_then(|operand| operand.value).ok_or_else(refused)?;
3879                let number = self.number(value).ok_or_else(refused)?;
3880                i32::try_from(number).map_err(|_| refused())?
3881            }
3882        };
3883        Ok(mir::Mem { base, scale: 1, disp, segment: at.segment, ..mir::Mem::default() })
3884    }
3885
3886    /// The number in that value, for one an `iconst` defined, read at the width of its own type.
3887    ///
3888    /// Signed, because the two things a template asks this for are a distance into an address and
3889    /// the number on an instruction, and both of those are signed wherever they land. A constant
3890    /// whose type is unsigned and whose top bit is set therefore reads as a negative number here,
3891    /// which is the same number and is the reading that fits in the thirty two bits an addressing
3892    /// mode has room for.
3893    fn number(&self, value: Value) -> Option<i128> {
3894        let Def::Result { inst, .. } = self.source[value].def else { return None };
3895        if self.source[inst].opcode != Opcode::IConst {
3896            return None;
3897        }
3898        let Extra::Imm(imm) = self.source[inst].extra else { return None };
3899        let bits = self.source[imm].bits();
3900        let width = self.source[value].ty.bits();
3901        if width == 0 || width > 128 {
3902            return None;
3903        }
3904        let spare = 128 - width;
3905        Some(((bits << spare) as i128) >> spare)
3906    }
3907
3908    /// A register holding a value the program has no claim on, written as a zero.
3909    ///
3910    /// Every other way of saying it costs the same instruction or needs a word the machine IR does
3911    /// not have, and a zero is the one that reads the same on every run.
3912    fn undefined(&mut self, inst: Inst, result: Value) -> Result<(), Unsupported> {
3913        let ty = self.source[result].ty;
3914        let refused = Unsupported::Assembly { inst, refused: Written::Operand };
3915        if self.class_of(ty) != self.gpr || !matches!(ty.bits(), 8 | 16 | 32 | 64) {
3916            return Err(refused);
3917        }
3918        let block = self.at.expect("a block is being filled");
3919        let span = self.source.span(inst);
3920        let reg = self.new_reg(result);
3921        let put = mir::Opcode::new(self.names.intern(&format!("{PREFIX}mov_ri_{}", ty.bits())));
3922        self.out.build(block, put).at(span).def(reg, self.gpr).imm(0).finish();
3923        Ok(())
3924    }
3925
3926    /// Whether a type is the width an address is, which is what makes a cast to or from one free.
3927    fn is_address_width(&self, ty: Type) -> bool {
3928        ty.is_ptr() || (ty.is_int() && ty.bits() == ADDRESS_BITS)
3929    }
3930
3931    /// Where a block goes, which in machine IR is on the block rather than on its terminator.
3932    ///
3933    /// That is why no rule ever names a block: a branch is selected for what it reads and the
3934    /// edges are copied across here, arguments and all. The arguments are read last, after every
3935    /// instruction of the block is written, because an argument that is a constant is
3936    /// materialized where it is first wanted and the end of the block is where an edge wants it.
3937    ///
3938    /// Which is not quite the end. A block that leaves two ways has the branch as its last
3939    /// instruction, and a block that leaves through a register has the indirect jump as its last,
3940    /// and anything appended after either is something it has already jumped past, so a constant
3941    /// materialized here would be a register the block below reads and nothing ever writes. The
3942    /// one that was there is put back on the end when that happened, which is the only reordering
3943    /// anything in this crate does and is why it is remembered before a single argument is read.
3944    fn edges(&mut self, block: Block, out: mir::Block) -> Result<(), Unsupported> {
3945        let Some(term) = self.source.terminator(block) else { return Ok(()) };
3946        let leaves = matches!(self.source[term].opcode, Opcode::BrIf | Opcode::IndirectBr);
3947        let branch = if leaves { self.out.terminator(out) } else { None };
3948
3949        let calls: Vec<rucc_ir::BlockCall> = self.source.successors(term).collect();
3950        let mut succs = Vec::with_capacity(calls.len());
3951        for call in calls {
3952            let args: Vec<Value> = self.source[call.args].to_vec();
3953            let mut regs = Vec::with_capacity(args.len());
3954            for value in args {
3955                // The address of where the value is rather than the value, for the one type a
3956                // register holds none of. The block on the other side copies the bytes out of it
3957                // into a slot of its own, which is what makes a second edge into the same block
3958                // safe.
3959                let reg = if on_x87(self.source[value].ty) {
3960                    self.x87_slot(value)
3961                } else {
3962                    self.reg_of(value)?
3963                };
3964                regs.push(reg);
3965            }
3966            succs.push(mir::BlockCall::with(self.out_block(call.block), regs));
3967        }
3968        if let Some(branch) = branch {
3969            if self.out.terminator(out) != Some(branch) {
3970                self.out.remove_inst(branch);
3971                self.out.append_inst(out, branch);
3972            }
3973        }
3974        *self.out.succs_mut(out) = succs;
3975        Ok(())
3976    }
3977
3978    /// The machine IR block an IR block became.
3979    fn out_block(&self, block: Block) -> mir::Block {
3980        self.blocks[block.index()].expect("every block was created before any was filled")
3981    }
3982
3983    /// The parameters of the entry block, which are the function's arguments.
3984    ///
3985    /// They are not block parameters in the machine IR and they cannot be. A block parameter is
3986    /// given its value by a move on the edge into the block, and there is no edge into an entry
3987    /// block, so what arrives in a function is the convention's to say. [`crate::abi`] is what
3988    /// says it.
3989    ///
3990    /// The ones past the last register arrived in the caller's memory and are read out of it, and
3991    /// the loads that read them come back here so that the frame can finish them the way it
3992    /// finishes an `alloca`.
3993    fn arrive(&mut self, block: Block, out: mir::Block) -> Result<(), Unsupported> {
3994        let params = self.source[block].params.clone();
3995        // The type of each is the block's answer and what the ABI asks of it is the signature's,
3996        // and the two lists are the same list: a parameter the classification turned into a
3997        // pointer is a pointer in the block too. A block with more parameters than the signature
3998        // names is not one the front end writes, and each of those is taken as a plain value.
3999        let asked: Vec<Abi> = self.source.signature().params.iter().map(|it| it.abi).collect();
4000        let types: Vec<Param> = params
4001            .iter()
4002            .enumerate()
4003            .map(|(index, &value)| {
4004                let abi = asked.get(index).copied().unwrap_or_default();
4005                Param { ty: self.source[value].ty, abi }
4006            })
4007            .collect();
4008        // A save area for a function that takes arguments its signature does not name, which is a
4009        // block of this function's frame on one convention and the shadow space the caller already
4010        // reserved on the other. Which of the two it is is [`varargs::Area::of`]'s answer and
4011        // [`Self::save_area`] is where the difference is spent.
4012        let variadic = self.source.signature().variadic;
4013        let area = variadic.then(|| varargs::Area::of(self.conv));
4014        let arrived = abi::entry(&mut self.out, out, &types, self.conv, self.names, area)
4015            .map_err(|(index, missing)| Unsupported::Argument { index, missing })?;
4016        for (&param, reg) in params.iter().zip(&arrived.regs) {
4017            self.regs[param.index()] = Some(*reg);
4018        }
4019        if let Some(area) = area {
4020            self.save_area(out, &arrived, area);
4021        }
4022        self.stack.arguments.extend(arrived.stack);
4023        Ok(())
4024    }
4025
4026    /// The prologue of a variadic function, which is every argument register it was handed written
4027    /// into the frame.
4028    ///
4029    /// Every one the signature did not name, that is. Which of those hold anything is a thing only
4030    /// the caller knew and there is nothing here to ask, so all of them are written, and the ones a
4031    /// named parameter took are not, because `va_start` sets the two offsets past them and nothing
4032    /// ever reads their slots.
4033    ///
4034    /// What that costs is up to fourteen stores in the prologue of a function that may read none of
4035    /// them, and the convention's answer to that is the count of vector registers in `%al`, which
4036    /// lets a callee skip the eight vector stores when the call passed no floats. Skipping them is a
4037    /// branch in a prologue, and a prologue is written long after this by [`crate::finish`], which
4038    /// has no blocks to branch between. So they are all written every time, which is correct and is
4039    /// what `-O0` costs. Issue #323 is the branch.
4040    ///
4041    /// A vector register is written all sixteen bytes at a time, because a `_Float128` fills one and
4042    /// a `va_arg` of a quad reads the slot back whole. gcc writes the same sixteen with the same
4043    /// instruction, which is what [`crate::varargs`] says a list has to be built out of.
4044    ///
4045    /// The address is computed once into a register rather than written as a displacement off the
4046    /// stack pointer, because a displacement into a frame is not known until after allocation and
4047    /// one `lea` costs less than a fixup list for a dozen stores. It is the same `lea` an `alloca`
4048    /// gets and [`crate::finish`] fills it in the same way.
4049    ///
4050    /// A convention that homes its register arguments has none of that. Its area is the shadow
4051    /// space the caller reserved above the return address, so there is no object to make and no
4052    /// address to work out: each store reaches into the caller's argument area the way the load of
4053    /// a parameter the registers ran out before does, which is the same waiting list and the same
4054    /// fixup. There are at most four of them and none is a vector register, since a float the
4055    /// signature does not name arrived in a general purpose register too and that is the copy the
4056    /// walk reads.
4057    fn save_area(&mut self, out: mir::Block, arrived: &abi::Arrived, area: varargs::Area) {
4058        if self.conv.shared_positions {
4059            self.varargs = Some(Varargs::Pointer { incoming: arrived.beyond });
4060            let store = mir::Opcode::new(self.names.intern("x64.mov_mr_64"));
4061            for &(reg, class, at) in &arrived.spare {
4062                let sp = mir::Operand::read(mir::Reg::physical(self.conv.stack_pointer), self.gpr);
4063                let made =
4064                    self.out.build(out, store).uses(reg, class).mem(mir::Mem::at(sp)).finish();
4065                self.stack.arguments.push((made, at));
4066            }
4067            return;
4068        }
4069
4070        let save = self.stack.locals.len();
4071        self.stack.locals.push(Local { size: area.size, align: varargs::VECTOR_SLOT });
4072        self.varargs = Some(Varargs::Fields {
4073            save,
4074            incoming: arrived.beyond,
4075            integers: u32::try_from(arrived.took.0).unwrap_or(0) * area.stride(false),
4076            floats: area.starts_at(true)
4077                + u32::try_from(arrived.took.1).unwrap_or(0) * area.stride(true),
4078        });
4079
4080        let base = self.frame_address(out, save);
4081        for &(reg, class, at) in &arrived.spare {
4082            let name = if class == self.gpr { "x64.mov_mr_64" } else { "x64.movaps_mr" };
4083            let store = mir::Opcode::new(self.names.intern(name));
4084            let up = i32::try_from(at).expect("a register save area under two gigabytes");
4085            let mem = mir::Mem::at(mir::Operand::read(base, self.gpr)).plus(up);
4086            self.out.build(out, store).uses(reg, class).mem(mem).finish();
4087        }
4088    }
4089
4090    /// The address of one of the function's stack objects, in a fresh register.
4091    ///
4092    /// Written with nothing in its displacement, because where an object is in a frame is not known
4093    /// until after allocation, and given to [`crate::finish`] to fill in the way an `alloca` is.
4094    fn frame_address(&mut self, out: mir::Block, local: usize) -> mir::Reg {
4095        let reg = self.out.new_vreg(self.gpr);
4096        let lea = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{}", x86_64::FRAME.lea)));
4097        let sp = mir::Operand::read(mir::Reg::physical(self.conv.stack_pointer), self.gpr);
4098        let made = self.out.build(out, lea).def(reg, self.gpr).mem(mir::Mem::at(sp)).finish();
4099        self.stack.addresses.push((made, local));
4100        reg
4101    }
4102
4103    /// Whether an instruction is one no machine instruction is written for where it stands.
4104    ///
4105    /// Four of them, and none is a lowering decision, which is why none is a rule. A constant is
4106    /// written where a register for it is first wanted rather than where the IR put it, and every
4107    /// reader of one may have folded it into an immediate, in which case nowhere is the right
4108    /// place. A return of nothing has nothing to put anywhere: the epilogue gives the frame back
4109    /// and leaves, and it is appended to every block with no successors long after this has
4110    /// finished, so a return with a value is one instruction here and a return without one is
4111    /// none. Unless the value went back through memory, in which case there is something to put
4112    /// somewhere after all and the IR does not carry it: the address the caller handed over has
4113    /// to be in `rax` on the way out, and [`Lowering::returned`] is what writes that.
4114    ///
4115    /// An unconditional jump is the third, and there is even less of it: the edge is on the
4116    /// block, and whether the block it goes to is the next one and needs no jump at all is the
4117    /// block layout's answer rather than this one's.
4118    ///
4119    /// The fourth is a point control does not arrive at, in both of the forms the IR has for it:
4120    /// the `unreachable` terminator the front end puts at the end of a function whose body can run
4121    /// off the bottom, and the `unreachable_hint` a call to `__builtin_unreachable` becomes. What
4122    /// to write for a place nothing reaches is a question with no wrong answer, and nothing is the
4123    /// smallest one and the one gcc 16.2.0 gives at `-O0`. The terminator leaves the block with no
4124    /// successors, so the epilogue lands at the end of it the way it does on any other block that
4125    /// goes nowhere, and the function cannot fall out of its own last instruction into whatever
4126    /// the assembler puts next.
4127    fn writes_nothing(&self, inst: Inst) -> bool {
4128        let data = &self.source[inst];
4129        match data.opcode {
4130            Opcode::IConst | Opcode::Jump | Opcode::Unreachable | Opcode::UnreachableHint => true,
4131            Opcode::Return => self.source[data.args].is_empty() && self.sret().is_none(),
4132            _ => false,
4133        }
4134    }
4135
4136    /// What every instruction in one block matched, with a set of values nobody may take.
4137    ///
4138    /// Backwards, because an instruction that has been folded into a later one does not get to
4139    /// fold anything into itself: the rule that took it only reached one level down, so what is
4140    /// under it is not in the term the matcher saw and cannot be replaced.
4141    fn decide(&self, insts: &[Inst], refused: &HashSet<Value>) -> Decided {
4142        let mut found: Vec<Option<Match<Term>>> = (0..insts.len()).map(|_| None).collect();
4143        let mut plans: Vec<Option<Plan>> = vec![None; insts.len()];
4144        let mut folded: Vec<Inst> = Vec::new();
4145        for (index, &inst) in insts.iter().enumerate().rev() {
4146            if folded.contains(&inst) {
4147                continue;
4148            }
4149            if let Some((plan, matched)) = self.select(inst, refused) {
4150                folded.extend(self.folds(inst, plan));
4151                found[index] = Some(matched);
4152                plans[index] = Some(plan);
4153            }
4154        }
4155        Decided { found, plans, folded }
4156    }
4157
4158    /// A value some of its readers took and some of them did not, which is the one case folding
4159    /// buys nothing.
4160    ///
4161    /// Folding does not delete the instruction that computed a value for anybody else, so a
4162    /// reader that did not take it still needs it in a register and the instruction stays. The
4163    /// reader that did take it now does that work again. Either all of them take it, in which
4164    /// case nothing is left to read it and the instruction goes, or none of them do.
4165    ///
4166    /// The count is over the whole function rather than over the block, since a value read from
4167    /// another block is read from a register there whatever this block decides. An instruction
4168    /// built by name rather than matched, a call being the one that matters, has no plan and so
4169    /// takes nothing, which is the right answer for it as well.
4170    fn left_alive(&self, insts: &[Inst], plans: &[Option<Plan>]) -> Option<Value> {
4171        let mut taken = vec![0u32; self.uses.len()];
4172        for (&inst, plan) in insts.iter().zip(plans) {
4173            let Some(plan) = plan else { continue };
4174            let args = &self.source[self.source[inst].args];
4175            for (index, &arg) in args.iter().take(MAX_ARGS).enumerate() {
4176                if plan[index] == Shown::Expand {
4177                    taken[arg.index()] += 1;
4178                }
4179            }
4180        }
4181        for (&inst, plan) in insts.iter().zip(plans) {
4182            let Some(plan) = plan else { continue };
4183            let args = &self.source[self.source[inst].args];
4184            for (index, &arg) in args.iter().take(MAX_ARGS).enumerate() {
4185                if plan[index] == Shown::Expand && taken[arg.index()] < self.uses[arg.index()] {
4186                    return Some(arg);
4187                }
4188            }
4189        }
4190        None
4191    }
4192
4193    /// The rule that fires on an instruction, and what it bound.
4194    ///
4195    /// The plans are tried in order and the first that matches wins, which is the maximal munch
4196    /// `spec/10-backend.md` asks for: a plan that offers more to the matcher is tried before one
4197    /// that offers less.
4198    fn select(&self, inst: Inst, refused: &HashSet<Value>) -> Option<(Plan, Match<Term>)> {
4199        for plan in self.plans(inst, refused) {
4200            let terms = Terms::new(self.source, inst, plan);
4201            if let Some(matched) = TABLE.find(&terms, Term::Root) {
4202                return Some((plan, matched));
4203            }
4204        }
4205        None
4206    }
4207
4208    /// Every way this instruction can be shown to the matcher, most offered first.
4209    fn plans(&self, inst: Inst, refused: &HashSet<Value>) -> Vec<Plan> {
4210        let args = &self.source[self.source[inst].args];
4211        let mut plans = vec![PLAIN];
4212        for (index, &arg) in args.iter().enumerate().take(MAX_ARGS) {
4213            let mut ways = Vec::new();
4214            if self.foldable(inst, arg, refused) {
4215                ways.push(Shown::Expand);
4216            }
4217            if Terms::new(self.source, inst, PLAIN).constant(arg).is_some() {
4218                ways.push(Shown::Const);
4219            }
4220            ways.push(Shown::Reg);
4221            plans = plans
4222                .into_iter()
4223                .flat_map(|plan| {
4224                    ways.iter().map(move |&way| {
4225                        let mut next = plan;
4226                        next[index] = way;
4227                        next
4228                    })
4229                })
4230                .collect();
4231        }
4232        plans
4233    }
4234
4235    /// Whether an operand may be shown as the instruction that computed it.
4236    ///
4237    /// It has to be in the same block, because a rule that folds one instruction into another
4238    /// moves the work to where the second one is. It has to be something rather than a block
4239    /// parameter, and not a constant, which is shown as a constant instead. And it has to be a
4240    /// value [`Lowering::left_alive`] has not put back, which is how the one reader at a time
4241    /// question is asked here: this says yes to a value with any number of readers, and a value
4242    /// only some of them could take is refused after the fact and asked again.
4243    ///
4244    /// A value with several readers used to be refused outright, on the reasoning that folding
4245    /// does not delete the instruction for anybody else. That reasoning is about the set of
4246    /// readers and was being applied to one reader at a time, which is stricter than it needs to
4247    /// be: when every reader takes it there is nobody left to read it and the instruction goes.
4248    /// An address a store and a load share is the shape that matters, since a memory operand has
4249    /// room for the whole of it and both readers have a memory operand.
4250    fn foldable(&self, into: Inst, value: Value, refused: &HashSet<Value>) -> bool {
4251        let Def::Result { inst, .. } = self.source[value].def else { return false };
4252        if self.source[inst].opcode == Opcode::IConst || refused.contains(&value) {
4253            return false;
4254        }
4255        self.source.block_of(inst).is_some()
4256            && self.source.block_of(inst) == self.source.block_of(into)
4257    }
4258
4259    /// The instructions a match folded into the one it matched.
4260    ///
4261    /// The plan is what says this, not the bindings: a binding is a register or a number either
4262    /// way, and an operand shown as the instruction that computed it is one no rule could have
4263    /// matched without taking that instruction, because the plan offered the matcher nothing
4264    /// else to call it.
4265    fn folds(&self, inst: Inst, plan: Plan) -> Vec<Inst> {
4266        let args = &self.source[self.source[inst].args];
4267        args.iter()
4268            .take(MAX_ARGS)
4269            .enumerate()
4270            .filter(|&(index, _)| plan[index] == Shown::Expand)
4271            .filter_map(|(_, &arg)| match self.source[arg].def {
4272                Def::Result { inst, .. } => Some(inst),
4273                Def::Param { .. } => None,
4274            })
4275            .collect()
4276    }
4277
4278    /// What the IR instruction said about itself that the machine instruction has to keep saying.
4279    ///
4280    /// One flag today. `volatile` says the access happens exactly once and is never moved or
4281    /// merged, and nothing below here can work that out again: a `volatile` load and an ordinary
4282    /// one are the same instruction over the same address, so a pass that puts two accesses
4283    /// together would put these together too. Carried rather than checked here, because the pass
4284    /// that has to refuse is a long way down and this is the last place the answer is known.
4285    ///
4286    /// The instructions this compiler writes for itself get nothing, which is the right answer
4287    /// for all of them: a prologue, a spill and the moves around a call were asked for by the
4288    /// machine rather than by the program.
4289    ///
4290    /// Every access the flag is legal on carries it: the loads and the stores a rule matched,
4291    /// the two ends of a `long double` copy that are the program's own memory, and the compare
4292    /// and exchange and the read modify write. An `asm` statement does not, and it is the one
4293    /// exception on purpose. What the flag says there is that the statement stays even when
4294    /// nothing reads what it wrote, which is a different sentence about a different thing, and
4295    /// every `asm` is already fixed where it stands whether the word was written or not.
4296    fn carried(&self, inst: Inst) -> mir::Flags {
4297        if self.source[inst].flags.contains(Flags::VOLATILE) {
4298            mir::Flags::VOLATILE
4299        } else {
4300            mir::Flags::NONE
4301        }
4302    }
4303
4304    /// Build the machine instruction a match calls for.
4305    fn emit(&mut self, inst: Inst, matched: &Match<Term>) -> Result<(), Unsupported> {
4306        let rule: &Rule = TABLE.rule(matched);
4307        let pieces = rule.replacement;
4308        let Some(Piece::App { head, arity }) = pieces.first() else {
4309            return Err(self.unsupported(inst));
4310        };
4311        let opcode = head.strip_prefix(PREFIX).ok_or_else(|| self.unsupported(inst))?;
4312        let form = x86_64::form(opcode).ok_or_else(|| self.unsupported(inst))?;
4313
4314        let mut read = Read::default();
4315        let mut at = 1;
4316        for _ in 0..*arity {
4317            at = self.read(inst, pieces, at, &matched.bindings, &mut read)?;
4318        }
4319
4320        let descs = form.operands();
4321        let writes = descs.iter().take_while(|desc| desc.role.is_def()).count();
4322        if descs.len() - writes != read.regs.len() {
4323            return Err(self.unsupported(inst));
4324        }
4325
4326        // The first thing the instruction writes is what it computes, and any others are
4327        // registers the machine destroys on the way, which are fresh because nothing else is in
4328        // them and nothing reads them. An instruction that writes nothing at all is one whose
4329        // whole purpose is its effect, which is what a store is, and there is no result to put
4330        // anywhere.
4331        let mut regs = Vec::new();
4332        if writes > 0 {
4333            let result = self.source[inst].first_result.ok_or_else(|| self.unsupported(inst))?;
4334            regs.push(self.new_reg(result));
4335            // The rest are the registers the machine destroys on the way, and the class each is in
4336            // is the one the instruction's description gives it rather than a guess, so that an
4337            // instruction that wrecks a register in the other file says so.
4338            regs.extend(descs[1..writes].iter().map(|desc| self.out.new_vreg(desc.class)));
4339        } else if self.source[inst].first_result.is_some() {
4340            // A rule that throws away a value the IR gave a name to would leave every reader of
4341            // that name with nothing to read, so it is a rule this and the target disagree about.
4342            return Err(self.unsupported(inst));
4343        }
4344        regs.extend(read.regs.iter().copied());
4345
4346        let block = self.at.expect("a block is being filled");
4347        let opcode = mir::Opcode::new(self.names.intern(head));
4348        let (span, flags) = (self.source.span(inst), self.carried(inst));
4349        let mut build = self.out.build(block, opcode).at(span).flags(flags);
4350        for (desc, reg) in descs.iter().zip(regs) {
4351            let operand = mir::Operand {
4352                reg,
4353                class: desc.class,
4354                role: desc.role,
4355                constraint: desc.constraint,
4356            };
4357            build = build.operand(operand);
4358        }
4359        if let Some(mem) = read.mem {
4360            build = build.mem(mem);
4361        }
4362        if let Some(imm) = read.imm {
4363            build = build.imm(imm);
4364        }
4365        build.finish();
4366        Ok(())
4367    }
4368
4369    /// Read one argument of a replacement, which is a register, a number or an address.
4370    ///
4371    /// Gives back the position after it, because a replacement is flat and an address takes
4372    /// arguments of its own.
4373    fn read(
4374        &mut self,
4375        inst: Inst,
4376        pieces: &'static [Piece],
4377        at: usize,
4378        bindings: &[Term],
4379        out: &mut Read,
4380    ) -> Result<usize, Unsupported> {
4381        match pieces.get(at) {
4382            Some(Piece::Int(value)) => {
4383                out.imm = i64::try_from(*value).ok();
4384                Ok(at + 1)
4385            }
4386            // A number the rule worked out of the ones it matched rather than one it wrote down,
4387            // which is an immediate once it has been worked out and is read here as one. It gives
4388            // nothing back when a binding it reads is a register, and a replacement that cannot be
4389            // built is a rule this file and the matcher disagree about, which is what `unsupported`
4390            // is for.
4391            Some(Piece::Computed { work, .. }) => {
4392                let matched: Vec<Option<i128>> = bindings
4393                    .iter()
4394                    .map(|term| match *term {
4395                        Term::Num(value) => Some(value),
4396                        _ => None,
4397                    })
4398                    .collect();
4399                let number = work(&matched).ok_or_else(|| self.unsupported(inst))?;
4400                out.imm = i64::try_from(number).ok();
4401                Ok(at + 1)
4402            }
4403            Some(Piece::Var { index, .. }) => {
4404                match bindings.get(*index) {
4405                    Some(&Term::Reg(value)) => {
4406                        let reg = self.reg_of(value)?;
4407                        out.regs.push(reg);
4408                    }
4409                    Some(&Term::Num(value)) => out.imm = i64::try_from(value).ok(),
4410                    // A pattern binds a register or a number and nothing else, so this is a
4411                    // rule the matcher and this file disagree about.
4412                    _ => return Err(self.unsupported(inst)),
4413                }
4414                Ok(at + 1)
4415            }
4416            Some(Piece::App { head, arity }) => {
4417                let kind = x86_64::address(head).ok_or_else(|| self.unsupported(inst))?;
4418                let mut inner = Read::default();
4419                let mut next = at + 1;
4420                for _ in 0..*arity {
4421                    next = self.read(inst, pieces, next, bindings, &mut inner)?;
4422                }
4423                let mem = address(kind, &inner, self.gpr).ok_or_else(|| self.unsupported(inst))?;
4424                out.mem = Some(mem);
4425                Ok(next)
4426            }
4427            None => Err(self.unsupported(inst)),
4428        }
4429    }
4430
4431    /// The register a value is in, materializing it if it is a constant that has not been put in
4432    /// one yet.
4433    ///
4434    /// A constant is written where it is wanted rather than where the IR defined it, and where it
4435    /// is wanted is a block that need not be the one the IR defined it in. So the register holding
4436    /// one is only good inside the block it was written into, and a second block that wants the
4437    /// same constant gets its own. Anything else is a register read where nothing wrote it: the
4438    /// IR guarantees a definition dominates its uses, and this moved the definition.
4439    ///
4440    /// Writing the number again is also the right answer and not merely the safe one. It is one
4441    /// instruction that reads nothing, which is cheaper than holding a register live across a
4442    /// branch for it, and it is what a rematerializing allocator would do with the value anyway.
4443    fn reg_of(&mut self, value: Value) -> Result<mir::Reg, Unsupported> {
4444        let constant = match self.source[value].def {
4445            Def::Result { inst, .. } => {
4446                (self.source[inst].opcode == Opcode::IConst).then_some(inst)
4447            }
4448            Def::Param { .. } => None,
4449        };
4450        let here = self.at.expect("a block is being filled");
4451        if let Some(reg) = self.regs[value.index()] {
4452            if constant.is_none() || self.written[value.index()] == Some(here) {
4453                return Ok(reg);
4454            }
4455        }
4456        if let Some(inst) = constant {
4457            // Cleared so that the register the constant is written into is a new one rather than
4458            // the one the block above wrote, which is still being read up there.
4459            self.regs[value.index()] = None;
4460            // Nothing is refused here. A constant is written on its own, out of the loop over the
4461            // block, and the operands of the rule that writes one are the number and nothing else.
4462            let matched = self
4463                .select(inst, &HashSet::new())
4464                .map(|(_, matched)| matched)
4465                .ok_or_else(|| self.unsupported(inst))?;
4466            self.emit(inst, &matched)?;
4467            // The same mark the loop over the instructions makes, and it has to be made here as
4468            // well because this is the only place a constant is ever selected: the loop skips one
4469            // where the IR wrote it, so a rule that lowers a constant fires from nowhere else and
4470            // would be reported as a rule nothing reaches.
4471            self.fired.mark(matched.rule);
4472            self.written[value.index()] = Some(here);
4473            return Ok(self.regs[value.index()].expect("a constant is written into a register"));
4474        }
4475        Ok(self.new_reg(value))
4476    }
4477
4478    /// Which register file a value of that type lives in.
4479    ///
4480    /// The vector one for the two float widths the machine has scalar instructions for and for the
4481    /// one it only moves, and the general purpose one for everything else. An eighty bit `long
4482    /// double` is in neither, and it is here rather than in the vector class on purpose: it would
4483    /// be put in a register that cannot hold it, and there is no rule that names one, so the
4484    /// instruction computing it is reported. The wrong class would make that a wrong program
4485    /// instead of a refused one.
4486    ///
4487    /// A hundred and twenty eight bit float is in the vector class and fits it exactly, which is
4488    /// the difference. Nothing computes in it, so every arithmetic on one is still reported, and
4489    /// what the class buys is the moves: a register that holds the whole value is a register a
4490    /// spill, a reload and a copy are each one instruction for.
4491    fn class_of(&self, ty: Type) -> RegClass {
4492        if crate::term::in_vector_file(ty) { self.conv.sse_class } else { self.gpr }
4493    }
4494
4495    /// A fresh register for a value, which is what the instruction computing it writes.
4496    ///
4497    /// Any declaration the value is a value of comes with it. Here rather than once at the end over
4498    /// the whole map, because a constant is written again in every block that wants one and the map
4499    /// only remembers the last of those registers, and a local held in a constant is a local that
4500    /// would otherwise be findable in one block of the function and nowhere else.
4501    fn new_reg(&mut self, value: Value) -> mir::Reg {
4502        if let Some(reg) = self.regs[value.index()] {
4503            return reg;
4504        }
4505        let reg = self.out.new_vreg(self.class_of(self.source[value].ty));
4506        self.regs[value.index()] = Some(reg);
4507        let source = self.source;
4508        for decl in source.value_decls(value) {
4509            self.out.named.push((decl, reg));
4510        }
4511        reg
4512    }
4513
4514    fn unsupported(&self, inst: Inst) -> Unsupported {
4515        let data = &self.source[inst];
4516        Unsupported::Inst {
4517            inst,
4518            term: Terms::new(self.source, inst, PLAIN).name(inst),
4519            opcode: data.opcode,
4520            ty: data.first_result.map(|result| self.source[result].ty),
4521        }
4522    }
4523}
4524
4525/// What the arguments of one replacement came to.
4526#[derive(Debug, Default)]
4527struct Read {
4528    regs: Vec<mir::Reg>,
4529    imm: Option<i64>,
4530    mem: Option<mir::Mem>,
4531}
4532
4533/// The addressing mode an address constructor's arguments make.
4534///
4535/// One arm per constructor rather than a question asked of the kind, because what the arguments
4536/// mean is the whole of what tells the four apart: the same register is a base in one and an
4537/// index in another, and the same constant is a scale in one and a displacement in another.
4538fn address(kind: x86_64::Address, read: &Read, gpr: RegClass) -> Option<mir::Mem> {
4539    let mut regs = read.regs.iter().copied().map(|reg| mir::Operand::read(reg, gpr));
4540    match kind {
4541        x86_64::Address::BaseIndexScale => {
4542            let base = regs.next()?;
4543            let index = regs.next()?;
4544            Some(mir::Mem::at(base).indexed(index, u8::try_from(read.imm?).ok()?))
4545        }
4546        x86_64::Address::IndexScale => Some(mir::Mem {
4547            base: None,
4548            index: Some(regs.next()?),
4549            scale: u8::try_from(read.imm?).ok()?,
4550            disp: 0,
4551            symbol: None,
4552            block: None,
4553            reach: mir::Reach::Itself,
4554            segment: None,
4555        }),
4556        x86_64::Address::Base => Some(mir::Mem::at(regs.next()?)),
4557        // The rule that writes this has a guard saying the constant fits, so a displacement that
4558        // does not is a rule and a target that disagree rather than a program this cannot compile.
4559        x86_64::Address::BaseOffset => {
4560            Some(mir::Mem { disp: i32::try_from(read.imm?).ok()?, ..mir::Mem::at(regs.next()?) })
4561        }
4562    }
4563}
4564
4565/// The table this selector matches with.
4566///
4567/// One target for now, because one target has a rule file. Which table to use becomes a question
4568/// the moment a second one does, and the answer will be the target the session was given rather
4569/// than a constant here.
4570static TABLE: &Table = &crate::select::x86_64::TABLE;
4571
4572#[cfg(test)]
4573mod tests {
4574    use rucc_ir::{
4575        AsmInfo, Builder, CallInfo, Flags, InstData, MemInfo, MemOrder, Restrict, Signature, Type,
4576    };
4577    use rucc_regalloc::assign::Env;
4578    use rucc_target::x86_64::{FRAME, REGS, SYSV};
4579
4580    use super::*;
4581    use crate::finish::{Convention, finish};
4582    use crate::frame::{Frame, Incoming, Layout};
4583
4584    /// A function of as many 64 bit parameters as the test wants, and the block they are in.
4585    fn blank(params: &[Type]) -> (Interner, Func, Block, Vec<Value>) {
4586        let mut names = Interner::new();
4587        let mut func = Func::new(names.intern("f"), Signature::new());
4588        let block = func.create_block();
4589        let values = params.iter().map(|&ty| func.append_param(block, ty)).collect();
4590        (names, func, block, values)
4591    }
4592
4593    /// An ordinary access: not atomic, and aligned enough that nothing here has an opinion.
4594    /// Neither field reaches selection, which is the point of saying it once here.
4595    fn plain() -> MemInfo {
4596        MemInfo {
4597            size: 0,
4598            align: 1,
4599            order: MemOrder::NotAtomic,
4600            tbaa: None,
4601            owns: 0,
4602            restrict: Restrict::NONE,
4603        }
4604    }
4605
4606    /// What the allocator is given: every integer register the convention offers except two, held
4607    /// back so that a move on an edge has somewhere to break a cycle and a spilled value has
4608    /// somewhere to be read into. Which two does not matter, and holding back the last two the
4609    /// convention would reach for leaves every expectation below unchanged.
4610    fn env() -> Env {
4611        const SCRATCH: [PhysReg; 2] = [x86_64::R10, x86_64::R11];
4612        let order: Vec<PhysReg> =
4613            SYSV.int_order.iter().copied().filter(|reg| !SCRATCH.contains(reg)).collect();
4614        Env::new().with(x86_64::GPR, &order, &SCRATCH)
4615    }
4616
4617    /// The machine IR text a function lowers to.
4618    fn lower(names: &mut Interner, source: &Func) -> String {
4619        let out = func(source, names, &SYSV, &Elsewhere::default())
4620            .expect("every instruction has a rule");
4621        mir::print_func(&out.func, names, &REGS)
4622    }
4623
4624    #[test]
4625    fn an_addition_of_two_registers_is_one_instruction() {
4626        let i32 = Type::int(32);
4627        let (mut names, mut func, block, args) = blank(&[i32, i32]);
4628        let mut build = Builder::new(&mut func, block);
4629        build.binary(Opcode::Add, args[0], args[1], Flags::default());
4630
4631        assert_eq!(
4632            lower(&mut names, &func),
4633            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_32\n    \
4634             %1:gpr($rsi) = x64.arg_val_32\n    %2:gpr(reuse 1) = x64.add_rr_32 %0, %1\n}\n"
4635        );
4636    }
4637
4638    #[test]
4639    fn a_constant_operand_becomes_an_immediate() {
4640        let i32 = Type::int(32);
4641        let (mut names, mut func, block, args) = blank(&[i32]);
4642        let mut build = Builder::new(&mut func, block);
4643        let seven = build.iconst(i32, 7);
4644        build.binary(Opcode::Add, args[0], seven, Flags::default());
4645
4646        // The constant is in the instruction and nothing was written to hold it, which is what
4647        // materializing one where a register for it is wanted buys.
4648        assert_eq!(
4649            lower(&mut names, &func),
4650            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_32\n    \
4651             %1:gpr(reuse 1) = x64.add_ri_32 %0, 7\n}\n"
4652        );
4653    }
4654
4655    #[test]
4656    fn a_constant_too_wide_for_an_immediate_goes_into_a_register() {
4657        let i64 = Type::int(64);
4658        let (mut names, mut func, block, args) = blank(&[i64]);
4659        let mut build = Builder::new(&mut func, block);
4660        let big = build.iconst(i64, i128::from(i32::MAX) + 1);
4661        build.binary(Opcode::Add, args[0], big, Flags::default());
4662
4663        // Nobody wrote this fallback down. The rule that takes an immediate has a guard that
4664        // turns a number this wide down, so it does not fire, and the next way of showing the
4665        // operand puts it in a register.
4666        assert_eq!(
4667            lower(&mut names, &func),
4668            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_64\n    \
4669             %1:gpr = x64.mov_ri_64 2147483648\n    %2:gpr(reuse 1) = x64.add_rr_64 %0, %1\n}\n"
4670        );
4671    }
4672
4673    #[test]
4674    fn an_index_calculation_folds_into_an_address() {
4675        let i64 = Type::int(64);
4676        let (mut names, mut func, block, args) = blank(&[i64, i64]);
4677        let mut build = Builder::new(&mut func, block);
4678        let four = build.iconst(i64, 4);
4679        let scaled = build.binary(Opcode::Mul, args[1], four, Flags::default());
4680        build.binary(Opcode::Add, args[0], scaled, Flags::default());
4681
4682        // Three IR instructions and one machine instruction. The multiply is gone because the
4683        // rule that matched reached down and took it.
4684        assert_eq!(
4685            lower(&mut names, &func),
4686            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_64\n    \
4687             %1:gpr($rsi) = x64.arg_val_64\n    %2:gpr = x64.lea_64 [%0 + %1*4]\n}\n"
4688        );
4689    }
4690
4691    #[test]
4692    fn an_instruction_every_reader_can_take_is_folded_into_all_of_them() {
4693        let i64 = Type::int(64);
4694        let (mut names, mut func, block, args) = blank(&[i64, i64]);
4695        let mut build = Builder::new(&mut func, block);
4696        let four = build.iconst(i64, 4);
4697        let scaled = build.binary(Opcode::Mul, args[1], four, Flags::default());
4698        let first = build.binary(Opcode::Add, args[0], scaled, Flags::default());
4699        build.binary(Opcode::Add, first, scaled, Flags::default());
4700
4701        // Both readers have room for a scaled index, so both of them take it and nothing is left
4702        // to read the multiply. Three IR instructions become two machine ones, where refusing to
4703        // fold into either reader would have left three.
4704        assert_eq!(
4705            lower(&mut names, &func),
4706            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_64\n    \
4707             %1:gpr($rsi) = x64.arg_val_64\n    %2:gpr = x64.lea_64 [%0 + %1*4]\n    \
4708             %3:gpr = x64.lea_64 [%2 + %1*4]\n}\n"
4709        );
4710    }
4711
4712    #[test]
4713    fn an_instruction_one_of_its_readers_cannot_take_is_folded_into_none_of_them() {
4714        let i64 = Type::int(64);
4715        let (mut names, mut func, block, args) = blank(&[i64, i64]);
4716        let mut build = Builder::new(&mut func, block);
4717        let four = build.iconst(i64, 4);
4718        let scaled = build.binary(Opcode::Mul, args[1], four, Flags::default());
4719        build.binary(Opcode::Add, args[0], scaled, Flags::default());
4720        build.store(scaled, args[0], plain(), Flags::default());
4721
4722        // The addition has room for the multiply and the store does not: what a store writes is
4723        // a register, and no rule reaches through it. Folding into the addition alone would
4724        // leave the multiply where it is for the store to read and do the work twice, so the
4725        // multiply is put back and both readers read the register it wrote.
4726        let text = lower(&mut names, &func);
4727        assert!(text.contains("x64.lea_64 [%1*4]"), "{text}");
4728        assert!(text.contains("x64.add_rr_64"), "{text}");
4729    }
4730
4731    #[test]
4732    fn a_shift_by_a_register_asks_for_it_in_cl() {
4733        let i32 = Type::int(32);
4734        let (mut names, mut func, block, args) = blank(&[i32, i32]);
4735        let mut build = Builder::new(&mut func, block);
4736        build.binary(Opcode::Shl, args[0], args[1], Flags::default());
4737
4738        // The fixed register is not in the rule. It is what the target says the instruction does
4739        // with its operands, and the allocator is what will act on it.
4740        let text = lower(&mut names, &func);
4741        assert!(text.contains("x64.shl_rcl_32 %0, %1($rcx)"), "{text}");
4742    }
4743
4744    #[test]
4745    fn a_division_names_the_registers_and_the_register_it_destroys() {
4746        let i32 = Type::int(32);
4747        let (mut names, mut func, block, args) = blank(&[i32, i32]);
4748        let mut build = Builder::new(&mut func, block);
4749        build.binary(Opcode::SDiv, args[0], args[1], Flags::default());
4750
4751        // Two definitions, because a division writes the remainder whether anybody wanted it or
4752        // not, and the second one is early because it is destroyed before the operands are read.
4753        let text = lower(&mut names, &func);
4754        assert!(
4755            text.contains("%2:gpr($rax), early %3:gpr($rdx) = x64.idiv_quo_32 %0($rax), %1"),
4756            "{text}"
4757        );
4758    }
4759
4760    #[test]
4761    fn a_load_reads_through_the_register_the_address_is_in() {
4762        let i64 = Type::int(64);
4763        let (mut names, mut func, block, args) = blank(&[i64]);
4764        let mut build = Builder::new(&mut func, block);
4765        build.load(Type::int(32), args[0], plain(), Flags::default());
4766
4767        assert_eq!(
4768            lower(&mut names, &func),
4769            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_64\n    \
4770             %1:gpr = x64.mov_rm_32 [%0]\n}\n"
4771        );
4772    }
4773
4774    #[test]
4775    fn a_store_writes_no_register_and_the_value_it_writes_is_the_one_the_ir_gave_it() {
4776        let (mut names, mut func, block, args) = blank(&[Type::int(32), Type::int(64)]);
4777        let mut build = Builder::new(&mut func, block);
4778        build.store(args[0], args[1], plain(), Flags::default());
4779
4780        // The value is the first parameter and the address is the second, and the instruction
4781        // takes them the other way round. Getting that backwards would compile to a store of the
4782        // address into the value, which is a program that runs and does the wrong thing.
4783        assert_eq!(
4784            lower(&mut names, &func),
4785            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_32\n    \
4786             %1:gpr($rsi) = x64.arg_val_64\n    x64.mov_mr_32 %0, [%1]\n}\n"
4787        );
4788    }
4789
4790    #[test]
4791    fn an_address_with_a_constant_added_folds_into_the_access() {
4792        let i64 = Type::int(64);
4793        let (mut names, mut func, block, args) = blank(&[i64]);
4794        let mut build = Builder::new(&mut func, block);
4795        let twelve = build.iconst(i64, 12);
4796        let field = build.binary(Opcode::Add, args[0], twelve, Flags::default());
4797        build.load(Type::int(64), field, plain(), Flags::default());
4798
4799        // Two IR instructions and one machine instruction, which is what every read of a field
4800        // of a structure comes to.
4801        assert_eq!(
4802            lower(&mut names, &func),
4803            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_64\n    \
4804             %1:gpr = x64.mov_rm_64 [%0 + 12]\n}\n"
4805        );
4806    }
4807
4808    #[test]
4809    fn a_displacement_too_wide_to_encode_leaves_the_addition_where_it_is() {
4810        let i64 = Type::int(64);
4811        let (mut names, mut func, block, args) = blank(&[i64]);
4812        let mut build = Builder::new(&mut func, block);
4813        let big = build.iconst(i64, i128::from(i32::MAX) + 1);
4814        let far = build.binary(Opcode::Add, args[0], big, Flags::default());
4815        build.load(Type::int(32), far, plain(), Flags::default());
4816
4817        // A displacement is signed and 32 bits. The rule that folds one has a guard that turns
4818        // this down, so the addition stays and the load reads through what it produced. Nobody
4819        // wrote that fallback: it is the next way of showing the operand.
4820        let text = lower(&mut names, &func);
4821        assert!(text.contains("x64.mov_rm_32 [%2]"), "{text}");
4822        assert!(text.contains("x64.add_rr_64"), "{text}");
4823    }
4824
4825    #[test]
4826    fn a_store_of_a_value_that_was_loaded_is_two_instructions_and_no_arithmetic() {
4827        let i64 = Type::int(64);
4828        let (mut names, mut func, block, args) = blank(&[i64, i64]);
4829        let mut build = Builder::new(&mut func, block);
4830        let got = build.load(Type::int(8), args[0], plain(), Flags::default());
4831        build.store(got, args[1], plain(), Flags::default());
4832
4833        // A load feeding a store is the one place folding would be wrong: an x86-64 `mov` has at
4834        // most one memory operand, and there is no rule that takes two, so the load is left where
4835        // it is and the store reads the register it wrote.
4836        assert_eq!(
4837            lower(&mut names, &func),
4838            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_64\n    \
4839             %1:gpr($rsi) = x64.arg_val_64\n    %2:gpr = x64.mov_rm_8 [%0]\n    \
4840             x64.mov_mr_8 %2, [%1]\n}\n"
4841        );
4842    }
4843
4844    #[test]
4845    fn an_access_at_a_width_no_rule_is_written_at_is_reported() {
4846        let i64 = Type::int(64);
4847        let (mut names, mut source, block, args) = blank(&[i64]);
4848        let mut build = Builder::new(&mut source, block);
4849        build.load(Type::int(128), args[0], plain(), Flags::default());
4850
4851        // The width is the whole of what is wrong here, so the width is in the message: `load`
4852        // on its own is written about at every other width and would send a reader looking in
4853        // the wrong place.
4854        let failed = func(&source, &mut names, &SYSV, &Elsewhere::default())
4855            .expect_err("nothing loads 128 bits");
4856        assert_eq!(failed.to_string(), "no rule lowers a `load` producing a `i128`");
4857    }
4858
4859    #[test]
4860    fn a_return_asks_for_the_value_in_the_register_the_caller_reads() {
4861        let (mut names, mut func, block, args) = blank(&[Type::int(32)]);
4862        let mut build = Builder::new(&mut func, block);
4863        build.ret(&[args[0]]);
4864
4865        // The register is not in the rule, the same way `cl` is not in the rule for a shift. It
4866        // is what the target says the instruction does with its operand, and the allocator is
4867        // what will act on it. There is no `ret` here, because giving the frame back has to
4868        // happen between this and leaving and the frame is not worked out yet.
4869        assert_eq!(
4870            lower(&mut names, &func),
4871            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_32\n    \
4872             x64.ret_val_32 %0($rax)\n}\n"
4873        );
4874    }
4875
4876    #[test]
4877    fn a_return_of_two_values_asks_for_the_second_register_as_well() {
4878        let i64 = Type::int(64);
4879        let (mut names, mut func, block, args) = blank(&[i64, i64]);
4880        let mut build = Builder::new(&mut func, block);
4881        build.ret(&[args[0], args[1]]);
4882
4883        // `struct { long a, b; } f(long a, long b)`, after the front end has classified it. Both
4884        // halves are integers, so the second is in the second integer return register, and both
4885        // pseudos say so the same way the one for a single value does.
4886        assert_eq!(
4887            lower(&mut names, &func),
4888            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_64\n    \
4889             %1:gpr($rsi) = x64.arg_val_64\n    x64.ret_val_64 %0($rax)\n    \
4890             x64.ret_val2_64 %1($rdx)\n}\n"
4891        );
4892    }
4893
4894    #[test]
4895    fn two_values_back_in_different_files_are_both_the_first_of_their_own() {
4896        let f64 = Type::float(rucc_ir::Float::F64);
4897        let (mut names, mut func, block, args) = blank(&[f64, Type::int(64)]);
4898        let mut build = Builder::new(&mut func, block);
4899        build.ret(&[args[0], args[1]]);
4900
4901        // `struct { double a; long b; } f(double a, long b)`. The two files are counted apart, so
4902        // neither half is the second of anything and the `double` is in `xmm0` rather than in the
4903        // register a second `double` would have been in. Getting this wrong is not a crash: the
4904        // caller reads a register nobody wrote, and this is where that is ruled out.
4905        assert_eq!(
4906            lower(&mut names, &func),
4907            "mfunc @f {\nblock0:\n    %0:xmm($xmm0) = x64.arg_val_f64\n    \
4908             %1:gpr($rdi) = x64.arg_val_64\n    x64.ret_val_f64 %0($xmm0)\n    \
4909             x64.ret_val_64 %1($rax)\n}\n"
4910        );
4911    }
4912
4913    #[test]
4914    fn two_of_the_same_file_back_take_the_first_two_of_it() {
4915        let f64 = Type::float(rucc_ir::Float::F64);
4916        let (mut names, mut func, block, args) = blank(&[f64, f64]);
4917        let mut build = Builder::new(&mut func, block);
4918        build.ret(&[args[0], args[1]]);
4919
4920        // `struct { double x, y; } f(double x, double y)`, which is the vector half of the pair
4921        // above and counts in its own file the same way.
4922        assert_eq!(
4923            lower(&mut names, &func),
4924            "mfunc @f {\nblock0:\n    %0:xmm($xmm0) = x64.arg_val_f64\n    \
4925             %1:xmm($xmm1) = x64.arg_val_f64\n    x64.ret_val_f64 %0($xmm0)\n    \
4926             x64.ret_val2_f64 %1($xmm1)\n}\n"
4927        );
4928    }
4929
4930    /// A function whose answer goes back through memory, with the pointer to the space for it in
4931    /// front of whatever else it takes. Only the signature says it is one.
4932    fn returning_through_memory(params: &[Type]) -> (Interner, Func, Block, Vec<Value>) {
4933        let mut names = Interner::new();
4934        let sret = Abi::Sret { size: 32, align: 8 };
4935        let mut signature = Signature::new().and_param(Param::with_abi(Type::PTR, sret));
4936        signature.params.extend(params.iter().copied().map(Param::new));
4937        let mut func = Func::new(names.intern("f"), signature);
4938        let block = func.create_block();
4939        let space = func.append_param(block, Type::PTR);
4940        let values = std::iter::once(space)
4941            .chain(params.iter().map(|&ty| func.append_param(block, ty)))
4942            .collect();
4943        (names, func, block, values)
4944    }
4945
4946    #[test]
4947    fn the_space_a_return_through_memory_was_given_goes_back_in_the_first_return_register() {
4948        let (mut names, mut func, block, _) = returning_through_memory(&[]);
4949        Builder::new(&mut func, block).ret(&[]);
4950
4951        // `struct big f(void)`, where `big` is too large to come back in registers. The `return`
4952        // carries nothing, because the value went into the space the caller handed over, and the
4953        // document still says that address comes back in `rax`. Nothing in the IR says it, so the
4954        // convention says it, and the pseudo is the one any other pointer return would use.
4955        assert_eq!(
4956            lower(&mut names, &func),
4957            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_64\n    \
4958             x64.ret_val_64 %0($rax)\n}\n"
4959        );
4960    }
4961
4962    #[test]
4963    fn what_the_function_did_in_between_does_not_take_the_register_off_it() {
4964        let (mut names, mut func, block, args) = returning_through_memory(&[Type::int(32)]);
4965        let mut build = Builder::new(&mut func, block);
4966        build.store(args[1], args[0], plain(), Flags::default());
4967        build.ret(&[]);
4968
4969        // The register is a read at the end and not a move at the start, so it is live across
4970        // everything between the two and the allocator has to keep it somewhere. In a function
4971        // with a call in it that somewhere is a callee saved register, and the address comes back
4972        // into `rax` here rather than whatever the last instruction happened to leave there. That
4973        // is issue #333, and a store is enough to show the value outlives the entry block.
4974        let text = lower(&mut names, &func);
4975        assert!(text.contains("x64.mov_mr_32 %1, [%0]"), "{text}");
4976        assert!(text.ends_with("    x64.ret_val_64 %0($rax)\n}\n"), "{text}");
4977    }
4978
4979    #[test]
4980    fn a_pointer_that_is_only_a_pointer_is_not_given_back() {
4981        let (mut names, mut func, block, args) = blank(&[Type::PTR]);
4982        let mut build = Builder::new(&mut func, block);
4983        build.store(args[0], args[0], plain(), Flags::default());
4984        build.ret(&[]);
4985
4986        // `void f(void **p)`. It takes a pointer first and returns nothing, which is the shape of
4987        // the one above and none of its meaning, and what tells them apart is the signature. A
4988        // `void` function leaves `rax` alone.
4989        assert!(!lower(&mut names, &func).contains("ret_val"));
4990    }
4991
4992    #[test]
4993    fn a_return_of_a_constant_puts_it_in_a_register_first() {
4994        let (mut names, mut func, block, _) = blank(&[]);
4995        let mut build = Builder::new(&mut func, block);
4996        let zero = build.iconst(Type::int(32), 0);
4997        build.ret(&[zero]);
4998
4999        // No rule returns an immediate, so the plan that offers one is turned down and the next
5000        // one materializes it. That is `int main(void) { return 0; }` in full, once the epilogue
5001        // is appended to it.
5002        assert_eq!(
5003            lower(&mut names, &func),
5004            "mfunc @f {\nblock0:\n    %0:gpr = x64.mov_ri_32 0\n    x64.ret_val_32 %0($rax)\n}\n"
5005        );
5006    }
5007
5008    #[test]
5009    fn the_rule_that_writes_a_constant_down_is_recorded_as_a_rule_that_fired() {
5010        let (mut names, mut func, block, _) = blank(&[]);
5011        let mut build = Builder::new(&mut func, block);
5012        let zero = build.iconst(Type::int(32), 0);
5013        build.ret(&[zero]);
5014
5015        // The loop over the instructions passes a constant by, because a constant is written where
5016        // a register for it is first wanted rather than where the IR put it. So the only place a
5017        // rule about one is ever selected is the materialization, and a mark made in the loop
5018        // alone would report every rule about a constant as a rule nothing reaches.
5019        let out = super::func(&func, &mut names, &SYSV, &Elsewhere::default())
5020            .expect("every instruction has a rule");
5021        let rules = &crate::select::x86_64::TABLE.rules;
5022        let fired: Vec<&str> = rules
5023            .iter()
5024            .enumerate()
5025            .filter(|(index, _)| out.fired.has(*index))
5026            .map(|(_, rule)| rule.pattern)
5027            .collect();
5028        assert!(fired.contains(&"(iconst.i32 k)"), "{fired:?}");
5029    }
5030
5031    #[test]
5032    fn a_return_of_nothing_is_no_instruction_at_all() {
5033        let (mut names, mut func, block, _) = blank(&[]);
5034        let mut build = Builder::new(&mut func, block);
5035        build.ret(&[]);
5036
5037        // Every part of leaving a function that returns nothing is the epilogue's, and the
5038        // epilogue goes in after allocation. A block with nothing in it is the right answer here
5039        // rather than a function that could not be lowered.
5040        assert_eq!(lower(&mut names, &func), "mfunc @f {\nblock0:\n}\n");
5041    }
5042
5043    #[test]
5044    fn the_allocator_is_what_moves_the_answer_into_the_return_register() {
5045        let (mut names, mut source, block, _) = blank(&[]);
5046        let mut build = Builder::new(&mut source, block);
5047        let zero = build.iconst(Type::int(32), 0);
5048        build.ret(&[zero]);
5049
5050        let mut out = func(&source, &mut names, &SYSV, &Elsewhere::default())
5051            .expect("every instruction has a rule")
5052            .func;
5053        let env = env();
5054        let allocation = rucc_regalloc::run(&mut out, &env, "test", true);
5055        let frame = Frame::of(&out, &allocation, &Layout::new(&SYSV, REGS));
5056        finish(
5057            &mut out,
5058            &allocation,
5059            &frame,
5060            &Stack::default(),
5061            Convention::new(&SYSV, &FRAME),
5062            &mut names,
5063        );
5064
5065        // `int main(void) { return 0; }` end to end. Nothing here asked for `rax`: the rule said
5066        // the value goes back, the target said where, and the allocator is what made it true. The
5067        // epilogue is what leaves, and this function needs no frame, so it is the return alone.
5068        //
5069        // Two instructions and no copy, which is what a hint buys. The return insists on `rax`,
5070        // so `rax` is the register the allocator tries first for the value the return reads, and
5071        // the constant is written straight into it.
5072        assert_eq!(
5073            mir::print_func(&out, &names, &REGS),
5074            "mfunc @f {\nblock0:\n    $rax = x64.mov_ri_32 0\n    \
5075             x64.ret_val_32 $rax($rax)\n    x64.ret\n}\n"
5076        );
5077    }
5078
5079    #[test]
5080    fn a_function_of_two_arguments_is_a_whole_function_now() {
5081        let i32 = Type::int(32);
5082        let (mut names, mut source, block, args) = blank(&[i32, i32]);
5083        let mut build = Builder::new(&mut source, block);
5084        let sum = build.binary(Opcode::Add, args[0], args[1], Flags::default());
5085        build.ret(&[sum]);
5086
5087        let mut out = func(&source, &mut names, &SYSV, &Elsewhere::default())
5088            .expect("every instruction has a rule")
5089            .func;
5090        let env = env();
5091        let allocation = rucc_regalloc::run(&mut out, &env, "test", true);
5092        let frame = Frame::of(&out, &allocation, &Layout::new(&SYSV, REGS));
5093        finish(
5094            &mut out,
5095            &allocation,
5096            &frame,
5097            &Stack::default(),
5098            Convention::new(&SYSV, &FRAME),
5099            &mut names,
5100        );
5101
5102        // `int f(int a, int b) { return a + b; }` end to end, and this is the test the argument
5103        // side exists for. Before it there was no way to write one: the allocator refuses a
5104        // function whose entry block takes parameters, because there is no edge into an entry
5105        // block for the moves that give a block parameter its value to go on.
5106        //
5107        // One move, and it is the one the machine's addition needs rather than one the allocator
5108        // owes anybody. Each argument stays in the register it arrived in, because the pseudo
5109        // that defines it insists on that register and the allocator now tries it first, and the
5110        // sum stays in the register the addition wrote it to until the return reads it out. The
5111        // copy in front of a two address instruction is what makes its destination one of the
5112        // registers it reads, and the source operand keeps its own name because the destination
5113        // is what the encoder writes.
5114        assert_eq!(
5115            mir::print_func(&out, &names, &REGS),
5116            "mfunc @f {\nblock0:\n    $rdi($rdi) = x64.arg_val_32\n    \
5117             $rsi($rsi) = x64.arg_val_32\n    \
5118             $rdi(reuse 1) = x64.add_rr_32 $rdi, $rsi\n    $rax = x64.mov_rr_64 $rdi\n    \
5119             x64.ret_val_32 $rax($rax)\n    x64.ret\n}\n"
5120        );
5121    }
5122
5123    #[test]
5124    fn an_argument_with_no_register_left_for_it_is_read_out_of_the_caller_s_stack() {
5125        let i64 = Type::int(64);
5126        let (mut names, mut source, block, args) = blank(&[i64; 7]);
5127        let mut build = Builder::new(&mut source, block);
5128        build.ret(&[args[6]]);
5129
5130        let lowered = func(&source, &mut names, &SYSV, &Elsewhere::default())
5131            .expect("the seventh is read from memory");
5132
5133        // SysV passes six integers in registers and the seventh in the caller's memory, so six of
5134        // these are pseudos that encode to nothing and the seventh is a load that encodes to real
5135        // bytes. Its displacement is nothing here for the reason a local's is: there is no frame
5136        // yet. What the walk hands on is which instruction is waiting, and for how far up the
5137        // caller's argument area, which is the bottom of it because it is the first one there.
5138        assert_eq!(lowered.stack.arguments.len(), 1);
5139        assert_eq!(lowered.stack.arguments[0].1, 0);
5140        let text = mir::print_func(&lowered.func, &names, &REGS);
5141        assert!(text.contains("%6:gpr = x64.mov_rm_64 [$rsp]"), "{text}");
5142        assert_eq!(text.matches("x64.arg_val_64").count(), 6, "{text}");
5143    }
5144
5145    #[test]
5146    fn the_frame_is_what_says_how_far_up_the_caller_s_stack_an_argument_is() {
5147        let i64 = Type::int(64);
5148        let (mut names, mut source, block, args) = blank(&[i64; 8]);
5149        let mut build = Builder::new(&mut source, block);
5150        let sum = build.binary(Opcode::Add, args[6], args[7], Flags::default());
5151        build.ret(&[sum]);
5152
5153        let lowered = func(&source, &mut names, &SYSV, &Elsewhere::default())
5154            .expect("both are read from memory");
5155        let stack = lowered.stack;
5156        let mut out = lowered.func;
5157        let env = env();
5158        let allocation = rucc_regalloc::run(&mut out, &env, "test", true);
5159        let layout = stack.layout(Layout::new(&SYSV, REGS));
5160        let frame = Frame::of(&out, &allocation, &layout);
5161        finish(&mut out, &allocation, &frame, &stack, Convention::new(&SYSV, &FRAME), &mut names);
5162
5163        // A leaf that takes no frame, so the stack pointer never moves and the only thing between
5164        // it and the caller's arguments is the return address the call pushed. The seventh
5165        // parameter is at the bottom of the caller's argument area and the eighth is one word
5166        // further up, which is the eight bytes between the two offsets.
5167        let text = mir::print_func(&out, &names, &REGS);
5168        assert_eq!(frame.size(), 0);
5169        assert_eq!(frame.incoming(), Incoming::from_stack(8));
5170        assert!(text.contains("x64.mov_rm_64 [$rsp + 8]"), "{text}");
5171        assert!(text.contains("x64.mov_rm_64 [$rsp + 16]"), "{text}");
5172    }
5173
5174    #[test]
5175    fn a_realigned_frame_reaches_the_caller_s_arguments_through_the_frame_pointer() {
5176        let i64 = Type::int(64);
5177        let (mut names, mut source, block, args) = blank(&[i64; 7]);
5178        let wide = slot(&mut source, block, 64, 32);
5179        let mut build = Builder::new(&mut source, block);
5180        build.store(args[6], wide, plain(), Flags::default());
5181        build.ret(&[args[6]]);
5182
5183        let lowered = func(&source, &mut names, &SYSV, &Elsewhere::default())
5184            .expect("every instruction has a rule");
5185        let stack = lowered.stack;
5186        let mut out = lowered.func;
5187        let env = env();
5188        let allocation = rucc_regalloc::run(&mut out, &env, "test", true);
5189        let layout = stack.layout(Layout::new(&SYSV, REGS));
5190        let frame = Frame::of(&out, &allocation, &layout);
5191        finish(&mut out, &allocation, &frame, &stack, Convention::new(&SYSV, &FRAME), &mut names);
5192
5193        // A local wanting thirty two byte alignment makes the prologue force the stack pointer,
5194        // which throws away how far the caller's stack was. So the load the lowering wrote off the
5195        // stack pointer is rewritten to read through the frame pointer, at the one distance that
5196        // survives: the word the prologue pushed the frame pointer into, and the return address
5197        // above it.
5198        let text = mir::print_func(&out, &names, &REGS);
5199        assert_eq!(frame.realign(), Some(32));
5200        assert_eq!(frame.incoming(), Incoming::from_frame(16));
5201        assert!(text.contains("x64.mov_rm_64 [$rbp + 16]"), "{text}");
5202        assert!(!text.contains("x64.mov_rm_64 [$rsp"), "{text}");
5203    }
5204
5205    #[test]
5206    fn a_jump_is_the_edge_and_nothing_else() {
5207        let i32 = Type::int(32);
5208        let (mut names, mut source, entry, args) = blank(&[i32]);
5209        let next = source.create_block();
5210        let got = source.append_param(next, i32);
5211        Builder::new(&mut source, entry).jump(next, &[args[0]]);
5212        Builder::new(&mut source, next).ret(&[got]);
5213
5214        // Two blocks and two instructions, and the jump is neither of them. What it was is the
5215        // arm on the first block, and what the arm carries is the argument it was called with.
5216        assert_eq!(
5217            lower(&mut names, &source),
5218            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_32 block1(%0)\n\n\
5219             block1(%1:gpr):\n    x64.ret_val_32 %1($rax)\n}\n"
5220        );
5221    }
5222
5223    /// A block that reads what a block below it writes is filled after it, not before it.
5224    ///
5225    /// The blocks are written entry, `early`, `late`, `exit`, and the entry jumps straight past
5226    /// `early` to `late`, so `late` dominates `early` while sitting below it in the function.
5227    /// Filling them in the order they are written reaches the read in `early` first, and reading
5228    /// a value with no register yet mints one. The cast in `late` is no instruction at all, so
5229    /// what it does is give its answer the register its operand is already in, and that is not
5230    /// the register the read minted. Nothing writes the register the read minted. The printer
5231    /// says `%?` for a register nothing defines, which is what this looks for, and what came out
5232    /// of the real bug was SQLite loading a stack slot no store ever reached.
5233    #[test]
5234    fn a_block_that_reads_what_a_block_below_it_writes_is_filled_after_it() {
5235        let i64 = Type::int(64);
5236        let (mut names, mut source, entry, args) = blank(&[i64, i64]);
5237        let early = source.create_block();
5238        let late = source.create_block();
5239        let exit = source.create_block();
5240
5241        Builder::new(&mut source, entry).jump(late, &[]);
5242        let ptr = cast(&mut source, late, Opcode::IntToPtr, args[0], Type::PTR);
5243        Builder::new(&mut source, early).ret(&[ptr]);
5244        let mut build = Builder::new(&mut source, late);
5245        let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
5246        build.br_if(cond, early, &[], exit, &[]);
5247        Builder::new(&mut source, exit).ret(&[args[1]]);
5248
5249        let text = lower(&mut names, &source);
5250        assert!(!text.contains("%?"), "every register has something that writes it: {text}");
5251    }
5252
5253    /// A constant is written where it is wanted rather than where the IR defined it, and two
5254    /// blocks wanting the same one is two places. Writing it once and reading it in both is a
5255    /// register read where nothing wrote it, unless the block it was written in happens to
5256    /// dominate the other, which nothing here checks and which the second arm of a branch never
5257    /// does. Each block gets its own copy of the number instead.
5258    #[test]
5259    fn a_constant_two_blocks_want_is_written_in_both_of_them() {
5260        let i32 = Type::int(32);
5261        let (mut names, mut source, entry, args) = blank(&[i32, i32]);
5262        let then = source.create_block();
5263        let other = source.create_block();
5264        let join = source.create_block();
5265        let got = source.append_param(join, i32);
5266
5267        let mut build = Builder::new(&mut source, entry);
5268        let seven = build.iconst(i32, 7);
5269        let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
5270        build.br_if(cond, then, &[], other, &[]);
5271        // Both arms want the seven in a register, because a block argument is never an immediate,
5272        // and neither arm dominates the other.
5273        Builder::new(&mut source, then).jump(join, &[seven]);
5274        Builder::new(&mut source, other).jump(join, &[seven]);
5275        Builder::new(&mut source, join).ret(&[got]);
5276
5277        let text = lower(&mut names, &source);
5278        assert_eq!(text.matches("x64.mov_ri_32 7").count(), 2, "one seven per block: {text}");
5279    }
5280
5281    /// An argument on an edge out of a block that leaves two ways is read after every instruction
5282    /// of the block is written, and reading one can write an instruction, which would land after
5283    /// the branch that has already jumped past it. The branch goes back on the end.
5284    #[test]
5285    fn a_constant_an_edge_wants_is_written_before_the_branch_and_not_after_it() {
5286        let i32 = Type::int(32);
5287        let (mut names, mut source, entry, args) = blank(&[i32, i32]);
5288        let then = source.create_block();
5289        let join = source.create_block();
5290        let got = source.append_param(join, i32);
5291
5292        let mut build = Builder::new(&mut source, entry);
5293        let nine = build.iconst(i32, 9);
5294        let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
5295        build.br_if(cond, then, &[], join, &[nine]);
5296        Builder::new(&mut source, then).jump(join, &[args[0]]);
5297        Builder::new(&mut source, join).ret(&[got]);
5298
5299        let out = func(&source, &mut names, &SYSV, &Elsewhere::default())
5300            .expect("every instruction has a rule")
5301            .func;
5302        let entry = out.entry().expect("an entry block");
5303        let last = out.terminator(entry).expect("a block that leaves two ways has a branch");
5304        let branch = names.intern("x64.br_cond_8");
5305        assert_eq!(
5306            out[last].opcode,
5307            mir::Opcode::new(branch),
5308            "the branch is last: {}",
5309            mir::print_func(&out, &names, &REGS)
5310        );
5311    }
5312
5313    #[test]
5314    fn a_conditional_branch_is_lowered_to_the_condition_and_nothing_about_where_it_goes() {
5315        let i32 = Type::int(32);
5316        let (mut names, mut source, entry, args) = blank(&[i32, i32]);
5317        let then = source.create_block();
5318        let other = source.create_block();
5319        let mut build = Builder::new(&mut source, entry);
5320        let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
5321        build.br_if(cond, then, &[], other, &[]);
5322        Builder::new(&mut source, then).ret(&[args[0]]);
5323        Builder::new(&mut source, other).ret(&[args[1]]);
5324
5325        // The comparison writes a byte and the branch reads it, and neither says a block. Both
5326        // arms are on the entry block, in the order the branch took them, so the arm that runs
5327        // when the condition holds is the first.
5328        assert_eq!(
5329            lower(&mut names, &source),
5330            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_32\n    \
5331             %1:gpr($rsi) = x64.arg_val_32\n    %2:gpr = x64.cmp_set_l_32 %0, %1\n    \
5332             x64.br_cond_8 %2, block1, block2\n\n\
5333             block1:\n    x64.ret_val_32 %0($rax)\n\n\
5334             block2:\n    x64.ret_val_32 %1($rax)\n}\n"
5335        );
5336    }
5337
5338    /// A choice between two values, which is one instruction and no blocks at all.
5339    ///
5340    /// The arms come out the other way round from the IR, because a conditional move overwrites its
5341    /// destination and the destination is the arm taken when the condition does not hold. The
5342    /// condition arrives last for the same reason: it is read by the test in front of the move
5343    /// rather than by the move.
5344    #[test]
5345    fn a_select_is_lowered_to_a_test_and_a_conditional_move() {
5346        let i32 = Type::int(32);
5347        let (mut names, mut source, entry, args) = blank(&[i32, i32]);
5348        let mut build = Builder::new(&mut source, entry);
5349        let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
5350        let picked = build.select(cond, args[0], args[1]);
5351        build.ret(&[picked]);
5352
5353        assert_eq!(
5354            lower(&mut names, &source),
5355            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_32\n    \
5356             %1:gpr($rsi) = x64.arg_val_32\n    %2:gpr = x64.cmp_set_l_32 %0, %1\n    \
5357             %3:gpr(reuse 1) = x64.test_cmov_ne_32 %1, %0, %2\n    \
5358             x64.ret_val_32 %3($rax)\n}\n"
5359        );
5360    }
5361
5362    #[test]
5363    fn a_branch_over_a_block_is_a_whole_function_now() {
5364        let i32 = Type::int(32);
5365        let (mut names, mut source, entry, args) = blank(&[i32, i32]);
5366        let then = source.create_block();
5367        let other = source.create_block();
5368        let join = source.create_block();
5369        let got = source.append_param(join, i32);
5370        let mut build = Builder::new(&mut source, entry);
5371        let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
5372        build.br_if(cond, then, &[], other, &[]);
5373        let mut build = Builder::new(&mut source, then);
5374        let sum = build.binary(Opcode::Add, args[0], args[1], Flags::default());
5375        build.jump(join, &[sum]);
5376        Builder::new(&mut source, other).jump(join, &[args[1]]);
5377        Builder::new(&mut source, join).ret(&[got]);
5378
5379        // `int f(int a, int b) { if (a < b) return a + b; else return b; }` end to end, written
5380        // the way a front end writes it: both arms of the branch are blocks of their own and the
5381        // return is the block they meet at. No edge here is critical, because the two arms out of
5382        // the entry carry nothing and the two arms into the join each leave a block that goes
5383        // nowhere else, so each has its own end to put its move at.
5384        let mut out = func(&source, &mut names, &SYSV, &Elsewhere::default())
5385            .expect("every instruction has a rule")
5386            .func;
5387        assert_eq!(crate::split::critical(&mut out), 0, "no edge here is critical");
5388        let env = env();
5389        let allocation = rucc_regalloc::run(&mut out, &env, "test", true);
5390        let frame = Frame::of(&out, &allocation, &Layout::new(&SYSV, REGS));
5391        finish(
5392            &mut out,
5393            &allocation,
5394            &frame,
5395            &Stack::default(),
5396            Convention::new(&SYSV, &FRAME),
5397            &mut names,
5398        );
5399
5400        // One epilogue, on the join, which is the one block the function leaves from, and the
5401        // moves that give the join its parameter are at the end of each arm. Every register is
5402        // physical and the branch is still a branch on a register, because turning it into a
5403        // `test` and a `jcc` is the block layout's and there is no block layout yet.
5404        let text = mir::print_func(&out, &names, &REGS);
5405        assert_eq!(text.matches("x64.ret\n").count(), 1, "{text}");
5406        assert!(text.contains("x64.br_cond_8"), "{text}");
5407        assert!(text.contains("x64.add_rr_32"), "{text}");
5408        assert!(!text.contains('%'), "{text}");
5409    }
5410
5411    #[test]
5412    fn a_critical_edge_is_split_before_the_allocator_ever_sees_it() {
5413        let i32 = Type::int(32);
5414        let (mut names, mut source, entry, args) = blank(&[i32, i32]);
5415        let then = source.create_block();
5416        let join = source.create_block();
5417        let got = source.append_param(join, i32);
5418        let mut build = Builder::new(&mut source, entry);
5419        let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
5420        build.br_if(cond, then, &[], join, &[args[1]]);
5421        Builder::new(&mut source, then).jump(join, &[args[0]]);
5422        let mut build = Builder::new(&mut source, join);
5423        let twice = build.binary(Opcode::Add, got, got, Flags::default());
5424        build.ret(&[twice]);
5425
5426        // The else arm is critical: the entry block leaves two ways and the join is arrived at
5427        // two ways, and the arm carries a value. Without splitting it the allocator asserts,
5428        // because the move that gives the join its parameter would have to run at the end of a
5429        // block that also goes to the other arm.
5430        let mut out = func(&source, &mut names, &SYSV, &Elsewhere::default())
5431            .expect("every instruction has a rule")
5432            .func;
5433        assert_eq!(crate::split::critical(&mut out), 1);
5434        let env = env();
5435        let allocation = rucc_regalloc::run(&mut out, &env, "test", true);
5436        let frame = Frame::of(&out, &allocation, &Layout::new(&SYSV, REGS));
5437        finish(
5438            &mut out,
5439            &allocation,
5440            &frame,
5441            &Stack::default(),
5442            Convention::new(&SYSV, &FRAME),
5443            &mut names,
5444        );
5445
5446        // The block the split added is where the move went, and it is the whole of that block.
5447        let text = mir::print_func(&out, &names, &REGS);
5448        assert_eq!(out.block_count(), 4, "{text}");
5449        assert_eq!(text.matches("x64.ret\n").count(), 1, "{text}");
5450    }
5451
5452    #[test]
5453    fn a_call_passes_what_the_convention_says_and_takes_back_what_it_says() {
5454        let i32 = Type::int(32);
5455        let (mut names, mut source, block, args) = blank(&[i32, i32]);
5456        let sig =
5457            source.add_signature(Signature::new().with_params(&[i32, i32]).with_returns(&[i32]));
5458        let callee = names.intern("g");
5459        let call = Builder::new(&mut source, block).call(callee, sig, &[args[0], args[1]]);
5460        let got = source[call].first_result.expect("an integer comes back");
5461        Builder::new(&mut source, block).ret(&[got]);
5462
5463        // `int f(int a, int b) { return g(a, b); }`. The arguments arrived where the call wants
5464        // them, so what the call reads is what arrived, and the whole of the convention is in the
5465        // constraints rather than in a move.
5466        let text = lower(&mut names, &source);
5467        assert!(text.contains("= x64.call %0($rdi), %1($rsi), @g"), "{text}");
5468        assert!(text.contains("x64.ret_val_32 %2($rax)"), "{text}");
5469        // What the call writes is the value that comes back and then every register the callee is
5470        // free to destroy, in both classes, which is the whole of what stops the allocator from
5471        // leaving something in one of them.
5472        assert!(text.contains("%2:gpr($rax), $rcx, $rdx, $r8, $r9, $r10, $r11, $xmm0,"), "{text}");
5473        assert!(text.contains("$xmm15 = x64.call"), "{text}");
5474    }
5475
5476    #[test]
5477    fn what_the_frame_owes_a_call_comes_back_with_the_function() {
5478        let i32 = Type::int(32);
5479        let sig = |source: &mut Func| source.add_signature(Signature::new().with_params(&[i32]));
5480
5481        let (mut names, mut source, block, args) = blank(&[i32]);
5482        let sig = sig(&mut source);
5483        let callee = names.intern("g");
5484        Builder::new(&mut source, block).call(callee, sig, &[args[0]]);
5485        let out = func(&source, &mut names, &SYSV, &Elsewhere::default())
5486            .expect("every instruction has a rule");
5487
5488        // Nothing on the stack, so nothing owed, but not a leaf either: a function that calls
5489        // owes the callee an aligned stack pointer and may not use the red zone.
5490        assert_eq!(out.stack.calls, Some(0));
5491        let layout = out.stack.layout(Layout::new(&SYSV, REGS));
5492        assert!(!layout.leaf);
5493        assert_eq!(layout.outgoing, 0);
5494
5495        // The same call under the other convention owes thirty two bytes for the callee to spill
5496        // its register arguments into, which is a fact about the convention and not about the call.
5497        let out = func(&source, &mut names, &x86_64::WIN64, &Elsewhere::default())
5498            .expect("every instruction has a rule");
5499        assert_eq!(out.stack.calls, Some(32));
5500
5501        // And a function that calls nothing is a leaf, which is what says it may use the red zone.
5502        let (mut names, mut source, block, args) = blank(&[i32]);
5503        Builder::new(&mut source, block).ret(&[args[0]]);
5504        let out = func(&source, &mut names, &SYSV, &Elsewhere::default())
5505            .expect("every instruction has a rule");
5506        assert_eq!(out.stack.calls, None);
5507        assert!(out.stack.layout(Layout::new(&SYSV, REGS)).leaf);
5508    }
5509
5510    /// A Windows variadic prologue writes the argument registers the signature did not name into
5511    /// the shadow space the caller already reserved, which makes every argument one run of words up
5512    /// there and a `va_start` the address of the first of them. One `lea` and one store, and no
5513    /// counts, because a list that is a pointer has nowhere to put one and nothing that reads one.
5514    #[test]
5515    fn a_windows_variadic_function_homes_its_spare_registers_in_the_callers_area() {
5516        let mut names = Interner::new();
5517        let params = [Type::int(32), Type::PTR];
5518        let signature = Signature::new().with_params(&params).variadic();
5519        let mut source = Func::new(names.intern("f"), signature);
5520        let block = source.create_block();
5521        let values: Vec<Value> = params.iter().map(|&ty| source.append_param(block, ty)).collect();
5522        let mut build = Builder::new(&mut source, block);
5523        let args = build.func().push_values(&values[1..]);
5524        build.inst(InstData { args, ..InstData::new(Opcode::VaStart) }, &[]);
5525        build.ret(&[]);
5526
5527        let out = func(&source, &mut names, &x86_64::WIN64, &Elsewhere::default())
5528            .expect("every instruction has a rule");
5529        let text = mir::print_func(&out.func, &names, &REGS);
5530
5531        // Two named parameters, so the registers at the next two positions hold arguments nobody
5532        // named and both are written up into the caller's area. The displacement is empty here and
5533        // `finish` fills it in, the same way it does for a parameter the registers ran out before.
5534        assert!(text.contains("($r8) = x64.arg_val_64"), "{text}");
5535        assert!(text.contains("($r9) = x64.arg_val_64"), "{text}");
5536        assert_eq!(text.matches("x64.mov_mr_64").count(), 3, "two homed and one stored: {text}");
5537        assert!(!text.contains("x64.mov_ri_32"), "and no field holds a count: {text}");
5538
5539        // All three waiting on the same fixup, and the last of them is the `lea` the list is given,
5540        // sixteen bytes up, which is where the two arguments the signature does name stopped.
5541        assert_eq!(out.stack.arguments.len(), 3);
5542        assert_eq!(out.stack.arguments[2].1, 16);
5543    }
5544
5545    #[test]
5546    fn a_value_that_outlives_a_call_is_not_left_where_the_call_destroys_it() {
5547        let i32 = Type::int(32);
5548        let (mut names, mut source, block, args) = blank(&[i32]);
5549        let sig = source.add_signature(Signature::new().with_params(&[i32]).with_returns(&[i32]));
5550        let callee = names.intern("g");
5551        let call = Builder::new(&mut source, block).call(callee, sig, &[args[0]]);
5552        let got = source[call].first_result.expect("an integer comes back");
5553        let mut build = Builder::new(&mut source, block);
5554        let sum = build.binary(Opcode::Add, got, args[0], Flags::default());
5555        build.ret(&[sum]);
5556
5557        // `int f(int a) { return g(a) + a; }`, which is the smallest program that asks the
5558        // question: `a` is read after the call and `rdi` is a register the call destroys.
5559        let lowered = func(&source, &mut names, &SYSV, &Elsewhere::default())
5560            .expect("every instruction has a rule");
5561        let layout = lowered.stack.layout(Layout::new(&SYSV, REGS));
5562        let mut out = lowered.func;
5563        let env = env();
5564        let allocation = rucc_regalloc::run(&mut out, &env, "test", true);
5565        let frame = Frame::of(&out, &allocation, &layout);
5566        finish(
5567            &mut out,
5568            &allocation,
5569            &frame,
5570            &Stack::default(),
5571            Convention::new(&SYSV, &FRAME),
5572            &mut names,
5573        );
5574
5575        // It went to a register the callee has to put back, and the prologue and epilogue are what
5576        // put it back, which is the whole bargain the two halves of a convention make.
5577        let text = mir::print_func(&out, &names, &REGS);
5578        assert!(text.contains("$rbx"), "{text}");
5579        assert!(!text.contains('%'), "{text}");
5580        assert_eq!(text.matches("x64.call").count(), 1, "{text}");
5581    }
5582
5583    #[test]
5584    fn a_call_with_more_arguments_than_registers_writes_the_rest_into_the_outgoing_area() {
5585        let i64 = Type::int(64);
5586        let (mut names, mut source, block, args) = blank(&[i64]);
5587        let seven = vec![i64; 7];
5588        let sig = source.add_signature(Signature::new().with_params(&seven));
5589        let callee = names.intern("g");
5590        let passed = vec![args[0]; 7];
5591        Builder::new(&mut source, block).call(callee, sig, &passed);
5592
5593        let lowered = func(&source, &mut names, &SYSV, &Elsewhere::default())
5594            .expect("the seventh goes to memory");
5595        // The bytes the call needs are on the layout the frame is worked out from, so that the
5596        // frame reserves as many as the widest call in the function asked for.
5597        assert_eq!(lowered.stack.calls, Some(8));
5598        let text = mir::print_func(&lowered.func, &names, &REGS);
5599        assert!(text.contains("x64.mov_mr_64 %0, [$rsp]\n"), "{text}");
5600    }
5601
5602    #[test]
5603    fn a_call_this_cannot_make_is_reported_rather_than_made() {
5604        let (mut names, mut source, block, _) = blank(&[]);
5605        let returns = [Type::float(rucc_ir::Float::F80), Type::int(64)];
5606        let sig = source.add_signature(Signature::new().with_returns(&returns));
5607        let callee = names.intern("g");
5608        Builder::new(&mut source, block).call(callee, sig, &[]);
5609        let failed = func(&source, &mut names, &SYSV, &Elsewhere::default())
5610            .expect_err("a long double is on the x87");
5611        assert_eq!(failed.to_string(), "what this call gives back is on the x87 stack");
5612    }
5613
5614    /// A `long double` on its own is a different answer, because on its own it comes back on the
5615    /// x87 stack rather than in a register, which is somewhere the call cannot be said to write.
5616    ///
5617    /// So the call gives back nothing at all and the value is taken off the stack by the `fstp`
5618    /// straight after it. That instruction has to be straight after it: the stack is one place and
5619    /// anything else that touched it before this ran would be looking at the value still on it.
5620    #[test]
5621    fn a_call_that_gives_back_a_long_double_takes_it_off_the_stack_at_once() {
5622        let (mut names, mut source, block, _) = blank(&[]);
5623        let long_double = Type::float(rucc_ir::Float::F80);
5624        let sig = source.add_signature(Signature::new().with_returns(&[long_double]));
5625        let callee = names.intern("g");
5626        Builder::new(&mut source, block).call(callee, sig, &[]);
5627
5628        let lowered = func(&source, &mut names, &SYSV, &Elsewhere::default())
5629            .expect("the value comes back in st0");
5630        let text = mir::print_func(&lowered.func, &names, &REGS);
5631        let after: Vec<&str> =
5632            text.lines().skip_while(|line| !line.contains("x64.call")).skip(1).collect();
5633        assert_eq!(after[0].trim(), "%0:gpr = x64.lea_64 [$rsp]", "{text}");
5634        assert_eq!(after[1].trim(), "x64.fstp_t [%0]", "{text}");
5635        // And the slot it went into is the sixteen bytes the type takes, like every other one.
5636        assert_eq!(lowered.stack.locals.len(), 1, "{text}");
5637        assert_eq!(lowered.stack.locals[0].size, X87_BYTES);
5638    }
5639
5640    #[test]
5641    fn a_call_through_an_address_goes_through_the_register_the_address_is_in() {
5642        let i32 = Type::int(32);
5643        let (mut names, mut source, block, args) = blank(&[Type::PTR, i32]);
5644        let sig = source.add_signature(Signature::new().with_params(&[i32]).with_returns(&[i32]));
5645        let varargs = source.push_abis(&[]);
5646        let info = source.add_call(CallInfo { callee: None, signature: sig, varargs });
5647        let mut build = Builder::new(&mut source, block);
5648        let inst = InstData {
5649            args: build.func().push_values(&[args[0], args[1]]),
5650            extra: Extra::Call(info),
5651            ..InstData::new(Opcode::CallIndirect)
5652        };
5653        let called = build.inst(inst, &[i32]);
5654        let got = source[called].first_result.expect("an integer comes back");
5655        Builder::new(&mut source, block).ret(&[got]);
5656
5657        // `int f(int (*g)(int), int a) { return g(a); }`. The first operand is the address and
5658        // the arguments are the ones behind it, and everything else about the call is what a call
5659        // to a name would have been.
5660        let text = lower(&mut names, &source);
5661        assert!(text.contains("= x64.call_reg %0, %1($rdi)"), "{text}");
5662        assert!(text.contains("x64.ret_val_32 %2($rax)"), "{text}");
5663        assert!(!text.contains("@g"), "a call through an address names nobody: {text}");
5664    }
5665
5666    #[test]
5667    fn an_instruction_no_rule_covers_is_reported() {
5668        let (mut names, mut source, block, args) = blank(&[Type::PTR]);
5669        let mut build = Builder::new(&mut source, block);
5670        let operands = build.func().push_values(&[args[0]]);
5671        build.inst(InstData { args: operands, ..InstData::new(Opcode::MetaBegin) }, &[]);
5672
5673        // The mark that an object has come into being, which nothing writes an instruction for
5674        // yet: what it needs is a write over a range of the lifetime plane, and that is
5675        // `tamnd/rucc#856`. Nothing about it is a width or a register, so there is nothing for the
5676        // message to add beyond the name.
5677        let failed = func(&source, &mut names, &SYSV, &Elsewhere::default())
5678            .expect_err("no rule writes the beginning of a lifetime");
5679        assert_eq!(failed.to_string(), "no rule lowers a `meta_begin`");
5680
5681        // It produces nothing, so there is no type in the message and nothing invents one, and the
5682        // instruction comes back so a caller can ask the function where it was.
5683        let inst = failed.inst().expect("the instruction it is about");
5684        assert_eq!(source[inst].opcode, Opcode::MetaBegin);
5685    }
5686
5687    /// A barrier is written by name here, and what it is depends on the ordering and on nothing
5688    /// else. `crate::expand` is where the reasoning about this machine's memory model lives.
5689    #[test]
5690    fn a_barrier_is_one_instruction_at_the_strongest_ordering_and_none_below_it() {
5691        for order in MemOrder::all().filter(|&order| order != MemOrder::NotAtomic) {
5692            let (mut names, mut source, block, _) = blank(&[]);
5693            let mut build = Builder::new(&mut source, block);
5694            build
5695                .inst(InstData { extra: Extra::Order(order), ..InstData::new(Opcode::Fence) }, &[]);
5696
5697            let text = lower(&mut names, &source);
5698            assert_eq!(text.contains("x64.mfence"), order == MemOrder::SeqCst, "{order:?}: {text}");
5699        }
5700    }
5701
5702    /// A compare and exchange is written by name too, and at the width of the value rather than at
5703    /// the width of the address, which is the mistake worth pinning: everything here is a pointer
5704    /// and only the value says how many bytes the instruction touches.
5705    #[test]
5706    fn a_compare_and_exchange_is_one_instruction_at_the_width_of_the_value() {
5707        for bits in [8, 16, 32, 64] {
5708            let ty = Type::int(bits);
5709            let (mut names, mut source, block, args) = blank(&[Type::PTR, ty, ty]);
5710            let mut build = Builder::new(&mut source, block);
5711            let mem = build.func().add_mem(MemInfo {
5712                size: u64::from(bits / 8),
5713                align: bits / 8,
5714                order: MemOrder::SeqCst,
5715                ..plain()
5716            });
5717            let operands = build.func().push_values(&[args[0], args[1], args[2]]);
5718            build.inst(
5719                InstData {
5720                    args: operands,
5721                    extra: Extra::Mem(mem),
5722                    ..InstData::new(Opcode::Cmpxchg)
5723                },
5724                &[ty, Type::I1],
5725            );
5726
5727            // Two values out of one instruction, the first of them in the register the machine
5728            // reads the expected value out of, the second free for the allocator to place. The
5729            // address is the memory operand and neither of the two values is.
5730            let text = lower(&mut names, &source);
5731            let written = format!("%3:gpr($rax), %4:gpr = x64.cmpxchg_{bits} %1($rax), %2, [%0]");
5732            assert!(text.contains(&written), "{bits}: {text}");
5733        }
5734    }
5735
5736    #[test]
5737    fn more_values_back_than_the_convention_has_registers_for_is_reported() {
5738        let i64 = Type::int(64);
5739        let (mut names, mut source, block, args) = blank(&[i64, i64, i64]);
5740        let mut build = Builder::new(&mut source, block);
5741        build.ret(&[args[0], args[1], args[2]]);
5742
5743        // Two integers come back in `rax` and `rdx` and a third has nowhere to go, which is not a
5744        // gap in the rules but the convention saying no. The front end classifies before it gets
5745        // here, so this is the shape that would mean the classification went wrong.
5746        let failed = func(&source, &mut names, &SYSV, &Elsewhere::default())
5747            .expect_err("only two come back");
5748        assert_eq!(
5749            failed.to_string(),
5750            "what this function gives back takes more registers than this convention has for it"
5751        );
5752
5753        let inst = failed.inst().expect("the instruction it is about");
5754        assert_eq!(source[inst].opcode, Opcode::Return);
5755    }
5756
5757    /// A refusal about a signature has no instruction, which is what makes it the one arm apart.
5758    ///
5759    /// Everything else is about something written somewhere in the body and hands it back so a
5760    /// caller can ask the function where it came from. A parameter arrives before the first
5761    /// instruction runs, so there is nothing in the body to point at and the message is about
5762    /// the function.
5763    #[test]
5764    fn a_refusal_about_a_parameter_has_no_instruction_to_point_at() {
5765        let missing = Unsupported::Argument { index: 0, missing: Missing::OnX87 };
5766        assert_eq!(missing.inst(), None);
5767    }
5768
5769    /// An `alloca` of a fixed size, which is what every local whose address is taken becomes.
5770    fn slot(source: &mut Func, block: Block, size: u64, align: u32) -> Value {
5771        let info = MemInfo { size, align, ..plain() };
5772        let mut build = Builder::new(source, block);
5773        let mem = build.func().add_mem(info);
5774        build.value(InstData { extra: Extra::Mem(mem), ..InstData::new(Opcode::Alloca) }, Type::PTR)
5775    }
5776
5777    #[test]
5778    fn a_local_is_memory_in_the_frame_and_one_instruction_that_says_where() {
5779        let (mut names, mut source, block, _) = blank(&[]);
5780        let slot = slot(&mut source, block, 4, 4);
5781        let mut build = Builder::new(&mut source, block);
5782        let nine = build.iconst(Type::int(32), 9);
5783        build.store(nine, slot, plain(), Flags::default());
5784        let loaded = build.load(Type::int(32), slot, plain(), Flags::default());
5785        build.ret(&[loaded]);
5786
5787        let lowered = func(&source, &mut names, &SYSV, &Elsewhere::default())
5788            .expect("every instruction has a rule");
5789
5790        // Four bytes on the list the frame is laid out from, and the one instruction that reads
5791        // where they went. Its displacement is nothing here because there is no frame yet, and
5792        // which instruction is waiting for which local is what `finish` is handed.
5793        assert_eq!(lowered.stack.locals, vec![Local { size: 4, align: 4 }]);
5794        assert_eq!(lowered.stack.addresses.len(), 1);
5795        assert_eq!(lowered.stack.addresses[0].1, 0);
5796        assert_eq!(
5797            mir::print_func(&lowered.func, &names, &REGS),
5798            "mfunc @f {\nblock0:\n    %0:gpr = x64.lea_64 [$rsp]\n    \
5799             %1:gpr = x64.mov_ri_32 9\n    x64.mov_mr_32 %1, [%0]\n    \
5800             %2:gpr = x64.mov_rm_32 [%0]\n    x64.ret_val_32 %2($rax)\n}\n"
5801        );
5802    }
5803
5804    #[test]
5805    fn a_local_the_program_declared_says_which_declaration_it_is_and_the_rest_say_nothing() {
5806        let (mut names, mut source, block, _) = blank(&[]);
5807        let scratch = slot(&mut source, block, 4, 4);
5808        let mut build = Builder::new(&mut source, block);
5809        let mem = build.func().add_mem(MemInfo { size: 8, align: 8, ..plain() });
5810        let declared = build
5811            .value(InstData { extra: Extra::Mem(mem), ..InstData::new(Opcode::Alloca) }, Type::PTR);
5812        build.func().declare_mem(mem, 41);
5813        build.store(scratch, declared, MemInfo { size: 8, align: 8, ..plain() }, Flags::default());
5814        build.ret(&[]);
5815
5816        let lowered = func(&source, &mut names, &SYSV, &Elsewhere::default())
5817            .expect("every instruction has a rule");
5818
5819        // Two locals and one declaration, held against the order the allocas were lowered in,
5820        // which is the only name a local has by the time the frame places it. The scratch one was
5821        // reached first and is local zero, so the declared one is local one.
5822        assert_eq!(lowered.stack.locals.len(), 2);
5823        assert_eq!(lowered.stack.declared, vec![(1, 41)]);
5824    }
5825
5826    /// A local the program kept in a value comes out saying which register holds it.
5827    ///
5828    /// The other half of the local above, which had a slot. This one has none, so what carries the
5829    /// declaration is the register the instruction computing it writes into.
5830    #[test]
5831    fn a_local_the_program_kept_in_a_value_says_which_register_holds_it() {
5832        let (mut names, mut source, block, _) = blank(&[]);
5833        let mut build = Builder::new(&mut source, block);
5834        let nine = build.iconst(Type::int(32), 9);
5835        let ten = build.iconst(Type::int(32), 10);
5836        let sum = build.binary(Opcode::Add, nine, ten, Flags::default());
5837        build.func().declare_value(sum, 41);
5838        build.ret(&[sum]);
5839
5840        let lowered = func(&source, &mut names, &SYSV, &Elsewhere::default())
5841            .expect("every instruction has a rule");
5842
5843        // One pair and not three. The constants are values the program never declared, and a
5844        // register holding one of those is nobody's. The register is the one the addition writes,
5845        // which the listing under it is what pins down.
5846        assert_eq!(lowered.func.named, vec![(41, mir::Reg::virtual_reg(1))]);
5847        assert_eq!(
5848            mir::print_func(&lowered.func, &names, &REGS),
5849            "mfunc @f {\nblock0:\n    %0:gpr = x64.mov_ri_32 9\n    \
5850             %1:gpr(reuse 1) = x64.add_ri_32 %0, 10\n    x64.ret_val_32 %1($rax)\n}\n"
5851        );
5852    }
5853
5854    /// A local held in a constant two blocks want is two registers and both of them are it.
5855    ///
5856    /// Why the declaration is written down as each register is handed out rather than once at the
5857    /// end over the map from values to registers. That map remembers the last register a value was
5858    /// written into, and a constant is written again in every block that wants one, so a local held
5859    /// in one would come out findable in the last block of the function and nowhere else.
5860    #[test]
5861    fn a_local_held_in_a_constant_two_blocks_want_is_named_in_both_of_them() {
5862        let i32 = Type::int(32);
5863        let (mut names, mut source, entry, args) = blank(&[i32, i32]);
5864        let then = source.create_block();
5865        let other = source.create_block();
5866        let join = source.create_block();
5867        let got = source.append_param(join, i32);
5868
5869        let mut build = Builder::new(&mut source, entry);
5870        let seven = build.iconst(i32, 7);
5871        let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
5872        build.func().declare_value(seven, 41);
5873        build.br_if(cond, then, &[], other, &[]);
5874        Builder::new(&mut source, then).jump(join, &[seven]);
5875        Builder::new(&mut source, other).jump(join, &[seven]);
5876        Builder::new(&mut source, join).ret(&[got]);
5877
5878        let lowered = func(&source, &mut names, &SYSV, &Elsewhere::default())
5879            .expect("every instruction has a rule");
5880
5881        let held = &lowered.func.named;
5882        assert_eq!(held.len(), 2, "one register per block that wanted the seven: {held:?}");
5883        assert!(held.iter().all(|&(decl, _)| decl == 41), "{held:?}");
5884        assert_ne!(held[0].1, held[1].1, "the same register in two blocks: {held:?}");
5885    }
5886
5887    /// A parameter the program declared comes out named too, in the register it arrived in.
5888    ///
5889    /// The case the walk over the map at the end is for. A parameter is put in a register the
5890    /// convention chose rather than in a fresh one, so nothing asks the mint for it and the pair
5891    /// would otherwise never be written down.
5892    #[test]
5893    fn a_parameter_the_program_declared_says_which_register_it_arrived_in() {
5894        let i32 = Type::int(32);
5895        let (mut names, mut source, block, args) = blank(&[i32]);
5896        let mut build = Builder::new(&mut source, block);
5897        build.func().declare_value(args[0], 41);
5898        build.ret(&[args[0]]);
5899
5900        let lowered = func(&source, &mut names, &SYSV, &Elsewhere::default())
5901            .expect("every instruction has a rule");
5902
5903        let held = &lowered.func.named;
5904        assert_eq!(held.len(), 1, "one pair for the one parameter: {held:?}");
5905        assert_eq!(held[0].0, 41);
5906    }
5907
5908    /// A function with nothing declared in it says nothing, which is every function compiled
5909    /// without debugging information asked for.
5910    #[test]
5911    fn a_function_the_front_end_named_nothing_in_names_no_registers() {
5912        let (mut names, mut source, block, _) = blank(&[]);
5913        let mut build = Builder::new(&mut source, block);
5914        let nine = build.iconst(Type::int(32), 9);
5915        build.ret(&[nine]);
5916
5917        let lowered = func(&source, &mut names, &SYSV, &Elsewhere::default())
5918            .expect("every instruction has a rule");
5919        assert!(lowered.func.named.is_empty(), "{:?}", lowered.func.named);
5920    }
5921
5922    #[test]
5923    fn the_frame_is_what_fills_the_address_of_a_local_in() {
5924        let (mut names, mut source, block, _) = blank(&[]);
5925        let slot = slot(&mut source, block, 4, 4);
5926        let mut build = Builder::new(&mut source, block);
5927        let nine = build.iconst(Type::int(32), 9);
5928        build.store(nine, slot, plain(), Flags::default());
5929        let loaded = build.load(Type::int(32), slot, plain(), Flags::default());
5930        build.ret(&[loaded]);
5931
5932        let lowered = func(&source, &mut names, &SYSV, &Elsewhere::default())
5933            .expect("every instruction has a rule");
5934        let stack = lowered.stack;
5935        let mut out = lowered.func;
5936        let env = env();
5937        let allocation = rucc_regalloc::run(&mut out, &env, "test", true);
5938        let layout = stack.layout(Layout::new(&SYSV, REGS));
5939        let frame = Frame::of(&out, &allocation, &layout);
5940        finish(&mut out, &allocation, &frame, &stack, Convention::new(&SYSV, &FRAME), &mut names);
5941
5942        // `int f(void) { int x; x = 9; return x; }` with the address of `x` taken, end to end.
5943        // A leaf small enough to live in the red zone takes no frame at all, so the stack pointer
5944        // never moves and the four bytes are below it, which is what the negative offset is. The
5945        // instruction the lowering left with nothing in its displacement now has the answer in it.
5946        let text = mir::print_func(&out, &names, &REGS);
5947        assert!(text.contains("$rax = x64.lea_64 [$rsp - 8]"), "{text}");
5948        assert!(!text.contains("x64.sub_ri_64"), "{text}");
5949        assert_eq!(frame.size(), 0);
5950        assert_eq!(frame.local(0), Some(-8));
5951    }
5952
5953    /// An `alloca` whose size is an operand, which is a variable length array.
5954    fn growing(source: &mut Func, block: Block, size: Value, align: u32) -> Value {
5955        let info = MemInfo { size: 0, align, ..plain() };
5956        let mut build = Builder::new(source, block);
5957        let mem = build.func().add_mem(info);
5958        let args = build.func().push_values(&[size]);
5959        build.value(
5960            InstData { args, extra: Extra::Mem(mem), ..InstData::new(Opcode::Alloca) },
5961            Type::PTR,
5962        )
5963    }
5964
5965    #[test]
5966    fn a_stack_slot_whose_size_is_not_known_until_it_runs_takes_the_bytes_off_the_stack_pointer() {
5967        let (mut names, mut source, block, args) = blank(&[Type::int(64)]);
5968        let slot = growing(&mut source, block, args[0], 16);
5969        Builder::new(&mut source, block).ret(&[slot]);
5970
5971        let lowered = func(&source, &mut names, &SYSV, &Elsewhere::default())
5972            .expect("every instruction has a rule");
5973
5974        // The bytes come off the stack pointer where the declaration stands and the address is
5975        // where the stack pointer then is, which is one subtraction and one `lea` rather than a
5976        // slot the frame laid out. Nothing is on the list of locals, because there is nothing
5977        // about this the frame could place.
5978        let text = mir::print_func(&lowered.func, &names, &REGS);
5979        assert!(text.contains("$rsp = x64.sub_rr_64 $rsp, %0"), "{text}");
5980        assert!(text.contains("x64.lea_64 [$rsp]"), "{text}");
5981        assert!(lowered.stack.locals.is_empty(), "{text}");
5982        assert_eq!(lowered.stack.dynamic.len(), 1);
5983        assert!(lowered.stack.grown_at.is_some());
5984    }
5985
5986    #[test]
5987    fn a_growing_slot_wanting_more_alignment_than_the_stack_pointer_has_is_reported() {
5988        let (mut names, mut source, block, args) = blank(&[Type::int(64)]);
5989        let slot = growing(&mut source, block, args[0], 32);
5990        Builder::new(&mut source, block).ret(&[slot]);
5991
5992        // Thirty two is more than a call leaves the stack pointer on, so giving it what it asked
5993        // for means masking the stack pointer after moving it, and after that no constant reaches
5994        // the rest of the frame from the frame pointer either. A second pointer held for the
5995        // purpose is what fixes it and there is not one yet.
5996        let failed = func(&source, &mut names, &SYSV, &Elsewhere::default())
5997            .expect_err("nothing realigns a frame that grows");
5998        assert_eq!(
5999            failed.to_string(),
6000            "this local wants more alignment than the stack pointer is left on, which needs a \
6001             base register nothing here keeps"
6002        );
6003    }
6004
6005    #[test]
6006    fn a_frame_that_grows_reaches_its_own_locals_through_the_frame_pointer() {
6007        let (mut names, mut source, block, args) = blank(&[Type::int(64)]);
6008        let fixed = slot(&mut source, block, 4, 4);
6009        let mut build = Builder::new(&mut source, block);
6010        let nine = build.iconst(Type::int(32), 9);
6011        build.store(nine, fixed, plain(), Flags::default());
6012        let grown = growing(&mut source, block, args[0], 16);
6013        Builder::new(&mut source, block).ret(&[grown]);
6014
6015        let lowered = func(&source, &mut names, &SYSV, &Elsewhere::default())
6016            .expect("every instruction has a rule");
6017        let stack = lowered.stack;
6018        let mut out = lowered.func;
6019        let env = env();
6020        let allocation = rucc_regalloc::run(&mut out, &env, "test", true);
6021        let layout = stack.layout(Layout::new(&SYSV, REGS));
6022        let frame = Frame::of(&out, &allocation, &layout);
6023        finish(&mut out, &allocation, &frame, &stack, Convention::new(&SYSV, &FRAME), &mut names);
6024
6025        // The stack pointer moves in the middle of the function, so the four bytes of the fixed
6026        // local are not a constant away from it any more and the frame pointer is what reaches
6027        // them. The frame keeps one whatever the flags asked for, takes its bytes rather than
6028        // living in the red zone, and the address of the growing slot is off the stack pointer as
6029        // it stands after the subtraction rather than off anything the prologue left.
6030        let text = mir::print_func(&out, &names, &REGS);
6031        assert!(frame.grows());
6032        assert!(frame.frame_pointer());
6033        assert!(frame.size() > 0, "{text}");
6034        assert!(text.contains("x64.lea_64 [$rbp"), "{text}");
6035        assert!(text.contains("$rsp = x64.sub_rr_64 $rsp"), "{text}");
6036        assert!(text.contains("x64.lea_64 [$rsp]"), "{text}");
6037    }
6038
6039    #[test]
6040    fn an_address_is_read_written_and_added_to_like_the_integer_it_is() {
6041        let (mut names, mut source, block, args) = blank(&[Type::PTR, Type::int(64)]);
6042        let mut build = Builder::new(&mut source, block);
6043        let stepped = build.func().push_values(&[args[0], args[1]]);
6044        let next =
6045            build.value(InstData { args: stepped, ..InstData::new(Opcode::PtrAdd) }, Type::PTR);
6046        let loaded = build.load(Type::int(32), next, plain(), Flags::default());
6047        build.ret(&[loaded]);
6048
6049        // `int f(int *p, long i) { return *(int *)((char *)p + i); }`. Nothing about this is new
6050        // in the rule set, which is the point: the two addresses arrive in registers because an
6051        // address is an integer as wide as one, and the arithmetic on them is the add it always
6052        // was, so every rule written about an add reaches it.
6053        //
6054        // The add stays its own instruction rather than folding into the address the load reads
6055        // from. Two registers with no scale on either is the one addressing mode the rules have no
6056        // load through, because the folds that exist are the displacement one and the scaled ones,
6057        // and this is neither. That is a peephole worth having and not a thing this changes.
6058        assert_eq!(
6059            lower(&mut names, &source),
6060            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_64\n    \
6061             %1:gpr($rsi) = x64.arg_val_64\n    %2:gpr(reuse 1) = x64.add_rr_64 %0, %1\n    \
6062             %3:gpr = x64.mov_rm_32 [%2]\n    x64.ret_val_32 %3($rax)\n}\n"
6063        );
6064    }
6065
6066    /// The address of a file scope name, which is what every use of a global and every string
6067    /// literal starts from.
6068    fn address_of(source: &mut Func, block: Block, names: &mut Interner, name: &str) -> Value {
6069        let symbol = names.intern(name);
6070        let mut build = Builder::new(source, block);
6071        build.value(
6072            InstData { extra: Extra::Symbol(symbol), ..InstData::new(Opcode::GlobalAddr) },
6073            Type::PTR,
6074        )
6075    }
6076
6077    #[test]
6078    fn the_address_of_a_name_is_one_instruction_carrying_the_name() {
6079        let (mut names, mut source, block, _) = blank(&[]);
6080        let counter = address_of(&mut source, block, &mut names, "counter");
6081        let mut build = Builder::new(&mut source, block);
6082        let loaded = build.load(Type::int(32), counter, plain(), Flags::default());
6083        build.ret(&[loaded]);
6084
6085        // `extern int counter; int f(void) { return counter; }`. The address is an addressing mode
6086        // that names no register and carries the symbol, which is what the assembler writes
6087        // relative to `%rip` and what the object writer leaves a relocation for.
6088        assert_eq!(
6089            lower(&mut names, &source),
6090            "mfunc @f {\nblock0:\n    %0:gpr = x64.lea_64 [@counter]\n    \
6091             %1:gpr = x64.mov_rm_32 [%0]\n    x64.ret_val_32 %1($rax)\n}\n"
6092        );
6093    }
6094
6095    #[test]
6096    fn the_address_of_a_name_outside_the_file_is_read_out_of_the_offset_table() {
6097        let (mut names, mut source, block, _) = blank(&[]);
6098        let away = address_of(&mut source, block, &mut names, "away");
6099        Builder::new(&mut source, block).ret(&[away]);
6100        let elsewhere: Elsewhere = [names.intern("away")].into_iter().collect();
6101
6102        // `extern void away(void); void *f(void) { return away; }`. A load and not an address
6103        // computation, because the distance from here to a name a shared library may be the one
6104        // that defines is not a number any link can work out, and the slot the linker fills in is
6105        // in this program and so is a distance it has.
6106        let out =
6107            func(&source, &mut names, &SYSV, &elsewhere).expect("every instruction has a rule");
6108        assert_eq!(
6109            mir::print_func(&out.func, &names, &REGS),
6110            "mfunc @f {\nblock0:\n    %0:gpr = x64.mov_rm_64 [got @away]\n    \
6111             x64.ret_val_64 %0($rax)\n}\n"
6112        );
6113    }
6114
6115    #[test]
6116    fn the_address_of_a_thread_local_is_an_offset_out_of_the_table_plus_where_this_thread_starts() {
6117        let (mut names, mut source, block, _) = blank(&[]);
6118        let own = address_of(&mut source, block, &mut names, "own");
6119        Builder::new(&mut source, block).ret(&[own]);
6120        let elsewhere = Elsewhere::default().with_threads([names.intern("own")]);
6121
6122        // `extern _Thread_local int own; void *f(void) { return &own; }`. Three instructions where
6123        // the two cases above are one, because there is no address to load or to work out: the
6124        // slot holds how far into a thread's block the variable sits, `%fs:0` is where this
6125        // thread's block starts, and the sum of the two is this thread's copy.
6126        let out =
6127            func(&source, &mut names, &SYSV, &elsewhere).expect("every instruction has a rule");
6128        assert_eq!(
6129            mir::print_func(&out.func, &names, &REGS),
6130            "mfunc @f {\nblock0:\n    %0:gpr = x64.mov_rm_64 [thread @own]\n    \
6131             %1:gpr = x64.mov_rm_64 [fs:0]\n    %2:gpr(reuse 1) = x64.add_rr_64 %0, %1\n    \
6132             x64.ret_val_64 %2($rax)\n}\n"
6133        );
6134    }
6135
6136    /// The same load with nothing added to it, which is the whole of `__builtin_thread_pointer`.
6137    #[test]
6138    fn the_start_of_this_thread_s_own_storage_is_the_one_load_and_no_arithmetic() {
6139        let (mut names, mut source, block, _) = blank(&[]);
6140        let here =
6141            Builder::new(&mut source, block).value(InstData::new(Opcode::ThreadPointer), Type::PTR);
6142        Builder::new(&mut source, block).ret(&[here]);
6143
6144        let out = func(&source, &mut names, &SYSV, &Elsewhere::default())
6145            .expect("every instruction has a rule");
6146        assert_eq!(
6147            mir::print_func(&out.func, &names, &REGS),
6148            "mfunc @f {\nblock0:\n    %0:gpr = x64.mov_rm_64 [fs:0]\n    \
6149             x64.ret_val_64 %0($rax)\n}\n"
6150        );
6151    }
6152
6153    /// One `asm` statement, with its template and its constraint list written as a program does.
6154    fn assembly(
6155        source: &mut Func,
6156        block: Block,
6157        names: &mut Interner,
6158        template: &str,
6159        constraints: &str,
6160        args: &[Value],
6161        results: &[Type],
6162    ) -> Inst {
6163        clobbering(source, block, names, template, constraints, "memory", args, results)
6164    }
6165
6166    /// The same with a clobber list of its own, for the statements that are about one.
6167    #[allow(clippy::too_many_arguments)]
6168    fn clobbering(
6169        source: &mut Func,
6170        block: Block,
6171        names: &mut Interner,
6172        template: &str,
6173        constraints: &str,
6174        clobbers: &str,
6175        args: &[Value],
6176        results: &[Type],
6177    ) -> Inst {
6178        let info = AsmInfo {
6179            template: names.intern(template),
6180            constraints: names.intern(constraints),
6181            clobbers: names.intern(clobbers),
6182            targets: rucc_ir::BlockCallList::EMPTY,
6183        };
6184        Builder::new(source, block).inline_asm(info, args, results, Flags::VOLATILE)
6185    }
6186
6187    /// What a program asking the processor what it can do writes, which is the instruction whose
6188    /// every operand is a register its text does not name.
6189    #[test]
6190    fn a_template_whose_registers_are_named_by_the_constraints_places_them_from_the_letters() {
6191        let u32 = Type::int(32);
6192        let (mut names, mut source, block, _) = blank(&[]);
6193        let zero = Builder::new(&mut source, block).iconst(u32, 0);
6194        let out = clobbering(
6195            &mut source,
6196            block,
6197            &mut names,
6198            "cpuid",
6199            "=a,a",
6200            "ebx,ecx,edx",
6201            &[zero],
6202            &[u32],
6203        );
6204        let produced = source[out].results().next().expect("one result");
6205        Builder::new(&mut source, block).ret(&[produced]);
6206
6207        // `asm ("cpuid" : "=a" (n) : "a" (0) : "ebx", "ecx", "edx")`, which is the first thing
6208        // every program that has a faster path on some machines writes. Four registers written and
6209        // two read, none of them in the template, all of them out of the description, and the two
6210        // that the letters named are the statement's own. The subleaf is a zero because the
6211        // instruction reads `ecx` and the program said nothing about what is in it. The three
6212        // clobbers are gone because `cpuid` writes those three anyway, and saying it twice is one
6213        // register with two definitions.
6214        assert_eq!(
6215            lower(&mut names, &source),
6216            "mfunc @f {\nblock0:\n    %0:gpr = x64.mov_ri_32 0\n    \
6217             %1:gpr = x64.mov_ri_64 0\n    \
6218             %2:gpr($rax), %3:gpr($rbx), %4:gpr($rcx), %5:gpr($rdx) = x64.cpuid %0($rax), \
6219             %1($rcx)\n    x64.ret_val_32 %2($rax)\n}\n"
6220        );
6221    }
6222
6223    /// An operand the program pinned, by declaring the object it comes from `register long x asm
6224    /// ("r12")`. The letter on its own leaves the allocator to pick, and a template that reads the
6225    /// register by name needs the two to be the same register, so the brace is what ties them
6226    /// together. That is the one use of a local register variable the GNU manual calls reliable,
6227    /// and it is what tcc's `tests/tcctest.c` counts on.
6228    #[test]
6229    fn an_operand_the_program_pinned_is_placed_in_the_register_it_named() {
6230        let u64 = Type::int(64);
6231        let (mut names, mut source, block, _) = blank(&[]);
6232        let out =
6233            assembly(&mut source, block, &mut names, "mov $0x4542, %r12", "=r{r12}", &[], &[u64]);
6234        let produced = source[out].results().next().expect("one result");
6235        Builder::new(&mut source, block).ret(&[produced]);
6236
6237        // The template is one instruction the table already has, so it lowers to that instruction
6238        // rather than to text nobody read, and the register it names is the statement's own output
6239        // because the brace put the output there. Without the brace the letter would have let the
6240        // allocator pick, the two `%r12` would have been different registers, and the program would
6241        // have come back with whatever was in the one it picked.
6242        assert_eq!(
6243            lower(&mut names, &source),
6244            "mfunc @f {\nblock0:\n    %0:gpr($r12) = x64.mov_ri_64 17730\n    \
6245             x64.ret_val_64 %0($rax)\n}\n"
6246        );
6247    }
6248
6249    /// A clobber the instruction does not write itself, which is the case the list is there for.
6250    /// It goes on as a definition of the register, in among the other definitions, because that is
6251    /// the whole of how a machine function says a register is not worth anything after this.
6252    #[test]
6253    fn a_clobber_the_instruction_does_not_write_itself_is_a_definition_of_that_register() {
6254        let (mut names, mut source, block, _) = blank(&[]);
6255        clobbering(&mut source, block, &mut names, "pause", "", "rsi,cc,memory", &[], &[]);
6256        Builder::new(&mut source, block).ret(&[]);
6257
6258        assert_eq!(lower(&mut names, &source), "mfunc @f {\nblock0:\n    $rsi = x64.pause\n}\n");
6259    }
6260
6261    /// A clobber naming something this has no register for. Refused rather than dropped, since the
6262    /// list is the program saying which registers it may not leave anything in, and an entry
6263    /// nobody read is a register something may still be left in.
6264    #[test]
6265    fn a_clobber_this_has_no_register_for_is_refused() {
6266        let (mut names, mut source, block, _) = blank(&[]);
6267        clobbering(&mut source, block, &mut names, "pause", "", "zmm0", &[], &[]);
6268        Builder::new(&mut source, block).ret(&[]);
6269
6270        let failed = func(&source, &mut names, &SYSV, &Elsewhere::default())
6271            .expect_err("there is no such register here");
6272        assert_eq!(
6273            failed.to_string(),
6274            "this `asm` says it destroys a register this has no name for"
6275        );
6276    }
6277
6278    #[test]
6279    fn an_asm_with_an_empty_template_and_no_operands_is_no_instructions() {
6280        let (mut names, mut source, block, _) = blank(&[]);
6281        assembly(&mut source, block, &mut names, "", "", &[], &[]);
6282        Builder::new(&mut source, block).ret(&[]);
6283
6284        // `asm volatile ("" : : : "memory")`, which is a barrier and nothing else. The barrier was
6285        // spent on the optimizer, which has finished by now, so what is left is nothing.
6286        assert_eq!(lower(&mut names, &source), "mfunc @f {\nblock0:\n}\n");
6287    }
6288
6289    #[test]
6290    fn an_output_an_input_is_tied_to_is_the_register_that_input_arrived_in() {
6291        let i32 = Type::int(32);
6292        let (mut names, mut source, block, args) = blank(&[i32]);
6293        let out = assembly(&mut source, block, &mut names, "", "=r,0", &args, &[i32]);
6294        let produced = source[out].results().next().expect("one result");
6295        Builder::new(&mut source, block).ret(&[produced]);
6296
6297        // `asm ("" : "=r" (x) : "0" (x))`, which is how a program stops the optimizer following a
6298        // value without changing it. The two share a place and the template writes nothing over
6299        // it, so the value comes back out of the register it went in.
6300        assert_eq!(
6301            lower(&mut names, &source),
6302            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_32\n    \
6303             x64.ret_val_32 %0($rax)\n}\n"
6304        );
6305    }
6306
6307    #[test]
6308    fn an_output_written_plus_is_the_same_rename() {
6309        let i32 = Type::int(32);
6310        let (mut names, mut source, block, args) = blank(&[i32]);
6311        let out = assembly(&mut source, block, &mut names, "", "+r", &args, &[i32]);
6312        let produced = source[out].results().next().expect("one result");
6313        Builder::new(&mut source, block).ret(&[produced]);
6314
6315        // `asm ("" : "+r" (x))`, which says the same thing in one operand instead of two.
6316        assert_eq!(
6317            lower(&mut names, &source),
6318            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_32\n    \
6319             x64.ret_val_32 %0($rax)\n}\n"
6320        );
6321    }
6322
6323    #[test]
6324    fn an_output_nothing_is_tied_to_is_a_zero() {
6325        let i32 = Type::int(32);
6326        let (mut names, mut source, block, _) = blank(&[]);
6327        let out = assembly(&mut source, block, &mut names, "", "=r", &[], &[i32]);
6328        let produced = source[out].results().next().expect("one result");
6329        Builder::new(&mut source, block).ret(&[produced]);
6330
6331        // `asm ("" : "=r" (y))`, whose answer is whatever the assembly left in the register, and
6332        // an empty template leaves nothing. A definite value rather than a register nothing wrote,
6333        // because the allocator is owed a definition before the use however little the program is.
6334        assert_eq!(
6335            lower(&mut names, &source),
6336            "mfunc @f {\nblock0:\n    %0:gpr = x64.mov_ri_32 0\n    x64.ret_val_32 %0($rax)\n}\n"
6337        );
6338    }
6339
6340    #[test]
6341    fn a_template_that_is_one_instruction_becomes_that_instruction() {
6342        let (mut names, mut source, block, _) = blank(&[]);
6343        assembly(&mut source, block, &mut names, "pause", "", &[], &[]);
6344        Builder::new(&mut source, block).ret(&[]);
6345
6346        // `asm volatile ("pause")`, which is what every spin lock in every allocator writes. One
6347        // instruction, no operands, and nothing between the template and the machine but the table
6348        // that already says what a `pause` is.
6349        assert_eq!(lower(&mut names, &source), "mfunc @f {\nblock0:\n    x64.pause\n}\n");
6350    }
6351
6352    #[test]
6353    fn a_template_that_reads_a_segment_becomes_the_load_it_already_was() {
6354        let i64 = Type::int(64);
6355        let (mut names, mut source, block, _) = blank(&[]);
6356        let out = assembly(&mut source, block, &mut names, "movq %%fs:0, %0", "=r", &[], &[i64]);
6357        let produced = source[out].results().next().expect("one result");
6358        Builder::new(&mut source, block).ret(&[produced]);
6359
6360        // `asm ("movq %%fs:0, %0" : "=r" (tid))`, which is how a program finds the block its own
6361        // thread owns. The same instruction `crate::lower` already writes for a thread-local
6362        // variable, reached this time because a program wrote it out by hand.
6363        assert_eq!(
6364            lower(&mut names, &source),
6365            "mfunc @f {\nblock0:\n    %0:gpr = x64.mov_rm_64 [fs:0]\n    \
6366             x64.ret_val_64 %0($rax)\n}\n"
6367        );
6368    }
6369
6370    #[test]
6371    fn a_template_naming_an_instruction_this_machine_has_not_got_is_refused() {
6372        let (mut names, mut source, block, _) = blank(&[]);
6373        assembly(&mut source, block, &mut names, "hcf", "", &[], &[]);
6374        Builder::new(&mut source, block).ret(&[]);
6375
6376        let failed = func(&source, &mut names, &SYSV, &Elsewhere::default())
6377            .expect_err("there is no such instruction");
6378        assert_eq!(
6379            failed.to_string(),
6380            "this `asm` has instructions in its template, which nothing here assembles"
6381        );
6382    }
6383
6384    /// A register the template named is placed as itself, fixed to the register the program wrote
6385    /// down. A register a constraint letter names is a different thing and is placed too, which the
6386    /// test above is about: there the statement said which of its own operands is in the register,
6387    /// and a name in the middle of a template says the register and nothing about any operand.
6388    #[test]
6389    fn a_template_naming_a_register_gets_that_register() {
6390        let i64 = Type::int(64);
6391        let (mut names, mut source, block, _) = blank(&[]);
6392        let out = assembly(&mut source, block, &mut names, "movq %%rax, %0", "=r", &[], &[i64]);
6393        let produced = source[out].results().next().expect("one result");
6394        Builder::new(&mut source, block).ret(&[produced]);
6395
6396        // `asm ("movq %%rax, %0" : "=r" (x))`, which is a program reading whatever is in `%rax`.
6397        // The source is the register itself and the destination is one the allocator picks.
6398        assert_eq!(
6399            lower(&mut names, &source),
6400            "mfunc @f {\nblock0:\n    %0:gpr = x64.mov_rr_64 $rax($rax)\n    \
6401             x64.ret_val_64 %0($rax)\n}\n"
6402        );
6403    }
6404
6405    /// The half of the same thing every register saving template needs. micropython writes the
6406    /// callee-saved registers into a buffer one `movq %%r12, 48(%%rdi)` at a time, and both halves
6407    /// of that line are a register the template named: the one being stored and the one the address
6408    /// is counted from.
6409    #[test]
6410    fn a_template_counting_an_address_from_a_register_it_named_gets_that_register() {
6411        let (mut names, mut source, block, _) = blank(&[]);
6412        assembly(&mut source, block, &mut names, "movq %%r12, 48(%%rdi)", "", &[], &[]);
6413        Builder::new(&mut source, block).ret(&[]);
6414
6415        assert_eq!(
6416            lower(&mut names, &source),
6417            "mfunc @f {\nblock0:\n    x64.mov_mr_64 $r12($r12), [$rdi + 48]\n}\n"
6418        );
6419    }
6420
6421    /// A local kept in a named register, which is the same register named as itself and reached
6422    /// from the other side. micropython's collector writes six of these and reads them with
6423    /// ordinary C rather than with a template.
6424    #[test]
6425    fn a_local_kept_in_a_named_register_is_one_move_out_of_it() {
6426        let (mut names, mut source, block, _) = blank(&[]);
6427        let held = names.intern("rbx");
6428        let value = Builder::new(&mut source, block).value(
6429            InstData { extra: Extra::Symbol(held), ..InstData::new(Opcode::RegisterValue) },
6430            Type::int(64),
6431        );
6432        Builder::new(&mut source, block).ret(&[value]);
6433
6434        assert_eq!(
6435            lower(&mut names, &source),
6436            "mfunc @f {\nblock0:\n    %0:gpr = x64.mov_rr_64 $rbx($rbx)\n    \
6437             x64.ret_val_64 %0($rax)\n}\n"
6438        );
6439    }
6440
6441    /// The sigil gcc allows in front of the name is syntax and comes off, and a name that is not
6442    /// a register of this machine is refused in words that say which name it was.
6443    #[test]
6444    fn a_register_name_is_read_with_or_without_its_sigil_and_refused_when_there_is_no_such_one() {
6445        for written in ["%r12", "r12"] {
6446            let (mut names, mut source, block, _) = blank(&[]);
6447            let held = names.intern(written);
6448            let value = Builder::new(&mut source, block).value(
6449                InstData { extra: Extra::Symbol(held), ..InstData::new(Opcode::RegisterValue) },
6450                Type::int(64),
6451            );
6452            Builder::new(&mut source, block).ret(&[value]);
6453            assert!(lower(&mut names, &source).contains("$r12($r12)"), "{written} is not read");
6454        }
6455
6456        let (mut names, mut source, block, _) = blank(&[]);
6457        let held = names.intern("nowhere");
6458        let value = Builder::new(&mut source, block).value(
6459            InstData { extra: Extra::Symbol(held), ..InstData::new(Opcode::RegisterValue) },
6460            Type::int(64),
6461        );
6462        Builder::new(&mut source, block).ret(&[value]);
6463
6464        let failed = func(&source, &mut names, &SYSV, &Elsewhere::default())
6465            .expect_err("there is no such register");
6466        assert_eq!(
6467            failed.to_string(),
6468            "this object is kept in `nowhere`, which is not a register this machine has"
6469        );
6470    }
6471
6472    #[test]
6473    fn a_constraint_list_that_does_not_describe_the_operands_is_refused() {
6474        let i32 = Type::int(32);
6475        let (mut names, mut source, block, args) = blank(&[i32]);
6476        assembly(&mut source, block, &mut names, "", "=r", &args, &[]);
6477        Builder::new(&mut source, block).ret(&[]);
6478
6479        // An output with no result to be, which is what the front end never writes and what a
6480        // hand written module can. Refused rather than placed by a guess.
6481        let failed = func(&source, &mut names, &SYSV, &Elsewhere::default())
6482            .expect_err("the list and the instruction disagree");
6483        assert_eq!(failed.to_string(), "this `asm` has an operand this cannot place");
6484    }
6485
6486    /// A cast between a pointer and an integer, at whatever width the result is asked for.
6487    fn cast(source: &mut Func, block: Block, opcode: Opcode, from: Value, to: Type) -> Value {
6488        let mut build = Builder::new(source, block);
6489        let args = build.func().push_values(&[from]);
6490        build.value(InstData { args, ..InstData::new(opcode) }, to)
6491    }
6492
6493    #[test]
6494    fn a_cast_between_a_pointer_and_an_integer_as_wide_is_no_instruction_at_all() {
6495        let (mut names, mut source, block, args) = blank(&[Type::PTR]);
6496        let number = cast(&mut source, block, Opcode::PtrToInt, args[0], Type::int(64));
6497        Builder::new(&mut source, block).ret(&[number]);
6498
6499        // `long f(void *p) { return (long)p; }`. An address on this machine is an integer as wide
6500        // as the machine addresses, so the cast changes what the type system calls the value and
6501        // changes nothing about the value, and the register holding it is the one that held it.
6502        assert_eq!(
6503            lower(&mut names, &source),
6504            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_64\n    \
6505             x64.ret_val_64 %0($rax)\n}\n"
6506        );
6507    }
6508
6509    #[test]
6510    fn a_null_pointer_is_a_constant_that_reaches_a_register_before_anything_reads_it() {
6511        let (mut names, mut source, block, _) = blank(&[]);
6512        let mut build = Builder::new(&mut source, block);
6513        let zero = build.iconst(Type::int(64), 0);
6514        let null = cast(&mut source, block, Opcode::IntToPtr, zero, Type::PTR);
6515        Builder::new(&mut source, block).ret(&[null]);
6516
6517        // `void *f(void) { return 0; }`. The cast is nothing, and reading its operand is what
6518        // writes the zero down: a constant is materialized where it is wanted rather than where
6519        // the IR defined it, and without the read there would be no instruction at all.
6520        assert_eq!(
6521            lower(&mut names, &source),
6522            "mfunc @f {\nblock0:\n    %0:gpr = x64.mov_ri_64 0\n    x64.ret_val_64 %0($rax)\n}\n"
6523        );
6524    }
6525
6526    #[test]
6527    fn the_five_linkages_the_ir_has_narrow_to_the_three_an_object_file_can_say() {
6528        let readings = [
6529            (Linkage::External, mir::Binding::Global),
6530            (Linkage::Common, mir::Binding::Global),
6531            (Linkage::Internal, mir::Binding::Local),
6532            (Linkage::Weak, mir::Binding::Weak),
6533            (Linkage::LinkOnce, mir::Binding::Weak),
6534        ];
6535        for (linkage, wanted) in readings {
6536            let (mut names, mut source, block, _) = blank(&[]);
6537            source.linkage = linkage;
6538            Builder::new(&mut source, block).ret(&[]);
6539            let out = func(&source, &mut names, &SYSV, &Elsewhere::default()).expect("a return");
6540            // The narrowing is done here rather than where the object is written, because a
6541            // machine function is all the assembler and the writer are ever handed.
6542            assert_eq!(out.func.binding, wanted, "{linkage:?}");
6543        }
6544    }
6545
6546    /// The visibility makes the same trip and is not narrowed on the way, because ELF says all
6547    /// three of them.
6548    ///
6549    /// Here for the reason the linkage above is here. A machine function is the whole of what the
6550    /// assembler and the object writer are handed, so a fact about the symbol that does not get
6551    /// onto one is a fact that is gone by the time anything could write it down, and the way that
6552    /// shows up is a shared library exporting the wrong set of names with nothing said anywhere.
6553    #[test]
6554    fn the_visibility_survives_the_trip_from_the_ir_to_a_machine_function() {
6555        let readings = [
6556            (Visibility::Default, mir::Visibility::Default),
6557            (Visibility::Hidden, mir::Visibility::Hidden),
6558            (Visibility::Protected, mir::Visibility::Protected),
6559        ];
6560        for (visibility, wanted) in readings {
6561            let (mut names, mut source, block, _) = blank(&[]);
6562            source.visibility = visibility;
6563            Builder::new(&mut source, block).ret(&[]);
6564            let out = func(&source, &mut names, &SYSV, &Elsewhere::default()).expect("a return");
6565            assert_eq!(out.func.visibility, wanted, "{visibility:?}");
6566        }
6567    }
6568
6569    #[test]
6570    fn a_cast_between_a_pointer_and_a_narrower_integer_is_reported() {
6571        let (mut names, mut source, block, args) = blank(&[Type::PTR]);
6572        let number = cast(&mut source, block, Opcode::PtrToInt, args[0], Type::int(32));
6573        Builder::new(&mut source, block).ret(&[number]);
6574
6575        // The front end never writes one: it casts at the address width and truncates or extends
6576        // around it, so both of those are the rules they always were. IR from somewhere else that
6577        // does write one is refused rather than compiled to a move that keeps the high half.
6578        let failed = func(&source, &mut names, &SYSV, &Elsewhere::default())
6579            .expect_err("no rule narrows an address");
6580        assert_eq!(failed.to_string(), "no rule lowers a `ptrtoint` producing a `i32`");
6581    }
6582
6583    /// The type this machine has no register for.
6584    fn long_double() -> Type {
6585        Type::float(rucc_ir::Float::F80)
6586    }
6587
6588    #[test]
6589    fn a_double_widened_and_narrowed_again_goes_out_through_the_frame_and_back() {
6590        let f64 = Type::float(rucc_ir::Float::F64);
6591        let (mut names, mut source, block, args) = blank(&[f64]);
6592        let wide = cast(&mut source, block, Opcode::FPExt, args[0], long_double());
6593        let back = cast(&mut source, block, Opcode::FPTrunc, wide, f64);
6594        Builder::new(&mut source, block).ret(&[back]);
6595
6596        // `double f(double d) { long double x = d; return x; }`. The x87 reads memory and nothing
6597        // else, so the value is written to the crossing slot, loaded at the format that widens it
6598        // and put in the slot the eighty bit value lives in. Coming back is the same three the
6599        // other way. Both slots are addressed by a `lea` with nothing in it yet, which is what
6600        // every address in a frame looks like here until `finish` has the numbers.
6601        assert_eq!(
6602            lower(&mut names, &source),
6603            "mfunc @f {\nblock0:\n    \
6604             %0:xmm($xmm0) = x64.arg_val_f64\n    \
6605             %1:gpr = x64.lea_64 [$rsp]\n    \
6606             %2:gpr = x64.lea_64 [$rsp]\n    \
6607             x64.movsd_mr %0, [%1]\n    \
6608             x64.fld_l [%1]\n    \
6609             x64.fstp_t [%2]\n    \
6610             %3:gpr = x64.lea_64 [$rsp]\n    \
6611             %4:gpr = x64.lea_64 [$rsp]\n    \
6612             x64.fld_t [%3]\n    \
6613             x64.fstp_l [%4]\n    \
6614             %5:xmm = x64.movsd_rm [%4]\n    \
6615             x64.ret_val_f64 %5($xmm0)\n}\n"
6616        );
6617    }
6618
6619    #[test]
6620    fn a_long_double_has_sixteen_bytes_of_its_own_and_keeps_them() {
6621        let f64 = Type::float(rucc_ir::Float::F64);
6622        let (mut names, mut source, block, args) = blank(&[f64]);
6623        let wide = cast(&mut source, block, Opcode::FPExt, args[0], long_double());
6624        let once = cast(&mut source, block, Opcode::FPTrunc, wide, f64);
6625        let twice = cast(&mut source, block, Opcode::FPTrunc, wide, f64);
6626        let mut build = Builder::new(&mut source, block);
6627        let sum = build.binary(Opcode::FAdd, once, twice, Flags::default());
6628        build.ret(&[sum]);
6629
6630        let out = func(&source, &mut names, &SYSV, &Elsewhere::default())
6631            .expect("every instruction is written");
6632
6633        // Two slots and not four: sixteen bytes for the one eighty bit value, which is what the
6634        // psABI says one takes and is aligned to, and eight for the crossing, which every group
6635        // in the function shares because nothing is ever left in it. The value's slot is its own
6636        // for the whole function, so reading it twice reads the same sixteen bytes.
6637        assert_eq!(
6638            out.stack.locals,
6639            vec![Local { size: 8, align: 8 }, Local { size: 16, align: 16 }]
6640        );
6641    }
6642
6643    #[test]
6644    fn an_integer_becomes_a_long_double_by_being_loaded_as_one() {
6645        let (mut names, mut source, block, args) = blank(&[Type::int(64)]);
6646        let wide = cast(&mut source, block, Opcode::SIToFP, args[0], long_double());
6647        let back =
6648            cast(&mut source, block, Opcode::FPTrunc, wide, Type::float(rucc_ir::Float::F64));
6649        Builder::new(&mut source, block).ret(&[back]);
6650
6651        // `double f(long n) { long double x = n; return x; }`. `fild` is the same push at another
6652        // format, so the conversion is the load and there is no instruction that converts.
6653        let text = lower(&mut names, &source);
6654        assert!(text.contains("x64.mov_mr_64 %0, [%1]"), "{text}");
6655        assert!(text.contains("x64.fild_ll [%1]"), "{text}");
6656    }
6657
6658    #[test]
6659    fn a_long_double_becoming_an_integer_cuts_towards_zero_with_the_control_word() {
6660        let (mut names, mut source, block, args) = blank(&[Type::float(rucc_ir::Float::F64)]);
6661        let wide = cast(&mut source, block, Opcode::FPExt, args[0], long_double());
6662        let whole = cast(&mut source, block, Opcode::FPToSI, wide, Type::int(32));
6663        Builder::new(&mut source, block).ret(&[whole]);
6664
6665        // The one conversion here with no single instruction behind it. C cuts towards zero and
6666        // the unit rounds the way its control word says, so the word is saved, ORed with the two
6667        // bits that mean truncate, loaded, used and put back. Nine instructions for what `fisttp`
6668        // does in one, and `spec/10-backend.md` section 10.8 says why that one is not used.
6669        let text = lower(&mut names, &source);
6670        let group: Vec<&str> = text
6671            .lines()
6672            .map(str::trim)
6673            .filter(|line| line.starts_with("x64.f") || line.contains("_16"))
6674            .collect();
6675        assert_eq!(
6676            group,
6677            [
6678                "x64.fld_l [%1]",
6679                "x64.fstp_t [%2]",
6680                "x64.fnstcw [%5]",
6681                "%6:gpr = x64.mov_rm_16 [%5]",
6682                "%7:gpr(reuse 1) = x64.or_ri_16 %6, 3072",
6683                "x64.mov_mr_16 %7, [%5 + 2]",
6684                "x64.fldcw [%5 + 2]",
6685                "x64.fld_t [%3]",
6686                "x64.fistp_l [%4]",
6687                "x64.fldcw [%5]",
6688            ],
6689            "{text}"
6690        );
6691    }
6692
6693    #[test]
6694    fn a_long_double_is_read_and_written_as_the_bits_it_already_is() {
6695        let (mut names, mut source, block, args) = blank(&[Type::PTR, Type::PTR]);
6696        let mut build = Builder::new(&mut source, block);
6697        let value = build.load(long_double(), args[0], plain(), Flags::default());
6698        build.store(value, args[1], plain(), Flags::default());
6699        build.ret(&[]);
6700
6701        // `void f(long double *a, long double *b) { *b = *a; }`. A copy is a push and a pop at the
6702        // format the value is already in, which neither converts nor looks: a signalling NaN stays
6703        // one and nothing is raised, which is the whole of what makes it a copy.
6704        let text = lower(&mut names, &source);
6705        let group: Vec<&str> =
6706            text.lines().map(str::trim).filter(|line| line.starts_with("x64.f")).collect();
6707        assert_eq!(
6708            group,
6709            ["x64.fld_t [%0]", "x64.fstp_t [%2]", "x64.fld_t [%3]", "x64.fstp_t [%1]"],
6710            "{text}"
6711        );
6712    }
6713
6714    /// Two `long double` values, from two `double` parameters, and the instructions that made
6715    /// them, which every test below this one throws away.
6716    fn two_long_doubles(source: &mut Func, block: Block, args: &[Value]) -> (Value, Value) {
6717        let left = cast(source, block, Opcode::FPExt, args[0], long_double());
6718        let right = cast(source, block, Opcode::FPExt, args[1], long_double());
6719        (left, right)
6720    }
6721
6722    /// The x87 instructions of a function, in order, with everything else dropped.
6723    fn stack_only(text: &str) -> Vec<&str> {
6724        text.lines().map(str::trim).filter(|line| line.contains("x64.f")).collect()
6725    }
6726
6727    /// The two frame slots the last two addresses of a function were taken of, which in a
6728    /// comparison are the two operands in the order they go on the stack.
6729    fn pushed(out: &Lowered) -> Vec<usize> {
6730        let taken: Vec<usize> = out.stack.addresses.iter().map(|&(_, local)| local).collect();
6731        taken[taken.len() - 2..].to_vec()
6732    }
6733
6734    #[test]
6735    fn adding_two_long_doubles_pushes_both_and_leaves_the_answer_in_a_slot() {
6736        let f64 = Type::float(rucc_ir::Float::F64);
6737        let (mut names, mut source, block, args) = blank(&[f64, f64]);
6738        let (left, right) = two_long_doubles(&mut source, block, &args);
6739        let sum =
6740            Builder::new(&mut source, block).binary(Opcode::FAdd, left, right, Flags::default());
6741        let back = cast(&mut source, block, Opcode::FPTrunc, sum, f64);
6742        Builder::new(&mut source, block).ret(&[back]);
6743
6744        // `double f(double a, double b) { return (long double) a + (long double) b; }`. The last
6745        // four lines are the add: both operands pushed, the instruction that names neither of
6746        // them because they are the top two of a stack, and the answer taken off into its slot.
6747        let text = lower(&mut names, &source);
6748        assert_eq!(
6749            stack_only(&text),
6750            [
6751                "x64.fld_l [%2]",
6752                "x64.fstp_t [%3]",
6753                "x64.fld_l [%4]",
6754                "x64.fstp_t [%5]",
6755                "x64.fld_t [%6]",
6756                "x64.fld_t [%7]",
6757                "x64.fadd_p",
6758                "x64.fstp_t [%8]",
6759                "x64.fld_t [%9]",
6760                "x64.fstp_l [%10]",
6761            ],
6762            "{text}"
6763        );
6764    }
6765
6766    #[test]
6767    fn a_subtraction_pushes_the_left_operand_first_and_asks_for_the_att_spelling() {
6768        let f64 = Type::float(rucc_ir::Float::F64);
6769        let (mut names, mut source, block, args) = blank(&[f64, f64]);
6770        let (left, right) = two_long_doubles(&mut source, block, &args);
6771        let less =
6772            Builder::new(&mut source, block).binary(Opcode::FSub, left, right, Flags::default());
6773        let back = cast(&mut source, block, Opcode::FPTrunc, less, f64);
6774        Builder::new(&mut source, block).ret(&[back]);
6775
6776        // The left one goes on first, so it ends up under the right one, and the answer wanted is
6777        // the one below minus the top. In AT&T that is `fsubrp`, since `fsubp` there is `DE E0+i`
6778        // and computes the other one. The `r` says which spelling this is and not which order the
6779        // pushes were in. `crates/rucc/tests/x87.rs` is what says the answer is right, because a
6780        // name is what got this wrong the first time.
6781        let text = lower(&mut names, &source);
6782        assert_eq!(
6783            &stack_only(&text)[4..8],
6784            ["x64.fld_t [%6]", "x64.fld_t [%7]", "x64.fsubr_p", "x64.fstp_t [%8]"],
6785            "{text}"
6786        );
6787    }
6788
6789    #[test]
6790    fn negating_a_long_double_turns_the_sign_over_and_reads_nothing() {
6791        let f64 = Type::float(rucc_ir::Float::F64);
6792        let (mut names, mut source, block, args) = blank(&[f64]);
6793        let wide = cast(&mut source, block, Opcode::FPExt, args[0], long_double());
6794        let flipped = Builder::new(&mut source, block).unary(Opcode::FNeg, wide, long_double());
6795        let back = cast(&mut source, block, Opcode::FPTrunc, flipped, f64);
6796        Builder::new(&mut source, block).ret(&[back]);
6797
6798        // `fchs` and not a subtraction from zero, which would give a different answer at a negative
6799        // zero and would signal at a NaN. It does not read the value as a number at all.
6800        let text = lower(&mut names, &source);
6801        assert_eq!(
6802            &stack_only(&text)[2..5],
6803            ["x64.fld_t [%3]", "x64.fchs", "x64.fstp_t [%4]"],
6804            "{text}"
6805        );
6806    }
6807
6808    #[test]
6809    fn comparing_two_long_doubles_puts_the_left_one_on_top() {
6810        let f64 = Type::float(rucc_ir::Float::F64);
6811        let (mut names, mut source, block, args) = blank(&[f64, f64]);
6812        let (left, right) = two_long_doubles(&mut source, block, &args);
6813        let mut build = Builder::new(&mut source, block);
6814        build.fcmp(FloatPred::Ogt, left, right, Flags::default());
6815        build.ret(&[]);
6816
6817        // `a > b`. `fucomip` asks about the top of the stack against what is under it, so the
6818        // operand the predicate is about has to go on last, which is the other way round from the
6819        // arithmetic above. The pop that clears the loser and the byte that reads the flags are
6820        // both inside the one opcode.
6821        let out = func(&source, &mut names, &SYSV, &Elsewhere::default())
6822            .expect("every instruction is written");
6823        let slots = pushed(&out);
6824        assert_eq!(slots, [2, 1], "the right operand goes on first and the left one on top");
6825        let text = mir::print_func(&out.func, &names, &REGS);
6826        assert_eq!(
6827            &stack_only(&text)[4..],
6828            ["x64.fld_t [%6]", "x64.fld_t [%7]", "%8:gpr = x64.fucomip_set_a"],
6829            "{text}"
6830        );
6831    }
6832
6833    #[test]
6834    fn a_comparison_that_the_machine_has_backwards_swaps_the_two_pushes() {
6835        let f64 = Type::float(rucc_ir::Float::F64);
6836        let (mut names, mut source, block, args) = blank(&[f64, f64]);
6837        let (left, right) = two_long_doubles(&mut source, block, &args);
6838        let mut build = Builder::new(&mut source, block);
6839        build.fcmp(FloatPred::Olt, left, right, Flags::default());
6840        build.ret(&[]);
6841
6842        // `a < b` is `b > a` and this machine has the one condition, so the same opcode runs with
6843        // the operands the other way round. The same trade the vector rules make, and it has to
6844        // be the same one: a `long double` comparison that picked a different condition from the
6845        // `double` comparison of the same two numbers would be wrong at exactly the unordered
6846        // cases the two conditions differ on.
6847        //
6848        // Which slot each push names is the whole of the difference from the test above, and the
6849        // text does not show it, since an address in a frame is a `lea` with nothing in it until
6850        // `finish` has the numbers. So the slots are what is read here.
6851        let out = func(&source, &mut names, &SYSV, &Elsewhere::default())
6852            .expect("every instruction is written");
6853        let slots = pushed(&out);
6854        assert_eq!(slots, [1, 2], "the left operand goes on first and the right one on top");
6855        let text = mir::print_func(&out.func, &names, &REGS);
6856        assert_eq!(
6857            &stack_only(&text)[4..],
6858            ["x64.fld_t [%6]", "x64.fld_t [%7]", "%8:gpr = x64.fucomip_set_a"],
6859            "{text}"
6860        );
6861    }
6862
6863    #[test]
6864    fn an_ordered_equal_needs_a_second_byte_to_put_the_two_conditions_together() {
6865        let f64 = Type::float(rucc_ir::Float::F64);
6866        let (mut names, mut source, block, args) = blank(&[f64, f64]);
6867        let (left, right) = two_long_doubles(&mut source, block, &args);
6868        let mut build = Builder::new(&mut source, block);
6869        build.fcmp(FloatPred::Oeq, left, right, Flags::default());
6870        build.ret(&[]);
6871
6872        // Equal and ordered are two conditions and the flags carry both, so the opcode writes a
6873        // second register as well as the one the value is in and ANDs them together. Said here by
6874        // handing it a spare, since an instruction that wrote a register nothing knew about would
6875        // be an instruction the allocator could put a live value in the way of.
6876        let text = lower(&mut names, &source);
6877        assert!(text.contains("%8:gpr, %9:gpr = x64.fucomip_set_e_and_np"), "{text}");
6878    }
6879
6880    #[test]
6881    fn a_comparison_that_is_never_asked_is_reported() {
6882        let f64 = Type::float(rucc_ir::Float::F64);
6883        let (mut names, mut source, block, args) = blank(&[f64, f64]);
6884        let (left, right) = two_long_doubles(&mut source, block, &args);
6885        let mut build = Builder::new(&mut source, block);
6886        build.fcmp(FloatPred::False, left, right, Flags::default());
6887        build.ret(&[]);
6888
6889        // Always false is a constant and not a comparison, so there is no condition to pick and
6890        // nothing here folds it into one: an instruction that quietly agreed with it would hide
6891        // that the optimizer left a comparison in that it should have taken out.
6892        let failed = func(&source, &mut names, &SYSV, &Elsewhere::default())
6893            .expect_err("no condition is always false");
6894        assert_eq!(failed.to_string(), "no rule lowers a `fcmp` producing a `i1`");
6895    }
6896
6897    #[test]
6898    fn a_long_double_constant_is_the_bits_of_it_put_where_the_value_lives() {
6899        let (mut names, mut source, block, args) = blank(&[Type::PTR]);
6900        let mut build = Builder::new(&mut source, block);
6901        // `1.5L`, which is the leading bit and one more of significand, and an exponent of zero.
6902        let one_and_a_half = build.fconst(long_double(), 0x3fff_c000_0000_0000_0000);
6903        build.store(one_and_a_half, args[0], plain(), Flags::default());
6904        build.ret(&[]);
6905
6906        // No x87 instruction at all. A slot holding one of these is the value, so a constant is
6907        // its ten bytes written where the value lives, and whatever reads it does the `fld`.
6908        let text = lower(&mut names, &source);
6909        assert!(text.contains("x64.mov_ri_64 -4611686018427387904"), "{text}");
6910        assert!(text.contains("x64.mov_ri_16 16383"), "{text}");
6911        assert!(text.contains("x64.mov_mr_16 %3, [%1 + 8]"), "{text}");
6912        // The six bytes above the ten are the padding that makes the type sixteen wide, and they
6913        // are unspecified rather than zero, so nothing writes them.
6914        assert_eq!(text.matches("x64.mov_mr").count(), 2, "{text}");
6915    }
6916
6917    #[test]
6918    fn a_negative_long_double_constant_keeps_the_bit_above_its_exponent() {
6919        let (mut names, mut source, block, args) = blank(&[Type::PTR]);
6920        let mut build = Builder::new(&mut source, block);
6921        let minus = build.fconst(long_double(), 0xbfff_c000_0000_0000_0000);
6922        build.store(minus, args[0], plain(), Flags::default());
6923        build.ret(&[]);
6924
6925        // `-1.5L`. The sign is the top bit of the two byte half, so the immediate that half is put
6926        // in a register with is above the signed range of sixteen bits and has to stay there: read
6927        // as a number it would be negative, and it is not a number, it is two bytes.
6928        let text = lower(&mut names, &source);
6929        assert!(text.contains("x64.mov_ri_16 49151"), "{text}");
6930    }
6931
6932    #[test]
6933    fn a_long_double_crosses_an_edge_as_an_address_and_is_copied_where_it_lands() {
6934        let (mut names, mut source, block, args) = blank(&[Type::float(rucc_ir::Float::F64)]);
6935        let wide = cast(&mut source, block, Opcode::FPExt, args[0], long_double());
6936        let next = source.create_block();
6937        let param = source.append_param(next, long_double());
6938        Builder::new(&mut source, block).jump(next, &[wide]);
6939        Builder::new(&mut source, next).ret(&[param]);
6940
6941        // What the edge carries is the address of the slot the value is already in, which is an
6942        // ordinary register the allocator has an opinion about. The block on the other side copies
6943        // the sixteen bytes into a slot of its own before anything reads them, so a second edge
6944        // handing over a second address would still leave one place for a reader to look.
6945        let text = lower(&mut names, &source);
6946        let second: Vec<&str> = text
6947            .lines()
6948            .skip_while(|line| !line.starts_with("block1"))
6949            .skip(1)
6950            .take(3)
6951            .map(str::trim)
6952            .collect();
6953        assert_eq!(
6954            second,
6955            ["x64.fld_t [%4]", "%5:gpr = x64.lea_64 [$rsp]", "x64.fstp_t [%5]"],
6956            "{text}"
6957        );
6958    }
6959
6960    #[test]
6961    fn more_long_doubles_at_a_block_than_the_stack_is_deep_are_reported() {
6962        let f64 = Type::float(rucc_ir::Float::F64);
6963        let (mut names, mut source, block, args) = blank(&[f64]);
6964        let wide = cast(&mut source, block, Opcode::FPExt, args[0], long_double());
6965        let next = source.create_block();
6966        let params: Vec<Value> =
6967            (0..=X87_DEPTH).map(|_| source.append_param(next, long_double())).collect();
6968        let carried: Vec<Value> = params.iter().map(|_| wide).collect();
6969        Builder::new(&mut source, block).jump(next, &carried);
6970        Builder::new(&mut source, next).ret(&[params[0]]);
6971
6972        // The copies go through the x87 stack so that every one of them is read before any of them
6973        // is written, which is what makes a block that swaps two of these right. Nine of them do
6974        // not fit on the stack, and copying the ninth before or after the rest is the order that
6975        // could be wrong, so it is refused instead.
6976        let failed = func(&source, &mut names, &SYSV, &Elsewhere::default())
6977            .expect_err("nine do not fit on the stack");
6978        assert_eq!(
6979            failed.to_string(),
6980            "block1 takes 9 parameters of type `f80` and only 8 can cross an edge at once"
6981        );
6982        assert_eq!(failed.inst(), None);
6983    }
6984}