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/// The same instruction [`x86_64::FRAME`] names for the end of a tail call, named here as well
105/// because what reaches this one is a template in a function with no prologue and no epilogue,
106/// which is nothing to do with the frame.
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 the block `__builtin_apply_args` answers takes, which is a word for where the
177/// arguments in memory are, a word of nothing and then the register save area of a variadic
178/// function. See [`Lowering::save_arguments`].
179const APPLY_ARGS: u32 = 192;
180
181/// How far into that block the registers start, which is how far the save area has moved up.
182const APPLY_REGS: u32 = 16;
183
184/// How many bytes the block `__builtin_apply` answers takes, which is two words and two vectors.
185const APPLY_BACK: u32 = 48;
186
187/// How many bytes a value passes through on its way between a register and the x87 stack.
188///
189/// Eight, because the widest thing that crosses is a `double` or a sixty four bit integer, and
190/// nothing crosses at eighty bits: a value that wide is already in the frame and the stack reaches
191/// it where it is.
192const X87_CROSSING: u32 = 8;
193
194/// Where the rounding field of the x87 control word is and what it has to be set to for the unit
195/// to cut towards zero, which is the one rounding C asks for that the unit does not do by default.
196///
197/// Both bits on is truncate. The field is ORed into the word that was already there rather than
198/// written over it, so the precision control and the exception masks somebody else set stay set.
199const X87_TRUNCATE: i64 = 0x0c00;
200
201/// Whether a type is the one this machine has no register for.
202///
203/// Only the eighty bit float is, and that is a fact about x86-64 rather than about floats: every
204/// other scalar the front end produces is in a general purpose register or a vector one, and this
205/// one is on the x87 stack while it is being worked on and in memory the rest of the time. So it
206/// has no place in [`Lowering::class_of`] and no name in [`crate::term`], and every instruction
207/// that touches one is written out by hand in this file.
208fn on_x87(ty: Type) -> bool {
209    ty.is_scalar() && ty.is_float() && ty.bits() == 80
210}
211
212/// Where one operand of an assembly statement is, on each side of the assembly.
213///
214/// Two registers rather than one, because an operand written `+` is a value that arrives and a
215/// value that leaves and those are two values. The machine IR has one definition per register by
216/// construction, so an instruction of the template that reads the operand and writes it has to name
217/// a different register in each place, and what makes the two one register in the end is the
218/// [`Constraint::Reuse`] the instruction's description carries: the allocator reads it, gives both
219/// the same physical register, and copies the incoming value somewhere first when something else is
220/// still using it.
221///
222/// Most operands have one of the two. An input has only a place it is read from and an output
223/// written `=` has only a place it is written to, and asking either of them for the other is an
224/// operand read where the opcode writes or written where it reads, which [`Lowering::placed`]
225/// refuses.
226#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
227struct Place {
228    /// The register the value arrives in, for an operand something reads.
229    read: Option<mir::Reg>,
230    /// The register the value leaves in, for an operand something writes.
231    write: Option<mir::Reg>,
232}
233
234/// Whether that operand of the statement is one the assembly may read, and so where a read of it
235/// gets its value from.
236///
237/// [`bound`] asks this question of an operand a constraint letter named and this asks it of one the
238/// template numbered, which is the same question twice because a two-address instruction reaches
239/// its first source both ways. `mulq %3` reaches `rax` by the letter on the output and libgmp says
240/// what is in it with `"%0"` on an input. `addq %5,%q1` reaches its first source by numbering the
241/// output, and libgmp says what is in it with `"0"` on an input in the same way.
242///
243/// So an output written `=` has no value of its own and is still readable when an input is tied to
244/// it, and the value the read wants is that input's. An output written `+` carries its own value
245/// and answers with that. An output nothing is tied to answers `None`, which is a program that told
246/// the compiler the assembly only writes the operand while the instruction reads it before it
247/// writes it, and is refused where it is asked.
248fn read_as(list: &[AsmOperand<'_>], index: usize) -> Option<Value> {
249    let operand = list.get(index)?;
250    if operand.value.is_some() {
251        return operand.value;
252    }
253    operand.result?;
254    list.iter().find(|entry| entry.tied == Some(index)).and_then(|entry| entry.value)
255}
256
257/// Which of an assembly statement's operands is in that register, for an instruction that reaches
258/// the register without its text saying so.
259///
260/// The constraint is what says so, and it is the only thing in such a statement that could:
261/// `"=a"` is an output in `rax`, `"c"` is an input in `rcx`, an operand that is a local register
262/// variable is in the register its declaration named, and a register nothing names is a register
263/// nobody has said anything about. So a write looks among the outputs and a read among the inputs,
264/// and an output written `+` answers for either, since it is read before it is written. See
265/// [`pinned`], which is the one question asked of both ways of saying it.
266///
267/// The other way a read of such a register is said is a matching constraint. `"=a"` on an output
268/// and `"0"` on an input is the program saying that one register holds the input on the way in and
269/// the output on the way out, and it is how a statement fills a register the instruction reads and
270/// writes without writing the register down twice. The letter is on the output, which has no value
271/// to read, and the value is on the input, which has no letter, and the answer is the output: its
272/// place is read out of the register the input arrived in, and in a template with a loop in it the
273/// place moves on to wherever the last write left it, which is what a read on the next time round
274/// wants. tcc steps a pointer along a string with `lodsb` and `"=&S"` tied to `"0"`, and a read of
275/// the input would start the string again every time round.
276///
277/// And a read of a register an output alone is in is a read of that output, the same as a read of
278/// an output the template numbered. tcc copies a string with `lodsb` and `stosb` and `"=&a"` on an
279/// output nothing is tied to, and what `stosb` stores is what `lodsb` loaded one line up, which is
280/// the output as the template left it rather than anything the statement handed in.
281///
282/// `None` is a register the instruction uses and the statement put nothing in, which is the usual
283/// answer rather than an unusual one. `cpuid` writes four registers and a program that wanted one
284/// of them names one. See [`Lowering::spare`], which is where that one goes.
285fn bound(list: &[AsmOperand<'_>], reg: PhysReg, role: Role) -> Option<usize> {
286    let output =
287        list.iter().position(|operand| operand.result.is_some() && pinned(operand) == Some(reg));
288    if role.is_def() {
289        return output;
290    }
291    // The output first when something is in it on the way in, which is what `+` and a matching
292    // constraint both say, since its place is where a write earlier in the template left it and
293    // the read wants that. See [`read_as`] for what it holds before anything wrote it.
294    let arrives = |at: usize| read_as(list, at).is_some();
295    if let Some(at) = output.filter(|&at| arrives(at)) {
296        return Some(at);
297    }
298    let named = list.iter().position(|operand| {
299        operand.result.is_none() && operand.value.is_some() && pinned(operand) == Some(reg)
300    });
301    named.or(output)
302}
303
304/// The register one of an assembly statement's operands is in, whichever of the two ways said it.
305///
306/// A constraint letter is one way and is the only way a program can say one of the six registers
307/// that have a letter. A local register variable is the other, and it is the only way to say any
308/// of the rest: there is no letter for `r12`, which is the whole reason the extension exists, so
309/// the declaration says it and the front end wrote the name into the constraint. The name is read
310/// against this machine's table here, the same place the letter is read against it, and a name the
311/// machine has not got answers nothing, which leaves the operand where an operand nobody placed
312/// goes.
313///
314/// The sigil gcc allows in front of a name is taken off here, because what a name is written with
315/// is syntax and which register it means is this question.
316fn pinned(operand: &AsmOperand<'_>) -> Option<PhysReg> {
317    match operand.named {
318        Some(name) => {
319            let (reg, _) = x86_64::gpr_named(name.strip_prefix('%').unwrap_or(name))?;
320            Some(reg)
321        }
322        None => operand.fixed.and_then(x86_64::gpr_letter),
323    }
324}
325
326/// Whether a constraint says nothing but what it says on every machine.
327///
328/// [`AsmOperands::read`] gives the x86 meaning to every letter it knows, and most of the letters
329/// mean something else on AArch64: `Q` is an address in one register there rather than one of four
330/// registers, and `a` to `d` name nothing. So an AArch64 statement is taken only with the letters
331/// the two agree on, which are a register, a constant, memory, the immediate ranges and a matching
332/// number, and anything else is refused rather than read as x86. `w` and `Q` are the exceptions.
333/// `w` is a register on both, and which file it is in is decided by the caller with
334/// [`vector_letter`]. `Q` is read as `m` by the caller before the list is read. A
335/// register the front end named in braces is read against AArch64's own names, so what is inside
336/// them is not a letter.
337fn shared_letters(constraint: &str) -> bool {
338    let mut inside = false;
339    constraint.chars().all(|c| match c {
340        '{' => {
341            inside = true;
342            true
343        }
344        '}' => {
345            inside = false;
346            true
347        }
348        _ if inside => true,
349        _ => matches!(
350            c,
351            '=' | '+' | '&' | '%' | 'r' | 'w' | 'Q' | 'm' | 'o' | 'V' | 'g' | 'X' | 'i' | 'n'
352                | 'p' | 'I'..='N' | '0'..='9'
353        ),
354    })
355}
356
357/// A constraint list with every letter outside braces put through `swap`, and what is inside them,
358/// which is a register's name rather than letters, left alone.
359fn letters_outside(constraints: &str, swap: impl Fn(char) -> char) -> String {
360    let mut inside = false;
361    constraints
362        .chars()
363        .map(|c| {
364            match c {
365                '{' => inside = true,
366                '}' => inside = false,
367                _ if !inside => return swap(c),
368                _ => {}
369            }
370            c
371        })
372        .collect()
373}
374
375/// Whether an AArch64 constraint asks for a floating point or vector register, which is what `w`
376/// means there. A register named in braces is not a letter, so a `w` inside one is not read.
377fn vector_letter(constraint: &str) -> bool {
378    let mut inside = false;
379    constraint.chars().any(|c| {
380        match c {
381            '{' => inside = true,
382            '}' => inside = false,
383            _ => {}
384        }
385        !inside && c == 'w'
386    })
387}
388
389/// The x86-64 vector register one entry of a clobber list names, spelled `xmm0` or `ymm0` with or
390/// without the sigil, or nothing for any other entry. Only the sixteen there are without AVX-512,
391/// so `zmm0` and `xmm16` are still refused as names this has no register for.
392fn vector_named(entry: &str) -> Option<PhysReg> {
393    let entry = entry.trim().trim_matches('"');
394    let entry = entry.strip_prefix('%').unwrap_or(entry);
395    let number = entry.strip_prefix("xmm").or_else(|| entry.strip_prefix("ymm"))?;
396    if number.len() > 1 && number.starts_with('0') {
397        return None;
398    }
399    let number: u8 = number.parse().ok()?;
400    (number < 16).then(|| x86_64::xmm(number))
401}
402
403/// Whether a line of a template names, by number, an operand `wanted` says yes to.
404///
405/// `%%` is a percent sign rather than an operand, and a modifier letter may stand between the sign
406/// and the number.
407fn names_one(line: &str, wanted: impl Fn(usize) -> bool) -> bool {
408    let mut rest = line;
409    while let Some(at) = rest.find('%') {
410        let after = &rest[at + 1..];
411        if let Some(escaped) = after.strip_prefix('%') {
412            rest = escaped;
413            continue;
414        }
415        let after = after.strip_prefix(|c: char| c.is_ascii_alphabetic()).unwrap_or(after);
416        let digits = after.len() - after.trim_start_matches(|c: char| c.is_ascii_digit()).len();
417        if after[..digits].parse().is_ok_and(&wanted) {
418            return true;
419        }
420        rest = &after[digits..];
421    }
422    false
423}
424
425/// Why a function could not be lowered.
426///
427/// One reason and then nothing. A function with no rule for something in it is a function this
428/// cannot finish, and the second thing it could not lower is not news.
429#[derive(Debug, Clone, PartialEq, Eq)]
430pub enum Unsupported {
431    /// An instruction no rule fires on.
432    Inst {
433        /// The instruction that stopped it.
434        inst: Inst,
435        /// What the rule file would call it, or nothing if the rule language has no name for it
436        /// at all, which is what an instruction at a width nothing is written about looks like.
437        term: Option<&'static str>,
438        /// The opcode, which is what gets named when the rule language has no word for it.
439        ///
440        /// An opcode the rule language has no word for is exactly the opcode no rule lowers, so
441        /// without this the message would be empty in every case where somebody needs it.
442        opcode: Opcode,
443        /// What it produces, or nothing for an instruction that is only an effect.
444        ty: Option<Type>,
445    },
446    /// A parameter that does not arrive somewhere this can bring it in from.
447    ///
448    /// Not an instruction, which is why it is a separate arm: it is a fact about the signature
449    /// and there is nothing in the body of the function to point at.
450    Argument {
451        /// Its position in the signature.
452        index: usize,
453        /// What is wrong with where it arrives.
454        missing: Missing,
455    },
456    /// A call that passes or gives back a value this cannot put where the convention wants it.
457    Call {
458        /// The call.
459        inst: Inst,
460        /// Which value, and what is wrong with where it travels.
461        refused: Refused,
462    },
463    /// A `return` this cannot put where the convention wants it.
464    ///
465    /// A separate arm from [`Unsupported::Inst`] because it is not an instruction no rule fires
466    /// on. A return of more than one value is built from the convention rather than matched, the
467    /// same way a call is, so what goes wrong with one is what goes wrong with a call and not the
468    /// absence of a rule.
469    Returned {
470        /// The `return`.
471        inst: Inst,
472        /// What is wrong with where one of the values travels.
473        missing: Missing,
474    },
475    /// A stack slot the frame cannot give the bytes it asked for.
476    ///
477    /// Not an instruction no rule covers. An `alloca` is built here rather than matched, so what
478    /// goes wrong with one is what the frame can and cannot hold rather than what the rules spell.
479    Dynamic {
480        /// The `alloca`.
481        inst: Inst,
482        /// What the frame could not do about it.
483        growing: Growing,
484    },
485    /// More parameters of a type that travels on the x87 stack than the stack is deep.
486    ///
487    /// Not an instruction either, for the reason a function's parameter is not one: it is a fact
488    /// about the block and there is nothing in the block to point at. What crosses an edge for one
489    /// of these is the address of where the value is, and the block copies the bytes into a slot
490    /// of its own, all of them through the stack at once so that a block carrying two of them
491    /// swapped is copied in an order that is right. Eight is as many as the stack holds, and a
492    /// ninth would have to be copied before or after the rest, which is the order that could be
493    /// wrong.
494    Phi {
495        /// Which block it arrives at.
496        block: Block,
497        /// How many of them arrive there, which is the whole of what is wrong.
498        count: usize,
499        /// What they are.
500        ty: Type,
501    },
502    /// An `asm` statement this cannot build.
503    ///
504    /// Not an instruction no rule fires on, for the reason a call is not one: what it stands for is
505    /// whatever its template says, and no pattern over terms can read a string.
506    Assembly {
507        /// The `inline_asm`.
508        inst: Inst,
509        /// What about it is not built here yet.
510        refused: Written,
511    },
512    /// A `register long x asm ("...")` naming something this machine has not got.
513    ///
514    /// Not an instruction no rule fires on. There is a rule's worth of instruction here and what
515    /// is wrong is the string beside it, which is a name rather than a term, so the message says
516    /// the name. Which names a machine has is the machine's own question and this is where it is
517    /// asked, at the table a clobber list is read against.
518    Register {
519        /// The `register_value`.
520        inst: Inst,
521        /// The name the program wrote, as it wrote it.
522        name: String,
523    },
524    /// A naked function whose frame is not empty.
525    ///
526    /// Not an instruction no rule fires on, and there is nothing in the body to point at: the
527    /// function asked for no prologue and then wanted bytes only a prologue takes. Refused rather
528    /// than given the bytes anyway, because an offset into a frame nothing set up reaches into
529    /// whatever the caller left below its own stack pointer, which is wrong code that assembles.
530    /// See [`crate::frame::Layout::naked`].
531    Naked {
532        /// How many bytes it wanted, which is the whole of what is wrong.
533        bytes: u32,
534    },
535    /// Something the x86-64 lowering writes by hand and nothing has written for this machine yet.
536    ///
537    /// Refused rather than written with the x86 instructions, which is what the walk would do
538    /// otherwise, since these are the places it names them itself.
539    Unported {
540        /// The instruction, or nothing for the one that is about a signature.
541        inst: Option<Inst>,
542        /// Which of them.
543        what: Unported,
544    },
545}
546
547/// What [`Unsupported::Unported`] is about.
548#[derive(Debug, Clone, Copy, PartialEq, Eq)]
549pub enum Unported {
550    /// The thread pointer on Apple's platforms, which keep it somewhere other than Linux does.
551    Thread,
552}
553
554impl Unported {
555    /// The whole message, since there is nothing to put in front of it.
556    #[must_use]
557    pub fn why(self) -> &'static str {
558        match self {
559            Unported::Thread => "the thread pointer is not written for this platform yet",
560        }
561    }
562}
563
564/// What about an `asm` statement is not built yet.
565#[derive(Debug, Clone, Copy, PartialEq, Eq)]
566pub enum Written {
567    /// A template with instructions in it.
568    Template,
569    /// An `asm goto`, whose labels make the statement a terminator.
570    Goto,
571    /// An operand this cannot put where the constraint says it goes.
572    Operand,
573    /// A clobber list naming something this has no register for.
574    Clobber,
575    /// A `jmp` out of the function in a function that has an epilogue behind it.
576    Away,
577}
578
579impl Written {
580    /// The rest of the sentence that starts with the statement.
581    #[must_use]
582    pub fn why(self) -> &'static str {
583        match self {
584            // The template is the assembler's to read and there is no assembler here yet, so a
585            // template with anything in it is a string nothing can turn into bytes. An empty one is
586            // no instructions, and no instructions is something this can write.
587            Written::Template => "has instructions in its template, which nothing here assembles",
588            Written::Goto => "jumps to a label, which nothing here builds an edge for",
589            Written::Operand => "has an operand this cannot place",
590            Written::Clobber => "says it destroys a register this has no name for",
591            Written::Away => {
592                "jumps out of the function, which only a function that is `naked` may do, since \
593                 anywhere else there is an epilogue behind it to give the frame back"
594            }
595        }
596    }
597}
598
599/// What the frame could not do about a stack slot.
600#[derive(Debug, Clone, Copy, PartialEq, Eq)]
601pub enum Growing {
602    /// An object of a size the number a frame counts bytes in does not reach.
603    Huge,
604    /// A variable length array wanting more alignment than a call leaves the stack pointer with.
605    ///
606    /// Rounding the stack pointer down again after the bytes have been taken would put it
607    /// somewhere no constant reaches the rest of the frame from, so a frame like this needs a
608    /// second base register held for the whole of the function. Nothing here holds one.
609    ///
610    /// [`crate::expand::rounds`] takes the array away before this sees it, by asking for the
611    /// alignment in extra bytes and handing out an address inside them, so what is left of this
612    /// is IR that arrived without going through that pass and the fixed local in
613    /// [`crate::pipeline`] that wants the same thing from the other side.
614    Aligned,
615    /// A variable length array in a function written without a prologue.
616    ///
617    /// A frame that grows is reached from a frame pointer, and establishing one is the first two
618    /// instructions of a prologue that `__attribute__((naked))` asked there be none of. See
619    /// [`crate::frame::Layout::naked`].
620    Naked,
621}
622
623impl Growing {
624    /// The rest of the sentence that starts with the slot.
625    #[must_use]
626    pub fn why(self) -> &'static str {
627        match self {
628            Growing::Huge => "is more bytes than a frame counts",
629            Growing::Aligned => {
630                "wants more alignment than the stack pointer is left on, which needs a base \
631                 register nothing here keeps"
632            }
633            Growing::Naked => {
634                "is in a function that is `naked`, which has no prologue to point a frame pointer \
635                 at it with"
636            }
637        }
638    }
639}
640
641impl Unsupported {
642    /// The instruction it is about, or nothing for the one arm that is about a signature.
643    ///
644    /// What a caller wants this for is the span. The function knows where every instruction in
645    /// it came from, so a caller holding both can point a message at the line somebody wrote
646    /// rather than at the file as a whole, and nothing here has to carry a span of its own.
647    pub fn inst(&self) -> Option<Inst> {
648        match *self {
649            Unsupported::Inst { inst, .. }
650            | Unsupported::Call { inst, .. }
651            | Unsupported::Returned { inst, .. }
652            | Unsupported::Dynamic { inst, .. }
653            | Unsupported::Assembly { inst, .. }
654            | Unsupported::Register { inst, .. } => Some(inst),
655            Unsupported::Unported { inst, .. } => inst,
656            Unsupported::Argument { .. } | Unsupported::Phi { .. } | Unsupported::Naked { .. } => {
657                None
658            }
659        }
660    }
661}
662
663impl fmt::Display for Unsupported {
664    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
665        match *self {
666            Unsupported::Inst { term: Some(term), .. } => write!(f, "no rule lowers `{term}`"),
667            Unsupported::Inst { term: None, opcode, ty: Some(ty), .. } => {
668                write!(f, "no rule lowers a `{opcode}` producing a `{ty}`")
669            }
670            Unsupported::Inst { term: None, opcode, ty: None, .. } => {
671                write!(f, "no rule lowers a `{opcode}`")
672            }
673            Unsupported::Argument { index, missing } => {
674                write!(f, "parameter {index} {}", missing.why())
675            }
676            Unsupported::Call { refused: Refused { argument: Some(index), missing }, .. } => {
677                write!(f, "argument {index} of this call {}", missing.why())
678            }
679            Unsupported::Call { refused: Refused { argument: None, missing }, .. } => {
680                write!(f, "what this call gives back {}", missing.why())
681            }
682            Unsupported::Returned { missing, .. } => {
683                write!(f, "what this function gives back {}", missing.why())
684            }
685            Unsupported::Dynamic { growing, .. } => {
686                write!(f, "this local {}", growing.why())
687            }
688            Unsupported::Phi { block, count, ty } => {
689                let block = block.index();
690                write!(
691                    f,
692                    "block{block} takes {count} parameters of type `{ty}` and only {X87_DEPTH} can cross an edge at once"
693                )
694            }
695            Unsupported::Assembly { refused, .. } => write!(f, "this `asm` {}", refused.why()),
696            Unsupported::Unported { what, .. } => f.write_str(what.why()),
697            Unsupported::Register { ref name, .. } => {
698                write!(
699                    f,
700                    "this object is kept in `{name}`, which is not a register this machine has"
701                )
702            }
703            Unsupported::Naked { bytes } => write!(
704                f,
705                "this function is `naked` and wants {bytes} bytes of frame, which there is no prologue to take"
706            ),
707        }
708    }
709}
710
711impl std::error::Error for Unsupported {}
712
713/// A lowered function, and what the frame needs that the machine IR does not hold.
714#[derive(Debug)]
715pub struct Lowered {
716    /// The function, in machine instructions.
717    pub func: mir::Func,
718    /// What it wants its stack to look like, which is separate from the function so that the two
719    /// can be read and written at the same time.
720    pub stack: Stack,
721    /// Which rules of the table lowered it, which is what `-Zrule-coverage` asks for and what
722    /// `crate::coverage` writes down.
723    pub fired: Fired,
724    /// Which machine IR block each IR block became, indexed by the IR block's own index, and
725    /// nothing for a block the walk never reached.
726    ///
727    /// Here because it is the only place the correspondence exists. Selection makes one block per
728    /// block, in the same order and with the arms in the same order, so anything the IR knows
729    /// about a block can be carried down through this and nothing else, and
730    /// [`crate::weights::carry`] is what does.
731    pub blocks: Vec<Option<mir::Block>>,
732}
733
734/// What a function's stack has to hold, as far as selection is able to say.
735///
736/// All of it is answered here because selection is where a call is built and where an `alloca`
737/// is read, and nothing after it could tell what either of them needed.
738#[derive(Debug, Default)]
739pub struct Stack {
740    /// How many bytes the widest call in the function needs below the stack pointer for the
741    /// arguments it passes there, or `None` for a function that makes no call at all.
742    ///
743    /// `None` is a leaf, which is the function that may use the red zone and the one whose stack
744    /// pointer does not have to be left aligned for anybody.
745    pub calls: Option<u32>,
746    /// The memory the function asked for itself, one entry for every `alloca` in it, in the order
747    /// the walk reached them.
748    pub locals: Vec<Local>,
749    /// Which instruction computes the address of which of those locals.
750    ///
751    /// An address in the frame is a distance from the stack pointer, and there is no frame until
752    /// after allocation, so the instruction is written here with nothing in its displacement and
753    /// [`crate::finish`] writes the number in once [`crate::frame::Frame`] knows it.
754    pub addresses: Vec<(mir::Inst, usize)>,
755    /// Which of those locals is which declaration in the source, for the ones the program declared.
756    ///
757    /// The number is the one the IR function carries and means nothing here. What it is for is the
758    /// debugging information, which has to say where a named local ended up and cannot ask the
759    /// frame directly: the frame knows a local by the order the `alloca` for it was lowered in and
760    /// by nothing else.
761    ///
762    /// Shorter than the list above rather than the same length, because most of what a function
763    /// keeps in its frame is memory an expression wanted somewhere to put.
764    pub declared: Vec<(usize, u32)>,
765    /// Which instruction computes the address of a piece of memory whose size the function works
766    /// out while it runs, which is what a variable length array is.
767    ///
768    /// Waiting on [`crate::finish`] for a different number from the one the addresses above are:
769    /// the bytes were taken off the stack pointer by the instruction in front of this one, so where
770    /// they start is however much of the bottom of the frame belongs to the arguments of a call,
771    /// and that is not known until the frame is.
772    pub dynamic: Vec<mir::Inst>,
773    /// Which instruction takes those bytes off the stack pointer, one for every one of them, in the
774    /// order the walk reached them.
775    ///
776    /// Read by [`crate::finish`] on a command line that asked for the stack to be touched a page at
777    /// a time, which is the one thing that has to find these again: the bytes are in a register by
778    /// then, so the walk down to them is a loop, and a loop is written around an instruction rather
779    /// than in front of a block. Nothing else looks at them, because everything else about a frame
780    /// that grows is answered by the address the instruction below this one computes.
781    pub grown: Vec<mir::Inst>,
782    /// Where the function first moves the stack pointer while it runs, if it does at all.
783    ///
784    /// Two things are read off this. One is whether at all, which is what [`crate::frame::Layout`]
785    /// wants, because a frame that moves its stack pointer has a different shape from one that does
786    /// not and the layout is built before the instructions are looked at again. See `Growing` in
787    /// [`crate::frame`]. The other is where, so that a caller that cannot accept such a frame has
788    /// somewhere to point when it says so.
789    pub grown_at: Option<Inst>,
790    /// Which instruction reads which of the arguments the caller passed on the stack, as how far up
791    /// the caller's argument area it reads.
792    ///
793    /// Waiting on [`crate::finish`] for the same reason the addresses above are, and on one thing
794    /// more: where the caller's argument area is from inside this function depends on whether the
795    /// prologue had to force the stack pointer's alignment, so which register the load reads
796    /// through is not settled here either.
797    pub arguments: Vec<(mir::Inst, u32)>,
798    /// Whether the function asked where its own frame is, which is what `__builtin_frame_address`
799    /// and `__builtin_return_address` both start from.
800    ///
801    /// A function like that keeps a frame pointer whatever the flags say, because the register is
802    /// the answer to the first of them and the start of the walk for every depth above zero. There
803    /// is no other way to reach it: the distance from the stack pointer to the frame is a number
804    /// the layout works out, and what a walk up the chain needs is the link the prologue saved.
805    pub walks_frames: bool,
806    /// Whether the function saved a place for a `__builtin_longjmp` to come back to, which is what
807    /// `__builtin_setjmp` does.
808    ///
809    /// A function like that keeps a frame pointer whatever the flags say as well, and for a reason
810    /// of the same shape: the two registers the restore puts back are the frame pointer and the
811    /// stack pointer, and a frame that did not keep the first of them has nothing in it saying
812    /// where the caller's frame is for the epilogue to find after control has come back.
813    pub saves_place: bool,
814    /// The calls a `tail_call` became that [`crate::tail::jumps`] may turn into a jump, which is
815    /// the ones that passed everything in registers.
816    pub tails: Vec<crate::tail::Tail>,
817}
818
819impl Stack {
820    /// The layout given, with the three fields only the lowering knows the answer to filled in.
821    ///
822    /// Everything else in a layout comes from the flags the function is compiled under or from the
823    /// allocation, so this takes one and returns it rather than building one.
824    ///
825    /// A function that saved a place is not a leaf whatever it called. What a leaf buys is the red
826    /// zone, which is the words below the stack pointer nothing else may write, and a function
827    /// control comes back into from a `__builtin_longjmp` has already had something else running
828    /// down there: whatever it called and whatever that called, or a signal handler on the same
829    /// stack. Every one of those has written over the red zone by the time control arrives, so a
830    /// value this function left there would not be there any more.
831    #[must_use]
832    pub fn layout<'a>(&'a self, base: Layout<'a>) -> Layout<'a> {
833        Layout {
834            leaf: self.calls.is_none() && !self.saves_place,
835            outgoing: self.calls.unwrap_or(0),
836            locals: &self.locals,
837            grows: self.grown_at.is_some(),
838            ..base
839        }
840    }
841}
842
843/// The machine IR for that function, for the machine the selector describes.
844///
845/// # Errors
846///
847/// The first instruction no rule fires on, which today is anything at a width the rule set is not
848/// written at, a parameter that does not arrive in a register this can read, or a call that
849/// passes something this cannot put where the convention wants it.
850pub fn func(
851    source: &Func,
852    names: &mut Interner,
853    selector: &'static Selector,
854    conv: &'static CallRegs,
855    elsewhere: &Elsewhere,
856) -> Result<Lowered, Unsupported> {
857    func_for(source, names, selector, conv, elsewhere, true)
858}
859
860/// [`func`], for a build that says whether it writes debugging information. Without it the walk
861/// leaves out which value each declaration holds on the way into each block, since that is read
862/// only for the debugging information.
863///
864/// # Errors
865///
866/// The same as [`func`].
867pub fn func_for(
868    source: &Func,
869    names: &mut Interner,
870    selector: &'static Selector,
871    conv: &'static CallRegs,
872    elsewhere: &Elsewhere,
873    debug: bool,
874) -> Result<Lowered, Unsupported> {
875    Lowering::new(source, names, selector, conv, elsewhere, debug).run()
876}
877
878/// What the matcher settled on for one block, indexed the way the block's instructions are.
879struct Decided {
880    /// What each instruction matched, and nothing for one that matched no rule or was folded
881    /// into a later one.
882    found: Vec<Option<Match<Term>>>,
883    /// How each instruction showed its operands to the matcher, which is what says what it took.
884    plans: Vec<Option<Plan>>,
885    /// The instructions some other instruction took, which are the ones with nothing to write.
886    folded: Vec<Inst>,
887}
888
889/// The instruction in front of an assignment that starts a declaration on a value, and the first
890/// machine instruction after it once the block is filled.
891type Mark = (Option<Inst>, Option<mir::Inst>);
892
893/// One function being lowered.
894struct Lowering<'a> {
895    source: &'a Func,
896    names: &'a mut Interner,
897    out: mir::Func,
898    /// The machine register each IR value is in, once it has one.
899    regs: Vec<Option<mir::Reg>>,
900    /// For a constant that has been written into a register, the block it was written into,
901    /// which is the only block that register is any good in.
902    written: Vec<Option<mir::Block>>,
903    /// How many times each IR value is read, which is what says whether an instruction may be
904    /// folded into the one that reads it.
905    uses: Vec<u32>,
906    /// The block being filled.
907    at: Option<mir::Block>,
908    /// The machine IR block each IR block became.
909    blocks: Vec<Option<mir::Block>>,
910    /// The class an address is in, which is the general purpose one and is not a question: every
911    /// register an addressing mode names holds part of an address, and there is no machine here
912    /// that computes an address anywhere but in this file. Which class a *value* is in is
913    /// [`Lowering::class_of`], and it is a question, because a float is in the other one.
914    gpr: RegClass,
915    /// The machine this selects for.
916    selector: &'static Selector,
917    /// Where the convention this function is compiled for puts things, which is read for the
918    /// arguments and for the calls.
919    conv: &'static CallRegs,
920    /// Which names this function may not work an address out for itself, which is a fact about the
921    /// module and so is worked out before any of this and handed in.
922    elsewhere: &'a Elsewhere,
923    /// Whether the build writes debugging information, which is the one thing that reads which
924    /// value a declaration holds on the way into each block.
925    debug: bool,
926    /// What the function wants its stack to look like, filled in as the walk finds out.
927    stack: Stack,
928    /// What a `va_start` in this function has to write, or nothing for a function that takes no
929    /// arguments its signature does not name.
930    ///
931    /// Worked out once, when the entry block binds the parameters, because every number in it is
932    /// about where those parameters left the walk over the argument registers and there is nowhere
933    /// else that knows.
934    varargs: Option<Varargs>,
935    /// Which of the function's stack objects each eighty bit value lives in, once it has asked
936    /// for one.
937    ///
938    /// One slot per value and it is never given back, which is what makes an eighty bit value
939    /// behave like every other one: it is written once and read wherever it is read, and no two
940    /// of them share a slot the way two of them would share a register. What is in a register is
941    /// the address, and that is worked out again at every use rather than kept, so nothing here
942    /// holds a general purpose register open across a whole function.
943    slots: Vec<Option<usize>>,
944    /// The eight bytes a value passes through between a register and the x87 stack, once
945    /// something has wanted them.
946    ///
947    /// One for the whole function, because every group that uses it is a handful of instructions
948    /// with nothing in between: the bytes are written, read straight back and never looked at
949    /// again, so a second slot would be a second slot holding the same nothing.
950    crossing: Option<usize>,
951    /// The four bytes the control word is saved in and the changed copy written to, once
952    /// something has wanted them.
953    ///
954    /// One for the whole function for the reason above, and four rather than two because it is
955    /// two words: the one the unit had and the one with the rounding field turned to truncate.
956    control: Option<usize>,
957    /// The word a `__builtin_setjmp` in this function answers with, once one has asked for it.
958    ///
959    /// One for the whole function however many saves there are in it, because the word is written
960    /// and read back with nothing in between: the save writes a zero into it and the instruction
961    /// straight after reads it, and the only other thing that ever writes it is a restore arriving
962    /// between those two. Two saves sharing it is two pairs each doing that, and neither can be
963    /// inside the other.
964    answer: Option<usize>,
965    /// The block `__builtin_apply_args` answers the address of, or nothing in a function that holds
966    /// none.
967    ///
968    /// Written once, in the prologue, because what it holds is every argument register as it was
969    /// on the way in, and by the time the walk reaches the call the registers hold whatever the
970    /// function has done since. Every `__builtin_apply_args` in the function answers the same one.
971    applied: Option<usize>,
972    /// Which rules have fired so far.
973    fired: Fired,
974    /// Where each assignment that starts a declaration on a value part of the way through is, by
975    /// the IR block it is in and the instruction in front of it, and which machine instruction
976    /// is the first one after it once the block has been filled. See
977    /// [`rucc_ir::Func::declare_value_from`].
978    marks: HashMap<Block, Vec<Mark>>,
979    /// The frame slot each fixed size `alloca` was given, which a landing pad writes the address
980    /// of again rather than reading the register the rest of the function has it in. See
981    /// [`Self::pad`].
982    frame_slots: HashMap<Value, usize>,
983    /// The machine call each IR call with an unwind edge became, which [`Self::edges`] pairs with
984    /// the pad the edge went to. See [`rucc_ir::Opcode::Unwound`].
985    unwinding: HashMap<Inst, mir::Inst>,
986}
987
988/// What a `va_start` in a variadic function writes into the list it is given.
989///
990/// Two shapes, because two conventions describe a list two ways, and [`crate::varargs`] is where
991/// both are written down. Neither is a set of numbers on its own: where the save area is and where
992/// the caller's argument area is are distances into a frame that does not exist until after
993/// allocation, so each is a `lea` [`crate::finish`] fills in.
994#[derive(Debug, Clone, Copy, PartialEq, Eq)]
995enum Varargs {
996    /// The four field list, whose two offsets are settled here and whose two addresses are not.
997    Fields {
998        /// Which of the function's stack objects is the register save area.
999        save: usize,
1000        /// How far up the caller's argument area the first argument the signature does not name is,
1001        /// which is the whole of that area the named ones did not take.
1002        incoming: u32,
1003        /// What `gp_offset` starts at, which is past the general purpose registers the named
1004        /// arguments took.
1005        integers: u32,
1006        /// What `fp_offset` starts at, which is past the vector ones.
1007        floats: u32,
1008    },
1009    /// The AAPCS64 list, whose two offsets count up to zero from the top of each half of the save
1010    /// area. The two tops are addresses in the frame and so is the first field, like the SysV list.
1011    Aapcs {
1012        /// Which of the function's stack objects is the register save area.
1013        save: usize,
1014        /// How far up the caller's argument area the first argument the signature does not name is.
1015        incoming: u32,
1016        /// Where the general purpose half of the save area ends.
1017        integers_end: u32,
1018        /// Where the vector half ends, which is the end of the area.
1019        floats_end: u32,
1020        /// What `__gr_offs` starts at, which is minus the general purpose half the named arguments
1021        /// did not take.
1022        integers: i32,
1023        /// What `__vr_offs` starts at.
1024        floats: i32,
1025    },
1026    /// The list that is a pointer, which is the one address and nothing else.
1027    Pointer {
1028        /// How far up the caller's argument area the first argument the signature does not name is,
1029        /// which on this convention is the word belonging to the position the named ones stopped
1030        /// at.
1031        incoming: u32,
1032    },
1033}
1034
1035/// How far a function's name reaches, narrowed from the linkage the IR gave it.
1036///
1037/// The IR has five and an object file says three, and the two the linker cannot tell apart are
1038/// the two weak ones: which of them a symbol had is a fact the optimizer reads and the linker has
1039/// no way to record. A function is never `Common`, since that is what a tentative definition of an
1040/// object is and there is no tentative definition of a function, and it is written here rather
1041/// than left out so that a linkage added later has to come past this.
1042const fn binding(linkage: Linkage) -> mir::Binding {
1043    match linkage {
1044        Linkage::Internal => mir::Binding::Local,
1045        Linkage::Weak | Linkage::LinkOnce => mir::Binding::Weak,
1046        Linkage::External | Linkage::Common => mir::Binding::Global,
1047    }
1048}
1049
1050/// How far a function's name reaches outside a shared library, carried across unchanged.
1051///
1052/// Nothing is narrowed here the way [`binding`] narrows the linkage, because ELF records all
1053/// three of these and the two enumerations are the same three answers written twice: once in a
1054/// crate that is not allowed to know what an object file is and once in one that is.
1055const fn visibility(visibility: Visibility) -> mir::Visibility {
1056    match visibility {
1057        Visibility::Default => mir::Visibility::Default,
1058        Visibility::Hidden => mir::Visibility::Hidden,
1059        Visibility::Protected => mir::Visibility::Protected,
1060    }
1061}
1062
1063impl<'a> Lowering<'a> {
1064    fn new(
1065        source: &'a Func,
1066        names: &'a mut Interner,
1067        selector: &'static Selector,
1068        conv: &'static CallRegs,
1069        elsewhere: &'a Elsewhere,
1070        debug: bool,
1071    ) -> Self {
1072        let counts = source.counts();
1073        let name = source.name;
1074        let mut uses = vec![0; counts.values];
1075        for block in source.blocks() {
1076            for inst in source.insts(block) {
1077                for &arg in &source[source[inst].args] {
1078                    uses[arg.index()] += 1;
1079                }
1080                for call in source.successors(inst) {
1081                    for &arg in &source[call.args] {
1082                        uses[arg.index()] += 1;
1083                    }
1084                }
1085            }
1086        }
1087        let mut out = mir::Func::new(name);
1088        out.align = source.align;
1089        // Carried rather than worked out here, because where a function was declared is a fact
1090        // about the source and this is a long way past it. What wants it is the line table.
1091        out.declared = source.declared;
1092        out.binding = binding(source.linkage);
1093        out.visibility = visibility(source.visibility);
1094        Self {
1095            source,
1096            names,
1097            out,
1098            regs: vec![None; counts.values],
1099            written: vec![None; counts.values],
1100            blocks: vec![None; counts.blocks],
1101            uses,
1102            at: None,
1103            gpr: selector.gpr,
1104            selector,
1105            conv,
1106            elsewhere,
1107            debug,
1108            stack: Stack::default(),
1109            varargs: None,
1110            slots: vec![None; counts.values],
1111            crossing: None,
1112            control: None,
1113            answer: None,
1114            applied: None,
1115            fired: Fired::new(),
1116            marks: HashMap::new(),
1117            frame_slots: HashMap::new(),
1118            unwinding: HashMap::new(),
1119        }
1120    }
1121
1122    fn run(mut self) -> Result<Lowered, Unsupported> {
1123        for value in self.source.values() {
1124            for start in self.source.value_starts(value) {
1125                let Some((block, after)) = self.source.start_place(start) else { continue };
1126                let marks = self.marks.entry(block).or_default();
1127                if !marks.iter().any(|&(have, _)| have == after) {
1128                    marks.push((after, None));
1129                }
1130            }
1131        }
1132        // Every block before any of them is filled, because a block that jumps forward has to
1133        // name the block it jumps to and a machine IR block is named by a handle rather than by
1134        // the IR block it came from.
1135        for block in self.source.blocks() {
1136            let out = self.out.create_block();
1137            self.blocks[block.index()] = Some(out);
1138        }
1139        for block in self.order() {
1140            self.block(block)?;
1141        }
1142        // And the name each block an image holds the address of was given, which nothing in the
1143        // walk above would ask for: the `lea` a label address is inside the function needs no
1144        // symbol, and the one thing that does is a relocation in another section.
1145        let named: Vec<(Block, Symbol)> = self.source.named_blocks().collect();
1146        let labels: Vec<(mir::Block, Symbol)> =
1147            named.into_iter().map(|(block, name)| (self.out_block(block), name)).collect();
1148        self.out.labels = labels;
1149        self.naming();
1150        Ok(Lowered { func: self.out, stack: self.stack, fired: self.fired, blocks: self.blocks })
1151    }
1152
1153    /// Which register each declaration the front end kept in a value ended up in, as far as this
1154    /// walk can say, which is the other half of what [`Lowering::new_reg`] writes down as it goes.
1155    ///
1156    /// Two halves because there are two ways a value gets a register here. Most of them ask for a
1157    /// fresh one and that is where `new_reg` catches them, and the rest are put in a register
1158    /// something else chose: a parameter arrives in whichever one the convention handed it, a block
1159    /// parameter in whichever one the edge agreed on, and a result of a rule that names its own
1160    /// registers in the one the rule named. None of those goes past the mint, so this is the map at
1161    /// the end read off the other side, and the two together are every value a declaration is
1162    /// behind.
1163    ///
1164    /// The map on its own would not do, which is why `new_reg` writes down what it writes down: the
1165    /// entry for a constant is cleared every time the walk leaves the block that wrote it, so a
1166    /// local a constant holds is in the map for one block of the function and nowhere else.
1167    fn naming(&mut self) {
1168        let mut named = std::mem::take(&mut self.out.named);
1169        for value in self.source.values() {
1170            let Some(reg) = self.regs[value.index()] else { continue };
1171            named.extend(self.source.value_decls(value).map(|decl| (decl, reg)));
1172            // A start in a block a pass took out was never reached above, and it says nothing
1173            // rather than something about another place.
1174            for start in self.source.value_starts(value) {
1175                let Some((block, after)) = self.source.start_place(start) else { continue };
1176                let first = self.marks.get(&block).and_then(|marks| {
1177                    marks.iter().find(|&&(have, _)| have == after).and_then(|&(_, at)| at)
1178                });
1179                if let Some(first) = first {
1180                    self.out.starts.push((start.decl, reg, first));
1181                }
1182            }
1183        }
1184        named.sort_unstable();
1185        named.dedup();
1186        self.out.named = named;
1187        self.out.starts.sort_unstable();
1188        self.out.starts.dedup();
1189        // Which of its values a declaration holds on the way into a block, for the blocks where
1190        // two of them are live at once. A block a pass took out says nothing, and neither does a
1191        // value the map above has lost the register of, since that is not the same as having none.
1192        // Only for a build that writes debugging information, since that is all that reads it,
1193        // and on a function of tens of thousands of blocks it is a walk of all of them for every
1194        // local.
1195        let mut entries = Vec::new();
1196        let held = if self.debug { crate::holding::on_entry(self.source) } else { Vec::new() };
1197        for (decl, block, value) in held {
1198            if let (Some(block), Some(reg)) = (self.blocks[block.index()], self.regs[value.index()])
1199            {
1200                entries.push((decl, block, reg));
1201            }
1202        }
1203        entries.sort_unstable();
1204        entries.dedup();
1205        self.out.entries = entries;
1206    }
1207
1208    /// The order the blocks are filled in, which is not the order they are written in.
1209    ///
1210    /// Reverse postorder, because a value is written in a block that dominates every block that
1211    /// reads it and a block in reverse postorder comes before every block it dominates. The order
1212    /// the blocks are written in does not have that property: a block written early can read a
1213    /// value a block below it writes, and reading a value with no register yet mints one, so the
1214    /// register the definition writes later is not the register the read named. Nothing writes the
1215    /// one the read named, and what comes out is a function that loads a stack slot no store ever
1216    /// reached. It is the order this walk goes in rather than the order the blocks come out in,
1217    /// which is what the loop above fixes, so the machine function is still written the way the IR
1218    /// function was.
1219    ///
1220    /// Blocks the entry does not reach come last, in the order they are written in. Nothing runs
1221    /// them and nothing they name is read by anything that does, but they still have to be filled,
1222    /// because a machine block with no terminator is not one the passes below can read.
1223    fn order(&self) -> Vec<Block> {
1224        let Some(entry) = self.source.entry() else { return self.source.blocks().collect() };
1225        let count = self.blocks.len();
1226        let mut succs: Vec<Vec<Block>> = vec![Vec::new(); count];
1227        for block in self.source.blocks() {
1228            let Some(term) = self.source.terminator(block) else { continue };
1229            succs[block.index()] = self.source.successors(term).map(|call| call.block).collect();
1230        }
1231        // An explicit stack, because the depth of the walk is the number of blocks and a function
1232        // built by a generator has as many of those as it likes.
1233        let mut seen = vec![false; count];
1234        let mut order = Vec::with_capacity(count);
1235        let mut stack = vec![(entry, 0usize)];
1236        seen[entry.index()] = true;
1237        while let Some((block, at)) = stack.pop() {
1238            let Some(&next) = succs[block.index()].get(at) else {
1239                order.push(block);
1240                continue;
1241            };
1242            stack.push((block, at + 1));
1243            if !seen[next.index()] {
1244                seen[next.index()] = true;
1245                stack.push((next, 0));
1246            }
1247        }
1248        order.reverse();
1249        order.extend(self.source.blocks().filter(|block| !seen[block.index()]));
1250        order
1251    }
1252
1253    /// One block: its parameters, then every instruction in it that is not folded into another.
1254    fn block(&mut self, block: Block) -> Result<(), Unsupported> {
1255        let out = self.out_block(block);
1256        self.at = Some(out);
1257        if self.source.entry() == Some(block) {
1258            self.arrive(block, out)?;
1259        } else {
1260            let mut arriving = Vec::new();
1261            for &param in &self.source[block].params {
1262                // A value with no register to arrive in, which the class would not say, since
1263                // `class_of` puts one of these in the general purpose file on purpose and what it
1264                // means by that is that nothing there can hold it. What crosses the edge for one
1265                // of those is the address of where the value already is, so the parameter is a
1266                // pointer here and the bytes it points at are copied below.
1267                let ty = self.source[param].ty;
1268                let reg = self.out.append_param(out, self.class_of(ty));
1269                self.regs[param.index()] = Some(reg);
1270                if on_x87(ty) {
1271                    arriving.push((param, reg));
1272                }
1273            }
1274            self.settle(block, &arriving)?;
1275        }
1276        let kept = self.pad(block)?;
1277
1278        // What each instruction matched, and which instructions were folded into another. The
1279        // decision is made for the whole block before any of it is written, and it is made more
1280        // than once: a value that only some of its readers took has to be put back in a register
1281        // for all of them, and taking it away from those readers changes what they match.
1282        let insts: Vec<Inst> = self.source.insts(block).collect();
1283        let mut refused: HashSet<Value> = HashSet::new();
1284        let mut decided = self.decide(&insts, &refused);
1285        while let Some(value) = self.left_alive(&insts, &decided.plans) {
1286            refused.insert(value);
1287            decided = self.decide(&insts, &refused);
1288        }
1289        let Decided { found, folded, .. } = decided;
1290
1291        // Where each assignment in this block that starts a declaration on a value is, as the
1292        // machine instruction in front of the place its IR instruction left off, or the block
1293        // for one where nothing has been written yet. What comes after it is not known until the
1294        // block is filled, so that is read below.
1295        let wanted: HashSet<Option<Inst>> =
1296            self.marks.get(&block).into_iter().flatten().map(|&(after, _)| after).collect();
1297        let mut reached: Vec<(Option<Inst>, mir::Block, Option<mir::Inst>)> = Vec::new();
1298        for (index, (&inst, matched)) in insts.iter().zip(found).enumerate() {
1299            let before = index.checked_sub(1).map(|index| insts[index]);
1300            if wanted.contains(&before) {
1301                let at = self.at.unwrap_or(out);
1302                reached.push((before, at, self.out.terminator(at)));
1303            }
1304            if folded.contains(&inst) || self.writes_nothing(inst) {
1305                continue;
1306            }
1307            // A call is built from the convention rather than matched, which is why it is the one
1308            // opcode looked at by name here. Through an address it is a different instruction and
1309            // the same convention, so the two arrive at the same place and differ in one line of
1310            // it.
1311            match self.source[inst].opcode {
1312                Opcode::Call | Opcode::CallIndirect => {
1313                    self.called(inst)?;
1314                    continue;
1315                }
1316                // The exception a landing pad was entered with, which the unwinder left in the
1317                // first return register. Built by name for the reason a named register is.
1318                Opcode::Landing => {
1319                    self.landing(inst)?;
1320                    continue;
1321                }
1322                // A call and the return behind it, which is what `crate::tail::mark` made it out
1323                // of, and both are built the way they would have been. What makes it a jump is
1324                // written at the very end, once the epilogue is there to jump from.
1325                Opcode::TailCall => {
1326                    self.tail_called(inst)?;
1327                    continue;
1328                }
1329                // Built from the frame rather than matched, for the same shape of reason a call
1330                // is built from the convention: what a rule replaces a term with is instructions,
1331                // and what an `alloca` needs first is bytes, which the rule language has no way
1332                // to ask for.
1333                Opcode::Alloca => {
1334                    self.reserve(inst)?;
1335                    continue;
1336                }
1337                // Reading the stack pointer and writing it back, which are the two ends of a scope
1338                // holding a variable length array. Built here for the reason an `alloca` is: the
1339                // value is a register the rule language has no way to name, because what it holds
1340                // is not a value the program computed but where the machine's stack had got to.
1341                // The arguments the function was handed, saved in the prologue, and a call made
1342                // out of them. Built here because neither is a value a rule could say anything
1343                // about: the first is a place in the frame and the second is a call, whose
1344                // arguments are a block of registers rather than values.
1345                Opcode::ApplyArgs => {
1346                    self.apply_args(inst)?;
1347                    continue;
1348                }
1349                Opcode::Apply => {
1350                    self.apply(inst)?;
1351                    continue;
1352                }
1353                Opcode::StackSave => {
1354                    self.stack_pointer(inst, false)?;
1355                    continue;
1356                }
1357                Opcode::StackRestore => {
1358                    self.stack_pointer(inst, true)?;
1359                    continue;
1360                }
1361                // The address of a name, built here for the same reason an `alloca` is: what a
1362                // rule replaces a term with is instructions over values, and the operand of this
1363                // one is a symbol, which is a thing the rule language has no way to bind and the
1364                // solver has no way to say anything about. There is nothing in `lea sym(%rip)` a
1365                // proof over bitvectors could discharge, because what makes it the right answer
1366                // is the relocation and what the linker does with it.
1367                Opcode::GlobalAddr => {
1368                    self.address_of(inst)?;
1369                    continue;
1370                }
1371                // The address of a label and the branch that reads one, built here for the same
1372                // reason and for one more. The reason is the same: what the first of them names is
1373                // a block, which is not a value a rule pattern can bind, and there is nothing in
1374                // the distance between two places in one function that a proof over bitvectors
1375                // could discharge. The extra one is that the second is a terminator whose arms are
1376                // not two and not fixed, and a rule says what an instruction reads rather than
1377                // where a block goes.
1378                Opcode::BlockAddr => {
1379                    self.block_address(inst)?;
1380                    continue;
1381                }
1382                Opcode::IndirectBr => {
1383                    self.indirect_branch(inst)?;
1384                    continue;
1385                }
1386                // A `switch` that `crate::switch` found dense enough for a table, which is a load
1387                // out of the table and the same jump. Built here for the reasons the jump above
1388                // is, and because what the load reads is a place in this function.
1389                Opcode::Switch => {
1390                    self.jump_table(inst)?;
1391                    continue;
1392                }
1393                // The pair that saves a place in this function and comes back to it. Built here
1394                // for the reason the address of a label is, and for two more. The reason is the
1395                // same: the first of them writes down where control comes back to, which is a
1396                // place in this function and not a value a rule pattern can bind. The extra ones
1397                // are that each of them is a group of instructions over a buffer the program owns
1398                // rather than one instruction, and that the first of them leaves the block it was
1399                // written in and carries on in a new one, which is a thing no rule can do.
1400                Opcode::SetjmpMarker => {
1401                    self.saves_place(inst)?;
1402                    continue;
1403                }
1404                Opcode::LongjmpMarker => {
1405                    self.comes_back(inst)?;
1406                    continue;
1407                }
1408                // Where this thread's own storage starts, built here for a reason of the same
1409                // shape: what it reads is `%fs`, which is not a register the rule language can
1410                // bind and not one a proof over bitvectors could say anything about, because what
1411                // makes the load the right answer is an agreement between the loader and the C
1412                // library rather than any arithmetic.
1413                Opcode::ThreadPointer => {
1414                    self.thread_pointer(inst)?;
1415                    continue;
1416                }
1417                // What a named machine register holds, built here for the reason above written
1418                // about any register rather than about one: which register it is is a string
1419                // beside the instruction, and a rule matches on an opcode and a type and could
1420                // not see it. There is nothing to prove either, since the answer is the register
1421                // and the instruction is the move that reads it.
1422                Opcode::RegisterValue => {
1423                    self.register_value(inst)?;
1424                    continue;
1425                }
1426                // Where a frame is and what it returns to, built here for the same reason and one
1427                // more. The reason is the same: what the walk starts from is the frame pointer,
1428                // which is not a register a rule pattern can bind, and there is nothing in reading
1429                // the link the prologue saved that a proof over bitvectors could discharge. The
1430                // extra one is that how long the walk is comes out of a number beside the
1431                // instruction, so one of these is not one instruction but however many the depth
1432                // says, and a rule replaces a term with a term.
1433                Opcode::FrameAddress | Opcode::ReturnAddress => {
1434                    self.frames(inst)?;
1435                    continue;
1436                }
1437                // Built from the frame for the reason an `alloca` is, and from the convention for
1438                // the reason a call is: three of the four fields it writes are distances that do
1439                // not exist until the frame does, and the fourth is where the walk over the
1440                // argument registers stopped. A function that is not variadic has no such walk to
1441                // report, so it has nothing here and is refused below, which is the right answer
1442                // for a `va_start` in one.
1443                Opcode::VaStart if self.varargs.is_some() => {
1444                    self.va_start(inst)?;
1445                    continue;
1446                }
1447                // A return of more than one value, which is a structure small enough to come
1448                // back in a pair of registers. Built from the convention for the reason a call
1449                // is: which register each half goes in depends on the halves in front of it,
1450                // because the two register files are walked separately, and a pattern over a term
1451                // cannot see them. A return of one value is a term with a name and a rule, and it
1452                // stays one.
1453                //
1454                // A return of none in a function whose answer went through memory is here too,
1455                // and for a different reason: what it gives back is not written in the IR at all.
1456                // The convention says the address the caller handed over comes back, and only the
1457                // signature says this function was handed one.
1458                //
1459                // And a return of one eighty bit value, for a third reason: what a rule would
1460                // write is an instruction leaving the value in a register, and this one is left on
1461                // the x87 stack instead. A rule could not name that stack any more than any other
1462                // rule about this type could.
1463                //
1464                // And a return the convention asks this side to extend, which a rule has no way to
1465                // know about since the signature is what says so and not the value.
1466                Opcode::Return
1467                    if self.source[self.source[inst].args].len() > 1
1468                        || self.sret().is_some()
1469                        || self.gives_back_x87(inst)
1470                        || self.widens_return() =>
1471                {
1472                    let values = self.source[self.source[inst].args].to_vec();
1473                    self.returned(inst, values)?;
1474                    continue;
1475                }
1476                // A cast between a pointer and an integer of the same width, which on this
1477                // machine is every one the front end writes. No instruction at all, so no rule
1478                // could name one.
1479                Opcode::PtrToInt | Opcode::IntToPtr => {
1480                    self.rename(inst)?;
1481                    continue;
1482                }
1483                // A barrier, which is one instruction or none depending on the ordering. Written
1484                // by name because there is nothing about it a rule could be proved against, the
1485                // way there is nothing to prove about the address of a symbol.
1486                Opcode::Fence => {
1487                    self.barrier(inst)?;
1488                    continue;
1489                }
1490                // An ordered load or store that `crate::expand::orderings` left alone, which on a
1491                // machine that is not total store order is every one stronger than relaxed. Written
1492                // by name for the barrier's reason: what it adds to the plain access is an ordering.
1493                Opcode::AtomicLoad | Opcode::AtomicStore if self.on_aarch64() => {
1494                    self.ordered(inst)?;
1495                    continue;
1496                }
1497                // A hint, written by name for the reason a barrier is and one step further: not
1498                // only is there no equality for a proof to discharge, there is nothing about the
1499                // program around it either. Which of the four instructions it is comes out of the
1500                // number the builtin was given, which is beside the instruction rather than in it.
1501                Opcode::Prefetch => {
1502                    self.hint(inst)?;
1503                    continue;
1504                }
1505                // Stopping, written by name for the first half of the barrier's reason: it
1506                // computes nothing, so there is no term for a rule to replace, and what makes it
1507                // right is what the operating system does with the fault rather than anything a
1508                // proof over bitvectors could discharge.
1509                Opcode::Trap => {
1510                    self.trap(inst);
1511                    continue;
1512                }
1513                // A compare and exchange, which is written by name because it produces two values
1514                // and a rule produces one. The replacement of a rule is one term, a term names the
1515                // value an instruction computes, and there is no way in that language to say that
1516                // an instruction leaves an answer in one place and a yes or no in another.
1517                Opcode::Cmpxchg => {
1518                    self.exchange(inst)?;
1519                    continue;
1520                }
1521                // A read modify write, which is written by name for a different reason: it produces
1522                // one value, so a rule could name it, and what it does is not in the head a rule
1523                // matches on. Every one of the thirteen operations is the same opcode at the same
1524                // type and differs only in what is carried beside it, so one pattern would be all
1525                // thirteen patterns. Of the thirteen only the three with an instruction reach here,
1526                // since `crate::retry` turned the rest into loops a long way above this.
1527                Opcode::AtomicRmw => {
1528                    self.modify(inst)?;
1529                    continue;
1530                }
1531                // An `asm` statement, whose lowering is its template and there is no term for a
1532                // string. Written by name for the reason a barrier is, and before the x87 arm
1533                // below so that an `asm` holding a `long double` is refused as the `asm` it is
1534                // rather than as an instruction nothing computes.
1535                Opcode::InlineAsm => {
1536                    // The template is read as x86 assembly, and that reader is the only one there
1537                    // is. AArch64 keeps every template as text, and any other machine's `asm` is
1538                    // refused here rather than read as the wrong language.
1539                    if self.on_aarch64() {
1540                        self.spelled(inst)?;
1541                        continue;
1542                    }
1543                    if !std::ptr::eq(self.selector.shapes, &x86_64::MACHINE) {
1544                        return Err(self.unsupported(inst));
1545                    }
1546                    if self.touches_x87(inst) {
1547                        self.x87_assembly(inst)?;
1548                        continue;
1549                    }
1550                    self.assembly(inst)?;
1551                    continue;
1552                }
1553                // Anything at all with an eighty bit float in it, which is the one arm here
1554                // chosen by a type rather than by an opcode, because what makes these different
1555                // is not what they do but where the value is. A `long double` has no register,
1556                // so it has no name in `crate::term` and no rule could bind one: every one of
1557                // these is a group of instructions over a frame slot, written out below.
1558                //
1559                // Last of the arms, so that a call and a return with one of these in them reach
1560                // the convention first and are refused by it, which is the truer answer: what is
1561                // wrong there is where the value has to travel and not that nothing can compute
1562                // it.
1563                _ if self.touches_x87(inst) => {
1564                    self.x87(inst)?;
1565                    continue;
1566                }
1567                _ => {}
1568            }
1569            let matched = matched.ok_or_else(|| self.unsupported(inst))?;
1570            self.emit(inst, &matched)?;
1571            // After it is built rather than when it matched, so that what is recorded is the rules
1572            // this function was lowered by and not the rules something was tried with.
1573            self.fired.mark(matched.rule);
1574        }
1575        // Whichever block the walk ended in rather than the one it started in. The two are the
1576        // same block for every function that does not save a place for a `__builtin_longjmp`, and
1577        // where they differ it is the last of them that the terminator and the arms belong to.
1578        // See [`Self::saves_place`].
1579        let last = self.at.expect("a block is being filled");
1580        self.edges(block, last)?;
1581        for (value, reg) in kept {
1582            self.regs[value.index()] = reg;
1583        }
1584        // Now that the block is filled, the instruction after each place an assignment was is the
1585        // first one it holds its value at. One with nothing after it, which a block ending in the
1586        // assignment would be, stays unanswered.
1587        if let Some(marks) = self.marks.get_mut(&block) {
1588            for &(before, at, last) in &reached {
1589                let first = match last {
1590                    Some(last) => self.out.next_inst(last),
1591                    None => self.out.insts(at).next(),
1592                };
1593                for mark in marks.iter_mut().filter(|(after, _)| *after == before) {
1594                    mark.1 = first;
1595                }
1596            }
1597        }
1598        Ok(())
1599    }
1600
1601    /// One call, which is built from the convention rather than matched against the table for the
1602    /// same reason the arguments of the function itself are.
1603    ///
1604    /// The arguments are read before the call is built, which is what materializes a constant
1605    /// argument into a register, since no call passes an immediate.
1606    ///
1607    /// A call to a name and a call through an address are both here, and what tells them apart is
1608    /// the opcode rather than whether a callee was recorded, which is the same thing the verifier
1609    /// reads. Through an address the first operand is the address and the arguments are the ones
1610    /// behind it, and everything after that is the same: where each argument goes, where the value
1611    /// comes back and which registers are gone across it are the convention's answers and the
1612    /// convention does not ask what is being called.
1613    fn called(&mut self, inst: Inst) -> Result<u32, Unsupported> {
1614        let data = &self.source[inst];
1615        let Extra::Call(info) = data.extra else { return Err(self.unsupported(inst)) };
1616        let info = self.source[info];
1617        let indirect = data.opcode == Opcode::CallIndirect;
1618
1619        let values: Vec<Value> = self.source[data.args].to_vec();
1620        let callee = if indirect {
1621            let &address = values.first().ok_or_else(|| self.unsupported(inst))?;
1622            abi::Callee::Through(self.reg_of(address)?)
1623        } else {
1624            abi::Callee::Named(info.callee.ok_or_else(|| self.unsupported(inst))?)
1625        };
1626
1627        // What the ABI asks of each argument, read out before any of them is, because reading one
1628        // borrows the function this is a table in. The ones the signature names are the signature's
1629        // answer and the ones behind them are the call's, which is where a structure passed to a
1630        // variadic callee by value says that its bytes travel: there is no parameter to say it on.
1631        let signature = &self.source[info.signature];
1632        let variadic = signature.variadic;
1633        let named: Vec<Abi> = signature.params.iter().map(|param| param.abi).collect();
1634        let beyond: Vec<Abi> = self.source[info.varargs].to_vec();
1635        // Every value that comes back and not only the first. A structure small enough to travel
1636        // in registers comes back in up to two of them, and which register each half is in is the
1637        // convention's answer, which is why the whole list goes to the same place the arguments do
1638        // rather than to a rule.
1639        let returns: Vec<Type> = signature.return_types().collect();
1640
1641        let mut args = Vec::with_capacity(values.len());
1642        for (index, value) in values.into_iter().skip(usize::from(indirect)).enumerate() {
1643            let abi = named.get(index).or_else(|| beyond.get(index - named.len()));
1644            let abi = abi.copied().unwrap_or_default();
1645            let ty = self.source[value].ty;
1646            // What travels for an eighty bit value is its bytes, so what the call is handed is
1647            // where they are rather than a register they are in, and there is no register they
1648            // could be in. Everything else about it is a sixteen byte object passed by value and
1649            // is built by the same code.
1650            let reg =
1651                if abi::on_the_stack(ty) { self.x87_slot(value) } else { self.reg_of(value)? };
1652            args.push(abi::Passing { ty, reg, abi });
1653        }
1654        let block = self.at.expect("a block is being filled");
1655        let what = abi::Calling {
1656            callee,
1657            args: &args,
1658            returns: &returns,
1659            variadic,
1660            named: named.len(),
1661            at: self.source.span(inst),
1662        };
1663        let made = abi::call(&mut self.out, block, &what, self.conv, self.selector.abi, self.names)
1664            .map_err(|refused| Unsupported::Call { inst, refused })?;
1665        if self.source.unwinds_to_pad(inst) {
1666            let call = self.out.insts(block).last().expect("the call just built");
1667            self.unwinding.insert(inst, call);
1668        }
1669        let calls = &mut self.stack.calls;
1670        *calls = Some(calls.unwrap_or(0).max(made.outgoing));
1671        // An eighty bit value came back on the x87 stack, and the one thing that has to happen
1672        // before anything else touches that stack is taking it off. So the `fstp` goes here, in
1673        // front of everything the block does next, and after it the value is in its slot and is
1674        // read the way every other one is. A complex one is two of them, the real half on top, so
1675        // taking them off in order leaves each in its own slot and the stack empty.
1676        let results: Vec<Value> = self.source[inst].results().collect();
1677        let types: Vec<Type> = results.iter().map(|&result| self.source[result].ty).collect();
1678        if abi::back_on_x87(&types) {
1679            let span = self.source.span(inst);
1680            for result in results {
1681                let into = self.x87_slot(result);
1682                let into = self.through(into);
1683                self.x87_at("fstp_t", span, into);
1684            }
1685            return Ok(made.outgoing);
1686        }
1687        for (result, &reg) in results.into_iter().zip(&made.results) {
1688            self.regs[result.index()] = Some(reg);
1689        }
1690        Ok(made.outgoing)
1691    }
1692
1693    /// One `tail_call`, as the call and a return of what it gave back.
1694    ///
1695    /// The call is written down for [`crate::tail::jumps`] when it can be made after the frame is
1696    /// gone. That is when it put nothing in the argument area, which is the bottom of this frame,
1697    /// and when the answer comes back in registers, since one on the x87 stack is taken off and put
1698    /// back by instructions after the call. A call that is not written down stays a call and a
1699    /// return, which is what the IR said before `crate::tail::mark` read it.
1700    fn tail_called(&mut self, inst: Inst) -> Result<(), Unsupported> {
1701        let outgoing = self.called(inst)?;
1702        let block = self.at.expect("a block is being filled");
1703        let call = self.out.insts(block).last().expect("the call just built");
1704        let values: Vec<Value> = self.source[inst].results().collect();
1705        let x87 = self.x87_values(&values);
1706        self.returned(inst, values)?;
1707        if outgoing == 0 && !x87 && self.sret().is_none() {
1708            let returns = self.out.insts(block).skip_while(|&at| at != call).skip(1).collect();
1709            self.stack.tails.push(crate::tail::Tail { call, returns });
1710        }
1711        Ok(())
1712    }
1713
1714    /// The pointer a function returning through memory was handed, or nothing in a function that
1715    /// was not.
1716    ///
1717    /// It is the first parameter and the signature is what says so, since in the IR it is an
1718    /// ordinary pointer and reads like one everywhere in the body. A function with a signature
1719    /// like that and no entry block has nothing to give back and no body to give it back from.
1720    fn sret(&self) -> Option<Value> {
1721        let first = self.source.signature().params.first()?;
1722        if !matches!(first.abi, Abi::Sret { .. }) {
1723            return None;
1724        }
1725        self.source[self.source.entry()?].params.first().copied()
1726    }
1727
1728    /// One `return` the convention has to write, as the place each value has to be in by the end.
1729    ///
1730    /// One pseudo per value, each a read constrained to a return register, which is what a return
1731    /// of one value already is and is the whole of what either does. The `ret` itself comes from
1732    /// the epilogue for both, long after this, because the frame has to be given back first.
1733    ///
1734    /// The two register files are counted separately, so a structure of a `double` and a `long`
1735    /// leaves the `double` in the first vector register and the `long` in the first integer one
1736    /// rather than in the second of either. That is the same walk `rucc_codegen::abi` makes on
1737    /// the other side of the call, which is what makes the two ends agree.
1738    ///
1739    /// A function whose answer went through memory gives back the address it was handed, in front
1740    /// of nothing else, because a signature that returns that way returns nothing else. That the
1741    /// caller already knows the address is not enough: it is allowed to read the register instead,
1742    /// and a caller that does gets whatever the allocator last left there. In a leaf function that
1743    /// is usually the right answer by accident, and one call in the body is enough to make it a
1744    /// wild pointer, which is why this is written rather than left to luck.
1745    ///
1746    /// Where everything goes is worked out before anything is written, so a return this cannot
1747    /// make leaves no half of one behind.
1748    /// Whether a value this function gives back has to be extended first, which is Apple's arm64
1749    /// asking the callee to fill the 32 bits above a `char` or a `short` by its sign.
1750    fn widens_return(&self) -> bool {
1751        let returns = &self.source.signature().returns;
1752        returns.iter().any(|it| (self.selector.abi.extend)(it.ty, it.abi).is_some())
1753    }
1754
1755    /// Whether what a `return` gives back goes back on the x87 stack, per [`abi::back_on_x87`].
1756    fn gives_back_x87(&self, inst: Inst) -> bool {
1757        self.x87_values(&self.source[self.source[inst].args])
1758    }
1759
1760    /// Whether those values go back on the x87 stack, per [`abi::back_on_x87`].
1761    fn x87_values(&self, values: &[Value]) -> bool {
1762        let types: Vec<Type> = values.iter().map(|&value| self.source[value].ty).collect();
1763        abi::back_on_x87(&types)
1764    }
1765
1766    fn returned(&mut self, inst: Inst, values: Vec<Value>) -> Result<(), Unsupported> {
1767        let (mut ints, mut floats) = (0usize, 0usize);
1768        let mut parts = Vec::with_capacity(values.len() + 1);
1769        // An eighty bit value goes back on the x87 stack, which is where the convention says it is
1770        // and is the one place a value is left rather than put in a register. So the whole of the
1771        // return is an `fld` of its slot, and the stack it leaves the value on is not empty at the
1772        // `ret`, which is the one time in this file that is true and is what the convention asks
1773        // for. What comes after is the epilogue, which gives the frame back and touches nothing in
1774        // the unit. A complex one loads its imaginary half first so that the real half ends up on
1775        // top of it, in `st(0)`, with the imaginary half under it in `st(1)`.
1776        if self.x87_values(&values) && self.sret().is_none() {
1777            let span = self.source.span(inst);
1778            for &value in values.iter().rev() {
1779                let from = self.x87_slot(value);
1780                let from = self.through(from);
1781                self.x87_at("fld_t", span, from);
1782            }
1783            return Ok(());
1784        }
1785        // What the signature says about the bits above a narrow one, which on an ABI that extends
1786        // it is an obligation of this side: the caller reads the whole of the 32 bit register.
1787        let asked: Vec<Abi> = self.source.signature().returns.iter().map(|it| it.abi).collect();
1788        let asked = asked.into_iter().chain(std::iter::repeat(Abi::Plain));
1789        let sret = self.sret().map(|value| (value, Abi::Plain));
1790        for (value, abi) in sret.into_iter().chain(values.into_iter().zip(asked)) {
1791            let ty = self.source[value].ty;
1792            let at = if crate::term::in_vector_file(ty) { &mut floats } else { &mut ints };
1793            // Why it cannot come back, and not only that it cannot. A type that travels nowhere
1794            // says so itself, and a type that travels perfectly well ran out of registers.
1795            let missing = abi::refuses(ty, self.selector.abi).unwrap_or(Missing::NoRoom);
1796            let name =
1797                (self.selector.abi.ret)(ty, *at).ok_or(Unsupported::Returned { inst, missing })?;
1798            *at += 1;
1799            // The register is the target's answer and not one worked out here, the same as it is
1800            // for a return of one value, so that both halves of a pair and every rule that writes
1801            // half of one are reading the same table.
1802            let opcode =
1803                name.strip_prefix(self.selector.prefix()).ok_or_else(|| self.unsupported(inst))?;
1804            let descs = self.selector.operands(opcode).ok_or_else(|| self.unsupported(inst))?;
1805            let [desc] = descs else { return Err(self.unsupported(inst)) };
1806            let widen = (self.selector.abi.extend)(ty, abi).map(|name| self.names.intern(name));
1807            parts.push((self.names.intern(name), self.reg_of(value)?, *desc, widen));
1808        }
1809
1810        let block = self.at.expect("a block is being filled");
1811        let span = self.source.span(inst);
1812        for (opcode, mut reg, desc, widen) in parts {
1813            if let Some(widen) = widen {
1814                let wide = self.out.new_vreg(desc.class);
1815                let build = self.out.build(block, mir::Opcode::new(widen)).at(span);
1816                build.def(wide, desc.class).uses(reg, desc.class).finish();
1817                reg = wide;
1818            }
1819            let operand = mir::Operand {
1820                reg,
1821                class: desc.class,
1822                role: desc.role,
1823                constraint: desc.constraint,
1824            };
1825            self.out.build(block, mir::Opcode::new(opcode)).at(span).operand(operand).finish();
1826        }
1827        Ok(())
1828    }
1829
1830    /// One `alloca`: the bytes it asks for go on the list the frame is laid out from, and the
1831    /// address of them is one instruction.
1832    ///
1833    /// The instruction is a `lea` off the stack pointer, which is the one register that reaches
1834    /// the frame in every function, and its displacement is left at nothing because there is no
1835    /// frame yet. Which instruction is waiting for which local is remembered, and
1836    /// [`crate::finish`] fills the numbers in after [`crate::frame::Frame`] has placed them.
1837    ///
1838    /// There is deliberately no rule for `alloca` and no name for one in [`crate::term`], and
1839    /// that is what stops it being folded into something else. An operand shown as the
1840    /// instruction that computed it is offered to the matcher by its name, so an `alloca` with no
1841    /// name is one no pattern can reach past, and the address it computes is always in a register
1842    /// by the time anything reads it.
1843    fn reserve(&mut self, inst: Inst) -> Result<(), Unsupported> {
1844        let data = &self.source[inst];
1845        // A variable length array carries the size it wants as an operand rather than in the
1846        // instruction, which is the whole of what tells the two apart here.
1847        if let Some(&size) = self.source[data.args].first() {
1848            return self.grow(inst, size);
1849        }
1850        let Extra::Mem(mem) = data.extra else { return Err(self.unsupported(inst)) };
1851        let info = self.source[mem];
1852        let size = u32::try_from(info.size)
1853            .map_err(|_| Unsupported::Dynamic { inst, growing: Growing::Huge })?;
1854        let result = data.first_result.ok_or_else(|| self.unsupported(inst))?;
1855
1856        // At least one, because the frame divides by the alignment and an object with no
1857        // alignment at all is one the front end had nothing to say about rather than one that may
1858        // go anywhere.
1859        let index = self.stack.locals.len();
1860        self.stack.locals.push(Local { size, align: info.align.max(1) });
1861        if let Some(decl) = self.source.mem_decl(mem) {
1862            self.stack.declared.push((index, decl));
1863        }
1864
1865        let block = self.at.expect("a block is being filled");
1866        let reg = self.new_reg(result);
1867        let span = self.source.span(inst);
1868        let lea = self.named(self.selector.frame.lea);
1869        let sp = mir::Operand::read(mir::Reg::physical(self.conv.stack_pointer), self.gpr);
1870        let made =
1871            self.out.build(block, lea).at(span).def(reg, self.gpr).mem(mir::Mem::at(sp)).finish();
1872        self.stack.addresses.push((made, index));
1873        self.frame_slots.insert(result, index);
1874        Ok(())
1875    }
1876
1877    /// The other kind of `alloca`: one whose size the function does not know until it runs, which
1878    /// is what a variable length array is.
1879    ///
1880    /// Nothing about it is a slot the frame laid out, because the frame is laid out once and this
1881    /// happens as often as control reaches the declaration. The bytes come off the stack pointer
1882    /// where the declaration stands, which is two instructions:
1883    ///
1884    /// ```text
1885    ///   sub sp, bytes     the stack pointer moves down over the memory, which is what takes it
1886    ///   lea reg, [sp+n]   where the memory starts, which is above the outgoing argument area
1887    /// ```
1888    ///
1889    /// The displacement is left at nothing for the reason the constant kind leaves its own at
1890    /// nothing, and for a different number: that area belongs to the arguments of whatever this
1891    /// function calls, it stays at the bottom of the frame wherever the bottom has moved to, and
1892    /// how big it is is not known until every call in the function has been seen.
1893    ///
1894    /// The bytes are already a multiple of the stack pointer's alignment by the time they arrive,
1895    /// because [`crate::expand::rounds`] rounded them up in the IR, so nothing here has to mask the
1896    /// stack pointer afterwards and the stack pointer stays somewhere a call can be made from.
1897    ///
1898    /// Two instructions here and not always two in the finished function. On a command line that
1899    /// asked for the stack to be touched a page at a time, the subtraction becomes a loop that
1900    /// walks the same distance a page at a time, which [`crate::finish`] writes. That is why the
1901    /// instruction is written down in [`Stack::grown`] as well as left where it is.
1902    ///
1903    /// An array wanting more alignment than the convention leaves the stack pointer with does not
1904    /// reach here asking for it: [`crate::expand::rounds`] gives it the alignment in extra bytes
1905    /// and turns the array into a `ptr_add` of the offset that lands inside them, so what arrives
1906    /// is a block asking for the convention's alignment like any other. The refusal below is what
1907    /// answers IR that came from somewhere other than that pass, since forcing the alignment here
1908    /// would be a second rounding of a register the frame already rounded, and after it no
1909    /// constant reaches the rest of the frame from anywhere. See `Growing` in [`crate::frame`].
1910    fn grow(&mut self, inst: Inst, size: Value) -> Result<(), Unsupported> {
1911        let data = &self.source[inst];
1912        let Extra::Mem(mem) = data.extra else { return Err(self.unsupported(inst)) };
1913        let info = self.source[mem];
1914        if info.align > self.conv.stack_align {
1915            return Err(Unsupported::Dynamic { inst, growing: Growing::Aligned });
1916        }
1917        let result = data.first_result.ok_or_else(|| self.unsupported(inst))?;
1918        let bytes = self.reg_of(size)?;
1919
1920        let block = self.at.expect("a block is being filled");
1921        let span = self.source.span(inst);
1922        let stack = mir::Reg::physical(self.conv.stack_pointer);
1923        let grow = self.named(self.selector.frame.grow);
1924        let took = self
1925            .out
1926            .build(block, grow)
1927            .at(span)
1928            .operand(mir::Operand::write(stack, self.gpr))
1929            .operand(mir::Operand::read(stack, self.gpr))
1930            .operand(mir::Operand::read(bytes, self.gpr))
1931            .finish();
1932        self.stack.grown.push(took);
1933
1934        let reg = self.new_reg(result);
1935        let lea = self.named(self.selector.frame.lea);
1936        let sp = mir::Operand::read(stack, self.gpr);
1937        let made =
1938            self.out.build(block, lea).at(span).def(reg, self.gpr).mem(mir::Mem::at(sp)).finish();
1939        self.stack.dynamic.push(made);
1940        self.stack.grown_at.get_or_insert(inst);
1941        Ok(())
1942    }
1943
1944    /// Where the stack pointer is, kept so that something later can put it back.
1945    ///
1946    /// One move out of the stack pointer and one move into it, which is the whole of what the two
1947    /// halves are. What makes them worth writing is where the front end puts them: a scope holding
1948    /// a variable length array saves the stack pointer as it opens and puts it back as it closes,
1949    /// so a loop declaring one takes its bytes once round rather than once per iteration, and a
1950    /// jump out of the scope gives the bytes back on the way out.
1951    ///
1952    /// The value travels in an ordinary register the allocator hands out, so it may be spilled like
1953    /// any other, and a spill slot in a frame that grows is reached through the frame pointer,
1954    /// which is exactly the register that still means something after the stack pointer has moved.
1955    fn stack_pointer(&mut self, inst: Inst, into: bool) -> Result<(), Unsupported> {
1956        let data = &self.source[inst];
1957        let block = self.at.expect("a block is being filled");
1958        let span = self.source.span(inst);
1959        let stack = mir::Reg::physical(self.conv.stack_pointer);
1960        let mov =
1961            self.selector.frame.moves(self.gpr).expect("a class the target says how to move").mov;
1962        let mov = self.named(mov);
1963        let (write, read) = if into {
1964            let &saved = self.source[data.args].first().ok_or_else(|| self.unsupported(inst))?;
1965            (stack, self.reg_of(saved)?)
1966        } else {
1967            let result = data.first_result.ok_or_else(|| self.unsupported(inst))?;
1968            (self.new_reg(result), stack)
1969        };
1970        self.out
1971            .build(block, mov)
1972            .at(span)
1973            .operand(mir::Operand::write(write, self.gpr))
1974            .operand(mir::Operand::read(read, self.gpr))
1975            .finish();
1976        // Only the write is a move of the stack pointer, and it is the one that makes the frame a
1977        // growing one. A read of it in a function that never writes it back is a function that
1978        // asked where the stack was and did nothing with the answer.
1979        if into {
1980            self.stack.grown_at.get_or_insert(inst);
1981        }
1982        Ok(())
1983    }
1984
1985    /// Whether an instruction has an eighty bit float anywhere in it.
1986    ///
1987    /// Producing one and reading one are the same question here, because what makes one of these
1988    /// different from every other instruction is not the operation but where the value is. A
1989    /// `long double` is on the x87 stack while it is being worked on and in a frame slot the rest
1990    /// of the time, and neither of those is somewhere the operand of a rule could point.
1991    fn touches_x87(&self, inst: Inst) -> bool {
1992        let data = &self.source[inst];
1993        data.results().any(|value| on_x87(self.source[value].ty))
1994            || self.source[data.args].iter().any(|&arg| on_x87(self.source[arg].ty))
1995    }
1996
1997    /// Everything that happens to an eighty bit float, as the group of instructions it is.
1998    ///
1999    /// The first six move one, and every one of those is a load, a store, or a load and a store at
2000    /// two different formats, because that is the whole of what this machine converts with: the
2001    /// x87 has no instruction that turns one thing on its stack into another, so a widening is
2002    /// `fld` of the narrow format and a narrowing is `fstp` of it.
2003    ///
2004    /// The rest work on one, and they are here rather than in a rule for the same reason the six
2005    /// are. An add is a push, a push, the add and a pop, and what passes between those four is the
2006    /// top of a stack nothing allocates from, so there is no value in the middle of the group for
2007    /// a pattern to bind or a replacement to name. The comparison is the same shape with its last
2008    /// two instructions folded into one opcode, which is where the byte it produces comes from.
2009    ///
2010    /// Every group leaves the stack as empty as it found it, which is what `spec/10-backend.md`
2011    /// section 10.8 asks of one and is why nothing in this file has to track a depth: each push
2012    /// below is answered by a pop a line or two later, so no two groups can ever be looking at
2013    /// the same eight registers.
2014    fn x87(&mut self, inst: Inst) -> Result<(), Unsupported> {
2015        match self.source[inst].opcode {
2016            Opcode::Load => self.x87_load(inst),
2017            Opcode::Store => self.x87_store(inst),
2018            Opcode::FPExt => self.x87_widen(inst),
2019            Opcode::FPTrunc => self.x87_narrow(inst),
2020            Opcode::SIToFP => self.x87_from_signed(inst),
2021            Opcode::FPToSI => self.x87_to_signed(inst),
2022            Opcode::FAdd => self.x87_arith(inst, "fadd_p"),
2023            Opcode::FSub => self.x87_arith(inst, "fsubr_p"),
2024            Opcode::FMul => self.x87_arith(inst, "fmul_p"),
2025            Opcode::FDiv => self.x87_arith(inst, "fdivr_p"),
2026            Opcode::FNeg => self.x87_flip(inst),
2027            Opcode::FCmp => self.x87_compare(inst),
2028            Opcode::FConst => self.x87_const(inst),
2029            _ => Err(self.unsupported(inst)),
2030        }
2031    }
2032
2033    /// The eighty bit parameters of a block, copied out of the addresses an edge handed over and
2034    /// into slots of the block's own.
2035    ///
2036    /// What crosses an edge for a value of this type is an address, because the value is sixteen
2037    /// bytes of the frame and no register holds any of it. The block cannot keep that address: a
2038    /// second edge into the same block hands over a second one, and a read after the block would
2039    /// then be a read of whichever edge was taken rather than of one place. So the block has a
2040    /// slot per parameter and the bytes are copied into it here, which is the move on an edge that
2041    /// every other type gets from the allocator.
2042    ///
2043    /// Every load runs before every store and the stores run backwards, so all of the values are
2044    /// on the x87 stack at once and nothing reads a slot another one has already written. That
2045    /// costs nothing in the ordinary case of one parameter and is what makes the back edge of a
2046    /// loop that swaps two of these work. It is also the reason for the limit: the stack is eight
2047    /// deep, and a block with more of these than that is refused rather than copied in an order
2048    /// that could be wrong.
2049    fn settle(&mut self, block: Block, arriving: &[(Value, mir::Reg)]) -> Result<(), Unsupported> {
2050        let Some(&(first, _)) = arriving.first() else { return Ok(()) };
2051        if arriving.len() > X87_DEPTH {
2052            let ty = self.source[first].ty;
2053            return Err(Unsupported::Phi { block, count: arriving.len(), ty });
2054        }
2055        // A block parameter comes from no instruction, so what this points at is the first thing
2056        // in the block, which is where a reader looking for the copy would look.
2057        let first_inst = self.source.insts(block).next();
2058        let span = first_inst.map_or(Span::DUMMY, |it| self.source.span(it));
2059        for &(_, reg) in arriving {
2060            let from = self.through(reg);
2061            self.x87_at("fld_t", span, from);
2062        }
2063        for &(param, _) in arriving.iter().rev() {
2064            let into = self.x87_slot(param);
2065            let into = self.through(into);
2066            self.x87_at("fstp_t", span, into);
2067        }
2068        Ok(())
2069    }
2070
2071    /// The frame slot an eighty bit value lives in, as its address in a fresh register.
2072    ///
2073    /// The slot is the value's for the whole function and is taken the first time somebody asks.
2074    /// The address is worked out again every time, which is a `lea` per use and is deliberate: one
2075    /// address kept in a register from the definition to the last use would hold a general purpose
2076    /// register open across everything in between, and a function with a handful of these in it
2077    /// would spend its registers on addresses of things rather than on things.
2078    fn x87_slot(&mut self, value: Value) -> mir::Reg {
2079        // An argument of the function has a slot already and it is the caller's. The convention
2080        // puts the bytes in the argument area and hands over where they are, so the address that
2081        // arrived is the answer and no second copy of the value is made. Nothing ever writes to a
2082        // value of this type once it exists, so nothing writes to the caller's copy either. A
2083        // parameter of any other block is not this: what arrived there is an address a predecessor
2084        // chose, [`Lowering::settle`] has already copied the bytes out of it, and the slot those
2085        // bytes landed in is the one below.
2086        let entry = self.source.entry();
2087        if let (Def::Param { block, .. }, Some(reg)) =
2088            (self.source[value].def, self.regs[value.index()])
2089        {
2090            if entry == Some(block) {
2091                return reg;
2092            }
2093        }
2094        let index = match self.slots[value.index()] {
2095            Some(index) => index,
2096            None => {
2097                let index = self.stack.locals.len();
2098                self.stack.locals.push(Local { size: X87_BYTES, align: X87_BYTES });
2099                self.slots[value.index()] = Some(index);
2100                index
2101            }
2102        };
2103        let block = self.at.expect("a block is being filled");
2104        self.frame_address(block, index)
2105    }
2106
2107    /// The bytes a value crosses between a register and the x87 stack through, as their address
2108    /// in a fresh register.
2109    fn x87_crossing(&mut self) -> mir::Reg {
2110        let index = match self.crossing {
2111            Some(index) => index,
2112            None => {
2113                let index = self.stack.locals.len();
2114                self.stack.locals.push(Local { size: X87_CROSSING, align: X87_CROSSING });
2115                self.crossing = Some(index);
2116                index
2117            }
2118        };
2119        let block = self.at.expect("a block is being filled");
2120        self.frame_address(block, index)
2121    }
2122
2123    /// The two control words, as the address of the first of them in a fresh register.
2124    fn x87_control(&mut self) -> mir::Reg {
2125        let index = match self.control {
2126            Some(index) => index,
2127            None => {
2128                let index = self.stack.locals.len();
2129                self.stack.locals.push(Local { size: 4, align: 4 });
2130                self.control = Some(index);
2131                index
2132            }
2133        };
2134        let block = self.at.expect("a block is being filled");
2135        self.frame_address(block, index)
2136    }
2137
2138    /// An address held in a register, as the addressing mode that reaches it.
2139    fn through(&self, reg: mir::Reg) -> mir::Mem {
2140        mir::Mem::at(mir::Operand::read(reg, self.gpr))
2141    }
2142
2143    /// One instruction of a group, which names an address and nothing else.
2144    ///
2145    /// Every x87 instruction that moves a value is one of these. What it does to the stack is in
2146    /// the mnemonic rather than in an operand, so there is no register to write down and no
2147    /// register the allocator gets a say in.
2148    fn x87_at(&mut self, name: &str, span: Span, at: mir::Mem) {
2149        let block = self.at.expect("a block is being filled");
2150        let opcode = self.named(name);
2151        self.out.build(block, opcode).at(span).mem(at).finish();
2152    }
2153
2154    /// The one instruction of a group that reaches the program's own memory.
2155    ///
2156    /// A `long double` moves in two instructions with a frame slot at one end of them, and the
2157    /// other end is the address the program wrote. That end is the access, so it is the one that
2158    /// carries what the program said about it, and the trip through the slot is this compiler's
2159    /// own business the way a spill is. See [`Self::carried`].
2160    fn x87_touching(&mut self, name: &str, inst: Inst, at: mir::Mem) {
2161        let block = self.at.expect("a block is being filled");
2162        let opcode = self.named(name);
2163        let (span, flags) = (self.source.span(inst), self.carried(inst));
2164        self.out.build(block, opcode).at(span).flags(flags).mem(at).finish();
2165    }
2166
2167    /// One instruction of a group that names nothing at all.
2168    ///
2169    /// The arithmetic is these. Both of an add's operands are already on the stack when it runs
2170    /// and so is where the answer goes, and the stack is not somewhere an instruction says, so
2171    /// `faddp` has an argument in the assembler's syntax and nothing here for the argument to come
2172    /// from. What it works on is which two pushes came before it, which is a fact about the order
2173    /// of the group and is why the group is written in one place.
2174    fn x87_only(&mut self, name: &str, span: Span) {
2175        let block = self.at.expect("a block is being filled");
2176        let opcode = self.named(name);
2177        self.out.build(block, opcode).at(span).finish();
2178    }
2179
2180    /// A `load` of a `long double`: onto the stack from where it was, and off it into the slot.
2181    ///
2182    /// Two instructions rather than the two general purpose moves the same sixteen bytes would
2183    /// take, because `fld` and `fstp` at this format neither convert nor look: the value goes on
2184    /// in the format it was already in and comes back off in it, so a signalling NaN stays one
2185    /// and nothing is raised. Which is what makes this a copy at all.
2186    fn x87_load(&mut self, inst: Inst) -> Result<(), Unsupported> {
2187        let (args, result) = self.ends(inst)?;
2188        let &address = args.first().ok_or_else(|| self.unsupported(inst))?;
2189        let span = self.source.span(inst);
2190        let from = self.reg_of(address)?;
2191        let from = self.through(from);
2192        let into = self.x87_slot(result);
2193        let into = self.through(into);
2194        self.x87_touching("fld_t", inst, from);
2195        self.x87_at("fstp_t", span, into);
2196        Ok(())
2197    }
2198
2199    /// A `store` of a `long double`: the same pair the other way round.
2200    fn x87_store(&mut self, inst: Inst) -> Result<(), Unsupported> {
2201        let args = self.source[self.source[inst].args].to_vec();
2202        let [value, address] = args[..] else { return Err(self.unsupported(inst)) };
2203        let span = self.source.span(inst);
2204        let from = self.x87_slot(value);
2205        let from = self.through(from);
2206        let into = self.reg_of(address)?;
2207        let into = self.through(into);
2208        self.x87_at("fld_t", span, from);
2209        self.x87_touching("fstp_t", inst, into);
2210        Ok(())
2211    }
2212
2213    /// A `float`, a `double` or an integer becoming a `long double`.
2214    ///
2215    /// Through memory, because the x87 reads memory and nothing else: the value is in a register
2216    /// the machine has and the unit has no way to be handed one, so it is written to the crossing
2217    /// bytes and loaded back at the format that widens it. Every one of these is exact. Sixty four
2218    /// bits of significand and fifteen of exponent hold every `float`, every `double` and every
2219    /// sixty four bit integer outright, so none of the four can round and none can raise.
2220    fn x87_across(
2221        &mut self,
2222        inst: Inst,
2223        put: &'static str,
2224        class: RegClass,
2225        get: &'static str,
2226    ) -> Result<(), Unsupported> {
2227        let (args, result) = self.ends(inst)?;
2228        let &source = args.first().ok_or_else(|| self.unsupported(inst))?;
2229        let span = self.source.span(inst);
2230        let value = self.reg_of(source)?;
2231        let across = self.x87_crossing();
2232        let across = self.through(across);
2233        let into = self.x87_slot(result);
2234        let into = self.through(into);
2235
2236        let block = self.at.expect("a block is being filled");
2237        let store = self.named(put);
2238        self.out.build(block, store).at(span).uses(value, class).mem(across).finish();
2239        self.x87_at(get, span, across);
2240        self.x87_at("fstp_t", span, into);
2241        Ok(())
2242    }
2243
2244    /// A `long double` becoming a `float`, a `double` or an integer.
2245    ///
2246    /// Through memory for the reason above and in the same three instructions backwards. The two
2247    /// that go to a float round to nearest, which is what the control word says unless somebody
2248    /// has changed it and is what C wants. The two that go to an integer do not, which is why they
2249    /// do not come here.
2250    fn x87_back(
2251        &mut self,
2252        inst: Inst,
2253        put: &'static str,
2254        get: &'static str,
2255        class: RegClass,
2256    ) -> Result<(), Unsupported> {
2257        let (args, result) = self.ends(inst)?;
2258        let &source = args.first().ok_or_else(|| self.unsupported(inst))?;
2259        let span = self.source.span(inst);
2260        let from = self.x87_slot(source);
2261        let from = self.through(from);
2262        let across = self.x87_crossing();
2263        let across = self.through(across);
2264
2265        self.x87_at("fld_t", span, from);
2266        self.x87_at(put, span, across);
2267        let block = self.at.expect("a block is being filled");
2268        let reg = self.new_reg(result);
2269        let load = self.named(get);
2270        self.out.build(block, load).at(span).def(reg, class).mem(across).finish();
2271        Ok(())
2272    }
2273
2274    /// An `fpext` up to a `long double`, which is the only direction this machine has one in.
2275    fn x87_widen(&mut self, inst: Inst) -> Result<(), Unsupported> {
2276        let sse = self.conv.sse_class;
2277        match self.source[self.narrow(inst)?].ty.bits() {
2278            32 => self.x87_across(inst, "movss_mr", sse, "fld_s"),
2279            64 => self.x87_across(inst, "movsd_mr", sse, "fld_l"),
2280            _ => Err(self.unsupported(inst)),
2281        }
2282    }
2283
2284    /// An `fptrunc` down from a `long double`, which is the other direction of the same.
2285    fn x87_narrow(&mut self, inst: Inst) -> Result<(), Unsupported> {
2286        let sse = self.conv.sse_class;
2287        let result = self.source[inst].first_result.ok_or_else(|| self.unsupported(inst))?;
2288        match self.source[result].ty.bits() {
2289            32 => self.x87_back(inst, "fstp_s", "movss_rm", sse),
2290            64 => self.x87_back(inst, "fstp_l", "movsd_rm", sse),
2291            _ => Err(self.unsupported(inst)),
2292        }
2293    }
2294
2295    /// A `sitofp` up to a `long double`.
2296    ///
2297    /// Thirty two bits and sixty four, and nothing narrower, because C widens an integer to `int`
2298    /// before it converts one and the front end writes that widening down. An unsigned integer is
2299    /// not here at all: `fild` reads its operand as signed, so a value above the signed range
2300    /// comes back short by two to the sixty fourth and has to be added back, which is arithmetic
2301    /// rather than a move and waits with the rest of it.
2302    fn x87_from_signed(&mut self, inst: Inst) -> Result<(), Unsupported> {
2303        let gpr = self.gpr;
2304        match self.source[self.narrow(inst)?].ty.bits() {
2305            32 => self.x87_across(inst, "mov_mr_32", gpr, "fild_l"),
2306            64 => self.x87_across(inst, "mov_mr_64", gpr, "fild_ll"),
2307            _ => Err(self.unsupported(inst)),
2308        }
2309    }
2310
2311    /// An `fptosi` down from a `long double`, which is the one conversion here with no single
2312    /// instruction behind it.
2313    ///
2314    /// C cuts towards zero and the unit rounds the way its control word says, so the store that
2315    /// takes the value off the stack is wrapped in the control word being saved, changed and put
2316    /// back. Five instructions around the one that does the work, and three more moving the word
2317    /// through a register, because this machine has no way to OR a constant into memory at this
2318    /// width. The unit has a shorter answer in `fisttp`, and `spec/10-backend.md` section 10.8
2319    /// says why it is not used: it is SSE3, the x86-64 baseline is not, and there is nothing here
2320    /// that can gate an instruction on a feature yet.
2321    fn x87_to_signed(&mut self, inst: Inst) -> Result<(), Unsupported> {
2322        let (args, result) = self.ends(inst)?;
2323        let &source = args.first().ok_or_else(|| self.unsupported(inst))?;
2324        let (put, get) = match self.source[result].ty.bits() {
2325            32 => ("fistp_l", "mov_rm_32"),
2326            64 => ("fistp_ll", "mov_rm_64"),
2327            _ => return Err(self.unsupported(inst)),
2328        };
2329        let span = self.source.span(inst);
2330        let gpr = self.gpr;
2331        let from = self.x87_slot(source);
2332        let from = self.through(from);
2333        let across = self.x87_crossing();
2334        let across = self.through(across);
2335        let control = self.x87_control();
2336        let saved = self.through(control).plus(0);
2337        let cut = self.through(control).plus(2);
2338
2339        // The word the unit has now, into the first of the two slots and into a register, with the
2340        // rounding field turned to truncate on the way to the second.
2341        self.x87_at("fnstcw", span, saved);
2342        let block = self.at.expect("a block is being filled");
2343        let was = self.out.new_vreg(gpr);
2344        let read = self.named("mov_rm_16");
2345        self.out.build(block, read).at(span).def(was, gpr).mem(saved).finish();
2346        let now = self.out.new_vreg(gpr);
2347        let set = self.named("or_ri_16");
2348        // Two address, which is written out here rather than taken from the two shorthands
2349        // because the shorthands leave an operand unconstrained: this machine ORs into the
2350        // register it read, so the two have to be the same one and only the constraint says so.
2351        self.out
2352            .build(block, set)
2353            .at(span)
2354            .operand(mir::Operand::write(now, gpr).with(Constraint::Reuse(1)))
2355            .operand(mir::Operand::read(was, gpr))
2356            .imm(X87_TRUNCATE)
2357            .finish();
2358        let write = self.named("mov_mr_16");
2359        self.out.build(block, write).at(span).uses(now, gpr).mem(cut).finish();
2360
2361        // The conversion itself, under the changed word, and then the word the unit had put back
2362        // before anything else runs.
2363        self.x87_at("fldcw", span, cut);
2364        self.x87_at("fld_t", span, from);
2365        self.x87_at(put, span, across);
2366        self.x87_at("fldcw", span, saved);
2367
2368        let block = self.at.expect("a block is being filled");
2369        let reg = self.new_reg(result);
2370        let load = self.named(get);
2371        self.out.build(block, load).at(span).def(reg, gpr).mem(across).finish();
2372        Ok(())
2373    }
2374
2375    /// A constant of this type, as the bits of it written into its slot.
2376    ///
2377    /// No x87 instruction at all, which is the surprise here. A slot holding an eighty bit value is
2378    /// the value, so a constant is ten bytes put where the value lives, and the unit never has to
2379    /// see it: whatever reads it will `fld` it out of the slot the way it reads any other one.
2380    ///
2381    /// Ten bytes in two goes, because the machine stores eight at a time and there is no store of
2382    /// an immediate to memory, so each half is put in a register first. The six bytes above the ten
2383    /// are left alone, since nothing reads them: they are the padding that makes the type sixteen
2384    /// wide and they are unspecified in the psABI rather than zero.
2385    ///
2386    /// The other way is a constant pool, an `fldt` of a symbol, and a relocation, which is what a
2387    /// compiler with somewhere to put a literal does. This back end has nowhere to put one yet, and
2388    /// four instructions in the frame is what that costs until it does.
2389    fn x87_const(&mut self, inst: Inst) -> Result<(), Unsupported> {
2390        let Extra::Imm(imm) = self.source[inst].extra else { return Err(self.unsupported(inst)) };
2391        let result = self.source[inst].first_result.ok_or_else(|| self.unsupported(inst))?;
2392        let bits = self.source[imm].bits();
2393        let span = self.source.span(inst);
2394        let gpr = self.gpr;
2395        let slot = self.x87_slot(result);
2396        let low = self.through(slot).plus(0);
2397        let high = self.through(slot).plus(8);
2398
2399        let block = self.at.expect("a block is being filled");
2400        for (bytes, at, into) in
2401            [(bits as u64 as i64, low, "64"), (((bits >> 64) & 0xffff) as i64, high, "16")]
2402        {
2403            let held = self.out.new_vreg(gpr);
2404            let put = self.named(&format!("mov_ri_{into}"));
2405            self.out.build(block, put).at(span).def(held, gpr).imm(bytes).finish();
2406            let store = self.named(&format!("mov_mr_{into}"));
2407            self.out.build(block, store).at(span).uses(held, gpr).mem(at).finish();
2408        }
2409        Ok(())
2410    }
2411
2412    /// One arithmetic instruction on two eighty bit values, as the four it takes.
2413    ///
2414    /// The left operand is pushed first and the right one on top of it, so the left ends up
2415    /// underneath and the answer wanted is the one below against the top in that order. Which of
2416    /// the two mnemonics computes that is a question about the spelling rather than about the
2417    /// machine, and the two spellings disagree. Intel's `FSUBP ST(i), ST(0)` is `ST(i) - ST(0)`
2418    /// and is `DE E8+i`, and AT&T's `fsubp` is `DE E0+i`, which is the other subtraction. This
2419    /// compiler writes AT&T and encodes what gas encodes, so what it asks for here is `fsubr_p`
2420    /// and `fdivr_p`, and the `r` is not a reversal of anything the code generator decided.
2421    ///
2422    /// An addition and a multiplication have one form each and do not care, which is why a test
2423    /// that reads the mnemonic back would not have caught this and one that computes a subtraction
2424    /// and checks the answer does.
2425    ///
2426    /// The answer is left where the deeper of the two was and the shallower is gone, which is what
2427    /// the `p` on the mnemonic means, so one push has already been paid back by the time the
2428    /// `fstp` runs and the stack is level again after it.
2429    ///
2430    /// Nothing here is folded and nothing is reused. Two values that are the same value get two
2431    /// pushes of the same slot, and an operand that was just computed is read back out of the slot
2432    /// it was written to rather than left on the stack, which costs a store and a load per
2433    /// instruction in an expression. Keeping a partial result on the stack across the next
2434    /// instruction's operands means knowing how deep the stack is at every point in the block, and
2435    /// that is a different thing from writing a group.
2436    fn x87_arith(&mut self, inst: Inst, with: &'static str) -> Result<(), Unsupported> {
2437        let (args, result) = self.ends(inst)?;
2438        let [left, right] = args[..] else { return Err(self.unsupported(inst)) };
2439        let span = self.source.span(inst);
2440        let left = self.x87_slot(left);
2441        let left = self.through(left);
2442        let right = self.x87_slot(right);
2443        let right = self.through(right);
2444        let into = self.x87_slot(result);
2445        let into = self.through(into);
2446        self.x87_at("fld_t", span, left);
2447        self.x87_at("fld_t", span, right);
2448        self.x87_only(with, span);
2449        self.x87_at("fstp_t", span, into);
2450        Ok(())
2451    }
2452
2453    /// A negation, which is a push, the sign bit turned over and a pop.
2454    ///
2455    /// `fchs` does not read the value as a number, so this is right for a zero, for an infinity
2456    /// and for a NaN, and it raises nothing on any of them. Which is what C asks of a negation and
2457    /// is not what subtracting from zero would give: `0.0L - x` is a different answer at a
2458    /// negative zero and a signalling one at a NaN.
2459    fn x87_flip(&mut self, inst: Inst) -> Result<(), Unsupported> {
2460        let (args, result) = self.ends(inst)?;
2461        let &source = args.first().ok_or_else(|| self.unsupported(inst))?;
2462        let span = self.source.span(inst);
2463        let from = self.x87_slot(source);
2464        let from = self.through(from);
2465        let into = self.x87_slot(result);
2466        let into = self.through(into);
2467        self.x87_at("fld_t", span, from);
2468        self.x87_only("fchs", span);
2469        self.x87_at("fstp_t", span, into);
2470        Ok(())
2471    }
2472
2473    /// A comparison of two eighty bit values, as the two pushes and the one opcode that reads them.
2474    ///
2475    /// The right operand is pushed first and the left one on top of it, which is the other way
2476    /// round from the arithmetic and is because `fucomip` asks about the top against what is under
2477    /// it: the comparison this machine can do is the top's, so the value the predicate is about
2478    /// has to be the top. The pop that gets the loser off the stack and the byte that reads the
2479    /// flags are both inside the opcode, since what passes between those and the comparison is the
2480    /// flags and the flags are not something anything here can name.
2481    ///
2482    /// Which of the ten opcodes, and which way round, is the same table the vector comparisons
2483    /// match against in `rules/x86-64.rules`, and it has to stay the same table: a predicate that
2484    /// picked a different condition here than there would be a `long double` comparison that
2485    /// disagreed with the `double` comparison of the same two numbers, which is the one thing a
2486    /// wider format is not allowed to do.
2487    ///
2488    /// The always false and the always true are refused rather than folded into a constant,
2489    /// because a comparison this machine never has to do is one the optimizer should have removed
2490    /// and an instruction here that quietly agreed with it would hide that it did not.
2491    fn x87_compare(&mut self, inst: Inst) -> Result<(), Unsupported> {
2492        let Extra::FloatPred(pred) = self.source[inst].extra else {
2493            return Err(self.unsupported(inst));
2494        };
2495        let (args, result) = self.ends(inst)?;
2496        let [left, right] = args[..] else { return Err(self.unsupported(inst)) };
2497        // Two of the fourteen need a second byte and an instruction to put the two together,
2498        // because they are two conditions at once: an ordered equal is equal and not unordered,
2499        // and an unordered not equal is either. The opcode carries all of that and says here only
2500        // that it writes somewhere else as well.
2501        let (name, reversed, both) = match pred {
2502            FloatPred::Ogt => ("fucomip_set_a", false, false),
2503            FloatPred::Oge => ("fucomip_set_ae", false, false),
2504            FloatPred::Olt => ("fucomip_set_a", true, false),
2505            FloatPred::Ole => ("fucomip_set_ae", true, false),
2506            FloatPred::One => ("fucomip_set_ne", false, false),
2507            FloatPred::Ord => ("fucomip_set_np", false, false),
2508            FloatPred::Uno => ("fucomip_set_p", false, false),
2509            FloatPred::Ueq => ("fucomip_set_e", false, false),
2510            FloatPred::Ult => ("fucomip_set_b", false, false),
2511            FloatPred::Ule => ("fucomip_set_be", false, false),
2512            FloatPred::Ugt => ("fucomip_set_b", true, false),
2513            FloatPred::Uge => ("fucomip_set_be", true, false),
2514            FloatPred::Oeq => ("fucomip_set_e_and_np", false, true),
2515            FloatPred::Une => ("fucomip_set_ne_or_p", false, true),
2516            FloatPred::False | FloatPred::True => return Err(self.unsupported(inst)),
2517        };
2518        let (top, under) = if reversed { (right, left) } else { (left, right) };
2519
2520        let span = self.source.span(inst);
2521        let gpr = self.gpr;
2522        let under = self.x87_slot(under);
2523        let under = self.through(under);
2524        let top = self.x87_slot(top);
2525        let top = self.through(top);
2526        self.x87_at("fld_t", span, under);
2527        self.x87_at("fld_t", span, top);
2528
2529        let block = self.at.expect("a block is being filled");
2530        let reg = self.new_reg(result);
2531        // Taken before the instruction is started rather than inside it, since both come from the
2532        // same function being built and only one thing at a time may be adding to it.
2533        let spare = both.then(|| self.out.new_vreg(gpr));
2534        let opcode = self.named(name);
2535        let mut build = self.out.build(block, opcode).at(span).def(reg, gpr);
2536        if let Some(spare) = spare {
2537            build = build.def(spare, gpr);
2538        }
2539        build.finish();
2540        Ok(())
2541    }
2542
2543    /// The operands and the one result of an instruction that has exactly one.
2544    fn ends(&self, inst: Inst) -> Result<(&'a [Value], Value), Unsupported> {
2545        let data = &self.source[inst];
2546        let result = data.first_result.ok_or_else(|| self.unsupported(inst))?;
2547        Ok((&self.source[data.args], result))
2548    }
2549
2550    /// The operand of a conversion, which is the end of it that is not the `long double`.
2551    fn narrow(&self, inst: Inst) -> Result<Value, Unsupported> {
2552        let args = &self.source[self.source[inst].args];
2553        args.first().copied().ok_or_else(|| self.unsupported(inst))
2554    }
2555
2556    /// One `va_start`, as the fields of the list it was handed.
2557    ///
2558    /// On the four field list, two of them are numbers this already knows, and each costs an
2559    /// instruction to put in a register before it can be stored, because the machine here has no
2560    /// store of an immediate to memory. The other two are addresses in the frame, and each is a
2561    /// `lea` [`crate::finish`] finishes: the save area is one of the function's own stack objects,
2562    /// and the caller's argument area is where the parameters that had no register came from, which
2563    /// is the same place and the same fixup a parameter past the sixth already uses.
2564    ///
2565    /// On the list that is a pointer it is the second of those four and nothing else, since the
2566    /// whole of what that list says is where the walk is and the walk starts at the first argument
2567    /// the signature does not name. One `lea` and one store.
2568    ///
2569    /// What is written is exactly the fields [`crate::varargs`] describes, in the order they are
2570    /// laid out, so that reading this beside that table is the whole of the check.
2571    fn va_start(&mut self, inst: Inst) -> Result<(), Unsupported> {
2572        let Some(&list) = self.source[self.source[inst].args].first() else {
2573            return Err(self.unsupported(inst));
2574        };
2575        let started = self.varargs.ok_or_else(|| self.unsupported(inst))?;
2576        let list = self.reg_of(list)?;
2577        let block = self.at.expect("a block is being filled");
2578        let span = self.source.span(inst);
2579
2580        let (save, incoming) = match started {
2581            Varargs::Pointer { incoming } => (None, incoming),
2582            Varargs::Fields { save, incoming, integers, floats } => {
2583                let counts = [(varargs::GP_OFFSET, integers), (varargs::FP_OFFSET, floats)];
2584                for (at, count) in counts {
2585                    self.store_small(list, at, i64::from(count), span);
2586                }
2587                (Some(save), incoming)
2588            }
2589            Varargs::Aapcs { save, incoming, integers_end, floats_end, integers, floats } => {
2590                let counts =
2591                    [(varargs::aapcs::GR_OFFS, integers), (varargs::aapcs::VR_OFFS, floats)];
2592                for (at, count) in counts {
2593                    self.store_small(list, at, i64::from(count), span);
2594                }
2595                let overflow = self.overflow(block, incoming, span);
2596                let integers_top = self.frame_address_plus(block, save, integers_end);
2597                let floats_top = self.frame_address_plus(block, save, floats_end);
2598                let fields = [
2599                    (varargs::aapcs::STACK, overflow),
2600                    (varargs::aapcs::GR_TOP, integers_top),
2601                    (varargs::aapcs::VR_TOP, floats_top),
2602                ];
2603                for (at, held) in fields {
2604                    self.store_word(list, at, held, span);
2605                }
2606                return Ok(());
2607            }
2608        };
2609
2610        // At the front of the list when that address is the whole of it, and at the field the
2611        // layout gives it when there are four, with the save area behind it.
2612        let overflow = self.overflow(block, incoming, span);
2613        let fields = match save {
2614            None => vec![(0, overflow)],
2615            Some(save) => {
2616                let save = self.frame_address(block, save);
2617                vec![(varargs::OVERFLOW, overflow), (varargs::SAVE_AREA, save)]
2618            }
2619        };
2620        for (at, held) in fields {
2621            self.store_word(list, at, held, span);
2622        }
2623        Ok(())
2624    }
2625
2626    /// The first argument the signature did not name, which is as far up the caller's argument
2627    /// area as the ones it did name reached. Nothing here knows where that area is, so the distance
2628    /// is recorded the way a parameter read out of it is and finished with it.
2629    fn overflow(&mut self, block: mir::Block, incoming: u32, span: Span) -> mir::Reg {
2630        let overflow = self.out.new_vreg(self.gpr);
2631        let lea = self.named(self.selector.frame.lea);
2632        let sp = mir::Operand::read(mir::Reg::physical(self.conv.stack_pointer), self.gpr);
2633        let made = self
2634            .out
2635            .build(block, lea)
2636            .at(span)
2637            .def(overflow, self.gpr)
2638            .mem(mir::Mem::at(sp))
2639            .finish();
2640        self.stack.arguments.push((made, incoming));
2641        overflow
2642    }
2643
2644    /// Writes a small constant into a 32 bit field of a list.
2645    fn store_small(&mut self, list: mir::Reg, at: i64, value: i64, span: Span) {
2646        let block = self.at.expect("a block is being filled");
2647        let held = self.out.new_vreg(self.gpr);
2648        let load = mir::Opcode::new(self.names.intern(self.selector.abi.small));
2649        self.out.build(block, load).at(span).def(held, self.gpr).imm(value).finish();
2650
2651        let head = (self.selector.abi.store)(Type::int(32)).expect("a store of a word");
2652        let store = mir::Opcode::new(self.names.intern(head));
2653        let mem = self.field(list, at);
2654        self.out.build(block, store).at(span).uses(held, self.gpr).mem(mem).finish();
2655    }
2656
2657    /// Writes an address into a pointer field of a list.
2658    fn store_word(&mut self, list: mir::Reg, at: i64, held: mir::Reg, span: Span) {
2659        let block = self.at.expect("a block is being filled");
2660        let head = (self.selector.abi.store)(Type::int(64)).expect("a store of an address");
2661        let store = mir::Opcode::new(self.names.intern(head));
2662        let mem = self.field(list, at);
2663        self.out.build(block, store).at(span).uses(held, self.gpr).mem(mem).finish();
2664    }
2665
2666    /// One field of a list, as the addressing mode that reaches it.
2667    fn field(&self, list: mir::Reg, at: i64) -> mir::Mem {
2668        let base = mir::Operand::read(list, self.gpr);
2669        mir::Mem::at(base).plus(i32::try_from(at).expect("a field of a list is a small offset"))
2670    }
2671
2672    /// The address of a name: one `lea` off the instruction pointer, with the name on it.
2673    ///
2674    /// That is x86-64, and [`Selector::symbols`] is what says so. AArch64 writes the same thing as
2675    /// an `adrp` of the page and an `add` of the low twelve bits, which is one opcode with the name
2676    /// as its own symbol and no addressing mode, and the table read is an `adrp` and an `ldr`.
2677    ///
2678    /// The same instruction an `alloca` gets and for a related reason. An address that is not in
2679    /// the program is a `lea` of an addressing mode that names no register, and the mode carries
2680    /// the symbol so that [`rucc_asm`] can write it relative to `%rip` and leave the relocation
2681    /// for the assembler. Both halves of that already existed: the printer writes `sym(%rip)` and
2682    /// the encoder emits the relocation, because a call to a name the file does not define needed
2683    /// them first.
2684    ///
2685    /// One `mov` and not one `lea` when the name is one [`Elsewhere`] holds, because the distance
2686    /// the `lea` adds to the instruction pointer is a number only a link that puts the name in
2687    /// this program can work out, and the address of a function this file merely declares is not
2688    /// such a number. The load reads the address out of the slot the linker fills in instead. The
2689    /// linker turns it back into the `lea` when the name turns out to have been here all along,
2690    /// so this is not slower in the case that was already right.
2691    ///
2692    /// There is deliberately no name for this in [`crate::term`], which is what stops the address
2693    /// being folded into the instruction that reads it. Folding it is the right thing to do and
2694    /// is what turns a load of a global from two instructions into one, but it is a separate
2695    /// question about addressing modes and issue #282 is it. Until then the address is in a
2696    /// register before anything uses it, which is correct and one instruction longer.
2697    ///
2698    /// What this does not do is give the name anything to refer to. A module carries its globals
2699    /// and nothing writes them out, so a file that defines the variable it reads compiles to a
2700    /// reference the linker cannot resolve. Issue #293 is the other half.
2701    ///
2702    /// A thread-local variable is neither of the two above and is [`Self::thread_address`].
2703    fn address_of(&mut self, inst: Inst) -> Result<(), Unsupported> {
2704        let data = &self.source[inst];
2705        let Extra::Symbol(symbol) = data.extra else { return Err(self.unsupported(inst)) };
2706        let result = data.first_result.ok_or_else(|| self.unsupported(inst))?;
2707        if self.elsewhere.thread(symbol) {
2708            return self.thread_address(inst, symbol, result);
2709        }
2710
2711        let block = self.at.expect("a block is being filled");
2712        let reg = self.new_reg(result);
2713        let span = self.source.span(inst);
2714        let far = self.elsewhere.holds(symbol);
2715        let symbols = self.selector.symbols;
2716        match if far { symbols.far } else { symbols.near } {
2717            Reach::Mode(name) => {
2718                let mem = if far { mir::Mem::got(symbol) } else { mir::Mem::of(symbol) };
2719                let opcode = self.named(name);
2720                self.out.build(block, opcode).at(span).def(reg, self.gpr).mem(mem).finish();
2721            }
2722            Reach::Own(name) => {
2723                let opcode = self.named(name);
2724                self.out.build(block, opcode).at(span).def(reg, self.gpr).symbol(symbol).finish();
2725            }
2726        }
2727        Ok(())
2728    }
2729
2730    /// The address of a thread-local variable, which is this thread's copy of it.
2731    ///
2732    /// Neither instruction the ordinary case writes would mean anything here. There is no distance
2733    /// to the variable for a `lea` to add, because there is no variable: there is one copy of it per
2734    /// thread and they are at different addresses, so a link asked for the distance to the name
2735    /// refuses rather than picking one. And there is no address for a table slot to hold either, for
2736    /// the same reason.
2737    ///
2738    /// What is the same in every thread is where the variable sits inside the block of storage a
2739    /// thread gets, so that offset is what the link writes down, and the address of the running
2740    /// thread's block is what turns it into an address. x86-64 keeps that address in `%fs`, at the
2741    /// front of the block, so the whole of this is three instructions:
2742    ///
2743    /// ```text
2744    /// movq  x@gottpoff(%rip), %off   # how far into the block x sits, which the link fills in
2745    /// movq  %fs:0, %tp               # where this thread's block is, which only the machine knows
2746    /// addq  %tp, %off                # this thread's copy of x
2747    /// ```
2748    ///
2749    /// That is the initial exec model. It is one instruction longer than what gcc writes at `-O2`
2750    /// in an executable, which folds the addition into the instruction that uses the address, and
2751    /// the difference is issue #282 rather than anything about threads: nothing here folds an
2752    /// address into its reader yet. The link relaxes the first instruction into an immediate when it
2753    /// is making an executable, since it lays the blocks out and therefore knows the number, so the
2754    /// table slot costs nothing in the case that is common.
2755    ///
2756    /// It is not the most general model. A library loaded by `dlopen` gets its storage after the
2757    /// program is already running, and the block this reaches was laid out before it started, so
2758    /// the loader has to find room in that block for the library's variables. glibc keeps a little
2759    /// spare room for exactly this and a library that fits in it loads and runs; one that does not
2760    /// fails to load, with a message saying so. The model with no such limit calls `__tls_get_addr`
2761    /// and is what gcc writes under `-fPIC` by default, and it is issue #1104.
2762    ///
2763    /// So this is the model gcc writes under `-ftls-model=initial-exec`: right for an executable,
2764    /// right for a library the program is linked against, and a load that either works or is
2765    /// refused out loud for a library something opens later. What it is never is quietly wrong.
2766    ///
2767    /// AArch64 Linux is the same three steps. The slot is reached with `adrp` and `ldr` against
2768    /// `:gottprel:`, the thread pointer is `tpidr_el0` read with `mrs`, and the add has three
2769    /// operands. Apple's platforms reach a thread-local variable through a descriptor call instead,
2770    /// which is [`Self::thread_descriptor`].
2771    fn thread_address(
2772        &mut self,
2773        inst: Inst,
2774        symbol: Symbol,
2775        result: Value,
2776    ) -> Result<(), Unsupported> {
2777        if self.elsewhere.described() {
2778            return self.thread_descriptor(inst, symbol, result);
2779        }
2780        if self.elsewhere.indexed() {
2781            return self.thread_indexed(inst, symbol, result);
2782        }
2783        let block = self.at.expect("a block is being filled");
2784        let span = self.source.span(inst);
2785        let gpr = self.gpr;
2786
2787        let offset = self.out.new_vreg(gpr);
2788        match self.selector.symbols.thread {
2789            Reach::Mode(name) => {
2790                let load = self.named(name);
2791                let mem = mir::Mem::thread(symbol);
2792                self.out.build(block, load).at(span).def(offset, gpr).mem(mem).finish();
2793            }
2794            Reach::Own(name) => {
2795                let load = self.named(name);
2796                self.out.build(block, load).at(span).def(offset, gpr).symbol(symbol).finish();
2797            }
2798        }
2799        let pointer = self.out.new_vreg(gpr);
2800        self.read_thread_pointer(block, span, pointer);
2801
2802        // Two address on x86-64, for the reason `x87_to_int` gives: that machine adds into the
2803        // register it read, and only the constraint says the two are the same one.
2804        let reg = self.new_reg(result);
2805        let jumps = self.selector.jumps;
2806        let add = self.named(jumps.add);
2807        let written = mir::Operand::write(reg, gpr);
2808        let written = if jumps.two_address { written.with(Constraint::Reuse(1)) } else { written };
2809        self.out
2810            .build(block, add)
2811            .at(span)
2812            .operand(written)
2813            .operand(mir::Operand::read(offset, gpr))
2814            .operand(mir::Operand::read(pointer, gpr))
2815            .finish();
2816        Ok(())
2817    }
2818
2819    /// A thread-local variable on Mach-O, which is a call.
2820    ///
2821    /// The slot the machine's thread load reads holds the address of the variable's descriptor
2822    /// there, `_v@TLVP` on x86-64 and `_v@TLVPPAGE` with `_v@TLVPPAGEOFF` on AArch64. The first
2823    /// word of the descriptor is the function that finds this thread's copy, and it takes the
2824    /// descriptor's address as its one argument and gives back the copy's address. That is the
2825    /// sequence clang writes on both machines.
2826    ///
2827    /// The call is built as an ordinary call through an address, so it costs what any call costs:
2828    /// everything the convention does not preserve is taken to be gone across it. Apple's function
2829    /// keeps more than that, all but the result and the two scratch registers on AArch64, and
2830    /// taking the fewer registers as gone would be faster. What this gives up is speed, and a
2831    /// function that reads a thread-local is no longer a leaf.
2832    fn thread_descriptor(
2833        &mut self,
2834        inst: Inst,
2835        symbol: Symbol,
2836        result: Value,
2837    ) -> Result<(), Unsupported> {
2838        let block = self.at.expect("a block is being filled");
2839        let span = self.source.span(inst);
2840        let gpr = self.gpr;
2841
2842        let descriptor = self.out.new_vreg(gpr);
2843        match self.selector.symbols.thread {
2844            Reach::Mode(name) => {
2845                let load = self.named(name);
2846                let mem = mir::Mem::thread(symbol);
2847                self.out.build(block, load).at(span).def(descriptor, gpr).mem(mem).finish();
2848            }
2849            Reach::Own(name) => {
2850                let load = self.named(name);
2851                let build = self.out.build(block, load).at(span);
2852                build.def(descriptor, gpr).symbol(symbol).finish();
2853            }
2854        }
2855        let finder = self.out.new_vreg(gpr);
2856        let word = (self.selector.abi.load)(Type::PTR).ok_or_else(|| self.unsupported(inst))?;
2857        let word = mir::Opcode::new(self.names.intern(word));
2858        let mem = mir::Mem::at(mir::Operand::read(descriptor, gpr));
2859        self.out.build(block, word).at(span).def(finder, gpr).mem(mem).finish();
2860
2861        let args = [abi::Passing { ty: Type::PTR, reg: descriptor, abi: Abi::default() }];
2862        let what = abi::Calling {
2863            callee: abi::Callee::Through(finder),
2864            args: &args,
2865            returns: &[Type::PTR],
2866            variadic: false,
2867            named: 1,
2868            at: span,
2869        };
2870        let made = abi::call(&mut self.out, block, &what, self.conv, self.selector.abi, self.names)
2871            .map_err(|refused| Unsupported::Call { inst, refused })?;
2872        let calls = &mut self.stack.calls;
2873        *calls = Some(calls.unwrap_or(0).max(made.outgoing));
2874        let &[reg] = &made.results[..] else { return Err(self.unsupported(inst)) };
2875        self.regs[result.index()] = Some(reg);
2876        Ok(())
2877    }
2878
2879    /// A thread-local variable on Windows, which is four loads and no call.
2880    ///
2881    /// `_tls_index` is this image's slot in the array of `.tls` copies the thread block holds at
2882    /// `%gs:88`, and the variable is as far into this thread's copy as it is into the section. The
2883    /// C runtime defines the index and the linker writes the offset. See [`crate::select::Indexed`] for
2884    /// the four instructions, which are the ones gcc writes.
2885    fn thread_indexed(
2886        &mut self,
2887        inst: Inst,
2888        symbol: Symbol,
2889        result: Value,
2890    ) -> Result<(), Unsupported> {
2891        let Some(indexed) = self.selector.symbols.indexed.as_ref() else {
2892            return Err(Unsupported::Unported { inst: Some(inst), what: Unported::Thread });
2893        };
2894        let block = self.at.expect("a block is being filled");
2895        let span = self.source.span(inst);
2896        let gpr = self.gpr;
2897
2898        let slot = self.out.new_vreg(gpr);
2899        let tls_index = self.names.intern("_tls_index");
2900        let index = self.named(indexed.index);
2901        self.out.build(block, index).at(span).def(slot, gpr).mem(mir::Mem::of(tls_index)).finish();
2902
2903        let array = self.out.new_vreg(gpr);
2904        let load = self.named(indexed.load);
2905        let at = mir::Mem::in_segment(indexed.segment, indexed.at);
2906        self.out.build(block, load).at(span).def(array, gpr).mem(at).finish();
2907
2908        let copy = self.out.new_vreg(gpr);
2909        let mem =
2910            mir::Mem::at(mir::Operand::read(array, gpr)).indexed(mir::Operand::read(slot, gpr), 8);
2911        self.out.build(block, load).at(span).def(copy, gpr).mem(mem).finish();
2912
2913        let reg = self.new_reg(result);
2914        let add = self.named(indexed.add);
2915        let mem = mir::Mem::section(mir::Operand::read(copy, gpr), symbol);
2916        self.out.build(block, add).at(span).def(reg, gpr).mem(mem).finish();
2917        Ok(())
2918    }
2919
2920    /// Refuses the thread pointer where it is not written, which is Mach-O. Apple keeps it in a
2921    /// different register from the one Linux does on both machines, and nothing written for it
2922    /// has been checked on one.
2923    fn threads_written(&self, inst: Inst) -> Result<(), Unsupported> {
2924        if self.elsewhere.described() || self.elsewhere.indexed() {
2925            return Err(Unsupported::Unported { inst: Some(inst), what: Unported::Thread });
2926        }
2927        Ok(())
2928    }
2929
2930    /// The front of this thread's block into `reg`.
2931    ///
2932    /// On x86-64 that is the one thing no instruction can work out: `%fs` is not a register a
2933    /// program can read, and what it points at is a word holding its own address, so reading
2934    /// through it at zero is how the address is come by. AArch64 keeps it in `tpidr_el0`, which
2935    /// `mrs` reads.
2936    fn read_thread_pointer(&mut self, block: mir::Block, span: Span, reg: mir::Reg) {
2937        let gpr = self.gpr;
2938        match self.selector.symbols.pointer {
2939            Pointer::Segment(name, segment) => {
2940                let load = self.named(name);
2941                let at = mir::Mem::in_segment(segment, 0);
2942                self.out.build(block, load).at(span).def(reg, gpr).mem(at).finish();
2943            }
2944            Pointer::Own(name) => {
2945                let read = self.named(name);
2946                self.out.build(block, read).at(span).def(reg, gpr).finish();
2947            }
2948        }
2949    }
2950
2951    /// `&&label`, GNU's address of a label, which is the same `lea` a global gets against a place
2952    /// in this same function.
2953    ///
2954    /// What the two have in common is the whole of the instruction: an address worked out from
2955    /// where the instruction is, which is what `(%rip)` means and is the only way this compiler
2956    /// reaches anything. What they do not have in common is what fills the four bytes in. A
2957    /// global is a name, so the number is a relocation and the linker writes it. A block is a
2958    /// place in this function, so both ends are in one section and the number is known as soon as
2959    /// the blocks have been laid out, which is why `rucc_asm` fills it in the way it fills in a
2960    /// jump rather than leaving a relocation behind.
2961    ///
2962    /// Nothing here says the block is one control can arrive at. That is said by the
2963    /// [`Opcode::IndirectBr`] that reads the address, which lists every block it can arrive at,
2964    /// and by nothing else: an address on its own is a number.
2965    fn block_address(&mut self, inst: Inst) -> Result<(), Unsupported> {
2966        let result = self.source[inst].first_result.ok_or_else(|| self.unsupported(inst))?;
2967        let Some(call) = self.source.successors(inst).next() else {
2968            return Err(self.unsupported(inst));
2969        };
2970        let block = self.at.expect("a block is being filled");
2971        let reg = self.new_reg(result);
2972        let span = self.source.span(inst);
2973        let opcode = self.named(self.selector.jumps.near);
2974        let mem = mir::Mem::block(self.out_block(call.block));
2975        self.out.build(block, opcode).at(span).def(reg, self.gpr).mem(mem).finish();
2976        Ok(())
2977    }
2978
2979    /// `goto *p`, GNU's computed goto, which is a jump through a register.
2980    ///
2981    /// Where it goes is not written here and cannot be. Every block it can arrive at is on the
2982    /// block this ends, the way every other arm is, and which of them the address holds is decided
2983    /// while the program runs. So this is one instruction with one operand, and the arms are
2984    /// copied across by [`Self::edges`] like anybody else's.
2985    fn indirect_branch(&mut self, inst: Inst) -> Result<(), Unsupported> {
2986        let data = &self.source[inst];
2987        let &address = self.source[data.args].first().ok_or_else(|| self.unsupported(inst))?;
2988        let reg = self.reg_of(address)?;
2989        let block = self.at.expect("a block is being filled");
2990        let span = self.source.span(inst);
2991        let name = self.selector.branch.indirect;
2992        let opcode = self.named(name);
2993        self.out.build(block, opcode).at(span).operand(mir::Operand::read(reg, self.gpr)).finish();
2994        Ok(())
2995    }
2996
2997    /// A `switch` on an index from zero up, as a jump through a table of this function.
2998    ///
2999    /// Every `switch` that reaches here is one `crate::switch` left behind on purpose: it has
3000    /// already checked the value is inside the table and taken the lowest case off it, so the
3001    /// operand is a 64 bit index, the cases are the values from zero up with gaps where the
3002    /// program had no case, and the default is only where those gaps go. What is written is the
3003    /// shape gcc writes for the same statement in position independent code:
3004    ///
3005    /// ```text
3006    /// leaq    table(%rip), %base
3007    /// movslq  (%base,%index,4), %offset
3008    /// addq    %base, %offset
3009    /// jmp     *%offset
3010    /// ```
3011    ///
3012    /// The table holds distances from itself to each arm rather than addresses, which is what
3013    /// lets it be filled in by the assembler with nothing left for a linker to do. Each cell is
3014    /// stored as the place of an arm among this block's successors, which [`Self::edges`] copies
3015    /// across in the IR's own order, the default first and then one per case. See
3016    /// [`mir::Table`] for why a place and not a block.
3017    fn jump_table(&mut self, inst: Inst) -> Result<(), Unsupported> {
3018        let data = &self.source[inst];
3019        let Extra::Switch(info) = data.extra else { return Err(self.unsupported(inst)) };
3020        let &index = self.source[data.args].first().ok_or_else(|| self.unsupported(inst))?;
3021        let ty = self.source[index].ty;
3022        if ty != Type::int(u64::BITS) {
3023            return Err(self.unsupported(inst));
3024        }
3025        let cases = self.source[self.source[info].cases].to_vec();
3026        let mut cells: Vec<u32> = Vec::new();
3027        for (arm, case) in cases.iter().enumerate() {
3028            let at = usize::try_from(case.signed(ty)).map_err(|_| self.unsupported(inst))?;
3029            if at >= cells.len() {
3030                cells.resize(at + 1, 0);
3031            }
3032            cells[at] = u32::try_from(arm + 1).map_err(|_| self.unsupported(inst))?;
3033        }
3034        let reg = self.reg_of(index)?;
3035        let block = self.at.expect("a block is being filled");
3036        let span = self.source.span(inst);
3037        let gpr = self.gpr;
3038        let table = u32::try_from(self.out.tables.len()).expect("fewer tables than that");
3039
3040        let jumps = self.selector.jumps;
3041
3042        let base = self.out.new_vreg(gpr);
3043        let near = self.named(jumps.near);
3044        self.out.build(block, near).at(span).def(base, gpr).mem(mir::Mem::table(table)).finish();
3045        let offset = self.out.new_vreg(gpr);
3046        let cell =
3047            mir::Mem::at(mir::Operand::read(base, gpr)).indexed(mir::Operand::read(reg, gpr), 4);
3048        let load = self.named(jumps.cell);
3049        self.out.build(block, load).at(span).def(offset, gpr).mem(cell).finish();
3050        // Two address on x86-64, for the reason `thread_pointer` gives.
3051        let to = self.out.new_vreg(gpr);
3052        let add = self.named(jumps.add);
3053        let written = mir::Operand::write(to, gpr);
3054        let written = if jumps.two_address { written.with(Constraint::Reuse(1)) } else { written };
3055        self.out
3056            .build(block, add)
3057            .at(span)
3058            .operand(written)
3059            .operand(mir::Operand::read(offset, gpr))
3060            .operand(mir::Operand::read(base, gpr))
3061            .finish();
3062        let jump = self.named(self.selector.branch.indirect);
3063        let jump =
3064            self.out.build(block, jump).at(span).operand(mir::Operand::read(to, gpr)).finish();
3065        self.out.tables.push(mir::Table { jump, cells });
3066        Ok(())
3067    }
3068
3069    /// `__builtin_setjmp`, which writes down where the function is so that a `__builtin_longjmp`
3070    /// somewhere else can bring control back here, and answers zero on the way past.
3071    ///
3072    /// Four words of the buffer, the three gcc writes and one of this compiler's own, and then the
3073    /// block ends: everything after the save in the IR block is put into a new machine IR block,
3074    /// and the address of that block is what went into the buffer. That is the whole reason the
3075    /// block is split here. An address points at a label, a machine IR block is the only thing in
3076    /// this representation that has one, and a save is in the middle of a block rather than at the
3077    /// end of one.
3078    ///
3079    /// # How the answer gets back
3080    ///
3081    /// Through the frame rather than through a register. The save writes a zero into a word of its
3082    /// own frame, puts the address of that word in the buffer, and the new block reads the word
3083    /// back. The restore writes a one through the address it finds in the buffer before it goes.
3084    /// So one load answers zero on the way past and one on the way back, and neither path has to
3085    /// agree with the other about a register.
3086    ///
3087    /// gcc does it the other way round, with a second block that sets the answer to one and is
3088    /// what the restore arrives at. That block is one nothing in the function jumps to, and a
3089    /// machine IR whose blocks are walked from the entry has nowhere to put such a thing: the
3090    /// allocator lays a function out in the line it is going to be emitted in, and a block no edge
3091    /// reaches is not in that line. The word in the frame costs eight bytes of stack and one load,
3092    /// and it needs nothing said anywhere about a block arrived at from outside.
3093    ///
3094    /// # What the allocator is told
3095    ///
3096    /// That every register it hands out is gone at the end of the first block. That is what makes
3097    /// the rest of the function right on the way back: control arrives from a `__builtin_longjmp`
3098    /// in some other function, and the only two registers that puts back are the stack pointer and
3099    /// the frame pointer, so anything this function still wants has to be in the frame those two
3100    /// reach. It is said with a write of every one of those registers, which is the same thing a
3101    /// call says about the registers a callee may destroy, on an instruction with nothing else on
3102    /// it so that the stores above are not caught up in it.
3103    fn saves_place(&mut self, inst: Inst) -> Result<(), Unsupported> {
3104        let data = &self.source[inst];
3105        let result = data.first_result.ok_or_else(|| self.unsupported(inst))?;
3106        let &buffer = self.source[data.args].first().ok_or_else(|| self.unsupported(inst))?;
3107        let span = self.source.span(inst);
3108        let buf = self.reg_of(buffer)?;
3109        let at = self.at.expect("a block is being filled");
3110        let gpr = self.gpr;
3111        let moves = self.selector.frame.moves(gpr).expect("a class the target says how to move");
3112        let store = self.named(moves.store);
3113        let load = self.named(moves.load);
3114        let lea = self.named(self.selector.frame.lea);
3115        let put = self.named(self.selector.frame.imm);
3116        let nothing =
3117            self.selector.frame.pad.expect("a target with an instruction that does nothing");
3118        let nothing = self.named(nothing);
3119        self.stack.saves_place = true;
3120        let answer = self.answer_slot();
3121        let back = self.out.create_block();
3122
3123        // The zero this answers with, into the word a restore writes a one into.
3124        let zero = self.out.new_vreg(gpr);
3125        self.out.build(at, put).at(span).def(zero, gpr).imm(0).finish();
3126        let mem = self.frame_mem();
3127        let made = self.out.build(at, store).at(span).uses(zero, gpr).mem(mem).finish();
3128        self.stack.addresses.push((made, answer));
3129
3130        // The four words: where that word is, where control comes back to, and the two registers
3131        // the restore puts back.
3132        let found = self.frame_address(at, answer);
3133        self.write_word(at, span, store, found, buf, JUMP_ANSWER);
3134        let pc = self.out.new_vreg(gpr);
3135        self.out.build(at, lea).at(span).def(pc, gpr).mem(mir::Mem::block(back)).finish();
3136        self.write_word(at, span, store, pc, buf, JUMP_PC);
3137        let frame = mir::Reg::physical(self.conv.frame_pointer);
3138        self.write_word(at, span, store, frame, buf, JUMP_FRAME);
3139        let stack = mir::Reg::physical(self.conv.stack_pointer);
3140        self.write_word(at, span, store, stack, buf, JUMP_STACK);
3141
3142        // Nothing is in a register past this point, which is what the rest of the function is
3143        // allowed to assume about the way back in.
3144        let gone = self.across_jump();
3145        let mut build = self.out.build(at, nothing).at(span);
3146        for (reg, class) in gone {
3147            build = build.operand(mir::Operand::write(reg, class));
3148        }
3149        build.finish();
3150
3151        // And the rest of the block, which is the block the address above was of.
3152        *self.out.succs_mut(at) = vec![mir::BlockCall::to(back)];
3153        self.at = Some(back);
3154        let reg = self.new_reg(result);
3155        let mem = self.frame_mem();
3156        let made = self.out.build(back, load).at(span).def(reg, gpr).mem(mem).finish();
3157        self.stack.addresses.push((made, answer));
3158        Ok(())
3159    }
3160
3161    /// `__builtin_longjmp`, which reads a buffer a `__builtin_setjmp` filled in and goes there.
3162    ///
3163    /// Everything comes out of the buffer before anything is put back, and the four registers it
3164    /// comes out into are physical ones rather than values the allocator places. Both of those are
3165    /// about the same moment. The stack pointer is one of the things being put back, a value the
3166    /// allocator sent to the stack is reached through the stack pointer, and between the
3167    /// instruction that moves it and the jump there is no stack this function owns any more. A
3168    /// register named outright is a register nothing reloads into and nothing else is in, which is
3169    /// the only way to hold something across that moment.
3170    ///
3171    /// Four of them because that is how many things are in the air at once: where to go, the frame
3172    /// pointer to put back, the one the matching save is to answer with, and one register used
3173    /// twice, first for the address that one is written through and then for the stack pointer.
3174    ///
3175    /// Nothing after this in the block is reached. The marker is not a terminator, for the reason
3176    /// `spec/08-ir.md` gives, so the block goes on and whatever the front end wrote after it is
3177    /// written out and never run.
3178    fn comes_back(&mut self, inst: Inst) -> Result<(), Unsupported> {
3179        let data = &self.source[inst];
3180        let &buffer = self.source[data.args].first().ok_or_else(|| self.unsupported(inst))?;
3181        let span = self.source.span(inst);
3182        let buf = self.reg_of(buffer)?;
3183        let at = self.at.expect("a block is being filled");
3184        let gpr = self.gpr;
3185        let moves = self.selector.frame.moves(gpr).expect("a class the target says how to move");
3186        let load = self.named(moves.load);
3187        let store = self.named(moves.store);
3188        let mov = self.named(moves.mov);
3189        let put = self.named(self.selector.frame.imm);
3190        let jump = self.named(self.selector.branch.indirect);
3191
3192        let held = self.jump_regs();
3193        if held.len() < JUMP_REGS {
3194            return Err(self.unsupported(inst));
3195        }
3196        let pc = mir::Reg::physical(held[0]);
3197        let frame = mir::Reg::physical(held[1]);
3198        let spare = mir::Reg::physical(held[2]);
3199        let one = mir::Reg::physical(held[3]);
3200
3201        self.read_word(at, span, load, pc, buf, JUMP_PC);
3202        self.read_word(at, span, load, frame, buf, JUMP_FRAME);
3203        self.read_word(at, span, load, spare, buf, JUMP_ANSWER);
3204
3205        // What the matching save answers with, written through the address that came out of the
3206        // buffer, because the word it goes in is in the other function's frame and this one has no
3207        // way of knowing where that is.
3208        self.out.build(at, put).at(span).def(one, gpr).imm(1).finish();
3209        let mem = mir::Mem::at(mir::Operand::read(spare, gpr));
3210        self.out.build(at, store).at(span).uses(one, gpr).mem(mem).finish();
3211
3212        // The stack last of the four, so that the register the buffer is reached through is done
3213        // with before the stack it may have been spilled to stops being this function's.
3214        self.read_word(at, span, load, spare, buf, JUMP_STACK);
3215        let stack = mir::Reg::physical(self.conv.stack_pointer);
3216        self.copy(at, span, mov, stack, spare);
3217        let base = mir::Reg::physical(self.conv.frame_pointer);
3218        self.copy(at, span, mov, base, frame);
3219
3220        // And the jump, which reads the two registers just put back as well as the address it
3221        // goes through. Neither of those is printed, because the target's spelling of an indirect
3222        // jump has one argument and it is the first one read. They are there because the code
3223        // control arrives at reaches its frame through them, and because without them the two
3224        // instructions above write registers nothing reads: a scheduler is then free to put the
3225        // jump in front of them, and at `-O2` it does.
3226        self.out
3227            .build(at, jump)
3228            .at(span)
3229            .operand(mir::Operand::read(pc, gpr))
3230            .operand(mir::Operand::read(stack, gpr))
3231            .operand(mir::Operand::read(base, gpr))
3232            .finish();
3233        Ok(())
3234    }
3235
3236    /// One word of the buffer of a `__builtin_setjmp`, written from a register.
3237    fn write_word(
3238        &mut self,
3239        at: mir::Block,
3240        span: Span,
3241        store: mir::Opcode,
3242        from: mir::Reg,
3243        buf: mir::Reg,
3244        word: i32,
3245    ) {
3246        let mem = mir::Mem::at(mir::Operand::read(buf, self.gpr)).plus(word);
3247        self.out.build(at, store).at(span).uses(from, self.gpr).mem(mem).finish();
3248    }
3249
3250    /// One word of that buffer, read back into a register.
3251    fn read_word(
3252        &mut self,
3253        at: mir::Block,
3254        span: Span,
3255        load: mir::Opcode,
3256        into: mir::Reg,
3257        buf: mir::Reg,
3258        word: i32,
3259    ) {
3260        let mem = mir::Mem::at(mir::Operand::read(buf, self.gpr)).plus(word);
3261        self.out.build(at, load).at(span).def(into, self.gpr).mem(mem).finish();
3262    }
3263
3264    /// One register into another, which is the one shape of instruction the builder has no word
3265    /// for because neither operand is a definition of a value or a read of memory.
3266    fn copy(
3267        &mut self,
3268        at: mir::Block,
3269        span: Span,
3270        mov: mir::Opcode,
3271        into: mir::Reg,
3272        from: mir::Reg,
3273    ) {
3274        self.out
3275            .build(at, mov)
3276            .at(span)
3277            .operand(mir::Operand::write(into, self.gpr))
3278            .operand(mir::Operand::read(from, self.gpr))
3279            .finish();
3280    }
3281
3282    /// The word a `__builtin_setjmp` in this function answers with, asked for once and kept.
3283    fn answer_slot(&mut self) -> usize {
3284        match self.answer {
3285            Some(index) => index,
3286            None => {
3287                let index = self.stack.locals.len();
3288                self.stack.locals.push(Local { size: JUMP_WORD, align: JUMP_WORD });
3289                self.answer = Some(index);
3290                index
3291            }
3292        }
3293    }
3294
3295    /// An address in this function's frame with nothing in its displacement, which is what an
3296    /// instruction reaching one of its stack objects is written with until [`crate::finish`] knows
3297    /// where the object is.
3298    fn frame_mem(&self) -> mir::Mem {
3299        mir::Mem::at(mir::Operand::read(mir::Reg::physical(self.conv.stack_pointer), self.gpr))
3300    }
3301
3302    /// Every register the allocator hands out, which is what a `__builtin_setjmp` destroys.
3303    ///
3304    /// Both files, since a `double` live across a save has the same problem an integer does. The
3305    /// two registers a frame is reached through are not here: the restore puts both of them back,
3306    /// which is the whole of what it puts back, and a function whose frame pointer was destroyed
3307    /// by its own save would have nothing left to find its caller with.
3308    fn across_jump(&self) -> Vec<(mir::Reg, RegClass)> {
3309        let mut gone = Vec::new();
3310        for &reg in self.conv.int_order {
3311            if reg == self.conv.stack_pointer || reg == self.conv.frame_pointer {
3312                continue;
3313            }
3314            gone.push((mir::Reg::physical(reg), self.gpr));
3315        }
3316        for &reg in self.conv.sse_order {
3317            gone.push((mir::Reg::physical(reg), self.conv.sse_class));
3318        }
3319        gone
3320    }
3321
3322    /// The registers a `__builtin_longjmp` may hold things in while it puts a frame back.
3323    ///
3324    /// The ones the allocator hands out, less the two a frame is reached through. The scratch
3325    /// registers are not among them on purpose: the rewriter writes a reload into one of those
3326    /// wherever it likes, and one of these has to survive from the load that fills it to the
3327    /// instruction that reads it however many instructions apart those are.
3328    fn jump_regs(&self) -> Vec<PhysReg> {
3329        self.conv
3330            .int_order
3331            .iter()
3332            .copied()
3333            .filter(|&reg| {
3334                reg != self.conv.stack_pointer
3335                    && reg != self.conv.frame_pointer
3336                    && !self.selector.scratch.contains(&reg)
3337            })
3338            .collect()
3339    }
3340
3341    /// A machine opcode of this target from the name the target gives it.
3342    fn named(&mut self, name: &str) -> mir::Opcode {
3343        mir::Opcode::new(self.names.intern(&format!("{}{name}", self.selector.prefix())))
3344    }
3345
3346    /// `__builtin_frame_address` and `__builtin_return_address`, which are a walk up the chain of
3347    /// saved frame pointers and then one thing read at the end of it.
3348    ///
3349    /// Every frame that kept a frame pointer holds the caller's at the address the register points
3350    /// at, and the address that frame returns to one word above that, which is where the call
3351    /// instruction put it and where the prologue's push left it. So the walk is a load through the
3352    /// register for each link, the frame address is wherever the walk stopped, and the return
3353    /// address is one more load from a word above it. gcc 16.2.0 writes exactly this, measured on
3354    /// x86-64 at `-O2` for depths zero to three of both builtins.
3355    ///
3356    /// The function is given a frame pointer because of this, which is what [`Stack::walks_frames`]
3357    /// carries out to the layout. A depth of zero needs it as the answer and every depth above zero
3358    /// needs it as the start, so there is no case here where it is not wanted.
3359    ///
3360    /// How far the chain actually reaches is the program's business and not this one's. A caller
3361    /// compiled without a frame pointer has no link in it for the walk to follow, so a depth above
3362    /// zero is a promise about how the whole program was built. That is why gcc documents a nonzero
3363    /// depth as unsafe rather than as an answer, and why the depth is refused above a limit in
3364    /// `check/builtin/frame.rs` rather than walked as far as it says.
3365    fn frames(&mut self, inst: Inst) -> Result<(), Unsupported> {
3366        let data = &self.source[inst];
3367        let Extra::Depth(depth) = data.extra else { return Err(self.unsupported(inst)) };
3368        let result = data.first_result.ok_or_else(|| self.unsupported(inst))?;
3369        let returning = data.opcode == Opcode::ReturnAddress;
3370        let block = self.at.expect("a block is being filled");
3371        let span = self.source.span(inst);
3372        let moves =
3373            self.selector.frame.moves(self.gpr).expect("a class the target says how to move");
3374        let load = self.named(moves.load);
3375        self.stack.walks_frames = true;
3376
3377        // Where the walk is up to. The frame pointer to begin with, and the register the last load
3378        // wrote after that.
3379        let reg = self.new_reg(result);
3380        let mut base = mir::Reg::physical(self.conv.frame_pointer);
3381        for link in 0..depth {
3382            // The last load of a walk that is looking for a frame writes the answer itself, which
3383            // is what keeps a walk of so many links that many instructions and not one more.
3384            let ends_here = link + 1 == depth && !returning;
3385            let next = if ends_here { reg } else { self.out.new_vreg(self.gpr) };
3386            let at = mir::Mem::at(mir::Operand::read(base, self.gpr));
3387            self.out.build(block, load).at(span).def(next, self.gpr).mem(at).finish();
3388            base = next;
3389        }
3390
3391        if returning {
3392            let up = i32::try_from(self.conv.return_address).expect("a word above the frame");
3393            let at = mir::Mem::at(mir::Operand::read(base, self.gpr)).plus(up);
3394            self.out.build(block, load).at(span).def(reg, self.gpr).mem(at).finish();
3395        } else if depth == 0 {
3396            // The one case with no load in it at all: the frame this function is running in is the
3397            // register itself, and a physical register is not one the allocator hands out, so the
3398            // answer is a copy of it.
3399            let mov = self.named(moves.mov);
3400            self.out
3401                .build(block, mov)
3402                .at(span)
3403                .operand(mir::Operand::write(reg, self.gpr))
3404                .operand(mir::Operand::read(base, self.gpr))
3405                .finish();
3406        }
3407        Ok(())
3408    }
3409
3410    /// `__builtin_thread_pointer`, which is the front of the block [`Self::thread_address`] adds
3411    /// an offset to.
3412    ///
3413    /// The same one instruction, on its own this time and with nothing to add to it. A program
3414    /// writes this when what it wants is a number that is different in every thread and cheap to
3415    /// come by, rather than a variable of its own in the block, so there is no relocation here and
3416    /// no name for the link to resolve.
3417    fn thread_pointer(&mut self, inst: Inst) -> Result<(), Unsupported> {
3418        self.threads_written(inst)?;
3419        let result = self.source[inst].first_result.ok_or_else(|| self.unsupported(inst))?;
3420        let block = self.at.expect("a block is being filled");
3421        let span = self.source.span(inst);
3422        let reg = self.new_reg(result);
3423        self.read_thread_pointer(block, span, reg);
3424        Ok(())
3425    }
3426
3427    /// What a named machine register holds, which is `register long x asm ("rbx");`.
3428    ///
3429    /// One move out of that register, with the register named as itself the way a register a
3430    /// template wrote is named, which is [`Self::itself`] and is the thing #1653 built. What it
3431    /// buys here is what it buys there: the register is part of the instruction the allocator
3432    /// sees, so it is a use the allocator will not have written over first, and the value goes
3433    /// into an ordinary one of its own that everything downstream reads.
3434    ///
3435    /// The whole sixty four bits are moved whatever the type is, because the register is that
3436    /// wide and a narrower type reads the low end of the copy, which is the same low end. A type
3437    /// wider than the register is refused, since there is no register holding it to read. On
3438    /// AArch64 a float may be kept in a vector register, `register double x asm ("d8");`, and it is
3439    /// moved out of that file the same way.
3440    ///
3441    /// A name the machine has not got is refused too, and is the only thing that can be wrong
3442    /// with the string: which register a name means is this machine's question and this is where
3443    /// the question is asked, at the same table `asm` asks about clobbers at. The sigil gcc
3444    /// allows in front of it is taken off here, because what the name is written with is syntax.
3445    fn register_value(&mut self, inst: Inst) -> Result<(), Unsupported> {
3446        let Extra::Symbol(symbol) = self.source[inst].extra else {
3447            return Err(self.unsupported(inst));
3448        };
3449        let result = self.source[inst].first_result.ok_or_else(|| self.unsupported(inst))?;
3450        let ty = self.source[result].ty;
3451        let bits = if ty.is_ptr() { ADDRESS_BITS } else { ty.bits() };
3452        if bits > ADDRESS_BITS {
3453            return Err(self.unsupported(inst));
3454        }
3455        let spelled = self.names.resolve(symbol).to_owned();
3456        let bare = spelled.strip_prefix('%').unwrap_or(&spelled);
3457        let named = if self.on_aarch64() {
3458            aarch64::named(bare)
3459        } else if self.class_of(ty) != self.gpr {
3460            return Err(self.unsupported(inst));
3461        } else {
3462            x86_64::gpr_named(bare).map(|(reg, _)| (reg, self.gpr))
3463        };
3464        let Some((held, file)) = named else {
3465            return Err(Unsupported::Register { inst, name: spelled });
3466        };
3467        // A float in a general purpose register, or a number in a vector one, is a register the
3468        // machine has holding a type that is not kept there, and would need a move between the
3469        // files that nothing here makes yet.
3470        if on_x87(ty) || self.class_of(ty) != file {
3471            return Err(self.unsupported(inst));
3472        }
3473        let block = self.at.expect("a block is being filled");
3474        let span = self.source.span(inst);
3475        let mov = self.selector.frame.moves(file).expect("a class the target says how to move").mov;
3476        let mov = self.named(mov);
3477        let into = self.new_reg(result);
3478        self.out
3479            .build(block, mov)
3480            .at(span)
3481            .operand(mir::Operand::write(into, file))
3482            .operand(
3483                mir::Operand::read(mir::Reg::physical(held), file).with(Constraint::Fixed(held)),
3484            )
3485            .finish();
3486        Ok(())
3487    }
3488
3489    /// A conversion that converts nothing: the result is the operand under another type.
3490    ///
3491    /// `ptrtoint` and `inttoptr` at one width are the whole of this. An address on this machine is
3492    /// an integer as wide as the machine addresses, so a cast between the two changes what the
3493    /// type system calls the value and changes nothing about the value, and the register holding
3494    /// it is the register that already held it. The front end never writes either of them at any
3495    /// other width, because it widens or narrows around the cast rather than through it, so the
3496    /// two widths disagreeing here means the IR came from somewhere else and is refused rather
3497    /// than guessed at.
3498    ///
3499    /// Reading the operand first is what materializes it when it is a constant, which is the case
3500    /// that matters: a null pointer is an `inttoptr` of zero, and that zero has to reach a
3501    /// register before anything can call it an address.
3502    fn rename(&mut self, inst: Inst) -> Result<(), Unsupported> {
3503        let data = &self.source[inst];
3504        let [arg] = self.source[data.args] else { return Err(self.unsupported(inst)) };
3505        let result = data.first_result.ok_or_else(|| self.unsupported(inst))?;
3506        if !self.is_address_width(self.source[arg].ty)
3507            || !self.is_address_width(self.source[result].ty)
3508        {
3509            return Err(self.unsupported(inst));
3510        }
3511        let reg = self.reg_of(arg)?;
3512        self.regs[result.index()] = Some(reg);
3513        Ok(())
3514    }
3515
3516    /// One barrier, which on this machine is one instruction at the strongest ordering and no
3517    /// instruction at all at every other one.
3518    ///
3519    /// x86-64 is total store order, so the only reordering the machine does is a store followed by
3520    /// a load of a different address, and the only ordering that forbids that is sequential
3521    /// consistency. An acquire, a release and an acquire release fence are therefore already true
3522    /// of every program running here, and what a program wanted from writing one is that the
3523    /// compiler not move memory accesses across it. The optimizer has finished by the time this
3524    /// runs and nothing below reorders one access past another, so the constraint is already
3525    /// discharged and there is nothing to write.
3526    ///
3527    /// The strongest one is `mfence`, which is what gcc 16.2.0 writes for
3528    /// `__atomic_thread_fence(__ATOMIC_SEQ_CST)` and for `__sync_synchronize`. A locked instruction
3529    /// on the stack is faster on most parts and is what some compilers write instead; it is also a
3530    /// write to memory the program did not ask for, and the plain barrier is the one that says what
3531    /// it means.
3532    ///
3533    /// Written here by name rather than by a rule, for the same reason a `lea` of a symbol is:
3534    /// there is nothing in a barrier that a proof over bitvectors could discharge. It computes
3535    /// nothing, so there is no equality to state, and what makes it the right answer is the memory
3536    /// model, which the rule language cannot talk about.
3537    fn barrier(&mut self, inst: Inst) -> Result<(), Unsupported> {
3538        let Extra::Order(order) = self.source[inst].extra else {
3539            return Err(self.unsupported(inst));
3540        };
3541        // AArch64 is not total store order, so every ordering above relaxed is an instruction
3542        // there. An acquire fence only has to keep later accesses after earlier loads, which is
3543        // `dmb ishld`, and everything stronger is the full `dmb ish` gcc writes for it.
3544        let name = match order {
3545            MemOrder::NotAtomic | MemOrder::Relaxed => return Ok(()),
3546            MemOrder::Acquire if self.on_aarch64() => "fence_acquire",
3547            _ if self.on_aarch64() => self.selector.fence,
3548            MemOrder::SeqCst => self.selector.fence,
3549            _ => return Ok(()),
3550        };
3551        let block = self.at.expect("a block is being filled");
3552        let span = self.source.span(inst);
3553        let fence = self.named(name);
3554        self.out.build(block, fence).at(span).finish();
3555        Ok(())
3556    }
3557
3558    /// The instruction a program stops on, which is one byte pair and no operands.
3559    ///
3560    /// `ud2` is an opcode the manual promises will never be given a meaning, so a processor that
3561    /// reaches it raises the fault for an instruction it does not know, and on Linux that arrives
3562    /// at the program as `SIGILL`. That is what `__builtin_trap` is for: a stop that cannot be
3563    /// caught by anything the program installed for an ordinary error, cannot be returned from,
3564    /// and leaves the address of the fault in the core file.
3565    ///
3566    /// Why not a call to `abort`. It is two bytes against a call and a relocation, it needs no
3567    /// library, and it works in the places this one is written most, which are a kernel and a
3568    /// freestanding program that has no `abort` to call. gcc 16.2.0 writes `ud2` here too.
3569    fn trap(&mut self, inst: Inst) {
3570        let block = self.at.expect("a block is being filled");
3571        let span = self.source.span(inst);
3572        let stop = self.named(self.selector.trap);
3573        self.out.build(block, stop).at(span).finish();
3574    }
3575
3576    /// One hint that an address is about to be used, which is one instruction and no promise.
3577    ///
3578    /// Four instructions on this machine and the locality picks between them, which is what the
3579    /// number means: how much of the data will still be wanted after the access. None of it wanted
3580    /// is `prefetchnta`, which brings the line in without keeping it, and all of it wanted is
3581    /// `prefetcht0`, which brings it as close as the machine can. The two in between are the levels
3582    /// between those. Measured against gcc 16.2.0 on x86-64 rather than read off the manual: zero
3583    /// gives `prefetchnta`, one `prefetcht2`, two `prefetcht1` and three `prefetcht0`.
3584    ///
3585    /// Whether the access will write is not read on x86-64, and that is the machine rather than an
3586    /// omission. The write hint is `prefetchw`, which is not in the base instruction set, and gcc
3587    /// writes it only when the command line said the part has it. So a prefetch for a write is the
3588    /// same instruction as a prefetch for a read, which is what gcc 16.2.0 writes without
3589    /// `-mprfchw`. AArch64 has it in the base set, so there a write picks the four `pst` forms of
3590    /// `prfm` in place of the `pld` ones, at the same levels.
3591    ///
3592    /// The address goes in the addressing mode rather than in an operand, the way a store's does.
3593    /// It is built here as the plainest one there is, a register and nothing else, because what
3594    /// arrives is a value and folding an addition into the mode is a rule's job and no rule reaches
3595    /// this instruction. An address the program computed is therefore one `lea` or one add in front
3596    /// of this, which is what it would have been for the load the hint is about anyway.
3597    fn hint(&mut self, inst: Inst) -> Result<(), Unsupported> {
3598        let Extra::Prefetch(hint) = self.source[inst].extra else {
3599            return Err(self.unsupported(inst));
3600        };
3601        let args: Vec<Value> = self.source[self.source[inst].args].to_vec();
3602        let [address] = args[..] else { return Err(self.unsupported(inst)) };
3603        // AArch64 has the write hint in the base instruction set, and gcc 16.2.0 writes it there.
3604        let write = hint.write && self.on_aarch64();
3605        let name = match (hint.locality, write) {
3606            (0, false) => "prefetch_nta",
3607            (1, false) => "prefetch_t2",
3608            (2, false) => "prefetch_t1",
3609            (PrefetchHint::MOST, false) => "prefetch_t0",
3610            (0, true) => "prefetch_w_nta",
3611            (1, true) => "prefetch_w_t2",
3612            (2, true) => "prefetch_w_t1",
3613            (PrefetchHint::MOST, true) => "prefetch_w_t0",
3614            // Nothing else exists. The checker reads a locality outside the range as zero and the
3615            // verifier refuses one that got here another way, so this is a hint that was built
3616            // rather than checked, and the safe answer for a hint is to write no instruction.
3617            _ => return Err(self.unsupported(inst)),
3618        };
3619        let base = self.reg_of(address)?;
3620        let block = self.at.expect("a block is being filled");
3621        let opcode = self.named(name);
3622        self.out
3623            .build(block, opcode)
3624            .at(self.source.span(inst))
3625            .mem(mir::Mem::at(mir::Operand::read(base, self.gpr)))
3626            .finish();
3627        Ok(())
3628    }
3629
3630    /// One compare and exchange, which is the instruction every other atomic on this machine is
3631    /// built out of.
3632    ///
3633    /// What the IR asks for is: read what is at an address, compare it against a value the program
3634    /// expected, put a second value there if the two were equal, and say both what was read and
3635    /// whether the exchange happened. The machine has exactly that instruction, and the `lock` in
3636    /// front of it is what makes the whole of it one step as far as every other processor is
3637    /// concerned.
3638    ///
3639    /// The ordering is not read here, and that is the memory model rather than an omission. A
3640    /// locked instruction on x86-64 is a full barrier whatever the program asked for, so a relaxed
3641    /// compare and exchange and a sequentially consistent one are the same instruction, and there
3642    /// is nothing weaker to emit for the weaker orderings. The failure ordering is not read for the
3643    /// same reason.
3644    ///
3645    /// The two values it produces are why this is written by name. The one the program compares
3646    /// against and the one it gets back are both `rax`, which the instruction reads and writes
3647    /// without being told, and the table says so with a fixed constraint at each end rather than
3648    /// leaving the allocator to find out. The second value is the byte behind it, which is the zero
3649    /// flag read out by a `sete`, and it is a definition of the same instruction so that the
3650    /// allocator knows the two are live together and never gives the byte the register the answer
3651    /// is in.
3652    fn exchange(&mut self, inst: Inst) -> Result<(), Unsupported> {
3653        let args: Vec<Value> = self.source[self.source[inst].args].to_vec();
3654        let results: Vec<Value> = self.source[inst].results().collect();
3655        let [addr, expected, desired] = args[..] else { return Err(self.unsupported(inst)) };
3656        let [old, exchanged] = results[..] else { return Err(self.unsupported(inst)) };
3657        if self.on_aarch64() {
3658            return self.exchange_a64(inst, [addr, expected, desired], [old, exchanged]);
3659        }
3660
3661        // A value the machine can compare in one instruction, which is an integer or an address at
3662        // one of the four widths it has a compare and exchange for. Anything else is a type this
3663        // has no instruction for rather than a program that is wrong, and the front end refuses it
3664        // before ever getting here.
3665        let ty = self.source[old].ty;
3666        let bits = if ty.is_ptr() { ADDRESS_BITS } else { ty.bits() };
3667        if (!ty.is_int() && !ty.is_ptr()) || !matches!(bits, 8 | 16 | 32 | 64) {
3668            return Err(self.unsupported(inst));
3669        }
3670
3671        let base = self.reg_of(addr)?;
3672        let want = self.reg_of(expected)?;
3673        let put = self.reg_of(desired)?;
3674        let got = self.new_reg(old);
3675        let flag = self.new_reg(exchanged);
3676
3677        let name = format!("cmpxchg_{bits}");
3678        let descs = self.selector.operands(&name).ok_or_else(|| self.unsupported(inst))?;
3679        let block = self.at.expect("a block is being filled");
3680        let opcode = self.named(&name);
3681        let (span, flags) = (self.source.span(inst), self.carried(inst));
3682        let mut build = self.out.build(block, opcode).at(span).flags(flags);
3683        for (desc, reg) in descs.iter().zip([got, flag, want, put]) {
3684            let operand = mir::Operand {
3685                reg,
3686                class: desc.class,
3687                role: desc.role,
3688                constraint: desc.constraint,
3689            };
3690            build = build.operand(operand);
3691        }
3692        build.mem(mir::Mem::at(mir::Operand::read(base, self.gpr))).finish();
3693        Ok(())
3694    }
3695
3696    /// One read modify write, for the three operations this machine does in a single instruction.
3697    ///
3698    /// What the IR asks for is: read what is at an address, do something to it, put the answer back,
3699    /// say what was there before, and let nothing get between the three steps. The machine has
3700    /// `xchg` for putting a value there and `lock xadd` for adding one, and both leave what they
3701    /// found in the register the operand arrived in, which is why the value that comes back and the
3702    /// value that went in are one register here.
3703    ///
3704    /// A subtraction is the add over the negated operand, which is right at every width because the
3705    /// machine's arithmetic wraps and negating then adding is subtracting in two's complement
3706    /// whatever the operands were. The negate is a separate instruction in front, over a register of
3707    /// its own, so that the value the program handed over is not the one written on: an operand may
3708    /// be live after this and a program that read it again would read the negation.
3709    ///
3710    /// The ordering is not read, for the reason the compare and exchange beside this does not read
3711    /// it. `xchg` with memory locks the bus whether it is asked to or not and `lock xadd` is asked
3712    /// to, so both are full barriers on this machine and there is nothing weaker to fall to.
3713    ///
3714    /// Eight of the other ten never arrive, because `crate::retry` turned each of them into a loop
3715    /// around a compare and exchange before anything here saw it. The two that do arrive are the
3716    /// ones on floating values, and they are refused: a compare and exchange of a float wants the
3717    /// value carried through an integer of the same width, and an eighty bit float has no such
3718    /// width. Neither family of builtins can write one yet either, so a program that reaches this
3719    /// refusal is a program that reached an unimplemented builtin first.
3720    fn modify(&mut self, inst: Inst) -> Result<(), Unsupported> {
3721        let Extra::Rmw(op, _) = self.source[inst].extra else {
3722            return Err(self.unsupported(inst));
3723        };
3724        let args: Vec<Value> = self.source[self.source[inst].args].to_vec();
3725        let [addr, operand] = args[..] else { return Err(self.unsupported(inst)) };
3726        let old = self.source[inst].first_result.ok_or_else(|| self.unsupported(inst))?;
3727
3728        // A value the machine can exchange in one instruction, which is an integer at one of the
3729        // four widths it has these for. A pointer arrives as an address, so it is an integer by the
3730        // time it is here, and anything else is a type this has no instruction for.
3731        let ty = self.source[old].ty;
3732        if !ty.is_int() || !matches!(ty.bits(), 8 | 16 | 32 | 64) {
3733            return Err(self.unsupported(inst));
3734        }
3735        if self.on_aarch64() {
3736            return self.modify_a64(inst, op, [addr, operand], old);
3737        }
3738        let name = match op {
3739            RmwOp::Xchg => format!("xchg_{}", ty.bits()),
3740            RmwOp::Add | RmwOp::Sub => format!("xadd_{}", ty.bits()),
3741            _ => return Err(self.unsupported(inst)),
3742        };
3743
3744        let base = self.reg_of(addr)?;
3745        let mut put = self.reg_of(operand)?;
3746        let block = self.at.expect("a block is being filled");
3747        let span = self.source.span(inst);
3748        if op == RmwOp::Sub {
3749            let negated = self.out.new_vreg(self.gpr);
3750            let negate = self.named(&format!("neg_r_{}", ty.bits()));
3751            let descs = self
3752                .selector
3753                .operands(&format!("neg_r_{}", ty.bits()))
3754                .ok_or_else(|| self.unsupported(inst))?;
3755            let mut build = self.out.build(block, negate).at(span);
3756            for (desc, reg) in descs.iter().zip([negated, put]) {
3757                build = build.operand(mir::Operand {
3758                    reg,
3759                    class: desc.class,
3760                    role: desc.role,
3761                    constraint: desc.constraint,
3762                });
3763            }
3764            build.finish();
3765            put = negated;
3766        }
3767
3768        let got = self.new_reg(old);
3769        let descs = self.selector.operands(&name).ok_or_else(|| self.unsupported(inst))?;
3770        let opcode = self.named(&name);
3771        let flags = self.carried(inst);
3772        let mut build = self.out.build(block, opcode).at(span).flags(flags);
3773        for (desc, reg) in descs.iter().zip([got, put]) {
3774            build = build.operand(mir::Operand {
3775                reg,
3776                class: desc.class,
3777                role: desc.role,
3778                constraint: desc.constraint,
3779            });
3780        }
3781        build.mem(mir::Mem::at(mir::Operand::read(base, self.gpr))).finish();
3782        Ok(())
3783    }
3784
3785    /// The width an AArch64 atomic works at, which is an integer or an address of one of the four
3786    /// widths the exclusive loads and stores have. Anything else is refused.
3787    fn atomic_bits(&self, inst: Inst, ty: Type) -> Result<u32, Unsupported> {
3788        let bits = if ty.is_ptr() { ADDRESS_BITS } else { ty.bits() };
3789        if (!ty.is_int() && !ty.is_ptr()) || !matches!(bits, 8 | 16 | 32 | 64) {
3790            return Err(self.unsupported(inst));
3791        }
3792        Ok(bits)
3793    }
3794
3795    /// One instruction by name, with its operands in the order the table lists them.
3796    fn written_as(&mut self, inst: Inst, name: &str, regs: &[mir::Reg]) -> Result<(), Unsupported> {
3797        let descs = self.selector.operands(name).ok_or_else(|| self.unsupported(inst))?;
3798        if descs.len() != regs.len() {
3799            return Err(self.unsupported(inst));
3800        }
3801        let block = self.at.expect("a block is being filled");
3802        let opcode = self.named(name);
3803        let (span, flags) = (self.source.span(inst), self.carried(inst));
3804        let mut build = self.out.build(block, opcode).at(span).flags(flags);
3805        for (desc, &reg) in descs.iter().zip(regs) {
3806            build = build.operand(mir::Operand {
3807                reg,
3808                class: desc.class,
3809                role: desc.role,
3810                constraint: desc.constraint,
3811            });
3812        }
3813        build.finish();
3814        Ok(())
3815    }
3816
3817    /// An acquiring load or a releasing store on AArch64, which is `ldar` or `stlr`.
3818    ///
3819    /// Only a relaxed access became the plain one above this, so what arrives is acquire or
3820    /// stronger for a load and release or stronger for a store. `ldar` and `stlr` are also
3821    /// sequentially consistent with each other, which is why the strongest ordering needs no fence
3822    /// on either side, and is what gcc 16.2.0 writes for all of them.
3823    fn ordered(&mut self, inst: Inst) -> Result<(), Unsupported> {
3824        let args: Vec<Value> = self.source[self.source[inst].args].to_vec();
3825        if self.source[inst].opcode == Opcode::AtomicLoad {
3826            let [addr] = args[..] else { return Err(self.unsupported(inst)) };
3827            let result = self.source[inst].first_result.ok_or_else(|| self.unsupported(inst))?;
3828            let bits = self.atomic_bits(inst, self.source[result].ty)?;
3829            let base = self.reg_of(addr)?;
3830            let got = self.new_reg(result);
3831            return self.written_as(inst, &format!("ldar_{bits}"), &[got, base]);
3832        }
3833        let [value, addr] = args[..] else { return Err(self.unsupported(inst)) };
3834        let bits = self.atomic_bits(inst, self.source[value].ty)?;
3835        let put = self.reg_of(value)?;
3836        let base = self.reg_of(addr)?;
3837        self.written_as(inst, &format!("stlr_{bits}"), &[put, base])
3838    }
3839
3840    /// A compare and exchange on AArch64, which is a loop of an exclusive load and store.
3841    ///
3842    /// The loop is one instruction as far as everything below is concerned, so that nothing can
3843    /// be spilled or reloaded between the two exclusive accesses, which would lose the reservation
3844    /// on some parts every time. Its definitions are all early, since they are written before the
3845    /// last read. The acquiring and releasing forms are used whatever the ordering, which is what
3846    /// gcc writes at the strongest one and is never wrong at a weaker one. The yes or no comes out
3847    /// of the status register the store wrote, read as a flag after the loop.
3848    fn exchange_a64(
3849        &mut self,
3850        inst: Inst,
3851        [addr, expected, desired]: [Value; 3],
3852        [old, exchanged]: [Value; 2],
3853    ) -> Result<(), Unsupported> {
3854        let bits = self.atomic_bits(inst, self.source[old].ty)?;
3855        let base = self.reg_of(addr)?;
3856        let want = self.reg_of(expected)?;
3857        let put = self.reg_of(desired)?;
3858        let got = self.new_reg(old);
3859        let flag = self.new_reg(exchanged);
3860        self.written_as(inst, &format!("cmpxchg_{bits}"), &[got, flag, base, want, put])
3861    }
3862
3863    /// A read modify write on AArch64, for the three operations that reach here, each a loop of
3864    /// an exclusive load and store for the reason the compare and exchange above is.
3865    fn modify_a64(
3866        &mut self,
3867        inst: Inst,
3868        op: RmwOp,
3869        [addr, operand]: [Value; 2],
3870        old: Value,
3871    ) -> Result<(), Unsupported> {
3872        let bits = self.atomic_bits(inst, self.source[old].ty)?;
3873        let base = self.reg_of(addr)?;
3874        let put = self.reg_of(operand)?;
3875        let got = self.new_reg(old);
3876        let status = self.out.new_vreg(self.gpr);
3877        match op {
3878            RmwOp::Xchg => {
3879                self.written_as(inst, &format!("xchg_{bits}"), &[got, status, base, put])
3880            }
3881            RmwOp::Add | RmwOp::Sub => {
3882                let name = if op == RmwOp::Add { "xadd" } else { "xsub" };
3883                let new = self.out.new_vreg(self.gpr);
3884                self.written_as(inst, &format!("{name}_{bits}"), &[got, new, status, base, put])
3885            }
3886            _ => Err(self.unsupported(inst)),
3887        }
3888    }
3889
3890    /// One `asm` statement.
3891    ///
3892    /// An empty template is most of the inline assembly in a test suite, and it is not a corner
3893    /// case somebody wrote by accident. A program that wants a value computed where it stands, or a
3894    /// loop the optimizer must not touch, writes `asm volatile ("" : : : "memory")`, and forty
3895    /// years of bug reports about optimizers are full of them. What such a statement asks for is
3896    /// the barrier and the operand places, and no instructions at all.
3897    ///
3898    /// So the operands are the half that is always real: a constraint says where a value has to be,
3899    /// and where it has to be is still true when the template between them is empty.
3900    ///
3901    /// What the constraints ask for, on an empty template, is only ever that two operands share a
3902    /// place. Nothing reads a register no text names, so `"r"` on its own asks for a register and
3903    /// no particular one, and any register at all answers it. A matching constraint is different,
3904    /// because it says the output the assembly leaves is the place the input arrived in, and with
3905    /// no instructions between them that is the input unchanged. So it is a rename and not a move:
3906    /// the value is already in a register and the result is that register.
3907    ///
3908    /// An output nothing is tied to and no instruction writes is whatever the assembly left there,
3909    /// which for a template that writes nothing is whatever was in the register. That is a value
3910    /// the program is not entitled to, and this writes a zero rather than reading one, because the
3911    /// allocator has to be given a definition before a use whatever the program is entitled to.
3912    ///
3913    /// # A template with instructions in it
3914    ///
3915    /// [`x86_64::read`] turns the text into the opcodes this backend already has, which is what
3916    /// `spec/11-asm-objects-debug.md` section 11.1 asks for: the machine is described once, and an
3917    /// instruction a program wrote is looked up in that description rather than copied through to
3918    /// an assembler that has one of its own. So nothing here assembles anything. What it does is
3919    /// put the statement's operands where the opcode holds them, and from there an `asm` statement
3920    /// is ordinary machine code: the allocator picks the registers, the listing and the object file
3921    /// are written from the same table as every other instruction, and a spill around one works
3922    /// because there is nothing left about it for a spill to get wrong.
3923    ///
3924    /// A register the template named in its own text is the one thing in there that is nobody's
3925    /// operand, and it is placed as itself. See [`Self::itself`] for why that is safer here than
3926    /// the thing gcc does, which is to copy the name out and leave the allocator none the wiser.
3927    ///
3928    /// Two things are refused, both for one reason, which is that placing them by a guess gives a
3929    /// program that assembles into something other than what it says.
3930    ///
3931    /// An output the template writes more than once, which is one place with two definitions in it,
3932    /// and the machine IR between here and the allocator has one definition per register by
3933    /// construction. An output tied to an input and written once is not that: it is two registers
3934    /// the description ties together, which is what [`Place`] is about.
3935    ///
3936    /// An operand read where the opcode writes, or written where it reads. An output that has not
3937    /// been written yet is not a value, and an input the assembly writes over is a value something
3938    /// else may still be using.
3939    ///
3940    /// # A register the instruction uses without being told
3941    ///
3942    /// An instruction may reach a register its text does not name, and `cpuid` is all of them at
3943    /// once: the leaf goes in `eax`, the subleaf in `ecx`, and the answer comes back in all four
3944    /// registers. The description holds every bit of that already, so what is left is to say which
3945    /// of the statement's operands is in each of those registers, and the constraint letter is the
3946    /// one thing in an assembly statement that says it. `"=a"` is an output in `rax` and `"c"` is
3947    /// an input in `rcx`, which is why a program writing `cpuid` writes its constraints that way
3948    /// and has no choice about it.
3949    ///
3950    /// A register no letter named is one the statement put nothing in, and that is the usual case
3951    /// rather than an unusual one, since an instruction that answers four questions is written by
3952    /// programs that asked one. A write of one is the register being destroyed and gets a register
3953    /// of its own, which is what tells the allocator to keep everything else out of it. A read of
3954    /// one is a register the instruction looks at and the program never filled, which gets a zero
3955    /// for the reason [`Self::undefined`] gives.
3956    ///
3957    /// # The clobber list
3958    ///
3959    /// Read now, as the registers it names being written by every instruction of the template. By
3960    /// every one rather than by one of them, because the list says the assembly as a whole leaves
3961    /// them ruined and nothing here knows which line did it. Every entry has to be a register this
3962    /// machine has a name for or the statement is refused, since a name nobody read is a register
3963    /// nobody is keeping out of.
3964    ///
3965    /// `memory` and `cc` are the two entries that are not registers and both are skipped. `memory`
3966    /// says the assembly touches storage, which is already true of every `asm` this writes and is
3967    /// nothing a register list could hold. `cc` says it ruins the condition flags, and the flag
3968    /// tracking already has that from the instructions the template was read into, since it takes
3969    /// every instruction it does not recognize as writing them and every instruction here is one
3970    /// this machine describes. `flags` is the name gcc's own register table gives the same thing on
3971    /// this machine, so a program writing it has written `cc` and is read that way: tcc's
3972    /// `tests/tcctest.c` lists both on one statement.
3973    ///
3974    /// A clobber the instruction already writes is left off it. `cpuid` writes all four registers
3975    /// by description, and a statement listing three of them as clobbers as well is saying the
3976    /// same thing twice, which the allocator would read as one register with two definitions.
3977    ///
3978    /// On a template with nothing in it the list is ignored, as it was before, since a template
3979    /// with no instructions ruins nothing whatever it said about what it ruins.
3980    fn assembly(&mut self, inst: Inst) -> Result<(), Unsupported> {
3981        let data = &self.source[inst];
3982        let Extra::Asm(asm) = data.extra else { return Err(self.unsupported(inst)) };
3983        let info = self.source[asm];
3984        if self.jumps_from_text(inst) {
3985            return Err(Unsupported::Assembly { inst, refused: Written::Goto });
3986        }
3987        let refused = || Unsupported::Assembly { inst, refused: Written::Operand };
3988
3989        let constraints = self.names.resolve(info.constraints).to_string();
3990        let results: Vec<Value> = data.results().collect();
3991        let operands = AsmOperands::read(&constraints, &results, &self.source[data.args])
3992            .ok_or_else(refused)?;
3993        let list: Vec<AsmOperand<'_>> = operands.iter().copied().collect();
3994
3995        // Read after the constraints and not before them, because a mnemonic whose suffix the
3996        // program left off is read at the width of the operands it names, and the operands are
3997        // what the constraints are a list of.
3998        let widths: Vec<Option<x86_64::Width>> = list
3999            .iter()
4000            .map(|operand| {
4001                let ty = self.source[operand.result.or(operand.value)?].ty;
4002                if !ty.is_scalar() {
4003                    return None;
4004                }
4005                x86_64::Width::of_bits(held_bits(ty))
4006            })
4007            .collect();
4008        // An operand in memory is an address the statement holds and an object the template names,
4009        // so the reader is told which ones those are and spells `%0` for one as the object.
4010        let memory: Vec<bool> = list.iter().map(|operand| operand.memory).collect();
4011        let template = self.names.resolve(info.template).to_string();
4012        // A clobber list naming a vector register goes the way a template this cannot read does.
4013        // The instructions read here are all in the general purpose file, and what keeps the text
4014        // already takes every vector register a call may use away from the allocator across it.
4015        let clobbers = self.names.resolve(info.clobbers);
4016        if clobbers.split(',').any(|entry| vector_named(entry).is_some()) {
4017            return self.kept(inst, &template, &list, &widths, &memory);
4018        }
4019        let steps = if template.trim().is_empty() {
4020            Vec::new()
4021        } else {
4022            match x86_64::read_in(&template, &widths, &memory) {
4023                Some(steps) => steps,
4024                None => return self.kept(inst, &template, &list, &widths, &memory),
4025            }
4026        };
4027
4028        // Which operands the template writes, counted before anything is placed, because the answer
4029        // decides where each of the three below comes from and one instruction may name an operand
4030        // that a later one writes. Which of them any instruction puts in a register at all is
4031        // counted in the same walk, since an operand no instruction reaches that way is one nothing
4032        // has to put anywhere: a constant a template names only as the distance into an address is
4033        // written into the instruction, and a register holding a copy of it would be one nobody
4034        // reads. An operand the address is counted from is reached that way and is counted here for
4035        // that reason, because the walk below it is over the opcode's operands and an address is
4036        // not one of those.
4037        //
4038        // Whether any instruction reads an operand an instruction above it wrote is counted in the
4039        // same walk too. Such a template is one whose instructions have to be written in order with
4040        // each read taken from wherever the last write left the operand, which is what
4041        // [`Self::woven`] does, and so is one that writes an operand twice.
4042        let mut writes = vec![0usize; list.len()];
4043        let mut reads = vec![false; list.len()];
4044        let mut held = vec![false; list.len()];
4045        let mut after = false;
4046        for step in &steps {
4047            // A call out of the template writes every register the convention lets the callee
4048            // leave anything in, and an output pinned to one of those is written by it.
4049            if let x86_64::Step::Call { .. } = step {
4050                for index in self.lost(&list).into_iter().filter_map(|(_, _, index)| index) {
4051                    *writes.get_mut(index).ok_or_else(refused)? += 1;
4052                }
4053                continue;
4054            }
4055            let x86_64::Step::Line(line) = step else { continue };
4056            match line.at.and_then(|at| at.base) {
4057                Some(x86_64::Piece::Operand { index, .. }) => {
4058                    *held.get_mut(index).ok_or_else(refused)? = true;
4059                    after |= writes[index] > 0;
4060                }
4061                Some(x86_64::Piece::Reg { reg, .. }) => {
4062                    if let Some(index) = bound(&list, reg, Role::Use) {
4063                        *held.get_mut(index).ok_or_else(refused)? = true;
4064                        after |= writes[index] > 0;
4065                    }
4066                }
4067                _ => {}
4068            }
4069            let mut written = Vec::new();
4070            let form = x86_64::form(line.opcode).ok_or_else(refused)?;
4071            // Which registers the instruction reaches, asked the same way it is asked again when
4072            // the instruction is written. See [`Self::lettered`] for the one opcode whose answer
4073            // comes from the constraint letters rather than from the description.
4074            let lettered = (line.opcode == x86_64::LITERAL).then(|| self.lettered(&list));
4075            let (described, pieces) = match &lettered {
4076                Some((described, pieces)) => (described.as_slice(), pieces.as_slice()),
4077                None => (form.operands(), line.operands.as_slice()),
4078            };
4079            for (desc, piece) in described.iter().zip(pieces) {
4080                // An operand the instruction reaches without its text saying so is the statement's
4081                // only when a constraint letter put something there. One that is nobody's writes
4082                // nothing of the program's, so it is counted nowhere and is dealt with where it is
4083                // placed.
4084                let index = match *piece {
4085                    x86_64::Piece::Operand { index, .. } => index,
4086                    x86_64::Piece::Implicit { reg } => match bound(&list, reg, desc.role) {
4087                        Some(index) => index,
4088                        None => continue,
4089                    },
4090                    x86_64::Piece::Reg { reg, .. } => match bound(&list, reg, desc.role) {
4091                        Some(index) => index,
4092                        None => continue,
4093                    },
4094                };
4095                *held.get_mut(index).ok_or_else(refused)? = true;
4096                if matches!(desc.role, Role::Def | Role::EarlyDef) {
4097                    written.push(index);
4098                } else {
4099                    *reads.get_mut(index).ok_or_else(refused)? = true;
4100                    after |= writes[index] > 0;
4101                }
4102            }
4103            for index in written {
4104                *writes.get_mut(index).ok_or_else(refused)? += 1;
4105            }
4106        }
4107        let woven = after
4108            || writes.iter().any(|&count| count > 1)
4109            || steps.iter().any(|step| !matches!(step, x86_64::Step::Line(_)));
4110
4111        // Where every operand is. Worked out in full before the first instruction is written, since
4112        // reading a value may be what puts it in a register in the first place, and that has to
4113        // happen in front of the assembly rather than in the middle of it.
4114        let mut places: Vec<Place> = vec![Place::default(); list.len()];
4115        for (index, operand) in list.iter().copied().enumerate() {
4116            let Some(result) = operand.result else {
4117                // An input, or an output the assembly was handed the address of, and both are a
4118                // value that arrives in a register and is read out of it, unless no instruction of
4119                // the template reads it out of one.
4120                let value = operand.value.ok_or_else(refused)?;
4121                if held[index] {
4122                    places[index].read = Some(self.reg_of(value)?);
4123                }
4124                continue;
4125            };
4126            let ty = self.source[result].ty;
4127            if on_x87(ty) {
4128                return Err(refused());
4129            }
4130            let tied = operands.tied_to(index);
4131            if let Some(from) = tied {
4132                if self.class_of(self.source[from].ty) != self.class_of(ty) {
4133                    return Err(refused());
4134                }
4135                places[index].read = Some(self.reg_of(from)?);
4136            }
4137            if writes[index] > 0 {
4138                places[index].write = Some(self.new_reg(result));
4139                continue;
4140            }
4141            match tied {
4142                // The place the input arrived in, which the assembly wrote nothing over. One
4143                // register, so this is a rename rather than a move.
4144                Some(_) => {
4145                    let reg = places[index].read.ok_or_else(refused)?;
4146                    self.regs[result.index()] = Some(reg);
4147                    places[index].write = Some(reg);
4148                }
4149                None => {
4150                    self.undefined(inst, result)?;
4151                    places[index].write = self.regs[result.index()];
4152                }
4153            }
4154        }
4155
4156        // An output an instruction of the template also reads, which the statement said nothing
4157        // about because an output is what a statement says the other thing about. What it holds
4158        // there is undefined, and a program writing one means it: `sbb %0, %0` in libgmp's
4159        // `add_mssaaaa` subtracts a register from itself and is asking for the borrow bit rather
4160        // than for the number, so whatever the register held, the answer is the same. Undefined is
4161        // not the same as absent though, since the allocator is owed a definition in front of every
4162        // use, so it gets the zero an output nothing wrote gets and for the same reason.
4163        //
4164        // Unless an input could have been in the same register, in which case gcc's allocator puts
4165        // it there whenever it can and a program may have been written against that. tcc's test of
4166        // a call from a template reads its output `"=a" (s)` to pass `"r" (str)` to `getenv`, which
4167        // is only the string because gcc gave the two of them `rax`. So an output nothing has
4168        // written yet reads the one input that could share its place, when there is exactly one.
4169        // One written `&` is written before the inputs are read and shares nothing.
4170        for index in 0..list.len() {
4171            if !reads[index] || places[index].read.is_some() || places[index].write.is_none() {
4172                continue;
4173            }
4174            let reg = match self.shared(&list, index) {
4175                Some(value) => self.reg_of(value)?,
4176                None => self.seeded(inst, list[index])?,
4177            };
4178            places[index].read = Some(reg);
4179        }
4180
4181        // Worked out once for the whole template, since the list is one list and every instruction
4182        // of the template gets it. Not worked out at all for a template with no instructions, which
4183        // is where there is nothing for it to go on.
4184        let clobbers = self.names.resolve(info.clobbers).to_string();
4185        let clobbered =
4186            if steps.is_empty() { Vec::new() } else { Self::clobbered(inst, &clobbers)? };
4187
4188        // A template with a label in it is not one run of instructions, and what it is instead is
4189        // in [`Self::woven`], which is also where a template goes whose instructions read what the
4190        // ones above them wrote. Every other template is what it has always been, which is every
4191        // instruction of it written into the block the statement stands in.
4192        if woven {
4193            return self.woven(inst, &steps, &mut places, &list, &clobbered, &writes);
4194        }
4195        for step in &steps {
4196            let x86_64::Step::Line(line) = step else { continue };
4197            self.instruction(inst, line, &places, &list, &clobbered)?;
4198        }
4199        Ok(())
4200    }
4201
4202    /// A template the reader could not take apart, kept as its text. See [`x86_64::Form::Template`].
4203    ///
4204    /// What the text names is spelled into it here, the way gcc prints it into its listing: a
4205    /// constant as `$5`, or as `5` under the `c` modifier, and the address of a name as the name.
4206    /// An object in memory is the one thing that cannot be spelled yet, since where it is depends on
4207    /// registers nothing has chosen, so it is left as a hole the writer fills and its address is the
4208    /// instruction's memory operand. One is all an instruction has room for, and every template this
4209    /// has met names one at most. A template that names an operand by name rather than by number is
4210    /// refused for now.
4211    ///
4212    /// # An operand in a register
4213    ///
4214    /// Which register is not known until the allocator has run, and the text is written down before
4215    /// then, so an operand in a register is a hole too. It names the instruction's own operand and
4216    /// the width the modifier asked for, or the width of the operand's type when there was none,
4217    /// and the writer spells whatever register the operand ended up in. What the text writes goes
4218    /// in first as definitions and what it reads goes in last as uses, with the registers below in
4219    /// between, so the allocator sees the statement as one instruction with every operand said. An
4220    /// output tied to an input, by `+` or by a number, reuses the input's register, and one written
4221    /// `&` is written early. Anything wider than a general purpose register is refused.
4222    ///
4223    /// A statement written with no colons is basic assembly, where `%` is a character like any
4224    /// other and a register is written `%eax`. The front end keeps no mark of which kind a statement
4225    /// was, so one with no operands and no clobbers is read as basic, which is what gcc would do for
4226    /// every such template but one written with empty colons around it.
4227    ///
4228    /// The registers a call may write are taken as written, see below for why.
4229    fn kept(
4230        &mut self,
4231        inst: Inst,
4232        template: &str,
4233        list: &[AsmOperand<'_>],
4234        widths: &[Option<x86_64::Width>],
4235        memory: &[bool],
4236    ) -> Result<(), Unsupported> {
4237        // Refused as the template it is, since keeping it is what was tried after reading it
4238        // failed, and what could not be kept is what it names rather than any one operand.
4239        let refused = || Unsupported::Assembly { inst, refused: Written::Template };
4240        let data = &self.source[inst];
4241        let Extra::Asm(asm) = data.extra else { return Err(self.unsupported(inst)) };
4242        let clobbers = self.names.resolve(self.source[asm].clobbers).to_string();
4243        let basic = list.is_empty() && clobbers.trim().is_empty();
4244
4245        // Every register a call may leave anything in, as well as the ones the list names. The
4246        // text can write any register it likes without saying so, and tcc's tests do: gcc gets
4247        // away with that at `-O0` because nothing lives in a register between two statements
4248        // there, and taking these away from the allocator across the template is what gives the
4249        // same answer here. Nothing is written to them by this, so a register one template leaves
4250        // a value in is still holding it when the next template reads it.
4251        let a64 = self.on_aarch64();
4252        let mut clobbered: Vec<(PhysReg, RegClass)> =
4253            self.lost(list).into_iter().map(|(reg, class, _)| (reg, class)).collect();
4254        let named = if a64 {
4255            Self::clobbered_a64(inst, &clobbers)?
4256        } else {
4257            Self::clobbered_x86(inst, &clobbers, self.gpr, self.conv.sse_class)?
4258        };
4259        for &(reg, class) in &named {
4260            if !clobbered.iter().any(|&(had, of)| had == reg && of == class) {
4261                clobbered.push((reg, class));
4262            }
4263        }
4264
4265        // The file each operand is in. On AArch64 `w` is a floating point or vector register and an
4266        // input tied to an output is in that output's file. A value whose type puts it in the other
4267        // file would need a move into this one first, which gcc makes and this does not yet, so
4268        // that is refused below.
4269        let mut files = vec![self.gpr; list.len()];
4270        if a64 {
4271            let constraints = self.names.resolve(self.source[asm].constraints);
4272            for (file, entry) in files.iter_mut().zip(constraints.split(',')) {
4273                if vector_letter(entry) {
4274                    *file = self.conv.sse_class;
4275                }
4276            }
4277            for index in 0..list.len() {
4278                if let Some(&file) = list[index].tied.and_then(|output| files.get(output)) {
4279                    files[index] = file;
4280                }
4281            }
4282        }
4283        let pins: Vec<_> = list.iter().map(|operand| self.pinned_here(operand)).collect();
4284        let pin = |index: usize, file: RegClass| match pins[index] {
4285            Some((at, class)) if class == file => Ok(Some(Constraint::Fixed(at))),
4286            Some(_) => Err(refused()),
4287            None => Ok(None),
4288        };
4289
4290        // The operands in a register, as the instruction's own. An input the text is handed as a
4291        // constant or as the address of a name is spelled into the text instead, when its
4292        // constraint allows a constant at all and no output is tied to it. `"a" (0x1234)` is a
4293        // register holding the number, the way gcc loads it, since the text may ask for `%h0`.
4294        let mut defs: Vec<mir::Operand> = Vec::new();
4295        let mut uses: Vec<mir::Operand> = Vec::new();
4296        let mut def_of: Vec<Option<usize>> = vec![None; list.len()];
4297        let mut use_of: Vec<Option<usize>> = vec![None; list.len()];
4298        if !basic {
4299            for (index, operand) in list.iter().enumerate() {
4300                let Some(result) = operand.result else { continue };
4301                let (ty, file) = (self.source[result].ty, files[index]);
4302                if on_x87(ty) || self.class_of(ty) != file {
4303                    return Err(refused());
4304                }
4305                let reg = self.new_reg(result);
4306                let written = if operand.early {
4307                    mir::Operand::write_early(reg, file)
4308                } else {
4309                    mir::Operand::write(reg, file)
4310                };
4311                def_of[index] = Some(defs.len());
4312                defs.push(match pin(index, file)? {
4313                    Some(fixed) => written.with(fixed),
4314                    None => written,
4315                });
4316            }
4317            for (index, operand) in list.iter().enumerate() {
4318                let Some(value) = operand.value else { continue };
4319                let spelled = operand.result.is_none()
4320                    && operand.tied.is_none()
4321                    && operand.immediate
4322                    && (self.number(value).is_some() || self.named_address(value).is_some());
4323                // An operand in memory is spelled on AArch64 as the register its address is in,
4324                // which is `[x3]` and is an address every instruction that takes one reads.
4325                if (operand.memory && !a64) || spelled {
4326                    continue;
4327                }
4328                let (ty, file) = (self.source[value].ty, files[index]);
4329                if on_x87(ty) || self.class_of(ty) != file {
4330                    return Err(refused());
4331                }
4332                let read = mir::Operand::read(self.reg_of(value)?, file);
4333                use_of[index] = Some(uses.len());
4334                uses.push(match pin(index, file)? {
4335                    Some(fixed) => read.with(fixed),
4336                    None => read,
4337                });
4338            }
4339        }
4340        // Every register a call may write is more than a template can give up when it has more
4341        // operands in registers than the convention keeps across a call. `sodium_sub` in
4342        // libsodium's `utils.c` is one: eight outputs written early and two inputs pinned, against
4343        // the five registers SysV preserves, so an output has nowhere to go and nothing is left to
4344        // carry one to its slot either. gcc gives that template ten registers, and a program that
4345        // writes a register it did not name is only owed what gcc would have done, which here is
4346        // one of the ten. So the registers taken as written without being named are handed back,
4347        // from the end of the convention's order, until the operands fit in what is left. One the
4348        // list names or an operand is pinned to stays where it is.
4349        let fixed_to: Vec<PhysReg> = defs
4350            .iter()
4351            .chain(&uses)
4352            .filter_map(|operand| match operand.constraint {
4353                Constraint::Fixed(at) => Some(at),
4354                _ => None,
4355            })
4356            .collect();
4357        let wanted = defs.iter().chain(&uses).count() - fixed_to.len();
4358        let int = self.conv.int_class;
4359        let free = |clobbered: &[(PhysReg, RegClass)]| {
4360            self.conv
4361                .int_order
4362                .iter()
4363                .filter(|&&reg| !fixed_to.contains(&reg) && !clobbered.contains(&(reg, int)))
4364                .count()
4365        };
4366        while free(&clobbered) < wanted {
4367            let Some(at) = clobbered.iter().rposition(|&(reg, class)| {
4368                class == int && !named.contains(&(reg, class)) && !fixed_to.contains(&reg)
4369            }) else {
4370                break;
4371            };
4372            clobbered.remove(at);
4373        }
4374
4375        // A register an output is pinned to is that output's definition and not a clobber as well.
4376        // One an input is pinned to is written as the instruction finishes, the way a call writes
4377        // the register its argument came in, and every other one is written early, since the text
4378        // may write it before it has read its inputs and an input must not be in it.
4379        let mut written: Vec<mir::Operand> = Vec::new();
4380        for (reg, class) in clobbered {
4381            let fixed = |operand: &mir::Operand| {
4382                operand.class == class && operand.constraint == Constraint::Fixed(reg)
4383            };
4384            if defs.iter().any(fixed) {
4385                continue;
4386            }
4387            let reg = mir::Reg::physical(reg);
4388            written.push(if uses.iter().any(fixed) {
4389                mir::Operand::write(reg, class)
4390            } else {
4391                mir::Operand::write_early(reg, class)
4392            });
4393        }
4394        // An output tied to an input is one register, which the definition says by reusing the
4395        // use, or by both being fixed to the same one when the output was pinned.
4396        //
4397        // A reused register is kept from every other input already, since the allocator counts the
4398        // output as taken from where the instruction reads. So `+&` asks for nothing more than `+`,
4399        // and saying it as an early write as well costs a register: the allocator only hands an
4400        // output the register of the input it reuses when the output starts at the instruction, and
4401        // an early one starts a point sooner, so it gets one of its own and a copy in front. Eleven
4402        // operands written that way in xz's range decoder need seventeen registers and run out. The
4403        // one case where `&` still means something is an input reading the same value as the one
4404        // tied, which would be in the same register and read after the output was written.
4405        let first_use = defs.len() + written.len();
4406        for (output, operand) in list.iter().enumerate() {
4407            let Some(def) = def_of[output] else { continue };
4408            let input = if operand.value.is_some() {
4409                Some(output)
4410            } else {
4411                list.iter().position(|entry| entry.tied == Some(output))
4412            };
4413            let Some(read) = input.and_then(|input| use_of[input]) else { continue };
4414            match defs[def].constraint {
4415                Constraint::Fixed(_) => uses[read].constraint = defs[def].constraint,
4416                _ => {
4417                    let at = u8::try_from(first_use + read).map_err(|_| refused())?;
4418                    defs[def].constraint = Constraint::Reuse(at);
4419                    let source = uses[read].reg;
4420                    let shared = uses
4421                        .iter()
4422                        .enumerate()
4423                        .any(|(other, operand)| other != read && operand.reg == source);
4424                    if defs[def].role == Role::EarlyDef && !shared {
4425                        defs[def].role = Role::Def;
4426                    }
4427                }
4428            }
4429        }
4430
4431        // A line naming an operand in a register, with an instruction on it the reader knows, is
4432        // one the reader refused for a reason of its own, and keeping it as text would hand the
4433        // assembler what the reader already said no to. `addq %1, %k0` is that: a quadword add
4434        // into half a register. What is kept is a line with an instruction nothing here knows.
4435        let registered = |index: usize| def_of[index].is_some() || use_of[index].is_some();
4436        if !a64 && (0..list.len()).any(registered) {
4437            for line in template.split(['\n', ';']) {
4438                if names_one(line, registered)
4439                    && x86_64::known(line, widths, memory)
4440                    && x86_64::read_in(line, widths, memory).is_none()
4441                {
4442                    return Err(refused());
4443                }
4444            }
4445        }
4446
4447        let mut text = String::with_capacity(template.len());
4448        let mut memory: Option<usize> = None;
4449        if basic {
4450            text.push_str(template);
4451        } else {
4452            let mut chars = template.chars().peekable();
4453            // Inside `{att|intel}`, and past the `|` in it, which is the half nobody reads. AArch64
4454            // has one dialect, and a brace there is a list of vector registers.
4455            let mut dialect = false;
4456            let mut skipped = false;
4457            while let Some(c) = chars.next() {
4458                match c {
4459                    '{' if !a64 => {
4460                        dialect = true;
4461                        continue;
4462                    }
4463                    '|' if dialect => {
4464                        skipped = true;
4465                        continue;
4466                    }
4467                    '}' if dialect => {
4468                        dialect = false;
4469                        skipped = false;
4470                        continue;
4471                    }
4472                    _ if skipped => continue,
4473                    '%' => {}
4474                    _ => {
4475                        text.push(c);
4476                        continue;
4477                    }
4478                }
4479                match chars.peek().copied() {
4480                    Some(c @ ('%' | '{' | '|' | '}')) => {
4481                        chars.next();
4482                        text.push(c);
4483                        continue;
4484                    }
4485                    Some('=') => {
4486                        chars.next();
4487                        text.push_str(&inst.index().to_string());
4488                        continue;
4489                    }
4490                    _ => {}
4491                }
4492                let modifier = match chars.peek().copied() {
4493                    Some(c) if c.is_ascii_alphabetic() => {
4494                        chars.next();
4495                        Some(c)
4496                    }
4497                    _ => None,
4498                };
4499                let mut digits = String::new();
4500                while let Some(c) = chars.peek().copied().filter(char::is_ascii_digit) {
4501                    digits.push(c);
4502                    chars.next();
4503                }
4504                let index: usize = digits.parse().map_err(|_| refused())?;
4505                let operand = list.get(index).ok_or_else(refused)?;
4506                if operand.memory && a64 {
4507                    let at = use_of[index].map(|at| first_use + at).ok_or_else(refused)?;
4508                    if modifier.is_some() {
4509                        return Err(refused());
4510                    }
4511                    text.push('[');
4512                    text.push_str(&template_reg(at, 'x'));
4513                    text.push(']');
4514                    continue;
4515                }
4516                if operand.memory {
4517                    if modifier.is_some() || memory.is_some_and(|had| had != index) {
4518                        return Err(refused());
4519                    }
4520                    memory = Some(index);
4521                    text.push_str(x86_64::TEMPLATE_MEM);
4522                    continue;
4523                }
4524                let placed = def_of[index].or(use_of[index].map(|at| first_use + at));
4525                if let Some(at) = placed {
4526                    let value = operand.result.or(operand.value).ok_or_else(refused)?;
4527                    let bits = held_bits(self.source[value].ty);
4528                    // `w` and `x` are the two names every general purpose register has, and one
4529                    // with no modifier is named at the width of its type, as gcc names it. A
4530                    // vector register with no modifier is `v`, which is what gcc writes for one
4531                    // whatever is in it, and the modifiers name the scalar views of it.
4532                    let width = if a64 && files[index] != self.gpr {
4533                        match modifier {
4534                            None => 'v',
4535                            Some(view @ ('b' | 'h' | 's' | 'd' | 'q')) => view,
4536                            Some(_) => return Err(refused()),
4537                        }
4538                    } else if a64 {
4539                        match (modifier, bits) {
4540                            (None, 8 | 16 | 32) | (Some('w'), _) => 'w',
4541                            (None, 64) | (Some('x'), _) => 'x',
4542                            _ => return Err(refused()),
4543                        }
4544                    } else {
4545                        match modifier {
4546                            None => match held_bits(self.source[value].ty) {
4547                                8 => 'b',
4548                                16 => 'w',
4549                                32 => 'k',
4550                                64 => 'q',
4551                                _ => return Err(refused()),
4552                            },
4553                            Some(width @ ('b' | 'w' | 'k' | 'q')) => width,
4554                            // The second byte is a name only four registers have, so it is taken for
4555                            // an operand pinned to one of them and for nothing the allocator chose.
4556                            Some('h') if pinned(operand).and_then(x86_64::gpr_high).is_some() => {
4557                                'h'
4558                            }
4559                            Some(_) => return Err(refused()),
4560                        }
4561                    };
4562                    text.push_str(&template_reg(at, width));
4563                    continue;
4564                }
4565                let value = operand.value.ok_or_else(refused)?;
4566                let bare = match modifier {
4567                    None => false,
4568                    Some('c' | 'P' | 'p') => true,
4569                    Some(_) => return Err(refused()),
4570                };
4571                // A constant is bare on AArch64 whatever the modifier, which is how gcc prints one
4572                // there and a form GNU as takes wherever `#` would go.
4573                if !bare && !a64 {
4574                    text.push('$');
4575                }
4576                if let Some(number) = self.number(value) {
4577                    text.push_str(&number.to_string());
4578                } else if let Some(symbol) = self.named_address(value) {
4579                    text.push_str(&template_name(self.names.resolve(symbol)));
4580                } else {
4581                    return Err(refused());
4582                }
4583            }
4584        }
4585
4586        // An object in this function's frame is named by where it is in the frame, the way gcc
4587        // names it, rather than by a register its address was put in first. The text may write
4588        // registers it does not declare, and tcc's tests do: one that writes `%ecx` behind the
4589        // compiler's back would otherwise take the address with it.
4590        let mut local = None;
4591        let at = match memory.filter(|_| !a64) {
4592            Some(index) => {
4593                let value = list[index].value.ok_or_else(refused)?;
4594                local = self.local_of(value);
4595                let base = match local {
4596                    Some(_) => mir::Reg::physical(self.conv.stack_pointer),
4597                    None => self.reg_of(value)?,
4598                };
4599                Some(mir::Mem::at(mir::Operand::read(base, self.gpr)))
4600            }
4601            None => None,
4602        };
4603        let symbol = self.names.intern(&text);
4604        let opcode = self.named(if a64 { aarch64::TEMPLATE } else { x86_64::TEMPLATE });
4605        let block = self.at.expect("a block is being filled");
4606        let span = self.source.span(inst);
4607        let mut build = self.out.build(block, opcode).at(span).symbol(symbol);
4608        for operand in defs.into_iter().chain(written).chain(uses) {
4609            build = build.operand(operand);
4610        }
4611        if let Some(mem) = at {
4612            build = build.mem(mem);
4613        }
4614        let made = build.finish();
4615        if let Some(local) = local {
4616            self.stack.addresses.push((made, local));
4617        }
4618        Ok(())
4619    }
4620
4621    /// The object in this function's frame a value is the address of, for one an `alloca` of a
4622    /// size known here made. See [`Self::reserve`], which is where the `lea` it is found by came
4623    /// from.
4624    fn local_of(&self, value: Value) -> Option<usize> {
4625        let Def::Result { inst, .. } = self.source[value].def else { return None };
4626        if self.source[inst].opcode != Opcode::Alloca
4627            || !self.source[self.source[inst].args].is_empty()
4628        {
4629            return None;
4630        }
4631        let reg = self.regs[value.index()]?;
4632        self.stack.addresses.iter().find_map(|&(made, local)| {
4633            let data = &self.out[made];
4634            let defined = self.out[data.operands].first()?;
4635            (defined.reg == reg).then_some(local)
4636        })
4637    }
4638
4639    /// The name a value is the address of, for one a `global_addr` defined.
4640    fn named_address(&self, value: Value) -> Option<Symbol> {
4641        let Def::Result { inst, .. } = self.source[value].def else { return None };
4642        if self.source[inst].opcode != Opcode::GlobalAddr {
4643            return None;
4644        }
4645        let Extra::Symbol(symbol) = self.source[inst].extra else { return None };
4646        Some(symbol)
4647    }
4648
4649    /// A register holding a zero, for an operand of a template that is read before anything filled
4650    /// it.
4651    ///
4652    /// Two things ask for this and they are the same thing twice. An output the template reads has
4653    /// nothing to be read out of until the instruction that writes it has run, and a loop carries
4654    /// an operand into a block before the instruction that fills it, so both are a use in front of
4655    /// every definition. What the program is owed there is nothing, since the value is undefined
4656    /// either way, and what the allocator is owed is a register something wrote.
4657    fn seeded(&mut self, inst: Inst, operand: AsmOperand<'_>) -> Result<mir::Reg, Unsupported> {
4658        let refused = || Unsupported::Assembly { inst, refused: Written::Operand };
4659        let value = operand.result.or(operand.value).ok_or_else(refused)?;
4660        let class = self.class_of(self.source[value].ty);
4661        if class != self.gpr {
4662            return Err(refused());
4663        }
4664        let block = self.at.expect("a block is being filled");
4665        let reg = self.out.new_vreg(class);
4666        let put = self.named("mov_ri_64");
4667        self.out.build(block, put).at(self.source.span(inst)).def(reg, class).imm(0).finish();
4668        Ok(reg)
4669    }
4670
4671    /// A template with labels in it, as the blocks its jumps leave and arrive at.
4672    ///
4673    /// A statement is an instruction of the IR and stands inside one block, so a template that
4674    /// jumps has to stop being one thing. Each label becomes a block, each jump ends the block it
4675    /// stands in and gives it two arms, and whatever follows the statement goes into whichever
4676    /// block the walk finished in, which is what [`Self::block`] already reads off `self.at` and
4677    /// what [`Self::saves_place`] already does for the same reason.
4678    ///
4679    /// # What is carried between them
4680    ///
4681    /// The machine IR here is in the form where a register is written once, so an operand written
4682    /// inside a loop and read again at the top of it cannot be one register. What arrives at the
4683    /// top is a parameter of that block, and every jump to it carries whichever register held the
4684    /// operand where the jump stands. That is the whole of the bookkeeping: every block a label
4685    /// made takes one parameter for each operand that is in a register at all, in one order, so an
4686    /// arm's arguments and a block's parameters are the same list read twice.
4687    ///
4688    /// Which register an operand is in at each point is kept in the read half of its place, since
4689    /// that is what the instructions below read it out of. An instruction that writes an operand
4690    /// leaves it in the register it wrote, and a jump below carries that one. The block an
4691    /// untaken jump falls into is arrived at one way only and so takes no parameters, and nothing
4692    /// about where the operands are changes there.
4693    ///
4694    /// An operand written by the template and filled by nothing is written as a zero first, for
4695    /// the reason [`Self::undefined`] gives and one more: a jump may carry it before the
4696    /// instruction that fills it has run, and an argument has to be a register something wrote.
4697    ///
4698    /// # The condition state
4699    ///
4700    /// Nothing carries it and nothing has to. The instruction that sets it and the jump that reads
4701    /// it are both written here, next to each other in one block, and what the allocator may put
4702    /// between them is a move, which on this machine leaves the condition state alone. The edge
4703    /// into a block a loop goes back to is a critical edge and `crate::split` gives it a block of
4704    /// its own, so the moves an arm turns into land behind the jump rather than in front of it.
4705    fn woven(
4706        &mut self,
4707        inst: Inst,
4708        steps: &[x86_64::Step],
4709        places: &mut [Place],
4710        list: &[AsmOperand<'_>],
4711        clobbered: &[PhysReg],
4712        writes: &[usize],
4713    ) -> Result<(), Unsupported> {
4714        let refused = || Unsupported::Assembly { inst, refused: Written::Operand };
4715        let span = self.source.span(inst);
4716
4717        // Which operands are carried, which is every one that is in a register at all. An operand
4718        // the template never puts in one, such as a constant it names only as the distance into an
4719        // address, is in the instruction and has nowhere to be carried from.
4720        let mut carried: Vec<(usize, RegClass)> = Vec::new();
4721        for (index, operand) in list.iter().enumerate() {
4722            if places[index].read.is_none() && places[index].write.is_none() {
4723                continue;
4724            }
4725            let value = operand.result.or(operand.value).ok_or_else(refused)?;
4726            let ty = self.source[value].ty;
4727            if on_x87(ty) {
4728                return Err(refused());
4729            }
4730            carried.push((index, self.class_of(ty)));
4731        }
4732
4733        // What each of them holds where the template starts.
4734        for &(index, _) in &carried {
4735            if places[index].read.is_some() {
4736                continue;
4737            }
4738            if writes[index] == 0 {
4739                places[index].read = places[index].write;
4740                continue;
4741            }
4742            places[index].read = Some(self.seeded(inst, list[index])?);
4743        }
4744
4745        // The blocks, made before the walk because a jump forwards names a label the walk has not
4746        // reached yet.
4747        let mut labels: Vec<(&str, mir::Block, Vec<mir::Reg>)> = Vec::new();
4748        for step in steps {
4749            let x86_64::Step::Label(name) = step else { continue };
4750            let block = self.out.create_block();
4751            let mut params = Vec::with_capacity(carried.len());
4752            for &(_, class) in &carried {
4753                params.push(self.out.append_param(block, class));
4754            }
4755            labels.push((name.as_str(), block, params));
4756        }
4757
4758        let mut wrote: Vec<usize> = Vec::new();
4759        for step in steps {
4760            match step {
4761                x86_64::Step::Label(name) => {
4762                    let (block, params) = Self::went(&labels, name).ok_or_else(refused)?;
4763                    let from = self.at.expect("a block is being filled");
4764                    let args = Self::held(places, &carried).ok_or_else(refused)?;
4765                    *self.out.succs_mut(from) = vec![mir::BlockCall::with(block, args)];
4766                    self.at = Some(block);
4767                    for (at, &(index, _)) in carried.iter().enumerate() {
4768                        places[index].read = params.get(at).copied();
4769                    }
4770                }
4771                x86_64::Step::Jump { opcode, to } => {
4772                    let (block, _) = Self::went(&labels, to).ok_or_else(refused)?;
4773                    let from = self.at.expect("a block is being filled");
4774                    let args = Self::held(places, &carried).ok_or_else(refused)?;
4775                    let opcode = self.named(opcode);
4776                    self.out.build(from, opcode).at(span).finish();
4777                    let next = self.out.create_block();
4778                    *self.out.succs_mut(from) =
4779                        vec![mir::BlockCall::with(block, args), mir::BlockCall::to(next)];
4780                    self.at = Some(next);
4781                }
4782                x86_64::Step::Away { symbol } => {
4783                    // Only in a function that is written without a prologue, which is the one
4784                    // place the jump means what it says. Anywhere else there is an epilogue behind
4785                    // the statement that puts the registers back and gives the frame up, and a
4786                    // jump over it goes to the next function with this function's frame still
4787                    // taken. The reader already made sure it is the last step of the template, so
4788                    // what is left to ask is about the function around it.
4789                    if !self.source.attrs.set.contains(AttrSet::NAKED) {
4790                        return Err(Unsupported::Assembly { inst, refused: Written::Away });
4791                    }
4792                    let from = self.at.expect("a block is being filled");
4793                    let opcode = self.named(AWAY);
4794                    let symbol = self.names.intern(symbol);
4795                    self.out.build(from, opcode).at(span).symbol(symbol).finish();
4796                    // Nowhere, which is what a jump out of the function leaves behind it and is
4797                    // the same list a `ret` leaves. The block after it is made for the walk above
4798                    // rather than for the program: the statement may be in the middle of a body
4799                    // that goes on being lowered, and what that lowering writes is reached by
4800                    // nothing and thrown away with the block.
4801                    *self.out.succs_mut(from) = Vec::new();
4802                    self.at = Some(self.out.create_block());
4803                }
4804                x86_64::Step::Call { symbol } => {
4805                    self.call_out(inst, symbol, places, list, clobbered, &carried, &mut wrote)?;
4806                }
4807                x86_64::Step::Line(line) => {
4808                    let form = x86_64::form(line.opcode).ok_or_else(refused)?;
4809                    let mut written = Vec::new();
4810                    for (desc, piece) in form.operands().iter().zip(&line.operands) {
4811                        if !desc.role.is_def() {
4812                            continue;
4813                        }
4814                        let index = match *piece {
4815                            x86_64::Piece::Operand { index, .. } => index,
4816                            x86_64::Piece::Implicit { reg } => match bound(list, reg, desc.role) {
4817                                Some(index) => index,
4818                                None => continue,
4819                            },
4820                            x86_64::Piece::Reg { reg, .. } => match bound(list, reg, desc.role) {
4821                                Some(index) => index,
4822                                None => continue,
4823                            },
4824                        };
4825                        written.push(index);
4826                    }
4827                    // A register is written once in this form of the machine IR, so an operand
4828                    // an instruction above already wrote is written into a new one here, and what
4829                    // reads it below reads that one.
4830                    for &index in &written {
4831                        if !wrote.contains(&index) {
4832                            wrote.push(index);
4833                            continue;
4834                        }
4835                        let &(_, class) =
4836                            carried.iter().find(|&&(at, _)| at == index).ok_or_else(refused)?;
4837                        let place = places.get_mut(index).ok_or_else(refused)?;
4838                        place.write = Some(self.out.new_vreg(class));
4839                    }
4840                    self.instruction(inst, line, places, list, clobbered)?;
4841                    for index in written {
4842                        let place = places.get_mut(index).ok_or_else(refused)?;
4843                        if place.write.is_some() {
4844                            place.read = place.write;
4845                        }
4846                    }
4847                }
4848            }
4849        }
4850
4851        // Where the walk left each output, which is the parameter of the block a label made when
4852        // the template ends in one and the register an instruction wrote when it does not.
4853        for (index, operand) in list.iter().enumerate() {
4854            let Some(result) = operand.result else { continue };
4855            if let Some(reg) = places[index].read {
4856                self.regs[result.index()] = Some(reg);
4857            }
4858        }
4859        Ok(())
4860    }
4861
4862    /// A template's call to a function somewhere else, as the call the convention makes.
4863    ///
4864    /// The opcode is the one a call written in C becomes, so everything that asks whether a
4865    /// function calls anything gets the answer it would for one: the stack pointer is left aligned
4866    /// at the statement and nothing is kept in the red zone. What is not the same is the operands.
4867    /// Nothing is passed by the convention, since the template put the arguments where it wanted
4868    /// them, and what comes back is whatever an output is pinned to, since that is the only thing
4869    /// the template says about it. Every other register the callee may leave anything in is
4870    /// written here, which is what a program that calls from a template never says and always
4871    /// means.
4872    #[allow(clippy::too_many_arguments)]
4873    fn call_out(
4874        &mut self,
4875        inst: Inst,
4876        symbol: &str,
4877        places: &mut [Place],
4878        list: &[AsmOperand<'_>],
4879        clobbered: &[PhysReg],
4880        carried: &[(usize, RegClass)],
4881        wrote: &mut Vec<usize>,
4882    ) -> Result<(), Unsupported> {
4883        let refused = || Unsupported::Assembly { inst, refused: Written::Operand };
4884        let mut operands = Vec::new();
4885        let mut written = Vec::new();
4886        let lost = self.lost(list);
4887        for &(reg, class, index) in &lost {
4888            let Some(index) = index else {
4889                operands.push(mir::Operand::write(mir::Reg::physical(reg), class));
4890                continue;
4891            };
4892            // Written once in this form of the machine IR, so a second write is a new register,
4893            // the same as for an instruction in [`Self::woven`].
4894            if wrote.contains(&index) {
4895                let &(_, class) =
4896                    carried.iter().find(|&&(at, _)| at == index).ok_or_else(refused)?;
4897                places.get_mut(index).ok_or_else(refused)?.write = Some(self.out.new_vreg(class));
4898            } else {
4899                wrote.push(index);
4900            }
4901            let place = places.get(index).ok_or_else(refused)?.write.ok_or_else(refused)?;
4902            operands.push(mir::Operand::write(place, class).with(Constraint::Fixed(reg)));
4903            written.push(index);
4904        }
4905        for &reg in clobbered {
4906            if lost.iter().all(|&(gone, class, _)| gone != reg || class != self.gpr) {
4907                operands.push(mir::Operand::write(mir::Reg::physical(reg), self.gpr));
4908            }
4909        }
4910        let block = self.at.expect("a block is being filled");
4911        let span = self.source.span(inst);
4912        let opcode = mir::Opcode::new(self.names.intern(abi::CALL));
4913        let symbol = self.names.intern(symbol);
4914        let mut build = self.out.build(block, opcode).at(span).symbol(symbol);
4915        for operand in operands {
4916            build = build.operand(operand);
4917        }
4918        build.finish();
4919        let calls = &mut self.stack.calls;
4920        *calls = Some(calls.unwrap_or(0));
4921        for index in written {
4922            let place = places.get_mut(index).ok_or_else(refused)?;
4923            place.read = place.write;
4924        }
4925        Ok(())
4926    }
4927
4928    /// Every register a call may leave anything in, with its file and the output pinned to it if
4929    /// one is.
4930    ///
4931    /// A register is asked about with its file, since the two files are numbered from nought alike
4932    /// and a question about `v8` alone would find an output pinned to `x8`.
4933    fn lost(&self, list: &[AsmOperand<'_>]) -> Vec<(PhysReg, RegClass, Option<usize>)> {
4934        let conv = self.conv;
4935        let ints = conv.int_order.iter().filter(|&&reg| !conv.preserves_int(reg));
4936        let sses = conv.sse_order.iter().filter(|&&reg| !conv.preserves_sse(reg));
4937        let written = |reg, class| {
4938            list.iter().position(|operand| {
4939                operand.result.is_some() && self.pinned_here(operand) == Some((reg, class))
4940            })
4941        };
4942        ints.map(|&reg| (reg, conv.int_class, written(reg, conv.int_class)))
4943            .chain(sses.map(|&reg| (reg, conv.sse_class, written(reg, conv.sse_class))))
4944            .collect()
4945    }
4946
4947    /// The input an output read before anything wrote it shares its register with, which is the
4948    /// one input that could be in that register, or nothing when there is none or more than one.
4949    ///
4950    /// Could be means nothing ties it elsewhere: it is in a register rather than in memory, no
4951    /// constraint pins it anywhere the output is not, and it is not tied to another output. An
4952    /// output written `&` shares nothing, since the assembly writes it before it reads the inputs.
4953    fn shared(&self, list: &[AsmOperand<'_>], index: usize) -> Option<Value> {
4954        let output = list.get(index)?;
4955        if output.early || output.tied.is_some() {
4956            return None;
4957        }
4958        let class = self.class_of(self.source[output.result?].ty);
4959        let mut fits = list.iter().filter(|operand| {
4960            operand.result.is_none()
4961                && !operand.memory
4962                && operand.tied.is_none()
4963                && operand.value.is_some_and(|value| self.class_of(self.source[value].ty) == class)
4964                && pinned(operand).is_none_or(|reg| pinned(output) == Some(reg))
4965        });
4966        let value = fits.next()?.value;
4967        if fits.next().is_some() {
4968            return None;
4969        }
4970        value
4971    }
4972
4973    /// The block one of the template's labels made, and the parameters it takes.
4974    fn went<'b>(
4975        labels: &'b [(&str, mir::Block, Vec<mir::Reg>)],
4976        name: &str,
4977    ) -> Option<(mir::Block, &'b [mir::Reg])> {
4978        labels
4979            .iter()
4980            .find(|(had, ..)| *had == name)
4981            .map(|(_, block, params)| (*block, params.as_slice()))
4982    }
4983
4984    /// The register each carried operand is in, which is what an arm to a label carries.
4985    fn held(places: &[Place], carried: &[(usize, RegClass)]) -> Option<Vec<mir::Reg>> {
4986        carried.iter().map(|&(index, _)| places.get(index)?.read).collect()
4987    }
4988
4989    /// The registers a clobber list names, in the order it named them.
4990    ///
4991    /// Nothing is dropped. A name this has no register for is refused, because the list is the
4992    /// program telling the compiler which registers it may not leave anything in, and an entry
4993    /// nobody read is a register something may still be left in. See [`Self::assembly`] for the
4994    /// two entries that are not registers and for why they are skipped rather than refused.
4995    fn clobbered(inst: Inst, clobbers: &str) -> Result<Vec<PhysReg>, Unsupported> {
4996        let refused = || Unsupported::Assembly { inst, refused: Written::Clobber };
4997        let mut named = Vec::new();
4998        for entry in clobbers.split(',') {
4999            let entry = entry.trim().trim_matches('"');
5000            // The sigil is optional in a clobber list and means nothing when it is there, unlike
5001            // in a template, where it is what tells a register from an operand.
5002            let entry = entry.strip_prefix('%').unwrap_or(entry);
5003            if entry.is_empty() || matches!(entry, "memory" | "cc" | "flags") {
5004                continue;
5005            }
5006            let (reg, _) = x86_64::gpr_named(entry).ok_or_else(refused)?;
5007            if !named.contains(&reg) {
5008                named.push(reg);
5009            }
5010        }
5011        Ok(named)
5012    }
5013
5014    /// [`Self::clobbered`] for a template kept as text, where a clobber may also name a vector
5015    /// register, `xmm0` or its wider spelling `ymm0`, which busybox's `xorbuf16_aligned_long` does.
5016    /// Each comes back with the file it is in, since `xmm0` and `rax` are both register nought.
5017    fn clobbered_x86(
5018        inst: Inst,
5019        clobbers: &str,
5020        gpr: RegClass,
5021        sse: RegClass,
5022    ) -> Result<Vec<(PhysReg, RegClass)>, Unsupported> {
5023        let mut named = Vec::new();
5024        let mut general = Vec::new();
5025        for entry in clobbers.split(',') {
5026            match vector_named(entry) {
5027                Some(reg) => {
5028                    if !named.contains(&(reg, sse)) {
5029                        named.push((reg, sse));
5030                    }
5031                }
5032                None => general.push(entry),
5033            }
5034        }
5035        for reg in Self::clobbered(inst, &general.join(","))? {
5036            named.push((reg, gpr));
5037        }
5038        Ok(named)
5039    }
5040
5041    /// [`Self::clobbered`] on AArch64, where a clobber may name a vector register as well as a
5042    /// general purpose one, so each comes back with the file it is in. See [`aarch64::named`].
5043    fn clobbered_a64(inst: Inst, clobbers: &str) -> Result<Vec<(PhysReg, RegClass)>, Unsupported> {
5044        let refused = || Unsupported::Assembly { inst, refused: Written::Clobber };
5045        let mut named = Vec::new();
5046        for entry in clobbers.split(',') {
5047            let entry = entry.trim().trim_matches('"');
5048            if entry.is_empty() || matches!(entry, "memory" | "cc") {
5049                continue;
5050            }
5051            let reg = aarch64::named(entry).ok_or_else(refused)?;
5052            if !named.contains(&reg) {
5053                named.push(reg);
5054            }
5055        }
5056        Ok(named)
5057    }
5058
5059    /// Whether the machine being lowered for is AArch64.
5060    fn on_aarch64(&self) -> bool {
5061        std::ptr::eq(self.selector.shapes, &aarch64::MACHINE)
5062    }
5063
5064    /// The register an operand is pinned to on the machine being lowered for.
5065    ///
5066    /// [`pinned`] on x86, where it is always a general purpose register. AArch64 has no constraint
5067    /// letter for one register, so there only a local register variable pins anything, and its name
5068    /// is read against [`aarch64::named`], which may put it in either file. The file comes back with
5069    /// the register because the two are numbered from nought alike, and `x8` is not `v8`.
5070    fn pinned_here(&self, operand: &AsmOperand<'_>) -> Option<(PhysReg, RegClass)> {
5071        if !self.on_aarch64() {
5072            return pinned(operand).map(|reg| (reg, self.gpr));
5073        }
5074        let name = operand.named?;
5075        aarch64::named(name.strip_prefix('%').unwrap_or(name))
5076    }
5077
5078    /// An `asm` statement whose operands are `long double` values on the x87 stack.
5079    ///
5080    /// `t` is the top of the stack and `u` is the register under it, and those two letters, or a
5081    /// number tying an input to an output in one of them, are the only places taken here. That is
5082    /// what glibc's old `<bits/mathinline.h>` writes, `fpatan` with `=t`, `0` and `u` and `st(1)`
5083    /// in the clobber list, and it is gcc-torture `execute/990413-2.c`.
5084    ///
5085    /// The group is the shape every other one in [`Self::x87`] has. The inputs are pushed from the
5086    /// deepest up, so the `t` one is pushed last and ends up on top, then the template runs, then
5087    /// the outputs are popped into their slots from the top down. That leaves the stack as empty
5088    /// as it was found only when the template popped every input it was handed and pushed every
5089    /// output it says it leaves, and gcc's rule for these statements says when that is: an input
5090    /// tied to an output or named in the clobber list is one the template pops. So a statement
5091    /// with an input it leaves behind is refused, as is one with an operand anywhere other than
5092    /// `st(0)` and `st(1)`, since nothing here would know what to do with the stack after it.
5093    fn x87_assembly(&mut self, inst: Inst) -> Result<(), Unsupported> {
5094        let data = &self.source[inst];
5095        let Extra::Asm(asm) = data.extra else { return Err(self.unsupported(inst)) };
5096        let info = self.source[asm];
5097        if !self.source[info.targets].is_empty() {
5098            return Err(Unsupported::Assembly { inst, refused: Written::Goto });
5099        }
5100        let refused = || Unsupported::Assembly { inst, refused: Written::Operand };
5101        let constraints = self.names.resolve(info.constraints).to_string();
5102        let results: Vec<Value> = data.results().collect();
5103        let operands = AsmOperands::read(&constraints, &results, &self.source[data.args])
5104            .ok_or_else(refused)?;
5105        let list: Vec<AsmOperand<'_>> = operands.iter().copied().collect();
5106
5107        // Where on the stack each operand is, as a depth from the top.
5108        let letters: Vec<&str> = constraints.split(',').collect();
5109        let mut depths = Vec::with_capacity(list.len());
5110        for (operand, letter) in list.iter().zip(&letters) {
5111            let value = operand.result.or(operand.value).ok_or_else(refused)?;
5112            if operand.memory || !on_x87(self.source[value].ty) {
5113                return Err(refused());
5114            }
5115            let depth = match operand.tied {
5116                Some(output) => *depths.get(output).ok_or_else(refused)?,
5117                None => match letter.trim_start_matches(['=', '+', '&']) {
5118                    "t" => 0,
5119                    "u" => 1,
5120                    _ => return Err(refused()),
5121                },
5122            };
5123            depths.push(depth);
5124        }
5125
5126        // Which depths the clobber list says the template pops.
5127        let clobbers = self.names.resolve(info.clobbers).to_string();
5128        let mut popped = [false; 2];
5129        for entry in clobbers.split(',') {
5130            let entry = entry.trim().trim_matches('"');
5131            let entry = entry.strip_prefix('%').unwrap_or(entry);
5132            match entry {
5133                "" | "memory" | "cc" | "flags" => {}
5134                "st" | "st(0)" => popped[0] = true,
5135                "st(1)" => popped[1] = true,
5136                _ => return Err(Unsupported::Assembly { inst, refused: Written::Clobber }),
5137            }
5138        }
5139
5140        // The inputs, one per depth and from the top down with no gap, and each one popped.
5141        let mut inputs: Vec<Option<Value>> = vec![None; 2];
5142        let mut outputs: Vec<Option<Value>> = vec![None; 2];
5143        for (index, operand) in list.iter().enumerate() {
5144            let depth = depths[index];
5145            if let Some(result) = operand.result {
5146                if outputs[depth].replace(result).is_some() {
5147                    return Err(refused());
5148                }
5149            }
5150            let Some(value) = operand.value else { continue };
5151            // An output written `+` is an input tied to itself.
5152            let consumed = operand.result.is_some() || operand.tied.is_some() || popped[depth];
5153            if !consumed {
5154                return Err(refused());
5155            }
5156            if inputs[depth].replace(value).is_some() {
5157                return Err(refused());
5158            }
5159        }
5160        let gapless =
5161            |held: &[Option<Value>]| held.iter().skip_while(|it| it.is_some()).all(Option::is_none);
5162        if !gapless(&inputs) || !gapless(&outputs) {
5163            return Err(refused());
5164        }
5165
5166        // The text, with an operand spelled as the register it is in.
5167        let template = self.names.resolve(info.template).to_string();
5168        let mut text = String::with_capacity(template.len());
5169        let mut chars = template.chars().peekable();
5170        while let Some(c) = chars.next() {
5171            if c != '%' {
5172                text.push(c);
5173                continue;
5174            }
5175            match chars.peek().copied() {
5176                Some('%') => {
5177                    chars.next();
5178                    text.push('%');
5179                }
5180                Some('=') => {
5181                    chars.next();
5182                    text.push_str(&inst.index().to_string());
5183                }
5184                Some(digit) if digit.is_ascii_digit() => {
5185                    chars.next();
5186                    if chars.peek().is_some_and(char::is_ascii_digit) {
5187                        return Err(refused());
5188                    }
5189                    let index = digit.to_digit(10).map_or(usize::MAX, |it| it as usize);
5190                    match depths.get(index).ok_or_else(refused)? {
5191                        0 => text.push_str("%st"),
5192                        depth => text.push_str(&format!("%st({depth})")),
5193                    }
5194                }
5195                _ => return Err(refused()),
5196            }
5197        }
5198
5199        let span = self.source.span(inst);
5200        for value in inputs.iter().rev().flatten() {
5201            let from = self.x87_slot(*value);
5202            let from = self.through(from);
5203            self.x87_at("fld_t", span, from);
5204        }
5205        let symbol = self.names.intern(&text);
5206        let opcode = self.named(x86_64::TEMPLATE);
5207        let block = self.at.expect("a block is being filled");
5208        self.out.build(block, opcode).at(span).symbol(symbol).finish();
5209        for value in outputs.iter().flatten() {
5210            let into = self.x87_slot(*value);
5211            let into = self.through(into);
5212            self.x87_at("fstp_t", span, into);
5213        }
5214        Ok(())
5215    }
5216
5217    /// An `asm` statement on AArch64, which is kept as text whatever is in it.
5218    ///
5219    /// Nothing reads AArch64 assembly back into instructions yet, so every template goes the way
5220    /// one the x86 reader could not take apart goes, which is [`Self::kept`]: the text is carried
5221    /// to the listing with a hole for each operand, and the operands are the instruction's own. A
5222    /// constraint with a letter whose meaning differs between the two machines is refused first.
5223    /// See [`shared_letters`].
5224    fn spelled(&mut self, inst: Inst) -> Result<(), Unsupported> {
5225        let data = &self.source[inst];
5226        let Extra::Asm(asm) = data.extra else { return Err(self.unsupported(inst)) };
5227        let info = self.source[asm];
5228        if self.jumps_from_text(inst) {
5229            return Err(Unsupported::Assembly { inst, refused: Written::Goto });
5230        }
5231        let refused = || Unsupported::Assembly { inst, refused: Written::Operand };
5232        let constraints = self.names.resolve(info.constraints).to_string();
5233        if !constraints.split(',').all(shared_letters) {
5234            return Err(refused());
5235        }
5236        // `Q` is memory addressed by one register and nothing else, which is how every operand in
5237        // memory is spelled here already, so it is read as `m`. See [`shared_letters`].
5238        let constraints = letters_outside(&constraints, |c| if c == 'Q' { 'm' } else { c });
5239        let results: Vec<Value> = data.results().collect();
5240        let operands = AsmOperands::read(&constraints, &results, &self.source[data.args])
5241            .ok_or_else(refused)?;
5242        let list: Vec<AsmOperand<'_>> = operands.iter().copied().collect();
5243        let widths = vec![None; list.len()];
5244        let memory: Vec<bool> = list.iter().map(|operand| operand.memory).collect();
5245        let template = self.names.resolve(info.template).to_string();
5246        self.kept(inst, &template, &list, &widths, &memory)
5247    }
5248
5249    /// One instruction of a template, as the machine instruction it was read back into.
5250    fn instruction(
5251        &mut self,
5252        inst: Inst,
5253        line: &x86_64::Line,
5254        places: &[Place],
5255        list: &[AsmOperand<'_>],
5256        clobbered: &[PhysReg],
5257    ) -> Result<(), Unsupported> {
5258        let refused = || Unsupported::Assembly { inst, refused: Written::Operand };
5259        let form = x86_64::form(line.opcode).ok_or_else(refused)?;
5260        // What the instruction reaches and what is in each of them. The description answers the
5261        // first for every opcode but one, and the pieces the template was read into answer the
5262        // second. Bytes a program wrote out itself are the one, since nothing in a number is a
5263        // register anybody could read, so the constraint letters answer both. See
5264        // [`Self::lettered`].
5265        let lettered = (line.opcode == x86_64::LITERAL).then(|| self.lettered(list));
5266        let (described, pieces) = match &lettered {
5267            Some((described, pieces)) => (described.as_slice(), pieces.as_slice()),
5268            None => (form.operands(), line.operands.as_slice()),
5269        };
5270        let mut built = Vec::with_capacity(pieces.len() + clobbered.len());
5271        for (desc, piece) in described.iter().zip(pieces) {
5272            built.push(self.placed(inst, *desc, *piece, places, list)?);
5273        }
5274        // The clobbers go in among the definitions rather than behind the reads, because an operand
5275        // vector in the machine IR is every definition and then every use and what counts them
5276        // reads that order rather than each operand's role.
5277        let defs = built.iter().take_while(|operand| operand.role.is_def()).count();
5278        let mut added = 0usize;
5279        for &reg in clobbered {
5280            if described.iter().any(|desc| desc.constraint == Constraint::Fixed(reg)) {
5281                continue;
5282            }
5283            built.insert(defs, mir::Operand::write(mir::Reg::physical(reg), self.gpr));
5284            added += 1;
5285        }
5286        // A constraint tying one operand to another names it by its place in this vector, and the
5287        // clobbers were put in the middle of the vector, so everything behind them moved. The
5288        // description is written against an instruction with no clobbers in it and cannot know
5289        // that, which makes this the one place the two numberings have to be reconciled.
5290        for operand in &mut built {
5291            if let Constraint::Reuse(at) = operand.constraint {
5292                if usize::from(at) >= defs {
5293                    let moved = usize::from(at) + added;
5294                    operand.constraint =
5295                        Constraint::Reuse(u8::try_from(moved).map_err(|_| refused())?);
5296                }
5297            }
5298        }
5299        let at = match line.at {
5300            Some(at) => Some(self.addressed(inst, at, places, list)?),
5301            None => None,
5302        };
5303
5304        let block = self.at.expect("a block is being filled");
5305        let span = self.source.span(inst);
5306        let opcode = self.named(line.opcode);
5307        let mut build = self.out.build(block, opcode).at(span);
5308        for operand in built {
5309            build = build.operand(operand);
5310        }
5311        if let Some(value) = line.imm {
5312            build = build.imm(value);
5313        }
5314        if let Some(mem) = at {
5315            build = build.mem(mem);
5316        }
5317        build.finish();
5318        Ok(())
5319    }
5320
5321    /// The registers a run of bytes reaches, taken from the constraint letters rather than from the
5322    /// description of an opcode.
5323    ///
5324    /// Every other instruction of a template has a description saying which registers it reaches
5325    /// without naming them, and [`Self::assembly`] matches the letters against that. Bytes a program
5326    /// wrote out itself have no such description and could not have one: what the instruction is, is
5327    /// a number, and nothing in a number is a register anything could read. So the letters are the
5328    /// whole of what is known, and they are enough, because a program writing an instruction this
5329    /// way has to say where its operands go for exactly the reason a program writing `cpuid` does.
5330    ///
5331    /// Each register named by a letter gets one entry for the write and one for the read, the same
5332    /// two `cpuid` has, and only the half the statement asked for: a register no output names is not
5333    /// written here and one no input names is not read. The writes come first because that is the
5334    /// order an operand vector in the machine IR is counted in. A register named by nothing is left
5335    /// out rather than given a spare one, which is the difference from `cpuid` and is right for the
5336    /// same reason: `cpuid` writes four registers whatever the program said, and what these bytes
5337    /// touch is known only from what the program said.
5338    fn lettered(&self, list: &[AsmOperand<'_>]) -> (Vec<OperandDesc>, Vec<x86_64::Piece>) {
5339        let mut named: Vec<PhysReg> = Vec::new();
5340        for operand in list {
5341            if let Some(reg) = pinned(operand) {
5342                if !named.contains(&reg) {
5343                    named.push(reg);
5344                }
5345            }
5346        }
5347        let mut described = Vec::with_capacity(named.len() * 2);
5348        let mut pieces = Vec::with_capacity(named.len() * 2);
5349        for role in [Role::Def, Role::Use] {
5350            for &reg in &named {
5351                if bound(list, reg, role).is_none() {
5352                    continue;
5353                }
5354                let desc = if role.is_def() {
5355                    OperandDesc::write(self.gpr)
5356                } else {
5357                    OperandDesc::read(self.gpr)
5358                };
5359                described.push(desc.with(Constraint::Fixed(reg)));
5360                pieces.push(x86_64::Piece::Implicit { reg });
5361            }
5362        }
5363        (described, pieces)
5364    }
5365
5366    /// One operand of one instruction of a template, in the register the statement put it in.
5367    fn placed(
5368        &mut self,
5369        inst: Inst,
5370        desc: OperandDesc,
5371        piece: x86_64::Piece,
5372        places: &[Place],
5373        list: &[AsmOperand<'_>],
5374    ) -> Result<mir::Operand, Unsupported> {
5375        let refused = || Unsupported::Assembly { inst, refused: Written::Operand };
5376        // A register the instruction reaches without its text naming it belongs to whichever of the
5377        // statement's operands a constraint letter put there, and to nobody when no letter did.
5378        // There is no width to check in that case: the operand is the register the letter named and
5379        // the instruction does what it does to it, which is what a program writing `"=a"` asked for.
5380        let (index, spelled) = match piece {
5381            x86_64::Piece::Operand { index, width, stated } => (index, Some((width, stated))),
5382            x86_64::Piece::Implicit { reg } => match bound(list, reg, desc.role) {
5383                Some(index) => (index, None),
5384                None => return self.spare(inst, desc),
5385            },
5386            // A register the template named, which belongs to one of the statement's operands when
5387            // a constraint letter put that operand there and to nobody otherwise. Asked in that
5388            // order rather than placed straight away, because `"D" (p)` with `%rdi` in the text is
5389            // the program saying one thing twice, and answering it twice would hand the allocator
5390            // one register holding two values.
5391            x86_64::Piece::Reg { reg, .. } => match bound(list, reg, desc.role) {
5392                Some(index) => (index, None),
5393                None => return self.itself(inst, desc, reg),
5394            },
5395        };
5396        let operand = list.get(index).copied().ok_or_else(refused)?;
5397        // The two halves of an operand written `+`, which arrives in one register and leaves in
5398        // another with the allocator told to make them the same one. Everything else has one of
5399        // the two and asking for the other is the refusal below.
5400        let place = places.get(index).copied().ok_or_else(refused)?;
5401        let reg = match desc.role {
5402            Role::Use => place.read,
5403            Role::Def | Role::EarlyDef => place.write,
5404        }
5405        .ok_or_else(refused)?;
5406
5407        // Read where the opcode reads and written where it writes, which is what the first half of
5408        // this asks. An output has a result and an input has a value, an output written `+` has
5409        // both because it is read before it is written, and an output a matching constraint names
5410        // is read as the input that named it. See [`read_as`].
5411        // An output with neither is read as well, and what it holds there is undefined, which
5412        // [`Self::assembly`] says why and puts a zero in a register for.
5413        let placeable = match desc.role {
5414            Role::Use => read_as(list, index).is_some() || operand.result.is_some(),
5415            Role::Def | Role::EarlyDef => operand.result.is_some(),
5416        };
5417        let ty = match (operand.result, operand.value) {
5418            (Some(result), _) => self.source[result].ty,
5419            (None, Some(value)) => self.source[value].ty,
5420            (None, None) => return Err(refused()),
5421        };
5422        let bits = held_bits(ty);
5423        if !placeable || self.class_of(ty) != desc.class {
5424            return Err(refused());
5425        }
5426        if let Some((width, stated)) = spelled {
5427            // An operand the template wrote a width on may be written by an instruction that fills
5428            // more of the register than the object in it does, and the object is then the low part
5429            // of what was written. That is what gmp asks for when it counts the low zero bits of a
5430            // limb into an `unsigned` and spells the count `%q0`: one quadword instruction writes
5431            // the whole register and the `unsigned` is the bottom of it, which is every bit of an
5432            // answer that cannot exceed sixty four anyway.
5433            //
5434            // An operand read at a width the template wrote is the other way round: the object is
5435            // in the register and the instruction looks at the bottom of it. tcc tests the low bits
5436            // of a `size_t` count with `testb $2,%b4`, and every bit that test reads is one the
5437            // object put there.
5438            //
5439            // A write of less of a register than the object fills is right in one case, which is
5440            // an instruction that reads the register it writes and an operand that arrives with
5441            // the object in it. The top of the register is then the top of the object, and the
5442            // instruction leaves it alone. tcc swaps the bytes of an `unsigned` with `xchgb
5443            // %b0,%h0` and a rotate between two of them, and the swap only ever touches the low
5444            // half.
5445            //
5446            // The two that stay refused are a read of more of a register than its type fills,
5447            // which hands an instruction bits nothing ever put there, and a write of less of one
5448            // that nothing carried the object into, which leaves the top of the object holding
5449            // whatever the register held before. An operand the template left plain is refused
5450            // either way, because what gets spelled for that one is the register at the width of
5451            // its type and no other instruction is the one written down.
5452            let carried = matches!(desc.constraint, Constraint::Reuse(_) | Constraint::Fixed(_))
5453                && read_as(list, index).is_some();
5454            // The other case is the one the machine settles by itself: a write of the low four
5455            // bytes of a register clears the four above them, so a sixty four bit object written
5456            // that way holds the thirty two bit answer and nothing else. tcc loads a word through
5457            // `movl 4(%0),%k0` into a `long` and means exactly that.
5458            let cleared = desc.class == self.gpr && width == x86_64::Width::Long && bits == 64;
5459            let widened = stated && desc.role.is_def() && width.bits() > bits;
5460            let narrowed =
5461                stated && width.bits() < bits && (!desc.role.is_def() || carried || cleared);
5462            if bits != width.bits() && !widened && !narrowed {
5463                return Err(refused());
5464            }
5465        }
5466        // An operand the program pinned is in that register and nowhere else, whatever the opcode
5467        // would have allowed it. That is the whole of what a local register variable asks for, and
5468        // it is the same shape a division already has: the allocator is told the register, puts a
5469        // move in front or behind where it has to, and leaves it out where it does not.
5470        let constraint = match pinned(&operand) {
5471            Some(reg) => Constraint::Fixed(reg),
5472            None => desc.constraint,
5473        };
5474        Ok(mir::Operand { reg, class: desc.class, role: desc.role, constraint })
5475    }
5476
5477    /// A register the template named in its own text.
5478    ///
5479    /// Not one of the statement's operands and not something the allocator handed out. The program
5480    /// wrote `%rbx` in the middle of a template and meant that register, which is what code doing
5481    /// something the constraint letters cannot say is made of: micropython saves the callee-saved
5482    /// registers into a buffer by name because the whole point of the buffer is that those exact
5483    /// registers are in it, and there is no constraint letter for `%rsp`.
5484    ///
5485    /// So it is placed as itself, fixed to the register the template named. What that buys is the
5486    /// thing gcc does not do: the register becomes part of the instruction the allocator sees, so a
5487    /// write of one is a definition it knows about and will not leave anything of the program's
5488    /// across, and a read of one is a use it will not have put something else in first. gcc copies
5489    /// the text out and a register two things believe they own is a wrong program nothing reports.
5490    /// Here the allocator is told, and a program that also named the register in its clobber list
5491    /// says the same thing twice rather than something new.
5492    fn itself(
5493        &mut self,
5494        inst: Inst,
5495        desc: OperandDesc,
5496        reg: PhysReg,
5497    ) -> Result<mir::Operand, Unsupported> {
5498        let refused = Unsupported::Assembly { inst, refused: Written::Operand };
5499        if desc.class != self.gpr {
5500            return Err(refused);
5501        }
5502        Ok(mir::Operand {
5503            reg: mir::Reg::physical(reg),
5504            class: self.gpr,
5505            role: desc.role,
5506            constraint: Constraint::Fixed(reg),
5507        })
5508    }
5509
5510    /// A register an instruction of a template uses and the statement put nothing in.
5511    ///
5512    /// A write of one is the register being destroyed, which is what a clobber list is usually
5513    /// written to say and what an instruction with more answers than the program asked for does
5514    /// anyway: `cpuid` writes all four registers whether or not the statement wanted all four. A
5515    /// register of its own is the whole of what that needs, since a value nothing reads is one the
5516    /// allocator may put anywhere and is told about so that nothing else is put there.
5517    ///
5518    /// A read of one is a register the instruction looks at and the program never filled, which
5519    /// gcc leaves as whatever happened to be there. A zero is written instead, for the reason
5520    /// [`Self::undefined`] gives: the allocator has to be given a definition before a use, and a
5521    /// zero is the one answer that reads the same on every run.
5522    fn spare(&mut self, inst: Inst, desc: OperandDesc) -> Result<mir::Operand, Unsupported> {
5523        let refused = Unsupported::Assembly { inst, refused: Written::Operand };
5524        if desc.class != self.gpr {
5525            return Err(refused);
5526        }
5527        let reg = self.out.new_vreg(desc.class);
5528        if !desc.role.is_def() {
5529            let block = self.at.expect("a block is being filled");
5530            let span = self.source.span(inst);
5531            let put = self.named("mov_ri_64");
5532            self.out.build(block, put).at(span).def(reg, desc.class).imm(0).finish();
5533        }
5534        Ok(mir::Operand { reg, class: desc.class, role: desc.role, constraint: desc.constraint })
5535    }
5536
5537    /// The address one instruction of a template reads or writes.
5538    fn addressed(
5539        &mut self,
5540        inst: Inst,
5541        at: x86_64::At,
5542        places: &[Place],
5543        list: &[AsmOperand<'_>],
5544    ) -> Result<mir::Mem, Unsupported> {
5545        let refused = || Unsupported::Assembly { inst, refused: Written::Operand };
5546        let base = match at.base {
5547            None => None,
5548            Some(x86_64::Piece::Operand { index, .. }) => {
5549                // The register an address is counted from is read and never written, whatever the
5550                // instruction does to what it finds there.
5551                let reg = places.get(index).and_then(|place| place.read).ok_or_else(refused)?;
5552                Some(mir::Operand::read(reg, self.gpr))
5553            }
5554            // A register the template named, counted from as itself. See [`Self::itself`], and note
5555            // that this is the half of it every one of these templates needs: `movq %rax, 16(%rdi)`
5556            // names one register as the thing being stored and another as where to store it. An
5557            // operand a constraint letter put in that register is that operand, for the reason
5558            // [`Self::placed`] gives.
5559            Some(x86_64::Piece::Reg { reg, .. }) => match bound(list, reg, Role::Use) {
5560                Some(index) => {
5561                    let reg = places.get(index).and_then(|place| place.read).ok_or_else(refused)?;
5562                    Some(mir::Operand::read(reg, self.gpr))
5563                }
5564                None => Some(
5565                    mir::Operand::read(mir::Reg::physical(reg), self.gpr)
5566                        .with(Constraint::Fixed(reg)),
5567                ),
5568            },
5569            // An address counted from a register the instruction reaches without being told is
5570            // not something this machine has: every addressing mode is written out in the text it
5571            // is part of, so a base that got here another way is a base nothing wrote down.
5572            Some(x86_64::Piece::Implicit { .. }) => return Err(refused()),
5573        };
5574        // A distance the template wrote, or the one in an operand the template pointed at, which is
5575        // the same distance said by something that knows how big a thing is. It has to be a number
5576        // the compiler can read at translation time, since it goes in the instruction rather than
5577        // in a register, and an operand holding anything else is refused rather than put somewhere.
5578        let disp = match at.disp {
5579            x86_64::Disp::Number(disp) => disp,
5580            x86_64::Disp::Operand(index) => {
5581                let value =
5582                    list.get(index).and_then(|operand| operand.value).ok_or_else(refused)?;
5583                let number = self.number(value).ok_or_else(refused)?;
5584                i32::try_from(number).map_err(|_| refused())?
5585            }
5586        };
5587        Ok(mir::Mem { base, scale: 1, disp, segment: at.segment, ..mir::Mem::default() })
5588    }
5589
5590    /// The number in that value, for one an `iconst` defined, read at the width of its own type.
5591    ///
5592    /// Signed, because the two things a template asks this for are a distance into an address and
5593    /// the number on an instruction, and both of those are signed wherever they land. A constant
5594    /// whose type is unsigned and whose top bit is set therefore reads as a negative number here,
5595    /// which is the same number and is the reading that fits in the thirty two bits an addressing
5596    /// mode has room for.
5597    fn number(&self, value: Value) -> Option<i128> {
5598        let Def::Result { inst, .. } = self.source[value].def else { return None };
5599        if self.source[inst].opcode != Opcode::IConst {
5600            return None;
5601        }
5602        let Extra::Imm(imm) = self.source[inst].extra else { return None };
5603        let bits = self.source[imm].bits();
5604        let width = self.source[value].ty.bits();
5605        if width == 0 || width > 128 {
5606            return None;
5607        }
5608        let spare = 128 - width;
5609        Some(((bits << spare) as i128) >> spare)
5610    }
5611
5612    /// A register holding a value the program has no claim on, written as a zero.
5613    ///
5614    /// Every other way of saying it costs the same instruction or needs a word the machine IR does
5615    /// not have, and a zero is the one that reads the same on every run.
5616    fn undefined(&mut self, inst: Inst, result: Value) -> Result<(), Unsupported> {
5617        let ty = self.source[result].ty;
5618        let refused = Unsupported::Assembly { inst, refused: Written::Operand };
5619        let bits = held_bits(ty);
5620        if self.class_of(ty) != self.gpr || !matches!(bits, 8 | 16 | 32 | 64) {
5621            return Err(refused);
5622        }
5623        let block = self.at.expect("a block is being filled");
5624        let span = self.source.span(inst);
5625        let reg = self.new_reg(result);
5626        let put = self.named(&format!("mov_ri_{bits}"));
5627        self.out.build(block, put).at(span).def(reg, self.gpr).imm(0).finish();
5628        Ok(())
5629    }
5630
5631    /// Whether a type is the width an address is, which is what makes a cast to or from one free.
5632    fn is_address_width(&self, ty: Type) -> bool {
5633        ty.is_ptr() || (ty.is_int() && ty.bits() == ADDRESS_BITS)
5634    }
5635
5636    /// Where a block goes, which in machine IR is on the block rather than on its terminator.
5637    ///
5638    /// That is why no rule ever names a block: a branch is selected for what it reads and the
5639    /// edges are copied across here, arguments and all. The arguments are read last, after every
5640    /// instruction of the block is written, because an argument that is a constant is
5641    /// materialized where it is first wanted and the end of the block is where an edge wants it.
5642    ///
5643    /// Which is not quite the end. A block that leaves two ways has the branch as its last
5644    /// instruction, and a block that leaves through a register has the indirect jump as its last,
5645    /// and anything appended after either is something it has already jumped past, so a constant
5646    /// materialized here would be a register the block below reads and nothing ever writes. The
5647    /// one that was there is put back on the end when that happened, which is the only reordering
5648    /// anything in this crate does and is why it is remembered before a single argument is read.
5649    fn edges(&mut self, block: Block, out: mir::Block) -> Result<(), Unsupported> {
5650        let Some(term) = self.source.terminator(block) else { return Ok(()) };
5651        // An `asm goto` whose template has nothing in it can only fall through, since there is no
5652        // instruction in it to jump with, so the only edge the machine block gets is the first
5653        // one. The labels it names are still arms in the IR, which is what kept the passes above
5654        // from assuming anything about the way into them, and here they are blocks nothing jumps
5655        // to, the same as a label no `goto` names. One that does have instructions was refused by
5656        // [`Self::jumps_from_text`] before this.
5657        if self.source[term].opcode == Opcode::InlineAsm {
5658            let Some(call) = self.source.successors(term).next() else { return Ok(()) };
5659            let args: Vec<Value> = self.source[call.args].to_vec();
5660            let regs =
5661                args.into_iter().map(|value| self.reg_of(value)).collect::<Result<_, _>>()?;
5662            *self.out.succs_mut(out) = vec![mir::BlockCall::with(self.out_block(call.block), regs)];
5663            return Ok(());
5664        }
5665        // A call's unwind edge, which is not an edge of the machine function at all. The branch was
5666        // never written, so what the block has is the arm control takes when the call returns, and
5667        // the pad is a block with nothing in front of it that the call site table is what reaches.
5668        // See [`Self::pad`] for why that is a block the allocator can be handed.
5669        if let Some(unwound) = self.unwind_edge(term) {
5670            let arms: Vec<rucc_ir::BlockCall> = self.source.successors(term).collect();
5671            let next = arms[1];
5672            let args: Vec<Value> = self.source[next.args].to_vec();
5673            let regs =
5674                args.into_iter().map(|value| self.reg_of(value)).collect::<Result<_, _>>()?;
5675            *self.out.succs_mut(out) = vec![mir::BlockCall::with(self.out_block(next.block), regs)];
5676            let call = self.source.prev_inst(unwound).and_then(|call| self.unwinding.get(&call));
5677            if let Some(&call) = call {
5678                let pad = self.out_block(arms[0].block);
5679                self.out.landings.push((call, pad));
5680            }
5681            return Ok(());
5682        }
5683        let leaves =
5684            matches!(self.source[term].opcode, Opcode::BrIf | Opcode::IndirectBr | Opcode::Switch);
5685        let branch = if leaves { self.out.terminator(out) } else { None };
5686
5687        let calls: Vec<rucc_ir::BlockCall> = self.source.successors(term).collect();
5688        let mut succs = Vec::with_capacity(calls.len());
5689        for call in calls {
5690            let args: Vec<Value> = self.source[call.args].to_vec();
5691            let mut regs = Vec::with_capacity(args.len());
5692            for value in args {
5693                // The address of where the value is rather than the value, for the one type a
5694                // register holds none of. The block on the other side copies the bytes out of it
5695                // into a slot of its own, which is what makes a second edge into the same block
5696                // safe.
5697                let reg = if on_x87(self.source[value].ty) {
5698                    self.x87_slot(value)
5699                } else {
5700                    self.reg_of(value)?
5701                };
5702                regs.push(reg);
5703            }
5704            succs.push(mir::BlockCall::with(self.out_block(call.block), regs));
5705        }
5706        if let Some(branch) = branch {
5707            if self.out.terminator(out) != Some(branch) {
5708                self.out.remove_inst(branch);
5709                self.out.append_inst(out, branch);
5710            }
5711        }
5712        *self.out.succs_mut(out) = succs;
5713        Ok(())
5714    }
5715
5716    /// The `unwound` a branch reads, when the branch is a call's unwind edge.
5717    fn unwind_edge(&self, inst: Inst) -> Option<Inst> {
5718        let data = &self.source[inst];
5719        if data.opcode != Opcode::BrIf {
5720            return None;
5721        }
5722        let &cond = self.source[data.args].first()?;
5723        match self.source[cond].def {
5724            Def::Result { inst, .. } if self.source[inst].opcode == Opcode::Unwound => Some(inst),
5725            _ => None,
5726        }
5727    }
5728
5729    /// The exception a landing pad was entered with, as a copy out of the register the unwinder
5730    /// left it in, which is the first register a value comes back in.
5731    fn landing(&mut self, inst: Inst) -> Result<(), Unsupported> {
5732        let result = self.source[inst].first_result.ok_or_else(|| self.unsupported(inst))?;
5733        let held = *self.conv.int_returns.first().ok_or_else(|| self.unsupported(inst))?;
5734        let block = self.at.expect("a block is being filled");
5735        let span = self.source.span(inst);
5736        let mov = self.selector.frame.moves(self.gpr).expect("a class the target says how to move");
5737        let mov = self.named(mov.mov);
5738        let into = self.new_reg(result);
5739        self.out
5740            .build(block, mov)
5741            .at(span)
5742            .operand(mir::Operand::write(into, self.gpr))
5743            .operand(
5744                mir::Operand::read(mir::Reg::physical(held), self.gpr)
5745                    .with(Constraint::Fixed(held)),
5746            )
5747            .finish();
5748        Ok(())
5749    }
5750
5751    /// Makes a landing pad a block that reads nothing from the blocks around it, and says what to
5752    /// put back once it has been filled.
5753    ///
5754    /// The pad has no machine block in front of it, because the edge into it is not one the machine
5755    /// takes: control arrives from the unwinder, with the registers the frame rules at the call put
5756    /// back. So nothing the allocator keeps in a register can reach it, and a value it reads from
5757    /// elsewhere is made again inside it. What a pad reads is the address of each object a handler
5758    /// is owed, which is a slot of the frame, the address of a name, or a constant, and each of
5759    /// those can be written a second time from nothing. Anything else is refused.
5760    ///
5761    /// The registers the rest of the function knows those values by are put back afterwards,
5762    /// which is what the answer is for: the pad's copies are its own.
5763    fn pad(&mut self, block: Block) -> Result<Vec<(Value, Option<mir::Reg>)>, Unsupported> {
5764        let mut kept = Vec::new();
5765        let first = self.source.insts(block).next();
5766        if !first.is_some_and(|inst| self.source[inst].opcode == Opcode::Landing) {
5767            return Ok(kept);
5768        }
5769        let out = self.at.expect("a block is being filled");
5770        let insts: Vec<Inst> = self.source.insts(block).collect();
5771        for inst in insts {
5772            let args: Vec<Value> = self.source[self.source[inst].args].to_vec();
5773            for value in args {
5774                let Def::Result { inst: def, .. } = self.source[value].def else {
5775                    return Err(self.unsupported(inst));
5776                };
5777                if self.source.block_of(def) == Some(block)
5778                    || kept.iter().any(|&(done, _)| done == value)
5779                {
5780                    continue;
5781                }
5782                match self.source[def].opcode {
5783                    Opcode::IConst => {}
5784                    Opcode::Alloca => {
5785                        let &index =
5786                            self.frame_slots.get(&value).ok_or_else(|| self.unsupported(def))?;
5787                        kept.push((value, self.regs[value.index()]));
5788                        let reg = self.out.new_vreg(self.gpr);
5789                        self.regs[value.index()] = Some(reg);
5790                        let lea = self.named(self.selector.frame.lea);
5791                        let sp = mir::Reg::physical(self.conv.stack_pointer);
5792                        let sp = mir::Operand::read(sp, self.gpr);
5793                        let span = self.source.span(def);
5794                        let made = self
5795                            .out
5796                            .build(out, lea)
5797                            .at(span)
5798                            .def(reg, self.gpr)
5799                            .mem(mir::Mem::at(sp))
5800                            .finish();
5801                        self.stack.addresses.push((made, index));
5802                    }
5803                    Opcode::GlobalAddr => {
5804                        kept.push((value, self.regs[value.index()]));
5805                        self.regs[value.index()] = None;
5806                        self.address_of(def)?;
5807                    }
5808                    _ => return Err(self.unsupported(def)),
5809                }
5810            }
5811        }
5812        Ok(kept)
5813    }
5814
5815    /// Whether an `asm goto` has instructions in its template, which is what it would jump with.
5816    ///
5817    /// One with an empty template is what a program writes to tell the optimizer that control may
5818    /// arrive at a label without saying how, and the torture suite has several of them. It never
5819    /// jumps, so it is written as the statement it would be without its labels and a fall through
5820    /// into its first arm. See [`Self::edges`]. One with anything in it needs the labels it names
5821    /// written into the text and an edge for each of them the allocator knows about, and that is
5822    /// still refused.
5823    fn jumps_from_text(&self, inst: Inst) -> bool {
5824        let Extra::Asm(asm) = self.source[inst].extra else { return false };
5825        let info = self.source[asm];
5826        !self.source[info.targets].is_empty()
5827            && !self.names.resolve(info.template).trim().is_empty()
5828    }
5829
5830    /// The machine IR block an IR block became.
5831    fn out_block(&self, block: Block) -> mir::Block {
5832        self.blocks[block.index()].expect("every block was created before any was filled")
5833    }
5834
5835    /// The parameters of the entry block, which are the function's arguments.
5836    ///
5837    /// They are not block parameters in the machine IR and they cannot be. A block parameter is
5838    /// given its value by a move on the edge into the block, and there is no edge into an entry
5839    /// block, so what arrives in a function is the convention's to say. [`crate::abi`] is what
5840    /// says it.
5841    ///
5842    /// The ones past the last register arrived in the caller's memory and are read out of it, and
5843    /// the loads that read them come back here so that the frame can finish them the way it
5844    /// finishes an `alloca`.
5845    fn arrive(&mut self, block: Block, out: mir::Block) -> Result<(), Unsupported> {
5846        let params = self.source[block].params.clone();
5847        // The type of each is the block's answer and what the ABI asks of it is the signature's,
5848        // and the two lists are the same list: a parameter the classification turned into a
5849        // pointer is a pointer in the block too. A block with more parameters than the signature
5850        // names is not one the front end writes, and each of those is taken as a plain value.
5851        let asked: Vec<Abi> = self.source.signature().params.iter().map(|it| it.abi).collect();
5852        let types: Vec<Param> = params
5853            .iter()
5854            .enumerate()
5855            .map(|(index, &value)| {
5856                let abi = asked.get(index).copied().unwrap_or_default();
5857                Param { ty: self.source[value].ty, abi }
5858            })
5859            .collect();
5860        // A save area for a function that takes arguments its signature does not name, which is a
5861        // block of this function's frame on one convention and the shadow space the caller already
5862        // reserved on the other. Which of the two it is is [`varargs::Area::of`]'s answer and
5863        // [`Self::save_area`] is where the difference is spent.
5864        //
5865        // Apple's AArch64 is neither. Every argument a signature does not name is in the caller's
5866        // memory, so there is nothing to save and the list starts at the first word past the named
5867        // ones.
5868        //
5869        // A function holding `__builtin_apply_args` asks for the same area whether it is variadic
5870        // or not, because what it saves is every argument register, and the area is where the
5871        // walk that binds them says where each one goes.
5872        let variadic = self.source.signature().variadic;
5873        let in_memory = self.conv.abi.variadic == Variadic::AlwaysMemory;
5874        let applies = self.saves_arguments();
5875        let area = (variadic && !in_memory || applies).then(|| varargs::Area::of(self.conv));
5876        let arrived =
5877            abi::entry(&mut self.out, out, &types, self.conv, self.selector.abi, self.names, area)
5878                .map_err(|(index, missing)| Unsupported::Argument { index, missing })?;
5879        for (&param, reg) in params.iter().zip(&arrived.regs) {
5880            self.regs[param.index()] = Some(*reg);
5881        }
5882        if applies {
5883            self.save_arguments(out, &arrived);
5884        }
5885        if let (true, Some(area)) = (variadic && !in_memory, area) {
5886            self.save_area(out, &arrived, area);
5887        } else if variadic {
5888            let incoming = arrived.beyond.next_multiple_of(self.conv.word);
5889            self.varargs = Some(Varargs::Pointer { incoming });
5890        }
5891        self.stack.arguments.extend(arrived.stack);
5892        Ok(())
5893    }
5894
5895    /// The prologue of a variadic function, which is every argument register it was handed written
5896    /// into the frame.
5897    ///
5898    /// Every one the signature did not name, that is. Which of those hold anything is a thing only
5899    /// the caller knew and there is nothing here to ask, so all of them are written, and the ones a
5900    /// named parameter took are not, because `va_start` sets the two offsets past them and nothing
5901    /// ever reads their slots.
5902    ///
5903    /// What that costs is up to fourteen stores in the prologue of a function that may read none of
5904    /// them, and the convention's answer to that is the count of vector registers in `%al`, which
5905    /// lets a callee skip the eight vector stores when the call passed no floats. Skipping them is a
5906    /// branch in a prologue, and a prologue is written long after this by [`crate::finish`], which
5907    /// has no blocks to branch between. So they are all written every time, which is correct and is
5908    /// what `-O0` costs. Issue #323 is the branch.
5909    ///
5910    /// A vector register is written all sixteen bytes at a time, because a `_Float128` fills one and
5911    /// a `va_arg` of a quad reads the slot back whole. gcc writes the same sixteen with the same
5912    /// instruction, which is what [`crate::varargs`] says a list has to be built out of.
5913    ///
5914    /// The address is computed once into a register rather than written as a displacement off the
5915    /// stack pointer, because a displacement into a frame is not known until after allocation and
5916    /// one `lea` costs less than a fixup list for a dozen stores. It is the same `lea` an `alloca`
5917    /// gets and [`crate::finish`] fills it in the same way.
5918    ///
5919    /// A convention that homes its register arguments has none of that. Its area is the shadow
5920    /// space the caller reserved above the return address, so there is no object to make and no
5921    /// address to work out: each store reaches into the caller's argument area the way the load of
5922    /// a parameter the registers ran out before does, which is the same waiting list and the same
5923    /// fixup. There are at most four of them and none is a vector register, since a float the
5924    /// signature does not name arrived in a general purpose register too and that is the copy the
5925    /// walk reads.
5926    fn save_area(&mut self, out: mir::Block, arrived: &abi::Arrived, area: varargs::Area) {
5927        if self.conv.shared_positions {
5928            self.varargs = Some(Varargs::Pointer { incoming: arrived.beyond });
5929            let store = self.named("mov_mr_64");
5930            for &(reg, class, at) in &arrived.spare {
5931                let sp = mir::Operand::read(mir::Reg::physical(self.conv.stack_pointer), self.gpr);
5932                let made =
5933                    self.out.build(out, store).uses(reg, class).mem(mir::Mem::at(sp)).finish();
5934                self.stack.arguments.push((made, at));
5935            }
5936            return;
5937        }
5938
5939        let save = self.stack.locals.len();
5940        self.stack.locals.push(Local { size: area.size, align: varargs::VECTOR_SLOT });
5941        let took = |count: usize, float: bool| {
5942            let count = u32::try_from(count).unwrap_or(0).min(area.holds(float));
5943            area.starts_at(float) + count * area.stride(float)
5944        };
5945        let integers = took(arrived.took.0, false);
5946        let floats = took(arrived.took.1, true);
5947        self.varargs = Some(if self.conv.list == VaList::Aapcs {
5948            // Minus what is left of each half, since the two offsets count up to its top.
5949            let left = |at: u32, float: bool| {
5950                i32::try_from(at).unwrap_or(0) - i32::try_from(area.ends_at(float)).unwrap_or(0)
5951            };
5952            Varargs::Aapcs {
5953                save,
5954                incoming: arrived.beyond,
5955                integers_end: area.ends_at(false),
5956                floats_end: area.ends_at(true),
5957                integers: left(integers, false),
5958                floats: left(floats, true),
5959            }
5960        } else {
5961            Varargs::Fields { save, incoming: arrived.beyond, integers, floats }
5962        });
5963
5964        // A vector register is saved all sixteen bytes wide, as a quad is, whatever it held.
5965        let base = self.frame_address(out, save);
5966        for &(reg, class, at) in &arrived.spare {
5967            let ty =
5968                if class == self.gpr { Type::int(64) } else { Type::float(rucc_ir::Float::F128) };
5969            let head = (self.selector.abi.store)(ty).expect("a store of a whole register");
5970            let store = mir::Opcode::new(self.names.intern(head));
5971            let up = i32::try_from(at).expect("a register save area under two gigabytes");
5972            let mem = mir::Mem::at(mir::Operand::read(base, self.gpr)).plus(up);
5973            self.out.build(out, store).uses(reg, class).mem(mem).finish();
5974        }
5975    }
5976
5977    /// Whether the function holds a `__builtin_apply_args`, on a convention this can save the
5978    /// arguments of.
5979    ///
5980    /// Only the one that keeps the two register files apart and saves them the way a SysV list
5981    /// does, since the block is that layout with one word in front of it. On any other the call is
5982    /// refused where it stands, which is [`Self::apply_args`] finding nothing saved.
5983    fn saves_arguments(&self) -> bool {
5984        if self.conv.list != VaList::SysV || self.conv.shared_positions {
5985            return false;
5986        }
5987        let source = self.source;
5988        source
5989            .blocks()
5990            .any(|block| source.insts(block).any(|inst| source[inst].opcode == Opcode::ApplyArgs))
5991    }
5992
5993    /// The prologue of a function holding `__builtin_apply_args`, which is every argument register
5994    /// it was handed and where the arguments in memory start, written into a block of its frame.
5995    ///
5996    /// The block is the one gcc lays out on this convention, so that a program reading it the way
5997    /// gcc's manual says reads the same bytes:
5998    ///
5999    /// ```text
6000    ///   0        where the arguments that came in memory are
6001    ///   8        nothing, so that what follows is sixteen byte aligned
6002    ///   16..64   the six general purpose argument registers, a word each
6003    ///   64..192  the eight vector argument registers, sixteen bytes each
6004    /// ```
6005    ///
6006    /// Which is the register save area of a variadic function with a word and a pad in front, so
6007    /// the offsets are that area's plus sixteen. What is different is that every register is
6008    /// written and not only the ones no parameter took: the one a parameter arrived in is written
6009    /// from the register the parameter was bound to, which holds it untouched because nothing has
6010    /// run yet, and the rest from the pseudos the walk made for them.
6011    fn save_arguments(&mut self, out: mir::Block, arrived: &abi::Arrived) {
6012        let applied = self.stack.locals.len();
6013        self.stack.locals.push(Local { size: APPLY_ARGS, align: varargs::VECTOR_SLOT });
6014        self.applied = Some(applied);
6015        let base = self.frame_address(out, applied);
6016        let overflow = self.overflow(out, 0, Span::DUMMY);
6017        let head = (self.selector.abi.store)(Type::int(64)).expect("a store of an address");
6018        let store = mir::Opcode::new(self.names.intern(head));
6019        let mem = mir::Mem::at(mir::Operand::read(base, self.gpr));
6020        self.out.build(out, store).uses(overflow, self.gpr).mem(mem).finish();
6021
6022        let named = arrived.named.iter().map(|&(index, at)| {
6023            let reg = arrived.regs[index];
6024            let class = self.out.class_of(reg).unwrap_or(self.gpr);
6025            (reg, class, at)
6026        });
6027        let every: Vec<_> = named.chain(arrived.spare.iter().copied()).collect();
6028        for (reg, class, at) in every {
6029            let ty =
6030                if class == self.gpr { Type::int(64) } else { Type::float(rucc_ir::Float::F128) };
6031            let head = (self.selector.abi.store)(ty).expect("a store of a whole register");
6032            let store = mir::Opcode::new(self.names.intern(head));
6033            let up = i32::try_from(at + APPLY_REGS).expect("a block of under two gigabytes");
6034            let mem = mir::Mem::at(mir::Operand::read(base, self.gpr)).plus(up);
6035            self.out.build(out, store).uses(reg, class).mem(mem).finish();
6036        }
6037    }
6038
6039    /// One `__builtin_apply_args`, which is the address of the block the prologue wrote.
6040    fn apply_args(&mut self, inst: Inst) -> Result<(), Unsupported> {
6041        let Some(applied) = self.applied else { return Err(self.unsupported(inst)) };
6042        let result = self.source[inst].first_result.ok_or_else(|| self.unsupported(inst))?;
6043        let block = self.at.expect("a block is being filled");
6044        let reg = self.frame_address(block, applied);
6045        self.regs[result.index()] = Some(reg);
6046        Ok(())
6047    }
6048
6049    /// One `__builtin_apply`, which is a call whose arguments are every register in a block
6050    /// `__builtin_apply_args` answered and some bytes of the memory it says the arguments in
6051    /// memory were in.
6052    ///
6053    /// Built as a call of fourteen arguments, six words and eight vectors, which puts each in the
6054    /// register it came out of, and one object of the size the program gave, which is copied into
6055    /// the bottom of the outgoing area the way a structure passed by value is. The call is made as
6056    /// to a variadic function, so the count of vector registers is eight and a variadic callee
6057    /// saves all of them.
6058    ///
6059    /// What comes back is every register a value can come back in, which is two of each file, and
6060    /// they are written into a block of this function's frame whose address is the answer: the two
6061    /// words at 0 and 8 and the two vectors at 16 and 32. An eighty bit value comes back on the x87
6062    /// stack and is not in it, which is the one thing gcc's block holds that this one does not.
6063    fn apply(&mut self, inst: Inst) -> Result<(), Unsupported> {
6064        if self.conv.list != VaList::SysV || self.conv.shared_positions {
6065            return Err(self.unsupported(inst));
6066        }
6067        let values: Vec<Value> = self.source[self.source[inst].args].to_vec();
6068        let [function, saved, size] = values[..] else { return Err(self.unsupported(inst)) };
6069        let size = self.number(size).ok_or_else(|| self.unsupported(inst))?;
6070        let size = u32::try_from(size).map_err(|_| self.unsupported(inst))?;
6071        let result = self.source[inst].first_result.ok_or_else(|| self.unsupported(inst))?;
6072        let function = self.reg_of(function)?;
6073        let saved = self.reg_of(saved)?;
6074        let block = self.at.expect("a block is being filled");
6075        let span = self.source.span(inst);
6076
6077        let word = Type::int(64);
6078        let vector = Type::float(rucc_ir::Float::F128);
6079        let area = varargs::Area::of(self.conv);
6080        let load = |ty: Type| (self.selector.abi.load)(ty).expect("a load of a whole register");
6081        let (load_word, load_vector) = (load(word), load(vector));
6082        let mut read = |ty: Type, head: &str, class: RegClass, at: u32| {
6083            let reg = self.out.new_vreg(class);
6084            let opcode = mir::Opcode::new(self.names.intern(head));
6085            let at = i32::try_from(at).expect("a block of under two gigabytes");
6086            let mem = mir::Mem::at(mir::Operand::read(saved, self.gpr)).plus(at);
6087            self.out.build(block, opcode).at(span).def(reg, class).mem(mem).finish();
6088            abi::Passing { ty, reg, abi: Abi::Plain }
6089        };
6090        let sse = self.conv.sse_class;
6091        let gpr = self.gpr;
6092        let mut args = Vec::with_capacity(15);
6093        for (float, ty, head, class) in
6094            [(false, word, load_word, gpr), (true, vector, load_vector, sse)]
6095        {
6096            for index in 0..area.holds(float) {
6097                let at = APPLY_REGS + area.starts_at(float) + index * area.stride(float);
6098                args.push(read(ty, head, class, at));
6099            }
6100        }
6101        if size > 0 {
6102            let memory = read(word, load_word, gpr, 0);
6103            let object =
6104                Abi::ByVal { size: u64::from(size), align: 8, drains: rucc_ir::Drains::Nothing };
6105            args.push(abi::Passing { abi: object, ..memory });
6106        }
6107        let returns = [word, word, vector, vector];
6108        let what = abi::Calling {
6109            callee: abi::Callee::Through(function),
6110            args: &args,
6111            returns: &returns,
6112            variadic: true,
6113            named: args.len(),
6114            at: span,
6115        };
6116        let made = abi::call(&mut self.out, block, &what, self.conv, self.selector.abi, self.names)
6117            .map_err(|refused| Unsupported::Call { inst, refused })?;
6118        let calls = &mut self.stack.calls;
6119        *calls = Some(calls.unwrap_or(0).max(made.outgoing));
6120
6121        let back = self.stack.locals.len();
6122        self.stack.locals.push(Local { size: APPLY_BACK, align: varargs::VECTOR_SLOT });
6123        let base = self.frame_address(block, back);
6124        for ((&reg, ty), at) in made.results.iter().zip(returns).zip([0, 8, 16, 32]) {
6125            let class = if ty == word { gpr } else { sse };
6126            let head = (self.selector.abi.store)(ty).expect("a store of a whole register");
6127            let store = mir::Opcode::new(self.names.intern(head));
6128            let mem = mir::Mem::at(mir::Operand::read(base, self.gpr)).plus(at);
6129            self.out.build(block, store).at(span).uses(reg, class).mem(mem).finish();
6130        }
6131        let answer = self.frame_address(block, back);
6132        self.regs[result.index()] = Some(answer);
6133        Ok(())
6134    }
6135
6136    /// The address of one of the function's stack objects, in a fresh register.
6137    ///
6138    /// Written with nothing in its displacement, because where an object is in a frame is not known
6139    /// until after allocation, and given to [`crate::finish`] to fill in the way an `alloca` is.
6140    fn frame_address(&mut self, out: mir::Block, local: usize) -> mir::Reg {
6141        self.frame_address_plus(out, local, 0)
6142    }
6143
6144    /// The address some way into a local, which the frame finishes the same way, adding where the
6145    /// local is to what is already there.
6146    fn frame_address_plus(&mut self, out: mir::Block, local: usize, plus: u32) -> mir::Reg {
6147        let reg = self.out.new_vreg(self.gpr);
6148        let lea = self.named(self.selector.frame.lea);
6149        let sp = mir::Operand::read(mir::Reg::physical(self.conv.stack_pointer), self.gpr);
6150        let plus = i32::try_from(plus).expect("an offset into a local under two gigabytes");
6151        let mem = mir::Mem::at(sp).plus(plus);
6152        let made = self.out.build(out, lea).def(reg, self.gpr).mem(mem).finish();
6153        self.stack.addresses.push((made, local));
6154        reg
6155    }
6156
6157    /// Whether an instruction is one no machine instruction is written for where it stands.
6158    ///
6159    /// Four of them, and none is a lowering decision, which is why none is a rule. A constant is
6160    /// written where a register for it is first wanted rather than where the IR put it, and every
6161    /// reader of one may have folded it into an immediate, in which case nowhere is the right
6162    /// place. A return of nothing has nothing to put anywhere: the epilogue gives the frame back
6163    /// and leaves, and it is appended to every block with no successors long after this has
6164    /// finished, so a return with a value is one instruction here and a return without one is
6165    /// none. Unless the value went back through memory, in which case there is something to put
6166    /// somewhere after all and the IR does not carry it: the address the caller handed over has
6167    /// to be in `rax` on the way out, and [`Lowering::returned`] is what writes that.
6168    ///
6169    /// An unconditional jump is the third, and there is even less of it: the edge is on the
6170    /// block, and whether the block it goes to is the next one and needs no jump at all is the
6171    /// block layout's answer rather than this one's.
6172    ///
6173    /// The fourth is a point control does not arrive at, in both of the forms the IR has for it:
6174    /// the `unreachable` terminator the front end puts at the end of a function whose body can run
6175    /// off the bottom, and the `unreachable_hint` a call to `__builtin_unreachable` becomes. What
6176    /// to write for a place nothing reaches is a question with no wrong answer, and nothing is the
6177    /// smallest one and the one gcc 16.2.0 gives at `-O0`. The terminator leaves the block with no
6178    /// successors, so the epilogue lands at the end of it the way it does on any other block that
6179    /// goes nowhere, and the function cannot fall out of its own last instruction into whatever
6180    /// the assembler puts next.
6181    fn writes_nothing(&self, inst: Inst) -> bool {
6182        let data = &self.source[inst];
6183        match data.opcode {
6184            Opcode::IConst | Opcode::Jump | Opcode::Unreachable | Opcode::UnreachableHint => true,
6185            // The question of whether a call unwound and the branch on its answer, neither of which
6186            // is an instruction. See [`Self::edges`].
6187            Opcode::Unwound => true,
6188            Opcode::BrIf => self.unwind_edge(inst).is_some(),
6189            Opcode::Return => self.source[data.args].is_empty() && self.sret().is_none(),
6190            _ => false,
6191        }
6192    }
6193
6194    /// What every instruction in one block matched, with a set of values nobody may take.
6195    ///
6196    /// Backwards, because an instruction that has been folded into a later one does not get to
6197    /// fold anything into itself: the rule that took it only reached one level down, so what is
6198    /// under it is not in the term the matcher saw and cannot be replaced.
6199    fn decide(&self, insts: &[Inst], refused: &HashSet<Value>) -> Decided {
6200        let mut found: Vec<Option<Match<Term>>> = (0..insts.len()).map(|_| None).collect();
6201        let mut plans: Vec<Option<Plan>> = vec![None; insts.len()];
6202        let mut folded: Vec<Inst> = Vec::new();
6203        for (index, &inst) in insts.iter().enumerate().rev() {
6204            if folded.contains(&inst) {
6205                continue;
6206            }
6207            if let Some((plan, matched)) = self.select(inst, refused) {
6208                folded.extend(self.folds(inst, plan));
6209                found[index] = Some(matched);
6210                plans[index] = Some(plan);
6211            }
6212        }
6213        Decided { found, plans, folded }
6214    }
6215
6216    /// A value some of its readers took and some of them did not, which is the one case folding
6217    /// buys nothing.
6218    ///
6219    /// Folding does not delete the instruction that computed a value for anybody else, so a
6220    /// reader that did not take it still needs it in a register and the instruction stays. The
6221    /// reader that did take it now does that work again. Either all of them take it, in which
6222    /// case nothing is left to read it and the instruction goes, or none of them do.
6223    ///
6224    /// The count is over the whole function rather than over the block, since a value read from
6225    /// another block is read from a register there whatever this block decides. An instruction
6226    /// built by name rather than matched, a call being the one that matters, has no plan and so
6227    /// takes nothing, which is the right answer for it as well.
6228    ///
6229    /// The count is kept only for the values this block's instructions take. It used to be a slot
6230    /// for every value in the function, cleared for every block, and on a function of thirty
6231    /// thousand blocks and a hundred and seventy thousand values that clearing was four percent of
6232    /// an optimized compile.
6233    fn left_alive(&self, insts: &[Inst], plans: &[Option<Plan>]) -> Option<Value> {
6234        let mut taken: HashMap<Value, u32> = HashMap::new();
6235        for (&inst, plan) in insts.iter().zip(plans) {
6236            let Some(plan) = plan else { continue };
6237            let args = &self.source[self.source[inst].args];
6238            for (index, &arg) in args.iter().take(MAX_ARGS).enumerate() {
6239                if plan[index] == Shown::Expand {
6240                    *taken.entry(arg).or_default() += 1;
6241                }
6242            }
6243        }
6244        for (&inst, plan) in insts.iter().zip(plans) {
6245            let Some(plan) = plan else { continue };
6246            let args = &self.source[self.source[inst].args];
6247            for (index, &arg) in args.iter().take(MAX_ARGS).enumerate() {
6248                if plan[index] == Shown::Expand && taken[&arg] < self.uses[arg.index()] {
6249                    return Some(arg);
6250                }
6251            }
6252        }
6253        None
6254    }
6255
6256    /// The rule that fires on an instruction, and what it bound.
6257    ///
6258    /// The plans are tried in order and the first that matches wins, which is the maximal munch
6259    /// `spec/10-backend.md` asks for: a plan that offers more to the matcher is tried before one
6260    /// that offers less.
6261    fn select(&self, inst: Inst, refused: &HashSet<Value>) -> Option<(Plan, Match<Term>)> {
6262        for plan in self.plans(inst, refused) {
6263            let terms = Terms::new(self.source, inst, plan);
6264            if let Some(matched) = self.selector.table.find(&terms, Term::Root) {
6265                return Some((plan, matched));
6266            }
6267        }
6268        None
6269    }
6270
6271    /// Every way this instruction can be shown to the matcher, most offered first.
6272    fn plans(&self, inst: Inst, refused: &HashSet<Value>) -> Vec<Plan> {
6273        let args = &self.source[self.source[inst].args];
6274        let mut plans = vec![PLAIN];
6275        for (index, &arg) in args.iter().enumerate().take(MAX_ARGS) {
6276            let mut ways = Vec::new();
6277            if self.foldable(inst, arg, refused) {
6278                ways.push(Shown::Expand);
6279            }
6280            if Terms::new(self.source, inst, PLAIN).constant(arg).is_some() {
6281                ways.push(Shown::Const);
6282            }
6283            ways.push(Shown::Reg);
6284            plans = plans
6285                .into_iter()
6286                .flat_map(|plan| {
6287                    ways.iter().map(move |&way| {
6288                        let mut next = plan;
6289                        next[index] = way;
6290                        next
6291                    })
6292                })
6293                .collect();
6294        }
6295        plans
6296    }
6297
6298    /// Whether an operand may be shown as the instruction that computed it.
6299    ///
6300    /// It has to be in the same block, because a rule that folds one instruction into another
6301    /// moves the work to where the second one is. It has to be something rather than a block
6302    /// parameter, and not a constant, which is shown as a constant instead. And it has to be a
6303    /// value [`Lowering::left_alive`] has not put back, which is how the one reader at a time
6304    /// question is asked here: this says yes to a value with any number of readers, and a value
6305    /// only some of them could take is refused after the fact and asked again.
6306    ///
6307    /// A value with several readers used to be refused outright, on the reasoning that folding
6308    /// does not delete the instruction for anybody else. That reasoning is about the set of
6309    /// readers and was being applied to one reader at a time, which is stricter than it needs to
6310    /// be: when every reader takes it there is nobody left to read it and the instruction goes.
6311    /// An address a store and a load share is the shape that matters, since a memory operand has
6312    /// room for the whole of it and both readers have a memory operand.
6313    fn foldable(&self, into: Inst, value: Value, refused: &HashSet<Value>) -> bool {
6314        let Def::Result { inst, .. } = self.source[value].def else { return false };
6315        if self.source[inst].opcode == Opcode::IConst || refused.contains(&value) {
6316            return false;
6317        }
6318        self.source.block_of(inst).is_some()
6319            && self.source.block_of(inst) == self.source.block_of(into)
6320    }
6321
6322    /// The instructions a match folded into the one it matched.
6323    ///
6324    /// The plan is what says this, not the bindings: a binding is a register or a number either
6325    /// way, and an operand shown as the instruction that computed it is one no rule could have
6326    /// matched without taking that instruction, because the plan offered the matcher nothing
6327    /// else to call it.
6328    fn folds(&self, inst: Inst, plan: Plan) -> Vec<Inst> {
6329        let args = &self.source[self.source[inst].args];
6330        args.iter()
6331            .take(MAX_ARGS)
6332            .enumerate()
6333            .filter(|&(index, _)| plan[index] == Shown::Expand)
6334            .filter_map(|(_, &arg)| match self.source[arg].def {
6335                Def::Result { inst, .. } => Some(inst),
6336                Def::Param { .. } => None,
6337            })
6338            .collect()
6339    }
6340
6341    /// What the IR instruction said about itself that the machine instruction has to keep saying.
6342    ///
6343    /// One flag today. `volatile` says the access happens exactly once and is never moved or
6344    /// merged, and nothing below here can work that out again: a `volatile` load and an ordinary
6345    /// one are the same instruction over the same address, so a pass that puts two accesses
6346    /// together would put these together too. Carried rather than checked here, because the pass
6347    /// that has to refuse is a long way down and this is the last place the answer is known.
6348    ///
6349    /// The instructions this compiler writes for itself get nothing, which is the right answer
6350    /// for all of them: a prologue, a spill and the moves around a call were asked for by the
6351    /// machine rather than by the program.
6352    ///
6353    /// Every access the flag is legal on carries it: the loads and the stores a rule matched,
6354    /// the two ends of a `long double` copy that are the program's own memory, and the compare
6355    /// and exchange and the read modify write. An `asm` statement does not, and it is the one
6356    /// exception on purpose. What the flag says there is that the statement stays even when
6357    /// nothing reads what it wrote, which is a different sentence about a different thing, and
6358    /// every `asm` is already fixed where it stands whether the word was written or not.
6359    fn carried(&self, inst: Inst) -> mir::Flags {
6360        if self.source[inst].flags.contains(Flags::VOLATILE) {
6361            mir::Flags::VOLATILE
6362        } else {
6363            mir::Flags::NONE
6364        }
6365    }
6366
6367    /// Build the machine instructions a match calls for.
6368    fn emit(&mut self, inst: Inst, matched: &Match<Term>) -> Result<(), Unsupported> {
6369        let rule: &Rule = self.selector.table.rule(matched);
6370        self.build(inst, rule.replacement, 0, &matched.bindings, true).map(|_| ())
6371    }
6372
6373    /// Build the machine term that starts at `at`, and give back the position after it and the
6374    /// register it wrote, if it wrote one.
6375    ///
6376    /// The outermost term computes what the IR instruction does, so what it writes is the
6377    /// register of the instruction's result. A term inside another is a step on the way and
6378    /// writes a register of its own, which the term around it then reads. Its operands are read
6379    /// before it is built and it is built before the term around it, so the instructions come
6380    /// out in the order the values are needed.
6381    fn build(
6382        &mut self,
6383        inst: Inst,
6384        pieces: &'static [Piece],
6385        at: usize,
6386        bindings: &[Term],
6387        outermost: bool,
6388    ) -> Result<(usize, Option<mir::Reg>), Unsupported> {
6389        let Some(Piece::App { head, arity }) = pieces.get(at) else {
6390            return Err(self.unsupported(inst));
6391        };
6392        let opcode =
6393            head.strip_prefix(self.selector.prefix()).ok_or_else(|| self.unsupported(inst))?;
6394        let descs = self.selector.operands(opcode).ok_or_else(|| self.unsupported(inst))?;
6395
6396        let mut read = Read::default();
6397        let mut at = at + 1;
6398        for _ in 0..*arity {
6399            at = self.read(inst, pieces, at, bindings, &mut read)?;
6400        }
6401
6402        let writes = descs.iter().take_while(|desc| desc.role.is_def()).count();
6403        if descs.len() - writes != read.regs.len() {
6404            return Err(self.unsupported(inst));
6405        }
6406
6407        // The first thing the instruction writes is what it computes, and any others are
6408        // registers the machine destroys on the way, which are fresh because nothing else is in
6409        // them and nothing reads them. An instruction that writes nothing at all is one whose
6410        // whole purpose is its effect, which is what a store is, and there is no result to put
6411        // anywhere.
6412        let mut regs = Vec::new();
6413        if writes > 0 {
6414            // A term inside another computes a step rather than the result, into a register only
6415            // the term around it reads.
6416            let first = match outermost {
6417                true => {
6418                    let result =
6419                        self.source[inst].first_result.ok_or_else(|| self.unsupported(inst))?;
6420                    self.new_reg(result)
6421                }
6422                false => self.out.new_vreg(descs[0].class),
6423            };
6424            regs.push(first);
6425            // The rest are the registers the machine destroys on the way, and the class each is in
6426            // is the one the instruction's description gives it rather than a guess, so that an
6427            // instruction that wrecks a register in the other file says so.
6428            regs.extend(descs[1..writes].iter().map(|desc| self.out.new_vreg(desc.class)));
6429        } else if !outermost || self.source[inst].first_result.is_some() {
6430            // A rule that throws away a value the IR gave a name to would leave every reader of
6431            // that name with nothing to read, so it is a rule this and the target disagree about.
6432            // So is a term inside another that writes nothing for the one around it to read.
6433            return Err(self.unsupported(inst));
6434        }
6435        let written = regs.first().copied();
6436        regs.extend(read.regs.iter().copied());
6437
6438        let block = self.at.expect("a block is being filled");
6439        let opcode = mir::Opcode::new(self.names.intern(head));
6440        let (span, flags) = (self.source.span(inst), self.carried(inst));
6441        let mut build = self.out.build(block, opcode).at(span).flags(flags);
6442        for (desc, reg) in descs.iter().zip(regs) {
6443            let operand = mir::Operand {
6444                reg,
6445                class: desc.class,
6446                role: desc.role,
6447                constraint: desc.constraint,
6448            };
6449            build = build.operand(operand);
6450        }
6451        if let Some(mem) = read.mem {
6452            build = build.mem(mem);
6453        }
6454        if let Some(imm) = read.imm {
6455            build = build.imm(imm);
6456        }
6457        build.finish();
6458        Ok((at, written))
6459    }
6460
6461    /// Read one argument of a replacement, which is a register, a number, an address or another
6462    /// machine term.
6463    ///
6464    /// Gives back the position after it, because a replacement is flat and an address or a term
6465    /// takes arguments of its own. A machine term is built on the spot, and what is read is the
6466    /// register it wrote.
6467    fn read(
6468        &mut self,
6469        inst: Inst,
6470        pieces: &'static [Piece],
6471        at: usize,
6472        bindings: &[Term],
6473        out: &mut Read,
6474    ) -> Result<usize, Unsupported> {
6475        match pieces.get(at) {
6476            Some(Piece::Int(value)) => {
6477                out.imm = i64::try_from(*value).ok();
6478                Ok(at + 1)
6479            }
6480            // A number the rule worked out of the ones it matched rather than one it wrote down,
6481            // which is an immediate once it has been worked out and is read here as one. It gives
6482            // nothing back when a binding it reads is a register, and a replacement that cannot be
6483            // built is a rule this file and the matcher disagree about, which is what `unsupported`
6484            // is for.
6485            Some(Piece::Computed { work, .. }) => {
6486                let matched: Vec<Option<i128>> = bindings
6487                    .iter()
6488                    .map(|term| match *term {
6489                        Term::Num(value) => Some(value),
6490                        _ => None,
6491                    })
6492                    .collect();
6493                let number = work(&matched).ok_or_else(|| self.unsupported(inst))?;
6494                out.imm = i64::try_from(number).ok();
6495                Ok(at + 1)
6496            }
6497            Some(Piece::Var { index, .. }) => {
6498                match bindings.get(*index) {
6499                    Some(&Term::Reg(value)) => {
6500                        let reg = self.reg_of(value)?;
6501                        out.regs.push(reg);
6502                    }
6503                    Some(&Term::Num(value)) => out.imm = i64::try_from(value).ok(),
6504                    // A pattern binds a register or a number and nothing else, so this is a
6505                    // rule the matcher and this file disagree about.
6506                    _ => return Err(self.unsupported(inst)),
6507                }
6508                Ok(at + 1)
6509            }
6510            Some(Piece::App { head, .. }) if (self.selector.address)(head).is_none() => {
6511                let (next, reg) = self.build(inst, pieces, at, bindings, false)?;
6512                out.regs.push(reg.ok_or_else(|| self.unsupported(inst))?);
6513                Ok(next)
6514            }
6515            Some(Piece::App { head, arity }) => {
6516                let kind = (self.selector.address)(head).ok_or_else(|| self.unsupported(inst))?;
6517                let mut inner = Read::default();
6518                let mut next = at + 1;
6519                for _ in 0..*arity {
6520                    next = self.read(inst, pieces, next, bindings, &mut inner)?;
6521                }
6522                let mem = address(kind, &inner, self.gpr).ok_or_else(|| self.unsupported(inst))?;
6523                out.mem = Some(mem);
6524                Ok(next)
6525            }
6526            None => Err(self.unsupported(inst)),
6527        }
6528    }
6529
6530    /// The register a value is in, materializing it if it is a constant that has not been put in
6531    /// one yet.
6532    ///
6533    /// A constant is written where it is wanted rather than where the IR defined it, and where it
6534    /// is wanted is a block that need not be the one the IR defined it in. So the register holding
6535    /// one is only good inside the block it was written into, and a second block that wants the
6536    /// same constant gets its own. Anything else is a register read where nothing wrote it: the
6537    /// IR guarantees a definition dominates its uses, and this moved the definition.
6538    ///
6539    /// Writing the number again is also the right answer and not merely the safe one. It is one
6540    /// instruction that reads nothing, which is cheaper than holding a register live across a
6541    /// branch for it, and it is what a rematerializing allocator would do with the value anyway.
6542    fn reg_of(&mut self, value: Value) -> Result<mir::Reg, Unsupported> {
6543        let constant = match self.source[value].def {
6544            Def::Result { inst, .. } => {
6545                (self.source[inst].opcode == Opcode::IConst).then_some(inst)
6546            }
6547            Def::Param { .. } => None,
6548        };
6549        let here = self.at.expect("a block is being filled");
6550        if let Some(reg) = self.regs[value.index()] {
6551            if constant.is_none() || self.written[value.index()] == Some(here) {
6552                return Ok(reg);
6553            }
6554        }
6555        if let Some(inst) = constant {
6556            // Cleared so that the register the constant is written into is a new one rather than
6557            // the one the block above wrote, which is still being read up there.
6558            self.regs[value.index()] = None;
6559            // Nothing is refused here. A constant is written on its own, out of the loop over the
6560            // block, and the operands of the rule that writes one are the number and nothing else.
6561            let matched = self
6562                .select(inst, &HashSet::new())
6563                .map(|(_, matched)| matched)
6564                .ok_or_else(|| self.unsupported(inst))?;
6565            self.emit(inst, &matched)?;
6566            // The same mark the loop over the instructions makes, and it has to be made here as
6567            // well because this is the only place a constant is ever selected: the loop skips one
6568            // where the IR wrote it, so a rule that lowers a constant fires from nowhere else and
6569            // would be reported as a rule nothing reaches.
6570            self.fired.mark(matched.rule);
6571            self.written[value.index()] = Some(here);
6572            return Ok(self.regs[value.index()].expect("a constant is written into a register"));
6573        }
6574        Ok(self.new_reg(value))
6575    }
6576
6577    /// Which register file a value of that type lives in.
6578    ///
6579    /// The vector one for the two float widths the machine has scalar instructions for and for the
6580    /// one it only moves, and the general purpose one for everything else. An eighty bit `long
6581    /// double` is in neither, and it is here rather than in the vector class on purpose: it would
6582    /// be put in a register that cannot hold it, and there is no rule that names one, so the
6583    /// instruction computing it is reported. The wrong class would make that a wrong program
6584    /// instead of a refused one.
6585    ///
6586    /// A hundred and twenty eight bit float is in the vector class and fits it exactly, which is
6587    /// the difference. Nothing computes in it, so every arithmetic on one is still reported, and
6588    /// what the class buys is the moves: a register that holds the whole value is a register a
6589    /// spill, a reload and a copy are each one instruction for.
6590    fn class_of(&self, ty: Type) -> RegClass {
6591        if crate::term::in_vector_file(ty) { self.conv.sse_class } else { self.gpr }
6592    }
6593
6594    /// A fresh register for a value, which is what the instruction computing it writes.
6595    ///
6596    /// Any declaration the value is a value of comes with it. Here rather than once at the end over
6597    /// the whole map, because a constant is written again in every block that wants one and the map
6598    /// only remembers the last of those registers, and a local held in a constant is a local that
6599    /// would otherwise be findable in one block of the function and nowhere else.
6600    fn new_reg(&mut self, value: Value) -> mir::Reg {
6601        if let Some(reg) = self.regs[value.index()] {
6602            return reg;
6603        }
6604        let reg = self.out.new_vreg(self.class_of(self.source[value].ty));
6605        self.regs[value.index()] = Some(reg);
6606        let source = self.source;
6607        for decl in source.value_decls(value) {
6608            self.out.named.push((decl, reg));
6609        }
6610        reg
6611    }
6612
6613    fn unsupported(&self, inst: Inst) -> Unsupported {
6614        let data = &self.source[inst];
6615        Unsupported::Inst {
6616            inst,
6617            term: Terms::new(self.source, inst, PLAIN).name(inst),
6618            opcode: data.opcode,
6619            ty: data.first_result.map(|result| self.source[result].ty),
6620        }
6621    }
6622}
6623
6624/// What the arguments of one replacement came to.
6625#[derive(Debug, Default)]
6626struct Read {
6627    regs: Vec<mir::Reg>,
6628    imm: Option<i64>,
6629    mem: Option<mir::Mem>,
6630}
6631
6632/// The addressing mode an address constructor's arguments make.
6633///
6634/// One arm per constructor rather than a question asked of the kind, because what the arguments
6635/// mean is the whole of what tells the four apart: the same register is a base in one and an
6636/// index in another, and the same constant is a scale in one and a displacement in another.
6637fn address(kind: Address, read: &Read, gpr: RegClass) -> Option<mir::Mem> {
6638    let mut regs = read.regs.iter().copied().map(|reg| mir::Operand::read(reg, gpr));
6639    match kind {
6640        Address::BaseIndexScale => {
6641            let base = regs.next()?;
6642            let index = regs.next()?;
6643            Some(mir::Mem::at(base).indexed(index, u8::try_from(read.imm?).ok()?))
6644        }
6645        Address::IndexScale => Some(mir::Mem {
6646            base: None,
6647            index: Some(regs.next()?),
6648            scale: u8::try_from(read.imm?).ok()?,
6649            disp: 0,
6650            symbol: None,
6651            block: None,
6652            table: None,
6653            reach: mir::Reach::Itself,
6654            segment: None,
6655        }),
6656        Address::Base => Some(mir::Mem::at(regs.next()?)),
6657        // The rule that writes this has a guard saying the constant fits, so a displacement that
6658        // does not is a rule and a target that disagree rather than a program this cannot compile.
6659        Address::BaseOffset => {
6660            Some(mir::Mem { disp: i32::try_from(read.imm?).ok()?, ..mir::Mem::at(regs.next()?) })
6661        }
6662    }
6663}
6664
6665#[cfg(test)]
6666mod tests {
6667    use rucc_ir::{
6668        AsmInfo, Builder, CallInfo, Flags, InstData, MemInfo, MemOrder, Restrict, Signature, Type,
6669    };
6670    use rucc_regalloc::assign::Env;
6671    use rucc_target::x86_64::{FRAME, REGS, SYSV};
6672
6673    use super::*;
6674    use crate::finish::{Convention, finish};
6675    use crate::frame::{Frame, Incoming, Layout};
6676    use crate::select::x86_64::SELECTOR;
6677
6678    /// A function of as many 64 bit parameters as the test wants, and the block they are in.
6679    fn blank(params: &[Type]) -> (Interner, Func, Block, Vec<Value>) {
6680        let mut names = Interner::new();
6681        let mut func = Func::new(names.intern("f"), Signature::new());
6682        let block = func.create_block();
6683        let values = params.iter().map(|&ty| func.append_param(block, ty)).collect();
6684        (names, func, block, values)
6685    }
6686
6687    /// An ordinary access: not atomic, and aligned enough that nothing here has an opinion.
6688    /// Neither field reaches selection, which is the point of saying it once here.
6689    fn plain() -> MemInfo {
6690        MemInfo {
6691            size: 0,
6692            align: 1,
6693            order: MemOrder::NotAtomic,
6694            tbaa: None,
6695            owns: 0,
6696            restrict: Restrict::NONE,
6697        }
6698    }
6699
6700    /// What the allocator is given: every integer register the convention offers except two, held
6701    /// back so that a move on an edge has somewhere to break a cycle and a spilled value has
6702    /// somewhere to be read into. Which two does not matter, and holding back the last two the
6703    /// convention would reach for leaves every expectation below unchanged.
6704    fn env() -> Env {
6705        const SCRATCH: [PhysReg; 2] = [x86_64::R10, x86_64::R11];
6706        let order: Vec<PhysReg> =
6707            SYSV.int_order.iter().copied().filter(|reg| !SCRATCH.contains(reg)).collect();
6708        Env::new().with(x86_64::GPR, &order, &SCRATCH)
6709    }
6710
6711    /// The machine IR text a function lowers to.
6712    fn lower(names: &mut Interner, source: &Func) -> String {
6713        let out = func(source, names, &SELECTOR, &SYSV, &Elsewhere::default())
6714            .expect("every instruction has a rule");
6715        mir::print_func(&out.func, names, &REGS)
6716    }
6717
6718    /// The same function lowered for AArch64, which is the first thing this file writes for a
6719    /// machine other than x86-64. Nothing past selection runs here, so what is checked is that the
6720    /// arguments, the rule and the return all come out named for the machine that was asked for.
6721    #[test]
6722    fn an_addition_lowers_for_aarch64_with_its_own_names() {
6723        let i32 = Type::int(32);
6724        let (mut names, mut func, block, args) = blank(&[i32, i32]);
6725        let mut build = Builder::new(&mut func, block);
6726        let sum = build.binary(Opcode::Add, args[0], args[1], Flags::default());
6727        build.ret(&[sum]);
6728
6729        let conv = &aarch64::AAPCS64;
6730        let selector = &crate::select::aarch64::SELECTOR;
6731        let out = super::func(&func, &mut names, selector, conv, &Elsewhere::default())
6732            .expect("an addition and a return have AArch64 rules");
6733        let text = mir::print_func(&out.func, &names, &aarch64::REGS);
6734        assert!(!text.contains("x64."), "{text}");
6735        assert!(text.contains("= a64.arg_val_32"), "{text}");
6736        assert!(text.contains("= a64.add_rr_32 %0, %1"), "{text}");
6737        assert!(text.contains("a64.ret_val_32 %2"), "{text}");
6738    }
6739
6740    /// Lowers one function for AArch64 and prints it, or says why it could not.
6741    fn lower_a64(names: &mut Interner, func: &Func) -> Result<String, String> {
6742        let conv = &aarch64::AAPCS64;
6743        let selector = &crate::select::aarch64::SELECTOR;
6744        let out = super::func(func, names, selector, conv, &Elsewhere::default())
6745            .map_err(|why| why.to_string())?;
6746        Ok(mir::print_func(&out.func, names, &aarch64::REGS))
6747    }
6748
6749    /// Nothing reads AArch64 assembly back into instructions, so every template there is kept as
6750    /// its text. The operands are the instruction's own, with the output first and the inputs
6751    /// last, a hole in the text asks for the `w` or the `x` name of one, and a vector register the
6752    /// clobber list names is written by it as well as every register a call may leave anything in.
6753    #[test]
6754    fn a_template_on_aarch64_is_kept_as_text_with_its_operands_in_registers() {
6755        let (i32, i64) = (Type::int(32), Type::int(64));
6756        let (mut names, mut source, block, args) = blank(&[i32, i64]);
6757        let out = clobbering(
6758            &mut source,
6759            block,
6760            &mut names,
6761            "add %w0, %w1, #1\n\tstr %2, [sp]",
6762            "=r,r,r",
6763            "d8",
6764            &[args[0], args[1]],
6765            &[i32],
6766        );
6767        let produced = source[out].results().next().expect("one result");
6768        Builder::new(&mut source, block).ret(&[produced]);
6769
6770        // Forty one registers between the output and the inputs: `x0` to `x15`, the sixteen vector
6771        // registers a call does not keep, and `v8`, which is the one the program named.
6772        let text = lower_a64(&mut names, &source).expect("kept as text");
6773        assert!(text.contains("%2:gpr, early $x0, early $x1,"), "{text}");
6774        assert!(text.contains(
6775            "early $v31, early $v8 = a64.template %0, %1, \
6776             @add \u{1}r0w\u{2}, \u{1}r42w\u{2}, #1\n\tstr \u{1}r43x\u{2}, [sp]\n"
6777        ));
6778    }
6779
6780    /// A letter that means one thing on x86 and another on AArch64 is refused there rather than
6781    /// read as x86. `a` to `d` and `S` name one register each on x86 and nothing on AArch64.
6782    #[test]
6783    fn a_constraint_letter_the_two_machines_disagree_about_is_refused_on_aarch64() {
6784        let i64 = Type::int(64);
6785        for constraints in ["=a,r", "=r,S", "=r,c"] {
6786            let (mut names, mut source, block, args) = blank(&[i64]);
6787            let out = clobbering(
6788                &mut source,
6789                block,
6790                &mut names,
6791                "mov %0, %1",
6792                constraints,
6793                "",
6794                &[args[0]],
6795                &[i64],
6796            );
6797            let produced = source[out].results().next().expect("one result");
6798            Builder::new(&mut source, block).ret(&[produced]);
6799            let refused = lower_a64(&mut names, &source).expect_err(constraints);
6800            assert!(refused.contains("has an operand this cannot place"), "{refused}");
6801        }
6802    }
6803
6804    /// `Q` on AArch64 is memory addressed by one register, which is `[x3]` and is how an operand in
6805    /// memory is spelled there already.
6806    #[test]
6807    fn a_q_operand_on_aarch64_is_its_address_in_brackets() {
6808        let (i64, ptr) = (Type::int(64), Type::PTR);
6809        let (mut names, mut source, block, args) = blank(&[ptr]);
6810        let out =
6811            clobbering(&mut source, block, &mut names, "ldr %x0, %1", "=r,Q", "", &args, &[i64]);
6812        let produced = source[out].results().next().expect("one result");
6813        Builder::new(&mut source, block).ret(&[produced]);
6814        let text = lower_a64(&mut names, &source).expect("kept as text");
6815        assert!(text.contains("@ldr \u{1}r0x\u{2}, [\u{1}r"), "{text}");
6816    }
6817
6818    /// `w` on AArch64 is a vector register, named `v` with no modifier the way gcc names it and by
6819    /// its scalar view with one. An integer asked for in one is refused, since it would need a move
6820    /// into that file first.
6821    #[test]
6822    fn a_vector_operand_on_aarch64_is_in_the_vector_file() {
6823        let f64 = Type::float(rucc_ir::Float::F64);
6824        let (mut names, mut source, block, args) = blank(&[f64, f64]);
6825        let out = clobbering(
6826            &mut source,
6827            block,
6828            &mut names,
6829            "fadd %d0, %d1, %d2\n\tmov %0.16b, %0.16b",
6830            "=w,w,w",
6831            "",
6832            &[args[0], args[1]],
6833            &[f64],
6834        );
6835        let produced = source[out].results().next().expect("one result");
6836        Builder::new(&mut source, block).ret(&[produced]);
6837        let text = lower_a64(&mut names, &source).expect("kept as text");
6838        assert!(text.contains("%2:fpr, early $x0,"), "{text}");
6839        assert!(text.contains("@fadd \u{1}r0d\u{2}, \u{1}r"), "{text}");
6840        assert!(text.contains("\n\tmov \u{1}r0v\u{2}.16b, \u{1}r0v\u{2}.16b\n"), "{text}");
6841
6842        let i64 = Type::int(64);
6843        let (mut names, mut source, block, args) = blank(&[i64]);
6844        let out =
6845            clobbering(&mut source, block, &mut names, "fmov %d0, %d1", "=w,w", "", &args, &[i64]);
6846        let produced = source[out].results().next().expect("one result");
6847        Builder::new(&mut source, block).ret(&[produced]);
6848        assert!(lower_a64(&mut names, &source).is_err());
6849    }
6850
6851    #[test]
6852    fn an_addition_of_two_registers_is_one_instruction() {
6853        let i32 = Type::int(32);
6854        let (mut names, mut func, block, args) = blank(&[i32, i32]);
6855        let mut build = Builder::new(&mut func, block);
6856        build.binary(Opcode::Add, args[0], args[1], Flags::default());
6857
6858        assert_eq!(
6859            lower(&mut names, &func),
6860            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_32\n    \
6861             %1:gpr($rsi) = x64.arg_val_32\n    %2:gpr(reuse 1) = x64.add_rr_32 %0, %1\n}\n"
6862        );
6863    }
6864
6865    #[test]
6866    fn a_constant_operand_becomes_an_immediate() {
6867        let i32 = Type::int(32);
6868        let (mut names, mut func, block, args) = blank(&[i32]);
6869        let mut build = Builder::new(&mut func, block);
6870        let seven = build.iconst(i32, 7);
6871        build.binary(Opcode::Add, args[0], seven, Flags::default());
6872
6873        // The constant is in the instruction and nothing was written to hold it, which is what
6874        // materializing one where a register for it is wanted buys.
6875        assert_eq!(
6876            lower(&mut names, &func),
6877            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_32\n    \
6878             %1:gpr(reuse 1) = x64.add_ri_32 %0, 7\n}\n"
6879        );
6880    }
6881
6882    #[test]
6883    fn a_constant_too_wide_for_an_immediate_goes_into_a_register() {
6884        let i64 = Type::int(64);
6885        let (mut names, mut func, block, args) = blank(&[i64]);
6886        let mut build = Builder::new(&mut func, block);
6887        let big = build.iconst(i64, i128::from(i32::MAX) + 1);
6888        build.binary(Opcode::Add, args[0], big, Flags::default());
6889
6890        // Nobody wrote this fallback down. The rule that takes an immediate has a guard that
6891        // turns a number this wide down, so it does not fire, and the next way of showing the
6892        // operand puts it in a register.
6893        assert_eq!(
6894            lower(&mut names, &func),
6895            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_64\n    \
6896             %1:gpr = x64.mov_ri_64 2147483648\n    %2:gpr(reuse 1) = x64.add_rr_64 %0, %1\n}\n"
6897        );
6898    }
6899
6900    #[test]
6901    fn an_index_calculation_folds_into_an_address() {
6902        let i64 = Type::int(64);
6903        let (mut names, mut func, block, args) = blank(&[i64, i64]);
6904        let mut build = Builder::new(&mut func, block);
6905        let four = build.iconst(i64, 4);
6906        let scaled = build.binary(Opcode::Mul, args[1], four, Flags::default());
6907        build.binary(Opcode::Add, args[0], scaled, Flags::default());
6908
6909        // Three IR instructions and one machine instruction. The multiply is gone because the
6910        // rule that matched reached down and took it.
6911        assert_eq!(
6912            lower(&mut names, &func),
6913            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_64\n    \
6914             %1:gpr($rsi) = x64.arg_val_64\n    %2:gpr = x64.lea_64 [%0 + %1*4]\n}\n"
6915        );
6916    }
6917
6918    #[test]
6919    fn an_instruction_every_reader_can_take_is_folded_into_all_of_them() {
6920        let i64 = Type::int(64);
6921        let (mut names, mut func, block, args) = blank(&[i64, i64]);
6922        let mut build = Builder::new(&mut func, block);
6923        let four = build.iconst(i64, 4);
6924        let scaled = build.binary(Opcode::Mul, args[1], four, Flags::default());
6925        let first = build.binary(Opcode::Add, args[0], scaled, Flags::default());
6926        build.binary(Opcode::Add, first, scaled, Flags::default());
6927
6928        // Both readers have room for a scaled index, so both of them take it and nothing is left
6929        // to read the multiply. Three IR instructions become two machine ones, where refusing to
6930        // fold into either reader would have left three.
6931        assert_eq!(
6932            lower(&mut names, &func),
6933            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_64\n    \
6934             %1:gpr($rsi) = x64.arg_val_64\n    %2:gpr = x64.lea_64 [%0 + %1*4]\n    \
6935             %3:gpr = x64.lea_64 [%2 + %1*4]\n}\n"
6936        );
6937    }
6938
6939    #[test]
6940    fn an_instruction_one_of_its_readers_cannot_take_is_folded_into_none_of_them() {
6941        let i64 = Type::int(64);
6942        let (mut names, mut func, block, args) = blank(&[i64, i64]);
6943        let mut build = Builder::new(&mut func, block);
6944        let four = build.iconst(i64, 4);
6945        let scaled = build.binary(Opcode::Mul, args[1], four, Flags::default());
6946        build.binary(Opcode::Add, args[0], scaled, Flags::default());
6947        build.store(scaled, args[0], plain(), Flags::default());
6948
6949        // The addition has room for the multiply and the store does not: what a store writes is
6950        // a register, and no rule reaches through it. Folding into the addition alone would
6951        // leave the multiply where it is for the store to read and do the work twice, so the
6952        // multiply is put back and both readers read the register it wrote.
6953        let text = lower(&mut names, &func);
6954        assert!(text.contains("x64.lea_64 [%1*4]"), "{text}");
6955        assert!(text.contains("x64.add_rr_64"), "{text}");
6956    }
6957
6958    #[test]
6959    fn a_shift_by_a_register_asks_for_it_in_cl() {
6960        let i32 = Type::int(32);
6961        let (mut names, mut func, block, args) = blank(&[i32, i32]);
6962        let mut build = Builder::new(&mut func, block);
6963        build.binary(Opcode::Shl, args[0], args[1], Flags::default());
6964
6965        // The fixed register is not in the rule. It is what the target says the instruction does
6966        // with its operands, and the allocator is what will act on it.
6967        let text = lower(&mut names, &func);
6968        assert!(text.contains("x64.shl_rcl_32 %0, %1($rcx)"), "{text}");
6969    }
6970
6971    #[test]
6972    fn a_division_names_the_registers_and_the_register_it_destroys() {
6973        let i32 = Type::int(32);
6974        let (mut names, mut func, block, args) = blank(&[i32, i32]);
6975        let mut build = Builder::new(&mut func, block);
6976        build.binary(Opcode::SDiv, args[0], args[1], Flags::default());
6977
6978        // Two definitions, because a division writes the remainder whether anybody wanted it or
6979        // not, and the second one is early because it is destroyed before the operands are read.
6980        let text = lower(&mut names, &func);
6981        assert!(
6982            text.contains("%2:gpr($rax), early %3:gpr($rdx) = x64.idiv_quo_32 %0($rax), %1"),
6983            "{text}"
6984        );
6985    }
6986
6987    #[test]
6988    fn a_load_reads_through_the_register_the_address_is_in() {
6989        let i64 = Type::int(64);
6990        let (mut names, mut func, block, args) = blank(&[i64]);
6991        let mut build = Builder::new(&mut func, block);
6992        build.load(Type::int(32), args[0], plain(), Flags::default());
6993
6994        assert_eq!(
6995            lower(&mut names, &func),
6996            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_64\n    \
6997             %1:gpr = x64.mov_rm_32 [%0]\n}\n"
6998        );
6999    }
7000
7001    #[test]
7002    fn a_store_writes_no_register_and_the_value_it_writes_is_the_one_the_ir_gave_it() {
7003        let (mut names, mut func, block, args) = blank(&[Type::int(32), Type::int(64)]);
7004        let mut build = Builder::new(&mut func, block);
7005        build.store(args[0], args[1], plain(), Flags::default());
7006
7007        // The value is the first parameter and the address is the second, and the instruction
7008        // takes them the other way round. Getting that backwards would compile to a store of the
7009        // address into the value, which is a program that runs and does the wrong thing.
7010        assert_eq!(
7011            lower(&mut names, &func),
7012            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_32\n    \
7013             %1:gpr($rsi) = x64.arg_val_64\n    x64.mov_mr_32 %0, [%1]\n}\n"
7014        );
7015    }
7016
7017    #[test]
7018    fn an_address_with_a_constant_added_folds_into_the_access() {
7019        let i64 = Type::int(64);
7020        let (mut names, mut func, block, args) = blank(&[i64]);
7021        let mut build = Builder::new(&mut func, block);
7022        let twelve = build.iconst(i64, 12);
7023        let field = build.binary(Opcode::Add, args[0], twelve, Flags::default());
7024        build.load(Type::int(64), field, plain(), Flags::default());
7025
7026        // Two IR instructions and one machine instruction, which is what every read of a field
7027        // of a structure comes to.
7028        assert_eq!(
7029            lower(&mut names, &func),
7030            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_64\n    \
7031             %1:gpr = x64.mov_rm_64 [%0 + 12]\n}\n"
7032        );
7033    }
7034
7035    #[test]
7036    fn a_displacement_too_wide_to_encode_leaves_the_addition_where_it_is() {
7037        let i64 = Type::int(64);
7038        let (mut names, mut func, block, args) = blank(&[i64]);
7039        let mut build = Builder::new(&mut func, block);
7040        let big = build.iconst(i64, i128::from(i32::MAX) + 1);
7041        let far = build.binary(Opcode::Add, args[0], big, Flags::default());
7042        build.load(Type::int(32), far, plain(), Flags::default());
7043
7044        // A displacement is signed and 32 bits. The rule that folds one has a guard that turns
7045        // this down, so the addition stays and the load reads through what it produced. Nobody
7046        // wrote that fallback: it is the next way of showing the operand.
7047        let text = lower(&mut names, &func);
7048        assert!(text.contains("x64.mov_rm_32 [%2]"), "{text}");
7049        assert!(text.contains("x64.add_rr_64"), "{text}");
7050    }
7051
7052    #[test]
7053    fn a_store_of_a_value_that_was_loaded_is_two_instructions_and_no_arithmetic() {
7054        let i64 = Type::int(64);
7055        let (mut names, mut func, block, args) = blank(&[i64, i64]);
7056        let mut build = Builder::new(&mut func, block);
7057        let got = build.load(Type::int(8), args[0], plain(), Flags::default());
7058        build.store(got, args[1], plain(), Flags::default());
7059
7060        // A load feeding a store is the one place folding would be wrong: an x86-64 `mov` has at
7061        // most one memory operand, and there is no rule that takes two, so the load is left where
7062        // it is and the store reads the register it wrote.
7063        assert_eq!(
7064            lower(&mut names, &func),
7065            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_64\n    \
7066             %1:gpr($rsi) = x64.arg_val_64\n    %2:gpr = x64.mov_rm_8 [%0]\n    \
7067             x64.mov_mr_8 %2, [%1]\n}\n"
7068        );
7069    }
7070
7071    #[test]
7072    fn an_access_at_a_width_no_rule_is_written_at_is_reported() {
7073        let i64 = Type::int(64);
7074        let (mut names, mut source, block, args) = blank(&[i64]);
7075        let mut build = Builder::new(&mut source, block);
7076        build.load(Type::int(128), args[0], plain(), Flags::default());
7077
7078        // The width is the whole of what is wrong here, so the width is in the message: `load`
7079        // on its own is written about at every other width and would send a reader looking in
7080        // the wrong place.
7081        let failed = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
7082            .expect_err("nothing loads 128 bits");
7083        assert_eq!(failed.to_string(), "no rule lowers a `load` producing a `i128`");
7084    }
7085
7086    #[test]
7087    fn a_return_asks_for_the_value_in_the_register_the_caller_reads() {
7088        let (mut names, mut func, block, args) = blank(&[Type::int(32)]);
7089        let mut build = Builder::new(&mut func, block);
7090        build.ret(&[args[0]]);
7091
7092        // The register is not in the rule, the same way `cl` is not in the rule for a shift. It
7093        // is what the target says the instruction does with its operand, and the allocator is
7094        // what will act on it. There is no `ret` here, because giving the frame back has to
7095        // happen between this and leaving and the frame is not worked out yet.
7096        assert_eq!(
7097            lower(&mut names, &func),
7098            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_32\n    \
7099             x64.ret_val_32 %0($rax)\n}\n"
7100        );
7101    }
7102
7103    #[test]
7104    fn a_return_of_two_values_asks_for_the_second_register_as_well() {
7105        let i64 = Type::int(64);
7106        let (mut names, mut func, block, args) = blank(&[i64, i64]);
7107        let mut build = Builder::new(&mut func, block);
7108        build.ret(&[args[0], args[1]]);
7109
7110        // `struct { long a, b; } f(long a, long b)`, after the front end has classified it. Both
7111        // halves are integers, so the second is in the second integer return register, and both
7112        // pseudos say so the same way the one for a single value does.
7113        assert_eq!(
7114            lower(&mut names, &func),
7115            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_64\n    \
7116             %1:gpr($rsi) = x64.arg_val_64\n    x64.ret_val_64 %0($rax)\n    \
7117             x64.ret_val2_64 %1($rdx)\n}\n"
7118        );
7119    }
7120
7121    #[test]
7122    fn two_values_back_in_different_files_are_both_the_first_of_their_own() {
7123        let f64 = Type::float(rucc_ir::Float::F64);
7124        let (mut names, mut func, block, args) = blank(&[f64, Type::int(64)]);
7125        let mut build = Builder::new(&mut func, block);
7126        build.ret(&[args[0], args[1]]);
7127
7128        // `struct { double a; long b; } f(double a, long b)`. The two files are counted apart, so
7129        // neither half is the second of anything and the `double` is in `xmm0` rather than in the
7130        // register a second `double` would have been in. Getting this wrong is not a crash: the
7131        // caller reads a register nobody wrote, and this is where that is ruled out.
7132        assert_eq!(
7133            lower(&mut names, &func),
7134            "mfunc @f {\nblock0:\n    %0:xmm($xmm0) = x64.arg_val_f64\n    \
7135             %1:gpr($rdi) = x64.arg_val_64\n    x64.ret_val_f64 %0($xmm0)\n    \
7136             x64.ret_val_64 %1($rax)\n}\n"
7137        );
7138    }
7139
7140    #[test]
7141    fn two_of_the_same_file_back_take_the_first_two_of_it() {
7142        let f64 = Type::float(rucc_ir::Float::F64);
7143        let (mut names, mut func, block, args) = blank(&[f64, f64]);
7144        let mut build = Builder::new(&mut func, block);
7145        build.ret(&[args[0], args[1]]);
7146
7147        // `struct { double x, y; } f(double x, double y)`, which is the vector half of the pair
7148        // above and counts in its own file the same way.
7149        assert_eq!(
7150            lower(&mut names, &func),
7151            "mfunc @f {\nblock0:\n    %0:xmm($xmm0) = x64.arg_val_f64\n    \
7152             %1:xmm($xmm1) = x64.arg_val_f64\n    x64.ret_val_f64 %0($xmm0)\n    \
7153             x64.ret_val2_f64 %1($xmm1)\n}\n"
7154        );
7155    }
7156
7157    /// A function whose answer goes back through memory, with the pointer to the space for it in
7158    /// front of whatever else it takes. Only the signature says it is one.
7159    fn returning_through_memory(params: &[Type]) -> (Interner, Func, Block, Vec<Value>) {
7160        let mut names = Interner::new();
7161        let sret = Abi::Sret { size: 32, align: 8 };
7162        let mut signature = Signature::new().and_param(Param::with_abi(Type::PTR, sret));
7163        signature.params.extend(params.iter().copied().map(Param::new));
7164        let mut func = Func::new(names.intern("f"), signature);
7165        let block = func.create_block();
7166        let space = func.append_param(block, Type::PTR);
7167        let values = std::iter::once(space)
7168            .chain(params.iter().map(|&ty| func.append_param(block, ty)))
7169            .collect();
7170        (names, func, block, values)
7171    }
7172
7173    #[test]
7174    fn the_space_a_return_through_memory_was_given_goes_back_in_the_first_return_register() {
7175        let (mut names, mut func, block, _) = returning_through_memory(&[]);
7176        Builder::new(&mut func, block).ret(&[]);
7177
7178        // `struct big f(void)`, where `big` is too large to come back in registers. The `return`
7179        // carries nothing, because the value went into the space the caller handed over, and the
7180        // document still says that address comes back in `rax`. Nothing in the IR says it, so the
7181        // convention says it, and the pseudo is the one any other pointer return would use.
7182        assert_eq!(
7183            lower(&mut names, &func),
7184            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_64\n    \
7185             x64.ret_val_64 %0($rax)\n}\n"
7186        );
7187    }
7188
7189    #[test]
7190    fn what_the_function_did_in_between_does_not_take_the_register_off_it() {
7191        let (mut names, mut func, block, args) = returning_through_memory(&[Type::int(32)]);
7192        let mut build = Builder::new(&mut func, block);
7193        build.store(args[1], args[0], plain(), Flags::default());
7194        build.ret(&[]);
7195
7196        // The register is a read at the end and not a move at the start, so it is live across
7197        // everything between the two and the allocator has to keep it somewhere. In a function
7198        // with a call in it that somewhere is a callee saved register, and the address comes back
7199        // into `rax` here rather than whatever the last instruction happened to leave there. That
7200        // is issue #333, and a store is enough to show the value outlives the entry block.
7201        let text = lower(&mut names, &func);
7202        assert!(text.contains("x64.mov_mr_32 %1, [%0]"), "{text}");
7203        assert!(text.ends_with("    x64.ret_val_64 %0($rax)\n}\n"), "{text}");
7204    }
7205
7206    #[test]
7207    fn a_pointer_that_is_only_a_pointer_is_not_given_back() {
7208        let (mut names, mut func, block, args) = blank(&[Type::PTR]);
7209        let mut build = Builder::new(&mut func, block);
7210        build.store(args[0], args[0], plain(), Flags::default());
7211        build.ret(&[]);
7212
7213        // `void f(void **p)`. It takes a pointer first and returns nothing, which is the shape of
7214        // the one above and none of its meaning, and what tells them apart is the signature. A
7215        // `void` function leaves `rax` alone.
7216        assert!(!lower(&mut names, &func).contains("ret_val"));
7217    }
7218
7219    #[test]
7220    fn a_return_of_a_constant_puts_it_in_a_register_first() {
7221        let (mut names, mut func, block, _) = blank(&[]);
7222        let mut build = Builder::new(&mut func, block);
7223        let zero = build.iconst(Type::int(32), 0);
7224        build.ret(&[zero]);
7225
7226        // No rule returns an immediate, so the plan that offers one is turned down and the next
7227        // one materializes it. That is `int main(void) { return 0; }` in full, once the epilogue
7228        // is appended to it.
7229        assert_eq!(
7230            lower(&mut names, &func),
7231            "mfunc @f {\nblock0:\n    %0:gpr = x64.mov_ri_32 0\n    x64.ret_val_32 %0($rax)\n}\n"
7232        );
7233    }
7234
7235    #[test]
7236    fn the_rule_that_writes_a_constant_down_is_recorded_as_a_rule_that_fired() {
7237        let (mut names, mut func, block, _) = blank(&[]);
7238        let mut build = Builder::new(&mut func, block);
7239        let zero = build.iconst(Type::int(32), 0);
7240        build.ret(&[zero]);
7241
7242        // The loop over the instructions passes a constant by, because a constant is written where
7243        // a register for it is first wanted rather than where the IR put it. So the only place a
7244        // rule about one is ever selected is the materialization, and a mark made in the loop
7245        // alone would report every rule about a constant as a rule nothing reaches.
7246        let out = super::func(&func, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
7247            .expect("every instruction has a rule");
7248        let rules = &crate::select::x86_64::TABLE.rules;
7249        let fired: Vec<&str> = rules
7250            .iter()
7251            .enumerate()
7252            .filter(|(index, _)| out.fired.has(*index))
7253            .map(|(_, rule)| rule.pattern)
7254            .collect();
7255        assert!(fired.contains(&"(iconst.i32 k)"), "{fired:?}");
7256    }
7257
7258    #[test]
7259    fn a_return_of_nothing_is_no_instruction_at_all() {
7260        let (mut names, mut func, block, _) = blank(&[]);
7261        let mut build = Builder::new(&mut func, block);
7262        build.ret(&[]);
7263
7264        // Every part of leaving a function that returns nothing is the epilogue's, and the
7265        // epilogue goes in after allocation. A block with nothing in it is the right answer here
7266        // rather than a function that could not be lowered.
7267        assert_eq!(lower(&mut names, &func), "mfunc @f {\nblock0:\n}\n");
7268    }
7269
7270    #[test]
7271    fn the_allocator_is_what_moves_the_answer_into_the_return_register() {
7272        let (mut names, mut source, block, _) = blank(&[]);
7273        let mut build = Builder::new(&mut source, block);
7274        let zero = build.iconst(Type::int(32), 0);
7275        build.ret(&[zero]);
7276
7277        let mut out = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
7278            .expect("every instruction has a rule")
7279            .func;
7280        let env = env();
7281        let allocation = rucc_regalloc::run(&mut out, &env, "test", true);
7282        let frame = Frame::of(&out, &allocation, &Layout::new(&SYSV, REGS));
7283        finish(
7284            &mut out,
7285            &allocation,
7286            &frame,
7287            &Stack::default(),
7288            Convention::new(&SYSV, &FRAME),
7289            &mut names,
7290        );
7291
7292        // `int main(void) { return 0; }` end to end. Nothing here asked for `rax`: the rule said
7293        // the value goes back, the target said where, and the allocator is what made it true. The
7294        // epilogue is what leaves, and this function needs no frame, so it is the return alone.
7295        //
7296        // Two instructions and no copy, which is what a hint buys. The return insists on `rax`,
7297        // so `rax` is the register the allocator tries first for the value the return reads, and
7298        // the constant is written straight into it.
7299        assert_eq!(
7300            mir::print_func(&out, &names, &REGS),
7301            "mfunc @f {\nblock0:\n    $rax = x64.mov_ri_32 0\n    \
7302             x64.ret_val_32 $rax($rax)\n    x64.ret\n}\n"
7303        );
7304    }
7305
7306    #[test]
7307    fn a_function_of_two_arguments_is_a_whole_function_now() {
7308        let i32 = Type::int(32);
7309        let (mut names, mut source, block, args) = blank(&[i32, i32]);
7310        let mut build = Builder::new(&mut source, block);
7311        let sum = build.binary(Opcode::Add, args[0], args[1], Flags::default());
7312        build.ret(&[sum]);
7313
7314        let mut out = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
7315            .expect("every instruction has a rule")
7316            .func;
7317        let env = env();
7318        let allocation = rucc_regalloc::run(&mut out, &env, "test", true);
7319        let frame = Frame::of(&out, &allocation, &Layout::new(&SYSV, REGS));
7320        finish(
7321            &mut out,
7322            &allocation,
7323            &frame,
7324            &Stack::default(),
7325            Convention::new(&SYSV, &FRAME),
7326            &mut names,
7327        );
7328
7329        // `int f(int a, int b) { return a + b; }` end to end, and this is the test the argument
7330        // side exists for. Before it there was no way to write one: the allocator refuses a
7331        // function whose entry block takes parameters, because there is no edge into an entry
7332        // block for the moves that give a block parameter its value to go on.
7333        //
7334        // One move, and it is the one the machine's addition needs rather than one the allocator
7335        // owes anybody. Each argument stays in the register it arrived in, because the pseudo
7336        // that defines it insists on that register and the allocator now tries it first, and the
7337        // sum stays in the register the addition wrote it to until the return reads it out. The
7338        // copy in front of a two address instruction is what makes its destination one of the
7339        // registers it reads, and the source operand keeps its own name because the destination
7340        // is what the encoder writes.
7341        assert_eq!(
7342            mir::print_func(&out, &names, &REGS),
7343            "mfunc @f {\nblock0:\n    $rdi($rdi) = x64.arg_val_32\n    \
7344             $rsi($rsi) = x64.arg_val_32\n    \
7345             $rdi(reuse 1) = x64.add_rr_32 $rdi, $rsi\n    $rax = x64.mov_rr_64 $rdi\n    \
7346             x64.ret_val_32 $rax($rax)\n    x64.ret\n}\n"
7347        );
7348    }
7349
7350    #[test]
7351    fn an_argument_with_no_register_left_for_it_is_read_out_of_the_caller_s_stack() {
7352        let i64 = Type::int(64);
7353        let (mut names, mut source, block, args) = blank(&[i64; 7]);
7354        let mut build = Builder::new(&mut source, block);
7355        build.ret(&[args[6]]);
7356
7357        let lowered = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
7358            .expect("the seventh is read from memory");
7359
7360        // SysV passes six integers in registers and the seventh in the caller's memory, so six of
7361        // these are pseudos that encode to nothing and the seventh is a load that encodes to real
7362        // bytes. Its displacement is nothing here for the reason a local's is: there is no frame
7363        // yet. What the walk hands on is which instruction is waiting, and for how far up the
7364        // caller's argument area, which is the bottom of it because it is the first one there.
7365        assert_eq!(lowered.stack.arguments.len(), 1);
7366        assert_eq!(lowered.stack.arguments[0].1, 0);
7367        let text = mir::print_func(&lowered.func, &names, &REGS);
7368        assert!(text.contains("%6:gpr = x64.mov_rm_64 [$rsp]"), "{text}");
7369        assert_eq!(text.matches("x64.arg_val_64").count(), 6, "{text}");
7370    }
7371
7372    #[test]
7373    fn the_frame_is_what_says_how_far_up_the_caller_s_stack_an_argument_is() {
7374        let i64 = Type::int(64);
7375        let (mut names, mut source, block, args) = blank(&[i64; 8]);
7376        let mut build = Builder::new(&mut source, block);
7377        let sum = build.binary(Opcode::Add, args[6], args[7], Flags::default());
7378        build.ret(&[sum]);
7379
7380        let lowered = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
7381            .expect("both are read from memory");
7382        let stack = lowered.stack;
7383        let mut out = lowered.func;
7384        let env = env();
7385        let allocation = rucc_regalloc::run(&mut out, &env, "test", true);
7386        let layout = stack.layout(Layout::new(&SYSV, REGS));
7387        let frame = Frame::of(&out, &allocation, &layout);
7388        finish(&mut out, &allocation, &frame, &stack, Convention::new(&SYSV, &FRAME), &mut names);
7389
7390        // A leaf that takes no frame, so the stack pointer never moves and the only thing between
7391        // it and the caller's arguments is the return address the call pushed. The seventh
7392        // parameter is at the bottom of the caller's argument area and the eighth is one word
7393        // further up, which is the eight bytes between the two offsets.
7394        let text = mir::print_func(&out, &names, &REGS);
7395        assert_eq!(frame.size(), 0);
7396        assert_eq!(frame.incoming(), Incoming::from_stack(8));
7397        assert!(text.contains("x64.mov_rm_64 [$rsp + 8]"), "{text}");
7398        assert!(text.contains("x64.mov_rm_64 [$rsp + 16]"), "{text}");
7399    }
7400
7401    #[test]
7402    fn a_realigned_frame_reaches_the_caller_s_arguments_through_the_frame_pointer() {
7403        let i64 = Type::int(64);
7404        let (mut names, mut source, block, args) = blank(&[i64; 7]);
7405        let wide = slot(&mut source, block, 64, 32);
7406        let mut build = Builder::new(&mut source, block);
7407        build.store(args[6], wide, plain(), Flags::default());
7408        build.ret(&[args[6]]);
7409
7410        let lowered = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
7411            .expect("every instruction has a rule");
7412        let stack = lowered.stack;
7413        let mut out = lowered.func;
7414        let env = env();
7415        let allocation = rucc_regalloc::run(&mut out, &env, "test", true);
7416        let layout = stack.layout(Layout::new(&SYSV, REGS));
7417        let frame = Frame::of(&out, &allocation, &layout);
7418        finish(&mut out, &allocation, &frame, &stack, Convention::new(&SYSV, &FRAME), &mut names);
7419
7420        // A local wanting thirty two byte alignment makes the prologue force the stack pointer,
7421        // which throws away how far the caller's stack was. So the load the lowering wrote off the
7422        // stack pointer is rewritten to read through the frame pointer, at the one distance that
7423        // survives: the word the prologue pushed the frame pointer into, and the return address
7424        // above it.
7425        let text = mir::print_func(&out, &names, &REGS);
7426        assert_eq!(frame.realign(), Some(32));
7427        assert_eq!(frame.incoming(), Incoming::from_frame(16));
7428        assert!(text.contains("x64.mov_rm_64 [$rbp + 16]"), "{text}");
7429        assert!(!text.contains("x64.mov_rm_64 [$rsp"), "{text}");
7430    }
7431
7432    #[test]
7433    fn a_jump_is_the_edge_and_nothing_else() {
7434        let i32 = Type::int(32);
7435        let (mut names, mut source, entry, args) = blank(&[i32]);
7436        let next = source.create_block();
7437        let got = source.append_param(next, i32);
7438        Builder::new(&mut source, entry).jump(next, &[args[0]]);
7439        Builder::new(&mut source, next).ret(&[got]);
7440
7441        // Two blocks and two instructions, and the jump is neither of them. What it was is the
7442        // arm on the first block, and what the arm carries is the argument it was called with.
7443        assert_eq!(
7444            lower(&mut names, &source),
7445            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_32 block1(%0)\n\n\
7446             block1(%1:gpr):\n    x64.ret_val_32 %1($rax)\n}\n"
7447        );
7448    }
7449
7450    /// A block that reads what a block below it writes is filled after it, not before it.
7451    ///
7452    /// The blocks are written entry, `early`, `late`, `exit`, and the entry jumps straight past
7453    /// `early` to `late`, so `late` dominates `early` while sitting below it in the function.
7454    /// Filling them in the order they are written reaches the read in `early` first, and reading
7455    /// a value with no register yet mints one. The cast in `late` is no instruction at all, so
7456    /// what it does is give its answer the register its operand is already in, and that is not
7457    /// the register the read minted. Nothing writes the register the read minted. The printer
7458    /// says `%?` for a register nothing defines, which is what this looks for, and what came out
7459    /// of the real bug was SQLite loading a stack slot no store ever reached.
7460    #[test]
7461    fn a_block_that_reads_what_a_block_below_it_writes_is_filled_after_it() {
7462        let i64 = Type::int(64);
7463        let (mut names, mut source, entry, args) = blank(&[i64, i64]);
7464        let early = source.create_block();
7465        let late = source.create_block();
7466        let exit = source.create_block();
7467
7468        Builder::new(&mut source, entry).jump(late, &[]);
7469        let ptr = cast(&mut source, late, Opcode::IntToPtr, args[0], Type::PTR);
7470        Builder::new(&mut source, early).ret(&[ptr]);
7471        let mut build = Builder::new(&mut source, late);
7472        let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
7473        build.br_if(cond, early, &[], exit, &[]);
7474        Builder::new(&mut source, exit).ret(&[args[1]]);
7475
7476        let text = lower(&mut names, &source);
7477        assert!(!text.contains("%?"), "every register has something that writes it: {text}");
7478    }
7479
7480    /// A constant is written where it is wanted rather than where the IR defined it, and two
7481    /// blocks wanting the same one is two places. Writing it once and reading it in both is a
7482    /// register read where nothing wrote it, unless the block it was written in happens to
7483    /// dominate the other, which nothing here checks and which the second arm of a branch never
7484    /// does. Each block gets its own copy of the number instead.
7485    #[test]
7486    fn a_constant_two_blocks_want_is_written_in_both_of_them() {
7487        let i32 = Type::int(32);
7488        let (mut names, mut source, entry, args) = blank(&[i32, i32]);
7489        let then = source.create_block();
7490        let other = source.create_block();
7491        let join = source.create_block();
7492        let got = source.append_param(join, i32);
7493
7494        let mut build = Builder::new(&mut source, entry);
7495        let seven = build.iconst(i32, 7);
7496        let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
7497        build.br_if(cond, then, &[], other, &[]);
7498        // Both arms want the seven in a register, because a block argument is never an immediate,
7499        // and neither arm dominates the other.
7500        Builder::new(&mut source, then).jump(join, &[seven]);
7501        Builder::new(&mut source, other).jump(join, &[seven]);
7502        Builder::new(&mut source, join).ret(&[got]);
7503
7504        let text = lower(&mut names, &source);
7505        assert_eq!(text.matches("x64.mov_ri_32 7").count(), 2, "one seven per block: {text}");
7506    }
7507
7508    /// An argument on an edge out of a block that leaves two ways is read after every instruction
7509    /// of the block is written, and reading one can write an instruction, which would land after
7510    /// the branch that has already jumped past it. The branch goes back on the end.
7511    #[test]
7512    fn a_constant_an_edge_wants_is_written_before_the_branch_and_not_after_it() {
7513        let i32 = Type::int(32);
7514        let (mut names, mut source, entry, args) = blank(&[i32, i32]);
7515        let then = source.create_block();
7516        let join = source.create_block();
7517        let got = source.append_param(join, i32);
7518
7519        let mut build = Builder::new(&mut source, entry);
7520        let nine = build.iconst(i32, 9);
7521        let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
7522        build.br_if(cond, then, &[], join, &[nine]);
7523        Builder::new(&mut source, then).jump(join, &[args[0]]);
7524        Builder::new(&mut source, join).ret(&[got]);
7525
7526        let out = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
7527            .expect("every instruction has a rule")
7528            .func;
7529        let entry = out.entry().expect("an entry block");
7530        let last = out.terminator(entry).expect("a block that leaves two ways has a branch");
7531        let branch = names.intern("x64.br_cond_8");
7532        assert_eq!(
7533            out[last].opcode,
7534            mir::Opcode::new(branch),
7535            "the branch is last: {}",
7536            mir::print_func(&out, &names, &REGS)
7537        );
7538    }
7539
7540    #[test]
7541    fn a_conditional_branch_is_lowered_to_the_condition_and_nothing_about_where_it_goes() {
7542        let i32 = Type::int(32);
7543        let (mut names, mut source, entry, args) = blank(&[i32, i32]);
7544        let then = source.create_block();
7545        let other = source.create_block();
7546        let mut build = Builder::new(&mut source, entry);
7547        let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
7548        build.br_if(cond, then, &[], other, &[]);
7549        Builder::new(&mut source, then).ret(&[args[0]]);
7550        Builder::new(&mut source, other).ret(&[args[1]]);
7551
7552        // The comparison writes a byte and the branch reads it, and neither says a block. Both
7553        // arms are on the entry block, in the order the branch took them, so the arm that runs
7554        // when the condition holds is the first.
7555        assert_eq!(
7556            lower(&mut names, &source),
7557            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_32\n    \
7558             %1:gpr($rsi) = x64.arg_val_32\n    %2:gpr = x64.cmp_set_l_32 %0, %1\n    \
7559             x64.br_cond_8 %2, block1, block2\n\n\
7560             block1:\n    x64.ret_val_32 %0($rax)\n\n\
7561             block2:\n    x64.ret_val_32 %1($rax)\n}\n"
7562        );
7563    }
7564
7565    /// A choice between two values, which is one instruction and no blocks at all.
7566    ///
7567    /// The arms come out the other way round from the IR, because a conditional move overwrites its
7568    /// destination and the destination is the arm taken when the condition does not hold. The
7569    /// condition arrives last for the same reason: it is read by the test in front of the move
7570    /// rather than by the move.
7571    #[test]
7572    fn a_select_is_lowered_to_a_test_and_a_conditional_move() {
7573        let i32 = Type::int(32);
7574        let (mut names, mut source, entry, args) = blank(&[i32, i32]);
7575        let mut build = Builder::new(&mut source, entry);
7576        let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
7577        let picked = build.select(cond, args[0], args[1]);
7578        build.ret(&[picked]);
7579
7580        assert_eq!(
7581            lower(&mut names, &source),
7582            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_32\n    \
7583             %1:gpr($rsi) = x64.arg_val_32\n    %2:gpr = x64.cmp_set_l_32 %0, %1\n    \
7584             %3:gpr(reuse 1) = x64.test_cmov_ne_32 %1, %0, %2\n    \
7585             x64.ret_val_32 %3($rax)\n}\n"
7586        );
7587    }
7588
7589    #[test]
7590    fn a_branch_over_a_block_is_a_whole_function_now() {
7591        let i32 = Type::int(32);
7592        let (mut names, mut source, entry, args) = blank(&[i32, i32]);
7593        let then = source.create_block();
7594        let other = source.create_block();
7595        let join = source.create_block();
7596        let got = source.append_param(join, i32);
7597        let mut build = Builder::new(&mut source, entry);
7598        let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
7599        build.br_if(cond, then, &[], other, &[]);
7600        let mut build = Builder::new(&mut source, then);
7601        let sum = build.binary(Opcode::Add, args[0], args[1], Flags::default());
7602        build.jump(join, &[sum]);
7603        Builder::new(&mut source, other).jump(join, &[args[1]]);
7604        Builder::new(&mut source, join).ret(&[got]);
7605
7606        // `int f(int a, int b) { if (a < b) return a + b; else return b; }` end to end, written
7607        // the way a front end writes it: both arms of the branch are blocks of their own and the
7608        // return is the block they meet at. No edge here is critical, because the two arms out of
7609        // the entry carry nothing and the two arms into the join each leave a block that goes
7610        // nowhere else, so each has its own end to put its move at.
7611        let mut out = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
7612            .expect("every instruction has a rule")
7613            .func;
7614        assert_eq!(crate::split::critical(&mut out), 0, "no edge here is critical");
7615        let env = env();
7616        let allocation = rucc_regalloc::run(&mut out, &env, "test", true);
7617        let frame = Frame::of(&out, &allocation, &Layout::new(&SYSV, REGS));
7618        finish(
7619            &mut out,
7620            &allocation,
7621            &frame,
7622            &Stack::default(),
7623            Convention::new(&SYSV, &FRAME),
7624            &mut names,
7625        );
7626
7627        // One epilogue, on the join, which is the one block the function leaves from, and the
7628        // moves that give the join its parameter are at the end of each arm. Every register is
7629        // physical and the branch is still a branch on a register, because turning it into a
7630        // `test` and a `jcc` is the block layout's and there is no block layout yet.
7631        let text = mir::print_func(&out, &names, &REGS);
7632        assert_eq!(text.matches("x64.ret\n").count(), 1, "{text}");
7633        assert!(text.contains("x64.br_cond_8"), "{text}");
7634        assert!(text.contains("x64.add_rr_32"), "{text}");
7635        assert!(!text.contains('%'), "{text}");
7636    }
7637
7638    #[test]
7639    fn a_critical_edge_is_split_before_the_allocator_ever_sees_it() {
7640        let i32 = Type::int(32);
7641        let (mut names, mut source, entry, args) = blank(&[i32, i32]);
7642        let then = source.create_block();
7643        let join = source.create_block();
7644        let got = source.append_param(join, i32);
7645        let mut build = Builder::new(&mut source, entry);
7646        let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
7647        build.br_if(cond, then, &[], join, &[args[1]]);
7648        Builder::new(&mut source, then).jump(join, &[args[0]]);
7649        let mut build = Builder::new(&mut source, join);
7650        let twice = build.binary(Opcode::Add, got, got, Flags::default());
7651        build.ret(&[twice]);
7652
7653        // The else arm is critical: the entry block leaves two ways and the join is arrived at
7654        // two ways, and the arm carries a value. Without splitting it the allocator asserts,
7655        // because the move that gives the join its parameter would have to run at the end of a
7656        // block that also goes to the other arm.
7657        let mut out = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
7658            .expect("every instruction has a rule")
7659            .func;
7660        assert_eq!(crate::split::critical(&mut out), 1);
7661        let env = env();
7662        let allocation = rucc_regalloc::run(&mut out, &env, "test", true);
7663        let frame = Frame::of(&out, &allocation, &Layout::new(&SYSV, REGS));
7664        finish(
7665            &mut out,
7666            &allocation,
7667            &frame,
7668            &Stack::default(),
7669            Convention::new(&SYSV, &FRAME),
7670            &mut names,
7671        );
7672
7673        // The block the split added is where the move went, and it is the whole of that block.
7674        let text = mir::print_func(&out, &names, &REGS);
7675        assert_eq!(out.block_count(), 4, "{text}");
7676        assert_eq!(text.matches("x64.ret\n").count(), 1, "{text}");
7677    }
7678
7679    #[test]
7680    fn a_call_passes_what_the_convention_says_and_takes_back_what_it_says() {
7681        let i32 = Type::int(32);
7682        let (mut names, mut source, block, args) = blank(&[i32, i32]);
7683        let sig =
7684            source.add_signature(Signature::new().with_params(&[i32, i32]).with_returns(&[i32]));
7685        let callee = names.intern("g");
7686        let call = Builder::new(&mut source, block).call(callee, sig, &[args[0], args[1]]);
7687        let got = source[call].first_result.expect("an integer comes back");
7688        Builder::new(&mut source, block).ret(&[got]);
7689
7690        // `int f(int a, int b) { return g(a, b); }`. The arguments arrived where the call wants
7691        // them, so what the call reads is what arrived, and the whole of the convention is in the
7692        // constraints rather than in a move.
7693        let text = lower(&mut names, &source);
7694        assert!(text.contains("= x64.call %0($rdi), %1($rsi), @g"), "{text}");
7695        assert!(text.contains("x64.ret_val_32 %2($rax)"), "{text}");
7696        // What the call writes is the value that comes back and then every register the callee is
7697        // free to destroy, in both classes, which is the whole of what stops the allocator from
7698        // leaving something in one of them.
7699        assert!(text.contains("%2:gpr($rax), $rcx, $rdx, $r8, $r9, $r10, $r11, $xmm0,"), "{text}");
7700        assert!(text.contains("$xmm15 = x64.call"), "{text}");
7701    }
7702
7703    #[test]
7704    fn what_the_frame_owes_a_call_comes_back_with_the_function() {
7705        let i32 = Type::int(32);
7706        let sig = |source: &mut Func| source.add_signature(Signature::new().with_params(&[i32]));
7707
7708        let (mut names, mut source, block, args) = blank(&[i32]);
7709        let sig = sig(&mut source);
7710        let callee = names.intern("g");
7711        Builder::new(&mut source, block).call(callee, sig, &[args[0]]);
7712        let out = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
7713            .expect("every instruction has a rule");
7714
7715        // Nothing on the stack, so nothing owed, but not a leaf either: a function that calls
7716        // owes the callee an aligned stack pointer and may not use the red zone.
7717        assert_eq!(out.stack.calls, Some(0));
7718        let layout = out.stack.layout(Layout::new(&SYSV, REGS));
7719        assert!(!layout.leaf);
7720        assert_eq!(layout.outgoing, 0);
7721
7722        // The same call under the other convention owes thirty two bytes for the callee to spill
7723        // its register arguments into, which is a fact about the convention and not about the call.
7724        let out = func(&source, &mut names, &SELECTOR, &x86_64::WIN64, &Elsewhere::default())
7725            .expect("every instruction has a rule");
7726        assert_eq!(out.stack.calls, Some(32));
7727
7728        // And a function that calls nothing is a leaf, which is what says it may use the red zone.
7729        let (mut names, mut source, block, args) = blank(&[i32]);
7730        Builder::new(&mut source, block).ret(&[args[0]]);
7731        let out = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
7732            .expect("every instruction has a rule");
7733        assert_eq!(out.stack.calls, None);
7734        assert!(out.stack.layout(Layout::new(&SYSV, REGS)).leaf);
7735    }
7736
7737    /// A Windows variadic prologue writes the argument registers the signature did not name into
7738    /// the shadow space the caller already reserved, which makes every argument one run of words up
7739    /// there and a `va_start` the address of the first of them. One `lea` and one store, and no
7740    /// counts, because a list that is a pointer has nowhere to put one and nothing that reads one.
7741    #[test]
7742    fn a_windows_variadic_function_homes_its_spare_registers_in_the_callers_area() {
7743        let mut names = Interner::new();
7744        let params = [Type::int(32), Type::PTR];
7745        let signature = Signature::new().with_params(&params).variadic();
7746        let mut source = Func::new(names.intern("f"), signature);
7747        let block = source.create_block();
7748        let values: Vec<Value> = params.iter().map(|&ty| source.append_param(block, ty)).collect();
7749        let mut build = Builder::new(&mut source, block);
7750        let args = build.func().push_values(&values[1..]);
7751        build.inst(InstData { args, ..InstData::new(Opcode::VaStart) }, &[]);
7752        build.ret(&[]);
7753
7754        let out = func(&source, &mut names, &SELECTOR, &x86_64::WIN64, &Elsewhere::default())
7755            .expect("every instruction has a rule");
7756        let text = mir::print_func(&out.func, &names, &REGS);
7757
7758        // Two named parameters, so the registers at the next two positions hold arguments nobody
7759        // named and both are written up into the caller's area. The displacement is empty here and
7760        // `finish` fills it in, the same way it does for a parameter the registers ran out before.
7761        assert!(text.contains("($r8) = x64.arg_val_64"), "{text}");
7762        assert!(text.contains("($r9) = x64.arg_val_64"), "{text}");
7763        assert_eq!(text.matches("x64.mov_mr_64").count(), 3, "two homed and one stored: {text}");
7764        assert!(!text.contains("x64.mov_ri_32"), "and no field holds a count: {text}");
7765
7766        // All three waiting on the same fixup, and the last of them is the `lea` the list is given,
7767        // sixteen bytes up, which is where the two arguments the signature does name stopped.
7768        assert_eq!(out.stack.arguments.len(), 3);
7769        assert_eq!(out.stack.arguments[2].1, 16);
7770    }
7771
7772    #[test]
7773    fn a_value_that_outlives_a_call_is_not_left_where_the_call_destroys_it() {
7774        let i32 = Type::int(32);
7775        let (mut names, mut source, block, args) = blank(&[i32]);
7776        let sig = source.add_signature(Signature::new().with_params(&[i32]).with_returns(&[i32]));
7777        let callee = names.intern("g");
7778        let call = Builder::new(&mut source, block).call(callee, sig, &[args[0]]);
7779        let got = source[call].first_result.expect("an integer comes back");
7780        let mut build = Builder::new(&mut source, block);
7781        let sum = build.binary(Opcode::Add, got, args[0], Flags::default());
7782        build.ret(&[sum]);
7783
7784        // `int f(int a) { return g(a) + a; }`, which is the smallest program that asks the
7785        // question: `a` is read after the call and `rdi` is a register the call destroys.
7786        let lowered = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
7787            .expect("every instruction has a rule");
7788        let layout = lowered.stack.layout(Layout::new(&SYSV, REGS));
7789        let mut out = lowered.func;
7790        let env = env();
7791        let allocation = rucc_regalloc::run(&mut out, &env, "test", true);
7792        let frame = Frame::of(&out, &allocation, &layout);
7793        finish(
7794            &mut out,
7795            &allocation,
7796            &frame,
7797            &Stack::default(),
7798            Convention::new(&SYSV, &FRAME),
7799            &mut names,
7800        );
7801
7802        // It went to a register the callee has to put back, and the prologue and epilogue are what
7803        // put it back, which is the whole bargain the two halves of a convention make.
7804        let text = mir::print_func(&out, &names, &REGS);
7805        assert!(text.contains("$rbx"), "{text}");
7806        assert!(!text.contains('%'), "{text}");
7807        assert_eq!(text.matches("x64.call").count(), 1, "{text}");
7808    }
7809
7810    #[test]
7811    fn a_call_with_more_arguments_than_registers_writes_the_rest_into_the_outgoing_area() {
7812        let i64 = Type::int(64);
7813        let (mut names, mut source, block, args) = blank(&[i64]);
7814        let seven = vec![i64; 7];
7815        let sig = source.add_signature(Signature::new().with_params(&seven));
7816        let callee = names.intern("g");
7817        let passed = vec![args[0]; 7];
7818        Builder::new(&mut source, block).call(callee, sig, &passed);
7819
7820        let lowered = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
7821            .expect("the seventh goes to memory");
7822        // The bytes the call needs are on the layout the frame is worked out from, so that the
7823        // frame reserves as many as the widest call in the function asked for.
7824        assert_eq!(lowered.stack.calls, Some(8));
7825        let text = mir::print_func(&lowered.func, &names, &REGS);
7826        assert!(text.contains("x64.mov_mr_64 %0, [$rsp]\n"), "{text}");
7827    }
7828
7829    #[test]
7830    fn a_call_this_cannot_make_is_reported_rather_than_made() {
7831        let (mut names, mut source, block, _) = blank(&[]);
7832        let returns = [Type::float(rucc_ir::Float::F80), Type::int(64)];
7833        let sig = source.add_signature(Signature::new().with_returns(&returns));
7834        let callee = names.intern("g");
7835        Builder::new(&mut source, block).call(callee, sig, &[]);
7836        let failed = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
7837            .expect_err("a long double is on the x87");
7838        assert_eq!(failed.to_string(), "what this call gives back is on the x87 stack");
7839    }
7840
7841    /// A `long double` on its own is a different answer, because on its own it comes back on the
7842    /// x87 stack rather than in a register, which is somewhere the call cannot be said to write.
7843    ///
7844    /// So the call gives back nothing at all and the value is taken off the stack by the `fstp`
7845    /// straight after it. That instruction has to be straight after it: the stack is one place and
7846    /// anything else that touched it before this ran would be looking at the value still on it.
7847    #[test]
7848    fn a_call_that_gives_back_a_long_double_takes_it_off_the_stack_at_once() {
7849        let (mut names, mut source, block, _) = blank(&[]);
7850        let long_double = Type::float(rucc_ir::Float::F80);
7851        let sig = source.add_signature(Signature::new().with_returns(&[long_double]));
7852        let callee = names.intern("g");
7853        Builder::new(&mut source, block).call(callee, sig, &[]);
7854
7855        let lowered = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
7856            .expect("the value comes back in st0");
7857        let text = mir::print_func(&lowered.func, &names, &REGS);
7858        let after: Vec<&str> =
7859            text.lines().skip_while(|line| !line.contains("x64.call")).skip(1).collect();
7860        assert_eq!(after[0].trim(), "%0:gpr = x64.lea_64 [$rsp]", "{text}");
7861        assert_eq!(after[1].trim(), "x64.fstp_t [%0]", "{text}");
7862        // And the slot it went into is the sixteen bytes the type takes, like every other one.
7863        assert_eq!(lowered.stack.locals.len(), 1, "{text}");
7864        assert_eq!(lowered.stack.locals[0].size, X87_BYTES);
7865    }
7866
7867    #[test]
7868    fn a_call_through_an_address_goes_through_the_register_the_address_is_in() {
7869        let i32 = Type::int(32);
7870        let (mut names, mut source, block, args) = blank(&[Type::PTR, i32]);
7871        let sig = source.add_signature(Signature::new().with_params(&[i32]).with_returns(&[i32]));
7872        let varargs = source.push_abis(&[]);
7873        let info = source.add_call(CallInfo { callee: None, signature: sig, varargs });
7874        let mut build = Builder::new(&mut source, block);
7875        let inst = InstData {
7876            args: build.func().push_values(&[args[0], args[1]]),
7877            extra: Extra::Call(info),
7878            ..InstData::new(Opcode::CallIndirect)
7879        };
7880        let called = build.inst(inst, &[i32]);
7881        let got = source[called].first_result.expect("an integer comes back");
7882        Builder::new(&mut source, block).ret(&[got]);
7883
7884        // `int f(int (*g)(int), int a) { return g(a); }`. The first operand is the address and
7885        // the arguments are the ones behind it, and everything else about the call is what a call
7886        // to a name would have been.
7887        let text = lower(&mut names, &source);
7888        assert!(text.contains("= x64.call_reg %0, %1($rdi)"), "{text}");
7889        assert!(text.contains("x64.ret_val_32 %2($rax)"), "{text}");
7890        assert!(!text.contains("@g"), "a call through an address names nobody: {text}");
7891    }
7892
7893    #[test]
7894    fn an_instruction_no_rule_covers_is_reported() {
7895        let (mut names, mut source, block, args) = blank(&[Type::PTR]);
7896        let mut build = Builder::new(&mut source, block);
7897        let operands = build.func().push_values(&[args[0]]);
7898        build.inst(InstData { args: operands, ..InstData::new(Opcode::MetaBegin) }, &[]);
7899
7900        // The mark that an object has come into being, which nothing writes an instruction for
7901        // yet: what it needs is a write over a range of the lifetime plane, and that is
7902        // `tamnd/rucc#856`. Nothing about it is a width or a register, so there is nothing for the
7903        // message to add beyond the name.
7904        let failed = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
7905            .expect_err("no rule writes the beginning of a lifetime");
7906        assert_eq!(failed.to_string(), "no rule lowers a `meta_begin`");
7907
7908        // It produces nothing, so there is no type in the message and nothing invents one, and the
7909        // instruction comes back so a caller can ask the function where it was.
7910        let inst = failed.inst().expect("the instruction it is about");
7911        assert_eq!(source[inst].opcode, Opcode::MetaBegin);
7912    }
7913
7914    /// A barrier is written by name here, and what it is depends on the ordering and on nothing
7915    /// else. `crate::expand` is where the reasoning about this machine's memory model lives.
7916    #[test]
7917    fn a_barrier_is_one_instruction_at_the_strongest_ordering_and_none_below_it() {
7918        for order in MemOrder::all().filter(|&order| order != MemOrder::NotAtomic) {
7919            let (mut names, mut source, block, _) = blank(&[]);
7920            let mut build = Builder::new(&mut source, block);
7921            build
7922                .inst(InstData { extra: Extra::Order(order), ..InstData::new(Opcode::Fence) }, &[]);
7923
7924            let text = lower(&mut names, &source);
7925            assert_eq!(text.contains("x64.mfence"), order == MemOrder::SeqCst, "{order:?}: {text}");
7926        }
7927    }
7928
7929    /// A compare and exchange is written by name too, and at the width of the value rather than at
7930    /// the width of the address, which is the mistake worth pinning: everything here is a pointer
7931    /// and only the value says how many bytes the instruction touches.
7932    #[test]
7933    fn a_compare_and_exchange_is_one_instruction_at_the_width_of_the_value() {
7934        for bits in [8, 16, 32, 64] {
7935            let ty = Type::int(bits);
7936            let (mut names, mut source, block, args) = blank(&[Type::PTR, ty, ty]);
7937            let mut build = Builder::new(&mut source, block);
7938            let mem = build.func().add_mem(MemInfo {
7939                size: u64::from(bits / 8),
7940                align: bits / 8,
7941                order: MemOrder::SeqCst,
7942                ..plain()
7943            });
7944            let operands = build.func().push_values(&[args[0], args[1], args[2]]);
7945            build.inst(
7946                InstData {
7947                    args: operands,
7948                    extra: Extra::Mem(mem),
7949                    ..InstData::new(Opcode::Cmpxchg)
7950                },
7951                &[ty, Type::I1],
7952            );
7953
7954            // Two values out of one instruction, the first of them in the register the machine
7955            // reads the expected value out of, the second free for the allocator to place. The
7956            // address is the memory operand and neither of the two values is.
7957            let text = lower(&mut names, &source);
7958            let written = format!("%3:gpr($rax), %4:gpr = x64.cmpxchg_{bits} %1($rax), %2, [%0]");
7959            assert!(text.contains(&written), "{bits}: {text}");
7960        }
7961    }
7962
7963    #[test]
7964    fn more_values_back_than_the_convention_has_registers_for_is_reported() {
7965        let i64 = Type::int(64);
7966        let (mut names, mut source, block, args) = blank(&[i64, i64, i64]);
7967        let mut build = Builder::new(&mut source, block);
7968        build.ret(&[args[0], args[1], args[2]]);
7969
7970        // Two integers come back in `rax` and `rdx` and a third has nowhere to go, which is not a
7971        // gap in the rules but the convention saying no. The front end classifies before it gets
7972        // here, so this is the shape that would mean the classification went wrong.
7973        let failed = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
7974            .expect_err("only two come back");
7975        assert_eq!(
7976            failed.to_string(),
7977            "what this function gives back takes more registers than this convention has for it"
7978        );
7979
7980        let inst = failed.inst().expect("the instruction it is about");
7981        assert_eq!(source[inst].opcode, Opcode::Return);
7982    }
7983
7984    /// A refusal about a signature has no instruction, which is what makes it the one arm apart.
7985    ///
7986    /// Everything else is about something written somewhere in the body and hands it back so a
7987    /// caller can ask the function where it came from. A parameter arrives before the first
7988    /// instruction runs, so there is nothing in the body to point at and the message is about
7989    /// the function.
7990    #[test]
7991    fn a_refusal_about_a_parameter_has_no_instruction_to_point_at() {
7992        let missing = Unsupported::Argument { index: 0, missing: Missing::OnX87 };
7993        assert_eq!(missing.inst(), None);
7994    }
7995
7996    /// An `alloca` of a fixed size, which is what every local whose address is taken becomes.
7997    fn slot(source: &mut Func, block: Block, size: u64, align: u32) -> Value {
7998        let info = MemInfo { size, align, ..plain() };
7999        let mut build = Builder::new(source, block);
8000        let mem = build.func().add_mem(info);
8001        build.value(InstData { extra: Extra::Mem(mem), ..InstData::new(Opcode::Alloca) }, Type::PTR)
8002    }
8003
8004    #[test]
8005    fn a_local_is_memory_in_the_frame_and_one_instruction_that_says_where() {
8006        let (mut names, mut source, block, _) = blank(&[]);
8007        let slot = slot(&mut source, block, 4, 4);
8008        let mut build = Builder::new(&mut source, block);
8009        let nine = build.iconst(Type::int(32), 9);
8010        build.store(nine, slot, plain(), Flags::default());
8011        let loaded = build.load(Type::int(32), slot, plain(), Flags::default());
8012        build.ret(&[loaded]);
8013
8014        let lowered = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
8015            .expect("every instruction has a rule");
8016
8017        // Four bytes on the list the frame is laid out from, and the one instruction that reads
8018        // where they went. Its displacement is nothing here because there is no frame yet, and
8019        // which instruction is waiting for which local is what `finish` is handed.
8020        assert_eq!(lowered.stack.locals, vec![Local { size: 4, align: 4 }]);
8021        assert_eq!(lowered.stack.addresses.len(), 1);
8022        assert_eq!(lowered.stack.addresses[0].1, 0);
8023        assert_eq!(
8024            mir::print_func(&lowered.func, &names, &REGS),
8025            "mfunc @f {\nblock0:\n    %0:gpr = x64.lea_64 [$rsp]\n    \
8026             %1:gpr = x64.mov_ri_32 9\n    x64.mov_mr_32 %1, [%0]\n    \
8027             %2:gpr = x64.mov_rm_32 [%0]\n    x64.ret_val_32 %2($rax)\n}\n"
8028        );
8029    }
8030
8031    #[test]
8032    fn a_local_the_program_declared_says_which_declaration_it_is_and_the_rest_say_nothing() {
8033        let (mut names, mut source, block, _) = blank(&[]);
8034        let scratch = slot(&mut source, block, 4, 4);
8035        let mut build = Builder::new(&mut source, block);
8036        let mem = build.func().add_mem(MemInfo { size: 8, align: 8, ..plain() });
8037        let declared = build
8038            .value(InstData { extra: Extra::Mem(mem), ..InstData::new(Opcode::Alloca) }, Type::PTR);
8039        build.func().declare_mem(mem, 41);
8040        build.store(scratch, declared, MemInfo { size: 8, align: 8, ..plain() }, Flags::default());
8041        build.ret(&[]);
8042
8043        let lowered = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
8044            .expect("every instruction has a rule");
8045
8046        // Two locals and one declaration, held against the order the allocas were lowered in,
8047        // which is the only name a local has by the time the frame places it. The scratch one was
8048        // reached first and is local zero, so the declared one is local one.
8049        assert_eq!(lowered.stack.locals.len(), 2);
8050        assert_eq!(lowered.stack.declared, vec![(1, 41)]);
8051    }
8052
8053    /// A local the program kept in a value comes out saying which register holds it.
8054    ///
8055    /// The other half of the local above, which had a slot. This one has none, so what carries the
8056    /// declaration is the register the instruction computing it writes into.
8057    #[test]
8058    fn a_local_the_program_kept_in_a_value_says_which_register_holds_it() {
8059        let (mut names, mut source, block, _) = blank(&[]);
8060        let mut build = Builder::new(&mut source, block);
8061        let nine = build.iconst(Type::int(32), 9);
8062        let ten = build.iconst(Type::int(32), 10);
8063        let sum = build.binary(Opcode::Add, nine, ten, Flags::default());
8064        build.func().declare_value(sum, 41);
8065        build.ret(&[sum]);
8066
8067        let lowered = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
8068            .expect("every instruction has a rule");
8069
8070        // One pair and not three. The constants are values the program never declared, and a
8071        // register holding one of those is nobody's. The register is the one the addition writes,
8072        // which the listing under it is what pins down.
8073        assert_eq!(lowered.func.named, vec![(41, mir::Reg::virtual_reg(1))]);
8074        assert_eq!(
8075            mir::print_func(&lowered.func, &names, &REGS),
8076            "mfunc @f {\nblock0:\n    %0:gpr = x64.mov_ri_32 9\n    \
8077             %1:gpr(reuse 1) = x64.add_ri_32 %0, 10\n    x64.ret_val_32 %1($rax)\n}\n"
8078        );
8079    }
8080
8081    /// A local held in a constant two blocks want is two registers and both of them are it.
8082    ///
8083    /// Why the declaration is written down as each register is handed out rather than once at the
8084    /// end over the map from values to registers. That map remembers the last register a value was
8085    /// written into, and a constant is written again in every block that wants one, so a local held
8086    /// in one would come out findable in the last block of the function and nowhere else.
8087    #[test]
8088    fn a_local_held_in_a_constant_two_blocks_want_is_named_in_both_of_them() {
8089        let i32 = Type::int(32);
8090        let (mut names, mut source, entry, args) = blank(&[i32, i32]);
8091        let then = source.create_block();
8092        let other = source.create_block();
8093        let join = source.create_block();
8094        let got = source.append_param(join, i32);
8095
8096        let mut build = Builder::new(&mut source, entry);
8097        let seven = build.iconst(i32, 7);
8098        let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
8099        build.func().declare_value(seven, 41);
8100        build.br_if(cond, then, &[], other, &[]);
8101        Builder::new(&mut source, then).jump(join, &[seven]);
8102        Builder::new(&mut source, other).jump(join, &[seven]);
8103        Builder::new(&mut source, join).ret(&[got]);
8104
8105        let lowered = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
8106            .expect("every instruction has a rule");
8107
8108        let held = &lowered.func.named;
8109        assert_eq!(held.len(), 2, "one register per block that wanted the seven: {held:?}");
8110        assert!(held.iter().all(|&(decl, _)| decl == 41), "{held:?}");
8111        assert_ne!(held[0].1, held[1].1, "the same register in two blocks: {held:?}");
8112    }
8113
8114    /// A parameter the program declared comes out named too, in the register it arrived in.
8115    ///
8116    /// The case the walk over the map at the end is for. A parameter is put in a register the
8117    /// convention chose rather than in a fresh one, so nothing asks the mint for it and the pair
8118    /// would otherwise never be written down.
8119    #[test]
8120    fn a_parameter_the_program_declared_says_which_register_it_arrived_in() {
8121        let i32 = Type::int(32);
8122        let (mut names, mut source, block, args) = blank(&[i32]);
8123        let mut build = Builder::new(&mut source, block);
8124        build.func().declare_value(args[0], 41);
8125        build.ret(&[args[0]]);
8126
8127        let lowered = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
8128            .expect("every instruction has a rule");
8129
8130        let held = &lowered.func.named;
8131        assert_eq!(held.len(), 1, "one pair for the one parameter: {held:?}");
8132        assert_eq!(held[0].0, 41);
8133    }
8134
8135    /// A function with nothing declared in it says nothing, which is every function compiled
8136    /// without debugging information asked for.
8137    #[test]
8138    fn a_function_the_front_end_named_nothing_in_names_no_registers() {
8139        let (mut names, mut source, block, _) = blank(&[]);
8140        let mut build = Builder::new(&mut source, block);
8141        let nine = build.iconst(Type::int(32), 9);
8142        build.ret(&[nine]);
8143
8144        let lowered = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
8145            .expect("every instruction has a rule");
8146        assert!(lowered.func.named.is_empty(), "{:?}", lowered.func.named);
8147    }
8148
8149    #[test]
8150    fn the_frame_is_what_fills_the_address_of_a_local_in() {
8151        let (mut names, mut source, block, _) = blank(&[]);
8152        let slot = slot(&mut source, block, 4, 4);
8153        let mut build = Builder::new(&mut source, block);
8154        let nine = build.iconst(Type::int(32), 9);
8155        build.store(nine, slot, plain(), Flags::default());
8156        let loaded = build.load(Type::int(32), slot, plain(), Flags::default());
8157        build.ret(&[loaded]);
8158
8159        let lowered = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
8160            .expect("every instruction has a rule");
8161        let stack = lowered.stack;
8162        let mut out = lowered.func;
8163        let env = env();
8164        let allocation = rucc_regalloc::run(&mut out, &env, "test", true);
8165        let layout = stack.layout(Layout::new(&SYSV, REGS));
8166        let frame = Frame::of(&out, &allocation, &layout);
8167        finish(&mut out, &allocation, &frame, &stack, Convention::new(&SYSV, &FRAME), &mut names);
8168
8169        // `int f(void) { int x; x = 9; return x; }` with the address of `x` taken, end to end.
8170        // A leaf small enough to live in the red zone takes no frame at all, so the stack pointer
8171        // never moves and the four bytes are below it, which is what the negative offset is. The
8172        // instruction the lowering left with nothing in its displacement now has the answer in it.
8173        let text = mir::print_func(&out, &names, &REGS);
8174        assert!(text.contains("$rax = x64.lea_64 [$rsp - 8]"), "{text}");
8175        assert!(!text.contains("x64.sub_ri_64"), "{text}");
8176        assert_eq!(frame.size(), 0);
8177        assert_eq!(frame.local(0), Some(-8));
8178    }
8179
8180    /// An `alloca` whose size is an operand, which is a variable length array.
8181    fn growing(source: &mut Func, block: Block, size: Value, align: u32) -> Value {
8182        let info = MemInfo { size: 0, align, ..plain() };
8183        let mut build = Builder::new(source, block);
8184        let mem = build.func().add_mem(info);
8185        let args = build.func().push_values(&[size]);
8186        build.value(
8187            InstData { args, extra: Extra::Mem(mem), ..InstData::new(Opcode::Alloca) },
8188            Type::PTR,
8189        )
8190    }
8191
8192    #[test]
8193    fn a_stack_slot_whose_size_is_not_known_until_it_runs_takes_the_bytes_off_the_stack_pointer() {
8194        let (mut names, mut source, block, args) = blank(&[Type::int(64)]);
8195        let slot = growing(&mut source, block, args[0], 16);
8196        Builder::new(&mut source, block).ret(&[slot]);
8197
8198        let lowered = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
8199            .expect("every instruction has a rule");
8200
8201        // The bytes come off the stack pointer where the declaration stands and the address is
8202        // where the stack pointer then is, which is one subtraction and one `lea` rather than a
8203        // slot the frame laid out. Nothing is on the list of locals, because there is nothing
8204        // about this the frame could place.
8205        let text = mir::print_func(&lowered.func, &names, &REGS);
8206        assert!(text.contains("$rsp = x64.sub_rr_64 $rsp, %0"), "{text}");
8207        assert!(text.contains("x64.lea_64 [$rsp]"), "{text}");
8208        assert!(lowered.stack.locals.is_empty(), "{text}");
8209        assert_eq!(lowered.stack.dynamic.len(), 1);
8210        assert!(lowered.stack.grown_at.is_some());
8211    }
8212
8213    #[test]
8214    fn a_growing_slot_wanting_more_alignment_than_the_stack_pointer_has_is_reported() {
8215        let (mut names, mut source, block, args) = blank(&[Type::int(64)]);
8216        let slot = growing(&mut source, block, args[0], 32);
8217        Builder::new(&mut source, block).ret(&[slot]);
8218
8219        // Thirty two is more than a call leaves the stack pointer on, so giving it what it asked
8220        // for means masking the stack pointer after moving it, and after that no constant reaches
8221        // the rest of the frame from the frame pointer either. A second pointer held for the
8222        // purpose is what fixes it and there is not one yet.
8223        let failed = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
8224            .expect_err("nothing realigns a frame that grows");
8225        assert_eq!(
8226            failed.to_string(),
8227            "this local wants more alignment than the stack pointer is left on, which needs a \
8228             base register nothing here keeps"
8229        );
8230    }
8231
8232    #[test]
8233    fn a_frame_that_grows_reaches_its_own_locals_through_the_frame_pointer() {
8234        let (mut names, mut source, block, args) = blank(&[Type::int(64)]);
8235        let fixed = slot(&mut source, block, 4, 4);
8236        let mut build = Builder::new(&mut source, block);
8237        let nine = build.iconst(Type::int(32), 9);
8238        build.store(nine, fixed, plain(), Flags::default());
8239        let grown = growing(&mut source, block, args[0], 16);
8240        Builder::new(&mut source, block).ret(&[grown]);
8241
8242        let lowered = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
8243            .expect("every instruction has a rule");
8244        let stack = lowered.stack;
8245        let mut out = lowered.func;
8246        let env = env();
8247        let allocation = rucc_regalloc::run(&mut out, &env, "test", true);
8248        let layout = stack.layout(Layout::new(&SYSV, REGS));
8249        let frame = Frame::of(&out, &allocation, &layout);
8250        finish(&mut out, &allocation, &frame, &stack, Convention::new(&SYSV, &FRAME), &mut names);
8251
8252        // The stack pointer moves in the middle of the function, so the four bytes of the fixed
8253        // local are not a constant away from it any more and the frame pointer is what reaches
8254        // them. The frame keeps one whatever the flags asked for, takes its bytes rather than
8255        // living in the red zone, and the address of the growing slot is off the stack pointer as
8256        // it stands after the subtraction rather than off anything the prologue left.
8257        let text = mir::print_func(&out, &names, &REGS);
8258        assert!(frame.grows());
8259        assert!(frame.frame_pointer());
8260        assert!(frame.size() > 0, "{text}");
8261        assert!(text.contains("x64.lea_64 [$rbp"), "{text}");
8262        assert!(text.contains("$rsp = x64.sub_rr_64 $rsp"), "{text}");
8263        assert!(text.contains("x64.lea_64 [$rsp]"), "{text}");
8264    }
8265
8266    #[test]
8267    fn an_address_is_read_written_and_added_to_like_the_integer_it_is() {
8268        let (mut names, mut source, block, args) = blank(&[Type::PTR, Type::int(64)]);
8269        let mut build = Builder::new(&mut source, block);
8270        let stepped = build.func().push_values(&[args[0], args[1]]);
8271        let next =
8272            build.value(InstData { args: stepped, ..InstData::new(Opcode::PtrAdd) }, Type::PTR);
8273        let loaded = build.load(Type::int(32), next, plain(), Flags::default());
8274        build.ret(&[loaded]);
8275
8276        // `int f(int *p, long i) { return *(int *)((char *)p + i); }`. Nothing about this is new
8277        // in the rule set, which is the point: the two addresses arrive in registers because an
8278        // address is an integer as wide as one, and the arithmetic on them is the add it always
8279        // was, so every rule written about an add reaches it.
8280        //
8281        // The add stays its own instruction here rather than folding into the address the load
8282        // reads from. Two registers with no scale on either is the one addressing mode the rules
8283        // have no load through, because the folds that exist are the displacement one and the
8284        // scaled ones, and this is neither. `crate::fold` is what puts the two together, after
8285        // selection, and this is the pair it is handed.
8286        assert_eq!(
8287            lower(&mut names, &source),
8288            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_64\n    \
8289             %1:gpr($rsi) = x64.arg_val_64\n    %2:gpr(reuse 1) = x64.add_rr_64 %0, %1\n    \
8290             %3:gpr = x64.mov_rm_32 [%2]\n    x64.ret_val_32 %3($rax)\n}\n"
8291        );
8292    }
8293
8294    /// The address of a file scope name, which is what every use of a global and every string
8295    /// literal starts from.
8296    fn address_of(source: &mut Func, block: Block, names: &mut Interner, name: &str) -> Value {
8297        let symbol = names.intern(name);
8298        let mut build = Builder::new(source, block);
8299        build.value(
8300            InstData { extra: Extra::Symbol(symbol), ..InstData::new(Opcode::GlobalAddr) },
8301            Type::PTR,
8302        )
8303    }
8304
8305    #[test]
8306    fn the_address_of_a_name_is_one_instruction_carrying_the_name() {
8307        let (mut names, mut source, block, _) = blank(&[]);
8308        let counter = address_of(&mut source, block, &mut names, "counter");
8309        let mut build = Builder::new(&mut source, block);
8310        let loaded = build.load(Type::int(32), counter, plain(), Flags::default());
8311        build.ret(&[loaded]);
8312
8313        // `extern int counter; int f(void) { return counter; }`. The address is an addressing mode
8314        // that names no register and carries the symbol, which is what the assembler writes
8315        // relative to `%rip` and what the object writer leaves a relocation for.
8316        assert_eq!(
8317            lower(&mut names, &source),
8318            "mfunc @f {\nblock0:\n    %0:gpr = x64.lea_64 [@counter]\n    \
8319             %1:gpr = x64.mov_rm_32 [%0]\n    x64.ret_val_32 %1($rax)\n}\n"
8320        );
8321    }
8322
8323    #[test]
8324    fn the_address_of_a_name_outside_the_file_is_read_out_of_the_offset_table() {
8325        let (mut names, mut source, block, _) = blank(&[]);
8326        let away = address_of(&mut source, block, &mut names, "away");
8327        Builder::new(&mut source, block).ret(&[away]);
8328        let elsewhere: Elsewhere = [names.intern("away")].into_iter().collect();
8329
8330        // `extern void away(void); void *f(void) { return away; }`. A load and not an address
8331        // computation, because the distance from here to a name a shared library may be the one
8332        // that defines is not a number any link can work out, and the slot the linker fills in is
8333        // in this program and so is a distance it has.
8334        let out = func(&source, &mut names, &SELECTOR, &SYSV, &elsewhere)
8335            .expect("every instruction has a rule");
8336        assert_eq!(
8337            mir::print_func(&out.func, &names, &REGS),
8338            "mfunc @f {\nblock0:\n    %0:gpr = x64.mov_rm_64 [got @away]\n    \
8339             x64.ret_val_64 %0($rax)\n}\n"
8340        );
8341    }
8342
8343    #[test]
8344    fn the_address_of_a_thread_local_is_an_offset_out_of_the_table_plus_where_this_thread_starts() {
8345        let (mut names, mut source, block, _) = blank(&[]);
8346        let own = address_of(&mut source, block, &mut names, "own");
8347        Builder::new(&mut source, block).ret(&[own]);
8348        let elsewhere = Elsewhere::default().with_threads([names.intern("own")]);
8349
8350        // `extern _Thread_local int own; void *f(void) { return &own; }`. Three instructions where
8351        // the two cases above are one, because there is no address to load or to work out: the
8352        // slot holds how far into a thread's block the variable sits, `%fs:0` is where this
8353        // thread's block starts, and the sum of the two is this thread's copy.
8354        let out = func(&source, &mut names, &SELECTOR, &SYSV, &elsewhere)
8355            .expect("every instruction has a rule");
8356        assert_eq!(
8357            mir::print_func(&out.func, &names, &REGS),
8358            "mfunc @f {\nblock0:\n    %0:gpr = x64.mov_rm_64 [thread @own]\n    \
8359             %1:gpr = x64.mov_rm_64 [fs:0]\n    %2:gpr(reuse 1) = x64.add_rr_64 %0, %1\n    \
8360             x64.ret_val_64 %2($rax)\n}\n"
8361        );
8362    }
8363
8364    /// The same load with nothing added to it, which is the whole of `__builtin_thread_pointer`.
8365    #[test]
8366    fn the_start_of_this_thread_s_own_storage_is_the_one_load_and_no_arithmetic() {
8367        let (mut names, mut source, block, _) = blank(&[]);
8368        let here =
8369            Builder::new(&mut source, block).value(InstData::new(Opcode::ThreadPointer), Type::PTR);
8370        Builder::new(&mut source, block).ret(&[here]);
8371
8372        let out = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
8373            .expect("every instruction has a rule");
8374        assert_eq!(
8375            mir::print_func(&out.func, &names, &REGS),
8376            "mfunc @f {\nblock0:\n    %0:gpr = x64.mov_rm_64 [fs:0]\n    \
8377             x64.ret_val_64 %0($rax)\n}\n"
8378        );
8379    }
8380
8381    /// One `asm` statement, with its template and its constraint list written as a program does.
8382    fn assembly(
8383        source: &mut Func,
8384        block: Block,
8385        names: &mut Interner,
8386        template: &str,
8387        constraints: &str,
8388        args: &[Value],
8389        results: &[Type],
8390    ) -> Inst {
8391        clobbering(source, block, names, template, constraints, "memory", args, results)
8392    }
8393
8394    /// The same with a clobber list of its own, for the statements that are about one.
8395    #[allow(clippy::too_many_arguments)]
8396    fn clobbering(
8397        source: &mut Func,
8398        block: Block,
8399        names: &mut Interner,
8400        template: &str,
8401        constraints: &str,
8402        clobbers: &str,
8403        args: &[Value],
8404        results: &[Type],
8405    ) -> Inst {
8406        let info = AsmInfo {
8407            template: names.intern(template),
8408            constraints: names.intern(constraints),
8409            clobbers: names.intern(clobbers),
8410            targets: rucc_ir::BlockCallList::EMPTY,
8411        };
8412        Builder::new(source, block).inline_asm(info, args, results, Flags::VOLATILE)
8413    }
8414
8415    /// What a program asking the processor what it can do writes, which is the instruction whose
8416    /// every operand is a register its text does not name.
8417    #[test]
8418    fn a_template_whose_registers_are_named_by_the_constraints_places_them_from_the_letters() {
8419        let u32 = Type::int(32);
8420        let (mut names, mut source, block, _) = blank(&[]);
8421        let zero = Builder::new(&mut source, block).iconst(u32, 0);
8422        let out = clobbering(
8423            &mut source,
8424            block,
8425            &mut names,
8426            "cpuid",
8427            "=a,a",
8428            "ebx,ecx,edx",
8429            &[zero],
8430            &[u32],
8431        );
8432        let produced = source[out].results().next().expect("one result");
8433        Builder::new(&mut source, block).ret(&[produced]);
8434
8435        // `asm ("cpuid" : "=a" (n) : "a" (0) : "ebx", "ecx", "edx")`, which is the first thing
8436        // every program that has a faster path on some machines writes. Four registers written and
8437        // two read, none of them in the template, all of them out of the description, and the two
8438        // that the letters named are the statement's own. The subleaf is a zero because the
8439        // instruction reads `ecx` and the program said nothing about what is in it. The three
8440        // clobbers are gone because `cpuid` writes those three anyway, and saying it twice is one
8441        // register with two definitions.
8442        assert_eq!(
8443            lower(&mut names, &source),
8444            "mfunc @f {\nblock0:\n    %0:gpr = x64.mov_ri_32 0\n    \
8445             %1:gpr = x64.mov_ri_64 0\n    \
8446             %2:gpr($rax), %3:gpr($rbx), %4:gpr($rcx), %5:gpr($rdx) = x64.cpuid %0($rax), \
8447             %1($rcx)\n    x64.ret_val_32 %2($rax)\n}\n"
8448        );
8449    }
8450
8451    /// An operand the program pinned, by declaring the object it comes from `register long x asm
8452    /// ("r12")`. The letter on its own leaves the allocator to pick, and a template that reads the
8453    /// register by name needs the two to be the same register, so the brace is what ties them
8454    /// together. That is the one use of a local register variable the GNU manual calls reliable,
8455    /// and it is what tcc's `tests/tcctest.c` counts on.
8456    #[test]
8457    fn an_operand_the_program_pinned_is_placed_in_the_register_it_named() {
8458        let u64 = Type::int(64);
8459        let (mut names, mut source, block, _) = blank(&[]);
8460        let out =
8461            assembly(&mut source, block, &mut names, "mov $0x4542, %r12", "=r{r12}", &[], &[u64]);
8462        let produced = source[out].results().next().expect("one result");
8463        Builder::new(&mut source, block).ret(&[produced]);
8464
8465        // The template is one instruction the table already has, so it lowers to that instruction
8466        // rather than to text nobody read, and the register it names is the statement's own output
8467        // because the brace put the output there. Without the brace the letter would have let the
8468        // allocator pick, the two `%r12` would have been different registers, and the program would
8469        // have come back with whatever was in the one it picked.
8470        assert_eq!(
8471            lower(&mut names, &source),
8472            "mfunc @f {\nblock0:\n    %0:gpr($r12) = x64.mov_ri_64 17730\n    \
8473             x64.ret_val_64 %0($rax)\n}\n"
8474        );
8475    }
8476
8477    /// A clobber the instruction does not write itself, which is the case the list is there for.
8478    /// It goes on as a definition of the register, in among the other definitions, because that is
8479    /// the whole of how a machine function says a register is not worth anything after this.
8480    #[test]
8481    fn a_clobber_the_instruction_does_not_write_itself_is_a_definition_of_that_register() {
8482        let (mut names, mut source, block, _) = blank(&[]);
8483        clobbering(&mut source, block, &mut names, "pause", "", "rsi,cc,memory", &[], &[]);
8484        Builder::new(&mut source, block).ret(&[]);
8485
8486        assert_eq!(lower(&mut names, &source), "mfunc @f {\nblock0:\n    $rsi = x64.pause\n}\n");
8487    }
8488
8489    /// A clobber naming something this has no register for. Refused rather than dropped, since the
8490    /// list is the program saying which registers it may not leave anything in, and an entry
8491    /// nobody read is a register something may still be left in.
8492    #[test]
8493    fn a_clobber_this_has_no_register_for_is_refused() {
8494        let (mut names, mut source, block, _) = blank(&[]);
8495        clobbering(&mut source, block, &mut names, "pause", "", "zmm0", &[], &[]);
8496        Builder::new(&mut source, block).ret(&[]);
8497
8498        let failed = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
8499            .expect_err("there is no such register here");
8500        assert_eq!(
8501            failed.to_string(),
8502            "this `asm` says it destroys a register this has no name for"
8503        );
8504    }
8505
8506    #[test]
8507    fn an_asm_with_an_empty_template_and_no_operands_is_no_instructions() {
8508        let (mut names, mut source, block, _) = blank(&[]);
8509        assembly(&mut source, block, &mut names, "", "", &[], &[]);
8510        Builder::new(&mut source, block).ret(&[]);
8511
8512        // `asm volatile ("" : : : "memory")`, which is a barrier and nothing else. The barrier was
8513        // spent on the optimizer, which has finished by now, so what is left is nothing.
8514        assert_eq!(lower(&mut names, &source), "mfunc @f {\nblock0:\n}\n");
8515    }
8516
8517    #[test]
8518    fn an_output_an_input_is_tied_to_is_the_register_that_input_arrived_in() {
8519        let i32 = Type::int(32);
8520        let (mut names, mut source, block, args) = blank(&[i32]);
8521        let out = assembly(&mut source, block, &mut names, "", "=r,0", &args, &[i32]);
8522        let produced = source[out].results().next().expect("one result");
8523        Builder::new(&mut source, block).ret(&[produced]);
8524
8525        // `asm ("" : "=r" (x) : "0" (x))`, which is how a program stops the optimizer following a
8526        // value without changing it. The two share a place and the template writes nothing over
8527        // it, so the value comes back out of the register it went in.
8528        assert_eq!(
8529            lower(&mut names, &source),
8530            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_32\n    \
8531             x64.ret_val_32 %0($rax)\n}\n"
8532        );
8533    }
8534
8535    #[test]
8536    fn an_output_written_plus_is_the_same_rename() {
8537        let i32 = Type::int(32);
8538        let (mut names, mut source, block, args) = blank(&[i32]);
8539        let out = assembly(&mut source, block, &mut names, "", "+r", &args, &[i32]);
8540        let produced = source[out].results().next().expect("one result");
8541        Builder::new(&mut source, block).ret(&[produced]);
8542
8543        // `asm ("" : "+r" (x))`, which says the same thing in one operand instead of two.
8544        assert_eq!(
8545            lower(&mut names, &source),
8546            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_32\n    \
8547             x64.ret_val_32 %0($rax)\n}\n"
8548        );
8549    }
8550
8551    #[test]
8552    fn an_output_nothing_is_tied_to_is_a_zero() {
8553        let i32 = Type::int(32);
8554        let (mut names, mut source, block, _) = blank(&[]);
8555        let out = assembly(&mut source, block, &mut names, "", "=r", &[], &[i32]);
8556        let produced = source[out].results().next().expect("one result");
8557        Builder::new(&mut source, block).ret(&[produced]);
8558
8559        // `asm ("" : "=r" (y))`, whose answer is whatever the assembly left in the register, and
8560        // an empty template leaves nothing. A definite value rather than a register nothing wrote,
8561        // because the allocator is owed a definition before the use however little the program is.
8562        assert_eq!(
8563            lower(&mut names, &source),
8564            "mfunc @f {\nblock0:\n    %0:gpr = x64.mov_ri_32 0\n    x64.ret_val_32 %0($rax)\n}\n"
8565        );
8566    }
8567
8568    #[test]
8569    fn a_template_that_is_one_instruction_becomes_that_instruction() {
8570        let (mut names, mut source, block, _) = blank(&[]);
8571        assembly(&mut source, block, &mut names, "pause", "", &[], &[]);
8572        Builder::new(&mut source, block).ret(&[]);
8573
8574        // `asm volatile ("pause")`, which is what every spin lock in every allocator writes. One
8575        // instruction, no operands, and nothing between the template and the machine but the table
8576        // that already says what a `pause` is.
8577        assert_eq!(lower(&mut names, &source), "mfunc @f {\nblock0:\n    x64.pause\n}\n");
8578    }
8579
8580    #[test]
8581    fn a_template_that_reads_a_segment_becomes_the_load_it_already_was() {
8582        let i64 = Type::int(64);
8583        let (mut names, mut source, block, _) = blank(&[]);
8584        let out = assembly(&mut source, block, &mut names, "movq %%fs:0, %0", "=r", &[], &[i64]);
8585        let produced = source[out].results().next().expect("one result");
8586        Builder::new(&mut source, block).ret(&[produced]);
8587
8588        // `asm ("movq %%fs:0, %0" : "=r" (tid))`, which is how a program finds the block its own
8589        // thread owns. The same instruction `crate::lower` already writes for a thread-local
8590        // variable, reached this time because a program wrote it out by hand.
8591        assert_eq!(
8592            lower(&mut names, &source),
8593            "mfunc @f {\nblock0:\n    %0:gpr = x64.mov_rm_64 [fs:0]\n    \
8594             x64.ret_val_64 %0($rax)\n}\n"
8595        );
8596    }
8597
8598    /// A template this cannot read is kept as its text, which is what gcc does with every template.
8599    /// Whether the text is an instruction is the assembler's question, asked when the unit is
8600    /// assembled from its listing.
8601    #[test]
8602    fn a_template_naming_an_instruction_this_machine_has_not_got_is_kept_as_text() {
8603        let (mut names, mut source, block, _) = blank(&[]);
8604        assembly(&mut source, block, &mut names, "hcf", "", &[], &[]);
8605        Builder::new(&mut source, block).ret(&[]);
8606
8607        let printed = lower(&mut names, &source);
8608        assert!(printed.contains("x64.template"), "{printed}");
8609        assert!(printed.contains("@hcf"), "{printed}");
8610    }
8611
8612    /// A template kept as text with an operand in a register reads the operand, and its text holds
8613    /// a hole naming that operand of the instruction, which the writer fills with the register the
8614    /// allocator chose. The input is the instruction's only use, behind every register a call may
8615    /// write.
8616    #[test]
8617    fn a_template_kept_as_text_reads_an_operand_in_a_register_through_a_hole() {
8618        let i32 = Type::int(32);
8619        let (mut names, mut source, block, args) = blank(&[i32]);
8620        assembly(&mut source, block, &mut names, "hcf %0", "r", &[args[0]], &[]);
8621        Builder::new(&mut source, block).ret(&[]);
8622
8623        let printed = lower(&mut names, &source);
8624        let line = printed.lines().find(|line| line.contains("x64.template")).unwrap_or_default();
8625        // Twenty five registers are written ahead of it, so the operand read is the twenty sixth,
8626        // spelled at the width of an `int`.
8627        assert!(line.contains("x64.template %0, @hcf \u{1}r25k\u{2}"), "{printed}");
8628        assert!(line.contains("early $rax"), "{printed}");
8629    }
8630
8631    /// A template kept as text with more outputs than the convention keeps registers across a call
8632    /// gets back as many of the registers a call may write as it needs, from the end of the order,
8633    /// and keeps the rest. Six outputs against five preserved registers is one handed back, which is
8634    /// `r11`. The shape is `sodium_sub` in libsodium, whose `sbbq` into memory the reader has no
8635    /// form for, and before this the allocator ran out of registers on it.
8636    #[test]
8637    fn a_template_kept_as_text_with_more_outputs_than_are_kept_gets_registers_back() {
8638        let i64 = Type::int(64);
8639        let (mut names, mut source, block, _) = blank(&[]);
8640        let outputs = [i64; 6];
8641        let asm = assembly(
8642            &mut source,
8643            block,
8644            &mut names,
8645            "hcf %0, %1, %2, %3, %4, %5",
8646            "=&r,=&r,=&r,=&r,=&r,=&r",
8647            &[],
8648            &outputs,
8649        );
8650        let produced: Vec<Value> = source[asm].results().collect();
8651        Builder::new(&mut source, block).ret(&produced[..1]);
8652
8653        let printed = lower(&mut names, &source);
8654        let line = printed.lines().find(|line| line.contains("x64.template")).unwrap_or_default();
8655        assert!(line.contains("early $r10"), "{printed}");
8656        assert!(!line.contains("early $r11"), "{printed}");
8657    }
8658
8659    /// A register the template named is placed as itself, fixed to the register the program wrote
8660    /// down. A register a constraint letter names is a different thing and is placed too, which the
8661    /// test above is about: there the statement said which of its own operands is in the register,
8662    /// and a name in the middle of a template says the register and nothing about any operand.
8663    #[test]
8664    fn a_template_naming_a_register_gets_that_register() {
8665        let i64 = Type::int(64);
8666        let (mut names, mut source, block, _) = blank(&[]);
8667        let out = assembly(&mut source, block, &mut names, "movq %%rax, %0", "=r", &[], &[i64]);
8668        let produced = source[out].results().next().expect("one result");
8669        Builder::new(&mut source, block).ret(&[produced]);
8670
8671        // `asm ("movq %%rax, %0" : "=r" (x))`, which is a program reading whatever is in `%rax`.
8672        // The source is the register itself and the destination is one the allocator picks.
8673        assert_eq!(
8674            lower(&mut names, &source),
8675            "mfunc @f {\nblock0:\n    %0:gpr = x64.mov_rr_64 $rax($rax)\n    \
8676             x64.ret_val_64 %0($rax)\n}\n"
8677        );
8678    }
8679
8680    /// The half of the same thing every register saving template needs. micropython writes the
8681    /// callee-saved registers into a buffer one `movq %%r12, 48(%%rdi)` at a time, and both halves
8682    /// of that line are a register the template named: the one being stored and the one the address
8683    /// is counted from.
8684    #[test]
8685    fn a_template_counting_an_address_from_a_register_it_named_gets_that_register() {
8686        let (mut names, mut source, block, _) = blank(&[]);
8687        assembly(&mut source, block, &mut names, "movq %%r12, 48(%%rdi)", "", &[], &[]);
8688        Builder::new(&mut source, block).ret(&[]);
8689
8690        assert_eq!(
8691            lower(&mut names, &source),
8692            "mfunc @f {\nblock0:\n    x64.mov_mr_64 $r12($r12), [$rdi + 48]\n}\n"
8693        );
8694    }
8695
8696    /// A local kept in a named register, which is the same register named as itself and reached
8697    /// from the other side. micropython's collector writes six of these and reads them with
8698    /// ordinary C rather than with a template.
8699    #[test]
8700    fn a_local_kept_in_a_named_register_is_one_move_out_of_it() {
8701        let (mut names, mut source, block, _) = blank(&[]);
8702        let held = names.intern("rbx");
8703        let value = Builder::new(&mut source, block).value(
8704            InstData { extra: Extra::Symbol(held), ..InstData::new(Opcode::RegisterValue) },
8705            Type::int(64),
8706        );
8707        Builder::new(&mut source, block).ret(&[value]);
8708
8709        assert_eq!(
8710            lower(&mut names, &source),
8711            "mfunc @f {\nblock0:\n    %0:gpr = x64.mov_rr_64 $rbx($rbx)\n    \
8712             x64.ret_val_64 %0($rax)\n}\n"
8713        );
8714    }
8715
8716    /// The sigil gcc allows in front of the name is syntax and comes off, and a name that is not
8717    /// a register of this machine is refused in words that say which name it was.
8718    #[test]
8719    fn a_register_name_is_read_with_or_without_its_sigil_and_refused_when_there_is_no_such_one() {
8720        for written in ["%r12", "r12"] {
8721            let (mut names, mut source, block, _) = blank(&[]);
8722            let held = names.intern(written);
8723            let value = Builder::new(&mut source, block).value(
8724                InstData { extra: Extra::Symbol(held), ..InstData::new(Opcode::RegisterValue) },
8725                Type::int(64),
8726            );
8727            Builder::new(&mut source, block).ret(&[value]);
8728            assert!(lower(&mut names, &source).contains("$r12($r12)"), "{written} is not read");
8729        }
8730
8731        let (mut names, mut source, block, _) = blank(&[]);
8732        let held = names.intern("nowhere");
8733        let value = Builder::new(&mut source, block).value(
8734            InstData { extra: Extra::Symbol(held), ..InstData::new(Opcode::RegisterValue) },
8735            Type::int(64),
8736        );
8737        Builder::new(&mut source, block).ret(&[value]);
8738
8739        let failed = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
8740            .expect_err("there is no such register");
8741        assert_eq!(
8742            failed.to_string(),
8743            "this object is kept in `nowhere`, which is not a register this machine has"
8744        );
8745    }
8746
8747    #[test]
8748    fn a_constraint_list_that_does_not_describe_the_operands_is_refused() {
8749        let i32 = Type::int(32);
8750        let (mut names, mut source, block, args) = blank(&[i32]);
8751        assembly(&mut source, block, &mut names, "", "=r", &args, &[]);
8752        Builder::new(&mut source, block).ret(&[]);
8753
8754        // An output with no result to be, which is what the front end never writes and what a
8755        // hand written module can. Refused rather than placed by a guess.
8756        let failed = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
8757            .expect_err("the list and the instruction disagree");
8758        assert_eq!(failed.to_string(), "this `asm` has an operand this cannot place");
8759    }
8760
8761    /// A cast between a pointer and an integer, at whatever width the result is asked for.
8762    fn cast(source: &mut Func, block: Block, opcode: Opcode, from: Value, to: Type) -> Value {
8763        let mut build = Builder::new(source, block);
8764        let args = build.func().push_values(&[from]);
8765        build.value(InstData { args, ..InstData::new(opcode) }, to)
8766    }
8767
8768    #[test]
8769    fn a_cast_between_a_pointer_and_an_integer_as_wide_is_no_instruction_at_all() {
8770        let (mut names, mut source, block, args) = blank(&[Type::PTR]);
8771        let number = cast(&mut source, block, Opcode::PtrToInt, args[0], Type::int(64));
8772        Builder::new(&mut source, block).ret(&[number]);
8773
8774        // `long f(void *p) { return (long)p; }`. An address on this machine is an integer as wide
8775        // as the machine addresses, so the cast changes what the type system calls the value and
8776        // changes nothing about the value, and the register holding it is the one that held it.
8777        assert_eq!(
8778            lower(&mut names, &source),
8779            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_64\n    \
8780             x64.ret_val_64 %0($rax)\n}\n"
8781        );
8782    }
8783
8784    #[test]
8785    fn a_null_pointer_is_a_constant_that_reaches_a_register_before_anything_reads_it() {
8786        let (mut names, mut source, block, _) = blank(&[]);
8787        let mut build = Builder::new(&mut source, block);
8788        let zero = build.iconst(Type::int(64), 0);
8789        let null = cast(&mut source, block, Opcode::IntToPtr, zero, Type::PTR);
8790        Builder::new(&mut source, block).ret(&[null]);
8791
8792        // `void *f(void) { return 0; }`. The cast is nothing, and reading its operand is what
8793        // writes the zero down: a constant is materialized where it is wanted rather than where
8794        // the IR defined it, and without the read there would be no instruction at all.
8795        assert_eq!(
8796            lower(&mut names, &source),
8797            "mfunc @f {\nblock0:\n    %0:gpr = x64.mov_ri_64 0\n    x64.ret_val_64 %0($rax)\n}\n"
8798        );
8799    }
8800
8801    #[test]
8802    fn the_five_linkages_the_ir_has_narrow_to_the_three_an_object_file_can_say() {
8803        let readings = [
8804            (Linkage::External, mir::Binding::Global),
8805            (Linkage::Common, mir::Binding::Global),
8806            (Linkage::Internal, mir::Binding::Local),
8807            (Linkage::Weak, mir::Binding::Weak),
8808            (Linkage::LinkOnce, mir::Binding::Weak),
8809        ];
8810        for (linkage, wanted) in readings {
8811            let (mut names, mut source, block, _) = blank(&[]);
8812            source.linkage = linkage;
8813            Builder::new(&mut source, block).ret(&[]);
8814            let out = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
8815                .expect("a return");
8816            // The narrowing is done here rather than where the object is written, because a
8817            // machine function is all the assembler and the writer are ever handed.
8818            assert_eq!(out.func.binding, wanted, "{linkage:?}");
8819        }
8820    }
8821
8822    /// The visibility makes the same trip and is not narrowed on the way, because ELF says all
8823    /// three of them.
8824    ///
8825    /// Here for the reason the linkage above is here. A machine function is the whole of what the
8826    /// assembler and the object writer are handed, so a fact about the symbol that does not get
8827    /// onto one is a fact that is gone by the time anything could write it down, and the way that
8828    /// shows up is a shared library exporting the wrong set of names with nothing said anywhere.
8829    #[test]
8830    fn the_visibility_survives_the_trip_from_the_ir_to_a_machine_function() {
8831        let readings = [
8832            (Visibility::Default, mir::Visibility::Default),
8833            (Visibility::Hidden, mir::Visibility::Hidden),
8834            (Visibility::Protected, mir::Visibility::Protected),
8835        ];
8836        for (visibility, wanted) in readings {
8837            let (mut names, mut source, block, _) = blank(&[]);
8838            source.visibility = visibility;
8839            Builder::new(&mut source, block).ret(&[]);
8840            let out = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
8841                .expect("a return");
8842            assert_eq!(out.func.visibility, wanted, "{visibility:?}");
8843        }
8844    }
8845
8846    #[test]
8847    fn a_cast_between_a_pointer_and_a_narrower_integer_is_reported() {
8848        let (mut names, mut source, block, args) = blank(&[Type::PTR]);
8849        let number = cast(&mut source, block, Opcode::PtrToInt, args[0], Type::int(32));
8850        Builder::new(&mut source, block).ret(&[number]);
8851
8852        // The front end never writes one: it casts at the address width and truncates or extends
8853        // around it, so both of those are the rules they always were. IR from somewhere else that
8854        // does write one is refused rather than compiled to a move that keeps the high half.
8855        let failed = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
8856            .expect_err("no rule narrows an address");
8857        assert_eq!(failed.to_string(), "no rule lowers a `ptrtoint` producing a `i32`");
8858    }
8859
8860    /// The type this machine has no register for.
8861    fn long_double() -> Type {
8862        Type::float(rucc_ir::Float::F80)
8863    }
8864
8865    #[test]
8866    fn a_double_widened_and_narrowed_again_goes_out_through_the_frame_and_back() {
8867        let f64 = Type::float(rucc_ir::Float::F64);
8868        let (mut names, mut source, block, args) = blank(&[f64]);
8869        let wide = cast(&mut source, block, Opcode::FPExt, args[0], long_double());
8870        let back = cast(&mut source, block, Opcode::FPTrunc, wide, f64);
8871        Builder::new(&mut source, block).ret(&[back]);
8872
8873        // `double f(double d) { long double x = d; return x; }`. The x87 reads memory and nothing
8874        // else, so the value is written to the crossing slot, loaded at the format that widens it
8875        // and put in the slot the eighty bit value lives in. Coming back is the same three the
8876        // other way. Both slots are addressed by a `lea` with nothing in it yet, which is what
8877        // every address in a frame looks like here until `finish` has the numbers.
8878        assert_eq!(
8879            lower(&mut names, &source),
8880            "mfunc @f {\nblock0:\n    \
8881             %0:xmm($xmm0) = x64.arg_val_f64\n    \
8882             %1:gpr = x64.lea_64 [$rsp]\n    \
8883             %2:gpr = x64.lea_64 [$rsp]\n    \
8884             x64.movsd_mr %0, [%1]\n    \
8885             x64.fld_l [%1]\n    \
8886             x64.fstp_t [%2]\n    \
8887             %3:gpr = x64.lea_64 [$rsp]\n    \
8888             %4:gpr = x64.lea_64 [$rsp]\n    \
8889             x64.fld_t [%3]\n    \
8890             x64.fstp_l [%4]\n    \
8891             %5:xmm = x64.movsd_rm [%4]\n    \
8892             x64.ret_val_f64 %5($xmm0)\n}\n"
8893        );
8894    }
8895
8896    #[test]
8897    fn a_long_double_has_sixteen_bytes_of_its_own_and_keeps_them() {
8898        let f64 = Type::float(rucc_ir::Float::F64);
8899        let (mut names, mut source, block, args) = blank(&[f64]);
8900        let wide = cast(&mut source, block, Opcode::FPExt, args[0], long_double());
8901        let once = cast(&mut source, block, Opcode::FPTrunc, wide, f64);
8902        let twice = cast(&mut source, block, Opcode::FPTrunc, wide, f64);
8903        let mut build = Builder::new(&mut source, block);
8904        let sum = build.binary(Opcode::FAdd, once, twice, Flags::default());
8905        build.ret(&[sum]);
8906
8907        let out = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
8908            .expect("every instruction is written");
8909
8910        // Two slots and not four: sixteen bytes for the one eighty bit value, which is what the
8911        // psABI says one takes and is aligned to, and eight for the crossing, which every group
8912        // in the function shares because nothing is ever left in it. The value's slot is its own
8913        // for the whole function, so reading it twice reads the same sixteen bytes.
8914        assert_eq!(
8915            out.stack.locals,
8916            vec![Local { size: 8, align: 8 }, Local { size: 16, align: 16 }]
8917        );
8918    }
8919
8920    #[test]
8921    fn an_integer_becomes_a_long_double_by_being_loaded_as_one() {
8922        let (mut names, mut source, block, args) = blank(&[Type::int(64)]);
8923        let wide = cast(&mut source, block, Opcode::SIToFP, args[0], long_double());
8924        let back =
8925            cast(&mut source, block, Opcode::FPTrunc, wide, Type::float(rucc_ir::Float::F64));
8926        Builder::new(&mut source, block).ret(&[back]);
8927
8928        // `double f(long n) { long double x = n; return x; }`. `fild` is the same push at another
8929        // format, so the conversion is the load and there is no instruction that converts.
8930        let text = lower(&mut names, &source);
8931        assert!(text.contains("x64.mov_mr_64 %0, [%1]"), "{text}");
8932        assert!(text.contains("x64.fild_ll [%1]"), "{text}");
8933    }
8934
8935    #[test]
8936    fn a_long_double_becoming_an_integer_cuts_towards_zero_with_the_control_word() {
8937        let (mut names, mut source, block, args) = blank(&[Type::float(rucc_ir::Float::F64)]);
8938        let wide = cast(&mut source, block, Opcode::FPExt, args[0], long_double());
8939        let whole = cast(&mut source, block, Opcode::FPToSI, wide, Type::int(32));
8940        Builder::new(&mut source, block).ret(&[whole]);
8941
8942        // The one conversion here with no single instruction behind it. C cuts towards zero and
8943        // the unit rounds the way its control word says, so the word is saved, ORed with the two
8944        // bits that mean truncate, loaded, used and put back. Nine instructions for what `fisttp`
8945        // does in one, and `spec/10-backend.md` section 10.8 says why that one is not used.
8946        let text = lower(&mut names, &source);
8947        let group: Vec<&str> = text
8948            .lines()
8949            .map(str::trim)
8950            .filter(|line| line.starts_with("x64.f") || line.contains("_16"))
8951            .collect();
8952        assert_eq!(
8953            group,
8954            [
8955                "x64.fld_l [%1]",
8956                "x64.fstp_t [%2]",
8957                "x64.fnstcw [%5]",
8958                "%6:gpr = x64.mov_rm_16 [%5]",
8959                "%7:gpr(reuse 1) = x64.or_ri_16 %6, 3072",
8960                "x64.mov_mr_16 %7, [%5 + 2]",
8961                "x64.fldcw [%5 + 2]",
8962                "x64.fld_t [%3]",
8963                "x64.fistp_l [%4]",
8964                "x64.fldcw [%5]",
8965            ],
8966            "{text}"
8967        );
8968    }
8969
8970    #[test]
8971    fn a_long_double_is_read_and_written_as_the_bits_it_already_is() {
8972        let (mut names, mut source, block, args) = blank(&[Type::PTR, Type::PTR]);
8973        let mut build = Builder::new(&mut source, block);
8974        let value = build.load(long_double(), args[0], plain(), Flags::default());
8975        build.store(value, args[1], plain(), Flags::default());
8976        build.ret(&[]);
8977
8978        // `void f(long double *a, long double *b) { *b = *a; }`. A copy is a push and a pop at the
8979        // format the value is already in, which neither converts nor looks: a signalling NaN stays
8980        // one and nothing is raised, which is the whole of what makes it a copy.
8981        let text = lower(&mut names, &source);
8982        let group: Vec<&str> =
8983            text.lines().map(str::trim).filter(|line| line.starts_with("x64.f")).collect();
8984        assert_eq!(
8985            group,
8986            ["x64.fld_t [%0]", "x64.fstp_t [%2]", "x64.fld_t [%3]", "x64.fstp_t [%1]"],
8987            "{text}"
8988        );
8989    }
8990
8991    /// Two `long double` values, from two `double` parameters, and the instructions that made
8992    /// them, which every test below this one throws away.
8993    fn two_long_doubles(source: &mut Func, block: Block, args: &[Value]) -> (Value, Value) {
8994        let left = cast(source, block, Opcode::FPExt, args[0], long_double());
8995        let right = cast(source, block, Opcode::FPExt, args[1], long_double());
8996        (left, right)
8997    }
8998
8999    /// The x87 instructions of a function, in order, with everything else dropped.
9000    fn stack_only(text: &str) -> Vec<&str> {
9001        text.lines().map(str::trim).filter(|line| line.contains("x64.f")).collect()
9002    }
9003
9004    /// The two frame slots the last two addresses of a function were taken of, which in a
9005    /// comparison are the two operands in the order they go on the stack.
9006    fn pushed(out: &Lowered) -> Vec<usize> {
9007        let taken: Vec<usize> = out.stack.addresses.iter().map(|&(_, local)| local).collect();
9008        taken[taken.len() - 2..].to_vec()
9009    }
9010
9011    #[test]
9012    fn adding_two_long_doubles_pushes_both_and_leaves_the_answer_in_a_slot() {
9013        let f64 = Type::float(rucc_ir::Float::F64);
9014        let (mut names, mut source, block, args) = blank(&[f64, f64]);
9015        let (left, right) = two_long_doubles(&mut source, block, &args);
9016        let sum =
9017            Builder::new(&mut source, block).binary(Opcode::FAdd, left, right, Flags::default());
9018        let back = cast(&mut source, block, Opcode::FPTrunc, sum, f64);
9019        Builder::new(&mut source, block).ret(&[back]);
9020
9021        // `double f(double a, double b) { return (long double) a + (long double) b; }`. The last
9022        // four lines are the add: both operands pushed, the instruction that names neither of
9023        // them because they are the top two of a stack, and the answer taken off into its slot.
9024        let text = lower(&mut names, &source);
9025        assert_eq!(
9026            stack_only(&text),
9027            [
9028                "x64.fld_l [%2]",
9029                "x64.fstp_t [%3]",
9030                "x64.fld_l [%4]",
9031                "x64.fstp_t [%5]",
9032                "x64.fld_t [%6]",
9033                "x64.fld_t [%7]",
9034                "x64.fadd_p",
9035                "x64.fstp_t [%8]",
9036                "x64.fld_t [%9]",
9037                "x64.fstp_l [%10]",
9038            ],
9039            "{text}"
9040        );
9041    }
9042
9043    #[test]
9044    fn a_subtraction_pushes_the_left_operand_first_and_asks_for_the_att_spelling() {
9045        let f64 = Type::float(rucc_ir::Float::F64);
9046        let (mut names, mut source, block, args) = blank(&[f64, f64]);
9047        let (left, right) = two_long_doubles(&mut source, block, &args);
9048        let less =
9049            Builder::new(&mut source, block).binary(Opcode::FSub, left, right, Flags::default());
9050        let back = cast(&mut source, block, Opcode::FPTrunc, less, f64);
9051        Builder::new(&mut source, block).ret(&[back]);
9052
9053        // The left one goes on first, so it ends up under the right one, and the answer wanted is
9054        // the one below minus the top. In AT&T that is `fsubrp`, since `fsubp` there is `DE E0+i`
9055        // and computes the other one. The `r` says which spelling this is and not which order the
9056        // pushes were in. `crates/rucc/tests/x87.rs` is what says the answer is right, because a
9057        // name is what got this wrong the first time.
9058        let text = lower(&mut names, &source);
9059        assert_eq!(
9060            &stack_only(&text)[4..8],
9061            ["x64.fld_t [%6]", "x64.fld_t [%7]", "x64.fsubr_p", "x64.fstp_t [%8]"],
9062            "{text}"
9063        );
9064    }
9065
9066    #[test]
9067    fn negating_a_long_double_turns_the_sign_over_and_reads_nothing() {
9068        let f64 = Type::float(rucc_ir::Float::F64);
9069        let (mut names, mut source, block, args) = blank(&[f64]);
9070        let wide = cast(&mut source, block, Opcode::FPExt, args[0], long_double());
9071        let flipped = Builder::new(&mut source, block).unary(Opcode::FNeg, wide, long_double());
9072        let back = cast(&mut source, block, Opcode::FPTrunc, flipped, f64);
9073        Builder::new(&mut source, block).ret(&[back]);
9074
9075        // `fchs` and not a subtraction from zero, which would give a different answer at a negative
9076        // zero and would signal at a NaN. It does not read the value as a number at all.
9077        let text = lower(&mut names, &source);
9078        assert_eq!(
9079            &stack_only(&text)[2..5],
9080            ["x64.fld_t [%3]", "x64.fchs", "x64.fstp_t [%4]"],
9081            "{text}"
9082        );
9083    }
9084
9085    #[test]
9086    fn comparing_two_long_doubles_puts_the_left_one_on_top() {
9087        let f64 = Type::float(rucc_ir::Float::F64);
9088        let (mut names, mut source, block, args) = blank(&[f64, f64]);
9089        let (left, right) = two_long_doubles(&mut source, block, &args);
9090        let mut build = Builder::new(&mut source, block);
9091        build.fcmp(FloatPred::Ogt, left, right, Flags::default());
9092        build.ret(&[]);
9093
9094        // `a > b`. `fucomip` asks about the top of the stack against what is under it, so the
9095        // operand the predicate is about has to go on last, which is the other way round from the
9096        // arithmetic above. The pop that clears the loser and the byte that reads the flags are
9097        // both inside the one opcode.
9098        let out = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
9099            .expect("every instruction is written");
9100        let slots = pushed(&out);
9101        assert_eq!(slots, [2, 1], "the right operand goes on first and the left one on top");
9102        let text = mir::print_func(&out.func, &names, &REGS);
9103        assert_eq!(
9104            &stack_only(&text)[4..],
9105            ["x64.fld_t [%6]", "x64.fld_t [%7]", "%8:gpr = x64.fucomip_set_a"],
9106            "{text}"
9107        );
9108    }
9109
9110    #[test]
9111    fn a_comparison_that_the_machine_has_backwards_swaps_the_two_pushes() {
9112        let f64 = Type::float(rucc_ir::Float::F64);
9113        let (mut names, mut source, block, args) = blank(&[f64, f64]);
9114        let (left, right) = two_long_doubles(&mut source, block, &args);
9115        let mut build = Builder::new(&mut source, block);
9116        build.fcmp(FloatPred::Olt, left, right, Flags::default());
9117        build.ret(&[]);
9118
9119        // `a < b` is `b > a` and this machine has the one condition, so the same opcode runs with
9120        // the operands the other way round. The same trade the vector rules make, and it has to
9121        // be the same one: a `long double` comparison that picked a different condition from the
9122        // `double` comparison of the same two numbers would be wrong at exactly the unordered
9123        // cases the two conditions differ on.
9124        //
9125        // Which slot each push names is the whole of the difference from the test above, and the
9126        // text does not show it, since an address in a frame is a `lea` with nothing in it until
9127        // `finish` has the numbers. So the slots are what is read here.
9128        let out = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
9129            .expect("every instruction is written");
9130        let slots = pushed(&out);
9131        assert_eq!(slots, [1, 2], "the left operand goes on first and the right one on top");
9132        let text = mir::print_func(&out.func, &names, &REGS);
9133        assert_eq!(
9134            &stack_only(&text)[4..],
9135            ["x64.fld_t [%6]", "x64.fld_t [%7]", "%8:gpr = x64.fucomip_set_a"],
9136            "{text}"
9137        );
9138    }
9139
9140    #[test]
9141    fn an_ordered_equal_needs_a_second_byte_to_put_the_two_conditions_together() {
9142        let f64 = Type::float(rucc_ir::Float::F64);
9143        let (mut names, mut source, block, args) = blank(&[f64, f64]);
9144        let (left, right) = two_long_doubles(&mut source, block, &args);
9145        let mut build = Builder::new(&mut source, block);
9146        build.fcmp(FloatPred::Oeq, left, right, Flags::default());
9147        build.ret(&[]);
9148
9149        // Equal and ordered are two conditions and the flags carry both, so the opcode writes a
9150        // second register as well as the one the value is in and ANDs them together. Said here by
9151        // handing it a spare, since an instruction that wrote a register nothing knew about would
9152        // be an instruction the allocator could put a live value in the way of.
9153        let text = lower(&mut names, &source);
9154        assert!(text.contains("%8:gpr, %9:gpr = x64.fucomip_set_e_and_np"), "{text}");
9155    }
9156
9157    #[test]
9158    fn a_comparison_that_is_never_asked_is_reported() {
9159        let f64 = Type::float(rucc_ir::Float::F64);
9160        let (mut names, mut source, block, args) = blank(&[f64, f64]);
9161        let (left, right) = two_long_doubles(&mut source, block, &args);
9162        let mut build = Builder::new(&mut source, block);
9163        build.fcmp(FloatPred::False, left, right, Flags::default());
9164        build.ret(&[]);
9165
9166        // Always false is a constant and not a comparison, so there is no condition to pick and
9167        // nothing here folds it into one: an instruction that quietly agreed with it would hide
9168        // that the optimizer left a comparison in that it should have taken out.
9169        let failed = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
9170            .expect_err("no condition is always false");
9171        assert_eq!(failed.to_string(), "no rule lowers a `fcmp` producing a `i1`");
9172    }
9173
9174    #[test]
9175    fn a_long_double_constant_is_the_bits_of_it_put_where_the_value_lives() {
9176        let (mut names, mut source, block, args) = blank(&[Type::PTR]);
9177        let mut build = Builder::new(&mut source, block);
9178        // `1.5L`, which is the leading bit and one more of significand, and an exponent of zero.
9179        let one_and_a_half = build.fconst(long_double(), 0x3fff_c000_0000_0000_0000);
9180        build.store(one_and_a_half, args[0], plain(), Flags::default());
9181        build.ret(&[]);
9182
9183        // No x87 instruction at all. A slot holding one of these is the value, so a constant is
9184        // its ten bytes written where the value lives, and whatever reads it does the `fld`.
9185        let text = lower(&mut names, &source);
9186        assert!(text.contains("x64.mov_ri_64 -4611686018427387904"), "{text}");
9187        assert!(text.contains("x64.mov_ri_16 16383"), "{text}");
9188        assert!(text.contains("x64.mov_mr_16 %3, [%1 + 8]"), "{text}");
9189        // The six bytes above the ten are the padding that makes the type sixteen wide, and they
9190        // are unspecified rather than zero, so nothing writes them.
9191        assert_eq!(text.matches("x64.mov_mr").count(), 2, "{text}");
9192    }
9193
9194    #[test]
9195    fn a_negative_long_double_constant_keeps_the_bit_above_its_exponent() {
9196        let (mut names, mut source, block, args) = blank(&[Type::PTR]);
9197        let mut build = Builder::new(&mut source, block);
9198        let minus = build.fconst(long_double(), 0xbfff_c000_0000_0000_0000);
9199        build.store(minus, args[0], plain(), Flags::default());
9200        build.ret(&[]);
9201
9202        // `-1.5L`. The sign is the top bit of the two byte half, so the immediate that half is put
9203        // in a register with is above the signed range of sixteen bits and has to stay there: read
9204        // as a number it would be negative, and it is not a number, it is two bytes.
9205        let text = lower(&mut names, &source);
9206        assert!(text.contains("x64.mov_ri_16 49151"), "{text}");
9207    }
9208
9209    #[test]
9210    fn a_long_double_crosses_an_edge_as_an_address_and_is_copied_where_it_lands() {
9211        let (mut names, mut source, block, args) = blank(&[Type::float(rucc_ir::Float::F64)]);
9212        let wide = cast(&mut source, block, Opcode::FPExt, args[0], long_double());
9213        let next = source.create_block();
9214        let param = source.append_param(next, long_double());
9215        Builder::new(&mut source, block).jump(next, &[wide]);
9216        Builder::new(&mut source, next).ret(&[param]);
9217
9218        // What the edge carries is the address of the slot the value is already in, which is an
9219        // ordinary register the allocator has an opinion about. The block on the other side copies
9220        // the sixteen bytes into a slot of its own before anything reads them, so a second edge
9221        // handing over a second address would still leave one place for a reader to look.
9222        let text = lower(&mut names, &source);
9223        let second: Vec<&str> = text
9224            .lines()
9225            .skip_while(|line| !line.starts_with("block1"))
9226            .skip(1)
9227            .take(3)
9228            .map(str::trim)
9229            .collect();
9230        assert_eq!(
9231            second,
9232            ["x64.fld_t [%4]", "%5:gpr = x64.lea_64 [$rsp]", "x64.fstp_t [%5]"],
9233            "{text}"
9234        );
9235    }
9236
9237    #[test]
9238    fn more_long_doubles_at_a_block_than_the_stack_is_deep_are_reported() {
9239        let f64 = Type::float(rucc_ir::Float::F64);
9240        let (mut names, mut source, block, args) = blank(&[f64]);
9241        let wide = cast(&mut source, block, Opcode::FPExt, args[0], long_double());
9242        let next = source.create_block();
9243        let params: Vec<Value> =
9244            (0..=X87_DEPTH).map(|_| source.append_param(next, long_double())).collect();
9245        let carried: Vec<Value> = params.iter().map(|_| wide).collect();
9246        Builder::new(&mut source, block).jump(next, &carried);
9247        Builder::new(&mut source, next).ret(&[params[0]]);
9248
9249        // The copies go through the x87 stack so that every one of them is read before any of them
9250        // is written, which is what makes a block that swaps two of these right. Nine of them do
9251        // not fit on the stack, and copying the ninth before or after the rest is the order that
9252        // could be wrong, so it is refused instead.
9253        let failed = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
9254            .expect_err("nine do not fit on the stack");
9255        assert_eq!(
9256            failed.to_string(),
9257            "block1 takes 9 parameters of type `f80` and only 8 can cross an edge at once"
9258        );
9259        assert_eq!(failed.inst(), None);
9260    }
9261}