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