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, Convention, OperandDesc, PhysReg, RegClass, Role, VaList,
91    Variadic,
92};
93use rucc_target::{aarch64, x86_64};
94
95use crate::abi::{self, Missing, Refused};
96use crate::coverage::Fired;
97use crate::elsewhere::{Elsewhere, Slot};
98use crate::frame::{Layout, Local};
99use crate::select::{Match, Piece, Pointer, Reach, Rule, Selector};
100use crate::term::{MAX_ARGS, PLAIN, Plan, Shown, Term, Terms};
101use crate::varargs;
102
103/// The instruction a template's `jmp` to a name outside it becomes.
104///
105/// The same instruction [`x86_64::FRAME`] names for the end of a tail call, named here as well
106/// because what reaches this one is a template in a function with no prologue and no epilogue,
107/// which is nothing to do with the frame.
108/// See [`x86_64::Step::Away`].
109const AWAY: &str = "jmp_away";
110
111/// How wide an address is on this target, which is the width a cast between a pointer and an
112/// integer has to be at for the cast to be nothing.
113const ADDRESS_BITS: u32 = 64;
114
115/// How much of a register an operand of an `asm` statement fills, which is the width of its type
116/// with two exceptions. A pointer is an address, and a truth value is the byte it is stored in: a
117/// program that writes `sete %0` into a `_Bool` is asking for exactly that byte, which is what tcc's
118/// own test of the width of one checks.
119fn held_bits(ty: Type) -> u32 {
120    if ty.is_ptr() {
121        ADDRESS_BITS
122    } else if ty.bits() == 1 {
123        8
124    } else {
125        ty.bits()
126    }
127}
128
129/// How many bytes a `long double` takes in memory, and what it is aligned to, which are the same
130/// number and are both more than the ten bytes that mean anything.
131///
132/// The psABI's answer rather than a choice here. `sizeof (long double)` is sixteen on this
133/// machine, so an array of them is laid out this way whatever a slot holding one does, and a slot
134/// that agreed with the array is one fewer thing to get wrong.
135const X87_BYTES: u32 = 16;
136
137/// How many values the x87 stack holds at once.
138///
139/// Eight, which is the machine's number rather than a choice here, and it matters in one place:
140/// the parameters of a block are copied through the stack so that they all move at once, and a
141/// block with more of them than this has nowhere to put the ninth.
142const X87_DEPTH: usize = 8;
143
144/// How far into the buffer of a `__builtin_setjmp` each of the four words it writes is.
145///
146/// The first three are gcc's, measured against gcc 16.2.0 on x86-64 at `-O0`: the frame pointer,
147/// the address control comes back to, and the stack pointer, in that order. The fourth is this
148/// compiler's own. gcc has no word for the answer because it writes a second block that sets the
149/// answer to one and is arrived at from the restore, and this writes the answer through memory
150/// instead, for the reason [`Lowering::saves_place`] gives.
151///
152/// None of the four is an interface. The buffer is the program's memory and its five words are
153/// the front end's promise about how much of it there is, but nothing except the matching restore
154/// ever reads a word of it, and a buffer written by one compiler was never going to be one another
155/// compiler could come back through.
156const JUMP_FRAME: i32 = 0;
157
158/// Where the address control comes back to is. See [`JUMP_FRAME`].
159const JUMP_PC: i32 = 8;
160
161/// Where the stack pointer is. See [`JUMP_FRAME`].
162const JUMP_STACK: i32 = 16;
163
164/// Where the address of the word the answer arrives in is. See [`JUMP_FRAME`].
165const JUMP_ANSWER: i32 = 24;
166
167/// How many bytes the word a `__builtin_setjmp` answers with takes in the frame, and what it is
168/// aligned to, which are the same number because it is one machine word.
169const JUMP_WORD: u32 = 8;
170
171/// How many registers the restore needs to hold things in while it puts the frame back.
172///
173/// Four, and every one of them is a register nothing else in the function may be in, which is why
174/// they are counted here rather than asked for one at a time. See [`Lowering::comes_back`].
175const JUMP_REGS: usize = 4;
176
177/// How many bytes the block `__builtin_apply_args` answers takes, which is a word for where the
178/// arguments in memory are, a word of nothing and then the register save area of a variadic
179/// function. See [`Lowering::save_arguments`].
180const APPLY_ARGS: u32 = 192;
181
182/// How far into that block the registers start, which is how far the save area has moved up.
183const APPLY_REGS: u32 = 16;
184
185/// How many bytes the block `__builtin_apply` answers takes, which is two words and two vectors.
186const APPLY_BACK: u32 = 48;
187
188/// How many bytes a value passes through on its way between a register and the x87 stack.
189///
190/// Eight, because the widest thing that crosses is a `double` or a sixty four bit integer, and
191/// nothing crosses at eighty bits: a value that wide is already in the frame and the stack reaches
192/// it where it is.
193const X87_CROSSING: u32 = 8;
194
195/// Where the rounding field of the x87 control word is and what it has to be set to for the unit
196/// to cut towards zero, which is the one rounding C asks for that the unit does not do by default.
197///
198/// Both bits on is truncate. The field is ORed into the word that was already there rather than
199/// written over it, so the precision control and the exception masks somebody else set stay set.
200const X87_TRUNCATE: i64 = 0x0c00;
201
202/// Whether a type is the one this machine has no register for.
203///
204/// Only the eighty bit float is, and that is a fact about x86-64 rather than about floats: every
205/// other scalar the front end produces is in a general purpose register or a vector one, and this
206/// one is on the x87 stack while it is being worked on and in memory the rest of the time. So it
207/// has no place in [`Lowering::class_of`] and no name in [`crate::term`], and every instruction
208/// that touches one is written out by hand in this file.
209fn on_x87(ty: Type) -> bool {
210    ty.is_scalar() && ty.is_float() && ty.bits() == 80
211}
212
213/// Where one operand of an assembly statement is, on each side of the assembly.
214///
215/// Two registers rather than one, because an operand written `+` is a value that arrives and a
216/// value that leaves and those are two values. The machine IR has one definition per register by
217/// construction, so an instruction of the template that reads the operand and writes it has to name
218/// a different register in each place, and what makes the two one register in the end is the
219/// [`Constraint::Reuse`] the instruction's description carries: the allocator reads it, gives both
220/// the same physical register, and copies the incoming value somewhere first when something else is
221/// still using it.
222///
223/// Most operands have one of the two. An input has only a place it is read from and an output
224/// written `=` has only a place it is written to, and asking either of them for the other is an
225/// operand read where the opcode writes or written where it reads, which [`Lowering::placed`]
226/// refuses.
227#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
228struct Place {
229    /// The register the value arrives in, for an operand something reads.
230    read: Option<mir::Reg>,
231    /// The register the value leaves in, for an operand something writes.
232    write: Option<mir::Reg>,
233}
234
235/// Whether that operand of the statement is one the assembly may read, and so where a read of it
236/// gets its value from.
237///
238/// [`bound`] asks this question of an operand a constraint letter named and this asks it of one the
239/// template numbered, which is the same question twice because a two-address instruction reaches
240/// its first source both ways. `mulq %3` reaches `rax` by the letter on the output and libgmp says
241/// what is in it with `"%0"` on an input. `addq %5,%q1` reaches its first source by numbering the
242/// output, and libgmp says what is in it with `"0"` on an input in the same way.
243///
244/// So an output written `=` has no value of its own and is still readable when an input is tied to
245/// it, and the value the read wants is that input's. An output written `+` carries its own value
246/// and answers with that. An output nothing is tied to answers `None`, which is a program that told
247/// the compiler the assembly only writes the operand while the instruction reads it before it
248/// writes it, and is refused where it is asked.
249fn read_as(list: &[AsmOperand<'_>], index: usize) -> Option<Value> {
250    let operand = list.get(index)?;
251    if operand.value.is_some() {
252        return operand.value;
253    }
254    operand.result?;
255    list.iter().find(|entry| entry.tied == Some(index)).and_then(|entry| entry.value)
256}
257
258/// Which of an assembly statement's operands is in that register, for an instruction that reaches
259/// the register without its text saying so.
260///
261/// The constraint is what says so, and it is the only thing in such a statement that could:
262/// `"=a"` is an output in `rax`, `"c"` is an input in `rcx`, an operand that is a local register
263/// variable is in the register its declaration named, and a register nothing names is a register
264/// nobody has said anything about. So a write looks among the outputs and a read among the inputs,
265/// and an output written `+` answers for either, since it is read before it is written. See
266/// [`pinned`], which is the one question asked of both ways of saying it.
267///
268/// The other way a read of such a register is said is a matching constraint. `"=a"` on an output
269/// and `"0"` on an input is the program saying that one register holds the input on the way in and
270/// the output on the way out, and it is how a statement fills a register the instruction reads and
271/// writes without writing the register down twice. The letter is on the output, which has no value
272/// to read, and the value is on the input, which has no letter, and the answer is the output: its
273/// place is read out of the register the input arrived in, and in a template with a loop in it the
274/// place moves on to wherever the last write left it, which is what a read on the next time round
275/// wants. tcc steps a pointer along a string with `lodsb` and `"=&S"` tied to `"0"`, and a read of
276/// the input would start the string again every time round.
277///
278/// And a read of a register an output alone is in is a read of that output, the same as a read of
279/// an output the template numbered. tcc copies a string with `lodsb` and `stosb` and `"=&a"` on an
280/// output nothing is tied to, and what `stosb` stores is what `lodsb` loaded one line up, which is
281/// the output as the template left it rather than anything the statement handed in.
282///
283/// `None` is a register the instruction uses and the statement put nothing in, which is the usual
284/// answer rather than an unusual one. `cpuid` writes four registers and a program that wanted one
285/// of them names one. See [`Lowering::spare`], which is where that one goes.
286fn bound(list: &[AsmOperand<'_>], reg: PhysReg, role: Role) -> Option<usize> {
287    let output =
288        list.iter().position(|operand| operand.result.is_some() && pinned(operand) == Some(reg));
289    if role.is_def() {
290        return output;
291    }
292    // The output first when something is in it on the way in, which is what `+` and a matching
293    // constraint both say, since its place is where a write earlier in the template left it and
294    // the read wants that. See [`read_as`] for what it holds before anything wrote it.
295    let arrives = |at: usize| read_as(list, at).is_some();
296    if let Some(at) = output.filter(|&at| arrives(at)) {
297        return Some(at);
298    }
299    let named = list.iter().position(|operand| {
300        operand.result.is_none() && operand.value.is_some() && pinned(operand) == Some(reg)
301    });
302    named.or(output)
303}
304
305/// The register one of an assembly statement's operands is in, whichever of the two ways said it.
306///
307/// A constraint letter is one way and is the only way a program can say one of the six registers
308/// that have a letter. A local register variable is the other, and it is the only way to say any
309/// of the rest: there is no letter for `r12`, which is the whole reason the extension exists, so
310/// the declaration says it and the front end wrote the name into the constraint. The name is read
311/// against this machine's table here, the same place the letter is read against it, and a name the
312/// machine has not got answers nothing, which leaves the operand where an operand nobody placed
313/// goes.
314///
315/// The sigil gcc allows in front of a name is taken off here, because what a name is written with
316/// is syntax and which register it means is this question.
317fn pinned(operand: &AsmOperand<'_>) -> Option<PhysReg> {
318    match operand.named {
319        Some(name) => {
320            let (reg, _) = x86_64::gpr_named(name.strip_prefix('%').unwrap_or(name))?;
321            Some(reg)
322        }
323        None => operand.fixed.and_then(x86_64::gpr_letter),
324    }
325}
326
327/// Whether a constraint says nothing but what it says on every machine.
328///
329/// [`AsmOperands::read`] gives the x86 meaning to every letter it knows, and most of the letters
330/// mean something else on AArch64: `Q` is an address in one register there rather than one of four
331/// registers, and `a` to `d` name nothing. So an AArch64 statement is taken only with the letters
332/// the two agree on, which are a register, a constant, memory, the immediate ranges and a matching
333/// number, and anything else is refused rather than read as x86. `w` and `Q` are the exceptions.
334/// `w` is a register on both, and which file it is in is decided by the caller with
335/// [`vector_letter`]. `Q` is read as `m` by the caller before the list is read. A
336/// register the front end named in braces is read against AArch64's own names, so what is inside
337/// them is not a letter.
338fn shared_letters(constraint: &str) -> bool {
339    let mut inside = false;
340    constraint.chars().all(|c| match c {
341        '{' => {
342            inside = true;
343            true
344        }
345        '}' => {
346            inside = false;
347            true
348        }
349        _ if inside => true,
350        _ => matches!(
351            c,
352            '=' | '+' | '&' | '%' | 'r' | 'w' | 'Q' | 'm' | 'o' | 'V' | 'g' | 'X' | 'i' | 'n'
353                | 'p' | 'I'..='N' | '0'..='9'
354        ),
355    })
356}
357
358/// A constraint list with every letter outside braces put through `swap`, and what is inside them,
359/// which is a register's name rather than letters, left alone.
360fn letters_outside(constraints: &str, swap: impl Fn(char) -> char) -> String {
361    let mut inside = false;
362    constraints
363        .chars()
364        .map(|c| {
365            match c {
366                '{' => inside = true,
367                '}' => inside = false,
368                _ if !inside => return swap(c),
369                _ => {}
370            }
371            c
372        })
373        .collect()
374}
375
376/// Whether an AArch64 constraint asks for a floating point or vector register, which is what `w`
377/// means there. A register named in braces is not a letter, so a `w` inside one is not read.
378fn vector_letter(constraint: &str) -> bool {
379    let mut inside = false;
380    constraint.chars().any(|c| {
381        match c {
382            '{' => inside = true,
383            '}' => inside = false,
384            _ => {}
385        }
386        !inside && c == 'w'
387    })
388}
389
390/// The x86-64 vector register one entry of a clobber list names, spelled `xmm0` or `ymm0` with or
391/// without the sigil, or nothing for any other entry. Only the sixteen there are without AVX-512,
392/// so `zmm0` and `xmm16` are still refused as names this has no register for.
393fn vector_named(entry: &str) -> Option<PhysReg> {
394    let entry = entry.trim().trim_matches('"');
395    let entry = entry.strip_prefix('%').unwrap_or(entry);
396    let number = entry.strip_prefix("xmm").or_else(|| entry.strip_prefix("ymm"))?;
397    if number.len() > 1 && number.starts_with('0') {
398        return None;
399    }
400    let number: u8 = number.parse().ok()?;
401    (number < 16).then(|| x86_64::xmm(number))
402}
403
404/// Whether a line of a template names, by number, an operand `wanted` says yes to.
405///
406/// `%%` is a percent sign rather than an operand, and a modifier letter may stand between the sign
407/// and the number.
408fn names_one(line: &str, wanted: impl Fn(usize) -> bool) -> bool {
409    let mut rest = line;
410    while let Some(at) = rest.find('%') {
411        let after = &rest[at + 1..];
412        if let Some(escaped) = after.strip_prefix('%') {
413            rest = escaped;
414            continue;
415        }
416        let after = after.strip_prefix(|c: char| c.is_ascii_alphabetic()).unwrap_or(after);
417        let digits = after.len() - after.trim_start_matches(|c: char| c.is_ascii_digit()).len();
418        if after[..digits].parse().is_ok_and(&wanted) {
419            return true;
420        }
421        rest = &after[digits..];
422    }
423    false
424}
425
426/// Why a function could not be lowered.
427///
428/// One reason and then nothing. A function with no rule for something in it is a function this
429/// cannot finish, and the second thing it could not lower is not news.
430#[derive(Debug, Clone, PartialEq, Eq)]
431pub enum Unsupported {
432    /// An instruction no rule fires on.
433    Inst {
434        /// The instruction that stopped it.
435        inst: Inst,
436        /// What the rule file would call it, or nothing if the rule language has no name for it
437        /// at all, which is what an instruction at a width nothing is written about looks like.
438        term: Option<&'static str>,
439        /// The opcode, which is what gets named when the rule language has no word for it.
440        ///
441        /// An opcode the rule language has no word for is exactly the opcode no rule lowers, so
442        /// without this the message would be empty in every case where somebody needs it.
443        opcode: Opcode,
444        /// What it produces, or nothing for an instruction that is only an effect.
445        ty: Option<Type>,
446    },
447    /// A parameter that does not arrive somewhere this can bring it in from.
448    ///
449    /// Not an instruction, which is why it is a separate arm: it is a fact about the signature
450    /// and there is nothing in the body of the function to point at.
451    Argument {
452        /// Its position in the signature.
453        index: usize,
454        /// What is wrong with where it arrives.
455        missing: Missing,
456    },
457    /// A call that passes or gives back a value this cannot put where the convention wants it.
458    Call {
459        /// The call.
460        inst: Inst,
461        /// Which value, and what is wrong with where it travels.
462        refused: Refused,
463    },
464    /// A `return` this cannot put where the convention wants it.
465    ///
466    /// A separate arm from [`Unsupported::Inst`] because it is not an instruction no rule fires
467    /// on. A return of more than one value is built from the convention rather than matched, the
468    /// same way a call is, so what goes wrong with one is what goes wrong with a call and not the
469    /// absence of a rule.
470    Returned {
471        /// The `return`.
472        inst: Inst,
473        /// What is wrong with where one of the values travels.
474        missing: Missing,
475    },
476    /// A stack slot the frame cannot give the bytes it asked for.
477    ///
478    /// Not an instruction no rule covers. An `alloca` is built here rather than matched, so what
479    /// goes wrong with one is what the frame can and cannot hold rather than what the rules spell.
480    Dynamic {
481        /// The `alloca`.
482        inst: Inst,
483        /// What the frame could not do about it.
484        growing: Growing,
485    },
486    /// More parameters of a type that travels on the x87 stack than the stack is deep.
487    ///
488    /// Not an instruction either, for the reason a function's parameter is not one: it is a fact
489    /// about the block and there is nothing in the block to point at. What crosses an edge for one
490    /// of these is the address of where the value is, and the block copies the bytes into a slot
491    /// of its own, all of them through the stack at once so that a block carrying two of them
492    /// swapped is copied in an order that is right. Eight is as many as the stack holds, and a
493    /// ninth would have to be copied before or after the rest, which is the order that could be
494    /// wrong.
495    Phi {
496        /// Which block it arrives at.
497        block: Block,
498        /// How many of them arrive there, which is the whole of what is wrong.
499        count: usize,
500        /// What they are.
501        ty: Type,
502    },
503    /// An `asm` statement this cannot build.
504    ///
505    /// Not an instruction no rule fires on, for the reason a call is not one: what it stands for is
506    /// whatever its template says, and no pattern over terms can read a string.
507    Assembly {
508        /// The `inline_asm`.
509        inst: Inst,
510        /// What about it is not built here yet.
511        refused: Written,
512    },
513    /// A `register long x asm ("...")` naming something this machine has not got.
514    ///
515    /// Not an instruction no rule fires on. There is a rule's worth of instruction here and what
516    /// is wrong is the string beside it, which is a name rather than a term, so the message says
517    /// the name. Which names a machine has is the machine's own question and this is where it is
518    /// asked, at the table a clobber list is read against.
519    Register {
520        /// The `register_value`.
521        inst: Inst,
522        /// The name the program wrote, as it wrote it.
523        name: String,
524    },
525    /// A naked function whose frame is not empty.
526    ///
527    /// Not an instruction no rule fires on, and there is nothing in the body to point at: the
528    /// function asked for no prologue and then wanted bytes only a prologue takes. Refused rather
529    /// than given the bytes anyway, because an offset into a frame nothing set up reaches into
530    /// whatever the caller left below its own stack pointer, which is wrong code that assembles.
531    /// See [`crate::frame::Layout::naked`].
532    Naked {
533        /// How many bytes it wanted, which is the whole of what is wrong.
534        bytes: u32,
535    },
536    /// Something the x86-64 lowering writes by hand and nothing has written for this machine yet.
537    ///
538    /// Refused rather than written with the x86 instructions, which is what the walk would do
539    /// otherwise, since these are the places it names them itself.
540    Unported {
541        /// The instruction, or nothing for the one that is about a signature.
542        inst: Option<Inst>,
543        /// Which of them.
544        what: Unported,
545    },
546}
547
548/// What [`Unsupported::Unported`] is about.
549#[derive(Debug, Clone, Copy, PartialEq, Eq)]
550pub enum Unported {
551    /// The thread pointer on Apple's platforms, which keep it somewhere other than Linux does.
552    Thread,
553    /// A call in a convention the platform has no registers for, which the front end never asks
554    /// for since it reads `ms_abi` and `sysv_abi` on x86-64 alone, and is refused rather than
555    /// made in the wrong one if something else ever does.
556    Convention,
557}
558
559impl Unported {
560    /// The whole message, since there is nothing to put in front of it.
561    #[must_use]
562    pub fn why(self) -> &'static str {
563        match self {
564            Unported::Thread => "the thread pointer is not written for this platform yet",
565            Unported::Convention => {
566                "this calls a function of a calling convention this platform does not have"
567            }
568        }
569    }
570}
571
572/// What about an `asm` statement is not built yet.
573#[derive(Debug, Clone, Copy, PartialEq, Eq)]
574pub enum Written {
575    /// A template with instructions in it.
576    Template,
577    /// An `asm goto`, whose labels make the statement a terminator.
578    Goto,
579    /// An operand this cannot put where the constraint says it goes.
580    Operand,
581    /// A clobber list naming something this has no register for.
582    Clobber,
583    /// A `jmp` out of the function in a function that has an epilogue behind it.
584    Away,
585}
586
587impl Written {
588    /// The rest of the sentence that starts with the statement.
589    #[must_use]
590    pub fn why(self) -> &'static str {
591        match self {
592            // The template is the assembler's to read and there is no assembler here yet, so a
593            // template with anything in it is a string nothing can turn into bytes. An empty one is
594            // no instructions, and no instructions is something this can write.
595            Written::Template => "has instructions in its template, which nothing here assembles",
596            Written::Goto => "jumps to a label, which nothing here builds an edge for",
597            Written::Operand => "has an operand this cannot place",
598            Written::Clobber => "says it destroys a register this has no name for",
599            Written::Away => {
600                "jumps out of the function, which only a function that is `naked` may do, since \
601                 anywhere else there is an epilogue behind it to give the frame back"
602            }
603        }
604    }
605}
606
607/// What the frame could not do about a stack slot.
608#[derive(Debug, Clone, Copy, PartialEq, Eq)]
609pub enum Growing {
610    /// An object of a size the number a frame counts bytes in does not reach.
611    Huge,
612    /// A variable length array wanting more alignment than a call leaves the stack pointer with.
613    ///
614    /// Rounding the stack pointer down again after the bytes have been taken would put it
615    /// somewhere no constant reaches the rest of the frame from, so a frame like this needs a
616    /// second base register held for the whole of the function. Nothing here holds one.
617    ///
618    /// [`crate::expand::rounds`] takes the array away before this sees it, by asking for the
619    /// alignment in extra bytes and handing out an address inside them, so what is left of this
620    /// is IR that arrived without going through that pass and the fixed local in
621    /// [`crate::pipeline`] that wants the same thing from the other side.
622    Aligned,
623    /// A variable length array in a function written without a prologue.
624    ///
625    /// A frame that grows is reached from a frame pointer, and establishing one is the first two
626    /// instructions of a prologue that `__attribute__((naked))` asked there be none of. See
627    /// [`crate::frame::Layout::naked`].
628    Naked,
629}
630
631impl Growing {
632    /// The rest of the sentence that starts with the slot.
633    #[must_use]
634    pub fn why(self) -> &'static str {
635        match self {
636            Growing::Huge => "is more bytes than a frame counts",
637            Growing::Aligned => {
638                "wants more alignment than the stack pointer is left on, which needs a base \
639                 register nothing here keeps"
640            }
641            Growing::Naked => {
642                "is in a function that is `naked`, which has no prologue to point a frame pointer \
643                 at it with"
644            }
645        }
646    }
647}
648
649impl Unsupported {
650    /// The instruction it is about, or nothing for the one arm that is about a signature.
651    ///
652    /// What a caller wants this for is the span. The function knows where every instruction in
653    /// it came from, so a caller holding both can point a message at the line somebody wrote
654    /// rather than at the file as a whole, and nothing here has to carry a span of its own.
655    pub fn inst(&self) -> Option<Inst> {
656        match *self {
657            Unsupported::Inst { inst, .. }
658            | Unsupported::Call { inst, .. }
659            | Unsupported::Returned { inst, .. }
660            | Unsupported::Dynamic { inst, .. }
661            | Unsupported::Assembly { inst, .. }
662            | Unsupported::Register { inst, .. } => Some(inst),
663            Unsupported::Unported { inst, .. } => inst,
664            Unsupported::Argument { .. } | Unsupported::Phi { .. } | Unsupported::Naked { .. } => {
665                None
666            }
667        }
668    }
669}
670
671impl fmt::Display for Unsupported {
672    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
673        match *self {
674            Unsupported::Inst { term: Some(term), .. } => write!(f, "no rule lowers `{term}`"),
675            Unsupported::Inst { term: None, opcode, ty: Some(ty), .. } => {
676                write!(f, "no rule lowers a `{opcode}` producing a `{ty}`")
677            }
678            Unsupported::Inst { term: None, opcode, ty: None, .. } => {
679                write!(f, "no rule lowers a `{opcode}`")
680            }
681            Unsupported::Argument { index, missing } => {
682                write!(f, "parameter {index} {}", missing.why())
683            }
684            Unsupported::Call { refused: Refused { argument: Some(index), missing }, .. } => {
685                write!(f, "argument {index} of this call {}", missing.why())
686            }
687            Unsupported::Call { refused: Refused { argument: None, missing }, .. } => {
688                write!(f, "what this call gives back {}", missing.why())
689            }
690            Unsupported::Returned { missing, .. } => {
691                write!(f, "what this function gives back {}", missing.why())
692            }
693            Unsupported::Dynamic { growing, .. } => {
694                write!(f, "this local {}", growing.why())
695            }
696            Unsupported::Phi { block, count, ty } => {
697                let block = block.index();
698                write!(
699                    f,
700                    "block{block} takes {count} parameters of type `{ty}` and only {X87_DEPTH} can cross an edge at once"
701                )
702            }
703            Unsupported::Assembly { refused, .. } => write!(f, "this `asm` {}", refused.why()),
704            Unsupported::Unported { what, .. } => f.write_str(what.why()),
705            Unsupported::Register { ref name, .. } => {
706                write!(
707                    f,
708                    "this object is kept in `{name}`, which is not a register this machine has"
709                )
710            }
711            Unsupported::Naked { bytes } => write!(
712                f,
713                "this function is `naked` and wants {bytes} bytes of frame, which there is no prologue to take"
714            ),
715        }
716    }
717}
718
719impl std::error::Error for Unsupported {}
720
721/// A lowered function, and what the frame needs that the machine IR does not hold.
722#[derive(Debug)]
723pub struct Lowered {
724    /// The function, in machine instructions.
725    pub func: mir::Func,
726    /// What it wants its stack to look like, which is separate from the function so that the two
727    /// can be read and written at the same time.
728    pub stack: Stack,
729    /// Which rules of the table lowered it, which is what `-Zrule-coverage` asks for and what
730    /// `crate::coverage` writes down.
731    pub fired: Fired,
732    /// Which machine IR block each IR block became, indexed by the IR block's own index, and
733    /// nothing for a block the walk never reached.
734    ///
735    /// Here because it is the only place the correspondence exists. Selection makes one block per
736    /// block, in the same order and with the arms in the same order, so anything the IR knows
737    /// about a block can be carried down through this and nothing else, and
738    /// [`crate::weights::carry`] is what does.
739    pub blocks: Vec<Option<mir::Block>>,
740}
741
742/// What a function's stack has to hold, as far as selection is able to say.
743///
744/// All of it is answered here because selection is where a call is built and where an `alloca`
745/// is read, and nothing after it could tell what either of them needed.
746#[derive(Debug, Default)]
747pub struct Stack {
748    /// How many bytes the widest call in the function needs below the stack pointer for the
749    /// arguments it passes there, or `None` for a function that makes no call at all.
750    ///
751    /// `None` is a leaf, which is the function that may use the red zone and the one whose stack
752    /// pointer does not have to be left aligned for anybody.
753    pub calls: Option<u32>,
754    /// The memory the function asked for itself, one entry for every `alloca` in it, in the order
755    /// the walk reached them.
756    pub locals: Vec<Local>,
757    /// Which instruction computes the address of which of those locals.
758    ///
759    /// An address in the frame is a distance from the stack pointer, and there is no frame until
760    /// after allocation, so the instruction is written here with nothing in its displacement and
761    /// [`crate::finish`] writes the number in once [`crate::frame::Frame`] knows it.
762    pub addresses: Vec<(mir::Inst, usize)>,
763    /// Which of those locals is which declaration in the source, for the ones the program declared.
764    ///
765    /// The number is the one the IR function carries and means nothing here. What it is for is the
766    /// debugging information, which has to say where a named local ended up and cannot ask the
767    /// frame directly: the frame knows a local by the order the `alloca` for it was lowered in and
768    /// by nothing else.
769    ///
770    /// Shorter than the list above rather than the same length, because most of what a function
771    /// keeps in its frame is memory an expression wanted somewhere to put.
772    pub declared: Vec<(usize, u32)>,
773    /// Which instruction computes the address of a piece of memory whose size the function works
774    /// out while it runs, which is what a variable length array is.
775    ///
776    /// Waiting on [`crate::finish`] for a different number from the one the addresses above are:
777    /// the bytes were taken off the stack pointer by the instruction in front of this one, so where
778    /// they start is however much of the bottom of the frame belongs to the arguments of a call,
779    /// and that is not known until the frame is.
780    pub dynamic: Vec<mir::Inst>,
781    /// Which instruction takes those bytes off the stack pointer, one for every one of them, in the
782    /// order the walk reached them.
783    ///
784    /// Read by [`crate::finish`] on a command line that asked for the stack to be touched a page at
785    /// a time, which is the one thing that has to find these again: the bytes are in a register by
786    /// then, so the walk down to them is a loop, and a loop is written around an instruction rather
787    /// than in front of a block. Nothing else looks at them, because everything else about a frame
788    /// that grows is answered by the address the instruction below this one computes.
789    pub grown: Vec<mir::Inst>,
790    /// Where the function first moves the stack pointer while it runs, if it does at all.
791    ///
792    /// Two things are read off this. One is whether at all, which is what [`crate::frame::Layout`]
793    /// wants, because a frame that moves its stack pointer has a different shape from one that does
794    /// not and the layout is built before the instructions are looked at again. See `Growing` in
795    /// [`crate::frame`]. The other is where, so that a caller that cannot accept such a frame has
796    /// somewhere to point when it says so.
797    pub grown_at: Option<Inst>,
798    /// Which instruction reads which of the arguments the caller passed on the stack, as how far up
799    /// the caller's argument area it reads.
800    ///
801    /// Waiting on [`crate::finish`] for the same reason the addresses above are, and on one thing
802    /// more: where the caller's argument area is from inside this function depends on whether the
803    /// prologue had to force the stack pointer's alignment, so which register the load reads
804    /// through is not settled here either.
805    pub arguments: Vec<(mir::Inst, u32)>,
806    /// Whether the function asked where its own frame is, which is what `__builtin_frame_address`
807    /// and `__builtin_return_address` both start from.
808    ///
809    /// A function like that keeps a frame pointer whatever the flags say, because the register is
810    /// the answer to the first of them and the start of the walk for every depth above zero. There
811    /// is no other way to reach it: the distance from the stack pointer to the frame is a number
812    /// the layout works out, and what a walk up the chain needs is the link the prologue saved.
813    pub walks_frames: bool,
814    /// Whether the function saved a place for a `__builtin_longjmp` to come back to, which is what
815    /// `__builtin_setjmp` does.
816    ///
817    /// A function like that keeps a frame pointer whatever the flags say as well, and for a reason
818    /// of the same shape: the two registers the restore puts back are the frame pointer and the
819    /// stack pointer, and a frame that did not keep the first of them has nothing in it saying
820    /// where the caller's frame is for the epilogue to find after control has come back.
821    pub saves_place: bool,
822    /// The calls a `tail_call` became that [`crate::tail::jumps`] may turn into a jump, which is
823    /// the ones that passed everything in registers.
824    pub tails: Vec<crate::tail::Tail>,
825    /// How many bytes the prologue takes above the frame record to home the argument registers
826    /// into, which is nothing except in a variadic function on Windows on AArch64.
827    ///
828    /// That convention has no shadow space the caller reserves, so the callee makes its own: the
829    /// first thing its prologue does is take sixty four bytes, which puts `x0` to `x7` directly
830    /// below the arguments the caller left on the stack and makes the whole run one list of words
831    /// a `char *` can walk. See `home` on [`rucc_target::CallRegs`].
832    pub home: u32,
833}
834
835impl Stack {
836    /// The layout given, with the three fields only the lowering knows the answer to filled in.
837    ///
838    /// Everything else in a layout comes from the flags the function is compiled under or from the
839    /// allocation, so this takes one and returns it rather than building one.
840    ///
841    /// A function that saved a place is not a leaf whatever it called. What a leaf buys is the red
842    /// zone, which is the words below the stack pointer nothing else may write, and a function
843    /// control comes back into from a `__builtin_longjmp` has already had something else running
844    /// down there: whatever it called and whatever that called, or a signal handler on the same
845    /// stack. Every one of those has written over the red zone by the time control arrives, so a
846    /// value this function left there would not be there any more.
847    #[must_use]
848    pub fn layout<'a>(&'a self, base: Layout<'a>) -> Layout<'a> {
849        Layout {
850            leaf: self.calls.is_none() && !self.saves_place,
851            outgoing: self.calls.unwrap_or(0),
852            locals: &self.locals,
853            grows: self.grown_at.is_some(),
854            home: self.home,
855            ..base
856        }
857    }
858}
859
860/// The machine IR for that function, for the machine the selector describes.
861///
862/// # Errors
863///
864/// The first instruction no rule fires on, which today is anything at a width the rule set is not
865/// written at, a parameter that does not arrive in a register this can read, or a call that
866/// passes something this cannot put where the convention wants it.
867pub fn func(
868    source: &Func,
869    names: &mut Interner,
870    selector: &'static Selector,
871    conv: &'static CallRegs,
872    elsewhere: &Elsewhere,
873) -> Result<Lowered, Unsupported> {
874    func_for(source, names, selector, conv, elsewhere, true)
875}
876
877/// [`func`], for a build that says whether it writes debugging information. Without it the walk
878/// leaves out which value each declaration holds on the way into each block, since that is read
879/// only for the debugging information.
880///
881/// # Errors
882///
883/// The same as [`func`].
884pub fn func_for(
885    source: &Func,
886    names: &mut Interner,
887    selector: &'static Selector,
888    conv: &'static CallRegs,
889    elsewhere: &Elsewhere,
890    debug: bool,
891) -> Result<Lowered, Unsupported> {
892    Lowering::new(source, names, selector, conv, elsewhere, debug).run()
893}
894
895/// What the matcher settled on for one block, indexed the way the block's instructions are.
896struct Decided {
897    /// What each instruction matched, and nothing for one that matched no rule or was folded
898    /// into a later one.
899    found: Vec<Option<Match<Term>>>,
900    /// How each instruction showed its operands to the matcher, which is what says what it took.
901    plans: Vec<Option<Plan>>,
902    /// The instructions some other instruction took, which are the ones with nothing to write.
903    folded: Vec<Inst>,
904}
905
906/// The instruction in front of an assignment that starts a declaration on a value, and the first
907/// machine instruction after it once the block is filled.
908type Mark = (Option<Inst>, Option<mir::Inst>);
909
910/// One function being lowered.
911struct Lowering<'a> {
912    source: &'a Func,
913    names: &'a mut Interner,
914    out: mir::Func,
915    /// The machine register each IR value is in, once it has one.
916    regs: Vec<Option<mir::Reg>>,
917    /// For a constant that has been written into a register, the block it was written into,
918    /// which is the only block that register is any good in.
919    written: Vec<Option<mir::Block>>,
920    /// How many times each IR value is read, which is what says whether an instruction may be
921    /// folded into the one that reads it.
922    uses: Vec<u32>,
923    /// The block being filled.
924    at: Option<mir::Block>,
925    /// The machine IR block each IR block became.
926    blocks: Vec<Option<mir::Block>>,
927    /// The class an address is in, which is the general purpose one and is not a question: every
928    /// register an addressing mode names holds part of an address, and there is no machine here
929    /// that computes an address anywhere but in this file. Which class a *value* is in is
930    /// [`Lowering::class_of`], and it is a question, because a float is in the other one.
931    gpr: RegClass,
932    /// The machine this selects for.
933    selector: &'static Selector,
934    /// Where the convention this function is compiled for puts things, which is read for the
935    /// arguments and for the calls.
936    conv: &'static CallRegs,
937    /// Which names this function may not work an address out for itself, which is a fact about the
938    /// module and so is worked out before any of this and handed in.
939    elsewhere: &'a Elsewhere,
940    /// Whether the build writes debugging information, which is the one thing that reads which
941    /// value a declaration holds on the way into each block.
942    debug: bool,
943    /// What the function wants its stack to look like, filled in as the walk finds out.
944    stack: Stack,
945    /// What a `va_start` in this function has to write, or nothing for a function that takes no
946    /// arguments its signature does not name.
947    ///
948    /// Worked out once, when the entry block binds the parameters, because every number in it is
949    /// about where those parameters left the walk over the argument registers and there is nowhere
950    /// else that knows.
951    varargs: Option<Varargs>,
952    /// Which of the function's stack objects each eighty bit value lives in, once it has asked
953    /// for one.
954    ///
955    /// One slot per value and it is never given back, which is what makes an eighty bit value
956    /// behave like every other one: it is written once and read wherever it is read, and no two
957    /// of them share a slot the way two of them would share a register. What is in a register is
958    /// the address, and that is worked out again at every use rather than kept, so nothing here
959    /// holds a general purpose register open across a whole function.
960    slots: Vec<Option<usize>>,
961    /// The eight bytes a value passes through between a register and the x87 stack, once
962    /// something has wanted them.
963    ///
964    /// One for the whole function, because every group that uses it is a handful of instructions
965    /// with nothing in between: the bytes are written, read straight back and never looked at
966    /// again, so a second slot would be a second slot holding the same nothing.
967    crossing: Option<usize>,
968    /// The four bytes the control word is saved in and the changed copy written to, once
969    /// something has wanted them.
970    ///
971    /// One for the whole function for the reason above, and four rather than two because it is
972    /// two words: the one the unit had and the one with the rounding field turned to truncate.
973    control: Option<usize>,
974    /// The word a `__builtin_setjmp` in this function answers with, once one has asked for it.
975    ///
976    /// One for the whole function however many saves there are in it, because the word is written
977    /// and read back with nothing in between: the save writes a zero into it and the instruction
978    /// straight after reads it, and the only other thing that ever writes it is a restore arriving
979    /// between those two. Two saves sharing it is two pairs each doing that, and neither can be
980    /// inside the other.
981    answer: Option<usize>,
982    /// The block `__builtin_apply_args` answers the address of, or nothing in a function that holds
983    /// none.
984    ///
985    /// Written once, in the prologue, because what it holds is every argument register as it was
986    /// on the way in, and by the time the walk reaches the call the registers hold whatever the
987    /// function has done since. Every `__builtin_apply_args` in the function answers the same one.
988    applied: Option<usize>,
989    /// Which rules have fired so far.
990    fired: Fired,
991    /// Where each assignment that starts a declaration on a value part of the way through is, by
992    /// the IR block it is in and the instruction in front of it, and which machine instruction
993    /// is the first one after it once the block has been filled. See
994    /// [`rucc_ir::Func::declare_value_from`].
995    marks: HashMap<Block, Vec<Mark>>,
996    /// The frame slot each fixed size `alloca` was given, which a landing pad writes the address
997    /// of again rather than reading the register the rest of the function has it in. See
998    /// [`Self::pad`].
999    frame_slots: HashMap<Value, usize>,
1000    /// The machine call each IR call with an unwind edge became, which [`Self::edges`] pairs with
1001    /// the pad the edge went to. See [`rucc_ir::Opcode::Unwound`].
1002    unwinding: HashMap<Inst, mir::Inst>,
1003}
1004
1005/// What a `va_start` in a variadic function writes into the list it is given.
1006///
1007/// Two shapes, because two conventions describe a list two ways, and [`crate::varargs`] is where
1008/// both are written down. Neither is a set of numbers on its own: where the save area is and where
1009/// the caller's argument area is are distances into a frame that does not exist until after
1010/// allocation, so each is a `lea` [`crate::finish`] fills in.
1011#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1012enum Varargs {
1013    /// The four field list, whose two offsets are settled here and whose two addresses are not.
1014    Fields {
1015        /// Which of the function's stack objects is the register save area.
1016        save: usize,
1017        /// How far up the caller's argument area the first argument the signature does not name is,
1018        /// which is the whole of that area the named ones did not take.
1019        incoming: u32,
1020        /// What `gp_offset` starts at, which is past the general purpose registers the named
1021        /// arguments took.
1022        integers: u32,
1023        /// What `fp_offset` starts at, which is past the vector ones.
1024        floats: u32,
1025    },
1026    /// The AAPCS64 list, whose two offsets count up to zero from the top of each half of the save
1027    /// area. The two tops are addresses in the frame and so is the first field, like the SysV list.
1028    Aapcs {
1029        /// Which of the function's stack objects is the register save area.
1030        save: usize,
1031        /// How far up the caller's argument area the first argument the signature does not name is.
1032        incoming: u32,
1033        /// Where the general purpose half of the save area ends.
1034        integers_end: u32,
1035        /// Where the vector half ends, which is the end of the area.
1036        floats_end: u32,
1037        /// What `__gr_offs` starts at, which is minus the general purpose half the named arguments
1038        /// did not take.
1039        integers: i32,
1040        /// What `__vr_offs` starts at.
1041        floats: i32,
1042    },
1043    /// The list that is a pointer, which is the one address and nothing else.
1044    Pointer {
1045        /// How far up the caller's argument area the first argument the signature does not name is,
1046        /// which on this convention is the word belonging to the position the named ones stopped
1047        /// at.
1048        incoming: u32,
1049    },
1050}
1051
1052/// How far a function's name reaches, narrowed from the linkage the IR gave it.
1053///
1054/// The IR has five and an object file says three, and the two the linker cannot tell apart are
1055/// the two weak ones: which of them a symbol had is a fact the optimizer reads and the linker has
1056/// no way to record. A function is never `Common`, since that is what a tentative definition of an
1057/// object is and there is no tentative definition of a function, and it is written here rather
1058/// than left out so that a linkage added later has to come past this.
1059const fn binding(linkage: Linkage) -> mir::Binding {
1060    match linkage {
1061        Linkage::Internal => mir::Binding::Local,
1062        Linkage::Weak | Linkage::LinkOnce => mir::Binding::Weak,
1063        Linkage::External | Linkage::Common => mir::Binding::Global,
1064    }
1065}
1066
1067/// How far a function's name reaches outside a shared library, carried across unchanged.
1068///
1069/// Nothing is narrowed here the way [`binding`] narrows the linkage, because ELF records all
1070/// three of these and the two enumerations are the same three answers written twice: once in a
1071/// crate that is not allowed to know what an object file is and once in one that is.
1072const fn visibility(visibility: Visibility) -> mir::Visibility {
1073    match visibility {
1074        Visibility::Default => mir::Visibility::Default,
1075        Visibility::Hidden => mir::Visibility::Hidden,
1076        Visibility::Protected => mir::Visibility::Protected,
1077    }
1078}
1079
1080impl<'a> Lowering<'a> {
1081    fn new(
1082        source: &'a Func,
1083        names: &'a mut Interner,
1084        selector: &'static Selector,
1085        conv: &'static CallRegs,
1086        elsewhere: &'a Elsewhere,
1087        debug: bool,
1088    ) -> Self {
1089        let counts = source.counts();
1090        let name = source.name;
1091        let mut uses = vec![0; counts.values];
1092        for block in source.blocks() {
1093            for inst in source.insts(block) {
1094                for &arg in &source[source[inst].args] {
1095                    uses[arg.index()] += 1;
1096                }
1097                for call in source.successors(inst) {
1098                    for &arg in &source[call.args] {
1099                        uses[arg.index()] += 1;
1100                    }
1101                }
1102            }
1103        }
1104        let mut out = mir::Func::new(name);
1105        out.align = source.align;
1106        // Carried rather than worked out here, because where a function was declared is a fact
1107        // about the source and this is a long way past it. What wants it is the line table.
1108        out.declared = source.declared;
1109        out.binding = binding(source.linkage);
1110        out.visibility = visibility(source.visibility);
1111        Self {
1112            source,
1113            names,
1114            out,
1115            regs: vec![None; counts.values],
1116            written: vec![None; counts.values],
1117            blocks: vec![None; counts.blocks],
1118            uses,
1119            at: None,
1120            gpr: selector.gpr,
1121            selector,
1122            conv,
1123            elsewhere,
1124            debug,
1125            stack: Stack::default(),
1126            varargs: None,
1127            slots: vec![None; counts.values],
1128            crossing: None,
1129            control: None,
1130            answer: None,
1131            applied: None,
1132            fired: Fired::new(),
1133            marks: HashMap::new(),
1134            frame_slots: HashMap::new(),
1135            unwinding: HashMap::new(),
1136        }
1137    }
1138
1139    fn run(mut self) -> Result<Lowered, Unsupported> {
1140        for value in self.source.values() {
1141            for start in self.source.value_starts(value) {
1142                let Some((block, after)) = self.source.start_place(start) else { continue };
1143                let marks = self.marks.entry(block).or_default();
1144                if !marks.iter().any(|&(have, _)| have == after) {
1145                    marks.push((after, None));
1146                }
1147            }
1148        }
1149        // Every block before any of them is filled, because a block that jumps forward has to
1150        // name the block it jumps to and a machine IR block is named by a handle rather than by
1151        // the IR block it came from.
1152        for block in self.source.blocks() {
1153            let out = self.out.create_block();
1154            self.blocks[block.index()] = Some(out);
1155        }
1156        for block in self.order() {
1157            self.block(block)?;
1158        }
1159        // And the name each block an image holds the address of was given, which nothing in the
1160        // walk above would ask for: the `lea` a label address is inside the function needs no
1161        // symbol, and the one thing that does is a relocation in another section.
1162        let named: Vec<(Block, Symbol)> = self.source.named_blocks().collect();
1163        let labels: Vec<(mir::Block, Symbol)> =
1164            named.into_iter().map(|(block, name)| (self.out_block(block), name)).collect();
1165        self.out.labels = labels;
1166        self.naming();
1167        Ok(Lowered { func: self.out, stack: self.stack, fired: self.fired, blocks: self.blocks })
1168    }
1169
1170    /// Which register each declaration the front end kept in a value ended up in, as far as this
1171    /// walk can say, which is the other half of what [`Lowering::new_reg`] writes down as it goes.
1172    ///
1173    /// Two halves because there are two ways a value gets a register here. Most of them ask for a
1174    /// fresh one and that is where `new_reg` catches them, and the rest are put in a register
1175    /// something else chose: a parameter arrives in whichever one the convention handed it, a block
1176    /// parameter in whichever one the edge agreed on, and a result of a rule that names its own
1177    /// registers in the one the rule named. None of those goes past the mint, so this is the map at
1178    /// the end read off the other side, and the two together are every value a declaration is
1179    /// behind.
1180    ///
1181    /// The map on its own would not do, which is why `new_reg` writes down what it writes down: the
1182    /// entry for a constant is cleared every time the walk leaves the block that wrote it, so a
1183    /// local a constant holds is in the map for one block of the function and nowhere else.
1184    fn naming(&mut self) {
1185        let mut named = std::mem::take(&mut self.out.named);
1186        for value in self.source.values() {
1187            let Some(reg) = self.regs[value.index()] else { continue };
1188            named.extend(self.source.value_decls(value).map(|decl| (decl, reg)));
1189            // A start in a block a pass took out was never reached above, and it says nothing
1190            // rather than something about another place.
1191            for start in self.source.value_starts(value) {
1192                let Some((block, after)) = self.source.start_place(start) else { continue };
1193                let first = self.marks.get(&block).and_then(|marks| {
1194                    marks.iter().find(|&&(have, _)| have == after).and_then(|&(_, at)| at)
1195                });
1196                if let Some(first) = first {
1197                    self.out.starts.push((start.decl, reg, first));
1198                }
1199            }
1200        }
1201        named.sort_unstable();
1202        named.dedup();
1203        self.out.named = named;
1204        self.out.starts.sort_unstable();
1205        self.out.starts.dedup();
1206        // Which of its values a declaration holds on the way into a block, for the blocks where
1207        // two of them are live at once. A block a pass took out says nothing, and neither does a
1208        // value the map above has lost the register of, since that is not the same as having none.
1209        // Only for a build that writes debugging information, since that is all that reads it,
1210        // and on a function of tens of thousands of blocks it is a walk of all of them for every
1211        // local.
1212        let mut entries = Vec::new();
1213        let held = if self.debug { crate::holding::on_entry(self.source) } else { Vec::new() };
1214        for (decl, block, value) in held {
1215            if let (Some(block), Some(reg)) = (self.blocks[block.index()], self.regs[value.index()])
1216            {
1217                entries.push((decl, block, reg));
1218            }
1219        }
1220        entries.sort_unstable();
1221        entries.dedup();
1222        self.out.entries = entries;
1223    }
1224
1225    /// The order the blocks are filled in, which is not the order they are written in.
1226    ///
1227    /// Reverse postorder, because a value is written in a block that dominates every block that
1228    /// reads it and a block in reverse postorder comes before every block it dominates. The order
1229    /// the blocks are written in does not have that property: a block written early can read a
1230    /// value a block below it writes, and reading a value with no register yet mints one, so the
1231    /// register the definition writes later is not the register the read named. Nothing writes the
1232    /// one the read named, and what comes out is a function that loads a stack slot no store ever
1233    /// reached. It is the order this walk goes in rather than the order the blocks come out in,
1234    /// which is what the loop above fixes, so the machine function is still written the way the IR
1235    /// function was.
1236    ///
1237    /// Blocks the entry does not reach come last, in the order they are written in. Nothing runs
1238    /// them and nothing they name is read by anything that does, but they still have to be filled,
1239    /// because a machine block with no terminator is not one the passes below can read.
1240    fn order(&self) -> Vec<Block> {
1241        let Some(entry) = self.source.entry() else { return self.source.blocks().collect() };
1242        let count = self.blocks.len();
1243        let mut succs: Vec<Vec<Block>> = vec![Vec::new(); count];
1244        for block in self.source.blocks() {
1245            let Some(term) = self.source.terminator(block) else { continue };
1246            succs[block.index()] = self.source.successors(term).map(|call| call.block).collect();
1247        }
1248        // An explicit stack, because the depth of the walk is the number of blocks and a function
1249        // built by a generator has as many of those as it likes.
1250        let mut seen = vec![false; count];
1251        let mut order = Vec::with_capacity(count);
1252        let mut stack = vec![(entry, 0usize)];
1253        seen[entry.index()] = true;
1254        while let Some((block, at)) = stack.pop() {
1255            let Some(&next) = succs[block.index()].get(at) else {
1256                order.push(block);
1257                continue;
1258            };
1259            stack.push((block, at + 1));
1260            if !seen[next.index()] {
1261                seen[next.index()] = true;
1262                stack.push((next, 0));
1263            }
1264        }
1265        order.reverse();
1266        order.extend(self.source.blocks().filter(|block| !seen[block.index()]));
1267        order
1268    }
1269
1270    /// One block: its parameters, then every instruction in it that is not folded into another.
1271    fn block(&mut self, block: Block) -> Result<(), Unsupported> {
1272        let out = self.out_block(block);
1273        self.at = Some(out);
1274        if self.source.entry() == Some(block) {
1275            self.arrive(block, out)?;
1276        } else {
1277            let mut arriving = Vec::new();
1278            for &param in &self.source[block].params {
1279                // A value with no register to arrive in, which the class would not say, since
1280                // `class_of` puts one of these in the general purpose file on purpose and what it
1281                // means by that is that nothing there can hold it. What crosses the edge for one
1282                // of those is the address of where the value already is, so the parameter is a
1283                // pointer here and the bytes it points at are copied below.
1284                let ty = self.source[param].ty;
1285                let reg = self.out.append_param(out, self.class_of(ty));
1286                self.sized(reg, ty);
1287                self.regs[param.index()] = Some(reg);
1288                if on_x87(ty) {
1289                    arriving.push((param, reg));
1290                }
1291            }
1292            self.settle(block, &arriving)?;
1293        }
1294        let kept = self.pad(block)?;
1295
1296        // What each instruction matched, and which instructions were folded into another. The
1297        // decision is made for the whole block before any of it is written, and it is made more
1298        // than once: a value that only some of its readers took has to be put back in a register
1299        // for all of them, and taking it away from those readers changes what they match.
1300        let insts: Vec<Inst> = self.source.insts(block).collect();
1301        let mut refused: HashSet<Value> = HashSet::new();
1302        let mut decided = self.decide(&insts, &refused);
1303        while let Some(value) = self.left_alive(&insts, &decided.plans) {
1304            refused.insert(value);
1305            decided = self.decide(&insts, &refused);
1306        }
1307        let Decided { found, folded, .. } = decided;
1308
1309        // Where each assignment in this block that starts a declaration on a value is, as the
1310        // machine instruction in front of the place its IR instruction left off, or the block
1311        // for one where nothing has been written yet. What comes after it is not known until the
1312        // block is filled, so that is read below.
1313        let wanted: HashSet<Option<Inst>> =
1314            self.marks.get(&block).into_iter().flatten().map(|&(after, _)| after).collect();
1315        let mut reached: Vec<(Option<Inst>, mir::Block, Option<mir::Inst>)> = Vec::new();
1316        for (index, (&inst, matched)) in insts.iter().zip(found).enumerate() {
1317            let before = index.checked_sub(1).map(|index| insts[index]);
1318            if wanted.contains(&before) {
1319                let at = self.at.unwrap_or(out);
1320                reached.push((before, at, self.out.terminator(at)));
1321            }
1322            if folded.contains(&inst) || self.writes_nothing(inst) {
1323                continue;
1324            }
1325            // A call is built from the convention rather than matched, which is why it is the one
1326            // opcode looked at by name here. Through an address it is a different instruction and
1327            // the same convention, so the two arrive at the same place and differ in one line of
1328            // it.
1329            match self.source[inst].opcode {
1330                Opcode::Call | Opcode::CallIndirect => {
1331                    self.called(inst)?;
1332                    continue;
1333                }
1334                // The exception a landing pad was entered with, which the unwinder left in the
1335                // first return register. Built by name for the reason a named register is.
1336                Opcode::Landing => {
1337                    self.landing(inst)?;
1338                    continue;
1339                }
1340                // A call and the return behind it, which is what `crate::tail::mark` made it out
1341                // of, and both are built the way they would have been. What makes it a jump is
1342                // written at the very end, once the epilogue is there to jump from.
1343                Opcode::TailCall => {
1344                    self.tail_called(inst)?;
1345                    continue;
1346                }
1347                // Built from the frame rather than matched, for the same shape of reason a call
1348                // is built from the convention: what a rule replaces a term with is instructions,
1349                // and what an `alloca` needs first is bytes, which the rule language has no way
1350                // to ask for.
1351                Opcode::Alloca => {
1352                    self.reserve(inst)?;
1353                    continue;
1354                }
1355                // Reading the stack pointer and writing it back, which are the two ends of a scope
1356                // holding a variable length array. Built here for the reason an `alloca` is: the
1357                // value is a register the rule language has no way to name, because what it holds
1358                // is not a value the program computed but where the machine's stack had got to.
1359                // The arguments the function was handed, saved in the prologue, and a call made
1360                // out of them. Built here because neither is a value a rule could say anything
1361                // about: the first is a place in the frame and the second is a call, whose
1362                // arguments are a block of registers rather than values.
1363                Opcode::ApplyArgs => {
1364                    self.apply_args(inst)?;
1365                    continue;
1366                }
1367                Opcode::Apply => {
1368                    self.apply(inst)?;
1369                    continue;
1370                }
1371                Opcode::StackSave => {
1372                    self.stack_pointer(inst, false)?;
1373                    continue;
1374                }
1375                Opcode::StackRestore => {
1376                    self.stack_pointer(inst, true)?;
1377                    continue;
1378                }
1379                // The address of a name, built here for the same reason an `alloca` is: what a
1380                // rule replaces a term with is instructions over values, and the operand of this
1381                // one is a symbol, which is a thing the rule language has no way to bind and the
1382                // solver has no way to say anything about. There is nothing in `lea sym(%rip)` a
1383                // proof over bitvectors could discharge, because what makes it the right answer
1384                // is the relocation and what the linker does with it.
1385                Opcode::GlobalAddr => {
1386                    self.address_of(inst)?;
1387                    continue;
1388                }
1389                // The address of a label and the branch that reads one, built here for the same
1390                // reason and for one more. The reason is the same: what the first of them names is
1391                // a block, which is not a value a rule pattern can bind, and there is nothing in
1392                // the distance between two places in one function that a proof over bitvectors
1393                // could discharge. The extra one is that the second is a terminator whose arms are
1394                // not two and not fixed, and a rule says what an instruction reads rather than
1395                // where a block goes.
1396                Opcode::BlockAddr => {
1397                    self.block_address(inst)?;
1398                    continue;
1399                }
1400                Opcode::IndirectBr => {
1401                    self.indirect_branch(inst)?;
1402                    continue;
1403                }
1404                // A `switch` that `crate::switch` found dense enough for a table, which is a load
1405                // out of the table and the same jump. Built here for the reasons the jump above
1406                // is, and because what the load reads is a place in this function.
1407                Opcode::Switch => {
1408                    self.jump_table(inst)?;
1409                    continue;
1410                }
1411                // The pair that saves a place in this function and comes back to it. Built here
1412                // for the reason the address of a label is, and for two more. The reason is the
1413                // same: the first of them writes down where control comes back to, which is a
1414                // place in this function and not a value a rule pattern can bind. The extra ones
1415                // are that each of them is a group of instructions over a buffer the program owns
1416                // rather than one instruction, and that the first of them leaves the block it was
1417                // written in and carries on in a new one, which is a thing no rule can do.
1418                Opcode::SetjmpMarker => {
1419                    self.saves_place(inst)?;
1420                    continue;
1421                }
1422                Opcode::LongjmpMarker => {
1423                    self.comes_back(inst)?;
1424                    continue;
1425                }
1426                // Where this thread's own storage starts, built here for a reason of the same
1427                // shape: what it reads is `%fs`, which is not a register the rule language can
1428                // bind and not one a proof over bitvectors could say anything about, because what
1429                // makes the load the right answer is an agreement between the loader and the C
1430                // library rather than any arithmetic.
1431                Opcode::ThreadPointer => {
1432                    self.thread_pointer(inst)?;
1433                    continue;
1434                }
1435                // Where the stack pointer was on entry, built here because it is an address in
1436                // the caller's argument area, which only the frame knows the distance to.
1437                Opcode::SpEntry => {
1438                    self.sp_entry(inst)?;
1439                    continue;
1440                }
1441                // What a named machine register holds, built here for the reason above written
1442                // about any register rather than about one: which register it is is a string
1443                // beside the instruction, and a rule matches on an opcode and a type and could
1444                // not see it. There is nothing to prove either, since the answer is the register
1445                // and the instruction is the move that reads it.
1446                Opcode::RegisterValue => {
1447                    self.register_value(inst)?;
1448                    continue;
1449                }
1450                // Where a frame is and what it returns to, built here for the same reason and one
1451                // more. The reason is the same: what the walk starts from is the frame pointer,
1452                // which is not a register a rule pattern can bind, and there is nothing in reading
1453                // the link the prologue saved that a proof over bitvectors could discharge. The
1454                // extra one is that how long the walk is comes out of a number beside the
1455                // instruction, so one of these is not one instruction but however many the depth
1456                // says, and a rule replaces a term with a term.
1457                Opcode::FrameAddress | Opcode::ReturnAddress => {
1458                    self.frames(inst)?;
1459                    continue;
1460                }
1461                // Built from the frame for the reason an `alloca` is, and from the convention for
1462                // the reason a call is: three of the four fields it writes are distances that do
1463                // not exist until the frame does, and the fourth is where the walk over the
1464                // argument registers stopped. A function that is not variadic has no such walk to
1465                // report, so it has nothing here and is refused below, which is the right answer
1466                // for a `va_start` in one.
1467                Opcode::VaStart if self.varargs.is_some() => {
1468                    self.va_start(inst)?;
1469                    continue;
1470                }
1471                // A return of more than one value, which is a structure small enough to come
1472                // back in a pair of registers. Built from the convention for the reason a call
1473                // is: which register each half goes in depends on the halves in front of it,
1474                // because the two register files are walked separately, and a pattern over a term
1475                // cannot see them. A return of one value is a term with a name and a rule, and it
1476                // stays one.
1477                //
1478                // A return of none in a function whose answer went through memory is here too,
1479                // and for a different reason: what it gives back is not written in the IR at all.
1480                // The convention says the address the caller handed over comes back, and only the
1481                // signature says this function was handed one.
1482                //
1483                // And a return of one eighty bit value, for a third reason: what a rule would
1484                // write is an instruction leaving the value in a register, and this one is left on
1485                // the x87 stack instead. A rule could not name that stack any more than any other
1486                // rule about this type could.
1487                //
1488                // And a return the convention asks this side to extend, which a rule has no way to
1489                // know about since the signature is what says so and not the value.
1490                Opcode::Return
1491                    if self.source[self.source[inst].args].len() > 1
1492                        || self.sret().is_some()
1493                        || self.gives_back_x87(inst)
1494                        || self.widens_return() =>
1495                {
1496                    let values = self.source[self.source[inst].args].to_vec();
1497                    self.returned(inst, values)?;
1498                    continue;
1499                }
1500                // A cast between a pointer and an integer of the same width, which on this
1501                // machine is every one the front end writes. No instruction at all, so no rule
1502                // could name one.
1503                Opcode::PtrToInt | Opcode::IntToPtr => {
1504                    self.rename(inst)?;
1505                    continue;
1506                }
1507                // A barrier, which is one instruction or none depending on the ordering. Written
1508                // by name because there is nothing about it a rule could be proved against, the
1509                // way there is nothing to prove about the address of a symbol.
1510                Opcode::Fence => {
1511                    self.barrier(inst)?;
1512                    continue;
1513                }
1514                // An ordered load or store that `crate::expand::orderings` left alone, which on a
1515                // machine that is not total store order is every one stronger than relaxed. Written
1516                // by name for the barrier's reason: what it adds to the plain access is an ordering.
1517                Opcode::AtomicLoad | Opcode::AtomicStore if self.on_aarch64() => {
1518                    self.ordered(inst)?;
1519                    continue;
1520                }
1521                // A hint, written by name for the reason a barrier is and one step further: not
1522                // only is there no equality for a proof to discharge, there is nothing about the
1523                // program around it either. Which of the four instructions it is comes out of the
1524                // number the builtin was given, which is beside the instruction rather than in it.
1525                Opcode::Prefetch => {
1526                    self.hint(inst)?;
1527                    continue;
1528                }
1529                // Stopping, written by name for the first half of the barrier's reason: it
1530                // computes nothing, so there is no term for a rule to replace, and what makes it
1531                // right is what the operating system does with the fault rather than anything a
1532                // proof over bitvectors could discharge.
1533                Opcode::Trap => {
1534                    self.trap(inst);
1535                    continue;
1536                }
1537                // A compare and exchange, which is written by name because it produces two values
1538                // and a rule produces one. The replacement of a rule is one term, a term names the
1539                // value an instruction computes, and there is no way in that language to say that
1540                // an instruction leaves an answer in one place and a yes or no in another.
1541                Opcode::Cmpxchg => {
1542                    self.exchange(inst)?;
1543                    continue;
1544                }
1545                // A read modify write, which is written by name for a different reason: it produces
1546                // one value, so a rule could name it, and what it does is not in the head a rule
1547                // matches on. Every one of the thirteen operations is the same opcode at the same
1548                // type and differs only in what is carried beside it, so one pattern would be all
1549                // thirteen patterns. Of the thirteen only the three with an instruction reach here,
1550                // since `crate::retry` turned the rest into loops a long way above this.
1551                Opcode::AtomicRmw => {
1552                    self.modify(inst)?;
1553                    continue;
1554                }
1555                // An `asm` statement, whose lowering is its template and there is no term for a
1556                // string. Written by name for the reason a barrier is, and before the x87 arm
1557                // below so that an `asm` holding a `long double` is refused as the `asm` it is
1558                // rather than as an instruction nothing computes.
1559                Opcode::InlineAsm => {
1560                    // The template is read as x86 assembly, and that reader is the only one there
1561                    // is. AArch64 keeps every template as text, and any other machine's `asm` is
1562                    // refused here rather than read as the wrong language.
1563                    if self.on_aarch64() {
1564                        self.spelled(inst)?;
1565                        continue;
1566                    }
1567                    if !std::ptr::eq(self.selector.shapes, &x86_64::MACHINE) {
1568                        return Err(self.unsupported(inst));
1569                    }
1570                    if self.touches_x87(inst) {
1571                        self.x87_assembly(inst)?;
1572                        continue;
1573                    }
1574                    self.assembly(inst)?;
1575                    continue;
1576                }
1577                // Anything at all with an eighty bit float in it, which is the one arm here
1578                // chosen by a type rather than by an opcode, because what makes these different
1579                // is not what they do but where the value is. A `long double` has no register,
1580                // so it has no name in `crate::term` and no rule could bind one: every one of
1581                // these is a group of instructions over a frame slot, written out below.
1582                //
1583                // Last of the arms, so that a call and a return with one of these in them reach
1584                // the convention first and are refused by it, which is the truer answer: what is
1585                // wrong there is where the value has to travel and not that nothing can compute
1586                // it.
1587                _ if self.touches_x87(inst) => {
1588                    self.x87(inst)?;
1589                    continue;
1590                }
1591                _ => {}
1592            }
1593            let matched = matched.ok_or_else(|| self.unsupported(inst))?;
1594            self.emit(inst, &matched)?;
1595            // After it is built rather than when it matched, so that what is recorded is the rules
1596            // this function was lowered by and not the rules something was tried with.
1597            self.fired.mark(matched.rule);
1598        }
1599        // Whichever block the walk ended in rather than the one it started in. The two are the
1600        // same block for every function that does not save a place for a `__builtin_longjmp`, and
1601        // where they differ it is the last of them that the terminator and the arms belong to.
1602        // See [`Self::saves_place`].
1603        let last = self.at.expect("a block is being filled");
1604        self.edges(block, last)?;
1605        for (value, reg) in kept {
1606            self.regs[value.index()] = reg;
1607        }
1608        // Now that the block is filled, the instruction after each place an assignment was is the
1609        // first one it holds its value at. One with nothing after it, which a block ending in the
1610        // assignment would be, stays unanswered.
1611        if let Some(marks) = self.marks.get_mut(&block) {
1612            for &(before, at, last) in &reached {
1613                let first = match last {
1614                    Some(last) => self.out.next_inst(last),
1615                    None => self.out.insts(at).next(),
1616                };
1617                for mark in marks.iter_mut().filter(|(after, _)| *after == before) {
1618                    mark.1 = first;
1619                }
1620            }
1621        }
1622        Ok(())
1623    }
1624
1625    /// One call, which is built from the convention rather than matched against the table for the
1626    /// same reason the arguments of the function itself are.
1627    ///
1628    /// The arguments are read before the call is built, which is what materializes a constant
1629    /// argument into a register, since no call passes an immediate.
1630    ///
1631    /// A call to a name and a call through an address are both here, and what tells them apart is
1632    /// the opcode rather than whether a callee was recorded, which is the same thing the verifier
1633    /// reads. Through an address the first operand is the address and the arguments are the ones
1634    /// behind it, and everything after that is the same: where each argument goes, where the value
1635    /// comes back and which registers are gone across it are the convention's answers and the
1636    /// convention does not ask what is being called.
1637    fn called(&mut self, inst: Inst) -> Result<u32, Unsupported> {
1638        let data = &self.source[inst];
1639        let Extra::Call(info) = data.extra else { return Err(self.unsupported(inst)) };
1640        let info = self.source[info];
1641        let indirect = data.opcode == Opcode::CallIndirect;
1642
1643        let values: Vec<Value> = self.source[data.args].to_vec();
1644        let callee = if indirect {
1645            let &address = values.first().ok_or_else(|| self.unsupported(inst))?;
1646            abi::Callee::Through(self.reg_of(address)?)
1647        } else {
1648            let symbol = info.callee.ok_or_else(|| self.unsupported(inst))?;
1649            // A function a declaration said is in a DLL is called through the pointer the loader
1650            // fills in, which is what gcc writes at `-O0`: the pointer into a register and a call
1651            // through the register. gcc at `-O2` and clang call through the pointer in memory,
1652            // which is one instruction shorter and the same call.
1653            match self.elsewhere.slot(symbol) {
1654                Some(slot) => {
1655                    let reg = self.out.new_vreg(self.gpr);
1656                    self.through_slot(inst, slot, symbol, reg)?;
1657                    abi::Callee::Through(reg)
1658                }
1659                None => abi::Callee::Named(symbol),
1660            }
1661        };
1662
1663        // What the ABI asks of each argument, read out before any of them is, because reading one
1664        // borrows the function this is a table in. The ones the signature names are the signature's
1665        // answer and the ones behind them are the call's, which is where a structure passed to a
1666        // variadic callee by value says that its bytes travel: there is no parameter to say it on.
1667        let signature = &self.source[info.signature];
1668        let variadic = signature.variadic;
1669        let named: Vec<Abi> = signature.params.iter().map(|param| param.abi).collect();
1670        let beyond: Vec<Abi> = self.source[info.varargs].to_vec();
1671        // Every value that comes back and not only the first. A structure small enough to travel
1672        // in registers comes back in up to two of them, and which register each half is in is the
1673        // convention's answer, which is why the whole list goes to the same place the arguments do
1674        // rather than to a rule.
1675        let returns: Vec<Type> = signature.return_types().collect();
1676
1677        let mut args = Vec::with_capacity(values.len());
1678        for (index, value) in values.into_iter().skip(usize::from(indirect)).enumerate() {
1679            let abi = named.get(index).or_else(|| beyond.get(index - named.len()));
1680            let abi = abi.copied().unwrap_or_default();
1681            let ty = self.source[value].ty;
1682            // What travels for an eighty bit value is its bytes, so what the call is handed is
1683            // where they are rather than a register they are in, and there is no register they
1684            // could be in. Everything else about it is a sixteen byte object passed by value and
1685            // is built by the same code.
1686            let reg =
1687                if abi::on_the_stack(ty) { self.x87_slot(value) } else { self.reg_of(value)? };
1688            args.push(abi::Passing { ty, reg, abi });
1689        }
1690        let block = self.at.expect("a block is being filled");
1691        let what = abi::Calling {
1692            callee,
1693            args: &args,
1694            returns: &returns,
1695            variadic,
1696            named: named.len(),
1697            at: self.source.span(inst),
1698        };
1699        // The callee's convention and not this function's, since the two differ when either was
1700        // written `ms_abi` or `sysv_abi`: where the arguments go, what the callee leaves alone and
1701        // how much room it is owed above the return address are all the callee's to say, and a
1702        // function of one convention calls functions of the other.
1703        let called = self.source[info.signature].convention;
1704        let conv = self
1705            .conv
1706            .under(called)
1707            .ok_or(Unsupported::Unported { inst: Some(inst), what: Unported::Convention })?;
1708        let made = abi::call(&mut self.out, block, &what, conv, self.selector.abi, self.names)
1709            .map_err(|refused| Unsupported::Call { inst, refused })?;
1710        if self.source.unwinds_to_pad(inst) {
1711            let call = self.out.insts(block).last().expect("the call just built");
1712            self.unwinding.insert(inst, call);
1713        }
1714        let calls = &mut self.stack.calls;
1715        *calls = Some(calls.unwrap_or(0).max(made.outgoing));
1716        // An eighty bit value came back on the x87 stack, and the one thing that has to happen
1717        // before anything else touches that stack is taking it off. So the `fstp` goes here, in
1718        // front of everything the block does next, and after it the value is in its slot and is
1719        // read the way every other one is. A complex one is two of them, the real half on top, so
1720        // taking them off in order leaves each in its own slot and the stack empty.
1721        let results: Vec<Value> = self.source[inst].results().collect();
1722        let types: Vec<Type> = results.iter().map(|&result| self.source[result].ty).collect();
1723        if abi::back_on_x87(&types) {
1724            let span = self.source.span(inst);
1725            for result in results {
1726                let into = self.x87_slot(result);
1727                let into = self.through(into);
1728                self.x87_at("fstp_t", span, into);
1729            }
1730            return Ok(made.outgoing);
1731        }
1732        for (result, &reg) in results.into_iter().zip(&made.results) {
1733            self.sized(reg, self.source[result].ty);
1734            self.regs[result.index()] = Some(reg);
1735        }
1736        Ok(made.outgoing)
1737    }
1738
1739    /// One `tail_call`, as the call and a return of what it gave back.
1740    ///
1741    /// The call is written down for [`crate::tail::jumps`] when it can be made after the frame is
1742    /// gone. That is when it put nothing in the argument area, which is the bottom of this frame,
1743    /// and when the answer comes back in registers, since one on the x87 stack is taken off and put
1744    /// back by instructions after the call. A call that is not written down stays a call and a
1745    /// return, which is what the IR said before `crate::tail::mark` read it.
1746    fn tail_called(&mut self, inst: Inst) -> Result<(), Unsupported> {
1747        let outgoing = self.called(inst)?;
1748        let block = self.at.expect("a block is being filled");
1749        let call = self.out.insts(block).last().expect("the call just built");
1750        let values: Vec<Value> = self.source[inst].results().collect();
1751        let x87 = self.x87_values(&values);
1752        self.returned(inst, values)?;
1753        if outgoing == 0 && !x87 && self.sret().is_none() {
1754            let returns = self.out.insts(block).skip_while(|&at| at != call).skip(1).collect();
1755            self.stack.tails.push(crate::tail::Tail { call, returns });
1756        }
1757        Ok(())
1758    }
1759
1760    /// The pointer a function returning through memory was handed, or nothing in a function that
1761    /// was not.
1762    ///
1763    /// It is the first parameter and the signature is what says so, since in the IR it is an
1764    /// ordinary pointer and reads like one everywhere in the body. A function with a signature
1765    /// like that and no entry block has nothing to give back and no body to give it back from.
1766    fn sret(&self) -> Option<Value> {
1767        let first = self.source.signature().params.first()?;
1768        if !matches!(first.abi, Abi::Sret { .. }) {
1769            return None;
1770        }
1771        self.source[self.source.entry()?].params.first().copied()
1772    }
1773
1774    /// One `return` the convention has to write, as the place each value has to be in by the end.
1775    ///
1776    /// One pseudo per value, each a read constrained to a return register, which is what a return
1777    /// of one value already is and is the whole of what either does. The `ret` itself comes from
1778    /// the epilogue for both, long after this, because the frame has to be given back first.
1779    ///
1780    /// The two register files are counted separately, so a structure of a `double` and a `long`
1781    /// leaves the `double` in the first vector register and the `long` in the first integer one
1782    /// rather than in the second of either. That is the same walk `rucc_codegen::abi` makes on
1783    /// the other side of the call, which is what makes the two ends agree.
1784    ///
1785    /// A function whose answer went through memory gives back the address it was handed, in front
1786    /// of nothing else, because a signature that returns that way returns nothing else. That the
1787    /// caller already knows the address is not enough: it is allowed to read the register instead,
1788    /// and a caller that does gets whatever the allocator last left there. In a leaf function that
1789    /// is usually the right answer by accident, and one call in the body is enough to make it a
1790    /// wild pointer, which is why this is written rather than left to luck.
1791    ///
1792    /// Where everything goes is worked out before anything is written, so a return this cannot
1793    /// make leaves no half of one behind.
1794    /// Whether a value this function gives back has to be extended first, which is Apple's arm64
1795    /// asking the callee to fill the 32 bits above a `char` or a `short` by its sign.
1796    fn widens_return(&self) -> bool {
1797        let returns = &self.source.signature().returns;
1798        returns.iter().any(|it| (self.selector.abi.extend)(it.ty, it.abi).is_some())
1799    }
1800
1801    /// Whether what a `return` gives back goes back on the x87 stack, per [`abi::back_on_x87`].
1802    fn gives_back_x87(&self, inst: Inst) -> bool {
1803        self.x87_values(&self.source[self.source[inst].args])
1804    }
1805
1806    /// Whether those values go back on the x87 stack, per [`abi::back_on_x87`].
1807    fn x87_values(&self, values: &[Value]) -> bool {
1808        let types: Vec<Type> = values.iter().map(|&value| self.source[value].ty).collect();
1809        abi::back_on_x87(&types)
1810    }
1811
1812    fn returned(&mut self, inst: Inst, values: Vec<Value>) -> Result<(), Unsupported> {
1813        let (mut ints, mut floats) = (0usize, 0usize);
1814        let mut parts = Vec::with_capacity(values.len() + 1);
1815        // An eighty bit value goes back on the x87 stack, which is where the convention says it is
1816        // and is the one place a value is left rather than put in a register. So the whole of the
1817        // return is an `fld` of its slot, and the stack it leaves the value on is not empty at the
1818        // `ret`, which is the one time in this file that is true and is what the convention asks
1819        // for. What comes after is the epilogue, which gives the frame back and touches nothing in
1820        // the unit. A complex one loads its imaginary half first so that the real half ends up on
1821        // top of it, in `st(0)`, with the imaginary half under it in `st(1)`.
1822        if self.x87_values(&values) && self.sret().is_none() {
1823            let span = self.source.span(inst);
1824            for &value in values.iter().rev() {
1825                let from = self.x87_slot(value);
1826                let from = self.through(from);
1827                self.x87_at("fld_t", span, from);
1828            }
1829            return Ok(());
1830        }
1831        // What the signature says about the bits above a narrow one, which on an ABI that extends
1832        // it is an obligation of this side: the caller reads the whole of the 32 bit register.
1833        let asked: Vec<Abi> = self.source.signature().returns.iter().map(|it| it.abi).collect();
1834        let asked = asked.into_iter().chain(std::iter::repeat(Abi::Plain));
1835        let sret = self.sret().map(|value| (value, Abi::Plain));
1836        for (value, abi) in sret.into_iter().chain(values.into_iter().zip(asked)) {
1837            let ty = self.source[value].ty;
1838            let at = if crate::term::in_vector_file(ty) { &mut floats } else { &mut ints };
1839            // Why it cannot come back, and not only that it cannot. A type that travels nowhere
1840            // says so itself, and a type that travels perfectly well ran out of registers.
1841            let missing = abi::refuses(ty, self.selector.abi).unwrap_or(Missing::NoRoom);
1842            let name =
1843                (self.selector.abi.ret)(ty, *at).ok_or(Unsupported::Returned { inst, missing })?;
1844            *at += 1;
1845            // The register is the target's answer and not one worked out here, the same as it is
1846            // for a return of one value, so that both halves of a pair and every rule that writes
1847            // half of one are reading the same table.
1848            let opcode =
1849                name.strip_prefix(self.selector.prefix()).ok_or_else(|| self.unsupported(inst))?;
1850            let descs = self.selector.operands(opcode).ok_or_else(|| self.unsupported(inst))?;
1851            let [desc] = descs else { return Err(self.unsupported(inst)) };
1852            let widen = (self.selector.abi.extend)(ty, abi).map(|name| self.names.intern(name));
1853            parts.push((self.names.intern(name), self.reg_of(value)?, *desc, widen));
1854        }
1855
1856        let block = self.at.expect("a block is being filled");
1857        let span = self.source.span(inst);
1858        for (opcode, mut reg, desc, widen) in parts {
1859            if let Some(widen) = widen {
1860                let wide = self.out.new_vreg(desc.class);
1861                let build = self.out.build(block, mir::Opcode::new(widen)).at(span);
1862                build.def(wide, desc.class).uses(reg, desc.class).finish();
1863                reg = wide;
1864            }
1865            let operand = mir::Operand {
1866                reg,
1867                class: desc.class,
1868                role: desc.role,
1869                constraint: desc.constraint,
1870            };
1871            self.out.build(block, mir::Opcode::new(opcode)).at(span).operand(operand).finish();
1872        }
1873        Ok(())
1874    }
1875
1876    /// One `alloca`: the bytes it asks for go on the list the frame is laid out from, and the
1877    /// address of them is one instruction.
1878    ///
1879    /// The instruction is a `lea` off the stack pointer, which is the one register that reaches
1880    /// the frame in every function, and its displacement is left at nothing because there is no
1881    /// frame yet. Which instruction is waiting for which local is remembered, and
1882    /// [`crate::finish`] fills the numbers in after [`crate::frame::Frame`] has placed them.
1883    ///
1884    /// There is deliberately no rule for `alloca` and no name for one in [`crate::term`], and
1885    /// that is what stops it being folded into something else. An operand shown as the
1886    /// instruction that computed it is offered to the matcher by its name, so an `alloca` with no
1887    /// name is one no pattern can reach past, and the address it computes is always in a register
1888    /// by the time anything reads it.
1889    fn reserve(&mut self, inst: Inst) -> Result<(), Unsupported> {
1890        let data = &self.source[inst];
1891        // A variable length array carries the size it wants as an operand rather than in the
1892        // instruction, which is the whole of what tells the two apart here.
1893        if let Some(&size) = self.source[data.args].first() {
1894            return self.grow(inst, size);
1895        }
1896        let Extra::Mem(mem) = data.extra else { return Err(self.unsupported(inst)) };
1897        let info = self.source[mem];
1898        let size = u32::try_from(info.size)
1899            .map_err(|_| Unsupported::Dynamic { inst, growing: Growing::Huge })?;
1900        let result = data.first_result.ok_or_else(|| self.unsupported(inst))?;
1901
1902        // At least one, because the frame divides by the alignment and an object with no
1903        // alignment at all is one the front end had nothing to say about rather than one that may
1904        // go anywhere.
1905        let index = self.stack.locals.len();
1906        self.stack.locals.push(Local { size, align: info.align.max(1) });
1907        if let Some(decl) = self.source.mem_decl(mem) {
1908            self.stack.declared.push((index, decl));
1909        }
1910
1911        let block = self.at.expect("a block is being filled");
1912        let reg = self.new_reg(result);
1913        let span = self.source.span(inst);
1914        let lea = self.named(self.selector.frame.lea);
1915        let sp = mir::Operand::read(mir::Reg::physical(self.conv.stack_pointer), self.gpr);
1916        let made =
1917            self.out.build(block, lea).at(span).def(reg, self.gpr).mem(mir::Mem::at(sp)).finish();
1918        self.stack.addresses.push((made, index));
1919        self.frame_slots.insert(result, index);
1920        Ok(())
1921    }
1922
1923    /// The other kind of `alloca`: one whose size the function does not know until it runs, which
1924    /// is what a variable length array is.
1925    ///
1926    /// Nothing about it is a slot the frame laid out, because the frame is laid out once and this
1927    /// happens as often as control reaches the declaration. The bytes come off the stack pointer
1928    /// where the declaration stands, which is two instructions:
1929    ///
1930    /// ```text
1931    ///   sub sp, bytes     the stack pointer moves down over the memory, which is what takes it
1932    ///   lea reg, [sp+n]   where the memory starts, which is above the outgoing argument area
1933    /// ```
1934    ///
1935    /// The displacement is left at nothing for the reason the constant kind leaves its own at
1936    /// nothing, and for a different number: that area belongs to the arguments of whatever this
1937    /// function calls, it stays at the bottom of the frame wherever the bottom has moved to, and
1938    /// how big it is is not known until every call in the function has been seen.
1939    ///
1940    /// The bytes are already a multiple of the stack pointer's alignment by the time they arrive,
1941    /// because [`crate::expand::rounds`] rounded them up in the IR, so nothing here has to mask the
1942    /// stack pointer afterwards and the stack pointer stays somewhere a call can be made from.
1943    ///
1944    /// Two instructions here and not always two in the finished function. On a command line that
1945    /// asked for the stack to be touched a page at a time, the subtraction becomes a loop that
1946    /// walks the same distance a page at a time, which [`crate::finish`] writes. That is why the
1947    /// instruction is written down in [`Stack::grown`] as well as left where it is.
1948    ///
1949    /// An array wanting more alignment than the convention leaves the stack pointer with does not
1950    /// reach here asking for it: [`crate::expand::rounds`] gives it the alignment in extra bytes
1951    /// and turns the array into a `ptr_add` of the offset that lands inside them, so what arrives
1952    /// is a block asking for the convention's alignment like any other. The refusal below is what
1953    /// answers IR that came from somewhere other than that pass, since forcing the alignment here
1954    /// would be a second rounding of a register the frame already rounded, and after it no
1955    /// constant reaches the rest of the frame from anywhere. See `Growing` in [`crate::frame`].
1956    fn grow(&mut self, inst: Inst, size: Value) -> Result<(), Unsupported> {
1957        let data = &self.source[inst];
1958        let Extra::Mem(mem) = data.extra else { return Err(self.unsupported(inst)) };
1959        let info = self.source[mem];
1960        if info.align > self.conv.stack_align {
1961            return Err(Unsupported::Dynamic { inst, growing: Growing::Aligned });
1962        }
1963        let result = data.first_result.ok_or_else(|| self.unsupported(inst))?;
1964        let bytes = self.reg_of(size)?;
1965
1966        let block = self.at.expect("a block is being filled");
1967        let span = self.source.span(inst);
1968        let stack = mir::Reg::physical(self.conv.stack_pointer);
1969        let grow = self.named(self.selector.frame.grow);
1970        let took = self
1971            .out
1972            .build(block, grow)
1973            .at(span)
1974            .operand(mir::Operand::write(stack, self.gpr))
1975            .operand(mir::Operand::read(stack, self.gpr))
1976            .operand(mir::Operand::read(bytes, self.gpr))
1977            .finish();
1978        self.stack.grown.push(took);
1979
1980        let reg = self.new_reg(result);
1981        let lea = self.named(self.selector.frame.lea);
1982        let sp = mir::Operand::read(stack, self.gpr);
1983        let made =
1984            self.out.build(block, lea).at(span).def(reg, self.gpr).mem(mir::Mem::at(sp)).finish();
1985        self.stack.dynamic.push(made);
1986        self.stack.grown_at.get_or_insert(inst);
1987        Ok(())
1988    }
1989
1990    /// Where the stack pointer is, kept so that something later can put it back.
1991    ///
1992    /// One move out of the stack pointer and one move into it, which is the whole of what the two
1993    /// halves are. What makes them worth writing is where the front end puts them: a scope holding
1994    /// a variable length array saves the stack pointer as it opens and puts it back as it closes,
1995    /// so a loop declaring one takes its bytes once round rather than once per iteration, and a
1996    /// jump out of the scope gives the bytes back on the way out.
1997    ///
1998    /// The value travels in an ordinary register the allocator hands out, so it may be spilled like
1999    /// any other, and a spill slot in a frame that grows is reached through the frame pointer,
2000    /// which is exactly the register that still means something after the stack pointer has moved.
2001    fn stack_pointer(&mut self, inst: Inst, into: bool) -> Result<(), Unsupported> {
2002        let data = &self.source[inst];
2003        let block = self.at.expect("a block is being filled");
2004        let span = self.source.span(inst);
2005        let stack = mir::Reg::physical(self.conv.stack_pointer);
2006        let mov =
2007            self.selector.frame.moves(self.gpr).expect("a class the target says how to move").mov;
2008        let mov = self.named(mov);
2009        let (write, read) = if into {
2010            let &saved = self.source[data.args].first().ok_or_else(|| self.unsupported(inst))?;
2011            (stack, self.reg_of(saved)?)
2012        } else {
2013            let result = data.first_result.ok_or_else(|| self.unsupported(inst))?;
2014            (self.new_reg(result), stack)
2015        };
2016        self.out
2017            .build(block, mov)
2018            .at(span)
2019            .operand(mir::Operand::write(write, self.gpr))
2020            .operand(mir::Operand::read(read, self.gpr))
2021            .finish();
2022        // Only the write is a move of the stack pointer, and it is the one that makes the frame a
2023        // growing one. A read of it in a function that never writes it back is a function that
2024        // asked where the stack was and did nothing with the answer.
2025        if into {
2026            self.stack.grown_at.get_or_insert(inst);
2027        }
2028        Ok(())
2029    }
2030
2031    /// Whether an instruction has an eighty bit float anywhere in it.
2032    ///
2033    /// Producing one and reading one are the same question here, because what makes one of these
2034    /// different from every other instruction is not the operation but where the value is. A
2035    /// `long double` is on the x87 stack while it is being worked on and in a frame slot the rest
2036    /// of the time, and neither of those is somewhere the operand of a rule could point.
2037    fn touches_x87(&self, inst: Inst) -> bool {
2038        let data = &self.source[inst];
2039        data.results().any(|value| on_x87(self.source[value].ty))
2040            || self.source[data.args].iter().any(|&arg| on_x87(self.source[arg].ty))
2041    }
2042
2043    /// Everything that happens to an eighty bit float, as the group of instructions it is.
2044    ///
2045    /// The first six move one, and every one of those is a load, a store, or a load and a store at
2046    /// two different formats, because that is the whole of what this machine converts with: the
2047    /// x87 has no instruction that turns one thing on its stack into another, so a widening is
2048    /// `fld` of the narrow format and a narrowing is `fstp` of it.
2049    ///
2050    /// The rest work on one, and they are here rather than in a rule for the same reason the six
2051    /// are. An add is a push, a push, the add and a pop, and what passes between those four is the
2052    /// top of a stack nothing allocates from, so there is no value in the middle of the group for
2053    /// a pattern to bind or a replacement to name. The comparison is the same shape with its last
2054    /// two instructions folded into one opcode, which is where the byte it produces comes from.
2055    ///
2056    /// Every group leaves the stack as empty as it found it, which is what `spec/10-backend.md`
2057    /// section 10.8 asks of one and is why nothing in this file has to track a depth: each push
2058    /// below is answered by a pop a line or two later, so no two groups can ever be looking at
2059    /// the same eight registers.
2060    fn x87(&mut self, inst: Inst) -> Result<(), Unsupported> {
2061        match self.source[inst].opcode {
2062            Opcode::Load => self.x87_load(inst),
2063            Opcode::Store => self.x87_store(inst),
2064            Opcode::FPExt => self.x87_widen(inst),
2065            Opcode::FPTrunc => self.x87_narrow(inst),
2066            Opcode::SIToFP => self.x87_from_signed(inst),
2067            Opcode::FPToSI => self.x87_to_signed(inst),
2068            Opcode::FAdd => self.x87_arith(inst, "fadd_p"),
2069            Opcode::FSub => self.x87_arith(inst, "fsubr_p"),
2070            Opcode::FMul => self.x87_arith(inst, "fmul_p"),
2071            Opcode::FDiv => self.x87_arith(inst, "fdivr_p"),
2072            Opcode::FNeg => self.x87_flip(inst),
2073            Opcode::FCmp => self.x87_compare(inst),
2074            Opcode::FConst => self.x87_const(inst),
2075            _ => Err(self.unsupported(inst)),
2076        }
2077    }
2078
2079    /// The eighty bit parameters of a block, copied out of the addresses an edge handed over and
2080    /// into slots of the block's own.
2081    ///
2082    /// What crosses an edge for a value of this type is an address, because the value is sixteen
2083    /// bytes of the frame and no register holds any of it. The block cannot keep that address: a
2084    /// second edge into the same block hands over a second one, and a read after the block would
2085    /// then be a read of whichever edge was taken rather than of one place. So the block has a
2086    /// slot per parameter and the bytes are copied into it here, which is the move on an edge that
2087    /// every other type gets from the allocator.
2088    ///
2089    /// Every load runs before every store and the stores run backwards, so all of the values are
2090    /// on the x87 stack at once and nothing reads a slot another one has already written. That
2091    /// costs nothing in the ordinary case of one parameter and is what makes the back edge of a
2092    /// loop that swaps two of these work. It is also the reason for the limit: the stack is eight
2093    /// deep, and a block with more of these than that is refused rather than copied in an order
2094    /// that could be wrong.
2095    fn settle(&mut self, block: Block, arriving: &[(Value, mir::Reg)]) -> Result<(), Unsupported> {
2096        let Some(&(first, _)) = arriving.first() else { return Ok(()) };
2097        if arriving.len() > X87_DEPTH {
2098            let ty = self.source[first].ty;
2099            return Err(Unsupported::Phi { block, count: arriving.len(), ty });
2100        }
2101        // A block parameter comes from no instruction, so what this points at is the first thing
2102        // in the block, which is where a reader looking for the copy would look.
2103        let first_inst = self.source.insts(block).next();
2104        let span = first_inst.map_or(Span::DUMMY, |it| self.source.span(it));
2105        for &(_, reg) in arriving {
2106            let from = self.through(reg);
2107            self.x87_at("fld_t", span, from);
2108        }
2109        for &(param, _) in arriving.iter().rev() {
2110            let into = self.x87_slot(param);
2111            let into = self.through(into);
2112            self.x87_at("fstp_t", span, into);
2113        }
2114        Ok(())
2115    }
2116
2117    /// The frame slot an eighty bit value lives in, as its address in a fresh register.
2118    ///
2119    /// The slot is the value's for the whole function and is taken the first time somebody asks.
2120    /// The address is worked out again every time, which is a `lea` per use and is deliberate: one
2121    /// address kept in a register from the definition to the last use would hold a general purpose
2122    /// register open across everything in between, and a function with a handful of these in it
2123    /// would spend its registers on addresses of things rather than on things.
2124    fn x87_slot(&mut self, value: Value) -> mir::Reg {
2125        // An argument of the function has a slot already and it is the caller's. The convention
2126        // puts the bytes in the argument area and hands over where they are, so the address that
2127        // arrived is the answer and no second copy of the value is made. Nothing ever writes to a
2128        // value of this type once it exists, so nothing writes to the caller's copy either. A
2129        // parameter of any other block is not this: what arrived there is an address a predecessor
2130        // chose, [`Lowering::settle`] has already copied the bytes out of it, and the slot those
2131        // bytes landed in is the one below.
2132        let entry = self.source.entry();
2133        if let (Def::Param { block, .. }, Some(reg)) =
2134            (self.source[value].def, self.regs[value.index()])
2135        {
2136            if entry == Some(block) {
2137                return reg;
2138            }
2139        }
2140        let index = match self.slots[value.index()] {
2141            Some(index) => index,
2142            None => {
2143                let index = self.stack.locals.len();
2144                self.stack.locals.push(Local { size: X87_BYTES, align: X87_BYTES });
2145                self.slots[value.index()] = Some(index);
2146                index
2147            }
2148        };
2149        let block = self.at.expect("a block is being filled");
2150        self.frame_address(block, index)
2151    }
2152
2153    /// The bytes a value crosses between a register and the x87 stack through, as their address
2154    /// in a fresh register.
2155    fn x87_crossing(&mut self) -> mir::Reg {
2156        let index = match self.crossing {
2157            Some(index) => index,
2158            None => {
2159                let index = self.stack.locals.len();
2160                self.stack.locals.push(Local { size: X87_CROSSING, align: X87_CROSSING });
2161                self.crossing = Some(index);
2162                index
2163            }
2164        };
2165        let block = self.at.expect("a block is being filled");
2166        self.frame_address(block, index)
2167    }
2168
2169    /// The two control words, as the address of the first of them in a fresh register.
2170    fn x87_control(&mut self) -> mir::Reg {
2171        let index = match self.control {
2172            Some(index) => index,
2173            None => {
2174                let index = self.stack.locals.len();
2175                self.stack.locals.push(Local { size: 4, align: 4 });
2176                self.control = Some(index);
2177                index
2178            }
2179        };
2180        let block = self.at.expect("a block is being filled");
2181        self.frame_address(block, index)
2182    }
2183
2184    /// An address held in a register, as the addressing mode that reaches it.
2185    fn through(&self, reg: mir::Reg) -> mir::Mem {
2186        mir::Mem::at(mir::Operand::read(reg, self.gpr))
2187    }
2188
2189    /// One instruction of a group, which names an address and nothing else.
2190    ///
2191    /// Every x87 instruction that moves a value is one of these. What it does to the stack is in
2192    /// the mnemonic rather than in an operand, so there is no register to write down and no
2193    /// register the allocator gets a say in.
2194    fn x87_at(&mut self, name: &str, span: Span, at: mir::Mem) {
2195        let block = self.at.expect("a block is being filled");
2196        let opcode = self.named(name);
2197        self.out.build(block, opcode).at(span).mem(at).finish();
2198    }
2199
2200    /// The one instruction of a group that reaches the program's own memory.
2201    ///
2202    /// A `long double` moves in two instructions with a frame slot at one end of them, and the
2203    /// other end is the address the program wrote. That end is the access, so it is the one that
2204    /// carries what the program said about it, and the trip through the slot is this compiler's
2205    /// own business the way a spill is. See [`Self::carried`].
2206    fn x87_touching(&mut self, name: &str, inst: Inst, at: mir::Mem) {
2207        let block = self.at.expect("a block is being filled");
2208        let opcode = self.named(name);
2209        let (span, flags) = (self.source.span(inst), self.carried(inst));
2210        self.out.build(block, opcode).at(span).flags(flags).mem(at).finish();
2211    }
2212
2213    /// One instruction of a group that names nothing at all.
2214    ///
2215    /// The arithmetic is these. Both of an add's operands are already on the stack when it runs
2216    /// and so is where the answer goes, and the stack is not somewhere an instruction says, so
2217    /// `faddp` has an argument in the assembler's syntax and nothing here for the argument to come
2218    /// from. What it works on is which two pushes came before it, which is a fact about the order
2219    /// of the group and is why the group is written in one place.
2220    fn x87_only(&mut self, name: &str, span: Span) {
2221        let block = self.at.expect("a block is being filled");
2222        let opcode = self.named(name);
2223        self.out.build(block, opcode).at(span).finish();
2224    }
2225
2226    /// A `load` of a `long double`: onto the stack from where it was, and off it into the slot.
2227    ///
2228    /// Two instructions rather than the two general purpose moves the same sixteen bytes would
2229    /// take, because `fld` and `fstp` at this format neither convert nor look: the value goes on
2230    /// in the format it was already in and comes back off in it, so a signalling NaN stays one
2231    /// and nothing is raised. Which is what makes this a copy at all.
2232    fn x87_load(&mut self, inst: Inst) -> Result<(), Unsupported> {
2233        let (args, result) = self.ends(inst)?;
2234        let &address = args.first().ok_or_else(|| self.unsupported(inst))?;
2235        let span = self.source.span(inst);
2236        let from = self.reg_of(address)?;
2237        let from = self.through(from);
2238        let into = self.x87_slot(result);
2239        let into = self.through(into);
2240        self.x87_touching("fld_t", inst, from);
2241        self.x87_at("fstp_t", span, into);
2242        Ok(())
2243    }
2244
2245    /// A `store` of a `long double`: the same pair the other way round.
2246    fn x87_store(&mut self, inst: Inst) -> Result<(), Unsupported> {
2247        let args = self.source[self.source[inst].args].to_vec();
2248        let [value, address] = args[..] else { return Err(self.unsupported(inst)) };
2249        let span = self.source.span(inst);
2250        let from = self.x87_slot(value);
2251        let from = self.through(from);
2252        let into = self.reg_of(address)?;
2253        let into = self.through(into);
2254        self.x87_at("fld_t", span, from);
2255        self.x87_touching("fstp_t", inst, into);
2256        Ok(())
2257    }
2258
2259    /// A `float`, a `double` or an integer becoming a `long double`.
2260    ///
2261    /// Through memory, because the x87 reads memory and nothing else: the value is in a register
2262    /// the machine has and the unit has no way to be handed one, so it is written to the crossing
2263    /// bytes and loaded back at the format that widens it. Every one of these is exact. Sixty four
2264    /// bits of significand and fifteen of exponent hold every `float`, every `double` and every
2265    /// sixty four bit integer outright, so none of the four can round and none can raise.
2266    fn x87_across(
2267        &mut self,
2268        inst: Inst,
2269        put: &'static str,
2270        class: RegClass,
2271        get: &'static str,
2272    ) -> Result<(), Unsupported> {
2273        let (args, result) = self.ends(inst)?;
2274        let &source = args.first().ok_or_else(|| self.unsupported(inst))?;
2275        let span = self.source.span(inst);
2276        let value = self.reg_of(source)?;
2277        let across = self.x87_crossing();
2278        let across = self.through(across);
2279        let into = self.x87_slot(result);
2280        let into = self.through(into);
2281
2282        let block = self.at.expect("a block is being filled");
2283        let store = self.named(put);
2284        self.out.build(block, store).at(span).uses(value, class).mem(across).finish();
2285        self.x87_at(get, span, across);
2286        self.x87_at("fstp_t", span, into);
2287        Ok(())
2288    }
2289
2290    /// A `long double` becoming a `float`, a `double` or an integer.
2291    ///
2292    /// Through memory for the reason above and in the same three instructions backwards. The two
2293    /// that go to a float round to nearest, which is what the control word says unless somebody
2294    /// has changed it and is what C wants. The two that go to an integer do not, which is why they
2295    /// do not come here.
2296    fn x87_back(
2297        &mut self,
2298        inst: Inst,
2299        put: &'static str,
2300        get: &'static str,
2301        class: RegClass,
2302    ) -> Result<(), Unsupported> {
2303        let (args, result) = self.ends(inst)?;
2304        let &source = args.first().ok_or_else(|| self.unsupported(inst))?;
2305        let span = self.source.span(inst);
2306        let from = self.x87_slot(source);
2307        let from = self.through(from);
2308        let across = self.x87_crossing();
2309        let across = self.through(across);
2310
2311        self.x87_at("fld_t", span, from);
2312        self.x87_at(put, span, across);
2313        let block = self.at.expect("a block is being filled");
2314        let reg = self.new_reg(result);
2315        let load = self.named(get);
2316        self.out.build(block, load).at(span).def(reg, class).mem(across).finish();
2317        Ok(())
2318    }
2319
2320    /// An `fpext` up to a `long double`, which is the only direction this machine has one in.
2321    fn x87_widen(&mut self, inst: Inst) -> Result<(), Unsupported> {
2322        let sse = self.conv.sse_class;
2323        match self.source[self.narrow(inst)?].ty.bits() {
2324            32 => self.x87_across(inst, "movss_mr", sse, "fld_s"),
2325            64 => self.x87_across(inst, "movsd_mr", sse, "fld_l"),
2326            _ => Err(self.unsupported(inst)),
2327        }
2328    }
2329
2330    /// An `fptrunc` down from a `long double`, which is the other direction of the same.
2331    fn x87_narrow(&mut self, inst: Inst) -> Result<(), Unsupported> {
2332        let sse = self.conv.sse_class;
2333        let result = self.source[inst].first_result.ok_or_else(|| self.unsupported(inst))?;
2334        match self.source[result].ty.bits() {
2335            32 => self.x87_back(inst, "fstp_s", "movss_rm", sse),
2336            64 => self.x87_back(inst, "fstp_l", "movsd_rm", sse),
2337            _ => Err(self.unsupported(inst)),
2338        }
2339    }
2340
2341    /// A `sitofp` up to a `long double`.
2342    ///
2343    /// Thirty two bits and sixty four, and nothing narrower, because C widens an integer to `int`
2344    /// before it converts one and the front end writes that widening down. An unsigned integer is
2345    /// not here at all: `fild` reads its operand as signed, so a value above the signed range
2346    /// comes back short by two to the sixty fourth and has to be added back, which is arithmetic
2347    /// rather than a move and waits with the rest of it.
2348    fn x87_from_signed(&mut self, inst: Inst) -> Result<(), Unsupported> {
2349        let gpr = self.gpr;
2350        match self.source[self.narrow(inst)?].ty.bits() {
2351            32 => self.x87_across(inst, "mov_mr_32", gpr, "fild_l"),
2352            64 => self.x87_across(inst, "mov_mr_64", gpr, "fild_ll"),
2353            _ => Err(self.unsupported(inst)),
2354        }
2355    }
2356
2357    /// An `fptosi` down from a `long double`, which is the one conversion here with no single
2358    /// instruction behind it.
2359    ///
2360    /// C cuts towards zero and the unit rounds the way its control word says, so the store that
2361    /// takes the value off the stack is wrapped in the control word being saved, changed and put
2362    /// back. Five instructions around the one that does the work, and three more moving the word
2363    /// through a register, because this machine has no way to OR a constant into memory at this
2364    /// width. The unit has a shorter answer in `fisttp`, and `spec/10-backend.md` section 10.8
2365    /// says why it is not used: it is SSE3, the x86-64 baseline is not, and there is nothing here
2366    /// that can gate an instruction on a feature yet.
2367    fn x87_to_signed(&mut self, inst: Inst) -> Result<(), Unsupported> {
2368        let (args, result) = self.ends(inst)?;
2369        let &source = args.first().ok_or_else(|| self.unsupported(inst))?;
2370        let (put, get) = match self.source[result].ty.bits() {
2371            32 => ("fistp_l", "mov_rm_32"),
2372            64 => ("fistp_ll", "mov_rm_64"),
2373            _ => return Err(self.unsupported(inst)),
2374        };
2375        let span = self.source.span(inst);
2376        let gpr = self.gpr;
2377        let from = self.x87_slot(source);
2378        let from = self.through(from);
2379        let across = self.x87_crossing();
2380        let across = self.through(across);
2381        let control = self.x87_control();
2382        let saved = self.through(control).plus(0);
2383        let cut = self.through(control).plus(2);
2384
2385        // The word the unit has now, into the first of the two slots and into a register, with the
2386        // rounding field turned to truncate on the way to the second.
2387        self.x87_at("fnstcw", span, saved);
2388        let block = self.at.expect("a block is being filled");
2389        let was = self.out.new_vreg(gpr);
2390        let read = self.named("mov_rm_16");
2391        self.out.build(block, read).at(span).def(was, gpr).mem(saved).finish();
2392        let now = self.out.new_vreg(gpr);
2393        let set = self.named("or_ri_16");
2394        // Two address, which is written out here rather than taken from the two shorthands
2395        // because the shorthands leave an operand unconstrained: this machine ORs into the
2396        // register it read, so the two have to be the same one and only the constraint says so.
2397        self.out
2398            .build(block, set)
2399            .at(span)
2400            .operand(mir::Operand::write(now, gpr).with(Constraint::Reuse(1)))
2401            .operand(mir::Operand::read(was, gpr))
2402            .imm(X87_TRUNCATE)
2403            .finish();
2404        let write = self.named("mov_mr_16");
2405        self.out.build(block, write).at(span).uses(now, gpr).mem(cut).finish();
2406
2407        // The conversion itself, under the changed word, and then the word the unit had put back
2408        // before anything else runs.
2409        self.x87_at("fldcw", span, cut);
2410        self.x87_at("fld_t", span, from);
2411        self.x87_at(put, span, across);
2412        self.x87_at("fldcw", span, saved);
2413
2414        let block = self.at.expect("a block is being filled");
2415        let reg = self.new_reg(result);
2416        let load = self.named(get);
2417        self.out.build(block, load).at(span).def(reg, gpr).mem(across).finish();
2418        Ok(())
2419    }
2420
2421    /// A constant of this type, as the bits of it written into its slot.
2422    ///
2423    /// No x87 instruction at all, which is the surprise here. A slot holding an eighty bit value is
2424    /// the value, so a constant is ten bytes put where the value lives, and the unit never has to
2425    /// see it: whatever reads it will `fld` it out of the slot the way it reads any other one.
2426    ///
2427    /// Ten bytes in two goes, because the machine stores eight at a time and there is no store of
2428    /// an immediate to memory, so each half is put in a register first. The six bytes above the ten
2429    /// are left alone, since nothing reads them: they are the padding that makes the type sixteen
2430    /// wide and they are unspecified in the psABI rather than zero.
2431    ///
2432    /// The other way is a constant pool, an `fldt` of a symbol, and a relocation, which is what a
2433    /// compiler with somewhere to put a literal does. This back end has nowhere to put one yet, and
2434    /// four instructions in the frame is what that costs until it does.
2435    fn x87_const(&mut self, inst: Inst) -> Result<(), Unsupported> {
2436        let Extra::Imm(imm) = self.source[inst].extra else { return Err(self.unsupported(inst)) };
2437        let result = self.source[inst].first_result.ok_or_else(|| self.unsupported(inst))?;
2438        let bits = self.source[imm].bits();
2439        let span = self.source.span(inst);
2440        let gpr = self.gpr;
2441        let slot = self.x87_slot(result);
2442        let low = self.through(slot).plus(0);
2443        let high = self.through(slot).plus(8);
2444
2445        let block = self.at.expect("a block is being filled");
2446        for (bytes, at, into) in
2447            [(bits as u64 as i64, low, "64"), (((bits >> 64) & 0xffff) as i64, high, "16")]
2448        {
2449            let held = self.out.new_vreg(gpr);
2450            let put = self.named(&format!("mov_ri_{into}"));
2451            self.out.build(block, put).at(span).def(held, gpr).imm(bytes).finish();
2452            let store = self.named(&format!("mov_mr_{into}"));
2453            self.out.build(block, store).at(span).uses(held, gpr).mem(at).finish();
2454        }
2455        Ok(())
2456    }
2457
2458    /// One arithmetic instruction on two eighty bit values, as the four it takes.
2459    ///
2460    /// The left operand is pushed first and the right one on top of it, so the left ends up
2461    /// underneath and the answer wanted is the one below against the top in that order. Which of
2462    /// the two mnemonics computes that is a question about the spelling rather than about the
2463    /// machine, and the two spellings disagree. Intel's `FSUBP ST(i), ST(0)` is `ST(i) - ST(0)`
2464    /// and is `DE E8+i`, and AT&T's `fsubp` is `DE E0+i`, which is the other subtraction. This
2465    /// compiler writes AT&T and encodes what gas encodes, so what it asks for here is `fsubr_p`
2466    /// and `fdivr_p`, and the `r` is not a reversal of anything the code generator decided.
2467    ///
2468    /// An addition and a multiplication have one form each and do not care, which is why a test
2469    /// that reads the mnemonic back would not have caught this and one that computes a subtraction
2470    /// and checks the answer does.
2471    ///
2472    /// The answer is left where the deeper of the two was and the shallower is gone, which is what
2473    /// the `p` on the mnemonic means, so one push has already been paid back by the time the
2474    /// `fstp` runs and the stack is level again after it.
2475    ///
2476    /// Nothing here is folded and nothing is reused. Two values that are the same value get two
2477    /// pushes of the same slot, and an operand that was just computed is read back out of the slot
2478    /// it was written to rather than left on the stack, which costs a store and a load per
2479    /// instruction in an expression. Keeping a partial result on the stack across the next
2480    /// instruction's operands means knowing how deep the stack is at every point in the block, and
2481    /// that is a different thing from writing a group.
2482    fn x87_arith(&mut self, inst: Inst, with: &'static str) -> Result<(), Unsupported> {
2483        let (args, result) = self.ends(inst)?;
2484        let [left, right] = args[..] else { return Err(self.unsupported(inst)) };
2485        let span = self.source.span(inst);
2486        let left = self.x87_slot(left);
2487        let left = self.through(left);
2488        let right = self.x87_slot(right);
2489        let right = self.through(right);
2490        let into = self.x87_slot(result);
2491        let into = self.through(into);
2492        self.x87_at("fld_t", span, left);
2493        self.x87_at("fld_t", span, right);
2494        self.x87_only(with, span);
2495        self.x87_at("fstp_t", span, into);
2496        Ok(())
2497    }
2498
2499    /// A negation, which is a push, the sign bit turned over and a pop.
2500    ///
2501    /// `fchs` does not read the value as a number, so this is right for a zero, for an infinity
2502    /// and for a NaN, and it raises nothing on any of them. Which is what C asks of a negation and
2503    /// is not what subtracting from zero would give: `0.0L - x` is a different answer at a
2504    /// negative zero and a signalling one at a NaN.
2505    fn x87_flip(&mut self, inst: Inst) -> Result<(), Unsupported> {
2506        let (args, result) = self.ends(inst)?;
2507        let &source = args.first().ok_or_else(|| self.unsupported(inst))?;
2508        let span = self.source.span(inst);
2509        let from = self.x87_slot(source);
2510        let from = self.through(from);
2511        let into = self.x87_slot(result);
2512        let into = self.through(into);
2513        self.x87_at("fld_t", span, from);
2514        self.x87_only("fchs", span);
2515        self.x87_at("fstp_t", span, into);
2516        Ok(())
2517    }
2518
2519    /// A comparison of two eighty bit values, as the two pushes and the one opcode that reads them.
2520    ///
2521    /// The right operand is pushed first and the left one on top of it, which is the other way
2522    /// round from the arithmetic and is because `fucomip` asks about the top against what is under
2523    /// it: the comparison this machine can do is the top's, so the value the predicate is about
2524    /// has to be the top. The pop that gets the loser off the stack and the byte that reads the
2525    /// flags are both inside the opcode, since what passes between those and the comparison is the
2526    /// flags and the flags are not something anything here can name.
2527    ///
2528    /// Which of the ten opcodes, and which way round, is the same table the vector comparisons
2529    /// match against in `rules/x86-64.rules`, and it has to stay the same table: a predicate that
2530    /// picked a different condition here than there would be a `long double` comparison that
2531    /// disagreed with the `double` comparison of the same two numbers, which is the one thing a
2532    /// wider format is not allowed to do.
2533    ///
2534    /// The always false and the always true are refused rather than folded into a constant,
2535    /// because a comparison this machine never has to do is one the optimizer should have removed
2536    /// and an instruction here that quietly agreed with it would hide that it did not.
2537    fn x87_compare(&mut self, inst: Inst) -> Result<(), Unsupported> {
2538        let Extra::FloatPred(pred) = self.source[inst].extra else {
2539            return Err(self.unsupported(inst));
2540        };
2541        let (args, result) = self.ends(inst)?;
2542        let [left, right] = args[..] else { return Err(self.unsupported(inst)) };
2543        // Two of the fourteen need a second byte and an instruction to put the two together,
2544        // because they are two conditions at once: an ordered equal is equal and not unordered,
2545        // and an unordered not equal is either. The opcode carries all of that and says here only
2546        // that it writes somewhere else as well.
2547        let (name, reversed, both) = match pred {
2548            FloatPred::Ogt => ("fucomip_set_a", false, false),
2549            FloatPred::Oge => ("fucomip_set_ae", false, false),
2550            FloatPred::Olt => ("fucomip_set_a", true, false),
2551            FloatPred::Ole => ("fucomip_set_ae", true, false),
2552            FloatPred::One => ("fucomip_set_ne", false, false),
2553            FloatPred::Ord => ("fucomip_set_np", false, false),
2554            FloatPred::Uno => ("fucomip_set_p", false, false),
2555            FloatPred::Ueq => ("fucomip_set_e", false, false),
2556            FloatPred::Ult => ("fucomip_set_b", false, false),
2557            FloatPred::Ule => ("fucomip_set_be", false, false),
2558            FloatPred::Ugt => ("fucomip_set_b", true, false),
2559            FloatPred::Uge => ("fucomip_set_be", true, false),
2560            FloatPred::Oeq => ("fucomip_set_e_and_np", false, true),
2561            FloatPred::Une => ("fucomip_set_ne_or_p", false, true),
2562            FloatPred::False | FloatPred::True => return Err(self.unsupported(inst)),
2563        };
2564        let (top, under) = if reversed { (right, left) } else { (left, right) };
2565
2566        let span = self.source.span(inst);
2567        let gpr = self.gpr;
2568        let under = self.x87_slot(under);
2569        let under = self.through(under);
2570        let top = self.x87_slot(top);
2571        let top = self.through(top);
2572        self.x87_at("fld_t", span, under);
2573        self.x87_at("fld_t", span, top);
2574
2575        let block = self.at.expect("a block is being filled");
2576        let reg = self.new_reg(result);
2577        // Taken before the instruction is started rather than inside it, since both come from the
2578        // same function being built and only one thing at a time may be adding to it.
2579        let spare = both.then(|| self.out.new_vreg(gpr));
2580        let opcode = self.named(name);
2581        let mut build = self.out.build(block, opcode).at(span).def(reg, gpr);
2582        if let Some(spare) = spare {
2583            build = build.def(spare, gpr);
2584        }
2585        build.finish();
2586        Ok(())
2587    }
2588
2589    /// The operands and the one result of an instruction that has exactly one.
2590    fn ends(&self, inst: Inst) -> Result<(&'a [Value], Value), Unsupported> {
2591        let data = &self.source[inst];
2592        let result = data.first_result.ok_or_else(|| self.unsupported(inst))?;
2593        Ok((&self.source[data.args], result))
2594    }
2595
2596    /// The operand of a conversion, which is the end of it that is not the `long double`.
2597    fn narrow(&self, inst: Inst) -> Result<Value, Unsupported> {
2598        let args = &self.source[self.source[inst].args];
2599        args.first().copied().ok_or_else(|| self.unsupported(inst))
2600    }
2601
2602    /// One `va_start`, as the fields of the list it was handed.
2603    ///
2604    /// On the four field list, two of them are numbers this already knows, and each costs an
2605    /// instruction to put in a register before it can be stored, because the machine here has no
2606    /// store of an immediate to memory. The other two are addresses in the frame, and each is a
2607    /// `lea` [`crate::finish`] finishes: the save area is one of the function's own stack objects,
2608    /// and the caller's argument area is where the parameters that had no register came from, which
2609    /// is the same place and the same fixup a parameter past the sixth already uses.
2610    ///
2611    /// On the list that is a pointer it is the second of those four and nothing else, since the
2612    /// whole of what that list says is where the walk is and the walk starts at the first argument
2613    /// the signature does not name. One `lea` and one store.
2614    ///
2615    /// What is written is exactly the fields [`crate::varargs`] describes, in the order they are
2616    /// laid out, so that reading this beside that table is the whole of the check.
2617    fn va_start(&mut self, inst: Inst) -> Result<(), Unsupported> {
2618        let Some(&list) = self.source[self.source[inst].args].first() else {
2619            return Err(self.unsupported(inst));
2620        };
2621        let started = self.varargs.ok_or_else(|| self.unsupported(inst))?;
2622        let list = self.reg_of(list)?;
2623        let block = self.at.expect("a block is being filled");
2624        let span = self.source.span(inst);
2625
2626        let (save, incoming) = match started {
2627            Varargs::Pointer { incoming } => (None, incoming),
2628            Varargs::Fields { save, incoming, integers, floats } => {
2629                let counts = [(varargs::GP_OFFSET, integers), (varargs::FP_OFFSET, floats)];
2630                for (at, count) in counts {
2631                    self.store_small(list, at, i64::from(count), span);
2632                }
2633                (Some(save), incoming)
2634            }
2635            Varargs::Aapcs { save, incoming, integers_end, floats_end, integers, floats } => {
2636                let counts =
2637                    [(varargs::aapcs::GR_OFFS, integers), (varargs::aapcs::VR_OFFS, floats)];
2638                for (at, count) in counts {
2639                    self.store_small(list, at, i64::from(count), span);
2640                }
2641                let overflow = self.overflow(block, incoming, span);
2642                let integers_top = self.frame_address_plus(block, save, integers_end);
2643                let floats_top = self.frame_address_plus(block, save, floats_end);
2644                let fields = [
2645                    (varargs::aapcs::STACK, overflow),
2646                    (varargs::aapcs::GR_TOP, integers_top),
2647                    (varargs::aapcs::VR_TOP, floats_top),
2648                ];
2649                for (at, held) in fields {
2650                    self.store_word(list, at, held, span);
2651                }
2652                return Ok(());
2653            }
2654        };
2655
2656        // At the front of the list when that address is the whole of it, and at the field the
2657        // layout gives it when there are four, with the save area behind it.
2658        let overflow = self.overflow(block, incoming, span);
2659        let fields = match save {
2660            None => vec![(0, overflow)],
2661            Some(save) => {
2662                let save = self.frame_address(block, save);
2663                vec![(varargs::OVERFLOW, overflow), (varargs::SAVE_AREA, save)]
2664            }
2665        };
2666        for (at, held) in fields {
2667            self.store_word(list, at, held, span);
2668        }
2669        Ok(())
2670    }
2671
2672    /// The first argument the signature did not name, which is as far up the caller's argument
2673    /// area as the ones it did name reached. Nothing here knows where that area is, so the distance
2674    /// is recorded the way a parameter read out of it is and finished with it.
2675    fn overflow(&mut self, block: mir::Block, incoming: u32, span: Span) -> mir::Reg {
2676        let overflow = self.out.new_vreg(self.gpr);
2677        let lea = self.named(self.selector.frame.lea);
2678        let sp = mir::Operand::read(mir::Reg::physical(self.conv.stack_pointer), self.gpr);
2679        let made = self
2680            .out
2681            .build(block, lea)
2682            .at(span)
2683            .def(overflow, self.gpr)
2684            .mem(mir::Mem::at(sp))
2685            .finish();
2686        self.stack.arguments.push((made, incoming));
2687        overflow
2688    }
2689
2690    /// Writes a small constant into a 32 bit field of a list.
2691    fn store_small(&mut self, list: mir::Reg, at: i64, value: i64, span: Span) {
2692        let block = self.at.expect("a block is being filled");
2693        let held = self.out.new_vreg(self.gpr);
2694        let load = mir::Opcode::new(self.names.intern(self.selector.abi.small));
2695        self.out.build(block, load).at(span).def(held, self.gpr).imm(value).finish();
2696
2697        let head = (self.selector.abi.store)(Type::int(32)).expect("a store of a word");
2698        let store = mir::Opcode::new(self.names.intern(head));
2699        let mem = self.field(list, at);
2700        self.out.build(block, store).at(span).uses(held, self.gpr).mem(mem).finish();
2701    }
2702
2703    /// Writes an address into a pointer field of a list.
2704    fn store_word(&mut self, list: mir::Reg, at: i64, held: mir::Reg, span: Span) {
2705        let block = self.at.expect("a block is being filled");
2706        let head = (self.selector.abi.store)(Type::int(64)).expect("a store of an address");
2707        let store = mir::Opcode::new(self.names.intern(head));
2708        let mem = self.field(list, at);
2709        self.out.build(block, store).at(span).uses(held, self.gpr).mem(mem).finish();
2710    }
2711
2712    /// One field of a list, as the addressing mode that reaches it.
2713    fn field(&self, list: mir::Reg, at: i64) -> mir::Mem {
2714        let base = mir::Operand::read(list, self.gpr);
2715        mir::Mem::at(base).plus(i32::try_from(at).expect("a field of a list is a small offset"))
2716    }
2717
2718    /// The address of a name: one `lea` off the instruction pointer, with the name on it.
2719    ///
2720    /// That is x86-64, and [`Selector::symbols`] is what says so. AArch64 writes the same thing as
2721    /// an `adrp` of the page and an `add` of the low twelve bits, which is one opcode with the name
2722    /// as its own symbol and no addressing mode, and the table read is an `adrp` and an `ldr`.
2723    ///
2724    /// The same instruction an `alloca` gets and for a related reason. An address that is not in
2725    /// the program is a `lea` of an addressing mode that names no register, and the mode carries
2726    /// the symbol so that [`rucc_asm`] can write it relative to `%rip` and leave the relocation
2727    /// for the assembler. Both halves of that already existed: the printer writes `sym(%rip)` and
2728    /// the encoder emits the relocation, because a call to a name the file does not define needed
2729    /// them first.
2730    ///
2731    /// One `mov` and not one `lea` when the name is one [`Elsewhere`] holds, because the distance
2732    /// the `lea` adds to the instruction pointer is a number only a link that puts the name in
2733    /// this program can work out, and the address of a function this file merely declares is not
2734    /// such a number. The load reads the address out of the slot the linker fills in instead. The
2735    /// linker turns it back into the `lea` when the name turns out to have been here all along,
2736    /// so this is not slower in the case that was already right.
2737    ///
2738    /// There is deliberately no name for this in [`crate::term`], which is what stops the address
2739    /// being folded into the instruction that reads it. Folding it is the right thing to do and
2740    /// is what turns a load of a global from two instructions into one, but it is a separate
2741    /// question about addressing modes and issue #282 is it. Until then the address is in a
2742    /// register before anything uses it, which is correct and one instruction longer.
2743    ///
2744    /// What this does not do is give the name anything to refer to. A module carries its globals
2745    /// and nothing writes them out, so a file that defines the variable it reads compiles to a
2746    /// reference the linker cannot resolve. Issue #293 is the other half.
2747    ///
2748    /// A thread-local variable is neither of the two above and is [`Self::thread_address`].
2749    fn address_of(&mut self, inst: Inst) -> Result<(), Unsupported> {
2750        let data = &self.source[inst];
2751        let Extra::Symbol(symbol) = data.extra else { return Err(self.unsupported(inst)) };
2752        let result = data.first_result.ok_or_else(|| self.unsupported(inst))?;
2753        if self.elsewhere.thread(symbol) {
2754            return self.thread_address(inst, symbol, result);
2755        }
2756        if let Some(slot) = self.elsewhere.slot(symbol) {
2757            let reg = self.new_reg(result);
2758            return self.through_slot(inst, slot, symbol, reg);
2759        }
2760
2761        let block = self.at.expect("a block is being filled");
2762        let reg = self.new_reg(result);
2763        let span = self.source.span(inst);
2764        let far = self.elsewhere.holds(symbol);
2765        let symbols = self.selector.symbols;
2766        match if far { symbols.far } else { symbols.near } {
2767            Reach::Mode(name) => {
2768                let mem = if far { mir::Mem::got(symbol) } else { mir::Mem::of(symbol) };
2769                let opcode = self.named(name);
2770                self.out.build(block, opcode).at(span).def(reg, self.gpr).mem(mem).finish();
2771            }
2772            Reach::Own(name) => {
2773                let opcode = self.named(name);
2774                self.out.build(block, opcode).at(span).def(reg, self.gpr).symbol(symbol).finish();
2775            }
2776        }
2777        Ok(())
2778    }
2779
2780    /// The address of a name on COFF that is reached through a pointer, into `reg`.
2781    ///
2782    /// One load of the pointer from the instruction pointer, which is the same instruction the
2783    /// global offset table is read with on the other formats and for much the same reason: the
2784    /// pointer is in this image, so the distance to it is a number the linker has, and what it
2785    /// holds is an address the loader or the runtime writes once the DLL the name is in has been
2786    /// put somewhere. See [`Slot`] for which pointer and who writes it.
2787    ///
2788    /// ```text
2789    /// movq  __imp_GetCurrentProcessId(%rip), %rax
2790    /// movq  .refptr.environ(%rip), %rax
2791    /// ```
2792    fn through_slot(
2793        &mut self,
2794        inst: Inst,
2795        slot: Slot,
2796        symbol: Symbol,
2797        reg: mir::Reg,
2798    ) -> Result<(), Unsupported> {
2799        let Reach::Mode(name) = self.selector.symbols.far else {
2800            return Err(self.unsupported(inst));
2801        };
2802        let block = self.at.expect("a block is being filled");
2803        let span = self.source.span(inst);
2804        let pointer = slot.name(self.names.resolve(symbol));
2805        let pointer = self.names.intern(&pointer);
2806        let opcode = self.named(name);
2807        self.out
2808            .build(block, opcode)
2809            .at(span)
2810            .def(reg, self.gpr)
2811            .mem(mir::Mem::of(pointer))
2812            .finish();
2813        Ok(())
2814    }
2815
2816    /// The address of a thread-local variable, which is this thread's copy of it.
2817    ///
2818    /// Neither instruction the ordinary case writes would mean anything here. There is no distance
2819    /// to the variable for a `lea` to add, because there is no variable: there is one copy of it per
2820    /// thread and they are at different addresses, so a link asked for the distance to the name
2821    /// refuses rather than picking one. And there is no address for a table slot to hold either, for
2822    /// the same reason.
2823    ///
2824    /// What is the same in every thread is where the variable sits inside the block of storage a
2825    /// thread gets, so that offset is what the link writes down, and the address of the running
2826    /// thread's block is what turns it into an address. x86-64 keeps that address in `%fs`, at the
2827    /// front of the block, so the whole of this is three instructions:
2828    ///
2829    /// ```text
2830    /// movq  x@gottpoff(%rip), %off   # how far into the block x sits, which the link fills in
2831    /// movq  %fs:0, %tp               # where this thread's block is, which only the machine knows
2832    /// addq  %tp, %off                # this thread's copy of x
2833    /// ```
2834    ///
2835    /// That is the initial exec model. It is one instruction longer than what gcc writes at `-O2`
2836    /// in an executable, which folds the addition into the instruction that uses the address, and
2837    /// the difference is issue #282 rather than anything about threads: nothing here folds an
2838    /// address into its reader yet. The link relaxes the first instruction into an immediate when it
2839    /// is making an executable, since it lays the blocks out and therefore knows the number, so the
2840    /// table slot costs nothing in the case that is common.
2841    ///
2842    /// It is not the most general model. A library loaded by `dlopen` gets its storage after the
2843    /// program is already running, and the block this reaches was laid out before it started, so
2844    /// the loader has to find room in that block for the library's variables. glibc keeps a little
2845    /// spare room for exactly this and a library that fits in it loads and runs; one that does not
2846    /// fails to load, with a message saying so. The model with no such limit calls `__tls_get_addr`
2847    /// and is what gcc writes under `-fPIC` by default, and it is issue #1104.
2848    ///
2849    /// So this is the model gcc writes under `-ftls-model=initial-exec`: right for an executable,
2850    /// right for a library the program is linked against, and a load that either works or is
2851    /// refused out loud for a library something opens later. What it is never is quietly wrong.
2852    ///
2853    /// AArch64 Linux is the same three steps. The slot is reached with `adrp` and `ldr` against
2854    /// `:gottprel:`, the thread pointer is `tpidr_el0` read with `mrs`, and the add has three
2855    /// operands. Apple's platforms reach a thread-local variable through a descriptor call instead,
2856    /// which is [`Self::thread_descriptor`].
2857    fn thread_address(
2858        &mut self,
2859        inst: Inst,
2860        symbol: Symbol,
2861        result: Value,
2862    ) -> Result<(), Unsupported> {
2863        if self.elsewhere.described() {
2864            return self.thread_descriptor(inst, symbol, result);
2865        }
2866        if self.elsewhere.indexed() {
2867            return self.thread_indexed(inst, symbol, result);
2868        }
2869        let block = self.at.expect("a block is being filled");
2870        let span = self.source.span(inst);
2871        let gpr = self.gpr;
2872
2873        let offset = self.out.new_vreg(gpr);
2874        match self.selector.symbols.thread {
2875            Reach::Mode(name) => {
2876                let load = self.named(name);
2877                let mem = mir::Mem::thread(symbol);
2878                self.out.build(block, load).at(span).def(offset, gpr).mem(mem).finish();
2879            }
2880            Reach::Own(name) => {
2881                let load = self.named(name);
2882                self.out.build(block, load).at(span).def(offset, gpr).symbol(symbol).finish();
2883            }
2884        }
2885        let pointer = self.out.new_vreg(gpr);
2886        self.read_thread_pointer(block, span, pointer);
2887
2888        // Two address on x86-64, for the reason `x87_to_int` gives: that machine adds into the
2889        // register it read, and only the constraint says the two are the same one.
2890        let reg = self.new_reg(result);
2891        let jumps = self.selector.jumps;
2892        let add = self.named(jumps.add);
2893        let written = mir::Operand::write(reg, gpr);
2894        let written = if jumps.two_address { written.with(Constraint::Reuse(1)) } else { written };
2895        self.out
2896            .build(block, add)
2897            .at(span)
2898            .operand(written)
2899            .operand(mir::Operand::read(offset, gpr))
2900            .operand(mir::Operand::read(pointer, gpr))
2901            .finish();
2902        Ok(())
2903    }
2904
2905    /// A thread-local variable on Mach-O, which is a call.
2906    ///
2907    /// The slot the machine's thread load reads holds the address of the variable's descriptor
2908    /// there, `_v@TLVP` on x86-64 and `_v@TLVPPAGE` with `_v@TLVPPAGEOFF` on AArch64. The first
2909    /// word of the descriptor is the function that finds this thread's copy, and it takes the
2910    /// descriptor's address as its one argument and gives back the copy's address. That is the
2911    /// sequence clang writes on both machines.
2912    ///
2913    /// The call is built as an ordinary call through an address, so it costs what any call costs:
2914    /// everything the convention does not preserve is taken to be gone across it. Apple's function
2915    /// keeps more than that, all but the result and the two scratch registers on AArch64, and
2916    /// taking the fewer registers as gone would be faster. What this gives up is speed, and a
2917    /// function that reads a thread-local is no longer a leaf.
2918    fn thread_descriptor(
2919        &mut self,
2920        inst: Inst,
2921        symbol: Symbol,
2922        result: Value,
2923    ) -> Result<(), Unsupported> {
2924        let block = self.at.expect("a block is being filled");
2925        let span = self.source.span(inst);
2926        let gpr = self.gpr;
2927
2928        let descriptor = self.out.new_vreg(gpr);
2929        match self.selector.symbols.thread {
2930            Reach::Mode(name) => {
2931                let load = self.named(name);
2932                let mem = mir::Mem::thread(symbol);
2933                self.out.build(block, load).at(span).def(descriptor, gpr).mem(mem).finish();
2934            }
2935            Reach::Own(name) => {
2936                let load = self.named(name);
2937                let build = self.out.build(block, load).at(span);
2938                build.def(descriptor, gpr).symbol(symbol).finish();
2939            }
2940        }
2941        let finder = self.out.new_vreg(gpr);
2942        let word = (self.selector.abi.load)(Type::PTR).ok_or_else(|| self.unsupported(inst))?;
2943        let word = mir::Opcode::new(self.names.intern(word));
2944        let mem = mir::Mem::at(mir::Operand::read(descriptor, gpr));
2945        self.out.build(block, word).at(span).def(finder, gpr).mem(mem).finish();
2946
2947        let args = [abi::Passing { ty: Type::PTR, reg: descriptor, abi: Abi::default() }];
2948        let what = abi::Calling {
2949            callee: abi::Callee::Through(finder),
2950            args: &args,
2951            returns: &[Type::PTR],
2952            variadic: false,
2953            named: 1,
2954            at: span,
2955        };
2956        let made = abi::call(&mut self.out, block, &what, self.conv, self.selector.abi, self.names)
2957            .map_err(|refused| Unsupported::Call { inst, refused })?;
2958        let calls = &mut self.stack.calls;
2959        *calls = Some(calls.unwrap_or(0).max(made.outgoing));
2960        let &[reg] = &made.results[..] else { return Err(self.unsupported(inst)) };
2961        self.regs[result.index()] = Some(reg);
2962        Ok(())
2963    }
2964
2965    /// A thread-local variable on Windows, which is four loads and no call.
2966    ///
2967    /// `_tls_index` is this image's slot in the array of `.tls` copies the thread block holds at
2968    /// `%gs:88`, and the variable is as far into this thread's copy as it is into the section. The
2969    /// C runtime defines the index and the linker writes the offset. See [`crate::select::Indexed`] for
2970    /// the four instructions, which are the ones gcc writes.
2971    fn thread_indexed(
2972        &mut self,
2973        inst: Inst,
2974        symbol: Symbol,
2975        result: Value,
2976    ) -> Result<(), Unsupported> {
2977        let Some(indexed) = self.selector.symbols.indexed.as_ref() else {
2978            return Err(Unsupported::Unported { inst: Some(inst), what: Unported::Thread });
2979        };
2980        let block = self.at.expect("a block is being filled");
2981        let span = self.source.span(inst);
2982        let gpr = self.gpr;
2983
2984        let slot = self.out.new_vreg(gpr);
2985        let tls_index = self.names.intern("_tls_index");
2986        let index = self.named(indexed.index);
2987        self.out.build(block, index).at(span).def(slot, gpr).mem(mir::Mem::of(tls_index)).finish();
2988
2989        let array = self.out.new_vreg(gpr);
2990        let load = self.named(indexed.load);
2991        let at = mir::Mem::in_segment(indexed.segment, indexed.at);
2992        self.out.build(block, load).at(span).def(array, gpr).mem(at).finish();
2993
2994        let copy = self.out.new_vreg(gpr);
2995        let mem =
2996            mir::Mem::at(mir::Operand::read(array, gpr)).indexed(mir::Operand::read(slot, gpr), 8);
2997        self.out.build(block, load).at(span).def(copy, gpr).mem(mem).finish();
2998
2999        let reg = self.new_reg(result);
3000        let add = self.named(indexed.add);
3001        let mem = mir::Mem::section(mir::Operand::read(copy, gpr), symbol);
3002        self.out.build(block, add).at(span).def(reg, gpr).mem(mem).finish();
3003        Ok(())
3004    }
3005
3006    /// Refuses the thread pointer where it is not written, which is Mach-O. Apple keeps it in a
3007    /// different register from the one Linux does on both machines, and nothing written for it
3008    /// has been checked on one.
3009    fn threads_written(&self, inst: Inst) -> Result<(), Unsupported> {
3010        if self.elsewhere.described() || self.elsewhere.indexed() {
3011            return Err(Unsupported::Unported { inst: Some(inst), what: Unported::Thread });
3012        }
3013        Ok(())
3014    }
3015
3016    /// The front of this thread's block into `reg`.
3017    ///
3018    /// On x86-64 that is the one thing no instruction can work out: `%fs` is not a register a
3019    /// program can read, and what it points at is a word holding its own address, so reading
3020    /// through it at zero is how the address is come by. AArch64 keeps it in `tpidr_el0`, which
3021    /// `mrs` reads.
3022    fn read_thread_pointer(&mut self, block: mir::Block, span: Span, reg: mir::Reg) {
3023        let gpr = self.gpr;
3024        match self.selector.symbols.pointer {
3025            Pointer::Segment(name, segment) => {
3026                let load = self.named(name);
3027                let at = mir::Mem::in_segment(segment, 0);
3028                self.out.build(block, load).at(span).def(reg, gpr).mem(at).finish();
3029            }
3030            Pointer::Own(name) => {
3031                let read = self.named(name);
3032                self.out.build(block, read).at(span).def(reg, gpr).finish();
3033            }
3034        }
3035    }
3036
3037    /// `&&label`, GNU's address of a label, which is the same `lea` a global gets against a place
3038    /// in this same function.
3039    ///
3040    /// What the two have in common is the whole of the instruction: an address worked out from
3041    /// where the instruction is, which is what `(%rip)` means and is the only way this compiler
3042    /// reaches anything. What they do not have in common is what fills the four bytes in. A
3043    /// global is a name, so the number is a relocation and the linker writes it. A block is a
3044    /// place in this function, so both ends are in one section and the number is known as soon as
3045    /// the blocks have been laid out, which is why `rucc_asm` fills it in the way it fills in a
3046    /// jump rather than leaving a relocation behind.
3047    ///
3048    /// Nothing here says the block is one control can arrive at. That is said by the
3049    /// [`Opcode::IndirectBr`] that reads the address, which lists every block it can arrive at,
3050    /// and by nothing else: an address on its own is a number.
3051    fn block_address(&mut self, inst: Inst) -> Result<(), Unsupported> {
3052        let result = self.source[inst].first_result.ok_or_else(|| self.unsupported(inst))?;
3053        let Some(call) = self.source.successors(inst).next() else {
3054            return Err(self.unsupported(inst));
3055        };
3056        let block = self.at.expect("a block is being filled");
3057        let reg = self.new_reg(result);
3058        let span = self.source.span(inst);
3059        let opcode = self.named(self.selector.jumps.near);
3060        let mem = mir::Mem::block(self.out_block(call.block));
3061        self.out.build(block, opcode).at(span).def(reg, self.gpr).mem(mem).finish();
3062        Ok(())
3063    }
3064
3065    /// `goto *p`, GNU's computed goto, which is a jump through a register.
3066    ///
3067    /// Where it goes is not written here and cannot be. Every block it can arrive at is on the
3068    /// block this ends, the way every other arm is, and which of them the address holds is decided
3069    /// while the program runs. So this is one instruction with one operand, and the arms are
3070    /// copied across by [`Self::edges`] like anybody else's.
3071    fn indirect_branch(&mut self, inst: Inst) -> Result<(), Unsupported> {
3072        let data = &self.source[inst];
3073        let &address = self.source[data.args].first().ok_or_else(|| self.unsupported(inst))?;
3074        let reg = self.reg_of(address)?;
3075        let block = self.at.expect("a block is being filled");
3076        let span = self.source.span(inst);
3077        let name = self.selector.branch.indirect;
3078        let opcode = self.named(name);
3079        self.out.build(block, opcode).at(span).operand(mir::Operand::read(reg, self.gpr)).finish();
3080        Ok(())
3081    }
3082
3083    /// A `switch` on an index from zero up, as a jump through a table of this function.
3084    ///
3085    /// Every `switch` that reaches here is one `crate::switch` left behind on purpose: it has
3086    /// already checked the value is inside the table and taken the lowest case off it, so the
3087    /// operand is a 64 bit index, the cases are the values from zero up with gaps where the
3088    /// program had no case, and the default is only where those gaps go. What is written is the
3089    /// shape gcc writes for the same statement in position independent code:
3090    ///
3091    /// ```text
3092    /// leaq    table(%rip), %base
3093    /// movslq  (%base,%index,4), %offset
3094    /// addq    %base, %offset
3095    /// jmp     *%offset
3096    /// ```
3097    ///
3098    /// The table holds distances from itself to each arm rather than addresses, which is what
3099    /// lets it be filled in by the assembler with nothing left for a linker to do. Each cell is
3100    /// stored as the place of an arm among this block's successors, which [`Self::edges`] copies
3101    /// across in the IR's own order, the default first and then one per case. See
3102    /// [`mir::Table`] for why a place and not a block.
3103    fn jump_table(&mut self, inst: Inst) -> Result<(), Unsupported> {
3104        let data = &self.source[inst];
3105        let Extra::Switch(info) = data.extra else { return Err(self.unsupported(inst)) };
3106        let &index = self.source[data.args].first().ok_or_else(|| self.unsupported(inst))?;
3107        let ty = self.source[index].ty;
3108        if ty != Type::int(u64::BITS) {
3109            return Err(self.unsupported(inst));
3110        }
3111        let cases = self.source[self.source[info].cases].to_vec();
3112        let mut cells: Vec<u32> = Vec::new();
3113        for (arm, case) in cases.iter().enumerate() {
3114            let at = usize::try_from(case.signed(ty)).map_err(|_| self.unsupported(inst))?;
3115            if at >= cells.len() {
3116                cells.resize(at + 1, 0);
3117            }
3118            cells[at] = u32::try_from(arm + 1).map_err(|_| self.unsupported(inst))?;
3119        }
3120        let reg = self.reg_of(index)?;
3121        let block = self.at.expect("a block is being filled");
3122        let span = self.source.span(inst);
3123        let gpr = self.gpr;
3124        let table = u32::try_from(self.out.tables.len()).expect("fewer tables than that");
3125
3126        let jumps = self.selector.jumps;
3127
3128        let base = self.out.new_vreg(gpr);
3129        let near = self.named(jumps.near);
3130        self.out.build(block, near).at(span).def(base, gpr).mem(mir::Mem::table(table)).finish();
3131        let offset = self.out.new_vreg(gpr);
3132        let cell =
3133            mir::Mem::at(mir::Operand::read(base, gpr)).indexed(mir::Operand::read(reg, gpr), 4);
3134        let load = self.named(jumps.cell);
3135        self.out.build(block, load).at(span).def(offset, gpr).mem(cell).finish();
3136        // Two address on x86-64, for the reason `thread_pointer` gives.
3137        let to = self.out.new_vreg(gpr);
3138        let add = self.named(jumps.add);
3139        let written = mir::Operand::write(to, gpr);
3140        let written = if jumps.two_address { written.with(Constraint::Reuse(1)) } else { written };
3141        self.out
3142            .build(block, add)
3143            .at(span)
3144            .operand(written)
3145            .operand(mir::Operand::read(offset, gpr))
3146            .operand(mir::Operand::read(base, gpr))
3147            .finish();
3148        let jump = self.named(self.selector.branch.indirect);
3149        let jump =
3150            self.out.build(block, jump).at(span).operand(mir::Operand::read(to, gpr)).finish();
3151        self.out.tables.push(mir::Table { jump, cells });
3152        Ok(())
3153    }
3154
3155    /// `__builtin_setjmp`, which writes down where the function is so that a `__builtin_longjmp`
3156    /// somewhere else can bring control back here, and answers zero on the way past.
3157    ///
3158    /// Four words of the buffer, the three gcc writes and one of this compiler's own, and then the
3159    /// block ends: everything after the save in the IR block is put into a new machine IR block,
3160    /// and the address of that block is what went into the buffer. That is the whole reason the
3161    /// block is split here. An address points at a label, a machine IR block is the only thing in
3162    /// this representation that has one, and a save is in the middle of a block rather than at the
3163    /// end of one.
3164    ///
3165    /// # How the answer gets back
3166    ///
3167    /// Through the frame rather than through a register. The save writes a zero into a word of its
3168    /// own frame, puts the address of that word in the buffer, and the new block reads the word
3169    /// back. The restore writes a one through the address it finds in the buffer before it goes.
3170    /// So one load answers zero on the way past and one on the way back, and neither path has to
3171    /// agree with the other about a register.
3172    ///
3173    /// gcc does it the other way round, with a second block that sets the answer to one and is
3174    /// what the restore arrives at. That block is one nothing in the function jumps to, and a
3175    /// machine IR whose blocks are walked from the entry has nowhere to put such a thing: the
3176    /// allocator lays a function out in the line it is going to be emitted in, and a block no edge
3177    /// reaches is not in that line. The word in the frame costs eight bytes of stack and one load,
3178    /// and it needs nothing said anywhere about a block arrived at from outside.
3179    ///
3180    /// # What the allocator is told
3181    ///
3182    /// That every register it hands out is gone at the end of the first block. That is what makes
3183    /// the rest of the function right on the way back: control arrives from a `__builtin_longjmp`
3184    /// in some other function, and the only two registers that puts back are the stack pointer and
3185    /// the frame pointer, so anything this function still wants has to be in the frame those two
3186    /// reach. It is said with a write of every one of those registers, which is the same thing a
3187    /// call says about the registers a callee may destroy, on an instruction with nothing else on
3188    /// it so that the stores above are not caught up in it.
3189    fn saves_place(&mut self, inst: Inst) -> Result<(), Unsupported> {
3190        let data = &self.source[inst];
3191        let result = data.first_result.ok_or_else(|| self.unsupported(inst))?;
3192        let &buffer = self.source[data.args].first().ok_or_else(|| self.unsupported(inst))?;
3193        let span = self.source.span(inst);
3194        let buf = self.reg_of(buffer)?;
3195        let at = self.at.expect("a block is being filled");
3196        let gpr = self.gpr;
3197        let moves = self.selector.frame.moves(gpr).expect("a class the target says how to move");
3198        let store = self.named(moves.store);
3199        let load = self.named(moves.load);
3200        let lea = self.named(self.selector.frame.lea);
3201        let put = self.named(self.selector.frame.imm);
3202        let nothing =
3203            self.selector.frame.pad.expect("a target with an instruction that does nothing");
3204        let nothing = self.named(nothing);
3205        self.stack.saves_place = true;
3206        let answer = self.answer_slot();
3207        let back = self.out.create_block();
3208
3209        // The zero this answers with, into the word a restore writes a one into.
3210        let zero = self.out.new_vreg(gpr);
3211        self.out.build(at, put).at(span).def(zero, gpr).imm(0).finish();
3212        let mem = self.frame_mem();
3213        let made = self.out.build(at, store).at(span).uses(zero, gpr).mem(mem).finish();
3214        self.stack.addresses.push((made, answer));
3215
3216        // The four words: where that word is, where control comes back to, and the two registers
3217        // the restore puts back.
3218        let found = self.frame_address(at, answer);
3219        self.write_word(at, span, store, found, buf, JUMP_ANSWER);
3220        let pc = self.out.new_vreg(gpr);
3221        self.out.build(at, lea).at(span).def(pc, gpr).mem(mir::Mem::block(back)).finish();
3222        self.write_word(at, span, store, pc, buf, JUMP_PC);
3223        let frame = mir::Reg::physical(self.conv.frame_pointer);
3224        self.write_word(at, span, store, frame, buf, JUMP_FRAME);
3225        let stack = mir::Reg::physical(self.conv.stack_pointer);
3226        self.write_word(at, span, store, stack, buf, JUMP_STACK);
3227
3228        // Nothing is in a register past this point, which is what the rest of the function is
3229        // allowed to assume about the way back in.
3230        let gone = self.across_jump();
3231        let mut build = self.out.build(at, nothing).at(span);
3232        for (reg, class) in gone {
3233            build = build.operand(mir::Operand::write(reg, class));
3234        }
3235        build.finish();
3236
3237        // And the rest of the block, which is the block the address above was of.
3238        *self.out.succs_mut(at) = vec![mir::BlockCall::to(back)];
3239        self.at = Some(back);
3240        let reg = self.new_reg(result);
3241        let mem = self.frame_mem();
3242        let made = self.out.build(back, load).at(span).def(reg, gpr).mem(mem).finish();
3243        self.stack.addresses.push((made, answer));
3244        Ok(())
3245    }
3246
3247    /// `__builtin_longjmp`, which reads a buffer a `__builtin_setjmp` filled in and goes there.
3248    ///
3249    /// Everything comes out of the buffer before anything is put back, and the four registers it
3250    /// comes out into are physical ones rather than values the allocator places. Both of those are
3251    /// about the same moment. The stack pointer is one of the things being put back, a value the
3252    /// allocator sent to the stack is reached through the stack pointer, and between the
3253    /// instruction that moves it and the jump there is no stack this function owns any more. A
3254    /// register named outright is a register nothing reloads into and nothing else is in, which is
3255    /// the only way to hold something across that moment.
3256    ///
3257    /// Four of them because that is how many things are in the air at once: where to go, the frame
3258    /// pointer to put back, the one the matching save is to answer with, and one register used
3259    /// twice, first for the address that one is written through and then for the stack pointer.
3260    ///
3261    /// Nothing after this in the block is reached. The marker is not a terminator, for the reason
3262    /// `spec/08-ir.md` gives, so the block goes on and whatever the front end wrote after it is
3263    /// written out and never run.
3264    fn comes_back(&mut self, inst: Inst) -> Result<(), Unsupported> {
3265        let data = &self.source[inst];
3266        let &buffer = self.source[data.args].first().ok_or_else(|| self.unsupported(inst))?;
3267        let span = self.source.span(inst);
3268        let buf = self.reg_of(buffer)?;
3269        let at = self.at.expect("a block is being filled");
3270        let gpr = self.gpr;
3271        let moves = self.selector.frame.moves(gpr).expect("a class the target says how to move");
3272        let load = self.named(moves.load);
3273        let store = self.named(moves.store);
3274        let mov = self.named(moves.mov);
3275        let put = self.named(self.selector.frame.imm);
3276        let jump = self.named(self.selector.branch.indirect);
3277
3278        let held = self.jump_regs();
3279        if held.len() < JUMP_REGS {
3280            return Err(self.unsupported(inst));
3281        }
3282        let pc = mir::Reg::physical(held[0]);
3283        let frame = mir::Reg::physical(held[1]);
3284        let spare = mir::Reg::physical(held[2]);
3285        let one = mir::Reg::physical(held[3]);
3286
3287        self.read_word(at, span, load, pc, buf, JUMP_PC);
3288        self.read_word(at, span, load, frame, buf, JUMP_FRAME);
3289        self.read_word(at, span, load, spare, buf, JUMP_ANSWER);
3290
3291        // What the matching save answers with, written through the address that came out of the
3292        // buffer, because the word it goes in is in the other function's frame and this one has no
3293        // way of knowing where that is.
3294        self.out.build(at, put).at(span).def(one, gpr).imm(1).finish();
3295        let mem = mir::Mem::at(mir::Operand::read(spare, gpr));
3296        self.out.build(at, store).at(span).uses(one, gpr).mem(mem).finish();
3297
3298        // The stack last of the four, so that the register the buffer is reached through is done
3299        // with before the stack it may have been spilled to stops being this function's.
3300        self.read_word(at, span, load, spare, buf, JUMP_STACK);
3301        let stack = mir::Reg::physical(self.conv.stack_pointer);
3302        self.copy(at, span, mov, stack, spare);
3303        let base = mir::Reg::physical(self.conv.frame_pointer);
3304        self.copy(at, span, mov, base, frame);
3305
3306        // And the jump, which reads the two registers just put back as well as the address it
3307        // goes through. Neither of those is printed, because the target's spelling of an indirect
3308        // jump has one argument and it is the first one read. They are there because the code
3309        // control arrives at reaches its frame through them, and because without them the two
3310        // instructions above write registers nothing reads: a scheduler is then free to put the
3311        // jump in front of them, and at `-O2` it does.
3312        self.out
3313            .build(at, jump)
3314            .at(span)
3315            .operand(mir::Operand::read(pc, gpr))
3316            .operand(mir::Operand::read(stack, gpr))
3317            .operand(mir::Operand::read(base, gpr))
3318            .finish();
3319        Ok(())
3320    }
3321
3322    /// One word of the buffer of a `__builtin_setjmp`, written from a register.
3323    fn write_word(
3324        &mut self,
3325        at: mir::Block,
3326        span: Span,
3327        store: mir::Opcode,
3328        from: mir::Reg,
3329        buf: mir::Reg,
3330        word: i32,
3331    ) {
3332        let mem = mir::Mem::at(mir::Operand::read(buf, self.gpr)).plus(word);
3333        self.out.build(at, store).at(span).uses(from, self.gpr).mem(mem).finish();
3334    }
3335
3336    /// One word of that buffer, read back into a register.
3337    fn read_word(
3338        &mut self,
3339        at: mir::Block,
3340        span: Span,
3341        load: mir::Opcode,
3342        into: mir::Reg,
3343        buf: mir::Reg,
3344        word: i32,
3345    ) {
3346        let mem = mir::Mem::at(mir::Operand::read(buf, self.gpr)).plus(word);
3347        self.out.build(at, load).at(span).def(into, self.gpr).mem(mem).finish();
3348    }
3349
3350    /// One register into another, which is the one shape of instruction the builder has no word
3351    /// for because neither operand is a definition of a value or a read of memory.
3352    fn copy(
3353        &mut self,
3354        at: mir::Block,
3355        span: Span,
3356        mov: mir::Opcode,
3357        into: mir::Reg,
3358        from: mir::Reg,
3359    ) {
3360        self.out
3361            .build(at, mov)
3362            .at(span)
3363            .operand(mir::Operand::write(into, self.gpr))
3364            .operand(mir::Operand::read(from, self.gpr))
3365            .finish();
3366    }
3367
3368    /// The word a `__builtin_setjmp` in this function answers with, asked for once and kept.
3369    fn answer_slot(&mut self) -> usize {
3370        match self.answer {
3371            Some(index) => index,
3372            None => {
3373                let index = self.stack.locals.len();
3374                self.stack.locals.push(Local { size: JUMP_WORD, align: JUMP_WORD });
3375                self.answer = Some(index);
3376                index
3377            }
3378        }
3379    }
3380
3381    /// An address in this function's frame with nothing in its displacement, which is what an
3382    /// instruction reaching one of its stack objects is written with until [`crate::finish`] knows
3383    /// where the object is.
3384    fn frame_mem(&self) -> mir::Mem {
3385        mir::Mem::at(mir::Operand::read(mir::Reg::physical(self.conv.stack_pointer), self.gpr))
3386    }
3387
3388    /// Every register the allocator hands out, which is what a `__builtin_setjmp` destroys.
3389    ///
3390    /// Both files, since a `double` live across a save has the same problem an integer does. The
3391    /// two registers a frame is reached through are not here: the restore puts both of them back,
3392    /// which is the whole of what it puts back, and a function whose frame pointer was destroyed
3393    /// by its own save would have nothing left to find its caller with.
3394    fn across_jump(&self) -> Vec<(mir::Reg, RegClass)> {
3395        let mut gone = Vec::new();
3396        for &reg in self.conv.int_order {
3397            if reg == self.conv.stack_pointer || reg == self.conv.frame_pointer {
3398                continue;
3399            }
3400            gone.push((mir::Reg::physical(reg), self.gpr));
3401        }
3402        for &reg in self.conv.sse_order {
3403            gone.push((mir::Reg::physical(reg), self.conv.sse_class));
3404        }
3405        gone
3406    }
3407
3408    /// The registers a `__builtin_longjmp` may hold things in while it puts a frame back.
3409    ///
3410    /// The ones the allocator hands out, less the two a frame is reached through. The scratch
3411    /// registers are not among them on purpose: the rewriter writes a reload into one of those
3412    /// wherever it likes, and one of these has to survive from the load that fills it to the
3413    /// instruction that reads it however many instructions apart those are.
3414    fn jump_regs(&self) -> Vec<PhysReg> {
3415        self.conv
3416            .int_order
3417            .iter()
3418            .copied()
3419            .filter(|&reg| {
3420                reg != self.conv.stack_pointer
3421                    && reg != self.conv.frame_pointer
3422                    && !self.selector.scratch.contains(&reg)
3423            })
3424            .collect()
3425    }
3426
3427    /// A machine opcode of this target from the name the target gives it.
3428    fn named(&mut self, name: &str) -> mir::Opcode {
3429        mir::Opcode::new(self.names.intern(&format!("{}{name}", self.selector.prefix())))
3430    }
3431
3432    /// `__builtin_frame_address` and `__builtin_return_address`, which are a walk up the chain of
3433    /// saved frame pointers and then one thing read at the end of it.
3434    ///
3435    /// Every frame that kept a frame pointer holds the caller's at the address the register points
3436    /// at, and the address that frame returns to one word above that, which is where the call
3437    /// instruction put it and where the prologue's push left it. So the walk is a load through the
3438    /// register for each link, the frame address is wherever the walk stopped, and the return
3439    /// address is one more load from a word above it. gcc 16.2.0 writes exactly this, measured on
3440    /// x86-64 at `-O2` for depths zero to three of both builtins.
3441    ///
3442    /// The function is given a frame pointer because of this, which is what [`Stack::walks_frames`]
3443    /// carries out to the layout. A depth of zero needs it as the answer and every depth above zero
3444    /// needs it as the start, so there is no case here where it is not wanted.
3445    ///
3446    /// How far the chain actually reaches is the program's business and not this one's. A caller
3447    /// compiled without a frame pointer has no link in it for the walk to follow, so a depth above
3448    /// zero is a promise about how the whole program was built. That is why gcc documents a nonzero
3449    /// depth as unsafe rather than as an answer, and why the depth is refused above a limit in
3450    /// `check/builtin/frame.rs` rather than walked as far as it says.
3451    fn frames(&mut self, inst: Inst) -> Result<(), Unsupported> {
3452        let data = &self.source[inst];
3453        let Extra::Depth(depth) = data.extra else { return Err(self.unsupported(inst)) };
3454        let result = data.first_result.ok_or_else(|| self.unsupported(inst))?;
3455        let returning = data.opcode == Opcode::ReturnAddress;
3456        let block = self.at.expect("a block is being filled");
3457        let span = self.source.span(inst);
3458        let moves =
3459            self.selector.frame.moves(self.gpr).expect("a class the target says how to move");
3460        let load = self.named(moves.load);
3461        self.stack.walks_frames = true;
3462
3463        // Where the walk is up to. The frame pointer to begin with, and the register the last load
3464        // wrote after that.
3465        let reg = self.new_reg(result);
3466        let mut base = mir::Reg::physical(self.conv.frame_pointer);
3467        for link in 0..depth {
3468            // The last load of a walk that is looking for a frame writes the answer itself, which
3469            // is what keeps a walk of so many links that many instructions and not one more.
3470            let ends_here = link + 1 == depth && !returning;
3471            let next = if ends_here { reg } else { self.out.new_vreg(self.gpr) };
3472            let at = mir::Mem::at(mir::Operand::read(base, self.gpr));
3473            self.out.build(block, load).at(span).def(next, self.gpr).mem(at).finish();
3474            base = next;
3475        }
3476
3477        if returning {
3478            let up = i32::try_from(self.conv.return_address).expect("a word above the frame");
3479            let at = mir::Mem::at(mir::Operand::read(base, self.gpr)).plus(up);
3480            self.out.build(block, load).at(span).def(reg, self.gpr).mem(at).finish();
3481        } else if depth == 0 {
3482            // The one case with no load in it at all: the frame this function is running in is the
3483            // register itself, and a physical register is not one the allocator hands out, so the
3484            // answer is a copy of it.
3485            let mov = self.named(moves.mov);
3486            self.out
3487                .build(block, mov)
3488                .at(span)
3489                .operand(mir::Operand::write(reg, self.gpr))
3490                .operand(mir::Operand::read(base, self.gpr))
3491                .finish();
3492        }
3493        Ok(())
3494    }
3495
3496    /// `__builtin_thread_pointer`, which is the front of the block [`Self::thread_address`] adds
3497    /// an offset to.
3498    ///
3499    /// The same one instruction, on its own this time and with nothing to add to it. A program
3500    /// writes this when what it wants is a number that is different in every thread and cheap to
3501    /// come by, rather than a variable of its own in the block, so there is no relocation here and
3502    /// no name for the link to resolve.
3503    fn thread_pointer(&mut self, inst: Inst) -> Result<(), Unsupported> {
3504        self.threads_written(inst)?;
3505        let result = self.source[inst].first_result.ok_or_else(|| self.unsupported(inst))?;
3506        let block = self.at.expect("a block is being filled");
3507        let span = self.source.span(inst);
3508        let reg = self.new_reg(result);
3509        self.read_thread_pointer(block, span, reg);
3510        Ok(())
3511    }
3512
3513    /// `__builtin_sponentry`, the stack pointer this function was entered with.
3514    ///
3515    /// On AArch64 that is where the caller's arguments on the stack start, so it is the address
3516    /// of the first of them, recorded at zero the way [`Self::overflow`] records the first one the
3517    /// signature did not name and finished with the rest once the frame is laid out. Sema refuses
3518    /// the builtin on every other machine, and this does too, since on x86-64 the return address
3519    /// sits between the two and zero would be the wrong answer.
3520    fn sp_entry(&mut self, inst: Inst) -> Result<(), Unsupported> {
3521        if !self.on_aarch64() {
3522            return Err(self.unsupported(inst));
3523        }
3524        let result = self.source[inst].first_result.ok_or_else(|| self.unsupported(inst))?;
3525        let block = self.at.expect("a block is being filled");
3526        let span = self.source.span(inst);
3527        let reg = self.new_reg(result);
3528        let lea = self.named(self.selector.frame.lea);
3529        let sp = mir::Operand::read(mir::Reg::physical(self.conv.stack_pointer), self.gpr);
3530        let made =
3531            self.out.build(block, lea).at(span).def(reg, self.gpr).mem(mir::Mem::at(sp)).finish();
3532        self.stack.arguments.push((made, 0));
3533        Ok(())
3534    }
3535
3536    /// What a named machine register holds, which is `register long x asm ("rbx");`.
3537    ///
3538    /// One move out of that register, with the register named as itself the way a register a
3539    /// template wrote is named, which is [`Self::itself`] and is the thing #1653 built. What it
3540    /// buys here is what it buys there: the register is part of the instruction the allocator
3541    /// sees, so it is a use the allocator will not have written over first, and the value goes
3542    /// into an ordinary one of its own that everything downstream reads.
3543    ///
3544    /// The whole sixty four bits are moved whatever the type is, because the register is that
3545    /// wide and a narrower type reads the low end of the copy, which is the same low end. A type
3546    /// wider than the register is refused, since there is no register holding it to read. On
3547    /// AArch64 a float may be kept in a vector register, `register double x asm ("d8");`, and it is
3548    /// moved out of that file the same way.
3549    ///
3550    /// A name the machine has not got is refused too, and is the only thing that can be wrong
3551    /// with the string: which register a name means is this machine's question and this is where
3552    /// the question is asked, at the same table `asm` asks about clobbers at. The sigil gcc
3553    /// allows in front of it is taken off here, because what the name is written with is syntax.
3554    fn register_value(&mut self, inst: Inst) -> Result<(), Unsupported> {
3555        let Extra::Symbol(symbol) = self.source[inst].extra else {
3556            return Err(self.unsupported(inst));
3557        };
3558        let result = self.source[inst].first_result.ok_or_else(|| self.unsupported(inst))?;
3559        let ty = self.source[result].ty;
3560        let bits = if ty.is_ptr() { ADDRESS_BITS } else { ty.bits() };
3561        if bits > ADDRESS_BITS {
3562            return Err(self.unsupported(inst));
3563        }
3564        let spelled = self.names.resolve(symbol).to_owned();
3565        let bare = spelled.strip_prefix('%').unwrap_or(&spelled);
3566        let named = if self.on_aarch64() {
3567            aarch64::named(bare)
3568        } else if self.class_of(ty) != self.gpr {
3569            return Err(self.unsupported(inst));
3570        } else {
3571            x86_64::gpr_named(bare).map(|(reg, _)| (reg, self.gpr))
3572        };
3573        let Some((held, file)) = named else {
3574            return Err(Unsupported::Register { inst, name: spelled });
3575        };
3576        // A float in a general purpose register, or a number in a vector one, is a register the
3577        // machine has holding a type that is not kept there, and would need a move between the
3578        // files that nothing here makes yet.
3579        if on_x87(ty) || self.class_of(ty) != file {
3580            return Err(self.unsupported(inst));
3581        }
3582        let block = self.at.expect("a block is being filled");
3583        let span = self.source.span(inst);
3584        let mov = self.selector.frame.moves(file).expect("a class the target says how to move").mov;
3585        let mov = self.named(mov);
3586        let into = self.new_reg(result);
3587        self.out
3588            .build(block, mov)
3589            .at(span)
3590            .operand(mir::Operand::write(into, file))
3591            .operand(
3592                mir::Operand::read(mir::Reg::physical(held), file).with(Constraint::Fixed(held)),
3593            )
3594            .finish();
3595        Ok(())
3596    }
3597
3598    /// A conversion that converts nothing: the result is the operand under another type.
3599    ///
3600    /// `ptrtoint` and `inttoptr` at one width are the whole of this. An address on this machine is
3601    /// an integer as wide as the machine addresses, so a cast between the two changes what the
3602    /// type system calls the value and changes nothing about the value, and the register holding
3603    /// it is the register that already held it. The front end never writes either of them at any
3604    /// other width, because it widens or narrows around the cast rather than through it, so the
3605    /// two widths disagreeing here means the IR came from somewhere else and is refused rather
3606    /// than guessed at.
3607    ///
3608    /// Reading the operand first is what materializes it when it is a constant, which is the case
3609    /// that matters: a null pointer is an `inttoptr` of zero, and that zero has to reach a
3610    /// register before anything can call it an address.
3611    fn rename(&mut self, inst: Inst) -> Result<(), Unsupported> {
3612        let data = &self.source[inst];
3613        let [arg] = self.source[data.args] else { return Err(self.unsupported(inst)) };
3614        let result = data.first_result.ok_or_else(|| self.unsupported(inst))?;
3615        if !self.is_address_width(self.source[arg].ty)
3616            || !self.is_address_width(self.source[result].ty)
3617        {
3618            return Err(self.unsupported(inst));
3619        }
3620        let reg = self.reg_of(arg)?;
3621        self.regs[result.index()] = Some(reg);
3622        Ok(())
3623    }
3624
3625    /// One barrier, which on this machine is one instruction at the strongest ordering and no
3626    /// instruction at all at every other one.
3627    ///
3628    /// x86-64 is total store order, so the only reordering the machine does is a store followed by
3629    /// a load of a different address, and the only ordering that forbids that is sequential
3630    /// consistency. An acquire, a release and an acquire release fence are therefore already true
3631    /// of every program running here, and what a program wanted from writing one is that the
3632    /// compiler not move memory accesses across it. The optimizer has finished by the time this
3633    /// runs and nothing below reorders one access past another, so the constraint is already
3634    /// discharged and there is nothing to write.
3635    ///
3636    /// The strongest one is `mfence`, which is what gcc 16.2.0 writes for
3637    /// `__atomic_thread_fence(__ATOMIC_SEQ_CST)` and for `__sync_synchronize`. A locked instruction
3638    /// on the stack is faster on most parts and is what some compilers write instead; it is also a
3639    /// write to memory the program did not ask for, and the plain barrier is the one that says what
3640    /// it means.
3641    ///
3642    /// Written here by name rather than by a rule, for the same reason a `lea` of a symbol is:
3643    /// there is nothing in a barrier that a proof over bitvectors could discharge. It computes
3644    /// nothing, so there is no equality to state, and what makes it the right answer is the memory
3645    /// model, which the rule language cannot talk about.
3646    fn barrier(&mut self, inst: Inst) -> Result<(), Unsupported> {
3647        let Extra::Order(order) = self.source[inst].extra else {
3648            return Err(self.unsupported(inst));
3649        };
3650        // AArch64 is not total store order, so every ordering above relaxed is an instruction
3651        // there. An acquire fence only has to keep later accesses after earlier loads, which is
3652        // `dmb ishld`, and everything stronger is the full `dmb ish` gcc writes for it.
3653        let name = match order {
3654            MemOrder::NotAtomic | MemOrder::Relaxed => return Ok(()),
3655            MemOrder::Acquire if self.on_aarch64() => "fence_acquire",
3656            _ if self.on_aarch64() => self.selector.fence,
3657            MemOrder::SeqCst => self.selector.fence,
3658            _ => return Ok(()),
3659        };
3660        let block = self.at.expect("a block is being filled");
3661        let span = self.source.span(inst);
3662        let fence = self.named(name);
3663        self.out.build(block, fence).at(span).finish();
3664        Ok(())
3665    }
3666
3667    /// The instruction a program stops on, which is one byte pair and no operands.
3668    ///
3669    /// `ud2` is an opcode the manual promises will never be given a meaning, so a processor that
3670    /// reaches it raises the fault for an instruction it does not know, and on Linux that arrives
3671    /// at the program as `SIGILL`. That is what `__builtin_trap` is for: a stop that cannot be
3672    /// caught by anything the program installed for an ordinary error, cannot be returned from,
3673    /// and leaves the address of the fault in the core file.
3674    ///
3675    /// Why not a call to `abort`. It is two bytes against a call and a relocation, it needs no
3676    /// library, and it works in the places this one is written most, which are a kernel and a
3677    /// freestanding program that has no `abort` to call. gcc 16.2.0 writes `ud2` here too.
3678    fn trap(&mut self, inst: Inst) {
3679        let block = self.at.expect("a block is being filled");
3680        let span = self.source.span(inst);
3681        let stop = self.named(self.selector.trap);
3682        self.out.build(block, stop).at(span).finish();
3683    }
3684
3685    /// One hint that an address is about to be used, which is one instruction and no promise.
3686    ///
3687    /// Four instructions on this machine and the locality picks between them, which is what the
3688    /// number means: how much of the data will still be wanted after the access. None of it wanted
3689    /// is `prefetchnta`, which brings the line in without keeping it, and all of it wanted is
3690    /// `prefetcht0`, which brings it as close as the machine can. The two in between are the levels
3691    /// between those. Measured against gcc 16.2.0 on x86-64 rather than read off the manual: zero
3692    /// gives `prefetchnta`, one `prefetcht2`, two `prefetcht1` and three `prefetcht0`.
3693    ///
3694    /// Whether the access will write is not read on x86-64, and that is the machine rather than an
3695    /// omission. The write hint is `prefetchw`, which is not in the base instruction set, and gcc
3696    /// writes it only when the command line said the part has it. So a prefetch for a write is the
3697    /// same instruction as a prefetch for a read, which is what gcc 16.2.0 writes without
3698    /// `-mprfchw`. AArch64 has it in the base set, so there a write picks the four `pst` forms of
3699    /// `prfm` in place of the `pld` ones, at the same levels.
3700    ///
3701    /// The address goes in the addressing mode rather than in an operand, the way a store's does.
3702    /// It is built here as the plainest one there is, a register and nothing else, because what
3703    /// arrives is a value and folding an addition into the mode is a rule's job and no rule reaches
3704    /// this instruction. An address the program computed is therefore one `lea` or one add in front
3705    /// of this, which is what it would have been for the load the hint is about anyway.
3706    fn hint(&mut self, inst: Inst) -> Result<(), Unsupported> {
3707        let Extra::Prefetch(hint) = self.source[inst].extra else {
3708            return Err(self.unsupported(inst));
3709        };
3710        let args: Vec<Value> = self.source[self.source[inst].args].to_vec();
3711        let [address] = args[..] else { return Err(self.unsupported(inst)) };
3712        // AArch64 has the write hint in the base instruction set, and gcc 16.2.0 writes it there.
3713        let write = hint.write && self.on_aarch64();
3714        let name = match (hint.locality, write) {
3715            (0, false) => "prefetch_nta",
3716            (1, false) => "prefetch_t2",
3717            (2, false) => "prefetch_t1",
3718            (PrefetchHint::MOST, false) => "prefetch_t0",
3719            (0, true) => "prefetch_w_nta",
3720            (1, true) => "prefetch_w_t2",
3721            (2, true) => "prefetch_w_t1",
3722            (PrefetchHint::MOST, true) => "prefetch_w_t0",
3723            // Nothing else exists. The checker reads a locality outside the range as zero and the
3724            // verifier refuses one that got here another way, so this is a hint that was built
3725            // rather than checked, and the safe answer for a hint is to write no instruction.
3726            _ => return Err(self.unsupported(inst)),
3727        };
3728        let base = self.reg_of(address)?;
3729        let block = self.at.expect("a block is being filled");
3730        let opcode = self.named(name);
3731        self.out
3732            .build(block, opcode)
3733            .at(self.source.span(inst))
3734            .mem(mir::Mem::at(mir::Operand::read(base, self.gpr)))
3735            .finish();
3736        Ok(())
3737    }
3738
3739    /// One compare and exchange, which is the instruction every other atomic on this machine is
3740    /// built out of.
3741    ///
3742    /// What the IR asks for is: read what is at an address, compare it against a value the program
3743    /// expected, put a second value there if the two were equal, and say both what was read and
3744    /// whether the exchange happened. The machine has exactly that instruction, and the `lock` in
3745    /// front of it is what makes the whole of it one step as far as every other processor is
3746    /// concerned.
3747    ///
3748    /// The ordering is not read here, and that is the memory model rather than an omission. A
3749    /// locked instruction on x86-64 is a full barrier whatever the program asked for, so a relaxed
3750    /// compare and exchange and a sequentially consistent one are the same instruction, and there
3751    /// is nothing weaker to emit for the weaker orderings. The failure ordering is not read for the
3752    /// same reason.
3753    ///
3754    /// The two values it produces are why this is written by name. The one the program compares
3755    /// against and the one it gets back are both `rax`, which the instruction reads and writes
3756    /// without being told, and the table says so with a fixed constraint at each end rather than
3757    /// leaving the allocator to find out. The second value is the byte behind it, which is the zero
3758    /// flag read out by a `sete`, and it is a definition of the same instruction so that the
3759    /// allocator knows the two are live together and never gives the byte the register the answer
3760    /// is in.
3761    fn exchange(&mut self, inst: Inst) -> Result<(), Unsupported> {
3762        let args: Vec<Value> = self.source[self.source[inst].args].to_vec();
3763        let results: Vec<Value> = self.source[inst].results().collect();
3764        let [addr, expected, desired] = args[..] else { return Err(self.unsupported(inst)) };
3765        let [old, exchanged] = results[..] else { return Err(self.unsupported(inst)) };
3766        if self.on_aarch64() {
3767            return self.exchange_a64(inst, [addr, expected, desired], [old, exchanged]);
3768        }
3769
3770        // A value the machine can compare in one instruction, which is an integer or an address at
3771        // one of the four widths it has a compare and exchange for. Anything else is a type this
3772        // has no instruction for rather than a program that is wrong, and the front end refuses it
3773        // before ever getting here.
3774        let ty = self.source[old].ty;
3775        let bits = if ty.is_ptr() { ADDRESS_BITS } else { ty.bits() };
3776        if (!ty.is_int() && !ty.is_ptr()) || !matches!(bits, 8 | 16 | 32 | 64) {
3777            return Err(self.unsupported(inst));
3778        }
3779
3780        let base = self.reg_of(addr)?;
3781        let want = self.reg_of(expected)?;
3782        let put = self.reg_of(desired)?;
3783        let got = self.new_reg(old);
3784        let flag = self.new_reg(exchanged);
3785
3786        let name = format!("cmpxchg_{bits}");
3787        let descs = self.selector.operands(&name).ok_or_else(|| self.unsupported(inst))?;
3788        let block = self.at.expect("a block is being filled");
3789        let opcode = self.named(&name);
3790        let (span, flags) = (self.source.span(inst), self.carried(inst));
3791        let mut build = self.out.build(block, opcode).at(span).flags(flags);
3792        for (desc, reg) in descs.iter().zip([got, flag, want, put]) {
3793            let operand = mir::Operand {
3794                reg,
3795                class: desc.class,
3796                role: desc.role,
3797                constraint: desc.constraint,
3798            };
3799            build = build.operand(operand);
3800        }
3801        build.mem(mir::Mem::at(mir::Operand::read(base, self.gpr))).finish();
3802        Ok(())
3803    }
3804
3805    /// One read modify write, for the three operations this machine does in a single instruction.
3806    ///
3807    /// What the IR asks for is: read what is at an address, do something to it, put the answer back,
3808    /// say what was there before, and let nothing get between the three steps. The machine has
3809    /// `xchg` for putting a value there and `lock xadd` for adding one, and both leave what they
3810    /// found in the register the operand arrived in, which is why the value that comes back and the
3811    /// value that went in are one register here.
3812    ///
3813    /// A subtraction is the add over the negated operand, which is right at every width because the
3814    /// machine's arithmetic wraps and negating then adding is subtracting in two's complement
3815    /// whatever the operands were. The negate is a separate instruction in front, over a register of
3816    /// its own, so that the value the program handed over is not the one written on: an operand may
3817    /// be live after this and a program that read it again would read the negation.
3818    ///
3819    /// The ordering is not read, for the reason the compare and exchange beside this does not read
3820    /// it. `xchg` with memory locks the bus whether it is asked to or not and `lock xadd` is asked
3821    /// to, so both are full barriers on this machine and there is nothing weaker to fall to.
3822    ///
3823    /// Eight of the other ten never arrive, because `crate::retry` turned each of them into a loop
3824    /// around a compare and exchange before anything here saw it. The two that do arrive are the
3825    /// ones on floating values, and they are refused: a compare and exchange of a float wants the
3826    /// value carried through an integer of the same width, and an eighty bit float has no such
3827    /// width. Neither family of builtins can write one yet either, so a program that reaches this
3828    /// refusal is a program that reached an unimplemented builtin first.
3829    fn modify(&mut self, inst: Inst) -> Result<(), Unsupported> {
3830        let Extra::Rmw(op, _) = self.source[inst].extra else {
3831            return Err(self.unsupported(inst));
3832        };
3833        let args: Vec<Value> = self.source[self.source[inst].args].to_vec();
3834        let [addr, operand] = args[..] else { return Err(self.unsupported(inst)) };
3835        let old = self.source[inst].first_result.ok_or_else(|| self.unsupported(inst))?;
3836
3837        // A value the machine can exchange in one instruction, which is an integer at one of the
3838        // four widths it has these for. A pointer arrives as an address, so it is an integer by the
3839        // time it is here, and anything else is a type this has no instruction for.
3840        let ty = self.source[old].ty;
3841        if !ty.is_int() || !matches!(ty.bits(), 8 | 16 | 32 | 64) {
3842            return Err(self.unsupported(inst));
3843        }
3844        if self.on_aarch64() {
3845            return self.modify_a64(inst, op, [addr, operand], old);
3846        }
3847        let name = match op {
3848            RmwOp::Xchg => format!("xchg_{}", ty.bits()),
3849            RmwOp::Add | RmwOp::Sub => format!("xadd_{}", ty.bits()),
3850            _ => return Err(self.unsupported(inst)),
3851        };
3852
3853        let base = self.reg_of(addr)?;
3854        let mut put = self.reg_of(operand)?;
3855        let block = self.at.expect("a block is being filled");
3856        let span = self.source.span(inst);
3857        if op == RmwOp::Sub {
3858            let negated = self.out.new_vreg(self.gpr);
3859            let negate = self.named(&format!("neg_r_{}", ty.bits()));
3860            let descs = self
3861                .selector
3862                .operands(&format!("neg_r_{}", ty.bits()))
3863                .ok_or_else(|| self.unsupported(inst))?;
3864            let mut build = self.out.build(block, negate).at(span);
3865            for (desc, reg) in descs.iter().zip([negated, put]) {
3866                build = build.operand(mir::Operand {
3867                    reg,
3868                    class: desc.class,
3869                    role: desc.role,
3870                    constraint: desc.constraint,
3871                });
3872            }
3873            build.finish();
3874            put = negated;
3875        }
3876
3877        let got = self.new_reg(old);
3878        let descs = self.selector.operands(&name).ok_or_else(|| self.unsupported(inst))?;
3879        let opcode = self.named(&name);
3880        let flags = self.carried(inst);
3881        let mut build = self.out.build(block, opcode).at(span).flags(flags);
3882        for (desc, reg) in descs.iter().zip([got, put]) {
3883            build = build.operand(mir::Operand {
3884                reg,
3885                class: desc.class,
3886                role: desc.role,
3887                constraint: desc.constraint,
3888            });
3889        }
3890        build.mem(mir::Mem::at(mir::Operand::read(base, self.gpr))).finish();
3891        Ok(())
3892    }
3893
3894    /// The width an AArch64 atomic works at, which is an integer or an address of one of the four
3895    /// widths the exclusive loads and stores have. Anything else is refused.
3896    fn atomic_bits(&self, inst: Inst, ty: Type) -> Result<u32, Unsupported> {
3897        let bits = if ty.is_ptr() { ADDRESS_BITS } else { ty.bits() };
3898        if (!ty.is_int() && !ty.is_ptr()) || !matches!(bits, 8 | 16 | 32 | 64) {
3899            return Err(self.unsupported(inst));
3900        }
3901        Ok(bits)
3902    }
3903
3904    /// One instruction by name, with its operands in the order the table lists them.
3905    fn written_as(&mut self, inst: Inst, name: &str, regs: &[mir::Reg]) -> Result<(), Unsupported> {
3906        let descs = self.selector.operands(name).ok_or_else(|| self.unsupported(inst))?;
3907        if descs.len() != regs.len() {
3908            return Err(self.unsupported(inst));
3909        }
3910        let block = self.at.expect("a block is being filled");
3911        let opcode = self.named(name);
3912        let (span, flags) = (self.source.span(inst), self.carried(inst));
3913        let mut build = self.out.build(block, opcode).at(span).flags(flags);
3914        for (desc, &reg) in descs.iter().zip(regs) {
3915            build = build.operand(mir::Operand {
3916                reg,
3917                class: desc.class,
3918                role: desc.role,
3919                constraint: desc.constraint,
3920            });
3921        }
3922        build.finish();
3923        Ok(())
3924    }
3925
3926    /// An acquiring load or a releasing store on AArch64, which is `ldar` or `stlr`.
3927    ///
3928    /// Only a relaxed access became the plain one above this, so what arrives is acquire or
3929    /// stronger for a load and release or stronger for a store. `ldar` and `stlr` are also
3930    /// sequentially consistent with each other, which is why the strongest ordering needs no fence
3931    /// on either side, and is what gcc 16.2.0 writes for all of them.
3932    fn ordered(&mut self, inst: Inst) -> Result<(), Unsupported> {
3933        let args: Vec<Value> = self.source[self.source[inst].args].to_vec();
3934        if self.source[inst].opcode == Opcode::AtomicLoad {
3935            let [addr] = args[..] else { return Err(self.unsupported(inst)) };
3936            let result = self.source[inst].first_result.ok_or_else(|| self.unsupported(inst))?;
3937            let bits = self.atomic_bits(inst, self.source[result].ty)?;
3938            let base = self.reg_of(addr)?;
3939            let got = self.new_reg(result);
3940            return self.written_as(inst, &format!("ldar_{bits}"), &[got, base]);
3941        }
3942        let [value, addr] = args[..] else { return Err(self.unsupported(inst)) };
3943        let bits = self.atomic_bits(inst, self.source[value].ty)?;
3944        let put = self.reg_of(value)?;
3945        let base = self.reg_of(addr)?;
3946        self.written_as(inst, &format!("stlr_{bits}"), &[put, base])
3947    }
3948
3949    /// A compare and exchange on AArch64, which is a loop of an exclusive load and store.
3950    ///
3951    /// The loop is one instruction as far as everything below is concerned, so that nothing can
3952    /// be spilled or reloaded between the two exclusive accesses, which would lose the reservation
3953    /// on some parts every time. Its definitions are all early, since they are written before the
3954    /// last read. The acquiring and releasing forms are used whatever the ordering, which is what
3955    /// gcc writes at the strongest one and is never wrong at a weaker one. The yes or no comes out
3956    /// of the status register the store wrote, read as a flag after the loop.
3957    fn exchange_a64(
3958        &mut self,
3959        inst: Inst,
3960        [addr, expected, desired]: [Value; 3],
3961        [old, exchanged]: [Value; 2],
3962    ) -> Result<(), Unsupported> {
3963        let bits = self.atomic_bits(inst, self.source[old].ty)?;
3964        let base = self.reg_of(addr)?;
3965        let want = self.reg_of(expected)?;
3966        let put = self.reg_of(desired)?;
3967        let got = self.new_reg(old);
3968        let flag = self.new_reg(exchanged);
3969        self.written_as(inst, &format!("cmpxchg_{bits}"), &[got, flag, base, want, put])
3970    }
3971
3972    /// A read modify write on AArch64, for the three operations that reach here, each a loop of
3973    /// an exclusive load and store for the reason the compare and exchange above is.
3974    fn modify_a64(
3975        &mut self,
3976        inst: Inst,
3977        op: RmwOp,
3978        [addr, operand]: [Value; 2],
3979        old: Value,
3980    ) -> Result<(), Unsupported> {
3981        let bits = self.atomic_bits(inst, self.source[old].ty)?;
3982        let base = self.reg_of(addr)?;
3983        let put = self.reg_of(operand)?;
3984        let got = self.new_reg(old);
3985        let status = self.out.new_vreg(self.gpr);
3986        match op {
3987            RmwOp::Xchg => {
3988                self.written_as(inst, &format!("xchg_{bits}"), &[got, status, base, put])
3989            }
3990            RmwOp::Add | RmwOp::Sub => {
3991                let name = if op == RmwOp::Add { "xadd" } else { "xsub" };
3992                let new = self.out.new_vreg(self.gpr);
3993                self.written_as(inst, &format!("{name}_{bits}"), &[got, new, status, base, put])
3994            }
3995            _ => Err(self.unsupported(inst)),
3996        }
3997    }
3998
3999    /// One `asm` statement.
4000    ///
4001    /// An empty template is most of the inline assembly in a test suite, and it is not a corner
4002    /// case somebody wrote by accident. A program that wants a value computed where it stands, or a
4003    /// loop the optimizer must not touch, writes `asm volatile ("" : : : "memory")`, and forty
4004    /// years of bug reports about optimizers are full of them. What such a statement asks for is
4005    /// the barrier and the operand places, and no instructions at all.
4006    ///
4007    /// So the operands are the half that is always real: a constraint says where a value has to be,
4008    /// and where it has to be is still true when the template between them is empty.
4009    ///
4010    /// What the constraints ask for, on an empty template, is only ever that two operands share a
4011    /// place. Nothing reads a register no text names, so `"r"` on its own asks for a register and
4012    /// no particular one, and any register at all answers it. A matching constraint is different,
4013    /// because it says the output the assembly leaves is the place the input arrived in, and with
4014    /// no instructions between them that is the input unchanged. So it is a rename and not a move:
4015    /// the value is already in a register and the result is that register.
4016    ///
4017    /// An output nothing is tied to and no instruction writes is whatever the assembly left there,
4018    /// which for a template that writes nothing is whatever was in the register. That is a value
4019    /// the program is not entitled to, and this writes a zero rather than reading one, because the
4020    /// allocator has to be given a definition before a use whatever the program is entitled to.
4021    ///
4022    /// # A template with instructions in it
4023    ///
4024    /// [`x86_64::read`] turns the text into the opcodes this backend already has, which is what
4025    /// `spec/11-asm-objects-debug.md` section 11.1 asks for: the machine is described once, and an
4026    /// instruction a program wrote is looked up in that description rather than copied through to
4027    /// an assembler that has one of its own. So nothing here assembles anything. What it does is
4028    /// put the statement's operands where the opcode holds them, and from there an `asm` statement
4029    /// is ordinary machine code: the allocator picks the registers, the listing and the object file
4030    /// are written from the same table as every other instruction, and a spill around one works
4031    /// because there is nothing left about it for a spill to get wrong.
4032    ///
4033    /// A register the template named in its own text is the one thing in there that is nobody's
4034    /// operand, and it is placed as itself. See [`Self::itself`] for why that is safer here than
4035    /// the thing gcc does, which is to copy the name out and leave the allocator none the wiser.
4036    ///
4037    /// Two things are refused, both for one reason, which is that placing them by a guess gives a
4038    /// program that assembles into something other than what it says.
4039    ///
4040    /// An output the template writes more than once, which is one place with two definitions in it,
4041    /// and the machine IR between here and the allocator has one definition per register by
4042    /// construction. An output tied to an input and written once is not that: it is two registers
4043    /// the description ties together, which is what [`Place`] is about.
4044    ///
4045    /// An operand read where the opcode writes, or written where it reads. An output that has not
4046    /// been written yet is not a value, and an input the assembly writes over is a value something
4047    /// else may still be using.
4048    ///
4049    /// # A register the instruction uses without being told
4050    ///
4051    /// An instruction may reach a register its text does not name, and `cpuid` is all of them at
4052    /// once: the leaf goes in `eax`, the subleaf in `ecx`, and the answer comes back in all four
4053    /// registers. The description holds every bit of that already, so what is left is to say which
4054    /// of the statement's operands is in each of those registers, and the constraint letter is the
4055    /// one thing in an assembly statement that says it. `"=a"` is an output in `rax` and `"c"` is
4056    /// an input in `rcx`, which is why a program writing `cpuid` writes its constraints that way
4057    /// and has no choice about it.
4058    ///
4059    /// A register no letter named is one the statement put nothing in, and that is the usual case
4060    /// rather than an unusual one, since an instruction that answers four questions is written by
4061    /// programs that asked one. A write of one is the register being destroyed and gets a register
4062    /// of its own, which is what tells the allocator to keep everything else out of it. A read of
4063    /// one is a register the instruction looks at and the program never filled, which gets a zero
4064    /// for the reason [`Self::undefined`] gives.
4065    ///
4066    /// # The clobber list
4067    ///
4068    /// Read now, as the registers it names being written by every instruction of the template. By
4069    /// every one rather than by one of them, because the list says the assembly as a whole leaves
4070    /// them ruined and nothing here knows which line did it. Every entry has to be a register this
4071    /// machine has a name for or the statement is refused, since a name nobody read is a register
4072    /// nobody is keeping out of.
4073    ///
4074    /// `memory` and `cc` are the two entries that are not registers and both are skipped. `memory`
4075    /// says the assembly touches storage, which is already true of every `asm` this writes and is
4076    /// nothing a register list could hold. `cc` says it ruins the condition flags, and the flag
4077    /// tracking already has that from the instructions the template was read into, since it takes
4078    /// every instruction it does not recognize as writing them and every instruction here is one
4079    /// this machine describes. `flags` is the name gcc's own register table gives the same thing on
4080    /// this machine, so a program writing it has written `cc` and is read that way: tcc's
4081    /// `tests/tcctest.c` lists both on one statement.
4082    ///
4083    /// A clobber the instruction already writes is left off it. `cpuid` writes all four registers
4084    /// by description, and a statement listing three of them as clobbers as well is saying the
4085    /// same thing twice, which the allocator would read as one register with two definitions.
4086    ///
4087    /// On a template with nothing in it the list is ignored, as it was before, since a template
4088    /// with no instructions ruins nothing whatever it said about what it ruins.
4089    fn assembly(&mut self, inst: Inst) -> Result<(), Unsupported> {
4090        let data = &self.source[inst];
4091        let Extra::Asm(asm) = data.extra else { return Err(self.unsupported(inst)) };
4092        let info = self.source[asm];
4093        if self.jumps_from_text(inst) {
4094            return Err(Unsupported::Assembly { inst, refused: Written::Goto });
4095        }
4096        let refused = || Unsupported::Assembly { inst, refused: Written::Operand };
4097
4098        let constraints = self.names.resolve(info.constraints).to_string();
4099        let results: Vec<Value> = data.results().collect();
4100        let operands = AsmOperands::read(&constraints, &results, &self.source[data.args])
4101            .ok_or_else(refused)?;
4102        let list: Vec<AsmOperand<'_>> = operands.iter().copied().collect();
4103
4104        // Read after the constraints and not before them, because a mnemonic whose suffix the
4105        // program left off is read at the width of the operands it names, and the operands are
4106        // what the constraints are a list of.
4107        let widths: Vec<Option<x86_64::Width>> = list
4108            .iter()
4109            .map(|operand| {
4110                let ty = self.source[operand.result.or(operand.value)?].ty;
4111                if !ty.is_scalar() {
4112                    return None;
4113                }
4114                x86_64::Width::of_bits(held_bits(ty))
4115            })
4116            .collect();
4117        // An operand in memory is an address the statement holds and an object the template names,
4118        // so the reader is told which ones those are and spells `%0` for one as the object.
4119        let memory: Vec<bool> = list.iter().map(|operand| operand.memory).collect();
4120        let template = self.names.resolve(info.template).to_string();
4121        // A clobber list naming a vector register goes the way a template this cannot read does.
4122        // The instructions read here are all in the general purpose file, and what keeps the text
4123        // already takes every vector register a call may use away from the allocator across it.
4124        let clobbers = self.names.resolve(info.clobbers);
4125        if clobbers.split(',').any(|entry| vector_named(entry).is_some()) {
4126            return self.kept(inst, &template, &list, &widths, &memory);
4127        }
4128        let steps = if template.trim().is_empty() {
4129            Vec::new()
4130        } else {
4131            match x86_64::read_in(&template, &widths, &memory) {
4132                Some(steps) => steps,
4133                None => return self.kept(inst, &template, &list, &widths, &memory),
4134            }
4135        };
4136
4137        // Which operands the template writes, counted before anything is placed, because the answer
4138        // decides where each of the three below comes from and one instruction may name an operand
4139        // that a later one writes. Which of them any instruction puts in a register at all is
4140        // counted in the same walk, since an operand no instruction reaches that way is one nothing
4141        // has to put anywhere: a constant a template names only as the distance into an address is
4142        // written into the instruction, and a register holding a copy of it would be one nobody
4143        // reads. An operand the address is counted from is reached that way and is counted here for
4144        // that reason, because the walk below it is over the opcode's operands and an address is
4145        // not one of those.
4146        //
4147        // Whether any instruction reads an operand an instruction above it wrote is counted in the
4148        // same walk too. Such a template is one whose instructions have to be written in order with
4149        // each read taken from wherever the last write left the operand, which is what
4150        // [`Self::woven`] does, and so is one that writes an operand twice.
4151        let mut writes = vec![0usize; list.len()];
4152        let mut reads = vec![false; list.len()];
4153        let mut held = vec![false; list.len()];
4154        let mut after = false;
4155        for step in &steps {
4156            // A call out of the template writes every register the convention lets the callee
4157            // leave anything in, and an output pinned to one of those is written by it.
4158            if let x86_64::Step::Call { .. } = step {
4159                for index in self.lost(&list).into_iter().filter_map(|(_, _, index)| index) {
4160                    *writes.get_mut(index).ok_or_else(refused)? += 1;
4161                }
4162                continue;
4163            }
4164            let x86_64::Step::Line(line) = step else { continue };
4165            match line.at.and_then(|at| at.base) {
4166                Some(x86_64::Piece::Operand { index, .. }) => {
4167                    *held.get_mut(index).ok_or_else(refused)? = true;
4168                    after |= writes[index] > 0;
4169                }
4170                Some(x86_64::Piece::Reg { reg, .. }) => {
4171                    if let Some(index) = bound(&list, reg, Role::Use) {
4172                        *held.get_mut(index).ok_or_else(refused)? = true;
4173                        after |= writes[index] > 0;
4174                    }
4175                }
4176                _ => {}
4177            }
4178            let mut written = Vec::new();
4179            let form = x86_64::form(line.opcode).ok_or_else(refused)?;
4180            // Which registers the instruction reaches, asked the same way it is asked again when
4181            // the instruction is written. See [`Self::lettered`] for the one opcode whose answer
4182            // comes from the constraint letters rather than from the description.
4183            let lettered = (line.opcode == x86_64::LITERAL).then(|| self.lettered(&list));
4184            let (described, pieces) = match &lettered {
4185                Some((described, pieces)) => (described.as_slice(), pieces.as_slice()),
4186                None => (form.operands(), line.operands.as_slice()),
4187            };
4188            for (desc, piece) in described.iter().zip(pieces) {
4189                // An operand the instruction reaches without its text saying so is the statement's
4190                // only when a constraint letter put something there. One that is nobody's writes
4191                // nothing of the program's, so it is counted nowhere and is dealt with where it is
4192                // placed.
4193                let index = match *piece {
4194                    x86_64::Piece::Operand { index, .. } => index,
4195                    x86_64::Piece::Implicit { reg } => match bound(&list, reg, desc.role) {
4196                        Some(index) => index,
4197                        None => continue,
4198                    },
4199                    x86_64::Piece::Reg { reg, .. } => match bound(&list, reg, desc.role) {
4200                        Some(index) => index,
4201                        None => continue,
4202                    },
4203                };
4204                *held.get_mut(index).ok_or_else(refused)? = true;
4205                if matches!(desc.role, Role::Def | Role::EarlyDef) {
4206                    written.push(index);
4207                } else {
4208                    *reads.get_mut(index).ok_or_else(refused)? = true;
4209                    after |= writes[index] > 0;
4210                }
4211            }
4212            for index in written {
4213                *writes.get_mut(index).ok_or_else(refused)? += 1;
4214            }
4215        }
4216        let woven = after
4217            || writes.iter().any(|&count| count > 1)
4218            || steps.iter().any(|step| !matches!(step, x86_64::Step::Line(_)));
4219
4220        // Where every operand is. Worked out in full before the first instruction is written, since
4221        // reading a value may be what puts it in a register in the first place, and that has to
4222        // happen in front of the assembly rather than in the middle of it.
4223        let mut places: Vec<Place> = vec![Place::default(); list.len()];
4224        for (index, operand) in list.iter().copied().enumerate() {
4225            let Some(result) = operand.result else {
4226                // An input, or an output the assembly was handed the address of, and both are a
4227                // value that arrives in a register and is read out of it, unless no instruction of
4228                // the template reads it out of one.
4229                let value = operand.value.ok_or_else(refused)?;
4230                if held[index] {
4231                    places[index].read = Some(self.reg_of(value)?);
4232                }
4233                continue;
4234            };
4235            let ty = self.source[result].ty;
4236            if on_x87(ty) {
4237                return Err(refused());
4238            }
4239            let tied = operands.tied_to(index);
4240            if let Some(from) = tied {
4241                if self.class_of(self.source[from].ty) != self.class_of(ty) {
4242                    return Err(refused());
4243                }
4244                places[index].read = Some(self.reg_of(from)?);
4245            }
4246            if writes[index] > 0 {
4247                places[index].write = Some(self.new_reg(result));
4248                continue;
4249            }
4250            match tied {
4251                // The place the input arrived in, which the assembly wrote nothing over. One
4252                // register, so this is a rename rather than a move.
4253                Some(_) => {
4254                    let reg = places[index].read.ok_or_else(refused)?;
4255                    self.regs[result.index()] = Some(reg);
4256                    places[index].write = Some(reg);
4257                }
4258                None => {
4259                    self.undefined(inst, result)?;
4260                    places[index].write = self.regs[result.index()];
4261                }
4262            }
4263        }
4264
4265        // An output an instruction of the template also reads, which the statement said nothing
4266        // about because an output is what a statement says the other thing about. What it holds
4267        // there is undefined, and a program writing one means it: `sbb %0, %0` in libgmp's
4268        // `add_mssaaaa` subtracts a register from itself and is asking for the borrow bit rather
4269        // than for the number, so whatever the register held, the answer is the same. Undefined is
4270        // not the same as absent though, since the allocator is owed a definition in front of every
4271        // use, so it gets the zero an output nothing wrote gets and for the same reason.
4272        //
4273        // Unless an input could have been in the same register, in which case gcc's allocator puts
4274        // it there whenever it can and a program may have been written against that. tcc's test of
4275        // a call from a template reads its output `"=a" (s)` to pass `"r" (str)` to `getenv`, which
4276        // is only the string because gcc gave the two of them `rax`. So an output nothing has
4277        // written yet reads the one input that could share its place, when there is exactly one.
4278        // One written `&` is written before the inputs are read and shares nothing.
4279        for index in 0..list.len() {
4280            if !reads[index] || places[index].read.is_some() || places[index].write.is_none() {
4281                continue;
4282            }
4283            let reg = match self.shared(&list, index) {
4284                Some(value) => self.reg_of(value)?,
4285                None => self.seeded(inst, list[index])?,
4286            };
4287            places[index].read = Some(reg);
4288        }
4289
4290        // Worked out once for the whole template, since the list is one list and every instruction
4291        // of the template gets it. Not worked out at all for a template with no instructions, which
4292        // is where there is nothing for it to go on.
4293        let clobbers = self.names.resolve(info.clobbers).to_string();
4294        let clobbered =
4295            if steps.is_empty() { Vec::new() } else { Self::clobbered(inst, &clobbers)? };
4296
4297        // A template with a label in it is not one run of instructions, and what it is instead is
4298        // in [`Self::woven`], which is also where a template goes whose instructions read what the
4299        // ones above them wrote. Every other template is what it has always been, which is every
4300        // instruction of it written into the block the statement stands in.
4301        if woven {
4302            return self.woven(inst, &steps, &mut places, &list, &clobbered, &writes);
4303        }
4304        for step in &steps {
4305            let x86_64::Step::Line(line) = step else { continue };
4306            self.instruction(inst, line, &places, &list, &clobbered)?;
4307        }
4308        Ok(())
4309    }
4310
4311    /// A template the reader could not take apart, kept as its text. See [`x86_64::Form::Template`].
4312    ///
4313    /// What the text names is spelled into it here, the way gcc prints it into its listing: a
4314    /// constant as `$5`, or as `5` under the `c` modifier, and the address of a name as the name.
4315    /// An object in memory is the one thing that cannot be spelled yet, since where it is depends on
4316    /// registers nothing has chosen, so it is left as a hole the writer fills and its address is the
4317    /// instruction's memory operand. One is all an instruction has room for, and every template this
4318    /// has met names one at most. A template that names an operand by name rather than by number is
4319    /// refused for now.
4320    ///
4321    /// # An operand in a register
4322    ///
4323    /// Which register is not known until the allocator has run, and the text is written down before
4324    /// then, so an operand in a register is a hole too. It names the instruction's own operand and
4325    /// the width the modifier asked for, or the width of the operand's type when there was none,
4326    /// and the writer spells whatever register the operand ended up in. What the text writes goes
4327    /// in first as definitions and what it reads goes in last as uses, with the registers below in
4328    /// between, so the allocator sees the statement as one instruction with every operand said. An
4329    /// output tied to an input, by `+` or by a number, reuses the input's register, and one written
4330    /// `&` is written early. Anything wider than a general purpose register is refused.
4331    ///
4332    /// A statement written with no colons is basic assembly, where `%` is a character like any
4333    /// other and a register is written `%eax`. The front end keeps no mark of which kind a statement
4334    /// was, so one with no operands and no clobbers is read as basic, which is what gcc would do for
4335    /// every such template but one written with empty colons around it.
4336    ///
4337    /// The registers a call may write are taken as written, see below for why.
4338    fn kept(
4339        &mut self,
4340        inst: Inst,
4341        template: &str,
4342        list: &[AsmOperand<'_>],
4343        widths: &[Option<x86_64::Width>],
4344        memory: &[bool],
4345    ) -> Result<(), Unsupported> {
4346        // Refused as the template it is, since keeping it is what was tried after reading it
4347        // failed, and what could not be kept is what it names rather than any one operand.
4348        let refused = || Unsupported::Assembly { inst, refused: Written::Template };
4349        let data = &self.source[inst];
4350        let Extra::Asm(asm) = data.extra else { return Err(self.unsupported(inst)) };
4351        let clobbers = self.names.resolve(self.source[asm].clobbers).to_string();
4352        let basic = list.is_empty() && clobbers.trim().is_empty();
4353
4354        // Every register a call may leave anything in, as well as the ones the list names. The
4355        // text can write any register it likes without saying so, and tcc's tests do: gcc gets
4356        // away with that at `-O0` because nothing lives in a register between two statements
4357        // there, and taking these away from the allocator across the template is what gives the
4358        // same answer here. Nothing is written to them by this, so a register one template leaves
4359        // a value in is still holding it when the next template reads it.
4360        let a64 = self.on_aarch64();
4361        let mut clobbered: Vec<(PhysReg, RegClass)> =
4362            self.lost(list).into_iter().map(|(reg, class, _)| (reg, class)).collect();
4363        let named = if a64 {
4364            Self::clobbered_a64(inst, &clobbers)?
4365        } else {
4366            Self::clobbered_x86(inst, &clobbers, self.gpr, self.conv.sse_class)?
4367        };
4368        for &(reg, class) in &named {
4369            if !clobbered.iter().any(|&(had, of)| had == reg && of == class) {
4370                clobbered.push((reg, class));
4371            }
4372        }
4373
4374        // The file each operand is in. On AArch64 `w` is a floating point or vector register and an
4375        // input tied to an output is in that output's file. A value whose type puts it in the other
4376        // file would need a move into this one first, which gcc makes and this does not yet, so
4377        // that is refused below.
4378        let mut files = vec![self.gpr; list.len()];
4379        if a64 {
4380            let constraints = self.names.resolve(self.source[asm].constraints);
4381            for (file, entry) in files.iter_mut().zip(constraints.split(',')) {
4382                if vector_letter(entry) {
4383                    *file = self.conv.sse_class;
4384                }
4385            }
4386            for index in 0..list.len() {
4387                if let Some(&file) = list[index].tied.and_then(|output| files.get(output)) {
4388                    files[index] = file;
4389                }
4390            }
4391        }
4392        let pins: Vec<_> = list.iter().map(|operand| self.pinned_here(operand)).collect();
4393        let pin = |index: usize, file: RegClass| match pins[index] {
4394            Some((at, class)) if class == file => Ok(Some(Constraint::Fixed(at))),
4395            Some(_) => Err(refused()),
4396            None => Ok(None),
4397        };
4398
4399        // The operands in a register, as the instruction's own. An input the text is handed as a
4400        // constant or as the address of a name is spelled into the text instead, when its
4401        // constraint allows a constant at all and no output is tied to it. `"a" (0x1234)` is a
4402        // register holding the number, the way gcc loads it, since the text may ask for `%h0`.
4403        let mut defs: Vec<mir::Operand> = Vec::new();
4404        let mut uses: Vec<mir::Operand> = Vec::new();
4405        let mut def_of: Vec<Option<usize>> = vec![None; list.len()];
4406        let mut use_of: Vec<Option<usize>> = vec![None; list.len()];
4407        if !basic {
4408            for (index, operand) in list.iter().enumerate() {
4409                let Some(result) = operand.result else { continue };
4410                let (ty, file) = (self.source[result].ty, files[index]);
4411                if on_x87(ty) || self.class_of(ty) != file {
4412                    return Err(refused());
4413                }
4414                let reg = self.new_reg(result);
4415                let written = if operand.early {
4416                    mir::Operand::write_early(reg, file)
4417                } else {
4418                    mir::Operand::write(reg, file)
4419                };
4420                def_of[index] = Some(defs.len());
4421                defs.push(match pin(index, file)? {
4422                    Some(fixed) => written.with(fixed),
4423                    None => written,
4424                });
4425            }
4426            for (index, operand) in list.iter().enumerate() {
4427                let Some(value) = operand.value else { continue };
4428                let spelled = operand.result.is_none()
4429                    && operand.tied.is_none()
4430                    && operand.immediate
4431                    && (self.number(value).is_some() || self.named_address(value).is_some());
4432                // An operand in memory is spelled on AArch64 as the register its address is in,
4433                // which is `[x3]` and is an address every instruction that takes one reads.
4434                if (operand.memory && !a64) || spelled {
4435                    continue;
4436                }
4437                let (ty, file) = (self.source[value].ty, files[index]);
4438                if on_x87(ty) || self.class_of(ty) != file {
4439                    return Err(refused());
4440                }
4441                let read = mir::Operand::read(self.reg_of(value)?, file);
4442                use_of[index] = Some(uses.len());
4443                uses.push(match pin(index, file)? {
4444                    Some(fixed) => read.with(fixed),
4445                    None => read,
4446                });
4447            }
4448        }
4449        // Every register a call may write is more than a template can give up when it has more
4450        // operands in registers than the convention keeps across a call. `sodium_sub` in
4451        // libsodium's `utils.c` is one: eight outputs written early and two inputs pinned, against
4452        // the five registers SysV preserves, so an output has nowhere to go and nothing is left to
4453        // carry one to its slot either. gcc gives that template ten registers, and a program that
4454        // writes a register it did not name is only owed what gcc would have done, which here is
4455        // one of the ten. So the registers taken as written without being named are handed back,
4456        // from the end of the convention's order, until the operands fit in what is left. One the
4457        // list names or an operand is pinned to stays where it is. What is left does not count the
4458        // two scratch registers the allocator holds back, since no operand is ever given one of
4459        // those, and counting them left two outputs short above -O0 with nothing to carry them.
4460        let fixed_to: Vec<PhysReg> = defs
4461            .iter()
4462            .chain(&uses)
4463            .filter_map(|operand| match operand.constraint {
4464                Constraint::Fixed(at) => Some(at),
4465                _ => None,
4466            })
4467            .collect();
4468        let wanted = defs.iter().chain(&uses).count() - fixed_to.len();
4469        let int = self.conv.int_class;
4470        let held: &[PhysReg] =
4471            if a64 { &crate::pipeline::AARCH64_SCRATCH } else { &crate::pipeline::SCRATCH };
4472        let free = |clobbered: &[(PhysReg, RegClass)]| {
4473            self.conv
4474                .int_order
4475                .iter()
4476                .filter(|&&reg| {
4477                    !held.contains(&reg)
4478                        && !fixed_to.contains(&reg)
4479                        && !clobbered.contains(&(reg, int))
4480                })
4481                .count()
4482        };
4483        while free(&clobbered) < wanted {
4484            let Some(at) = clobbered.iter().rposition(|&(reg, class)| {
4485                class == int && !named.contains(&(reg, class)) && !fixed_to.contains(&reg)
4486            }) else {
4487                break;
4488            };
4489            clobbered.remove(at);
4490        }
4491
4492        // A register an output is pinned to is that output's definition and not a clobber as well.
4493        // One an input is pinned to is written as the instruction finishes, the way a call writes
4494        // the register its argument came in, and every other one is written early, since the text
4495        // may write it before it has read its inputs and an input must not be in it.
4496        let mut written: Vec<mir::Operand> = Vec::new();
4497        for (reg, class) in clobbered {
4498            let fixed = |operand: &mir::Operand| {
4499                operand.class == class && operand.constraint == Constraint::Fixed(reg)
4500            };
4501            if defs.iter().any(fixed) {
4502                continue;
4503            }
4504            let reg = mir::Reg::physical(reg);
4505            written.push(if uses.iter().any(fixed) {
4506                mir::Operand::write(reg, class)
4507            } else {
4508                mir::Operand::write_early(reg, class)
4509            });
4510        }
4511        // An output tied to an input is one register, which the definition says by reusing the
4512        // use, or by both being fixed to the same one when the output was pinned.
4513        //
4514        // A reused register is kept from every other input already, since the allocator counts the
4515        // output as taken from where the instruction reads. So `+&` asks for nothing more than `+`,
4516        // and saying it as an early write as well costs a register: the allocator only hands an
4517        // output the register of the input it reuses when the output starts at the instruction, and
4518        // an early one starts a point sooner, so it gets one of its own and a copy in front. Eleven
4519        // operands written that way in xz's range decoder need seventeen registers and run out. The
4520        // one case where `&` still means something is an input reading the same value as the one
4521        // tied, which would be in the same register and read after the output was written.
4522        let first_use = defs.len() + written.len();
4523        for (output, operand) in list.iter().enumerate() {
4524            let Some(def) = def_of[output] else { continue };
4525            let input = if operand.value.is_some() {
4526                Some(output)
4527            } else {
4528                list.iter().position(|entry| entry.tied == Some(output))
4529            };
4530            let Some(read) = input.and_then(|input| use_of[input]) else { continue };
4531            match defs[def].constraint {
4532                Constraint::Fixed(_) => uses[read].constraint = defs[def].constraint,
4533                _ => {
4534                    let at = u8::try_from(first_use + read).map_err(|_| refused())?;
4535                    defs[def].constraint = Constraint::Reuse(at);
4536                    let source = uses[read].reg;
4537                    let shared = uses
4538                        .iter()
4539                        .enumerate()
4540                        .any(|(other, operand)| other != read && operand.reg == source);
4541                    if defs[def].role == Role::EarlyDef && !shared {
4542                        defs[def].role = Role::Def;
4543                    }
4544                }
4545            }
4546        }
4547
4548        // A line naming an operand in a register, with an instruction on it the reader knows, is
4549        // one the reader refused for a reason of its own, and keeping it as text would hand the
4550        // assembler what the reader already said no to. `addq %1, %k0` is that: a quadword add
4551        // into half a register. What is kept is a line with an instruction nothing here knows.
4552        let registered = |index: usize| def_of[index].is_some() || use_of[index].is_some();
4553        if !a64 && (0..list.len()).any(registered) {
4554            for line in template.split(['\n', ';']) {
4555                if names_one(line, registered)
4556                    && x86_64::known(line, widths, memory)
4557                    && x86_64::read_in(line, widths, memory).is_none()
4558                {
4559                    return Err(refused());
4560                }
4561            }
4562        }
4563
4564        let mut text = String::with_capacity(template.len());
4565        let mut memory: Option<usize> = None;
4566        if basic {
4567            text.push_str(template);
4568        } else {
4569            let mut chars = template.chars().peekable();
4570            // Inside `{att|intel}`, and past the `|` in it, which is the half nobody reads. AArch64
4571            // has one dialect, and a brace there is a list of vector registers.
4572            let mut dialect = false;
4573            let mut skipped = false;
4574            while let Some(c) = chars.next() {
4575                match c {
4576                    '{' if !a64 => {
4577                        dialect = true;
4578                        continue;
4579                    }
4580                    '|' if dialect => {
4581                        skipped = true;
4582                        continue;
4583                    }
4584                    '}' if dialect => {
4585                        dialect = false;
4586                        skipped = false;
4587                        continue;
4588                    }
4589                    _ if skipped => continue,
4590                    '%' => {}
4591                    _ => {
4592                        text.push(c);
4593                        continue;
4594                    }
4595                }
4596                match chars.peek().copied() {
4597                    Some(c @ ('%' | '{' | '|' | '}')) => {
4598                        chars.next();
4599                        text.push(c);
4600                        continue;
4601                    }
4602                    Some('=') => {
4603                        chars.next();
4604                        text.push_str(&inst.index().to_string());
4605                        continue;
4606                    }
4607                    _ => {}
4608                }
4609                let modifier = match chars.peek().copied() {
4610                    Some(c) if c.is_ascii_alphabetic() => {
4611                        chars.next();
4612                        Some(c)
4613                    }
4614                    _ => None,
4615                };
4616                let mut digits = String::new();
4617                while let Some(c) = chars.peek().copied().filter(char::is_ascii_digit) {
4618                    digits.push(c);
4619                    chars.next();
4620                }
4621                let index: usize = digits.parse().map_err(|_| refused())?;
4622                let operand = list.get(index).ok_or_else(refused)?;
4623                if operand.memory && a64 {
4624                    let at = use_of[index].map(|at| first_use + at).ok_or_else(refused)?;
4625                    if modifier.is_some() {
4626                        return Err(refused());
4627                    }
4628                    text.push('[');
4629                    text.push_str(&template_reg(at, 'x'));
4630                    text.push(']');
4631                    continue;
4632                }
4633                if operand.memory {
4634                    if modifier.is_some() || memory.is_some_and(|had| had != index) {
4635                        return Err(refused());
4636                    }
4637                    memory = Some(index);
4638                    text.push_str(x86_64::TEMPLATE_MEM);
4639                    continue;
4640                }
4641                let placed = def_of[index].or(use_of[index].map(|at| first_use + at));
4642                if let Some(at) = placed {
4643                    let value = operand.result.or(operand.value).ok_or_else(refused)?;
4644                    let bits = held_bits(self.source[value].ty);
4645                    // `w` and `x` are the two names every general purpose register has, and one
4646                    // with no modifier is named at the width of its type, as gcc names it. A
4647                    // vector register with no modifier is `v`, which is what gcc writes for one
4648                    // whatever is in it, and the modifiers name the scalar views of it.
4649                    let width = if a64 && files[index] != self.gpr {
4650                        match modifier {
4651                            None => 'v',
4652                            Some(view @ ('b' | 'h' | 's' | 'd' | 'q')) => view,
4653                            Some(_) => return Err(refused()),
4654                        }
4655                    } else if a64 {
4656                        match (modifier, bits) {
4657                            (None, 8 | 16 | 32) | (Some('w'), _) => 'w',
4658                            (None, 64) | (Some('x'), _) => 'x',
4659                            _ => return Err(refused()),
4660                        }
4661                    } else {
4662                        match modifier {
4663                            None => match held_bits(self.source[value].ty) {
4664                                8 => 'b',
4665                                16 => 'w',
4666                                32 => 'k',
4667                                64 => 'q',
4668                                _ => return Err(refused()),
4669                            },
4670                            Some(width @ ('b' | 'w' | 'k' | 'q')) => width,
4671                            // The second byte is a name only four registers have, so it is taken for
4672                            // an operand pinned to one of them and for nothing the allocator chose.
4673                            Some('h') if pinned(operand).and_then(x86_64::gpr_high).is_some() => {
4674                                'h'
4675                            }
4676                            Some(_) => return Err(refused()),
4677                        }
4678                    };
4679                    text.push_str(&template_reg(at, width));
4680                    continue;
4681                }
4682                let value = operand.value.ok_or_else(refused)?;
4683                let bare = match modifier {
4684                    None => false,
4685                    Some('c' | 'P' | 'p') => true,
4686                    Some(_) => return Err(refused()),
4687                };
4688                // A constant is bare on AArch64 whatever the modifier, which is how gcc prints one
4689                // there and a form GNU as takes wherever `#` would go.
4690                if !bare && !a64 {
4691                    text.push('$');
4692                }
4693                if let Some(number) = self.number(value) {
4694                    text.push_str(&number.to_string());
4695                } else if let Some(symbol) = self.named_address(value) {
4696                    text.push_str(&template_name(self.names.resolve(symbol)));
4697                } else {
4698                    return Err(refused());
4699                }
4700            }
4701        }
4702
4703        // An object in this function's frame is named by where it is in the frame, the way gcc
4704        // names it, rather than by a register its address was put in first. The text may write
4705        // registers it does not declare, and tcc's tests do: one that writes `%ecx` behind the
4706        // compiler's back would otherwise take the address with it.
4707        let mut local = None;
4708        let at = match memory.filter(|_| !a64) {
4709            Some(index) => {
4710                let value = list[index].value.ok_or_else(refused)?;
4711                local = self.local_of(value);
4712                let base = match local {
4713                    Some(_) => mir::Reg::physical(self.conv.stack_pointer),
4714                    None => self.reg_of(value)?,
4715                };
4716                Some(mir::Mem::at(mir::Operand::read(base, self.gpr)))
4717            }
4718            None => None,
4719        };
4720        let symbol = self.names.intern(&text);
4721        let opcode = self.named(if a64 { aarch64::TEMPLATE } else { x86_64::TEMPLATE });
4722        let block = self.at.expect("a block is being filled");
4723        let span = self.source.span(inst);
4724        let mut build = self.out.build(block, opcode).at(span).symbol(symbol);
4725        for operand in defs.into_iter().chain(written).chain(uses) {
4726            build = build.operand(operand);
4727        }
4728        if let Some(mem) = at {
4729            build = build.mem(mem);
4730        }
4731        let made = build.finish();
4732        if let Some(local) = local {
4733            self.stack.addresses.push((made, local));
4734        }
4735        Ok(())
4736    }
4737
4738    /// The object in this function's frame a value is the address of, for one an `alloca` of a
4739    /// size known here made. See [`Self::reserve`], which is where the `lea` it is found by came
4740    /// from.
4741    fn local_of(&self, value: Value) -> Option<usize> {
4742        let Def::Result { inst, .. } = self.source[value].def else { return None };
4743        if self.source[inst].opcode != Opcode::Alloca
4744            || !self.source[self.source[inst].args].is_empty()
4745        {
4746            return None;
4747        }
4748        let reg = self.regs[value.index()]?;
4749        self.stack.addresses.iter().find_map(|&(made, local)| {
4750            let data = &self.out[made];
4751            let defined = self.out[data.operands].first()?;
4752            (defined.reg == reg).then_some(local)
4753        })
4754    }
4755
4756    /// The name a value is the address of, for one a `global_addr` defined.
4757    fn named_address(&self, value: Value) -> Option<Symbol> {
4758        let Def::Result { inst, .. } = self.source[value].def else { return None };
4759        if self.source[inst].opcode != Opcode::GlobalAddr {
4760            return None;
4761        }
4762        let Extra::Symbol(symbol) = self.source[inst].extra else { return None };
4763        Some(symbol)
4764    }
4765
4766    /// A register holding a zero, for an operand of a template that is read before anything filled
4767    /// it.
4768    ///
4769    /// Two things ask for this and they are the same thing twice. An output the template reads has
4770    /// nothing to be read out of until the instruction that writes it has run, and a loop carries
4771    /// an operand into a block before the instruction that fills it, so both are a use in front of
4772    /// every definition. What the program is owed there is nothing, since the value is undefined
4773    /// either way, and what the allocator is owed is a register something wrote.
4774    fn seeded(&mut self, inst: Inst, operand: AsmOperand<'_>) -> Result<mir::Reg, Unsupported> {
4775        let refused = || Unsupported::Assembly { inst, refused: Written::Operand };
4776        let value = operand.result.or(operand.value).ok_or_else(refused)?;
4777        let class = self.class_of(self.source[value].ty);
4778        if class != self.gpr {
4779            return Err(refused());
4780        }
4781        let block = self.at.expect("a block is being filled");
4782        let reg = self.out.new_vreg(class);
4783        let put = self.named("mov_ri_64");
4784        self.out.build(block, put).at(self.source.span(inst)).def(reg, class).imm(0).finish();
4785        Ok(reg)
4786    }
4787
4788    /// A template with labels in it, as the blocks its jumps leave and arrive at.
4789    ///
4790    /// A statement is an instruction of the IR and stands inside one block, so a template that
4791    /// jumps has to stop being one thing. Each label becomes a block, each jump ends the block it
4792    /// stands in and gives it two arms, and whatever follows the statement goes into whichever
4793    /// block the walk finished in, which is what [`Self::block`] already reads off `self.at` and
4794    /// what [`Self::saves_place`] already does for the same reason.
4795    ///
4796    /// # What is carried between them
4797    ///
4798    /// The machine IR here is in the form where a register is written once, so an operand written
4799    /// inside a loop and read again at the top of it cannot be one register. What arrives at the
4800    /// top is a parameter of that block, and every jump to it carries whichever register held the
4801    /// operand where the jump stands. That is the whole of the bookkeeping: every block a label
4802    /// made takes one parameter for each operand that is in a register at all, in one order, so an
4803    /// arm's arguments and a block's parameters are the same list read twice.
4804    ///
4805    /// Which register an operand is in at each point is kept in the read half of its place, since
4806    /// that is what the instructions below read it out of. An instruction that writes an operand
4807    /// leaves it in the register it wrote, and a jump below carries that one. The block an
4808    /// untaken jump falls into is arrived at one way only and so takes no parameters, and nothing
4809    /// about where the operands are changes there.
4810    ///
4811    /// An operand written by the template and filled by nothing is written as a zero first, for
4812    /// the reason [`Self::undefined`] gives and one more: a jump may carry it before the
4813    /// instruction that fills it has run, and an argument has to be a register something wrote.
4814    ///
4815    /// # The condition state
4816    ///
4817    /// Nothing carries it and nothing has to. The instruction that sets it and the jump that reads
4818    /// it are both written here, next to each other in one block, and what the allocator may put
4819    /// between them is a move, which on this machine leaves the condition state alone. The edge
4820    /// into a block a loop goes back to is a critical edge and `crate::split` gives it a block of
4821    /// its own, so the moves an arm turns into land behind the jump rather than in front of it.
4822    fn woven(
4823        &mut self,
4824        inst: Inst,
4825        steps: &[x86_64::Step],
4826        places: &mut [Place],
4827        list: &[AsmOperand<'_>],
4828        clobbered: &[PhysReg],
4829        writes: &[usize],
4830    ) -> Result<(), Unsupported> {
4831        let refused = || Unsupported::Assembly { inst, refused: Written::Operand };
4832        let span = self.source.span(inst);
4833
4834        // Which operands are carried, which is every one that is in a register at all. An operand
4835        // the template never puts in one, such as a constant it names only as the distance into an
4836        // address, is in the instruction and has nowhere to be carried from.
4837        let mut carried: Vec<(usize, RegClass)> = Vec::new();
4838        for (index, operand) in list.iter().enumerate() {
4839            if places[index].read.is_none() && places[index].write.is_none() {
4840                continue;
4841            }
4842            let value = operand.result.or(operand.value).ok_or_else(refused)?;
4843            let ty = self.source[value].ty;
4844            if on_x87(ty) {
4845                return Err(refused());
4846            }
4847            carried.push((index, self.class_of(ty)));
4848        }
4849
4850        // What each of them holds where the template starts.
4851        for &(index, _) in &carried {
4852            if places[index].read.is_some() {
4853                continue;
4854            }
4855            if writes[index] == 0 {
4856                places[index].read = places[index].write;
4857                continue;
4858            }
4859            places[index].read = Some(self.seeded(inst, list[index])?);
4860        }
4861
4862        // The blocks, made before the walk because a jump forwards names a label the walk has not
4863        // reached yet.
4864        let mut labels: Vec<(&str, mir::Block, Vec<mir::Reg>)> = Vec::new();
4865        for step in steps {
4866            let x86_64::Step::Label(name) = step else { continue };
4867            let block = self.out.create_block();
4868            let mut params = Vec::with_capacity(carried.len());
4869            for &(_, class) in &carried {
4870                params.push(self.out.append_param(block, class));
4871            }
4872            labels.push((name.as_str(), block, params));
4873        }
4874
4875        let mut wrote: Vec<usize> = Vec::new();
4876        for step in steps {
4877            match step {
4878                x86_64::Step::Label(name) => {
4879                    let (block, params) = Self::went(&labels, name).ok_or_else(refused)?;
4880                    let from = self.at.expect("a block is being filled");
4881                    let args = Self::held(places, &carried).ok_or_else(refused)?;
4882                    *self.out.succs_mut(from) = vec![mir::BlockCall::with(block, args)];
4883                    self.at = Some(block);
4884                    for (at, &(index, _)) in carried.iter().enumerate() {
4885                        places[index].read = params.get(at).copied();
4886                    }
4887                }
4888                x86_64::Step::Jump { opcode, to } => {
4889                    let (block, _) = Self::went(&labels, to).ok_or_else(refused)?;
4890                    let from = self.at.expect("a block is being filled");
4891                    let args = Self::held(places, &carried).ok_or_else(refused)?;
4892                    let opcode = self.named(opcode);
4893                    self.out.build(from, opcode).at(span).finish();
4894                    let next = self.out.create_block();
4895                    *self.out.succs_mut(from) =
4896                        vec![mir::BlockCall::with(block, args), mir::BlockCall::to(next)];
4897                    self.at = Some(next);
4898                }
4899                x86_64::Step::Away { symbol } => {
4900                    // Only in a function that is written without a prologue, which is the one
4901                    // place the jump means what it says. Anywhere else there is an epilogue behind
4902                    // the statement that puts the registers back and gives the frame up, and a
4903                    // jump over it goes to the next function with this function's frame still
4904                    // taken. The reader already made sure it is the last step of the template, so
4905                    // what is left to ask is about the function around it.
4906                    if !self.source.attrs.set.contains(AttrSet::NAKED) {
4907                        return Err(Unsupported::Assembly { inst, refused: Written::Away });
4908                    }
4909                    let from = self.at.expect("a block is being filled");
4910                    let opcode = self.named(AWAY);
4911                    let symbol = self.names.intern(symbol);
4912                    self.out.build(from, opcode).at(span).symbol(symbol).finish();
4913                    // Nowhere, which is what a jump out of the function leaves behind it and is
4914                    // the same list a `ret` leaves. The block after it is made for the walk above
4915                    // rather than for the program: the statement may be in the middle of a body
4916                    // that goes on being lowered, and what that lowering writes is reached by
4917                    // nothing and thrown away with the block.
4918                    *self.out.succs_mut(from) = Vec::new();
4919                    self.at = Some(self.out.create_block());
4920                }
4921                x86_64::Step::Call { symbol } => {
4922                    self.call_out(inst, symbol, places, list, clobbered, &carried, &mut wrote)?;
4923                }
4924                x86_64::Step::Line(line) => {
4925                    let form = x86_64::form(line.opcode).ok_or_else(refused)?;
4926                    let mut written = Vec::new();
4927                    for (desc, piece) in form.operands().iter().zip(&line.operands) {
4928                        if !desc.role.is_def() {
4929                            continue;
4930                        }
4931                        let index = match *piece {
4932                            x86_64::Piece::Operand { index, .. } => index,
4933                            x86_64::Piece::Implicit { reg } => match bound(list, reg, desc.role) {
4934                                Some(index) => index,
4935                                None => continue,
4936                            },
4937                            x86_64::Piece::Reg { reg, .. } => match bound(list, reg, desc.role) {
4938                                Some(index) => index,
4939                                None => continue,
4940                            },
4941                        };
4942                        written.push(index);
4943                    }
4944                    // A register is written once in this form of the machine IR, so an operand
4945                    // an instruction above already wrote is written into a new one here, and what
4946                    // reads it below reads that one.
4947                    for &index in &written {
4948                        if !wrote.contains(&index) {
4949                            wrote.push(index);
4950                            continue;
4951                        }
4952                        let &(_, class) =
4953                            carried.iter().find(|&&(at, _)| at == index).ok_or_else(refused)?;
4954                        let place = places.get_mut(index).ok_or_else(refused)?;
4955                        place.write = Some(self.out.new_vreg(class));
4956                    }
4957                    self.instruction(inst, line, places, list, clobbered)?;
4958                    for index in written {
4959                        let place = places.get_mut(index).ok_or_else(refused)?;
4960                        if place.write.is_some() {
4961                            place.read = place.write;
4962                        }
4963                    }
4964                }
4965            }
4966        }
4967
4968        // Where the walk left each output, which is the parameter of the block a label made when
4969        // the template ends in one and the register an instruction wrote when it does not.
4970        for (index, operand) in list.iter().enumerate() {
4971            let Some(result) = operand.result else { continue };
4972            if let Some(reg) = places[index].read {
4973                self.regs[result.index()] = Some(reg);
4974            }
4975        }
4976        Ok(())
4977    }
4978
4979    /// A template's call to a function somewhere else, as the call the convention makes.
4980    ///
4981    /// The opcode is the one a call written in C becomes, so everything that asks whether a
4982    /// function calls anything gets the answer it would for one: the stack pointer is left aligned
4983    /// at the statement and nothing is kept in the red zone. What is not the same is the operands.
4984    /// Nothing is passed by the convention, since the template put the arguments where it wanted
4985    /// them, and what comes back is whatever an output is pinned to, since that is the only thing
4986    /// the template says about it. Every other register the callee may leave anything in is
4987    /// written here, which is what a program that calls from a template never says and always
4988    /// means.
4989    #[allow(clippy::too_many_arguments)]
4990    fn call_out(
4991        &mut self,
4992        inst: Inst,
4993        symbol: &str,
4994        places: &mut [Place],
4995        list: &[AsmOperand<'_>],
4996        clobbered: &[PhysReg],
4997        carried: &[(usize, RegClass)],
4998        wrote: &mut Vec<usize>,
4999    ) -> Result<(), Unsupported> {
5000        let refused = || Unsupported::Assembly { inst, refused: Written::Operand };
5001        let mut operands = Vec::new();
5002        let mut written = Vec::new();
5003        let lost = self.lost(list);
5004        for &(reg, class, index) in &lost {
5005            let Some(index) = index else {
5006                operands.push(mir::Operand::write(mir::Reg::physical(reg), class));
5007                continue;
5008            };
5009            // Written once in this form of the machine IR, so a second write is a new register,
5010            // the same as for an instruction in [`Self::woven`].
5011            if wrote.contains(&index) {
5012                let &(_, class) =
5013                    carried.iter().find(|&&(at, _)| at == index).ok_or_else(refused)?;
5014                places.get_mut(index).ok_or_else(refused)?.write = Some(self.out.new_vreg(class));
5015            } else {
5016                wrote.push(index);
5017            }
5018            let place = places.get(index).ok_or_else(refused)?.write.ok_or_else(refused)?;
5019            operands.push(mir::Operand::write(place, class).with(Constraint::Fixed(reg)));
5020            written.push(index);
5021        }
5022        for &reg in clobbered {
5023            if lost.iter().all(|&(gone, class, _)| gone != reg || class != self.gpr) {
5024                operands.push(mir::Operand::write(mir::Reg::physical(reg), self.gpr));
5025            }
5026        }
5027        let block = self.at.expect("a block is being filled");
5028        let span = self.source.span(inst);
5029        let opcode = mir::Opcode::new(self.names.intern(abi::CALL));
5030        let symbol = self.names.intern(symbol);
5031        let mut build = self.out.build(block, opcode).at(span).symbol(symbol);
5032        for operand in operands {
5033            build = build.operand(operand);
5034        }
5035        build.finish();
5036        let calls = &mut self.stack.calls;
5037        *calls = Some(calls.unwrap_or(0));
5038        for index in written {
5039            let place = places.get_mut(index).ok_or_else(refused)?;
5040            place.read = place.write;
5041        }
5042        Ok(())
5043    }
5044
5045    /// Every register a call may leave anything in, with its file and the output pinned to it if
5046    /// one is.
5047    ///
5048    /// A register is asked about with its file, since the two files are numbered from nought alike
5049    /// and a question about `v8` alone would find an output pinned to `x8`.
5050    ///
5051    /// The platform's own convention, whatever this function was written in, since what an `asm`
5052    /// statement calls is an ordinary function of the platform.
5053    fn lost(&self, list: &[AsmOperand<'_>]) -> Vec<(PhysReg, RegClass, Option<usize>)> {
5054        let conv = self.conv.under(Convention::Target).unwrap_or(self.conv);
5055        let ints = conv.int_order.iter().filter(|&&reg| !conv.preserves_int(reg));
5056        let sses = conv.sse_order.iter().filter(|&&reg| !conv.preserves_sse(reg));
5057        let written = |reg, class| {
5058            list.iter().position(|operand| {
5059                operand.result.is_some() && self.pinned_here(operand) == Some((reg, class))
5060            })
5061        };
5062        ints.map(|&reg| (reg, conv.int_class, written(reg, conv.int_class)))
5063            .chain(sses.map(|&reg| (reg, conv.sse_class, written(reg, conv.sse_class))))
5064            .collect()
5065    }
5066
5067    /// The input an output read before anything wrote it shares its register with, which is the
5068    /// one input that could be in that register, or nothing when there is none or more than one.
5069    ///
5070    /// Could be means nothing ties it elsewhere: it is in a register rather than in memory, no
5071    /// constraint pins it anywhere the output is not, and it is not tied to another output. An
5072    /// output written `&` shares nothing, since the assembly writes it before it reads the inputs.
5073    fn shared(&self, list: &[AsmOperand<'_>], index: usize) -> Option<Value> {
5074        let output = list.get(index)?;
5075        if output.early || output.tied.is_some() {
5076            return None;
5077        }
5078        let class = self.class_of(self.source[output.result?].ty);
5079        let mut fits = list.iter().filter(|operand| {
5080            operand.result.is_none()
5081                && !operand.memory
5082                && operand.tied.is_none()
5083                && operand.value.is_some_and(|value| self.class_of(self.source[value].ty) == class)
5084                && pinned(operand).is_none_or(|reg| pinned(output) == Some(reg))
5085        });
5086        let value = fits.next()?.value;
5087        if fits.next().is_some() {
5088            return None;
5089        }
5090        value
5091    }
5092
5093    /// The block one of the template's labels made, and the parameters it takes.
5094    fn went<'b>(
5095        labels: &'b [(&str, mir::Block, Vec<mir::Reg>)],
5096        name: &str,
5097    ) -> Option<(mir::Block, &'b [mir::Reg])> {
5098        labels
5099            .iter()
5100            .find(|(had, ..)| *had == name)
5101            .map(|(_, block, params)| (*block, params.as_slice()))
5102    }
5103
5104    /// The register each carried operand is in, which is what an arm to a label carries.
5105    fn held(places: &[Place], carried: &[(usize, RegClass)]) -> Option<Vec<mir::Reg>> {
5106        carried.iter().map(|&(index, _)| places.get(index)?.read).collect()
5107    }
5108
5109    /// The registers a clobber list names, in the order it named them.
5110    ///
5111    /// Nothing is dropped. A name this has no register for is refused, because the list is the
5112    /// program telling the compiler which registers it may not leave anything in, and an entry
5113    /// nobody read is a register something may still be left in. See [`Self::assembly`] for the
5114    /// two entries that are not registers and for why they are skipped rather than refused.
5115    fn clobbered(inst: Inst, clobbers: &str) -> Result<Vec<PhysReg>, Unsupported> {
5116        let refused = || Unsupported::Assembly { inst, refused: Written::Clobber };
5117        let mut named = Vec::new();
5118        for entry in clobbers.split(',') {
5119            let entry = entry.trim().trim_matches('"');
5120            // The sigil is optional in a clobber list and means nothing when it is there, unlike
5121            // in a template, where it is what tells a register from an operand.
5122            let entry = entry.strip_prefix('%').unwrap_or(entry);
5123            if entry.is_empty() || matches!(entry, "memory" | "cc" | "flags") {
5124                continue;
5125            }
5126            let (reg, _) = x86_64::gpr_named(entry).ok_or_else(refused)?;
5127            if !named.contains(&reg) {
5128                named.push(reg);
5129            }
5130        }
5131        Ok(named)
5132    }
5133
5134    /// [`Self::clobbered`] for a template kept as text, where a clobber may also name a vector
5135    /// register, `xmm0` or its wider spelling `ymm0`, which busybox's `xorbuf16_aligned_long` does.
5136    /// Each comes back with the file it is in, since `xmm0` and `rax` are both register nought.
5137    fn clobbered_x86(
5138        inst: Inst,
5139        clobbers: &str,
5140        gpr: RegClass,
5141        sse: RegClass,
5142    ) -> Result<Vec<(PhysReg, RegClass)>, Unsupported> {
5143        let mut named = Vec::new();
5144        let mut general = Vec::new();
5145        for entry in clobbers.split(',') {
5146            match vector_named(entry) {
5147                Some(reg) => {
5148                    if !named.contains(&(reg, sse)) {
5149                        named.push((reg, sse));
5150                    }
5151                }
5152                None => general.push(entry),
5153            }
5154        }
5155        for reg in Self::clobbered(inst, &general.join(","))? {
5156            named.push((reg, gpr));
5157        }
5158        Ok(named)
5159    }
5160
5161    /// [`Self::clobbered`] on AArch64, where a clobber may name a vector register as well as a
5162    /// general purpose one, so each comes back with the file it is in. See [`aarch64::named`].
5163    fn clobbered_a64(inst: Inst, clobbers: &str) -> Result<Vec<(PhysReg, RegClass)>, Unsupported> {
5164        let refused = || Unsupported::Assembly { inst, refused: Written::Clobber };
5165        let mut named = Vec::new();
5166        for entry in clobbers.split(',') {
5167            let entry = entry.trim().trim_matches('"');
5168            if entry.is_empty() || matches!(entry, "memory" | "cc") {
5169                continue;
5170            }
5171            let reg = aarch64::named(entry).ok_or_else(refused)?;
5172            if !named.contains(&reg) {
5173                named.push(reg);
5174            }
5175        }
5176        Ok(named)
5177    }
5178
5179    /// Whether the machine being lowered for is AArch64.
5180    fn on_aarch64(&self) -> bool {
5181        std::ptr::eq(self.selector.shapes, &aarch64::MACHINE)
5182    }
5183
5184    /// The register an operand is pinned to on the machine being lowered for.
5185    ///
5186    /// [`pinned`] on x86, where it is always a general purpose register. AArch64 has no constraint
5187    /// letter for one register, so there only a local register variable pins anything, and its name
5188    /// is read against [`aarch64::named`], which may put it in either file. The file comes back with
5189    /// the register because the two are numbered from nought alike, and `x8` is not `v8`.
5190    fn pinned_here(&self, operand: &AsmOperand<'_>) -> Option<(PhysReg, RegClass)> {
5191        if !self.on_aarch64() {
5192            return pinned(operand).map(|reg| (reg, self.gpr));
5193        }
5194        let name = operand.named?;
5195        aarch64::named(name.strip_prefix('%').unwrap_or(name))
5196    }
5197
5198    /// An `asm` statement whose operands are `long double` values on the x87 stack.
5199    ///
5200    /// `t` is the top of the stack and `u` is the register under it, and those two letters, or a
5201    /// number tying an input to an output in one of them, are the only places taken here. That is
5202    /// what glibc's old `<bits/mathinline.h>` writes, `fpatan` with `=t`, `0` and `u` and `st(1)`
5203    /// in the clobber list, and it is gcc-torture `execute/990413-2.c`.
5204    ///
5205    /// The group is the shape every other one in [`Self::x87`] has. The inputs are pushed from the
5206    /// deepest up, so the `t` one is pushed last and ends up on top, then the template runs, then
5207    /// the outputs are popped into their slots from the top down. That leaves the stack as empty
5208    /// as it was found only when the template popped every input it was handed and pushed every
5209    /// output it says it leaves, and gcc's rule for these statements says when that is: an input
5210    /// tied to an output or named in the clobber list is one the template pops. So a statement
5211    /// with an input it leaves behind is refused, as is one with an operand anywhere other than
5212    /// `st(0)` and `st(1)`, since nothing here would know what to do with the stack after it.
5213    fn x87_assembly(&mut self, inst: Inst) -> Result<(), Unsupported> {
5214        let data = &self.source[inst];
5215        let Extra::Asm(asm) = data.extra else { return Err(self.unsupported(inst)) };
5216        let info = self.source[asm];
5217        if !self.source[info.targets].is_empty() {
5218            return Err(Unsupported::Assembly { inst, refused: Written::Goto });
5219        }
5220        let refused = || Unsupported::Assembly { inst, refused: Written::Operand };
5221        let constraints = self.names.resolve(info.constraints).to_string();
5222        let results: Vec<Value> = data.results().collect();
5223        let operands = AsmOperands::read(&constraints, &results, &self.source[data.args])
5224            .ok_or_else(refused)?;
5225        let list: Vec<AsmOperand<'_>> = operands.iter().copied().collect();
5226
5227        // Where on the stack each operand is, as a depth from the top.
5228        let letters: Vec<&str> = constraints.split(',').collect();
5229        let mut depths = Vec::with_capacity(list.len());
5230        for (operand, letter) in list.iter().zip(&letters) {
5231            let value = operand.result.or(operand.value).ok_or_else(refused)?;
5232            if operand.memory || !on_x87(self.source[value].ty) {
5233                return Err(refused());
5234            }
5235            let depth = match operand.tied {
5236                Some(output) => *depths.get(output).ok_or_else(refused)?,
5237                None => match letter.trim_start_matches(['=', '+', '&']) {
5238                    "t" => 0,
5239                    "u" => 1,
5240                    _ => return Err(refused()),
5241                },
5242            };
5243            depths.push(depth);
5244        }
5245
5246        // Which depths the clobber list says the template pops.
5247        let clobbers = self.names.resolve(info.clobbers).to_string();
5248        let mut popped = [false; 2];
5249        for entry in clobbers.split(',') {
5250            let entry = entry.trim().trim_matches('"');
5251            let entry = entry.strip_prefix('%').unwrap_or(entry);
5252            match entry {
5253                "" | "memory" | "cc" | "flags" => {}
5254                "st" | "st(0)" => popped[0] = true,
5255                "st(1)" => popped[1] = true,
5256                _ => return Err(Unsupported::Assembly { inst, refused: Written::Clobber }),
5257            }
5258        }
5259
5260        // The inputs, one per depth and from the top down with no gap, and each one popped.
5261        let mut inputs: Vec<Option<Value>> = vec![None; 2];
5262        let mut outputs: Vec<Option<Value>> = vec![None; 2];
5263        for (index, operand) in list.iter().enumerate() {
5264            let depth = depths[index];
5265            if let Some(result) = operand.result {
5266                if outputs[depth].replace(result).is_some() {
5267                    return Err(refused());
5268                }
5269            }
5270            let Some(value) = operand.value else { continue };
5271            // An output written `+` is an input tied to itself.
5272            let consumed = operand.result.is_some() || operand.tied.is_some() || popped[depth];
5273            if !consumed {
5274                return Err(refused());
5275            }
5276            if inputs[depth].replace(value).is_some() {
5277                return Err(refused());
5278            }
5279        }
5280        let gapless =
5281            |held: &[Option<Value>]| held.iter().skip_while(|it| it.is_some()).all(Option::is_none);
5282        if !gapless(&inputs) || !gapless(&outputs) {
5283            return Err(refused());
5284        }
5285
5286        // The text, with an operand spelled as the register it is in.
5287        let template = self.names.resolve(info.template).to_string();
5288        let mut text = String::with_capacity(template.len());
5289        let mut chars = template.chars().peekable();
5290        while let Some(c) = chars.next() {
5291            if c != '%' {
5292                text.push(c);
5293                continue;
5294            }
5295            match chars.peek().copied() {
5296                Some('%') => {
5297                    chars.next();
5298                    text.push('%');
5299                }
5300                Some('=') => {
5301                    chars.next();
5302                    text.push_str(&inst.index().to_string());
5303                }
5304                Some(digit) if digit.is_ascii_digit() => {
5305                    chars.next();
5306                    if chars.peek().is_some_and(char::is_ascii_digit) {
5307                        return Err(refused());
5308                    }
5309                    let index = digit.to_digit(10).map_or(usize::MAX, |it| it as usize);
5310                    match depths.get(index).ok_or_else(refused)? {
5311                        0 => text.push_str("%st"),
5312                        depth => text.push_str(&format!("%st({depth})")),
5313                    }
5314                }
5315                _ => return Err(refused()),
5316            }
5317        }
5318
5319        let span = self.source.span(inst);
5320        for value in inputs.iter().rev().flatten() {
5321            let from = self.x87_slot(*value);
5322            let from = self.through(from);
5323            self.x87_at("fld_t", span, from);
5324        }
5325        let symbol = self.names.intern(&text);
5326        let opcode = self.named(x86_64::TEMPLATE);
5327        let block = self.at.expect("a block is being filled");
5328        self.out.build(block, opcode).at(span).symbol(symbol).finish();
5329        for value in outputs.iter().flatten() {
5330            let into = self.x87_slot(*value);
5331            let into = self.through(into);
5332            self.x87_at("fstp_t", span, into);
5333        }
5334        Ok(())
5335    }
5336
5337    /// An `asm` statement on AArch64, which is kept as text whatever is in it.
5338    ///
5339    /// Nothing reads AArch64 assembly back into instructions yet, so every template goes the way
5340    /// one the x86 reader could not take apart goes, which is [`Self::kept`]: the text is carried
5341    /// to the listing with a hole for each operand, and the operands are the instruction's own. A
5342    /// constraint with a letter whose meaning differs between the two machines is refused first.
5343    /// See [`shared_letters`].
5344    fn spelled(&mut self, inst: Inst) -> Result<(), Unsupported> {
5345        let data = &self.source[inst];
5346        let Extra::Asm(asm) = data.extra else { return Err(self.unsupported(inst)) };
5347        let info = self.source[asm];
5348        if self.jumps_from_text(inst) {
5349            return Err(Unsupported::Assembly { inst, refused: Written::Goto });
5350        }
5351        let refused = || Unsupported::Assembly { inst, refused: Written::Operand };
5352        let constraints = self.names.resolve(info.constraints).to_string();
5353        if !constraints.split(',').all(shared_letters) {
5354            return Err(refused());
5355        }
5356        // `Q` is memory addressed by one register and nothing else, which is how every operand in
5357        // memory is spelled here already, so it is read as `m`. See [`shared_letters`].
5358        let constraints = letters_outside(&constraints, |c| if c == 'Q' { 'm' } else { c });
5359        let results: Vec<Value> = data.results().collect();
5360        let operands = AsmOperands::read(&constraints, &results, &self.source[data.args])
5361            .ok_or_else(refused)?;
5362        let list: Vec<AsmOperand<'_>> = operands.iter().copied().collect();
5363        let widths = vec![None; list.len()];
5364        let memory: Vec<bool> = list.iter().map(|operand| operand.memory).collect();
5365        let template = self.names.resolve(info.template).to_string();
5366        self.kept(inst, &template, &list, &widths, &memory)
5367    }
5368
5369    /// One instruction of a template, as the machine instruction it was read back into.
5370    fn instruction(
5371        &mut self,
5372        inst: Inst,
5373        line: &x86_64::Line,
5374        places: &[Place],
5375        list: &[AsmOperand<'_>],
5376        clobbered: &[PhysReg],
5377    ) -> Result<(), Unsupported> {
5378        let refused = || Unsupported::Assembly { inst, refused: Written::Operand };
5379        let form = x86_64::form(line.opcode).ok_or_else(refused)?;
5380        // What the instruction reaches and what is in each of them. The description answers the
5381        // first for every opcode but one, and the pieces the template was read into answer the
5382        // second. Bytes a program wrote out itself are the one, since nothing in a number is a
5383        // register anybody could read, so the constraint letters answer both. See
5384        // [`Self::lettered`].
5385        let lettered = (line.opcode == x86_64::LITERAL).then(|| self.lettered(list));
5386        let (described, pieces) = match &lettered {
5387            Some((described, pieces)) => (described.as_slice(), pieces.as_slice()),
5388            None => (form.operands(), line.operands.as_slice()),
5389        };
5390        let mut built = Vec::with_capacity(pieces.len() + clobbered.len());
5391        for (desc, piece) in described.iter().zip(pieces) {
5392            built.push(self.placed(inst, *desc, *piece, places, list)?);
5393        }
5394        // The clobbers go in among the definitions rather than behind the reads, because an operand
5395        // vector in the machine IR is every definition and then every use and what counts them
5396        // reads that order rather than each operand's role.
5397        let defs = built.iter().take_while(|operand| operand.role.is_def()).count();
5398        let mut added = 0usize;
5399        for &reg in clobbered {
5400            if described.iter().any(|desc| desc.constraint == Constraint::Fixed(reg)) {
5401                continue;
5402            }
5403            built.insert(defs, mir::Operand::write(mir::Reg::physical(reg), self.gpr));
5404            added += 1;
5405        }
5406        // A constraint tying one operand to another names it by its place in this vector, and the
5407        // clobbers were put in the middle of the vector, so everything behind them moved. The
5408        // description is written against an instruction with no clobbers in it and cannot know
5409        // that, which makes this the one place the two numberings have to be reconciled.
5410        for operand in &mut built {
5411            if let Constraint::Reuse(at) = operand.constraint {
5412                if usize::from(at) >= defs {
5413                    let moved = usize::from(at) + added;
5414                    operand.constraint =
5415                        Constraint::Reuse(u8::try_from(moved).map_err(|_| refused())?);
5416                }
5417            }
5418        }
5419        let at = match line.at {
5420            Some(at) => Some(self.addressed(inst, at, places, list)?),
5421            None => None,
5422        };
5423
5424        let block = self.at.expect("a block is being filled");
5425        let span = self.source.span(inst);
5426        let opcode = self.named(line.opcode);
5427        let mut build = self.out.build(block, opcode).at(span);
5428        for operand in built {
5429            build = build.operand(operand);
5430        }
5431        if let Some(value) = line.imm {
5432            build = build.imm(value);
5433        }
5434        if let Some(mem) = at {
5435            build = build.mem(mem);
5436        }
5437        build.finish();
5438        Ok(())
5439    }
5440
5441    /// The registers a run of bytes reaches, taken from the constraint letters rather than from the
5442    /// description of an opcode.
5443    ///
5444    /// Every other instruction of a template has a description saying which registers it reaches
5445    /// without naming them, and [`Self::assembly`] matches the letters against that. Bytes a program
5446    /// wrote out itself have no such description and could not have one: what the instruction is, is
5447    /// a number, and nothing in a number is a register anything could read. So the letters are the
5448    /// whole of what is known, and they are enough, because a program writing an instruction this
5449    /// way has to say where its operands go for exactly the reason a program writing `cpuid` does.
5450    ///
5451    /// Each register named by a letter gets one entry for the write and one for the read, the same
5452    /// two `cpuid` has, and only the half the statement asked for: a register no output names is not
5453    /// written here and one no input names is not read. The writes come first because that is the
5454    /// order an operand vector in the machine IR is counted in. A register named by nothing is left
5455    /// out rather than given a spare one, which is the difference from `cpuid` and is right for the
5456    /// same reason: `cpuid` writes four registers whatever the program said, and what these bytes
5457    /// touch is known only from what the program said.
5458    fn lettered(&self, list: &[AsmOperand<'_>]) -> (Vec<OperandDesc>, Vec<x86_64::Piece>) {
5459        let mut named: Vec<PhysReg> = Vec::new();
5460        for operand in list {
5461            if let Some(reg) = pinned(operand) {
5462                if !named.contains(&reg) {
5463                    named.push(reg);
5464                }
5465            }
5466        }
5467        let mut described = Vec::with_capacity(named.len() * 2);
5468        let mut pieces = Vec::with_capacity(named.len() * 2);
5469        for role in [Role::Def, Role::Use] {
5470            for &reg in &named {
5471                if bound(list, reg, role).is_none() {
5472                    continue;
5473                }
5474                let desc = if role.is_def() {
5475                    OperandDesc::write(self.gpr)
5476                } else {
5477                    OperandDesc::read(self.gpr)
5478                };
5479                described.push(desc.with(Constraint::Fixed(reg)));
5480                pieces.push(x86_64::Piece::Implicit { reg });
5481            }
5482        }
5483        (described, pieces)
5484    }
5485
5486    /// One operand of one instruction of a template, in the register the statement put it in.
5487    fn placed(
5488        &mut self,
5489        inst: Inst,
5490        desc: OperandDesc,
5491        piece: x86_64::Piece,
5492        places: &[Place],
5493        list: &[AsmOperand<'_>],
5494    ) -> Result<mir::Operand, Unsupported> {
5495        let refused = || Unsupported::Assembly { inst, refused: Written::Operand };
5496        // A register the instruction reaches without its text naming it belongs to whichever of the
5497        // statement's operands a constraint letter put there, and to nobody when no letter did.
5498        // There is no width to check in that case: the operand is the register the letter named and
5499        // the instruction does what it does to it, which is what a program writing `"=a"` asked for.
5500        let (index, spelled) = match piece {
5501            x86_64::Piece::Operand { index, width, stated } => (index, Some((width, stated))),
5502            x86_64::Piece::Implicit { reg } => match bound(list, reg, desc.role) {
5503                Some(index) => (index, None),
5504                None => return self.spare(inst, desc),
5505            },
5506            // A register the template named, which belongs to one of the statement's operands when
5507            // a constraint letter put that operand there and to nobody otherwise. Asked in that
5508            // order rather than placed straight away, because `"D" (p)` with `%rdi` in the text is
5509            // the program saying one thing twice, and answering it twice would hand the allocator
5510            // one register holding two values.
5511            x86_64::Piece::Reg { reg, .. } => match bound(list, reg, desc.role) {
5512                Some(index) => (index, None),
5513                None => return self.itself(inst, desc, reg),
5514            },
5515        };
5516        let operand = list.get(index).copied().ok_or_else(refused)?;
5517        // The two halves of an operand written `+`, which arrives in one register and leaves in
5518        // another with the allocator told to make them the same one. Everything else has one of
5519        // the two and asking for the other is the refusal below.
5520        let place = places.get(index).copied().ok_or_else(refused)?;
5521        let reg = match desc.role {
5522            Role::Use => place.read,
5523            Role::Def | Role::EarlyDef => place.write,
5524        }
5525        .ok_or_else(refused)?;
5526
5527        // Read where the opcode reads and written where it writes, which is what the first half of
5528        // this asks. An output has a result and an input has a value, an output written `+` has
5529        // both because it is read before it is written, and an output a matching constraint names
5530        // is read as the input that named it. See [`read_as`].
5531        // An output with neither is read as well, and what it holds there is undefined, which
5532        // [`Self::assembly`] says why and puts a zero in a register for.
5533        let placeable = match desc.role {
5534            Role::Use => read_as(list, index).is_some() || operand.result.is_some(),
5535            Role::Def | Role::EarlyDef => operand.result.is_some(),
5536        };
5537        let ty = match (operand.result, operand.value) {
5538            (Some(result), _) => self.source[result].ty,
5539            (None, Some(value)) => self.source[value].ty,
5540            (None, None) => return Err(refused()),
5541        };
5542        let bits = held_bits(ty);
5543        if !placeable || self.class_of(ty) != desc.class {
5544            return Err(refused());
5545        }
5546        if let Some((width, stated)) = spelled {
5547            // An operand the template wrote a width on may be written by an instruction that fills
5548            // more of the register than the object in it does, and the object is then the low part
5549            // of what was written. That is what gmp asks for when it counts the low zero bits of a
5550            // limb into an `unsigned` and spells the count `%q0`: one quadword instruction writes
5551            // the whole register and the `unsigned` is the bottom of it, which is every bit of an
5552            // answer that cannot exceed sixty four anyway.
5553            //
5554            // An operand read at a width the template wrote is the other way round: the object is
5555            // in the register and the instruction looks at the bottom of it. tcc tests the low bits
5556            // of a `size_t` count with `testb $2,%b4`, and every bit that test reads is one the
5557            // object put there.
5558            //
5559            // A write of less of a register than the object fills is right in one case, which is
5560            // an instruction that reads the register it writes and an operand that arrives with
5561            // the object in it. The top of the register is then the top of the object, and the
5562            // instruction leaves it alone. tcc swaps the bytes of an `unsigned` with `xchgb
5563            // %b0,%h0` and a rotate between two of them, and the swap only ever touches the low
5564            // half.
5565            //
5566            // The two that stay refused are a read of more of a register than its type fills,
5567            // which hands an instruction bits nothing ever put there, and a write of less of one
5568            // that nothing carried the object into, which leaves the top of the object holding
5569            // whatever the register held before. An operand the template left plain is refused
5570            // either way, because what gets spelled for that one is the register at the width of
5571            // its type and no other instruction is the one written down.
5572            let carried = matches!(desc.constraint, Constraint::Reuse(_) | Constraint::Fixed(_))
5573                && read_as(list, index).is_some();
5574            // The other case is the one the machine settles by itself: a write of the low four
5575            // bytes of a register clears the four above them, so a sixty four bit object written
5576            // that way holds the thirty two bit answer and nothing else. tcc loads a word through
5577            // `movl 4(%0),%k0` into a `long` and means exactly that.
5578            let cleared = desc.class == self.gpr && width == x86_64::Width::Long && bits == 64;
5579            let widened = stated && desc.role.is_def() && width.bits() > bits;
5580            let narrowed =
5581                stated && width.bits() < bits && (!desc.role.is_def() || carried || cleared);
5582            if bits != width.bits() && !widened && !narrowed {
5583                return Err(refused());
5584            }
5585        }
5586        // An operand the program pinned is in that register and nowhere else, whatever the opcode
5587        // would have allowed it. That is the whole of what a local register variable asks for, and
5588        // it is the same shape a division already has: the allocator is told the register, puts a
5589        // move in front or behind where it has to, and leaves it out where it does not.
5590        let constraint = match pinned(&operand) {
5591            Some(reg) => Constraint::Fixed(reg),
5592            None => desc.constraint,
5593        };
5594        Ok(mir::Operand { reg, class: desc.class, role: desc.role, constraint })
5595    }
5596
5597    /// A register the template named in its own text.
5598    ///
5599    /// Not one of the statement's operands and not something the allocator handed out. The program
5600    /// wrote `%rbx` in the middle of a template and meant that register, which is what code doing
5601    /// something the constraint letters cannot say is made of: micropython saves the callee-saved
5602    /// registers into a buffer by name because the whole point of the buffer is that those exact
5603    /// registers are in it, and there is no constraint letter for `%rsp`.
5604    ///
5605    /// So it is placed as itself, fixed to the register the template named. What that buys is the
5606    /// thing gcc does not do: the register becomes part of the instruction the allocator sees, so a
5607    /// write of one is a definition it knows about and will not leave anything of the program's
5608    /// across, and a read of one is a use it will not have put something else in first. gcc copies
5609    /// the text out and a register two things believe they own is a wrong program nothing reports.
5610    /// Here the allocator is told, and a program that also named the register in its clobber list
5611    /// says the same thing twice rather than something new.
5612    fn itself(
5613        &mut self,
5614        inst: Inst,
5615        desc: OperandDesc,
5616        reg: PhysReg,
5617    ) -> Result<mir::Operand, Unsupported> {
5618        let refused = Unsupported::Assembly { inst, refused: Written::Operand };
5619        if desc.class != self.gpr {
5620            return Err(refused);
5621        }
5622        Ok(mir::Operand {
5623            reg: mir::Reg::physical(reg),
5624            class: self.gpr,
5625            role: desc.role,
5626            constraint: Constraint::Fixed(reg),
5627        })
5628    }
5629
5630    /// A register an instruction of a template uses and the statement put nothing in.
5631    ///
5632    /// A write of one is the register being destroyed, which is what a clobber list is usually
5633    /// written to say and what an instruction with more answers than the program asked for does
5634    /// anyway: `cpuid` writes all four registers whether or not the statement wanted all four. A
5635    /// register of its own is the whole of what that needs, since a value nothing reads is one the
5636    /// allocator may put anywhere and is told about so that nothing else is put there.
5637    ///
5638    /// A read of one is a register the instruction looks at and the program never filled, which
5639    /// gcc leaves as whatever happened to be there. A zero is written instead, for the reason
5640    /// [`Self::undefined`] gives: the allocator has to be given a definition before a use, and a
5641    /// zero is the one answer that reads the same on every run.
5642    fn spare(&mut self, inst: Inst, desc: OperandDesc) -> Result<mir::Operand, Unsupported> {
5643        let refused = Unsupported::Assembly { inst, refused: Written::Operand };
5644        if desc.class != self.gpr {
5645            return Err(refused);
5646        }
5647        let reg = self.out.new_vreg(desc.class);
5648        if !desc.role.is_def() {
5649            let block = self.at.expect("a block is being filled");
5650            let span = self.source.span(inst);
5651            let put = self.named("mov_ri_64");
5652            self.out.build(block, put).at(span).def(reg, desc.class).imm(0).finish();
5653        }
5654        Ok(mir::Operand { reg, class: desc.class, role: desc.role, constraint: desc.constraint })
5655    }
5656
5657    /// The address one instruction of a template reads or writes.
5658    fn addressed(
5659        &mut self,
5660        inst: Inst,
5661        at: x86_64::At,
5662        places: &[Place],
5663        list: &[AsmOperand<'_>],
5664    ) -> Result<mir::Mem, Unsupported> {
5665        let refused = || Unsupported::Assembly { inst, refused: Written::Operand };
5666        let base = match at.base {
5667            None => None,
5668            Some(x86_64::Piece::Operand { index, .. }) => {
5669                // The register an address is counted from is read and never written, whatever the
5670                // instruction does to what it finds there.
5671                let reg = places.get(index).and_then(|place| place.read).ok_or_else(refused)?;
5672                Some(mir::Operand::read(reg, self.gpr))
5673            }
5674            // A register the template named, counted from as itself. See [`Self::itself`], and note
5675            // that this is the half of it every one of these templates needs: `movq %rax, 16(%rdi)`
5676            // names one register as the thing being stored and another as where to store it. An
5677            // operand a constraint letter put in that register is that operand, for the reason
5678            // [`Self::placed`] gives.
5679            Some(x86_64::Piece::Reg { reg, .. }) => match bound(list, reg, Role::Use) {
5680                Some(index) => {
5681                    let reg = places.get(index).and_then(|place| place.read).ok_or_else(refused)?;
5682                    Some(mir::Operand::read(reg, self.gpr))
5683                }
5684                None => Some(
5685                    mir::Operand::read(mir::Reg::physical(reg), self.gpr)
5686                        .with(Constraint::Fixed(reg)),
5687                ),
5688            },
5689            // An address counted from a register the instruction reaches without being told is
5690            // not something this machine has: every addressing mode is written out in the text it
5691            // is part of, so a base that got here another way is a base nothing wrote down.
5692            Some(x86_64::Piece::Implicit { .. }) => return Err(refused()),
5693        };
5694        // A distance the template wrote, or the one in an operand the template pointed at, which is
5695        // the same distance said by something that knows how big a thing is. It has to be a number
5696        // the compiler can read at translation time, since it goes in the instruction rather than
5697        // in a register, and an operand holding anything else is refused rather than put somewhere.
5698        let disp = match at.disp {
5699            x86_64::Disp::Number(disp) => disp,
5700            x86_64::Disp::Operand(index) => {
5701                let value =
5702                    list.get(index).and_then(|operand| operand.value).ok_or_else(refused)?;
5703                let number = self.number(value).ok_or_else(refused)?;
5704                i32::try_from(number).map_err(|_| refused())?
5705            }
5706        };
5707        Ok(mir::Mem { base, scale: 1, disp, segment: at.segment, ..mir::Mem::default() })
5708    }
5709
5710    /// The number in that value, for one an `iconst` defined, read at the width of its own type.
5711    ///
5712    /// Signed, because the two things a template asks this for are a distance into an address and
5713    /// the number on an instruction, and both of those are signed wherever they land. A constant
5714    /// whose type is unsigned and whose top bit is set therefore reads as a negative number here,
5715    /// which is the same number and is the reading that fits in the thirty two bits an addressing
5716    /// mode has room for.
5717    fn number(&self, value: Value) -> Option<i128> {
5718        let Def::Result { inst, .. } = self.source[value].def else { return None };
5719        if self.source[inst].opcode != Opcode::IConst {
5720            return None;
5721        }
5722        let Extra::Imm(imm) = self.source[inst].extra else { return None };
5723        let bits = self.source[imm].bits();
5724        let width = self.source[value].ty.bits();
5725        if width == 0 || width > 128 {
5726            return None;
5727        }
5728        let spare = 128 - width;
5729        Some(((bits << spare) as i128) >> spare)
5730    }
5731
5732    /// A register holding a value the program has no claim on, written as a zero.
5733    ///
5734    /// Every other way of saying it costs the same instruction or needs a word the machine IR does
5735    /// not have, and a zero is the one that reads the same on every run.
5736    fn undefined(&mut self, inst: Inst, result: Value) -> Result<(), Unsupported> {
5737        let ty = self.source[result].ty;
5738        let refused = Unsupported::Assembly { inst, refused: Written::Operand };
5739        let bits = held_bits(ty);
5740        if self.class_of(ty) != self.gpr || !matches!(bits, 8 | 16 | 32 | 64) {
5741            return Err(refused);
5742        }
5743        let block = self.at.expect("a block is being filled");
5744        let span = self.source.span(inst);
5745        let reg = self.new_reg(result);
5746        let put = self.named(&format!("mov_ri_{bits}"));
5747        self.out.build(block, put).at(span).def(reg, self.gpr).imm(0).finish();
5748        Ok(())
5749    }
5750
5751    /// Whether a type is the width an address is, which is what makes a cast to or from one free.
5752    fn is_address_width(&self, ty: Type) -> bool {
5753        ty.is_ptr() || (ty.is_int() && ty.bits() == ADDRESS_BITS)
5754    }
5755
5756    /// Where a block goes, which in machine IR is on the block rather than on its terminator.
5757    ///
5758    /// That is why no rule ever names a block: a branch is selected for what it reads and the
5759    /// edges are copied across here, arguments and all. The arguments are read last, after every
5760    /// instruction of the block is written, because an argument that is a constant is
5761    /// materialized where it is first wanted and the end of the block is where an edge wants it.
5762    ///
5763    /// Which is not quite the end. A block that leaves two ways has the branch as its last
5764    /// instruction, and a block that leaves through a register has the indirect jump as its last,
5765    /// and anything appended after either is something it has already jumped past, so a constant
5766    /// materialized here would be a register the block below reads and nothing ever writes. The
5767    /// one that was there is put back on the end when that happened, which is the only reordering
5768    /// anything in this crate does and is why it is remembered before a single argument is read.
5769    fn edges(&mut self, block: Block, out: mir::Block) -> Result<(), Unsupported> {
5770        let Some(term) = self.source.terminator(block) else { return Ok(()) };
5771        // An `asm goto` whose template has nothing in it can only fall through, since there is no
5772        // instruction in it to jump with, so the only edge the machine block gets is the first
5773        // one. The labels it names are still arms in the IR, which is what kept the passes above
5774        // from assuming anything about the way into them, and here they are blocks nothing jumps
5775        // to, the same as a label no `goto` names. One that does have instructions was refused by
5776        // [`Self::jumps_from_text`] before this.
5777        if self.source[term].opcode == Opcode::InlineAsm {
5778            let Some(call) = self.source.successors(term).next() else { return Ok(()) };
5779            let args: Vec<Value> = self.source[call.args].to_vec();
5780            let regs =
5781                args.into_iter().map(|value| self.reg_of(value)).collect::<Result<_, _>>()?;
5782            *self.out.succs_mut(out) = vec![mir::BlockCall::with(self.out_block(call.block), regs)];
5783            return Ok(());
5784        }
5785        // A call's unwind edge, which is not an edge of the machine function at all. The branch was
5786        // never written, so what the block has is the arm control takes when the call returns, and
5787        // the pad is a block with nothing in front of it that the call site table is what reaches.
5788        // See [`Self::pad`] for why that is a block the allocator can be handed.
5789        if let Some(unwound) = self.unwind_edge(term) {
5790            let arms: Vec<rucc_ir::BlockCall> = self.source.successors(term).collect();
5791            let next = arms[1];
5792            let args: Vec<Value> = self.source[next.args].to_vec();
5793            let regs =
5794                args.into_iter().map(|value| self.reg_of(value)).collect::<Result<_, _>>()?;
5795            *self.out.succs_mut(out) = vec![mir::BlockCall::with(self.out_block(next.block), regs)];
5796            let call = self.source.prev_inst(unwound).and_then(|call| self.unwinding.get(&call));
5797            if let Some(&call) = call {
5798                let pad = self.out_block(arms[0].block);
5799                self.out.landings.push((call, pad));
5800            }
5801            return Ok(());
5802        }
5803        let leaves =
5804            matches!(self.source[term].opcode, Opcode::BrIf | Opcode::IndirectBr | Opcode::Switch);
5805        let branch = if leaves { self.out.terminator(out) } else { None };
5806
5807        let calls: Vec<rucc_ir::BlockCall> = self.source.successors(term).collect();
5808        let mut succs = Vec::with_capacity(calls.len());
5809        for call in calls {
5810            let args: Vec<Value> = self.source[call.args].to_vec();
5811            let mut regs = Vec::with_capacity(args.len());
5812            for value in args {
5813                // The address of where the value is rather than the value, for the one type a
5814                // register holds none of. The block on the other side copies the bytes out of it
5815                // into a slot of its own, which is what makes a second edge into the same block
5816                // safe.
5817                let reg = if on_x87(self.source[value].ty) {
5818                    self.x87_slot(value)
5819                } else {
5820                    self.reg_of(value)?
5821                };
5822                regs.push(reg);
5823            }
5824            succs.push(mir::BlockCall::with(self.out_block(call.block), regs));
5825        }
5826        if let Some(branch) = branch {
5827            if self.out.terminator(out) != Some(branch) {
5828                self.out.remove_inst(branch);
5829                self.out.append_inst(out, branch);
5830            }
5831        }
5832        *self.out.succs_mut(out) = succs;
5833        Ok(())
5834    }
5835
5836    /// The `unwound` a branch reads, when the branch is a call's unwind edge.
5837    fn unwind_edge(&self, inst: Inst) -> Option<Inst> {
5838        let data = &self.source[inst];
5839        if data.opcode != Opcode::BrIf {
5840            return None;
5841        }
5842        let &cond = self.source[data.args].first()?;
5843        match self.source[cond].def {
5844            Def::Result { inst, .. } if self.source[inst].opcode == Opcode::Unwound => Some(inst),
5845            _ => None,
5846        }
5847    }
5848
5849    /// The exception a landing pad was entered with, as a copy out of the register the unwinder
5850    /// left it in, which is the first register a value comes back in.
5851    fn landing(&mut self, inst: Inst) -> Result<(), Unsupported> {
5852        let result = self.source[inst].first_result.ok_or_else(|| self.unsupported(inst))?;
5853        let held = *self.conv.int_returns.first().ok_or_else(|| self.unsupported(inst))?;
5854        let block = self.at.expect("a block is being filled");
5855        let span = self.source.span(inst);
5856        let mov = self.selector.frame.moves(self.gpr).expect("a class the target says how to move");
5857        let mov = self.named(mov.mov);
5858        let into = self.new_reg(result);
5859        self.out
5860            .build(block, mov)
5861            .at(span)
5862            .operand(mir::Operand::write(into, self.gpr))
5863            .operand(
5864                mir::Operand::read(mir::Reg::physical(held), self.gpr)
5865                    .with(Constraint::Fixed(held)),
5866            )
5867            .finish();
5868        Ok(())
5869    }
5870
5871    /// Makes a landing pad a block that reads nothing from the blocks around it, and says what to
5872    /// put back once it has been filled.
5873    ///
5874    /// The pad has no machine block in front of it, because the edge into it is not one the machine
5875    /// takes: control arrives from the unwinder, with the registers the frame rules at the call put
5876    /// back. So nothing the allocator keeps in a register can reach it, and a value it reads from
5877    /// elsewhere is made again inside it. What a pad reads is the address of each object a handler
5878    /// is owed, which is a slot of the frame, the address of a name, or a constant, and each of
5879    /// those can be written a second time from nothing. Anything else is refused.
5880    ///
5881    /// The registers the rest of the function knows those values by are put back afterwards,
5882    /// which is what the answer is for: the pad's copies are its own.
5883    fn pad(&mut self, block: Block) -> Result<Vec<(Value, Option<mir::Reg>)>, Unsupported> {
5884        let mut kept = Vec::new();
5885        let first = self.source.insts(block).next();
5886        if !first.is_some_and(|inst| self.source[inst].opcode == Opcode::Landing) {
5887            return Ok(kept);
5888        }
5889        let out = self.at.expect("a block is being filled");
5890        let insts: Vec<Inst> = self.source.insts(block).collect();
5891        for inst in insts {
5892            let args: Vec<Value> = self.source[self.source[inst].args].to_vec();
5893            for value in args {
5894                let Def::Result { inst: def, .. } = self.source[value].def else {
5895                    return Err(self.unsupported(inst));
5896                };
5897                if self.source.block_of(def) == Some(block)
5898                    || kept.iter().any(|&(done, _)| done == value)
5899                {
5900                    continue;
5901                }
5902                match self.source[def].opcode {
5903                    Opcode::IConst => {}
5904                    Opcode::Alloca => {
5905                        let &index =
5906                            self.frame_slots.get(&value).ok_or_else(|| self.unsupported(def))?;
5907                        kept.push((value, self.regs[value.index()]));
5908                        let reg = self.out.new_vreg(self.gpr);
5909                        self.regs[value.index()] = Some(reg);
5910                        let lea = self.named(self.selector.frame.lea);
5911                        let sp = mir::Reg::physical(self.conv.stack_pointer);
5912                        let sp = mir::Operand::read(sp, self.gpr);
5913                        let span = self.source.span(def);
5914                        let made = self
5915                            .out
5916                            .build(out, lea)
5917                            .at(span)
5918                            .def(reg, self.gpr)
5919                            .mem(mir::Mem::at(sp))
5920                            .finish();
5921                        self.stack.addresses.push((made, index));
5922                    }
5923                    Opcode::GlobalAddr => {
5924                        kept.push((value, self.regs[value.index()]));
5925                        self.regs[value.index()] = None;
5926                        self.address_of(def)?;
5927                    }
5928                    _ => return Err(self.unsupported(def)),
5929                }
5930            }
5931        }
5932        Ok(kept)
5933    }
5934
5935    /// Whether an `asm goto` has instructions in its template, which is what it would jump with.
5936    ///
5937    /// One with an empty template is what a program writes to tell the optimizer that control may
5938    /// arrive at a label without saying how, and the torture suite has several of them. It never
5939    /// jumps, so it is written as the statement it would be without its labels and a fall through
5940    /// into its first arm. See [`Self::edges`]. One with anything in it needs the labels it names
5941    /// written into the text and an edge for each of them the allocator knows about, and that is
5942    /// still refused.
5943    fn jumps_from_text(&self, inst: Inst) -> bool {
5944        let Extra::Asm(asm) = self.source[inst].extra else { return false };
5945        let info = self.source[asm];
5946        !self.source[info.targets].is_empty()
5947            && !self.names.resolve(info.template).trim().is_empty()
5948    }
5949
5950    /// The machine IR block an IR block became.
5951    fn out_block(&self, block: Block) -> mir::Block {
5952        self.blocks[block.index()].expect("every block was created before any was filled")
5953    }
5954
5955    /// The parameters of the entry block, which are the function's arguments.
5956    ///
5957    /// They are not block parameters in the machine IR and they cannot be. A block parameter is
5958    /// given its value by a move on the edge into the block, and there is no edge into an entry
5959    /// block, so what arrives in a function is the convention's to say. [`crate::abi`] is what
5960    /// says it.
5961    ///
5962    /// The ones past the last register arrived in the caller's memory and are read out of it, and
5963    /// the loads that read them come back here so that the frame can finish them the way it
5964    /// finishes an `alloca`.
5965    fn arrive(&mut self, block: Block, out: mir::Block) -> Result<(), Unsupported> {
5966        let params = self.source[block].params.clone();
5967        // The type of each is the block's answer and what the ABI asks of it is the signature's,
5968        // and the two lists are the same list: a parameter the classification turned into a
5969        // pointer is a pointer in the block too. A block with more parameters than the signature
5970        // names is not one the front end writes, and each of those is taken as a plain value.
5971        let asked: Vec<Abi> = self.source.signature().params.iter().map(|it| it.abi).collect();
5972        let types: Vec<Param> = params
5973            .iter()
5974            .enumerate()
5975            .map(|(index, &value)| {
5976                let abi = asked.get(index).copied().unwrap_or_default();
5977                Param { ty: self.source[value].ty, abi }
5978            })
5979            .collect();
5980        // A save area for a function that takes arguments its signature does not name, which is a
5981        // block of this function's frame on one convention and the shadow space the caller already
5982        // reserved on the other. Which of the two it is is [`varargs::Area::of`]'s answer and
5983        // [`Self::save_area`] is where the difference is spent.
5984        //
5985        // Apple's AArch64 is neither. Every argument a signature does not name is in the caller's
5986        // memory, so there is nothing to save and the list starts at the first word past the named
5987        // ones.
5988        //
5989        // A function holding `__builtin_apply_args` asks for the same area whether it is variadic
5990        // or not, because what it saves is every argument register, and the area is where the
5991        // walk that binds them says where each one goes.
5992        //
5993        // Windows on AArch64 is the first kind seen from the other side. The caller reserves
5994        // nothing, so the function takes the words it homes its x registers in at the top of its
5995        // own frame, and from inside it that is a shadow space like Windows x64's. So the
5996        // registers the parameters are bound through are [`rucc_target::CallRegs::homed`], and
5997        // the prologue [`crate::finish`] writes takes the bytes before it saves anything.
5998        let variadic = self.source.signature().variadic;
5999        let foreign = self.source.signature().convention != Convention::Target;
6000        let homes = variadic && !foreign && self.conv.home > 0;
6001        let conv = if homes { self.conv.homed() } else { *self.conv };
6002        if homes {
6003            self.stack.home = self.conv.home;
6004        }
6005        let in_memory = self.conv.abi.variadic == Variadic::AlwaysMemory;
6006        let applies = self.saves_arguments();
6007        let area = (variadic && !in_memory || applies).then(|| varargs::Area::of(&conv));
6008        let arrived =
6009            abi::entry(&mut self.out, out, &types, &conv, self.selector.abi, self.names, area)
6010                .map_err(|(index, missing)| Unsupported::Argument { index, missing })?;
6011        for (&param, reg) in params.iter().zip(&arrived.regs) {
6012            self.regs[param.index()] = Some(*reg);
6013        }
6014        if applies {
6015            self.save_arguments(out, &arrived);
6016        }
6017        // A variadic function of the convention the platform does not call its own has no list
6018        // this can start. Its `va_list` would have to be the other platform's, which is a type C
6019        // has no name for here, and the front end refuses a definition with `...` in it for that
6020        // reason. What is left is an old style definition, which is variadic to a caller and has
6021        // no `...` for a `va_start` to follow, so nothing is set up and a `va_start` that reached
6022        // here all the same would be refused rather than read the wrong list.
6023        let variadic = variadic && !foreign;
6024        if let (true, Some(area)) = (variadic && !in_memory, area) {
6025            self.save_area(out, &arrived, area, conv.shared_positions);
6026        } else if variadic {
6027            let incoming = arrived.beyond.next_multiple_of(self.conv.word);
6028            self.varargs = Some(Varargs::Pointer { incoming });
6029        }
6030        self.stack.arguments.extend(arrived.stack);
6031        Ok(())
6032    }
6033
6034    /// The prologue of a variadic function, which is every argument register it was handed written
6035    /// into the frame.
6036    ///
6037    /// Every one the signature did not name, that is. Which of those hold anything is a thing only
6038    /// the caller knew and there is nothing here to ask, so all of them are written, and the ones a
6039    /// named parameter took are not, because `va_start` sets the two offsets past them and nothing
6040    /// ever reads their slots.
6041    ///
6042    /// What that costs is up to fourteen stores in the prologue of a function that may read none of
6043    /// them, and the convention's answer to that is the count of vector registers in `%al`, which
6044    /// lets a callee skip the eight vector stores when the call passed no floats. Skipping them is a
6045    /// branch in a prologue, and a prologue is written long after this by [`crate::finish`], which
6046    /// has no blocks to branch between. So they are all written every time, which is correct and is
6047    /// what `-O0` costs. Issue #323 is the branch.
6048    ///
6049    /// A vector register is written all sixteen bytes at a time, because a `_Float128` fills one and
6050    /// a `va_arg` of a quad reads the slot back whole. gcc writes the same sixteen with the same
6051    /// instruction, which is what [`crate::varargs`] says a list has to be built out of.
6052    ///
6053    /// The address is computed once into a register rather than written as a displacement off the
6054    /// stack pointer, because a displacement into a frame is not known until after allocation and
6055    /// one `lea` costs less than a fixup list for a dozen stores. It is the same `lea` an `alloca`
6056    /// gets and [`crate::finish`] fills it in the same way.
6057    ///
6058    /// A convention that homes its register arguments has none of that. Its area is the shadow
6059    /// space the caller reserved above the return address, so there is no object to make and no
6060    /// address to work out: each store reaches into the caller's argument area the way the load of
6061    /// a parameter the registers ran out before does, which is the same waiting list and the same
6062    /// fixup. There are at most four of them and none is a vector register, since a float the
6063    /// signature does not name arrived in a general purpose register too and that is the copy the
6064    /// walk reads.
6065    ///
6066    /// Windows on AArch64 homes its registers the same way, in an area the function takes for
6067    /// itself rather than one the caller left, and `shared` is what says a function is one of these.
6068    fn save_area(
6069        &mut self,
6070        out: mir::Block,
6071        arrived: &abi::Arrived,
6072        area: varargs::Area,
6073        shared: bool,
6074    ) {
6075        if shared {
6076            self.varargs = Some(Varargs::Pointer { incoming: arrived.beyond });
6077            let head =
6078                (self.selector.abi.store)(Type::int(64)).expect("a store of a whole register");
6079            let store = mir::Opcode::new(self.names.intern(head));
6080            for &(reg, class, at) in &arrived.spare {
6081                let sp = mir::Operand::read(mir::Reg::physical(self.conv.stack_pointer), self.gpr);
6082                let made =
6083                    self.out.build(out, store).uses(reg, class).mem(mir::Mem::at(sp)).finish();
6084                self.stack.arguments.push((made, at));
6085            }
6086            return;
6087        }
6088
6089        let save = self.stack.locals.len();
6090        self.stack.locals.push(Local { size: area.size, align: varargs::VECTOR_SLOT });
6091        let took = |count: usize, float: bool| {
6092            let count = u32::try_from(count).unwrap_or(0).min(area.holds(float));
6093            area.starts_at(float) + count * area.stride(float)
6094        };
6095        let integers = took(arrived.took.0, false);
6096        let floats = took(arrived.took.1, true);
6097        self.varargs = Some(if self.conv.list == VaList::Aapcs {
6098            // Minus what is left of each half, since the two offsets count up to its top.
6099            let left = |at: u32, float: bool| {
6100                i32::try_from(at).unwrap_or(0) - i32::try_from(area.ends_at(float)).unwrap_or(0)
6101            };
6102            Varargs::Aapcs {
6103                save,
6104                incoming: arrived.beyond,
6105                integers_end: area.ends_at(false),
6106                floats_end: area.ends_at(true),
6107                integers: left(integers, false),
6108                floats: left(floats, true),
6109            }
6110        } else {
6111            Varargs::Fields { save, incoming: arrived.beyond, integers, floats }
6112        });
6113
6114        // A vector register is saved all sixteen bytes wide, as a quad is, whatever it held.
6115        let base = self.frame_address(out, save);
6116        for &(reg, class, at) in &arrived.spare {
6117            let ty =
6118                if class == self.gpr { Type::int(64) } else { Type::float(rucc_ir::Float::F128) };
6119            let head = (self.selector.abi.store)(ty).expect("a store of a whole register");
6120            let store = mir::Opcode::new(self.names.intern(head));
6121            let up = i32::try_from(at).expect("a register save area under two gigabytes");
6122            let mem = mir::Mem::at(mir::Operand::read(base, self.gpr)).plus(up);
6123            self.out.build(out, store).uses(reg, class).mem(mem).finish();
6124        }
6125    }
6126
6127    /// Whether the function holds a `__builtin_apply_args`, on a convention this can save the
6128    /// arguments of.
6129    ///
6130    /// Only the one that keeps the two register files apart and saves them the way a SysV list
6131    /// does, since the block is that layout with one word in front of it. On any other the call is
6132    /// refused where it stands, which is [`Self::apply_args`] finding nothing saved.
6133    fn saves_arguments(&self) -> bool {
6134        if self.conv.list != VaList::SysV || self.conv.shared_positions {
6135            return false;
6136        }
6137        let source = self.source;
6138        source
6139            .blocks()
6140            .any(|block| source.insts(block).any(|inst| source[inst].opcode == Opcode::ApplyArgs))
6141    }
6142
6143    /// The prologue of a function holding `__builtin_apply_args`, which is every argument register
6144    /// it was handed and where the arguments in memory start, written into a block of its frame.
6145    ///
6146    /// The block is the one gcc lays out on this convention, so that a program reading it the way
6147    /// gcc's manual says reads the same bytes:
6148    ///
6149    /// ```text
6150    ///   0        where the arguments that came in memory are
6151    ///   8        nothing, so that what follows is sixteen byte aligned
6152    ///   16..64   the six general purpose argument registers, a word each
6153    ///   64..192  the eight vector argument registers, sixteen bytes each
6154    /// ```
6155    ///
6156    /// Which is the register save area of a variadic function with a word and a pad in front, so
6157    /// the offsets are that area's plus sixteen. What is different is that every register is
6158    /// written and not only the ones no parameter took: the one a parameter arrived in is written
6159    /// from the register the parameter was bound to, which holds it untouched because nothing has
6160    /// run yet, and the rest from the pseudos the walk made for them.
6161    fn save_arguments(&mut self, out: mir::Block, arrived: &abi::Arrived) {
6162        let applied = self.stack.locals.len();
6163        self.stack.locals.push(Local { size: APPLY_ARGS, align: varargs::VECTOR_SLOT });
6164        self.applied = Some(applied);
6165        let base = self.frame_address(out, applied);
6166        let overflow = self.overflow(out, 0, Span::DUMMY);
6167        let head = (self.selector.abi.store)(Type::int(64)).expect("a store of an address");
6168        let store = mir::Opcode::new(self.names.intern(head));
6169        let mem = mir::Mem::at(mir::Operand::read(base, self.gpr));
6170        self.out.build(out, store).uses(overflow, self.gpr).mem(mem).finish();
6171
6172        let named = arrived.named.iter().map(|&(index, at)| {
6173            let reg = arrived.regs[index];
6174            let class = self.out.class_of(reg).unwrap_or(self.gpr);
6175            (reg, class, at)
6176        });
6177        let every: Vec<_> = named.chain(arrived.spare.iter().copied()).collect();
6178        for (reg, class, at) in every {
6179            let ty =
6180                if class == self.gpr { Type::int(64) } else { Type::float(rucc_ir::Float::F128) };
6181            let head = (self.selector.abi.store)(ty).expect("a store of a whole register");
6182            let store = mir::Opcode::new(self.names.intern(head));
6183            let up = i32::try_from(at + APPLY_REGS).expect("a block of under two gigabytes");
6184            let mem = mir::Mem::at(mir::Operand::read(base, self.gpr)).plus(up);
6185            self.out.build(out, store).uses(reg, class).mem(mem).finish();
6186        }
6187    }
6188
6189    /// One `__builtin_apply_args`, which is the address of the block the prologue wrote.
6190    fn apply_args(&mut self, inst: Inst) -> Result<(), Unsupported> {
6191        let Some(applied) = self.applied else { return Err(self.unsupported(inst)) };
6192        let result = self.source[inst].first_result.ok_or_else(|| self.unsupported(inst))?;
6193        let block = self.at.expect("a block is being filled");
6194        let reg = self.frame_address(block, applied);
6195        self.regs[result.index()] = Some(reg);
6196        Ok(())
6197    }
6198
6199    /// One `__builtin_apply`, which is a call whose arguments are every register in a block
6200    /// `__builtin_apply_args` answered and some bytes of the memory it says the arguments in
6201    /// memory were in.
6202    ///
6203    /// Built as a call of fourteen arguments, six words and eight vectors, which puts each in the
6204    /// register it came out of, and one object of the size the program gave, which is copied into
6205    /// the bottom of the outgoing area the way a structure passed by value is. The call is made as
6206    /// to a variadic function, so the count of vector registers is eight and a variadic callee
6207    /// saves all of them.
6208    ///
6209    /// What comes back is every register a value can come back in, which is two of each file, and
6210    /// they are written into a block of this function's frame whose address is the answer: the two
6211    /// words at 0 and 8 and the two vectors at 16 and 32. An eighty bit value comes back on the x87
6212    /// stack and is not in it, which is the one thing gcc's block holds that this one does not.
6213    fn apply(&mut self, inst: Inst) -> Result<(), Unsupported> {
6214        if self.conv.list != VaList::SysV || self.conv.shared_positions {
6215            return Err(self.unsupported(inst));
6216        }
6217        let values: Vec<Value> = self.source[self.source[inst].args].to_vec();
6218        let [function, saved, size] = values[..] else { return Err(self.unsupported(inst)) };
6219        let size = self.number(size).ok_or_else(|| self.unsupported(inst))?;
6220        let size = u32::try_from(size).map_err(|_| self.unsupported(inst))?;
6221        let result = self.source[inst].first_result.ok_or_else(|| self.unsupported(inst))?;
6222        let function = self.reg_of(function)?;
6223        let saved = self.reg_of(saved)?;
6224        let block = self.at.expect("a block is being filled");
6225        let span = self.source.span(inst);
6226
6227        let word = Type::int(64);
6228        let vector = Type::float(rucc_ir::Float::F128);
6229        let area = varargs::Area::of(self.conv);
6230        let load = |ty: Type| (self.selector.abi.load)(ty).expect("a load of a whole register");
6231        let (load_word, load_vector) = (load(word), load(vector));
6232        let mut read = |ty: Type, head: &str, class: RegClass, at: u32| {
6233            let reg = self.out.new_vreg(class);
6234            let opcode = mir::Opcode::new(self.names.intern(head));
6235            let at = i32::try_from(at).expect("a block of under two gigabytes");
6236            let mem = mir::Mem::at(mir::Operand::read(saved, self.gpr)).plus(at);
6237            self.out.build(block, opcode).at(span).def(reg, class).mem(mem).finish();
6238            abi::Passing { ty, reg, abi: Abi::Plain }
6239        };
6240        let sse = self.conv.sse_class;
6241        let gpr = self.gpr;
6242        let mut args = Vec::with_capacity(15);
6243        for (float, ty, head, class) in
6244            [(false, word, load_word, gpr), (true, vector, load_vector, sse)]
6245        {
6246            for index in 0..area.holds(float) {
6247                let at = APPLY_REGS + area.starts_at(float) + index * area.stride(float);
6248                args.push(read(ty, head, class, at));
6249            }
6250        }
6251        if size > 0 {
6252            let memory = read(word, load_word, gpr, 0);
6253            let object =
6254                Abi::ByVal { size: u64::from(size), align: 8, drains: rucc_ir::Drains::Nothing };
6255            args.push(abi::Passing { abi: object, ..memory });
6256        }
6257        let returns = [word, word, vector, vector];
6258        let what = abi::Calling {
6259            callee: abi::Callee::Through(function),
6260            args: &args,
6261            returns: &returns,
6262            variadic: true,
6263            named: args.len(),
6264            at: span,
6265        };
6266        let made = abi::call(&mut self.out, block, &what, self.conv, self.selector.abi, self.names)
6267            .map_err(|refused| Unsupported::Call { inst, refused })?;
6268        let calls = &mut self.stack.calls;
6269        *calls = Some(calls.unwrap_or(0).max(made.outgoing));
6270
6271        let back = self.stack.locals.len();
6272        self.stack.locals.push(Local { size: APPLY_BACK, align: varargs::VECTOR_SLOT });
6273        let base = self.frame_address(block, back);
6274        for ((&reg, ty), at) in made.results.iter().zip(returns).zip([0, 8, 16, 32]) {
6275            let class = if ty == word { gpr } else { sse };
6276            let head = (self.selector.abi.store)(ty).expect("a store of a whole register");
6277            let store = mir::Opcode::new(self.names.intern(head));
6278            let mem = mir::Mem::at(mir::Operand::read(base, self.gpr)).plus(at);
6279            self.out.build(block, store).at(span).uses(reg, class).mem(mem).finish();
6280        }
6281        let answer = self.frame_address(block, back);
6282        self.regs[result.index()] = Some(answer);
6283        Ok(())
6284    }
6285
6286    /// The address of one of the function's stack objects, in a fresh register.
6287    ///
6288    /// Written with nothing in its displacement, because where an object is in a frame is not known
6289    /// until after allocation, and given to [`crate::finish`] to fill in the way an `alloca` is.
6290    fn frame_address(&mut self, out: mir::Block, local: usize) -> mir::Reg {
6291        self.frame_address_plus(out, local, 0)
6292    }
6293
6294    /// The address some way into a local, which the frame finishes the same way, adding where the
6295    /// local is to what is already there.
6296    fn frame_address_plus(&mut self, out: mir::Block, local: usize, plus: u32) -> mir::Reg {
6297        let reg = self.out.new_vreg(self.gpr);
6298        let lea = self.named(self.selector.frame.lea);
6299        let sp = mir::Operand::read(mir::Reg::physical(self.conv.stack_pointer), self.gpr);
6300        let plus = i32::try_from(plus).expect("an offset into a local under two gigabytes");
6301        let mem = mir::Mem::at(sp).plus(plus);
6302        let made = self.out.build(out, lea).def(reg, self.gpr).mem(mem).finish();
6303        self.stack.addresses.push((made, local));
6304        reg
6305    }
6306
6307    /// Whether an instruction is one no machine instruction is written for where it stands.
6308    ///
6309    /// Four of them, and none is a lowering decision, which is why none is a rule. A constant is
6310    /// written where a register for it is first wanted rather than where the IR put it, and every
6311    /// reader of one may have folded it into an immediate, in which case nowhere is the right
6312    /// place. A return of nothing has nothing to put anywhere: the epilogue gives the frame back
6313    /// and leaves, and it is appended to every block with no successors long after this has
6314    /// finished, so a return with a value is one instruction here and a return without one is
6315    /// none. Unless the value went back through memory, in which case there is something to put
6316    /// somewhere after all and the IR does not carry it: the address the caller handed over has
6317    /// to be in `rax` on the way out, and [`Lowering::returned`] is what writes that.
6318    ///
6319    /// An unconditional jump is the third, and there is even less of it: the edge is on the
6320    /// block, and whether the block it goes to is the next one and needs no jump at all is the
6321    /// block layout's answer rather than this one's.
6322    ///
6323    /// The fourth is a point control does not arrive at, in both of the forms the IR has for it:
6324    /// the `unreachable` terminator the front end puts at the end of a function whose body can run
6325    /// off the bottom, and the `unreachable_hint` a call to `__builtin_unreachable` becomes. What
6326    /// to write for a place nothing reaches is a question with no wrong answer, and nothing is the
6327    /// smallest one and the one gcc 16.2.0 gives at `-O0`. The terminator leaves the block with no
6328    /// successors, so the epilogue lands at the end of it the way it does on any other block that
6329    /// goes nowhere, and the function cannot fall out of its own last instruction into whatever
6330    /// the assembler puts next.
6331    fn writes_nothing(&self, inst: Inst) -> bool {
6332        let data = &self.source[inst];
6333        match data.opcode {
6334            Opcode::IConst | Opcode::Jump | Opcode::Unreachable | Opcode::UnreachableHint => true,
6335            // The question of whether a call unwound and the branch on its answer, neither of which
6336            // is an instruction. See [`Self::edges`].
6337            Opcode::Unwound => true,
6338            Opcode::BrIf => self.unwind_edge(inst).is_some(),
6339            Opcode::Return => self.source[data.args].is_empty() && self.sret().is_none(),
6340            _ => false,
6341        }
6342    }
6343
6344    /// What every instruction in one block matched, with a set of values nobody may take.
6345    ///
6346    /// Backwards, because an instruction that has been folded into a later one does not get to
6347    /// fold anything into itself: the rule that took it only reached one level down, so what is
6348    /// under it is not in the term the matcher saw and cannot be replaced.
6349    fn decide(&self, insts: &[Inst], refused: &HashSet<Value>) -> Decided {
6350        let mut found: Vec<Option<Match<Term>>> = (0..insts.len()).map(|_| None).collect();
6351        let mut plans: Vec<Option<Plan>> = vec![None; insts.len()];
6352        let mut folded: Vec<Inst> = Vec::new();
6353        for (index, &inst) in insts.iter().enumerate().rev() {
6354            if folded.contains(&inst) {
6355                continue;
6356            }
6357            if let Some((plan, matched)) = self.select(inst, refused) {
6358                folded.extend(self.folds(inst, plan));
6359                found[index] = Some(matched);
6360                plans[index] = Some(plan);
6361            }
6362        }
6363        Decided { found, plans, folded }
6364    }
6365
6366    /// A value some of its readers took and some of them did not, which is the one case folding
6367    /// buys nothing.
6368    ///
6369    /// Folding does not delete the instruction that computed a value for anybody else, so a
6370    /// reader that did not take it still needs it in a register and the instruction stays. The
6371    /// reader that did take it now does that work again. Either all of them take it, in which
6372    /// case nothing is left to read it and the instruction goes, or none of them do.
6373    ///
6374    /// The count is over the whole function rather than over the block, since a value read from
6375    /// another block is read from a register there whatever this block decides. An instruction
6376    /// built by name rather than matched, a call being the one that matters, has no plan and so
6377    /// takes nothing, which is the right answer for it as well.
6378    ///
6379    /// The count is kept only for the values this block's instructions take. It used to be a slot
6380    /// for every value in the function, cleared for every block, and on a function of thirty
6381    /// thousand blocks and a hundred and seventy thousand values that clearing was four percent of
6382    /// an optimized compile.
6383    fn left_alive(&self, insts: &[Inst], plans: &[Option<Plan>]) -> Option<Value> {
6384        let mut taken: HashMap<Value, u32> = HashMap::new();
6385        for (&inst, plan) in insts.iter().zip(plans) {
6386            let Some(plan) = plan else { continue };
6387            let args = &self.source[self.source[inst].args];
6388            for (index, &arg) in args.iter().take(MAX_ARGS).enumerate() {
6389                if plan[index] == Shown::Expand {
6390                    *taken.entry(arg).or_default() += 1;
6391                }
6392            }
6393        }
6394        for (&inst, plan) in insts.iter().zip(plans) {
6395            let Some(plan) = plan else { continue };
6396            let args = &self.source[self.source[inst].args];
6397            for (index, &arg) in args.iter().take(MAX_ARGS).enumerate() {
6398                if plan[index] == Shown::Expand && taken[&arg] < self.uses[arg.index()] {
6399                    return Some(arg);
6400                }
6401            }
6402        }
6403        None
6404    }
6405
6406    /// The rule that fires on an instruction, and what it bound.
6407    ///
6408    /// The plans are tried in order and the first that matches wins, which is the maximal munch
6409    /// `spec/10-backend.md` asks for: a plan that offers more to the matcher is tried before one
6410    /// that offers less.
6411    fn select(&self, inst: Inst, refused: &HashSet<Value>) -> Option<(Plan, Match<Term>)> {
6412        for plan in self.plans(inst, refused) {
6413            let terms = Terms::new(self.source, inst, plan);
6414            if let Some(matched) = self.selector.table.find(&terms, Term::Root) {
6415                return Some((plan, matched));
6416            }
6417        }
6418        None
6419    }
6420
6421    /// Every way this instruction can be shown to the matcher, most offered first.
6422    ///
6423    /// That is every choice of a way to show each operand, with the choice for the first operand
6424    /// changing slowest. The plans are counted out rather than collected, because this is asked
6425    /// for every instruction that is selected and the lists it used to build were an allocation
6426    /// or two per operand.
6427    fn plans(&self, inst: Inst, refused: &HashSet<Value>) -> impl Iterator<Item = Plan> {
6428        let args = &self.source[self.source[inst].args];
6429        let mut ways = [[Shown::Reg; 3]; MAX_ARGS];
6430        let mut counts = [1; MAX_ARGS];
6431        for (index, &arg) in args.iter().enumerate().take(MAX_ARGS) {
6432            let mut count = 0;
6433            if self.foldable(inst, arg, refused) {
6434                ways[index][count] = Shown::Expand;
6435                count += 1;
6436            }
6437            if Terms::new(self.source, inst, PLAIN).constant(arg).is_some() {
6438                ways[index][count] = Shown::Const;
6439                count += 1;
6440            }
6441            ways[index][count] = Shown::Reg;
6442            counts[index] = count + 1;
6443        }
6444        (0..counts.iter().product()).map(move |mut number: usize| {
6445            let mut plan = PLAIN;
6446            for index in (0..MAX_ARGS).rev() {
6447                plan[index] = ways[index][number % counts[index]];
6448                number /= counts[index];
6449            }
6450            plan
6451        })
6452    }
6453
6454    /// Whether an operand may be shown as the instruction that computed it.
6455    ///
6456    /// It has to be in the same block, because a rule that folds one instruction into another
6457    /// moves the work to where the second one is. It has to be something rather than a block
6458    /// parameter, and not a constant, which is shown as a constant instead. And it has to be a
6459    /// value [`Lowering::left_alive`] has not put back, which is how the one reader at a time
6460    /// question is asked here: this says yes to a value with any number of readers, and a value
6461    /// only some of them could take is refused after the fact and asked again.
6462    ///
6463    /// A value with several readers used to be refused outright, on the reasoning that folding
6464    /// does not delete the instruction for anybody else. That reasoning is about the set of
6465    /// readers and was being applied to one reader at a time, which is stricter than it needs to
6466    /// be: when every reader takes it there is nobody left to read it and the instruction goes.
6467    /// An address a store and a load share is the shape that matters, since a memory operand has
6468    /// room for the whole of it and both readers have a memory operand.
6469    fn foldable(&self, into: Inst, value: Value, refused: &HashSet<Value>) -> bool {
6470        let Def::Result { inst, .. } = self.source[value].def else { return false };
6471        if self.source[inst].opcode == Opcode::IConst || refused.contains(&value) {
6472            return false;
6473        }
6474        self.source.block_of(inst).is_some()
6475            && self.source.block_of(inst) == self.source.block_of(into)
6476    }
6477
6478    /// The instructions a match folded into the one it matched.
6479    ///
6480    /// The plan is what says this, not the bindings: a binding is a register or a number either
6481    /// way, and an operand shown as the instruction that computed it is one no rule could have
6482    /// matched without taking that instruction, because the plan offered the matcher nothing
6483    /// else to call it.
6484    fn folds(&self, inst: Inst, plan: Plan) -> Vec<Inst> {
6485        let args = &self.source[self.source[inst].args];
6486        args.iter()
6487            .take(MAX_ARGS)
6488            .enumerate()
6489            .filter(|&(index, _)| plan[index] == Shown::Expand)
6490            .filter_map(|(_, &arg)| match self.source[arg].def {
6491                Def::Result { inst, .. } => Some(inst),
6492                Def::Param { .. } => None,
6493            })
6494            .collect()
6495    }
6496
6497    /// What the IR instruction said about itself that the machine instruction has to keep saying.
6498    ///
6499    /// One flag today. `volatile` says the access happens exactly once and is never moved or
6500    /// merged, and nothing below here can work that out again: a `volatile` load and an ordinary
6501    /// one are the same instruction over the same address, so a pass that puts two accesses
6502    /// together would put these together too. Carried rather than checked here, because the pass
6503    /// that has to refuse is a long way down and this is the last place the answer is known.
6504    ///
6505    /// The instructions this compiler writes for itself get nothing, which is the right answer
6506    /// for all of them: a prologue, a spill and the moves around a call were asked for by the
6507    /// machine rather than by the program.
6508    ///
6509    /// Every access the flag is legal on carries it: the loads and the stores a rule matched,
6510    /// the two ends of a `long double` copy that are the program's own memory, and the compare
6511    /// and exchange and the read modify write. An `asm` statement does not, and it is the one
6512    /// exception on purpose. What the flag says there is that the statement stays even when
6513    /// nothing reads what it wrote, which is a different sentence about a different thing, and
6514    /// every `asm` is already fixed where it stands whether the word was written or not.
6515    fn carried(&self, inst: Inst) -> mir::Flags {
6516        if self.source[inst].flags.contains(Flags::VOLATILE) {
6517            mir::Flags::VOLATILE
6518        } else {
6519            mir::Flags::NONE
6520        }
6521    }
6522
6523    /// Build the machine instructions a match calls for.
6524    fn emit(&mut self, inst: Inst, matched: &Match<Term>) -> Result<(), Unsupported> {
6525        let rule: &Rule = self.selector.table.rule(matched);
6526        self.build(inst, rule.replacement, 0, &matched.bindings, true).map(|_| ())
6527    }
6528
6529    /// Build the machine term that starts at `at`, and give back the position after it and the
6530    /// register it wrote, if it wrote one.
6531    ///
6532    /// The outermost term computes what the IR instruction does, so what it writes is the
6533    /// register of the instruction's result. A term inside another is a step on the way and
6534    /// writes a register of its own, which the term around it then reads. Its operands are read
6535    /// before it is built and it is built before the term around it, so the instructions come
6536    /// out in the order the values are needed.
6537    fn build(
6538        &mut self,
6539        inst: Inst,
6540        pieces: &'static [Piece],
6541        at: usize,
6542        bindings: &[Term],
6543        outermost: bool,
6544    ) -> Result<(usize, Option<mir::Reg>), Unsupported> {
6545        let Some(Piece::App { head, arity }) = pieces.get(at) else {
6546            return Err(self.unsupported(inst));
6547        };
6548        let opcode =
6549            head.strip_prefix(self.selector.prefix()).ok_or_else(|| self.unsupported(inst))?;
6550        let descs = self.selector.operands(opcode).ok_or_else(|| self.unsupported(inst))?;
6551
6552        let mut read = Read::default();
6553        let mut at = at + 1;
6554        for _ in 0..*arity {
6555            at = self.read(inst, pieces, at, bindings, &mut read)?;
6556        }
6557
6558        let writes = descs.iter().take_while(|desc| desc.role.is_def()).count();
6559        if descs.len() - writes != read.regs.len() {
6560            return Err(self.unsupported(inst));
6561        }
6562
6563        // The first thing the instruction writes is what it computes, and any others are
6564        // registers the machine destroys on the way, which are fresh because nothing else is in
6565        // them and nothing reads them. An instruction that writes nothing at all is one whose
6566        // whole purpose is its effect, which is what a store is, and there is no result to put
6567        // anywhere.
6568        let mut regs = Vec::new();
6569        if writes > 0 {
6570            // A term inside another computes a step rather than the result, into a register only
6571            // the term around it reads.
6572            let first = match outermost {
6573                true => {
6574                    let result =
6575                        self.source[inst].first_result.ok_or_else(|| self.unsupported(inst))?;
6576                    self.new_reg(result)
6577                }
6578                false => self.out.new_vreg(descs[0].class),
6579            };
6580            regs.push(first);
6581            // The rest are the registers the machine destroys on the way, and the class each is in
6582            // is the one the instruction's description gives it rather than a guess, so that an
6583            // instruction that wrecks a register in the other file says so.
6584            regs.extend(descs[1..writes].iter().map(|desc| self.out.new_vreg(desc.class)));
6585        } else if !outermost || self.source[inst].first_result.is_some() {
6586            // A rule that throws away a value the IR gave a name to would leave every reader of
6587            // that name with nothing to read, so it is a rule this and the target disagree about.
6588            // So is a term inside another that writes nothing for the one around it to read.
6589            return Err(self.unsupported(inst));
6590        }
6591        let written = regs.first().copied();
6592        regs.extend(read.regs.iter().copied());
6593
6594        let block = self.at.expect("a block is being filled");
6595        let opcode = mir::Opcode::new(self.names.intern(head));
6596        let (span, flags) = (self.source.span(inst), self.carried(inst));
6597        let mut build = self.out.build(block, opcode).at(span).flags(flags);
6598        for (desc, reg) in descs.iter().zip(regs) {
6599            let operand = mir::Operand {
6600                reg,
6601                class: desc.class,
6602                role: desc.role,
6603                constraint: desc.constraint,
6604            };
6605            build = build.operand(operand);
6606        }
6607        if let Some(mem) = read.mem {
6608            build = build.mem(mem);
6609        }
6610        if let Some(imm) = read.imm {
6611            build = build.imm(imm);
6612        }
6613        build.finish();
6614        Ok((at, written))
6615    }
6616
6617    /// Read one argument of a replacement, which is a register, a number, an address or another
6618    /// machine term.
6619    ///
6620    /// Gives back the position after it, because a replacement is flat and an address or a term
6621    /// takes arguments of its own. A machine term is built on the spot, and what is read is the
6622    /// register it wrote.
6623    fn read(
6624        &mut self,
6625        inst: Inst,
6626        pieces: &'static [Piece],
6627        at: usize,
6628        bindings: &[Term],
6629        out: &mut Read,
6630    ) -> Result<usize, Unsupported> {
6631        match pieces.get(at) {
6632            Some(Piece::Int(value)) => {
6633                out.imm = i64::try_from(*value).ok();
6634                Ok(at + 1)
6635            }
6636            // A number the rule worked out of the ones it matched rather than one it wrote down,
6637            // which is an immediate once it has been worked out and is read here as one. It gives
6638            // nothing back when a binding it reads is a register, and a replacement that cannot be
6639            // built is a rule this file and the matcher disagree about, which is what `unsupported`
6640            // is for.
6641            Some(Piece::Computed { work, .. }) => {
6642                let matched: Vec<Option<i128>> = bindings
6643                    .iter()
6644                    .map(|term| match *term {
6645                        Term::Num(value) => Some(value),
6646                        _ => None,
6647                    })
6648                    .collect();
6649                let number = work(&matched).ok_or_else(|| self.unsupported(inst))?;
6650                out.imm = i64::try_from(number).ok();
6651                Ok(at + 1)
6652            }
6653            Some(Piece::Var { index, .. }) => {
6654                match bindings.get(*index) {
6655                    Some(&Term::Reg(value)) => {
6656                        let reg = self.reg_of(value)?;
6657                        out.regs.push(reg);
6658                    }
6659                    Some(&Term::Num(value)) => out.imm = i64::try_from(value).ok(),
6660                    // A pattern binds a register or a number and nothing else, so this is a
6661                    // rule the matcher and this file disagree about.
6662                    _ => return Err(self.unsupported(inst)),
6663                }
6664                Ok(at + 1)
6665            }
6666            Some(Piece::App { head, .. }) if (self.selector.address)(head).is_none() => {
6667                let (next, reg) = self.build(inst, pieces, at, bindings, false)?;
6668                out.regs.push(reg.ok_or_else(|| self.unsupported(inst))?);
6669                Ok(next)
6670            }
6671            Some(Piece::App { head, arity }) => {
6672                let kind = (self.selector.address)(head).ok_or_else(|| self.unsupported(inst))?;
6673                let mut inner = Read::default();
6674                let mut next = at + 1;
6675                for _ in 0..*arity {
6676                    next = self.read(inst, pieces, next, bindings, &mut inner)?;
6677                }
6678                let mem = address(kind, &inner, self.gpr).ok_or_else(|| self.unsupported(inst))?;
6679                out.mem = Some(mem);
6680                Ok(next)
6681            }
6682            None => Err(self.unsupported(inst)),
6683        }
6684    }
6685
6686    /// The register a value is in, materializing it if it is a constant that has not been put in
6687    /// one yet.
6688    ///
6689    /// A constant is written where it is wanted rather than where the IR defined it, and where it
6690    /// is wanted is a block that need not be the one the IR defined it in. So the register holding
6691    /// one is only good inside the block it was written into, and a second block that wants the
6692    /// same constant gets its own. Anything else is a register read where nothing wrote it: the
6693    /// IR guarantees a definition dominates its uses, and this moved the definition.
6694    ///
6695    /// Writing the number again is also the right answer and not merely the safe one. It is one
6696    /// instruction that reads nothing, which is cheaper than holding a register live across a
6697    /// branch for it, and it is what a rematerializing allocator would do with the value anyway.
6698    fn reg_of(&mut self, value: Value) -> Result<mir::Reg, Unsupported> {
6699        let constant = match self.source[value].def {
6700            Def::Result { inst, .. } => {
6701                (self.source[inst].opcode == Opcode::IConst).then_some(inst)
6702            }
6703            Def::Param { .. } => None,
6704        };
6705        let here = self.at.expect("a block is being filled");
6706        if let Some(reg) = self.regs[value.index()] {
6707            if constant.is_none() || self.written[value.index()] == Some(here) {
6708                return Ok(reg);
6709            }
6710        }
6711        if let Some(inst) = constant {
6712            // Cleared so that the register the constant is written into is a new one rather than
6713            // the one the block above wrote, which is still being read up there.
6714            self.regs[value.index()] = None;
6715            // Nothing is refused here. A constant is written on its own, out of the loop over the
6716            // block, and the operands of the rule that writes one are the number and nothing else.
6717            let matched = self
6718                .select(inst, &HashSet::new())
6719                .map(|(_, matched)| matched)
6720                .ok_or_else(|| self.unsupported(inst))?;
6721            self.emit(inst, &matched)?;
6722            // The same mark the loop over the instructions makes, and it has to be made here as
6723            // well because this is the only place a constant is ever selected: the loop skips one
6724            // where the IR wrote it, so a rule that lowers a constant fires from nowhere else and
6725            // would be reported as a rule nothing reaches.
6726            self.fired.mark(matched.rule);
6727            self.written[value.index()] = Some(here);
6728            return Ok(self.regs[value.index()].expect("a constant is written into a register"));
6729        }
6730        Ok(self.new_reg(value))
6731    }
6732
6733    /// Which register file a value of that type lives in.
6734    ///
6735    /// The vector one for the two float widths the machine has scalar instructions for and for the
6736    /// one it only moves, and the general purpose one for everything else. An eighty bit `long
6737    /// double` is in neither, and it is here rather than in the vector class on purpose: it would
6738    /// be put in a register that cannot hold it, and there is no rule that names one, so the
6739    /// instruction computing it is reported. The wrong class would make that a wrong program
6740    /// instead of a refused one.
6741    ///
6742    /// A hundred and twenty eight bit float is in the vector class and fits it exactly, which is
6743    /// the difference. Nothing computes in it, so every arithmetic on one is still reported, and
6744    /// what the class buys is the moves: a register that holds the whole value is a register a
6745    /// spill, a reload and a copy are each one instruction for.
6746    fn class_of(&self, ty: Type) -> RegClass {
6747        if crate::term::in_vector_file(ty) { self.conv.sse_class } else { self.gpr }
6748    }
6749
6750    /// A fresh register for a value, which is what the instruction computing it writes.
6751    ///
6752    /// Any declaration the value is a value of comes with it. Here rather than once at the end over
6753    /// the whole map, because a constant is written again in every block that wants one and the map
6754    /// only remembers the last of those registers, and a local held in a constant is a local that
6755    /// would otherwise be findable in one block of the function and nowhere else.
6756    fn new_reg(&mut self, value: Value) -> mir::Reg {
6757        if let Some(reg) = self.regs[value.index()] {
6758            return reg;
6759        }
6760        let ty = self.source[value].ty;
6761        let reg = self.out.new_vreg(self.class_of(ty));
6762        self.sized(reg, ty);
6763        self.regs[value.index()] = Some(reg);
6764        let source = self.source;
6765        for decl in source.value_decls(value) {
6766            self.out.named.push((decl, reg));
6767        }
6768        reg
6769    }
6770
6771    /// Says how much of its register a value of that type takes, when the register is a vector
6772    /// one, which is what lets a call that keeps only the bottom of one keep the value in it.
6773    fn sized(&mut self, reg: mir::Reg, ty: Type) {
6774        if crate::term::in_vector_file(ty) {
6775            self.out.set_width(reg, abi::float_bytes(ty));
6776        }
6777    }
6778
6779    fn unsupported(&self, inst: Inst) -> Unsupported {
6780        let data = &self.source[inst];
6781        Unsupported::Inst {
6782            inst,
6783            term: Terms::new(self.source, inst, PLAIN).name(inst),
6784            opcode: data.opcode,
6785            ty: data.first_result.map(|result| self.source[result].ty),
6786        }
6787    }
6788}
6789
6790/// What the arguments of one replacement came to.
6791#[derive(Debug, Default)]
6792struct Read {
6793    regs: Vec<mir::Reg>,
6794    imm: Option<i64>,
6795    mem: Option<mir::Mem>,
6796}
6797
6798/// The addressing mode an address constructor's arguments make.
6799///
6800/// One arm per constructor rather than a question asked of the kind, because what the arguments
6801/// mean is the whole of what tells the four apart: the same register is a base in one and an
6802/// index in another, and the same constant is a scale in one and a displacement in another.
6803fn address(kind: Address, read: &Read, gpr: RegClass) -> Option<mir::Mem> {
6804    let mut regs = read.regs.iter().copied().map(|reg| mir::Operand::read(reg, gpr));
6805    match kind {
6806        Address::BaseIndexScale => {
6807            let base = regs.next()?;
6808            let index = regs.next()?;
6809            Some(mir::Mem::at(base).indexed(index, u8::try_from(read.imm?).ok()?))
6810        }
6811        Address::IndexScale => Some(mir::Mem {
6812            base: None,
6813            index: Some(regs.next()?),
6814            scale: u8::try_from(read.imm?).ok()?,
6815            disp: 0,
6816            symbol: None,
6817            block: None,
6818            table: None,
6819            reach: mir::Reach::Itself,
6820            segment: None,
6821        }),
6822        Address::Base => Some(mir::Mem::at(regs.next()?)),
6823        // The rule that writes this has a guard saying the constant fits, so a displacement that
6824        // does not is a rule and a target that disagree rather than a program this cannot compile.
6825        Address::BaseOffset => {
6826            Some(mir::Mem { disp: i32::try_from(read.imm?).ok()?, ..mir::Mem::at(regs.next()?) })
6827        }
6828    }
6829}
6830
6831#[cfg(test)]
6832mod tests {
6833    use rucc_ir::{
6834        AsmInfo, Builder, CallInfo, Flags, InstData, MemInfo, MemOrder, Restrict, Signature, Type,
6835    };
6836    use rucc_regalloc::assign::Env;
6837    use rucc_target::x86_64::{FRAME, REGS, SYSV};
6838
6839    use super::*;
6840    use crate::finish::{Convention, finish};
6841    use crate::frame::{Frame, Incoming, Layout};
6842    use crate::select::x86_64::SELECTOR;
6843
6844    /// A function of as many 64 bit parameters as the test wants, and the block they are in.
6845    fn blank(params: &[Type]) -> (Interner, Func, Block, Vec<Value>) {
6846        let mut names = Interner::new();
6847        let mut func = Func::new(names.intern("f"), Signature::new());
6848        let block = func.create_block();
6849        let values = params.iter().map(|&ty| func.append_param(block, ty)).collect();
6850        (names, func, block, values)
6851    }
6852
6853    /// An ordinary access: not atomic, and aligned enough that nothing here has an opinion.
6854    /// Neither field reaches selection, which is the point of saying it once here.
6855    fn plain() -> MemInfo {
6856        MemInfo {
6857            size: 0,
6858            align: 1,
6859            order: MemOrder::NotAtomic,
6860            tbaa: None,
6861            owns: 0,
6862            restrict: Restrict::NONE,
6863        }
6864    }
6865
6866    /// What the allocator is given: every integer register the convention offers except two, held
6867    /// back so that a move on an edge has somewhere to break a cycle and a spilled value has
6868    /// somewhere to be read into. Which two does not matter, and holding back the last two the
6869    /// convention would reach for leaves every expectation below unchanged.
6870    fn env() -> Env {
6871        const SCRATCH: [PhysReg; 2] = [x86_64::R10, x86_64::R11];
6872        let order: Vec<PhysReg> =
6873            SYSV.int_order.iter().copied().filter(|reg| !SCRATCH.contains(reg)).collect();
6874        Env::new().with(x86_64::GPR, &order, &SCRATCH)
6875    }
6876
6877    /// The machine IR text a function lowers to.
6878    fn lower(names: &mut Interner, source: &Func) -> String {
6879        let out = func(source, names, &SELECTOR, &SYSV, &Elsewhere::default())
6880            .expect("every instruction has a rule");
6881        mir::print_func(&out.func, names, &REGS)
6882    }
6883
6884    /// The same function lowered for AArch64, which is the first thing this file writes for a
6885    /// machine other than x86-64. Nothing past selection runs here, so what is checked is that the
6886    /// arguments, the rule and the return all come out named for the machine that was asked for.
6887    #[test]
6888    fn an_addition_lowers_for_aarch64_with_its_own_names() {
6889        let i32 = Type::int(32);
6890        let (mut names, mut func, block, args) = blank(&[i32, i32]);
6891        let mut build = Builder::new(&mut func, block);
6892        let sum = build.binary(Opcode::Add, args[0], args[1], Flags::default());
6893        build.ret(&[sum]);
6894
6895        let conv = &aarch64::AAPCS64;
6896        let selector = &crate::select::aarch64::SELECTOR;
6897        let out = super::func(&func, &mut names, selector, conv, &Elsewhere::default())
6898            .expect("an addition and a return have AArch64 rules");
6899        let text = mir::print_func(&out.func, &names, &aarch64::REGS);
6900        assert!(!text.contains("x64."), "{text}");
6901        assert!(text.contains("= a64.arg_val_32"), "{text}");
6902        assert!(text.contains("= a64.add_rr_32 %0, %1"), "{text}");
6903        assert!(text.contains("a64.ret_val_32 %2"), "{text}");
6904    }
6905
6906    /// Lowers one function for AArch64 and prints it, or says why it could not.
6907    fn lower_a64(names: &mut Interner, func: &Func) -> Result<String, String> {
6908        let conv = &aarch64::AAPCS64;
6909        let selector = &crate::select::aarch64::SELECTOR;
6910        let out = super::func(func, names, selector, conv, &Elsewhere::default())
6911            .map_err(|why| why.to_string())?;
6912        Ok(mir::print_func(&out.func, names, &aarch64::REGS))
6913    }
6914
6915    /// Nothing reads AArch64 assembly back into instructions, so every template there is kept as
6916    /// its text. The operands are the instruction's own, with the output first and the inputs
6917    /// last, a hole in the text asks for the `w` or the `x` name of one, and a vector register the
6918    /// clobber list names is written by it as well as every register a call may leave anything in.
6919    #[test]
6920    fn a_template_on_aarch64_is_kept_as_text_with_its_operands_in_registers() {
6921        let (i32, i64) = (Type::int(32), Type::int(64));
6922        let (mut names, mut source, block, args) = blank(&[i32, i64]);
6923        let out = clobbering(
6924            &mut source,
6925            block,
6926            &mut names,
6927            "add %w0, %w1, #1\n\tstr %2, [sp]",
6928            "=r,r,r",
6929            "d8",
6930            &[args[0], args[1]],
6931            &[i32],
6932        );
6933        let produced = source[out].results().next().expect("one result");
6934        Builder::new(&mut source, block).ret(&[produced]);
6935
6936        // Forty one registers between the output and the inputs: `x0` to `x15`, the sixteen vector
6937        // registers a call does not keep, and `v8`, which is the one the program named.
6938        let text = lower_a64(&mut names, &source).expect("kept as text");
6939        assert!(text.contains("%2:gpr, early $x0, early $x1,"), "{text}");
6940        assert!(text.contains(
6941            "early $v31, early $v8 = a64.template %0, %1, \
6942             @add \u{1}r0w\u{2}, \u{1}r42w\u{2}, #1\n\tstr \u{1}r43x\u{2}, [sp]\n"
6943        ));
6944    }
6945
6946    /// A letter that means one thing on x86 and another on AArch64 is refused there rather than
6947    /// read as x86. `a` to `d` and `S` name one register each on x86 and nothing on AArch64.
6948    #[test]
6949    fn a_constraint_letter_the_two_machines_disagree_about_is_refused_on_aarch64() {
6950        let i64 = Type::int(64);
6951        for constraints in ["=a,r", "=r,S", "=r,c"] {
6952            let (mut names, mut source, block, args) = blank(&[i64]);
6953            let out = clobbering(
6954                &mut source,
6955                block,
6956                &mut names,
6957                "mov %0, %1",
6958                constraints,
6959                "",
6960                &[args[0]],
6961                &[i64],
6962            );
6963            let produced = source[out].results().next().expect("one result");
6964            Builder::new(&mut source, block).ret(&[produced]);
6965            let refused = lower_a64(&mut names, &source).expect_err(constraints);
6966            assert!(refused.contains("has an operand this cannot place"), "{refused}");
6967        }
6968    }
6969
6970    /// `Q` on AArch64 is memory addressed by one register, which is `[x3]` and is how an operand in
6971    /// memory is spelled there already.
6972    #[test]
6973    fn a_q_operand_on_aarch64_is_its_address_in_brackets() {
6974        let (i64, ptr) = (Type::int(64), Type::PTR);
6975        let (mut names, mut source, block, args) = blank(&[ptr]);
6976        let out =
6977            clobbering(&mut source, block, &mut names, "ldr %x0, %1", "=r,Q", "", &args, &[i64]);
6978        let produced = source[out].results().next().expect("one result");
6979        Builder::new(&mut source, block).ret(&[produced]);
6980        let text = lower_a64(&mut names, &source).expect("kept as text");
6981        assert!(text.contains("@ldr \u{1}r0x\u{2}, [\u{1}r"), "{text}");
6982    }
6983
6984    /// `w` on AArch64 is a vector register, named `v` with no modifier the way gcc names it and by
6985    /// its scalar view with one. An integer asked for in one is refused, since it would need a move
6986    /// into that file first.
6987    #[test]
6988    fn a_vector_operand_on_aarch64_is_in_the_vector_file() {
6989        let f64 = Type::float(rucc_ir::Float::F64);
6990        let (mut names, mut source, block, args) = blank(&[f64, f64]);
6991        let out = clobbering(
6992            &mut source,
6993            block,
6994            &mut names,
6995            "fadd %d0, %d1, %d2\n\tmov %0.16b, %0.16b",
6996            "=w,w,w",
6997            "",
6998            &[args[0], args[1]],
6999            &[f64],
7000        );
7001        let produced = source[out].results().next().expect("one result");
7002        Builder::new(&mut source, block).ret(&[produced]);
7003        let text = lower_a64(&mut names, &source).expect("kept as text");
7004        assert!(text.contains("%2:fpr, early $x0,"), "{text}");
7005        assert!(text.contains("@fadd \u{1}r0d\u{2}, \u{1}r"), "{text}");
7006        assert!(text.contains("\n\tmov \u{1}r0v\u{2}.16b, \u{1}r0v\u{2}.16b\n"), "{text}");
7007
7008        let i64 = Type::int(64);
7009        let (mut names, mut source, block, args) = blank(&[i64]);
7010        let out =
7011            clobbering(&mut source, block, &mut names, "fmov %d0, %d1", "=w,w", "", &args, &[i64]);
7012        let produced = source[out].results().next().expect("one result");
7013        Builder::new(&mut source, block).ret(&[produced]);
7014        assert!(lower_a64(&mut names, &source).is_err());
7015    }
7016
7017    #[test]
7018    fn an_addition_of_two_registers_is_one_instruction() {
7019        let i32 = Type::int(32);
7020        let (mut names, mut func, block, args) = blank(&[i32, i32]);
7021        let mut build = Builder::new(&mut func, block);
7022        build.binary(Opcode::Add, args[0], args[1], Flags::default());
7023
7024        assert_eq!(
7025            lower(&mut names, &func),
7026            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_32\n    \
7027             %1:gpr($rsi) = x64.arg_val_32\n    %2:gpr(reuse 1) = x64.add_rr_32 %0, %1\n}\n"
7028        );
7029    }
7030
7031    #[test]
7032    fn a_constant_operand_becomes_an_immediate() {
7033        let i32 = Type::int(32);
7034        let (mut names, mut func, block, args) = blank(&[i32]);
7035        let mut build = Builder::new(&mut func, block);
7036        let seven = build.iconst(i32, 7);
7037        build.binary(Opcode::Add, args[0], seven, Flags::default());
7038
7039        // The constant is in the instruction and nothing was written to hold it, which is what
7040        // materializing one where a register for it is wanted buys.
7041        assert_eq!(
7042            lower(&mut names, &func),
7043            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_32\n    \
7044             %1:gpr(reuse 1) = x64.add_ri_32 %0, 7\n}\n"
7045        );
7046    }
7047
7048    #[test]
7049    fn a_constant_too_wide_for_an_immediate_goes_into_a_register() {
7050        let i64 = Type::int(64);
7051        let (mut names, mut func, block, args) = blank(&[i64]);
7052        let mut build = Builder::new(&mut func, block);
7053        let big = build.iconst(i64, i128::from(i32::MAX) + 1);
7054        build.binary(Opcode::Add, args[0], big, Flags::default());
7055
7056        // Nobody wrote this fallback down. The rule that takes an immediate has a guard that
7057        // turns a number this wide down, so it does not fire, and the next way of showing the
7058        // operand puts it in a register.
7059        assert_eq!(
7060            lower(&mut names, &func),
7061            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_64\n    \
7062             %1:gpr = x64.mov_ri_64 2147483648\n    %2:gpr(reuse 1) = x64.add_rr_64 %0, %1\n}\n"
7063        );
7064    }
7065
7066    #[test]
7067    fn an_index_calculation_folds_into_an_address() {
7068        let i64 = Type::int(64);
7069        let (mut names, mut func, block, args) = blank(&[i64, i64]);
7070        let mut build = Builder::new(&mut func, block);
7071        let four = build.iconst(i64, 4);
7072        let scaled = build.binary(Opcode::Mul, args[1], four, Flags::default());
7073        build.binary(Opcode::Add, args[0], scaled, Flags::default());
7074
7075        // Three IR instructions and one machine instruction. The multiply is gone because the
7076        // rule that matched reached down and took it.
7077        assert_eq!(
7078            lower(&mut names, &func),
7079            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_64\n    \
7080             %1:gpr($rsi) = x64.arg_val_64\n    %2:gpr = x64.lea_64 [%0 + %1*4]\n}\n"
7081        );
7082    }
7083
7084    #[test]
7085    fn an_instruction_every_reader_can_take_is_folded_into_all_of_them() {
7086        let i64 = Type::int(64);
7087        let (mut names, mut func, block, args) = blank(&[i64, i64]);
7088        let mut build = Builder::new(&mut func, block);
7089        let four = build.iconst(i64, 4);
7090        let scaled = build.binary(Opcode::Mul, args[1], four, Flags::default());
7091        let first = build.binary(Opcode::Add, args[0], scaled, Flags::default());
7092        build.binary(Opcode::Add, first, scaled, Flags::default());
7093
7094        // Both readers have room for a scaled index, so both of them take it and nothing is left
7095        // to read the multiply. Three IR instructions become two machine ones, where refusing to
7096        // fold into either reader would have left three.
7097        assert_eq!(
7098            lower(&mut names, &func),
7099            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_64\n    \
7100             %1:gpr($rsi) = x64.arg_val_64\n    %2:gpr = x64.lea_64 [%0 + %1*4]\n    \
7101             %3:gpr = x64.lea_64 [%2 + %1*4]\n}\n"
7102        );
7103    }
7104
7105    #[test]
7106    fn an_instruction_one_of_its_readers_cannot_take_is_folded_into_none_of_them() {
7107        let i64 = Type::int(64);
7108        let (mut names, mut func, block, args) = blank(&[i64, i64]);
7109        let mut build = Builder::new(&mut func, block);
7110        let four = build.iconst(i64, 4);
7111        let scaled = build.binary(Opcode::Mul, args[1], four, Flags::default());
7112        build.binary(Opcode::Add, args[0], scaled, Flags::default());
7113        build.store(scaled, args[0], plain(), Flags::default());
7114
7115        // The addition has room for the multiply and the store does not: what a store writes is
7116        // a register, and no rule reaches through it. Folding into the addition alone would
7117        // leave the multiply where it is for the store to read and do the work twice, so the
7118        // multiply is put back and both readers read the register it wrote.
7119        let text = lower(&mut names, &func);
7120        assert!(text.contains("x64.lea_64 [%1*4]"), "{text}");
7121        assert!(text.contains("x64.add_rr_64"), "{text}");
7122    }
7123
7124    #[test]
7125    fn a_shift_by_a_register_asks_for_it_in_cl() {
7126        let i32 = Type::int(32);
7127        let (mut names, mut func, block, args) = blank(&[i32, i32]);
7128        let mut build = Builder::new(&mut func, block);
7129        build.binary(Opcode::Shl, args[0], args[1], Flags::default());
7130
7131        // The fixed register is not in the rule. It is what the target says the instruction does
7132        // with its operands, and the allocator is what will act on it.
7133        let text = lower(&mut names, &func);
7134        assert!(text.contains("x64.shl_rcl_32 %0, %1($rcx)"), "{text}");
7135    }
7136
7137    #[test]
7138    fn a_division_names_the_registers_and_the_register_it_destroys() {
7139        let i32 = Type::int(32);
7140        let (mut names, mut func, block, args) = blank(&[i32, i32]);
7141        let mut build = Builder::new(&mut func, block);
7142        build.binary(Opcode::SDiv, args[0], args[1], Flags::default());
7143
7144        // Two definitions, because a division writes the remainder whether anybody wanted it or
7145        // not, and the second one is early because it is destroyed before the operands are read.
7146        let text = lower(&mut names, &func);
7147        assert!(
7148            text.contains("%2:gpr($rax), early %3:gpr($rdx) = x64.idiv_quo_32 %0($rax), %1"),
7149            "{text}"
7150        );
7151    }
7152
7153    #[test]
7154    fn a_load_reads_through_the_register_the_address_is_in() {
7155        let i64 = Type::int(64);
7156        let (mut names, mut func, block, args) = blank(&[i64]);
7157        let mut build = Builder::new(&mut func, block);
7158        build.load(Type::int(32), args[0], plain(), Flags::default());
7159
7160        assert_eq!(
7161            lower(&mut names, &func),
7162            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_64\n    \
7163             %1:gpr = x64.mov_rm_32 [%0]\n}\n"
7164        );
7165    }
7166
7167    #[test]
7168    fn a_store_writes_no_register_and_the_value_it_writes_is_the_one_the_ir_gave_it() {
7169        let (mut names, mut func, block, args) = blank(&[Type::int(32), Type::int(64)]);
7170        let mut build = Builder::new(&mut func, block);
7171        build.store(args[0], args[1], plain(), Flags::default());
7172
7173        // The value is the first parameter and the address is the second, and the instruction
7174        // takes them the other way round. Getting that backwards would compile to a store of the
7175        // address into the value, which is a program that runs and does the wrong thing.
7176        assert_eq!(
7177            lower(&mut names, &func),
7178            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_32\n    \
7179             %1:gpr($rsi) = x64.arg_val_64\n    x64.mov_mr_32 %0, [%1]\n}\n"
7180        );
7181    }
7182
7183    #[test]
7184    fn an_address_with_a_constant_added_folds_into_the_access() {
7185        let i64 = Type::int(64);
7186        let (mut names, mut func, block, args) = blank(&[i64]);
7187        let mut build = Builder::new(&mut func, block);
7188        let twelve = build.iconst(i64, 12);
7189        let field = build.binary(Opcode::Add, args[0], twelve, Flags::default());
7190        build.load(Type::int(64), field, plain(), Flags::default());
7191
7192        // Two IR instructions and one machine instruction, which is what every read of a field
7193        // of a structure comes to.
7194        assert_eq!(
7195            lower(&mut names, &func),
7196            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_64\n    \
7197             %1:gpr = x64.mov_rm_64 [%0 + 12]\n}\n"
7198        );
7199    }
7200
7201    #[test]
7202    fn a_displacement_too_wide_to_encode_leaves_the_addition_where_it_is() {
7203        let i64 = Type::int(64);
7204        let (mut names, mut func, block, args) = blank(&[i64]);
7205        let mut build = Builder::new(&mut func, block);
7206        let big = build.iconst(i64, i128::from(i32::MAX) + 1);
7207        let far = build.binary(Opcode::Add, args[0], big, Flags::default());
7208        build.load(Type::int(32), far, plain(), Flags::default());
7209
7210        // A displacement is signed and 32 bits. The rule that folds one has a guard that turns
7211        // this down, so the addition stays and the load reads through what it produced. Nobody
7212        // wrote that fallback: it is the next way of showing the operand.
7213        let text = lower(&mut names, &func);
7214        assert!(text.contains("x64.mov_rm_32 [%2]"), "{text}");
7215        assert!(text.contains("x64.add_rr_64"), "{text}");
7216    }
7217
7218    #[test]
7219    fn a_store_of_a_value_that_was_loaded_is_two_instructions_and_no_arithmetic() {
7220        let i64 = Type::int(64);
7221        let (mut names, mut func, block, args) = blank(&[i64, i64]);
7222        let mut build = Builder::new(&mut func, block);
7223        let got = build.load(Type::int(8), args[0], plain(), Flags::default());
7224        build.store(got, args[1], plain(), Flags::default());
7225
7226        // A load feeding a store is the one place folding would be wrong: an x86-64 `mov` has at
7227        // most one memory operand, and there is no rule that takes two, so the load is left where
7228        // it is and the store reads the register it wrote.
7229        assert_eq!(
7230            lower(&mut names, &func),
7231            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_64\n    \
7232             %1:gpr($rsi) = x64.arg_val_64\n    %2:gpr = x64.mov_rm_8 [%0]\n    \
7233             x64.mov_mr_8 %2, [%1]\n}\n"
7234        );
7235    }
7236
7237    #[test]
7238    fn an_access_at_a_width_no_rule_is_written_at_is_reported() {
7239        let i64 = Type::int(64);
7240        let (mut names, mut source, block, args) = blank(&[i64]);
7241        let mut build = Builder::new(&mut source, block);
7242        build.load(Type::int(128), args[0], plain(), Flags::default());
7243
7244        // The width is the whole of what is wrong here, so the width is in the message: `load`
7245        // on its own is written about at every other width and would send a reader looking in
7246        // the wrong place.
7247        let failed = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
7248            .expect_err("nothing loads 128 bits");
7249        assert_eq!(failed.to_string(), "no rule lowers a `load` producing a `i128`");
7250    }
7251
7252    #[test]
7253    fn a_return_asks_for_the_value_in_the_register_the_caller_reads() {
7254        let (mut names, mut func, block, args) = blank(&[Type::int(32)]);
7255        let mut build = Builder::new(&mut func, block);
7256        build.ret(&[args[0]]);
7257
7258        // The register is not in the rule, the same way `cl` is not in the rule for a shift. It
7259        // is what the target says the instruction does with its operand, and the allocator is
7260        // what will act on it. There is no `ret` here, because giving the frame back has to
7261        // happen between this and leaving and the frame is not worked out yet.
7262        assert_eq!(
7263            lower(&mut names, &func),
7264            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_32\n    \
7265             x64.ret_val_32 %0($rax)\n}\n"
7266        );
7267    }
7268
7269    #[test]
7270    fn a_return_of_two_values_asks_for_the_second_register_as_well() {
7271        let i64 = Type::int(64);
7272        let (mut names, mut func, block, args) = blank(&[i64, i64]);
7273        let mut build = Builder::new(&mut func, block);
7274        build.ret(&[args[0], args[1]]);
7275
7276        // `struct { long a, b; } f(long a, long b)`, after the front end has classified it. Both
7277        // halves are integers, so the second is in the second integer return register, and both
7278        // pseudos say so the same way the one for a single value does.
7279        assert_eq!(
7280            lower(&mut names, &func),
7281            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_64\n    \
7282             %1:gpr($rsi) = x64.arg_val_64\n    x64.ret_val_64 %0($rax)\n    \
7283             x64.ret_val2_64 %1($rdx)\n}\n"
7284        );
7285    }
7286
7287    #[test]
7288    fn two_values_back_in_different_files_are_both_the_first_of_their_own() {
7289        let f64 = Type::float(rucc_ir::Float::F64);
7290        let (mut names, mut func, block, args) = blank(&[f64, Type::int(64)]);
7291        let mut build = Builder::new(&mut func, block);
7292        build.ret(&[args[0], args[1]]);
7293
7294        // `struct { double a; long b; } f(double a, long b)`. The two files are counted apart, so
7295        // neither half is the second of anything and the `double` is in `xmm0` rather than in the
7296        // register a second `double` would have been in. Getting this wrong is not a crash: the
7297        // caller reads a register nobody wrote, and this is where that is ruled out.
7298        assert_eq!(
7299            lower(&mut names, &func),
7300            "mfunc @f {\nblock0:\n    %0:xmm($xmm0) = x64.arg_val_f64\n    \
7301             %1:gpr($rdi) = x64.arg_val_64\n    x64.ret_val_f64 %0($xmm0)\n    \
7302             x64.ret_val_64 %1($rax)\n}\n"
7303        );
7304    }
7305
7306    #[test]
7307    fn two_of_the_same_file_back_take_the_first_two_of_it() {
7308        let f64 = Type::float(rucc_ir::Float::F64);
7309        let (mut names, mut func, block, args) = blank(&[f64, f64]);
7310        let mut build = Builder::new(&mut func, block);
7311        build.ret(&[args[0], args[1]]);
7312
7313        // `struct { double x, y; } f(double x, double y)`, which is the vector half of the pair
7314        // above and counts in its own file the same way.
7315        assert_eq!(
7316            lower(&mut names, &func),
7317            "mfunc @f {\nblock0:\n    %0:xmm($xmm0) = x64.arg_val_f64\n    \
7318             %1:xmm($xmm1) = x64.arg_val_f64\n    x64.ret_val_f64 %0($xmm0)\n    \
7319             x64.ret_val2_f64 %1($xmm1)\n}\n"
7320        );
7321    }
7322
7323    /// A function whose answer goes back through memory, with the pointer to the space for it in
7324    /// front of whatever else it takes. Only the signature says it is one.
7325    fn returning_through_memory(params: &[Type]) -> (Interner, Func, Block, Vec<Value>) {
7326        let mut names = Interner::new();
7327        let sret = Abi::Sret { size: 32, align: 8 };
7328        let mut signature = Signature::new().and_param(Param::with_abi(Type::PTR, sret));
7329        signature.params.extend(params.iter().copied().map(Param::new));
7330        let mut func = Func::new(names.intern("f"), signature);
7331        let block = func.create_block();
7332        let space = func.append_param(block, Type::PTR);
7333        let values = std::iter::once(space)
7334            .chain(params.iter().map(|&ty| func.append_param(block, ty)))
7335            .collect();
7336        (names, func, block, values)
7337    }
7338
7339    #[test]
7340    fn the_space_a_return_through_memory_was_given_goes_back_in_the_first_return_register() {
7341        let (mut names, mut func, block, _) = returning_through_memory(&[]);
7342        Builder::new(&mut func, block).ret(&[]);
7343
7344        // `struct big f(void)`, where `big` is too large to come back in registers. The `return`
7345        // carries nothing, because the value went into the space the caller handed over, and the
7346        // document still says that address comes back in `rax`. Nothing in the IR says it, so the
7347        // convention says it, and the pseudo is the one any other pointer return would use.
7348        assert_eq!(
7349            lower(&mut names, &func),
7350            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_64\n    \
7351             x64.ret_val_64 %0($rax)\n}\n"
7352        );
7353    }
7354
7355    #[test]
7356    fn what_the_function_did_in_between_does_not_take_the_register_off_it() {
7357        let (mut names, mut func, block, args) = returning_through_memory(&[Type::int(32)]);
7358        let mut build = Builder::new(&mut func, block);
7359        build.store(args[1], args[0], plain(), Flags::default());
7360        build.ret(&[]);
7361
7362        // The register is a read at the end and not a move at the start, so it is live across
7363        // everything between the two and the allocator has to keep it somewhere. In a function
7364        // with a call in it that somewhere is a callee saved register, and the address comes back
7365        // into `rax` here rather than whatever the last instruction happened to leave there. That
7366        // is issue #333, and a store is enough to show the value outlives the entry block.
7367        let text = lower(&mut names, &func);
7368        assert!(text.contains("x64.mov_mr_32 %1, [%0]"), "{text}");
7369        assert!(text.ends_with("    x64.ret_val_64 %0($rax)\n}\n"), "{text}");
7370    }
7371
7372    #[test]
7373    fn a_pointer_that_is_only_a_pointer_is_not_given_back() {
7374        let (mut names, mut func, block, args) = blank(&[Type::PTR]);
7375        let mut build = Builder::new(&mut func, block);
7376        build.store(args[0], args[0], plain(), Flags::default());
7377        build.ret(&[]);
7378
7379        // `void f(void **p)`. It takes a pointer first and returns nothing, which is the shape of
7380        // the one above and none of its meaning, and what tells them apart is the signature. A
7381        // `void` function leaves `rax` alone.
7382        assert!(!lower(&mut names, &func).contains("ret_val"));
7383    }
7384
7385    #[test]
7386    fn a_return_of_a_constant_puts_it_in_a_register_first() {
7387        let (mut names, mut func, block, _) = blank(&[]);
7388        let mut build = Builder::new(&mut func, block);
7389        let zero = build.iconst(Type::int(32), 0);
7390        build.ret(&[zero]);
7391
7392        // No rule returns an immediate, so the plan that offers one is turned down and the next
7393        // one materializes it. That is `int main(void) { return 0; }` in full, once the epilogue
7394        // is appended to it.
7395        assert_eq!(
7396            lower(&mut names, &func),
7397            "mfunc @f {\nblock0:\n    %0:gpr = x64.mov_ri_32 0\n    x64.ret_val_32 %0($rax)\n}\n"
7398        );
7399    }
7400
7401    #[test]
7402    fn the_rule_that_writes_a_constant_down_is_recorded_as_a_rule_that_fired() {
7403        let (mut names, mut func, block, _) = blank(&[]);
7404        let mut build = Builder::new(&mut func, block);
7405        let zero = build.iconst(Type::int(32), 0);
7406        build.ret(&[zero]);
7407
7408        // The loop over the instructions passes a constant by, because a constant is written where
7409        // a register for it is first wanted rather than where the IR put it. So the only place a
7410        // rule about one is ever selected is the materialization, and a mark made in the loop
7411        // alone would report every rule about a constant as a rule nothing reaches.
7412        let out = super::func(&func, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
7413            .expect("every instruction has a rule");
7414        let rules = &crate::select::x86_64::TABLE.rules;
7415        let fired: Vec<&str> = rules
7416            .iter()
7417            .enumerate()
7418            .filter(|(index, _)| out.fired.has(*index))
7419            .map(|(_, rule)| rule.pattern)
7420            .collect();
7421        assert!(fired.contains(&"(iconst.i32 k)"), "{fired:?}");
7422    }
7423
7424    #[test]
7425    fn a_return_of_nothing_is_no_instruction_at_all() {
7426        let (mut names, mut func, block, _) = blank(&[]);
7427        let mut build = Builder::new(&mut func, block);
7428        build.ret(&[]);
7429
7430        // Every part of leaving a function that returns nothing is the epilogue's, and the
7431        // epilogue goes in after allocation. A block with nothing in it is the right answer here
7432        // rather than a function that could not be lowered.
7433        assert_eq!(lower(&mut names, &func), "mfunc @f {\nblock0:\n}\n");
7434    }
7435
7436    #[test]
7437    fn the_allocator_is_what_moves_the_answer_into_the_return_register() {
7438        let (mut names, mut source, block, _) = blank(&[]);
7439        let mut build = Builder::new(&mut source, block);
7440        let zero = build.iconst(Type::int(32), 0);
7441        build.ret(&[zero]);
7442
7443        let mut out = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
7444            .expect("every instruction has a rule")
7445            .func;
7446        let env = env();
7447        let allocation = rucc_regalloc::run(&mut out, &env, "test", true);
7448        let frame = Frame::of(&out, &allocation, &Layout::new(&SYSV, REGS));
7449        finish(
7450            &mut out,
7451            &allocation,
7452            &frame,
7453            &Stack::default(),
7454            Convention::new(&SYSV, &FRAME),
7455            &mut names,
7456        );
7457
7458        // `int main(void) { return 0; }` end to end. Nothing here asked for `rax`: the rule said
7459        // the value goes back, the target said where, and the allocator is what made it true. The
7460        // epilogue is what leaves, and this function needs no frame, so it is the return alone.
7461        //
7462        // Two instructions and no copy, which is what a hint buys. The return insists on `rax`,
7463        // so `rax` is the register the allocator tries first for the value the return reads, and
7464        // the constant is written straight into it.
7465        assert_eq!(
7466            mir::print_func(&out, &names, &REGS),
7467            "mfunc @f {\nblock0:\n    $rax = x64.mov_ri_32 0\n    \
7468             x64.ret_val_32 $rax($rax)\n    x64.ret\n}\n"
7469        );
7470    }
7471
7472    #[test]
7473    fn a_function_of_two_arguments_is_a_whole_function_now() {
7474        let i32 = Type::int(32);
7475        let (mut names, mut source, block, args) = blank(&[i32, i32]);
7476        let mut build = Builder::new(&mut source, block);
7477        let sum = build.binary(Opcode::Add, args[0], args[1], Flags::default());
7478        build.ret(&[sum]);
7479
7480        let mut out = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
7481            .expect("every instruction has a rule")
7482            .func;
7483        let env = env();
7484        let allocation = rucc_regalloc::run(&mut out, &env, "test", true);
7485        let frame = Frame::of(&out, &allocation, &Layout::new(&SYSV, REGS));
7486        finish(
7487            &mut out,
7488            &allocation,
7489            &frame,
7490            &Stack::default(),
7491            Convention::new(&SYSV, &FRAME),
7492            &mut names,
7493        );
7494
7495        // `int f(int a, int b) { return a + b; }` end to end, and this is the test the argument
7496        // side exists for. Before it there was no way to write one: the allocator refuses a
7497        // function whose entry block takes parameters, because there is no edge into an entry
7498        // block for the moves that give a block parameter its value to go on.
7499        //
7500        // One move, and it is the one the machine's addition needs rather than one the allocator
7501        // owes anybody. Each argument stays in the register it arrived in, because the pseudo
7502        // that defines it insists on that register and the allocator now tries it first, and the
7503        // sum stays in the register the addition wrote it to until the return reads it out. The
7504        // copy in front of a two address instruction is what makes its destination one of the
7505        // registers it reads, and the source operand keeps its own name because the destination
7506        // is what the encoder writes.
7507        assert_eq!(
7508            mir::print_func(&out, &names, &REGS),
7509            "mfunc @f {\nblock0:\n    $rdi($rdi) = x64.arg_val_32\n    \
7510             $rsi($rsi) = x64.arg_val_32\n    \
7511             $rdi(reuse 1) = x64.add_rr_32 $rdi, $rsi\n    $rax = x64.mov_rr_64 $rdi\n    \
7512             x64.ret_val_32 $rax($rax)\n    x64.ret\n}\n"
7513        );
7514    }
7515
7516    #[test]
7517    fn an_argument_with_no_register_left_for_it_is_read_out_of_the_caller_s_stack() {
7518        let i64 = Type::int(64);
7519        let (mut names, mut source, block, args) = blank(&[i64; 7]);
7520        let mut build = Builder::new(&mut source, block);
7521        build.ret(&[args[6]]);
7522
7523        let lowered = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
7524            .expect("the seventh is read from memory");
7525
7526        // SysV passes six integers in registers and the seventh in the caller's memory, so six of
7527        // these are pseudos that encode to nothing and the seventh is a load that encodes to real
7528        // bytes. Its displacement is nothing here for the reason a local's is: there is no frame
7529        // yet. What the walk hands on is which instruction is waiting, and for how far up the
7530        // caller's argument area, which is the bottom of it because it is the first one there.
7531        assert_eq!(lowered.stack.arguments.len(), 1);
7532        assert_eq!(lowered.stack.arguments[0].1, 0);
7533        let text = mir::print_func(&lowered.func, &names, &REGS);
7534        assert!(text.contains("%6:gpr = x64.mov_rm_64 [$rsp]"), "{text}");
7535        assert_eq!(text.matches("x64.arg_val_64").count(), 6, "{text}");
7536    }
7537
7538    #[test]
7539    fn the_frame_is_what_says_how_far_up_the_caller_s_stack_an_argument_is() {
7540        let i64 = Type::int(64);
7541        let (mut names, mut source, block, args) = blank(&[i64; 8]);
7542        let mut build = Builder::new(&mut source, block);
7543        let sum = build.binary(Opcode::Add, args[6], args[7], Flags::default());
7544        build.ret(&[sum]);
7545
7546        let lowered = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
7547            .expect("both are read from memory");
7548        let stack = lowered.stack;
7549        let mut out = lowered.func;
7550        let env = env();
7551        let allocation = rucc_regalloc::run(&mut out, &env, "test", true);
7552        let layout = stack.layout(Layout::new(&SYSV, REGS));
7553        let frame = Frame::of(&out, &allocation, &layout);
7554        finish(&mut out, &allocation, &frame, &stack, Convention::new(&SYSV, &FRAME), &mut names);
7555
7556        // A leaf that takes no frame, so the stack pointer never moves and the only thing between
7557        // it and the caller's arguments is the return address the call pushed. The seventh
7558        // parameter is at the bottom of the caller's argument area and the eighth is one word
7559        // further up, which is the eight bytes between the two offsets.
7560        let text = mir::print_func(&out, &names, &REGS);
7561        assert_eq!(frame.size(), 0);
7562        assert_eq!(frame.incoming(), Incoming::from_stack(8));
7563        assert!(text.contains("x64.mov_rm_64 [$rsp + 8]"), "{text}");
7564        assert!(text.contains("x64.mov_rm_64 [$rsp + 16]"), "{text}");
7565    }
7566
7567    #[test]
7568    fn a_realigned_frame_reaches_the_caller_s_arguments_through_the_frame_pointer() {
7569        let i64 = Type::int(64);
7570        let (mut names, mut source, block, args) = blank(&[i64; 7]);
7571        let wide = slot(&mut source, block, 64, 32);
7572        let mut build = Builder::new(&mut source, block);
7573        build.store(args[6], wide, plain(), Flags::default());
7574        build.ret(&[args[6]]);
7575
7576        let lowered = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
7577            .expect("every instruction has a rule");
7578        let stack = lowered.stack;
7579        let mut out = lowered.func;
7580        let env = env();
7581        let allocation = rucc_regalloc::run(&mut out, &env, "test", true);
7582        let layout = stack.layout(Layout::new(&SYSV, REGS));
7583        let frame = Frame::of(&out, &allocation, &layout);
7584        finish(&mut out, &allocation, &frame, &stack, Convention::new(&SYSV, &FRAME), &mut names);
7585
7586        // A local wanting thirty two byte alignment makes the prologue force the stack pointer,
7587        // which throws away how far the caller's stack was. So the load the lowering wrote off the
7588        // stack pointer is rewritten to read through the frame pointer, at the one distance that
7589        // survives: the word the prologue pushed the frame pointer into, and the return address
7590        // above it.
7591        let text = mir::print_func(&out, &names, &REGS);
7592        assert_eq!(frame.realign(), Some(32));
7593        assert_eq!(frame.incoming(), Incoming::from_frame(16));
7594        assert!(text.contains("x64.mov_rm_64 [$rbp + 16]"), "{text}");
7595        assert!(!text.contains("x64.mov_rm_64 [$rsp"), "{text}");
7596    }
7597
7598    #[test]
7599    fn a_jump_is_the_edge_and_nothing_else() {
7600        let i32 = Type::int(32);
7601        let (mut names, mut source, entry, args) = blank(&[i32]);
7602        let next = source.create_block();
7603        let got = source.append_param(next, i32);
7604        Builder::new(&mut source, entry).jump(next, &[args[0]]);
7605        Builder::new(&mut source, next).ret(&[got]);
7606
7607        // Two blocks and two instructions, and the jump is neither of them. What it was is the
7608        // arm on the first block, and what the arm carries is the argument it was called with.
7609        assert_eq!(
7610            lower(&mut names, &source),
7611            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_32 block1(%0)\n\n\
7612             block1(%1:gpr):\n    x64.ret_val_32 %1($rax)\n}\n"
7613        );
7614    }
7615
7616    /// A block that reads what a block below it writes is filled after it, not before it.
7617    ///
7618    /// The blocks are written entry, `early`, `late`, `exit`, and the entry jumps straight past
7619    /// `early` to `late`, so `late` dominates `early` while sitting below it in the function.
7620    /// Filling them in the order they are written reaches the read in `early` first, and reading
7621    /// a value with no register yet mints one. The cast in `late` is no instruction at all, so
7622    /// what it does is give its answer the register its operand is already in, and that is not
7623    /// the register the read minted. Nothing writes the register the read minted. The printer
7624    /// says `%?` for a register nothing defines, which is what this looks for, and what came out
7625    /// of the real bug was SQLite loading a stack slot no store ever reached.
7626    #[test]
7627    fn a_block_that_reads_what_a_block_below_it_writes_is_filled_after_it() {
7628        let i64 = Type::int(64);
7629        let (mut names, mut source, entry, args) = blank(&[i64, i64]);
7630        let early = source.create_block();
7631        let late = source.create_block();
7632        let exit = source.create_block();
7633
7634        Builder::new(&mut source, entry).jump(late, &[]);
7635        let ptr = cast(&mut source, late, Opcode::IntToPtr, args[0], Type::PTR);
7636        Builder::new(&mut source, early).ret(&[ptr]);
7637        let mut build = Builder::new(&mut source, late);
7638        let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
7639        build.br_if(cond, early, &[], exit, &[]);
7640        Builder::new(&mut source, exit).ret(&[args[1]]);
7641
7642        let text = lower(&mut names, &source);
7643        assert!(!text.contains("%?"), "every register has something that writes it: {text}");
7644    }
7645
7646    /// A constant is written where it is wanted rather than where the IR defined it, and two
7647    /// blocks wanting the same one is two places. Writing it once and reading it in both is a
7648    /// register read where nothing wrote it, unless the block it was written in happens to
7649    /// dominate the other, which nothing here checks and which the second arm of a branch never
7650    /// does. Each block gets its own copy of the number instead.
7651    #[test]
7652    fn a_constant_two_blocks_want_is_written_in_both_of_them() {
7653        let i32 = Type::int(32);
7654        let (mut names, mut source, entry, args) = blank(&[i32, i32]);
7655        let then = source.create_block();
7656        let other = source.create_block();
7657        let join = source.create_block();
7658        let got = source.append_param(join, i32);
7659
7660        let mut build = Builder::new(&mut source, entry);
7661        let seven = build.iconst(i32, 7);
7662        let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
7663        build.br_if(cond, then, &[], other, &[]);
7664        // Both arms want the seven in a register, because a block argument is never an immediate,
7665        // and neither arm dominates the other.
7666        Builder::new(&mut source, then).jump(join, &[seven]);
7667        Builder::new(&mut source, other).jump(join, &[seven]);
7668        Builder::new(&mut source, join).ret(&[got]);
7669
7670        let text = lower(&mut names, &source);
7671        assert_eq!(text.matches("x64.mov_ri_32 7").count(), 2, "one seven per block: {text}");
7672    }
7673
7674    /// An argument on an edge out of a block that leaves two ways is read after every instruction
7675    /// of the block is written, and reading one can write an instruction, which would land after
7676    /// the branch that has already jumped past it. The branch goes back on the end.
7677    #[test]
7678    fn a_constant_an_edge_wants_is_written_before_the_branch_and_not_after_it() {
7679        let i32 = Type::int(32);
7680        let (mut names, mut source, entry, args) = blank(&[i32, i32]);
7681        let then = source.create_block();
7682        let join = source.create_block();
7683        let got = source.append_param(join, i32);
7684
7685        let mut build = Builder::new(&mut source, entry);
7686        let nine = build.iconst(i32, 9);
7687        let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
7688        build.br_if(cond, then, &[], join, &[nine]);
7689        Builder::new(&mut source, then).jump(join, &[args[0]]);
7690        Builder::new(&mut source, join).ret(&[got]);
7691
7692        let out = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
7693            .expect("every instruction has a rule")
7694            .func;
7695        let entry = out.entry().expect("an entry block");
7696        let last = out.terminator(entry).expect("a block that leaves two ways has a branch");
7697        let branch = names.intern("x64.br_cond_8");
7698        assert_eq!(
7699            out[last].opcode,
7700            mir::Opcode::new(branch),
7701            "the branch is last: {}",
7702            mir::print_func(&out, &names, &REGS)
7703        );
7704    }
7705
7706    #[test]
7707    fn a_conditional_branch_is_lowered_to_the_condition_and_nothing_about_where_it_goes() {
7708        let i32 = Type::int(32);
7709        let (mut names, mut source, entry, args) = blank(&[i32, i32]);
7710        let then = source.create_block();
7711        let other = source.create_block();
7712        let mut build = Builder::new(&mut source, entry);
7713        let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
7714        build.br_if(cond, then, &[], other, &[]);
7715        Builder::new(&mut source, then).ret(&[args[0]]);
7716        Builder::new(&mut source, other).ret(&[args[1]]);
7717
7718        // The comparison writes a byte and the branch reads it, and neither says a block. Both
7719        // arms are on the entry block, in the order the branch took them, so the arm that runs
7720        // when the condition holds is the first.
7721        assert_eq!(
7722            lower(&mut names, &source),
7723            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_32\n    \
7724             %1:gpr($rsi) = x64.arg_val_32\n    %2:gpr = x64.cmp_set_l_32 %0, %1\n    \
7725             x64.br_cond_8 %2, block1, block2\n\n\
7726             block1:\n    x64.ret_val_32 %0($rax)\n\n\
7727             block2:\n    x64.ret_val_32 %1($rax)\n}\n"
7728        );
7729    }
7730
7731    /// A choice between two values, which is one instruction and no blocks at all.
7732    ///
7733    /// The arms come out the other way round from the IR, because a conditional move overwrites its
7734    /// destination and the destination is the arm taken when the condition does not hold. The
7735    /// condition arrives last for the same reason: it is read by the test in front of the move
7736    /// rather than by the move.
7737    #[test]
7738    fn a_select_is_lowered_to_a_test_and_a_conditional_move() {
7739        let i32 = Type::int(32);
7740        let (mut names, mut source, entry, args) = blank(&[i32, i32]);
7741        let mut build = Builder::new(&mut source, entry);
7742        let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
7743        let picked = build.select(cond, args[0], args[1]);
7744        build.ret(&[picked]);
7745
7746        assert_eq!(
7747            lower(&mut names, &source),
7748            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_32\n    \
7749             %1:gpr($rsi) = x64.arg_val_32\n    %2:gpr = x64.cmp_set_l_32 %0, %1\n    \
7750             %3:gpr(reuse 1) = x64.test_cmov_ne_32 %1, %0, %2\n    \
7751             x64.ret_val_32 %3($rax)\n}\n"
7752        );
7753    }
7754
7755    #[test]
7756    fn a_branch_over_a_block_is_a_whole_function_now() {
7757        let i32 = Type::int(32);
7758        let (mut names, mut source, entry, args) = blank(&[i32, i32]);
7759        let then = source.create_block();
7760        let other = source.create_block();
7761        let join = source.create_block();
7762        let got = source.append_param(join, i32);
7763        let mut build = Builder::new(&mut source, entry);
7764        let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
7765        build.br_if(cond, then, &[], other, &[]);
7766        let mut build = Builder::new(&mut source, then);
7767        let sum = build.binary(Opcode::Add, args[0], args[1], Flags::default());
7768        build.jump(join, &[sum]);
7769        Builder::new(&mut source, other).jump(join, &[args[1]]);
7770        Builder::new(&mut source, join).ret(&[got]);
7771
7772        // `int f(int a, int b) { if (a < b) return a + b; else return b; }` end to end, written
7773        // the way a front end writes it: both arms of the branch are blocks of their own and the
7774        // return is the block they meet at. No edge here is critical, because the two arms out of
7775        // the entry carry nothing and the two arms into the join each leave a block that goes
7776        // nowhere else, so each has its own end to put its move at.
7777        let mut out = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
7778            .expect("every instruction has a rule")
7779            .func;
7780        assert_eq!(crate::split::critical(&mut out), 0, "no edge here is critical");
7781        let env = env();
7782        let allocation = rucc_regalloc::run(&mut out, &env, "test", true);
7783        let frame = Frame::of(&out, &allocation, &Layout::new(&SYSV, REGS));
7784        finish(
7785            &mut out,
7786            &allocation,
7787            &frame,
7788            &Stack::default(),
7789            Convention::new(&SYSV, &FRAME),
7790            &mut names,
7791        );
7792
7793        // One epilogue, on the join, which is the one block the function leaves from, and the
7794        // moves that give the join its parameter are at the end of each arm. Every register is
7795        // physical and the branch is still a branch on a register, because turning it into a
7796        // `test` and a `jcc` is the block layout's and there is no block layout yet.
7797        let text = mir::print_func(&out, &names, &REGS);
7798        assert_eq!(text.matches("x64.ret\n").count(), 1, "{text}");
7799        assert!(text.contains("x64.br_cond_8"), "{text}");
7800        assert!(text.contains("x64.add_rr_32"), "{text}");
7801        assert!(!text.contains('%'), "{text}");
7802    }
7803
7804    #[test]
7805    fn a_critical_edge_is_split_before_the_allocator_ever_sees_it() {
7806        let i32 = Type::int(32);
7807        let (mut names, mut source, entry, args) = blank(&[i32, i32]);
7808        let then = source.create_block();
7809        let join = source.create_block();
7810        let got = source.append_param(join, i32);
7811        let mut build = Builder::new(&mut source, entry);
7812        let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
7813        build.br_if(cond, then, &[], join, &[args[1]]);
7814        Builder::new(&mut source, then).jump(join, &[args[0]]);
7815        let mut build = Builder::new(&mut source, join);
7816        let twice = build.binary(Opcode::Add, got, got, Flags::default());
7817        build.ret(&[twice]);
7818
7819        // The else arm is critical: the entry block leaves two ways and the join is arrived at
7820        // two ways, and the arm carries a value. Without splitting it the allocator asserts,
7821        // because the move that gives the join its parameter would have to run at the end of a
7822        // block that also goes to the other arm.
7823        let mut out = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
7824            .expect("every instruction has a rule")
7825            .func;
7826        assert_eq!(crate::split::critical(&mut out), 1);
7827        let env = env();
7828        let allocation = rucc_regalloc::run(&mut out, &env, "test", true);
7829        let frame = Frame::of(&out, &allocation, &Layout::new(&SYSV, REGS));
7830        finish(
7831            &mut out,
7832            &allocation,
7833            &frame,
7834            &Stack::default(),
7835            Convention::new(&SYSV, &FRAME),
7836            &mut names,
7837        );
7838
7839        // The block the split added is where the move went, and it is the whole of that block.
7840        let text = mir::print_func(&out, &names, &REGS);
7841        assert_eq!(out.block_count(), 4, "{text}");
7842        assert_eq!(text.matches("x64.ret\n").count(), 1, "{text}");
7843    }
7844
7845    #[test]
7846    fn a_call_passes_what_the_convention_says_and_takes_back_what_it_says() {
7847        let i32 = Type::int(32);
7848        let (mut names, mut source, block, args) = blank(&[i32, i32]);
7849        let sig =
7850            source.add_signature(Signature::new().with_params(&[i32, i32]).with_returns(&[i32]));
7851        let callee = names.intern("g");
7852        let call = Builder::new(&mut source, block).call(callee, sig, &[args[0], args[1]]);
7853        let got = source[call].first_result.expect("an integer comes back");
7854        Builder::new(&mut source, block).ret(&[got]);
7855
7856        // `int f(int a, int b) { return g(a, b); }`. The arguments arrived where the call wants
7857        // them, so what the call reads is what arrived, and the whole of the convention is in the
7858        // constraints rather than in a move.
7859        let text = lower(&mut names, &source);
7860        assert!(text.contains("= x64.call %0($rdi), %1($rsi), @g"), "{text}");
7861        assert!(text.contains("x64.ret_val_32 %2($rax)"), "{text}");
7862        // What the call writes is the value that comes back and then every register the callee is
7863        // free to destroy, in both classes, which is the whole of what stops the allocator from
7864        // leaving something in one of them.
7865        assert!(text.contains("%2:gpr($rax), $rcx, $rdx, $r8, $r9, $r10, $r11, $xmm0,"), "{text}");
7866        assert!(text.contains("$xmm15 = x64.call"), "{text}");
7867    }
7868
7869    #[test]
7870    fn what_the_frame_owes_a_call_comes_back_with_the_function() {
7871        let i32 = Type::int(32);
7872        let sig = |source: &mut Func| source.add_signature(Signature::new().with_params(&[i32]));
7873
7874        let (mut names, mut source, block, args) = blank(&[i32]);
7875        let sig = sig(&mut source);
7876        let callee = names.intern("g");
7877        Builder::new(&mut source, block).call(callee, sig, &[args[0]]);
7878        let out = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
7879            .expect("every instruction has a rule");
7880
7881        // Nothing on the stack, so nothing owed, but not a leaf either: a function that calls
7882        // owes the callee an aligned stack pointer and may not use the red zone.
7883        assert_eq!(out.stack.calls, Some(0));
7884        let layout = out.stack.layout(Layout::new(&SYSV, REGS));
7885        assert!(!layout.leaf);
7886        assert_eq!(layout.outgoing, 0);
7887
7888        // The same call under the other convention owes thirty two bytes for the callee to spill
7889        // its register arguments into, which is a fact about the convention and not about the call.
7890        let out = func(&source, &mut names, &SELECTOR, &x86_64::WIN64, &Elsewhere::default())
7891            .expect("every instruction has a rule");
7892        assert_eq!(out.stack.calls, Some(32));
7893
7894        // And a function that calls nothing is a leaf, which is what says it may use the red zone.
7895        let (mut names, mut source, block, args) = blank(&[i32]);
7896        Builder::new(&mut source, block).ret(&[args[0]]);
7897        let out = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
7898            .expect("every instruction has a rule");
7899        assert_eq!(out.stack.calls, None);
7900        assert!(out.stack.layout(Layout::new(&SYSV, REGS)).leaf);
7901    }
7902
7903    /// A Windows variadic prologue writes the argument registers the signature did not name into
7904    /// the shadow space the caller already reserved, which makes every argument one run of words up
7905    /// there and a `va_start` the address of the first of them. One `lea` and one store, and no
7906    /// counts, because a list that is a pointer has nowhere to put one and nothing that reads one.
7907    #[test]
7908    fn a_windows_variadic_function_homes_its_spare_registers_in_the_callers_area() {
7909        let mut names = Interner::new();
7910        let params = [Type::int(32), Type::PTR];
7911        let signature = Signature::new().with_params(&params).variadic();
7912        let mut source = Func::new(names.intern("f"), signature);
7913        let block = source.create_block();
7914        let values: Vec<Value> = params.iter().map(|&ty| source.append_param(block, ty)).collect();
7915        let mut build = Builder::new(&mut source, block);
7916        let args = build.func().push_values(&values[1..]);
7917        build.inst(InstData { args, ..InstData::new(Opcode::VaStart) }, &[]);
7918        build.ret(&[]);
7919
7920        let out = func(&source, &mut names, &SELECTOR, &x86_64::WIN64, &Elsewhere::default())
7921            .expect("every instruction has a rule");
7922        let text = mir::print_func(&out.func, &names, &REGS);
7923
7924        // Two named parameters, so the registers at the next two positions hold arguments nobody
7925        // named and both are written up into the caller's area. The displacement is empty here and
7926        // `finish` fills it in, the same way it does for a parameter the registers ran out before.
7927        assert!(text.contains("($r8) = x64.arg_val_64"), "{text}");
7928        assert!(text.contains("($r9) = x64.arg_val_64"), "{text}");
7929        assert_eq!(text.matches("x64.mov_mr_64").count(), 3, "two homed and one stored: {text}");
7930        assert!(!text.contains("x64.mov_ri_32"), "and no field holds a count: {text}");
7931
7932        // All three waiting on the same fixup, and the last of them is the `lea` the list is given,
7933        // sixteen bytes up, which is where the two arguments the signature does name stopped.
7934        assert_eq!(out.stack.arguments.len(), 3);
7935        assert_eq!(out.stack.arguments[2].1, 16);
7936    }
7937
7938    #[test]
7939    fn a_value_that_outlives_a_call_is_not_left_where_the_call_destroys_it() {
7940        let i32 = Type::int(32);
7941        let (mut names, mut source, block, args) = blank(&[i32]);
7942        let sig = source.add_signature(Signature::new().with_params(&[i32]).with_returns(&[i32]));
7943        let callee = names.intern("g");
7944        let call = Builder::new(&mut source, block).call(callee, sig, &[args[0]]);
7945        let got = source[call].first_result.expect("an integer comes back");
7946        let mut build = Builder::new(&mut source, block);
7947        let sum = build.binary(Opcode::Add, got, args[0], Flags::default());
7948        build.ret(&[sum]);
7949
7950        // `int f(int a) { return g(a) + a; }`, which is the smallest program that asks the
7951        // question: `a` is read after the call and `rdi` is a register the call destroys.
7952        let lowered = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
7953            .expect("every instruction has a rule");
7954        let layout = lowered.stack.layout(Layout::new(&SYSV, REGS));
7955        let mut out = lowered.func;
7956        let env = env();
7957        let allocation = rucc_regalloc::run(&mut out, &env, "test", true);
7958        let frame = Frame::of(&out, &allocation, &layout);
7959        finish(
7960            &mut out,
7961            &allocation,
7962            &frame,
7963            &Stack::default(),
7964            Convention::new(&SYSV, &FRAME),
7965            &mut names,
7966        );
7967
7968        // It went to a register the callee has to put back, and the prologue and epilogue are what
7969        // put it back, which is the whole bargain the two halves of a convention make.
7970        let text = mir::print_func(&out, &names, &REGS);
7971        assert!(text.contains("$rbx"), "{text}");
7972        assert!(!text.contains('%'), "{text}");
7973        assert_eq!(text.matches("x64.call").count(), 1, "{text}");
7974    }
7975
7976    #[test]
7977    fn a_call_with_more_arguments_than_registers_writes_the_rest_into_the_outgoing_area() {
7978        let i64 = Type::int(64);
7979        let (mut names, mut source, block, args) = blank(&[i64]);
7980        let seven = vec![i64; 7];
7981        let sig = source.add_signature(Signature::new().with_params(&seven));
7982        let callee = names.intern("g");
7983        let passed = vec![args[0]; 7];
7984        Builder::new(&mut source, block).call(callee, sig, &passed);
7985
7986        let lowered = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
7987            .expect("the seventh goes to memory");
7988        // The bytes the call needs are on the layout the frame is worked out from, so that the
7989        // frame reserves as many as the widest call in the function asked for.
7990        assert_eq!(lowered.stack.calls, Some(8));
7991        let text = mir::print_func(&lowered.func, &names, &REGS);
7992        assert!(text.contains("x64.mov_mr_64 %0, [$rsp]\n"), "{text}");
7993    }
7994
7995    #[test]
7996    fn a_call_this_cannot_make_is_reported_rather_than_made() {
7997        let (mut names, mut source, block, _) = blank(&[]);
7998        let returns = [Type::float(rucc_ir::Float::F80), Type::int(64)];
7999        let sig = source.add_signature(Signature::new().with_returns(&returns));
8000        let callee = names.intern("g");
8001        Builder::new(&mut source, block).call(callee, sig, &[]);
8002        let failed = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
8003            .expect_err("a long double is on the x87");
8004        assert_eq!(failed.to_string(), "what this call gives back is on the x87 stack");
8005    }
8006
8007    /// A `long double` on its own is a different answer, because on its own it comes back on the
8008    /// x87 stack rather than in a register, which is somewhere the call cannot be said to write.
8009    ///
8010    /// So the call gives back nothing at all and the value is taken off the stack by the `fstp`
8011    /// straight after it. That instruction has to be straight after it: the stack is one place and
8012    /// anything else that touched it before this ran would be looking at the value still on it.
8013    #[test]
8014    fn a_call_that_gives_back_a_long_double_takes_it_off_the_stack_at_once() {
8015        let (mut names, mut source, block, _) = blank(&[]);
8016        let long_double = Type::float(rucc_ir::Float::F80);
8017        let sig = source.add_signature(Signature::new().with_returns(&[long_double]));
8018        let callee = names.intern("g");
8019        Builder::new(&mut source, block).call(callee, sig, &[]);
8020
8021        let lowered = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
8022            .expect("the value comes back in st0");
8023        let text = mir::print_func(&lowered.func, &names, &REGS);
8024        let after: Vec<&str> =
8025            text.lines().skip_while(|line| !line.contains("x64.call")).skip(1).collect();
8026        assert_eq!(after[0].trim(), "%0:gpr = x64.lea_64 [$rsp]", "{text}");
8027        assert_eq!(after[1].trim(), "x64.fstp_t [%0]", "{text}");
8028        // And the slot it went into is the sixteen bytes the type takes, like every other one.
8029        assert_eq!(lowered.stack.locals.len(), 1, "{text}");
8030        assert_eq!(lowered.stack.locals[0].size, X87_BYTES);
8031    }
8032
8033    #[test]
8034    fn a_call_through_an_address_goes_through_the_register_the_address_is_in() {
8035        let i32 = Type::int(32);
8036        let (mut names, mut source, block, args) = blank(&[Type::PTR, i32]);
8037        let sig = source.add_signature(Signature::new().with_params(&[i32]).with_returns(&[i32]));
8038        let varargs = source.push_abis(&[]);
8039        let info = source.add_call(CallInfo { callee: None, signature: sig, varargs });
8040        let mut build = Builder::new(&mut source, block);
8041        let inst = InstData {
8042            args: build.func().push_values(&[args[0], args[1]]),
8043            extra: Extra::Call(info),
8044            ..InstData::new(Opcode::CallIndirect)
8045        };
8046        let called = build.inst(inst, &[i32]);
8047        let got = source[called].first_result.expect("an integer comes back");
8048        Builder::new(&mut source, block).ret(&[got]);
8049
8050        // `int f(int (*g)(int), int a) { return g(a); }`. The first operand is the address and
8051        // the arguments are the ones behind it, and everything else about the call is what a call
8052        // to a name would have been.
8053        let text = lower(&mut names, &source);
8054        assert!(text.contains("= x64.call_reg %0, %1($rdi)"), "{text}");
8055        assert!(text.contains("x64.ret_val_32 %2($rax)"), "{text}");
8056        assert!(!text.contains("@g"), "a call through an address names nobody: {text}");
8057    }
8058
8059    #[test]
8060    fn an_instruction_no_rule_covers_is_reported() {
8061        let (mut names, mut source, block, args) = blank(&[Type::PTR]);
8062        let mut build = Builder::new(&mut source, block);
8063        let operands = build.func().push_values(&[args[0]]);
8064        build.inst(InstData { args: operands, ..InstData::new(Opcode::MetaBegin) }, &[]);
8065
8066        // The mark that an object has come into being, which nothing writes an instruction for
8067        // yet: what it needs is a write over a range of the lifetime plane, and that is
8068        // `tamnd/rucc#856`. Nothing about it is a width or a register, so there is nothing for the
8069        // message to add beyond the name.
8070        let failed = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
8071            .expect_err("no rule writes the beginning of a lifetime");
8072        assert_eq!(failed.to_string(), "no rule lowers a `meta_begin`");
8073
8074        // It produces nothing, so there is no type in the message and nothing invents one, and the
8075        // instruction comes back so a caller can ask the function where it was.
8076        let inst = failed.inst().expect("the instruction it is about");
8077        assert_eq!(source[inst].opcode, Opcode::MetaBegin);
8078    }
8079
8080    /// A barrier is written by name here, and what it is depends on the ordering and on nothing
8081    /// else. `crate::expand` is where the reasoning about this machine's memory model lives.
8082    #[test]
8083    fn a_barrier_is_one_instruction_at_the_strongest_ordering_and_none_below_it() {
8084        for order in MemOrder::all().filter(|&order| order != MemOrder::NotAtomic) {
8085            let (mut names, mut source, block, _) = blank(&[]);
8086            let mut build = Builder::new(&mut source, block);
8087            build
8088                .inst(InstData { extra: Extra::Order(order), ..InstData::new(Opcode::Fence) }, &[]);
8089
8090            let text = lower(&mut names, &source);
8091            assert_eq!(text.contains("x64.mfence"), order == MemOrder::SeqCst, "{order:?}: {text}");
8092        }
8093    }
8094
8095    /// A compare and exchange is written by name too, and at the width of the value rather than at
8096    /// the width of the address, which is the mistake worth pinning: everything here is a pointer
8097    /// and only the value says how many bytes the instruction touches.
8098    #[test]
8099    fn a_compare_and_exchange_is_one_instruction_at_the_width_of_the_value() {
8100        for bits in [8, 16, 32, 64] {
8101            let ty = Type::int(bits);
8102            let (mut names, mut source, block, args) = blank(&[Type::PTR, ty, ty]);
8103            let mut build = Builder::new(&mut source, block);
8104            let mem = build.func().add_mem(MemInfo {
8105                size: u64::from(bits / 8),
8106                align: bits / 8,
8107                order: MemOrder::SeqCst,
8108                ..plain()
8109            });
8110            let operands = build.func().push_values(&[args[0], args[1], args[2]]);
8111            build.inst(
8112                InstData {
8113                    args: operands,
8114                    extra: Extra::Mem(mem),
8115                    ..InstData::new(Opcode::Cmpxchg)
8116                },
8117                &[ty, Type::I1],
8118            );
8119
8120            // Two values out of one instruction, the first of them in the register the machine
8121            // reads the expected value out of, the second free for the allocator to place. The
8122            // address is the memory operand and neither of the two values is.
8123            let text = lower(&mut names, &source);
8124            let written = format!("%3:gpr($rax), %4:gpr = x64.cmpxchg_{bits} %1($rax), %2, [%0]");
8125            assert!(text.contains(&written), "{bits}: {text}");
8126        }
8127    }
8128
8129    #[test]
8130    fn more_values_back_than_the_convention_has_registers_for_is_reported() {
8131        let i64 = Type::int(64);
8132        let (mut names, mut source, block, args) = blank(&[i64, i64, i64]);
8133        let mut build = Builder::new(&mut source, block);
8134        build.ret(&[args[0], args[1], args[2]]);
8135
8136        // Two integers come back in `rax` and `rdx` and a third has nowhere to go, which is not a
8137        // gap in the rules but the convention saying no. The front end classifies before it gets
8138        // here, so this is the shape that would mean the classification went wrong.
8139        let failed = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
8140            .expect_err("only two come back");
8141        assert_eq!(
8142            failed.to_string(),
8143            "what this function gives back takes more registers than this convention has for it"
8144        );
8145
8146        let inst = failed.inst().expect("the instruction it is about");
8147        assert_eq!(source[inst].opcode, Opcode::Return);
8148    }
8149
8150    /// A refusal about a signature has no instruction, which is what makes it the one arm apart.
8151    ///
8152    /// Everything else is about something written somewhere in the body and hands it back so a
8153    /// caller can ask the function where it came from. A parameter arrives before the first
8154    /// instruction runs, so there is nothing in the body to point at and the message is about
8155    /// the function.
8156    #[test]
8157    fn a_refusal_about_a_parameter_has_no_instruction_to_point_at() {
8158        let missing = Unsupported::Argument { index: 0, missing: Missing::OnX87 };
8159        assert_eq!(missing.inst(), None);
8160    }
8161
8162    /// An `alloca` of a fixed size, which is what every local whose address is taken becomes.
8163    fn slot(source: &mut Func, block: Block, size: u64, align: u32) -> Value {
8164        let info = MemInfo { size, align, ..plain() };
8165        let mut build = Builder::new(source, block);
8166        let mem = build.func().add_mem(info);
8167        build.value(InstData { extra: Extra::Mem(mem), ..InstData::new(Opcode::Alloca) }, Type::PTR)
8168    }
8169
8170    #[test]
8171    fn a_local_is_memory_in_the_frame_and_one_instruction_that_says_where() {
8172        let (mut names, mut source, block, _) = blank(&[]);
8173        let slot = slot(&mut source, block, 4, 4);
8174        let mut build = Builder::new(&mut source, block);
8175        let nine = build.iconst(Type::int(32), 9);
8176        build.store(nine, slot, plain(), Flags::default());
8177        let loaded = build.load(Type::int(32), slot, plain(), Flags::default());
8178        build.ret(&[loaded]);
8179
8180        let lowered = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
8181            .expect("every instruction has a rule");
8182
8183        // Four bytes on the list the frame is laid out from, and the one instruction that reads
8184        // where they went. Its displacement is nothing here because there is no frame yet, and
8185        // which instruction is waiting for which local is what `finish` is handed.
8186        assert_eq!(lowered.stack.locals, vec![Local { size: 4, align: 4 }]);
8187        assert_eq!(lowered.stack.addresses.len(), 1);
8188        assert_eq!(lowered.stack.addresses[0].1, 0);
8189        assert_eq!(
8190            mir::print_func(&lowered.func, &names, &REGS),
8191            "mfunc @f {\nblock0:\n    %0:gpr = x64.lea_64 [$rsp]\n    \
8192             %1:gpr = x64.mov_ri_32 9\n    x64.mov_mr_32 %1, [%0]\n    \
8193             %2:gpr = x64.mov_rm_32 [%0]\n    x64.ret_val_32 %2($rax)\n}\n"
8194        );
8195    }
8196
8197    #[test]
8198    fn a_local_the_program_declared_says_which_declaration_it_is_and_the_rest_say_nothing() {
8199        let (mut names, mut source, block, _) = blank(&[]);
8200        let scratch = slot(&mut source, block, 4, 4);
8201        let mut build = Builder::new(&mut source, block);
8202        let mem = build.func().add_mem(MemInfo { size: 8, align: 8, ..plain() });
8203        let declared = build
8204            .value(InstData { extra: Extra::Mem(mem), ..InstData::new(Opcode::Alloca) }, Type::PTR);
8205        build.func().declare_mem(mem, 41);
8206        build.store(scratch, declared, MemInfo { size: 8, align: 8, ..plain() }, Flags::default());
8207        build.ret(&[]);
8208
8209        let lowered = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
8210            .expect("every instruction has a rule");
8211
8212        // Two locals and one declaration, held against the order the allocas were lowered in,
8213        // which is the only name a local has by the time the frame places it. The scratch one was
8214        // reached first and is local zero, so the declared one is local one.
8215        assert_eq!(lowered.stack.locals.len(), 2);
8216        assert_eq!(lowered.stack.declared, vec![(1, 41)]);
8217    }
8218
8219    /// A local the program kept in a value comes out saying which register holds it.
8220    ///
8221    /// The other half of the local above, which had a slot. This one has none, so what carries the
8222    /// declaration is the register the instruction computing it writes into.
8223    #[test]
8224    fn a_local_the_program_kept_in_a_value_says_which_register_holds_it() {
8225        let (mut names, mut source, block, _) = blank(&[]);
8226        let mut build = Builder::new(&mut source, block);
8227        let nine = build.iconst(Type::int(32), 9);
8228        let ten = build.iconst(Type::int(32), 10);
8229        let sum = build.binary(Opcode::Add, nine, ten, Flags::default());
8230        build.func().declare_value(sum, 41);
8231        build.ret(&[sum]);
8232
8233        let lowered = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
8234            .expect("every instruction has a rule");
8235
8236        // One pair and not three. The constants are values the program never declared, and a
8237        // register holding one of those is nobody's. The register is the one the addition writes,
8238        // which the listing under it is what pins down.
8239        assert_eq!(lowered.func.named, vec![(41, mir::Reg::virtual_reg(1))]);
8240        assert_eq!(
8241            mir::print_func(&lowered.func, &names, &REGS),
8242            "mfunc @f {\nblock0:\n    %0:gpr = x64.mov_ri_32 9\n    \
8243             %1:gpr(reuse 1) = x64.add_ri_32 %0, 10\n    x64.ret_val_32 %1($rax)\n}\n"
8244        );
8245    }
8246
8247    /// A local held in a constant two blocks want is two registers and both of them are it.
8248    ///
8249    /// Why the declaration is written down as each register is handed out rather than once at the
8250    /// end over the map from values to registers. That map remembers the last register a value was
8251    /// written into, and a constant is written again in every block that wants one, so a local held
8252    /// in one would come out findable in the last block of the function and nowhere else.
8253    #[test]
8254    fn a_local_held_in_a_constant_two_blocks_want_is_named_in_both_of_them() {
8255        let i32 = Type::int(32);
8256        let (mut names, mut source, entry, args) = blank(&[i32, i32]);
8257        let then = source.create_block();
8258        let other = source.create_block();
8259        let join = source.create_block();
8260        let got = source.append_param(join, i32);
8261
8262        let mut build = Builder::new(&mut source, entry);
8263        let seven = build.iconst(i32, 7);
8264        let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
8265        build.func().declare_value(seven, 41);
8266        build.br_if(cond, then, &[], other, &[]);
8267        Builder::new(&mut source, then).jump(join, &[seven]);
8268        Builder::new(&mut source, other).jump(join, &[seven]);
8269        Builder::new(&mut source, join).ret(&[got]);
8270
8271        let lowered = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
8272            .expect("every instruction has a rule");
8273
8274        let held = &lowered.func.named;
8275        assert_eq!(held.len(), 2, "one register per block that wanted the seven: {held:?}");
8276        assert!(held.iter().all(|&(decl, _)| decl == 41), "{held:?}");
8277        assert_ne!(held[0].1, held[1].1, "the same register in two blocks: {held:?}");
8278    }
8279
8280    /// A parameter the program declared comes out named too, in the register it arrived in.
8281    ///
8282    /// The case the walk over the map at the end is for. A parameter is put in a register the
8283    /// convention chose rather than in a fresh one, so nothing asks the mint for it and the pair
8284    /// would otherwise never be written down.
8285    #[test]
8286    fn a_parameter_the_program_declared_says_which_register_it_arrived_in() {
8287        let i32 = Type::int(32);
8288        let (mut names, mut source, block, args) = blank(&[i32]);
8289        let mut build = Builder::new(&mut source, block);
8290        build.func().declare_value(args[0], 41);
8291        build.ret(&[args[0]]);
8292
8293        let lowered = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
8294            .expect("every instruction has a rule");
8295
8296        let held = &lowered.func.named;
8297        assert_eq!(held.len(), 1, "one pair for the one parameter: {held:?}");
8298        assert_eq!(held[0].0, 41);
8299    }
8300
8301    /// A function with nothing declared in it says nothing, which is every function compiled
8302    /// without debugging information asked for.
8303    #[test]
8304    fn a_function_the_front_end_named_nothing_in_names_no_registers() {
8305        let (mut names, mut source, block, _) = blank(&[]);
8306        let mut build = Builder::new(&mut source, block);
8307        let nine = build.iconst(Type::int(32), 9);
8308        build.ret(&[nine]);
8309
8310        let lowered = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
8311            .expect("every instruction has a rule");
8312        assert!(lowered.func.named.is_empty(), "{:?}", lowered.func.named);
8313    }
8314
8315    #[test]
8316    fn the_frame_is_what_fills_the_address_of_a_local_in() {
8317        let (mut names, mut source, block, _) = blank(&[]);
8318        let slot = slot(&mut source, block, 4, 4);
8319        let mut build = Builder::new(&mut source, block);
8320        let nine = build.iconst(Type::int(32), 9);
8321        build.store(nine, slot, plain(), Flags::default());
8322        let loaded = build.load(Type::int(32), slot, plain(), Flags::default());
8323        build.ret(&[loaded]);
8324
8325        let lowered = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
8326            .expect("every instruction has a rule");
8327        let stack = lowered.stack;
8328        let mut out = lowered.func;
8329        let env = env();
8330        let allocation = rucc_regalloc::run(&mut out, &env, "test", true);
8331        let layout = stack.layout(Layout::new(&SYSV, REGS));
8332        let frame = Frame::of(&out, &allocation, &layout);
8333        finish(&mut out, &allocation, &frame, &stack, Convention::new(&SYSV, &FRAME), &mut names);
8334
8335        // `int f(void) { int x; x = 9; return x; }` with the address of `x` taken, end to end.
8336        // A leaf small enough to live in the red zone takes no frame at all, so the stack pointer
8337        // never moves and the four bytes are below it, which is what the negative offset is. The
8338        // instruction the lowering left with nothing in its displacement now has the answer in it.
8339        let text = mir::print_func(&out, &names, &REGS);
8340        assert!(text.contains("$rax = x64.lea_64 [$rsp - 8]"), "{text}");
8341        assert!(!text.contains("x64.sub_ri_64"), "{text}");
8342        assert_eq!(frame.size(), 0);
8343        assert_eq!(frame.local(0), Some(-8));
8344    }
8345
8346    /// An `alloca` whose size is an operand, which is a variable length array.
8347    fn growing(source: &mut Func, block: Block, size: Value, align: u32) -> Value {
8348        let info = MemInfo { size: 0, align, ..plain() };
8349        let mut build = Builder::new(source, block);
8350        let mem = build.func().add_mem(info);
8351        let args = build.func().push_values(&[size]);
8352        build.value(
8353            InstData { args, extra: Extra::Mem(mem), ..InstData::new(Opcode::Alloca) },
8354            Type::PTR,
8355        )
8356    }
8357
8358    #[test]
8359    fn a_stack_slot_whose_size_is_not_known_until_it_runs_takes_the_bytes_off_the_stack_pointer() {
8360        let (mut names, mut source, block, args) = blank(&[Type::int(64)]);
8361        let slot = growing(&mut source, block, args[0], 16);
8362        Builder::new(&mut source, block).ret(&[slot]);
8363
8364        let lowered = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
8365            .expect("every instruction has a rule");
8366
8367        // The bytes come off the stack pointer where the declaration stands and the address is
8368        // where the stack pointer then is, which is one subtraction and one `lea` rather than a
8369        // slot the frame laid out. Nothing is on the list of locals, because there is nothing
8370        // about this the frame could place.
8371        let text = mir::print_func(&lowered.func, &names, &REGS);
8372        assert!(text.contains("$rsp = x64.sub_rr_64 $rsp, %0"), "{text}");
8373        assert!(text.contains("x64.lea_64 [$rsp]"), "{text}");
8374        assert!(lowered.stack.locals.is_empty(), "{text}");
8375        assert_eq!(lowered.stack.dynamic.len(), 1);
8376        assert!(lowered.stack.grown_at.is_some());
8377    }
8378
8379    #[test]
8380    fn a_growing_slot_wanting_more_alignment_than_the_stack_pointer_has_is_reported() {
8381        let (mut names, mut source, block, args) = blank(&[Type::int(64)]);
8382        let slot = growing(&mut source, block, args[0], 32);
8383        Builder::new(&mut source, block).ret(&[slot]);
8384
8385        // Thirty two is more than a call leaves the stack pointer on, so giving it what it asked
8386        // for means masking the stack pointer after moving it, and after that no constant reaches
8387        // the rest of the frame from the frame pointer either. A second pointer held for the
8388        // purpose is what fixes it and there is not one yet.
8389        let failed = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
8390            .expect_err("nothing realigns a frame that grows");
8391        assert_eq!(
8392            failed.to_string(),
8393            "this local wants more alignment than the stack pointer is left on, which needs a \
8394             base register nothing here keeps"
8395        );
8396    }
8397
8398    #[test]
8399    fn a_frame_that_grows_reaches_its_own_locals_through_the_frame_pointer() {
8400        let (mut names, mut source, block, args) = blank(&[Type::int(64)]);
8401        let fixed = slot(&mut source, block, 4, 4);
8402        let mut build = Builder::new(&mut source, block);
8403        let nine = build.iconst(Type::int(32), 9);
8404        build.store(nine, fixed, plain(), Flags::default());
8405        let grown = growing(&mut source, block, args[0], 16);
8406        Builder::new(&mut source, block).ret(&[grown]);
8407
8408        let lowered = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
8409            .expect("every instruction has a rule");
8410        let stack = lowered.stack;
8411        let mut out = lowered.func;
8412        let env = env();
8413        let allocation = rucc_regalloc::run(&mut out, &env, "test", true);
8414        let layout = stack.layout(Layout::new(&SYSV, REGS));
8415        let frame = Frame::of(&out, &allocation, &layout);
8416        finish(&mut out, &allocation, &frame, &stack, Convention::new(&SYSV, &FRAME), &mut names);
8417
8418        // The stack pointer moves in the middle of the function, so the four bytes of the fixed
8419        // local are not a constant away from it any more and the frame pointer is what reaches
8420        // them. The frame keeps one whatever the flags asked for, takes its bytes rather than
8421        // living in the red zone, and the address of the growing slot is off the stack pointer as
8422        // it stands after the subtraction rather than off anything the prologue left.
8423        let text = mir::print_func(&out, &names, &REGS);
8424        assert!(frame.grows());
8425        assert!(frame.frame_pointer());
8426        assert!(frame.size() > 0, "{text}");
8427        assert!(text.contains("x64.lea_64 [$rbp"), "{text}");
8428        assert!(text.contains("$rsp = x64.sub_rr_64 $rsp"), "{text}");
8429        assert!(text.contains("x64.lea_64 [$rsp]"), "{text}");
8430    }
8431
8432    #[test]
8433    fn an_address_is_read_written_and_added_to_like_the_integer_it_is() {
8434        let (mut names, mut source, block, args) = blank(&[Type::PTR, Type::int(64)]);
8435        let mut build = Builder::new(&mut source, block);
8436        let stepped = build.func().push_values(&[args[0], args[1]]);
8437        let next =
8438            build.value(InstData { args: stepped, ..InstData::new(Opcode::PtrAdd) }, Type::PTR);
8439        let loaded = build.load(Type::int(32), next, plain(), Flags::default());
8440        build.ret(&[loaded]);
8441
8442        // `int f(int *p, long i) { return *(int *)((char *)p + i); }`. Nothing about this is new
8443        // in the rule set, which is the point: the two addresses arrive in registers because an
8444        // address is an integer as wide as one, and the arithmetic on them is the add it always
8445        // was, so every rule written about an add reaches it.
8446        //
8447        // The add stays its own instruction here rather than folding into the address the load
8448        // reads from. Two registers with no scale on either is the one addressing mode the rules
8449        // have no load through, because the folds that exist are the displacement one and the
8450        // scaled ones, and this is neither. `crate::fold` is what puts the two together, after
8451        // selection, and this is the pair it is handed.
8452        assert_eq!(
8453            lower(&mut names, &source),
8454            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_64\n    \
8455             %1:gpr($rsi) = x64.arg_val_64\n    %2:gpr(reuse 1) = x64.add_rr_64 %0, %1\n    \
8456             %3:gpr = x64.mov_rm_32 [%2]\n    x64.ret_val_32 %3($rax)\n}\n"
8457        );
8458    }
8459
8460    /// The address of a file scope name, which is what every use of a global and every string
8461    /// literal starts from.
8462    fn address_of(source: &mut Func, block: Block, names: &mut Interner, name: &str) -> Value {
8463        let symbol = names.intern(name);
8464        let mut build = Builder::new(source, block);
8465        build.value(
8466            InstData { extra: Extra::Symbol(symbol), ..InstData::new(Opcode::GlobalAddr) },
8467            Type::PTR,
8468        )
8469    }
8470
8471    #[test]
8472    fn the_address_of_a_name_is_one_instruction_carrying_the_name() {
8473        let (mut names, mut source, block, _) = blank(&[]);
8474        let counter = address_of(&mut source, block, &mut names, "counter");
8475        let mut build = Builder::new(&mut source, block);
8476        let loaded = build.load(Type::int(32), counter, plain(), Flags::default());
8477        build.ret(&[loaded]);
8478
8479        // `extern int counter; int f(void) { return counter; }`. The address is an addressing mode
8480        // that names no register and carries the symbol, which is what the assembler writes
8481        // relative to `%rip` and what the object writer leaves a relocation for.
8482        assert_eq!(
8483            lower(&mut names, &source),
8484            "mfunc @f {\nblock0:\n    %0:gpr = x64.lea_64 [@counter]\n    \
8485             %1:gpr = x64.mov_rm_32 [%0]\n    x64.ret_val_32 %1($rax)\n}\n"
8486        );
8487    }
8488
8489    #[test]
8490    fn the_address_of_a_name_outside_the_file_is_read_out_of_the_offset_table() {
8491        let (mut names, mut source, block, _) = blank(&[]);
8492        let away = address_of(&mut source, block, &mut names, "away");
8493        Builder::new(&mut source, block).ret(&[away]);
8494        let elsewhere: Elsewhere = [names.intern("away")].into_iter().collect();
8495
8496        // `extern void away(void); void *f(void) { return away; }`. A load and not an address
8497        // computation, because the distance from here to a name a shared library may be the one
8498        // that defines is not a number any link can work out, and the slot the linker fills in is
8499        // in this program and so is a distance it has.
8500        let out = func(&source, &mut names, &SELECTOR, &SYSV, &elsewhere)
8501            .expect("every instruction has a rule");
8502        assert_eq!(
8503            mir::print_func(&out.func, &names, &REGS),
8504            "mfunc @f {\nblock0:\n    %0:gpr = x64.mov_rm_64 [got @away]\n    \
8505             x64.ret_val_64 %0($rax)\n}\n"
8506        );
8507    }
8508
8509    #[test]
8510    fn the_address_of_a_thread_local_is_an_offset_out_of_the_table_plus_where_this_thread_starts() {
8511        let (mut names, mut source, block, _) = blank(&[]);
8512        let own = address_of(&mut source, block, &mut names, "own");
8513        Builder::new(&mut source, block).ret(&[own]);
8514        let elsewhere = Elsewhere::default().with_threads([names.intern("own")]);
8515
8516        // `extern _Thread_local int own; void *f(void) { return &own; }`. Three instructions where
8517        // the two cases above are one, because there is no address to load or to work out: the
8518        // slot holds how far into a thread's block the variable sits, `%fs:0` is where this
8519        // thread's block starts, and the sum of the two is this thread's copy.
8520        let out = func(&source, &mut names, &SELECTOR, &SYSV, &elsewhere)
8521            .expect("every instruction has a rule");
8522        assert_eq!(
8523            mir::print_func(&out.func, &names, &REGS),
8524            "mfunc @f {\nblock0:\n    %0:gpr = x64.mov_rm_64 [thread @own]\n    \
8525             %1:gpr = x64.mov_rm_64 [fs:0]\n    %2:gpr(reuse 1) = x64.add_rr_64 %0, %1\n    \
8526             x64.ret_val_64 %2($rax)\n}\n"
8527        );
8528    }
8529
8530    /// The same load with nothing added to it, which is the whole of `__builtin_thread_pointer`.
8531    #[test]
8532    fn the_start_of_this_thread_s_own_storage_is_the_one_load_and_no_arithmetic() {
8533        let (mut names, mut source, block, _) = blank(&[]);
8534        let here =
8535            Builder::new(&mut source, block).value(InstData::new(Opcode::ThreadPointer), Type::PTR);
8536        Builder::new(&mut source, block).ret(&[here]);
8537
8538        let out = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
8539            .expect("every instruction has a rule");
8540        assert_eq!(
8541            mir::print_func(&out.func, &names, &REGS),
8542            "mfunc @f {\nblock0:\n    %0:gpr = x64.mov_rm_64 [fs:0]\n    \
8543             x64.ret_val_64 %0($rax)\n}\n"
8544        );
8545    }
8546
8547    /// One `asm` statement, with its template and its constraint list written as a program does.
8548    fn assembly(
8549        source: &mut Func,
8550        block: Block,
8551        names: &mut Interner,
8552        template: &str,
8553        constraints: &str,
8554        args: &[Value],
8555        results: &[Type],
8556    ) -> Inst {
8557        clobbering(source, block, names, template, constraints, "memory", args, results)
8558    }
8559
8560    /// The same with a clobber list of its own, for the statements that are about one.
8561    #[allow(clippy::too_many_arguments)]
8562    fn clobbering(
8563        source: &mut Func,
8564        block: Block,
8565        names: &mut Interner,
8566        template: &str,
8567        constraints: &str,
8568        clobbers: &str,
8569        args: &[Value],
8570        results: &[Type],
8571    ) -> Inst {
8572        let info = AsmInfo {
8573            template: names.intern(template),
8574            constraints: names.intern(constraints),
8575            clobbers: names.intern(clobbers),
8576            targets: rucc_ir::BlockCallList::EMPTY,
8577        };
8578        Builder::new(source, block).inline_asm(info, args, results, Flags::VOLATILE)
8579    }
8580
8581    /// What a program asking the processor what it can do writes, which is the instruction whose
8582    /// every operand is a register its text does not name.
8583    #[test]
8584    fn a_template_whose_registers_are_named_by_the_constraints_places_them_from_the_letters() {
8585        let u32 = Type::int(32);
8586        let (mut names, mut source, block, _) = blank(&[]);
8587        let zero = Builder::new(&mut source, block).iconst(u32, 0);
8588        let out = clobbering(
8589            &mut source,
8590            block,
8591            &mut names,
8592            "cpuid",
8593            "=a,a",
8594            "ebx,ecx,edx",
8595            &[zero],
8596            &[u32],
8597        );
8598        let produced = source[out].results().next().expect("one result");
8599        Builder::new(&mut source, block).ret(&[produced]);
8600
8601        // `asm ("cpuid" : "=a" (n) : "a" (0) : "ebx", "ecx", "edx")`, which is the first thing
8602        // every program that has a faster path on some machines writes. Four registers written and
8603        // two read, none of them in the template, all of them out of the description, and the two
8604        // that the letters named are the statement's own. The subleaf is a zero because the
8605        // instruction reads `ecx` and the program said nothing about what is in it. The three
8606        // clobbers are gone because `cpuid` writes those three anyway, and saying it twice is one
8607        // register with two definitions.
8608        assert_eq!(
8609            lower(&mut names, &source),
8610            "mfunc @f {\nblock0:\n    %0:gpr = x64.mov_ri_32 0\n    \
8611             %1:gpr = x64.mov_ri_64 0\n    \
8612             %2:gpr($rax), %3:gpr($rbx), %4:gpr($rcx), %5:gpr($rdx) = x64.cpuid %0($rax), \
8613             %1($rcx)\n    x64.ret_val_32 %2($rax)\n}\n"
8614        );
8615    }
8616
8617    /// An operand the program pinned, by declaring the object it comes from `register long x asm
8618    /// ("r12")`. The letter on its own leaves the allocator to pick, and a template that reads the
8619    /// register by name needs the two to be the same register, so the brace is what ties them
8620    /// together. That is the one use of a local register variable the GNU manual calls reliable,
8621    /// and it is what tcc's `tests/tcctest.c` counts on.
8622    #[test]
8623    fn an_operand_the_program_pinned_is_placed_in_the_register_it_named() {
8624        let u64 = Type::int(64);
8625        let (mut names, mut source, block, _) = blank(&[]);
8626        let out =
8627            assembly(&mut source, block, &mut names, "mov $0x4542, %r12", "=r{r12}", &[], &[u64]);
8628        let produced = source[out].results().next().expect("one result");
8629        Builder::new(&mut source, block).ret(&[produced]);
8630
8631        // The template is one instruction the table already has, so it lowers to that instruction
8632        // rather than to text nobody read, and the register it names is the statement's own output
8633        // because the brace put the output there. Without the brace the letter would have let the
8634        // allocator pick, the two `%r12` would have been different registers, and the program would
8635        // have come back with whatever was in the one it picked.
8636        assert_eq!(
8637            lower(&mut names, &source),
8638            "mfunc @f {\nblock0:\n    %0:gpr($r12) = x64.mov_ri_64 17730\n    \
8639             x64.ret_val_64 %0($rax)\n}\n"
8640        );
8641    }
8642
8643    /// A clobber the instruction does not write itself, which is the case the list is there for.
8644    /// It goes on as a definition of the register, in among the other definitions, because that is
8645    /// the whole of how a machine function says a register is not worth anything after this.
8646    #[test]
8647    fn a_clobber_the_instruction_does_not_write_itself_is_a_definition_of_that_register() {
8648        let (mut names, mut source, block, _) = blank(&[]);
8649        clobbering(&mut source, block, &mut names, "pause", "", "rsi,cc,memory", &[], &[]);
8650        Builder::new(&mut source, block).ret(&[]);
8651
8652        assert_eq!(lower(&mut names, &source), "mfunc @f {\nblock0:\n    $rsi = x64.pause\n}\n");
8653    }
8654
8655    /// A clobber naming something this has no register for. Refused rather than dropped, since the
8656    /// list is the program saying which registers it may not leave anything in, and an entry
8657    /// nobody read is a register something may still be left in.
8658    #[test]
8659    fn a_clobber_this_has_no_register_for_is_refused() {
8660        let (mut names, mut source, block, _) = blank(&[]);
8661        clobbering(&mut source, block, &mut names, "pause", "", "zmm0", &[], &[]);
8662        Builder::new(&mut source, block).ret(&[]);
8663
8664        let failed = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
8665            .expect_err("there is no such register here");
8666        assert_eq!(
8667            failed.to_string(),
8668            "this `asm` says it destroys a register this has no name for"
8669        );
8670    }
8671
8672    #[test]
8673    fn an_asm_with_an_empty_template_and_no_operands_is_no_instructions() {
8674        let (mut names, mut source, block, _) = blank(&[]);
8675        assembly(&mut source, block, &mut names, "", "", &[], &[]);
8676        Builder::new(&mut source, block).ret(&[]);
8677
8678        // `asm volatile ("" : : : "memory")`, which is a barrier and nothing else. The barrier was
8679        // spent on the optimizer, which has finished by now, so what is left is nothing.
8680        assert_eq!(lower(&mut names, &source), "mfunc @f {\nblock0:\n}\n");
8681    }
8682
8683    #[test]
8684    fn an_output_an_input_is_tied_to_is_the_register_that_input_arrived_in() {
8685        let i32 = Type::int(32);
8686        let (mut names, mut source, block, args) = blank(&[i32]);
8687        let out = assembly(&mut source, block, &mut names, "", "=r,0", &args, &[i32]);
8688        let produced = source[out].results().next().expect("one result");
8689        Builder::new(&mut source, block).ret(&[produced]);
8690
8691        // `asm ("" : "=r" (x) : "0" (x))`, which is how a program stops the optimizer following a
8692        // value without changing it. The two share a place and the template writes nothing over
8693        // it, so the value comes back out of the register it went in.
8694        assert_eq!(
8695            lower(&mut names, &source),
8696            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_32\n    \
8697             x64.ret_val_32 %0($rax)\n}\n"
8698        );
8699    }
8700
8701    #[test]
8702    fn an_output_written_plus_is_the_same_rename() {
8703        let i32 = Type::int(32);
8704        let (mut names, mut source, block, args) = blank(&[i32]);
8705        let out = assembly(&mut source, block, &mut names, "", "+r", &args, &[i32]);
8706        let produced = source[out].results().next().expect("one result");
8707        Builder::new(&mut source, block).ret(&[produced]);
8708
8709        // `asm ("" : "+r" (x))`, which says the same thing in one operand instead of two.
8710        assert_eq!(
8711            lower(&mut names, &source),
8712            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_32\n    \
8713             x64.ret_val_32 %0($rax)\n}\n"
8714        );
8715    }
8716
8717    #[test]
8718    fn an_output_nothing_is_tied_to_is_a_zero() {
8719        let i32 = Type::int(32);
8720        let (mut names, mut source, block, _) = blank(&[]);
8721        let out = assembly(&mut source, block, &mut names, "", "=r", &[], &[i32]);
8722        let produced = source[out].results().next().expect("one result");
8723        Builder::new(&mut source, block).ret(&[produced]);
8724
8725        // `asm ("" : "=r" (y))`, whose answer is whatever the assembly left in the register, and
8726        // an empty template leaves nothing. A definite value rather than a register nothing wrote,
8727        // because the allocator is owed a definition before the use however little the program is.
8728        assert_eq!(
8729            lower(&mut names, &source),
8730            "mfunc @f {\nblock0:\n    %0:gpr = x64.mov_ri_32 0\n    x64.ret_val_32 %0($rax)\n}\n"
8731        );
8732    }
8733
8734    #[test]
8735    fn a_template_that_is_one_instruction_becomes_that_instruction() {
8736        let (mut names, mut source, block, _) = blank(&[]);
8737        assembly(&mut source, block, &mut names, "pause", "", &[], &[]);
8738        Builder::new(&mut source, block).ret(&[]);
8739
8740        // `asm volatile ("pause")`, which is what every spin lock in every allocator writes. One
8741        // instruction, no operands, and nothing between the template and the machine but the table
8742        // that already says what a `pause` is.
8743        assert_eq!(lower(&mut names, &source), "mfunc @f {\nblock0:\n    x64.pause\n}\n");
8744    }
8745
8746    #[test]
8747    fn a_template_that_reads_a_segment_becomes_the_load_it_already_was() {
8748        let i64 = Type::int(64);
8749        let (mut names, mut source, block, _) = blank(&[]);
8750        let out = assembly(&mut source, block, &mut names, "movq %%fs:0, %0", "=r", &[], &[i64]);
8751        let produced = source[out].results().next().expect("one result");
8752        Builder::new(&mut source, block).ret(&[produced]);
8753
8754        // `asm ("movq %%fs:0, %0" : "=r" (tid))`, which is how a program finds the block its own
8755        // thread owns. The same instruction `crate::lower` already writes for a thread-local
8756        // variable, reached this time because a program wrote it out by hand.
8757        assert_eq!(
8758            lower(&mut names, &source),
8759            "mfunc @f {\nblock0:\n    %0:gpr = x64.mov_rm_64 [fs:0]\n    \
8760             x64.ret_val_64 %0($rax)\n}\n"
8761        );
8762    }
8763
8764    /// A template this cannot read is kept as its text, which is what gcc does with every template.
8765    /// Whether the text is an instruction is the assembler's question, asked when the unit is
8766    /// assembled from its listing.
8767    #[test]
8768    fn a_template_naming_an_instruction_this_machine_has_not_got_is_kept_as_text() {
8769        let (mut names, mut source, block, _) = blank(&[]);
8770        assembly(&mut source, block, &mut names, "hcf", "", &[], &[]);
8771        Builder::new(&mut source, block).ret(&[]);
8772
8773        let printed = lower(&mut names, &source);
8774        assert!(printed.contains("x64.template"), "{printed}");
8775        assert!(printed.contains("@hcf"), "{printed}");
8776    }
8777
8778    /// A template kept as text with an operand in a register reads the operand, and its text holds
8779    /// a hole naming that operand of the instruction, which the writer fills with the register the
8780    /// allocator chose. The input is the instruction's only use, behind every register a call may
8781    /// write.
8782    #[test]
8783    fn a_template_kept_as_text_reads_an_operand_in_a_register_through_a_hole() {
8784        let i32 = Type::int(32);
8785        let (mut names, mut source, block, args) = blank(&[i32]);
8786        assembly(&mut source, block, &mut names, "hcf %0", "r", &[args[0]], &[]);
8787        Builder::new(&mut source, block).ret(&[]);
8788
8789        let printed = lower(&mut names, &source);
8790        let line = printed.lines().find(|line| line.contains("x64.template")).unwrap_or_default();
8791        // Twenty five registers are written ahead of it, so the operand read is the twenty sixth,
8792        // spelled at the width of an `int`.
8793        assert!(line.contains("x64.template %0, @hcf \u{1}r25k\u{2}"), "{printed}");
8794        assert!(line.contains("early $rax"), "{printed}");
8795    }
8796
8797    /// A template kept as text with more outputs than the convention keeps registers across a call
8798    /// gets back as many of the registers a call may write as it needs, from the end of the order,
8799    /// and keeps the rest. Six outputs against five preserved registers is one handed back, which is
8800    /// `r9`. `r11` and `r10` come back ahead of it without counting, since they are the allocator's
8801    /// scratch and no operand is given one, but an output it spills is carried in one of them, which
8802    /// it cannot be while the template claims it. The shape is `sodium_sub` in libsodium, whose
8803    /// `sbbq` into memory the reader has no form for, and before this the allocator ran out of
8804    /// registers on it.
8805    #[test]
8806    fn a_template_kept_as_text_with_more_outputs_than_are_kept_gets_registers_back() {
8807        let i64 = Type::int(64);
8808        let (mut names, mut source, block, _) = blank(&[]);
8809        let outputs = [i64; 6];
8810        let asm = assembly(
8811            &mut source,
8812            block,
8813            &mut names,
8814            "hcf %0, %1, %2, %3, %4, %5",
8815            "=&r,=&r,=&r,=&r,=&r,=&r",
8816            &[],
8817            &outputs,
8818        );
8819        let produced: Vec<Value> = source[asm].results().collect();
8820        Builder::new(&mut source, block).ret(&produced[..1]);
8821
8822        let printed = lower(&mut names, &source);
8823        let line = printed.lines().find(|line| line.contains("x64.template")).unwrap_or_default();
8824        assert!(line.contains("early $r8"), "{printed}");
8825        for reg in ["r9", "r10", "r11"] {
8826            assert!(!line.contains(&format!("early ${reg}")), "{printed}");
8827        }
8828    }
8829
8830    /// A register the template named is placed as itself, fixed to the register the program wrote
8831    /// down. A register a constraint letter names is a different thing and is placed too, which the
8832    /// test above is about: there the statement said which of its own operands is in the register,
8833    /// and a name in the middle of a template says the register and nothing about any operand.
8834    #[test]
8835    fn a_template_naming_a_register_gets_that_register() {
8836        let i64 = Type::int(64);
8837        let (mut names, mut source, block, _) = blank(&[]);
8838        let out = assembly(&mut source, block, &mut names, "movq %%rax, %0", "=r", &[], &[i64]);
8839        let produced = source[out].results().next().expect("one result");
8840        Builder::new(&mut source, block).ret(&[produced]);
8841
8842        // `asm ("movq %%rax, %0" : "=r" (x))`, which is a program reading whatever is in `%rax`.
8843        // The source is the register itself and the destination is one the allocator picks.
8844        assert_eq!(
8845            lower(&mut names, &source),
8846            "mfunc @f {\nblock0:\n    %0:gpr = x64.mov_rr_64 $rax($rax)\n    \
8847             x64.ret_val_64 %0($rax)\n}\n"
8848        );
8849    }
8850
8851    /// The half of the same thing every register saving template needs. micropython writes the
8852    /// callee-saved registers into a buffer one `movq %%r12, 48(%%rdi)` at a time, and both halves
8853    /// of that line are a register the template named: the one being stored and the one the address
8854    /// is counted from.
8855    #[test]
8856    fn a_template_counting_an_address_from_a_register_it_named_gets_that_register() {
8857        let (mut names, mut source, block, _) = blank(&[]);
8858        assembly(&mut source, block, &mut names, "movq %%r12, 48(%%rdi)", "", &[], &[]);
8859        Builder::new(&mut source, block).ret(&[]);
8860
8861        assert_eq!(
8862            lower(&mut names, &source),
8863            "mfunc @f {\nblock0:\n    x64.mov_mr_64 $r12($r12), [$rdi + 48]\n}\n"
8864        );
8865    }
8866
8867    /// A local kept in a named register, which is the same register named as itself and reached
8868    /// from the other side. micropython's collector writes six of these and reads them with
8869    /// ordinary C rather than with a template.
8870    #[test]
8871    fn a_local_kept_in_a_named_register_is_one_move_out_of_it() {
8872        let (mut names, mut source, block, _) = blank(&[]);
8873        let held = names.intern("rbx");
8874        let value = Builder::new(&mut source, block).value(
8875            InstData { extra: Extra::Symbol(held), ..InstData::new(Opcode::RegisterValue) },
8876            Type::int(64),
8877        );
8878        Builder::new(&mut source, block).ret(&[value]);
8879
8880        assert_eq!(
8881            lower(&mut names, &source),
8882            "mfunc @f {\nblock0:\n    %0:gpr = x64.mov_rr_64 $rbx($rbx)\n    \
8883             x64.ret_val_64 %0($rax)\n}\n"
8884        );
8885    }
8886
8887    /// The sigil gcc allows in front of the name is syntax and comes off, and a name that is not
8888    /// a register of this machine is refused in words that say which name it was.
8889    #[test]
8890    fn a_register_name_is_read_with_or_without_its_sigil_and_refused_when_there_is_no_such_one() {
8891        for written in ["%r12", "r12"] {
8892            let (mut names, mut source, block, _) = blank(&[]);
8893            let held = names.intern(written);
8894            let value = Builder::new(&mut source, block).value(
8895                InstData { extra: Extra::Symbol(held), ..InstData::new(Opcode::RegisterValue) },
8896                Type::int(64),
8897            );
8898            Builder::new(&mut source, block).ret(&[value]);
8899            assert!(lower(&mut names, &source).contains("$r12($r12)"), "{written} is not read");
8900        }
8901
8902        let (mut names, mut source, block, _) = blank(&[]);
8903        let held = names.intern("nowhere");
8904        let value = Builder::new(&mut source, block).value(
8905            InstData { extra: Extra::Symbol(held), ..InstData::new(Opcode::RegisterValue) },
8906            Type::int(64),
8907        );
8908        Builder::new(&mut source, block).ret(&[value]);
8909
8910        let failed = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
8911            .expect_err("there is no such register");
8912        assert_eq!(
8913            failed.to_string(),
8914            "this object is kept in `nowhere`, which is not a register this machine has"
8915        );
8916    }
8917
8918    #[test]
8919    fn a_constraint_list_that_does_not_describe_the_operands_is_refused() {
8920        let i32 = Type::int(32);
8921        let (mut names, mut source, block, args) = blank(&[i32]);
8922        assembly(&mut source, block, &mut names, "", "=r", &args, &[]);
8923        Builder::new(&mut source, block).ret(&[]);
8924
8925        // An output with no result to be, which is what the front end never writes and what a
8926        // hand written module can. Refused rather than placed by a guess.
8927        let failed = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
8928            .expect_err("the list and the instruction disagree");
8929        assert_eq!(failed.to_string(), "this `asm` has an operand this cannot place");
8930    }
8931
8932    /// A cast between a pointer and an integer, at whatever width the result is asked for.
8933    fn cast(source: &mut Func, block: Block, opcode: Opcode, from: Value, to: Type) -> Value {
8934        let mut build = Builder::new(source, block);
8935        let args = build.func().push_values(&[from]);
8936        build.value(InstData { args, ..InstData::new(opcode) }, to)
8937    }
8938
8939    #[test]
8940    fn a_cast_between_a_pointer_and_an_integer_as_wide_is_no_instruction_at_all() {
8941        let (mut names, mut source, block, args) = blank(&[Type::PTR]);
8942        let number = cast(&mut source, block, Opcode::PtrToInt, args[0], Type::int(64));
8943        Builder::new(&mut source, block).ret(&[number]);
8944
8945        // `long f(void *p) { return (long)p; }`. An address on this machine is an integer as wide
8946        // as the machine addresses, so the cast changes what the type system calls the value and
8947        // changes nothing about the value, and the register holding it is the one that held it.
8948        assert_eq!(
8949            lower(&mut names, &source),
8950            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_64\n    \
8951             x64.ret_val_64 %0($rax)\n}\n"
8952        );
8953    }
8954
8955    #[test]
8956    fn a_null_pointer_is_a_constant_that_reaches_a_register_before_anything_reads_it() {
8957        let (mut names, mut source, block, _) = blank(&[]);
8958        let mut build = Builder::new(&mut source, block);
8959        let zero = build.iconst(Type::int(64), 0);
8960        let null = cast(&mut source, block, Opcode::IntToPtr, zero, Type::PTR);
8961        Builder::new(&mut source, block).ret(&[null]);
8962
8963        // `void *f(void) { return 0; }`. The cast is nothing, and reading its operand is what
8964        // writes the zero down: a constant is materialized where it is wanted rather than where
8965        // the IR defined it, and without the read there would be no instruction at all.
8966        assert_eq!(
8967            lower(&mut names, &source),
8968            "mfunc @f {\nblock0:\n    %0:gpr = x64.mov_ri_64 0\n    x64.ret_val_64 %0($rax)\n}\n"
8969        );
8970    }
8971
8972    #[test]
8973    fn the_five_linkages_the_ir_has_narrow_to_the_three_an_object_file_can_say() {
8974        let readings = [
8975            (Linkage::External, mir::Binding::Global),
8976            (Linkage::Common, mir::Binding::Global),
8977            (Linkage::Internal, mir::Binding::Local),
8978            (Linkage::Weak, mir::Binding::Weak),
8979            (Linkage::LinkOnce, mir::Binding::Weak),
8980        ];
8981        for (linkage, wanted) in readings {
8982            let (mut names, mut source, block, _) = blank(&[]);
8983            source.linkage = linkage;
8984            Builder::new(&mut source, block).ret(&[]);
8985            let out = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
8986                .expect("a return");
8987            // The narrowing is done here rather than where the object is written, because a
8988            // machine function is all the assembler and the writer are ever handed.
8989            assert_eq!(out.func.binding, wanted, "{linkage:?}");
8990        }
8991    }
8992
8993    /// The visibility makes the same trip and is not narrowed on the way, because ELF says all
8994    /// three of them.
8995    ///
8996    /// Here for the reason the linkage above is here. A machine function is the whole of what the
8997    /// assembler and the object writer are handed, so a fact about the symbol that does not get
8998    /// onto one is a fact that is gone by the time anything could write it down, and the way that
8999    /// shows up is a shared library exporting the wrong set of names with nothing said anywhere.
9000    #[test]
9001    fn the_visibility_survives_the_trip_from_the_ir_to_a_machine_function() {
9002        let readings = [
9003            (Visibility::Default, mir::Visibility::Default),
9004            (Visibility::Hidden, mir::Visibility::Hidden),
9005            (Visibility::Protected, mir::Visibility::Protected),
9006        ];
9007        for (visibility, wanted) in readings {
9008            let (mut names, mut source, block, _) = blank(&[]);
9009            source.visibility = visibility;
9010            Builder::new(&mut source, block).ret(&[]);
9011            let out = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
9012                .expect("a return");
9013            assert_eq!(out.func.visibility, wanted, "{visibility:?}");
9014        }
9015    }
9016
9017    #[test]
9018    fn a_cast_between_a_pointer_and_a_narrower_integer_is_reported() {
9019        let (mut names, mut source, block, args) = blank(&[Type::PTR]);
9020        let number = cast(&mut source, block, Opcode::PtrToInt, args[0], Type::int(32));
9021        Builder::new(&mut source, block).ret(&[number]);
9022
9023        // The front end never writes one: it casts at the address width and truncates or extends
9024        // around it, so both of those are the rules they always were. IR from somewhere else that
9025        // does write one is refused rather than compiled to a move that keeps the high half.
9026        let failed = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
9027            .expect_err("no rule narrows an address");
9028        assert_eq!(failed.to_string(), "no rule lowers a `ptrtoint` producing a `i32`");
9029    }
9030
9031    /// The type this machine has no register for.
9032    fn long_double() -> Type {
9033        Type::float(rucc_ir::Float::F80)
9034    }
9035
9036    #[test]
9037    fn a_double_widened_and_narrowed_again_goes_out_through_the_frame_and_back() {
9038        let f64 = Type::float(rucc_ir::Float::F64);
9039        let (mut names, mut source, block, args) = blank(&[f64]);
9040        let wide = cast(&mut source, block, Opcode::FPExt, args[0], long_double());
9041        let back = cast(&mut source, block, Opcode::FPTrunc, wide, f64);
9042        Builder::new(&mut source, block).ret(&[back]);
9043
9044        // `double f(double d) { long double x = d; return x; }`. The x87 reads memory and nothing
9045        // else, so the value is written to the crossing slot, loaded at the format that widens it
9046        // and put in the slot the eighty bit value lives in. Coming back is the same three the
9047        // other way. Both slots are addressed by a `lea` with nothing in it yet, which is what
9048        // every address in a frame looks like here until `finish` has the numbers.
9049        assert_eq!(
9050            lower(&mut names, &source),
9051            "mfunc @f {\nblock0:\n    \
9052             %0:xmm($xmm0) = x64.arg_val_f64\n    \
9053             %1:gpr = x64.lea_64 [$rsp]\n    \
9054             %2:gpr = x64.lea_64 [$rsp]\n    \
9055             x64.movsd_mr %0, [%1]\n    \
9056             x64.fld_l [%1]\n    \
9057             x64.fstp_t [%2]\n    \
9058             %3:gpr = x64.lea_64 [$rsp]\n    \
9059             %4:gpr = x64.lea_64 [$rsp]\n    \
9060             x64.fld_t [%3]\n    \
9061             x64.fstp_l [%4]\n    \
9062             %5:xmm = x64.movsd_rm [%4]\n    \
9063             x64.ret_val_f64 %5($xmm0)\n}\n"
9064        );
9065    }
9066
9067    #[test]
9068    fn a_long_double_has_sixteen_bytes_of_its_own_and_keeps_them() {
9069        let f64 = Type::float(rucc_ir::Float::F64);
9070        let (mut names, mut source, block, args) = blank(&[f64]);
9071        let wide = cast(&mut source, block, Opcode::FPExt, args[0], long_double());
9072        let once = cast(&mut source, block, Opcode::FPTrunc, wide, f64);
9073        let twice = cast(&mut source, block, Opcode::FPTrunc, wide, f64);
9074        let mut build = Builder::new(&mut source, block);
9075        let sum = build.binary(Opcode::FAdd, once, twice, Flags::default());
9076        build.ret(&[sum]);
9077
9078        let out = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
9079            .expect("every instruction is written");
9080
9081        // Two slots and not four: sixteen bytes for the one eighty bit value, which is what the
9082        // psABI says one takes and is aligned to, and eight for the crossing, which every group
9083        // in the function shares because nothing is ever left in it. The value's slot is its own
9084        // for the whole function, so reading it twice reads the same sixteen bytes.
9085        assert_eq!(
9086            out.stack.locals,
9087            vec![Local { size: 8, align: 8 }, Local { size: 16, align: 16 }]
9088        );
9089    }
9090
9091    #[test]
9092    fn an_integer_becomes_a_long_double_by_being_loaded_as_one() {
9093        let (mut names, mut source, block, args) = blank(&[Type::int(64)]);
9094        let wide = cast(&mut source, block, Opcode::SIToFP, args[0], long_double());
9095        let back =
9096            cast(&mut source, block, Opcode::FPTrunc, wide, Type::float(rucc_ir::Float::F64));
9097        Builder::new(&mut source, block).ret(&[back]);
9098
9099        // `double f(long n) { long double x = n; return x; }`. `fild` is the same push at another
9100        // format, so the conversion is the load and there is no instruction that converts.
9101        let text = lower(&mut names, &source);
9102        assert!(text.contains("x64.mov_mr_64 %0, [%1]"), "{text}");
9103        assert!(text.contains("x64.fild_ll [%1]"), "{text}");
9104    }
9105
9106    #[test]
9107    fn a_long_double_becoming_an_integer_cuts_towards_zero_with_the_control_word() {
9108        let (mut names, mut source, block, args) = blank(&[Type::float(rucc_ir::Float::F64)]);
9109        let wide = cast(&mut source, block, Opcode::FPExt, args[0], long_double());
9110        let whole = cast(&mut source, block, Opcode::FPToSI, wide, Type::int(32));
9111        Builder::new(&mut source, block).ret(&[whole]);
9112
9113        // The one conversion here with no single instruction behind it. C cuts towards zero and
9114        // the unit rounds the way its control word says, so the word is saved, ORed with the two
9115        // bits that mean truncate, loaded, used and put back. Nine instructions for what `fisttp`
9116        // does in one, and `spec/10-backend.md` section 10.8 says why that one is not used.
9117        let text = lower(&mut names, &source);
9118        let group: Vec<&str> = text
9119            .lines()
9120            .map(str::trim)
9121            .filter(|line| line.starts_with("x64.f") || line.contains("_16"))
9122            .collect();
9123        assert_eq!(
9124            group,
9125            [
9126                "x64.fld_l [%1]",
9127                "x64.fstp_t [%2]",
9128                "x64.fnstcw [%5]",
9129                "%6:gpr = x64.mov_rm_16 [%5]",
9130                "%7:gpr(reuse 1) = x64.or_ri_16 %6, 3072",
9131                "x64.mov_mr_16 %7, [%5 + 2]",
9132                "x64.fldcw [%5 + 2]",
9133                "x64.fld_t [%3]",
9134                "x64.fistp_l [%4]",
9135                "x64.fldcw [%5]",
9136            ],
9137            "{text}"
9138        );
9139    }
9140
9141    #[test]
9142    fn a_long_double_is_read_and_written_as_the_bits_it_already_is() {
9143        let (mut names, mut source, block, args) = blank(&[Type::PTR, Type::PTR]);
9144        let mut build = Builder::new(&mut source, block);
9145        let value = build.load(long_double(), args[0], plain(), Flags::default());
9146        build.store(value, args[1], plain(), Flags::default());
9147        build.ret(&[]);
9148
9149        // `void f(long double *a, long double *b) { *b = *a; }`. A copy is a push and a pop at the
9150        // format the value is already in, which neither converts nor looks: a signalling NaN stays
9151        // one and nothing is raised, which is the whole of what makes it a copy.
9152        let text = lower(&mut names, &source);
9153        let group: Vec<&str> =
9154            text.lines().map(str::trim).filter(|line| line.starts_with("x64.f")).collect();
9155        assert_eq!(
9156            group,
9157            ["x64.fld_t [%0]", "x64.fstp_t [%2]", "x64.fld_t [%3]", "x64.fstp_t [%1]"],
9158            "{text}"
9159        );
9160    }
9161
9162    /// Two `long double` values, from two `double` parameters, and the instructions that made
9163    /// them, which every test below this one throws away.
9164    fn two_long_doubles(source: &mut Func, block: Block, args: &[Value]) -> (Value, Value) {
9165        let left = cast(source, block, Opcode::FPExt, args[0], long_double());
9166        let right = cast(source, block, Opcode::FPExt, args[1], long_double());
9167        (left, right)
9168    }
9169
9170    /// The x87 instructions of a function, in order, with everything else dropped.
9171    fn stack_only(text: &str) -> Vec<&str> {
9172        text.lines().map(str::trim).filter(|line| line.contains("x64.f")).collect()
9173    }
9174
9175    /// The two frame slots the last two addresses of a function were taken of, which in a
9176    /// comparison are the two operands in the order they go on the stack.
9177    fn pushed(out: &Lowered) -> Vec<usize> {
9178        let taken: Vec<usize> = out.stack.addresses.iter().map(|&(_, local)| local).collect();
9179        taken[taken.len() - 2..].to_vec()
9180    }
9181
9182    #[test]
9183    fn adding_two_long_doubles_pushes_both_and_leaves_the_answer_in_a_slot() {
9184        let f64 = Type::float(rucc_ir::Float::F64);
9185        let (mut names, mut source, block, args) = blank(&[f64, f64]);
9186        let (left, right) = two_long_doubles(&mut source, block, &args);
9187        let sum =
9188            Builder::new(&mut source, block).binary(Opcode::FAdd, left, right, Flags::default());
9189        let back = cast(&mut source, block, Opcode::FPTrunc, sum, f64);
9190        Builder::new(&mut source, block).ret(&[back]);
9191
9192        // `double f(double a, double b) { return (long double) a + (long double) b; }`. The last
9193        // four lines are the add: both operands pushed, the instruction that names neither of
9194        // them because they are the top two of a stack, and the answer taken off into its slot.
9195        let text = lower(&mut names, &source);
9196        assert_eq!(
9197            stack_only(&text),
9198            [
9199                "x64.fld_l [%2]",
9200                "x64.fstp_t [%3]",
9201                "x64.fld_l [%4]",
9202                "x64.fstp_t [%5]",
9203                "x64.fld_t [%6]",
9204                "x64.fld_t [%7]",
9205                "x64.fadd_p",
9206                "x64.fstp_t [%8]",
9207                "x64.fld_t [%9]",
9208                "x64.fstp_l [%10]",
9209            ],
9210            "{text}"
9211        );
9212    }
9213
9214    #[test]
9215    fn a_subtraction_pushes_the_left_operand_first_and_asks_for_the_att_spelling() {
9216        let f64 = Type::float(rucc_ir::Float::F64);
9217        let (mut names, mut source, block, args) = blank(&[f64, f64]);
9218        let (left, right) = two_long_doubles(&mut source, block, &args);
9219        let less =
9220            Builder::new(&mut source, block).binary(Opcode::FSub, left, right, Flags::default());
9221        let back = cast(&mut source, block, Opcode::FPTrunc, less, f64);
9222        Builder::new(&mut source, block).ret(&[back]);
9223
9224        // The left one goes on first, so it ends up under the right one, and the answer wanted is
9225        // the one below minus the top. In AT&T that is `fsubrp`, since `fsubp` there is `DE E0+i`
9226        // and computes the other one. The `r` says which spelling this is and not which order the
9227        // pushes were in. `crates/rucc/tests/x87.rs` is what says the answer is right, because a
9228        // name is what got this wrong the first time.
9229        let text = lower(&mut names, &source);
9230        assert_eq!(
9231            &stack_only(&text)[4..8],
9232            ["x64.fld_t [%6]", "x64.fld_t [%7]", "x64.fsubr_p", "x64.fstp_t [%8]"],
9233            "{text}"
9234        );
9235    }
9236
9237    #[test]
9238    fn negating_a_long_double_turns_the_sign_over_and_reads_nothing() {
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 flipped = Builder::new(&mut source, block).unary(Opcode::FNeg, wide, long_double());
9243        let back = cast(&mut source, block, Opcode::FPTrunc, flipped, f64);
9244        Builder::new(&mut source, block).ret(&[back]);
9245
9246        // `fchs` and not a subtraction from zero, which would give a different answer at a negative
9247        // zero and would signal at a NaN. It does not read the value as a number at all.
9248        let text = lower(&mut names, &source);
9249        assert_eq!(
9250            &stack_only(&text)[2..5],
9251            ["x64.fld_t [%3]", "x64.fchs", "x64.fstp_t [%4]"],
9252            "{text}"
9253        );
9254    }
9255
9256    #[test]
9257    fn comparing_two_long_doubles_puts_the_left_one_on_top() {
9258        let f64 = Type::float(rucc_ir::Float::F64);
9259        let (mut names, mut source, block, args) = blank(&[f64, f64]);
9260        let (left, right) = two_long_doubles(&mut source, block, &args);
9261        let mut build = Builder::new(&mut source, block);
9262        build.fcmp(FloatPred::Ogt, left, right, Flags::default());
9263        build.ret(&[]);
9264
9265        // `a > b`. `fucomip` asks about the top of the stack against what is under it, so the
9266        // operand the predicate is about has to go on last, which is the other way round from the
9267        // arithmetic above. The pop that clears the loser and the byte that reads the flags are
9268        // both inside the one opcode.
9269        let out = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
9270            .expect("every instruction is written");
9271        let slots = pushed(&out);
9272        assert_eq!(slots, [2, 1], "the right operand goes on first and the left one on top");
9273        let text = mir::print_func(&out.func, &names, &REGS);
9274        assert_eq!(
9275            &stack_only(&text)[4..],
9276            ["x64.fld_t [%6]", "x64.fld_t [%7]", "%8:gpr = x64.fucomip_set_a"],
9277            "{text}"
9278        );
9279    }
9280
9281    #[test]
9282    fn a_comparison_that_the_machine_has_backwards_swaps_the_two_pushes() {
9283        let f64 = Type::float(rucc_ir::Float::F64);
9284        let (mut names, mut source, block, args) = blank(&[f64, f64]);
9285        let (left, right) = two_long_doubles(&mut source, block, &args);
9286        let mut build = Builder::new(&mut source, block);
9287        build.fcmp(FloatPred::Olt, left, right, Flags::default());
9288        build.ret(&[]);
9289
9290        // `a < b` is `b > a` and this machine has the one condition, so the same opcode runs with
9291        // the operands the other way round. The same trade the vector rules make, and it has to
9292        // be the same one: a `long double` comparison that picked a different condition from the
9293        // `double` comparison of the same two numbers would be wrong at exactly the unordered
9294        // cases the two conditions differ on.
9295        //
9296        // Which slot each push names is the whole of the difference from the test above, and the
9297        // text does not show it, since an address in a frame is a `lea` with nothing in it until
9298        // `finish` has the numbers. So the slots are what is read here.
9299        let out = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
9300            .expect("every instruction is written");
9301        let slots = pushed(&out);
9302        assert_eq!(slots, [1, 2], "the left operand goes on first and the right one on top");
9303        let text = mir::print_func(&out.func, &names, &REGS);
9304        assert_eq!(
9305            &stack_only(&text)[4..],
9306            ["x64.fld_t [%6]", "x64.fld_t [%7]", "%8:gpr = x64.fucomip_set_a"],
9307            "{text}"
9308        );
9309    }
9310
9311    #[test]
9312    fn an_ordered_equal_needs_a_second_byte_to_put_the_two_conditions_together() {
9313        let f64 = Type::float(rucc_ir::Float::F64);
9314        let (mut names, mut source, block, args) = blank(&[f64, f64]);
9315        let (left, right) = two_long_doubles(&mut source, block, &args);
9316        let mut build = Builder::new(&mut source, block);
9317        build.fcmp(FloatPred::Oeq, left, right, Flags::default());
9318        build.ret(&[]);
9319
9320        // Equal and ordered are two conditions and the flags carry both, so the opcode writes a
9321        // second register as well as the one the value is in and ANDs them together. Said here by
9322        // handing it a spare, since an instruction that wrote a register nothing knew about would
9323        // be an instruction the allocator could put a live value in the way of.
9324        let text = lower(&mut names, &source);
9325        assert!(text.contains("%8:gpr, %9:gpr = x64.fucomip_set_e_and_np"), "{text}");
9326    }
9327
9328    #[test]
9329    fn a_comparison_that_is_never_asked_is_reported() {
9330        let f64 = Type::float(rucc_ir::Float::F64);
9331        let (mut names, mut source, block, args) = blank(&[f64, f64]);
9332        let (left, right) = two_long_doubles(&mut source, block, &args);
9333        let mut build = Builder::new(&mut source, block);
9334        build.fcmp(FloatPred::False, left, right, Flags::default());
9335        build.ret(&[]);
9336
9337        // Always false is a constant and not a comparison, so there is no condition to pick and
9338        // nothing here folds it into one: an instruction that quietly agreed with it would hide
9339        // that the optimizer left a comparison in that it should have taken out.
9340        let failed = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
9341            .expect_err("no condition is always false");
9342        assert_eq!(failed.to_string(), "no rule lowers a `fcmp` producing a `i1`");
9343    }
9344
9345    #[test]
9346    fn a_long_double_constant_is_the_bits_of_it_put_where_the_value_lives() {
9347        let (mut names, mut source, block, args) = blank(&[Type::PTR]);
9348        let mut build = Builder::new(&mut source, block);
9349        // `1.5L`, which is the leading bit and one more of significand, and an exponent of zero.
9350        let one_and_a_half = build.fconst(long_double(), 0x3fff_c000_0000_0000_0000);
9351        build.store(one_and_a_half, args[0], plain(), Flags::default());
9352        build.ret(&[]);
9353
9354        // No x87 instruction at all. A slot holding one of these is the value, so a constant is
9355        // its ten bytes written where the value lives, and whatever reads it does the `fld`.
9356        let text = lower(&mut names, &source);
9357        assert!(text.contains("x64.mov_ri_64 -4611686018427387904"), "{text}");
9358        assert!(text.contains("x64.mov_ri_16 16383"), "{text}");
9359        assert!(text.contains("x64.mov_mr_16 %3, [%1 + 8]"), "{text}");
9360        // The six bytes above the ten are the padding that makes the type sixteen wide, and they
9361        // are unspecified rather than zero, so nothing writes them.
9362        assert_eq!(text.matches("x64.mov_mr").count(), 2, "{text}");
9363    }
9364
9365    #[test]
9366    fn a_negative_long_double_constant_keeps_the_bit_above_its_exponent() {
9367        let (mut names, mut source, block, args) = blank(&[Type::PTR]);
9368        let mut build = Builder::new(&mut source, block);
9369        let minus = build.fconst(long_double(), 0xbfff_c000_0000_0000_0000);
9370        build.store(minus, args[0], plain(), Flags::default());
9371        build.ret(&[]);
9372
9373        // `-1.5L`. The sign is the top bit of the two byte half, so the immediate that half is put
9374        // in a register with is above the signed range of sixteen bits and has to stay there: read
9375        // as a number it would be negative, and it is not a number, it is two bytes.
9376        let text = lower(&mut names, &source);
9377        assert!(text.contains("x64.mov_ri_16 49151"), "{text}");
9378    }
9379
9380    #[test]
9381    fn a_long_double_crosses_an_edge_as_an_address_and_is_copied_where_it_lands() {
9382        let (mut names, mut source, block, args) = blank(&[Type::float(rucc_ir::Float::F64)]);
9383        let wide = cast(&mut source, block, Opcode::FPExt, args[0], long_double());
9384        let next = source.create_block();
9385        let param = source.append_param(next, long_double());
9386        Builder::new(&mut source, block).jump(next, &[wide]);
9387        Builder::new(&mut source, next).ret(&[param]);
9388
9389        // What the edge carries is the address of the slot the value is already in, which is an
9390        // ordinary register the allocator has an opinion about. The block on the other side copies
9391        // the sixteen bytes into a slot of its own before anything reads them, so a second edge
9392        // handing over a second address would still leave one place for a reader to look.
9393        let text = lower(&mut names, &source);
9394        let second: Vec<&str> = text
9395            .lines()
9396            .skip_while(|line| !line.starts_with("block1"))
9397            .skip(1)
9398            .take(3)
9399            .map(str::trim)
9400            .collect();
9401        assert_eq!(
9402            second,
9403            ["x64.fld_t [%4]", "%5:gpr = x64.lea_64 [$rsp]", "x64.fstp_t [%5]"],
9404            "{text}"
9405        );
9406    }
9407
9408    #[test]
9409    fn more_long_doubles_at_a_block_than_the_stack_is_deep_are_reported() {
9410        let f64 = Type::float(rucc_ir::Float::F64);
9411        let (mut names, mut source, block, args) = blank(&[f64]);
9412        let wide = cast(&mut source, block, Opcode::FPExt, args[0], long_double());
9413        let next = source.create_block();
9414        let params: Vec<Value> =
9415            (0..=X87_DEPTH).map(|_| source.append_param(next, long_double())).collect();
9416        let carried: Vec<Value> = params.iter().map(|_| wide).collect();
9417        Builder::new(&mut source, block).jump(next, &carried);
9418        Builder::new(&mut source, next).ret(&[params[0]]);
9419
9420        // The copies go through the x87 stack so that every one of them is read before any of them
9421        // is written, which is what makes a block that swaps two of these right. Nine of them do
9422        // not fit on the stack, and copying the ninth before or after the rest is the order that
9423        // could be wrong, so it is refused instead.
9424        let failed = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
9425            .expect_err("nine do not fit on the stack");
9426        assert_eq!(
9427            failed.to_string(),
9428            "block1 takes 9 parameters of type `f80` and only 8 can cross an edge at once"
9429        );
9430        assert_eq!(failed.inst(), None);
9431    }
9432}