Skip to main content

rucc_codegen/
lower.rs

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