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::{HashMap, 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::template::{template_name, template_reg};
89use rucc_target::{
90    Address, CallRegs, Constraint, OperandDesc, PhysReg, RegClass, Role, VaList, Variadic,
91};
92use rucc_target::{aarch64, x86_64};
93
94use crate::abi::{self, Missing, Refused};
95use crate::coverage::Fired;
96use crate::elsewhere::Elsewhere;
97use crate::frame::{Layout, Local};
98use crate::select::{Match, Piece, Pointer, Reach, Rule, Selector};
99use crate::term::{MAX_ARGS, PLAIN, Plan, Shown, Term, Terms};
100use crate::varargs;
101
102/// The instruction a template's `jmp` to a name outside it becomes.
103///
104/// Not in [`x86_64::FRAME`] with the other opcodes this file names, because a frame never writes
105/// one: the only function it appears in has no prologue and no epilogue for the frame to write
106/// anything into.
107/// See [`x86_64::Step::Away`].
108const AWAY: &str = "jmp_away";
109
110/// How wide an address is on this target, which is the width a cast between a pointer and an
111/// integer has to be at for the cast to be nothing.
112const ADDRESS_BITS: u32 = 64;
113
114/// How much of a register an operand of an `asm` statement fills, which is the width of its type
115/// with two exceptions. A pointer is an address, and a truth value is the byte it is stored in: a
116/// program that writes `sete %0` into a `_Bool` is asking for exactly that byte, which is what tcc's
117/// own test of the width of one checks.
118fn held_bits(ty: Type) -> u32 {
119    if ty.is_ptr() {
120        ADDRESS_BITS
121    } else if ty.bits() == 1 {
122        8
123    } else {
124        ty.bits()
125    }
126}
127
128/// How many bytes a `long double` takes in memory, and what it is aligned to, which are the same
129/// number and are both more than the ten bytes that mean anything.
130///
131/// The psABI's answer rather than a choice here. `sizeof (long double)` is sixteen on this
132/// machine, so an array of them is laid out this way whatever a slot holding one does, and a slot
133/// that agreed with the array is one fewer thing to get wrong.
134const X87_BYTES: u32 = 16;
135
136/// How many values the x87 stack holds at once.
137///
138/// Eight, which is the machine's number rather than a choice here, and it matters in one place:
139/// the parameters of a block are copied through the stack so that they all move at once, and a
140/// block with more of them than this has nowhere to put the ninth.
141const X87_DEPTH: usize = 8;
142
143/// How far into the buffer of a `__builtin_setjmp` each of the four words it writes is.
144///
145/// The first three are gcc's, measured against gcc 16.2.0 on x86-64 at `-O0`: the frame pointer,
146/// the address control comes back to, and the stack pointer, in that order. The fourth is this
147/// compiler's own. gcc has no word for the answer because it writes a second block that sets the
148/// answer to one and is arrived at from the restore, and this writes the answer through memory
149/// instead, for the reason [`Lowering::saves_place`] gives.
150///
151/// None of the four is an interface. The buffer is the program's memory and its five words are
152/// the front end's promise about how much of it there is, but nothing except the matching restore
153/// ever reads a word of it, and a buffer written by one compiler was never going to be one another
154/// compiler could come back through.
155const JUMP_FRAME: i32 = 0;
156
157/// Where the address control comes back to is. See [`JUMP_FRAME`].
158const JUMP_PC: i32 = 8;
159
160/// Where the stack pointer is. See [`JUMP_FRAME`].
161const JUMP_STACK: i32 = 16;
162
163/// Where the address of the word the answer arrives in is. See [`JUMP_FRAME`].
164const JUMP_ANSWER: i32 = 24;
165
166/// How many bytes the word a `__builtin_setjmp` answers with takes in the frame, and what it is
167/// aligned to, which are the same number because it is one machine word.
168const JUMP_WORD: u32 = 8;
169
170/// How many registers the restore needs to hold things in while it puts the frame back.
171///
172/// Four, and every one of them is a register nothing else in the function may be in, which is why
173/// they are counted here rather than asked for one at a time. See [`Lowering::comes_back`].
174const JUMP_REGS: usize = 4;
175
176/// How many bytes a value passes through on its way between a register and the x87 stack.
177///
178/// Eight, because the widest thing that crosses is a `double` or a sixty four bit integer, and
179/// nothing crosses at eighty bits: a value that wide is already in the frame and the stack reaches
180/// it where it is.
181const X87_CROSSING: u32 = 8;
182
183/// Where the rounding field of the x87 control word is and what it has to be set to for the unit
184/// to cut towards zero, which is the one rounding C asks for that the unit does not do by default.
185///
186/// Both bits on is truncate. The field is ORed into the word that was already there rather than
187/// written over it, so the precision control and the exception masks somebody else set stay set.
188const X87_TRUNCATE: i64 = 0x0c00;
189
190/// Whether a type is the one this machine has no register for.
191///
192/// Only the eighty bit float is, and that is a fact about x86-64 rather than about floats: every
193/// other scalar the front end produces is in a general purpose register or a vector one, and this
194/// one is on the x87 stack while it is being worked on and in memory the rest of the time. So it
195/// has no place in [`Lowering::class_of`] and no name in [`crate::term`], and every instruction
196/// that touches one is written out by hand in this file.
197fn on_x87(ty: Type) -> bool {
198    ty.is_scalar() && ty.is_float() && ty.bits() == 80
199}
200
201/// Where one operand of an assembly statement is, on each side of the assembly.
202///
203/// Two registers rather than one, because an operand written `+` is a value that arrives and a
204/// value that leaves and those are two values. The machine IR has one definition per register by
205/// construction, so an instruction of the template that reads the operand and writes it has to name
206/// a different register in each place, and what makes the two one register in the end is the
207/// [`Constraint::Reuse`] the instruction's description carries: the allocator reads it, gives both
208/// the same physical register, and copies the incoming value somewhere first when something else is
209/// still using it.
210///
211/// Most operands have one of the two. An input has only a place it is read from and an output
212/// written `=` has only a place it is written to, and asking either of them for the other is an
213/// operand read where the opcode writes or written where it reads, which [`Lowering::placed`]
214/// refuses.
215#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
216struct Place {
217    /// The register the value arrives in, for an operand something reads.
218    read: Option<mir::Reg>,
219    /// The register the value leaves in, for an operand something writes.
220    write: Option<mir::Reg>,
221}
222
223/// Whether that operand of the statement is one the assembly may read, and so where a read of it
224/// gets its value from.
225///
226/// [`bound`] asks this question of an operand a constraint letter named and this asks it of one the
227/// template numbered, which is the same question twice because a two-address instruction reaches
228/// its first source both ways. `mulq %3` reaches `rax` by the letter on the output and libgmp says
229/// what is in it with `"%0"` on an input. `addq %5,%q1` reaches its first source by numbering the
230/// output, and libgmp says what is in it with `"0"` on an input in the same way.
231///
232/// So an output written `=` has no value of its own and is still readable when an input is tied to
233/// it, and the value the read wants is that input's. An output written `+` carries its own value
234/// and answers with that. An output nothing is tied to answers `None`, which is a program that told
235/// the compiler the assembly only writes the operand while the instruction reads it before it
236/// writes it, and is refused where it is asked.
237fn read_as(list: &[AsmOperand<'_>], index: usize) -> Option<Value> {
238    let operand = list.get(index)?;
239    if operand.value.is_some() {
240        return operand.value;
241    }
242    operand.result?;
243    list.iter().find(|entry| entry.tied == Some(index)).and_then(|entry| entry.value)
244}
245
246/// Which of an assembly statement's operands is in that register, for an instruction that reaches
247/// the register without its text saying so.
248///
249/// The constraint is what says so, and it is the only thing in such a statement that could:
250/// `"=a"` is an output in `rax`, `"c"` is an input in `rcx`, an operand that is a local register
251/// variable is in the register its declaration named, and a register nothing names is a register
252/// nobody has said anything about. So a write looks among the outputs and a read among the inputs,
253/// and an output written `+` answers for either, since it is read before it is written. See
254/// [`pinned`], which is the one question asked of both ways of saying it.
255///
256/// The other way a read of such a register is said is a matching constraint. `"=a"` on an output
257/// and `"0"` on an input is the program saying that one register holds the input on the way in and
258/// the output on the way out, and it is how a statement fills a register the instruction reads and
259/// writes without writing the register down twice. The letter is on the output, which has no value
260/// to read, and the value is on the input, which has no letter, and the answer is the output: its
261/// place is read out of the register the input arrived in, and in a template with a loop in it the
262/// place moves on to wherever the last write left it, which is what a read on the next time round
263/// wants. tcc steps a pointer along a string with `lodsb` and `"=&S"` tied to `"0"`, and a read of
264/// the input would start the string again every time round.
265///
266/// And a read of a register an output alone is in is a read of that output, the same as a read of
267/// an output the template numbered. tcc copies a string with `lodsb` and `stosb` and `"=&a"` on an
268/// output nothing is tied to, and what `stosb` stores is what `lodsb` loaded one line up, which is
269/// the output as the template left it rather than anything the statement handed in.
270///
271/// `None` is a register the instruction uses and the statement put nothing in, which is the usual
272/// answer rather than an unusual one. `cpuid` writes four registers and a program that wanted one
273/// of them names one. See [`Lowering::spare`], which is where that one goes.
274fn bound(list: &[AsmOperand<'_>], reg: PhysReg, role: Role) -> Option<usize> {
275    let output =
276        list.iter().position(|operand| operand.result.is_some() && pinned(operand) == Some(reg));
277    if role.is_def() {
278        return output;
279    }
280    // The output first when something is in it on the way in, which is what `+` and a matching
281    // constraint both say, since its place is where a write earlier in the template left it and
282    // the read wants that. See [`read_as`] for what it holds before anything wrote it.
283    let arrives = |at: usize| read_as(list, at).is_some();
284    if let Some(at) = output.filter(|&at| arrives(at)) {
285        return Some(at);
286    }
287    let named = list.iter().position(|operand| {
288        operand.result.is_none() && operand.value.is_some() && pinned(operand) == Some(reg)
289    });
290    named.or(output)
291}
292
293/// The register one of an assembly statement's operands is in, whichever of the two ways said it.
294///
295/// A constraint letter is one way and is the only way a program can say one of the six registers
296/// that have a letter. A local register variable is the other, and it is the only way to say any
297/// of the rest: there is no letter for `r12`, which is the whole reason the extension exists, so
298/// the declaration says it and the front end wrote the name into the constraint. The name is read
299/// against this machine's table here, the same place the letter is read against it, and a name the
300/// machine has not got answers nothing, which leaves the operand where an operand nobody placed
301/// goes.
302///
303/// The sigil gcc allows in front of a name is taken off here, because what a name is written with
304/// is syntax and which register it means is this question.
305fn pinned(operand: &AsmOperand<'_>) -> Option<PhysReg> {
306    match operand.named {
307        Some(name) => {
308            let (reg, _) = x86_64::gpr_named(name.strip_prefix('%').unwrap_or(name))?;
309            Some(reg)
310        }
311        None => operand.fixed.and_then(x86_64::gpr_letter),
312    }
313}
314
315/// Whether a constraint says nothing but what it says on every machine.
316///
317/// [`AsmOperands::read`] gives the x86 meaning to every letter it knows, and most of the letters
318/// mean something else on AArch64: `Q` is an address in one register there rather than one of four
319/// registers, and `a` to `d` name nothing. So an AArch64 statement is taken only with the letters
320/// the two agree on, which are a register, a constant, memory, the immediate ranges and a matching
321/// number, and anything else is refused rather than read as x86. `w` and `Q` are the exceptions.
322/// `w` is a register on both, and which file it is in is decided by the caller with
323/// [`vector_letter`]. `Q` is read as `m` by the caller before the list is read. A
324/// register the front end named in braces is read against AArch64's own names, so what is inside
325/// them is not a letter.
326fn shared_letters(constraint: &str) -> bool {
327    let mut inside = false;
328    constraint.chars().all(|c| match c {
329        '{' => {
330            inside = true;
331            true
332        }
333        '}' => {
334            inside = false;
335            true
336        }
337        _ if inside => true,
338        _ => matches!(
339            c,
340            '=' | '+' | '&' | '%' | 'r' | 'w' | 'Q' | 'm' | 'o' | 'V' | 'g' | 'X' | 'i' | 'n'
341                | 'p' | 'I'..='N' | '0'..='9'
342        ),
343    })
344}
345
346/// A constraint list with every letter outside braces put through `swap`, and what is inside them,
347/// which is a register's name rather than letters, left alone.
348fn letters_outside(constraints: &str, swap: impl Fn(char) -> char) -> String {
349    let mut inside = false;
350    constraints
351        .chars()
352        .map(|c| {
353            match c {
354                '{' => inside = true,
355                '}' => inside = false,
356                _ if !inside => return swap(c),
357                _ => {}
358            }
359            c
360        })
361        .collect()
362}
363
364/// Whether an AArch64 constraint asks for a floating point or vector register, which is what `w`
365/// means there. A register named in braces is not a letter, so a `w` inside one is not read.
366fn vector_letter(constraint: &str) -> bool {
367    let mut inside = false;
368    constraint.chars().any(|c| {
369        match c {
370            '{' => inside = true,
371            '}' => inside = false,
372            _ => {}
373        }
374        !inside && c == 'w'
375    })
376}
377
378/// Whether a line of a template names, by number, an operand `wanted` says yes to.
379///
380/// `%%` is a percent sign rather than an operand, and a modifier letter may stand between the sign
381/// and the number.
382fn names_one(line: &str, wanted: impl Fn(usize) -> bool) -> bool {
383    let mut rest = line;
384    while let Some(at) = rest.find('%') {
385        let after = &rest[at + 1..];
386        if let Some(escaped) = after.strip_prefix('%') {
387            rest = escaped;
388            continue;
389        }
390        let after = after.strip_prefix(|c: char| c.is_ascii_alphabetic()).unwrap_or(after);
391        let digits = after.len() - after.trim_start_matches(|c: char| c.is_ascii_digit()).len();
392        if after[..digits].parse().is_ok_and(&wanted) {
393            return true;
394        }
395        rest = &after[digits..];
396    }
397    false
398}
399
400/// Why a function could not be lowered.
401///
402/// One reason and then nothing. A function with no rule for something in it is a function this
403/// cannot finish, and the second thing it could not lower is not news.
404#[derive(Debug, Clone, PartialEq, Eq)]
405pub enum Unsupported {
406    /// An instruction no rule fires on.
407    Inst {
408        /// The instruction that stopped it.
409        inst: Inst,
410        /// What the rule file would call it, or nothing if the rule language has no name for it
411        /// at all, which is what an instruction at a width nothing is written about looks like.
412        term: Option<&'static str>,
413        /// The opcode, which is what gets named when the rule language has no word for it.
414        ///
415        /// An opcode the rule language has no word for is exactly the opcode no rule lowers, so
416        /// without this the message would be empty in every case where somebody needs it.
417        opcode: Opcode,
418        /// What it produces, or nothing for an instruction that is only an effect.
419        ty: Option<Type>,
420    },
421    /// A parameter that does not arrive somewhere this can bring it in from.
422    ///
423    /// Not an instruction, which is why it is a separate arm: it is a fact about the signature
424    /// and there is nothing in the body of the function to point at.
425    Argument {
426        /// Its position in the signature.
427        index: usize,
428        /// What is wrong with where it arrives.
429        missing: Missing,
430    },
431    /// A call that passes or gives back a value this cannot put where the convention wants it.
432    Call {
433        /// The call.
434        inst: Inst,
435        /// Which value, and what is wrong with where it travels.
436        refused: Refused,
437    },
438    /// A `return` this cannot put where the convention wants it.
439    ///
440    /// A separate arm from [`Unsupported::Inst`] because it is not an instruction no rule fires
441    /// on. A return of more than one value is built from the convention rather than matched, the
442    /// same way a call is, so what goes wrong with one is what goes wrong with a call and not the
443    /// absence of a rule.
444    Returned {
445        /// The `return`.
446        inst: Inst,
447        /// What is wrong with where one of the values travels.
448        missing: Missing,
449    },
450    /// A stack slot the frame cannot give the bytes it asked for.
451    ///
452    /// Not an instruction no rule covers. An `alloca` is built here rather than matched, so what
453    /// goes wrong with one is what the frame can and cannot hold rather than what the rules spell.
454    Dynamic {
455        /// The `alloca`.
456        inst: Inst,
457        /// What the frame could not do about it.
458        growing: Growing,
459    },
460    /// More parameters of a type that travels on the x87 stack than the stack is deep.
461    ///
462    /// Not an instruction either, for the reason a function's parameter is not one: it is a fact
463    /// about the block and there is nothing in the block to point at. What crosses an edge for one
464    /// of these is the address of where the value is, and the block copies the bytes into a slot
465    /// of its own, all of them through the stack at once so that a block carrying two of them
466    /// swapped is copied in an order that is right. Eight is as many as the stack holds, and a
467    /// ninth would have to be copied before or after the rest, which is the order that could be
468    /// wrong.
469    Phi {
470        /// Which block it arrives at.
471        block: Block,
472        /// How many of them arrive there, which is the whole of what is wrong.
473        count: usize,
474        /// What they are.
475        ty: Type,
476    },
477    /// An `asm` statement this cannot build.
478    ///
479    /// Not an instruction no rule fires on, for the reason a call is not one: what it stands for is
480    /// whatever its template says, and no pattern over terms can read a string.
481    Assembly {
482        /// The `inline_asm`.
483        inst: Inst,
484        /// What about it is not built here yet.
485        refused: Written,
486    },
487    /// A `register long x asm ("...")` naming something this machine has not got.
488    ///
489    /// Not an instruction no rule fires on. There is a rule's worth of instruction here and what
490    /// is wrong is the string beside it, which is a name rather than a term, so the message says
491    /// the name. Which names a machine has is the machine's own question and this is where it is
492    /// asked, at the table a clobber list is read against.
493    Register {
494        /// The `register_value`.
495        inst: Inst,
496        /// The name the program wrote, as it wrote it.
497        name: String,
498    },
499    /// A naked function whose frame is not empty.
500    ///
501    /// Not an instruction no rule fires on, and there is nothing in the body to point at: the
502    /// function asked for no prologue and then wanted bytes only a prologue takes. Refused rather
503    /// than given the bytes anyway, because an offset into a frame nothing set up reaches into
504    /// whatever the caller left below its own stack pointer, which is wrong code that assembles.
505    /// See [`crate::frame::Layout::naked`].
506    Naked {
507        /// How many bytes it wanted, which is the whole of what is wrong.
508        bytes: u32,
509    },
510    /// Something the x86-64 lowering writes by hand and nothing has written for this machine yet.
511    ///
512    /// Refused rather than written with the x86 instructions, which is what the walk would do
513    /// otherwise, since these are the places it names them itself.
514    Unported {
515        /// The instruction, or nothing for the one that is about a signature.
516        inst: Option<Inst>,
517        /// Which of them.
518        what: Unported,
519    },
520}
521
522/// What [`Unsupported::Unported`] is about.
523#[derive(Debug, Clone, Copy, PartialEq, Eq)]
524pub enum Unported {
525    /// The thread pointer on Apple's platforms, which keep it somewhere other than Linux does.
526    Thread,
527}
528
529impl Unported {
530    /// The whole message, since there is nothing to put in front of it.
531    #[must_use]
532    pub fn why(self) -> &'static str {
533        match self {
534            Unported::Thread => "the thread pointer is not written for this platform yet",
535        }
536    }
537}
538
539/// What about an `asm` statement is not built yet.
540#[derive(Debug, Clone, Copy, PartialEq, Eq)]
541pub enum Written {
542    /// A template with instructions in it.
543    Template,
544    /// An `asm goto`, whose labels make the statement a terminator.
545    Goto,
546    /// An operand this cannot put where the constraint says it goes.
547    Operand,
548    /// A clobber list naming something this has no register for.
549    Clobber,
550    /// A `jmp` out of the function in a function that has an epilogue behind it.
551    Away,
552}
553
554impl Written {
555    /// The rest of the sentence that starts with the statement.
556    #[must_use]
557    pub fn why(self) -> &'static str {
558        match self {
559            // The template is the assembler's to read and there is no assembler here yet, so a
560            // template with anything in it is a string nothing can turn into bytes. An empty one is
561            // no instructions, and no instructions is something this can write.
562            Written::Template => "has instructions in its template, which nothing here assembles",
563            Written::Goto => "jumps to a label, which nothing here builds an edge for",
564            Written::Operand => "has an operand this cannot place",
565            Written::Clobber => "says it destroys a register this has no name for",
566            Written::Away => {
567                "jumps out of the function, which only a function that is `naked` may do, since \
568                 anywhere else there is an epilogue behind it to give the frame back"
569            }
570        }
571    }
572}
573
574/// What the frame could not do about a stack slot.
575#[derive(Debug, Clone, Copy, PartialEq, Eq)]
576pub enum Growing {
577    /// An object of a size the number a frame counts bytes in does not reach.
578    Huge,
579    /// A variable length array wanting more alignment than a call leaves the stack pointer with.
580    ///
581    /// Rounding the stack pointer down again after the bytes have been taken would put it
582    /// somewhere no constant reaches the rest of the frame from, so a frame like this needs a
583    /// second base register held for the whole of the function. Nothing here holds one.
584    ///
585    /// [`crate::expand::rounds`] takes the array away before this sees it, by asking for the
586    /// alignment in extra bytes and handing out an address inside them, so what is left of this
587    /// is IR that arrived without going through that pass and the fixed local in
588    /// [`crate::pipeline`] that wants the same thing from the other side.
589    Aligned,
590    /// A variable length array in a function written without a prologue.
591    ///
592    /// A frame that grows is reached from a frame pointer, and establishing one is the first two
593    /// instructions of a prologue that `__attribute__((naked))` asked there be none of. See
594    /// [`crate::frame::Layout::naked`].
595    Naked,
596}
597
598impl Growing {
599    /// The rest of the sentence that starts with the slot.
600    #[must_use]
601    pub fn why(self) -> &'static str {
602        match self {
603            Growing::Huge => "is more bytes than a frame counts",
604            Growing::Aligned => {
605                "wants more alignment than the stack pointer is left on, which needs a base \
606                 register nothing here keeps"
607            }
608            Growing::Naked => {
609                "is in a function that is `naked`, which has no prologue to point a frame pointer \
610                 at it with"
611            }
612        }
613    }
614}
615
616impl Unsupported {
617    /// The instruction it is about, or nothing for the one arm that is about a signature.
618    ///
619    /// What a caller wants this for is the span. The function knows where every instruction in
620    /// it came from, so a caller holding both can point a message at the line somebody wrote
621    /// rather than at the file as a whole, and nothing here has to carry a span of its own.
622    pub fn inst(&self) -> Option<Inst> {
623        match *self {
624            Unsupported::Inst { inst, .. }
625            | Unsupported::Call { inst, .. }
626            | Unsupported::Returned { inst, .. }
627            | Unsupported::Dynamic { inst, .. }
628            | Unsupported::Assembly { inst, .. }
629            | Unsupported::Register { inst, .. } => Some(inst),
630            Unsupported::Unported { inst, .. } => inst,
631            Unsupported::Argument { .. } | Unsupported::Phi { .. } | Unsupported::Naked { .. } => {
632                None
633            }
634        }
635    }
636}
637
638impl fmt::Display for Unsupported {
639    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
640        match *self {
641            Unsupported::Inst { term: Some(term), .. } => write!(f, "no rule lowers `{term}`"),
642            Unsupported::Inst { term: None, opcode, ty: Some(ty), .. } => {
643                write!(f, "no rule lowers a `{opcode}` producing a `{ty}`")
644            }
645            Unsupported::Inst { term: None, opcode, ty: None, .. } => {
646                write!(f, "no rule lowers a `{opcode}`")
647            }
648            Unsupported::Argument { index, missing } => {
649                write!(f, "parameter {index} {}", missing.why())
650            }
651            Unsupported::Call { refused: Refused { argument: Some(index), missing }, .. } => {
652                write!(f, "argument {index} of this call {}", missing.why())
653            }
654            Unsupported::Call { refused: Refused { argument: None, missing }, .. } => {
655                write!(f, "what this call gives back {}", missing.why())
656            }
657            Unsupported::Returned { missing, .. } => {
658                write!(f, "what this function gives back {}", missing.why())
659            }
660            Unsupported::Dynamic { growing, .. } => {
661                write!(f, "this local {}", growing.why())
662            }
663            Unsupported::Phi { block, count, ty } => {
664                let block = block.index();
665                write!(
666                    f,
667                    "block{block} takes {count} parameters of type `{ty}` and only {X87_DEPTH} can cross an edge at once"
668                )
669            }
670            Unsupported::Assembly { refused, .. } => write!(f, "this `asm` {}", refused.why()),
671            Unsupported::Unported { what, .. } => f.write_str(what.why()),
672            Unsupported::Register { ref name, .. } => {
673                write!(
674                    f,
675                    "this object is kept in `{name}`, which is not a register this machine has"
676                )
677            }
678            Unsupported::Naked { bytes } => write!(
679                f,
680                "this function is `naked` and wants {bytes} bytes of frame, which there is no prologue to take"
681            ),
682        }
683    }
684}
685
686impl std::error::Error for Unsupported {}
687
688/// A lowered function, and what the frame needs that the machine IR does not hold.
689#[derive(Debug)]
690pub struct Lowered {
691    /// The function, in machine instructions.
692    pub func: mir::Func,
693    /// What it wants its stack to look like, which is separate from the function so that the two
694    /// can be read and written at the same time.
695    pub stack: Stack,
696    /// Which rules of the table lowered it, which is what `-Zrule-coverage` asks for and what
697    /// `crate::coverage` writes down.
698    pub fired: Fired,
699    /// Which machine IR block each IR block became, indexed by the IR block's own index, and
700    /// nothing for a block the walk never reached.
701    ///
702    /// Here because it is the only place the correspondence exists. Selection makes one block per
703    /// block, in the same order and with the arms in the same order, so anything the IR knows
704    /// about a block can be carried down through this and nothing else, and
705    /// [`crate::weights::carry`] is what does.
706    pub blocks: Vec<Option<mir::Block>>,
707}
708
709/// What a function's stack has to hold, as far as selection is able to say.
710///
711/// All of it is answered here because selection is where a call is built and where an `alloca`
712/// is read, and nothing after it could tell what either of them needed.
713#[derive(Debug, Default)]
714pub struct Stack {
715    /// How many bytes the widest call in the function needs below the stack pointer for the
716    /// arguments it passes there, or `None` for a function that makes no call at all.
717    ///
718    /// `None` is a leaf, which is the function that may use the red zone and the one whose stack
719    /// pointer does not have to be left aligned for anybody.
720    pub calls: Option<u32>,
721    /// The memory the function asked for itself, one entry for every `alloca` in it, in the order
722    /// the walk reached them.
723    pub locals: Vec<Local>,
724    /// Which instruction computes the address of which of those locals.
725    ///
726    /// An address in the frame is a distance from the stack pointer, and there is no frame until
727    /// after allocation, so the instruction is written here with nothing in its displacement and
728    /// [`crate::finish`] writes the number in once [`crate::frame::Frame`] knows it.
729    pub addresses: Vec<(mir::Inst, usize)>,
730    /// Which of those locals is which declaration in the source, for the ones the program declared.
731    ///
732    /// The number is the one the IR function carries and means nothing here. What it is for is the
733    /// debugging information, which has to say where a named local ended up and cannot ask the
734    /// frame directly: the frame knows a local by the order the `alloca` for it was lowered in and
735    /// by nothing else.
736    ///
737    /// Shorter than the list above rather than the same length, because most of what a function
738    /// keeps in its frame is memory an expression wanted somewhere to put.
739    pub declared: Vec<(usize, u32)>,
740    /// Which instruction computes the address of a piece of memory whose size the function works
741    /// out while it runs, which is what a variable length array is.
742    ///
743    /// Waiting on [`crate::finish`] for a different number from the one the addresses above are:
744    /// the bytes were taken off the stack pointer by the instruction in front of this one, so where
745    /// they start is however much of the bottom of the frame belongs to the arguments of a call,
746    /// and that is not known until the frame is.
747    pub dynamic: Vec<mir::Inst>,
748    /// Which instruction takes those bytes off the stack pointer, one for every one of them, in the
749    /// order the walk reached them.
750    ///
751    /// Read by [`crate::finish`] on a command line that asked for the stack to be touched a page at
752    /// a time, which is the one thing that has to find these again: the bytes are in a register by
753    /// then, so the walk down to them is a loop, and a loop is written around an instruction rather
754    /// than in front of a block. Nothing else looks at them, because everything else about a frame
755    /// that grows is answered by the address the instruction below this one computes.
756    pub grown: Vec<mir::Inst>,
757    /// Where the function first moves the stack pointer while it runs, if it does at all.
758    ///
759    /// Two things are read off this. One is whether at all, which is what [`crate::frame::Layout`]
760    /// wants, because a frame that moves its stack pointer has a different shape from one that does
761    /// not and the layout is built before the instructions are looked at again. See `Growing` in
762    /// [`crate::frame`]. The other is where, so that a caller that cannot accept such a frame has
763    /// somewhere to point when it says so.
764    pub grown_at: Option<Inst>,
765    /// Which instruction reads which of the arguments the caller passed on the stack, as how far up
766    /// the caller's argument area it reads.
767    ///
768    /// Waiting on [`crate::finish`] for the same reason the addresses above are, and on one thing
769    /// more: where the caller's argument area is from inside this function depends on whether the
770    /// prologue had to force the stack pointer's alignment, so which register the load reads
771    /// through is not settled here either.
772    pub arguments: Vec<(mir::Inst, u32)>,
773    /// Whether the function asked where its own frame is, which is what `__builtin_frame_address`
774    /// and `__builtin_return_address` both start from.
775    ///
776    /// A function like that keeps a frame pointer whatever the flags say, because the register is
777    /// the answer to the first of them and the start of the walk for every depth above zero. There
778    /// is no other way to reach it: the distance from the stack pointer to the frame is a number
779    /// the layout works out, and what a walk up the chain needs is the link the prologue saved.
780    pub walks_frames: bool,
781    /// Whether the function saved a place for a `__builtin_longjmp` to come back to, which is what
782    /// `__builtin_setjmp` does.
783    ///
784    /// A function like that keeps a frame pointer whatever the flags say as well, and for a reason
785    /// of the same shape: the two registers the restore puts back are the frame pointer and the
786    /// stack pointer, and a frame that did not keep the first of them has nothing in it saying
787    /// where the caller's frame is for the epilogue to find after control has come back.
788    pub saves_place: bool,
789}
790
791impl Stack {
792    /// The layout given, with the three fields only the lowering knows the answer to filled in.
793    ///
794    /// Everything else in a layout comes from the flags the function is compiled under or from the
795    /// allocation, so this takes one and returns it rather than building one.
796    ///
797    /// A function that saved a place is not a leaf whatever it called. What a leaf buys is the red
798    /// zone, which is the words below the stack pointer nothing else may write, and a function
799    /// control comes back into from a `__builtin_longjmp` has already had something else running
800    /// down there: whatever it called and whatever that called, or a signal handler on the same
801    /// stack. Every one of those has written over the red zone by the time control arrives, so a
802    /// value this function left there would not be there any more.
803    #[must_use]
804    pub fn layout<'a>(&'a self, base: Layout<'a>) -> Layout<'a> {
805        Layout {
806            leaf: self.calls.is_none() && !self.saves_place,
807            outgoing: self.calls.unwrap_or(0),
808            locals: &self.locals,
809            grows: self.grown_at.is_some(),
810            ..base
811        }
812    }
813}
814
815/// The machine IR for that function, for the machine the selector describes.
816///
817/// # Errors
818///
819/// The first instruction no rule fires on, which today is anything at a width the rule set is not
820/// written at, a parameter that does not arrive in a register this can read, or a call that
821/// passes something this cannot put where the convention wants it.
822pub fn func(
823    source: &Func,
824    names: &mut Interner,
825    selector: &'static Selector,
826    conv: &'static CallRegs,
827    elsewhere: &Elsewhere,
828) -> Result<Lowered, Unsupported> {
829    Lowering::new(source, names, selector, conv, elsewhere).run()
830}
831
832/// What the matcher settled on for one block, indexed the way the block's instructions are.
833struct Decided {
834    /// What each instruction matched, and nothing for one that matched no rule or was folded
835    /// into a later one.
836    found: Vec<Option<Match<Term>>>,
837    /// How each instruction showed its operands to the matcher, which is what says what it took.
838    plans: Vec<Option<Plan>>,
839    /// The instructions some other instruction took, which are the ones with nothing to write.
840    folded: Vec<Inst>,
841}
842
843/// The instruction in front of an assignment that starts a declaration on a value, and the first
844/// machine instruction after it once the block is filled.
845type Mark = (Option<Inst>, Option<mir::Inst>);
846
847/// One function being lowered.
848struct Lowering<'a> {
849    source: &'a Func,
850    names: &'a mut Interner,
851    out: mir::Func,
852    /// The machine register each IR value is in, once it has one.
853    regs: Vec<Option<mir::Reg>>,
854    /// For a constant that has been written into a register, the block it was written into,
855    /// which is the only block that register is any good in.
856    written: Vec<Option<mir::Block>>,
857    /// How many times each IR value is read, which is what says whether an instruction may be
858    /// folded into the one that reads it.
859    uses: Vec<u32>,
860    /// The block being filled.
861    at: Option<mir::Block>,
862    /// The machine IR block each IR block became.
863    blocks: Vec<Option<mir::Block>>,
864    /// The class an address is in, which is the general purpose one and is not a question: every
865    /// register an addressing mode names holds part of an address, and there is no machine here
866    /// that computes an address anywhere but in this file. Which class a *value* is in is
867    /// [`Lowering::class_of`], and it is a question, because a float is in the other one.
868    gpr: RegClass,
869    /// The machine this selects for.
870    selector: &'static Selector,
871    /// Where the convention this function is compiled for puts things, which is read for the
872    /// arguments and for the calls.
873    conv: &'static CallRegs,
874    /// Which names this function may not work an address out for itself, which is a fact about the
875    /// module and so is worked out before any of this and handed in.
876    elsewhere: &'a Elsewhere,
877    /// What the function wants its stack to look like, filled in as the walk finds out.
878    stack: Stack,
879    /// What a `va_start` in this function has to write, or nothing for a function that takes no
880    /// arguments its signature does not name.
881    ///
882    /// Worked out once, when the entry block binds the parameters, because every number in it is
883    /// about where those parameters left the walk over the argument registers and there is nowhere
884    /// else that knows.
885    varargs: Option<Varargs>,
886    /// Which of the function's stack objects each eighty bit value lives in, once it has asked
887    /// for one.
888    ///
889    /// One slot per value and it is never given back, which is what makes an eighty bit value
890    /// behave like every other one: it is written once and read wherever it is read, and no two
891    /// of them share a slot the way two of them would share a register. What is in a register is
892    /// the address, and that is worked out again at every use rather than kept, so nothing here
893    /// holds a general purpose register open across a whole function.
894    slots: Vec<Option<usize>>,
895    /// The eight bytes a value passes through between a register and the x87 stack, once
896    /// something has wanted them.
897    ///
898    /// One for the whole function, because every group that uses it is a handful of instructions
899    /// with nothing in between: the bytes are written, read straight back and never looked at
900    /// again, so a second slot would be a second slot holding the same nothing.
901    crossing: Option<usize>,
902    /// The four bytes the control word is saved in and the changed copy written to, once
903    /// something has wanted them.
904    ///
905    /// One for the whole function for the reason above, and four rather than two because it is
906    /// two words: the one the unit had and the one with the rounding field turned to truncate.
907    control: Option<usize>,
908    /// The word a `__builtin_setjmp` in this function answers with, once one has asked for it.
909    ///
910    /// One for the whole function however many saves there are in it, because the word is written
911    /// and read back with nothing in between: the save writes a zero into it and the instruction
912    /// straight after reads it, and the only other thing that ever writes it is a restore arriving
913    /// between those two. Two saves sharing it is two pairs each doing that, and neither can be
914    /// inside the other.
915    answer: Option<usize>,
916    /// Which rules have fired so far.
917    fired: Fired,
918    /// Where each assignment that starts a declaration on a value part of the way through is, by
919    /// the IR block it is in and the instruction in front of it, and which machine instruction
920    /// is the first one after it once the block has been filled. See
921    /// [`rucc_ir::Func::declare_value_from`].
922    marks: HashMap<Block, Vec<Mark>>,
923}
924
925/// What a `va_start` in a variadic function writes into the list it is given.
926///
927/// Two shapes, because two conventions describe a list two ways, and [`crate::varargs`] is where
928/// both are written down. Neither is a set of numbers on its own: where the save area is and where
929/// the caller's argument area is are distances into a frame that does not exist until after
930/// allocation, so each is a `lea` [`crate::finish`] fills in.
931#[derive(Debug, Clone, Copy, PartialEq, Eq)]
932enum Varargs {
933    /// The four field list, whose two offsets are settled here and whose two addresses are not.
934    Fields {
935        /// Which of the function's stack objects is the register save area.
936        save: usize,
937        /// How far up the caller's argument area the first argument the signature does not name is,
938        /// which is the whole of that area the named ones did not take.
939        incoming: u32,
940        /// What `gp_offset` starts at, which is past the general purpose registers the named
941        /// arguments took.
942        integers: u32,
943        /// What `fp_offset` starts at, which is past the vector ones.
944        floats: u32,
945    },
946    /// The AAPCS64 list, whose two offsets count up to zero from the top of each half of the save
947    /// area. The two tops are addresses in the frame and so is the first field, like the SysV list.
948    Aapcs {
949        /// Which of the function's stack objects is the register save area.
950        save: usize,
951        /// How far up the caller's argument area the first argument the signature does not name is.
952        incoming: u32,
953        /// Where the general purpose half of the save area ends.
954        integers_end: u32,
955        /// Where the vector half ends, which is the end of the area.
956        floats_end: u32,
957        /// What `__gr_offs` starts at, which is minus the general purpose half the named arguments
958        /// did not take.
959        integers: i32,
960        /// What `__vr_offs` starts at.
961        floats: i32,
962    },
963    /// The list that is a pointer, which is the one address and nothing else.
964    Pointer {
965        /// How far up the caller's argument area the first argument the signature does not name is,
966        /// which on this convention is the word belonging to the position the named ones stopped
967        /// at.
968        incoming: u32,
969    },
970}
971
972/// How far a function's name reaches, narrowed from the linkage the IR gave it.
973///
974/// The IR has five and an object file says three, and the two the linker cannot tell apart are
975/// the two weak ones: which of them a symbol had is a fact the optimizer reads and the linker has
976/// no way to record. A function is never `Common`, since that is what a tentative definition of an
977/// object is and there is no tentative definition of a function, and it is written here rather
978/// than left out so that a linkage added later has to come past this.
979const fn binding(linkage: Linkage) -> mir::Binding {
980    match linkage {
981        Linkage::Internal => mir::Binding::Local,
982        Linkage::Weak | Linkage::LinkOnce => mir::Binding::Weak,
983        Linkage::External | Linkage::Common => mir::Binding::Global,
984    }
985}
986
987/// How far a function's name reaches outside a shared library, carried across unchanged.
988///
989/// Nothing is narrowed here the way [`binding`] narrows the linkage, because ELF records all
990/// three of these and the two enumerations are the same three answers written twice: once in a
991/// crate that is not allowed to know what an object file is and once in one that is.
992const fn visibility(visibility: Visibility) -> mir::Visibility {
993    match visibility {
994        Visibility::Default => mir::Visibility::Default,
995        Visibility::Hidden => mir::Visibility::Hidden,
996        Visibility::Protected => mir::Visibility::Protected,
997    }
998}
999
1000impl<'a> Lowering<'a> {
1001    fn new(
1002        source: &'a Func,
1003        names: &'a mut Interner,
1004        selector: &'static Selector,
1005        conv: &'static CallRegs,
1006        elsewhere: &'a Elsewhere,
1007    ) -> Self {
1008        let counts = source.counts();
1009        let name = source.name;
1010        let mut uses = vec![0; counts.values];
1011        for block in source.blocks() {
1012            for inst in source.insts(block) {
1013                for &arg in &source[source[inst].args] {
1014                    uses[arg.index()] += 1;
1015                }
1016                for call in source.successors(inst) {
1017                    for &arg in &source[call.args] {
1018                        uses[arg.index()] += 1;
1019                    }
1020                }
1021            }
1022        }
1023        let mut out = mir::Func::new(name);
1024        out.align = source.align;
1025        // Carried rather than worked out here, because where a function was declared is a fact
1026        // about the source and this is a long way past it. What wants it is the line table.
1027        out.declared = source.declared;
1028        out.binding = binding(source.linkage);
1029        out.visibility = visibility(source.visibility);
1030        Self {
1031            source,
1032            names,
1033            out,
1034            regs: vec![None; counts.values],
1035            written: vec![None; counts.values],
1036            blocks: vec![None; counts.blocks],
1037            uses,
1038            at: None,
1039            gpr: selector.gpr,
1040            selector,
1041            conv,
1042            elsewhere,
1043            stack: Stack::default(),
1044            varargs: None,
1045            slots: vec![None; counts.values],
1046            crossing: None,
1047            control: None,
1048            answer: None,
1049            fired: Fired::new(),
1050            marks: HashMap::new(),
1051        }
1052    }
1053
1054    fn run(mut self) -> Result<Lowered, Unsupported> {
1055        for value in self.source.values() {
1056            for start in self.source.value_starts(value) {
1057                let Some((block, after)) = self.source.start_place(start) else { continue };
1058                let marks = self.marks.entry(block).or_default();
1059                if !marks.iter().any(|&(have, _)| have == after) {
1060                    marks.push((after, None));
1061                }
1062            }
1063        }
1064        // Every block before any of them is filled, because a block that jumps forward has to
1065        // name the block it jumps to and a machine IR block is named by a handle rather than by
1066        // the IR block it came from.
1067        for block in self.source.blocks() {
1068            let out = self.out.create_block();
1069            self.blocks[block.index()] = Some(out);
1070        }
1071        for block in self.order() {
1072            self.block(block)?;
1073        }
1074        // And the name each block an image holds the address of was given, which nothing in the
1075        // walk above would ask for: the `lea` a label address is inside the function needs no
1076        // symbol, and the one thing that does is a relocation in another section.
1077        let named: Vec<(Block, Symbol)> = self.source.named_blocks().collect();
1078        let labels: Vec<(mir::Block, Symbol)> =
1079            named.into_iter().map(|(block, name)| (self.out_block(block), name)).collect();
1080        self.out.labels = labels;
1081        self.naming();
1082        Ok(Lowered { func: self.out, stack: self.stack, fired: self.fired, blocks: self.blocks })
1083    }
1084
1085    /// Which register each declaration the front end kept in a value ended up in, as far as this
1086    /// walk can say, which is the other half of what [`Lowering::new_reg`] writes down as it goes.
1087    ///
1088    /// Two halves because there are two ways a value gets a register here. Most of them ask for a
1089    /// fresh one and that is where `new_reg` catches them, and the rest are put in a register
1090    /// something else chose: a parameter arrives in whichever one the convention handed it, a block
1091    /// parameter in whichever one the edge agreed on, and a result of a rule that names its own
1092    /// registers in the one the rule named. None of those goes past the mint, so this is the map at
1093    /// the end read off the other side, and the two together are every value a declaration is
1094    /// behind.
1095    ///
1096    /// The map on its own would not do, which is why `new_reg` writes down what it writes down: the
1097    /// entry for a constant is cleared every time the walk leaves the block that wrote it, so a
1098    /// local a constant holds is in the map for one block of the function and nowhere else.
1099    fn naming(&mut self) {
1100        let mut named = std::mem::take(&mut self.out.named);
1101        for value in self.source.values() {
1102            let Some(reg) = self.regs[value.index()] else { continue };
1103            named.extend(self.source.value_decls(value).map(|decl| (decl, reg)));
1104            // A start in a block a pass took out was never reached above, and it says nothing
1105            // rather than something about another place.
1106            for start in self.source.value_starts(value) {
1107                let Some((block, after)) = self.source.start_place(start) else { continue };
1108                let first = self.marks.get(&block).and_then(|marks| {
1109                    marks.iter().find(|&&(have, _)| have == after).and_then(|&(_, at)| at)
1110                });
1111                if let Some(first) = first {
1112                    self.out.starts.push((start.decl, reg, first));
1113                }
1114            }
1115        }
1116        named.sort_unstable();
1117        named.dedup();
1118        self.out.named = named;
1119        self.out.starts.sort_unstable();
1120        self.out.starts.dedup();
1121        // Which of its values a declaration holds on the way into a block, for the blocks where
1122        // two of them are live at once. A block a pass took out says nothing, and neither does a
1123        // value the map above has lost the register of, since that is not the same as having none.
1124        let mut entries = Vec::new();
1125        for (decl, block, value) in crate::holding::on_entry(self.source) {
1126            if let (Some(block), Some(reg)) = (self.blocks[block.index()], self.regs[value.index()])
1127            {
1128                entries.push((decl, block, reg));
1129            }
1130        }
1131        entries.sort_unstable();
1132        entries.dedup();
1133        self.out.entries = entries;
1134    }
1135
1136    /// The order the blocks are filled in, which is not the order they are written in.
1137    ///
1138    /// Reverse postorder, because a value is written in a block that dominates every block that
1139    /// reads it and a block in reverse postorder comes before every block it dominates. The order
1140    /// the blocks are written in does not have that property: a block written early can read a
1141    /// value a block below it writes, and reading a value with no register yet mints one, so the
1142    /// register the definition writes later is not the register the read named. Nothing writes the
1143    /// one the read named, and what comes out is a function that loads a stack slot no store ever
1144    /// reached. It is the order this walk goes in rather than the order the blocks come out in,
1145    /// which is what the loop above fixes, so the machine function is still written the way the IR
1146    /// function was.
1147    ///
1148    /// Blocks the entry does not reach come last, in the order they are written in. Nothing runs
1149    /// them and nothing they name is read by anything that does, but they still have to be filled,
1150    /// because a machine block with no terminator is not one the passes below can read.
1151    fn order(&self) -> Vec<Block> {
1152        let Some(entry) = self.source.entry() else { return self.source.blocks().collect() };
1153        let count = self.blocks.len();
1154        let mut succs: Vec<Vec<Block>> = vec![Vec::new(); count];
1155        for block in self.source.blocks() {
1156            let Some(term) = self.source.terminator(block) else { continue };
1157            succs[block.index()] = self.source.successors(term).map(|call| call.block).collect();
1158        }
1159        // An explicit stack, because the depth of the walk is the number of blocks and a function
1160        // built by a generator has as many of those as it likes.
1161        let mut seen = vec![false; count];
1162        let mut order = Vec::with_capacity(count);
1163        let mut stack = vec![(entry, 0usize)];
1164        seen[entry.index()] = true;
1165        while let Some((block, at)) = stack.pop() {
1166            let Some(&next) = succs[block.index()].get(at) else {
1167                order.push(block);
1168                continue;
1169            };
1170            stack.push((block, at + 1));
1171            if !seen[next.index()] {
1172                seen[next.index()] = true;
1173                stack.push((next, 0));
1174            }
1175        }
1176        order.reverse();
1177        order.extend(self.source.blocks().filter(|block| !seen[block.index()]));
1178        order
1179    }
1180
1181    /// One block: its parameters, then every instruction in it that is not folded into another.
1182    fn block(&mut self, block: Block) -> Result<(), Unsupported> {
1183        let out = self.out_block(block);
1184        self.at = Some(out);
1185        if self.source.entry() == Some(block) {
1186            self.arrive(block, out)?;
1187        } else {
1188            let mut arriving = Vec::new();
1189            for &param in &self.source[block].params {
1190                // A value with no register to arrive in, which the class would not say, since
1191                // `class_of` puts one of these in the general purpose file on purpose and what it
1192                // means by that is that nothing there can hold it. What crosses the edge for one
1193                // of those is the address of where the value already is, so the parameter is a
1194                // pointer here and the bytes it points at are copied below.
1195                let ty = self.source[param].ty;
1196                let reg = self.out.append_param(out, self.class_of(ty));
1197                self.regs[param.index()] = Some(reg);
1198                if on_x87(ty) {
1199                    arriving.push((param, reg));
1200                }
1201            }
1202            self.settle(block, &arriving)?;
1203        }
1204
1205        // What each instruction matched, and which instructions were folded into another. The
1206        // decision is made for the whole block before any of it is written, and it is made more
1207        // than once: a value that only some of its readers took has to be put back in a register
1208        // for all of them, and taking it away from those readers changes what they match.
1209        let insts: Vec<Inst> = self.source.insts(block).collect();
1210        let mut refused: HashSet<Value> = HashSet::new();
1211        let mut decided = self.decide(&insts, &refused);
1212        while let Some(value) = self.left_alive(&insts, &decided.plans) {
1213            refused.insert(value);
1214            decided = self.decide(&insts, &refused);
1215        }
1216        let Decided { found, folded, .. } = decided;
1217
1218        // Where each assignment in this block that starts a declaration on a value is, as the
1219        // machine instruction in front of the place its IR instruction left off, or the block
1220        // for one where nothing has been written yet. What comes after it is not known until the
1221        // block is filled, so that is read below.
1222        let wanted: HashSet<Option<Inst>> =
1223            self.marks.get(&block).into_iter().flatten().map(|&(after, _)| after).collect();
1224        let mut reached: Vec<(Option<Inst>, mir::Block, Option<mir::Inst>)> = Vec::new();
1225        for (index, (&inst, matched)) in insts.iter().zip(found).enumerate() {
1226            let before = index.checked_sub(1).map(|index| insts[index]);
1227            if wanted.contains(&before) {
1228                let at = self.at.unwrap_or(out);
1229                reached.push((before, at, self.out.terminator(at)));
1230            }
1231            if folded.contains(&inst) || self.writes_nothing(inst) {
1232                continue;
1233            }
1234            // A call is built from the convention rather than matched, which is why it is the one
1235            // opcode looked at by name here. Through an address it is a different instruction and
1236            // the same convention, so the two arrive at the same place and differ in one line of
1237            // it.
1238            match self.source[inst].opcode {
1239                Opcode::Call | Opcode::CallIndirect => {
1240                    self.called(inst)?;
1241                    continue;
1242                }
1243                // Built from the frame rather than matched, for the same shape of reason a call
1244                // is built from the convention: what a rule replaces a term with is instructions,
1245                // and what an `alloca` needs first is bytes, which the rule language has no way
1246                // to ask for.
1247                Opcode::Alloca => {
1248                    self.reserve(inst)?;
1249                    continue;
1250                }
1251                // Reading the stack pointer and writing it back, which are the two ends of a scope
1252                // holding a variable length array. Built here for the reason an `alloca` is: the
1253                // value is a register the rule language has no way to name, because what it holds
1254                // is not a value the program computed but where the machine's stack had got to.
1255                Opcode::StackSave => {
1256                    self.stack_pointer(inst, false)?;
1257                    continue;
1258                }
1259                Opcode::StackRestore => {
1260                    self.stack_pointer(inst, true)?;
1261                    continue;
1262                }
1263                // The address of a name, built here for the same reason an `alloca` is: what a
1264                // rule replaces a term with is instructions over values, and the operand of this
1265                // one is a symbol, which is a thing the rule language has no way to bind and the
1266                // solver has no way to say anything about. There is nothing in `lea sym(%rip)` a
1267                // proof over bitvectors could discharge, because what makes it the right answer
1268                // is the relocation and what the linker does with it.
1269                Opcode::GlobalAddr => {
1270                    self.address_of(inst)?;
1271                    continue;
1272                }
1273                // The address of a label and the branch that reads one, built here for the same
1274                // reason and for one more. The reason is the same: what the first of them names is
1275                // a block, which is not a value a rule pattern can bind, and there is nothing in
1276                // the distance between two places in one function that a proof over bitvectors
1277                // could discharge. The extra one is that the second is a terminator whose arms are
1278                // not two and not fixed, and a rule says what an instruction reads rather than
1279                // where a block goes.
1280                Opcode::BlockAddr => {
1281                    self.block_address(inst)?;
1282                    continue;
1283                }
1284                Opcode::IndirectBr => {
1285                    self.indirect_branch(inst)?;
1286                    continue;
1287                }
1288                // A `switch` that `crate::switch` found dense enough for a table, which is a load
1289                // out of the table and the same jump. Built here for the reasons the jump above
1290                // is, and because what the load reads is a place in this function.
1291                Opcode::Switch => {
1292                    self.jump_table(inst)?;
1293                    continue;
1294                }
1295                // The pair that saves a place in this function and comes back to it. Built here
1296                // for the reason the address of a label is, and for two more. The reason is the
1297                // same: the first of them writes down where control comes back to, which is a
1298                // place in this function and not a value a rule pattern can bind. The extra ones
1299                // are that each of them is a group of instructions over a buffer the program owns
1300                // rather than one instruction, and that the first of them leaves the block it was
1301                // written in and carries on in a new one, which is a thing no rule can do.
1302                Opcode::SetjmpMarker => {
1303                    self.saves_place(inst)?;
1304                    continue;
1305                }
1306                Opcode::LongjmpMarker => {
1307                    self.comes_back(inst)?;
1308                    continue;
1309                }
1310                // Where this thread's own storage starts, built here for a reason of the same
1311                // shape: what it reads is `%fs`, which is not a register the rule language can
1312                // bind and not one a proof over bitvectors could say anything about, because what
1313                // makes the load the right answer is an agreement between the loader and the C
1314                // library rather than any arithmetic.
1315                Opcode::ThreadPointer => {
1316                    self.thread_pointer(inst)?;
1317                    continue;
1318                }
1319                // What a named machine register holds, built here for the reason above written
1320                // about any register rather than about one: which register it is is a string
1321                // beside the instruction, and a rule matches on an opcode and a type and could
1322                // not see it. There is nothing to prove either, since the answer is the register
1323                // and the instruction is the move that reads it.
1324                Opcode::RegisterValue => {
1325                    self.register_value(inst)?;
1326                    continue;
1327                }
1328                // Where a frame is and what it returns to, built here for the same reason and one
1329                // more. The reason is the same: what the walk starts from is the frame pointer,
1330                // which is not a register a rule pattern can bind, and there is nothing in reading
1331                // the link the prologue saved that a proof over bitvectors could discharge. The
1332                // extra one is that how long the walk is comes out of a number beside the
1333                // instruction, so one of these is not one instruction but however many the depth
1334                // says, and a rule replaces a term with a term.
1335                Opcode::FrameAddress | Opcode::ReturnAddress => {
1336                    self.frames(inst)?;
1337                    continue;
1338                }
1339                // Built from the frame for the reason an `alloca` is, and from the convention for
1340                // the reason a call is: three of the four fields it writes are distances that do
1341                // not exist until the frame does, and the fourth is where the walk over the
1342                // argument registers stopped. A function that is not variadic has no such walk to
1343                // report, so it has nothing here and is refused below, which is the right answer
1344                // for a `va_start` in one.
1345                Opcode::VaStart if self.varargs.is_some() => {
1346                    self.va_start(inst)?;
1347                    continue;
1348                }
1349                // A return of more than one value, which is a structure small enough to come
1350                // back in a pair of registers. Built from the convention for the reason a call
1351                // is: which register each half goes in depends on the halves in front of it,
1352                // because the two register files are walked separately, and a pattern over a term
1353                // cannot see them. A return of one value is a term with a name and a rule, and it
1354                // stays one.
1355                //
1356                // A return of none in a function whose answer went through memory is here too,
1357                // and for a different reason: what it gives back is not written in the IR at all.
1358                // The convention says the address the caller handed over comes back, and only the
1359                // signature says this function was handed one.
1360                //
1361                // And a return of one eighty bit value, for a third reason: what a rule would
1362                // write is an instruction leaving the value in a register, and this one is left on
1363                // the x87 stack instead. A rule could not name that stack any more than any other
1364                // rule about this type could.
1365                Opcode::Return
1366                    if self.source[self.source[inst].args].len() > 1
1367                        || self.sret().is_some()
1368                        || self.gives_back_x87(inst) =>
1369                {
1370                    self.returned(inst)?;
1371                    continue;
1372                }
1373                // A cast between a pointer and an integer of the same width, which on this
1374                // machine is every one the front end writes. No instruction at all, so no rule
1375                // could name one.
1376                Opcode::PtrToInt | Opcode::IntToPtr => {
1377                    self.rename(inst)?;
1378                    continue;
1379                }
1380                // A barrier, which is one instruction or none depending on the ordering. Written
1381                // by name because there is nothing about it a rule could be proved against, the
1382                // way there is nothing to prove about the address of a symbol.
1383                Opcode::Fence => {
1384                    self.barrier(inst)?;
1385                    continue;
1386                }
1387                // A hint, written by name for the reason a barrier is and one step further: not
1388                // only is there no equality for a proof to discharge, there is nothing about the
1389                // program around it either. Which of the four instructions it is comes out of the
1390                // number the builtin was given, which is beside the instruction rather than in it.
1391                Opcode::Prefetch => {
1392                    self.hint(inst)?;
1393                    continue;
1394                }
1395                // Stopping, written by name for the first half of the barrier's reason: it
1396                // computes nothing, so there is no term for a rule to replace, and what makes it
1397                // right is what the operating system does with the fault rather than anything a
1398                // proof over bitvectors could discharge.
1399                Opcode::Trap => {
1400                    self.trap(inst);
1401                    continue;
1402                }
1403                // A compare and exchange, which is written by name because it produces two values
1404                // and a rule produces one. The replacement of a rule is one term, a term names the
1405                // value an instruction computes, and there is no way in that language to say that
1406                // an instruction leaves an answer in one place and a yes or no in another.
1407                Opcode::Cmpxchg => {
1408                    self.exchange(inst)?;
1409                    continue;
1410                }
1411                // A read modify write, which is written by name for a different reason: it produces
1412                // one value, so a rule could name it, and what it does is not in the head a rule
1413                // matches on. Every one of the thirteen operations is the same opcode at the same
1414                // type and differs only in what is carried beside it, so one pattern would be all
1415                // thirteen patterns. Of the thirteen only the three with an instruction reach here,
1416                // since `crate::retry` turned the rest into loops a long way above this.
1417                Opcode::AtomicRmw => {
1418                    self.modify(inst)?;
1419                    continue;
1420                }
1421                // An `asm` statement, whose lowering is its template and there is no term for a
1422                // string. Written by name for the reason a barrier is, and before the x87 arm
1423                // below so that an `asm` holding a `long double` is refused as the `asm` it is
1424                // rather than as an instruction nothing computes.
1425                Opcode::InlineAsm => {
1426                    // The template is read as x86 assembly, and that reader is the only one there
1427                    // is. AArch64 keeps every template as text, and any other machine's `asm` is
1428                    // refused here rather than read as the wrong language.
1429                    if self.on_aarch64() {
1430                        self.spelled(inst)?;
1431                        continue;
1432                    }
1433                    if !std::ptr::eq(self.selector.shapes, &x86_64::MACHINE) {
1434                        return Err(self.unsupported(inst));
1435                    }
1436                    self.assembly(inst)?;
1437                    continue;
1438                }
1439                // Anything at all with an eighty bit float in it, which is the one arm here
1440                // chosen by a type rather than by an opcode, because what makes these different
1441                // is not what they do but where the value is. A `long double` has no register,
1442                // so it has no name in `crate::term` and no rule could bind one: every one of
1443                // these is a group of instructions over a frame slot, written out below.
1444                //
1445                // Last of the arms, so that a call and a return with one of these in them reach
1446                // the convention first and are refused by it, which is the truer answer: what is
1447                // wrong there is where the value has to travel and not that nothing can compute
1448                // it.
1449                _ if self.touches_x87(inst) => {
1450                    self.x87(inst)?;
1451                    continue;
1452                }
1453                _ => {}
1454            }
1455            let matched = matched.ok_or_else(|| self.unsupported(inst))?;
1456            self.emit(inst, &matched)?;
1457            // After it is built rather than when it matched, so that what is recorded is the rules
1458            // this function was lowered by and not the rules something was tried with.
1459            self.fired.mark(matched.rule);
1460        }
1461        // Whichever block the walk ended in rather than the one it started in. The two are the
1462        // same block for every function that does not save a place for a `__builtin_longjmp`, and
1463        // where they differ it is the last of them that the terminator and the arms belong to.
1464        // See [`Self::saves_place`].
1465        let last = self.at.expect("a block is being filled");
1466        self.edges(block, last)?;
1467        // Now that the block is filled, the instruction after each place an assignment was is the
1468        // first one it holds its value at. One with nothing after it, which a block ending in the
1469        // assignment would be, stays unanswered.
1470        if let Some(marks) = self.marks.get_mut(&block) {
1471            for &(before, at, last) in &reached {
1472                let first = match last {
1473                    Some(last) => self.out.next_inst(last),
1474                    None => self.out.insts(at).next(),
1475                };
1476                for mark in marks.iter_mut().filter(|(after, _)| *after == before) {
1477                    mark.1 = first;
1478                }
1479            }
1480        }
1481        Ok(())
1482    }
1483
1484    /// One call, which is built from the convention rather than matched against the table for the
1485    /// same reason the arguments of the function itself are.
1486    ///
1487    /// The arguments are read before the call is built, which is what materializes a constant
1488    /// argument into a register, since no call passes an immediate.
1489    ///
1490    /// A call to a name and a call through an address are both here, and what tells them apart is
1491    /// the opcode rather than whether a callee was recorded, which is the same thing the verifier
1492    /// reads. Through an address the first operand is the address and the arguments are the ones
1493    /// behind it, and everything after that is the same: where each argument goes, where the value
1494    /// comes back and which registers are gone across it are the convention's answers and the
1495    /// convention does not ask what is being called.
1496    fn called(&mut self, inst: Inst) -> Result<(), Unsupported> {
1497        let data = &self.source[inst];
1498        let Extra::Call(info) = data.extra else { return Err(self.unsupported(inst)) };
1499        let info = self.source[info];
1500        let indirect = data.opcode == Opcode::CallIndirect;
1501
1502        let values: Vec<Value> = self.source[data.args].to_vec();
1503        let callee = if indirect {
1504            let &address = values.first().ok_or_else(|| self.unsupported(inst))?;
1505            abi::Callee::Through(self.reg_of(address)?)
1506        } else {
1507            abi::Callee::Named(info.callee.ok_or_else(|| self.unsupported(inst))?)
1508        };
1509
1510        // What the ABI asks of each argument, read out before any of them is, because reading one
1511        // borrows the function this is a table in. The ones the signature names are the signature's
1512        // answer and the ones behind them are the call's, which is where a structure passed to a
1513        // variadic callee by value says that its bytes travel: there is no parameter to say it on.
1514        let signature = &self.source[info.signature];
1515        let variadic = signature.variadic;
1516        let named: Vec<Abi> = signature.params.iter().map(|param| param.abi).collect();
1517        let beyond: Vec<Abi> = self.source[info.varargs].to_vec();
1518        // Every value that comes back and not only the first. A structure small enough to travel
1519        // in registers comes back in up to two of them, and which register each half is in is the
1520        // convention's answer, which is why the whole list goes to the same place the arguments do
1521        // rather than to a rule.
1522        let returns: Vec<Type> = signature.return_types().collect();
1523
1524        let mut args = Vec::with_capacity(values.len());
1525        for (index, value) in values.into_iter().skip(usize::from(indirect)).enumerate() {
1526            let abi = named.get(index).or_else(|| beyond.get(index - named.len()));
1527            let abi = abi.copied().unwrap_or_default();
1528            let ty = self.source[value].ty;
1529            // What travels for an eighty bit value is its bytes, so what the call is handed is
1530            // where they are rather than a register they are in, and there is no register they
1531            // could be in. Everything else about it is a sixteen byte object passed by value and
1532            // is built by the same code.
1533            let reg =
1534                if abi::on_the_stack(ty) { self.x87_slot(value) } else { self.reg_of(value)? };
1535            args.push(abi::Passing { ty, reg, abi });
1536        }
1537        let block = self.at.expect("a block is being filled");
1538        let what = abi::Calling {
1539            callee,
1540            args: &args,
1541            returns: &returns,
1542            variadic,
1543            named: named.len(),
1544            at: self.source.span(inst),
1545        };
1546        let made = abi::call(&mut self.out, block, &what, self.conv, self.selector.abi, self.names)
1547            .map_err(|refused| Unsupported::Call { inst, refused })?;
1548        let calls = &mut self.stack.calls;
1549        *calls = Some(calls.unwrap_or(0).max(made.outgoing));
1550        // An eighty bit value came back on the x87 stack, and the one thing that has to happen
1551        // before anything else touches that stack is taking it off. So the `fstp` goes here, in
1552        // front of everything the block does next, and after it the value is in its slot and is
1553        // read the way every other one is. A complex one is two of them, the real half on top, so
1554        // taking them off in order leaves each in its own slot and the stack empty.
1555        let results: Vec<Value> = self.source[inst].results().collect();
1556        let types: Vec<Type> = results.iter().map(|&result| self.source[result].ty).collect();
1557        if abi::back_on_x87(&types) {
1558            let span = self.source.span(inst);
1559            for result in results {
1560                let into = self.x87_slot(result);
1561                let into = self.through(into);
1562                self.x87_at("fstp_t", span, into);
1563            }
1564            return Ok(());
1565        }
1566        for (result, &reg) in results.into_iter().zip(&made.results) {
1567            self.regs[result.index()] = Some(reg);
1568        }
1569        Ok(())
1570    }
1571
1572    /// The pointer a function returning through memory was handed, or nothing in a function that
1573    /// was not.
1574    ///
1575    /// It is the first parameter and the signature is what says so, since in the IR it is an
1576    /// ordinary pointer and reads like one everywhere in the body. A function with a signature
1577    /// like that and no entry block has nothing to give back and no body to give it back from.
1578    fn sret(&self) -> Option<Value> {
1579        let first = self.source.signature().params.first()?;
1580        if !matches!(first.abi, Abi::Sret { .. }) {
1581            return None;
1582        }
1583        self.source[self.source.entry()?].params.first().copied()
1584    }
1585
1586    /// One `return` the convention has to write, as the place each value has to be in by the end.
1587    ///
1588    /// One pseudo per value, each a read constrained to a return register, which is what a return
1589    /// of one value already is and is the whole of what either does. The `ret` itself comes from
1590    /// the epilogue for both, long after this, because the frame has to be given back first.
1591    ///
1592    /// The two register files are counted separately, so a structure of a `double` and a `long`
1593    /// leaves the `double` in the first vector register and the `long` in the first integer one
1594    /// rather than in the second of either. That is the same walk `rucc_codegen::abi` makes on
1595    /// the other side of the call, which is what makes the two ends agree.
1596    ///
1597    /// A function whose answer went through memory gives back the address it was handed, in front
1598    /// of nothing else, because a signature that returns that way returns nothing else. That the
1599    /// caller already knows the address is not enough: it is allowed to read the register instead,
1600    /// and a caller that does gets whatever the allocator last left there. In a leaf function that
1601    /// is usually the right answer by accident, and one call in the body is enough to make it a
1602    /// wild pointer, which is why this is written rather than left to luck.
1603    ///
1604    /// Where everything goes is worked out before anything is written, so a return this cannot
1605    /// make leaves no half of one behind.
1606    /// Whether what a `return` gives back goes back on the x87 stack, per [`abi::back_on_x87`].
1607    fn gives_back_x87(&self, inst: Inst) -> bool {
1608        let values = &self.source[self.source[inst].args];
1609        let types: Vec<Type> = values.iter().map(|&value| self.source[value].ty).collect();
1610        abi::back_on_x87(&types)
1611    }
1612
1613    fn returned(&mut self, inst: Inst) -> Result<(), Unsupported> {
1614        let values: Vec<Value> = self.source[self.source[inst].args].to_vec();
1615        let (mut ints, mut floats) = (0usize, 0usize);
1616        let mut parts = Vec::with_capacity(values.len() + 1);
1617        // An eighty bit value goes back on the x87 stack, which is where the convention says it is
1618        // and is the one place a value is left rather than put in a register. So the whole of the
1619        // return is an `fld` of its slot, and the stack it leaves the value on is not empty at the
1620        // `ret`, which is the one time in this file that is true and is what the convention asks
1621        // for. What comes after is the epilogue, which gives the frame back and touches nothing in
1622        // the unit. A complex one loads its imaginary half first so that the real half ends up on
1623        // top of it, in `st(0)`, with the imaginary half under it in `st(1)`.
1624        if self.gives_back_x87(inst) && self.sret().is_none() {
1625            let span = self.source.span(inst);
1626            for &value in values.iter().rev() {
1627                let from = self.x87_slot(value);
1628                let from = self.through(from);
1629                self.x87_at("fld_t", span, from);
1630            }
1631            return Ok(());
1632        }
1633        for value in self.sret().into_iter().chain(values) {
1634            let ty = self.source[value].ty;
1635            let at = if crate::term::in_vector_file(ty) { &mut floats } else { &mut ints };
1636            // Why it cannot come back, and not only that it cannot. A type that travels nowhere
1637            // says so itself, and a type that travels perfectly well ran out of registers.
1638            let missing = abi::refuses(ty, self.selector.abi).unwrap_or(Missing::NoRoom);
1639            let name =
1640                (self.selector.abi.ret)(ty, *at).ok_or(Unsupported::Returned { inst, missing })?;
1641            *at += 1;
1642            // The register is the target's answer and not one worked out here, the same as it is
1643            // for a return of one value, so that both halves of a pair and every rule that writes
1644            // half of one are reading the same table.
1645            let opcode =
1646                name.strip_prefix(self.selector.prefix()).ok_or_else(|| self.unsupported(inst))?;
1647            let descs = self.selector.operands(opcode).ok_or_else(|| self.unsupported(inst))?;
1648            let [desc] = descs else { return Err(self.unsupported(inst)) };
1649            parts.push((self.names.intern(name), self.reg_of(value)?, *desc));
1650        }
1651
1652        let block = self.at.expect("a block is being filled");
1653        let span = self.source.span(inst);
1654        for (opcode, reg, desc) in parts {
1655            let operand = mir::Operand {
1656                reg,
1657                class: desc.class,
1658                role: desc.role,
1659                constraint: desc.constraint,
1660            };
1661            self.out.build(block, mir::Opcode::new(opcode)).at(span).operand(operand).finish();
1662        }
1663        Ok(())
1664    }
1665
1666    /// One `alloca`: the bytes it asks for go on the list the frame is laid out from, and the
1667    /// address of them is one instruction.
1668    ///
1669    /// The instruction is a `lea` off the stack pointer, which is the one register that reaches
1670    /// the frame in every function, and its displacement is left at nothing because there is no
1671    /// frame yet. Which instruction is waiting for which local is remembered, and
1672    /// [`crate::finish`] fills the numbers in after [`crate::frame::Frame`] has placed them.
1673    ///
1674    /// There is deliberately no rule for `alloca` and no name for one in [`crate::term`], and
1675    /// that is what stops it being folded into something else. An operand shown as the
1676    /// instruction that computed it is offered to the matcher by its name, so an `alloca` with no
1677    /// name is one no pattern can reach past, and the address it computes is always in a register
1678    /// by the time anything reads it.
1679    fn reserve(&mut self, inst: Inst) -> Result<(), Unsupported> {
1680        let data = &self.source[inst];
1681        // A variable length array carries the size it wants as an operand rather than in the
1682        // instruction, which is the whole of what tells the two apart here.
1683        if let Some(&size) = self.source[data.args].first() {
1684            return self.grow(inst, size);
1685        }
1686        let Extra::Mem(mem) = data.extra else { return Err(self.unsupported(inst)) };
1687        let info = self.source[mem];
1688        let size = u32::try_from(info.size)
1689            .map_err(|_| Unsupported::Dynamic { inst, growing: Growing::Huge })?;
1690        let result = data.first_result.ok_or_else(|| self.unsupported(inst))?;
1691
1692        // At least one, because the frame divides by the alignment and an object with no
1693        // alignment at all is one the front end had nothing to say about rather than one that may
1694        // go anywhere.
1695        let index = self.stack.locals.len();
1696        self.stack.locals.push(Local { size, align: info.align.max(1) });
1697        if let Some(decl) = self.source.mem_decl(mem) {
1698            self.stack.declared.push((index, decl));
1699        }
1700
1701        let block = self.at.expect("a block is being filled");
1702        let reg = self.new_reg(result);
1703        let span = self.source.span(inst);
1704        let lea = self.named(self.selector.frame.lea);
1705        let sp = mir::Operand::read(mir::Reg::physical(self.conv.stack_pointer), self.gpr);
1706        let made =
1707            self.out.build(block, lea).at(span).def(reg, self.gpr).mem(mir::Mem::at(sp)).finish();
1708        self.stack.addresses.push((made, index));
1709        Ok(())
1710    }
1711
1712    /// The other kind of `alloca`: one whose size the function does not know until it runs, which
1713    /// is what a variable length array is.
1714    ///
1715    /// Nothing about it is a slot the frame laid out, because the frame is laid out once and this
1716    /// happens as often as control reaches the declaration. The bytes come off the stack pointer
1717    /// where the declaration stands, which is two instructions:
1718    ///
1719    /// ```text
1720    ///   sub sp, bytes     the stack pointer moves down over the memory, which is what takes it
1721    ///   lea reg, [sp+n]   where the memory starts, which is above the outgoing argument area
1722    /// ```
1723    ///
1724    /// The displacement is left at nothing for the reason the constant kind leaves its own at
1725    /// nothing, and for a different number: that area belongs to the arguments of whatever this
1726    /// function calls, it stays at the bottom of the frame wherever the bottom has moved to, and
1727    /// how big it is is not known until every call in the function has been seen.
1728    ///
1729    /// The bytes are already a multiple of the stack pointer's alignment by the time they arrive,
1730    /// because [`crate::expand::rounds`] rounded them up in the IR, so nothing here has to mask the
1731    /// stack pointer afterwards and the stack pointer stays somewhere a call can be made from.
1732    ///
1733    /// Two instructions here and not always two in the finished function. On a command line that
1734    /// asked for the stack to be touched a page at a time, the subtraction becomes a loop that
1735    /// walks the same distance a page at a time, which [`crate::finish`] writes. That is why the
1736    /// instruction is written down in [`Stack::grown`] as well as left where it is.
1737    ///
1738    /// An array wanting more alignment than the convention leaves the stack pointer with does not
1739    /// reach here asking for it: [`crate::expand::rounds`] gives it the alignment in extra bytes
1740    /// and turns the array into a `ptr_add` of the offset that lands inside them, so what arrives
1741    /// is a block asking for the convention's alignment like any other. The refusal below is what
1742    /// answers IR that came from somewhere other than that pass, since forcing the alignment here
1743    /// would be a second rounding of a register the frame already rounded, and after it no
1744    /// constant reaches the rest of the frame from anywhere. See `Growing` in [`crate::frame`].
1745    fn grow(&mut self, inst: Inst, size: Value) -> Result<(), Unsupported> {
1746        let data = &self.source[inst];
1747        let Extra::Mem(mem) = data.extra else { return Err(self.unsupported(inst)) };
1748        let info = self.source[mem];
1749        if info.align > self.conv.stack_align {
1750            return Err(Unsupported::Dynamic { inst, growing: Growing::Aligned });
1751        }
1752        let result = data.first_result.ok_or_else(|| self.unsupported(inst))?;
1753        let bytes = self.reg_of(size)?;
1754
1755        let block = self.at.expect("a block is being filled");
1756        let span = self.source.span(inst);
1757        let stack = mir::Reg::physical(self.conv.stack_pointer);
1758        let grow = self.named(self.selector.frame.grow);
1759        let took = self
1760            .out
1761            .build(block, grow)
1762            .at(span)
1763            .operand(mir::Operand::write(stack, self.gpr))
1764            .operand(mir::Operand::read(stack, self.gpr))
1765            .operand(mir::Operand::read(bytes, self.gpr))
1766            .finish();
1767        self.stack.grown.push(took);
1768
1769        let reg = self.new_reg(result);
1770        let lea = self.named(self.selector.frame.lea);
1771        let sp = mir::Operand::read(stack, self.gpr);
1772        let made =
1773            self.out.build(block, lea).at(span).def(reg, self.gpr).mem(mir::Mem::at(sp)).finish();
1774        self.stack.dynamic.push(made);
1775        self.stack.grown_at.get_or_insert(inst);
1776        Ok(())
1777    }
1778
1779    /// Where the stack pointer is, kept so that something later can put it back.
1780    ///
1781    /// One move out of the stack pointer and one move into it, which is the whole of what the two
1782    /// halves are. What makes them worth writing is where the front end puts them: a scope holding
1783    /// a variable length array saves the stack pointer as it opens and puts it back as it closes,
1784    /// so a loop declaring one takes its bytes once round rather than once per iteration, and a
1785    /// jump out of the scope gives the bytes back on the way out.
1786    ///
1787    /// The value travels in an ordinary register the allocator hands out, so it may be spilled like
1788    /// any other, and a spill slot in a frame that grows is reached through the frame pointer,
1789    /// which is exactly the register that still means something after the stack pointer has moved.
1790    fn stack_pointer(&mut self, inst: Inst, into: bool) -> Result<(), Unsupported> {
1791        let data = &self.source[inst];
1792        let block = self.at.expect("a block is being filled");
1793        let span = self.source.span(inst);
1794        let stack = mir::Reg::physical(self.conv.stack_pointer);
1795        let mov =
1796            self.selector.frame.moves(self.gpr).expect("a class the target says how to move").mov;
1797        let mov = self.named(mov);
1798        let (write, read) = if into {
1799            let &saved = self.source[data.args].first().ok_or_else(|| self.unsupported(inst))?;
1800            (stack, self.reg_of(saved)?)
1801        } else {
1802            let result = data.first_result.ok_or_else(|| self.unsupported(inst))?;
1803            (self.new_reg(result), stack)
1804        };
1805        self.out
1806            .build(block, mov)
1807            .at(span)
1808            .operand(mir::Operand::write(write, self.gpr))
1809            .operand(mir::Operand::read(read, self.gpr))
1810            .finish();
1811        // Only the write is a move of the stack pointer, and it is the one that makes the frame a
1812        // growing one. A read of it in a function that never writes it back is a function that
1813        // asked where the stack was and did nothing with the answer.
1814        if into {
1815            self.stack.grown_at.get_or_insert(inst);
1816        }
1817        Ok(())
1818    }
1819
1820    /// Whether an instruction has an eighty bit float anywhere in it.
1821    ///
1822    /// Producing one and reading one are the same question here, because what makes one of these
1823    /// different from every other instruction is not the operation but where the value is. A
1824    /// `long double` is on the x87 stack while it is being worked on and in a frame slot the rest
1825    /// of the time, and neither of those is somewhere the operand of a rule could point.
1826    fn touches_x87(&self, inst: Inst) -> bool {
1827        let data = &self.source[inst];
1828        data.results().any(|value| on_x87(self.source[value].ty))
1829            || self.source[data.args].iter().any(|&arg| on_x87(self.source[arg].ty))
1830    }
1831
1832    /// Everything that happens to an eighty bit float, as the group of instructions it is.
1833    ///
1834    /// The first six move one, and every one of those is a load, a store, or a load and a store at
1835    /// two different formats, because that is the whole of what this machine converts with: the
1836    /// x87 has no instruction that turns one thing on its stack into another, so a widening is
1837    /// `fld` of the narrow format and a narrowing is `fstp` of it.
1838    ///
1839    /// The rest work on one, and they are here rather than in a rule for the same reason the six
1840    /// are. An add is a push, a push, the add and a pop, and what passes between those four is the
1841    /// top of a stack nothing allocates from, so there is no value in the middle of the group for
1842    /// a pattern to bind or a replacement to name. The comparison is the same shape with its last
1843    /// two instructions folded into one opcode, which is where the byte it produces comes from.
1844    ///
1845    /// Every group leaves the stack as empty as it found it, which is what `spec/10-backend.md`
1846    /// section 10.8 asks of one and is why nothing in this file has to track a depth: each push
1847    /// below is answered by a pop a line or two later, so no two groups can ever be looking at
1848    /// the same eight registers.
1849    fn x87(&mut self, inst: Inst) -> Result<(), Unsupported> {
1850        match self.source[inst].opcode {
1851            Opcode::Load => self.x87_load(inst),
1852            Opcode::Store => self.x87_store(inst),
1853            Opcode::FPExt => self.x87_widen(inst),
1854            Opcode::FPTrunc => self.x87_narrow(inst),
1855            Opcode::SIToFP => self.x87_from_signed(inst),
1856            Opcode::FPToSI => self.x87_to_signed(inst),
1857            Opcode::FAdd => self.x87_arith(inst, "fadd_p"),
1858            Opcode::FSub => self.x87_arith(inst, "fsubr_p"),
1859            Opcode::FMul => self.x87_arith(inst, "fmul_p"),
1860            Opcode::FDiv => self.x87_arith(inst, "fdivr_p"),
1861            Opcode::FNeg => self.x87_flip(inst),
1862            Opcode::FCmp => self.x87_compare(inst),
1863            Opcode::FConst => self.x87_const(inst),
1864            _ => Err(self.unsupported(inst)),
1865        }
1866    }
1867
1868    /// The eighty bit parameters of a block, copied out of the addresses an edge handed over and
1869    /// into slots of the block's own.
1870    ///
1871    /// What crosses an edge for a value of this type is an address, because the value is sixteen
1872    /// bytes of the frame and no register holds any of it. The block cannot keep that address: a
1873    /// second edge into the same block hands over a second one, and a read after the block would
1874    /// then be a read of whichever edge was taken rather than of one place. So the block has a
1875    /// slot per parameter and the bytes are copied into it here, which is the move on an edge that
1876    /// every other type gets from the allocator.
1877    ///
1878    /// Every load runs before every store and the stores run backwards, so all of the values are
1879    /// on the x87 stack at once and nothing reads a slot another one has already written. That
1880    /// costs nothing in the ordinary case of one parameter and is what makes the back edge of a
1881    /// loop that swaps two of these work. It is also the reason for the limit: the stack is eight
1882    /// deep, and a block with more of these than that is refused rather than copied in an order
1883    /// that could be wrong.
1884    fn settle(&mut self, block: Block, arriving: &[(Value, mir::Reg)]) -> Result<(), Unsupported> {
1885        let Some(&(first, _)) = arriving.first() else { return Ok(()) };
1886        if arriving.len() > X87_DEPTH {
1887            let ty = self.source[first].ty;
1888            return Err(Unsupported::Phi { block, count: arriving.len(), ty });
1889        }
1890        // A block parameter comes from no instruction, so what this points at is the first thing
1891        // in the block, which is where a reader looking for the copy would look.
1892        let first_inst = self.source.insts(block).next();
1893        let span = first_inst.map_or(Span::DUMMY, |it| self.source.span(it));
1894        for &(_, reg) in arriving {
1895            let from = self.through(reg);
1896            self.x87_at("fld_t", span, from);
1897        }
1898        for &(param, _) in arriving.iter().rev() {
1899            let into = self.x87_slot(param);
1900            let into = self.through(into);
1901            self.x87_at("fstp_t", span, into);
1902        }
1903        Ok(())
1904    }
1905
1906    /// The frame slot an eighty bit value lives in, as its address in a fresh register.
1907    ///
1908    /// The slot is the value's for the whole function and is taken the first time somebody asks.
1909    /// The address is worked out again every time, which is a `lea` per use and is deliberate: one
1910    /// address kept in a register from the definition to the last use would hold a general purpose
1911    /// register open across everything in between, and a function with a handful of these in it
1912    /// would spend its registers on addresses of things rather than on things.
1913    fn x87_slot(&mut self, value: Value) -> mir::Reg {
1914        // An argument of the function has a slot already and it is the caller's. The convention
1915        // puts the bytes in the argument area and hands over where they are, so the address that
1916        // arrived is the answer and no second copy of the value is made. Nothing ever writes to a
1917        // value of this type once it exists, so nothing writes to the caller's copy either. A
1918        // parameter of any other block is not this: what arrived there is an address a predecessor
1919        // chose, [`Lowering::settle`] has already copied the bytes out of it, and the slot those
1920        // bytes landed in is the one below.
1921        let entry = self.source.entry();
1922        if let (Def::Param { block, .. }, Some(reg)) =
1923            (self.source[value].def, self.regs[value.index()])
1924        {
1925            if entry == Some(block) {
1926                return reg;
1927            }
1928        }
1929        let index = match self.slots[value.index()] {
1930            Some(index) => index,
1931            None => {
1932                let index = self.stack.locals.len();
1933                self.stack.locals.push(Local { size: X87_BYTES, align: X87_BYTES });
1934                self.slots[value.index()] = Some(index);
1935                index
1936            }
1937        };
1938        let block = self.at.expect("a block is being filled");
1939        self.frame_address(block, index)
1940    }
1941
1942    /// The bytes a value crosses between a register and the x87 stack through, as their address
1943    /// in a fresh register.
1944    fn x87_crossing(&mut self) -> mir::Reg {
1945        let index = match self.crossing {
1946            Some(index) => index,
1947            None => {
1948                let index = self.stack.locals.len();
1949                self.stack.locals.push(Local { size: X87_CROSSING, align: X87_CROSSING });
1950                self.crossing = Some(index);
1951                index
1952            }
1953        };
1954        let block = self.at.expect("a block is being filled");
1955        self.frame_address(block, index)
1956    }
1957
1958    /// The two control words, as the address of the first of them in a fresh register.
1959    fn x87_control(&mut self) -> mir::Reg {
1960        let index = match self.control {
1961            Some(index) => index,
1962            None => {
1963                let index = self.stack.locals.len();
1964                self.stack.locals.push(Local { size: 4, align: 4 });
1965                self.control = Some(index);
1966                index
1967            }
1968        };
1969        let block = self.at.expect("a block is being filled");
1970        self.frame_address(block, index)
1971    }
1972
1973    /// An address held in a register, as the addressing mode that reaches it.
1974    fn through(&self, reg: mir::Reg) -> mir::Mem {
1975        mir::Mem::at(mir::Operand::read(reg, self.gpr))
1976    }
1977
1978    /// One instruction of a group, which names an address and nothing else.
1979    ///
1980    /// Every x87 instruction that moves a value is one of these. What it does to the stack is in
1981    /// the mnemonic rather than in an operand, so there is no register to write down and no
1982    /// register the allocator gets a say in.
1983    fn x87_at(&mut self, name: &str, span: Span, at: mir::Mem) {
1984        let block = self.at.expect("a block is being filled");
1985        let opcode = self.named(name);
1986        self.out.build(block, opcode).at(span).mem(at).finish();
1987    }
1988
1989    /// The one instruction of a group that reaches the program's own memory.
1990    ///
1991    /// A `long double` moves in two instructions with a frame slot at one end of them, and the
1992    /// other end is the address the program wrote. That end is the access, so it is the one that
1993    /// carries what the program said about it, and the trip through the slot is this compiler's
1994    /// own business the way a spill is. See [`Self::carried`].
1995    fn x87_touching(&mut self, name: &str, inst: Inst, at: mir::Mem) {
1996        let block = self.at.expect("a block is being filled");
1997        let opcode = self.named(name);
1998        let (span, flags) = (self.source.span(inst), self.carried(inst));
1999        self.out.build(block, opcode).at(span).flags(flags).mem(at).finish();
2000    }
2001
2002    /// One instruction of a group that names nothing at all.
2003    ///
2004    /// The arithmetic is these. Both of an add's operands are already on the stack when it runs
2005    /// and so is where the answer goes, and the stack is not somewhere an instruction says, so
2006    /// `faddp` has an argument in the assembler's syntax and nothing here for the argument to come
2007    /// from. What it works on is which two pushes came before it, which is a fact about the order
2008    /// of the group and is why the group is written in one place.
2009    fn x87_only(&mut self, name: &str, span: Span) {
2010        let block = self.at.expect("a block is being filled");
2011        let opcode = self.named(name);
2012        self.out.build(block, opcode).at(span).finish();
2013    }
2014
2015    /// A `load` of a `long double`: onto the stack from where it was, and off it into the slot.
2016    ///
2017    /// Two instructions rather than the two general purpose moves the same sixteen bytes would
2018    /// take, because `fld` and `fstp` at this format neither convert nor look: the value goes on
2019    /// in the format it was already in and comes back off in it, so a signalling NaN stays one
2020    /// and nothing is raised. Which is what makes this a copy at all.
2021    fn x87_load(&mut self, inst: Inst) -> Result<(), Unsupported> {
2022        let (args, result) = self.ends(inst)?;
2023        let &address = args.first().ok_or_else(|| self.unsupported(inst))?;
2024        let span = self.source.span(inst);
2025        let from = self.reg_of(address)?;
2026        let from = self.through(from);
2027        let into = self.x87_slot(result);
2028        let into = self.through(into);
2029        self.x87_touching("fld_t", inst, from);
2030        self.x87_at("fstp_t", span, into);
2031        Ok(())
2032    }
2033
2034    /// A `store` of a `long double`: the same pair the other way round.
2035    fn x87_store(&mut self, inst: Inst) -> Result<(), Unsupported> {
2036        let args = self.source[self.source[inst].args].to_vec();
2037        let [value, address] = args[..] else { return Err(self.unsupported(inst)) };
2038        let span = self.source.span(inst);
2039        let from = self.x87_slot(value);
2040        let from = self.through(from);
2041        let into = self.reg_of(address)?;
2042        let into = self.through(into);
2043        self.x87_at("fld_t", span, from);
2044        self.x87_touching("fstp_t", inst, into);
2045        Ok(())
2046    }
2047
2048    /// A `float`, a `double` or an integer becoming a `long double`.
2049    ///
2050    /// Through memory, because the x87 reads memory and nothing else: the value is in a register
2051    /// the machine has and the unit has no way to be handed one, so it is written to the crossing
2052    /// bytes and loaded back at the format that widens it. Every one of these is exact. Sixty four
2053    /// bits of significand and fifteen of exponent hold every `float`, every `double` and every
2054    /// sixty four bit integer outright, so none of the four can round and none can raise.
2055    fn x87_across(
2056        &mut self,
2057        inst: Inst,
2058        put: &'static str,
2059        class: RegClass,
2060        get: &'static str,
2061    ) -> Result<(), Unsupported> {
2062        let (args, result) = self.ends(inst)?;
2063        let &source = args.first().ok_or_else(|| self.unsupported(inst))?;
2064        let span = self.source.span(inst);
2065        let value = self.reg_of(source)?;
2066        let across = self.x87_crossing();
2067        let across = self.through(across);
2068        let into = self.x87_slot(result);
2069        let into = self.through(into);
2070
2071        let block = self.at.expect("a block is being filled");
2072        let store = self.named(put);
2073        self.out.build(block, store).at(span).uses(value, class).mem(across).finish();
2074        self.x87_at(get, span, across);
2075        self.x87_at("fstp_t", span, into);
2076        Ok(())
2077    }
2078
2079    /// A `long double` becoming a `float`, a `double` or an integer.
2080    ///
2081    /// Through memory for the reason above and in the same three instructions backwards. The two
2082    /// that go to a float round to nearest, which is what the control word says unless somebody
2083    /// has changed it and is what C wants. The two that go to an integer do not, which is why they
2084    /// do not come here.
2085    fn x87_back(
2086        &mut self,
2087        inst: Inst,
2088        put: &'static str,
2089        get: &'static str,
2090        class: RegClass,
2091    ) -> Result<(), Unsupported> {
2092        let (args, result) = self.ends(inst)?;
2093        let &source = args.first().ok_or_else(|| self.unsupported(inst))?;
2094        let span = self.source.span(inst);
2095        let from = self.x87_slot(source);
2096        let from = self.through(from);
2097        let across = self.x87_crossing();
2098        let across = self.through(across);
2099
2100        self.x87_at("fld_t", span, from);
2101        self.x87_at(put, span, across);
2102        let block = self.at.expect("a block is being filled");
2103        let reg = self.new_reg(result);
2104        let load = self.named(get);
2105        self.out.build(block, load).at(span).def(reg, class).mem(across).finish();
2106        Ok(())
2107    }
2108
2109    /// An `fpext` up to a `long double`, which is the only direction this machine has one in.
2110    fn x87_widen(&mut self, inst: Inst) -> Result<(), Unsupported> {
2111        let sse = self.conv.sse_class;
2112        match self.source[self.narrow(inst)?].ty.bits() {
2113            32 => self.x87_across(inst, "movss_mr", sse, "fld_s"),
2114            64 => self.x87_across(inst, "movsd_mr", sse, "fld_l"),
2115            _ => Err(self.unsupported(inst)),
2116        }
2117    }
2118
2119    /// An `fptrunc` down from a `long double`, which is the other direction of the same.
2120    fn x87_narrow(&mut self, inst: Inst) -> Result<(), Unsupported> {
2121        let sse = self.conv.sse_class;
2122        let result = self.source[inst].first_result.ok_or_else(|| self.unsupported(inst))?;
2123        match self.source[result].ty.bits() {
2124            32 => self.x87_back(inst, "fstp_s", "movss_rm", sse),
2125            64 => self.x87_back(inst, "fstp_l", "movsd_rm", sse),
2126            _ => Err(self.unsupported(inst)),
2127        }
2128    }
2129
2130    /// A `sitofp` up to a `long double`.
2131    ///
2132    /// Thirty two bits and sixty four, and nothing narrower, because C widens an integer to `int`
2133    /// before it converts one and the front end writes that widening down. An unsigned integer is
2134    /// not here at all: `fild` reads its operand as signed, so a value above the signed range
2135    /// comes back short by two to the sixty fourth and has to be added back, which is arithmetic
2136    /// rather than a move and waits with the rest of it.
2137    fn x87_from_signed(&mut self, inst: Inst) -> Result<(), Unsupported> {
2138        let gpr = self.gpr;
2139        match self.source[self.narrow(inst)?].ty.bits() {
2140            32 => self.x87_across(inst, "mov_mr_32", gpr, "fild_l"),
2141            64 => self.x87_across(inst, "mov_mr_64", gpr, "fild_ll"),
2142            _ => Err(self.unsupported(inst)),
2143        }
2144    }
2145
2146    /// An `fptosi` down from a `long double`, which is the one conversion here with no single
2147    /// instruction behind it.
2148    ///
2149    /// C cuts towards zero and the unit rounds the way its control word says, so the store that
2150    /// takes the value off the stack is wrapped in the control word being saved, changed and put
2151    /// back. Five instructions around the one that does the work, and three more moving the word
2152    /// through a register, because this machine has no way to OR a constant into memory at this
2153    /// width. The unit has a shorter answer in `fisttp`, and `spec/10-backend.md` section 10.8
2154    /// says why it is not used: it is SSE3, the x86-64 baseline is not, and there is nothing here
2155    /// that can gate an instruction on a feature yet.
2156    fn x87_to_signed(&mut self, inst: Inst) -> Result<(), Unsupported> {
2157        let (args, result) = self.ends(inst)?;
2158        let &source = args.first().ok_or_else(|| self.unsupported(inst))?;
2159        let (put, get) = match self.source[result].ty.bits() {
2160            32 => ("fistp_l", "mov_rm_32"),
2161            64 => ("fistp_ll", "mov_rm_64"),
2162            _ => return Err(self.unsupported(inst)),
2163        };
2164        let span = self.source.span(inst);
2165        let gpr = self.gpr;
2166        let from = self.x87_slot(source);
2167        let from = self.through(from);
2168        let across = self.x87_crossing();
2169        let across = self.through(across);
2170        let control = self.x87_control();
2171        let saved = self.through(control).plus(0);
2172        let cut = self.through(control).plus(2);
2173
2174        // The word the unit has now, into the first of the two slots and into a register, with the
2175        // rounding field turned to truncate on the way to the second.
2176        self.x87_at("fnstcw", span, saved);
2177        let block = self.at.expect("a block is being filled");
2178        let was = self.out.new_vreg(gpr);
2179        let read = self.named("mov_rm_16");
2180        self.out.build(block, read).at(span).def(was, gpr).mem(saved).finish();
2181        let now = self.out.new_vreg(gpr);
2182        let set = self.named("or_ri_16");
2183        // Two address, which is written out here rather than taken from the two shorthands
2184        // because the shorthands leave an operand unconstrained: this machine ORs into the
2185        // register it read, so the two have to be the same one and only the constraint says so.
2186        self.out
2187            .build(block, set)
2188            .at(span)
2189            .operand(mir::Operand::write(now, gpr).with(Constraint::Reuse(1)))
2190            .operand(mir::Operand::read(was, gpr))
2191            .imm(X87_TRUNCATE)
2192            .finish();
2193        let write = self.named("mov_mr_16");
2194        self.out.build(block, write).at(span).uses(now, gpr).mem(cut).finish();
2195
2196        // The conversion itself, under the changed word, and then the word the unit had put back
2197        // before anything else runs.
2198        self.x87_at("fldcw", span, cut);
2199        self.x87_at("fld_t", span, from);
2200        self.x87_at(put, span, across);
2201        self.x87_at("fldcw", span, saved);
2202
2203        let block = self.at.expect("a block is being filled");
2204        let reg = self.new_reg(result);
2205        let load = self.named(get);
2206        self.out.build(block, load).at(span).def(reg, gpr).mem(across).finish();
2207        Ok(())
2208    }
2209
2210    /// A constant of this type, as the bits of it written into its slot.
2211    ///
2212    /// No x87 instruction at all, which is the surprise here. A slot holding an eighty bit value is
2213    /// the value, so a constant is ten bytes put where the value lives, and the unit never has to
2214    /// see it: whatever reads it will `fld` it out of the slot the way it reads any other one.
2215    ///
2216    /// Ten bytes in two goes, because the machine stores eight at a time and there is no store of
2217    /// an immediate to memory, so each half is put in a register first. The six bytes above the ten
2218    /// are left alone, since nothing reads them: they are the padding that makes the type sixteen
2219    /// wide and they are unspecified in the psABI rather than zero.
2220    ///
2221    /// The other way is a constant pool, an `fldt` of a symbol, and a relocation, which is what a
2222    /// compiler with somewhere to put a literal does. This back end has nowhere to put one yet, and
2223    /// four instructions in the frame is what that costs until it does.
2224    fn x87_const(&mut self, inst: Inst) -> Result<(), Unsupported> {
2225        let Extra::Imm(imm) = self.source[inst].extra else { return Err(self.unsupported(inst)) };
2226        let result = self.source[inst].first_result.ok_or_else(|| self.unsupported(inst))?;
2227        let bits = self.source[imm].bits();
2228        let span = self.source.span(inst);
2229        let gpr = self.gpr;
2230        let slot = self.x87_slot(result);
2231        let low = self.through(slot).plus(0);
2232        let high = self.through(slot).plus(8);
2233
2234        let block = self.at.expect("a block is being filled");
2235        for (bytes, at, into) in
2236            [(bits as u64 as i64, low, "64"), (((bits >> 64) & 0xffff) as i64, high, "16")]
2237        {
2238            let held = self.out.new_vreg(gpr);
2239            let put = self.named(&format!("mov_ri_{into}"));
2240            self.out.build(block, put).at(span).def(held, gpr).imm(bytes).finish();
2241            let store = self.named(&format!("mov_mr_{into}"));
2242            self.out.build(block, store).at(span).uses(held, gpr).mem(at).finish();
2243        }
2244        Ok(())
2245    }
2246
2247    /// One arithmetic instruction on two eighty bit values, as the four it takes.
2248    ///
2249    /// The left operand is pushed first and the right one on top of it, so the left ends up
2250    /// underneath and the answer wanted is the one below against the top in that order. Which of
2251    /// the two mnemonics computes that is a question about the spelling rather than about the
2252    /// machine, and the two spellings disagree. Intel's `FSUBP ST(i), ST(0)` is `ST(i) - ST(0)`
2253    /// and is `DE E8+i`, and AT&T's `fsubp` is `DE E0+i`, which is the other subtraction. This
2254    /// compiler writes AT&T and encodes what gas encodes, so what it asks for here is `fsubr_p`
2255    /// and `fdivr_p`, and the `r` is not a reversal of anything the code generator decided.
2256    ///
2257    /// An addition and a multiplication have one form each and do not care, which is why a test
2258    /// that reads the mnemonic back would not have caught this and one that computes a subtraction
2259    /// and checks the answer does.
2260    ///
2261    /// The answer is left where the deeper of the two was and the shallower is gone, which is what
2262    /// the `p` on the mnemonic means, so one push has already been paid back by the time the
2263    /// `fstp` runs and the stack is level again after it.
2264    ///
2265    /// Nothing here is folded and nothing is reused. Two values that are the same value get two
2266    /// pushes of the same slot, and an operand that was just computed is read back out of the slot
2267    /// it was written to rather than left on the stack, which costs a store and a load per
2268    /// instruction in an expression. Keeping a partial result on the stack across the next
2269    /// instruction's operands means knowing how deep the stack is at every point in the block, and
2270    /// that is a different thing from writing a group.
2271    fn x87_arith(&mut self, inst: Inst, with: &'static str) -> Result<(), Unsupported> {
2272        let (args, result) = self.ends(inst)?;
2273        let [left, right] = args[..] else { return Err(self.unsupported(inst)) };
2274        let span = self.source.span(inst);
2275        let left = self.x87_slot(left);
2276        let left = self.through(left);
2277        let right = self.x87_slot(right);
2278        let right = self.through(right);
2279        let into = self.x87_slot(result);
2280        let into = self.through(into);
2281        self.x87_at("fld_t", span, left);
2282        self.x87_at("fld_t", span, right);
2283        self.x87_only(with, span);
2284        self.x87_at("fstp_t", span, into);
2285        Ok(())
2286    }
2287
2288    /// A negation, which is a push, the sign bit turned over and a pop.
2289    ///
2290    /// `fchs` does not read the value as a number, so this is right for a zero, for an infinity
2291    /// and for a NaN, and it raises nothing on any of them. Which is what C asks of a negation and
2292    /// is not what subtracting from zero would give: `0.0L - x` is a different answer at a
2293    /// negative zero and a signalling one at a NaN.
2294    fn x87_flip(&mut self, inst: Inst) -> Result<(), Unsupported> {
2295        let (args, result) = self.ends(inst)?;
2296        let &source = args.first().ok_or_else(|| self.unsupported(inst))?;
2297        let span = self.source.span(inst);
2298        let from = self.x87_slot(source);
2299        let from = self.through(from);
2300        let into = self.x87_slot(result);
2301        let into = self.through(into);
2302        self.x87_at("fld_t", span, from);
2303        self.x87_only("fchs", span);
2304        self.x87_at("fstp_t", span, into);
2305        Ok(())
2306    }
2307
2308    /// A comparison of two eighty bit values, as the two pushes and the one opcode that reads them.
2309    ///
2310    /// The right operand is pushed first and the left one on top of it, which is the other way
2311    /// round from the arithmetic and is because `fucomip` asks about the top against what is under
2312    /// it: the comparison this machine can do is the top's, so the value the predicate is about
2313    /// has to be the top. The pop that gets the loser off the stack and the byte that reads the
2314    /// flags are both inside the opcode, since what passes between those and the comparison is the
2315    /// flags and the flags are not something anything here can name.
2316    ///
2317    /// Which of the ten opcodes, and which way round, is the same table the vector comparisons
2318    /// match against in `rules/x86-64.rules`, and it has to stay the same table: a predicate that
2319    /// picked a different condition here than there would be a `long double` comparison that
2320    /// disagreed with the `double` comparison of the same two numbers, which is the one thing a
2321    /// wider format is not allowed to do.
2322    ///
2323    /// The always false and the always true are refused rather than folded into a constant,
2324    /// because a comparison this machine never has to do is one the optimizer should have removed
2325    /// and an instruction here that quietly agreed with it would hide that it did not.
2326    fn x87_compare(&mut self, inst: Inst) -> Result<(), Unsupported> {
2327        let Extra::FloatPred(pred) = self.source[inst].extra else {
2328            return Err(self.unsupported(inst));
2329        };
2330        let (args, result) = self.ends(inst)?;
2331        let [left, right] = args[..] else { return Err(self.unsupported(inst)) };
2332        // Two of the fourteen need a second byte and an instruction to put the two together,
2333        // because they are two conditions at once: an ordered equal is equal and not unordered,
2334        // and an unordered not equal is either. The opcode carries all of that and says here only
2335        // that it writes somewhere else as well.
2336        let (name, reversed, both) = match pred {
2337            FloatPred::Ogt => ("fucomip_set_a", false, false),
2338            FloatPred::Oge => ("fucomip_set_ae", false, false),
2339            FloatPred::Olt => ("fucomip_set_a", true, false),
2340            FloatPred::Ole => ("fucomip_set_ae", true, false),
2341            FloatPred::One => ("fucomip_set_ne", false, false),
2342            FloatPred::Ord => ("fucomip_set_np", false, false),
2343            FloatPred::Uno => ("fucomip_set_p", false, false),
2344            FloatPred::Ueq => ("fucomip_set_e", false, false),
2345            FloatPred::Ult => ("fucomip_set_b", false, false),
2346            FloatPred::Ule => ("fucomip_set_be", false, false),
2347            FloatPred::Ugt => ("fucomip_set_b", true, false),
2348            FloatPred::Uge => ("fucomip_set_be", true, false),
2349            FloatPred::Oeq => ("fucomip_set_e_and_np", false, true),
2350            FloatPred::Une => ("fucomip_set_ne_or_p", false, true),
2351            FloatPred::False | FloatPred::True => return Err(self.unsupported(inst)),
2352        };
2353        let (top, under) = if reversed { (right, left) } else { (left, right) };
2354
2355        let span = self.source.span(inst);
2356        let gpr = self.gpr;
2357        let under = self.x87_slot(under);
2358        let under = self.through(under);
2359        let top = self.x87_slot(top);
2360        let top = self.through(top);
2361        self.x87_at("fld_t", span, under);
2362        self.x87_at("fld_t", span, top);
2363
2364        let block = self.at.expect("a block is being filled");
2365        let reg = self.new_reg(result);
2366        // Taken before the instruction is started rather than inside it, since both come from the
2367        // same function being built and only one thing at a time may be adding to it.
2368        let spare = both.then(|| self.out.new_vreg(gpr));
2369        let opcode = self.named(name);
2370        let mut build = self.out.build(block, opcode).at(span).def(reg, gpr);
2371        if let Some(spare) = spare {
2372            build = build.def(spare, gpr);
2373        }
2374        build.finish();
2375        Ok(())
2376    }
2377
2378    /// The operands and the one result of an instruction that has exactly one.
2379    fn ends(&self, inst: Inst) -> Result<(&'a [Value], Value), Unsupported> {
2380        let data = &self.source[inst];
2381        let result = data.first_result.ok_or_else(|| self.unsupported(inst))?;
2382        Ok((&self.source[data.args], result))
2383    }
2384
2385    /// The operand of a conversion, which is the end of it that is not the `long double`.
2386    fn narrow(&self, inst: Inst) -> Result<Value, Unsupported> {
2387        let args = &self.source[self.source[inst].args];
2388        args.first().copied().ok_or_else(|| self.unsupported(inst))
2389    }
2390
2391    /// One `va_start`, as the fields of the list it was handed.
2392    ///
2393    /// On the four field list, two of them are numbers this already knows, and each costs an
2394    /// instruction to put in a register before it can be stored, because the machine here has no
2395    /// store of an immediate to memory. The other two are addresses in the frame, and each is a
2396    /// `lea` [`crate::finish`] finishes: the save area is one of the function's own stack objects,
2397    /// and the caller's argument area is where the parameters that had no register came from, which
2398    /// is the same place and the same fixup a parameter past the sixth already uses.
2399    ///
2400    /// On the list that is a pointer it is the second of those four and nothing else, since the
2401    /// whole of what that list says is where the walk is and the walk starts at the first argument
2402    /// the signature does not name. One `lea` and one store.
2403    ///
2404    /// What is written is exactly the fields [`crate::varargs`] describes, in the order they are
2405    /// laid out, so that reading this beside that table is the whole of the check.
2406    fn va_start(&mut self, inst: Inst) -> Result<(), Unsupported> {
2407        let Some(&list) = self.source[self.source[inst].args].first() else {
2408            return Err(self.unsupported(inst));
2409        };
2410        let started = self.varargs.ok_or_else(|| self.unsupported(inst))?;
2411        let list = self.reg_of(list)?;
2412        let block = self.at.expect("a block is being filled");
2413        let span = self.source.span(inst);
2414
2415        let (save, incoming) = match started {
2416            Varargs::Pointer { incoming } => (None, incoming),
2417            Varargs::Fields { save, incoming, integers, floats } => {
2418                let counts = [(varargs::GP_OFFSET, integers), (varargs::FP_OFFSET, floats)];
2419                for (at, count) in counts {
2420                    self.store_small(list, at, i64::from(count), span);
2421                }
2422                (Some(save), incoming)
2423            }
2424            Varargs::Aapcs { save, incoming, integers_end, floats_end, integers, floats } => {
2425                let counts =
2426                    [(varargs::aapcs::GR_OFFS, integers), (varargs::aapcs::VR_OFFS, floats)];
2427                for (at, count) in counts {
2428                    self.store_small(list, at, i64::from(count), span);
2429                }
2430                let overflow = self.overflow(block, incoming, span);
2431                let integers_top = self.frame_address_plus(block, save, integers_end);
2432                let floats_top = self.frame_address_plus(block, save, floats_end);
2433                let fields = [
2434                    (varargs::aapcs::STACK, overflow),
2435                    (varargs::aapcs::GR_TOP, integers_top),
2436                    (varargs::aapcs::VR_TOP, floats_top),
2437                ];
2438                for (at, held) in fields {
2439                    self.store_word(list, at, held, span);
2440                }
2441                return Ok(());
2442            }
2443        };
2444
2445        // At the front of the list when that address is the whole of it, and at the field the
2446        // layout gives it when there are four, with the save area behind it.
2447        let overflow = self.overflow(block, incoming, span);
2448        let fields = match save {
2449            None => vec![(0, overflow)],
2450            Some(save) => {
2451                let save = self.frame_address(block, save);
2452                vec![(varargs::OVERFLOW, overflow), (varargs::SAVE_AREA, save)]
2453            }
2454        };
2455        for (at, held) in fields {
2456            self.store_word(list, at, held, span);
2457        }
2458        Ok(())
2459    }
2460
2461    /// The first argument the signature did not name, which is as far up the caller's argument
2462    /// area as the ones it did name reached. Nothing here knows where that area is, so the distance
2463    /// is recorded the way a parameter read out of it is and finished with it.
2464    fn overflow(&mut self, block: mir::Block, incoming: u32, span: Span) -> mir::Reg {
2465        let overflow = self.out.new_vreg(self.gpr);
2466        let lea = self.named(self.selector.frame.lea);
2467        let sp = mir::Operand::read(mir::Reg::physical(self.conv.stack_pointer), self.gpr);
2468        let made = self
2469            .out
2470            .build(block, lea)
2471            .at(span)
2472            .def(overflow, self.gpr)
2473            .mem(mir::Mem::at(sp))
2474            .finish();
2475        self.stack.arguments.push((made, incoming));
2476        overflow
2477    }
2478
2479    /// Writes a small constant into a 32 bit field of a list.
2480    fn store_small(&mut self, list: mir::Reg, at: i64, value: i64, span: Span) {
2481        let block = self.at.expect("a block is being filled");
2482        let held = self.out.new_vreg(self.gpr);
2483        let load = mir::Opcode::new(self.names.intern(self.selector.abi.small));
2484        self.out.build(block, load).at(span).def(held, self.gpr).imm(value).finish();
2485
2486        let head = (self.selector.abi.store)(Type::int(32)).expect("a store of a word");
2487        let store = mir::Opcode::new(self.names.intern(head));
2488        let mem = self.field(list, at);
2489        self.out.build(block, store).at(span).uses(held, self.gpr).mem(mem).finish();
2490    }
2491
2492    /// Writes an address into a pointer field of a list.
2493    fn store_word(&mut self, list: mir::Reg, at: i64, held: mir::Reg, span: Span) {
2494        let block = self.at.expect("a block is being filled");
2495        let head = (self.selector.abi.store)(Type::int(64)).expect("a store of an address");
2496        let store = mir::Opcode::new(self.names.intern(head));
2497        let mem = self.field(list, at);
2498        self.out.build(block, store).at(span).uses(held, self.gpr).mem(mem).finish();
2499    }
2500
2501    /// One field of a list, as the addressing mode that reaches it.
2502    fn field(&self, list: mir::Reg, at: i64) -> mir::Mem {
2503        let base = mir::Operand::read(list, self.gpr);
2504        mir::Mem::at(base).plus(i32::try_from(at).expect("a field of a list is a small offset"))
2505    }
2506
2507    /// The address of a name: one `lea` off the instruction pointer, with the name on it.
2508    ///
2509    /// That is x86-64, and [`Selector::symbols`] is what says so. AArch64 writes the same thing as
2510    /// an `adrp` of the page and an `add` of the low twelve bits, which is one opcode with the name
2511    /// as its own symbol and no addressing mode, and the table read is an `adrp` and an `ldr`.
2512    ///
2513    /// The same instruction an `alloca` gets and for a related reason. An address that is not in
2514    /// the program is a `lea` of an addressing mode that names no register, and the mode carries
2515    /// the symbol so that [`rucc_asm`] can write it relative to `%rip` and leave the relocation
2516    /// for the assembler. Both halves of that already existed: the printer writes `sym(%rip)` and
2517    /// the encoder emits the relocation, because a call to a name the file does not define needed
2518    /// them first.
2519    ///
2520    /// One `mov` and not one `lea` when the name is one [`Elsewhere`] holds, because the distance
2521    /// the `lea` adds to the instruction pointer is a number only a link that puts the name in
2522    /// this program can work out, and the address of a function this file merely declares is not
2523    /// such a number. The load reads the address out of the slot the linker fills in instead. The
2524    /// linker turns it back into the `lea` when the name turns out to have been here all along,
2525    /// so this is not slower in the case that was already right.
2526    ///
2527    /// There is deliberately no name for this in [`crate::term`], which is what stops the address
2528    /// being folded into the instruction that reads it. Folding it is the right thing to do and
2529    /// is what turns a load of a global from two instructions into one, but it is a separate
2530    /// question about addressing modes and issue #282 is it. Until then the address is in a
2531    /// register before anything uses it, which is correct and one instruction longer.
2532    ///
2533    /// What this does not do is give the name anything to refer to. A module carries its globals
2534    /// and nothing writes them out, so a file that defines the variable it reads compiles to a
2535    /// reference the linker cannot resolve. Issue #293 is the other half.
2536    ///
2537    /// A thread-local variable is neither of the two above and is [`Self::thread_address`].
2538    fn address_of(&mut self, inst: Inst) -> Result<(), Unsupported> {
2539        let data = &self.source[inst];
2540        let Extra::Symbol(symbol) = data.extra else { return Err(self.unsupported(inst)) };
2541        let result = data.first_result.ok_or_else(|| self.unsupported(inst))?;
2542        if self.elsewhere.thread(symbol) {
2543            return self.thread_address(inst, symbol, result);
2544        }
2545
2546        let block = self.at.expect("a block is being filled");
2547        let reg = self.new_reg(result);
2548        let span = self.source.span(inst);
2549        let far = self.elsewhere.holds(symbol);
2550        let symbols = self.selector.symbols;
2551        match if far { symbols.far } else { symbols.near } {
2552            Reach::Mode(name) => {
2553                let mem = if far { mir::Mem::got(symbol) } else { mir::Mem::of(symbol) };
2554                let opcode = self.named(name);
2555                self.out.build(block, opcode).at(span).def(reg, self.gpr).mem(mem).finish();
2556            }
2557            Reach::Own(name) => {
2558                let opcode = self.named(name);
2559                self.out.build(block, opcode).at(span).def(reg, self.gpr).symbol(symbol).finish();
2560            }
2561        }
2562        Ok(())
2563    }
2564
2565    /// The address of a thread-local variable, which is this thread's copy of it.
2566    ///
2567    /// Neither instruction the ordinary case writes would mean anything here. There is no distance
2568    /// to the variable for a `lea` to add, because there is no variable: there is one copy of it per
2569    /// thread and they are at different addresses, so a link asked for the distance to the name
2570    /// refuses rather than picking one. And there is no address for a table slot to hold either, for
2571    /// the same reason.
2572    ///
2573    /// What is the same in every thread is where the variable sits inside the block of storage a
2574    /// thread gets, so that offset is what the link writes down, and the address of the running
2575    /// thread's block is what turns it into an address. x86-64 keeps that address in `%fs`, at the
2576    /// front of the block, so the whole of this is three instructions:
2577    ///
2578    /// ```text
2579    /// movq  x@gottpoff(%rip), %off   # how far into the block x sits, which the link fills in
2580    /// movq  %fs:0, %tp               # where this thread's block is, which only the machine knows
2581    /// addq  %tp, %off                # this thread's copy of x
2582    /// ```
2583    ///
2584    /// That is the initial exec model. It is one instruction longer than what gcc writes at `-O2`
2585    /// in an executable, which folds the addition into the instruction that uses the address, and
2586    /// the difference is issue #282 rather than anything about threads: nothing here folds an
2587    /// address into its reader yet. The link relaxes the first instruction into an immediate when it
2588    /// is making an executable, since it lays the blocks out and therefore knows the number, so the
2589    /// table slot costs nothing in the case that is common.
2590    ///
2591    /// It is not the most general model. A library loaded by `dlopen` gets its storage after the
2592    /// program is already running, and the block this reaches was laid out before it started, so
2593    /// the loader has to find room in that block for the library's variables. glibc keeps a little
2594    /// spare room for exactly this and a library that fits in it loads and runs; one that does not
2595    /// fails to load, with a message saying so. The model with no such limit calls `__tls_get_addr`
2596    /// and is what gcc writes under `-fPIC` by default, and it is issue #1104.
2597    ///
2598    /// So this is the model gcc writes under `-ftls-model=initial-exec`: right for an executable,
2599    /// right for a library the program is linked against, and a load that either works or is
2600    /// refused out loud for a library something opens later. What it is never is quietly wrong.
2601    ///
2602    /// AArch64 Linux is the same three steps. The slot is reached with `adrp` and `ldr` against
2603    /// `:gottprel:`, the thread pointer is `tpidr_el0` read with `mrs`, and the add has three
2604    /// operands. Apple's platforms reach a thread-local variable through a descriptor call instead,
2605    /// which is [`Self::thread_descriptor`].
2606    fn thread_address(
2607        &mut self,
2608        inst: Inst,
2609        symbol: Symbol,
2610        result: Value,
2611    ) -> Result<(), Unsupported> {
2612        if self.elsewhere.described() {
2613            return self.thread_descriptor(inst, symbol, result);
2614        }
2615        let block = self.at.expect("a block is being filled");
2616        let span = self.source.span(inst);
2617        let gpr = self.gpr;
2618
2619        let offset = self.out.new_vreg(gpr);
2620        match self.selector.symbols.thread {
2621            Reach::Mode(name) => {
2622                let load = self.named(name);
2623                let mem = mir::Mem::thread(symbol);
2624                self.out.build(block, load).at(span).def(offset, gpr).mem(mem).finish();
2625            }
2626            Reach::Own(name) => {
2627                let load = self.named(name);
2628                self.out.build(block, load).at(span).def(offset, gpr).symbol(symbol).finish();
2629            }
2630        }
2631        let pointer = self.out.new_vreg(gpr);
2632        self.read_thread_pointer(block, span, pointer);
2633
2634        // Two address on x86-64, for the reason `x87_to_int` gives: that machine adds into the
2635        // register it read, and only the constraint says the two are the same one.
2636        let reg = self.new_reg(result);
2637        let jumps = self.selector.jumps;
2638        let add = self.named(jumps.add);
2639        let written = mir::Operand::write(reg, gpr);
2640        let written = if jumps.two_address { written.with(Constraint::Reuse(1)) } else { written };
2641        self.out
2642            .build(block, add)
2643            .at(span)
2644            .operand(written)
2645            .operand(mir::Operand::read(offset, gpr))
2646            .operand(mir::Operand::read(pointer, gpr))
2647            .finish();
2648        Ok(())
2649    }
2650
2651    /// A thread-local variable on Mach-O, which is a call.
2652    ///
2653    /// The slot the machine's thread load reads holds the address of the variable's descriptor
2654    /// there, `_v@TLVP` on x86-64 and `_v@TLVPPAGE` with `_v@TLVPPAGEOFF` on AArch64. The first
2655    /// word of the descriptor is the function that finds this thread's copy, and it takes the
2656    /// descriptor's address as its one argument and gives back the copy's address. That is the
2657    /// sequence clang writes on both machines.
2658    ///
2659    /// The call is built as an ordinary call through an address, so it costs what any call costs:
2660    /// everything the convention does not preserve is taken to be gone across it. Apple's function
2661    /// keeps more than that, all but the result and the two scratch registers on AArch64, and
2662    /// taking the fewer registers as gone would be faster. What this gives up is speed, and a
2663    /// function that reads a thread-local is no longer a leaf.
2664    fn thread_descriptor(
2665        &mut self,
2666        inst: Inst,
2667        symbol: Symbol,
2668        result: Value,
2669    ) -> Result<(), Unsupported> {
2670        let block = self.at.expect("a block is being filled");
2671        let span = self.source.span(inst);
2672        let gpr = self.gpr;
2673
2674        let descriptor = self.out.new_vreg(gpr);
2675        match self.selector.symbols.thread {
2676            Reach::Mode(name) => {
2677                let load = self.named(name);
2678                let mem = mir::Mem::thread(symbol);
2679                self.out.build(block, load).at(span).def(descriptor, gpr).mem(mem).finish();
2680            }
2681            Reach::Own(name) => {
2682                let load = self.named(name);
2683                let build = self.out.build(block, load).at(span);
2684                build.def(descriptor, gpr).symbol(symbol).finish();
2685            }
2686        }
2687        let finder = self.out.new_vreg(gpr);
2688        let word = (self.selector.abi.load)(Type::PTR).ok_or_else(|| self.unsupported(inst))?;
2689        let word = mir::Opcode::new(self.names.intern(word));
2690        let mem = mir::Mem::at(mir::Operand::read(descriptor, gpr));
2691        self.out.build(block, word).at(span).def(finder, gpr).mem(mem).finish();
2692
2693        let args = [abi::Passing { ty: Type::PTR, reg: descriptor, abi: Abi::default() }];
2694        let what = abi::Calling {
2695            callee: abi::Callee::Through(finder),
2696            args: &args,
2697            returns: &[Type::PTR],
2698            variadic: false,
2699            named: 1,
2700            at: span,
2701        };
2702        let made = abi::call(&mut self.out, block, &what, self.conv, self.selector.abi, self.names)
2703            .map_err(|refused| Unsupported::Call { inst, refused })?;
2704        let calls = &mut self.stack.calls;
2705        *calls = Some(calls.unwrap_or(0).max(made.outgoing));
2706        let &[reg] = &made.results[..] else { return Err(self.unsupported(inst)) };
2707        self.regs[result.index()] = Some(reg);
2708        Ok(())
2709    }
2710
2711    /// Refuses the thread pointer where it is not written, which is Mach-O. Apple keeps it in a
2712    /// different register from the one Linux does on both machines, and nothing written for it
2713    /// has been checked on one.
2714    fn threads_written(&self, inst: Inst) -> Result<(), Unsupported> {
2715        if self.elsewhere.described() {
2716            return Err(Unsupported::Unported { inst: Some(inst), what: Unported::Thread });
2717        }
2718        Ok(())
2719    }
2720
2721    /// The front of this thread's block into `reg`.
2722    ///
2723    /// On x86-64 that is the one thing no instruction can work out: `%fs` is not a register a
2724    /// program can read, and what it points at is a word holding its own address, so reading
2725    /// through it at zero is how the address is come by. AArch64 keeps it in `tpidr_el0`, which
2726    /// `mrs` reads.
2727    fn read_thread_pointer(&mut self, block: mir::Block, span: Span, reg: mir::Reg) {
2728        let gpr = self.gpr;
2729        match self.selector.symbols.pointer {
2730            Pointer::Segment(name, segment) => {
2731                let load = self.named(name);
2732                let at = mir::Mem::in_segment(segment, 0);
2733                self.out.build(block, load).at(span).def(reg, gpr).mem(at).finish();
2734            }
2735            Pointer::Own(name) => {
2736                let read = self.named(name);
2737                self.out.build(block, read).at(span).def(reg, gpr).finish();
2738            }
2739        }
2740    }
2741
2742    /// `&&label`, GNU's address of a label, which is the same `lea` a global gets against a place
2743    /// in this same function.
2744    ///
2745    /// What the two have in common is the whole of the instruction: an address worked out from
2746    /// where the instruction is, which is what `(%rip)` means and is the only way this compiler
2747    /// reaches anything. What they do not have in common is what fills the four bytes in. A
2748    /// global is a name, so the number is a relocation and the linker writes it. A block is a
2749    /// place in this function, so both ends are in one section and the number is known as soon as
2750    /// the blocks have been laid out, which is why `rucc_asm` fills it in the way it fills in a
2751    /// jump rather than leaving a relocation behind.
2752    ///
2753    /// Nothing here says the block is one control can arrive at. That is said by the
2754    /// [`Opcode::IndirectBr`] that reads the address, which lists every block it can arrive at,
2755    /// and by nothing else: an address on its own is a number.
2756    fn block_address(&mut self, inst: Inst) -> Result<(), Unsupported> {
2757        let result = self.source[inst].first_result.ok_or_else(|| self.unsupported(inst))?;
2758        let Some(call) = self.source.successors(inst).next() else {
2759            return Err(self.unsupported(inst));
2760        };
2761        let block = self.at.expect("a block is being filled");
2762        let reg = self.new_reg(result);
2763        let span = self.source.span(inst);
2764        let opcode = self.named(self.selector.jumps.near);
2765        let mem = mir::Mem::block(self.out_block(call.block));
2766        self.out.build(block, opcode).at(span).def(reg, self.gpr).mem(mem).finish();
2767        Ok(())
2768    }
2769
2770    /// `goto *p`, GNU's computed goto, which is a jump through a register.
2771    ///
2772    /// Where it goes is not written here and cannot be. Every block it can arrive at is on the
2773    /// block this ends, the way every other arm is, and which of them the address holds is decided
2774    /// while the program runs. So this is one instruction with one operand, and the arms are
2775    /// copied across by [`Self::edges`] like anybody else's.
2776    fn indirect_branch(&mut self, inst: Inst) -> Result<(), Unsupported> {
2777        let data = &self.source[inst];
2778        let &address = self.source[data.args].first().ok_or_else(|| self.unsupported(inst))?;
2779        let reg = self.reg_of(address)?;
2780        let block = self.at.expect("a block is being filled");
2781        let span = self.source.span(inst);
2782        let name = self.selector.branch.indirect;
2783        let opcode = self.named(name);
2784        self.out.build(block, opcode).at(span).operand(mir::Operand::read(reg, self.gpr)).finish();
2785        Ok(())
2786    }
2787
2788    /// A `switch` on an index from zero up, as a jump through a table of this function.
2789    ///
2790    /// Every `switch` that reaches here is one `crate::switch` left behind on purpose: it has
2791    /// already checked the value is inside the table and taken the lowest case off it, so the
2792    /// operand is a 64 bit index, the cases are the values from zero up with gaps where the
2793    /// program had no case, and the default is only where those gaps go. What is written is the
2794    /// shape gcc writes for the same statement in position independent code:
2795    ///
2796    /// ```text
2797    /// leaq    table(%rip), %base
2798    /// movslq  (%base,%index,4), %offset
2799    /// addq    %base, %offset
2800    /// jmp     *%offset
2801    /// ```
2802    ///
2803    /// The table holds distances from itself to each arm rather than addresses, which is what
2804    /// lets it be filled in by the assembler with nothing left for a linker to do. Each cell is
2805    /// stored as the place of an arm among this block's successors, which [`Self::edges`] copies
2806    /// across in the IR's own order, the default first and then one per case. See
2807    /// [`mir::Table`] for why a place and not a block.
2808    fn jump_table(&mut self, inst: Inst) -> Result<(), Unsupported> {
2809        let data = &self.source[inst];
2810        let Extra::Switch(info) = data.extra else { return Err(self.unsupported(inst)) };
2811        let &index = self.source[data.args].first().ok_or_else(|| self.unsupported(inst))?;
2812        let ty = self.source[index].ty;
2813        if ty != Type::int(u64::BITS) {
2814            return Err(self.unsupported(inst));
2815        }
2816        let cases = self.source[self.source[info].cases].to_vec();
2817        let mut cells: Vec<u32> = Vec::new();
2818        for (arm, case) in cases.iter().enumerate() {
2819            let at = usize::try_from(case.signed(ty)).map_err(|_| self.unsupported(inst))?;
2820            if at >= cells.len() {
2821                cells.resize(at + 1, 0);
2822            }
2823            cells[at] = u32::try_from(arm + 1).map_err(|_| self.unsupported(inst))?;
2824        }
2825        let reg = self.reg_of(index)?;
2826        let block = self.at.expect("a block is being filled");
2827        let span = self.source.span(inst);
2828        let gpr = self.gpr;
2829        let table = u32::try_from(self.out.tables.len()).expect("fewer tables than that");
2830
2831        let jumps = self.selector.jumps;
2832
2833        let base = self.out.new_vreg(gpr);
2834        let near = self.named(jumps.near);
2835        self.out.build(block, near).at(span).def(base, gpr).mem(mir::Mem::table(table)).finish();
2836        let offset = self.out.new_vreg(gpr);
2837        let cell =
2838            mir::Mem::at(mir::Operand::read(base, gpr)).indexed(mir::Operand::read(reg, gpr), 4);
2839        let load = self.named(jumps.cell);
2840        self.out.build(block, load).at(span).def(offset, gpr).mem(cell).finish();
2841        // Two address on x86-64, for the reason `thread_pointer` gives.
2842        let to = self.out.new_vreg(gpr);
2843        let add = self.named(jumps.add);
2844        let written = mir::Operand::write(to, gpr);
2845        let written = if jumps.two_address { written.with(Constraint::Reuse(1)) } else { written };
2846        self.out
2847            .build(block, add)
2848            .at(span)
2849            .operand(written)
2850            .operand(mir::Operand::read(offset, gpr))
2851            .operand(mir::Operand::read(base, gpr))
2852            .finish();
2853        let jump = self.named(self.selector.branch.indirect);
2854        let jump =
2855            self.out.build(block, jump).at(span).operand(mir::Operand::read(to, gpr)).finish();
2856        self.out.tables.push(mir::Table { jump, cells });
2857        Ok(())
2858    }
2859
2860    /// `__builtin_setjmp`, which writes down where the function is so that a `__builtin_longjmp`
2861    /// somewhere else can bring control back here, and answers zero on the way past.
2862    ///
2863    /// Four words of the buffer, the three gcc writes and one of this compiler's own, and then the
2864    /// block ends: everything after the save in the IR block is put into a new machine IR block,
2865    /// and the address of that block is what went into the buffer. That is the whole reason the
2866    /// block is split here. An address points at a label, a machine IR block is the only thing in
2867    /// this representation that has one, and a save is in the middle of a block rather than at the
2868    /// end of one.
2869    ///
2870    /// # How the answer gets back
2871    ///
2872    /// Through the frame rather than through a register. The save writes a zero into a word of its
2873    /// own frame, puts the address of that word in the buffer, and the new block reads the word
2874    /// back. The restore writes a one through the address it finds in the buffer before it goes.
2875    /// So one load answers zero on the way past and one on the way back, and neither path has to
2876    /// agree with the other about a register.
2877    ///
2878    /// gcc does it the other way round, with a second block that sets the answer to one and is
2879    /// what the restore arrives at. That block is one nothing in the function jumps to, and a
2880    /// machine IR whose blocks are walked from the entry has nowhere to put such a thing: the
2881    /// allocator lays a function out in the line it is going to be emitted in, and a block no edge
2882    /// reaches is not in that line. The word in the frame costs eight bytes of stack and one load,
2883    /// and it needs nothing said anywhere about a block arrived at from outside.
2884    ///
2885    /// # What the allocator is told
2886    ///
2887    /// That every register it hands out is gone at the end of the first block. That is what makes
2888    /// the rest of the function right on the way back: control arrives from a `__builtin_longjmp`
2889    /// in some other function, and the only two registers that puts back are the stack pointer and
2890    /// the frame pointer, so anything this function still wants has to be in the frame those two
2891    /// reach. It is said with a write of every one of those registers, which is the same thing a
2892    /// call says about the registers a callee may destroy, on an instruction with nothing else on
2893    /// it so that the stores above are not caught up in it.
2894    fn saves_place(&mut self, inst: Inst) -> Result<(), Unsupported> {
2895        let data = &self.source[inst];
2896        let result = data.first_result.ok_or_else(|| self.unsupported(inst))?;
2897        let &buffer = self.source[data.args].first().ok_or_else(|| self.unsupported(inst))?;
2898        let span = self.source.span(inst);
2899        let buf = self.reg_of(buffer)?;
2900        let at = self.at.expect("a block is being filled");
2901        let gpr = self.gpr;
2902        let moves = self.selector.frame.moves(gpr).expect("a class the target says how to move");
2903        let store = self.named(moves.store);
2904        let load = self.named(moves.load);
2905        let lea = self.named(self.selector.frame.lea);
2906        let put = self.named(self.selector.frame.imm);
2907        let nothing =
2908            self.selector.frame.pad.expect("a target with an instruction that does nothing");
2909        let nothing = self.named(nothing);
2910        self.stack.saves_place = true;
2911        let answer = self.answer_slot();
2912        let back = self.out.create_block();
2913
2914        // The zero this answers with, into the word a restore writes a one into.
2915        let zero = self.out.new_vreg(gpr);
2916        self.out.build(at, put).at(span).def(zero, gpr).imm(0).finish();
2917        let mem = self.frame_mem();
2918        let made = self.out.build(at, store).at(span).uses(zero, gpr).mem(mem).finish();
2919        self.stack.addresses.push((made, answer));
2920
2921        // The four words: where that word is, where control comes back to, and the two registers
2922        // the restore puts back.
2923        let found = self.frame_address(at, answer);
2924        self.write_word(at, span, store, found, buf, JUMP_ANSWER);
2925        let pc = self.out.new_vreg(gpr);
2926        self.out.build(at, lea).at(span).def(pc, gpr).mem(mir::Mem::block(back)).finish();
2927        self.write_word(at, span, store, pc, buf, JUMP_PC);
2928        let frame = mir::Reg::physical(self.conv.frame_pointer);
2929        self.write_word(at, span, store, frame, buf, JUMP_FRAME);
2930        let stack = mir::Reg::physical(self.conv.stack_pointer);
2931        self.write_word(at, span, store, stack, buf, JUMP_STACK);
2932
2933        // Nothing is in a register past this point, which is what the rest of the function is
2934        // allowed to assume about the way back in.
2935        let gone = self.across_jump();
2936        let mut build = self.out.build(at, nothing).at(span);
2937        for (reg, class) in gone {
2938            build = build.operand(mir::Operand::write(reg, class));
2939        }
2940        build.finish();
2941
2942        // And the rest of the block, which is the block the address above was of.
2943        *self.out.succs_mut(at) = vec![mir::BlockCall::to(back)];
2944        self.at = Some(back);
2945        let reg = self.new_reg(result);
2946        let mem = self.frame_mem();
2947        let made = self.out.build(back, load).at(span).def(reg, gpr).mem(mem).finish();
2948        self.stack.addresses.push((made, answer));
2949        Ok(())
2950    }
2951
2952    /// `__builtin_longjmp`, which reads a buffer a `__builtin_setjmp` filled in and goes there.
2953    ///
2954    /// Everything comes out of the buffer before anything is put back, and the four registers it
2955    /// comes out into are physical ones rather than values the allocator places. Both of those are
2956    /// about the same moment. The stack pointer is one of the things being put back, a value the
2957    /// allocator sent to the stack is reached through the stack pointer, and between the
2958    /// instruction that moves it and the jump there is no stack this function owns any more. A
2959    /// register named outright is a register nothing reloads into and nothing else is in, which is
2960    /// the only way to hold something across that moment.
2961    ///
2962    /// Four of them because that is how many things are in the air at once: where to go, the frame
2963    /// pointer to put back, the one the matching save is to answer with, and one register used
2964    /// twice, first for the address that one is written through and then for the stack pointer.
2965    ///
2966    /// Nothing after this in the block is reached. The marker is not a terminator, for the reason
2967    /// `spec/08-ir.md` gives, so the block goes on and whatever the front end wrote after it is
2968    /// written out and never run.
2969    fn comes_back(&mut self, inst: Inst) -> Result<(), Unsupported> {
2970        let data = &self.source[inst];
2971        let &buffer = self.source[data.args].first().ok_or_else(|| self.unsupported(inst))?;
2972        let span = self.source.span(inst);
2973        let buf = self.reg_of(buffer)?;
2974        let at = self.at.expect("a block is being filled");
2975        let gpr = self.gpr;
2976        let moves = self.selector.frame.moves(gpr).expect("a class the target says how to move");
2977        let load = self.named(moves.load);
2978        let store = self.named(moves.store);
2979        let mov = self.named(moves.mov);
2980        let put = self.named(self.selector.frame.imm);
2981        let jump = self.named(self.selector.branch.indirect);
2982
2983        let held = self.jump_regs();
2984        if held.len() < JUMP_REGS {
2985            return Err(self.unsupported(inst));
2986        }
2987        let pc = mir::Reg::physical(held[0]);
2988        let frame = mir::Reg::physical(held[1]);
2989        let spare = mir::Reg::physical(held[2]);
2990        let one = mir::Reg::physical(held[3]);
2991
2992        self.read_word(at, span, load, pc, buf, JUMP_PC);
2993        self.read_word(at, span, load, frame, buf, JUMP_FRAME);
2994        self.read_word(at, span, load, spare, buf, JUMP_ANSWER);
2995
2996        // What the matching save answers with, written through the address that came out of the
2997        // buffer, because the word it goes in is in the other function's frame and this one has no
2998        // way of knowing where that is.
2999        self.out.build(at, put).at(span).def(one, gpr).imm(1).finish();
3000        let mem = mir::Mem::at(mir::Operand::read(spare, gpr));
3001        self.out.build(at, store).at(span).uses(one, gpr).mem(mem).finish();
3002
3003        // The stack last of the four, so that the register the buffer is reached through is done
3004        // with before the stack it may have been spilled to stops being this function's.
3005        self.read_word(at, span, load, spare, buf, JUMP_STACK);
3006        let stack = mir::Reg::physical(self.conv.stack_pointer);
3007        self.copy(at, span, mov, stack, spare);
3008        let base = mir::Reg::physical(self.conv.frame_pointer);
3009        self.copy(at, span, mov, base, frame);
3010
3011        // And the jump, which reads the two registers just put back as well as the address it
3012        // goes through. Neither of those is printed, because the target's spelling of an indirect
3013        // jump has one argument and it is the first one read. They are there because the code
3014        // control arrives at reaches its frame through them, and because without them the two
3015        // instructions above write registers nothing reads: a scheduler is then free to put the
3016        // jump in front of them, and at `-O2` it does.
3017        self.out
3018            .build(at, jump)
3019            .at(span)
3020            .operand(mir::Operand::read(pc, gpr))
3021            .operand(mir::Operand::read(stack, gpr))
3022            .operand(mir::Operand::read(base, gpr))
3023            .finish();
3024        Ok(())
3025    }
3026
3027    /// One word of the buffer of a `__builtin_setjmp`, written from a register.
3028    fn write_word(
3029        &mut self,
3030        at: mir::Block,
3031        span: Span,
3032        store: mir::Opcode,
3033        from: mir::Reg,
3034        buf: mir::Reg,
3035        word: i32,
3036    ) {
3037        let mem = mir::Mem::at(mir::Operand::read(buf, self.gpr)).plus(word);
3038        self.out.build(at, store).at(span).uses(from, self.gpr).mem(mem).finish();
3039    }
3040
3041    /// One word of that buffer, read back into a register.
3042    fn read_word(
3043        &mut self,
3044        at: mir::Block,
3045        span: Span,
3046        load: mir::Opcode,
3047        into: mir::Reg,
3048        buf: mir::Reg,
3049        word: i32,
3050    ) {
3051        let mem = mir::Mem::at(mir::Operand::read(buf, self.gpr)).plus(word);
3052        self.out.build(at, load).at(span).def(into, self.gpr).mem(mem).finish();
3053    }
3054
3055    /// One register into another, which is the one shape of instruction the builder has no word
3056    /// for because neither operand is a definition of a value or a read of memory.
3057    fn copy(
3058        &mut self,
3059        at: mir::Block,
3060        span: Span,
3061        mov: mir::Opcode,
3062        into: mir::Reg,
3063        from: mir::Reg,
3064    ) {
3065        self.out
3066            .build(at, mov)
3067            .at(span)
3068            .operand(mir::Operand::write(into, self.gpr))
3069            .operand(mir::Operand::read(from, self.gpr))
3070            .finish();
3071    }
3072
3073    /// The word a `__builtin_setjmp` in this function answers with, asked for once and kept.
3074    fn answer_slot(&mut self) -> usize {
3075        match self.answer {
3076            Some(index) => index,
3077            None => {
3078                let index = self.stack.locals.len();
3079                self.stack.locals.push(Local { size: JUMP_WORD, align: JUMP_WORD });
3080                self.answer = Some(index);
3081                index
3082            }
3083        }
3084    }
3085
3086    /// An address in this function's frame with nothing in its displacement, which is what an
3087    /// instruction reaching one of its stack objects is written with until [`crate::finish`] knows
3088    /// where the object is.
3089    fn frame_mem(&self) -> mir::Mem {
3090        mir::Mem::at(mir::Operand::read(mir::Reg::physical(self.conv.stack_pointer), self.gpr))
3091    }
3092
3093    /// Every register the allocator hands out, which is what a `__builtin_setjmp` destroys.
3094    ///
3095    /// Both files, since a `double` live across a save has the same problem an integer does. The
3096    /// two registers a frame is reached through are not here: the restore puts both of them back,
3097    /// which is the whole of what it puts back, and a function whose frame pointer was destroyed
3098    /// by its own save would have nothing left to find its caller with.
3099    fn across_jump(&self) -> Vec<(mir::Reg, RegClass)> {
3100        let mut gone = Vec::new();
3101        for &reg in self.conv.int_order {
3102            if reg == self.conv.stack_pointer || reg == self.conv.frame_pointer {
3103                continue;
3104            }
3105            gone.push((mir::Reg::physical(reg), self.gpr));
3106        }
3107        for &reg in self.conv.sse_order {
3108            gone.push((mir::Reg::physical(reg), self.conv.sse_class));
3109        }
3110        gone
3111    }
3112
3113    /// The registers a `__builtin_longjmp` may hold things in while it puts a frame back.
3114    ///
3115    /// The ones the allocator hands out, less the two a frame is reached through. The scratch
3116    /// registers are not among them on purpose: the rewriter writes a reload into one of those
3117    /// wherever it likes, and one of these has to survive from the load that fills it to the
3118    /// instruction that reads it however many instructions apart those are.
3119    fn jump_regs(&self) -> Vec<PhysReg> {
3120        self.conv
3121            .int_order
3122            .iter()
3123            .copied()
3124            .filter(|&reg| {
3125                reg != self.conv.stack_pointer
3126                    && reg != self.conv.frame_pointer
3127                    && !self.selector.scratch.contains(&reg)
3128            })
3129            .collect()
3130    }
3131
3132    /// A machine opcode of this target from the name the target gives it.
3133    fn named(&mut self, name: &str) -> mir::Opcode {
3134        mir::Opcode::new(self.names.intern(&format!("{}{name}", self.selector.prefix())))
3135    }
3136
3137    /// `__builtin_frame_address` and `__builtin_return_address`, which are a walk up the chain of
3138    /// saved frame pointers and then one thing read at the end of it.
3139    ///
3140    /// Every frame that kept a frame pointer holds the caller's at the address the register points
3141    /// at, and the address that frame returns to one word above that, which is where the call
3142    /// instruction put it and where the prologue's push left it. So the walk is a load through the
3143    /// register for each link, the frame address is wherever the walk stopped, and the return
3144    /// address is one more load from a word above it. gcc 16.2.0 writes exactly this, measured on
3145    /// x86-64 at `-O2` for depths zero to three of both builtins.
3146    ///
3147    /// The function is given a frame pointer because of this, which is what [`Stack::walks_frames`]
3148    /// carries out to the layout. A depth of zero needs it as the answer and every depth above zero
3149    /// needs it as the start, so there is no case here where it is not wanted.
3150    ///
3151    /// How far the chain actually reaches is the program's business and not this one's. A caller
3152    /// compiled without a frame pointer has no link in it for the walk to follow, so a depth above
3153    /// zero is a promise about how the whole program was built. That is why gcc documents a nonzero
3154    /// depth as unsafe rather than as an answer, and why the depth is refused above a limit in
3155    /// `check/builtin/frame.rs` rather than walked as far as it says.
3156    fn frames(&mut self, inst: Inst) -> Result<(), Unsupported> {
3157        let data = &self.source[inst];
3158        let Extra::Depth(depth) = data.extra else { return Err(self.unsupported(inst)) };
3159        let result = data.first_result.ok_or_else(|| self.unsupported(inst))?;
3160        let returning = data.opcode == Opcode::ReturnAddress;
3161        let block = self.at.expect("a block is being filled");
3162        let span = self.source.span(inst);
3163        let moves =
3164            self.selector.frame.moves(self.gpr).expect("a class the target says how to move");
3165        let load = self.named(moves.load);
3166        self.stack.walks_frames = true;
3167
3168        // Where the walk is up to. The frame pointer to begin with, and the register the last load
3169        // wrote after that.
3170        let reg = self.new_reg(result);
3171        let mut base = mir::Reg::physical(self.conv.frame_pointer);
3172        for link in 0..depth {
3173            // The last load of a walk that is looking for a frame writes the answer itself, which
3174            // is what keeps a walk of so many links that many instructions and not one more.
3175            let ends_here = link + 1 == depth && !returning;
3176            let next = if ends_here { reg } else { self.out.new_vreg(self.gpr) };
3177            let at = mir::Mem::at(mir::Operand::read(base, self.gpr));
3178            self.out.build(block, load).at(span).def(next, self.gpr).mem(at).finish();
3179            base = next;
3180        }
3181
3182        if returning {
3183            let up = i32::try_from(self.conv.return_address).expect("a word above the frame");
3184            let at = mir::Mem::at(mir::Operand::read(base, self.gpr)).plus(up);
3185            self.out.build(block, load).at(span).def(reg, self.gpr).mem(at).finish();
3186        } else if depth == 0 {
3187            // The one case with no load in it at all: the frame this function is running in is the
3188            // register itself, and a physical register is not one the allocator hands out, so the
3189            // answer is a copy of it.
3190            let mov = self.named(moves.mov);
3191            self.out
3192                .build(block, mov)
3193                .at(span)
3194                .operand(mir::Operand::write(reg, self.gpr))
3195                .operand(mir::Operand::read(base, self.gpr))
3196                .finish();
3197        }
3198        Ok(())
3199    }
3200
3201    /// `__builtin_thread_pointer`, which is the front of the block [`Self::thread_address`] adds
3202    /// an offset to.
3203    ///
3204    /// The same one instruction, on its own this time and with nothing to add to it. A program
3205    /// writes this when what it wants is a number that is different in every thread and cheap to
3206    /// come by, rather than a variable of its own in the block, so there is no relocation here and
3207    /// no name for the link to resolve.
3208    fn thread_pointer(&mut self, inst: Inst) -> Result<(), Unsupported> {
3209        self.threads_written(inst)?;
3210        let result = self.source[inst].first_result.ok_or_else(|| self.unsupported(inst))?;
3211        let block = self.at.expect("a block is being filled");
3212        let span = self.source.span(inst);
3213        let reg = self.new_reg(result);
3214        self.read_thread_pointer(block, span, reg);
3215        Ok(())
3216    }
3217
3218    /// What a named machine register holds, which is `register long x asm ("rbx");`.
3219    ///
3220    /// One move out of that register, with the register named as itself the way a register a
3221    /// template wrote is named, which is [`Self::itself`] and is the thing #1653 built. What it
3222    /// buys here is what it buys there: the register is part of the instruction the allocator
3223    /// sees, so it is a use the allocator will not have written over first, and the value goes
3224    /// into an ordinary one of its own that everything downstream reads.
3225    ///
3226    /// The whole sixty four bits are moved whatever the type is, because the register is that
3227    /// wide and a narrower type reads the low end of the copy, which is the same low end. A type
3228    /// wider than the register is refused, since there is no register holding it to read. On
3229    /// AArch64 a float may be kept in a vector register, `register double x asm ("d8");`, and it is
3230    /// moved out of that file the same way.
3231    ///
3232    /// A name the machine has not got is refused too, and is the only thing that can be wrong
3233    /// with the string: which register a name means is this machine's question and this is where
3234    /// the question is asked, at the same table `asm` asks about clobbers at. The sigil gcc
3235    /// allows in front of it is taken off here, because what the name is written with is syntax.
3236    fn register_value(&mut self, inst: Inst) -> Result<(), Unsupported> {
3237        let Extra::Symbol(symbol) = self.source[inst].extra else {
3238            return Err(self.unsupported(inst));
3239        };
3240        let result = self.source[inst].first_result.ok_or_else(|| self.unsupported(inst))?;
3241        let ty = self.source[result].ty;
3242        let bits = if ty.is_ptr() { ADDRESS_BITS } else { ty.bits() };
3243        if bits > ADDRESS_BITS {
3244            return Err(self.unsupported(inst));
3245        }
3246        let spelled = self.names.resolve(symbol).to_owned();
3247        let bare = spelled.strip_prefix('%').unwrap_or(&spelled);
3248        let named = if self.on_aarch64() {
3249            aarch64::named(bare)
3250        } else if self.class_of(ty) != self.gpr {
3251            return Err(self.unsupported(inst));
3252        } else {
3253            x86_64::gpr_named(bare).map(|(reg, _)| (reg, self.gpr))
3254        };
3255        let Some((held, file)) = named else {
3256            return Err(Unsupported::Register { inst, name: spelled });
3257        };
3258        // A float in a general purpose register, or a number in a vector one, is a register the
3259        // machine has holding a type that is not kept there, and would need a move between the
3260        // files that nothing here makes yet.
3261        if on_x87(ty) || self.class_of(ty) != file {
3262            return Err(self.unsupported(inst));
3263        }
3264        let block = self.at.expect("a block is being filled");
3265        let span = self.source.span(inst);
3266        let mov = self.selector.frame.moves(file).expect("a class the target says how to move").mov;
3267        let mov = self.named(mov);
3268        let into = self.new_reg(result);
3269        self.out
3270            .build(block, mov)
3271            .at(span)
3272            .operand(mir::Operand::write(into, file))
3273            .operand(
3274                mir::Operand::read(mir::Reg::physical(held), file).with(Constraint::Fixed(held)),
3275            )
3276            .finish();
3277        Ok(())
3278    }
3279
3280    /// A conversion that converts nothing: the result is the operand under another type.
3281    ///
3282    /// `ptrtoint` and `inttoptr` at one width are the whole of this. An address on this machine is
3283    /// an integer as wide as the machine addresses, so a cast between the two changes what the
3284    /// type system calls the value and changes nothing about the value, and the register holding
3285    /// it is the register that already held it. The front end never writes either of them at any
3286    /// other width, because it widens or narrows around the cast rather than through it, so the
3287    /// two widths disagreeing here means the IR came from somewhere else and is refused rather
3288    /// than guessed at.
3289    ///
3290    /// Reading the operand first is what materializes it when it is a constant, which is the case
3291    /// that matters: a null pointer is an `inttoptr` of zero, and that zero has to reach a
3292    /// register before anything can call it an address.
3293    fn rename(&mut self, inst: Inst) -> Result<(), Unsupported> {
3294        let data = &self.source[inst];
3295        let [arg] = self.source[data.args] else { return Err(self.unsupported(inst)) };
3296        let result = data.first_result.ok_or_else(|| self.unsupported(inst))?;
3297        if !self.is_address_width(self.source[arg].ty)
3298            || !self.is_address_width(self.source[result].ty)
3299        {
3300            return Err(self.unsupported(inst));
3301        }
3302        let reg = self.reg_of(arg)?;
3303        self.regs[result.index()] = Some(reg);
3304        Ok(())
3305    }
3306
3307    /// One barrier, which on this machine is one instruction at the strongest ordering and no
3308    /// instruction at all at every other one.
3309    ///
3310    /// x86-64 is total store order, so the only reordering the machine does is a store followed by
3311    /// a load of a different address, and the only ordering that forbids that is sequential
3312    /// consistency. An acquire, a release and an acquire release fence are therefore already true
3313    /// of every program running here, and what a program wanted from writing one is that the
3314    /// compiler not move memory accesses across it. The optimizer has finished by the time this
3315    /// runs and nothing below reorders one access past another, so the constraint is already
3316    /// discharged and there is nothing to write.
3317    ///
3318    /// The strongest one is `mfence`, which is what gcc 16.2.0 writes for
3319    /// `__atomic_thread_fence(__ATOMIC_SEQ_CST)` and for `__sync_synchronize`. A locked instruction
3320    /// on the stack is faster on most parts and is what some compilers write instead; it is also a
3321    /// write to memory the program did not ask for, and the plain barrier is the one that says what
3322    /// it means.
3323    ///
3324    /// Written here by name rather than by a rule, for the same reason a `lea` of a symbol is:
3325    /// there is nothing in a barrier that a proof over bitvectors could discharge. It computes
3326    /// nothing, so there is no equality to state, and what makes it the right answer is the memory
3327    /// model, which the rule language cannot talk about.
3328    fn barrier(&mut self, inst: Inst) -> Result<(), Unsupported> {
3329        let Extra::Order(order) = self.source[inst].extra else {
3330            return Err(self.unsupported(inst));
3331        };
3332        if order != MemOrder::SeqCst {
3333            return Ok(());
3334        }
3335        let block = self.at.expect("a block is being filled");
3336        let span = self.source.span(inst);
3337        let fence = self.named(self.selector.fence);
3338        self.out.build(block, fence).at(span).finish();
3339        Ok(())
3340    }
3341
3342    /// The instruction a program stops on, which is one byte pair and no operands.
3343    ///
3344    /// `ud2` is an opcode the manual promises will never be given a meaning, so a processor that
3345    /// reaches it raises the fault for an instruction it does not know, and on Linux that arrives
3346    /// at the program as `SIGILL`. That is what `__builtin_trap` is for: a stop that cannot be
3347    /// caught by anything the program installed for an ordinary error, cannot be returned from,
3348    /// and leaves the address of the fault in the core file.
3349    ///
3350    /// Why not a call to `abort`. It is two bytes against a call and a relocation, it needs no
3351    /// library, and it works in the places this one is written most, which are a kernel and a
3352    /// freestanding program that has no `abort` to call. gcc 16.2.0 writes `ud2` here too.
3353    fn trap(&mut self, inst: Inst) {
3354        let block = self.at.expect("a block is being filled");
3355        let span = self.source.span(inst);
3356        let stop = self.named(self.selector.trap);
3357        self.out.build(block, stop).at(span).finish();
3358    }
3359
3360    /// One hint that an address is about to be used, which is one instruction and no promise.
3361    ///
3362    /// Four instructions on this machine and the locality picks between them, which is what the
3363    /// number means: how much of the data will still be wanted after the access. None of it wanted
3364    /// is `prefetchnta`, which brings the line in without keeping it, and all of it wanted is
3365    /// `prefetcht0`, which brings it as close as the machine can. The two in between are the levels
3366    /// between those. Measured against gcc 16.2.0 on x86-64 rather than read off the manual: zero
3367    /// gives `prefetchnta`, one `prefetcht2`, two `prefetcht1` and three `prefetcht0`.
3368    ///
3369    /// Whether the access will write is not read here, and that is this machine rather than an
3370    /// omission. The write hint is `prefetchw`, which is not in the base instruction set, and gcc
3371    /// writes it only when the command line said the part has it. So a prefetch for a write is the
3372    /// same instruction as a prefetch for a read, which is what gcc 16.2.0 writes without
3373    /// `-mprfchw`, and the difference is carried in the IR for a target that can use it.
3374    ///
3375    /// The address goes in the addressing mode rather than in an operand, the way a store's does.
3376    /// It is built here as the plainest one there is, a register and nothing else, because what
3377    /// arrives is a value and folding an addition into the mode is a rule's job and no rule reaches
3378    /// this instruction. An address the program computed is therefore one `lea` or one add in front
3379    /// of this, which is what it would have been for the load the hint is about anyway.
3380    fn hint(&mut self, inst: Inst) -> Result<(), Unsupported> {
3381        let Extra::Prefetch(hint) = self.source[inst].extra else {
3382            return Err(self.unsupported(inst));
3383        };
3384        let args: Vec<Value> = self.source[self.source[inst].args].to_vec();
3385        let [address] = args[..] else { return Err(self.unsupported(inst)) };
3386        let name = match hint.locality {
3387            0 => "prefetch_nta",
3388            1 => "prefetch_t2",
3389            2 => "prefetch_t1",
3390            PrefetchHint::MOST => "prefetch_t0",
3391            // Nothing else exists. The checker reads a locality outside the range as zero and the
3392            // verifier refuses one that got here another way, so this is a hint that was built
3393            // rather than checked, and the safe answer for a hint is to write no instruction.
3394            _ => return Err(self.unsupported(inst)),
3395        };
3396        let base = self.reg_of(address)?;
3397        let block = self.at.expect("a block is being filled");
3398        let opcode = self.named(name);
3399        self.out
3400            .build(block, opcode)
3401            .at(self.source.span(inst))
3402            .mem(mir::Mem::at(mir::Operand::read(base, self.gpr)))
3403            .finish();
3404        Ok(())
3405    }
3406
3407    /// One compare and exchange, which is the instruction every other atomic on this machine is
3408    /// built out of.
3409    ///
3410    /// What the IR asks for is: read what is at an address, compare it against a value the program
3411    /// expected, put a second value there if the two were equal, and say both what was read and
3412    /// whether the exchange happened. The machine has exactly that instruction, and the `lock` in
3413    /// front of it is what makes the whole of it one step as far as every other processor is
3414    /// concerned.
3415    ///
3416    /// The ordering is not read here, and that is the memory model rather than an omission. A
3417    /// locked instruction on x86-64 is a full barrier whatever the program asked for, so a relaxed
3418    /// compare and exchange and a sequentially consistent one are the same instruction, and there
3419    /// is nothing weaker to emit for the weaker orderings. The failure ordering is not read for the
3420    /// same reason.
3421    ///
3422    /// The two values it produces are why this is written by name. The one the program compares
3423    /// against and the one it gets back are both `rax`, which the instruction reads and writes
3424    /// without being told, and the table says so with a fixed constraint at each end rather than
3425    /// leaving the allocator to find out. The second value is the byte behind it, which is the zero
3426    /// flag read out by a `sete`, and it is a definition of the same instruction so that the
3427    /// allocator knows the two are live together and never gives the byte the register the answer
3428    /// is in.
3429    fn exchange(&mut self, inst: Inst) -> Result<(), Unsupported> {
3430        let args: Vec<Value> = self.source[self.source[inst].args].to_vec();
3431        let results: Vec<Value> = self.source[inst].results().collect();
3432        let [addr, expected, desired] = args[..] else { return Err(self.unsupported(inst)) };
3433        let [old, exchanged] = results[..] else { return Err(self.unsupported(inst)) };
3434
3435        // A value the machine can compare in one instruction, which is an integer or an address at
3436        // one of the four widths it has a compare and exchange for. Anything else is a type this
3437        // has no instruction for rather than a program that is wrong, and the front end refuses it
3438        // before ever getting here.
3439        let ty = self.source[old].ty;
3440        let bits = if ty.is_ptr() { ADDRESS_BITS } else { ty.bits() };
3441        if (!ty.is_int() && !ty.is_ptr()) || !matches!(bits, 8 | 16 | 32 | 64) {
3442            return Err(self.unsupported(inst));
3443        }
3444
3445        let base = self.reg_of(addr)?;
3446        let want = self.reg_of(expected)?;
3447        let put = self.reg_of(desired)?;
3448        let got = self.new_reg(old);
3449        let flag = self.new_reg(exchanged);
3450
3451        let name = format!("cmpxchg_{bits}");
3452        let descs = self.selector.operands(&name).ok_or_else(|| self.unsupported(inst))?;
3453        let block = self.at.expect("a block is being filled");
3454        let opcode = self.named(&name);
3455        let (span, flags) = (self.source.span(inst), self.carried(inst));
3456        let mut build = self.out.build(block, opcode).at(span).flags(flags);
3457        for (desc, reg) in descs.iter().zip([got, flag, want, put]) {
3458            let operand = mir::Operand {
3459                reg,
3460                class: desc.class,
3461                role: desc.role,
3462                constraint: desc.constraint,
3463            };
3464            build = build.operand(operand);
3465        }
3466        build.mem(mir::Mem::at(mir::Operand::read(base, self.gpr))).finish();
3467        Ok(())
3468    }
3469
3470    /// One read modify write, for the three operations this machine does in a single instruction.
3471    ///
3472    /// What the IR asks for is: read what is at an address, do something to it, put the answer back,
3473    /// say what was there before, and let nothing get between the three steps. The machine has
3474    /// `xchg` for putting a value there and `lock xadd` for adding one, and both leave what they
3475    /// found in the register the operand arrived in, which is why the value that comes back and the
3476    /// value that went in are one register here.
3477    ///
3478    /// A subtraction is the add over the negated operand, which is right at every width because the
3479    /// machine's arithmetic wraps and negating then adding is subtracting in two's complement
3480    /// whatever the operands were. The negate is a separate instruction in front, over a register of
3481    /// its own, so that the value the program handed over is not the one written on: an operand may
3482    /// be live after this and a program that read it again would read the negation.
3483    ///
3484    /// The ordering is not read, for the reason the compare and exchange beside this does not read
3485    /// it. `xchg` with memory locks the bus whether it is asked to or not and `lock xadd` is asked
3486    /// to, so both are full barriers on this machine and there is nothing weaker to fall to.
3487    ///
3488    /// Eight of the other ten never arrive, because `crate::retry` turned each of them into a loop
3489    /// around a compare and exchange before anything here saw it. The two that do arrive are the
3490    /// ones on floating values, and they are refused: a compare and exchange of a float wants the
3491    /// value carried through an integer of the same width, and an eighty bit float has no such
3492    /// width. Neither family of builtins can write one yet either, so a program that reaches this
3493    /// refusal is a program that reached an unimplemented builtin first.
3494    fn modify(&mut self, inst: Inst) -> Result<(), Unsupported> {
3495        let Extra::Rmw(op, _) = self.source[inst].extra else {
3496            return Err(self.unsupported(inst));
3497        };
3498        let args: Vec<Value> = self.source[self.source[inst].args].to_vec();
3499        let [addr, operand] = args[..] else { return Err(self.unsupported(inst)) };
3500        let old = self.source[inst].first_result.ok_or_else(|| self.unsupported(inst))?;
3501
3502        // A value the machine can exchange in one instruction, which is an integer at one of the
3503        // four widths it has these for. A pointer arrives as an address, so it is an integer by the
3504        // time it is here, and anything else is a type this has no instruction for.
3505        let ty = self.source[old].ty;
3506        if !ty.is_int() || !matches!(ty.bits(), 8 | 16 | 32 | 64) {
3507            return Err(self.unsupported(inst));
3508        }
3509        let name = match op {
3510            RmwOp::Xchg => format!("xchg_{}", ty.bits()),
3511            RmwOp::Add | RmwOp::Sub => format!("xadd_{}", ty.bits()),
3512            _ => return Err(self.unsupported(inst)),
3513        };
3514
3515        let base = self.reg_of(addr)?;
3516        let mut put = self.reg_of(operand)?;
3517        let block = self.at.expect("a block is being filled");
3518        let span = self.source.span(inst);
3519        if op == RmwOp::Sub {
3520            let negated = self.out.new_vreg(self.gpr);
3521            let negate = self.named(&format!("neg_r_{}", ty.bits()));
3522            let descs = self
3523                .selector
3524                .operands(&format!("neg_r_{}", ty.bits()))
3525                .ok_or_else(|| self.unsupported(inst))?;
3526            let mut build = self.out.build(block, negate).at(span);
3527            for (desc, reg) in descs.iter().zip([negated, put]) {
3528                build = build.operand(mir::Operand {
3529                    reg,
3530                    class: desc.class,
3531                    role: desc.role,
3532                    constraint: desc.constraint,
3533                });
3534            }
3535            build.finish();
3536            put = negated;
3537        }
3538
3539        let got = self.new_reg(old);
3540        let descs = self.selector.operands(&name).ok_or_else(|| self.unsupported(inst))?;
3541        let opcode = self.named(&name);
3542        let flags = self.carried(inst);
3543        let mut build = self.out.build(block, opcode).at(span).flags(flags);
3544        for (desc, reg) in descs.iter().zip([got, put]) {
3545            build = build.operand(mir::Operand {
3546                reg,
3547                class: desc.class,
3548                role: desc.role,
3549                constraint: desc.constraint,
3550            });
3551        }
3552        build.mem(mir::Mem::at(mir::Operand::read(base, self.gpr))).finish();
3553        Ok(())
3554    }
3555
3556    /// One `asm` statement.
3557    ///
3558    /// An empty template is most of the inline assembly in a test suite, and it is not a corner
3559    /// case somebody wrote by accident. A program that wants a value computed where it stands, or a
3560    /// loop the optimizer must not touch, writes `asm volatile ("" : : : "memory")`, and forty
3561    /// years of bug reports about optimizers are full of them. What such a statement asks for is
3562    /// the barrier and the operand places, and no instructions at all.
3563    ///
3564    /// So the operands are the half that is always real: a constraint says where a value has to be,
3565    /// and where it has to be is still true when the template between them is empty.
3566    ///
3567    /// What the constraints ask for, on an empty template, is only ever that two operands share a
3568    /// place. Nothing reads a register no text names, so `"r"` on its own asks for a register and
3569    /// no particular one, and any register at all answers it. A matching constraint is different,
3570    /// because it says the output the assembly leaves is the place the input arrived in, and with
3571    /// no instructions between them that is the input unchanged. So it is a rename and not a move:
3572    /// the value is already in a register and the result is that register.
3573    ///
3574    /// An output nothing is tied to and no instruction writes is whatever the assembly left there,
3575    /// which for a template that writes nothing is whatever was in the register. That is a value
3576    /// the program is not entitled to, and this writes a zero rather than reading one, because the
3577    /// allocator has to be given a definition before a use whatever the program is entitled to.
3578    ///
3579    /// # A template with instructions in it
3580    ///
3581    /// [`x86_64::read`] turns the text into the opcodes this backend already has, which is what
3582    /// `spec/11-asm-objects-debug.md` section 11.1 asks for: the machine is described once, and an
3583    /// instruction a program wrote is looked up in that description rather than copied through to
3584    /// an assembler that has one of its own. So nothing here assembles anything. What it does is
3585    /// put the statement's operands where the opcode holds them, and from there an `asm` statement
3586    /// is ordinary machine code: the allocator picks the registers, the listing and the object file
3587    /// are written from the same table as every other instruction, and a spill around one works
3588    /// because there is nothing left about it for a spill to get wrong.
3589    ///
3590    /// A register the template named in its own text is the one thing in there that is nobody's
3591    /// operand, and it is placed as itself. See [`Self::itself`] for why that is safer here than
3592    /// the thing gcc does, which is to copy the name out and leave the allocator none the wiser.
3593    ///
3594    /// Two things are refused, both for one reason, which is that placing them by a guess gives a
3595    /// program that assembles into something other than what it says.
3596    ///
3597    /// An output the template writes more than once, which is one place with two definitions in it,
3598    /// and the machine IR between here and the allocator has one definition per register by
3599    /// construction. An output tied to an input and written once is not that: it is two registers
3600    /// the description ties together, which is what [`Place`] is about.
3601    ///
3602    /// An operand read where the opcode writes, or written where it reads. An output that has not
3603    /// been written yet is not a value, and an input the assembly writes over is a value something
3604    /// else may still be using.
3605    ///
3606    /// # A register the instruction uses without being told
3607    ///
3608    /// An instruction may reach a register its text does not name, and `cpuid` is all of them at
3609    /// once: the leaf goes in `eax`, the subleaf in `ecx`, and the answer comes back in all four
3610    /// registers. The description holds every bit of that already, so what is left is to say which
3611    /// of the statement's operands is in each of those registers, and the constraint letter is the
3612    /// one thing in an assembly statement that says it. `"=a"` is an output in `rax` and `"c"` is
3613    /// an input in `rcx`, which is why a program writing `cpuid` writes its constraints that way
3614    /// and has no choice about it.
3615    ///
3616    /// A register no letter named is one the statement put nothing in, and that is the usual case
3617    /// rather than an unusual one, since an instruction that answers four questions is written by
3618    /// programs that asked one. A write of one is the register being destroyed and gets a register
3619    /// of its own, which is what tells the allocator to keep everything else out of it. A read of
3620    /// one is a register the instruction looks at and the program never filled, which gets a zero
3621    /// for the reason [`Self::undefined`] gives.
3622    ///
3623    /// # The clobber list
3624    ///
3625    /// Read now, as the registers it names being written by every instruction of the template. By
3626    /// every one rather than by one of them, because the list says the assembly as a whole leaves
3627    /// them ruined and nothing here knows which line did it. Every entry has to be a register this
3628    /// machine has a name for or the statement is refused, since a name nobody read is a register
3629    /// nobody is keeping out of.
3630    ///
3631    /// `memory` and `cc` are the two entries that are not registers and both are skipped. `memory`
3632    /// says the assembly touches storage, which is already true of every `asm` this writes and is
3633    /// nothing a register list could hold. `cc` says it ruins the condition flags, and the flag
3634    /// tracking already has that from the instructions the template was read into, since it takes
3635    /// every instruction it does not recognize as writing them and every instruction here is one
3636    /// this machine describes. `flags` is the name gcc's own register table gives the same thing on
3637    /// this machine, so a program writing it has written `cc` and is read that way: tcc's
3638    /// `tests/tcctest.c` lists both on one statement.
3639    ///
3640    /// A clobber the instruction already writes is left off it. `cpuid` writes all four registers
3641    /// by description, and a statement listing three of them as clobbers as well is saying the
3642    /// same thing twice, which the allocator would read as one register with two definitions.
3643    ///
3644    /// On a template with nothing in it the list is ignored, as it was before, since a template
3645    /// with no instructions ruins nothing whatever it said about what it ruins.
3646    fn assembly(&mut self, inst: Inst) -> Result<(), Unsupported> {
3647        let data = &self.source[inst];
3648        let Extra::Asm(asm) = data.extra else { return Err(self.unsupported(inst)) };
3649        let info = self.source[asm];
3650        if !self.source[info.targets].is_empty() {
3651            return Err(Unsupported::Assembly { inst, refused: Written::Goto });
3652        }
3653        let refused = || Unsupported::Assembly { inst, refused: Written::Operand };
3654
3655        let constraints = self.names.resolve(info.constraints).to_string();
3656        let results: Vec<Value> = data.results().collect();
3657        let operands = AsmOperands::read(&constraints, &results, &self.source[data.args])
3658            .ok_or_else(refused)?;
3659        let list: Vec<AsmOperand<'_>> = operands.iter().copied().collect();
3660
3661        // Read after the constraints and not before them, because a mnemonic whose suffix the
3662        // program left off is read at the width of the operands it names, and the operands are
3663        // what the constraints are a list of.
3664        let widths: Vec<Option<x86_64::Width>> = list
3665            .iter()
3666            .map(|operand| {
3667                let ty = self.source[operand.result.or(operand.value)?].ty;
3668                if !ty.is_scalar() {
3669                    return None;
3670                }
3671                x86_64::Width::of_bits(held_bits(ty))
3672            })
3673            .collect();
3674        // An operand in memory is an address the statement holds and an object the template names,
3675        // so the reader is told which ones those are and spells `%0` for one as the object.
3676        let memory: Vec<bool> = list.iter().map(|operand| operand.memory).collect();
3677        let template = self.names.resolve(info.template).to_string();
3678        let steps = if template.trim().is_empty() {
3679            Vec::new()
3680        } else {
3681            match x86_64::read_in(&template, &widths, &memory) {
3682                Some(steps) => steps,
3683                None => return self.kept(inst, &template, &list, &widths, &memory),
3684            }
3685        };
3686
3687        // Which operands the template writes, counted before anything is placed, because the answer
3688        // decides where each of the three below comes from and one instruction may name an operand
3689        // that a later one writes. Which of them any instruction puts in a register at all is
3690        // counted in the same walk, since an operand no instruction reaches that way is one nothing
3691        // has to put anywhere: a constant a template names only as the distance into an address is
3692        // written into the instruction, and a register holding a copy of it would be one nobody
3693        // reads. An operand the address is counted from is reached that way and is counted here for
3694        // that reason, because the walk below it is over the opcode's operands and an address is
3695        // not one of those.
3696        //
3697        // Whether any instruction reads an operand an instruction above it wrote is counted in the
3698        // same walk too. Such a template is one whose instructions have to be written in order with
3699        // each read taken from wherever the last write left the operand, which is what
3700        // [`Self::woven`] does, and so is one that writes an operand twice.
3701        let mut writes = vec![0usize; list.len()];
3702        let mut reads = vec![false; list.len()];
3703        let mut held = vec![false; list.len()];
3704        let mut after = false;
3705        for step in &steps {
3706            // A call out of the template writes every register the convention lets the callee
3707            // leave anything in, and an output pinned to one of those is written by it.
3708            if let x86_64::Step::Call { .. } = step {
3709                for index in self.lost(&list).into_iter().filter_map(|(_, _, index)| index) {
3710                    *writes.get_mut(index).ok_or_else(refused)? += 1;
3711                }
3712                continue;
3713            }
3714            let x86_64::Step::Line(line) = step else { continue };
3715            match line.at.and_then(|at| at.base) {
3716                Some(x86_64::Piece::Operand { index, .. }) => {
3717                    *held.get_mut(index).ok_or_else(refused)? = true;
3718                    after |= writes[index] > 0;
3719                }
3720                Some(x86_64::Piece::Reg { reg, .. }) => {
3721                    if let Some(index) = bound(&list, reg, Role::Use) {
3722                        *held.get_mut(index).ok_or_else(refused)? = true;
3723                        after |= writes[index] > 0;
3724                    }
3725                }
3726                _ => {}
3727            }
3728            let mut written = Vec::new();
3729            let form = x86_64::form(line.opcode).ok_or_else(refused)?;
3730            // Which registers the instruction reaches, asked the same way it is asked again when
3731            // the instruction is written. See [`Self::lettered`] for the one opcode whose answer
3732            // comes from the constraint letters rather than from the description.
3733            let lettered = (line.opcode == x86_64::LITERAL).then(|| self.lettered(&list));
3734            let (described, pieces) = match &lettered {
3735                Some((described, pieces)) => (described.as_slice(), pieces.as_slice()),
3736                None => (form.operands(), line.operands.as_slice()),
3737            };
3738            for (desc, piece) in described.iter().zip(pieces) {
3739                // An operand the instruction reaches without its text saying so is the statement's
3740                // only when a constraint letter put something there. One that is nobody's writes
3741                // nothing of the program's, so it is counted nowhere and is dealt with where it is
3742                // placed.
3743                let index = match *piece {
3744                    x86_64::Piece::Operand { index, .. } => index,
3745                    x86_64::Piece::Implicit { reg } => match bound(&list, reg, desc.role) {
3746                        Some(index) => index,
3747                        None => continue,
3748                    },
3749                    x86_64::Piece::Reg { reg, .. } => match bound(&list, reg, desc.role) {
3750                        Some(index) => index,
3751                        None => continue,
3752                    },
3753                };
3754                *held.get_mut(index).ok_or_else(refused)? = true;
3755                if matches!(desc.role, Role::Def | Role::EarlyDef) {
3756                    written.push(index);
3757                } else {
3758                    *reads.get_mut(index).ok_or_else(refused)? = true;
3759                    after |= writes[index] > 0;
3760                }
3761            }
3762            for index in written {
3763                *writes.get_mut(index).ok_or_else(refused)? += 1;
3764            }
3765        }
3766        let woven = after
3767            || writes.iter().any(|&count| count > 1)
3768            || steps.iter().any(|step| !matches!(step, x86_64::Step::Line(_)));
3769
3770        // Where every operand is. Worked out in full before the first instruction is written, since
3771        // reading a value may be what puts it in a register in the first place, and that has to
3772        // happen in front of the assembly rather than in the middle of it.
3773        let mut places: Vec<Place> = vec![Place::default(); list.len()];
3774        for (index, operand) in list.iter().copied().enumerate() {
3775            let Some(result) = operand.result else {
3776                // An input, or an output the assembly was handed the address of, and both are a
3777                // value that arrives in a register and is read out of it, unless no instruction of
3778                // the template reads it out of one.
3779                let value = operand.value.ok_or_else(refused)?;
3780                if held[index] {
3781                    places[index].read = Some(self.reg_of(value)?);
3782                }
3783                continue;
3784            };
3785            let ty = self.source[result].ty;
3786            if on_x87(ty) {
3787                return Err(refused());
3788            }
3789            let tied = operands.tied_to(index);
3790            if let Some(from) = tied {
3791                if self.class_of(self.source[from].ty) != self.class_of(ty) {
3792                    return Err(refused());
3793                }
3794                places[index].read = Some(self.reg_of(from)?);
3795            }
3796            if writes[index] > 0 {
3797                places[index].write = Some(self.new_reg(result));
3798                continue;
3799            }
3800            match tied {
3801                // The place the input arrived in, which the assembly wrote nothing over. One
3802                // register, so this is a rename rather than a move.
3803                Some(_) => {
3804                    let reg = places[index].read.ok_or_else(refused)?;
3805                    self.regs[result.index()] = Some(reg);
3806                    places[index].write = Some(reg);
3807                }
3808                None => {
3809                    self.undefined(inst, result)?;
3810                    places[index].write = self.regs[result.index()];
3811                }
3812            }
3813        }
3814
3815        // An output an instruction of the template also reads, which the statement said nothing
3816        // about because an output is what a statement says the other thing about. What it holds
3817        // there is undefined, and a program writing one means it: `sbb %0, %0` in libgmp's
3818        // `add_mssaaaa` subtracts a register from itself and is asking for the borrow bit rather
3819        // than for the number, so whatever the register held, the answer is the same. Undefined is
3820        // not the same as absent though, since the allocator is owed a definition in front of every
3821        // use, so it gets the zero an output nothing wrote gets and for the same reason.
3822        //
3823        // Unless an input could have been in the same register, in which case gcc's allocator puts
3824        // it there whenever it can and a program may have been written against that. tcc's test of
3825        // a call from a template reads its output `"=a" (s)` to pass `"r" (str)` to `getenv`, which
3826        // is only the string because gcc gave the two of them `rax`. So an output nothing has
3827        // written yet reads the one input that could share its place, when there is exactly one.
3828        // One written `&` is written before the inputs are read and shares nothing.
3829        for index in 0..list.len() {
3830            if !reads[index] || places[index].read.is_some() || places[index].write.is_none() {
3831                continue;
3832            }
3833            let reg = match self.shared(&list, index) {
3834                Some(value) => self.reg_of(value)?,
3835                None => self.seeded(inst, list[index])?,
3836            };
3837            places[index].read = Some(reg);
3838        }
3839
3840        // Worked out once for the whole template, since the list is one list and every instruction
3841        // of the template gets it. Not worked out at all for a template with no instructions, which
3842        // is where there is nothing for it to go on.
3843        let clobbers = self.names.resolve(info.clobbers).to_string();
3844        let clobbered =
3845            if steps.is_empty() { Vec::new() } else { Self::clobbered(inst, &clobbers)? };
3846
3847        // A template with a label in it is not one run of instructions, and what it is instead is
3848        // in [`Self::woven`], which is also where a template goes whose instructions read what the
3849        // ones above them wrote. Every other template is what it has always been, which is every
3850        // instruction of it written into the block the statement stands in.
3851        if woven {
3852            return self.woven(inst, &steps, &mut places, &list, &clobbered, &writes);
3853        }
3854        for step in &steps {
3855            let x86_64::Step::Line(line) = step else { continue };
3856            self.instruction(inst, line, &places, &list, &clobbered)?;
3857        }
3858        Ok(())
3859    }
3860
3861    /// A template the reader could not take apart, kept as its text. See [`x86_64::Form::Template`].
3862    ///
3863    /// What the text names is spelled into it here, the way gcc prints it into its listing: a
3864    /// constant as `$5`, or as `5` under the `c` modifier, and the address of a name as the name.
3865    /// An object in memory is the one thing that cannot be spelled yet, since where it is depends on
3866    /// registers nothing has chosen, so it is left as a hole the writer fills and its address is the
3867    /// instruction's memory operand. One is all an instruction has room for, and every template this
3868    /// has met names one at most. A template that names an operand by name rather than by number is
3869    /// refused for now.
3870    ///
3871    /// # An operand in a register
3872    ///
3873    /// Which register is not known until the allocator has run, and the text is written down before
3874    /// then, so an operand in a register is a hole too. It names the instruction's own operand and
3875    /// the width the modifier asked for, or the width of the operand's type when there was none,
3876    /// and the writer spells whatever register the operand ended up in. What the text writes goes
3877    /// in first as definitions and what it reads goes in last as uses, with the registers below in
3878    /// between, so the allocator sees the statement as one instruction with every operand said. An
3879    /// output tied to an input, by `+` or by a number, reuses the input's register, and one written
3880    /// `&` is written early. Anything wider than a general purpose register is refused.
3881    ///
3882    /// A statement written with no colons is basic assembly, where `%` is a character like any
3883    /// other and a register is written `%eax`. The front end keeps no mark of which kind a statement
3884    /// was, so one with no operands and no clobbers is read as basic, which is what gcc would do for
3885    /// every such template but one written with empty colons around it.
3886    ///
3887    /// The registers a call may write are taken as written, see below for why.
3888    fn kept(
3889        &mut self,
3890        inst: Inst,
3891        template: &str,
3892        list: &[AsmOperand<'_>],
3893        widths: &[Option<x86_64::Width>],
3894        memory: &[bool],
3895    ) -> Result<(), Unsupported> {
3896        // Refused as the template it is, since keeping it is what was tried after reading it
3897        // failed, and what could not be kept is what it names rather than any one operand.
3898        let refused = || Unsupported::Assembly { inst, refused: Written::Template };
3899        let data = &self.source[inst];
3900        let Extra::Asm(asm) = data.extra else { return Err(self.unsupported(inst)) };
3901        let clobbers = self.names.resolve(self.source[asm].clobbers).to_string();
3902        let basic = list.is_empty() && clobbers.trim().is_empty();
3903
3904        // Every register a call may leave anything in, as well as the ones the list names. The
3905        // text can write any register it likes without saying so, and tcc's tests do: gcc gets
3906        // away with that at `-O0` because nothing lives in a register between two statements
3907        // there, and taking these away from the allocator across the template is what gives the
3908        // same answer here. Nothing is written to them by this, so a register one template leaves
3909        // a value in is still holding it when the next template reads it.
3910        let a64 = self.on_aarch64();
3911        let mut clobbered: Vec<(PhysReg, RegClass)> =
3912            self.lost(list).into_iter().map(|(reg, class, _)| (reg, class)).collect();
3913        let named = if a64 {
3914            Self::clobbered_a64(inst, &clobbers)?
3915        } else {
3916            Self::clobbered(inst, &clobbers)?.into_iter().map(|reg| (reg, self.gpr)).collect()
3917        };
3918        for (reg, class) in named {
3919            if !clobbered.iter().any(|&(had, of)| had == reg && of == class) {
3920                clobbered.push((reg, class));
3921            }
3922        }
3923
3924        // The file each operand is in. On AArch64 `w` is a floating point or vector register and an
3925        // input tied to an output is in that output's file. A value whose type puts it in the other
3926        // file would need a move into this one first, which gcc makes and this does not yet, so
3927        // that is refused below.
3928        let mut files = vec![self.gpr; list.len()];
3929        if a64 {
3930            let constraints = self.names.resolve(self.source[asm].constraints);
3931            for (file, entry) in files.iter_mut().zip(constraints.split(',')) {
3932                if vector_letter(entry) {
3933                    *file = self.conv.sse_class;
3934                }
3935            }
3936            for index in 0..list.len() {
3937                if let Some(&file) = list[index].tied.and_then(|output| files.get(output)) {
3938                    files[index] = file;
3939                }
3940            }
3941        }
3942        let pins: Vec<_> = list.iter().map(|operand| self.pinned_here(operand)).collect();
3943        let pin = |index: usize, file: RegClass| match pins[index] {
3944            Some((at, class)) if class == file => Ok(Some(Constraint::Fixed(at))),
3945            Some(_) => Err(refused()),
3946            None => Ok(None),
3947        };
3948
3949        // The operands in a register, as the instruction's own. An input the text is handed as a
3950        // constant or as the address of a name is spelled into the text instead, when its
3951        // constraint allows a constant at all and no output is tied to it. `"a" (0x1234)` is a
3952        // register holding the number, the way gcc loads it, since the text may ask for `%h0`.
3953        let mut defs: Vec<mir::Operand> = Vec::new();
3954        let mut uses: Vec<mir::Operand> = Vec::new();
3955        let mut def_of: Vec<Option<usize>> = vec![None; list.len()];
3956        let mut use_of: Vec<Option<usize>> = vec![None; list.len()];
3957        if !basic {
3958            for (index, operand) in list.iter().enumerate() {
3959                let Some(result) = operand.result else { continue };
3960                let (ty, file) = (self.source[result].ty, files[index]);
3961                if on_x87(ty) || self.class_of(ty) != file {
3962                    return Err(refused());
3963                }
3964                let reg = self.new_reg(result);
3965                let written = if operand.early {
3966                    mir::Operand::write_early(reg, file)
3967                } else {
3968                    mir::Operand::write(reg, file)
3969                };
3970                def_of[index] = Some(defs.len());
3971                defs.push(match pin(index, file)? {
3972                    Some(fixed) => written.with(fixed),
3973                    None => written,
3974                });
3975            }
3976            for (index, operand) in list.iter().enumerate() {
3977                let Some(value) = operand.value else { continue };
3978                let spelled = operand.result.is_none()
3979                    && operand.tied.is_none()
3980                    && operand.immediate
3981                    && (self.number(value).is_some() || self.named_address(value).is_some());
3982                // An operand in memory is spelled on AArch64 as the register its address is in,
3983                // which is `[x3]` and is an address every instruction that takes one reads.
3984                if (operand.memory && !a64) || spelled {
3985                    continue;
3986                }
3987                let (ty, file) = (self.source[value].ty, files[index]);
3988                if on_x87(ty) || self.class_of(ty) != file {
3989                    return Err(refused());
3990                }
3991                let read = mir::Operand::read(self.reg_of(value)?, file);
3992                use_of[index] = Some(uses.len());
3993                uses.push(match pin(index, file)? {
3994                    Some(fixed) => read.with(fixed),
3995                    None => read,
3996                });
3997            }
3998        }
3999        // A register an output is pinned to is that output's definition and not a clobber as well.
4000        // One an input is pinned to is written as the instruction finishes, the way a call writes
4001        // the register its argument came in, and every other one is written early, since the text
4002        // may write it before it has read its inputs and an input must not be in it.
4003        let mut written: Vec<mir::Operand> = Vec::new();
4004        for (reg, class) in clobbered {
4005            let fixed = |operand: &mir::Operand| {
4006                operand.class == class && operand.constraint == Constraint::Fixed(reg)
4007            };
4008            if defs.iter().any(fixed) {
4009                continue;
4010            }
4011            let reg = mir::Reg::physical(reg);
4012            written.push(if uses.iter().any(fixed) {
4013                mir::Operand::write(reg, class)
4014            } else {
4015                mir::Operand::write_early(reg, class)
4016            });
4017        }
4018        // An output tied to an input is one register, which the definition says by reusing the
4019        // use, or by both being fixed to the same one when the output was pinned.
4020        let first_use = defs.len() + written.len();
4021        for (output, operand) in list.iter().enumerate() {
4022            let Some(def) = def_of[output] else { continue };
4023            let input = if operand.value.is_some() {
4024                Some(output)
4025            } else {
4026                list.iter().position(|entry| entry.tied == Some(output))
4027            };
4028            let Some(read) = input.and_then(|input| use_of[input]) else { continue };
4029            match defs[def].constraint {
4030                Constraint::Fixed(_) => uses[read].constraint = defs[def].constraint,
4031                _ => {
4032                    let at = u8::try_from(first_use + read).map_err(|_| refused())?;
4033                    defs[def].constraint = Constraint::Reuse(at);
4034                }
4035            }
4036        }
4037
4038        // A line naming an operand in a register, with an instruction on it the reader knows, is
4039        // one the reader refused for a reason of its own, and keeping it as text would hand the
4040        // assembler what the reader already said no to. `addq %1, %k0` is that: a quadword add
4041        // into half a register. What is kept is a line with an instruction nothing here knows.
4042        let registered = |index: usize| def_of[index].is_some() || use_of[index].is_some();
4043        if !a64 && (0..list.len()).any(registered) {
4044            for line in template.split(['\n', ';']) {
4045                if names_one(line, registered)
4046                    && x86_64::known(line, widths, memory)
4047                    && x86_64::read_in(line, widths, memory).is_none()
4048                {
4049                    return Err(refused());
4050                }
4051            }
4052        }
4053
4054        let mut text = String::with_capacity(template.len());
4055        let mut memory: Option<usize> = None;
4056        if basic {
4057            text.push_str(template);
4058        } else {
4059            let mut chars = template.chars().peekable();
4060            // Inside `{att|intel}`, and past the `|` in it, which is the half nobody reads. AArch64
4061            // has one dialect, and a brace there is a list of vector registers.
4062            let mut dialect = false;
4063            let mut skipped = false;
4064            while let Some(c) = chars.next() {
4065                match c {
4066                    '{' if !a64 => {
4067                        dialect = true;
4068                        continue;
4069                    }
4070                    '|' if dialect => {
4071                        skipped = true;
4072                        continue;
4073                    }
4074                    '}' if dialect => {
4075                        dialect = false;
4076                        skipped = false;
4077                        continue;
4078                    }
4079                    _ if skipped => continue,
4080                    '%' => {}
4081                    _ => {
4082                        text.push(c);
4083                        continue;
4084                    }
4085                }
4086                match chars.peek().copied() {
4087                    Some(c @ ('%' | '{' | '|' | '}')) => {
4088                        chars.next();
4089                        text.push(c);
4090                        continue;
4091                    }
4092                    Some('=') => {
4093                        chars.next();
4094                        text.push_str(&inst.index().to_string());
4095                        continue;
4096                    }
4097                    _ => {}
4098                }
4099                let modifier = match chars.peek().copied() {
4100                    Some(c) if c.is_ascii_alphabetic() => {
4101                        chars.next();
4102                        Some(c)
4103                    }
4104                    _ => None,
4105                };
4106                let mut digits = String::new();
4107                while let Some(c) = chars.peek().copied().filter(char::is_ascii_digit) {
4108                    digits.push(c);
4109                    chars.next();
4110                }
4111                let index: usize = digits.parse().map_err(|_| refused())?;
4112                let operand = list.get(index).ok_or_else(refused)?;
4113                if operand.memory && a64 {
4114                    let at = use_of[index].map(|at| first_use + at).ok_or_else(refused)?;
4115                    if modifier.is_some() {
4116                        return Err(refused());
4117                    }
4118                    text.push('[');
4119                    text.push_str(&template_reg(at, 'x'));
4120                    text.push(']');
4121                    continue;
4122                }
4123                if operand.memory {
4124                    if modifier.is_some() || memory.is_some_and(|had| had != index) {
4125                        return Err(refused());
4126                    }
4127                    memory = Some(index);
4128                    text.push_str(x86_64::TEMPLATE_MEM);
4129                    continue;
4130                }
4131                let placed = def_of[index].or(use_of[index].map(|at| first_use + at));
4132                if let Some(at) = placed {
4133                    let value = operand.result.or(operand.value).ok_or_else(refused)?;
4134                    let bits = held_bits(self.source[value].ty);
4135                    // `w` and `x` are the two names every general purpose register has, and one
4136                    // with no modifier is named at the width of its type, as gcc names it. A
4137                    // vector register with no modifier is `v`, which is what gcc writes for one
4138                    // whatever is in it, and the modifiers name the scalar views of it.
4139                    let width = if a64 && files[index] != self.gpr {
4140                        match modifier {
4141                            None => 'v',
4142                            Some(view @ ('b' | 'h' | 's' | 'd' | 'q')) => view,
4143                            Some(_) => return Err(refused()),
4144                        }
4145                    } else if a64 {
4146                        match (modifier, bits) {
4147                            (None, 8 | 16 | 32) | (Some('w'), _) => 'w',
4148                            (None, 64) | (Some('x'), _) => 'x',
4149                            _ => return Err(refused()),
4150                        }
4151                    } else {
4152                        match modifier {
4153                            None => match held_bits(self.source[value].ty) {
4154                                8 => 'b',
4155                                16 => 'w',
4156                                32 => 'k',
4157                                64 => 'q',
4158                                _ => return Err(refused()),
4159                            },
4160                            Some(width @ ('b' | 'w' | 'k' | 'q')) => width,
4161                            // The second byte is a name only four registers have, so it is taken for
4162                            // an operand pinned to one of them and for nothing the allocator chose.
4163                            Some('h') if pinned(operand).and_then(x86_64::gpr_high).is_some() => {
4164                                'h'
4165                            }
4166                            Some(_) => return Err(refused()),
4167                        }
4168                    };
4169                    text.push_str(&template_reg(at, width));
4170                    continue;
4171                }
4172                let value = operand.value.ok_or_else(refused)?;
4173                let bare = match modifier {
4174                    None => false,
4175                    Some('c' | 'P' | 'p') => true,
4176                    Some(_) => return Err(refused()),
4177                };
4178                // A constant is bare on AArch64 whatever the modifier, which is how gcc prints one
4179                // there and a form GNU as takes wherever `#` would go.
4180                if !bare && !a64 {
4181                    text.push('$');
4182                }
4183                if let Some(number) = self.number(value) {
4184                    text.push_str(&number.to_string());
4185                } else if let Some(symbol) = self.named_address(value) {
4186                    text.push_str(&template_name(self.names.resolve(symbol)));
4187                } else {
4188                    return Err(refused());
4189                }
4190            }
4191        }
4192
4193        // An object in this function's frame is named by where it is in the frame, the way gcc
4194        // names it, rather than by a register its address was put in first. The text may write
4195        // registers it does not declare, and tcc's tests do: one that writes `%ecx` behind the
4196        // compiler's back would otherwise take the address with it.
4197        let mut local = None;
4198        let at = match memory.filter(|_| !a64) {
4199            Some(index) => {
4200                let value = list[index].value.ok_or_else(refused)?;
4201                local = self.local_of(value);
4202                let base = match local {
4203                    Some(_) => mir::Reg::physical(self.conv.stack_pointer),
4204                    None => self.reg_of(value)?,
4205                };
4206                Some(mir::Mem::at(mir::Operand::read(base, self.gpr)))
4207            }
4208            None => None,
4209        };
4210        let symbol = self.names.intern(&text);
4211        let opcode = self.named(if a64 { aarch64::TEMPLATE } else { x86_64::TEMPLATE });
4212        let block = self.at.expect("a block is being filled");
4213        let span = self.source.span(inst);
4214        let mut build = self.out.build(block, opcode).at(span).symbol(symbol);
4215        for operand in defs.into_iter().chain(written).chain(uses) {
4216            build = build.operand(operand);
4217        }
4218        if let Some(mem) = at {
4219            build = build.mem(mem);
4220        }
4221        let made = build.finish();
4222        if let Some(local) = local {
4223            self.stack.addresses.push((made, local));
4224        }
4225        Ok(())
4226    }
4227
4228    /// The object in this function's frame a value is the address of, for one an `alloca` of a
4229    /// size known here made. See [`Self::reserve`], which is where the `lea` it is found by came
4230    /// from.
4231    fn local_of(&self, value: Value) -> Option<usize> {
4232        let Def::Result { inst, .. } = self.source[value].def else { return None };
4233        if self.source[inst].opcode != Opcode::Alloca
4234            || !self.source[self.source[inst].args].is_empty()
4235        {
4236            return None;
4237        }
4238        let reg = self.regs[value.index()]?;
4239        self.stack.addresses.iter().find_map(|&(made, local)| {
4240            let data = &self.out[made];
4241            let defined = self.out[data.operands].first()?;
4242            (defined.reg == reg).then_some(local)
4243        })
4244    }
4245
4246    /// The name a value is the address of, for one a `global_addr` defined.
4247    fn named_address(&self, value: Value) -> Option<Symbol> {
4248        let Def::Result { inst, .. } = self.source[value].def else { return None };
4249        if self.source[inst].opcode != Opcode::GlobalAddr {
4250            return None;
4251        }
4252        let Extra::Symbol(symbol) = self.source[inst].extra else { return None };
4253        Some(symbol)
4254    }
4255
4256    /// A register holding a zero, for an operand of a template that is read before anything filled
4257    /// it.
4258    ///
4259    /// Two things ask for this and they are the same thing twice. An output the template reads has
4260    /// nothing to be read out of until the instruction that writes it has run, and a loop carries
4261    /// an operand into a block before the instruction that fills it, so both are a use in front of
4262    /// every definition. What the program is owed there is nothing, since the value is undefined
4263    /// either way, and what the allocator is owed is a register something wrote.
4264    fn seeded(&mut self, inst: Inst, operand: AsmOperand<'_>) -> Result<mir::Reg, Unsupported> {
4265        let refused = || Unsupported::Assembly { inst, refused: Written::Operand };
4266        let value = operand.result.or(operand.value).ok_or_else(refused)?;
4267        let class = self.class_of(self.source[value].ty);
4268        if class != self.gpr {
4269            return Err(refused());
4270        }
4271        let block = self.at.expect("a block is being filled");
4272        let reg = self.out.new_vreg(class);
4273        let put = self.named("mov_ri_64");
4274        self.out.build(block, put).at(self.source.span(inst)).def(reg, class).imm(0).finish();
4275        Ok(reg)
4276    }
4277
4278    /// A template with labels in it, as the blocks its jumps leave and arrive at.
4279    ///
4280    /// A statement is an instruction of the IR and stands inside one block, so a template that
4281    /// jumps has to stop being one thing. Each label becomes a block, each jump ends the block it
4282    /// stands in and gives it two arms, and whatever follows the statement goes into whichever
4283    /// block the walk finished in, which is what [`Self::block`] already reads off `self.at` and
4284    /// what [`Self::saves_place`] already does for the same reason.
4285    ///
4286    /// # What is carried between them
4287    ///
4288    /// The machine IR here is in the form where a register is written once, so an operand written
4289    /// inside a loop and read again at the top of it cannot be one register. What arrives at the
4290    /// top is a parameter of that block, and every jump to it carries whichever register held the
4291    /// operand where the jump stands. That is the whole of the bookkeeping: every block a label
4292    /// made takes one parameter for each operand that is in a register at all, in one order, so an
4293    /// arm's arguments and a block's parameters are the same list read twice.
4294    ///
4295    /// Which register an operand is in at each point is kept in the read half of its place, since
4296    /// that is what the instructions below read it out of. An instruction that writes an operand
4297    /// leaves it in the register it wrote, and a jump below carries that one. The block an
4298    /// untaken jump falls into is arrived at one way only and so takes no parameters, and nothing
4299    /// about where the operands are changes there.
4300    ///
4301    /// An operand written by the template and filled by nothing is written as a zero first, for
4302    /// the reason [`Self::undefined`] gives and one more: a jump may carry it before the
4303    /// instruction that fills it has run, and an argument has to be a register something wrote.
4304    ///
4305    /// # The condition state
4306    ///
4307    /// Nothing carries it and nothing has to. The instruction that sets it and the jump that reads
4308    /// it are both written here, next to each other in one block, and what the allocator may put
4309    /// between them is a move, which on this machine leaves the condition state alone. The edge
4310    /// into a block a loop goes back to is a critical edge and `crate::split` gives it a block of
4311    /// its own, so the moves an arm turns into land behind the jump rather than in front of it.
4312    fn woven(
4313        &mut self,
4314        inst: Inst,
4315        steps: &[x86_64::Step],
4316        places: &mut [Place],
4317        list: &[AsmOperand<'_>],
4318        clobbered: &[PhysReg],
4319        writes: &[usize],
4320    ) -> Result<(), Unsupported> {
4321        let refused = || Unsupported::Assembly { inst, refused: Written::Operand };
4322        let span = self.source.span(inst);
4323
4324        // Which operands are carried, which is every one that is in a register at all. An operand
4325        // the template never puts in one, such as a constant it names only as the distance into an
4326        // address, is in the instruction and has nowhere to be carried from.
4327        let mut carried: Vec<(usize, RegClass)> = Vec::new();
4328        for (index, operand) in list.iter().enumerate() {
4329            if places[index].read.is_none() && places[index].write.is_none() {
4330                continue;
4331            }
4332            let value = operand.result.or(operand.value).ok_or_else(refused)?;
4333            let ty = self.source[value].ty;
4334            if on_x87(ty) {
4335                return Err(refused());
4336            }
4337            carried.push((index, self.class_of(ty)));
4338        }
4339
4340        // What each of them holds where the template starts.
4341        for &(index, _) in &carried {
4342            if places[index].read.is_some() {
4343                continue;
4344            }
4345            if writes[index] == 0 {
4346                places[index].read = places[index].write;
4347                continue;
4348            }
4349            places[index].read = Some(self.seeded(inst, list[index])?);
4350        }
4351
4352        // The blocks, made before the walk because a jump forwards names a label the walk has not
4353        // reached yet.
4354        let mut labels: Vec<(&str, mir::Block, Vec<mir::Reg>)> = Vec::new();
4355        for step in steps {
4356            let x86_64::Step::Label(name) = step else { continue };
4357            let block = self.out.create_block();
4358            let mut params = Vec::with_capacity(carried.len());
4359            for &(_, class) in &carried {
4360                params.push(self.out.append_param(block, class));
4361            }
4362            labels.push((name.as_str(), block, params));
4363        }
4364
4365        let mut wrote: Vec<usize> = Vec::new();
4366        for step in steps {
4367            match step {
4368                x86_64::Step::Label(name) => {
4369                    let (block, params) = Self::went(&labels, name).ok_or_else(refused)?;
4370                    let from = self.at.expect("a block is being filled");
4371                    let args = Self::held(places, &carried).ok_or_else(refused)?;
4372                    *self.out.succs_mut(from) = vec![mir::BlockCall::with(block, args)];
4373                    self.at = Some(block);
4374                    for (at, &(index, _)) in carried.iter().enumerate() {
4375                        places[index].read = params.get(at).copied();
4376                    }
4377                }
4378                x86_64::Step::Jump { opcode, to } => {
4379                    let (block, _) = Self::went(&labels, to).ok_or_else(refused)?;
4380                    let from = self.at.expect("a block is being filled");
4381                    let args = Self::held(places, &carried).ok_or_else(refused)?;
4382                    let opcode = self.named(opcode);
4383                    self.out.build(from, opcode).at(span).finish();
4384                    let next = self.out.create_block();
4385                    *self.out.succs_mut(from) =
4386                        vec![mir::BlockCall::with(block, args), mir::BlockCall::to(next)];
4387                    self.at = Some(next);
4388                }
4389                x86_64::Step::Away { symbol } => {
4390                    // Only in a function that is written without a prologue, which is the one
4391                    // place the jump means what it says. Anywhere else there is an epilogue behind
4392                    // the statement that puts the registers back and gives the frame up, and a
4393                    // jump over it goes to the next function with this function's frame still
4394                    // taken. The reader already made sure it is the last step of the template, so
4395                    // what is left to ask is about the function around it.
4396                    if !self.source.attrs.set.contains(AttrSet::NAKED) {
4397                        return Err(Unsupported::Assembly { inst, refused: Written::Away });
4398                    }
4399                    let from = self.at.expect("a block is being filled");
4400                    let opcode = self.named(AWAY);
4401                    let symbol = self.names.intern(symbol);
4402                    self.out.build(from, opcode).at(span).symbol(symbol).finish();
4403                    // Nowhere, which is what a jump out of the function leaves behind it and is
4404                    // the same list a `ret` leaves. The block after it is made for the walk above
4405                    // rather than for the program: the statement may be in the middle of a body
4406                    // that goes on being lowered, and what that lowering writes is reached by
4407                    // nothing and thrown away with the block.
4408                    *self.out.succs_mut(from) = Vec::new();
4409                    self.at = Some(self.out.create_block());
4410                }
4411                x86_64::Step::Call { symbol } => {
4412                    self.call_out(inst, symbol, places, list, clobbered, &carried, &mut wrote)?;
4413                }
4414                x86_64::Step::Line(line) => {
4415                    let form = x86_64::form(line.opcode).ok_or_else(refused)?;
4416                    let mut written = Vec::new();
4417                    for (desc, piece) in form.operands().iter().zip(&line.operands) {
4418                        if !desc.role.is_def() {
4419                            continue;
4420                        }
4421                        let index = match *piece {
4422                            x86_64::Piece::Operand { index, .. } => index,
4423                            x86_64::Piece::Implicit { reg } => match bound(list, reg, desc.role) {
4424                                Some(index) => index,
4425                                None => continue,
4426                            },
4427                            x86_64::Piece::Reg { reg, .. } => match bound(list, reg, desc.role) {
4428                                Some(index) => index,
4429                                None => continue,
4430                            },
4431                        };
4432                        written.push(index);
4433                    }
4434                    // A register is written once in this form of the machine IR, so an operand
4435                    // an instruction above already wrote is written into a new one here, and what
4436                    // reads it below reads that one.
4437                    for &index in &written {
4438                        if !wrote.contains(&index) {
4439                            wrote.push(index);
4440                            continue;
4441                        }
4442                        let &(_, class) =
4443                            carried.iter().find(|&&(at, _)| at == index).ok_or_else(refused)?;
4444                        let place = places.get_mut(index).ok_or_else(refused)?;
4445                        place.write = Some(self.out.new_vreg(class));
4446                    }
4447                    self.instruction(inst, line, places, list, clobbered)?;
4448                    for index in written {
4449                        let place = places.get_mut(index).ok_or_else(refused)?;
4450                        if place.write.is_some() {
4451                            place.read = place.write;
4452                        }
4453                    }
4454                }
4455            }
4456        }
4457
4458        // Where the walk left each output, which is the parameter of the block a label made when
4459        // the template ends in one and the register an instruction wrote when it does not.
4460        for (index, operand) in list.iter().enumerate() {
4461            let Some(result) = operand.result else { continue };
4462            if let Some(reg) = places[index].read {
4463                self.regs[result.index()] = Some(reg);
4464            }
4465        }
4466        Ok(())
4467    }
4468
4469    /// A template's call to a function somewhere else, as the call the convention makes.
4470    ///
4471    /// The opcode is the one a call written in C becomes, so everything that asks whether a
4472    /// function calls anything gets the answer it would for one: the stack pointer is left aligned
4473    /// at the statement and nothing is kept in the red zone. What is not the same is the operands.
4474    /// Nothing is passed by the convention, since the template put the arguments where it wanted
4475    /// them, and what comes back is whatever an output is pinned to, since that is the only thing
4476    /// the template says about it. Every other register the callee may leave anything in is
4477    /// written here, which is what a program that calls from a template never says and always
4478    /// means.
4479    #[allow(clippy::too_many_arguments)]
4480    fn call_out(
4481        &mut self,
4482        inst: Inst,
4483        symbol: &str,
4484        places: &mut [Place],
4485        list: &[AsmOperand<'_>],
4486        clobbered: &[PhysReg],
4487        carried: &[(usize, RegClass)],
4488        wrote: &mut Vec<usize>,
4489    ) -> Result<(), Unsupported> {
4490        let refused = || Unsupported::Assembly { inst, refused: Written::Operand };
4491        let mut operands = Vec::new();
4492        let mut written = Vec::new();
4493        let lost = self.lost(list);
4494        for &(reg, class, index) in &lost {
4495            let Some(index) = index else {
4496                operands.push(mir::Operand::write(mir::Reg::physical(reg), class));
4497                continue;
4498            };
4499            // Written once in this form of the machine IR, so a second write is a new register,
4500            // the same as for an instruction in [`Self::woven`].
4501            if wrote.contains(&index) {
4502                let &(_, class) =
4503                    carried.iter().find(|&&(at, _)| at == index).ok_or_else(refused)?;
4504                places.get_mut(index).ok_or_else(refused)?.write = Some(self.out.new_vreg(class));
4505            } else {
4506                wrote.push(index);
4507            }
4508            let place = places.get(index).ok_or_else(refused)?.write.ok_or_else(refused)?;
4509            operands.push(mir::Operand::write(place, class).with(Constraint::Fixed(reg)));
4510            written.push(index);
4511        }
4512        for &reg in clobbered {
4513            if lost.iter().all(|&(gone, class, _)| gone != reg || class != self.gpr) {
4514                operands.push(mir::Operand::write(mir::Reg::physical(reg), self.gpr));
4515            }
4516        }
4517        let block = self.at.expect("a block is being filled");
4518        let span = self.source.span(inst);
4519        let opcode = mir::Opcode::new(self.names.intern(abi::CALL));
4520        let symbol = self.names.intern(symbol);
4521        let mut build = self.out.build(block, opcode).at(span).symbol(symbol);
4522        for operand in operands {
4523            build = build.operand(operand);
4524        }
4525        build.finish();
4526        let calls = &mut self.stack.calls;
4527        *calls = Some(calls.unwrap_or(0));
4528        for index in written {
4529            let place = places.get_mut(index).ok_or_else(refused)?;
4530            place.read = place.write;
4531        }
4532        Ok(())
4533    }
4534
4535    /// Every register a call may leave anything in, with its file and the output pinned to it if
4536    /// one is.
4537    ///
4538    /// A register is asked about with its file, since the two files are numbered from nought alike
4539    /// and a question about `v8` alone would find an output pinned to `x8`.
4540    fn lost(&self, list: &[AsmOperand<'_>]) -> Vec<(PhysReg, RegClass, Option<usize>)> {
4541        let conv = self.conv;
4542        let ints = conv.int_order.iter().filter(|&&reg| !conv.preserves_int(reg));
4543        let sses = conv.sse_order.iter().filter(|&&reg| !conv.preserves_sse(reg));
4544        let written = |reg, class| {
4545            list.iter().position(|operand| {
4546                operand.result.is_some() && self.pinned_here(operand) == Some((reg, class))
4547            })
4548        };
4549        ints.map(|&reg| (reg, conv.int_class, written(reg, conv.int_class)))
4550            .chain(sses.map(|&reg| (reg, conv.sse_class, written(reg, conv.sse_class))))
4551            .collect()
4552    }
4553
4554    /// The input an output read before anything wrote it shares its register with, which is the
4555    /// one input that could be in that register, or nothing when there is none or more than one.
4556    ///
4557    /// Could be means nothing ties it elsewhere: it is in a register rather than in memory, no
4558    /// constraint pins it anywhere the output is not, and it is not tied to another output. An
4559    /// output written `&` shares nothing, since the assembly writes it before it reads the inputs.
4560    fn shared(&self, list: &[AsmOperand<'_>], index: usize) -> Option<Value> {
4561        let output = list.get(index)?;
4562        if output.early || output.tied.is_some() {
4563            return None;
4564        }
4565        let class = self.class_of(self.source[output.result?].ty);
4566        let mut fits = list.iter().filter(|operand| {
4567            operand.result.is_none()
4568                && !operand.memory
4569                && operand.tied.is_none()
4570                && operand.value.is_some_and(|value| self.class_of(self.source[value].ty) == class)
4571                && pinned(operand).is_none_or(|reg| pinned(output) == Some(reg))
4572        });
4573        let value = fits.next()?.value;
4574        if fits.next().is_some() {
4575            return None;
4576        }
4577        value
4578    }
4579
4580    /// The block one of the template's labels made, and the parameters it takes.
4581    fn went<'b>(
4582        labels: &'b [(&str, mir::Block, Vec<mir::Reg>)],
4583        name: &str,
4584    ) -> Option<(mir::Block, &'b [mir::Reg])> {
4585        labels
4586            .iter()
4587            .find(|(had, ..)| *had == name)
4588            .map(|(_, block, params)| (*block, params.as_slice()))
4589    }
4590
4591    /// The register each carried operand is in, which is what an arm to a label carries.
4592    fn held(places: &[Place], carried: &[(usize, RegClass)]) -> Option<Vec<mir::Reg>> {
4593        carried.iter().map(|&(index, _)| places.get(index)?.read).collect()
4594    }
4595
4596    /// The registers a clobber list names, in the order it named them.
4597    ///
4598    /// Nothing is dropped. A name this has no register for is refused, because the list is the
4599    /// program telling the compiler which registers it may not leave anything in, and an entry
4600    /// nobody read is a register something may still be left in. See [`Self::assembly`] for the
4601    /// two entries that are not registers and for why they are skipped rather than refused.
4602    fn clobbered(inst: Inst, clobbers: &str) -> Result<Vec<PhysReg>, Unsupported> {
4603        let refused = || Unsupported::Assembly { inst, refused: Written::Clobber };
4604        let mut named = Vec::new();
4605        for entry in clobbers.split(',') {
4606            let entry = entry.trim().trim_matches('"');
4607            // The sigil is optional in a clobber list and means nothing when it is there, unlike
4608            // in a template, where it is what tells a register from an operand.
4609            let entry = entry.strip_prefix('%').unwrap_or(entry);
4610            if entry.is_empty() || matches!(entry, "memory" | "cc" | "flags") {
4611                continue;
4612            }
4613            let (reg, _) = x86_64::gpr_named(entry).ok_or_else(refused)?;
4614            if !named.contains(&reg) {
4615                named.push(reg);
4616            }
4617        }
4618        Ok(named)
4619    }
4620
4621    /// [`Self::clobbered`] on AArch64, where a clobber may name a vector register as well as a
4622    /// general purpose one, so each comes back with the file it is in. See [`aarch64::named`].
4623    fn clobbered_a64(inst: Inst, clobbers: &str) -> Result<Vec<(PhysReg, RegClass)>, Unsupported> {
4624        let refused = || Unsupported::Assembly { inst, refused: Written::Clobber };
4625        let mut named = Vec::new();
4626        for entry in clobbers.split(',') {
4627            let entry = entry.trim().trim_matches('"');
4628            if entry.is_empty() || matches!(entry, "memory" | "cc") {
4629                continue;
4630            }
4631            let reg = aarch64::named(entry).ok_or_else(refused)?;
4632            if !named.contains(&reg) {
4633                named.push(reg);
4634            }
4635        }
4636        Ok(named)
4637    }
4638
4639    /// Whether the machine being lowered for is AArch64.
4640    fn on_aarch64(&self) -> bool {
4641        std::ptr::eq(self.selector.shapes, &aarch64::MACHINE)
4642    }
4643
4644    /// The register an operand is pinned to on the machine being lowered for.
4645    ///
4646    /// [`pinned`] on x86, where it is always a general purpose register. AArch64 has no constraint
4647    /// letter for one register, so there only a local register variable pins anything, and its name
4648    /// is read against [`aarch64::named`], which may put it in either file. The file comes back with
4649    /// the register because the two are numbered from nought alike, and `x8` is not `v8`.
4650    fn pinned_here(&self, operand: &AsmOperand<'_>) -> Option<(PhysReg, RegClass)> {
4651        if !self.on_aarch64() {
4652            return pinned(operand).map(|reg| (reg, self.gpr));
4653        }
4654        let name = operand.named?;
4655        aarch64::named(name.strip_prefix('%').unwrap_or(name))
4656    }
4657
4658    /// An `asm` statement on AArch64, which is kept as text whatever is in it.
4659    ///
4660    /// Nothing reads AArch64 assembly back into instructions yet, so every template goes the way
4661    /// one the x86 reader could not take apart goes, which is [`Self::kept`]: the text is carried
4662    /// to the listing with a hole for each operand, and the operands are the instruction's own. A
4663    /// constraint with a letter whose meaning differs between the two machines is refused first.
4664    /// See [`shared_letters`].
4665    fn spelled(&mut self, inst: Inst) -> Result<(), Unsupported> {
4666        let data = &self.source[inst];
4667        let Extra::Asm(asm) = data.extra else { return Err(self.unsupported(inst)) };
4668        let info = self.source[asm];
4669        if !self.source[info.targets].is_empty() {
4670            return Err(Unsupported::Assembly { inst, refused: Written::Goto });
4671        }
4672        let refused = || Unsupported::Assembly { inst, refused: Written::Operand };
4673        let constraints = self.names.resolve(info.constraints).to_string();
4674        if !constraints.split(',').all(shared_letters) {
4675            return Err(refused());
4676        }
4677        // `Q` is memory addressed by one register and nothing else, which is how every operand in
4678        // memory is spelled here already, so it is read as `m`. See [`shared_letters`].
4679        let constraints = letters_outside(&constraints, |c| if c == 'Q' { 'm' } else { c });
4680        let results: Vec<Value> = data.results().collect();
4681        let operands = AsmOperands::read(&constraints, &results, &self.source[data.args])
4682            .ok_or_else(refused)?;
4683        let list: Vec<AsmOperand<'_>> = operands.iter().copied().collect();
4684        let widths = vec![None; list.len()];
4685        let memory: Vec<bool> = list.iter().map(|operand| operand.memory).collect();
4686        let template = self.names.resolve(info.template).to_string();
4687        self.kept(inst, &template, &list, &widths, &memory)
4688    }
4689
4690    /// One instruction of a template, as the machine instruction it was read back into.
4691    fn instruction(
4692        &mut self,
4693        inst: Inst,
4694        line: &x86_64::Line,
4695        places: &[Place],
4696        list: &[AsmOperand<'_>],
4697        clobbered: &[PhysReg],
4698    ) -> Result<(), Unsupported> {
4699        let refused = || Unsupported::Assembly { inst, refused: Written::Operand };
4700        let form = x86_64::form(line.opcode).ok_or_else(refused)?;
4701        // What the instruction reaches and what is in each of them. The description answers the
4702        // first for every opcode but one, and the pieces the template was read into answer the
4703        // second. Bytes a program wrote out itself are the one, since nothing in a number is a
4704        // register anybody could read, so the constraint letters answer both. See
4705        // [`Self::lettered`].
4706        let lettered = (line.opcode == x86_64::LITERAL).then(|| self.lettered(list));
4707        let (described, pieces) = match &lettered {
4708            Some((described, pieces)) => (described.as_slice(), pieces.as_slice()),
4709            None => (form.operands(), line.operands.as_slice()),
4710        };
4711        let mut built = Vec::with_capacity(pieces.len() + clobbered.len());
4712        for (desc, piece) in described.iter().zip(pieces) {
4713            built.push(self.placed(inst, *desc, *piece, places, list)?);
4714        }
4715        // The clobbers go in among the definitions rather than behind the reads, because an operand
4716        // vector in the machine IR is every definition and then every use and what counts them
4717        // reads that order rather than each operand's role.
4718        let defs = built.iter().take_while(|operand| operand.role.is_def()).count();
4719        let mut added = 0usize;
4720        for &reg in clobbered {
4721            if described.iter().any(|desc| desc.constraint == Constraint::Fixed(reg)) {
4722                continue;
4723            }
4724            built.insert(defs, mir::Operand::write(mir::Reg::physical(reg), self.gpr));
4725            added += 1;
4726        }
4727        // A constraint tying one operand to another names it by its place in this vector, and the
4728        // clobbers were put in the middle of the vector, so everything behind them moved. The
4729        // description is written against an instruction with no clobbers in it and cannot know
4730        // that, which makes this the one place the two numberings have to be reconciled.
4731        for operand in &mut built {
4732            if let Constraint::Reuse(at) = operand.constraint {
4733                if usize::from(at) >= defs {
4734                    let moved = usize::from(at) + added;
4735                    operand.constraint =
4736                        Constraint::Reuse(u8::try_from(moved).map_err(|_| refused())?);
4737                }
4738            }
4739        }
4740        let at = match line.at {
4741            Some(at) => Some(self.addressed(inst, at, places, list)?),
4742            None => None,
4743        };
4744
4745        let block = self.at.expect("a block is being filled");
4746        let span = self.source.span(inst);
4747        let opcode = self.named(line.opcode);
4748        let mut build = self.out.build(block, opcode).at(span);
4749        for operand in built {
4750            build = build.operand(operand);
4751        }
4752        if let Some(value) = line.imm {
4753            build = build.imm(value);
4754        }
4755        if let Some(mem) = at {
4756            build = build.mem(mem);
4757        }
4758        build.finish();
4759        Ok(())
4760    }
4761
4762    /// The registers a run of bytes reaches, taken from the constraint letters rather than from the
4763    /// description of an opcode.
4764    ///
4765    /// Every other instruction of a template has a description saying which registers it reaches
4766    /// without naming them, and [`Self::assembly`] matches the letters against that. Bytes a program
4767    /// wrote out itself have no such description and could not have one: what the instruction is, is
4768    /// a number, and nothing in a number is a register anything could read. So the letters are the
4769    /// whole of what is known, and they are enough, because a program writing an instruction this
4770    /// way has to say where its operands go for exactly the reason a program writing `cpuid` does.
4771    ///
4772    /// Each register named by a letter gets one entry for the write and one for the read, the same
4773    /// two `cpuid` has, and only the half the statement asked for: a register no output names is not
4774    /// written here and one no input names is not read. The writes come first because that is the
4775    /// order an operand vector in the machine IR is counted in. A register named by nothing is left
4776    /// out rather than given a spare one, which is the difference from `cpuid` and is right for the
4777    /// same reason: `cpuid` writes four registers whatever the program said, and what these bytes
4778    /// touch is known only from what the program said.
4779    fn lettered(&self, list: &[AsmOperand<'_>]) -> (Vec<OperandDesc>, Vec<x86_64::Piece>) {
4780        let mut named: Vec<PhysReg> = Vec::new();
4781        for operand in list {
4782            if let Some(reg) = pinned(operand) {
4783                if !named.contains(&reg) {
4784                    named.push(reg);
4785                }
4786            }
4787        }
4788        let mut described = Vec::with_capacity(named.len() * 2);
4789        let mut pieces = Vec::with_capacity(named.len() * 2);
4790        for role in [Role::Def, Role::Use] {
4791            for &reg in &named {
4792                if bound(list, reg, role).is_none() {
4793                    continue;
4794                }
4795                let desc = if role.is_def() {
4796                    OperandDesc::write(self.gpr)
4797                } else {
4798                    OperandDesc::read(self.gpr)
4799                };
4800                described.push(desc.with(Constraint::Fixed(reg)));
4801                pieces.push(x86_64::Piece::Implicit { reg });
4802            }
4803        }
4804        (described, pieces)
4805    }
4806
4807    /// One operand of one instruction of a template, in the register the statement put it in.
4808    fn placed(
4809        &mut self,
4810        inst: Inst,
4811        desc: OperandDesc,
4812        piece: x86_64::Piece,
4813        places: &[Place],
4814        list: &[AsmOperand<'_>],
4815    ) -> Result<mir::Operand, Unsupported> {
4816        let refused = || Unsupported::Assembly { inst, refused: Written::Operand };
4817        // A register the instruction reaches without its text naming it belongs to whichever of the
4818        // statement's operands a constraint letter put there, and to nobody when no letter did.
4819        // There is no width to check in that case: the operand is the register the letter named and
4820        // the instruction does what it does to it, which is what a program writing `"=a"` asked for.
4821        let (index, spelled) = match piece {
4822            x86_64::Piece::Operand { index, width, stated } => (index, Some((width, stated))),
4823            x86_64::Piece::Implicit { reg } => match bound(list, reg, desc.role) {
4824                Some(index) => (index, None),
4825                None => return self.spare(inst, desc),
4826            },
4827            // A register the template named, which belongs to one of the statement's operands when
4828            // a constraint letter put that operand there and to nobody otherwise. Asked in that
4829            // order rather than placed straight away, because `"D" (p)` with `%rdi` in the text is
4830            // the program saying one thing twice, and answering it twice would hand the allocator
4831            // one register holding two values.
4832            x86_64::Piece::Reg { reg, .. } => match bound(list, reg, desc.role) {
4833                Some(index) => (index, None),
4834                None => return self.itself(inst, desc, reg),
4835            },
4836        };
4837        let operand = list.get(index).copied().ok_or_else(refused)?;
4838        // The two halves of an operand written `+`, which arrives in one register and leaves in
4839        // another with the allocator told to make them the same one. Everything else has one of
4840        // the two and asking for the other is the refusal below.
4841        let place = places.get(index).copied().ok_or_else(refused)?;
4842        let reg = match desc.role {
4843            Role::Use => place.read,
4844            Role::Def | Role::EarlyDef => place.write,
4845        }
4846        .ok_or_else(refused)?;
4847
4848        // Read where the opcode reads and written where it writes, which is what the first half of
4849        // this asks. An output has a result and an input has a value, an output written `+` has
4850        // both because it is read before it is written, and an output a matching constraint names
4851        // is read as the input that named it. See [`read_as`].
4852        // An output with neither is read as well, and what it holds there is undefined, which
4853        // [`Self::assembly`] says why and puts a zero in a register for.
4854        let placeable = match desc.role {
4855            Role::Use => read_as(list, index).is_some() || operand.result.is_some(),
4856            Role::Def | Role::EarlyDef => operand.result.is_some(),
4857        };
4858        let ty = match (operand.result, operand.value) {
4859            (Some(result), _) => self.source[result].ty,
4860            (None, Some(value)) => self.source[value].ty,
4861            (None, None) => return Err(refused()),
4862        };
4863        let bits = held_bits(ty);
4864        if !placeable || self.class_of(ty) != desc.class {
4865            return Err(refused());
4866        }
4867        if let Some((width, stated)) = spelled {
4868            // An operand the template wrote a width on may be written by an instruction that fills
4869            // more of the register than the object in it does, and the object is then the low part
4870            // of what was written. That is what gmp asks for when it counts the low zero bits of a
4871            // limb into an `unsigned` and spells the count `%q0`: one quadword instruction writes
4872            // the whole register and the `unsigned` is the bottom of it, which is every bit of an
4873            // answer that cannot exceed sixty four anyway.
4874            //
4875            // An operand read at a width the template wrote is the other way round: the object is
4876            // in the register and the instruction looks at the bottom of it. tcc tests the low bits
4877            // of a `size_t` count with `testb $2,%b4`, and every bit that test reads is one the
4878            // object put there.
4879            //
4880            // A write of less of a register than the object fills is right in one case, which is
4881            // an instruction that reads the register it writes and an operand that arrives with
4882            // the object in it. The top of the register is then the top of the object, and the
4883            // instruction leaves it alone. tcc swaps the bytes of an `unsigned` with `xchgb
4884            // %b0,%h0` and a rotate between two of them, and the swap only ever touches the low
4885            // half.
4886            //
4887            // The two that stay refused are a read of more of a register than its type fills,
4888            // which hands an instruction bits nothing ever put there, and a write of less of one
4889            // that nothing carried the object into, which leaves the top of the object holding
4890            // whatever the register held before. An operand the template left plain is refused
4891            // either way, because what gets spelled for that one is the register at the width of
4892            // its type and no other instruction is the one written down.
4893            let carried = matches!(desc.constraint, Constraint::Reuse(_) | Constraint::Fixed(_))
4894                && read_as(list, index).is_some();
4895            // The other case is the one the machine settles by itself: a write of the low four
4896            // bytes of a register clears the four above them, so a sixty four bit object written
4897            // that way holds the thirty two bit answer and nothing else. tcc loads a word through
4898            // `movl 4(%0),%k0` into a `long` and means exactly that.
4899            let cleared = desc.class == self.gpr && width == x86_64::Width::Long && bits == 64;
4900            let widened = stated && desc.role.is_def() && width.bits() > bits;
4901            let narrowed =
4902                stated && width.bits() < bits && (!desc.role.is_def() || carried || cleared);
4903            if bits != width.bits() && !widened && !narrowed {
4904                return Err(refused());
4905            }
4906        }
4907        // An operand the program pinned is in that register and nowhere else, whatever the opcode
4908        // would have allowed it. That is the whole of what a local register variable asks for, and
4909        // it is the same shape a division already has: the allocator is told the register, puts a
4910        // move in front or behind where it has to, and leaves it out where it does not.
4911        let constraint = match pinned(&operand) {
4912            Some(reg) => Constraint::Fixed(reg),
4913            None => desc.constraint,
4914        };
4915        Ok(mir::Operand { reg, class: desc.class, role: desc.role, constraint })
4916    }
4917
4918    /// A register the template named in its own text.
4919    ///
4920    /// Not one of the statement's operands and not something the allocator handed out. The program
4921    /// wrote `%rbx` in the middle of a template and meant that register, which is what code doing
4922    /// something the constraint letters cannot say is made of: micropython saves the callee-saved
4923    /// registers into a buffer by name because the whole point of the buffer is that those exact
4924    /// registers are in it, and there is no constraint letter for `%rsp`.
4925    ///
4926    /// So it is placed as itself, fixed to the register the template named. What that buys is the
4927    /// thing gcc does not do: the register becomes part of the instruction the allocator sees, so a
4928    /// write of one is a definition it knows about and will not leave anything of the program's
4929    /// across, and a read of one is a use it will not have put something else in first. gcc copies
4930    /// the text out and a register two things believe they own is a wrong program nothing reports.
4931    /// Here the allocator is told, and a program that also named the register in its clobber list
4932    /// says the same thing twice rather than something new.
4933    fn itself(
4934        &mut self,
4935        inst: Inst,
4936        desc: OperandDesc,
4937        reg: PhysReg,
4938    ) -> Result<mir::Operand, Unsupported> {
4939        let refused = Unsupported::Assembly { inst, refused: Written::Operand };
4940        if desc.class != self.gpr {
4941            return Err(refused);
4942        }
4943        Ok(mir::Operand {
4944            reg: mir::Reg::physical(reg),
4945            class: self.gpr,
4946            role: desc.role,
4947            constraint: Constraint::Fixed(reg),
4948        })
4949    }
4950
4951    /// A register an instruction of a template uses and the statement put nothing in.
4952    ///
4953    /// A write of one is the register being destroyed, which is what a clobber list is usually
4954    /// written to say and what an instruction with more answers than the program asked for does
4955    /// anyway: `cpuid` writes all four registers whether or not the statement wanted all four. A
4956    /// register of its own is the whole of what that needs, since a value nothing reads is one the
4957    /// allocator may put anywhere and is told about so that nothing else is put there.
4958    ///
4959    /// A read of one is a register the instruction looks at and the program never filled, which
4960    /// gcc leaves as whatever happened to be there. A zero is written instead, for the reason
4961    /// [`Self::undefined`] gives: the allocator has to be given a definition before a use, and a
4962    /// zero is the one answer that reads the same on every run.
4963    fn spare(&mut self, inst: Inst, desc: OperandDesc) -> Result<mir::Operand, Unsupported> {
4964        let refused = Unsupported::Assembly { inst, refused: Written::Operand };
4965        if desc.class != self.gpr {
4966            return Err(refused);
4967        }
4968        let reg = self.out.new_vreg(desc.class);
4969        if !desc.role.is_def() {
4970            let block = self.at.expect("a block is being filled");
4971            let span = self.source.span(inst);
4972            let put = self.named("mov_ri_64");
4973            self.out.build(block, put).at(span).def(reg, desc.class).imm(0).finish();
4974        }
4975        Ok(mir::Operand { reg, class: desc.class, role: desc.role, constraint: desc.constraint })
4976    }
4977
4978    /// The address one instruction of a template reads or writes.
4979    fn addressed(
4980        &mut self,
4981        inst: Inst,
4982        at: x86_64::At,
4983        places: &[Place],
4984        list: &[AsmOperand<'_>],
4985    ) -> Result<mir::Mem, Unsupported> {
4986        let refused = || Unsupported::Assembly { inst, refused: Written::Operand };
4987        let base = match at.base {
4988            None => None,
4989            Some(x86_64::Piece::Operand { index, .. }) => {
4990                // The register an address is counted from is read and never written, whatever the
4991                // instruction does to what it finds there.
4992                let reg = places.get(index).and_then(|place| place.read).ok_or_else(refused)?;
4993                Some(mir::Operand::read(reg, self.gpr))
4994            }
4995            // A register the template named, counted from as itself. See [`Self::itself`], and note
4996            // that this is the half of it every one of these templates needs: `movq %rax, 16(%rdi)`
4997            // names one register as the thing being stored and another as where to store it. An
4998            // operand a constraint letter put in that register is that operand, for the reason
4999            // [`Self::placed`] gives.
5000            Some(x86_64::Piece::Reg { reg, .. }) => match bound(list, reg, Role::Use) {
5001                Some(index) => {
5002                    let reg = places.get(index).and_then(|place| place.read).ok_or_else(refused)?;
5003                    Some(mir::Operand::read(reg, self.gpr))
5004                }
5005                None => Some(
5006                    mir::Operand::read(mir::Reg::physical(reg), self.gpr)
5007                        .with(Constraint::Fixed(reg)),
5008                ),
5009            },
5010            // An address counted from a register the instruction reaches without being told is
5011            // not something this machine has: every addressing mode is written out in the text it
5012            // is part of, so a base that got here another way is a base nothing wrote down.
5013            Some(x86_64::Piece::Implicit { .. }) => return Err(refused()),
5014        };
5015        // A distance the template wrote, or the one in an operand the template pointed at, which is
5016        // the same distance said by something that knows how big a thing is. It has to be a number
5017        // the compiler can read at translation time, since it goes in the instruction rather than
5018        // in a register, and an operand holding anything else is refused rather than put somewhere.
5019        let disp = match at.disp {
5020            x86_64::Disp::Number(disp) => disp,
5021            x86_64::Disp::Operand(index) => {
5022                let value =
5023                    list.get(index).and_then(|operand| operand.value).ok_or_else(refused)?;
5024                let number = self.number(value).ok_or_else(refused)?;
5025                i32::try_from(number).map_err(|_| refused())?
5026            }
5027        };
5028        Ok(mir::Mem { base, scale: 1, disp, segment: at.segment, ..mir::Mem::default() })
5029    }
5030
5031    /// The number in that value, for one an `iconst` defined, read at the width of its own type.
5032    ///
5033    /// Signed, because the two things a template asks this for are a distance into an address and
5034    /// the number on an instruction, and both of those are signed wherever they land. A constant
5035    /// whose type is unsigned and whose top bit is set therefore reads as a negative number here,
5036    /// which is the same number and is the reading that fits in the thirty two bits an addressing
5037    /// mode has room for.
5038    fn number(&self, value: Value) -> Option<i128> {
5039        let Def::Result { inst, .. } = self.source[value].def else { return None };
5040        if self.source[inst].opcode != Opcode::IConst {
5041            return None;
5042        }
5043        let Extra::Imm(imm) = self.source[inst].extra else { return None };
5044        let bits = self.source[imm].bits();
5045        let width = self.source[value].ty.bits();
5046        if width == 0 || width > 128 {
5047            return None;
5048        }
5049        let spare = 128 - width;
5050        Some(((bits << spare) as i128) >> spare)
5051    }
5052
5053    /// A register holding a value the program has no claim on, written as a zero.
5054    ///
5055    /// Every other way of saying it costs the same instruction or needs a word the machine IR does
5056    /// not have, and a zero is the one that reads the same on every run.
5057    fn undefined(&mut self, inst: Inst, result: Value) -> Result<(), Unsupported> {
5058        let ty = self.source[result].ty;
5059        let refused = Unsupported::Assembly { inst, refused: Written::Operand };
5060        let bits = held_bits(ty);
5061        if self.class_of(ty) != self.gpr || !matches!(bits, 8 | 16 | 32 | 64) {
5062            return Err(refused);
5063        }
5064        let block = self.at.expect("a block is being filled");
5065        let span = self.source.span(inst);
5066        let reg = self.new_reg(result);
5067        let put = self.named(&format!("mov_ri_{bits}"));
5068        self.out.build(block, put).at(span).def(reg, self.gpr).imm(0).finish();
5069        Ok(())
5070    }
5071
5072    /// Whether a type is the width an address is, which is what makes a cast to or from one free.
5073    fn is_address_width(&self, ty: Type) -> bool {
5074        ty.is_ptr() || (ty.is_int() && ty.bits() == ADDRESS_BITS)
5075    }
5076
5077    /// Where a block goes, which in machine IR is on the block rather than on its terminator.
5078    ///
5079    /// That is why no rule ever names a block: a branch is selected for what it reads and the
5080    /// edges are copied across here, arguments and all. The arguments are read last, after every
5081    /// instruction of the block is written, because an argument that is a constant is
5082    /// materialized where it is first wanted and the end of the block is where an edge wants it.
5083    ///
5084    /// Which is not quite the end. A block that leaves two ways has the branch as its last
5085    /// instruction, and a block that leaves through a register has the indirect jump as its last,
5086    /// and anything appended after either is something it has already jumped past, so a constant
5087    /// materialized here would be a register the block below reads and nothing ever writes. The
5088    /// one that was there is put back on the end when that happened, which is the only reordering
5089    /// anything in this crate does and is why it is remembered before a single argument is read.
5090    fn edges(&mut self, block: Block, out: mir::Block) -> Result<(), Unsupported> {
5091        let Some(term) = self.source.terminator(block) else { return Ok(()) };
5092        let leaves =
5093            matches!(self.source[term].opcode, Opcode::BrIf | Opcode::IndirectBr | Opcode::Switch);
5094        let branch = if leaves { self.out.terminator(out) } else { None };
5095
5096        let calls: Vec<rucc_ir::BlockCall> = self.source.successors(term).collect();
5097        let mut succs = Vec::with_capacity(calls.len());
5098        for call in calls {
5099            let args: Vec<Value> = self.source[call.args].to_vec();
5100            let mut regs = Vec::with_capacity(args.len());
5101            for value in args {
5102                // The address of where the value is rather than the value, for the one type a
5103                // register holds none of. The block on the other side copies the bytes out of it
5104                // into a slot of its own, which is what makes a second edge into the same block
5105                // safe.
5106                let reg = if on_x87(self.source[value].ty) {
5107                    self.x87_slot(value)
5108                } else {
5109                    self.reg_of(value)?
5110                };
5111                regs.push(reg);
5112            }
5113            succs.push(mir::BlockCall::with(self.out_block(call.block), regs));
5114        }
5115        if let Some(branch) = branch {
5116            if self.out.terminator(out) != Some(branch) {
5117                self.out.remove_inst(branch);
5118                self.out.append_inst(out, branch);
5119            }
5120        }
5121        *self.out.succs_mut(out) = succs;
5122        Ok(())
5123    }
5124
5125    /// The machine IR block an IR block became.
5126    fn out_block(&self, block: Block) -> mir::Block {
5127        self.blocks[block.index()].expect("every block was created before any was filled")
5128    }
5129
5130    /// The parameters of the entry block, which are the function's arguments.
5131    ///
5132    /// They are not block parameters in the machine IR and they cannot be. A block parameter is
5133    /// given its value by a move on the edge into the block, and there is no edge into an entry
5134    /// block, so what arrives in a function is the convention's to say. [`crate::abi`] is what
5135    /// says it.
5136    ///
5137    /// The ones past the last register arrived in the caller's memory and are read out of it, and
5138    /// the loads that read them come back here so that the frame can finish them the way it
5139    /// finishes an `alloca`.
5140    fn arrive(&mut self, block: Block, out: mir::Block) -> Result<(), Unsupported> {
5141        let params = self.source[block].params.clone();
5142        // The type of each is the block's answer and what the ABI asks of it is the signature's,
5143        // and the two lists are the same list: a parameter the classification turned into a
5144        // pointer is a pointer in the block too. A block with more parameters than the signature
5145        // names is not one the front end writes, and each of those is taken as a plain value.
5146        let asked: Vec<Abi> = self.source.signature().params.iter().map(|it| it.abi).collect();
5147        let types: Vec<Param> = params
5148            .iter()
5149            .enumerate()
5150            .map(|(index, &value)| {
5151                let abi = asked.get(index).copied().unwrap_or_default();
5152                Param { ty: self.source[value].ty, abi }
5153            })
5154            .collect();
5155        // A save area for a function that takes arguments its signature does not name, which is a
5156        // block of this function's frame on one convention and the shadow space the caller already
5157        // reserved on the other. Which of the two it is is [`varargs::Area::of`]'s answer and
5158        // [`Self::save_area`] is where the difference is spent.
5159        //
5160        // Apple's AArch64 is neither. Every argument a signature does not name is in the caller's
5161        // memory, so there is nothing to save and the list starts at the first word past the named
5162        // ones.
5163        let variadic = self.source.signature().variadic;
5164        let in_memory = self.conv.abi.variadic == Variadic::AlwaysMemory;
5165        let area = (variadic && !in_memory).then(|| varargs::Area::of(self.conv));
5166        let arrived =
5167            abi::entry(&mut self.out, out, &types, self.conv, self.selector.abi, self.names, area)
5168                .map_err(|(index, missing)| Unsupported::Argument { index, missing })?;
5169        for (&param, reg) in params.iter().zip(&arrived.regs) {
5170            self.regs[param.index()] = Some(*reg);
5171        }
5172        if let Some(area) = area {
5173            self.save_area(out, &arrived, area);
5174        } else if variadic {
5175            let incoming = arrived.beyond.next_multiple_of(self.conv.word);
5176            self.varargs = Some(Varargs::Pointer { incoming });
5177        }
5178        self.stack.arguments.extend(arrived.stack);
5179        Ok(())
5180    }
5181
5182    /// The prologue of a variadic function, which is every argument register it was handed written
5183    /// into the frame.
5184    ///
5185    /// Every one the signature did not name, that is. Which of those hold anything is a thing only
5186    /// the caller knew and there is nothing here to ask, so all of them are written, and the ones a
5187    /// named parameter took are not, because `va_start` sets the two offsets past them and nothing
5188    /// ever reads their slots.
5189    ///
5190    /// What that costs is up to fourteen stores in the prologue of a function that may read none of
5191    /// them, and the convention's answer to that is the count of vector registers in `%al`, which
5192    /// lets a callee skip the eight vector stores when the call passed no floats. Skipping them is a
5193    /// branch in a prologue, and a prologue is written long after this by [`crate::finish`], which
5194    /// has no blocks to branch between. So they are all written every time, which is correct and is
5195    /// what `-O0` costs. Issue #323 is the branch.
5196    ///
5197    /// A vector register is written all sixteen bytes at a time, because a `_Float128` fills one and
5198    /// a `va_arg` of a quad reads the slot back whole. gcc writes the same sixteen with the same
5199    /// instruction, which is what [`crate::varargs`] says a list has to be built out of.
5200    ///
5201    /// The address is computed once into a register rather than written as a displacement off the
5202    /// stack pointer, because a displacement into a frame is not known until after allocation and
5203    /// one `lea` costs less than a fixup list for a dozen stores. It is the same `lea` an `alloca`
5204    /// gets and [`crate::finish`] fills it in the same way.
5205    ///
5206    /// A convention that homes its register arguments has none of that. Its area is the shadow
5207    /// space the caller reserved above the return address, so there is no object to make and no
5208    /// address to work out: each store reaches into the caller's argument area the way the load of
5209    /// a parameter the registers ran out before does, which is the same waiting list and the same
5210    /// fixup. There are at most four of them and none is a vector register, since a float the
5211    /// signature does not name arrived in a general purpose register too and that is the copy the
5212    /// walk reads.
5213    fn save_area(&mut self, out: mir::Block, arrived: &abi::Arrived, area: varargs::Area) {
5214        if self.conv.shared_positions {
5215            self.varargs = Some(Varargs::Pointer { incoming: arrived.beyond });
5216            let store = self.named("mov_mr_64");
5217            for &(reg, class, at) in &arrived.spare {
5218                let sp = mir::Operand::read(mir::Reg::physical(self.conv.stack_pointer), self.gpr);
5219                let made =
5220                    self.out.build(out, store).uses(reg, class).mem(mir::Mem::at(sp)).finish();
5221                self.stack.arguments.push((made, at));
5222            }
5223            return;
5224        }
5225
5226        let save = self.stack.locals.len();
5227        self.stack.locals.push(Local { size: area.size, align: varargs::VECTOR_SLOT });
5228        let took = |count: usize, float: bool| {
5229            let count = u32::try_from(count).unwrap_or(0).min(area.holds(float));
5230            area.starts_at(float) + count * area.stride(float)
5231        };
5232        let integers = took(arrived.took.0, false);
5233        let floats = took(arrived.took.1, true);
5234        self.varargs = Some(if self.conv.list == VaList::Aapcs {
5235            // Minus what is left of each half, since the two offsets count up to its top.
5236            let left = |at: u32, float: bool| {
5237                i32::try_from(at).unwrap_or(0) - i32::try_from(area.ends_at(float)).unwrap_or(0)
5238            };
5239            Varargs::Aapcs {
5240                save,
5241                incoming: arrived.beyond,
5242                integers_end: area.ends_at(false),
5243                floats_end: area.ends_at(true),
5244                integers: left(integers, false),
5245                floats: left(floats, true),
5246            }
5247        } else {
5248            Varargs::Fields { save, incoming: arrived.beyond, integers, floats }
5249        });
5250
5251        // A vector register is saved all sixteen bytes wide, as a quad is, whatever it held.
5252        let base = self.frame_address(out, save);
5253        for &(reg, class, at) in &arrived.spare {
5254            let ty =
5255                if class == self.gpr { Type::int(64) } else { Type::float(rucc_ir::Float::F128) };
5256            let head = (self.selector.abi.store)(ty).expect("a store of a whole register");
5257            let store = mir::Opcode::new(self.names.intern(head));
5258            let up = i32::try_from(at).expect("a register save area under two gigabytes");
5259            let mem = mir::Mem::at(mir::Operand::read(base, self.gpr)).plus(up);
5260            self.out.build(out, store).uses(reg, class).mem(mem).finish();
5261        }
5262    }
5263
5264    /// The address of one of the function's stack objects, in a fresh register.
5265    ///
5266    /// Written with nothing in its displacement, because where an object is in a frame is not known
5267    /// until after allocation, and given to [`crate::finish`] to fill in the way an `alloca` is.
5268    fn frame_address(&mut self, out: mir::Block, local: usize) -> mir::Reg {
5269        self.frame_address_plus(out, local, 0)
5270    }
5271
5272    /// The address some way into a local, which the frame finishes the same way, adding where the
5273    /// local is to what is already there.
5274    fn frame_address_plus(&mut self, out: mir::Block, local: usize, plus: u32) -> mir::Reg {
5275        let reg = self.out.new_vreg(self.gpr);
5276        let lea = self.named(self.selector.frame.lea);
5277        let sp = mir::Operand::read(mir::Reg::physical(self.conv.stack_pointer), self.gpr);
5278        let plus = i32::try_from(plus).expect("an offset into a local under two gigabytes");
5279        let mem = mir::Mem::at(sp).plus(plus);
5280        let made = self.out.build(out, lea).def(reg, self.gpr).mem(mem).finish();
5281        self.stack.addresses.push((made, local));
5282        reg
5283    }
5284
5285    /// Whether an instruction is one no machine instruction is written for where it stands.
5286    ///
5287    /// Four of them, and none is a lowering decision, which is why none is a rule. A constant is
5288    /// written where a register for it is first wanted rather than where the IR put it, and every
5289    /// reader of one may have folded it into an immediate, in which case nowhere is the right
5290    /// place. A return of nothing has nothing to put anywhere: the epilogue gives the frame back
5291    /// and leaves, and it is appended to every block with no successors long after this has
5292    /// finished, so a return with a value is one instruction here and a return without one is
5293    /// none. Unless the value went back through memory, in which case there is something to put
5294    /// somewhere after all and the IR does not carry it: the address the caller handed over has
5295    /// to be in `rax` on the way out, and [`Lowering::returned`] is what writes that.
5296    ///
5297    /// An unconditional jump is the third, and there is even less of it: the edge is on the
5298    /// block, and whether the block it goes to is the next one and needs no jump at all is the
5299    /// block layout's answer rather than this one's.
5300    ///
5301    /// The fourth is a point control does not arrive at, in both of the forms the IR has for it:
5302    /// the `unreachable` terminator the front end puts at the end of a function whose body can run
5303    /// off the bottom, and the `unreachable_hint` a call to `__builtin_unreachable` becomes. What
5304    /// to write for a place nothing reaches is a question with no wrong answer, and nothing is the
5305    /// smallest one and the one gcc 16.2.0 gives at `-O0`. The terminator leaves the block with no
5306    /// successors, so the epilogue lands at the end of it the way it does on any other block that
5307    /// goes nowhere, and the function cannot fall out of its own last instruction into whatever
5308    /// the assembler puts next.
5309    fn writes_nothing(&self, inst: Inst) -> bool {
5310        let data = &self.source[inst];
5311        match data.opcode {
5312            Opcode::IConst | Opcode::Jump | Opcode::Unreachable | Opcode::UnreachableHint => true,
5313            Opcode::Return => self.source[data.args].is_empty() && self.sret().is_none(),
5314            _ => false,
5315        }
5316    }
5317
5318    /// What every instruction in one block matched, with a set of values nobody may take.
5319    ///
5320    /// Backwards, because an instruction that has been folded into a later one does not get to
5321    /// fold anything into itself: the rule that took it only reached one level down, so what is
5322    /// under it is not in the term the matcher saw and cannot be replaced.
5323    fn decide(&self, insts: &[Inst], refused: &HashSet<Value>) -> Decided {
5324        let mut found: Vec<Option<Match<Term>>> = (0..insts.len()).map(|_| None).collect();
5325        let mut plans: Vec<Option<Plan>> = vec![None; insts.len()];
5326        let mut folded: Vec<Inst> = Vec::new();
5327        for (index, &inst) in insts.iter().enumerate().rev() {
5328            if folded.contains(&inst) {
5329                continue;
5330            }
5331            if let Some((plan, matched)) = self.select(inst, refused) {
5332                folded.extend(self.folds(inst, plan));
5333                found[index] = Some(matched);
5334                plans[index] = Some(plan);
5335            }
5336        }
5337        Decided { found, plans, folded }
5338    }
5339
5340    /// A value some of its readers took and some of them did not, which is the one case folding
5341    /// buys nothing.
5342    ///
5343    /// Folding does not delete the instruction that computed a value for anybody else, so a
5344    /// reader that did not take it still needs it in a register and the instruction stays. The
5345    /// reader that did take it now does that work again. Either all of them take it, in which
5346    /// case nothing is left to read it and the instruction goes, or none of them do.
5347    ///
5348    /// The count is over the whole function rather than over the block, since a value read from
5349    /// another block is read from a register there whatever this block decides. An instruction
5350    /// built by name rather than matched, a call being the one that matters, has no plan and so
5351    /// takes nothing, which is the right answer for it as well.
5352    fn left_alive(&self, insts: &[Inst], plans: &[Option<Plan>]) -> Option<Value> {
5353        let mut taken = vec![0u32; self.uses.len()];
5354        for (&inst, plan) in insts.iter().zip(plans) {
5355            let Some(plan) = plan else { continue };
5356            let args = &self.source[self.source[inst].args];
5357            for (index, &arg) in args.iter().take(MAX_ARGS).enumerate() {
5358                if plan[index] == Shown::Expand {
5359                    taken[arg.index()] += 1;
5360                }
5361            }
5362        }
5363        for (&inst, plan) in insts.iter().zip(plans) {
5364            let Some(plan) = plan else { continue };
5365            let args = &self.source[self.source[inst].args];
5366            for (index, &arg) in args.iter().take(MAX_ARGS).enumerate() {
5367                if plan[index] == Shown::Expand && taken[arg.index()] < self.uses[arg.index()] {
5368                    return Some(arg);
5369                }
5370            }
5371        }
5372        None
5373    }
5374
5375    /// The rule that fires on an instruction, and what it bound.
5376    ///
5377    /// The plans are tried in order and the first that matches wins, which is the maximal munch
5378    /// `spec/10-backend.md` asks for: a plan that offers more to the matcher is tried before one
5379    /// that offers less.
5380    fn select(&self, inst: Inst, refused: &HashSet<Value>) -> Option<(Plan, Match<Term>)> {
5381        for plan in self.plans(inst, refused) {
5382            let terms = Terms::new(self.source, inst, plan);
5383            if let Some(matched) = self.selector.table.find(&terms, Term::Root) {
5384                return Some((plan, matched));
5385            }
5386        }
5387        None
5388    }
5389
5390    /// Every way this instruction can be shown to the matcher, most offered first.
5391    fn plans(&self, inst: Inst, refused: &HashSet<Value>) -> Vec<Plan> {
5392        let args = &self.source[self.source[inst].args];
5393        let mut plans = vec![PLAIN];
5394        for (index, &arg) in args.iter().enumerate().take(MAX_ARGS) {
5395            let mut ways = Vec::new();
5396            if self.foldable(inst, arg, refused) {
5397                ways.push(Shown::Expand);
5398            }
5399            if Terms::new(self.source, inst, PLAIN).constant(arg).is_some() {
5400                ways.push(Shown::Const);
5401            }
5402            ways.push(Shown::Reg);
5403            plans = plans
5404                .into_iter()
5405                .flat_map(|plan| {
5406                    ways.iter().map(move |&way| {
5407                        let mut next = plan;
5408                        next[index] = way;
5409                        next
5410                    })
5411                })
5412                .collect();
5413        }
5414        plans
5415    }
5416
5417    /// Whether an operand may be shown as the instruction that computed it.
5418    ///
5419    /// It has to be in the same block, because a rule that folds one instruction into another
5420    /// moves the work to where the second one is. It has to be something rather than a block
5421    /// parameter, and not a constant, which is shown as a constant instead. And it has to be a
5422    /// value [`Lowering::left_alive`] has not put back, which is how the one reader at a time
5423    /// question is asked here: this says yes to a value with any number of readers, and a value
5424    /// only some of them could take is refused after the fact and asked again.
5425    ///
5426    /// A value with several readers used to be refused outright, on the reasoning that folding
5427    /// does not delete the instruction for anybody else. That reasoning is about the set of
5428    /// readers and was being applied to one reader at a time, which is stricter than it needs to
5429    /// be: when every reader takes it there is nobody left to read it and the instruction goes.
5430    /// An address a store and a load share is the shape that matters, since a memory operand has
5431    /// room for the whole of it and both readers have a memory operand.
5432    fn foldable(&self, into: Inst, value: Value, refused: &HashSet<Value>) -> bool {
5433        let Def::Result { inst, .. } = self.source[value].def else { return false };
5434        if self.source[inst].opcode == Opcode::IConst || refused.contains(&value) {
5435            return false;
5436        }
5437        self.source.block_of(inst).is_some()
5438            && self.source.block_of(inst) == self.source.block_of(into)
5439    }
5440
5441    /// The instructions a match folded into the one it matched.
5442    ///
5443    /// The plan is what says this, not the bindings: a binding is a register or a number either
5444    /// way, and an operand shown as the instruction that computed it is one no rule could have
5445    /// matched without taking that instruction, because the plan offered the matcher nothing
5446    /// else to call it.
5447    fn folds(&self, inst: Inst, plan: Plan) -> Vec<Inst> {
5448        let args = &self.source[self.source[inst].args];
5449        args.iter()
5450            .take(MAX_ARGS)
5451            .enumerate()
5452            .filter(|&(index, _)| plan[index] == Shown::Expand)
5453            .filter_map(|(_, &arg)| match self.source[arg].def {
5454                Def::Result { inst, .. } => Some(inst),
5455                Def::Param { .. } => None,
5456            })
5457            .collect()
5458    }
5459
5460    /// What the IR instruction said about itself that the machine instruction has to keep saying.
5461    ///
5462    /// One flag today. `volatile` says the access happens exactly once and is never moved or
5463    /// merged, and nothing below here can work that out again: a `volatile` load and an ordinary
5464    /// one are the same instruction over the same address, so a pass that puts two accesses
5465    /// together would put these together too. Carried rather than checked here, because the pass
5466    /// that has to refuse is a long way down and this is the last place the answer is known.
5467    ///
5468    /// The instructions this compiler writes for itself get nothing, which is the right answer
5469    /// for all of them: a prologue, a spill and the moves around a call were asked for by the
5470    /// machine rather than by the program.
5471    ///
5472    /// Every access the flag is legal on carries it: the loads and the stores a rule matched,
5473    /// the two ends of a `long double` copy that are the program's own memory, and the compare
5474    /// and exchange and the read modify write. An `asm` statement does not, and it is the one
5475    /// exception on purpose. What the flag says there is that the statement stays even when
5476    /// nothing reads what it wrote, which is a different sentence about a different thing, and
5477    /// every `asm` is already fixed where it stands whether the word was written or not.
5478    fn carried(&self, inst: Inst) -> mir::Flags {
5479        if self.source[inst].flags.contains(Flags::VOLATILE) {
5480            mir::Flags::VOLATILE
5481        } else {
5482            mir::Flags::NONE
5483        }
5484    }
5485
5486    /// Build the machine instructions a match calls for.
5487    fn emit(&mut self, inst: Inst, matched: &Match<Term>) -> Result<(), Unsupported> {
5488        let rule: &Rule = self.selector.table.rule(matched);
5489        self.build(inst, rule.replacement, 0, &matched.bindings, true).map(|_| ())
5490    }
5491
5492    /// Build the machine term that starts at `at`, and give back the position after it and the
5493    /// register it wrote, if it wrote one.
5494    ///
5495    /// The outermost term computes what the IR instruction does, so what it writes is the
5496    /// register of the instruction's result. A term inside another is a step on the way and
5497    /// writes a register of its own, which the term around it then reads. Its operands are read
5498    /// before it is built and it is built before the term around it, so the instructions come
5499    /// out in the order the values are needed.
5500    fn build(
5501        &mut self,
5502        inst: Inst,
5503        pieces: &'static [Piece],
5504        at: usize,
5505        bindings: &[Term],
5506        outermost: bool,
5507    ) -> Result<(usize, Option<mir::Reg>), Unsupported> {
5508        let Some(Piece::App { head, arity }) = pieces.get(at) else {
5509            return Err(self.unsupported(inst));
5510        };
5511        let opcode =
5512            head.strip_prefix(self.selector.prefix()).ok_or_else(|| self.unsupported(inst))?;
5513        let descs = self.selector.operands(opcode).ok_or_else(|| self.unsupported(inst))?;
5514
5515        let mut read = Read::default();
5516        let mut at = at + 1;
5517        for _ in 0..*arity {
5518            at = self.read(inst, pieces, at, bindings, &mut read)?;
5519        }
5520
5521        let writes = descs.iter().take_while(|desc| desc.role.is_def()).count();
5522        if descs.len() - writes != read.regs.len() {
5523            return Err(self.unsupported(inst));
5524        }
5525
5526        // The first thing the instruction writes is what it computes, and any others are
5527        // registers the machine destroys on the way, which are fresh because nothing else is in
5528        // them and nothing reads them. An instruction that writes nothing at all is one whose
5529        // whole purpose is its effect, which is what a store is, and there is no result to put
5530        // anywhere.
5531        let mut regs = Vec::new();
5532        if writes > 0 {
5533            // A term inside another computes a step rather than the result, into a register only
5534            // the term around it reads.
5535            let first = match outermost {
5536                true => {
5537                    let result =
5538                        self.source[inst].first_result.ok_or_else(|| self.unsupported(inst))?;
5539                    self.new_reg(result)
5540                }
5541                false => self.out.new_vreg(descs[0].class),
5542            };
5543            regs.push(first);
5544            // The rest are the registers the machine destroys on the way, and the class each is in
5545            // is the one the instruction's description gives it rather than a guess, so that an
5546            // instruction that wrecks a register in the other file says so.
5547            regs.extend(descs[1..writes].iter().map(|desc| self.out.new_vreg(desc.class)));
5548        } else if !outermost || self.source[inst].first_result.is_some() {
5549            // A rule that throws away a value the IR gave a name to would leave every reader of
5550            // that name with nothing to read, so it is a rule this and the target disagree about.
5551            // So is a term inside another that writes nothing for the one around it to read.
5552            return Err(self.unsupported(inst));
5553        }
5554        let written = regs.first().copied();
5555        regs.extend(read.regs.iter().copied());
5556
5557        let block = self.at.expect("a block is being filled");
5558        let opcode = mir::Opcode::new(self.names.intern(head));
5559        let (span, flags) = (self.source.span(inst), self.carried(inst));
5560        let mut build = self.out.build(block, opcode).at(span).flags(flags);
5561        for (desc, reg) in descs.iter().zip(regs) {
5562            let operand = mir::Operand {
5563                reg,
5564                class: desc.class,
5565                role: desc.role,
5566                constraint: desc.constraint,
5567            };
5568            build = build.operand(operand);
5569        }
5570        if let Some(mem) = read.mem {
5571            build = build.mem(mem);
5572        }
5573        if let Some(imm) = read.imm {
5574            build = build.imm(imm);
5575        }
5576        build.finish();
5577        Ok((at, written))
5578    }
5579
5580    /// Read one argument of a replacement, which is a register, a number, an address or another
5581    /// machine term.
5582    ///
5583    /// Gives back the position after it, because a replacement is flat and an address or a term
5584    /// takes arguments of its own. A machine term is built on the spot, and what is read is the
5585    /// register it wrote.
5586    fn read(
5587        &mut self,
5588        inst: Inst,
5589        pieces: &'static [Piece],
5590        at: usize,
5591        bindings: &[Term],
5592        out: &mut Read,
5593    ) -> Result<usize, Unsupported> {
5594        match pieces.get(at) {
5595            Some(Piece::Int(value)) => {
5596                out.imm = i64::try_from(*value).ok();
5597                Ok(at + 1)
5598            }
5599            // A number the rule worked out of the ones it matched rather than one it wrote down,
5600            // which is an immediate once it has been worked out and is read here as one. It gives
5601            // nothing back when a binding it reads is a register, and a replacement that cannot be
5602            // built is a rule this file and the matcher disagree about, which is what `unsupported`
5603            // is for.
5604            Some(Piece::Computed { work, .. }) => {
5605                let matched: Vec<Option<i128>> = bindings
5606                    .iter()
5607                    .map(|term| match *term {
5608                        Term::Num(value) => Some(value),
5609                        _ => None,
5610                    })
5611                    .collect();
5612                let number = work(&matched).ok_or_else(|| self.unsupported(inst))?;
5613                out.imm = i64::try_from(number).ok();
5614                Ok(at + 1)
5615            }
5616            Some(Piece::Var { index, .. }) => {
5617                match bindings.get(*index) {
5618                    Some(&Term::Reg(value)) => {
5619                        let reg = self.reg_of(value)?;
5620                        out.regs.push(reg);
5621                    }
5622                    Some(&Term::Num(value)) => out.imm = i64::try_from(value).ok(),
5623                    // A pattern binds a register or a number and nothing else, so this is a
5624                    // rule the matcher and this file disagree about.
5625                    _ => return Err(self.unsupported(inst)),
5626                }
5627                Ok(at + 1)
5628            }
5629            Some(Piece::App { head, .. }) if (self.selector.address)(head).is_none() => {
5630                let (next, reg) = self.build(inst, pieces, at, bindings, false)?;
5631                out.regs.push(reg.ok_or_else(|| self.unsupported(inst))?);
5632                Ok(next)
5633            }
5634            Some(Piece::App { head, arity }) => {
5635                let kind = (self.selector.address)(head).ok_or_else(|| self.unsupported(inst))?;
5636                let mut inner = Read::default();
5637                let mut next = at + 1;
5638                for _ in 0..*arity {
5639                    next = self.read(inst, pieces, next, bindings, &mut inner)?;
5640                }
5641                let mem = address(kind, &inner, self.gpr).ok_or_else(|| self.unsupported(inst))?;
5642                out.mem = Some(mem);
5643                Ok(next)
5644            }
5645            None => Err(self.unsupported(inst)),
5646        }
5647    }
5648
5649    /// The register a value is in, materializing it if it is a constant that has not been put in
5650    /// one yet.
5651    ///
5652    /// A constant is written where it is wanted rather than where the IR defined it, and where it
5653    /// is wanted is a block that need not be the one the IR defined it in. So the register holding
5654    /// one is only good inside the block it was written into, and a second block that wants the
5655    /// same constant gets its own. Anything else is a register read where nothing wrote it: the
5656    /// IR guarantees a definition dominates its uses, and this moved the definition.
5657    ///
5658    /// Writing the number again is also the right answer and not merely the safe one. It is one
5659    /// instruction that reads nothing, which is cheaper than holding a register live across a
5660    /// branch for it, and it is what a rematerializing allocator would do with the value anyway.
5661    fn reg_of(&mut self, value: Value) -> Result<mir::Reg, Unsupported> {
5662        let constant = match self.source[value].def {
5663            Def::Result { inst, .. } => {
5664                (self.source[inst].opcode == Opcode::IConst).then_some(inst)
5665            }
5666            Def::Param { .. } => None,
5667        };
5668        let here = self.at.expect("a block is being filled");
5669        if let Some(reg) = self.regs[value.index()] {
5670            if constant.is_none() || self.written[value.index()] == Some(here) {
5671                return Ok(reg);
5672            }
5673        }
5674        if let Some(inst) = constant {
5675            // Cleared so that the register the constant is written into is a new one rather than
5676            // the one the block above wrote, which is still being read up there.
5677            self.regs[value.index()] = None;
5678            // Nothing is refused here. A constant is written on its own, out of the loop over the
5679            // block, and the operands of the rule that writes one are the number and nothing else.
5680            let matched = self
5681                .select(inst, &HashSet::new())
5682                .map(|(_, matched)| matched)
5683                .ok_or_else(|| self.unsupported(inst))?;
5684            self.emit(inst, &matched)?;
5685            // The same mark the loop over the instructions makes, and it has to be made here as
5686            // well because this is the only place a constant is ever selected: the loop skips one
5687            // where the IR wrote it, so a rule that lowers a constant fires from nowhere else and
5688            // would be reported as a rule nothing reaches.
5689            self.fired.mark(matched.rule);
5690            self.written[value.index()] = Some(here);
5691            return Ok(self.regs[value.index()].expect("a constant is written into a register"));
5692        }
5693        Ok(self.new_reg(value))
5694    }
5695
5696    /// Which register file a value of that type lives in.
5697    ///
5698    /// The vector one for the two float widths the machine has scalar instructions for and for the
5699    /// one it only moves, and the general purpose one for everything else. An eighty bit `long
5700    /// double` is in neither, and it is here rather than in the vector class on purpose: it would
5701    /// be put in a register that cannot hold it, and there is no rule that names one, so the
5702    /// instruction computing it is reported. The wrong class would make that a wrong program
5703    /// instead of a refused one.
5704    ///
5705    /// A hundred and twenty eight bit float is in the vector class and fits it exactly, which is
5706    /// the difference. Nothing computes in it, so every arithmetic on one is still reported, and
5707    /// what the class buys is the moves: a register that holds the whole value is a register a
5708    /// spill, a reload and a copy are each one instruction for.
5709    fn class_of(&self, ty: Type) -> RegClass {
5710        if crate::term::in_vector_file(ty) { self.conv.sse_class } else { self.gpr }
5711    }
5712
5713    /// A fresh register for a value, which is what the instruction computing it writes.
5714    ///
5715    /// Any declaration the value is a value of comes with it. Here rather than once at the end over
5716    /// the whole map, because a constant is written again in every block that wants one and the map
5717    /// only remembers the last of those registers, and a local held in a constant is a local that
5718    /// would otherwise be findable in one block of the function and nowhere else.
5719    fn new_reg(&mut self, value: Value) -> mir::Reg {
5720        if let Some(reg) = self.regs[value.index()] {
5721            return reg;
5722        }
5723        let reg = self.out.new_vreg(self.class_of(self.source[value].ty));
5724        self.regs[value.index()] = Some(reg);
5725        let source = self.source;
5726        for decl in source.value_decls(value) {
5727            self.out.named.push((decl, reg));
5728        }
5729        reg
5730    }
5731
5732    fn unsupported(&self, inst: Inst) -> Unsupported {
5733        let data = &self.source[inst];
5734        Unsupported::Inst {
5735            inst,
5736            term: Terms::new(self.source, inst, PLAIN).name(inst),
5737            opcode: data.opcode,
5738            ty: data.first_result.map(|result| self.source[result].ty),
5739        }
5740    }
5741}
5742
5743/// What the arguments of one replacement came to.
5744#[derive(Debug, Default)]
5745struct Read {
5746    regs: Vec<mir::Reg>,
5747    imm: Option<i64>,
5748    mem: Option<mir::Mem>,
5749}
5750
5751/// The addressing mode an address constructor's arguments make.
5752///
5753/// One arm per constructor rather than a question asked of the kind, because what the arguments
5754/// mean is the whole of what tells the four apart: the same register is a base in one and an
5755/// index in another, and the same constant is a scale in one and a displacement in another.
5756fn address(kind: Address, read: &Read, gpr: RegClass) -> Option<mir::Mem> {
5757    let mut regs = read.regs.iter().copied().map(|reg| mir::Operand::read(reg, gpr));
5758    match kind {
5759        Address::BaseIndexScale => {
5760            let base = regs.next()?;
5761            let index = regs.next()?;
5762            Some(mir::Mem::at(base).indexed(index, u8::try_from(read.imm?).ok()?))
5763        }
5764        Address::IndexScale => Some(mir::Mem {
5765            base: None,
5766            index: Some(regs.next()?),
5767            scale: u8::try_from(read.imm?).ok()?,
5768            disp: 0,
5769            symbol: None,
5770            block: None,
5771            table: None,
5772            reach: mir::Reach::Itself,
5773            segment: None,
5774        }),
5775        Address::Base => Some(mir::Mem::at(regs.next()?)),
5776        // The rule that writes this has a guard saying the constant fits, so a displacement that
5777        // does not is a rule and a target that disagree rather than a program this cannot compile.
5778        Address::BaseOffset => {
5779            Some(mir::Mem { disp: i32::try_from(read.imm?).ok()?, ..mir::Mem::at(regs.next()?) })
5780        }
5781    }
5782}
5783
5784#[cfg(test)]
5785mod tests {
5786    use rucc_ir::{
5787        AsmInfo, Builder, CallInfo, Flags, InstData, MemInfo, MemOrder, Restrict, Signature, Type,
5788    };
5789    use rucc_regalloc::assign::Env;
5790    use rucc_target::x86_64::{FRAME, REGS, SYSV};
5791
5792    use super::*;
5793    use crate::finish::{Convention, finish};
5794    use crate::frame::{Frame, Incoming, Layout};
5795    use crate::select::x86_64::SELECTOR;
5796
5797    /// A function of as many 64 bit parameters as the test wants, and the block they are in.
5798    fn blank(params: &[Type]) -> (Interner, Func, Block, Vec<Value>) {
5799        let mut names = Interner::new();
5800        let mut func = Func::new(names.intern("f"), Signature::new());
5801        let block = func.create_block();
5802        let values = params.iter().map(|&ty| func.append_param(block, ty)).collect();
5803        (names, func, block, values)
5804    }
5805
5806    /// An ordinary access: not atomic, and aligned enough that nothing here has an opinion.
5807    /// Neither field reaches selection, which is the point of saying it once here.
5808    fn plain() -> MemInfo {
5809        MemInfo {
5810            size: 0,
5811            align: 1,
5812            order: MemOrder::NotAtomic,
5813            tbaa: None,
5814            owns: 0,
5815            restrict: Restrict::NONE,
5816        }
5817    }
5818
5819    /// What the allocator is given: every integer register the convention offers except two, held
5820    /// back so that a move on an edge has somewhere to break a cycle and a spilled value has
5821    /// somewhere to be read into. Which two does not matter, and holding back the last two the
5822    /// convention would reach for leaves every expectation below unchanged.
5823    fn env() -> Env {
5824        const SCRATCH: [PhysReg; 2] = [x86_64::R10, x86_64::R11];
5825        let order: Vec<PhysReg> =
5826            SYSV.int_order.iter().copied().filter(|reg| !SCRATCH.contains(reg)).collect();
5827        Env::new().with(x86_64::GPR, &order, &SCRATCH)
5828    }
5829
5830    /// The machine IR text a function lowers to.
5831    fn lower(names: &mut Interner, source: &Func) -> String {
5832        let out = func(source, names, &SELECTOR, &SYSV, &Elsewhere::default())
5833            .expect("every instruction has a rule");
5834        mir::print_func(&out.func, names, &REGS)
5835    }
5836
5837    /// The same function lowered for AArch64, which is the first thing this file writes for a
5838    /// machine other than x86-64. Nothing past selection runs here, so what is checked is that the
5839    /// arguments, the rule and the return all come out named for the machine that was asked for.
5840    #[test]
5841    fn an_addition_lowers_for_aarch64_with_its_own_names() {
5842        let i32 = Type::int(32);
5843        let (mut names, mut func, block, args) = blank(&[i32, i32]);
5844        let mut build = Builder::new(&mut func, block);
5845        let sum = build.binary(Opcode::Add, args[0], args[1], Flags::default());
5846        build.ret(&[sum]);
5847
5848        let conv = &aarch64::AAPCS64;
5849        let selector = &crate::select::aarch64::SELECTOR;
5850        let out = super::func(&func, &mut names, selector, conv, &Elsewhere::default())
5851            .expect("an addition and a return have AArch64 rules");
5852        let text = mir::print_func(&out.func, &names, &aarch64::REGS);
5853        assert!(!text.contains("x64."), "{text}");
5854        assert!(text.contains("= a64.arg_val_32"), "{text}");
5855        assert!(text.contains("= a64.add_rr_32 %0, %1"), "{text}");
5856        assert!(text.contains("a64.ret_val_32 %2"), "{text}");
5857    }
5858
5859    /// Lowers one function for AArch64 and prints it, or says why it could not.
5860    fn lower_a64(names: &mut Interner, func: &Func) -> Result<String, String> {
5861        let conv = &aarch64::AAPCS64;
5862        let selector = &crate::select::aarch64::SELECTOR;
5863        let out = super::func(func, names, selector, conv, &Elsewhere::default())
5864            .map_err(|why| why.to_string())?;
5865        Ok(mir::print_func(&out.func, names, &aarch64::REGS))
5866    }
5867
5868    /// Nothing reads AArch64 assembly back into instructions, so every template there is kept as
5869    /// its text. The operands are the instruction's own, with the output first and the inputs
5870    /// last, a hole in the text asks for the `w` or the `x` name of one, and a vector register the
5871    /// clobber list names is written by it as well as every register a call may leave anything in.
5872    #[test]
5873    fn a_template_on_aarch64_is_kept_as_text_with_its_operands_in_registers() {
5874        let (i32, i64) = (Type::int(32), Type::int(64));
5875        let (mut names, mut source, block, args) = blank(&[i32, i64]);
5876        let out = clobbering(
5877            &mut source,
5878            block,
5879            &mut names,
5880            "add %w0, %w1, #1\n\tstr %2, [sp]",
5881            "=r,r,r",
5882            "d8",
5883            &[args[0], args[1]],
5884            &[i32],
5885        );
5886        let produced = source[out].results().next().expect("one result");
5887        Builder::new(&mut source, block).ret(&[produced]);
5888
5889        // Forty one registers between the output and the inputs: `x0` to `x15`, the sixteen vector
5890        // registers a call does not keep, and `v8`, which is the one the program named.
5891        let text = lower_a64(&mut names, &source).expect("kept as text");
5892        assert!(text.contains("%2:gpr, early $x0, early $x1,"), "{text}");
5893        assert!(text.contains(
5894            "early $v31, early $v8 = a64.template %0, %1, \
5895             @add \u{1}r0w\u{2}, \u{1}r42w\u{2}, #1\n\tstr \u{1}r43x\u{2}, [sp]\n"
5896        ));
5897    }
5898
5899    /// A letter that means one thing on x86 and another on AArch64 is refused there rather than
5900    /// read as x86. `a` to `d` and `S` name one register each on x86 and nothing on AArch64.
5901    #[test]
5902    fn a_constraint_letter_the_two_machines_disagree_about_is_refused_on_aarch64() {
5903        let i64 = Type::int(64);
5904        for constraints in ["=a,r", "=r,S", "=r,c"] {
5905            let (mut names, mut source, block, args) = blank(&[i64]);
5906            let out = clobbering(
5907                &mut source,
5908                block,
5909                &mut names,
5910                "mov %0, %1",
5911                constraints,
5912                "",
5913                &[args[0]],
5914                &[i64],
5915            );
5916            let produced = source[out].results().next().expect("one result");
5917            Builder::new(&mut source, block).ret(&[produced]);
5918            let refused = lower_a64(&mut names, &source).expect_err(constraints);
5919            assert!(refused.contains("has an operand this cannot place"), "{refused}");
5920        }
5921    }
5922
5923    /// `Q` on AArch64 is memory addressed by one register, which is `[x3]` and is how an operand in
5924    /// memory is spelled there already.
5925    #[test]
5926    fn a_q_operand_on_aarch64_is_its_address_in_brackets() {
5927        let (i64, ptr) = (Type::int(64), Type::PTR);
5928        let (mut names, mut source, block, args) = blank(&[ptr]);
5929        let out =
5930            clobbering(&mut source, block, &mut names, "ldr %x0, %1", "=r,Q", "", &args, &[i64]);
5931        let produced = source[out].results().next().expect("one result");
5932        Builder::new(&mut source, block).ret(&[produced]);
5933        let text = lower_a64(&mut names, &source).expect("kept as text");
5934        assert!(text.contains("@ldr \u{1}r0x\u{2}, [\u{1}r"), "{text}");
5935    }
5936
5937    /// `w` on AArch64 is a vector register, named `v` with no modifier the way gcc names it and by
5938    /// its scalar view with one. An integer asked for in one is refused, since it would need a move
5939    /// into that file first.
5940    #[test]
5941    fn a_vector_operand_on_aarch64_is_in_the_vector_file() {
5942        let f64 = Type::float(rucc_ir::Float::F64);
5943        let (mut names, mut source, block, args) = blank(&[f64, f64]);
5944        let out = clobbering(
5945            &mut source,
5946            block,
5947            &mut names,
5948            "fadd %d0, %d1, %d2\n\tmov %0.16b, %0.16b",
5949            "=w,w,w",
5950            "",
5951            &[args[0], args[1]],
5952            &[f64],
5953        );
5954        let produced = source[out].results().next().expect("one result");
5955        Builder::new(&mut source, block).ret(&[produced]);
5956        let text = lower_a64(&mut names, &source).expect("kept as text");
5957        assert!(text.contains("%2:fpr, early $x0,"), "{text}");
5958        assert!(text.contains("@fadd \u{1}r0d\u{2}, \u{1}r"), "{text}");
5959        assert!(text.contains("\n\tmov \u{1}r0v\u{2}.16b, \u{1}r0v\u{2}.16b\n"), "{text}");
5960
5961        let i64 = Type::int(64);
5962        let (mut names, mut source, block, args) = blank(&[i64]);
5963        let out =
5964            clobbering(&mut source, block, &mut names, "fmov %d0, %d1", "=w,w", "", &args, &[i64]);
5965        let produced = source[out].results().next().expect("one result");
5966        Builder::new(&mut source, block).ret(&[produced]);
5967        assert!(lower_a64(&mut names, &source).is_err());
5968    }
5969
5970    #[test]
5971    fn an_addition_of_two_registers_is_one_instruction() {
5972        let i32 = Type::int(32);
5973        let (mut names, mut func, block, args) = blank(&[i32, i32]);
5974        let mut build = Builder::new(&mut func, block);
5975        build.binary(Opcode::Add, args[0], args[1], Flags::default());
5976
5977        assert_eq!(
5978            lower(&mut names, &func),
5979            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_32\n    \
5980             %1:gpr($rsi) = x64.arg_val_32\n    %2:gpr(reuse 1) = x64.add_rr_32 %0, %1\n}\n"
5981        );
5982    }
5983
5984    #[test]
5985    fn a_constant_operand_becomes_an_immediate() {
5986        let i32 = Type::int(32);
5987        let (mut names, mut func, block, args) = blank(&[i32]);
5988        let mut build = Builder::new(&mut func, block);
5989        let seven = build.iconst(i32, 7);
5990        build.binary(Opcode::Add, args[0], seven, Flags::default());
5991
5992        // The constant is in the instruction and nothing was written to hold it, which is what
5993        // materializing one where a register for it is wanted buys.
5994        assert_eq!(
5995            lower(&mut names, &func),
5996            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_32\n    \
5997             %1:gpr(reuse 1) = x64.add_ri_32 %0, 7\n}\n"
5998        );
5999    }
6000
6001    #[test]
6002    fn a_constant_too_wide_for_an_immediate_goes_into_a_register() {
6003        let i64 = Type::int(64);
6004        let (mut names, mut func, block, args) = blank(&[i64]);
6005        let mut build = Builder::new(&mut func, block);
6006        let big = build.iconst(i64, i128::from(i32::MAX) + 1);
6007        build.binary(Opcode::Add, args[0], big, Flags::default());
6008
6009        // Nobody wrote this fallback down. The rule that takes an immediate has a guard that
6010        // turns a number this wide down, so it does not fire, and the next way of showing the
6011        // operand puts it in a register.
6012        assert_eq!(
6013            lower(&mut names, &func),
6014            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_64\n    \
6015             %1:gpr = x64.mov_ri_64 2147483648\n    %2:gpr(reuse 1) = x64.add_rr_64 %0, %1\n}\n"
6016        );
6017    }
6018
6019    #[test]
6020    fn an_index_calculation_folds_into_an_address() {
6021        let i64 = Type::int(64);
6022        let (mut names, mut func, block, args) = blank(&[i64, i64]);
6023        let mut build = Builder::new(&mut func, block);
6024        let four = build.iconst(i64, 4);
6025        let scaled = build.binary(Opcode::Mul, args[1], four, Flags::default());
6026        build.binary(Opcode::Add, args[0], scaled, Flags::default());
6027
6028        // Three IR instructions and one machine instruction. The multiply is gone because the
6029        // rule that matched reached down and took it.
6030        assert_eq!(
6031            lower(&mut names, &func),
6032            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_64\n    \
6033             %1:gpr($rsi) = x64.arg_val_64\n    %2:gpr = x64.lea_64 [%0 + %1*4]\n}\n"
6034        );
6035    }
6036
6037    #[test]
6038    fn an_instruction_every_reader_can_take_is_folded_into_all_of_them() {
6039        let i64 = Type::int(64);
6040        let (mut names, mut func, block, args) = blank(&[i64, i64]);
6041        let mut build = Builder::new(&mut func, block);
6042        let four = build.iconst(i64, 4);
6043        let scaled = build.binary(Opcode::Mul, args[1], four, Flags::default());
6044        let first = build.binary(Opcode::Add, args[0], scaled, Flags::default());
6045        build.binary(Opcode::Add, first, scaled, Flags::default());
6046
6047        // Both readers have room for a scaled index, so both of them take it and nothing is left
6048        // to read the multiply. Three IR instructions become two machine ones, where refusing to
6049        // fold into either reader would have left three.
6050        assert_eq!(
6051            lower(&mut names, &func),
6052            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_64\n    \
6053             %1:gpr($rsi) = x64.arg_val_64\n    %2:gpr = x64.lea_64 [%0 + %1*4]\n    \
6054             %3:gpr = x64.lea_64 [%2 + %1*4]\n}\n"
6055        );
6056    }
6057
6058    #[test]
6059    fn an_instruction_one_of_its_readers_cannot_take_is_folded_into_none_of_them() {
6060        let i64 = Type::int(64);
6061        let (mut names, mut func, block, args) = blank(&[i64, i64]);
6062        let mut build = Builder::new(&mut func, block);
6063        let four = build.iconst(i64, 4);
6064        let scaled = build.binary(Opcode::Mul, args[1], four, Flags::default());
6065        build.binary(Opcode::Add, args[0], scaled, Flags::default());
6066        build.store(scaled, args[0], plain(), Flags::default());
6067
6068        // The addition has room for the multiply and the store does not: what a store writes is
6069        // a register, and no rule reaches through it. Folding into the addition alone would
6070        // leave the multiply where it is for the store to read and do the work twice, so the
6071        // multiply is put back and both readers read the register it wrote.
6072        let text = lower(&mut names, &func);
6073        assert!(text.contains("x64.lea_64 [%1*4]"), "{text}");
6074        assert!(text.contains("x64.add_rr_64"), "{text}");
6075    }
6076
6077    #[test]
6078    fn a_shift_by_a_register_asks_for_it_in_cl() {
6079        let i32 = Type::int(32);
6080        let (mut names, mut func, block, args) = blank(&[i32, i32]);
6081        let mut build = Builder::new(&mut func, block);
6082        build.binary(Opcode::Shl, args[0], args[1], Flags::default());
6083
6084        // The fixed register is not in the rule. It is what the target says the instruction does
6085        // with its operands, and the allocator is what will act on it.
6086        let text = lower(&mut names, &func);
6087        assert!(text.contains("x64.shl_rcl_32 %0, %1($rcx)"), "{text}");
6088    }
6089
6090    #[test]
6091    fn a_division_names_the_registers_and_the_register_it_destroys() {
6092        let i32 = Type::int(32);
6093        let (mut names, mut func, block, args) = blank(&[i32, i32]);
6094        let mut build = Builder::new(&mut func, block);
6095        build.binary(Opcode::SDiv, args[0], args[1], Flags::default());
6096
6097        // Two definitions, because a division writes the remainder whether anybody wanted it or
6098        // not, and the second one is early because it is destroyed before the operands are read.
6099        let text = lower(&mut names, &func);
6100        assert!(
6101            text.contains("%2:gpr($rax), early %3:gpr($rdx) = x64.idiv_quo_32 %0($rax), %1"),
6102            "{text}"
6103        );
6104    }
6105
6106    #[test]
6107    fn a_load_reads_through_the_register_the_address_is_in() {
6108        let i64 = Type::int(64);
6109        let (mut names, mut func, block, args) = blank(&[i64]);
6110        let mut build = Builder::new(&mut func, block);
6111        build.load(Type::int(32), args[0], plain(), Flags::default());
6112
6113        assert_eq!(
6114            lower(&mut names, &func),
6115            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_64\n    \
6116             %1:gpr = x64.mov_rm_32 [%0]\n}\n"
6117        );
6118    }
6119
6120    #[test]
6121    fn a_store_writes_no_register_and_the_value_it_writes_is_the_one_the_ir_gave_it() {
6122        let (mut names, mut func, block, args) = blank(&[Type::int(32), Type::int(64)]);
6123        let mut build = Builder::new(&mut func, block);
6124        build.store(args[0], args[1], plain(), Flags::default());
6125
6126        // The value is the first parameter and the address is the second, and the instruction
6127        // takes them the other way round. Getting that backwards would compile to a store of the
6128        // address into the value, which is a program that runs and does the wrong thing.
6129        assert_eq!(
6130            lower(&mut names, &func),
6131            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_32\n    \
6132             %1:gpr($rsi) = x64.arg_val_64\n    x64.mov_mr_32 %0, [%1]\n}\n"
6133        );
6134    }
6135
6136    #[test]
6137    fn an_address_with_a_constant_added_folds_into_the_access() {
6138        let i64 = Type::int(64);
6139        let (mut names, mut func, block, args) = blank(&[i64]);
6140        let mut build = Builder::new(&mut func, block);
6141        let twelve = build.iconst(i64, 12);
6142        let field = build.binary(Opcode::Add, args[0], twelve, Flags::default());
6143        build.load(Type::int(64), field, plain(), Flags::default());
6144
6145        // Two IR instructions and one machine instruction, which is what every read of a field
6146        // of a structure comes to.
6147        assert_eq!(
6148            lower(&mut names, &func),
6149            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_64\n    \
6150             %1:gpr = x64.mov_rm_64 [%0 + 12]\n}\n"
6151        );
6152    }
6153
6154    #[test]
6155    fn a_displacement_too_wide_to_encode_leaves_the_addition_where_it_is() {
6156        let i64 = Type::int(64);
6157        let (mut names, mut func, block, args) = blank(&[i64]);
6158        let mut build = Builder::new(&mut func, block);
6159        let big = build.iconst(i64, i128::from(i32::MAX) + 1);
6160        let far = build.binary(Opcode::Add, args[0], big, Flags::default());
6161        build.load(Type::int(32), far, plain(), Flags::default());
6162
6163        // A displacement is signed and 32 bits. The rule that folds one has a guard that turns
6164        // this down, so the addition stays and the load reads through what it produced. Nobody
6165        // wrote that fallback: it is the next way of showing the operand.
6166        let text = lower(&mut names, &func);
6167        assert!(text.contains("x64.mov_rm_32 [%2]"), "{text}");
6168        assert!(text.contains("x64.add_rr_64"), "{text}");
6169    }
6170
6171    #[test]
6172    fn a_store_of_a_value_that_was_loaded_is_two_instructions_and_no_arithmetic() {
6173        let i64 = Type::int(64);
6174        let (mut names, mut func, block, args) = blank(&[i64, i64]);
6175        let mut build = Builder::new(&mut func, block);
6176        let got = build.load(Type::int(8), args[0], plain(), Flags::default());
6177        build.store(got, args[1], plain(), Flags::default());
6178
6179        // A load feeding a store is the one place folding would be wrong: an x86-64 `mov` has at
6180        // most one memory operand, and there is no rule that takes two, so the load is left where
6181        // it is and the store reads the register it wrote.
6182        assert_eq!(
6183            lower(&mut names, &func),
6184            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_64\n    \
6185             %1:gpr($rsi) = x64.arg_val_64\n    %2:gpr = x64.mov_rm_8 [%0]\n    \
6186             x64.mov_mr_8 %2, [%1]\n}\n"
6187        );
6188    }
6189
6190    #[test]
6191    fn an_access_at_a_width_no_rule_is_written_at_is_reported() {
6192        let i64 = Type::int(64);
6193        let (mut names, mut source, block, args) = blank(&[i64]);
6194        let mut build = Builder::new(&mut source, block);
6195        build.load(Type::int(128), args[0], plain(), Flags::default());
6196
6197        // The width is the whole of what is wrong here, so the width is in the message: `load`
6198        // on its own is written about at every other width and would send a reader looking in
6199        // the wrong place.
6200        let failed = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
6201            .expect_err("nothing loads 128 bits");
6202        assert_eq!(failed.to_string(), "no rule lowers a `load` producing a `i128`");
6203    }
6204
6205    #[test]
6206    fn a_return_asks_for_the_value_in_the_register_the_caller_reads() {
6207        let (mut names, mut func, block, args) = blank(&[Type::int(32)]);
6208        let mut build = Builder::new(&mut func, block);
6209        build.ret(&[args[0]]);
6210
6211        // The register is not in the rule, the same way `cl` is not in the rule for a shift. It
6212        // is what the target says the instruction does with its operand, and the allocator is
6213        // what will act on it. There is no `ret` here, because giving the frame back has to
6214        // happen between this and leaving and the frame is not worked out yet.
6215        assert_eq!(
6216            lower(&mut names, &func),
6217            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_32\n    \
6218             x64.ret_val_32 %0($rax)\n}\n"
6219        );
6220    }
6221
6222    #[test]
6223    fn a_return_of_two_values_asks_for_the_second_register_as_well() {
6224        let i64 = Type::int(64);
6225        let (mut names, mut func, block, args) = blank(&[i64, i64]);
6226        let mut build = Builder::new(&mut func, block);
6227        build.ret(&[args[0], args[1]]);
6228
6229        // `struct { long a, b; } f(long a, long b)`, after the front end has classified it. Both
6230        // halves are integers, so the second is in the second integer return register, and both
6231        // pseudos say so the same way the one for a single value does.
6232        assert_eq!(
6233            lower(&mut names, &func),
6234            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_64\n    \
6235             %1:gpr($rsi) = x64.arg_val_64\n    x64.ret_val_64 %0($rax)\n    \
6236             x64.ret_val2_64 %1($rdx)\n}\n"
6237        );
6238    }
6239
6240    #[test]
6241    fn two_values_back_in_different_files_are_both_the_first_of_their_own() {
6242        let f64 = Type::float(rucc_ir::Float::F64);
6243        let (mut names, mut func, block, args) = blank(&[f64, Type::int(64)]);
6244        let mut build = Builder::new(&mut func, block);
6245        build.ret(&[args[0], args[1]]);
6246
6247        // `struct { double a; long b; } f(double a, long b)`. The two files are counted apart, so
6248        // neither half is the second of anything and the `double` is in `xmm0` rather than in the
6249        // register a second `double` would have been in. Getting this wrong is not a crash: the
6250        // caller reads a register nobody wrote, and this is where that is ruled out.
6251        assert_eq!(
6252            lower(&mut names, &func),
6253            "mfunc @f {\nblock0:\n    %0:xmm($xmm0) = x64.arg_val_f64\n    \
6254             %1:gpr($rdi) = x64.arg_val_64\n    x64.ret_val_f64 %0($xmm0)\n    \
6255             x64.ret_val_64 %1($rax)\n}\n"
6256        );
6257    }
6258
6259    #[test]
6260    fn two_of_the_same_file_back_take_the_first_two_of_it() {
6261        let f64 = Type::float(rucc_ir::Float::F64);
6262        let (mut names, mut func, block, args) = blank(&[f64, f64]);
6263        let mut build = Builder::new(&mut func, block);
6264        build.ret(&[args[0], args[1]]);
6265
6266        // `struct { double x, y; } f(double x, double y)`, which is the vector half of the pair
6267        // above and counts in its own file the same way.
6268        assert_eq!(
6269            lower(&mut names, &func),
6270            "mfunc @f {\nblock0:\n    %0:xmm($xmm0) = x64.arg_val_f64\n    \
6271             %1:xmm($xmm1) = x64.arg_val_f64\n    x64.ret_val_f64 %0($xmm0)\n    \
6272             x64.ret_val2_f64 %1($xmm1)\n}\n"
6273        );
6274    }
6275
6276    /// A function whose answer goes back through memory, with the pointer to the space for it in
6277    /// front of whatever else it takes. Only the signature says it is one.
6278    fn returning_through_memory(params: &[Type]) -> (Interner, Func, Block, Vec<Value>) {
6279        let mut names = Interner::new();
6280        let sret = Abi::Sret { size: 32, align: 8 };
6281        let mut signature = Signature::new().and_param(Param::with_abi(Type::PTR, sret));
6282        signature.params.extend(params.iter().copied().map(Param::new));
6283        let mut func = Func::new(names.intern("f"), signature);
6284        let block = func.create_block();
6285        let space = func.append_param(block, Type::PTR);
6286        let values = std::iter::once(space)
6287            .chain(params.iter().map(|&ty| func.append_param(block, ty)))
6288            .collect();
6289        (names, func, block, values)
6290    }
6291
6292    #[test]
6293    fn the_space_a_return_through_memory_was_given_goes_back_in_the_first_return_register() {
6294        let (mut names, mut func, block, _) = returning_through_memory(&[]);
6295        Builder::new(&mut func, block).ret(&[]);
6296
6297        // `struct big f(void)`, where `big` is too large to come back in registers. The `return`
6298        // carries nothing, because the value went into the space the caller handed over, and the
6299        // document still says that address comes back in `rax`. Nothing in the IR says it, so the
6300        // convention says it, and the pseudo is the one any other pointer return would use.
6301        assert_eq!(
6302            lower(&mut names, &func),
6303            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_64\n    \
6304             x64.ret_val_64 %0($rax)\n}\n"
6305        );
6306    }
6307
6308    #[test]
6309    fn what_the_function_did_in_between_does_not_take_the_register_off_it() {
6310        let (mut names, mut func, block, args) = returning_through_memory(&[Type::int(32)]);
6311        let mut build = Builder::new(&mut func, block);
6312        build.store(args[1], args[0], plain(), Flags::default());
6313        build.ret(&[]);
6314
6315        // The register is a read at the end and not a move at the start, so it is live across
6316        // everything between the two and the allocator has to keep it somewhere. In a function
6317        // with a call in it that somewhere is a callee saved register, and the address comes back
6318        // into `rax` here rather than whatever the last instruction happened to leave there. That
6319        // is issue #333, and a store is enough to show the value outlives the entry block.
6320        let text = lower(&mut names, &func);
6321        assert!(text.contains("x64.mov_mr_32 %1, [%0]"), "{text}");
6322        assert!(text.ends_with("    x64.ret_val_64 %0($rax)\n}\n"), "{text}");
6323    }
6324
6325    #[test]
6326    fn a_pointer_that_is_only_a_pointer_is_not_given_back() {
6327        let (mut names, mut func, block, args) = blank(&[Type::PTR]);
6328        let mut build = Builder::new(&mut func, block);
6329        build.store(args[0], args[0], plain(), Flags::default());
6330        build.ret(&[]);
6331
6332        // `void f(void **p)`. It takes a pointer first and returns nothing, which is the shape of
6333        // the one above and none of its meaning, and what tells them apart is the signature. A
6334        // `void` function leaves `rax` alone.
6335        assert!(!lower(&mut names, &func).contains("ret_val"));
6336    }
6337
6338    #[test]
6339    fn a_return_of_a_constant_puts_it_in_a_register_first() {
6340        let (mut names, mut func, block, _) = blank(&[]);
6341        let mut build = Builder::new(&mut func, block);
6342        let zero = build.iconst(Type::int(32), 0);
6343        build.ret(&[zero]);
6344
6345        // No rule returns an immediate, so the plan that offers one is turned down and the next
6346        // one materializes it. That is `int main(void) { return 0; }` in full, once the epilogue
6347        // is appended to it.
6348        assert_eq!(
6349            lower(&mut names, &func),
6350            "mfunc @f {\nblock0:\n    %0:gpr = x64.mov_ri_32 0\n    x64.ret_val_32 %0($rax)\n}\n"
6351        );
6352    }
6353
6354    #[test]
6355    fn the_rule_that_writes_a_constant_down_is_recorded_as_a_rule_that_fired() {
6356        let (mut names, mut func, block, _) = blank(&[]);
6357        let mut build = Builder::new(&mut func, block);
6358        let zero = build.iconst(Type::int(32), 0);
6359        build.ret(&[zero]);
6360
6361        // The loop over the instructions passes a constant by, because a constant is written where
6362        // a register for it is first wanted rather than where the IR put it. So the only place a
6363        // rule about one is ever selected is the materialization, and a mark made in the loop
6364        // alone would report every rule about a constant as a rule nothing reaches.
6365        let out = super::func(&func, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
6366            .expect("every instruction has a rule");
6367        let rules = &crate::select::x86_64::TABLE.rules;
6368        let fired: Vec<&str> = rules
6369            .iter()
6370            .enumerate()
6371            .filter(|(index, _)| out.fired.has(*index))
6372            .map(|(_, rule)| rule.pattern)
6373            .collect();
6374        assert!(fired.contains(&"(iconst.i32 k)"), "{fired:?}");
6375    }
6376
6377    #[test]
6378    fn a_return_of_nothing_is_no_instruction_at_all() {
6379        let (mut names, mut func, block, _) = blank(&[]);
6380        let mut build = Builder::new(&mut func, block);
6381        build.ret(&[]);
6382
6383        // Every part of leaving a function that returns nothing is the epilogue's, and the
6384        // epilogue goes in after allocation. A block with nothing in it is the right answer here
6385        // rather than a function that could not be lowered.
6386        assert_eq!(lower(&mut names, &func), "mfunc @f {\nblock0:\n}\n");
6387    }
6388
6389    #[test]
6390    fn the_allocator_is_what_moves_the_answer_into_the_return_register() {
6391        let (mut names, mut source, block, _) = blank(&[]);
6392        let mut build = Builder::new(&mut source, block);
6393        let zero = build.iconst(Type::int(32), 0);
6394        build.ret(&[zero]);
6395
6396        let mut out = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
6397            .expect("every instruction has a rule")
6398            .func;
6399        let env = env();
6400        let allocation = rucc_regalloc::run(&mut out, &env, "test", true);
6401        let frame = Frame::of(&out, &allocation, &Layout::new(&SYSV, REGS));
6402        finish(
6403            &mut out,
6404            &allocation,
6405            &frame,
6406            &Stack::default(),
6407            Convention::new(&SYSV, &FRAME),
6408            &mut names,
6409        );
6410
6411        // `int main(void) { return 0; }` end to end. Nothing here asked for `rax`: the rule said
6412        // the value goes back, the target said where, and the allocator is what made it true. The
6413        // epilogue is what leaves, and this function needs no frame, so it is the return alone.
6414        //
6415        // Two instructions and no copy, which is what a hint buys. The return insists on `rax`,
6416        // so `rax` is the register the allocator tries first for the value the return reads, and
6417        // the constant is written straight into it.
6418        assert_eq!(
6419            mir::print_func(&out, &names, &REGS),
6420            "mfunc @f {\nblock0:\n    $rax = x64.mov_ri_32 0\n    \
6421             x64.ret_val_32 $rax($rax)\n    x64.ret\n}\n"
6422        );
6423    }
6424
6425    #[test]
6426    fn a_function_of_two_arguments_is_a_whole_function_now() {
6427        let i32 = Type::int(32);
6428        let (mut names, mut source, block, args) = blank(&[i32, i32]);
6429        let mut build = Builder::new(&mut source, block);
6430        let sum = build.binary(Opcode::Add, args[0], args[1], Flags::default());
6431        build.ret(&[sum]);
6432
6433        let mut out = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
6434            .expect("every instruction has a rule")
6435            .func;
6436        let env = env();
6437        let allocation = rucc_regalloc::run(&mut out, &env, "test", true);
6438        let frame = Frame::of(&out, &allocation, &Layout::new(&SYSV, REGS));
6439        finish(
6440            &mut out,
6441            &allocation,
6442            &frame,
6443            &Stack::default(),
6444            Convention::new(&SYSV, &FRAME),
6445            &mut names,
6446        );
6447
6448        // `int f(int a, int b) { return a + b; }` end to end, and this is the test the argument
6449        // side exists for. Before it there was no way to write one: the allocator refuses a
6450        // function whose entry block takes parameters, because there is no edge into an entry
6451        // block for the moves that give a block parameter its value to go on.
6452        //
6453        // One move, and it is the one the machine's addition needs rather than one the allocator
6454        // owes anybody. Each argument stays in the register it arrived in, because the pseudo
6455        // that defines it insists on that register and the allocator now tries it first, and the
6456        // sum stays in the register the addition wrote it to until the return reads it out. The
6457        // copy in front of a two address instruction is what makes its destination one of the
6458        // registers it reads, and the source operand keeps its own name because the destination
6459        // is what the encoder writes.
6460        assert_eq!(
6461            mir::print_func(&out, &names, &REGS),
6462            "mfunc @f {\nblock0:\n    $rdi($rdi) = x64.arg_val_32\n    \
6463             $rsi($rsi) = x64.arg_val_32\n    \
6464             $rdi(reuse 1) = x64.add_rr_32 $rdi, $rsi\n    $rax = x64.mov_rr_64 $rdi\n    \
6465             x64.ret_val_32 $rax($rax)\n    x64.ret\n}\n"
6466        );
6467    }
6468
6469    #[test]
6470    fn an_argument_with_no_register_left_for_it_is_read_out_of_the_caller_s_stack() {
6471        let i64 = Type::int(64);
6472        let (mut names, mut source, block, args) = blank(&[i64; 7]);
6473        let mut build = Builder::new(&mut source, block);
6474        build.ret(&[args[6]]);
6475
6476        let lowered = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
6477            .expect("the seventh is read from memory");
6478
6479        // SysV passes six integers in registers and the seventh in the caller's memory, so six of
6480        // these are pseudos that encode to nothing and the seventh is a load that encodes to real
6481        // bytes. Its displacement is nothing here for the reason a local's is: there is no frame
6482        // yet. What the walk hands on is which instruction is waiting, and for how far up the
6483        // caller's argument area, which is the bottom of it because it is the first one there.
6484        assert_eq!(lowered.stack.arguments.len(), 1);
6485        assert_eq!(lowered.stack.arguments[0].1, 0);
6486        let text = mir::print_func(&lowered.func, &names, &REGS);
6487        assert!(text.contains("%6:gpr = x64.mov_rm_64 [$rsp]"), "{text}");
6488        assert_eq!(text.matches("x64.arg_val_64").count(), 6, "{text}");
6489    }
6490
6491    #[test]
6492    fn the_frame_is_what_says_how_far_up_the_caller_s_stack_an_argument_is() {
6493        let i64 = Type::int(64);
6494        let (mut names, mut source, block, args) = blank(&[i64; 8]);
6495        let mut build = Builder::new(&mut source, block);
6496        let sum = build.binary(Opcode::Add, args[6], args[7], Flags::default());
6497        build.ret(&[sum]);
6498
6499        let lowered = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
6500            .expect("both are read from memory");
6501        let stack = lowered.stack;
6502        let mut out = lowered.func;
6503        let env = env();
6504        let allocation = rucc_regalloc::run(&mut out, &env, "test", true);
6505        let layout = stack.layout(Layout::new(&SYSV, REGS));
6506        let frame = Frame::of(&out, &allocation, &layout);
6507        finish(&mut out, &allocation, &frame, &stack, Convention::new(&SYSV, &FRAME), &mut names);
6508
6509        // A leaf that takes no frame, so the stack pointer never moves and the only thing between
6510        // it and the caller's arguments is the return address the call pushed. The seventh
6511        // parameter is at the bottom of the caller's argument area and the eighth is one word
6512        // further up, which is the eight bytes between the two offsets.
6513        let text = mir::print_func(&out, &names, &REGS);
6514        assert_eq!(frame.size(), 0);
6515        assert_eq!(frame.incoming(), Incoming::from_stack(8));
6516        assert!(text.contains("x64.mov_rm_64 [$rsp + 8]"), "{text}");
6517        assert!(text.contains("x64.mov_rm_64 [$rsp + 16]"), "{text}");
6518    }
6519
6520    #[test]
6521    fn a_realigned_frame_reaches_the_caller_s_arguments_through_the_frame_pointer() {
6522        let i64 = Type::int(64);
6523        let (mut names, mut source, block, args) = blank(&[i64; 7]);
6524        let wide = slot(&mut source, block, 64, 32);
6525        let mut build = Builder::new(&mut source, block);
6526        build.store(args[6], wide, plain(), Flags::default());
6527        build.ret(&[args[6]]);
6528
6529        let lowered = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
6530            .expect("every instruction has a rule");
6531        let stack = lowered.stack;
6532        let mut out = lowered.func;
6533        let env = env();
6534        let allocation = rucc_regalloc::run(&mut out, &env, "test", true);
6535        let layout = stack.layout(Layout::new(&SYSV, REGS));
6536        let frame = Frame::of(&out, &allocation, &layout);
6537        finish(&mut out, &allocation, &frame, &stack, Convention::new(&SYSV, &FRAME), &mut names);
6538
6539        // A local wanting thirty two byte alignment makes the prologue force the stack pointer,
6540        // which throws away how far the caller's stack was. So the load the lowering wrote off the
6541        // stack pointer is rewritten to read through the frame pointer, at the one distance that
6542        // survives: the word the prologue pushed the frame pointer into, and the return address
6543        // above it.
6544        let text = mir::print_func(&out, &names, &REGS);
6545        assert_eq!(frame.realign(), Some(32));
6546        assert_eq!(frame.incoming(), Incoming::from_frame(16));
6547        assert!(text.contains("x64.mov_rm_64 [$rbp + 16]"), "{text}");
6548        assert!(!text.contains("x64.mov_rm_64 [$rsp"), "{text}");
6549    }
6550
6551    #[test]
6552    fn a_jump_is_the_edge_and_nothing_else() {
6553        let i32 = Type::int(32);
6554        let (mut names, mut source, entry, args) = blank(&[i32]);
6555        let next = source.create_block();
6556        let got = source.append_param(next, i32);
6557        Builder::new(&mut source, entry).jump(next, &[args[0]]);
6558        Builder::new(&mut source, next).ret(&[got]);
6559
6560        // Two blocks and two instructions, and the jump is neither of them. What it was is the
6561        // arm on the first block, and what the arm carries is the argument it was called with.
6562        assert_eq!(
6563            lower(&mut names, &source),
6564            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_32 block1(%0)\n\n\
6565             block1(%1:gpr):\n    x64.ret_val_32 %1($rax)\n}\n"
6566        );
6567    }
6568
6569    /// A block that reads what a block below it writes is filled after it, not before it.
6570    ///
6571    /// The blocks are written entry, `early`, `late`, `exit`, and the entry jumps straight past
6572    /// `early` to `late`, so `late` dominates `early` while sitting below it in the function.
6573    /// Filling them in the order they are written reaches the read in `early` first, and reading
6574    /// a value with no register yet mints one. The cast in `late` is no instruction at all, so
6575    /// what it does is give its answer the register its operand is already in, and that is not
6576    /// the register the read minted. Nothing writes the register the read minted. The printer
6577    /// says `%?` for a register nothing defines, which is what this looks for, and what came out
6578    /// of the real bug was SQLite loading a stack slot no store ever reached.
6579    #[test]
6580    fn a_block_that_reads_what_a_block_below_it_writes_is_filled_after_it() {
6581        let i64 = Type::int(64);
6582        let (mut names, mut source, entry, args) = blank(&[i64, i64]);
6583        let early = source.create_block();
6584        let late = source.create_block();
6585        let exit = source.create_block();
6586
6587        Builder::new(&mut source, entry).jump(late, &[]);
6588        let ptr = cast(&mut source, late, Opcode::IntToPtr, args[0], Type::PTR);
6589        Builder::new(&mut source, early).ret(&[ptr]);
6590        let mut build = Builder::new(&mut source, late);
6591        let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
6592        build.br_if(cond, early, &[], exit, &[]);
6593        Builder::new(&mut source, exit).ret(&[args[1]]);
6594
6595        let text = lower(&mut names, &source);
6596        assert!(!text.contains("%?"), "every register has something that writes it: {text}");
6597    }
6598
6599    /// A constant is written where it is wanted rather than where the IR defined it, and two
6600    /// blocks wanting the same one is two places. Writing it once and reading it in both is a
6601    /// register read where nothing wrote it, unless the block it was written in happens to
6602    /// dominate the other, which nothing here checks and which the second arm of a branch never
6603    /// does. Each block gets its own copy of the number instead.
6604    #[test]
6605    fn a_constant_two_blocks_want_is_written_in_both_of_them() {
6606        let i32 = Type::int(32);
6607        let (mut names, mut source, entry, args) = blank(&[i32, i32]);
6608        let then = source.create_block();
6609        let other = source.create_block();
6610        let join = source.create_block();
6611        let got = source.append_param(join, i32);
6612
6613        let mut build = Builder::new(&mut source, entry);
6614        let seven = build.iconst(i32, 7);
6615        let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
6616        build.br_if(cond, then, &[], other, &[]);
6617        // Both arms want the seven in a register, because a block argument is never an immediate,
6618        // and neither arm dominates the other.
6619        Builder::new(&mut source, then).jump(join, &[seven]);
6620        Builder::new(&mut source, other).jump(join, &[seven]);
6621        Builder::new(&mut source, join).ret(&[got]);
6622
6623        let text = lower(&mut names, &source);
6624        assert_eq!(text.matches("x64.mov_ri_32 7").count(), 2, "one seven per block: {text}");
6625    }
6626
6627    /// An argument on an edge out of a block that leaves two ways is read after every instruction
6628    /// of the block is written, and reading one can write an instruction, which would land after
6629    /// the branch that has already jumped past it. The branch goes back on the end.
6630    #[test]
6631    fn a_constant_an_edge_wants_is_written_before_the_branch_and_not_after_it() {
6632        let i32 = Type::int(32);
6633        let (mut names, mut source, entry, args) = blank(&[i32, i32]);
6634        let then = source.create_block();
6635        let join = source.create_block();
6636        let got = source.append_param(join, i32);
6637
6638        let mut build = Builder::new(&mut source, entry);
6639        let nine = build.iconst(i32, 9);
6640        let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
6641        build.br_if(cond, then, &[], join, &[nine]);
6642        Builder::new(&mut source, then).jump(join, &[args[0]]);
6643        Builder::new(&mut source, join).ret(&[got]);
6644
6645        let out = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
6646            .expect("every instruction has a rule")
6647            .func;
6648        let entry = out.entry().expect("an entry block");
6649        let last = out.terminator(entry).expect("a block that leaves two ways has a branch");
6650        let branch = names.intern("x64.br_cond_8");
6651        assert_eq!(
6652            out[last].opcode,
6653            mir::Opcode::new(branch),
6654            "the branch is last: {}",
6655            mir::print_func(&out, &names, &REGS)
6656        );
6657    }
6658
6659    #[test]
6660    fn a_conditional_branch_is_lowered_to_the_condition_and_nothing_about_where_it_goes() {
6661        let i32 = Type::int(32);
6662        let (mut names, mut source, entry, args) = blank(&[i32, i32]);
6663        let then = source.create_block();
6664        let other = source.create_block();
6665        let mut build = Builder::new(&mut source, entry);
6666        let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
6667        build.br_if(cond, then, &[], other, &[]);
6668        Builder::new(&mut source, then).ret(&[args[0]]);
6669        Builder::new(&mut source, other).ret(&[args[1]]);
6670
6671        // The comparison writes a byte and the branch reads it, and neither says a block. Both
6672        // arms are on the entry block, in the order the branch took them, so the arm that runs
6673        // when the condition holds is the first.
6674        assert_eq!(
6675            lower(&mut names, &source),
6676            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_32\n    \
6677             %1:gpr($rsi) = x64.arg_val_32\n    %2:gpr = x64.cmp_set_l_32 %0, %1\n    \
6678             x64.br_cond_8 %2, block1, block2\n\n\
6679             block1:\n    x64.ret_val_32 %0($rax)\n\n\
6680             block2:\n    x64.ret_val_32 %1($rax)\n}\n"
6681        );
6682    }
6683
6684    /// A choice between two values, which is one instruction and no blocks at all.
6685    ///
6686    /// The arms come out the other way round from the IR, because a conditional move overwrites its
6687    /// destination and the destination is the arm taken when the condition does not hold. The
6688    /// condition arrives last for the same reason: it is read by the test in front of the move
6689    /// rather than by the move.
6690    #[test]
6691    fn a_select_is_lowered_to_a_test_and_a_conditional_move() {
6692        let i32 = Type::int(32);
6693        let (mut names, mut source, entry, args) = blank(&[i32, i32]);
6694        let mut build = Builder::new(&mut source, entry);
6695        let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
6696        let picked = build.select(cond, args[0], args[1]);
6697        build.ret(&[picked]);
6698
6699        assert_eq!(
6700            lower(&mut names, &source),
6701            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_32\n    \
6702             %1:gpr($rsi) = x64.arg_val_32\n    %2:gpr = x64.cmp_set_l_32 %0, %1\n    \
6703             %3:gpr(reuse 1) = x64.test_cmov_ne_32 %1, %0, %2\n    \
6704             x64.ret_val_32 %3($rax)\n}\n"
6705        );
6706    }
6707
6708    #[test]
6709    fn a_branch_over_a_block_is_a_whole_function_now() {
6710        let i32 = Type::int(32);
6711        let (mut names, mut source, entry, args) = blank(&[i32, i32]);
6712        let then = source.create_block();
6713        let other = source.create_block();
6714        let join = source.create_block();
6715        let got = source.append_param(join, i32);
6716        let mut build = Builder::new(&mut source, entry);
6717        let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
6718        build.br_if(cond, then, &[], other, &[]);
6719        let mut build = Builder::new(&mut source, then);
6720        let sum = build.binary(Opcode::Add, args[0], args[1], Flags::default());
6721        build.jump(join, &[sum]);
6722        Builder::new(&mut source, other).jump(join, &[args[1]]);
6723        Builder::new(&mut source, join).ret(&[got]);
6724
6725        // `int f(int a, int b) { if (a < b) return a + b; else return b; }` end to end, written
6726        // the way a front end writes it: both arms of the branch are blocks of their own and the
6727        // return is the block they meet at. No edge here is critical, because the two arms out of
6728        // the entry carry nothing and the two arms into the join each leave a block that goes
6729        // nowhere else, so each has its own end to put its move at.
6730        let mut out = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
6731            .expect("every instruction has a rule")
6732            .func;
6733        assert_eq!(crate::split::critical(&mut out), 0, "no edge here is critical");
6734        let env = env();
6735        let allocation = rucc_regalloc::run(&mut out, &env, "test", true);
6736        let frame = Frame::of(&out, &allocation, &Layout::new(&SYSV, REGS));
6737        finish(
6738            &mut out,
6739            &allocation,
6740            &frame,
6741            &Stack::default(),
6742            Convention::new(&SYSV, &FRAME),
6743            &mut names,
6744        );
6745
6746        // One epilogue, on the join, which is the one block the function leaves from, and the
6747        // moves that give the join its parameter are at the end of each arm. Every register is
6748        // physical and the branch is still a branch on a register, because turning it into a
6749        // `test` and a `jcc` is the block layout's and there is no block layout yet.
6750        let text = mir::print_func(&out, &names, &REGS);
6751        assert_eq!(text.matches("x64.ret\n").count(), 1, "{text}");
6752        assert!(text.contains("x64.br_cond_8"), "{text}");
6753        assert!(text.contains("x64.add_rr_32"), "{text}");
6754        assert!(!text.contains('%'), "{text}");
6755    }
6756
6757    #[test]
6758    fn a_critical_edge_is_split_before_the_allocator_ever_sees_it() {
6759        let i32 = Type::int(32);
6760        let (mut names, mut source, entry, args) = blank(&[i32, i32]);
6761        let then = source.create_block();
6762        let join = source.create_block();
6763        let got = source.append_param(join, i32);
6764        let mut build = Builder::new(&mut source, entry);
6765        let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
6766        build.br_if(cond, then, &[], join, &[args[1]]);
6767        Builder::new(&mut source, then).jump(join, &[args[0]]);
6768        let mut build = Builder::new(&mut source, join);
6769        let twice = build.binary(Opcode::Add, got, got, Flags::default());
6770        build.ret(&[twice]);
6771
6772        // The else arm is critical: the entry block leaves two ways and the join is arrived at
6773        // two ways, and the arm carries a value. Without splitting it the allocator asserts,
6774        // because the move that gives the join its parameter would have to run at the end of a
6775        // block that also goes to the other arm.
6776        let mut out = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
6777            .expect("every instruction has a rule")
6778            .func;
6779        assert_eq!(crate::split::critical(&mut out), 1);
6780        let env = env();
6781        let allocation = rucc_regalloc::run(&mut out, &env, "test", true);
6782        let frame = Frame::of(&out, &allocation, &Layout::new(&SYSV, REGS));
6783        finish(
6784            &mut out,
6785            &allocation,
6786            &frame,
6787            &Stack::default(),
6788            Convention::new(&SYSV, &FRAME),
6789            &mut names,
6790        );
6791
6792        // The block the split added is where the move went, and it is the whole of that block.
6793        let text = mir::print_func(&out, &names, &REGS);
6794        assert_eq!(out.block_count(), 4, "{text}");
6795        assert_eq!(text.matches("x64.ret\n").count(), 1, "{text}");
6796    }
6797
6798    #[test]
6799    fn a_call_passes_what_the_convention_says_and_takes_back_what_it_says() {
6800        let i32 = Type::int(32);
6801        let (mut names, mut source, block, args) = blank(&[i32, i32]);
6802        let sig =
6803            source.add_signature(Signature::new().with_params(&[i32, i32]).with_returns(&[i32]));
6804        let callee = names.intern("g");
6805        let call = Builder::new(&mut source, block).call(callee, sig, &[args[0], args[1]]);
6806        let got = source[call].first_result.expect("an integer comes back");
6807        Builder::new(&mut source, block).ret(&[got]);
6808
6809        // `int f(int a, int b) { return g(a, b); }`. The arguments arrived where the call wants
6810        // them, so what the call reads is what arrived, and the whole of the convention is in the
6811        // constraints rather than in a move.
6812        let text = lower(&mut names, &source);
6813        assert!(text.contains("= x64.call %0($rdi), %1($rsi), @g"), "{text}");
6814        assert!(text.contains("x64.ret_val_32 %2($rax)"), "{text}");
6815        // What the call writes is the value that comes back and then every register the callee is
6816        // free to destroy, in both classes, which is the whole of what stops the allocator from
6817        // leaving something in one of them.
6818        assert!(text.contains("%2:gpr($rax), $rcx, $rdx, $r8, $r9, $r10, $r11, $xmm0,"), "{text}");
6819        assert!(text.contains("$xmm15 = x64.call"), "{text}");
6820    }
6821
6822    #[test]
6823    fn what_the_frame_owes_a_call_comes_back_with_the_function() {
6824        let i32 = Type::int(32);
6825        let sig = |source: &mut Func| source.add_signature(Signature::new().with_params(&[i32]));
6826
6827        let (mut names, mut source, block, args) = blank(&[i32]);
6828        let sig = sig(&mut source);
6829        let callee = names.intern("g");
6830        Builder::new(&mut source, block).call(callee, sig, &[args[0]]);
6831        let out = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
6832            .expect("every instruction has a rule");
6833
6834        // Nothing on the stack, so nothing owed, but not a leaf either: a function that calls
6835        // owes the callee an aligned stack pointer and may not use the red zone.
6836        assert_eq!(out.stack.calls, Some(0));
6837        let layout = out.stack.layout(Layout::new(&SYSV, REGS));
6838        assert!(!layout.leaf);
6839        assert_eq!(layout.outgoing, 0);
6840
6841        // The same call under the other convention owes thirty two bytes for the callee to spill
6842        // its register arguments into, which is a fact about the convention and not about the call.
6843        let out = func(&source, &mut names, &SELECTOR, &x86_64::WIN64, &Elsewhere::default())
6844            .expect("every instruction has a rule");
6845        assert_eq!(out.stack.calls, Some(32));
6846
6847        // And a function that calls nothing is a leaf, which is what says it may use the red zone.
6848        let (mut names, mut source, block, args) = blank(&[i32]);
6849        Builder::new(&mut source, block).ret(&[args[0]]);
6850        let out = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
6851            .expect("every instruction has a rule");
6852        assert_eq!(out.stack.calls, None);
6853        assert!(out.stack.layout(Layout::new(&SYSV, REGS)).leaf);
6854    }
6855
6856    /// A Windows variadic prologue writes the argument registers the signature did not name into
6857    /// the shadow space the caller already reserved, which makes every argument one run of words up
6858    /// there and a `va_start` the address of the first of them. One `lea` and one store, and no
6859    /// counts, because a list that is a pointer has nowhere to put one and nothing that reads one.
6860    #[test]
6861    fn a_windows_variadic_function_homes_its_spare_registers_in_the_callers_area() {
6862        let mut names = Interner::new();
6863        let params = [Type::int(32), Type::PTR];
6864        let signature = Signature::new().with_params(&params).variadic();
6865        let mut source = Func::new(names.intern("f"), signature);
6866        let block = source.create_block();
6867        let values: Vec<Value> = params.iter().map(|&ty| source.append_param(block, ty)).collect();
6868        let mut build = Builder::new(&mut source, block);
6869        let args = build.func().push_values(&values[1..]);
6870        build.inst(InstData { args, ..InstData::new(Opcode::VaStart) }, &[]);
6871        build.ret(&[]);
6872
6873        let out = func(&source, &mut names, &SELECTOR, &x86_64::WIN64, &Elsewhere::default())
6874            .expect("every instruction has a rule");
6875        let text = mir::print_func(&out.func, &names, &REGS);
6876
6877        // Two named parameters, so the registers at the next two positions hold arguments nobody
6878        // named and both are written up into the caller's area. The displacement is empty here and
6879        // `finish` fills it in, the same way it does for a parameter the registers ran out before.
6880        assert!(text.contains("($r8) = x64.arg_val_64"), "{text}");
6881        assert!(text.contains("($r9) = x64.arg_val_64"), "{text}");
6882        assert_eq!(text.matches("x64.mov_mr_64").count(), 3, "two homed and one stored: {text}");
6883        assert!(!text.contains("x64.mov_ri_32"), "and no field holds a count: {text}");
6884
6885        // All three waiting on the same fixup, and the last of them is the `lea` the list is given,
6886        // sixteen bytes up, which is where the two arguments the signature does name stopped.
6887        assert_eq!(out.stack.arguments.len(), 3);
6888        assert_eq!(out.stack.arguments[2].1, 16);
6889    }
6890
6891    #[test]
6892    fn a_value_that_outlives_a_call_is_not_left_where_the_call_destroys_it() {
6893        let i32 = Type::int(32);
6894        let (mut names, mut source, block, args) = blank(&[i32]);
6895        let sig = source.add_signature(Signature::new().with_params(&[i32]).with_returns(&[i32]));
6896        let callee = names.intern("g");
6897        let call = Builder::new(&mut source, block).call(callee, sig, &[args[0]]);
6898        let got = source[call].first_result.expect("an integer comes back");
6899        let mut build = Builder::new(&mut source, block);
6900        let sum = build.binary(Opcode::Add, got, args[0], Flags::default());
6901        build.ret(&[sum]);
6902
6903        // `int f(int a) { return g(a) + a; }`, which is the smallest program that asks the
6904        // question: `a` is read after the call and `rdi` is a register the call destroys.
6905        let lowered = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
6906            .expect("every instruction has a rule");
6907        let layout = lowered.stack.layout(Layout::new(&SYSV, REGS));
6908        let mut out = lowered.func;
6909        let env = env();
6910        let allocation = rucc_regalloc::run(&mut out, &env, "test", true);
6911        let frame = Frame::of(&out, &allocation, &layout);
6912        finish(
6913            &mut out,
6914            &allocation,
6915            &frame,
6916            &Stack::default(),
6917            Convention::new(&SYSV, &FRAME),
6918            &mut names,
6919        );
6920
6921        // It went to a register the callee has to put back, and the prologue and epilogue are what
6922        // put it back, which is the whole bargain the two halves of a convention make.
6923        let text = mir::print_func(&out, &names, &REGS);
6924        assert!(text.contains("$rbx"), "{text}");
6925        assert!(!text.contains('%'), "{text}");
6926        assert_eq!(text.matches("x64.call").count(), 1, "{text}");
6927    }
6928
6929    #[test]
6930    fn a_call_with_more_arguments_than_registers_writes_the_rest_into_the_outgoing_area() {
6931        let i64 = Type::int(64);
6932        let (mut names, mut source, block, args) = blank(&[i64]);
6933        let seven = vec![i64; 7];
6934        let sig = source.add_signature(Signature::new().with_params(&seven));
6935        let callee = names.intern("g");
6936        let passed = vec![args[0]; 7];
6937        Builder::new(&mut source, block).call(callee, sig, &passed);
6938
6939        let lowered = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
6940            .expect("the seventh goes to memory");
6941        // The bytes the call needs are on the layout the frame is worked out from, so that the
6942        // frame reserves as many as the widest call in the function asked for.
6943        assert_eq!(lowered.stack.calls, Some(8));
6944        let text = mir::print_func(&lowered.func, &names, &REGS);
6945        assert!(text.contains("x64.mov_mr_64 %0, [$rsp]\n"), "{text}");
6946    }
6947
6948    #[test]
6949    fn a_call_this_cannot_make_is_reported_rather_than_made() {
6950        let (mut names, mut source, block, _) = blank(&[]);
6951        let returns = [Type::float(rucc_ir::Float::F80), Type::int(64)];
6952        let sig = source.add_signature(Signature::new().with_returns(&returns));
6953        let callee = names.intern("g");
6954        Builder::new(&mut source, block).call(callee, sig, &[]);
6955        let failed = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
6956            .expect_err("a long double is on the x87");
6957        assert_eq!(failed.to_string(), "what this call gives back is on the x87 stack");
6958    }
6959
6960    /// A `long double` on its own is a different answer, because on its own it comes back on the
6961    /// x87 stack rather than in a register, which is somewhere the call cannot be said to write.
6962    ///
6963    /// So the call gives back nothing at all and the value is taken off the stack by the `fstp`
6964    /// straight after it. That instruction has to be straight after it: the stack is one place and
6965    /// anything else that touched it before this ran would be looking at the value still on it.
6966    #[test]
6967    fn a_call_that_gives_back_a_long_double_takes_it_off_the_stack_at_once() {
6968        let (mut names, mut source, block, _) = blank(&[]);
6969        let long_double = Type::float(rucc_ir::Float::F80);
6970        let sig = source.add_signature(Signature::new().with_returns(&[long_double]));
6971        let callee = names.intern("g");
6972        Builder::new(&mut source, block).call(callee, sig, &[]);
6973
6974        let lowered = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
6975            .expect("the value comes back in st0");
6976        let text = mir::print_func(&lowered.func, &names, &REGS);
6977        let after: Vec<&str> =
6978            text.lines().skip_while(|line| !line.contains("x64.call")).skip(1).collect();
6979        assert_eq!(after[0].trim(), "%0:gpr = x64.lea_64 [$rsp]", "{text}");
6980        assert_eq!(after[1].trim(), "x64.fstp_t [%0]", "{text}");
6981        // And the slot it went into is the sixteen bytes the type takes, like every other one.
6982        assert_eq!(lowered.stack.locals.len(), 1, "{text}");
6983        assert_eq!(lowered.stack.locals[0].size, X87_BYTES);
6984    }
6985
6986    #[test]
6987    fn a_call_through_an_address_goes_through_the_register_the_address_is_in() {
6988        let i32 = Type::int(32);
6989        let (mut names, mut source, block, args) = blank(&[Type::PTR, i32]);
6990        let sig = source.add_signature(Signature::new().with_params(&[i32]).with_returns(&[i32]));
6991        let varargs = source.push_abis(&[]);
6992        let info = source.add_call(CallInfo { callee: None, signature: sig, varargs });
6993        let mut build = Builder::new(&mut source, block);
6994        let inst = InstData {
6995            args: build.func().push_values(&[args[0], args[1]]),
6996            extra: Extra::Call(info),
6997            ..InstData::new(Opcode::CallIndirect)
6998        };
6999        let called = build.inst(inst, &[i32]);
7000        let got = source[called].first_result.expect("an integer comes back");
7001        Builder::new(&mut source, block).ret(&[got]);
7002
7003        // `int f(int (*g)(int), int a) { return g(a); }`. The first operand is the address and
7004        // the arguments are the ones behind it, and everything else about the call is what a call
7005        // to a name would have been.
7006        let text = lower(&mut names, &source);
7007        assert!(text.contains("= x64.call_reg %0, %1($rdi)"), "{text}");
7008        assert!(text.contains("x64.ret_val_32 %2($rax)"), "{text}");
7009        assert!(!text.contains("@g"), "a call through an address names nobody: {text}");
7010    }
7011
7012    #[test]
7013    fn an_instruction_no_rule_covers_is_reported() {
7014        let (mut names, mut source, block, args) = blank(&[Type::PTR]);
7015        let mut build = Builder::new(&mut source, block);
7016        let operands = build.func().push_values(&[args[0]]);
7017        build.inst(InstData { args: operands, ..InstData::new(Opcode::MetaBegin) }, &[]);
7018
7019        // The mark that an object has come into being, which nothing writes an instruction for
7020        // yet: what it needs is a write over a range of the lifetime plane, and that is
7021        // `tamnd/rucc#856`. Nothing about it is a width or a register, so there is nothing for the
7022        // message to add beyond the name.
7023        let failed = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
7024            .expect_err("no rule writes the beginning of a lifetime");
7025        assert_eq!(failed.to_string(), "no rule lowers a `meta_begin`");
7026
7027        // It produces nothing, so there is no type in the message and nothing invents one, and the
7028        // instruction comes back so a caller can ask the function where it was.
7029        let inst = failed.inst().expect("the instruction it is about");
7030        assert_eq!(source[inst].opcode, Opcode::MetaBegin);
7031    }
7032
7033    /// A barrier is written by name here, and what it is depends on the ordering and on nothing
7034    /// else. `crate::expand` is where the reasoning about this machine's memory model lives.
7035    #[test]
7036    fn a_barrier_is_one_instruction_at_the_strongest_ordering_and_none_below_it() {
7037        for order in MemOrder::all().filter(|&order| order != MemOrder::NotAtomic) {
7038            let (mut names, mut source, block, _) = blank(&[]);
7039            let mut build = Builder::new(&mut source, block);
7040            build
7041                .inst(InstData { extra: Extra::Order(order), ..InstData::new(Opcode::Fence) }, &[]);
7042
7043            let text = lower(&mut names, &source);
7044            assert_eq!(text.contains("x64.mfence"), order == MemOrder::SeqCst, "{order:?}: {text}");
7045        }
7046    }
7047
7048    /// A compare and exchange is written by name too, and at the width of the value rather than at
7049    /// the width of the address, which is the mistake worth pinning: everything here is a pointer
7050    /// and only the value says how many bytes the instruction touches.
7051    #[test]
7052    fn a_compare_and_exchange_is_one_instruction_at_the_width_of_the_value() {
7053        for bits in [8, 16, 32, 64] {
7054            let ty = Type::int(bits);
7055            let (mut names, mut source, block, args) = blank(&[Type::PTR, ty, ty]);
7056            let mut build = Builder::new(&mut source, block);
7057            let mem = build.func().add_mem(MemInfo {
7058                size: u64::from(bits / 8),
7059                align: bits / 8,
7060                order: MemOrder::SeqCst,
7061                ..plain()
7062            });
7063            let operands = build.func().push_values(&[args[0], args[1], args[2]]);
7064            build.inst(
7065                InstData {
7066                    args: operands,
7067                    extra: Extra::Mem(mem),
7068                    ..InstData::new(Opcode::Cmpxchg)
7069                },
7070                &[ty, Type::I1],
7071            );
7072
7073            // Two values out of one instruction, the first of them in the register the machine
7074            // reads the expected value out of, the second free for the allocator to place. The
7075            // address is the memory operand and neither of the two values is.
7076            let text = lower(&mut names, &source);
7077            let written = format!("%3:gpr($rax), %4:gpr = x64.cmpxchg_{bits} %1($rax), %2, [%0]");
7078            assert!(text.contains(&written), "{bits}: {text}");
7079        }
7080    }
7081
7082    #[test]
7083    fn more_values_back_than_the_convention_has_registers_for_is_reported() {
7084        let i64 = Type::int(64);
7085        let (mut names, mut source, block, args) = blank(&[i64, i64, i64]);
7086        let mut build = Builder::new(&mut source, block);
7087        build.ret(&[args[0], args[1], args[2]]);
7088
7089        // Two integers come back in `rax` and `rdx` and a third has nowhere to go, which is not a
7090        // gap in the rules but the convention saying no. The front end classifies before it gets
7091        // here, so this is the shape that would mean the classification went wrong.
7092        let failed = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
7093            .expect_err("only two come back");
7094        assert_eq!(
7095            failed.to_string(),
7096            "what this function gives back takes more registers than this convention has for it"
7097        );
7098
7099        let inst = failed.inst().expect("the instruction it is about");
7100        assert_eq!(source[inst].opcode, Opcode::Return);
7101    }
7102
7103    /// A refusal about a signature has no instruction, which is what makes it the one arm apart.
7104    ///
7105    /// Everything else is about something written somewhere in the body and hands it back so a
7106    /// caller can ask the function where it came from. A parameter arrives before the first
7107    /// instruction runs, so there is nothing in the body to point at and the message is about
7108    /// the function.
7109    #[test]
7110    fn a_refusal_about_a_parameter_has_no_instruction_to_point_at() {
7111        let missing = Unsupported::Argument { index: 0, missing: Missing::OnX87 };
7112        assert_eq!(missing.inst(), None);
7113    }
7114
7115    /// An `alloca` of a fixed size, which is what every local whose address is taken becomes.
7116    fn slot(source: &mut Func, block: Block, size: u64, align: u32) -> Value {
7117        let info = MemInfo { size, align, ..plain() };
7118        let mut build = Builder::new(source, block);
7119        let mem = build.func().add_mem(info);
7120        build.value(InstData { extra: Extra::Mem(mem), ..InstData::new(Opcode::Alloca) }, Type::PTR)
7121    }
7122
7123    #[test]
7124    fn a_local_is_memory_in_the_frame_and_one_instruction_that_says_where() {
7125        let (mut names, mut source, block, _) = blank(&[]);
7126        let slot = slot(&mut source, block, 4, 4);
7127        let mut build = Builder::new(&mut source, block);
7128        let nine = build.iconst(Type::int(32), 9);
7129        build.store(nine, slot, plain(), Flags::default());
7130        let loaded = build.load(Type::int(32), slot, plain(), Flags::default());
7131        build.ret(&[loaded]);
7132
7133        let lowered = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
7134            .expect("every instruction has a rule");
7135
7136        // Four bytes on the list the frame is laid out from, and the one instruction that reads
7137        // where they went. Its displacement is nothing here because there is no frame yet, and
7138        // which instruction is waiting for which local is what `finish` is handed.
7139        assert_eq!(lowered.stack.locals, vec![Local { size: 4, align: 4 }]);
7140        assert_eq!(lowered.stack.addresses.len(), 1);
7141        assert_eq!(lowered.stack.addresses[0].1, 0);
7142        assert_eq!(
7143            mir::print_func(&lowered.func, &names, &REGS),
7144            "mfunc @f {\nblock0:\n    %0:gpr = x64.lea_64 [$rsp]\n    \
7145             %1:gpr = x64.mov_ri_32 9\n    x64.mov_mr_32 %1, [%0]\n    \
7146             %2:gpr = x64.mov_rm_32 [%0]\n    x64.ret_val_32 %2($rax)\n}\n"
7147        );
7148    }
7149
7150    #[test]
7151    fn a_local_the_program_declared_says_which_declaration_it_is_and_the_rest_say_nothing() {
7152        let (mut names, mut source, block, _) = blank(&[]);
7153        let scratch = slot(&mut source, block, 4, 4);
7154        let mut build = Builder::new(&mut source, block);
7155        let mem = build.func().add_mem(MemInfo { size: 8, align: 8, ..plain() });
7156        let declared = build
7157            .value(InstData { extra: Extra::Mem(mem), ..InstData::new(Opcode::Alloca) }, Type::PTR);
7158        build.func().declare_mem(mem, 41);
7159        build.store(scratch, declared, MemInfo { size: 8, align: 8, ..plain() }, Flags::default());
7160        build.ret(&[]);
7161
7162        let lowered = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
7163            .expect("every instruction has a rule");
7164
7165        // Two locals and one declaration, held against the order the allocas were lowered in,
7166        // which is the only name a local has by the time the frame places it. The scratch one was
7167        // reached first and is local zero, so the declared one is local one.
7168        assert_eq!(lowered.stack.locals.len(), 2);
7169        assert_eq!(lowered.stack.declared, vec![(1, 41)]);
7170    }
7171
7172    /// A local the program kept in a value comes out saying which register holds it.
7173    ///
7174    /// The other half of the local above, which had a slot. This one has none, so what carries the
7175    /// declaration is the register the instruction computing it writes into.
7176    #[test]
7177    fn a_local_the_program_kept_in_a_value_says_which_register_holds_it() {
7178        let (mut names, mut source, block, _) = blank(&[]);
7179        let mut build = Builder::new(&mut source, block);
7180        let nine = build.iconst(Type::int(32), 9);
7181        let ten = build.iconst(Type::int(32), 10);
7182        let sum = build.binary(Opcode::Add, nine, ten, Flags::default());
7183        build.func().declare_value(sum, 41);
7184        build.ret(&[sum]);
7185
7186        let lowered = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
7187            .expect("every instruction has a rule");
7188
7189        // One pair and not three. The constants are values the program never declared, and a
7190        // register holding one of those is nobody's. The register is the one the addition writes,
7191        // which the listing under it is what pins down.
7192        assert_eq!(lowered.func.named, vec![(41, mir::Reg::virtual_reg(1))]);
7193        assert_eq!(
7194            mir::print_func(&lowered.func, &names, &REGS),
7195            "mfunc @f {\nblock0:\n    %0:gpr = x64.mov_ri_32 9\n    \
7196             %1:gpr(reuse 1) = x64.add_ri_32 %0, 10\n    x64.ret_val_32 %1($rax)\n}\n"
7197        );
7198    }
7199
7200    /// A local held in a constant two blocks want is two registers and both of them are it.
7201    ///
7202    /// Why the declaration is written down as each register is handed out rather than once at the
7203    /// end over the map from values to registers. That map remembers the last register a value was
7204    /// written into, and a constant is written again in every block that wants one, so a local held
7205    /// in one would come out findable in the last block of the function and nowhere else.
7206    #[test]
7207    fn a_local_held_in_a_constant_two_blocks_want_is_named_in_both_of_them() {
7208        let i32 = Type::int(32);
7209        let (mut names, mut source, entry, args) = blank(&[i32, i32]);
7210        let then = source.create_block();
7211        let other = source.create_block();
7212        let join = source.create_block();
7213        let got = source.append_param(join, i32);
7214
7215        let mut build = Builder::new(&mut source, entry);
7216        let seven = build.iconst(i32, 7);
7217        let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
7218        build.func().declare_value(seven, 41);
7219        build.br_if(cond, then, &[], other, &[]);
7220        Builder::new(&mut source, then).jump(join, &[seven]);
7221        Builder::new(&mut source, other).jump(join, &[seven]);
7222        Builder::new(&mut source, join).ret(&[got]);
7223
7224        let lowered = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
7225            .expect("every instruction has a rule");
7226
7227        let held = &lowered.func.named;
7228        assert_eq!(held.len(), 2, "one register per block that wanted the seven: {held:?}");
7229        assert!(held.iter().all(|&(decl, _)| decl == 41), "{held:?}");
7230        assert_ne!(held[0].1, held[1].1, "the same register in two blocks: {held:?}");
7231    }
7232
7233    /// A parameter the program declared comes out named too, in the register it arrived in.
7234    ///
7235    /// The case the walk over the map at the end is for. A parameter is put in a register the
7236    /// convention chose rather than in a fresh one, so nothing asks the mint for it and the pair
7237    /// would otherwise never be written down.
7238    #[test]
7239    fn a_parameter_the_program_declared_says_which_register_it_arrived_in() {
7240        let i32 = Type::int(32);
7241        let (mut names, mut source, block, args) = blank(&[i32]);
7242        let mut build = Builder::new(&mut source, block);
7243        build.func().declare_value(args[0], 41);
7244        build.ret(&[args[0]]);
7245
7246        let lowered = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
7247            .expect("every instruction has a rule");
7248
7249        let held = &lowered.func.named;
7250        assert_eq!(held.len(), 1, "one pair for the one parameter: {held:?}");
7251        assert_eq!(held[0].0, 41);
7252    }
7253
7254    /// A function with nothing declared in it says nothing, which is every function compiled
7255    /// without debugging information asked for.
7256    #[test]
7257    fn a_function_the_front_end_named_nothing_in_names_no_registers() {
7258        let (mut names, mut source, block, _) = blank(&[]);
7259        let mut build = Builder::new(&mut source, block);
7260        let nine = build.iconst(Type::int(32), 9);
7261        build.ret(&[nine]);
7262
7263        let lowered = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
7264            .expect("every instruction has a rule");
7265        assert!(lowered.func.named.is_empty(), "{:?}", lowered.func.named);
7266    }
7267
7268    #[test]
7269    fn the_frame_is_what_fills_the_address_of_a_local_in() {
7270        let (mut names, mut source, block, _) = blank(&[]);
7271        let slot = slot(&mut source, block, 4, 4);
7272        let mut build = Builder::new(&mut source, block);
7273        let nine = build.iconst(Type::int(32), 9);
7274        build.store(nine, slot, plain(), Flags::default());
7275        let loaded = build.load(Type::int(32), slot, plain(), Flags::default());
7276        build.ret(&[loaded]);
7277
7278        let lowered = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
7279            .expect("every instruction has a rule");
7280        let stack = lowered.stack;
7281        let mut out = lowered.func;
7282        let env = env();
7283        let allocation = rucc_regalloc::run(&mut out, &env, "test", true);
7284        let layout = stack.layout(Layout::new(&SYSV, REGS));
7285        let frame = Frame::of(&out, &allocation, &layout);
7286        finish(&mut out, &allocation, &frame, &stack, Convention::new(&SYSV, &FRAME), &mut names);
7287
7288        // `int f(void) { int x; x = 9; return x; }` with the address of `x` taken, end to end.
7289        // A leaf small enough to live in the red zone takes no frame at all, so the stack pointer
7290        // never moves and the four bytes are below it, which is what the negative offset is. The
7291        // instruction the lowering left with nothing in its displacement now has the answer in it.
7292        let text = mir::print_func(&out, &names, &REGS);
7293        assert!(text.contains("$rax = x64.lea_64 [$rsp - 8]"), "{text}");
7294        assert!(!text.contains("x64.sub_ri_64"), "{text}");
7295        assert_eq!(frame.size(), 0);
7296        assert_eq!(frame.local(0), Some(-8));
7297    }
7298
7299    /// An `alloca` whose size is an operand, which is a variable length array.
7300    fn growing(source: &mut Func, block: Block, size: Value, align: u32) -> Value {
7301        let info = MemInfo { size: 0, align, ..plain() };
7302        let mut build = Builder::new(source, block);
7303        let mem = build.func().add_mem(info);
7304        let args = build.func().push_values(&[size]);
7305        build.value(
7306            InstData { args, extra: Extra::Mem(mem), ..InstData::new(Opcode::Alloca) },
7307            Type::PTR,
7308        )
7309    }
7310
7311    #[test]
7312    fn a_stack_slot_whose_size_is_not_known_until_it_runs_takes_the_bytes_off_the_stack_pointer() {
7313        let (mut names, mut source, block, args) = blank(&[Type::int(64)]);
7314        let slot = growing(&mut source, block, args[0], 16);
7315        Builder::new(&mut source, block).ret(&[slot]);
7316
7317        let lowered = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
7318            .expect("every instruction has a rule");
7319
7320        // The bytes come off the stack pointer where the declaration stands and the address is
7321        // where the stack pointer then is, which is one subtraction and one `lea` rather than a
7322        // slot the frame laid out. Nothing is on the list of locals, because there is nothing
7323        // about this the frame could place.
7324        let text = mir::print_func(&lowered.func, &names, &REGS);
7325        assert!(text.contains("$rsp = x64.sub_rr_64 $rsp, %0"), "{text}");
7326        assert!(text.contains("x64.lea_64 [$rsp]"), "{text}");
7327        assert!(lowered.stack.locals.is_empty(), "{text}");
7328        assert_eq!(lowered.stack.dynamic.len(), 1);
7329        assert!(lowered.stack.grown_at.is_some());
7330    }
7331
7332    #[test]
7333    fn a_growing_slot_wanting_more_alignment_than_the_stack_pointer_has_is_reported() {
7334        let (mut names, mut source, block, args) = blank(&[Type::int(64)]);
7335        let slot = growing(&mut source, block, args[0], 32);
7336        Builder::new(&mut source, block).ret(&[slot]);
7337
7338        // Thirty two is more than a call leaves the stack pointer on, so giving it what it asked
7339        // for means masking the stack pointer after moving it, and after that no constant reaches
7340        // the rest of the frame from the frame pointer either. A second pointer held for the
7341        // purpose is what fixes it and there is not one yet.
7342        let failed = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
7343            .expect_err("nothing realigns a frame that grows");
7344        assert_eq!(
7345            failed.to_string(),
7346            "this local wants more alignment than the stack pointer is left on, which needs a \
7347             base register nothing here keeps"
7348        );
7349    }
7350
7351    #[test]
7352    fn a_frame_that_grows_reaches_its_own_locals_through_the_frame_pointer() {
7353        let (mut names, mut source, block, args) = blank(&[Type::int(64)]);
7354        let fixed = slot(&mut source, block, 4, 4);
7355        let mut build = Builder::new(&mut source, block);
7356        let nine = build.iconst(Type::int(32), 9);
7357        build.store(nine, fixed, plain(), Flags::default());
7358        let grown = growing(&mut source, block, args[0], 16);
7359        Builder::new(&mut source, block).ret(&[grown]);
7360
7361        let lowered = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
7362            .expect("every instruction has a rule");
7363        let stack = lowered.stack;
7364        let mut out = lowered.func;
7365        let env = env();
7366        let allocation = rucc_regalloc::run(&mut out, &env, "test", true);
7367        let layout = stack.layout(Layout::new(&SYSV, REGS));
7368        let frame = Frame::of(&out, &allocation, &layout);
7369        finish(&mut out, &allocation, &frame, &stack, Convention::new(&SYSV, &FRAME), &mut names);
7370
7371        // The stack pointer moves in the middle of the function, so the four bytes of the fixed
7372        // local are not a constant away from it any more and the frame pointer is what reaches
7373        // them. The frame keeps one whatever the flags asked for, takes its bytes rather than
7374        // living in the red zone, and the address of the growing slot is off the stack pointer as
7375        // it stands after the subtraction rather than off anything the prologue left.
7376        let text = mir::print_func(&out, &names, &REGS);
7377        assert!(frame.grows());
7378        assert!(frame.frame_pointer());
7379        assert!(frame.size() > 0, "{text}");
7380        assert!(text.contains("x64.lea_64 [$rbp"), "{text}");
7381        assert!(text.contains("$rsp = x64.sub_rr_64 $rsp"), "{text}");
7382        assert!(text.contains("x64.lea_64 [$rsp]"), "{text}");
7383    }
7384
7385    #[test]
7386    fn an_address_is_read_written_and_added_to_like_the_integer_it_is() {
7387        let (mut names, mut source, block, args) = blank(&[Type::PTR, Type::int(64)]);
7388        let mut build = Builder::new(&mut source, block);
7389        let stepped = build.func().push_values(&[args[0], args[1]]);
7390        let next =
7391            build.value(InstData { args: stepped, ..InstData::new(Opcode::PtrAdd) }, Type::PTR);
7392        let loaded = build.load(Type::int(32), next, plain(), Flags::default());
7393        build.ret(&[loaded]);
7394
7395        // `int f(int *p, long i) { return *(int *)((char *)p + i); }`. Nothing about this is new
7396        // in the rule set, which is the point: the two addresses arrive in registers because an
7397        // address is an integer as wide as one, and the arithmetic on them is the add it always
7398        // was, so every rule written about an add reaches it.
7399        //
7400        // The add stays its own instruction here rather than folding into the address the load
7401        // reads from. Two registers with no scale on either is the one addressing mode the rules
7402        // have no load through, because the folds that exist are the displacement one and the
7403        // scaled ones, and this is neither. `crate::fold` is what puts the two together, after
7404        // selection, and this is the pair it is handed.
7405        assert_eq!(
7406            lower(&mut names, &source),
7407            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_64\n    \
7408             %1:gpr($rsi) = x64.arg_val_64\n    %2:gpr(reuse 1) = x64.add_rr_64 %0, %1\n    \
7409             %3:gpr = x64.mov_rm_32 [%2]\n    x64.ret_val_32 %3($rax)\n}\n"
7410        );
7411    }
7412
7413    /// The address of a file scope name, which is what every use of a global and every string
7414    /// literal starts from.
7415    fn address_of(source: &mut Func, block: Block, names: &mut Interner, name: &str) -> Value {
7416        let symbol = names.intern(name);
7417        let mut build = Builder::new(source, block);
7418        build.value(
7419            InstData { extra: Extra::Symbol(symbol), ..InstData::new(Opcode::GlobalAddr) },
7420            Type::PTR,
7421        )
7422    }
7423
7424    #[test]
7425    fn the_address_of_a_name_is_one_instruction_carrying_the_name() {
7426        let (mut names, mut source, block, _) = blank(&[]);
7427        let counter = address_of(&mut source, block, &mut names, "counter");
7428        let mut build = Builder::new(&mut source, block);
7429        let loaded = build.load(Type::int(32), counter, plain(), Flags::default());
7430        build.ret(&[loaded]);
7431
7432        // `extern int counter; int f(void) { return counter; }`. The address is an addressing mode
7433        // that names no register and carries the symbol, which is what the assembler writes
7434        // relative to `%rip` and what the object writer leaves a relocation for.
7435        assert_eq!(
7436            lower(&mut names, &source),
7437            "mfunc @f {\nblock0:\n    %0:gpr = x64.lea_64 [@counter]\n    \
7438             %1:gpr = x64.mov_rm_32 [%0]\n    x64.ret_val_32 %1($rax)\n}\n"
7439        );
7440    }
7441
7442    #[test]
7443    fn the_address_of_a_name_outside_the_file_is_read_out_of_the_offset_table() {
7444        let (mut names, mut source, block, _) = blank(&[]);
7445        let away = address_of(&mut source, block, &mut names, "away");
7446        Builder::new(&mut source, block).ret(&[away]);
7447        let elsewhere: Elsewhere = [names.intern("away")].into_iter().collect();
7448
7449        // `extern void away(void); void *f(void) { return away; }`. A load and not an address
7450        // computation, because the distance from here to a name a shared library may be the one
7451        // that defines is not a number any link can work out, and the slot the linker fills in is
7452        // in this program and so is a distance it has.
7453        let out = func(&source, &mut names, &SELECTOR, &SYSV, &elsewhere)
7454            .expect("every instruction has a rule");
7455        assert_eq!(
7456            mir::print_func(&out.func, &names, &REGS),
7457            "mfunc @f {\nblock0:\n    %0:gpr = x64.mov_rm_64 [got @away]\n    \
7458             x64.ret_val_64 %0($rax)\n}\n"
7459        );
7460    }
7461
7462    #[test]
7463    fn the_address_of_a_thread_local_is_an_offset_out_of_the_table_plus_where_this_thread_starts() {
7464        let (mut names, mut source, block, _) = blank(&[]);
7465        let own = address_of(&mut source, block, &mut names, "own");
7466        Builder::new(&mut source, block).ret(&[own]);
7467        let elsewhere = Elsewhere::default().with_threads([names.intern("own")]);
7468
7469        // `extern _Thread_local int own; void *f(void) { return &own; }`. Three instructions where
7470        // the two cases above are one, because there is no address to load or to work out: the
7471        // slot holds how far into a thread's block the variable sits, `%fs:0` is where this
7472        // thread's block starts, and the sum of the two is this thread's copy.
7473        let out = func(&source, &mut names, &SELECTOR, &SYSV, &elsewhere)
7474            .expect("every instruction has a rule");
7475        assert_eq!(
7476            mir::print_func(&out.func, &names, &REGS),
7477            "mfunc @f {\nblock0:\n    %0:gpr = x64.mov_rm_64 [thread @own]\n    \
7478             %1:gpr = x64.mov_rm_64 [fs:0]\n    %2:gpr(reuse 1) = x64.add_rr_64 %0, %1\n    \
7479             x64.ret_val_64 %2($rax)\n}\n"
7480        );
7481    }
7482
7483    /// The same load with nothing added to it, which is the whole of `__builtin_thread_pointer`.
7484    #[test]
7485    fn the_start_of_this_thread_s_own_storage_is_the_one_load_and_no_arithmetic() {
7486        let (mut names, mut source, block, _) = blank(&[]);
7487        let here =
7488            Builder::new(&mut source, block).value(InstData::new(Opcode::ThreadPointer), Type::PTR);
7489        Builder::new(&mut source, block).ret(&[here]);
7490
7491        let out = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
7492            .expect("every instruction has a rule");
7493        assert_eq!(
7494            mir::print_func(&out.func, &names, &REGS),
7495            "mfunc @f {\nblock0:\n    %0:gpr = x64.mov_rm_64 [fs:0]\n    \
7496             x64.ret_val_64 %0($rax)\n}\n"
7497        );
7498    }
7499
7500    /// One `asm` statement, with its template and its constraint list written as a program does.
7501    fn assembly(
7502        source: &mut Func,
7503        block: Block,
7504        names: &mut Interner,
7505        template: &str,
7506        constraints: &str,
7507        args: &[Value],
7508        results: &[Type],
7509    ) -> Inst {
7510        clobbering(source, block, names, template, constraints, "memory", args, results)
7511    }
7512
7513    /// The same with a clobber list of its own, for the statements that are about one.
7514    #[allow(clippy::too_many_arguments)]
7515    fn clobbering(
7516        source: &mut Func,
7517        block: Block,
7518        names: &mut Interner,
7519        template: &str,
7520        constraints: &str,
7521        clobbers: &str,
7522        args: &[Value],
7523        results: &[Type],
7524    ) -> Inst {
7525        let info = AsmInfo {
7526            template: names.intern(template),
7527            constraints: names.intern(constraints),
7528            clobbers: names.intern(clobbers),
7529            targets: rucc_ir::BlockCallList::EMPTY,
7530        };
7531        Builder::new(source, block).inline_asm(info, args, results, Flags::VOLATILE)
7532    }
7533
7534    /// What a program asking the processor what it can do writes, which is the instruction whose
7535    /// every operand is a register its text does not name.
7536    #[test]
7537    fn a_template_whose_registers_are_named_by_the_constraints_places_them_from_the_letters() {
7538        let u32 = Type::int(32);
7539        let (mut names, mut source, block, _) = blank(&[]);
7540        let zero = Builder::new(&mut source, block).iconst(u32, 0);
7541        let out = clobbering(
7542            &mut source,
7543            block,
7544            &mut names,
7545            "cpuid",
7546            "=a,a",
7547            "ebx,ecx,edx",
7548            &[zero],
7549            &[u32],
7550        );
7551        let produced = source[out].results().next().expect("one result");
7552        Builder::new(&mut source, block).ret(&[produced]);
7553
7554        // `asm ("cpuid" : "=a" (n) : "a" (0) : "ebx", "ecx", "edx")`, which is the first thing
7555        // every program that has a faster path on some machines writes. Four registers written and
7556        // two read, none of them in the template, all of them out of the description, and the two
7557        // that the letters named are the statement's own. The subleaf is a zero because the
7558        // instruction reads `ecx` and the program said nothing about what is in it. The three
7559        // clobbers are gone because `cpuid` writes those three anyway, and saying it twice is one
7560        // register with two definitions.
7561        assert_eq!(
7562            lower(&mut names, &source),
7563            "mfunc @f {\nblock0:\n    %0:gpr = x64.mov_ri_32 0\n    \
7564             %1:gpr = x64.mov_ri_64 0\n    \
7565             %2:gpr($rax), %3:gpr($rbx), %4:gpr($rcx), %5:gpr($rdx) = x64.cpuid %0($rax), \
7566             %1($rcx)\n    x64.ret_val_32 %2($rax)\n}\n"
7567        );
7568    }
7569
7570    /// An operand the program pinned, by declaring the object it comes from `register long x asm
7571    /// ("r12")`. The letter on its own leaves the allocator to pick, and a template that reads the
7572    /// register by name needs the two to be the same register, so the brace is what ties them
7573    /// together. That is the one use of a local register variable the GNU manual calls reliable,
7574    /// and it is what tcc's `tests/tcctest.c` counts on.
7575    #[test]
7576    fn an_operand_the_program_pinned_is_placed_in_the_register_it_named() {
7577        let u64 = Type::int(64);
7578        let (mut names, mut source, block, _) = blank(&[]);
7579        let out =
7580            assembly(&mut source, block, &mut names, "mov $0x4542, %r12", "=r{r12}", &[], &[u64]);
7581        let produced = source[out].results().next().expect("one result");
7582        Builder::new(&mut source, block).ret(&[produced]);
7583
7584        // The template is one instruction the table already has, so it lowers to that instruction
7585        // rather than to text nobody read, and the register it names is the statement's own output
7586        // because the brace put the output there. Without the brace the letter would have let the
7587        // allocator pick, the two `%r12` would have been different registers, and the program would
7588        // have come back with whatever was in the one it picked.
7589        assert_eq!(
7590            lower(&mut names, &source),
7591            "mfunc @f {\nblock0:\n    %0:gpr($r12) = x64.mov_ri_64 17730\n    \
7592             x64.ret_val_64 %0($rax)\n}\n"
7593        );
7594    }
7595
7596    /// A clobber the instruction does not write itself, which is the case the list is there for.
7597    /// It goes on as a definition of the register, in among the other definitions, because that is
7598    /// the whole of how a machine function says a register is not worth anything after this.
7599    #[test]
7600    fn a_clobber_the_instruction_does_not_write_itself_is_a_definition_of_that_register() {
7601        let (mut names, mut source, block, _) = blank(&[]);
7602        clobbering(&mut source, block, &mut names, "pause", "", "rsi,cc,memory", &[], &[]);
7603        Builder::new(&mut source, block).ret(&[]);
7604
7605        assert_eq!(lower(&mut names, &source), "mfunc @f {\nblock0:\n    $rsi = x64.pause\n}\n");
7606    }
7607
7608    /// A clobber naming something this has no register for. Refused rather than dropped, since the
7609    /// list is the program saying which registers it may not leave anything in, and an entry
7610    /// nobody read is a register something may still be left in.
7611    #[test]
7612    fn a_clobber_this_has_no_register_for_is_refused() {
7613        let (mut names, mut source, block, _) = blank(&[]);
7614        clobbering(&mut source, block, &mut names, "pause", "", "zmm0", &[], &[]);
7615        Builder::new(&mut source, block).ret(&[]);
7616
7617        let failed = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
7618            .expect_err("there is no such register here");
7619        assert_eq!(
7620            failed.to_string(),
7621            "this `asm` says it destroys a register this has no name for"
7622        );
7623    }
7624
7625    #[test]
7626    fn an_asm_with_an_empty_template_and_no_operands_is_no_instructions() {
7627        let (mut names, mut source, block, _) = blank(&[]);
7628        assembly(&mut source, block, &mut names, "", "", &[], &[]);
7629        Builder::new(&mut source, block).ret(&[]);
7630
7631        // `asm volatile ("" : : : "memory")`, which is a barrier and nothing else. The barrier was
7632        // spent on the optimizer, which has finished by now, so what is left is nothing.
7633        assert_eq!(lower(&mut names, &source), "mfunc @f {\nblock0:\n}\n");
7634    }
7635
7636    #[test]
7637    fn an_output_an_input_is_tied_to_is_the_register_that_input_arrived_in() {
7638        let i32 = Type::int(32);
7639        let (mut names, mut source, block, args) = blank(&[i32]);
7640        let out = assembly(&mut source, block, &mut names, "", "=r,0", &args, &[i32]);
7641        let produced = source[out].results().next().expect("one result");
7642        Builder::new(&mut source, block).ret(&[produced]);
7643
7644        // `asm ("" : "=r" (x) : "0" (x))`, which is how a program stops the optimizer following a
7645        // value without changing it. The two share a place and the template writes nothing over
7646        // it, so the value comes back out of the register it went in.
7647        assert_eq!(
7648            lower(&mut names, &source),
7649            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_32\n    \
7650             x64.ret_val_32 %0($rax)\n}\n"
7651        );
7652    }
7653
7654    #[test]
7655    fn an_output_written_plus_is_the_same_rename() {
7656        let i32 = Type::int(32);
7657        let (mut names, mut source, block, args) = blank(&[i32]);
7658        let out = assembly(&mut source, block, &mut names, "", "+r", &args, &[i32]);
7659        let produced = source[out].results().next().expect("one result");
7660        Builder::new(&mut source, block).ret(&[produced]);
7661
7662        // `asm ("" : "+r" (x))`, which says the same thing in one operand instead of two.
7663        assert_eq!(
7664            lower(&mut names, &source),
7665            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_32\n    \
7666             x64.ret_val_32 %0($rax)\n}\n"
7667        );
7668    }
7669
7670    #[test]
7671    fn an_output_nothing_is_tied_to_is_a_zero() {
7672        let i32 = Type::int(32);
7673        let (mut names, mut source, block, _) = blank(&[]);
7674        let out = assembly(&mut source, block, &mut names, "", "=r", &[], &[i32]);
7675        let produced = source[out].results().next().expect("one result");
7676        Builder::new(&mut source, block).ret(&[produced]);
7677
7678        // `asm ("" : "=r" (y))`, whose answer is whatever the assembly left in the register, and
7679        // an empty template leaves nothing. A definite value rather than a register nothing wrote,
7680        // because the allocator is owed a definition before the use however little the program is.
7681        assert_eq!(
7682            lower(&mut names, &source),
7683            "mfunc @f {\nblock0:\n    %0:gpr = x64.mov_ri_32 0\n    x64.ret_val_32 %0($rax)\n}\n"
7684        );
7685    }
7686
7687    #[test]
7688    fn a_template_that_is_one_instruction_becomes_that_instruction() {
7689        let (mut names, mut source, block, _) = blank(&[]);
7690        assembly(&mut source, block, &mut names, "pause", "", &[], &[]);
7691        Builder::new(&mut source, block).ret(&[]);
7692
7693        // `asm volatile ("pause")`, which is what every spin lock in every allocator writes. One
7694        // instruction, no operands, and nothing between the template and the machine but the table
7695        // that already says what a `pause` is.
7696        assert_eq!(lower(&mut names, &source), "mfunc @f {\nblock0:\n    x64.pause\n}\n");
7697    }
7698
7699    #[test]
7700    fn a_template_that_reads_a_segment_becomes_the_load_it_already_was() {
7701        let i64 = Type::int(64);
7702        let (mut names, mut source, block, _) = blank(&[]);
7703        let out = assembly(&mut source, block, &mut names, "movq %%fs:0, %0", "=r", &[], &[i64]);
7704        let produced = source[out].results().next().expect("one result");
7705        Builder::new(&mut source, block).ret(&[produced]);
7706
7707        // `asm ("movq %%fs:0, %0" : "=r" (tid))`, which is how a program finds the block its own
7708        // thread owns. The same instruction `crate::lower` already writes for a thread-local
7709        // variable, reached this time because a program wrote it out by hand.
7710        assert_eq!(
7711            lower(&mut names, &source),
7712            "mfunc @f {\nblock0:\n    %0:gpr = x64.mov_rm_64 [fs:0]\n    \
7713             x64.ret_val_64 %0($rax)\n}\n"
7714        );
7715    }
7716
7717    /// A template this cannot read is kept as its text, which is what gcc does with every template.
7718    /// Whether the text is an instruction is the assembler's question, asked when the unit is
7719    /// assembled from its listing.
7720    #[test]
7721    fn a_template_naming_an_instruction_this_machine_has_not_got_is_kept_as_text() {
7722        let (mut names, mut source, block, _) = blank(&[]);
7723        assembly(&mut source, block, &mut names, "hcf", "", &[], &[]);
7724        Builder::new(&mut source, block).ret(&[]);
7725
7726        let printed = lower(&mut names, &source);
7727        assert!(printed.contains("x64.template"), "{printed}");
7728        assert!(printed.contains("@hcf"), "{printed}");
7729    }
7730
7731    /// A template kept as text with an operand in a register reads the operand, and its text holds
7732    /// a hole naming that operand of the instruction, which the writer fills with the register the
7733    /// allocator chose. The input is the instruction's only use, behind every register a call may
7734    /// write.
7735    #[test]
7736    fn a_template_kept_as_text_reads_an_operand_in_a_register_through_a_hole() {
7737        let i32 = Type::int(32);
7738        let (mut names, mut source, block, args) = blank(&[i32]);
7739        assembly(&mut source, block, &mut names, "hcf %0", "r", &[args[0]], &[]);
7740        Builder::new(&mut source, block).ret(&[]);
7741
7742        let printed = lower(&mut names, &source);
7743        let line = printed.lines().find(|line| line.contains("x64.template")).unwrap_or_default();
7744        // Twenty five registers are written ahead of it, so the operand read is the twenty sixth,
7745        // spelled at the width of an `int`.
7746        assert!(line.contains("x64.template %0, @hcf \u{1}r25k\u{2}"), "{printed}");
7747        assert!(line.contains("early $rax"), "{printed}");
7748    }
7749
7750    /// A register the template named is placed as itself, fixed to the register the program wrote
7751    /// down. A register a constraint letter names is a different thing and is placed too, which the
7752    /// test above is about: there the statement said which of its own operands is in the register,
7753    /// and a name in the middle of a template says the register and nothing about any operand.
7754    #[test]
7755    fn a_template_naming_a_register_gets_that_register() {
7756        let i64 = Type::int(64);
7757        let (mut names, mut source, block, _) = blank(&[]);
7758        let out = assembly(&mut source, block, &mut names, "movq %%rax, %0", "=r", &[], &[i64]);
7759        let produced = source[out].results().next().expect("one result");
7760        Builder::new(&mut source, block).ret(&[produced]);
7761
7762        // `asm ("movq %%rax, %0" : "=r" (x))`, which is a program reading whatever is in `%rax`.
7763        // The source is the register itself and the destination is one the allocator picks.
7764        assert_eq!(
7765            lower(&mut names, &source),
7766            "mfunc @f {\nblock0:\n    %0:gpr = x64.mov_rr_64 $rax($rax)\n    \
7767             x64.ret_val_64 %0($rax)\n}\n"
7768        );
7769    }
7770
7771    /// The half of the same thing every register saving template needs. micropython writes the
7772    /// callee-saved registers into a buffer one `movq %%r12, 48(%%rdi)` at a time, and both halves
7773    /// of that line are a register the template named: the one being stored and the one the address
7774    /// is counted from.
7775    #[test]
7776    fn a_template_counting_an_address_from_a_register_it_named_gets_that_register() {
7777        let (mut names, mut source, block, _) = blank(&[]);
7778        assembly(&mut source, block, &mut names, "movq %%r12, 48(%%rdi)", "", &[], &[]);
7779        Builder::new(&mut source, block).ret(&[]);
7780
7781        assert_eq!(
7782            lower(&mut names, &source),
7783            "mfunc @f {\nblock0:\n    x64.mov_mr_64 $r12($r12), [$rdi + 48]\n}\n"
7784        );
7785    }
7786
7787    /// A local kept in a named register, which is the same register named as itself and reached
7788    /// from the other side. micropython's collector writes six of these and reads them with
7789    /// ordinary C rather than with a template.
7790    #[test]
7791    fn a_local_kept_in_a_named_register_is_one_move_out_of_it() {
7792        let (mut names, mut source, block, _) = blank(&[]);
7793        let held = names.intern("rbx");
7794        let value = Builder::new(&mut source, block).value(
7795            InstData { extra: Extra::Symbol(held), ..InstData::new(Opcode::RegisterValue) },
7796            Type::int(64),
7797        );
7798        Builder::new(&mut source, block).ret(&[value]);
7799
7800        assert_eq!(
7801            lower(&mut names, &source),
7802            "mfunc @f {\nblock0:\n    %0:gpr = x64.mov_rr_64 $rbx($rbx)\n    \
7803             x64.ret_val_64 %0($rax)\n}\n"
7804        );
7805    }
7806
7807    /// The sigil gcc allows in front of the name is syntax and comes off, and a name that is not
7808    /// a register of this machine is refused in words that say which name it was.
7809    #[test]
7810    fn a_register_name_is_read_with_or_without_its_sigil_and_refused_when_there_is_no_such_one() {
7811        for written in ["%r12", "r12"] {
7812            let (mut names, mut source, block, _) = blank(&[]);
7813            let held = names.intern(written);
7814            let value = Builder::new(&mut source, block).value(
7815                InstData { extra: Extra::Symbol(held), ..InstData::new(Opcode::RegisterValue) },
7816                Type::int(64),
7817            );
7818            Builder::new(&mut source, block).ret(&[value]);
7819            assert!(lower(&mut names, &source).contains("$r12($r12)"), "{written} is not read");
7820        }
7821
7822        let (mut names, mut source, block, _) = blank(&[]);
7823        let held = names.intern("nowhere");
7824        let value = Builder::new(&mut source, block).value(
7825            InstData { extra: Extra::Symbol(held), ..InstData::new(Opcode::RegisterValue) },
7826            Type::int(64),
7827        );
7828        Builder::new(&mut source, block).ret(&[value]);
7829
7830        let failed = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
7831            .expect_err("there is no such register");
7832        assert_eq!(
7833            failed.to_string(),
7834            "this object is kept in `nowhere`, which is not a register this machine has"
7835        );
7836    }
7837
7838    #[test]
7839    fn a_constraint_list_that_does_not_describe_the_operands_is_refused() {
7840        let i32 = Type::int(32);
7841        let (mut names, mut source, block, args) = blank(&[i32]);
7842        assembly(&mut source, block, &mut names, "", "=r", &args, &[]);
7843        Builder::new(&mut source, block).ret(&[]);
7844
7845        // An output with no result to be, which is what the front end never writes and what a
7846        // hand written module can. Refused rather than placed by a guess.
7847        let failed = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
7848            .expect_err("the list and the instruction disagree");
7849        assert_eq!(failed.to_string(), "this `asm` has an operand this cannot place");
7850    }
7851
7852    /// A cast between a pointer and an integer, at whatever width the result is asked for.
7853    fn cast(source: &mut Func, block: Block, opcode: Opcode, from: Value, to: Type) -> Value {
7854        let mut build = Builder::new(source, block);
7855        let args = build.func().push_values(&[from]);
7856        build.value(InstData { args, ..InstData::new(opcode) }, to)
7857    }
7858
7859    #[test]
7860    fn a_cast_between_a_pointer_and_an_integer_as_wide_is_no_instruction_at_all() {
7861        let (mut names, mut source, block, args) = blank(&[Type::PTR]);
7862        let number = cast(&mut source, block, Opcode::PtrToInt, args[0], Type::int(64));
7863        Builder::new(&mut source, block).ret(&[number]);
7864
7865        // `long f(void *p) { return (long)p; }`. An address on this machine is an integer as wide
7866        // as the machine addresses, so the cast changes what the type system calls the value and
7867        // changes nothing about the value, and the register holding it is the one that held it.
7868        assert_eq!(
7869            lower(&mut names, &source),
7870            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_64\n    \
7871             x64.ret_val_64 %0($rax)\n}\n"
7872        );
7873    }
7874
7875    #[test]
7876    fn a_null_pointer_is_a_constant_that_reaches_a_register_before_anything_reads_it() {
7877        let (mut names, mut source, block, _) = blank(&[]);
7878        let mut build = Builder::new(&mut source, block);
7879        let zero = build.iconst(Type::int(64), 0);
7880        let null = cast(&mut source, block, Opcode::IntToPtr, zero, Type::PTR);
7881        Builder::new(&mut source, block).ret(&[null]);
7882
7883        // `void *f(void) { return 0; }`. The cast is nothing, and reading its operand is what
7884        // writes the zero down: a constant is materialized where it is wanted rather than where
7885        // the IR defined it, and without the read there would be no instruction at all.
7886        assert_eq!(
7887            lower(&mut names, &source),
7888            "mfunc @f {\nblock0:\n    %0:gpr = x64.mov_ri_64 0\n    x64.ret_val_64 %0($rax)\n}\n"
7889        );
7890    }
7891
7892    #[test]
7893    fn the_five_linkages_the_ir_has_narrow_to_the_three_an_object_file_can_say() {
7894        let readings = [
7895            (Linkage::External, mir::Binding::Global),
7896            (Linkage::Common, mir::Binding::Global),
7897            (Linkage::Internal, mir::Binding::Local),
7898            (Linkage::Weak, mir::Binding::Weak),
7899            (Linkage::LinkOnce, mir::Binding::Weak),
7900        ];
7901        for (linkage, wanted) in readings {
7902            let (mut names, mut source, block, _) = blank(&[]);
7903            source.linkage = linkage;
7904            Builder::new(&mut source, block).ret(&[]);
7905            let out = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
7906                .expect("a return");
7907            // The narrowing is done here rather than where the object is written, because a
7908            // machine function is all the assembler and the writer are ever handed.
7909            assert_eq!(out.func.binding, wanted, "{linkage:?}");
7910        }
7911    }
7912
7913    /// The visibility makes the same trip and is not narrowed on the way, because ELF says all
7914    /// three of them.
7915    ///
7916    /// Here for the reason the linkage above is here. A machine function is the whole of what the
7917    /// assembler and the object writer are handed, so a fact about the symbol that does not get
7918    /// onto one is a fact that is gone by the time anything could write it down, and the way that
7919    /// shows up is a shared library exporting the wrong set of names with nothing said anywhere.
7920    #[test]
7921    fn the_visibility_survives_the_trip_from_the_ir_to_a_machine_function() {
7922        let readings = [
7923            (Visibility::Default, mir::Visibility::Default),
7924            (Visibility::Hidden, mir::Visibility::Hidden),
7925            (Visibility::Protected, mir::Visibility::Protected),
7926        ];
7927        for (visibility, wanted) in readings {
7928            let (mut names, mut source, block, _) = blank(&[]);
7929            source.visibility = visibility;
7930            Builder::new(&mut source, block).ret(&[]);
7931            let out = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
7932                .expect("a return");
7933            assert_eq!(out.func.visibility, wanted, "{visibility:?}");
7934        }
7935    }
7936
7937    #[test]
7938    fn a_cast_between_a_pointer_and_a_narrower_integer_is_reported() {
7939        let (mut names, mut source, block, args) = blank(&[Type::PTR]);
7940        let number = cast(&mut source, block, Opcode::PtrToInt, args[0], Type::int(32));
7941        Builder::new(&mut source, block).ret(&[number]);
7942
7943        // The front end never writes one: it casts at the address width and truncates or extends
7944        // around it, so both of those are the rules they always were. IR from somewhere else that
7945        // does write one is refused rather than compiled to a move that keeps the high half.
7946        let failed = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
7947            .expect_err("no rule narrows an address");
7948        assert_eq!(failed.to_string(), "no rule lowers a `ptrtoint` producing a `i32`");
7949    }
7950
7951    /// The type this machine has no register for.
7952    fn long_double() -> Type {
7953        Type::float(rucc_ir::Float::F80)
7954    }
7955
7956    #[test]
7957    fn a_double_widened_and_narrowed_again_goes_out_through_the_frame_and_back() {
7958        let f64 = Type::float(rucc_ir::Float::F64);
7959        let (mut names, mut source, block, args) = blank(&[f64]);
7960        let wide = cast(&mut source, block, Opcode::FPExt, args[0], long_double());
7961        let back = cast(&mut source, block, Opcode::FPTrunc, wide, f64);
7962        Builder::new(&mut source, block).ret(&[back]);
7963
7964        // `double f(double d) { long double x = d; return x; }`. The x87 reads memory and nothing
7965        // else, so the value is written to the crossing slot, loaded at the format that widens it
7966        // and put in the slot the eighty bit value lives in. Coming back is the same three the
7967        // other way. Both slots are addressed by a `lea` with nothing in it yet, which is what
7968        // every address in a frame looks like here until `finish` has the numbers.
7969        assert_eq!(
7970            lower(&mut names, &source),
7971            "mfunc @f {\nblock0:\n    \
7972             %0:xmm($xmm0) = x64.arg_val_f64\n    \
7973             %1:gpr = x64.lea_64 [$rsp]\n    \
7974             %2:gpr = x64.lea_64 [$rsp]\n    \
7975             x64.movsd_mr %0, [%1]\n    \
7976             x64.fld_l [%1]\n    \
7977             x64.fstp_t [%2]\n    \
7978             %3:gpr = x64.lea_64 [$rsp]\n    \
7979             %4:gpr = x64.lea_64 [$rsp]\n    \
7980             x64.fld_t [%3]\n    \
7981             x64.fstp_l [%4]\n    \
7982             %5:xmm = x64.movsd_rm [%4]\n    \
7983             x64.ret_val_f64 %5($xmm0)\n}\n"
7984        );
7985    }
7986
7987    #[test]
7988    fn a_long_double_has_sixteen_bytes_of_its_own_and_keeps_them() {
7989        let f64 = Type::float(rucc_ir::Float::F64);
7990        let (mut names, mut source, block, args) = blank(&[f64]);
7991        let wide = cast(&mut source, block, Opcode::FPExt, args[0], long_double());
7992        let once = cast(&mut source, block, Opcode::FPTrunc, wide, f64);
7993        let twice = cast(&mut source, block, Opcode::FPTrunc, wide, f64);
7994        let mut build = Builder::new(&mut source, block);
7995        let sum = build.binary(Opcode::FAdd, once, twice, Flags::default());
7996        build.ret(&[sum]);
7997
7998        let out = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
7999            .expect("every instruction is written");
8000
8001        // Two slots and not four: sixteen bytes for the one eighty bit value, which is what the
8002        // psABI says one takes and is aligned to, and eight for the crossing, which every group
8003        // in the function shares because nothing is ever left in it. The value's slot is its own
8004        // for the whole function, so reading it twice reads the same sixteen bytes.
8005        assert_eq!(
8006            out.stack.locals,
8007            vec![Local { size: 8, align: 8 }, Local { size: 16, align: 16 }]
8008        );
8009    }
8010
8011    #[test]
8012    fn an_integer_becomes_a_long_double_by_being_loaded_as_one() {
8013        let (mut names, mut source, block, args) = blank(&[Type::int(64)]);
8014        let wide = cast(&mut source, block, Opcode::SIToFP, args[0], long_double());
8015        let back =
8016            cast(&mut source, block, Opcode::FPTrunc, wide, Type::float(rucc_ir::Float::F64));
8017        Builder::new(&mut source, block).ret(&[back]);
8018
8019        // `double f(long n) { long double x = n; return x; }`. `fild` is the same push at another
8020        // format, so the conversion is the load and there is no instruction that converts.
8021        let text = lower(&mut names, &source);
8022        assert!(text.contains("x64.mov_mr_64 %0, [%1]"), "{text}");
8023        assert!(text.contains("x64.fild_ll [%1]"), "{text}");
8024    }
8025
8026    #[test]
8027    fn a_long_double_becoming_an_integer_cuts_towards_zero_with_the_control_word() {
8028        let (mut names, mut source, block, args) = blank(&[Type::float(rucc_ir::Float::F64)]);
8029        let wide = cast(&mut source, block, Opcode::FPExt, args[0], long_double());
8030        let whole = cast(&mut source, block, Opcode::FPToSI, wide, Type::int(32));
8031        Builder::new(&mut source, block).ret(&[whole]);
8032
8033        // The one conversion here with no single instruction behind it. C cuts towards zero and
8034        // the unit rounds the way its control word says, so the word is saved, ORed with the two
8035        // bits that mean truncate, loaded, used and put back. Nine instructions for what `fisttp`
8036        // does in one, and `spec/10-backend.md` section 10.8 says why that one is not used.
8037        let text = lower(&mut names, &source);
8038        let group: Vec<&str> = text
8039            .lines()
8040            .map(str::trim)
8041            .filter(|line| line.starts_with("x64.f") || line.contains("_16"))
8042            .collect();
8043        assert_eq!(
8044            group,
8045            [
8046                "x64.fld_l [%1]",
8047                "x64.fstp_t [%2]",
8048                "x64.fnstcw [%5]",
8049                "%6:gpr = x64.mov_rm_16 [%5]",
8050                "%7:gpr(reuse 1) = x64.or_ri_16 %6, 3072",
8051                "x64.mov_mr_16 %7, [%5 + 2]",
8052                "x64.fldcw [%5 + 2]",
8053                "x64.fld_t [%3]",
8054                "x64.fistp_l [%4]",
8055                "x64.fldcw [%5]",
8056            ],
8057            "{text}"
8058        );
8059    }
8060
8061    #[test]
8062    fn a_long_double_is_read_and_written_as_the_bits_it_already_is() {
8063        let (mut names, mut source, block, args) = blank(&[Type::PTR, Type::PTR]);
8064        let mut build = Builder::new(&mut source, block);
8065        let value = build.load(long_double(), args[0], plain(), Flags::default());
8066        build.store(value, args[1], plain(), Flags::default());
8067        build.ret(&[]);
8068
8069        // `void f(long double *a, long double *b) { *b = *a; }`. A copy is a push and a pop at the
8070        // format the value is already in, which neither converts nor looks: a signalling NaN stays
8071        // one and nothing is raised, which is the whole of what makes it a copy.
8072        let text = lower(&mut names, &source);
8073        let group: Vec<&str> =
8074            text.lines().map(str::trim).filter(|line| line.starts_with("x64.f")).collect();
8075        assert_eq!(
8076            group,
8077            ["x64.fld_t [%0]", "x64.fstp_t [%2]", "x64.fld_t [%3]", "x64.fstp_t [%1]"],
8078            "{text}"
8079        );
8080    }
8081
8082    /// Two `long double` values, from two `double` parameters, and the instructions that made
8083    /// them, which every test below this one throws away.
8084    fn two_long_doubles(source: &mut Func, block: Block, args: &[Value]) -> (Value, Value) {
8085        let left = cast(source, block, Opcode::FPExt, args[0], long_double());
8086        let right = cast(source, block, Opcode::FPExt, args[1], long_double());
8087        (left, right)
8088    }
8089
8090    /// The x87 instructions of a function, in order, with everything else dropped.
8091    fn stack_only(text: &str) -> Vec<&str> {
8092        text.lines().map(str::trim).filter(|line| line.contains("x64.f")).collect()
8093    }
8094
8095    /// The two frame slots the last two addresses of a function were taken of, which in a
8096    /// comparison are the two operands in the order they go on the stack.
8097    fn pushed(out: &Lowered) -> Vec<usize> {
8098        let taken: Vec<usize> = out.stack.addresses.iter().map(|&(_, local)| local).collect();
8099        taken[taken.len() - 2..].to_vec()
8100    }
8101
8102    #[test]
8103    fn adding_two_long_doubles_pushes_both_and_leaves_the_answer_in_a_slot() {
8104        let f64 = Type::float(rucc_ir::Float::F64);
8105        let (mut names, mut source, block, args) = blank(&[f64, f64]);
8106        let (left, right) = two_long_doubles(&mut source, block, &args);
8107        let sum =
8108            Builder::new(&mut source, block).binary(Opcode::FAdd, left, right, Flags::default());
8109        let back = cast(&mut source, block, Opcode::FPTrunc, sum, f64);
8110        Builder::new(&mut source, block).ret(&[back]);
8111
8112        // `double f(double a, double b) { return (long double) a + (long double) b; }`. The last
8113        // four lines are the add: both operands pushed, the instruction that names neither of
8114        // them because they are the top two of a stack, and the answer taken off into its slot.
8115        let text = lower(&mut names, &source);
8116        assert_eq!(
8117            stack_only(&text),
8118            [
8119                "x64.fld_l [%2]",
8120                "x64.fstp_t [%3]",
8121                "x64.fld_l [%4]",
8122                "x64.fstp_t [%5]",
8123                "x64.fld_t [%6]",
8124                "x64.fld_t [%7]",
8125                "x64.fadd_p",
8126                "x64.fstp_t [%8]",
8127                "x64.fld_t [%9]",
8128                "x64.fstp_l [%10]",
8129            ],
8130            "{text}"
8131        );
8132    }
8133
8134    #[test]
8135    fn a_subtraction_pushes_the_left_operand_first_and_asks_for_the_att_spelling() {
8136        let f64 = Type::float(rucc_ir::Float::F64);
8137        let (mut names, mut source, block, args) = blank(&[f64, f64]);
8138        let (left, right) = two_long_doubles(&mut source, block, &args);
8139        let less =
8140            Builder::new(&mut source, block).binary(Opcode::FSub, left, right, Flags::default());
8141        let back = cast(&mut source, block, Opcode::FPTrunc, less, f64);
8142        Builder::new(&mut source, block).ret(&[back]);
8143
8144        // The left one goes on first, so it ends up under the right one, and the answer wanted is
8145        // the one below minus the top. In AT&T that is `fsubrp`, since `fsubp` there is `DE E0+i`
8146        // and computes the other one. The `r` says which spelling this is and not which order the
8147        // pushes were in. `crates/rucc/tests/x87.rs` is what says the answer is right, because a
8148        // name is what got this wrong the first time.
8149        let text = lower(&mut names, &source);
8150        assert_eq!(
8151            &stack_only(&text)[4..8],
8152            ["x64.fld_t [%6]", "x64.fld_t [%7]", "x64.fsubr_p", "x64.fstp_t [%8]"],
8153            "{text}"
8154        );
8155    }
8156
8157    #[test]
8158    fn negating_a_long_double_turns_the_sign_over_and_reads_nothing() {
8159        let f64 = Type::float(rucc_ir::Float::F64);
8160        let (mut names, mut source, block, args) = blank(&[f64]);
8161        let wide = cast(&mut source, block, Opcode::FPExt, args[0], long_double());
8162        let flipped = Builder::new(&mut source, block).unary(Opcode::FNeg, wide, long_double());
8163        let back = cast(&mut source, block, Opcode::FPTrunc, flipped, f64);
8164        Builder::new(&mut source, block).ret(&[back]);
8165
8166        // `fchs` and not a subtraction from zero, which would give a different answer at a negative
8167        // zero and would signal at a NaN. It does not read the value as a number at all.
8168        let text = lower(&mut names, &source);
8169        assert_eq!(
8170            &stack_only(&text)[2..5],
8171            ["x64.fld_t [%3]", "x64.fchs", "x64.fstp_t [%4]"],
8172            "{text}"
8173        );
8174    }
8175
8176    #[test]
8177    fn comparing_two_long_doubles_puts_the_left_one_on_top() {
8178        let f64 = Type::float(rucc_ir::Float::F64);
8179        let (mut names, mut source, block, args) = blank(&[f64, f64]);
8180        let (left, right) = two_long_doubles(&mut source, block, &args);
8181        let mut build = Builder::new(&mut source, block);
8182        build.fcmp(FloatPred::Ogt, left, right, Flags::default());
8183        build.ret(&[]);
8184
8185        // `a > b`. `fucomip` asks about the top of the stack against what is under it, so the
8186        // operand the predicate is about has to go on last, which is the other way round from the
8187        // arithmetic above. The pop that clears the loser and the byte that reads the flags are
8188        // both inside the one opcode.
8189        let out = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
8190            .expect("every instruction is written");
8191        let slots = pushed(&out);
8192        assert_eq!(slots, [2, 1], "the right operand goes on first and the left one on top");
8193        let text = mir::print_func(&out.func, &names, &REGS);
8194        assert_eq!(
8195            &stack_only(&text)[4..],
8196            ["x64.fld_t [%6]", "x64.fld_t [%7]", "%8:gpr = x64.fucomip_set_a"],
8197            "{text}"
8198        );
8199    }
8200
8201    #[test]
8202    fn a_comparison_that_the_machine_has_backwards_swaps_the_two_pushes() {
8203        let f64 = Type::float(rucc_ir::Float::F64);
8204        let (mut names, mut source, block, args) = blank(&[f64, f64]);
8205        let (left, right) = two_long_doubles(&mut source, block, &args);
8206        let mut build = Builder::new(&mut source, block);
8207        build.fcmp(FloatPred::Olt, left, right, Flags::default());
8208        build.ret(&[]);
8209
8210        // `a < b` is `b > a` and this machine has the one condition, so the same opcode runs with
8211        // the operands the other way round. The same trade the vector rules make, and it has to
8212        // be the same one: a `long double` comparison that picked a different condition from the
8213        // `double` comparison of the same two numbers would be wrong at exactly the unordered
8214        // cases the two conditions differ on.
8215        //
8216        // Which slot each push names is the whole of the difference from the test above, and the
8217        // text does not show it, since an address in a frame is a `lea` with nothing in it until
8218        // `finish` has the numbers. So the slots are what is read here.
8219        let out = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
8220            .expect("every instruction is written");
8221        let slots = pushed(&out);
8222        assert_eq!(slots, [1, 2], "the left operand goes on first and the right one on top");
8223        let text = mir::print_func(&out.func, &names, &REGS);
8224        assert_eq!(
8225            &stack_only(&text)[4..],
8226            ["x64.fld_t [%6]", "x64.fld_t [%7]", "%8:gpr = x64.fucomip_set_a"],
8227            "{text}"
8228        );
8229    }
8230
8231    #[test]
8232    fn an_ordered_equal_needs_a_second_byte_to_put_the_two_conditions_together() {
8233        let f64 = Type::float(rucc_ir::Float::F64);
8234        let (mut names, mut source, block, args) = blank(&[f64, f64]);
8235        let (left, right) = two_long_doubles(&mut source, block, &args);
8236        let mut build = Builder::new(&mut source, block);
8237        build.fcmp(FloatPred::Oeq, left, right, Flags::default());
8238        build.ret(&[]);
8239
8240        // Equal and ordered are two conditions and the flags carry both, so the opcode writes a
8241        // second register as well as the one the value is in and ANDs them together. Said here by
8242        // handing it a spare, since an instruction that wrote a register nothing knew about would
8243        // be an instruction the allocator could put a live value in the way of.
8244        let text = lower(&mut names, &source);
8245        assert!(text.contains("%8:gpr, %9:gpr = x64.fucomip_set_e_and_np"), "{text}");
8246    }
8247
8248    #[test]
8249    fn a_comparison_that_is_never_asked_is_reported() {
8250        let f64 = Type::float(rucc_ir::Float::F64);
8251        let (mut names, mut source, block, args) = blank(&[f64, f64]);
8252        let (left, right) = two_long_doubles(&mut source, block, &args);
8253        let mut build = Builder::new(&mut source, block);
8254        build.fcmp(FloatPred::False, left, right, Flags::default());
8255        build.ret(&[]);
8256
8257        // Always false is a constant and not a comparison, so there is no condition to pick and
8258        // nothing here folds it into one: an instruction that quietly agreed with it would hide
8259        // that the optimizer left a comparison in that it should have taken out.
8260        let failed = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
8261            .expect_err("no condition is always false");
8262        assert_eq!(failed.to_string(), "no rule lowers a `fcmp` producing a `i1`");
8263    }
8264
8265    #[test]
8266    fn a_long_double_constant_is_the_bits_of_it_put_where_the_value_lives() {
8267        let (mut names, mut source, block, args) = blank(&[Type::PTR]);
8268        let mut build = Builder::new(&mut source, block);
8269        // `1.5L`, which is the leading bit and one more of significand, and an exponent of zero.
8270        let one_and_a_half = build.fconst(long_double(), 0x3fff_c000_0000_0000_0000);
8271        build.store(one_and_a_half, args[0], plain(), Flags::default());
8272        build.ret(&[]);
8273
8274        // No x87 instruction at all. A slot holding one of these is the value, so a constant is
8275        // its ten bytes written where the value lives, and whatever reads it does the `fld`.
8276        let text = lower(&mut names, &source);
8277        assert!(text.contains("x64.mov_ri_64 -4611686018427387904"), "{text}");
8278        assert!(text.contains("x64.mov_ri_16 16383"), "{text}");
8279        assert!(text.contains("x64.mov_mr_16 %3, [%1 + 8]"), "{text}");
8280        // The six bytes above the ten are the padding that makes the type sixteen wide, and they
8281        // are unspecified rather than zero, so nothing writes them.
8282        assert_eq!(text.matches("x64.mov_mr").count(), 2, "{text}");
8283    }
8284
8285    #[test]
8286    fn a_negative_long_double_constant_keeps_the_bit_above_its_exponent() {
8287        let (mut names, mut source, block, args) = blank(&[Type::PTR]);
8288        let mut build = Builder::new(&mut source, block);
8289        let minus = build.fconst(long_double(), 0xbfff_c000_0000_0000_0000);
8290        build.store(minus, args[0], plain(), Flags::default());
8291        build.ret(&[]);
8292
8293        // `-1.5L`. The sign is the top bit of the two byte half, so the immediate that half is put
8294        // in a register with is above the signed range of sixteen bits and has to stay there: read
8295        // as a number it would be negative, and it is not a number, it is two bytes.
8296        let text = lower(&mut names, &source);
8297        assert!(text.contains("x64.mov_ri_16 49151"), "{text}");
8298    }
8299
8300    #[test]
8301    fn a_long_double_crosses_an_edge_as_an_address_and_is_copied_where_it_lands() {
8302        let (mut names, mut source, block, args) = blank(&[Type::float(rucc_ir::Float::F64)]);
8303        let wide = cast(&mut source, block, Opcode::FPExt, args[0], long_double());
8304        let next = source.create_block();
8305        let param = source.append_param(next, long_double());
8306        Builder::new(&mut source, block).jump(next, &[wide]);
8307        Builder::new(&mut source, next).ret(&[param]);
8308
8309        // What the edge carries is the address of the slot the value is already in, which is an
8310        // ordinary register the allocator has an opinion about. The block on the other side copies
8311        // the sixteen bytes into a slot of its own before anything reads them, so a second edge
8312        // handing over a second address would still leave one place for a reader to look.
8313        let text = lower(&mut names, &source);
8314        let second: Vec<&str> = text
8315            .lines()
8316            .skip_while(|line| !line.starts_with("block1"))
8317            .skip(1)
8318            .take(3)
8319            .map(str::trim)
8320            .collect();
8321        assert_eq!(
8322            second,
8323            ["x64.fld_t [%4]", "%5:gpr = x64.lea_64 [$rsp]", "x64.fstp_t [%5]"],
8324            "{text}"
8325        );
8326    }
8327
8328    #[test]
8329    fn more_long_doubles_at_a_block_than_the_stack_is_deep_are_reported() {
8330        let f64 = Type::float(rucc_ir::Float::F64);
8331        let (mut names, mut source, block, args) = blank(&[f64]);
8332        let wide = cast(&mut source, block, Opcode::FPExt, args[0], long_double());
8333        let next = source.create_block();
8334        let params: Vec<Value> =
8335            (0..=X87_DEPTH).map(|_| source.append_param(next, long_double())).collect();
8336        let carried: Vec<Value> = params.iter().map(|_| wide).collect();
8337        Builder::new(&mut source, block).jump(next, &carried);
8338        Builder::new(&mut source, next).ret(&[params[0]]);
8339
8340        // The copies go through the x87 stack so that every one of them is read before any of them
8341        // is written, which is what makes a block that swaps two of these right. Nine of them do
8342        // not fit on the stack, and copying the ninth before or after the rest is the order that
8343        // could be wrong, so it is refused instead.
8344        let failed = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
8345            .expect_err("nine do not fit on the stack");
8346        assert_eq!(
8347            failed.to_string(),
8348            "block1 takes 9 parameters of type `f80` and only 8 can cross an edge at once"
8349        );
8350        assert_eq!(failed.inst(), None);
8351    }
8352}