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::fmt;
79
80use rucc_base::hash::{Map, Set};
81use rucc_base::{Interner, Symbol};
82use rucc_diag::Span;
83use rucc_ir::{
84 Abi, AsmOperand, AsmOperands, AttrSet, Block, Def, Extra, Flags, FloatPred, Func, Inst,
85 Linkage, MemOrder, Opcode, Param, PrefetchHint, RmwOp, Type, Value, Visibility,
86};
87use rucc_mir as mir;
88use rucc_target::template::{template_name, template_reg};
89use rucc_target::{
90 Address, CallRegs, Constraint, Convention, OperandDesc, PhysReg, RegClass, Role, VaList,
91 Variadic,
92};
93use rucc_target::{aarch64, x86_64};
94
95use crate::abi::{self, Missing, Refused};
96use crate::coverage::Fired;
97use crate::elsewhere::{Elsewhere, Slot};
98use crate::frame::{Layout, Local};
99use crate::select::{Match, Piece, Pointer, Reach, Rule, Selector};
100use crate::term::{MAX_ARGS, PLAIN, Plan, Shown, Term, Terms};
101use crate::varargs;
102
103/// The instruction a template's `jmp` to a name outside it becomes.
104///
105/// The same instruction [`x86_64::FRAME`] names for the end of a tail call, named here as well
106/// because what reaches this one is a template in a function with no prologue and no epilogue,
107/// which is nothing to do with the frame.
108/// See [`x86_64::Step::Away`].
109const AWAY: &str = "jmp_away";
110
111/// How wide an address is on this target, which is the width a cast between a pointer and an
112/// integer has to be at for the cast to be nothing.
113const ADDRESS_BITS: u32 = 64;
114
115/// How much of a register an operand of an `asm` statement fills, which is the width of its type
116/// with two exceptions. A pointer is an address, and a truth value is the byte it is stored in: a
117/// program that writes `sete %0` into a `_Bool` is asking for exactly that byte, which is what tcc's
118/// own test of the width of one checks.
119fn held_bits(ty: Type) -> u32 {
120 if ty.is_ptr() {
121 ADDRESS_BITS
122 } else if ty.bits() == 1 {
123 8
124 } else {
125 ty.bits()
126 }
127}
128
129/// How many bytes a `long double` takes in memory, and what it is aligned to, which are the same
130/// number and are both more than the ten bytes that mean anything.
131///
132/// The psABI's answer rather than a choice here. `sizeof (long double)` is sixteen on this
133/// machine, so an array of them is laid out this way whatever a slot holding one does, and a slot
134/// that agreed with the array is one fewer thing to get wrong.
135const X87_BYTES: u32 = 16;
136
137/// How many values the x87 stack holds at once.
138///
139/// Eight, which is the machine's number rather than a choice here, and it matters in one place:
140/// the parameters of a block are copied through the stack so that they all move at once, and a
141/// block with more of them than this has nowhere to put the ninth.
142const X87_DEPTH: usize = 8;
143
144/// How far into the buffer of a `__builtin_setjmp` each of the four words it writes is.
145///
146/// The first three are gcc's, measured against gcc 16.2.0 on x86-64 at `-O0`: the frame pointer,
147/// the address control comes back to, and the stack pointer, in that order. The fourth is this
148/// compiler's own. gcc has no word for the answer because it writes a second block that sets the
149/// answer to one and is arrived at from the restore, and this writes the answer through memory
150/// instead, for the reason [`Lowering::saves_place`] gives.
151///
152/// None of the four is an interface. The buffer is the program's memory and its five words are
153/// the front end's promise about how much of it there is, but nothing except the matching restore
154/// ever reads a word of it, and a buffer written by one compiler was never going to be one another
155/// compiler could come back through.
156const JUMP_FRAME: i32 = 0;
157
158/// Where the address control comes back to is. See [`JUMP_FRAME`].
159const JUMP_PC: i32 = 8;
160
161/// Where the stack pointer is. See [`JUMP_FRAME`].
162const JUMP_STACK: i32 = 16;
163
164/// Where the address of the word the answer arrives in is. See [`JUMP_FRAME`].
165const JUMP_ANSWER: i32 = 24;
166
167/// How many bytes the word a `__builtin_setjmp` answers with takes in the frame, and what it is
168/// aligned to, which are the same number because it is one machine word.
169const JUMP_WORD: u32 = 8;
170
171/// How many registers the restore needs to hold things in while it puts the frame back.
172///
173/// Four, and every one of them is a register nothing else in the function may be in, which is why
174/// they are counted here rather than asked for one at a time. See [`Lowering::comes_back`].
175const JUMP_REGS: usize = 4;
176
177/// How many bytes the block `__builtin_apply_args` answers takes, which is a word for where the
178/// arguments in memory are, a word of nothing and then the register save area of a variadic
179/// function. See [`Lowering::save_arguments`].
180const APPLY_ARGS: u32 = 192;
181
182/// How far into that block the registers start, which is how far the save area has moved up.
183const APPLY_REGS: u32 = 16;
184
185/// How many bytes the block `__builtin_apply` answers takes, which is two words and two vectors.
186const APPLY_BACK: u32 = 48;
187
188/// How many bytes a value passes through on its way between a register and the x87 stack.
189///
190/// Eight, because the widest thing that crosses is a `double` or a sixty four bit integer, and
191/// nothing crosses at eighty bits: a value that wide is already in the frame and the stack reaches
192/// it where it is.
193const X87_CROSSING: u32 = 8;
194
195/// Where the rounding field of the x87 control word is and what it has to be set to for the unit
196/// to cut towards zero, which is the one rounding C asks for that the unit does not do by default.
197///
198/// Both bits on is truncate. The field is ORed into the word that was already there rather than
199/// written over it, so the precision control and the exception masks somebody else set stay set.
200const X87_TRUNCATE: i64 = 0x0c00;
201
202/// Whether a type is the one this machine has no register for.
203///
204/// Only the eighty bit float is, and that is a fact about x86-64 rather than about floats: every
205/// other scalar the front end produces is in a general purpose register or a vector one, and this
206/// one is on the x87 stack while it is being worked on and in memory the rest of the time. So it
207/// has no place in [`Lowering::class_of`] and no name in [`crate::term`], and every instruction
208/// that touches one is written out by hand in this file.
209fn on_x87(ty: Type) -> bool {
210 ty.is_scalar() && ty.is_float() && ty.bits() == 80
211}
212
213/// Where one operand of an assembly statement is, on each side of the assembly.
214///
215/// Two registers rather than one, because an operand written `+` is a value that arrives and a
216/// value that leaves and those are two values. The machine IR has one definition per register by
217/// construction, so an instruction of the template that reads the operand and writes it has to name
218/// a different register in each place, and what makes the two one register in the end is the
219/// [`Constraint::Reuse`] the instruction's description carries: the allocator reads it, gives both
220/// the same physical register, and copies the incoming value somewhere first when something else is
221/// still using it.
222///
223/// Most operands have one of the two. An input has only a place it is read from and an output
224/// written `=` has only a place it is written to, and asking either of them for the other is an
225/// operand read where the opcode writes or written where it reads, which [`Lowering::placed`]
226/// refuses.
227#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
228struct Place {
229 /// The register the value arrives in, for an operand something reads.
230 read: Option<mir::Reg>,
231 /// The register the value leaves in, for an operand something writes.
232 write: Option<mir::Reg>,
233}
234
235/// Whether that operand of the statement is one the assembly may read, and so where a read of it
236/// gets its value from.
237///
238/// [`bound`] asks this question of an operand a constraint letter named and this asks it of one the
239/// template numbered, which is the same question twice because a two-address instruction reaches
240/// its first source both ways. `mulq %3` reaches `rax` by the letter on the output and libgmp says
241/// what is in it with `"%0"` on an input. `addq %5,%q1` reaches its first source by numbering the
242/// output, and libgmp says what is in it with `"0"` on an input in the same way.
243///
244/// So an output written `=` has no value of its own and is still readable when an input is tied to
245/// it, and the value the read wants is that input's. An output written `+` carries its own value
246/// and answers with that. An output nothing is tied to answers `None`, which is a program that told
247/// the compiler the assembly only writes the operand while the instruction reads it before it
248/// writes it, and is refused where it is asked.
249fn read_as(list: &[AsmOperand<'_>], index: usize) -> Option<Value> {
250 let operand = list.get(index)?;
251 if operand.value.is_some() {
252 return operand.value;
253 }
254 operand.result?;
255 list.iter().find(|entry| entry.tied == Some(index)).and_then(|entry| entry.value)
256}
257
258/// Which of an assembly statement's operands is in that register, for an instruction that reaches
259/// the register without its text saying so.
260///
261/// The constraint is what says so, and it is the only thing in such a statement that could:
262/// `"=a"` is an output in `rax`, `"c"` is an input in `rcx`, an operand that is a local register
263/// variable is in the register its declaration named, and a register nothing names is a register
264/// nobody has said anything about. So a write looks among the outputs and a read among the inputs,
265/// and an output written `+` answers for either, since it is read before it is written. See
266/// [`pinned`], which is the one question asked of both ways of saying it.
267///
268/// The other way a read of such a register is said is a matching constraint. `"=a"` on an output
269/// and `"0"` on an input is the program saying that one register holds the input on the way in and
270/// the output on the way out, and it is how a statement fills a register the instruction reads and
271/// writes without writing the register down twice. The letter is on the output, which has no value
272/// to read, and the value is on the input, which has no letter, and the answer is the output: its
273/// place is read out of the register the input arrived in, and in a template with a loop in it the
274/// place moves on to wherever the last write left it, which is what a read on the next time round
275/// wants. tcc steps a pointer along a string with `lodsb` and `"=&S"` tied to `"0"`, and a read of
276/// the input would start the string again every time round.
277///
278/// And a read of a register an output alone is in is a read of that output, the same as a read of
279/// an output the template numbered. tcc copies a string with `lodsb` and `stosb` and `"=&a"` on an
280/// output nothing is tied to, and what `stosb` stores is what `lodsb` loaded one line up, which is
281/// the output as the template left it rather than anything the statement handed in.
282///
283/// `None` is a register the instruction uses and the statement put nothing in, which is the usual
284/// answer rather than an unusual one. `cpuid` writes four registers and a program that wanted one
285/// of them names one. See [`Lowering::spare`], which is where that one goes.
286fn bound(list: &[AsmOperand<'_>], reg: PhysReg, role: Role) -> Option<usize> {
287 let output =
288 list.iter().position(|operand| operand.result.is_some() && pinned(operand) == Some(reg));
289 if role.is_def() {
290 return output;
291 }
292 // The output first when something is in it on the way in, which is what `+` and a matching
293 // constraint both say, since its place is where a write earlier in the template left it and
294 // the read wants that. See [`read_as`] for what it holds before anything wrote it.
295 let arrives = |at: usize| read_as(list, at).is_some();
296 if let Some(at) = output.filter(|&at| arrives(at)) {
297 return Some(at);
298 }
299 let named = list.iter().position(|operand| {
300 operand.result.is_none() && operand.value.is_some() && pinned(operand) == Some(reg)
301 });
302 named.or(output)
303}
304
305/// The register one of an assembly statement's operands is in, whichever of the two ways said it.
306///
307/// A constraint letter is one way and is the only way a program can say one of the six registers
308/// that have a letter. A local register variable is the other, and it is the only way to say any
309/// of the rest: there is no letter for `r12`, which is the whole reason the extension exists, so
310/// the declaration says it and the front end wrote the name into the constraint. The name is read
311/// against this machine's table here, the same place the letter is read against it, and a name the
312/// machine has not got answers nothing, which leaves the operand where an operand nobody placed
313/// goes.
314///
315/// The sigil gcc allows in front of a name is taken off here, because what a name is written with
316/// is syntax and which register it means is this question.
317fn pinned(operand: &AsmOperand<'_>) -> Option<PhysReg> {
318 match operand.named {
319 Some(name) => {
320 let (reg, _) = x86_64::gpr_named(name.strip_prefix('%').unwrap_or(name))?;
321 Some(reg)
322 }
323 None => operand.fixed.and_then(x86_64::gpr_letter),
324 }
325}
326
327/// Whether a constraint says nothing but what it says on every machine.
328///
329/// [`AsmOperands::read`] gives the x86 meaning to every letter it knows, and most of the letters
330/// mean something else on AArch64: `Q` is an address in one register there rather than one of four
331/// registers, and `a` to `d` name nothing. So an AArch64 statement is taken only with the letters
332/// the two agree on, which are a register, a constant, memory, the immediate ranges and a matching
333/// number, and anything else is refused rather than read as x86. `w` and `Q` are the exceptions.
334/// `w` is a register on both, and which file it is in is decided by the caller with
335/// [`vector_letter`]. `Q` is read as `m` by the caller before the list is read. A
336/// register the front end named in braces is read against AArch64's own names, so what is inside
337/// them is not a letter.
338fn shared_letters(constraint: &str) -> bool {
339 let mut inside = false;
340 constraint.chars().all(|c| match c {
341 '{' => {
342 inside = true;
343 true
344 }
345 '}' => {
346 inside = false;
347 true
348 }
349 _ if inside => true,
350 _ => matches!(
351 c,
352 '=' | '+' | '&' | '%' | 'r' | 'w' | 'Q' | 'm' | 'o' | 'V' | 'g' | 'X' | 'i' | 'n'
353 | 'p' | 'I'..='N' | '0'..='9'
354 ),
355 })
356}
357
358/// A constraint list with every letter outside braces put through `swap`, and what is inside them,
359/// which is a register's name rather than letters, left alone.
360fn letters_outside(constraints: &str, swap: impl Fn(char) -> char) -> String {
361 let mut inside = false;
362 constraints
363 .chars()
364 .map(|c| {
365 match c {
366 '{' => inside = true,
367 '}' => inside = false,
368 _ if !inside => return swap(c),
369 _ => {}
370 }
371 c
372 })
373 .collect()
374}
375
376/// Whether an AArch64 constraint asks for a floating point or vector register, which is what `w`
377/// means there. A register named in braces is not a letter, so a `w` inside one is not read.
378fn vector_letter(constraint: &str) -> bool {
379 let mut inside = false;
380 constraint.chars().any(|c| {
381 match c {
382 '{' => inside = true,
383 '}' => inside = false,
384 _ => {}
385 }
386 !inside && c == 'w'
387 })
388}
389
390/// The x86-64 vector register one entry of a clobber list names, spelled `xmm0` or `ymm0` with or
391/// without the sigil, or nothing for any other entry. Only the sixteen there are without AVX-512,
392/// so `zmm0` and `xmm16` are still refused as names this has no register for.
393fn vector_named(entry: &str) -> Option<PhysReg> {
394 let entry = entry.trim().trim_matches('"');
395 let entry = entry.strip_prefix('%').unwrap_or(entry);
396 let number = entry.strip_prefix("xmm").or_else(|| entry.strip_prefix("ymm"))?;
397 if number.len() > 1 && number.starts_with('0') {
398 return None;
399 }
400 let number: u8 = number.parse().ok()?;
401 (number < 16).then(|| x86_64::xmm(number))
402}
403
404/// Whether a line of a template names, by number, an operand `wanted` says yes to.
405///
406/// `%%` is a percent sign rather than an operand, and a modifier letter may stand between the sign
407/// and the number.
408fn names_one(line: &str, wanted: impl Fn(usize) -> bool) -> bool {
409 let mut rest = line;
410 while let Some(at) = rest.find('%') {
411 let after = &rest[at + 1..];
412 if let Some(escaped) = after.strip_prefix('%') {
413 rest = escaped;
414 continue;
415 }
416 let after = after.strip_prefix(|c: char| c.is_ascii_alphabetic()).unwrap_or(after);
417 let digits = after.len() - after.trim_start_matches(|c: char| c.is_ascii_digit()).len();
418 if after[..digits].parse().is_ok_and(&wanted) {
419 return true;
420 }
421 rest = &after[digits..];
422 }
423 false
424}
425
426/// Why a function could not be lowered.
427///
428/// One reason and then nothing. A function with no rule for something in it is a function this
429/// cannot finish, and the second thing it could not lower is not news.
430#[derive(Debug, Clone, PartialEq, Eq)]
431pub enum Unsupported {
432 /// An instruction no rule fires on.
433 Inst {
434 /// The instruction that stopped it.
435 inst: Inst,
436 /// What the rule file would call it, or nothing if the rule language has no name for it
437 /// at all, which is what an instruction at a width nothing is written about looks like.
438 term: Option<&'static str>,
439 /// The opcode, which is what gets named when the rule language has no word for it.
440 ///
441 /// An opcode the rule language has no word for is exactly the opcode no rule lowers, so
442 /// without this the message would be empty in every case where somebody needs it.
443 opcode: Opcode,
444 /// What it produces, or nothing for an instruction that is only an effect.
445 ty: Option<Type>,
446 },
447 /// A parameter that does not arrive somewhere this can bring it in from.
448 ///
449 /// Not an instruction, which is why it is a separate arm: it is a fact about the signature
450 /// and there is nothing in the body of the function to point at.
451 Argument {
452 /// Its position in the signature.
453 index: usize,
454 /// What is wrong with where it arrives.
455 missing: Missing,
456 },
457 /// A call that passes or gives back a value this cannot put where the convention wants it.
458 Call {
459 /// The call.
460 inst: Inst,
461 /// Which value, and what is wrong with where it travels.
462 refused: Refused,
463 },
464 /// A `return` this cannot put where the convention wants it.
465 ///
466 /// A separate arm from [`Unsupported::Inst`] because it is not an instruction no rule fires
467 /// on. A return of more than one value is built from the convention rather than matched, the
468 /// same way a call is, so what goes wrong with one is what goes wrong with a call and not the
469 /// absence of a rule.
470 Returned {
471 /// The `return`.
472 inst: Inst,
473 /// What is wrong with where one of the values travels.
474 missing: Missing,
475 },
476 /// A stack slot the frame cannot give the bytes it asked for.
477 ///
478 /// Not an instruction no rule covers. An `alloca` is built here rather than matched, so what
479 /// goes wrong with one is what the frame can and cannot hold rather than what the rules spell.
480 Dynamic {
481 /// The `alloca`.
482 inst: Inst,
483 /// What the frame could not do about it.
484 growing: Growing,
485 },
486 /// More parameters of a type that travels on the x87 stack than the stack is deep.
487 ///
488 /// Not an instruction either, for the reason a function's parameter is not one: it is a fact
489 /// about the block and there is nothing in the block to point at. What crosses an edge for one
490 /// of these is the address of where the value is, and the block copies the bytes into a slot
491 /// of its own, all of them through the stack at once so that a block carrying two of them
492 /// swapped is copied in an order that is right. Eight is as many as the stack holds, and a
493 /// ninth would have to be copied before or after the rest, which is the order that could be
494 /// wrong.
495 Phi {
496 /// Which block it arrives at.
497 block: Block,
498 /// How many of them arrive there, which is the whole of what is wrong.
499 count: usize,
500 /// What they are.
501 ty: Type,
502 },
503 /// An `asm` statement this cannot build.
504 ///
505 /// Not an instruction no rule fires on, for the reason a call is not one: what it stands for is
506 /// whatever its template says, and no pattern over terms can read a string.
507 Assembly {
508 /// The `inline_asm`.
509 inst: Inst,
510 /// What about it is not built here yet.
511 refused: Written,
512 },
513 /// A `register long x asm ("...")` naming something this machine has not got.
514 ///
515 /// Not an instruction no rule fires on. There is a rule's worth of instruction here and what
516 /// is wrong is the string beside it, which is a name rather than a term, so the message says
517 /// the name. Which names a machine has is the machine's own question and this is where it is
518 /// asked, at the table a clobber list is read against.
519 Register {
520 /// The `register_value`.
521 inst: Inst,
522 /// The name the program wrote, as it wrote it.
523 name: String,
524 },
525 /// A naked function whose frame is not empty.
526 ///
527 /// Not an instruction no rule fires on, and there is nothing in the body to point at: the
528 /// function asked for no prologue and then wanted bytes only a prologue takes. Refused rather
529 /// than given the bytes anyway, because an offset into a frame nothing set up reaches into
530 /// whatever the caller left below its own stack pointer, which is wrong code that assembles.
531 /// See [`crate::frame::Layout::naked`].
532 Naked {
533 /// How many bytes it wanted, which is the whole of what is wrong.
534 bytes: u32,
535 },
536 /// Something the x86-64 lowering writes by hand and nothing has written for this machine yet.
537 ///
538 /// Refused rather than written with the x86 instructions, which is what the walk would do
539 /// otherwise, since these are the places it names them itself.
540 Unported {
541 /// The instruction, or nothing for the one that is about a signature.
542 inst: Option<Inst>,
543 /// Which of them.
544 what: Unported,
545 },
546}
547
548/// What [`Unsupported::Unported`] is about.
549#[derive(Debug, Clone, Copy, PartialEq, Eq)]
550pub enum Unported {
551 /// The thread pointer on Apple's platforms, which keep it somewhere other than Linux does.
552 Thread,
553 /// A call in a convention the platform has no registers for, which the front end never asks
554 /// for since it reads `ms_abi` and `sysv_abi` on x86-64 alone, and is refused rather than
555 /// made in the wrong one if something else ever does.
556 Convention,
557}
558
559impl Unported {
560 /// The whole message, since there is nothing to put in front of it.
561 #[must_use]
562 pub fn why(self) -> &'static str {
563 match self {
564 Unported::Thread => "the thread pointer is not written for this platform yet",
565 Unported::Convention => {
566 "this calls a function of a calling convention this platform does not have"
567 }
568 }
569 }
570}
571
572/// What about an `asm` statement is not built yet.
573#[derive(Debug, Clone, Copy, PartialEq, Eq)]
574pub enum Written {
575 /// A template with instructions in it.
576 Template,
577 /// An `asm goto`, whose labels make the statement a terminator.
578 Goto,
579 /// An operand this cannot put where the constraint says it goes.
580 Operand,
581 /// A clobber list naming something this has no register for.
582 Clobber,
583 /// A `jmp` out of the function in a function that has an epilogue behind it.
584 Away,
585}
586
587impl Written {
588 /// The rest of the sentence that starts with the statement.
589 #[must_use]
590 pub fn why(self) -> &'static str {
591 match self {
592 // The template is the assembler's to read and there is no assembler here yet, so a
593 // template with anything in it is a string nothing can turn into bytes. An empty one is
594 // no instructions, and no instructions is something this can write.
595 Written::Template => "has instructions in its template, which nothing here assembles",
596 Written::Goto => "jumps to a label, which nothing here builds an edge for",
597 Written::Operand => "has an operand this cannot place",
598 Written::Clobber => "says it destroys a register this has no name for",
599 Written::Away => {
600 "jumps out of the function, which only a function that is `naked` may do, since \
601 anywhere else there is an epilogue behind it to give the frame back"
602 }
603 }
604 }
605}
606
607/// What the frame could not do about a stack slot.
608#[derive(Debug, Clone, Copy, PartialEq, Eq)]
609pub enum Growing {
610 /// An object of a size the number a frame counts bytes in does not reach.
611 Huge,
612 /// A variable length array wanting more alignment than a call leaves the stack pointer with.
613 ///
614 /// Rounding the stack pointer down again after the bytes have been taken would put it
615 /// somewhere no constant reaches the rest of the frame from, so a frame like this needs a
616 /// second base register held for the whole of the function. Nothing here holds one.
617 ///
618 /// [`crate::expand::rounds`] takes the array away before this sees it, by asking for the
619 /// alignment in extra bytes and handing out an address inside them, so what is left of this
620 /// is IR that arrived without going through that pass and the fixed local in
621 /// [`crate::pipeline`] that wants the same thing from the other side.
622 Aligned,
623 /// A variable length array in a function written without a prologue.
624 ///
625 /// A frame that grows is reached from a frame pointer, and establishing one is the first two
626 /// instructions of a prologue that `__attribute__((naked))` asked there be none of. See
627 /// [`crate::frame::Layout::naked`].
628 Naked,
629}
630
631impl Growing {
632 /// The rest of the sentence that starts with the slot.
633 #[must_use]
634 pub fn why(self) -> &'static str {
635 match self {
636 Growing::Huge => "is more bytes than a frame counts",
637 Growing::Aligned => {
638 "wants more alignment than the stack pointer is left on, which needs a base \
639 register nothing here keeps"
640 }
641 Growing::Naked => {
642 "is in a function that is `naked`, which has no prologue to point a frame pointer \
643 at it with"
644 }
645 }
646 }
647}
648
649impl Unsupported {
650 /// The instruction it is about, or nothing for the one arm that is about a signature.
651 ///
652 /// What a caller wants this for is the span. The function knows where every instruction in
653 /// it came from, so a caller holding both can point a message at the line somebody wrote
654 /// rather than at the file as a whole, and nothing here has to carry a span of its own.
655 pub fn inst(&self) -> Option<Inst> {
656 match *self {
657 Unsupported::Inst { inst, .. }
658 | Unsupported::Call { inst, .. }
659 | Unsupported::Returned { inst, .. }
660 | Unsupported::Dynamic { inst, .. }
661 | Unsupported::Assembly { inst, .. }
662 | Unsupported::Register { inst, .. } => Some(inst),
663 Unsupported::Unported { inst, .. } => inst,
664 Unsupported::Argument { .. } | Unsupported::Phi { .. } | Unsupported::Naked { .. } => {
665 None
666 }
667 }
668 }
669}
670
671impl fmt::Display for Unsupported {
672 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
673 match *self {
674 Unsupported::Inst { term: Some(term), .. } => write!(f, "no rule lowers `{term}`"),
675 Unsupported::Inst { term: None, opcode, ty: Some(ty), .. } => {
676 write!(f, "no rule lowers a `{opcode}` producing a `{ty}`")
677 }
678 Unsupported::Inst { term: None, opcode, ty: None, .. } => {
679 write!(f, "no rule lowers a `{opcode}`")
680 }
681 Unsupported::Argument { index, missing } => {
682 write!(f, "parameter {index} {}", missing.why())
683 }
684 Unsupported::Call { refused: Refused { argument: Some(index), missing }, .. } => {
685 write!(f, "argument {index} of this call {}", missing.why())
686 }
687 Unsupported::Call { refused: Refused { argument: None, missing }, .. } => {
688 write!(f, "what this call gives back {}", missing.why())
689 }
690 Unsupported::Returned { missing, .. } => {
691 write!(f, "what this function gives back {}", missing.why())
692 }
693 Unsupported::Dynamic { growing, .. } => {
694 write!(f, "this local {}", growing.why())
695 }
696 Unsupported::Phi { block, count, ty } => {
697 let block = block.index();
698 write!(
699 f,
700 "block{block} takes {count} parameters of type `{ty}` and only {X87_DEPTH} can cross an edge at once"
701 )
702 }
703 Unsupported::Assembly { refused, .. } => write!(f, "this `asm` {}", refused.why()),
704 Unsupported::Unported { what, .. } => f.write_str(what.why()),
705 Unsupported::Register { ref name, .. } => {
706 write!(
707 f,
708 "this object is kept in `{name}`, which is not a register this machine has"
709 )
710 }
711 Unsupported::Naked { bytes } => write!(
712 f,
713 "this function is `naked` and wants {bytes} bytes of frame, which there is no prologue to take"
714 ),
715 }
716 }
717}
718
719impl std::error::Error for Unsupported {}
720
721/// A lowered function, and what the frame needs that the machine IR does not hold.
722#[derive(Debug)]
723pub struct Lowered {
724 /// The function, in machine instructions.
725 pub func: mir::Func,
726 /// What it wants its stack to look like, which is separate from the function so that the two
727 /// can be read and written at the same time.
728 pub stack: Stack,
729 /// Which rules of the table lowered it, which is what `-Zrule-coverage` asks for and what
730 /// `crate::coverage` writes down.
731 pub fired: Fired,
732 /// Which machine IR block each IR block became, indexed by the IR block's own index, and
733 /// nothing for a block the walk never reached.
734 ///
735 /// Here because it is the only place the correspondence exists. Selection makes one block per
736 /// block, in the same order and with the arms in the same order, so anything the IR knows
737 /// about a block can be carried down through this and nothing else, and
738 /// [`crate::weights::carry`] is what does.
739 pub blocks: Vec<Option<mir::Block>>,
740}
741
742/// What a function's stack has to hold, as far as selection is able to say.
743///
744/// All of it is answered here because selection is where a call is built and where an `alloca`
745/// is read, and nothing after it could tell what either of them needed.
746#[derive(Debug, Default)]
747pub struct Stack {
748 /// How many bytes the widest call in the function needs below the stack pointer for the
749 /// arguments it passes there, or `None` for a function that makes no call at all.
750 ///
751 /// `None` is a leaf, which is the function that may use the red zone and the one whose stack
752 /// pointer does not have to be left aligned for anybody.
753 pub calls: Option<u32>,
754 /// The memory the function asked for itself, one entry for every `alloca` in it, in the order
755 /// the walk reached them.
756 pub locals: Vec<Local>,
757 /// Which instruction computes the address of which of those locals.
758 ///
759 /// An address in the frame is a distance from the stack pointer, and there is no frame until
760 /// after allocation, so the instruction is written here with nothing in its displacement and
761 /// [`crate::finish`] writes the number in once [`crate::frame::Frame`] knows it.
762 pub addresses: Vec<(mir::Inst, usize)>,
763 /// Which of those locals is which declaration in the source, for the ones the program declared.
764 ///
765 /// The number is the one the IR function carries and means nothing here. What it is for is the
766 /// debugging information, which has to say where a named local ended up and cannot ask the
767 /// frame directly: the frame knows a local by the order the `alloca` for it was lowered in and
768 /// by nothing else.
769 ///
770 /// Shorter than the list above rather than the same length, because most of what a function
771 /// keeps in its frame is memory an expression wanted somewhere to put.
772 pub declared: Vec<(usize, u32)>,
773 /// Which instruction computes the address of a piece of memory whose size the function works
774 /// out while it runs, which is what a variable length array is.
775 ///
776 /// Waiting on [`crate::finish`] for a different number from the one the addresses above are:
777 /// the bytes were taken off the stack pointer by the instruction in front of this one, so where
778 /// they start is however much of the bottom of the frame belongs to the arguments of a call,
779 /// and that is not known until the frame is.
780 pub dynamic: Vec<mir::Inst>,
781 /// Which instruction takes those bytes off the stack pointer, one for every one of them, in the
782 /// order the walk reached them.
783 ///
784 /// Read by [`crate::finish`] on a command line that asked for the stack to be touched a page at
785 /// a time, which is the one thing that has to find these again: the bytes are in a register by
786 /// then, so the walk down to them is a loop, and a loop is written around an instruction rather
787 /// than in front of a block. Nothing else looks at them, because everything else about a frame
788 /// that grows is answered by the address the instruction below this one computes.
789 pub grown: Vec<mir::Inst>,
790 /// Where the function first moves the stack pointer while it runs, if it does at all.
791 ///
792 /// Two things are read off this. One is whether at all, which is what [`crate::frame::Layout`]
793 /// wants, because a frame that moves its stack pointer has a different shape from one that does
794 /// not and the layout is built before the instructions are looked at again. See `Growing` in
795 /// [`crate::frame`]. The other is where, so that a caller that cannot accept such a frame has
796 /// somewhere to point when it says so.
797 pub grown_at: Option<Inst>,
798 /// Which instruction reads which of the arguments the caller passed on the stack, as how far up
799 /// the caller's argument area it reads.
800 ///
801 /// Waiting on [`crate::finish`] for the same reason the addresses above are, and on one thing
802 /// more: where the caller's argument area is from inside this function depends on whether the
803 /// prologue had to force the stack pointer's alignment, so which register the load reads
804 /// through is not settled here either.
805 pub arguments: Vec<(mir::Inst, u32)>,
806 /// Whether the function asked where its own frame is, which is what `__builtin_frame_address`
807 /// and `__builtin_return_address` both start from.
808 ///
809 /// A function like that keeps a frame pointer whatever the flags say, because the register is
810 /// the answer to the first of them and the start of the walk for every depth above zero. There
811 /// is no other way to reach it: the distance from the stack pointer to the frame is a number
812 /// the layout works out, and what a walk up the chain needs is the link the prologue saved.
813 pub walks_frames: bool,
814 /// Whether the function saved a place for a `__builtin_longjmp` to come back to, which is what
815 /// `__builtin_setjmp` does.
816 ///
817 /// A function like that keeps a frame pointer whatever the flags say as well, and for a reason
818 /// of the same shape: the two registers the restore puts back are the frame pointer and the
819 /// stack pointer, and a frame that did not keep the first of them has nothing in it saying
820 /// where the caller's frame is for the epilogue to find after control has come back.
821 pub saves_place: bool,
822 /// The calls a `tail_call` became that [`crate::tail::jumps`] may turn into a jump, which is
823 /// the ones that passed everything in registers.
824 pub tails: Vec<crate::tail::Tail>,
825 /// How many bytes the prologue takes above the frame record to home the argument registers
826 /// into, which is nothing except in a variadic function on Windows on AArch64.
827 ///
828 /// That convention has no shadow space the caller reserves, so the callee makes its own: the
829 /// first thing its prologue does is take sixty four bytes, which puts `x0` to `x7` directly
830 /// below the arguments the caller left on the stack and makes the whole run one list of words
831 /// a `char *` can walk. See `home` on [`rucc_target::CallRegs`].
832 pub home: u32,
833}
834
835impl Stack {
836 /// The layout given, with the three fields only the lowering knows the answer to filled in.
837 ///
838 /// Everything else in a layout comes from the flags the function is compiled under or from the
839 /// allocation, so this takes one and returns it rather than building one.
840 ///
841 /// A function that saved a place is not a leaf whatever it called. What a leaf buys is the red
842 /// zone, which is the words below the stack pointer nothing else may write, and a function
843 /// control comes back into from a `__builtin_longjmp` has already had something else running
844 /// down there: whatever it called and whatever that called, or a signal handler on the same
845 /// stack. Every one of those has written over the red zone by the time control arrives, so a
846 /// value this function left there would not be there any more.
847 #[must_use]
848 pub fn layout<'a>(&'a self, base: Layout<'a>) -> Layout<'a> {
849 Layout {
850 leaf: self.calls.is_none() && !self.saves_place,
851 outgoing: self.calls.unwrap_or(0),
852 locals: &self.locals,
853 grows: self.grown_at.is_some(),
854 home: self.home,
855 ..base
856 }
857 }
858}
859
860/// The machine IR for that function, for the machine the selector describes.
861///
862/// # Errors
863///
864/// The first instruction no rule fires on, which today is anything at a width the rule set is not
865/// written at, a parameter that does not arrive in a register this can read, or a call that
866/// passes something this cannot put where the convention wants it.
867pub fn func(
868 source: &Func,
869 names: &mut Interner,
870 selector: &'static Selector,
871 conv: &'static CallRegs,
872 elsewhere: &Elsewhere,
873) -> Result<Lowered, Unsupported> {
874 func_for(source, names, selector, conv, elsewhere, true)
875}
876
877/// [`func`], for a build that says whether it writes debugging information. Without it the walk
878/// leaves out which value each declaration holds on the way into each block, since that is read
879/// only for the debugging information.
880///
881/// # Errors
882///
883/// The same as [`func`].
884pub fn func_for(
885 source: &Func,
886 names: &mut Interner,
887 selector: &'static Selector,
888 conv: &'static CallRegs,
889 elsewhere: &Elsewhere,
890 debug: bool,
891) -> Result<Lowered, Unsupported> {
892 Lowering::new(source, names, selector, conv, elsewhere, debug).run()
893}
894
895/// What the matcher settled on for one block, indexed the way the block's instructions are.
896struct Decided {
897 /// What each instruction matched, and nothing for one that matched no rule or was folded
898 /// into a later one.
899 found: Vec<Option<Match<Term>>>,
900 /// How each instruction showed its operands to the matcher, which is what says what it took.
901 plans: Vec<Option<Plan>>,
902 /// The instructions some other instruction took, which are the ones with nothing to write.
903 folded: Vec<Inst>,
904}
905
906/// The instruction in front of an assignment that starts a declaration on a value, and the first
907/// machine instruction after it once the block is filled.
908type Mark = (Option<Inst>, Option<mir::Inst>);
909
910/// One function being lowered.
911struct Lowering<'a> {
912 source: &'a Func,
913 names: &'a mut Interner,
914 out: mir::Func,
915 /// The machine register each IR value is in, once it has one.
916 regs: Vec<Option<mir::Reg>>,
917 /// For a constant or an address that has been written into a register, the block it was
918 /// written into, which is the only block that register is any good in, and how many calls had
919 /// been lowered by then. An address written before a call is not read after it: see
920 /// [`Rebuilt::Name`].
921 written: Vec<Option<(mir::Block, u32)>>,
922 /// How many calls have been lowered so far, which is what [`Self::written`] counts with.
923 crossed: u32,
924 /// How many times each IR value is read, which is what says whether an instruction may be
925 /// folded into the one that reads it.
926 uses: Vec<u32>,
927 /// The block being filled.
928 at: Option<mir::Block>,
929 /// The machine IR block each IR block became.
930 blocks: Vec<Option<mir::Block>>,
931 /// The class an address is in, which is the general purpose one and is not a question: every
932 /// register an addressing mode names holds part of an address, and there is no machine here
933 /// that computes an address anywhere but in this file. Which class a *value* is in is
934 /// [`Lowering::class_of`], and it is a question, because a float is in the other one.
935 gpr: RegClass,
936 /// The machine this selects for.
937 selector: &'static Selector,
938 /// Where the convention this function is compiled for puts things, which is read for the
939 /// arguments and for the calls.
940 conv: &'static CallRegs,
941 /// Which names this function may not work an address out for itself, which is a fact about the
942 /// module and so is worked out before any of this and handed in.
943 elsewhere: &'a Elsewhere,
944 /// Whether the build writes debugging information, which is the one thing that reads which
945 /// value a declaration holds on the way into each block.
946 debug: bool,
947 /// What the function wants its stack to look like, filled in as the walk finds out.
948 stack: Stack,
949 /// What a `va_start` in this function has to write, or nothing for a function that takes no
950 /// arguments its signature does not name.
951 ///
952 /// Worked out once, when the entry block binds the parameters, because every number in it is
953 /// about where those parameters left the walk over the argument registers and there is nowhere
954 /// else that knows.
955 varargs: Option<Varargs>,
956 /// Which of the function's stack objects each eighty bit value lives in, once it has asked
957 /// for one.
958 ///
959 /// One slot per value and it is never given back, which is what makes an eighty bit value
960 /// behave like every other one: it is written once and read wherever it is read, and no two
961 /// of them share a slot the way two of them would share a register. What is in a register is
962 /// the address, and that is worked out again at every use rather than kept, so nothing here
963 /// holds a general purpose register open across a whole function.
964 slots: Vec<Option<usize>>,
965 /// The eight bytes a value passes through between a register and the x87 stack, once
966 /// something has wanted them.
967 ///
968 /// One for the whole function, because every group that uses it is a handful of instructions
969 /// with nothing in between: the bytes are written, read straight back and never looked at
970 /// again, so a second slot would be a second slot holding the same nothing.
971 crossing: Option<usize>,
972 /// The four bytes the control word is saved in and the changed copy written to, once
973 /// something has wanted them.
974 ///
975 /// One for the whole function for the reason above, and four rather than two because it is
976 /// two words: the one the unit had and the one with the rounding field turned to truncate.
977 control: Option<usize>,
978 /// The word a `__builtin_setjmp` in this function answers with, once one has asked for it.
979 ///
980 /// One for the whole function however many saves there are in it, because the word is written
981 /// and read back with nothing in between: the save writes a zero into it and the instruction
982 /// straight after reads it, and the only other thing that ever writes it is a restore arriving
983 /// between those two. Two saves sharing it is two pairs each doing that, and neither can be
984 /// inside the other.
985 answer: Option<usize>,
986 /// The block `__builtin_apply_args` answers the address of, or nothing in a function that holds
987 /// none.
988 ///
989 /// Written once, in the prologue, because what it holds is every argument register as it was
990 /// on the way in, and by the time the walk reaches the call the registers hold whatever the
991 /// function has done since. Every `__builtin_apply_args` in the function answers the same one.
992 applied: Option<usize>,
993 /// Which rules have fired so far.
994 fired: Fired,
995 /// Where each assignment that starts a declaration on a value part of the way through is, by
996 /// the IR block it is in and the instruction in front of it, and which machine instruction
997 /// is the first one after it once the block has been filled. See
998 /// [`rucc_ir::Func::declare_value_from`].
999 marks: Map<Block, Vec<Mark>>,
1000 /// The frame slot each fixed size `alloca` was given, which is what every reader of its
1001 /// address writes the address of. See [`Self::local`].
1002 frame_slots: Map<Value, usize>,
1003 /// The machine call each IR call with an unwind edge became, which [`Self::edges`] pairs with
1004 /// the pad the edge went to. See [`rucc_ir::Opcode::Unwound`].
1005 unwinding: Map<Inst, mir::Inst>,
1006 /// The machine opcode each head a rule builds is and the operands it has, by where the head's
1007 /// name is in the rule table. See [`Self::head`].
1008 heads: Map<(usize, usize), (mir::Opcode, &'static [OperandDesc])>,
1009}
1010
1011/// What a `va_start` in a variadic function writes into the list it is given.
1012///
1013/// Two shapes, because two conventions describe a list two ways, and [`crate::varargs`] is where
1014/// both are written down. Neither is a set of numbers on its own: where the save area is and where
1015/// the caller's argument area is are distances into a frame that does not exist until after
1016/// allocation, so each is a `lea` [`crate::finish`] fills in.
1017#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1018enum Varargs {
1019 /// The four field list, whose two offsets are settled here and whose two addresses are not.
1020 Fields {
1021 /// Which of the function's stack objects is the register save area.
1022 save: usize,
1023 /// How far up the caller's argument area the first argument the signature does not name is,
1024 /// which is the whole of that area the named ones did not take.
1025 incoming: u32,
1026 /// What `gp_offset` starts at, which is past the general purpose registers the named
1027 /// arguments took.
1028 integers: u32,
1029 /// What `fp_offset` starts at, which is past the vector ones.
1030 floats: u32,
1031 },
1032 /// The AAPCS64 list, whose two offsets count up to zero from the top of each half of the save
1033 /// area. The two tops are addresses in the frame and so is the first field, like the SysV list.
1034 Aapcs {
1035 /// Which of the function's stack objects is the register save area.
1036 save: usize,
1037 /// How far up the caller's argument area the first argument the signature does not name is.
1038 incoming: u32,
1039 /// Where the general purpose half of the save area ends.
1040 integers_end: u32,
1041 /// Where the vector half ends, which is the end of the area.
1042 floats_end: u32,
1043 /// What `__gr_offs` starts at, which is minus the general purpose half the named arguments
1044 /// did not take.
1045 integers: i32,
1046 /// What `__vr_offs` starts at.
1047 floats: i32,
1048 },
1049 /// The list that is a pointer, which is the one address and nothing else.
1050 Pointer {
1051 /// How far up the caller's argument area the first argument the signature does not name is,
1052 /// which on this convention is the word belonging to the position the named ones stopped
1053 /// at.
1054 incoming: u32,
1055 },
1056}
1057
1058/// How far a function's name reaches, narrowed from the linkage the IR gave it.
1059///
1060/// The IR has five and an object file says three, and the two the linker cannot tell apart are
1061/// the two weak ones: which of them a symbol had is a fact the optimizer reads and the linker has
1062/// no way to record. A function is never `Common`, since that is what a tentative definition of an
1063/// object is and there is no tentative definition of a function, and it is written here rather
1064/// than left out so that a linkage added later has to come past this.
1065const fn binding(linkage: Linkage) -> mir::Binding {
1066 match linkage {
1067 Linkage::Internal => mir::Binding::Local,
1068 Linkage::Weak | Linkage::LinkOnce => mir::Binding::Weak,
1069 Linkage::External | Linkage::Common => mir::Binding::Global,
1070 }
1071}
1072
1073/// How far a function's name reaches outside a shared library, carried across unchanged.
1074///
1075/// Nothing is narrowed here the way [`binding`] narrows the linkage, because ELF records all
1076/// three of these and the two enumerations are the same three answers written twice: once in a
1077/// crate that is not allowed to know what an object file is and once in one that is.
1078const fn visibility(visibility: Visibility) -> mir::Visibility {
1079 match visibility {
1080 Visibility::Default => mir::Visibility::Default,
1081 Visibility::Hidden => mir::Visibility::Hidden,
1082 Visibility::Protected => mir::Visibility::Protected,
1083 }
1084}
1085
1086impl<'a> Lowering<'a> {
1087 fn new(
1088 source: &'a Func,
1089 names: &'a mut Interner,
1090 selector: &'static Selector,
1091 conv: &'static CallRegs,
1092 elsewhere: &'a Elsewhere,
1093 debug: bool,
1094 ) -> Self {
1095 let counts = source.counts();
1096 let name = source.name;
1097 let mut uses = vec![0; counts.values];
1098 for block in source.blocks() {
1099 for inst in source.insts(block) {
1100 for &arg in &source[source[inst].args] {
1101 uses[arg.index()] += 1;
1102 }
1103 for call in source.successors(inst) {
1104 for &arg in &source[call.args] {
1105 uses[arg.index()] += 1;
1106 }
1107 }
1108 }
1109 }
1110 let mut out = mir::Func::new(name);
1111 out.align = source.align;
1112 // Carried rather than worked out here, because where a function was declared is a fact
1113 // about the source and this is a long way past it. What wants it is the line table.
1114 out.declared = source.declared;
1115 out.binding = binding(source.linkage);
1116 out.visibility = visibility(source.visibility);
1117 Self {
1118 source,
1119 names,
1120 out,
1121 regs: vec![None; counts.values],
1122 written: vec![None; counts.values],
1123 crossed: 0,
1124 blocks: vec![None; counts.blocks],
1125 uses,
1126 at: None,
1127 gpr: selector.gpr,
1128 selector,
1129 conv,
1130 elsewhere,
1131 debug,
1132 stack: Stack::default(),
1133 varargs: None,
1134 slots: vec![None; counts.values],
1135 crossing: None,
1136 control: None,
1137 answer: None,
1138 applied: None,
1139 fired: Fired::new(),
1140 marks: Map::default(),
1141 frame_slots: Map::default(),
1142 unwinding: Map::default(),
1143 heads: Map::default(),
1144 }
1145 }
1146
1147 fn run(mut self) -> Result<Lowered, Unsupported> {
1148 for value in self.source.values() {
1149 for start in self.source.value_starts(value) {
1150 let Some((block, after)) = self.source.start_place(start) else { continue };
1151 let marks = self.marks.entry(block).or_default();
1152 if !marks.iter().any(|&(have, _)| have == after) {
1153 marks.push((after, None));
1154 }
1155 }
1156 }
1157 // Every block before any of them is filled, because a block that jumps forward has to
1158 // name the block it jumps to and a machine IR block is named by a handle rather than by
1159 // the IR block it came from.
1160 for block in self.source.blocks() {
1161 let out = self.out.create_block();
1162 self.blocks[block.index()] = Some(out);
1163 }
1164 for block in self.order() {
1165 self.block(block)?;
1166 }
1167 // And the name each block an image holds the address of was given, which nothing in the
1168 // walk above would ask for: the `lea` a label address is inside the function needs no
1169 // symbol, and the one thing that does is a relocation in another section.
1170 let named: Vec<(Block, Symbol)> = self.source.named_blocks().collect();
1171 let labels: Vec<(mir::Block, Symbol)> =
1172 named.into_iter().map(|(block, name)| (self.out_block(block), name)).collect();
1173 self.out.labels = labels;
1174 self.naming();
1175 Ok(Lowered { func: self.out, stack: self.stack, fired: self.fired, blocks: self.blocks })
1176 }
1177
1178 /// Which register each declaration the front end kept in a value ended up in, as far as this
1179 /// walk can say, which is the other half of what [`Lowering::new_reg`] writes down as it goes.
1180 ///
1181 /// Two halves because there are two ways a value gets a register here. Most of them ask for a
1182 /// fresh one and that is where `new_reg` catches them, and the rest are put in a register
1183 /// something else chose: a parameter arrives in whichever one the convention handed it, a block
1184 /// parameter in whichever one the edge agreed on, and a result of a rule that names its own
1185 /// registers in the one the rule named. None of those goes past the mint, so this is the map at
1186 /// the end read off the other side, and the two together are every value a declaration is
1187 /// behind.
1188 ///
1189 /// The map on its own would not do, which is why `new_reg` writes down what it writes down: the
1190 /// entry for a constant is cleared every time the walk leaves the block that wrote it, so a
1191 /// local a constant holds is in the map for one block of the function and nowhere else.
1192 fn naming(&mut self) {
1193 let mut named = std::mem::take(&mut self.out.named);
1194 for value in self.source.values() {
1195 let Some(reg) = self.regs[value.index()] else { continue };
1196 named.extend(self.source.value_decls(value).map(|decl| (decl, reg)));
1197 // A start in a block a pass took out was never reached above, and it says nothing
1198 // rather than something about another place.
1199 for start in self.source.value_starts(value) {
1200 let Some((block, after)) = self.source.start_place(start) else { continue };
1201 let first = self.marks.get(&block).and_then(|marks| {
1202 marks.iter().find(|&&(have, _)| have == after).and_then(|&(_, at)| at)
1203 });
1204 if let Some(first) = first {
1205 self.out.starts.push((start.decl, reg, first));
1206 }
1207 }
1208 }
1209 named.sort_unstable();
1210 named.dedup();
1211 self.out.named = named;
1212 self.out.starts.sort_unstable();
1213 self.out.starts.dedup();
1214 // Which of its values a declaration holds on the way into a block, for the blocks where
1215 // two of them are live at once. A block a pass took out says nothing, and neither does a
1216 // value the map above has lost the register of, since that is not the same as having none.
1217 // Only for a build that writes debugging information, since that is all that reads it,
1218 // and on a function of tens of thousands of blocks it is a walk of all of them for every
1219 // local.
1220 let mut entries = Vec::new();
1221 let held = if self.debug { crate::holding::on_entry(self.source) } else { Vec::new() };
1222 for (decl, block, value) in held {
1223 if let (Some(block), Some(reg)) = (self.blocks[block.index()], self.regs[value.index()])
1224 {
1225 entries.push((decl, block, reg));
1226 }
1227 }
1228 entries.sort_unstable();
1229 entries.dedup();
1230 self.out.entries = entries;
1231 }
1232
1233 /// The order the blocks are filled in, which is not the order they are written in.
1234 ///
1235 /// Reverse postorder, because a value is written in a block that dominates every block that
1236 /// reads it and a block in reverse postorder comes before every block it dominates. The order
1237 /// the blocks are written in does not have that property: a block written early can read a
1238 /// value a block below it writes, and reading a value with no register yet mints one, so the
1239 /// register the definition writes later is not the register the read named. Nothing writes the
1240 /// one the read named, and what comes out is a function that loads a stack slot no store ever
1241 /// reached. It is the order this walk goes in rather than the order the blocks come out in,
1242 /// which is what the loop above fixes, so the machine function is still written the way the IR
1243 /// function was.
1244 ///
1245 /// Blocks the entry does not reach come last, in the order they are written in. Nothing runs
1246 /// them and nothing they name is read by anything that does, but they still have to be filled,
1247 /// because a machine block with no terminator is not one the passes below can read.
1248 fn order(&self) -> Vec<Block> {
1249 let Some(entry) = self.source.entry() else { return self.source.blocks().collect() };
1250 let count = self.blocks.len();
1251 let mut succs: Vec<Vec<Block>> = vec![Vec::new(); count];
1252 for block in self.source.blocks() {
1253 let Some(term) = self.source.terminator(block) else { continue };
1254 succs[block.index()] = self.source.successors(term).map(|call| call.block).collect();
1255 }
1256 // An explicit stack, because the depth of the walk is the number of blocks and a function
1257 // built by a generator has as many of those as it likes.
1258 let mut seen = vec![false; count];
1259 let mut order = Vec::with_capacity(count);
1260 let mut stack = vec![(entry, 0usize)];
1261 seen[entry.index()] = true;
1262 while let Some((block, at)) = stack.pop() {
1263 let Some(&next) = succs[block.index()].get(at) else {
1264 order.push(block);
1265 continue;
1266 };
1267 stack.push((block, at + 1));
1268 if !seen[next.index()] {
1269 seen[next.index()] = true;
1270 stack.push((next, 0));
1271 }
1272 }
1273 order.reverse();
1274 order.extend(self.source.blocks().filter(|block| !seen[block.index()]));
1275 order
1276 }
1277
1278 /// One block: its parameters, then every instruction in it that is not folded into another.
1279 fn block(&mut self, block: Block) -> Result<(), Unsupported> {
1280 let out = self.out_block(block);
1281 self.at = Some(out);
1282 if self.source.entry() == Some(block) {
1283 self.arrive(block, out)?;
1284 } else {
1285 let mut arriving = Vec::new();
1286 for ¶m in &self.source[block].params {
1287 // A value with no register to arrive in, which the class would not say, since
1288 // `class_of` puts one of these in the general purpose file on purpose and what it
1289 // means by that is that nothing there can hold it. What crosses the edge for one
1290 // of those is the address of where the value already is, so the parameter is a
1291 // pointer here and the bytes it points at are copied below.
1292 let ty = self.source[param].ty;
1293 let reg = self.out.append_param(out, self.class_of(ty));
1294 self.sized(reg, ty);
1295 self.regs[param.index()] = Some(reg);
1296 if on_x87(ty) {
1297 arriving.push((param, reg));
1298 }
1299 }
1300 self.settle(block, &arriving)?;
1301 }
1302 let kept = self.pad(block)?;
1303
1304 // What each instruction matched, and which instructions were folded into another. The
1305 // decision is made for the whole block before any of it is written, and it is made more
1306 // than once: a value that only some of its readers took has to be put back in a register
1307 // for all of them, and taking it away from those readers changes what they match.
1308 let insts: Vec<Inst> = self.source.insts(block).collect();
1309 let mut refused: Set<Value> = Set::default();
1310 let mut decided = self.decide(&insts, &refused);
1311 while let Some(value) = self.left_alive(&insts, &decided.plans) {
1312 refused.insert(value);
1313 decided = self.decide(&insts, &refused);
1314 }
1315 let Decided { found, folded, .. } = decided;
1316
1317 // Where each assignment in this block that starts a declaration on a value is, as the
1318 // machine instruction in front of the place its IR instruction left off, or the block
1319 // for one where nothing has been written yet. What comes after it is not known until the
1320 // block is filled, so that is read below.
1321 let wanted: Set<Option<Inst>> =
1322 self.marks.get(&block).into_iter().flatten().map(|&(after, _)| after).collect();
1323 let mut reached: Vec<(Option<Inst>, mir::Block, Option<mir::Inst>)> = Vec::new();
1324 for (index, (&inst, matched)) in insts.iter().zip(found).enumerate() {
1325 let before = index.checked_sub(1).map(|index| insts[index]);
1326 if wanted.contains(&before) {
1327 let at = self.at.unwrap_or(out);
1328 reached.push((before, at, self.out.terminator(at)));
1329 }
1330 if folded.contains(&inst) || self.writes_nothing(inst) {
1331 continue;
1332 }
1333 // A call is built from the convention rather than matched, which is why it is the one
1334 // opcode looked at by name here. Through an address it is a different instruction and
1335 // the same convention, so the two arrive at the same place and differ in one line of
1336 // it.
1337 match self.source[inst].opcode {
1338 Opcode::Call | Opcode::CallIndirect => {
1339 self.called(inst)?;
1340 continue;
1341 }
1342 // The exception a landing pad was entered with, which the unwinder left in the
1343 // first return register. Built by name for the reason a named register is.
1344 Opcode::Landing => {
1345 self.landing(inst)?;
1346 continue;
1347 }
1348 // A call and the return behind it, which is what `crate::tail::mark` made it out
1349 // of, and both are built the way they would have been. What makes it a jump is
1350 // written at the very end, once the epilogue is there to jump from.
1351 Opcode::TailCall => {
1352 self.tail_called(inst)?;
1353 continue;
1354 }
1355 // Built from the frame rather than matched, for the same shape of reason a call
1356 // is built from the convention: what a rule replaces a term with is instructions,
1357 // and what an `alloca` needs first is bytes, which the rule language has no way
1358 // to ask for.
1359 Opcode::Alloca => {
1360 self.reserve(inst)?;
1361 continue;
1362 }
1363 // Reading the stack pointer and writing it back, which are the two ends of a scope
1364 // holding a variable length array. Built here for the reason an `alloca` is: the
1365 // value is a register the rule language has no way to name, because what it holds
1366 // is not a value the program computed but where the machine's stack had got to.
1367 // The arguments the function was handed, saved in the prologue, and a call made
1368 // out of them. Built here because neither is a value a rule could say anything
1369 // about: the first is a place in the frame and the second is a call, whose
1370 // arguments are a block of registers rather than values.
1371 Opcode::ApplyArgs => {
1372 self.apply_args(inst)?;
1373 continue;
1374 }
1375 Opcode::Apply => {
1376 self.apply(inst)?;
1377 continue;
1378 }
1379 Opcode::StackSave => {
1380 self.stack_pointer(inst, false)?;
1381 continue;
1382 }
1383 Opcode::StackRestore => {
1384 self.stack_pointer(inst, true)?;
1385 continue;
1386 }
1387 // The address of a name, built here for the same reason an `alloca` is: what a
1388 // rule replaces a term with is instructions over values, and the operand of this
1389 // one is a symbol, which is a thing the rule language has no way to bind and the
1390 // solver has no way to say anything about. There is nothing in `lea sym(%rip)` a
1391 // proof over bitvectors could discharge, because what makes it the right answer
1392 // is the relocation and what the linker does with it.
1393 //
1394 // Only a thread-local variable is built where the IR put it. Every other name's
1395 // address is written again in each block that reads it, by [`Self::reg_of`], so
1396 // here it is nothing. See [`Rebuilt`].
1397 Opcode::GlobalAddr => {
1398 let result = self.source[inst].first_result;
1399 if result.is_none_or(|result| self.rebuilt(result).is_none()) {
1400 self.address_of(inst)?;
1401 }
1402 continue;
1403 }
1404 // The address of a label and the branch that reads one, built here for the same
1405 // reason and for one more. The reason is the same: what the first of them names is
1406 // a block, which is not a value a rule pattern can bind, and there is nothing in
1407 // the distance between two places in one function that a proof over bitvectors
1408 // could discharge. The extra one is that the second is a terminator whose arms are
1409 // not two and not fixed, and a rule says what an instruction reads rather than
1410 // where a block goes.
1411 Opcode::BlockAddr => {
1412 self.block_address(inst)?;
1413 continue;
1414 }
1415 Opcode::IndirectBr => {
1416 self.indirect_branch(inst)?;
1417 continue;
1418 }
1419 // A `switch` that `crate::switch` found dense enough for a table, which is a load
1420 // out of the table and the same jump. Built here for the reasons the jump above
1421 // is, and because what the load reads is a place in this function.
1422 Opcode::Switch => {
1423 self.jump_table(inst)?;
1424 continue;
1425 }
1426 // The pair that saves a place in this function and comes back to it. Built here
1427 // for the reason the address of a label is, and for two more. The reason is the
1428 // same: the first of them writes down where control comes back to, which is a
1429 // place in this function and not a value a rule pattern can bind. The extra ones
1430 // are that each of them is a group of instructions over a buffer the program owns
1431 // rather than one instruction, and that the first of them leaves the block it was
1432 // written in and carries on in a new one, which is a thing no rule can do.
1433 Opcode::SetjmpMarker => {
1434 self.saves_place(inst)?;
1435 continue;
1436 }
1437 Opcode::LongjmpMarker => {
1438 self.comes_back(inst)?;
1439 continue;
1440 }
1441 // Where this thread's own storage starts, built here for a reason of the same
1442 // shape: what it reads is `%fs`, which is not a register the rule language can
1443 // bind and not one a proof over bitvectors could say anything about, because what
1444 // makes the load the right answer is an agreement between the loader and the C
1445 // library rather than any arithmetic.
1446 Opcode::ThreadPointer => {
1447 self.thread_pointer(inst)?;
1448 continue;
1449 }
1450 // Where the stack pointer was on entry, built here because it is an address in
1451 // the caller's argument area, which only the frame knows the distance to.
1452 Opcode::SpEntry => {
1453 self.sp_entry(inst)?;
1454 continue;
1455 }
1456 // What a named machine register holds, built here for the reason above written
1457 // about any register rather than about one: which register it is is a string
1458 // beside the instruction, and a rule matches on an opcode and a type and could
1459 // not see it. There is nothing to prove either, since the answer is the register
1460 // and the instruction is the move that reads it.
1461 Opcode::RegisterValue => {
1462 self.register_value(inst)?;
1463 continue;
1464 }
1465 // Where a frame is and what it returns to, built here for the same reason and one
1466 // more. The reason is the same: what the walk starts from is the frame pointer,
1467 // which is not a register a rule pattern can bind, and there is nothing in reading
1468 // the link the prologue saved that a proof over bitvectors could discharge. The
1469 // extra one is that how long the walk is comes out of a number beside the
1470 // instruction, so one of these is not one instruction but however many the depth
1471 // says, and a rule replaces a term with a term.
1472 Opcode::FrameAddress | Opcode::ReturnAddress => {
1473 self.frames(inst)?;
1474 continue;
1475 }
1476 // Built from the frame for the reason an `alloca` is, and from the convention for
1477 // the reason a call is: three of the four fields it writes are distances that do
1478 // not exist until the frame does, and the fourth is where the walk over the
1479 // argument registers stopped. A function that is not variadic has no such walk to
1480 // report, so it has nothing here and is refused below, which is the right answer
1481 // for a `va_start` in one.
1482 Opcode::VaStart if self.varargs.is_some() => {
1483 self.va_start(inst)?;
1484 continue;
1485 }
1486 // A return of more than one value, which is a structure small enough to come
1487 // back in a pair of registers. Built from the convention for the reason a call
1488 // is: which register each half goes in depends on the halves in front of it,
1489 // because the two register files are walked separately, and a pattern over a term
1490 // cannot see them. A return of one value is a term with a name and a rule, and it
1491 // stays one.
1492 //
1493 // A return of none in a function whose answer went through memory is here too,
1494 // and for a different reason: what it gives back is not written in the IR at all.
1495 // The convention says the address the caller handed over comes back, and only the
1496 // signature says this function was handed one.
1497 //
1498 // And a return of one eighty bit value, for a third reason: what a rule would
1499 // write is an instruction leaving the value in a register, and this one is left on
1500 // the x87 stack instead. A rule could not name that stack any more than any other
1501 // rule about this type could.
1502 //
1503 // And a return the convention asks this side to extend, which a rule has no way to
1504 // know about since the signature is what says so and not the value.
1505 Opcode::Return
1506 if self.source[self.source[inst].args].len() > 1
1507 || self.sret().is_some()
1508 || self.gives_back_x87(inst)
1509 || self.widens_return() =>
1510 {
1511 let values = self.source[self.source[inst].args].to_vec();
1512 self.returned(inst, values)?;
1513 continue;
1514 }
1515 // A cast between a pointer and an integer of the same width, which on this
1516 // machine is every one the front end writes. No instruction at all, so no rule
1517 // could name one.
1518 Opcode::PtrToInt | Opcode::IntToPtr => {
1519 self.rename(inst)?;
1520 continue;
1521 }
1522 // A barrier, which is one instruction or none depending on the ordering. Written
1523 // by name because there is nothing about it a rule could be proved against, the
1524 // way there is nothing to prove about the address of a symbol.
1525 Opcode::Fence => {
1526 self.barrier(inst)?;
1527 continue;
1528 }
1529 // An ordered load or store that `crate::expand::orderings` left alone, which on a
1530 // machine that is not total store order is every one stronger than relaxed. Written
1531 // by name for the barrier's reason: what it adds to the plain access is an ordering.
1532 Opcode::AtomicLoad | Opcode::AtomicStore if self.on_aarch64() => {
1533 self.ordered(inst)?;
1534 continue;
1535 }
1536 // A hint, written by name for the reason a barrier is and one step further: not
1537 // only is there no equality for a proof to discharge, there is nothing about the
1538 // program around it either. Which of the four instructions it is comes out of the
1539 // number the builtin was given, which is beside the instruction rather than in it.
1540 Opcode::Prefetch => {
1541 self.hint(inst)?;
1542 continue;
1543 }
1544 // Stopping, written by name for the first half of the barrier's reason: it
1545 // computes nothing, so there is no term for a rule to replace, and what makes it
1546 // right is what the operating system does with the fault rather than anything a
1547 // proof over bitvectors could discharge.
1548 Opcode::Trap => {
1549 self.trap(inst);
1550 continue;
1551 }
1552 // A compare and exchange, which is written by name because it produces two values
1553 // and a rule produces one. The replacement of a rule is one term, a term names the
1554 // value an instruction computes, and there is no way in that language to say that
1555 // an instruction leaves an answer in one place and a yes or no in another.
1556 Opcode::Cmpxchg => {
1557 self.exchange(inst)?;
1558 continue;
1559 }
1560 // A read modify write, which is written by name for a different reason: it produces
1561 // one value, so a rule could name it, and what it does is not in the head a rule
1562 // matches on. Every one of the thirteen operations is the same opcode at the same
1563 // type and differs only in what is carried beside it, so one pattern would be all
1564 // thirteen patterns. Of the thirteen only the three with an instruction reach here,
1565 // since `crate::retry` turned the rest into loops a long way above this.
1566 Opcode::AtomicRmw => {
1567 self.modify(inst)?;
1568 continue;
1569 }
1570 // An `asm` statement, whose lowering is its template and there is no term for a
1571 // string. Written by name for the reason a barrier is, and before the x87 arm
1572 // below so that an `asm` holding a `long double` is refused as the `asm` it is
1573 // rather than as an instruction nothing computes.
1574 Opcode::InlineAsm => {
1575 // The template is read as x86 assembly, and that reader is the only one there
1576 // is. AArch64 keeps every template as text, and any other machine's `asm` is
1577 // refused here rather than read as the wrong language.
1578 if self.on_aarch64() {
1579 self.spelled(inst)?;
1580 continue;
1581 }
1582 if !std::ptr::eq(self.selector.shapes, &x86_64::MACHINE) {
1583 return Err(self.unsupported(inst));
1584 }
1585 if self.touches_x87(inst) {
1586 self.x87_assembly(inst)?;
1587 continue;
1588 }
1589 self.assembly(inst)?;
1590 continue;
1591 }
1592 // Anything at all with an eighty bit float in it, which is the one arm here
1593 // chosen by a type rather than by an opcode, because what makes these different
1594 // is not what they do but where the value is. A `long double` has no register,
1595 // so it has no name in `crate::term` and no rule could bind one: every one of
1596 // these is a group of instructions over a frame slot, written out below.
1597 //
1598 // Last of the arms, so that a call and a return with one of these in them reach
1599 // the convention first and are refused by it, which is the truer answer: what is
1600 // wrong there is where the value has to travel and not that nothing can compute
1601 // it.
1602 _ if self.touches_x87(inst) => {
1603 self.x87(inst)?;
1604 continue;
1605 }
1606 _ => {}
1607 }
1608 let matched = matched.ok_or_else(|| self.unsupported(inst))?;
1609 self.emit(inst, &matched)?;
1610 // After it is built rather than when it matched, so that what is recorded is the rules
1611 // this function was lowered by and not the rules something was tried with.
1612 self.fired.mark(matched.rule);
1613 }
1614 // Whichever block the walk ended in rather than the one it started in. The two are the
1615 // same block for every function that does not save a place for a `__builtin_longjmp`, and
1616 // where they differ it is the last of them that the terminator and the arms belong to.
1617 // See [`Self::saves_place`].
1618 let last = self.at.expect("a block is being filled");
1619 self.edges(block, last)?;
1620 for (value, reg) in kept {
1621 self.regs[value.index()] = reg;
1622 }
1623 // Now that the block is filled, the instruction after each place an assignment was is the
1624 // first one it holds its value at. One with nothing after it, which a block ending in the
1625 // assignment would be, stays unanswered.
1626 if let Some(marks) = self.marks.get_mut(&block) {
1627 for &(before, at, last) in &reached {
1628 let first = match last {
1629 Some(last) => self.out.next_inst(last),
1630 None => self.out.insts(at).next(),
1631 };
1632 for mark in marks.iter_mut().filter(|(after, _)| *after == before) {
1633 mark.1 = first;
1634 }
1635 }
1636 }
1637 Ok(())
1638 }
1639
1640 /// One call, which is built from the convention rather than matched against the table for the
1641 /// same reason the arguments of the function itself are.
1642 ///
1643 /// The arguments are read before the call is built, which is what materializes a constant
1644 /// argument into a register, since no call passes an immediate.
1645 ///
1646 /// A call to a name and a call through an address are both here, and what tells them apart is
1647 /// the opcode rather than whether a callee was recorded, which is the same thing the verifier
1648 /// reads. Through an address the first operand is the address and the arguments are the ones
1649 /// behind it, and everything after that is the same: where each argument goes, where the value
1650 /// comes back and which registers are gone across it are the convention's answers and the
1651 /// convention does not ask what is being called.
1652 fn called(&mut self, inst: Inst) -> Result<u32, Unsupported> {
1653 let data = &self.source[inst];
1654 let Extra::Call(info) = data.extra else { return Err(self.unsupported(inst)) };
1655 let info = self.source[info];
1656 let indirect = data.opcode == Opcode::CallIndirect;
1657
1658 let values: Vec<Value> = self.source[data.args].to_vec();
1659 let callee = if indirect {
1660 let &address = values.first().ok_or_else(|| self.unsupported(inst))?;
1661 abi::Callee::Through(self.reg_of(address)?)
1662 } else {
1663 let symbol = info.callee.ok_or_else(|| self.unsupported(inst))?;
1664 // A function a declaration said is in a DLL is called through the pointer the loader
1665 // fills in, which is what gcc writes at `-O0`: the pointer into a register and a call
1666 // through the register. gcc at `-O2` and clang call through the pointer in memory,
1667 // which is one instruction shorter and the same call.
1668 match self.elsewhere.slot(symbol) {
1669 Some(slot) => {
1670 let reg = self.out.new_vreg(self.gpr);
1671 self.through_slot(inst, slot, symbol, reg)?;
1672 abi::Callee::Through(reg)
1673 }
1674 None => abi::Callee::Named(symbol),
1675 }
1676 };
1677
1678 // What the ABI asks of each argument, read out before any of them is, because reading one
1679 // borrows the function this is a table in. The ones the signature names are the signature's
1680 // answer and the ones behind them are the call's, which is where a structure passed to a
1681 // variadic callee by value says that its bytes travel: there is no parameter to say it on.
1682 let signature = &self.source[info.signature];
1683 let variadic = signature.variadic;
1684 let named: Vec<Abi> = signature.params.iter().map(|param| param.abi).collect();
1685 let beyond: Vec<Abi> = self.source[info.varargs].to_vec();
1686 // Every value that comes back and not only the first. A structure small enough to travel
1687 // in registers comes back in up to two of them, and which register each half is in is the
1688 // convention's answer, which is why the whole list goes to the same place the arguments do
1689 // rather than to a rule.
1690 let returns: Vec<Type> = signature.return_types().collect();
1691
1692 let mut args = Vec::with_capacity(values.len());
1693 // The address each argument that is one was just written by, which goes down to where it
1694 // is passed once the call is built. See [`Self::passed_late`].
1695 let mut late = Vec::new();
1696 let here = self.at.expect("a block is being filled");
1697 for (index, value) in values.into_iter().skip(usize::from(indirect)).enumerate() {
1698 let abi = named.get(index).or_else(|| beyond.get(index - named.len()));
1699 let abi = abi.copied().unwrap_or_default();
1700 let ty = self.source[value].ty;
1701 // What travels for an eighty bit value is its bytes, so what the call is handed is
1702 // where they are rather than a register they are in, and there is no register they
1703 // could be in. Everything else about it is a sixteen byte object passed by value and
1704 // is built by the same code.
1705 let reg = if abi::on_the_stack(ty) {
1706 self.x87_slot(value)
1707 } else {
1708 let before = self.out.terminator(here);
1709 let reg = self.reg_of(value)?;
1710 let written = self.out.terminator(here);
1711 if matches!(self.rebuilt(value), Some(Rebuilt::Local(_) | Rebuilt::Name(_)))
1712 && written != before
1713 {
1714 late.extend(written);
1715 }
1716 reg
1717 };
1718 args.push(abi::Passing { ty, reg, abi });
1719 }
1720 let block = self.at.expect("a block is being filled");
1721 let what = abi::Calling {
1722 callee,
1723 args: &args,
1724 returns: &returns,
1725 variadic,
1726 named: named.len(),
1727 at: self.source.span(inst),
1728 };
1729 // The callee's convention and not this function's, since the two differ when either was
1730 // written `ms_abi` or `sysv_abi`: where the arguments go, what the callee leaves alone and
1731 // how much room it is owed above the return address are all the callee's to say, and a
1732 // function of one convention calls functions of the other.
1733 let called = self.source[info.signature].convention;
1734 let conv = self
1735 .conv
1736 .under(called)
1737 .ok_or(Unsupported::Unported { inst: Some(inst), what: Unported::Convention })?;
1738 let made = abi::call(&mut self.out, block, &what, conv, self.selector.abi, self.names)
1739 .map_err(|refused| Unsupported::Call { inst, refused })?;
1740 self.crossed += 1;
1741 self.passed_late(&late);
1742 if self.source.unwinds_to_pad(inst) {
1743 let call = self.out.insts(block).last().expect("the call just built");
1744 self.unwinding.insert(inst, call);
1745 }
1746 let calls = &mut self.stack.calls;
1747 *calls = Some(calls.unwrap_or(0).max(made.outgoing));
1748 // An eighty bit value came back on the x87 stack, and the one thing that has to happen
1749 // before anything else touches that stack is taking it off. So the `fstp` goes here, in
1750 // front of everything the block does next, and after it the value is in its slot and is
1751 // read the way every other one is. A complex one is two of them, the real half on top, so
1752 // taking them off in order leaves each in its own slot and the stack empty.
1753 let results: Vec<Value> = self.source[inst].results().collect();
1754 let types: Vec<Type> = results.iter().map(|&result| self.source[result].ty).collect();
1755 if abi::back_on_x87(&types) {
1756 let span = self.source.span(inst);
1757 for result in results {
1758 let into = self.x87_slot(result);
1759 let into = self.through(into);
1760 self.x87_at("fstp_t", span, into);
1761 }
1762 return Ok(made.outgoing);
1763 }
1764 for (result, ®) in results.into_iter().zip(&made.results) {
1765 self.sized(reg, self.source[result].ty);
1766 self.regs[result.index()] = Some(reg);
1767 }
1768 Ok(made.outgoing)
1769 }
1770
1771 /// One `tail_call`, as the call and a return of what it gave back.
1772 ///
1773 /// The call is written down for [`crate::tail::jumps`] when it can be made after the frame is
1774 /// gone. That is when it put nothing in the argument area, which is the bottom of this frame,
1775 /// and when the answer comes back in registers, since one on the x87 stack is taken off and put
1776 /// back by instructions after the call. A call that is not written down stays a call and a
1777 /// return, which is what the IR said before `crate::tail::mark` read it.
1778 fn tail_called(&mut self, inst: Inst) -> Result<(), Unsupported> {
1779 let outgoing = self.called(inst)?;
1780 let block = self.at.expect("a block is being filled");
1781 let call = self.out.insts(block).last().expect("the call just built");
1782 let values: Vec<Value> = self.source[inst].results().collect();
1783 let x87 = self.x87_values(&values);
1784 self.returned(inst, values)?;
1785 if outgoing == 0 && !x87 && self.sret().is_none() {
1786 let returns = self.out.insts(block).skip_while(|&at| at != call).skip(1).collect();
1787 self.stack.tails.push(crate::tail::Tail { call, returns });
1788 }
1789 Ok(())
1790 }
1791
1792 /// The pointer a function returning through memory was handed, or nothing in a function that
1793 /// was not.
1794 ///
1795 /// It is the first parameter and the signature is what says so, since in the IR it is an
1796 /// ordinary pointer and reads like one everywhere in the body. A function with a signature
1797 /// like that and no entry block has nothing to give back and no body to give it back from.
1798 fn sret(&self) -> Option<Value> {
1799 let first = self.source.signature().params.first()?;
1800 if !matches!(first.abi, Abi::Sret { .. }) {
1801 return None;
1802 }
1803 self.source[self.source.entry()?].params.first().copied()
1804 }
1805
1806 /// One `return` the convention has to write, as the place each value has to be in by the end.
1807 ///
1808 /// One pseudo per value, each a read constrained to a return register, which is what a return
1809 /// of one value already is and is the whole of what either does. The `ret` itself comes from
1810 /// the epilogue for both, long after this, because the frame has to be given back first.
1811 ///
1812 /// The two register files are counted separately, so a structure of a `double` and a `long`
1813 /// leaves the `double` in the first vector register and the `long` in the first integer one
1814 /// rather than in the second of either. That is the same walk `rucc_codegen::abi` makes on
1815 /// the other side of the call, which is what makes the two ends agree.
1816 ///
1817 /// A function whose answer went through memory gives back the address it was handed, in front
1818 /// of nothing else, because a signature that returns that way returns nothing else. That the
1819 /// caller already knows the address is not enough: it is allowed to read the register instead,
1820 /// and a caller that does gets whatever the allocator last left there. In a leaf function that
1821 /// is usually the right answer by accident, and one call in the body is enough to make it a
1822 /// wild pointer, which is why this is written rather than left to luck.
1823 ///
1824 /// Where everything goes is worked out before anything is written, so a return this cannot
1825 /// make leaves no half of one behind.
1826 /// Whether a value this function gives back has to be extended first, which is Apple's arm64
1827 /// asking the callee to fill the 32 bits above a `char` or a `short` by its sign.
1828 fn widens_return(&self) -> bool {
1829 let returns = &self.source.signature().returns;
1830 returns.iter().any(|it| (self.selector.abi.extend)(it.ty, it.abi).is_some())
1831 }
1832
1833 /// Whether what a `return` gives back goes back on the x87 stack, per [`abi::back_on_x87`].
1834 fn gives_back_x87(&self, inst: Inst) -> bool {
1835 self.x87_values(&self.source[self.source[inst].args])
1836 }
1837
1838 /// Whether those values go back on the x87 stack, per [`abi::back_on_x87`].
1839 fn x87_values(&self, values: &[Value]) -> bool {
1840 let types: Vec<Type> = values.iter().map(|&value| self.source[value].ty).collect();
1841 abi::back_on_x87(&types)
1842 }
1843
1844 fn returned(&mut self, inst: Inst, values: Vec<Value>) -> Result<(), Unsupported> {
1845 let (mut ints, mut floats) = (0usize, 0usize);
1846 let mut parts = Vec::with_capacity(values.len() + 1);
1847 // An eighty bit value goes back on the x87 stack, which is where the convention says it is
1848 // and is the one place a value is left rather than put in a register. So the whole of the
1849 // return is an `fld` of its slot, and the stack it leaves the value on is not empty at the
1850 // `ret`, which is the one time in this file that is true and is what the convention asks
1851 // for. What comes after is the epilogue, which gives the frame back and touches nothing in
1852 // the unit. A complex one loads its imaginary half first so that the real half ends up on
1853 // top of it, in `st(0)`, with the imaginary half under it in `st(1)`.
1854 if self.x87_values(&values) && self.sret().is_none() {
1855 let span = self.source.span(inst);
1856 for &value in values.iter().rev() {
1857 let from = self.x87_slot(value);
1858 let from = self.through(from);
1859 self.x87_at("fld_t", span, from);
1860 }
1861 return Ok(());
1862 }
1863 // What the signature says about the bits above a narrow one, which on an ABI that extends
1864 // it is an obligation of this side: the caller reads the whole of the 32 bit register.
1865 let asked: Vec<Abi> = self.source.signature().returns.iter().map(|it| it.abi).collect();
1866 let asked = asked.into_iter().chain(std::iter::repeat(Abi::Plain));
1867 let sret = self.sret().map(|value| (value, Abi::Plain));
1868 for (value, abi) in sret.into_iter().chain(values.into_iter().zip(asked)) {
1869 let ty = self.source[value].ty;
1870 let at = if crate::term::in_vector_file(ty) { &mut floats } else { &mut ints };
1871 // Why it cannot come back, and not only that it cannot. A type that travels nowhere
1872 // says so itself, and a type that travels perfectly well ran out of registers.
1873 let missing = abi::refuses(ty, self.selector.abi).unwrap_or(Missing::NoRoom);
1874 let name =
1875 (self.selector.abi.ret)(ty, *at).ok_or(Unsupported::Returned { inst, missing })?;
1876 *at += 1;
1877 // The register is the target's answer and not one worked out here, the same as it is
1878 // for a return of one value, so that both halves of a pair and every rule that writes
1879 // half of one are reading the same table.
1880 let opcode =
1881 name.strip_prefix(self.selector.prefix()).ok_or_else(|| self.unsupported(inst))?;
1882 let descs = self.selector.operands(opcode).ok_or_else(|| self.unsupported(inst))?;
1883 let [desc] = descs else { return Err(self.unsupported(inst)) };
1884 let widen = (self.selector.abi.extend)(ty, abi).map(|name| self.names.intern(name));
1885 parts.push((self.names.intern(name), self.reg_of(value)?, *desc, widen));
1886 }
1887
1888 let block = self.at.expect("a block is being filled");
1889 let span = self.source.span(inst);
1890 for (opcode, mut reg, desc, widen) in parts {
1891 if let Some(widen) = widen {
1892 let wide = self.out.new_vreg(desc.class);
1893 let build = self.out.build(block, mir::Opcode::new(widen)).at(span);
1894 build.def(wide, desc.class).uses(reg, desc.class).finish();
1895 reg = wide;
1896 }
1897 let operand = mir::Operand {
1898 reg,
1899 class: desc.class,
1900 role: desc.role,
1901 constraint: desc.constraint,
1902 };
1903 self.out.build(block, mir::Opcode::new(opcode)).at(span).operand(operand).finish();
1904 }
1905 Ok(())
1906 }
1907
1908 /// One `alloca`: the bytes it asks for go on the list the frame is laid out from, and the
1909 /// address of them is one instruction wherever it is read.
1910 ///
1911 /// Nothing is written where the `alloca` stands. The address is a `lea` off the stack pointer,
1912 /// which is the one register that reaches the frame in every function, and [`Self::reg_of`]
1913 /// writes one in front of each instruction that reads it, the way it writes a constant. See
1914 /// [`Rebuilt`] for why that and not one register for the whole function.
1915 ///
1916 /// There is deliberately no rule for `alloca` and no name for one in [`crate::term`], and
1917 /// that is what stops it being folded into something else. An operand shown as the
1918 /// instruction that computed it is offered to the matcher by its name, so an `alloca` with no
1919 /// name is one no pattern can reach past, and the address it computes is always in a register
1920 /// by the time anything reads it.
1921 fn reserve(&mut self, inst: Inst) -> Result<(), Unsupported> {
1922 let data = &self.source[inst];
1923 // A variable length array carries the size it wants as an operand rather than in the
1924 // instruction, which is the whole of what tells the two apart here.
1925 if let Some(&size) = self.source[data.args].first() {
1926 return self.grow(inst, size);
1927 }
1928 self.local(inst).map(|_| ())
1929 }
1930
1931 /// Which of the function's locals a fixed size `alloca` is, putting it on the list the frame
1932 /// is laid out from the first time it is asked.
1933 ///
1934 /// Asked by the `alloca` itself and by every reader of its address, and whichever of them
1935 /// comes first is the one that makes the entry. The `alloca` always does, since it dominates
1936 /// what reads it and the blocks are filled in an order that puts a dominator first.
1937 fn local(&mut self, inst: Inst) -> Result<usize, Unsupported> {
1938 let data = &self.source[inst];
1939 let result = data.first_result.ok_or_else(|| self.unsupported(inst))?;
1940 if let Some(&index) = self.frame_slots.get(&result) {
1941 return Ok(index);
1942 }
1943 let Extra::Mem(mem) = data.extra else { return Err(self.unsupported(inst)) };
1944 let info = self.source[mem];
1945 let size = u32::try_from(info.size)
1946 .map_err(|_| Unsupported::Dynamic { inst, growing: Growing::Huge })?;
1947
1948 // At least one, because the frame divides by the alignment and an object with no
1949 // alignment at all is one the front end had nothing to say about rather than one that may
1950 // go anywhere.
1951 let index = self.stack.locals.len();
1952 self.stack.locals.push(Local { size, align: info.align.max(1) });
1953 if let Some(decl) = self.source.mem_decl(mem) {
1954 self.stack.declared.push((index, decl));
1955 }
1956 self.frame_slots.insert(result, index);
1957 Ok(index)
1958 }
1959
1960 /// The address of a fixed size `alloca`, written into the block being filled.
1961 ///
1962 /// Its displacement is left at nothing because there is no frame yet. Which instruction is
1963 /// waiting for which local is remembered, and [`crate::finish`] fills the number in after
1964 /// [`crate::frame::Frame`] has placed it.
1965 fn local_address(&mut self, inst: Inst, value: Value) -> Result<mir::Reg, Unsupported> {
1966 let index = self.local(inst)?;
1967 let block = self.at.expect("a block is being filled");
1968 // Cleared first so that the register is a new one rather than the one an earlier reader
1969 // was handed, which that reader may still be reading.
1970 self.regs[value.index()] = None;
1971 let reg = self.new_reg(value);
1972 let span = self.source.span(inst);
1973 let lea = self.named(self.selector.frame.lea);
1974 let sp = mir::Operand::read(mir::Reg::physical(self.conv.stack_pointer), self.gpr);
1975 let made =
1976 self.out.build(block, lea).at(span).def(reg, self.gpr).mem(mir::Mem::at(sp)).finish();
1977 self.stack.addresses.push((made, index));
1978 Ok(reg)
1979 }
1980
1981 /// The other kind of `alloca`: one whose size the function does not know until it runs, which
1982 /// is what a variable length array is.
1983 ///
1984 /// Nothing about it is a slot the frame laid out, because the frame is laid out once and this
1985 /// happens as often as control reaches the declaration. The bytes come off the stack pointer
1986 /// where the declaration stands, which is two instructions:
1987 ///
1988 /// ```text
1989 /// sub sp, bytes the stack pointer moves down over the memory, which is what takes it
1990 /// lea reg, [sp+n] where the memory starts, which is above the outgoing argument area
1991 /// ```
1992 ///
1993 /// The displacement is left at nothing for the reason the constant kind leaves its own at
1994 /// nothing, and for a different number: that area belongs to the arguments of whatever this
1995 /// function calls, it stays at the bottom of the frame wherever the bottom has moved to, and
1996 /// how big it is is not known until every call in the function has been seen.
1997 ///
1998 /// The bytes are already a multiple of the stack pointer's alignment by the time they arrive,
1999 /// because [`crate::expand::rounds`] rounded them up in the IR, so nothing here has to mask the
2000 /// stack pointer afterwards and the stack pointer stays somewhere a call can be made from.
2001 ///
2002 /// Two instructions here and not always two in the finished function. On a command line that
2003 /// asked for the stack to be touched a page at a time, the subtraction becomes a loop that
2004 /// walks the same distance a page at a time, which [`crate::finish`] writes. That is why the
2005 /// instruction is written down in [`Stack::grown`] as well as left where it is.
2006 ///
2007 /// An array wanting more alignment than the convention leaves the stack pointer with does not
2008 /// reach here asking for it: [`crate::expand::rounds`] gives it the alignment in extra bytes
2009 /// and turns the array into a `ptr_add` of the offset that lands inside them, so what arrives
2010 /// is a block asking for the convention's alignment like any other. The refusal below is what
2011 /// answers IR that came from somewhere other than that pass, since forcing the alignment here
2012 /// would be a second rounding of a register the frame already rounded, and after it no
2013 /// constant reaches the rest of the frame from anywhere. See `Growing` in [`crate::frame`].
2014 fn grow(&mut self, inst: Inst, size: Value) -> Result<(), Unsupported> {
2015 let data = &self.source[inst];
2016 let Extra::Mem(mem) = data.extra else { return Err(self.unsupported(inst)) };
2017 let info = self.source[mem];
2018 if info.align > self.conv.stack_align {
2019 return Err(Unsupported::Dynamic { inst, growing: Growing::Aligned });
2020 }
2021 let result = data.first_result.ok_or_else(|| self.unsupported(inst))?;
2022 let bytes = self.reg_of(size)?;
2023
2024 let block = self.at.expect("a block is being filled");
2025 let span = self.source.span(inst);
2026 let stack = mir::Reg::physical(self.conv.stack_pointer);
2027 let grow = self.named(self.selector.frame.grow);
2028 let took = self
2029 .out
2030 .build(block, grow)
2031 .at(span)
2032 .operand(mir::Operand::write(stack, self.gpr))
2033 .operand(mir::Operand::read(stack, self.gpr))
2034 .operand(mir::Operand::read(bytes, self.gpr))
2035 .finish();
2036 self.stack.grown.push(took);
2037
2038 let reg = self.new_reg(result);
2039 let lea = self.named(self.selector.frame.lea);
2040 let sp = mir::Operand::read(stack, self.gpr);
2041 let made =
2042 self.out.build(block, lea).at(span).def(reg, self.gpr).mem(mir::Mem::at(sp)).finish();
2043 self.stack.dynamic.push(made);
2044 self.stack.grown_at.get_or_insert(inst);
2045 Ok(())
2046 }
2047
2048 /// Where the stack pointer is, kept so that something later can put it back.
2049 ///
2050 /// One move out of the stack pointer and one move into it, which is the whole of what the two
2051 /// halves are. What makes them worth writing is where the front end puts them: a scope holding
2052 /// a variable length array saves the stack pointer as it opens and puts it back as it closes,
2053 /// so a loop declaring one takes its bytes once round rather than once per iteration, and a
2054 /// jump out of the scope gives the bytes back on the way out.
2055 ///
2056 /// The value travels in an ordinary register the allocator hands out, so it may be spilled like
2057 /// any other, and a spill slot in a frame that grows is reached through the frame pointer,
2058 /// which is exactly the register that still means something after the stack pointer has moved.
2059 fn stack_pointer(&mut self, inst: Inst, into: bool) -> Result<(), Unsupported> {
2060 let data = &self.source[inst];
2061 let block = self.at.expect("a block is being filled");
2062 let span = self.source.span(inst);
2063 let stack = mir::Reg::physical(self.conv.stack_pointer);
2064 let mov =
2065 self.selector.frame.moves(self.gpr).expect("a class the target says how to move").mov;
2066 let mov = self.named(mov);
2067 let (write, read) = if into {
2068 let &saved = self.source[data.args].first().ok_or_else(|| self.unsupported(inst))?;
2069 (stack, self.reg_of(saved)?)
2070 } else {
2071 let result = data.first_result.ok_or_else(|| self.unsupported(inst))?;
2072 (self.new_reg(result), stack)
2073 };
2074 self.out
2075 .build(block, mov)
2076 .at(span)
2077 .operand(mir::Operand::write(write, self.gpr))
2078 .operand(mir::Operand::read(read, self.gpr))
2079 .finish();
2080 // Only the write is a move of the stack pointer, and it is the one that makes the frame a
2081 // growing one. A read of it in a function that never writes it back is a function that
2082 // asked where the stack was and did nothing with the answer.
2083 if into {
2084 self.stack.grown_at.get_or_insert(inst);
2085 }
2086 Ok(())
2087 }
2088
2089 /// Whether an instruction has an eighty bit float anywhere in it.
2090 ///
2091 /// Producing one and reading one are the same question here, because what makes one of these
2092 /// different from every other instruction is not the operation but where the value is. A
2093 /// `long double` is on the x87 stack while it is being worked on and in a frame slot the rest
2094 /// of the time, and neither of those is somewhere the operand of a rule could point.
2095 fn touches_x87(&self, inst: Inst) -> bool {
2096 let data = &self.source[inst];
2097 data.results().any(|value| on_x87(self.source[value].ty))
2098 || self.source[data.args].iter().any(|&arg| on_x87(self.source[arg].ty))
2099 }
2100
2101 /// Everything that happens to an eighty bit float, as the group of instructions it is.
2102 ///
2103 /// The first six move one, and every one of those is a load, a store, or a load and a store at
2104 /// two different formats, because that is the whole of what this machine converts with: the
2105 /// x87 has no instruction that turns one thing on its stack into another, so a widening is
2106 /// `fld` of the narrow format and a narrowing is `fstp` of it.
2107 ///
2108 /// The rest work on one, and they are here rather than in a rule for the same reason the six
2109 /// are. An add is a push, a push, the add and a pop, and what passes between those four is the
2110 /// top of a stack nothing allocates from, so there is no value in the middle of the group for
2111 /// a pattern to bind or a replacement to name. The comparison is the same shape with its last
2112 /// two instructions folded into one opcode, which is where the byte it produces comes from.
2113 ///
2114 /// Every group leaves the stack as empty as it found it, which is what `spec/10-backend.md`
2115 /// section 10.8 asks of one and is why nothing in this file has to track a depth: each push
2116 /// below is answered by a pop a line or two later, so no two groups can ever be looking at
2117 /// the same eight registers.
2118 fn x87(&mut self, inst: Inst) -> Result<(), Unsupported> {
2119 match self.source[inst].opcode {
2120 Opcode::Load => self.x87_load(inst),
2121 Opcode::Store => self.x87_store(inst),
2122 Opcode::FPExt => self.x87_widen(inst),
2123 Opcode::FPTrunc => self.x87_narrow(inst),
2124 Opcode::SIToFP => self.x87_from_signed(inst),
2125 Opcode::FPToSI => self.x87_to_signed(inst),
2126 Opcode::FAdd => self.x87_arith(inst, "fadd_p"),
2127 Opcode::FSub => self.x87_arith(inst, "fsubr_p"),
2128 Opcode::FMul => self.x87_arith(inst, "fmul_p"),
2129 Opcode::FDiv => self.x87_arith(inst, "fdivr_p"),
2130 Opcode::FNeg => self.x87_flip(inst),
2131 Opcode::FCmp => self.x87_compare(inst),
2132 Opcode::FConst => self.x87_const(inst),
2133 _ => Err(self.unsupported(inst)),
2134 }
2135 }
2136
2137 /// The eighty bit parameters of a block, copied out of the addresses an edge handed over and
2138 /// into slots of the block's own.
2139 ///
2140 /// What crosses an edge for a value of this type is an address, because the value is sixteen
2141 /// bytes of the frame and no register holds any of it. The block cannot keep that address: a
2142 /// second edge into the same block hands over a second one, and a read after the block would
2143 /// then be a read of whichever edge was taken rather than of one place. So the block has a
2144 /// slot per parameter and the bytes are copied into it here, which is the move on an edge that
2145 /// every other type gets from the allocator.
2146 ///
2147 /// Every load runs before every store and the stores run backwards, so all of the values are
2148 /// on the x87 stack at once and nothing reads a slot another one has already written. That
2149 /// costs nothing in the ordinary case of one parameter and is what makes the back edge of a
2150 /// loop that swaps two of these work. It is also the reason for the limit: the stack is eight
2151 /// deep, and a block with more of these than that is refused rather than copied in an order
2152 /// that could be wrong.
2153 fn settle(&mut self, block: Block, arriving: &[(Value, mir::Reg)]) -> Result<(), Unsupported> {
2154 let Some(&(first, _)) = arriving.first() else { return Ok(()) };
2155 if arriving.len() > X87_DEPTH {
2156 let ty = self.source[first].ty;
2157 return Err(Unsupported::Phi { block, count: arriving.len(), ty });
2158 }
2159 // A block parameter comes from no instruction, so what this points at is the first thing
2160 // in the block, which is where a reader looking for the copy would look.
2161 let first_inst = self.source.insts(block).next();
2162 let span = first_inst.map_or(Span::DUMMY, |it| self.source.span(it));
2163 for &(_, reg) in arriving {
2164 let from = self.through(reg);
2165 self.x87_at("fld_t", span, from);
2166 }
2167 for &(param, _) in arriving.iter().rev() {
2168 let into = self.x87_slot(param);
2169 let into = self.through(into);
2170 self.x87_at("fstp_t", span, into);
2171 }
2172 Ok(())
2173 }
2174
2175 /// The frame slot an eighty bit value lives in, as its address in a fresh register.
2176 ///
2177 /// The slot is the value's for the whole function and is taken the first time somebody asks.
2178 /// The address is worked out again every time, which is a `lea` per use and is deliberate: one
2179 /// address kept in a register from the definition to the last use would hold a general purpose
2180 /// register open across everything in between, and a function with a handful of these in it
2181 /// would spend its registers on addresses of things rather than on things.
2182 fn x87_slot(&mut self, value: Value) -> mir::Reg {
2183 // An argument of the function has a slot already and it is the caller's. The convention
2184 // puts the bytes in the argument area and hands over where they are, so the address that
2185 // arrived is the answer and no second copy of the value is made. Nothing ever writes to a
2186 // value of this type once it exists, so nothing writes to the caller's copy either. A
2187 // parameter of any other block is not this: what arrived there is an address a predecessor
2188 // chose, [`Lowering::settle`] has already copied the bytes out of it, and the slot those
2189 // bytes landed in is the one below.
2190 let entry = self.source.entry();
2191 if let (Def::Param { block, .. }, Some(reg)) =
2192 (self.source[value].def, self.regs[value.index()])
2193 {
2194 if entry == Some(block) {
2195 return reg;
2196 }
2197 }
2198 let index = match self.slots[value.index()] {
2199 Some(index) => index,
2200 None => {
2201 let index = self.stack.locals.len();
2202 self.stack.locals.push(Local { size: X87_BYTES, align: X87_BYTES });
2203 self.slots[value.index()] = Some(index);
2204 index
2205 }
2206 };
2207 let block = self.at.expect("a block is being filled");
2208 self.frame_address(block, index)
2209 }
2210
2211 /// The bytes a value crosses between a register and the x87 stack through, as their address
2212 /// in a fresh register.
2213 fn x87_crossing(&mut self) -> mir::Reg {
2214 let index = match self.crossing {
2215 Some(index) => index,
2216 None => {
2217 let index = self.stack.locals.len();
2218 self.stack.locals.push(Local { size: X87_CROSSING, align: X87_CROSSING });
2219 self.crossing = Some(index);
2220 index
2221 }
2222 };
2223 let block = self.at.expect("a block is being filled");
2224 self.frame_address(block, index)
2225 }
2226
2227 /// The two control words, as the address of the first of them in a fresh register.
2228 fn x87_control(&mut self) -> mir::Reg {
2229 let index = match self.control {
2230 Some(index) => index,
2231 None => {
2232 let index = self.stack.locals.len();
2233 self.stack.locals.push(Local { size: 4, align: 4 });
2234 self.control = Some(index);
2235 index
2236 }
2237 };
2238 let block = self.at.expect("a block is being filled");
2239 self.frame_address(block, index)
2240 }
2241
2242 /// An address held in a register, as the addressing mode that reaches it.
2243 fn through(&self, reg: mir::Reg) -> mir::Mem {
2244 mir::Mem::at(mir::Operand::read(reg, self.gpr))
2245 }
2246
2247 /// One instruction of a group, which names an address and nothing else.
2248 ///
2249 /// Every x87 instruction that moves a value is one of these. What it does to the stack is in
2250 /// the mnemonic rather than in an operand, so there is no register to write down and no
2251 /// register the allocator gets a say in.
2252 fn x87_at(&mut self, name: &str, span: Span, at: mir::Mem) {
2253 let block = self.at.expect("a block is being filled");
2254 let opcode = self.named(name);
2255 self.out.build(block, opcode).at(span).mem(at).finish();
2256 }
2257
2258 /// The one instruction of a group that reaches the program's own memory.
2259 ///
2260 /// A `long double` moves in two instructions with a frame slot at one end of them, and the
2261 /// other end is the address the program wrote. That end is the access, so it is the one that
2262 /// carries what the program said about it, and the trip through the slot is this compiler's
2263 /// own business the way a spill is. See [`Self::carried`].
2264 fn x87_touching(&mut self, name: &str, inst: Inst, at: mir::Mem) {
2265 let block = self.at.expect("a block is being filled");
2266 let opcode = self.named(name);
2267 let (span, flags) = (self.source.span(inst), self.carried(inst));
2268 self.out.build(block, opcode).at(span).flags(flags).mem(at).finish();
2269 }
2270
2271 /// One instruction of a group that names nothing at all.
2272 ///
2273 /// The arithmetic is these. Both of an add's operands are already on the stack when it runs
2274 /// and so is where the answer goes, and the stack is not somewhere an instruction says, so
2275 /// `faddp` has an argument in the assembler's syntax and nothing here for the argument to come
2276 /// from. What it works on is which two pushes came before it, which is a fact about the order
2277 /// of the group and is why the group is written in one place.
2278 fn x87_only(&mut self, name: &str, span: Span) {
2279 let block = self.at.expect("a block is being filled");
2280 let opcode = self.named(name);
2281 self.out.build(block, opcode).at(span).finish();
2282 }
2283
2284 /// A `load` of a `long double`: onto the stack from where it was, and off it into the slot.
2285 ///
2286 /// Two instructions rather than the two general purpose moves the same sixteen bytes would
2287 /// take, because `fld` and `fstp` at this format neither convert nor look: the value goes on
2288 /// in the format it was already in and comes back off in it, so a signalling NaN stays one
2289 /// and nothing is raised. Which is what makes this a copy at all.
2290 fn x87_load(&mut self, inst: Inst) -> Result<(), Unsupported> {
2291 let (args, result) = self.ends(inst)?;
2292 let &address = args.first().ok_or_else(|| self.unsupported(inst))?;
2293 let span = self.source.span(inst);
2294 let from = self.reg_of(address)?;
2295 let from = self.through(from);
2296 let into = self.x87_slot(result);
2297 let into = self.through(into);
2298 self.x87_touching("fld_t", inst, from);
2299 self.x87_at("fstp_t", span, into);
2300 Ok(())
2301 }
2302
2303 /// A `store` of a `long double`: the same pair the other way round.
2304 fn x87_store(&mut self, inst: Inst) -> Result<(), Unsupported> {
2305 let args = self.source[self.source[inst].args].to_vec();
2306 let [value, address] = args[..] else { return Err(self.unsupported(inst)) };
2307 let span = self.source.span(inst);
2308 let from = self.x87_slot(value);
2309 let from = self.through(from);
2310 let into = self.reg_of(address)?;
2311 let into = self.through(into);
2312 self.x87_at("fld_t", span, from);
2313 self.x87_touching("fstp_t", inst, into);
2314 Ok(())
2315 }
2316
2317 /// A `float`, a `double` or an integer becoming a `long double`.
2318 ///
2319 /// Through memory, because the x87 reads memory and nothing else: the value is in a register
2320 /// the machine has and the unit has no way to be handed one, so it is written to the crossing
2321 /// bytes and loaded back at the format that widens it. Every one of these is exact. Sixty four
2322 /// bits of significand and fifteen of exponent hold every `float`, every `double` and every
2323 /// sixty four bit integer outright, so none of the four can round and none can raise.
2324 fn x87_across(
2325 &mut self,
2326 inst: Inst,
2327 put: &'static str,
2328 class: RegClass,
2329 get: &'static str,
2330 ) -> Result<(), Unsupported> {
2331 let (args, result) = self.ends(inst)?;
2332 let &source = args.first().ok_or_else(|| self.unsupported(inst))?;
2333 let span = self.source.span(inst);
2334 let value = self.reg_of(source)?;
2335 let across = self.x87_crossing();
2336 let across = self.through(across);
2337 let into = self.x87_slot(result);
2338 let into = self.through(into);
2339
2340 let block = self.at.expect("a block is being filled");
2341 let store = self.named(put);
2342 self.out.build(block, store).at(span).uses(value, class).mem(across).finish();
2343 self.x87_at(get, span, across);
2344 self.x87_at("fstp_t", span, into);
2345 Ok(())
2346 }
2347
2348 /// A `long double` becoming a `float`, a `double` or an integer.
2349 ///
2350 /// Through memory for the reason above and in the same three instructions backwards. The two
2351 /// that go to a float round to nearest, which is what the control word says unless somebody
2352 /// has changed it and is what C wants. The two that go to an integer do not, which is why they
2353 /// do not come here.
2354 fn x87_back(
2355 &mut self,
2356 inst: Inst,
2357 put: &'static str,
2358 get: &'static str,
2359 class: RegClass,
2360 ) -> Result<(), Unsupported> {
2361 let (args, result) = self.ends(inst)?;
2362 let &source = args.first().ok_or_else(|| self.unsupported(inst))?;
2363 let span = self.source.span(inst);
2364 let from = self.x87_slot(source);
2365 let from = self.through(from);
2366 let across = self.x87_crossing();
2367 let across = self.through(across);
2368
2369 self.x87_at("fld_t", span, from);
2370 self.x87_at(put, span, across);
2371 let block = self.at.expect("a block is being filled");
2372 let reg = self.new_reg(result);
2373 let load = self.named(get);
2374 self.out.build(block, load).at(span).def(reg, class).mem(across).finish();
2375 Ok(())
2376 }
2377
2378 /// An `fpext` up to a `long double`, which is the only direction this machine has one in.
2379 fn x87_widen(&mut self, inst: Inst) -> Result<(), Unsupported> {
2380 let sse = self.conv.sse_class;
2381 match self.source[self.narrow(inst)?].ty.bits() {
2382 32 => self.x87_across(inst, "movss_mr", sse, "fld_s"),
2383 64 => self.x87_across(inst, "movsd_mr", sse, "fld_l"),
2384 _ => Err(self.unsupported(inst)),
2385 }
2386 }
2387
2388 /// An `fptrunc` down from a `long double`, which is the other direction of the same.
2389 fn x87_narrow(&mut self, inst: Inst) -> Result<(), Unsupported> {
2390 let sse = self.conv.sse_class;
2391 let result = self.source[inst].first_result.ok_or_else(|| self.unsupported(inst))?;
2392 match self.source[result].ty.bits() {
2393 32 => self.x87_back(inst, "fstp_s", "movss_rm", sse),
2394 64 => self.x87_back(inst, "fstp_l", "movsd_rm", sse),
2395 _ => Err(self.unsupported(inst)),
2396 }
2397 }
2398
2399 /// A `sitofp` up to a `long double`.
2400 ///
2401 /// Thirty two bits and sixty four, and nothing narrower, because C widens an integer to `int`
2402 /// before it converts one and the front end writes that widening down. An unsigned integer is
2403 /// not here at all: `fild` reads its operand as signed, so a value above the signed range
2404 /// comes back short by two to the sixty fourth and has to be added back, which is arithmetic
2405 /// rather than a move and waits with the rest of it.
2406 fn x87_from_signed(&mut self, inst: Inst) -> Result<(), Unsupported> {
2407 let gpr = self.gpr;
2408 match self.source[self.narrow(inst)?].ty.bits() {
2409 32 => self.x87_across(inst, "mov_mr_32", gpr, "fild_l"),
2410 64 => self.x87_across(inst, "mov_mr_64", gpr, "fild_ll"),
2411 _ => Err(self.unsupported(inst)),
2412 }
2413 }
2414
2415 /// An `fptosi` down from a `long double`, which is the one conversion here with no single
2416 /// instruction behind it.
2417 ///
2418 /// C cuts towards zero and the unit rounds the way its control word says, so the store that
2419 /// takes the value off the stack is wrapped in the control word being saved, changed and put
2420 /// back. Five instructions around the one that does the work, and three more moving the word
2421 /// through a register, because this machine has no way to OR a constant into memory at this
2422 /// width. The unit has a shorter answer in `fisttp`, and `spec/10-backend.md` section 10.8
2423 /// says why it is not used: it is SSE3, the x86-64 baseline is not, and there is nothing here
2424 /// that can gate an instruction on a feature yet.
2425 fn x87_to_signed(&mut self, inst: Inst) -> Result<(), Unsupported> {
2426 let (args, result) = self.ends(inst)?;
2427 let &source = args.first().ok_or_else(|| self.unsupported(inst))?;
2428 let (put, get) = match self.source[result].ty.bits() {
2429 32 => ("fistp_l", "mov_rm_32"),
2430 64 => ("fistp_ll", "mov_rm_64"),
2431 _ => return Err(self.unsupported(inst)),
2432 };
2433 let span = self.source.span(inst);
2434 let gpr = self.gpr;
2435 let from = self.x87_slot(source);
2436 let from = self.through(from);
2437 let across = self.x87_crossing();
2438 let across = self.through(across);
2439 let control = self.x87_control();
2440 let saved = self.through(control).plus(0);
2441 let cut = self.through(control).plus(2);
2442
2443 // The word the unit has now, into the first of the two slots and into a register, with the
2444 // rounding field turned to truncate on the way to the second.
2445 self.x87_at("fnstcw", span, saved);
2446 let block = self.at.expect("a block is being filled");
2447 let was = self.out.new_vreg(gpr);
2448 let read = self.named("mov_rm_16");
2449 self.out.build(block, read).at(span).def(was, gpr).mem(saved).finish();
2450 let now = self.out.new_vreg(gpr);
2451 let set = self.named("or_ri_16");
2452 // Two address, which is written out here rather than taken from the two shorthands
2453 // because the shorthands leave an operand unconstrained: this machine ORs into the
2454 // register it read, so the two have to be the same one and only the constraint says so.
2455 self.out
2456 .build(block, set)
2457 .at(span)
2458 .operand(mir::Operand::write(now, gpr).with(Constraint::Reuse(1)))
2459 .operand(mir::Operand::read(was, gpr))
2460 .imm(X87_TRUNCATE)
2461 .finish();
2462 let write = self.named("mov_mr_16");
2463 self.out.build(block, write).at(span).uses(now, gpr).mem(cut).finish();
2464
2465 // The conversion itself, under the changed word, and then the word the unit had put back
2466 // before anything else runs.
2467 self.x87_at("fldcw", span, cut);
2468 self.x87_at("fld_t", span, from);
2469 self.x87_at(put, span, across);
2470 self.x87_at("fldcw", span, saved);
2471
2472 let block = self.at.expect("a block is being filled");
2473 let reg = self.new_reg(result);
2474 let load = self.named(get);
2475 self.out.build(block, load).at(span).def(reg, gpr).mem(across).finish();
2476 Ok(())
2477 }
2478
2479 /// A constant of this type, as the bits of it written into its slot.
2480 ///
2481 /// No x87 instruction at all, which is the surprise here. A slot holding an eighty bit value is
2482 /// the value, so a constant is ten bytes put where the value lives, and the unit never has to
2483 /// see it: whatever reads it will `fld` it out of the slot the way it reads any other one.
2484 ///
2485 /// Ten bytes in two goes, because the machine stores eight at a time and there is no store of
2486 /// an immediate to memory, so each half is put in a register first. The six bytes above the ten
2487 /// are left alone, since nothing reads them: they are the padding that makes the type sixteen
2488 /// wide and they are unspecified in the psABI rather than zero.
2489 ///
2490 /// The other way is a constant pool, an `fldt` of a symbol, and a relocation, which is what a
2491 /// compiler with somewhere to put a literal does. This back end has nowhere to put one yet, and
2492 /// four instructions in the frame is what that costs until it does.
2493 fn x87_const(&mut self, inst: Inst) -> Result<(), Unsupported> {
2494 let Extra::Imm(imm) = self.source[inst].extra else { return Err(self.unsupported(inst)) };
2495 let result = self.source[inst].first_result.ok_or_else(|| self.unsupported(inst))?;
2496 let bits = self.source[imm].bits();
2497 let span = self.source.span(inst);
2498 let gpr = self.gpr;
2499 let slot = self.x87_slot(result);
2500 let low = self.through(slot).plus(0);
2501 let high = self.through(slot).plus(8);
2502
2503 let block = self.at.expect("a block is being filled");
2504 for (bytes, at, into) in
2505 [(bits as u64 as i64, low, "64"), (((bits >> 64) & 0xffff) as i64, high, "16")]
2506 {
2507 let held = self.out.new_vreg(gpr);
2508 let put = self.named(&format!("mov_ri_{into}"));
2509 self.out.build(block, put).at(span).def(held, gpr).imm(bytes).finish();
2510 let store = self.named(&format!("mov_mr_{into}"));
2511 self.out.build(block, store).at(span).uses(held, gpr).mem(at).finish();
2512 }
2513 Ok(())
2514 }
2515
2516 /// One arithmetic instruction on two eighty bit values, as the four it takes.
2517 ///
2518 /// The left operand is pushed first and the right one on top of it, so the left ends up
2519 /// underneath and the answer wanted is the one below against the top in that order. Which of
2520 /// the two mnemonics computes that is a question about the spelling rather than about the
2521 /// machine, and the two spellings disagree. Intel's `FSUBP ST(i), ST(0)` is `ST(i) - ST(0)`
2522 /// and is `DE E8+i`, and AT&T's `fsubp` is `DE E0+i`, which is the other subtraction. This
2523 /// compiler writes AT&T and encodes what gas encodes, so what it asks for here is `fsubr_p`
2524 /// and `fdivr_p`, and the `r` is not a reversal of anything the code generator decided.
2525 ///
2526 /// An addition and a multiplication have one form each and do not care, which is why a test
2527 /// that reads the mnemonic back would not have caught this and one that computes a subtraction
2528 /// and checks the answer does.
2529 ///
2530 /// The answer is left where the deeper of the two was and the shallower is gone, which is what
2531 /// the `p` on the mnemonic means, so one push has already been paid back by the time the
2532 /// `fstp` runs and the stack is level again after it.
2533 ///
2534 /// Nothing here is folded and nothing is reused. Two values that are the same value get two
2535 /// pushes of the same slot, and an operand that was just computed is read back out of the slot
2536 /// it was written to rather than left on the stack, which costs a store and a load per
2537 /// instruction in an expression. Keeping a partial result on the stack across the next
2538 /// instruction's operands means knowing how deep the stack is at every point in the block, and
2539 /// that is a different thing from writing a group.
2540 fn x87_arith(&mut self, inst: Inst, with: &'static str) -> Result<(), Unsupported> {
2541 let (args, result) = self.ends(inst)?;
2542 let [left, right] = args[..] else { return Err(self.unsupported(inst)) };
2543 let span = self.source.span(inst);
2544 let left = self.x87_slot(left);
2545 let left = self.through(left);
2546 let right = self.x87_slot(right);
2547 let right = self.through(right);
2548 let into = self.x87_slot(result);
2549 let into = self.through(into);
2550 self.x87_at("fld_t", span, left);
2551 self.x87_at("fld_t", span, right);
2552 self.x87_only(with, span);
2553 self.x87_at("fstp_t", span, into);
2554 Ok(())
2555 }
2556
2557 /// A negation, which is a push, the sign bit turned over and a pop.
2558 ///
2559 /// `fchs` does not read the value as a number, so this is right for a zero, for an infinity
2560 /// and for a NaN, and it raises nothing on any of them. Which is what C asks of a negation and
2561 /// is not what subtracting from zero would give: `0.0L - x` is a different answer at a
2562 /// negative zero and a signalling one at a NaN.
2563 fn x87_flip(&mut self, inst: Inst) -> Result<(), Unsupported> {
2564 let (args, result) = self.ends(inst)?;
2565 let &source = args.first().ok_or_else(|| self.unsupported(inst))?;
2566 let span = self.source.span(inst);
2567 let from = self.x87_slot(source);
2568 let from = self.through(from);
2569 let into = self.x87_slot(result);
2570 let into = self.through(into);
2571 self.x87_at("fld_t", span, from);
2572 self.x87_only("fchs", span);
2573 self.x87_at("fstp_t", span, into);
2574 Ok(())
2575 }
2576
2577 /// A comparison of two eighty bit values, as the two pushes and the one opcode that reads them.
2578 ///
2579 /// The right operand is pushed first and the left one on top of it, which is the other way
2580 /// round from the arithmetic and is because `fucomip` asks about the top against what is under
2581 /// it: the comparison this machine can do is the top's, so the value the predicate is about
2582 /// has to be the top. The pop that gets the loser off the stack and the byte that reads the
2583 /// flags are both inside the opcode, since what passes between those and the comparison is the
2584 /// flags and the flags are not something anything here can name.
2585 ///
2586 /// Which of the ten opcodes, and which way round, is the same table the vector comparisons
2587 /// match against in `rules/x86-64.rules`, and it has to stay the same table: a predicate that
2588 /// picked a different condition here than there would be a `long double` comparison that
2589 /// disagreed with the `double` comparison of the same two numbers, which is the one thing a
2590 /// wider format is not allowed to do.
2591 ///
2592 /// The always false and the always true are refused rather than folded into a constant,
2593 /// because a comparison this machine never has to do is one the optimizer should have removed
2594 /// and an instruction here that quietly agreed with it would hide that it did not.
2595 fn x87_compare(&mut self, inst: Inst) -> Result<(), Unsupported> {
2596 let Extra::FloatPred(pred) = self.source[inst].extra else {
2597 return Err(self.unsupported(inst));
2598 };
2599 let (args, result) = self.ends(inst)?;
2600 let [left, right] = args[..] else { return Err(self.unsupported(inst)) };
2601 // Two of the fourteen need a second byte and an instruction to put the two together,
2602 // because they are two conditions at once: an ordered equal is equal and not unordered,
2603 // and an unordered not equal is either. The opcode carries all of that and says here only
2604 // that it writes somewhere else as well.
2605 let (name, reversed, both) = match pred {
2606 FloatPred::Ogt => ("fucomip_set_a", false, false),
2607 FloatPred::Oge => ("fucomip_set_ae", false, false),
2608 FloatPred::Olt => ("fucomip_set_a", true, false),
2609 FloatPred::Ole => ("fucomip_set_ae", true, false),
2610 FloatPred::One => ("fucomip_set_ne", false, false),
2611 FloatPred::Ord => ("fucomip_set_np", false, false),
2612 FloatPred::Uno => ("fucomip_set_p", false, false),
2613 FloatPred::Ueq => ("fucomip_set_e", false, false),
2614 FloatPred::Ult => ("fucomip_set_b", false, false),
2615 FloatPred::Ule => ("fucomip_set_be", false, false),
2616 FloatPred::Ugt => ("fucomip_set_b", true, false),
2617 FloatPred::Uge => ("fucomip_set_be", true, false),
2618 FloatPred::Oeq => ("fucomip_set_e_and_np", false, true),
2619 FloatPred::Une => ("fucomip_set_ne_or_p", false, true),
2620 FloatPred::False | FloatPred::True => return Err(self.unsupported(inst)),
2621 };
2622 let (top, under) = if reversed { (right, left) } else { (left, right) };
2623
2624 let span = self.source.span(inst);
2625 let gpr = self.gpr;
2626 let under = self.x87_slot(under);
2627 let under = self.through(under);
2628 let top = self.x87_slot(top);
2629 let top = self.through(top);
2630 self.x87_at("fld_t", span, under);
2631 self.x87_at("fld_t", span, top);
2632
2633 let block = self.at.expect("a block is being filled");
2634 let reg = self.new_reg(result);
2635 // Taken before the instruction is started rather than inside it, since both come from the
2636 // same function being built and only one thing at a time may be adding to it.
2637 let spare = both.then(|| self.out.new_vreg(gpr));
2638 let opcode = self.named(name);
2639 let mut build = self.out.build(block, opcode).at(span).def(reg, gpr);
2640 if let Some(spare) = spare {
2641 build = build.def(spare, gpr);
2642 }
2643 build.finish();
2644 Ok(())
2645 }
2646
2647 /// The operands and the one result of an instruction that has exactly one.
2648 fn ends(&self, inst: Inst) -> Result<(&'a [Value], Value), Unsupported> {
2649 let data = &self.source[inst];
2650 let result = data.first_result.ok_or_else(|| self.unsupported(inst))?;
2651 Ok((&self.source[data.args], result))
2652 }
2653
2654 /// The operand of a conversion, which is the end of it that is not the `long double`.
2655 fn narrow(&self, inst: Inst) -> Result<Value, Unsupported> {
2656 let args = &self.source[self.source[inst].args];
2657 args.first().copied().ok_or_else(|| self.unsupported(inst))
2658 }
2659
2660 /// One `va_start`, as the fields of the list it was handed.
2661 ///
2662 /// On the four field list, two of them are numbers this already knows, and each costs an
2663 /// instruction to put in a register before it can be stored, because the machine here has no
2664 /// store of an immediate to memory. The other two are addresses in the frame, and each is a
2665 /// `lea` [`crate::finish`] finishes: the save area is one of the function's own stack objects,
2666 /// and the caller's argument area is where the parameters that had no register came from, which
2667 /// is the same place and the same fixup a parameter past the sixth already uses.
2668 ///
2669 /// On the list that is a pointer it is the second of those four and nothing else, since the
2670 /// whole of what that list says is where the walk is and the walk starts at the first argument
2671 /// the signature does not name. One `lea` and one store.
2672 ///
2673 /// What is written is exactly the fields [`crate::varargs`] describes, in the order they are
2674 /// laid out, so that reading this beside that table is the whole of the check.
2675 fn va_start(&mut self, inst: Inst) -> Result<(), Unsupported> {
2676 let Some(&list) = self.source[self.source[inst].args].first() else {
2677 return Err(self.unsupported(inst));
2678 };
2679 let started = self.varargs.ok_or_else(|| self.unsupported(inst))?;
2680 let list = self.reg_of(list)?;
2681 let block = self.at.expect("a block is being filled");
2682 let span = self.source.span(inst);
2683
2684 let (save, incoming) = match started {
2685 Varargs::Pointer { incoming } => (None, incoming),
2686 Varargs::Fields { save, incoming, integers, floats } => {
2687 let counts = [(varargs::GP_OFFSET, integers), (varargs::FP_OFFSET, floats)];
2688 for (at, count) in counts {
2689 self.store_small(list, at, i64::from(count), span);
2690 }
2691 (Some(save), incoming)
2692 }
2693 Varargs::Aapcs { save, incoming, integers_end, floats_end, integers, floats } => {
2694 let counts =
2695 [(varargs::aapcs::GR_OFFS, integers), (varargs::aapcs::VR_OFFS, floats)];
2696 for (at, count) in counts {
2697 self.store_small(list, at, i64::from(count), span);
2698 }
2699 let overflow = self.overflow(block, incoming, span);
2700 let integers_top = self.frame_address_plus(block, save, integers_end);
2701 let floats_top = self.frame_address_plus(block, save, floats_end);
2702 let fields = [
2703 (varargs::aapcs::STACK, overflow),
2704 (varargs::aapcs::GR_TOP, integers_top),
2705 (varargs::aapcs::VR_TOP, floats_top),
2706 ];
2707 for (at, held) in fields {
2708 self.store_word(list, at, held, span);
2709 }
2710 return Ok(());
2711 }
2712 };
2713
2714 // At the front of the list when that address is the whole of it, and at the field the
2715 // layout gives it when there are four, with the save area behind it.
2716 let overflow = self.overflow(block, incoming, span);
2717 let fields = match save {
2718 None => vec![(0, overflow)],
2719 Some(save) => {
2720 let save = self.frame_address(block, save);
2721 vec![(varargs::OVERFLOW, overflow), (varargs::SAVE_AREA, save)]
2722 }
2723 };
2724 for (at, held) in fields {
2725 self.store_word(list, at, held, span);
2726 }
2727 Ok(())
2728 }
2729
2730 /// The first argument the signature did not name, which is as far up the caller's argument
2731 /// area as the ones it did name reached. Nothing here knows where that area is, so the distance
2732 /// is recorded the way a parameter read out of it is and finished with it.
2733 fn overflow(&mut self, block: mir::Block, incoming: u32, span: Span) -> mir::Reg {
2734 let overflow = self.out.new_vreg(self.gpr);
2735 let lea = self.named(self.selector.frame.lea);
2736 let sp = mir::Operand::read(mir::Reg::physical(self.conv.stack_pointer), self.gpr);
2737 let made = self
2738 .out
2739 .build(block, lea)
2740 .at(span)
2741 .def(overflow, self.gpr)
2742 .mem(mir::Mem::at(sp))
2743 .finish();
2744 self.stack.arguments.push((made, incoming));
2745 overflow
2746 }
2747
2748 /// Writes a small constant into a 32 bit field of a list.
2749 fn store_small(&mut self, list: mir::Reg, at: i64, value: i64, span: Span) {
2750 let block = self.at.expect("a block is being filled");
2751 let held = self.out.new_vreg(self.gpr);
2752 let load = mir::Opcode::new(self.names.intern(self.selector.abi.small));
2753 self.out.build(block, load).at(span).def(held, self.gpr).imm(value).finish();
2754
2755 let head = (self.selector.abi.store)(Type::int(32)).expect("a store of a word");
2756 let store = mir::Opcode::new(self.names.intern(head));
2757 let mem = self.field(list, at);
2758 self.out.build(block, store).at(span).uses(held, self.gpr).mem(mem).finish();
2759 }
2760
2761 /// Writes an address into a pointer field of a list.
2762 fn store_word(&mut self, list: mir::Reg, at: i64, held: mir::Reg, span: Span) {
2763 let block = self.at.expect("a block is being filled");
2764 let head = (self.selector.abi.store)(Type::int(64)).expect("a store of an address");
2765 let store = mir::Opcode::new(self.names.intern(head));
2766 let mem = self.field(list, at);
2767 self.out.build(block, store).at(span).uses(held, self.gpr).mem(mem).finish();
2768 }
2769
2770 /// One field of a list, as the addressing mode that reaches it.
2771 fn field(&self, list: mir::Reg, at: i64) -> mir::Mem {
2772 let base = mir::Operand::read(list, self.gpr);
2773 mir::Mem::at(base).plus(i32::try_from(at).expect("a field of a list is a small offset"))
2774 }
2775
2776 /// The address of a name: one `lea` off the instruction pointer, with the name on it.
2777 ///
2778 /// That is x86-64, and [`Selector::symbols`] is what says so. AArch64 writes the same thing as
2779 /// an `adrp` of the page and an `add` of the low twelve bits, which is one opcode with the name
2780 /// as its own symbol and no addressing mode, and the table read is an `adrp` and an `ldr`.
2781 ///
2782 /// The same instruction an `alloca` gets and for a related reason. An address that is not in
2783 /// the program is a `lea` of an addressing mode that names no register, and the mode carries
2784 /// the symbol so that [`rucc_asm`] can write it relative to `%rip` and leave the relocation
2785 /// for the assembler. Both halves of that already existed: the printer writes `sym(%rip)` and
2786 /// the encoder emits the relocation, because a call to a name the file does not define needed
2787 /// them first.
2788 ///
2789 /// One `mov` and not one `lea` when the name is one [`Elsewhere`] holds, because the distance
2790 /// the `lea` adds to the instruction pointer is a number only a link that puts the name in
2791 /// this program can work out, and the address of a function this file merely declares is not
2792 /// such a number. The load reads the address out of the slot the linker fills in instead. The
2793 /// linker turns it back into the `lea` when the name turns out to have been here all along,
2794 /// so this is not slower in the case that was already right.
2795 ///
2796 /// There is deliberately no name for this in [`crate::term`], which is what stops the address
2797 /// being folded into the instruction that reads it. Folding it is the right thing to do and
2798 /// is what turns a load of a global from two instructions into one, but it is a separate
2799 /// question about addressing modes and issue #282 is it. Until then the address is in a
2800 /// register before anything uses it, which is correct and one instruction longer.
2801 ///
2802 /// What this does not do is give the name anything to refer to. A module carries its globals
2803 /// and nothing writes them out, so a file that defines the variable it reads compiles to a
2804 /// reference the linker cannot resolve. Issue #293 is the other half.
2805 ///
2806 /// A thread-local variable is neither of the two above and is [`Self::thread_address`].
2807 fn address_of(&mut self, inst: Inst) -> Result<(), Unsupported> {
2808 let data = &self.source[inst];
2809 let Extra::Symbol(symbol) = data.extra else { return Err(self.unsupported(inst)) };
2810 let result = data.first_result.ok_or_else(|| self.unsupported(inst))?;
2811 if self.elsewhere.thread(symbol) {
2812 return self.thread_address(inst, symbol, result);
2813 }
2814 if let Some(slot) = self.elsewhere.slot(symbol) {
2815 let reg = self.new_reg(result);
2816 return self.through_slot(inst, slot, symbol, reg);
2817 }
2818
2819 let block = self.at.expect("a block is being filled");
2820 let reg = self.new_reg(result);
2821 let span = self.source.span(inst);
2822 let far = self.elsewhere.holds(symbol);
2823 let symbols = self.selector.symbols;
2824 match if far { symbols.far } else { symbols.near } {
2825 Reach::Mode(name) => {
2826 let mem = if far { mir::Mem::got(symbol) } else { mir::Mem::of(symbol) };
2827 let opcode = self.named(name);
2828 self.out.build(block, opcode).at(span).def(reg, self.gpr).mem(mem).finish();
2829 }
2830 Reach::Own(name) => {
2831 let opcode = self.named(name);
2832 self.out.build(block, opcode).at(span).def(reg, self.gpr).symbol(symbol).finish();
2833 }
2834 }
2835 Ok(())
2836 }
2837
2838 /// The address of a name on COFF that is reached through a pointer, into `reg`.
2839 ///
2840 /// One load of the pointer from the instruction pointer, which is the same instruction the
2841 /// global offset table is read with on the other formats and for much the same reason: the
2842 /// pointer is in this image, so the distance to it is a number the linker has, and what it
2843 /// holds is an address the loader or the runtime writes once the DLL the name is in has been
2844 /// put somewhere. See [`Slot`] for which pointer and who writes it.
2845 ///
2846 /// ```text
2847 /// movq __imp_GetCurrentProcessId(%rip), %rax
2848 /// movq .refptr.environ(%rip), %rax
2849 /// ```
2850 ///
2851 /// AArch64 has no load relative to the instruction pointer that reaches that far, so it is the
2852 /// page of the pointer and a load from the low twelve bits of it, which is what clang writes.
2853 ///
2854 /// ```text
2855 /// adrp x8, __imp_GetCurrentProcessId
2856 /// ldr x8, [x8, :lo12:__imp_GetCurrentProcessId]
2857 /// ```
2858 fn through_slot(
2859 &mut self,
2860 inst: Inst,
2861 slot: Slot,
2862 symbol: Symbol,
2863 reg: mir::Reg,
2864 ) -> Result<(), Unsupported> {
2865 let block = self.at.expect("a block is being filled");
2866 let span = self.source.span(inst);
2867 let pointer = slot.name(self.names.resolve(symbol));
2868 let pointer = self.names.intern(&pointer);
2869 match self.selector.symbols.slot {
2870 Reach::Mode(name) => {
2871 let opcode = self.named(name);
2872 let mem = mir::Mem::of(pointer);
2873 self.out.build(block, opcode).at(span).def(reg, self.gpr).mem(mem).finish();
2874 }
2875 Reach::Own(name) => {
2876 let opcode = self.named(name);
2877 self.out.build(block, opcode).at(span).def(reg, self.gpr).symbol(pointer).finish();
2878 }
2879 }
2880 Ok(())
2881 }
2882
2883 /// The address of a thread-local variable, which is this thread's copy of it.
2884 ///
2885 /// Neither instruction the ordinary case writes would mean anything here. There is no distance
2886 /// to the variable for a `lea` to add, because there is no variable: there is one copy of it per
2887 /// thread and they are at different addresses, so a link asked for the distance to the name
2888 /// refuses rather than picking one. And there is no address for a table slot to hold either, for
2889 /// the same reason.
2890 ///
2891 /// What is the same in every thread is where the variable sits inside the block of storage a
2892 /// thread gets, so that offset is what the link writes down, and the address of the running
2893 /// thread's block is what turns it into an address. x86-64 keeps that address in `%fs`, at the
2894 /// front of the block, so the whole of this is three instructions:
2895 ///
2896 /// ```text
2897 /// movq x@gottpoff(%rip), %off # how far into the block x sits, which the link fills in
2898 /// movq %fs:0, %tp # where this thread's block is, which only the machine knows
2899 /// addq %tp, %off # this thread's copy of x
2900 /// ```
2901 ///
2902 /// That is the initial exec model. It is one instruction longer than what gcc writes at `-O2`
2903 /// in an executable, which folds the addition into the instruction that uses the address, and
2904 /// the difference is issue #282 rather than anything about threads: nothing here folds an
2905 /// address into its reader yet. The link relaxes the first instruction into an immediate when it
2906 /// is making an executable, since it lays the blocks out and therefore knows the number, so the
2907 /// table slot costs nothing in the case that is common.
2908 ///
2909 /// It is not the most general model. A library loaded by `dlopen` gets its storage after the
2910 /// program is already running, and the block this reaches was laid out before it started, so
2911 /// the loader has to find room in that block for the library's variables. glibc keeps a little
2912 /// spare room for exactly this and a library that fits in it loads and runs; one that does not
2913 /// fails to load, with a message saying so. The model with no such limit calls `__tls_get_addr`
2914 /// and is what gcc writes under `-fPIC` by default, and it is issue #1104.
2915 ///
2916 /// So this is the model gcc writes under `-ftls-model=initial-exec`: right for an executable,
2917 /// right for a library the program is linked against, and a load that either works or is
2918 /// refused out loud for a library something opens later. What it is never is quietly wrong.
2919 ///
2920 /// AArch64 Linux is the same three steps. The slot is reached with `adrp` and `ldr` against
2921 /// `:gottprel:`, the thread pointer is `tpidr_el0` read with `mrs`, and the add has three
2922 /// operands. Apple's platforms reach a thread-local variable through a descriptor call instead,
2923 /// which is [`Self::thread_descriptor`].
2924 fn thread_address(
2925 &mut self,
2926 inst: Inst,
2927 symbol: Symbol,
2928 result: Value,
2929 ) -> Result<(), Unsupported> {
2930 if self.elsewhere.described() {
2931 return self.thread_descriptor(inst, symbol, result);
2932 }
2933 if self.elsewhere.indexed() {
2934 return self.thread_indexed(inst, symbol, result);
2935 }
2936 let block = self.at.expect("a block is being filled");
2937 let span = self.source.span(inst);
2938 let gpr = self.gpr;
2939
2940 let offset = self.out.new_vreg(gpr);
2941 match self.selector.symbols.thread {
2942 Reach::Mode(name) => {
2943 let load = self.named(name);
2944 let mem = mir::Mem::thread(symbol);
2945 self.out.build(block, load).at(span).def(offset, gpr).mem(mem).finish();
2946 }
2947 Reach::Own(name) => {
2948 let load = self.named(name);
2949 self.out.build(block, load).at(span).def(offset, gpr).symbol(symbol).finish();
2950 }
2951 }
2952 let pointer = self.out.new_vreg(gpr);
2953 self.read_thread_pointer(block, span, pointer);
2954
2955 // Two address on x86-64, for the reason `x87_to_int` gives: that machine adds into the
2956 // register it read, and only the constraint says the two are the same one.
2957 let reg = self.new_reg(result);
2958 let jumps = self.selector.jumps;
2959 let add = self.named(jumps.add);
2960 let written = mir::Operand::write(reg, gpr);
2961 let written = if jumps.two_address { written.with(Constraint::Reuse(1)) } else { written };
2962 self.out
2963 .build(block, add)
2964 .at(span)
2965 .operand(written)
2966 .operand(mir::Operand::read(offset, gpr))
2967 .operand(mir::Operand::read(pointer, gpr))
2968 .finish();
2969 Ok(())
2970 }
2971
2972 /// A thread-local variable on Mach-O, which is a call.
2973 ///
2974 /// The slot the machine's thread load reads holds the address of the variable's descriptor
2975 /// there, `_v@TLVP` on x86-64 and `_v@TLVPPAGE` with `_v@TLVPPAGEOFF` on AArch64. The first
2976 /// word of the descriptor is the function that finds this thread's copy, and it takes the
2977 /// descriptor's address as its one argument and gives back the copy's address. That is the
2978 /// sequence clang writes on both machines.
2979 ///
2980 /// The call is built as an ordinary call through an address, so it costs what any call costs:
2981 /// everything the convention does not preserve is taken to be gone across it. Apple's function
2982 /// keeps more than that, all but the result and the two scratch registers on AArch64, and
2983 /// taking the fewer registers as gone would be faster. What this gives up is speed, and a
2984 /// function that reads a thread-local is no longer a leaf.
2985 fn thread_descriptor(
2986 &mut self,
2987 inst: Inst,
2988 symbol: Symbol,
2989 result: Value,
2990 ) -> Result<(), Unsupported> {
2991 let block = self.at.expect("a block is being filled");
2992 let span = self.source.span(inst);
2993 let gpr = self.gpr;
2994
2995 let descriptor = self.out.new_vreg(gpr);
2996 match self.selector.symbols.thread {
2997 Reach::Mode(name) => {
2998 let load = self.named(name);
2999 let mem = mir::Mem::thread(symbol);
3000 self.out.build(block, load).at(span).def(descriptor, gpr).mem(mem).finish();
3001 }
3002 Reach::Own(name) => {
3003 let load = self.named(name);
3004 let build = self.out.build(block, load).at(span);
3005 build.def(descriptor, gpr).symbol(symbol).finish();
3006 }
3007 }
3008 let finder = self.out.new_vreg(gpr);
3009 let word = (self.selector.abi.load)(Type::PTR).ok_or_else(|| self.unsupported(inst))?;
3010 let word = mir::Opcode::new(self.names.intern(word));
3011 let mem = mir::Mem::at(mir::Operand::read(descriptor, gpr));
3012 self.out.build(block, word).at(span).def(finder, gpr).mem(mem).finish();
3013
3014 let args = [abi::Passing { ty: Type::PTR, reg: descriptor, abi: Abi::default() }];
3015 let what = abi::Calling {
3016 callee: abi::Callee::Through(finder),
3017 args: &args,
3018 returns: &[Type::PTR],
3019 variadic: false,
3020 named: 1,
3021 at: span,
3022 };
3023 let made = abi::call(&mut self.out, block, &what, self.conv, self.selector.abi, self.names)
3024 .map_err(|refused| Unsupported::Call { inst, refused })?;
3025 let calls = &mut self.stack.calls;
3026 *calls = Some(calls.unwrap_or(0).max(made.outgoing));
3027 let &[reg] = &made.results[..] else { return Err(self.unsupported(inst)) };
3028 self.regs[result.index()] = Some(reg);
3029 Ok(())
3030 }
3031
3032 /// A thread-local variable on Windows, which is four loads and no call.
3033 ///
3034 /// `_tls_index` is this image's slot in the array of `.tls` copies the thread block holds at
3035 /// `%gs:88`, and the variable is as far into this thread's copy as it is into the section. The
3036 /// C runtime defines the index and the linker writes the offset. See [`crate::select::Indexed`] for
3037 /// the four instructions, which are the ones gcc writes.
3038 fn thread_indexed(
3039 &mut self,
3040 inst: Inst,
3041 symbol: Symbol,
3042 result: Value,
3043 ) -> Result<(), Unsupported> {
3044 if let Some(teb) = self.selector.symbols.teb.as_ref() {
3045 return self.thread_from_teb(inst, teb, symbol, result);
3046 }
3047 let Some(indexed) = self.selector.symbols.indexed.as_ref() else {
3048 return Err(Unsupported::Unported { inst: Some(inst), what: Unported::Thread });
3049 };
3050 let block = self.at.expect("a block is being filled");
3051 let span = self.source.span(inst);
3052 let gpr = self.gpr;
3053
3054 let slot = self.out.new_vreg(gpr);
3055 let tls_index = self.names.intern("_tls_index");
3056 let index = self.named(indexed.index);
3057 self.out.build(block, index).at(span).def(slot, gpr).mem(mir::Mem::of(tls_index)).finish();
3058
3059 let array = self.out.new_vreg(gpr);
3060 let load = self.named(indexed.load);
3061 let at = mir::Mem::in_segment(indexed.segment, indexed.at);
3062 self.out.build(block, load).at(span).def(array, gpr).mem(at).finish();
3063
3064 let copy = self.out.new_vreg(gpr);
3065 let mem =
3066 mir::Mem::at(mir::Operand::read(array, gpr)).indexed(mir::Operand::read(slot, gpr), 8);
3067 self.out.build(block, load).at(span).def(copy, gpr).mem(mem).finish();
3068
3069 let reg = self.new_reg(result);
3070 let add = self.named(indexed.add);
3071 let mem = mir::Mem::section(mir::Operand::read(copy, gpr), symbol);
3072 self.out.build(block, add).at(span).def(reg, gpr).mem(mem).finish();
3073 Ok(())
3074 }
3075
3076 /// [`Self::thread_indexed`] on AArch64, where the TEB is in `x18`. See [`crate::select::Teb`]
3077 /// for the instructions, which are the ones clang writes.
3078 fn thread_from_teb(
3079 &mut self,
3080 inst: Inst,
3081 teb: &crate::select::Teb,
3082 symbol: Symbol,
3083 result: Value,
3084 ) -> Result<(), Unsupported> {
3085 let block = self.at.expect("a block is being filled");
3086 let span = self.source.span(inst);
3087 let gpr = self.gpr;
3088
3089 let slot = self.out.new_vreg(gpr);
3090 let tls_index = self.names.intern("_tls_index");
3091 let index = self.named(teb.index);
3092 self.out.build(block, index).at(span).def(slot, gpr).symbol(tls_index).finish();
3093
3094 let array = self.out.new_vreg(gpr);
3095 let load = self.named(teb.array);
3096 self.out.build(block, load).at(span).def(array, gpr).finish();
3097
3098 let reg = self.new_reg(result);
3099 let add = self.named(teb.block);
3100 self.out
3101 .build(block, add)
3102 .at(span)
3103 .operand(mir::Operand::write(reg, gpr))
3104 .operand(mir::Operand::read(array, gpr))
3105 .operand(mir::Operand::read(slot, gpr))
3106 .symbol(symbol)
3107 .finish();
3108 Ok(())
3109 }
3110
3111 /// Refuses the thread pointer where it is not written, which is Mach-O. Apple keeps it in a
3112 /// different register from the one Linux does on both machines, and nothing written for it
3113 /// has been checked on one.
3114 fn threads_written(&self, inst: Inst) -> Result<(), Unsupported> {
3115 if self.elsewhere.described() || self.elsewhere.indexed() {
3116 return Err(Unsupported::Unported { inst: Some(inst), what: Unported::Thread });
3117 }
3118 Ok(())
3119 }
3120
3121 /// The front of this thread's block into `reg`.
3122 ///
3123 /// On x86-64 that is the one thing no instruction can work out: `%fs` is not a register a
3124 /// program can read, and what it points at is a word holding its own address, so reading
3125 /// through it at zero is how the address is come by. AArch64 keeps it in `tpidr_el0`, which
3126 /// `mrs` reads.
3127 fn read_thread_pointer(&mut self, block: mir::Block, span: Span, reg: mir::Reg) {
3128 let gpr = self.gpr;
3129 match self.selector.symbols.pointer {
3130 Pointer::Segment(name, segment) => {
3131 let load = self.named(name);
3132 let at = mir::Mem::in_segment(segment, 0);
3133 self.out.build(block, load).at(span).def(reg, gpr).mem(at).finish();
3134 }
3135 Pointer::Own(name) => {
3136 let read = self.named(name);
3137 self.out.build(block, read).at(span).def(reg, gpr).finish();
3138 }
3139 }
3140 }
3141
3142 /// `&&label`, GNU's address of a label, which is the same `lea` a global gets against a place
3143 /// in this same function.
3144 ///
3145 /// What the two have in common is the whole of the instruction: an address worked out from
3146 /// where the instruction is, which is what `(%rip)` means and is the only way this compiler
3147 /// reaches anything. What they do not have in common is what fills the four bytes in. A
3148 /// global is a name, so the number is a relocation and the linker writes it. A block is a
3149 /// place in this function, so both ends are in one section and the number is known as soon as
3150 /// the blocks have been laid out, which is why `rucc_asm` fills it in the way it fills in a
3151 /// jump rather than leaving a relocation behind.
3152 ///
3153 /// Nothing here says the block is one control can arrive at. That is said by the
3154 /// [`Opcode::IndirectBr`] that reads the address, which lists every block it can arrive at,
3155 /// and by nothing else: an address on its own is a number.
3156 fn block_address(&mut self, inst: Inst) -> Result<(), Unsupported> {
3157 let result = self.source[inst].first_result.ok_or_else(|| self.unsupported(inst))?;
3158 let Some(call) = self.source.successors(inst).next() else {
3159 return Err(self.unsupported(inst));
3160 };
3161 let block = self.at.expect("a block is being filled");
3162 let reg = self.new_reg(result);
3163 let span = self.source.span(inst);
3164 let opcode = self.named(self.selector.jumps.near);
3165 let mem = mir::Mem::block(self.out_block(call.block));
3166 self.out.build(block, opcode).at(span).def(reg, self.gpr).mem(mem).finish();
3167 Ok(())
3168 }
3169
3170 /// `goto *p`, GNU's computed goto, which is a jump through a register.
3171 ///
3172 /// Where it goes is not written here and cannot be. Every block it can arrive at is on the
3173 /// block this ends, the way every other arm is, and which of them the address holds is decided
3174 /// while the program runs. So this is one instruction with one operand, and the arms are
3175 /// copied across by [`Self::edges`] like anybody else's.
3176 fn indirect_branch(&mut self, inst: Inst) -> Result<(), Unsupported> {
3177 let data = &self.source[inst];
3178 let &address = self.source[data.args].first().ok_or_else(|| self.unsupported(inst))?;
3179 let reg = self.reg_of(address)?;
3180 let block = self.at.expect("a block is being filled");
3181 let span = self.source.span(inst);
3182 let name = self.selector.branch.indirect;
3183 let opcode = self.named(name);
3184 self.out.build(block, opcode).at(span).operand(mir::Operand::read(reg, self.gpr)).finish();
3185 Ok(())
3186 }
3187
3188 /// A `switch` on an index from zero up, as a jump through a table of this function.
3189 ///
3190 /// Every `switch` that reaches here is one `crate::switch` left behind on purpose: it has
3191 /// already checked the value is inside the table and taken the lowest case off it, so the
3192 /// operand is a 64 bit index, the cases are the values from zero up with gaps where the
3193 /// program had no case, and the default is only where those gaps go. What is written is the
3194 /// shape gcc writes for the same statement in position independent code:
3195 ///
3196 /// ```text
3197 /// leaq table(%rip), %base
3198 /// movslq (%base,%index,4), %offset
3199 /// addq %base, %offset
3200 /// jmp *%offset
3201 /// ```
3202 ///
3203 /// The table holds distances from itself to each arm rather than addresses, which is what
3204 /// lets it be filled in by the assembler with nothing left for a linker to do. Each cell is
3205 /// stored as the place of an arm among this block's successors, which [`Self::edges`] copies
3206 /// across in the IR's own order, the default first and then one per case. See
3207 /// [`mir::Table`] for why a place and not a block.
3208 fn jump_table(&mut self, inst: Inst) -> Result<(), Unsupported> {
3209 let data = &self.source[inst];
3210 let Extra::Switch(info) = data.extra else { return Err(self.unsupported(inst)) };
3211 let &index = self.source[data.args].first().ok_or_else(|| self.unsupported(inst))?;
3212 let ty = self.source[index].ty;
3213 if ty != Type::int(u64::BITS) {
3214 return Err(self.unsupported(inst));
3215 }
3216 let cases = self.source[self.source[info].cases].to_vec();
3217 let mut cells: Vec<u32> = Vec::new();
3218 for (arm, case) in cases.iter().enumerate() {
3219 let at = usize::try_from(case.signed(ty)).map_err(|_| self.unsupported(inst))?;
3220 if at >= cells.len() {
3221 cells.resize(at + 1, 0);
3222 }
3223 cells[at] = u32::try_from(arm + 1).map_err(|_| self.unsupported(inst))?;
3224 }
3225 let reg = self.reg_of(index)?;
3226 let block = self.at.expect("a block is being filled");
3227 let span = self.source.span(inst);
3228 let gpr = self.gpr;
3229 let table = u32::try_from(self.out.tables.len()).expect("fewer tables than that");
3230
3231 let jumps = self.selector.jumps;
3232
3233 let base = self.out.new_vreg(gpr);
3234 let near = self.named(jumps.near);
3235 self.out.build(block, near).at(span).def(base, gpr).mem(mir::Mem::table(table)).finish();
3236 let offset = self.out.new_vreg(gpr);
3237 let cell =
3238 mir::Mem::at(mir::Operand::read(base, gpr)).indexed(mir::Operand::read(reg, gpr), 4);
3239 let load = self.named(jumps.cell);
3240 self.out.build(block, load).at(span).def(offset, gpr).mem(cell).finish();
3241 // Two address on x86-64, for the reason `thread_pointer` gives.
3242 let to = self.out.new_vreg(gpr);
3243 let add = self.named(jumps.add);
3244 let written = mir::Operand::write(to, gpr);
3245 let written = if jumps.two_address { written.with(Constraint::Reuse(1)) } else { written };
3246 self.out
3247 .build(block, add)
3248 .at(span)
3249 .operand(written)
3250 .operand(mir::Operand::read(offset, gpr))
3251 .operand(mir::Operand::read(base, gpr))
3252 .finish();
3253 let jump = self.named(self.selector.branch.indirect);
3254 let jump =
3255 self.out.build(block, jump).at(span).operand(mir::Operand::read(to, gpr)).finish();
3256 self.out.tables.push(mir::Table { jump, cells });
3257 Ok(())
3258 }
3259
3260 /// `__builtin_setjmp`, which writes down where the function is so that a `__builtin_longjmp`
3261 /// somewhere else can bring control back here, and answers zero on the way past.
3262 ///
3263 /// Four words of the buffer, the three gcc writes and one of this compiler's own, and then the
3264 /// block ends: everything after the save in the IR block is put into a new machine IR block,
3265 /// and the address of that block is what went into the buffer. That is the whole reason the
3266 /// block is split here. An address points at a label, a machine IR block is the only thing in
3267 /// this representation that has one, and a save is in the middle of a block rather than at the
3268 /// end of one.
3269 ///
3270 /// # How the answer gets back
3271 ///
3272 /// Through the frame rather than through a register. The save writes a zero into a word of its
3273 /// own frame, puts the address of that word in the buffer, and the new block reads the word
3274 /// back. The restore writes a one through the address it finds in the buffer before it goes.
3275 /// So one load answers zero on the way past and one on the way back, and neither path has to
3276 /// agree with the other about a register.
3277 ///
3278 /// gcc does it the other way round, with a second block that sets the answer to one and is
3279 /// what the restore arrives at. That block is one nothing in the function jumps to, and a
3280 /// machine IR whose blocks are walked from the entry has nowhere to put such a thing: the
3281 /// allocator lays a function out in the line it is going to be emitted in, and a block no edge
3282 /// reaches is not in that line. The word in the frame costs eight bytes of stack and one load,
3283 /// and it needs nothing said anywhere about a block arrived at from outside.
3284 ///
3285 /// # What the allocator is told
3286 ///
3287 /// That every register it hands out is gone at the end of the first block. That is what makes
3288 /// the rest of the function right on the way back: control arrives from a `__builtin_longjmp`
3289 /// in some other function, and the only two registers that puts back are the stack pointer and
3290 /// the frame pointer, so anything this function still wants has to be in the frame those two
3291 /// reach. It is said with a write of every one of those registers, which is the same thing a
3292 /// call says about the registers a callee may destroy, on an instruction with nothing else on
3293 /// it so that the stores above are not caught up in it.
3294 fn saves_place(&mut self, inst: Inst) -> Result<(), Unsupported> {
3295 let data = &self.source[inst];
3296 let result = data.first_result.ok_or_else(|| self.unsupported(inst))?;
3297 let &buffer = self.source[data.args].first().ok_or_else(|| self.unsupported(inst))?;
3298 let span = self.source.span(inst);
3299 let buf = self.reg_of(buffer)?;
3300 let at = self.at.expect("a block is being filled");
3301 let gpr = self.gpr;
3302 let moves = self.selector.frame.moves(gpr).expect("a class the target says how to move");
3303 let store = self.named(moves.store);
3304 let load = self.named(moves.load);
3305 let lea = self.named(self.selector.frame.lea);
3306 let put = self.named(self.selector.frame.imm);
3307 let nothing =
3308 self.selector.frame.pad.expect("a target with an instruction that does nothing");
3309 let nothing = self.named(nothing);
3310 self.stack.saves_place = true;
3311 let answer = self.answer_slot();
3312 let back = self.out.create_block();
3313
3314 // The zero this answers with, into the word a restore writes a one into.
3315 let zero = self.out.new_vreg(gpr);
3316 self.out.build(at, put).at(span).def(zero, gpr).imm(0).finish();
3317 let mem = self.frame_mem();
3318 let made = self.out.build(at, store).at(span).uses(zero, gpr).mem(mem).finish();
3319 self.stack.addresses.push((made, answer));
3320
3321 // The four words: where that word is, where control comes back to, and the two registers
3322 // the restore puts back.
3323 let found = self.frame_address(at, answer);
3324 self.write_word(at, span, store, found, buf, JUMP_ANSWER);
3325 let pc = self.out.new_vreg(gpr);
3326 self.out.build(at, lea).at(span).def(pc, gpr).mem(mir::Mem::block(back)).finish();
3327 self.write_word(at, span, store, pc, buf, JUMP_PC);
3328 let frame = mir::Reg::physical(self.conv.frame_pointer);
3329 self.write_word(at, span, store, frame, buf, JUMP_FRAME);
3330 let stack = mir::Reg::physical(self.conv.stack_pointer);
3331 self.write_word(at, span, store, stack, buf, JUMP_STACK);
3332
3333 // Nothing is in a register past this point, which is what the rest of the function is
3334 // allowed to assume about the way back in.
3335 let gone = self.across_jump();
3336 let mut build = self.out.build(at, nothing).at(span);
3337 for (reg, class) in gone {
3338 build = build.operand(mir::Operand::write(reg, class));
3339 }
3340 build.finish();
3341
3342 // And the rest of the block, which is the block the address above was of.
3343 *self.out.succs_mut(at) = vec![mir::BlockCall::to(back)];
3344 self.at = Some(back);
3345 let reg = self.new_reg(result);
3346 let mem = self.frame_mem();
3347 let made = self.out.build(back, load).at(span).def(reg, gpr).mem(mem).finish();
3348 self.stack.addresses.push((made, answer));
3349 Ok(())
3350 }
3351
3352 /// `__builtin_longjmp`, which reads a buffer a `__builtin_setjmp` filled in and goes there.
3353 ///
3354 /// Everything comes out of the buffer before anything is put back, and the four registers it
3355 /// comes out into are physical ones rather than values the allocator places. Both of those are
3356 /// about the same moment. The stack pointer is one of the things being put back, a value the
3357 /// allocator sent to the stack is reached through the stack pointer, and between the
3358 /// instruction that moves it and the jump there is no stack this function owns any more. A
3359 /// register named outright is a register nothing reloads into and nothing else is in, which is
3360 /// the only way to hold something across that moment.
3361 ///
3362 /// Four of them because that is how many things are in the air at once: where to go, the frame
3363 /// pointer to put back, the one the matching save is to answer with, and one register used
3364 /// twice, first for the address that one is written through and then for the stack pointer.
3365 ///
3366 /// Nothing after this in the block is reached. The marker is not a terminator, for the reason
3367 /// `spec/08-ir.md` gives, so the block goes on and whatever the front end wrote after it is
3368 /// written out and never run.
3369 fn comes_back(&mut self, inst: Inst) -> Result<(), Unsupported> {
3370 let data = &self.source[inst];
3371 let &buffer = self.source[data.args].first().ok_or_else(|| self.unsupported(inst))?;
3372 let span = self.source.span(inst);
3373 let buf = self.reg_of(buffer)?;
3374 let at = self.at.expect("a block is being filled");
3375 let gpr = self.gpr;
3376 let moves = self.selector.frame.moves(gpr).expect("a class the target says how to move");
3377 let load = self.named(moves.load);
3378 let store = self.named(moves.store);
3379 let mov = self.named(moves.mov);
3380 let put = self.named(self.selector.frame.imm);
3381 let jump = self.named(self.selector.branch.indirect);
3382
3383 let held = self.jump_regs();
3384 if held.len() < JUMP_REGS {
3385 return Err(self.unsupported(inst));
3386 }
3387 let pc = mir::Reg::physical(held[0]);
3388 let frame = mir::Reg::physical(held[1]);
3389 let spare = mir::Reg::physical(held[2]);
3390 let one = mir::Reg::physical(held[3]);
3391
3392 self.read_word(at, span, load, pc, buf, JUMP_PC);
3393 self.read_word(at, span, load, frame, buf, JUMP_FRAME);
3394 self.read_word(at, span, load, spare, buf, JUMP_ANSWER);
3395
3396 // What the matching save answers with, written through the address that came out of the
3397 // buffer, because the word it goes in is in the other function's frame and this one has no
3398 // way of knowing where that is.
3399 self.out.build(at, put).at(span).def(one, gpr).imm(1).finish();
3400 let mem = mir::Mem::at(mir::Operand::read(spare, gpr));
3401 self.out.build(at, store).at(span).uses(one, gpr).mem(mem).finish();
3402
3403 // The stack last of the four, so that the register the buffer is reached through is done
3404 // with before the stack it may have been spilled to stops being this function's.
3405 self.read_word(at, span, load, spare, buf, JUMP_STACK);
3406 let stack = mir::Reg::physical(self.conv.stack_pointer);
3407 self.copy(at, span, mov, stack, spare);
3408 let base = mir::Reg::physical(self.conv.frame_pointer);
3409 self.copy(at, span, mov, base, frame);
3410
3411 // And the jump, which reads the two registers just put back as well as the address it
3412 // goes through. Neither of those is printed, because the target's spelling of an indirect
3413 // jump has one argument and it is the first one read. They are there because the code
3414 // control arrives at reaches its frame through them, and because without them the two
3415 // instructions above write registers nothing reads: a scheduler is then free to put the
3416 // jump in front of them, and at `-O2` it does.
3417 self.out
3418 .build(at, jump)
3419 .at(span)
3420 .operand(mir::Operand::read(pc, gpr))
3421 .operand(mir::Operand::read(stack, gpr))
3422 .operand(mir::Operand::read(base, gpr))
3423 .finish();
3424 Ok(())
3425 }
3426
3427 /// One word of the buffer of a `__builtin_setjmp`, written from a register.
3428 fn write_word(
3429 &mut self,
3430 at: mir::Block,
3431 span: Span,
3432 store: mir::Opcode,
3433 from: mir::Reg,
3434 buf: mir::Reg,
3435 word: i32,
3436 ) {
3437 let mem = mir::Mem::at(mir::Operand::read(buf, self.gpr)).plus(word);
3438 self.out.build(at, store).at(span).uses(from, self.gpr).mem(mem).finish();
3439 }
3440
3441 /// One word of that buffer, read back into a register.
3442 fn read_word(
3443 &mut self,
3444 at: mir::Block,
3445 span: Span,
3446 load: mir::Opcode,
3447 into: mir::Reg,
3448 buf: mir::Reg,
3449 word: i32,
3450 ) {
3451 let mem = mir::Mem::at(mir::Operand::read(buf, self.gpr)).plus(word);
3452 self.out.build(at, load).at(span).def(into, self.gpr).mem(mem).finish();
3453 }
3454
3455 /// One register into another, which is the one shape of instruction the builder has no word
3456 /// for because neither operand is a definition of a value or a read of memory.
3457 fn copy(
3458 &mut self,
3459 at: mir::Block,
3460 span: Span,
3461 mov: mir::Opcode,
3462 into: mir::Reg,
3463 from: mir::Reg,
3464 ) {
3465 self.out
3466 .build(at, mov)
3467 .at(span)
3468 .operand(mir::Operand::write(into, self.gpr))
3469 .operand(mir::Operand::read(from, self.gpr))
3470 .finish();
3471 }
3472
3473 /// The word a `__builtin_setjmp` in this function answers with, asked for once and kept.
3474 fn answer_slot(&mut self) -> usize {
3475 match self.answer {
3476 Some(index) => index,
3477 None => {
3478 let index = self.stack.locals.len();
3479 self.stack.locals.push(Local { size: JUMP_WORD, align: JUMP_WORD });
3480 self.answer = Some(index);
3481 index
3482 }
3483 }
3484 }
3485
3486 /// An address in this function's frame with nothing in its displacement, which is what an
3487 /// instruction reaching one of its stack objects is written with until [`crate::finish`] knows
3488 /// where the object is.
3489 fn frame_mem(&self) -> mir::Mem {
3490 mir::Mem::at(mir::Operand::read(mir::Reg::physical(self.conv.stack_pointer), self.gpr))
3491 }
3492
3493 /// Every register the allocator hands out, which is what a `__builtin_setjmp` destroys.
3494 ///
3495 /// Both files, since a `double` live across a save has the same problem an integer does. The
3496 /// two registers a frame is reached through are not here: the restore puts both of them back,
3497 /// which is the whole of what it puts back, and a function whose frame pointer was destroyed
3498 /// by its own save would have nothing left to find its caller with.
3499 fn across_jump(&self) -> Vec<(mir::Reg, RegClass)> {
3500 let mut gone = Vec::new();
3501 for ® in self.conv.int_order {
3502 if reg == self.conv.stack_pointer || reg == self.conv.frame_pointer {
3503 continue;
3504 }
3505 gone.push((mir::Reg::physical(reg), self.gpr));
3506 }
3507 for ® in self.conv.sse_order {
3508 gone.push((mir::Reg::physical(reg), self.conv.sse_class));
3509 }
3510 gone
3511 }
3512
3513 /// The registers a `__builtin_longjmp` may hold things in while it puts a frame back.
3514 ///
3515 /// The ones the allocator hands out, less the two a frame is reached through. The scratch
3516 /// registers are not among them on purpose: the rewriter writes a reload into one of those
3517 /// wherever it likes, and one of these has to survive from the load that fills it to the
3518 /// instruction that reads it however many instructions apart those are.
3519 fn jump_regs(&self) -> Vec<PhysReg> {
3520 self.conv
3521 .int_order
3522 .iter()
3523 .copied()
3524 .filter(|®| {
3525 reg != self.conv.stack_pointer
3526 && reg != self.conv.frame_pointer
3527 && !self.selector.scratch.contains(®)
3528 })
3529 .collect()
3530 }
3531
3532 /// A machine opcode of this target from the name the target gives it.
3533 fn named(&mut self, name: &str) -> mir::Opcode {
3534 mir::Opcode::new(self.names.intern(&format!("{}{name}", self.selector.prefix())))
3535 }
3536
3537 /// `__builtin_frame_address` and `__builtin_return_address`, which are a walk up the chain of
3538 /// saved frame pointers and then one thing read at the end of it.
3539 ///
3540 /// Every frame that kept a frame pointer holds the caller's at the address the register points
3541 /// at, and the address that frame returns to one word above that, which is where the call
3542 /// instruction put it and where the prologue's push left it. So the walk is a load through the
3543 /// register for each link, the frame address is wherever the walk stopped, and the return
3544 /// address is one more load from a word above it. gcc 16.2.0 writes exactly this, measured on
3545 /// x86-64 at `-O2` for depths zero to three of both builtins.
3546 ///
3547 /// The function is given a frame pointer because of this, which is what [`Stack::walks_frames`]
3548 /// carries out to the layout. A depth of zero needs it as the answer and every depth above zero
3549 /// needs it as the start, so there is no case here where it is not wanted.
3550 ///
3551 /// How far the chain actually reaches is the program's business and not this one's. A caller
3552 /// compiled without a frame pointer has no link in it for the walk to follow, so a depth above
3553 /// zero is a promise about how the whole program was built. That is why gcc documents a nonzero
3554 /// depth as unsafe rather than as an answer, and why the depth is refused above a limit in
3555 /// `check/builtin/frame.rs` rather than walked as far as it says.
3556 fn frames(&mut self, inst: Inst) -> Result<(), Unsupported> {
3557 let data = &self.source[inst];
3558 let Extra::Depth(depth) = data.extra else { return Err(self.unsupported(inst)) };
3559 let result = data.first_result.ok_or_else(|| self.unsupported(inst))?;
3560 let returning = data.opcode == Opcode::ReturnAddress;
3561 let block = self.at.expect("a block is being filled");
3562 let span = self.source.span(inst);
3563 let moves =
3564 self.selector.frame.moves(self.gpr).expect("a class the target says how to move");
3565 let load = self.named(moves.load);
3566 self.stack.walks_frames = true;
3567
3568 // Where the walk is up to. The frame pointer to begin with, and the register the last load
3569 // wrote after that.
3570 let reg = self.new_reg(result);
3571 let mut base = mir::Reg::physical(self.conv.frame_pointer);
3572 for link in 0..depth {
3573 // The last load of a walk that is looking for a frame writes the answer itself, which
3574 // is what keeps a walk of so many links that many instructions and not one more.
3575 let ends_here = link + 1 == depth && !returning;
3576 let next = if ends_here { reg } else { self.out.new_vreg(self.gpr) };
3577 let at = mir::Mem::at(mir::Operand::read(base, self.gpr));
3578 self.out.build(block, load).at(span).def(next, self.gpr).mem(at).finish();
3579 base = next;
3580 }
3581
3582 if returning {
3583 let up = i32::try_from(self.conv.return_address).expect("a word above the frame");
3584 let at = mir::Mem::at(mir::Operand::read(base, self.gpr)).plus(up);
3585 self.out.build(block, load).at(span).def(reg, self.gpr).mem(at).finish();
3586 } else if depth == 0 {
3587 // The one case with no load in it at all: the frame this function is running in is the
3588 // register itself, and a physical register is not one the allocator hands out, so the
3589 // answer is a copy of it.
3590 let mov = self.named(moves.mov);
3591 self.out
3592 .build(block, mov)
3593 .at(span)
3594 .operand(mir::Operand::write(reg, self.gpr))
3595 .operand(mir::Operand::read(base, self.gpr))
3596 .finish();
3597 }
3598 Ok(())
3599 }
3600
3601 /// `__builtin_thread_pointer`, which is the front of the block [`Self::thread_address`] adds
3602 /// an offset to.
3603 ///
3604 /// The same one instruction, on its own this time and with nothing to add to it. A program
3605 /// writes this when what it wants is a number that is different in every thread and cheap to
3606 /// come by, rather than a variable of its own in the block, so there is no relocation here and
3607 /// no name for the link to resolve.
3608 fn thread_pointer(&mut self, inst: Inst) -> Result<(), Unsupported> {
3609 self.threads_written(inst)?;
3610 let result = self.source[inst].first_result.ok_or_else(|| self.unsupported(inst))?;
3611 let block = self.at.expect("a block is being filled");
3612 let span = self.source.span(inst);
3613 let reg = self.new_reg(result);
3614 self.read_thread_pointer(block, span, reg);
3615 Ok(())
3616 }
3617
3618 /// `__builtin_sponentry`, the stack pointer this function was entered with.
3619 ///
3620 /// On AArch64 that is where the caller's arguments on the stack start, so it is the address
3621 /// of the first of them, recorded at zero the way [`Self::overflow`] records the first one the
3622 /// signature did not name and finished with the rest once the frame is laid out. Sema refuses
3623 /// the builtin on every other machine, and this does too, since on x86-64 the return address
3624 /// sits between the two and zero would be the wrong answer.
3625 fn sp_entry(&mut self, inst: Inst) -> Result<(), Unsupported> {
3626 if !self.on_aarch64() {
3627 return Err(self.unsupported(inst));
3628 }
3629 let result = self.source[inst].first_result.ok_or_else(|| self.unsupported(inst))?;
3630 let block = self.at.expect("a block is being filled");
3631 let span = self.source.span(inst);
3632 let reg = self.new_reg(result);
3633 let lea = self.named(self.selector.frame.lea);
3634 let sp = mir::Operand::read(mir::Reg::physical(self.conv.stack_pointer), self.gpr);
3635 let made =
3636 self.out.build(block, lea).at(span).def(reg, self.gpr).mem(mir::Mem::at(sp)).finish();
3637 self.stack.arguments.push((made, 0));
3638 Ok(())
3639 }
3640
3641 /// What a named machine register holds, which is `register long x asm ("rbx");`.
3642 ///
3643 /// One move out of that register, with the register named as itself the way a register a
3644 /// template wrote is named, which is [`Self::itself`] and is the thing #1653 built. What it
3645 /// buys here is what it buys there: the register is part of the instruction the allocator
3646 /// sees, so it is a use the allocator will not have written over first, and the value goes
3647 /// into an ordinary one of its own that everything downstream reads.
3648 ///
3649 /// The whole sixty four bits are moved whatever the type is, because the register is that
3650 /// wide and a narrower type reads the low end of the copy, which is the same low end. A type
3651 /// wider than the register is refused, since there is no register holding it to read. On
3652 /// AArch64 a float may be kept in a vector register, `register double x asm ("d8");`, and it is
3653 /// moved out of that file the same way.
3654 ///
3655 /// A name the machine has not got is refused too, and is the only thing that can be wrong
3656 /// with the string: which register a name means is this machine's question and this is where
3657 /// the question is asked, at the same table `asm` asks about clobbers at. The sigil gcc
3658 /// allows in front of it is taken off here, because what the name is written with is syntax.
3659 fn register_value(&mut self, inst: Inst) -> Result<(), Unsupported> {
3660 let Extra::Symbol(symbol) = self.source[inst].extra else {
3661 return Err(self.unsupported(inst));
3662 };
3663 let result = self.source[inst].first_result.ok_or_else(|| self.unsupported(inst))?;
3664 let ty = self.source[result].ty;
3665 let bits = if ty.is_ptr() { ADDRESS_BITS } else { ty.bits() };
3666 if bits > ADDRESS_BITS {
3667 return Err(self.unsupported(inst));
3668 }
3669 let spelled = self.names.resolve(symbol).to_owned();
3670 let bare = spelled.strip_prefix('%').unwrap_or(&spelled);
3671 let named = if self.on_aarch64() {
3672 aarch64::named(bare)
3673 } else if self.class_of(ty) != self.gpr {
3674 return Err(self.unsupported(inst));
3675 } else {
3676 x86_64::gpr_named(bare).map(|(reg, _)| (reg, self.gpr))
3677 };
3678 let Some((held, file)) = named else {
3679 return Err(Unsupported::Register { inst, name: spelled });
3680 };
3681 // A float in a general purpose register, or a number in a vector one, is a register the
3682 // machine has holding a type that is not kept there, and would need a move between the
3683 // files that nothing here makes yet.
3684 if on_x87(ty) || self.class_of(ty) != file {
3685 return Err(self.unsupported(inst));
3686 }
3687 let block = self.at.expect("a block is being filled");
3688 let span = self.source.span(inst);
3689 let mov = self.selector.frame.moves(file).expect("a class the target says how to move").mov;
3690 let mov = self.named(mov);
3691 let into = self.new_reg(result);
3692 self.out
3693 .build(block, mov)
3694 .at(span)
3695 .operand(mir::Operand::write(into, file))
3696 .operand(
3697 mir::Operand::read(mir::Reg::physical(held), file).with(Constraint::Fixed(held)),
3698 )
3699 .finish();
3700 Ok(())
3701 }
3702
3703 /// A conversion that converts nothing: the result is the operand under another type.
3704 ///
3705 /// `ptrtoint` and `inttoptr` at one width are the whole of this. An address on this machine is
3706 /// an integer as wide as the machine addresses, so a cast between the two changes what the
3707 /// type system calls the value and changes nothing about the value, and the register holding
3708 /// it is the register that already held it. The front end never writes either of them at any
3709 /// other width, because it widens or narrows around the cast rather than through it, so the
3710 /// two widths disagreeing here means the IR came from somewhere else and is refused rather
3711 /// than guessed at.
3712 ///
3713 /// Reading the operand first is what materializes it when it is a constant, which is the case
3714 /// that matters: a null pointer is an `inttoptr` of zero, and that zero has to reach a
3715 /// register before anything can call it an address.
3716 fn rename(&mut self, inst: Inst) -> Result<(), Unsupported> {
3717 let data = &self.source[inst];
3718 let [arg] = self.source[data.args] else { return Err(self.unsupported(inst)) };
3719 let result = data.first_result.ok_or_else(|| self.unsupported(inst))?;
3720 if !self.is_address_width(self.source[arg].ty)
3721 || !self.is_address_width(self.source[result].ty)
3722 {
3723 return Err(self.unsupported(inst));
3724 }
3725 let reg = self.reg_of(arg)?;
3726 self.regs[result.index()] = Some(reg);
3727 Ok(())
3728 }
3729
3730 /// One barrier, which on this machine is one instruction at the strongest ordering and no
3731 /// instruction at all at every other one.
3732 ///
3733 /// x86-64 is total store order, so the only reordering the machine does is a store followed by
3734 /// a load of a different address, and the only ordering that forbids that is sequential
3735 /// consistency. An acquire, a release and an acquire release fence are therefore already true
3736 /// of every program running here, and what a program wanted from writing one is that the
3737 /// compiler not move memory accesses across it. The optimizer has finished by the time this
3738 /// runs and nothing below reorders one access past another, so the constraint is already
3739 /// discharged and there is nothing to write.
3740 ///
3741 /// The strongest one is `mfence`, which is what gcc 16.2.0 writes for
3742 /// `__atomic_thread_fence(__ATOMIC_SEQ_CST)` and for `__sync_synchronize`. A locked instruction
3743 /// on the stack is faster on most parts and is what some compilers write instead; it is also a
3744 /// write to memory the program did not ask for, and the plain barrier is the one that says what
3745 /// it means.
3746 ///
3747 /// Written here by name rather than by a rule, for the same reason a `lea` of a symbol is:
3748 /// there is nothing in a barrier that a proof over bitvectors could discharge. It computes
3749 /// nothing, so there is no equality to state, and what makes it the right answer is the memory
3750 /// model, which the rule language cannot talk about.
3751 fn barrier(&mut self, inst: Inst) -> Result<(), Unsupported> {
3752 let Extra::Order(order) = self.source[inst].extra else {
3753 return Err(self.unsupported(inst));
3754 };
3755 // AArch64 is not total store order, so every ordering above relaxed is an instruction
3756 // there. An acquire fence only has to keep later accesses after earlier loads, which is
3757 // `dmb ishld`, and everything stronger is the full `dmb ish` gcc writes for it.
3758 let name = match order {
3759 MemOrder::NotAtomic | MemOrder::Relaxed => return Ok(()),
3760 MemOrder::Acquire if self.on_aarch64() => "fence_acquire",
3761 _ if self.on_aarch64() => self.selector.fence,
3762 MemOrder::SeqCst => self.selector.fence,
3763 _ => return Ok(()),
3764 };
3765 let block = self.at.expect("a block is being filled");
3766 let span = self.source.span(inst);
3767 let fence = self.named(name);
3768 self.out.build(block, fence).at(span).finish();
3769 Ok(())
3770 }
3771
3772 /// The instruction a program stops on, which is one byte pair and no operands.
3773 ///
3774 /// `ud2` is an opcode the manual promises will never be given a meaning, so a processor that
3775 /// reaches it raises the fault for an instruction it does not know, and on Linux that arrives
3776 /// at the program as `SIGILL`. That is what `__builtin_trap` is for: a stop that cannot be
3777 /// caught by anything the program installed for an ordinary error, cannot be returned from,
3778 /// and leaves the address of the fault in the core file.
3779 ///
3780 /// Why not a call to `abort`. It is two bytes against a call and a relocation, it needs no
3781 /// library, and it works in the places this one is written most, which are a kernel and a
3782 /// freestanding program that has no `abort` to call. gcc 16.2.0 writes `ud2` here too.
3783 fn trap(&mut self, inst: Inst) {
3784 let block = self.at.expect("a block is being filled");
3785 let span = self.source.span(inst);
3786 let stop = self.named(self.selector.trap);
3787 self.out.build(block, stop).at(span).finish();
3788 }
3789
3790 /// One hint that an address is about to be used, which is one instruction and no promise.
3791 ///
3792 /// Four instructions on this machine and the locality picks between them, which is what the
3793 /// number means: how much of the data will still be wanted after the access. None of it wanted
3794 /// is `prefetchnta`, which brings the line in without keeping it, and all of it wanted is
3795 /// `prefetcht0`, which brings it as close as the machine can. The two in between are the levels
3796 /// between those. Measured against gcc 16.2.0 on x86-64 rather than read off the manual: zero
3797 /// gives `prefetchnta`, one `prefetcht2`, two `prefetcht1` and three `prefetcht0`.
3798 ///
3799 /// Whether the access will write is not read on x86-64, and that is the machine rather than an
3800 /// omission. The write hint is `prefetchw`, which is not in the base instruction set, and gcc
3801 /// writes it only when the command line said the part has it. So a prefetch for a write is the
3802 /// same instruction as a prefetch for a read, which is what gcc 16.2.0 writes without
3803 /// `-mprfchw`. AArch64 has it in the base set, so there a write picks the four `pst` forms of
3804 /// `prfm` in place of the `pld` ones, at the same levels.
3805 ///
3806 /// The address goes in the addressing mode rather than in an operand, the way a store's does.
3807 /// It is built here as the plainest one there is, a register and nothing else, because what
3808 /// arrives is a value and folding an addition into the mode is a rule's job and no rule reaches
3809 /// this instruction. An address the program computed is therefore one `lea` or one add in front
3810 /// of this, which is what it would have been for the load the hint is about anyway.
3811 fn hint(&mut self, inst: Inst) -> Result<(), Unsupported> {
3812 let Extra::Prefetch(hint) = self.source[inst].extra else {
3813 return Err(self.unsupported(inst));
3814 };
3815 let args: Vec<Value> = self.source[self.source[inst].args].to_vec();
3816 let [address] = args[..] else { return Err(self.unsupported(inst)) };
3817 // AArch64 has the write hint in the base instruction set, and gcc 16.2.0 writes it there.
3818 let write = hint.write && self.on_aarch64();
3819 let name = match (hint.locality, write) {
3820 (0, false) => "prefetch_nta",
3821 (1, false) => "prefetch_t2",
3822 (2, false) => "prefetch_t1",
3823 (PrefetchHint::MOST, false) => "prefetch_t0",
3824 (0, true) => "prefetch_w_nta",
3825 (1, true) => "prefetch_w_t2",
3826 (2, true) => "prefetch_w_t1",
3827 (PrefetchHint::MOST, true) => "prefetch_w_t0",
3828 // Nothing else exists. The checker reads a locality outside the range as zero and the
3829 // verifier refuses one that got here another way, so this is a hint that was built
3830 // rather than checked, and the safe answer for a hint is to write no instruction.
3831 _ => return Err(self.unsupported(inst)),
3832 };
3833 let base = self.reg_of(address)?;
3834 let block = self.at.expect("a block is being filled");
3835 let opcode = self.named(name);
3836 self.out
3837 .build(block, opcode)
3838 .at(self.source.span(inst))
3839 .mem(mir::Mem::at(mir::Operand::read(base, self.gpr)))
3840 .finish();
3841 Ok(())
3842 }
3843
3844 /// One compare and exchange, which is the instruction every other atomic on this machine is
3845 /// built out of.
3846 ///
3847 /// What the IR asks for is: read what is at an address, compare it against a value the program
3848 /// expected, put a second value there if the two were equal, and say both what was read and
3849 /// whether the exchange happened. The machine has exactly that instruction, and the `lock` in
3850 /// front of it is what makes the whole of it one step as far as every other processor is
3851 /// concerned.
3852 ///
3853 /// The ordering is not read here, and that is the memory model rather than an omission. A
3854 /// locked instruction on x86-64 is a full barrier whatever the program asked for, so a relaxed
3855 /// compare and exchange and a sequentially consistent one are the same instruction, and there
3856 /// is nothing weaker to emit for the weaker orderings. The failure ordering is not read for the
3857 /// same reason.
3858 ///
3859 /// The two values it produces are why this is written by name. The one the program compares
3860 /// against and the one it gets back are both `rax`, which the instruction reads and writes
3861 /// without being told, and the table says so with a fixed constraint at each end rather than
3862 /// leaving the allocator to find out. The second value is the byte behind it, which is the zero
3863 /// flag read out by a `sete`, and it is a definition of the same instruction so that the
3864 /// allocator knows the two are live together and never gives the byte the register the answer
3865 /// is in.
3866 fn exchange(&mut self, inst: Inst) -> Result<(), Unsupported> {
3867 let args: Vec<Value> = self.source[self.source[inst].args].to_vec();
3868 let results: Vec<Value> = self.source[inst].results().collect();
3869 let [addr, expected, desired] = args[..] else { return Err(self.unsupported(inst)) };
3870 let [old, exchanged] = results[..] else { return Err(self.unsupported(inst)) };
3871 if self.on_aarch64() {
3872 return self.exchange_a64(inst, [addr, expected, desired], [old, exchanged]);
3873 }
3874
3875 // A value the machine can compare in one instruction, which is an integer or an address at
3876 // one of the four widths it has a compare and exchange for. Anything else is a type this
3877 // has no instruction for rather than a program that is wrong, and the front end refuses it
3878 // before ever getting here.
3879 let ty = self.source[old].ty;
3880 let bits = if ty.is_ptr() { ADDRESS_BITS } else { ty.bits() };
3881 if (!ty.is_int() && !ty.is_ptr()) || !matches!(bits, 8 | 16 | 32 | 64) {
3882 return Err(self.unsupported(inst));
3883 }
3884
3885 let base = self.reg_of(addr)?;
3886 let want = self.reg_of(expected)?;
3887 let put = self.reg_of(desired)?;
3888 let got = self.new_reg(old);
3889 let flag = self.new_reg(exchanged);
3890
3891 let name = format!("cmpxchg_{bits}");
3892 let descs = self.selector.operands(&name).ok_or_else(|| self.unsupported(inst))?;
3893 let block = self.at.expect("a block is being filled");
3894 let opcode = self.named(&name);
3895 let (span, flags) = (self.source.span(inst), self.carried(inst));
3896 let mut build = self.out.build(block, opcode).at(span).flags(flags);
3897 for (desc, reg) in descs.iter().zip([got, flag, want, put]) {
3898 let operand = mir::Operand {
3899 reg,
3900 class: desc.class,
3901 role: desc.role,
3902 constraint: desc.constraint,
3903 };
3904 build = build.operand(operand);
3905 }
3906 build.mem(mir::Mem::at(mir::Operand::read(base, self.gpr))).finish();
3907 Ok(())
3908 }
3909
3910 /// One read modify write, for the three operations this machine does in a single instruction.
3911 ///
3912 /// What the IR asks for is: read what is at an address, do something to it, put the answer back,
3913 /// say what was there before, and let nothing get between the three steps. The machine has
3914 /// `xchg` for putting a value there and `lock xadd` for adding one, and both leave what they
3915 /// found in the register the operand arrived in, which is why the value that comes back and the
3916 /// value that went in are one register here.
3917 ///
3918 /// A subtraction is the add over the negated operand, which is right at every width because the
3919 /// machine's arithmetic wraps and negating then adding is subtracting in two's complement
3920 /// whatever the operands were. The negate is a separate instruction in front, over a register of
3921 /// its own, so that the value the program handed over is not the one written on: an operand may
3922 /// be live after this and a program that read it again would read the negation.
3923 ///
3924 /// The ordering is not read, for the reason the compare and exchange beside this does not read
3925 /// it. `xchg` with memory locks the bus whether it is asked to or not and `lock xadd` is asked
3926 /// to, so both are full barriers on this machine and there is nothing weaker to fall to.
3927 ///
3928 /// Eight of the other ten never arrive, because `crate::retry` turned each of them into a loop
3929 /// around a compare and exchange before anything here saw it. The two that do arrive are the
3930 /// ones on floating values, and they are refused: a compare and exchange of a float wants the
3931 /// value carried through an integer of the same width, and an eighty bit float has no such
3932 /// width. Neither family of builtins can write one yet either, so a program that reaches this
3933 /// refusal is a program that reached an unimplemented builtin first.
3934 fn modify(&mut self, inst: Inst) -> Result<(), Unsupported> {
3935 let Extra::Rmw(op, _) = self.source[inst].extra else {
3936 return Err(self.unsupported(inst));
3937 };
3938 let args: Vec<Value> = self.source[self.source[inst].args].to_vec();
3939 let [addr, operand] = args[..] else { return Err(self.unsupported(inst)) };
3940 let old = self.source[inst].first_result.ok_or_else(|| self.unsupported(inst))?;
3941
3942 // A value the machine can exchange in one instruction, which is an integer at one of the
3943 // four widths it has these for. A pointer arrives as an address, so it is an integer by the
3944 // time it is here, and anything else is a type this has no instruction for.
3945 let ty = self.source[old].ty;
3946 if !ty.is_int() || !matches!(ty.bits(), 8 | 16 | 32 | 64) {
3947 return Err(self.unsupported(inst));
3948 }
3949 if self.on_aarch64() {
3950 return self.modify_a64(inst, op, [addr, operand], old);
3951 }
3952 let name = match op {
3953 RmwOp::Xchg => format!("xchg_{}", ty.bits()),
3954 RmwOp::Add | RmwOp::Sub => format!("xadd_{}", ty.bits()),
3955 _ => return Err(self.unsupported(inst)),
3956 };
3957
3958 let base = self.reg_of(addr)?;
3959 let mut put = self.reg_of(operand)?;
3960 let block = self.at.expect("a block is being filled");
3961 let span = self.source.span(inst);
3962 if op == RmwOp::Sub {
3963 let negated = self.out.new_vreg(self.gpr);
3964 let negate = self.named(&format!("neg_r_{}", ty.bits()));
3965 let descs = self
3966 .selector
3967 .operands(&format!("neg_r_{}", ty.bits()))
3968 .ok_or_else(|| self.unsupported(inst))?;
3969 let mut build = self.out.build(block, negate).at(span);
3970 for (desc, reg) in descs.iter().zip([negated, put]) {
3971 build = build.operand(mir::Operand {
3972 reg,
3973 class: desc.class,
3974 role: desc.role,
3975 constraint: desc.constraint,
3976 });
3977 }
3978 build.finish();
3979 put = negated;
3980 }
3981
3982 let got = self.new_reg(old);
3983 let descs = self.selector.operands(&name).ok_or_else(|| self.unsupported(inst))?;
3984 let opcode = self.named(&name);
3985 let flags = self.carried(inst);
3986 let mut build = self.out.build(block, opcode).at(span).flags(flags);
3987 for (desc, reg) in descs.iter().zip([got, put]) {
3988 build = build.operand(mir::Operand {
3989 reg,
3990 class: desc.class,
3991 role: desc.role,
3992 constraint: desc.constraint,
3993 });
3994 }
3995 build.mem(mir::Mem::at(mir::Operand::read(base, self.gpr))).finish();
3996 Ok(())
3997 }
3998
3999 /// The width an AArch64 atomic works at, which is an integer or an address of one of the four
4000 /// widths the exclusive loads and stores have. Anything else is refused.
4001 fn atomic_bits(&self, inst: Inst, ty: Type) -> Result<u32, Unsupported> {
4002 let bits = if ty.is_ptr() { ADDRESS_BITS } else { ty.bits() };
4003 if (!ty.is_int() && !ty.is_ptr()) || !matches!(bits, 8 | 16 | 32 | 64) {
4004 return Err(self.unsupported(inst));
4005 }
4006 Ok(bits)
4007 }
4008
4009 /// One instruction by name, with its operands in the order the table lists them.
4010 fn written_as(&mut self, inst: Inst, name: &str, regs: &[mir::Reg]) -> Result<(), Unsupported> {
4011 let descs = self.selector.operands(name).ok_or_else(|| self.unsupported(inst))?;
4012 if descs.len() != regs.len() {
4013 return Err(self.unsupported(inst));
4014 }
4015 let block = self.at.expect("a block is being filled");
4016 let opcode = self.named(name);
4017 let (span, flags) = (self.source.span(inst), self.carried(inst));
4018 let mut build = self.out.build(block, opcode).at(span).flags(flags);
4019 for (desc, ®) in descs.iter().zip(regs) {
4020 build = build.operand(mir::Operand {
4021 reg,
4022 class: desc.class,
4023 role: desc.role,
4024 constraint: desc.constraint,
4025 });
4026 }
4027 build.finish();
4028 Ok(())
4029 }
4030
4031 /// An acquiring load or a releasing store on AArch64, which is `ldar` or `stlr`.
4032 ///
4033 /// Only a relaxed access became the plain one above this, so what arrives is acquire or
4034 /// stronger for a load and release or stronger for a store. `ldar` and `stlr` are also
4035 /// sequentially consistent with each other, which is why the strongest ordering needs no fence
4036 /// on either side, and is what gcc 16.2.0 writes for all of them.
4037 fn ordered(&mut self, inst: Inst) -> Result<(), Unsupported> {
4038 let args: Vec<Value> = self.source[self.source[inst].args].to_vec();
4039 if self.source[inst].opcode == Opcode::AtomicLoad {
4040 let [addr] = args[..] else { return Err(self.unsupported(inst)) };
4041 let result = self.source[inst].first_result.ok_or_else(|| self.unsupported(inst))?;
4042 let bits = self.atomic_bits(inst, self.source[result].ty)?;
4043 let base = self.reg_of(addr)?;
4044 let got = self.new_reg(result);
4045 return self.written_as(inst, &format!("ldar_{bits}"), &[got, base]);
4046 }
4047 let [value, addr] = args[..] else { return Err(self.unsupported(inst)) };
4048 let bits = self.atomic_bits(inst, self.source[value].ty)?;
4049 let put = self.reg_of(value)?;
4050 let base = self.reg_of(addr)?;
4051 self.written_as(inst, &format!("stlr_{bits}"), &[put, base])
4052 }
4053
4054 /// A compare and exchange on AArch64, which is a loop of an exclusive load and store.
4055 ///
4056 /// The loop is one instruction as far as everything below is concerned, so that nothing can
4057 /// be spilled or reloaded between the two exclusive accesses, which would lose the reservation
4058 /// on some parts every time. Its definitions are all early, since they are written before the
4059 /// last read. The acquiring and releasing forms are used whatever the ordering, which is what
4060 /// gcc writes at the strongest one and is never wrong at a weaker one. The yes or no comes out
4061 /// of the status register the store wrote, read as a flag after the loop.
4062 fn exchange_a64(
4063 &mut self,
4064 inst: Inst,
4065 [addr, expected, desired]: [Value; 3],
4066 [old, exchanged]: [Value; 2],
4067 ) -> Result<(), Unsupported> {
4068 let bits = self.atomic_bits(inst, self.source[old].ty)?;
4069 let base = self.reg_of(addr)?;
4070 let want = self.reg_of(expected)?;
4071 let put = self.reg_of(desired)?;
4072 let got = self.new_reg(old);
4073 let flag = self.new_reg(exchanged);
4074 self.written_as(inst, &format!("cmpxchg_{bits}"), &[got, flag, base, want, put])
4075 }
4076
4077 /// A read modify write on AArch64, for the three operations that reach here, each a loop of
4078 /// an exclusive load and store for the reason the compare and exchange above is.
4079 fn modify_a64(
4080 &mut self,
4081 inst: Inst,
4082 op: RmwOp,
4083 [addr, operand]: [Value; 2],
4084 old: Value,
4085 ) -> Result<(), Unsupported> {
4086 let bits = self.atomic_bits(inst, self.source[old].ty)?;
4087 let base = self.reg_of(addr)?;
4088 let put = self.reg_of(operand)?;
4089 let got = self.new_reg(old);
4090 let status = self.out.new_vreg(self.gpr);
4091 match op {
4092 RmwOp::Xchg => {
4093 self.written_as(inst, &format!("xchg_{bits}"), &[got, status, base, put])
4094 }
4095 RmwOp::Add | RmwOp::Sub => {
4096 let name = if op == RmwOp::Add { "xadd" } else { "xsub" };
4097 let new = self.out.new_vreg(self.gpr);
4098 self.written_as(inst, &format!("{name}_{bits}"), &[got, new, status, base, put])
4099 }
4100 _ => Err(self.unsupported(inst)),
4101 }
4102 }
4103
4104 /// One `asm` statement.
4105 ///
4106 /// An empty template is most of the inline assembly in a test suite, and it is not a corner
4107 /// case somebody wrote by accident. A program that wants a value computed where it stands, or a
4108 /// loop the optimizer must not touch, writes `asm volatile ("" : : : "memory")`, and forty
4109 /// years of bug reports about optimizers are full of them. What such a statement asks for is
4110 /// the barrier and the operand places, and no instructions at all.
4111 ///
4112 /// So the operands are the half that is always real: a constraint says where a value has to be,
4113 /// and where it has to be is still true when the template between them is empty.
4114 ///
4115 /// What the constraints ask for, on an empty template, is only ever that two operands share a
4116 /// place. Nothing reads a register no text names, so `"r"` on its own asks for a register and
4117 /// no particular one, and any register at all answers it. A matching constraint is different,
4118 /// because it says the output the assembly leaves is the place the input arrived in, and with
4119 /// no instructions between them that is the input unchanged. So it is a rename and not a move:
4120 /// the value is already in a register and the result is that register.
4121 ///
4122 /// An output nothing is tied to and no instruction writes is whatever the assembly left there,
4123 /// which for a template that writes nothing is whatever was in the register. That is a value
4124 /// the program is not entitled to, and this writes a zero rather than reading one, because the
4125 /// allocator has to be given a definition before a use whatever the program is entitled to.
4126 ///
4127 /// # A template with instructions in it
4128 ///
4129 /// [`x86_64::read`] turns the text into the opcodes this backend already has, which is what
4130 /// `spec/11-asm-objects-debug.md` section 11.1 asks for: the machine is described once, and an
4131 /// instruction a program wrote is looked up in that description rather than copied through to
4132 /// an assembler that has one of its own. So nothing here assembles anything. What it does is
4133 /// put the statement's operands where the opcode holds them, and from there an `asm` statement
4134 /// is ordinary machine code: the allocator picks the registers, the listing and the object file
4135 /// are written from the same table as every other instruction, and a spill around one works
4136 /// because there is nothing left about it for a spill to get wrong.
4137 ///
4138 /// A register the template named in its own text is the one thing in there that is nobody's
4139 /// operand, and it is placed as itself. See [`Self::itself`] for why that is safer here than
4140 /// the thing gcc does, which is to copy the name out and leave the allocator none the wiser.
4141 ///
4142 /// Two things are refused, both for one reason, which is that placing them by a guess gives a
4143 /// program that assembles into something other than what it says.
4144 ///
4145 /// An output the template writes more than once, which is one place with two definitions in it,
4146 /// and the machine IR between here and the allocator has one definition per register by
4147 /// construction. An output tied to an input and written once is not that: it is two registers
4148 /// the description ties together, which is what [`Place`] is about.
4149 ///
4150 /// An operand read where the opcode writes, or written where it reads. An output that has not
4151 /// been written yet is not a value, and an input the assembly writes over is a value something
4152 /// else may still be using.
4153 ///
4154 /// # A register the instruction uses without being told
4155 ///
4156 /// An instruction may reach a register its text does not name, and `cpuid` is all of them at
4157 /// once: the leaf goes in `eax`, the subleaf in `ecx`, and the answer comes back in all four
4158 /// registers. The description holds every bit of that already, so what is left is to say which
4159 /// of the statement's operands is in each of those registers, and the constraint letter is the
4160 /// one thing in an assembly statement that says it. `"=a"` is an output in `rax` and `"c"` is
4161 /// an input in `rcx`, which is why a program writing `cpuid` writes its constraints that way
4162 /// and has no choice about it.
4163 ///
4164 /// A register no letter named is one the statement put nothing in, and that is the usual case
4165 /// rather than an unusual one, since an instruction that answers four questions is written by
4166 /// programs that asked one. A write of one is the register being destroyed and gets a register
4167 /// of its own, which is what tells the allocator to keep everything else out of it. A read of
4168 /// one is a register the instruction looks at and the program never filled, which gets a zero
4169 /// for the reason [`Self::undefined`] gives.
4170 ///
4171 /// # The clobber list
4172 ///
4173 /// Read now, as the registers it names being written by every instruction of the template. By
4174 /// every one rather than by one of them, because the list says the assembly as a whole leaves
4175 /// them ruined and nothing here knows which line did it. Every entry has to be a register this
4176 /// machine has a name for or the statement is refused, since a name nobody read is a register
4177 /// nobody is keeping out of.
4178 ///
4179 /// `memory` and `cc` are the two entries that are not registers and both are skipped. `memory`
4180 /// says the assembly touches storage, which is already true of every `asm` this writes and is
4181 /// nothing a register list could hold. `cc` says it ruins the condition flags, and the flag
4182 /// tracking already has that from the instructions the template was read into, since it takes
4183 /// every instruction it does not recognize as writing them and every instruction here is one
4184 /// this machine describes. `flags` is the name gcc's own register table gives the same thing on
4185 /// this machine, so a program writing it has written `cc` and is read that way: tcc's
4186 /// `tests/tcctest.c` lists both on one statement.
4187 ///
4188 /// A clobber the instruction already writes is left off it. `cpuid` writes all four registers
4189 /// by description, and a statement listing three of them as clobbers as well is saying the
4190 /// same thing twice, which the allocator would read as one register with two definitions.
4191 ///
4192 /// On a template with nothing in it the list is ignored, as it was before, since a template
4193 /// with no instructions ruins nothing whatever it said about what it ruins.
4194 fn assembly(&mut self, inst: Inst) -> Result<(), Unsupported> {
4195 let data = &self.source[inst];
4196 let Extra::Asm(asm) = data.extra else { return Err(self.unsupported(inst)) };
4197 let info = self.source[asm];
4198 if self.jumps_from_text(inst) {
4199 return Err(Unsupported::Assembly { inst, refused: Written::Goto });
4200 }
4201 let refused = || Unsupported::Assembly { inst, refused: Written::Operand };
4202
4203 let constraints = self.names.resolve(info.constraints).to_string();
4204 let results: Vec<Value> = data.results().collect();
4205 let operands = AsmOperands::read(&constraints, &results, &self.source[data.args])
4206 .ok_or_else(refused)?;
4207 let list: Vec<AsmOperand<'_>> = operands.iter().copied().collect();
4208
4209 // Read after the constraints and not before them, because a mnemonic whose suffix the
4210 // program left off is read at the width of the operands it names, and the operands are
4211 // what the constraints are a list of.
4212 let widths: Vec<Option<x86_64::Width>> = list
4213 .iter()
4214 .map(|operand| {
4215 let ty = self.source[operand.result.or(operand.value)?].ty;
4216 if !ty.is_scalar() {
4217 return None;
4218 }
4219 x86_64::Width::of_bits(held_bits(ty))
4220 })
4221 .collect();
4222 // An operand in memory is an address the statement holds and an object the template names,
4223 // so the reader is told which ones those are and spells `%0` for one as the object.
4224 let memory: Vec<bool> = list.iter().map(|operand| operand.memory).collect();
4225 let template = self.names.resolve(info.template).to_string();
4226 // A clobber list naming a vector register goes the way a template this cannot read does.
4227 // The instructions read here are all in the general purpose file, and what keeps the text
4228 // already takes every vector register a call may use away from the allocator across it.
4229 let clobbers = self.names.resolve(info.clobbers);
4230 if clobbers.split(',').any(|entry| vector_named(entry).is_some()) {
4231 return self.kept(inst, &template, &list, &widths, &memory);
4232 }
4233 let steps = if template.trim().is_empty() {
4234 Vec::new()
4235 } else {
4236 match x86_64::read_in(&template, &widths, &memory) {
4237 Some(steps) => steps,
4238 None => return self.kept(inst, &template, &list, &widths, &memory),
4239 }
4240 };
4241
4242 // Which operands the template writes, counted before anything is placed, because the answer
4243 // decides where each of the three below comes from and one instruction may name an operand
4244 // that a later one writes. Which of them any instruction puts in a register at all is
4245 // counted in the same walk, since an operand no instruction reaches that way is one nothing
4246 // has to put anywhere: a constant a template names only as the distance into an address is
4247 // written into the instruction, and a register holding a copy of it would be one nobody
4248 // reads. An operand the address is counted from is reached that way and is counted here for
4249 // that reason, because the walk below it is over the opcode's operands and an address is
4250 // not one of those.
4251 //
4252 // Whether any instruction reads an operand an instruction above it wrote is counted in the
4253 // same walk too. Such a template is one whose instructions have to be written in order with
4254 // each read taken from wherever the last write left the operand, which is what
4255 // [`Self::woven`] does, and so is one that writes an operand twice.
4256 let mut writes = vec![0usize; list.len()];
4257 let mut reads = vec![false; list.len()];
4258 let mut held = vec![false; list.len()];
4259 let mut after = false;
4260 for step in &steps {
4261 // A call out of the template writes every register the convention lets the callee
4262 // leave anything in, and an output pinned to one of those is written by it.
4263 if let x86_64::Step::Call { .. } = step {
4264 for index in self.lost(&list).into_iter().filter_map(|(_, _, index)| index) {
4265 *writes.get_mut(index).ok_or_else(refused)? += 1;
4266 }
4267 continue;
4268 }
4269 let x86_64::Step::Line(line) = step else { continue };
4270 match line.at.and_then(|at| at.base) {
4271 Some(x86_64::Piece::Operand { index, .. }) => {
4272 *held.get_mut(index).ok_or_else(refused)? = true;
4273 after |= writes[index] > 0;
4274 }
4275 Some(x86_64::Piece::Reg { reg, .. }) => {
4276 if let Some(index) = bound(&list, reg, Role::Use) {
4277 *held.get_mut(index).ok_or_else(refused)? = true;
4278 after |= writes[index] > 0;
4279 }
4280 }
4281 _ => {}
4282 }
4283 let mut written = Vec::new();
4284 let form = x86_64::form(line.opcode).ok_or_else(refused)?;
4285 // Which registers the instruction reaches, asked the same way it is asked again when
4286 // the instruction is written. See [`Self::lettered`] for the one opcode whose answer
4287 // comes from the constraint letters rather than from the description.
4288 let lettered = (line.opcode == x86_64::LITERAL).then(|| self.lettered(&list));
4289 let (described, pieces) = match &lettered {
4290 Some((described, pieces)) => (described.as_slice(), pieces.as_slice()),
4291 None => (form.operands(), line.operands.as_slice()),
4292 };
4293 for (desc, piece) in described.iter().zip(pieces) {
4294 // An operand the instruction reaches without its text saying so is the statement's
4295 // only when a constraint letter put something there. One that is nobody's writes
4296 // nothing of the program's, so it is counted nowhere and is dealt with where it is
4297 // placed.
4298 let index = match *piece {
4299 x86_64::Piece::Operand { index, .. } => index,
4300 x86_64::Piece::Implicit { reg } => match bound(&list, reg, desc.role) {
4301 Some(index) => index,
4302 None => continue,
4303 },
4304 x86_64::Piece::Reg { reg, .. } => match bound(&list, reg, desc.role) {
4305 Some(index) => index,
4306 None => continue,
4307 },
4308 };
4309 *held.get_mut(index).ok_or_else(refused)? = true;
4310 if matches!(desc.role, Role::Def | Role::EarlyDef) {
4311 written.push(index);
4312 } else {
4313 *reads.get_mut(index).ok_or_else(refused)? = true;
4314 after |= writes[index] > 0;
4315 }
4316 }
4317 for index in written {
4318 *writes.get_mut(index).ok_or_else(refused)? += 1;
4319 }
4320 }
4321 let woven = after
4322 || writes.iter().any(|&count| count > 1)
4323 || steps.iter().any(|step| !matches!(step, x86_64::Step::Line(_)));
4324
4325 // Where every operand is. Worked out in full before the first instruction is written, since
4326 // reading a value may be what puts it in a register in the first place, and that has to
4327 // happen in front of the assembly rather than in the middle of it.
4328 let mut places: Vec<Place> = vec![Place::default(); list.len()];
4329 for (index, operand) in list.iter().copied().enumerate() {
4330 let Some(result) = operand.result else {
4331 // An input, or an output the assembly was handed the address of, and both are a
4332 // value that arrives in a register and is read out of it, unless no instruction of
4333 // the template reads it out of one.
4334 let value = operand.value.ok_or_else(refused)?;
4335 if held[index] {
4336 places[index].read = Some(self.reg_of(value)?);
4337 }
4338 continue;
4339 };
4340 let ty = self.source[result].ty;
4341 if on_x87(ty) {
4342 return Err(refused());
4343 }
4344 let tied = operands.tied_to(index);
4345 if let Some(from) = tied {
4346 if self.class_of(self.source[from].ty) != self.class_of(ty) {
4347 return Err(refused());
4348 }
4349 places[index].read = Some(self.reg_of(from)?);
4350 }
4351 if writes[index] > 0 {
4352 places[index].write = Some(self.new_reg(result));
4353 continue;
4354 }
4355 match tied {
4356 // The place the input arrived in, which the assembly wrote nothing over. One
4357 // register, so this is a rename rather than a move.
4358 Some(_) => {
4359 let reg = places[index].read.ok_or_else(refused)?;
4360 self.regs[result.index()] = Some(reg);
4361 places[index].write = Some(reg);
4362 }
4363 None => {
4364 self.undefined(inst, result)?;
4365 places[index].write = self.regs[result.index()];
4366 }
4367 }
4368 }
4369
4370 // An output an instruction of the template also reads, which the statement said nothing
4371 // about because an output is what a statement says the other thing about. What it holds
4372 // there is undefined, and a program writing one means it: `sbb %0, %0` in libgmp's
4373 // `add_mssaaaa` subtracts a register from itself and is asking for the borrow bit rather
4374 // than for the number, so whatever the register held, the answer is the same. Undefined is
4375 // not the same as absent though, since the allocator is owed a definition in front of every
4376 // use, so it gets the zero an output nothing wrote gets and for the same reason.
4377 //
4378 // Unless an input could have been in the same register, in which case gcc's allocator puts
4379 // it there whenever it can and a program may have been written against that. tcc's test of
4380 // a call from a template reads its output `"=a" (s)` to pass `"r" (str)` to `getenv`, which
4381 // is only the string because gcc gave the two of them `rax`. So an output nothing has
4382 // written yet reads the one input that could share its place, when there is exactly one.
4383 // One written `&` is written before the inputs are read and shares nothing.
4384 for index in 0..list.len() {
4385 if !reads[index] || places[index].read.is_some() || places[index].write.is_none() {
4386 continue;
4387 }
4388 let reg = match self.shared(&list, index) {
4389 Some(value) => self.reg_of(value)?,
4390 None => self.seeded(inst, list[index])?,
4391 };
4392 places[index].read = Some(reg);
4393 }
4394
4395 // Worked out once for the whole template, since the list is one list and every instruction
4396 // of the template gets it. Not worked out at all for a template with no instructions, which
4397 // is where there is nothing for it to go on.
4398 let clobbers = self.names.resolve(info.clobbers).to_string();
4399 let clobbered =
4400 if steps.is_empty() { Vec::new() } else { Self::clobbered(inst, &clobbers)? };
4401
4402 // A template with a label in it is not one run of instructions, and what it is instead is
4403 // in [`Self::woven`], which is also where a template goes whose instructions read what the
4404 // ones above them wrote. Every other template is what it has always been, which is every
4405 // instruction of it written into the block the statement stands in.
4406 if woven {
4407 return self.woven(inst, &steps, &mut places, &list, &clobbered, &writes);
4408 }
4409 for step in &steps {
4410 let x86_64::Step::Line(line) = step else { continue };
4411 self.instruction(inst, line, &places, &list, &clobbered)?;
4412 }
4413 Ok(())
4414 }
4415
4416 /// A template the reader could not take apart, kept as its text. See [`x86_64::Form::Template`].
4417 ///
4418 /// What the text names is spelled into it here, the way gcc prints it into its listing: a
4419 /// constant as `$5`, or as `5` under the `c` modifier, and the address of a name as the name.
4420 /// An object in memory is the one thing that cannot be spelled yet, since where it is depends on
4421 /// registers nothing has chosen, so it is left as a hole the writer fills and its address is the
4422 /// instruction's memory operand. One is all an instruction has room for, and every template this
4423 /// has met names one at most. A template that names an operand by name rather than by number is
4424 /// refused for now.
4425 ///
4426 /// # An operand in a register
4427 ///
4428 /// Which register is not known until the allocator has run, and the text is written down before
4429 /// then, so an operand in a register is a hole too. It names the instruction's own operand and
4430 /// the width the modifier asked for, or the width of the operand's type when there was none,
4431 /// and the writer spells whatever register the operand ended up in. What the text writes goes
4432 /// in first as definitions and what it reads goes in last as uses, with the registers below in
4433 /// between, so the allocator sees the statement as one instruction with every operand said. An
4434 /// output tied to an input, by `+` or by a number, reuses the input's register, and one written
4435 /// `&` is written early. Anything wider than a general purpose register is refused.
4436 ///
4437 /// A statement written with no colons is basic assembly, where `%` is a character like any
4438 /// other and a register is written `%eax`. The front end keeps no mark of which kind a statement
4439 /// was, so one with no operands and no clobbers is read as basic, which is what gcc would do for
4440 /// every such template but one written with empty colons around it.
4441 ///
4442 /// The registers a call may write are taken as written, see below for why.
4443 fn kept(
4444 &mut self,
4445 inst: Inst,
4446 template: &str,
4447 list: &[AsmOperand<'_>],
4448 widths: &[Option<x86_64::Width>],
4449 memory: &[bool],
4450 ) -> Result<(), Unsupported> {
4451 // Refused as the template it is, since keeping it is what was tried after reading it
4452 // failed, and what could not be kept is what it names rather than any one operand.
4453 let refused = || Unsupported::Assembly { inst, refused: Written::Template };
4454 let data = &self.source[inst];
4455 let Extra::Asm(asm) = data.extra else { return Err(self.unsupported(inst)) };
4456 let clobbers = self.names.resolve(self.source[asm].clobbers).to_string();
4457 let basic = list.is_empty() && clobbers.trim().is_empty();
4458
4459 // Every register a call may leave anything in, as well as the ones the list names. The
4460 // text can write any register it likes without saying so, and tcc's tests do: gcc gets
4461 // away with that at `-O0` because nothing lives in a register between two statements
4462 // there, and taking these away from the allocator across the template is what gives the
4463 // same answer here. Nothing is written to them by this, so a register one template leaves
4464 // a value in is still holding it when the next template reads it.
4465 let a64 = self.on_aarch64();
4466 let mut clobbered: Vec<(PhysReg, RegClass)> =
4467 self.lost(list).into_iter().map(|(reg, class, _)| (reg, class)).collect();
4468 let named = if a64 {
4469 Self::clobbered_a64(inst, &clobbers)?
4470 } else {
4471 Self::clobbered_x86(inst, &clobbers, self.gpr, self.conv.sse_class)?
4472 };
4473 for &(reg, class) in &named {
4474 if !clobbered.iter().any(|&(had, of)| had == reg && of == class) {
4475 clobbered.push((reg, class));
4476 }
4477 }
4478
4479 // The file each operand is in. On AArch64 `w` is a floating point or vector register and an
4480 // input tied to an output is in that output's file. A value whose type puts it in the other
4481 // file would need a move into this one first, which gcc makes and this does not yet, so
4482 // that is refused below.
4483 let mut files = vec![self.gpr; list.len()];
4484 if a64 {
4485 let constraints = self.names.resolve(self.source[asm].constraints);
4486 for (file, entry) in files.iter_mut().zip(constraints.split(',')) {
4487 if vector_letter(entry) {
4488 *file = self.conv.sse_class;
4489 }
4490 }
4491 for index in 0..list.len() {
4492 if let Some(&file) = list[index].tied.and_then(|output| files.get(output)) {
4493 files[index] = file;
4494 }
4495 }
4496 }
4497 let pins: Vec<_> = list.iter().map(|operand| self.pinned_here(operand)).collect();
4498 let pin = |index: usize, file: RegClass| match pins[index] {
4499 Some((at, class)) if class == file => Ok(Some(Constraint::Fixed(at))),
4500 Some(_) => Err(refused()),
4501 None => Ok(None),
4502 };
4503
4504 // The operands in a register, as the instruction's own. An input the text is handed as a
4505 // constant or as the address of a name is spelled into the text instead, when its
4506 // constraint allows a constant at all and no output is tied to it. `"a" (0x1234)` is a
4507 // register holding the number, the way gcc loads it, since the text may ask for `%h0`.
4508 let mut defs: Vec<mir::Operand> = Vec::new();
4509 let mut uses: Vec<mir::Operand> = Vec::new();
4510 let mut def_of: Vec<Option<usize>> = vec![None; list.len()];
4511 let mut use_of: Vec<Option<usize>> = vec![None; list.len()];
4512 if !basic {
4513 for (index, operand) in list.iter().enumerate() {
4514 let Some(result) = operand.result else { continue };
4515 let (ty, file) = (self.source[result].ty, files[index]);
4516 if on_x87(ty) || self.class_of(ty) != file {
4517 return Err(refused());
4518 }
4519 let reg = self.new_reg(result);
4520 let written = if operand.early {
4521 mir::Operand::write_early(reg, file)
4522 } else {
4523 mir::Operand::write(reg, file)
4524 };
4525 def_of[index] = Some(defs.len());
4526 defs.push(match pin(index, file)? {
4527 Some(fixed) => written.with(fixed),
4528 None => written,
4529 });
4530 }
4531 for (index, operand) in list.iter().enumerate() {
4532 let Some(value) = operand.value else { continue };
4533 let spelled = operand.result.is_none()
4534 && operand.tied.is_none()
4535 && operand.immediate
4536 && (self.number(value).is_some() || self.named_address(value).is_some());
4537 // An operand in memory is spelled on AArch64 as the register its address is in,
4538 // which is `[x3]` and is an address every instruction that takes one reads.
4539 if (operand.memory && !a64) || spelled {
4540 continue;
4541 }
4542 let (ty, file) = (self.source[value].ty, files[index]);
4543 if on_x87(ty) || self.class_of(ty) != file {
4544 return Err(refused());
4545 }
4546 let read = mir::Operand::read(self.reg_of(value)?, file);
4547 use_of[index] = Some(uses.len());
4548 uses.push(match pin(index, file)? {
4549 Some(fixed) => read.with(fixed),
4550 None => read,
4551 });
4552 }
4553 }
4554 // Every register a call may write is more than a template can give up when it has more
4555 // operands in registers than the convention keeps across a call. `sodium_sub` in
4556 // libsodium's `utils.c` is one: eight outputs written early and two inputs pinned, against
4557 // the five registers SysV preserves, so an output has nowhere to go and nothing is left to
4558 // carry one to its slot either. gcc gives that template ten registers, and a program that
4559 // writes a register it did not name is only owed what gcc would have done, which here is
4560 // one of the ten. So the registers taken as written without being named are handed back,
4561 // from the end of the convention's order, until the operands fit in what is left. One the
4562 // list names or an operand is pinned to stays where it is. What is left does not count the
4563 // two scratch registers the allocator holds back, since no operand is ever given one of
4564 // those, and counting them left two outputs short above -O0 with nothing to carry them.
4565 let fixed_to: Vec<PhysReg> = defs
4566 .iter()
4567 .chain(&uses)
4568 .filter_map(|operand| match operand.constraint {
4569 Constraint::Fixed(at) => Some(at),
4570 _ => None,
4571 })
4572 .collect();
4573 let wanted = defs.iter().chain(&uses).count() - fixed_to.len();
4574 let int = self.conv.int_class;
4575 let held: &[PhysReg] =
4576 if a64 { &crate::pipeline::AARCH64_SCRATCH } else { &crate::pipeline::SCRATCH };
4577 let free = |clobbered: &[(PhysReg, RegClass)]| {
4578 self.conv
4579 .int_order
4580 .iter()
4581 .filter(|&®| {
4582 !held.contains(®)
4583 && !fixed_to.contains(®)
4584 && !clobbered.contains(&(reg, int))
4585 })
4586 .count()
4587 };
4588 while free(&clobbered) < wanted {
4589 let Some(at) = clobbered.iter().rposition(|&(reg, class)| {
4590 class == int && !named.contains(&(reg, class)) && !fixed_to.contains(®)
4591 }) else {
4592 break;
4593 };
4594 clobbered.remove(at);
4595 }
4596
4597 // A register an output is pinned to is that output's definition and not a clobber as well.
4598 // One an input is pinned to is written as the instruction finishes, the way a call writes
4599 // the register its argument came in, and every other one is written early, since the text
4600 // may write it before it has read its inputs and an input must not be in it.
4601 let mut written: Vec<mir::Operand> = Vec::new();
4602 for (reg, class) in clobbered {
4603 let fixed = |operand: &mir::Operand| {
4604 operand.class == class && operand.constraint == Constraint::Fixed(reg)
4605 };
4606 if defs.iter().any(fixed) {
4607 continue;
4608 }
4609 let reg = mir::Reg::physical(reg);
4610 written.push(if uses.iter().any(fixed) {
4611 mir::Operand::write(reg, class)
4612 } else {
4613 mir::Operand::write_early(reg, class)
4614 });
4615 }
4616 // An output tied to an input is one register, which the definition says by reusing the
4617 // use, or by both being fixed to the same one when the output was pinned.
4618 //
4619 // A reused register is kept from every other input already, since the allocator counts the
4620 // output as taken from where the instruction reads. So `+&` asks for nothing more than `+`,
4621 // and saying it as an early write as well costs a register: the allocator only hands an
4622 // output the register of the input it reuses when the output starts at the instruction, and
4623 // an early one starts a point sooner, so it gets one of its own and a copy in front. Eleven
4624 // operands written that way in xz's range decoder need seventeen registers and run out. The
4625 // one case where `&` still means something is an input reading the same value as the one
4626 // tied, which would be in the same register and read after the output was written.
4627 let first_use = defs.len() + written.len();
4628 for (output, operand) in list.iter().enumerate() {
4629 let Some(def) = def_of[output] else { continue };
4630 let input = if operand.value.is_some() {
4631 Some(output)
4632 } else {
4633 list.iter().position(|entry| entry.tied == Some(output))
4634 };
4635 let Some(read) = input.and_then(|input| use_of[input]) else { continue };
4636 match defs[def].constraint {
4637 Constraint::Fixed(_) => uses[read].constraint = defs[def].constraint,
4638 _ => {
4639 let at = u8::try_from(first_use + read).map_err(|_| refused())?;
4640 defs[def].constraint = Constraint::Reuse(at);
4641 let source = uses[read].reg;
4642 let shared = uses
4643 .iter()
4644 .enumerate()
4645 .any(|(other, operand)| other != read && operand.reg == source);
4646 if defs[def].role == Role::EarlyDef && !shared {
4647 defs[def].role = Role::Def;
4648 }
4649 }
4650 }
4651 }
4652
4653 // A line naming an operand in a register, with an instruction on it the reader knows, is
4654 // one the reader refused for a reason of its own, and keeping it as text would hand the
4655 // assembler what the reader already said no to. `addq %1, %k0` is that: a quadword add
4656 // into half a register. What is kept is a line with an instruction nothing here knows.
4657 let registered = |index: usize| def_of[index].is_some() || use_of[index].is_some();
4658 if !a64 && (0..list.len()).any(registered) {
4659 for line in template.split(['\n', ';']) {
4660 if names_one(line, registered)
4661 && x86_64::known(line, widths, memory)
4662 && x86_64::read_in(line, widths, memory).is_none()
4663 {
4664 return Err(refused());
4665 }
4666 }
4667 }
4668
4669 let mut text = String::with_capacity(template.len());
4670 let mut memory: Option<usize> = None;
4671 if basic {
4672 text.push_str(template);
4673 } else {
4674 let mut chars = template.chars().peekable();
4675 // Inside `{att|intel}`, and past the `|` in it, which is the half nobody reads. AArch64
4676 // has one dialect, and a brace there is a list of vector registers.
4677 let mut dialect = false;
4678 let mut skipped = false;
4679 while let Some(c) = chars.next() {
4680 match c {
4681 '{' if !a64 => {
4682 dialect = true;
4683 continue;
4684 }
4685 '|' if dialect => {
4686 skipped = true;
4687 continue;
4688 }
4689 '}' if dialect => {
4690 dialect = false;
4691 skipped = false;
4692 continue;
4693 }
4694 _ if skipped => continue,
4695 '%' => {}
4696 _ => {
4697 text.push(c);
4698 continue;
4699 }
4700 }
4701 match chars.peek().copied() {
4702 Some(c @ ('%' | '{' | '|' | '}')) => {
4703 chars.next();
4704 text.push(c);
4705 continue;
4706 }
4707 Some('=') => {
4708 chars.next();
4709 text.push_str(&inst.index().to_string());
4710 continue;
4711 }
4712 _ => {}
4713 }
4714 let modifier = match chars.peek().copied() {
4715 Some(c) if c.is_ascii_alphabetic() => {
4716 chars.next();
4717 Some(c)
4718 }
4719 _ => None,
4720 };
4721 let mut digits = String::new();
4722 while let Some(c) = chars.peek().copied().filter(char::is_ascii_digit) {
4723 digits.push(c);
4724 chars.next();
4725 }
4726 let index: usize = digits.parse().map_err(|_| refused())?;
4727 let operand = list.get(index).ok_or_else(refused)?;
4728 if operand.memory && a64 {
4729 let at = use_of[index].map(|at| first_use + at).ok_or_else(refused)?;
4730 if modifier.is_some() {
4731 return Err(refused());
4732 }
4733 text.push('[');
4734 text.push_str(&template_reg(at, 'x'));
4735 text.push(']');
4736 continue;
4737 }
4738 if operand.memory {
4739 if modifier.is_some() || memory.is_some_and(|had| had != index) {
4740 return Err(refused());
4741 }
4742 memory = Some(index);
4743 text.push_str(x86_64::TEMPLATE_MEM);
4744 continue;
4745 }
4746 let placed = def_of[index].or(use_of[index].map(|at| first_use + at));
4747 if let Some(at) = placed {
4748 let value = operand.result.or(operand.value).ok_or_else(refused)?;
4749 let bits = held_bits(self.source[value].ty);
4750 // `w` and `x` are the two names every general purpose register has, and one
4751 // with no modifier is named at the width of its type, as gcc names it. A
4752 // vector register with no modifier is `v`, which is what gcc writes for one
4753 // whatever is in it, and the modifiers name the scalar views of it.
4754 let width = if a64 && files[index] != self.gpr {
4755 match modifier {
4756 None => 'v',
4757 Some(view @ ('b' | 'h' | 's' | 'd' | 'q')) => view,
4758 Some(_) => return Err(refused()),
4759 }
4760 } else if a64 {
4761 match (modifier, bits) {
4762 (None, 8 | 16 | 32) | (Some('w'), _) => 'w',
4763 (None, 64) | (Some('x'), _) => 'x',
4764 _ => return Err(refused()),
4765 }
4766 } else {
4767 match modifier {
4768 None => match held_bits(self.source[value].ty) {
4769 8 => 'b',
4770 16 => 'w',
4771 32 => 'k',
4772 64 => 'q',
4773 _ => return Err(refused()),
4774 },
4775 Some(width @ ('b' | 'w' | 'k' | 'q')) => width,
4776 // The second byte is a name only four registers have, so it is taken for
4777 // an operand pinned to one of them and for nothing the allocator chose.
4778 Some('h') if pinned(operand).and_then(x86_64::gpr_high).is_some() => {
4779 'h'
4780 }
4781 Some(_) => return Err(refused()),
4782 }
4783 };
4784 text.push_str(&template_reg(at, width));
4785 continue;
4786 }
4787 let value = operand.value.ok_or_else(refused)?;
4788 let bare = match modifier {
4789 None => false,
4790 Some('c' | 'P' | 'p') => true,
4791 Some(_) => return Err(refused()),
4792 };
4793 // A constant is bare on AArch64 whatever the modifier, which is how gcc prints one
4794 // there and a form GNU as takes wherever `#` would go.
4795 if !bare && !a64 {
4796 text.push('$');
4797 }
4798 if let Some(number) = self.number(value) {
4799 text.push_str(&number.to_string());
4800 } else if let Some(symbol) = self.named_address(value) {
4801 text.push_str(&template_name(self.names.resolve(symbol)));
4802 } else {
4803 return Err(refused());
4804 }
4805 }
4806 }
4807
4808 // An object in this function's frame is named by where it is in the frame, the way gcc
4809 // names it, rather than by a register its address was put in first. The text may write
4810 // registers it does not declare, and tcc's tests do: one that writes `%ecx` behind the
4811 // compiler's back would otherwise take the address with it.
4812 let mut local = None;
4813 let at = match memory.filter(|_| !a64) {
4814 Some(index) => {
4815 let value = list[index].value.ok_or_else(refused)?;
4816 local = self.local_of(value);
4817 let base = match local {
4818 Some(_) => mir::Reg::physical(self.conv.stack_pointer),
4819 None => self.reg_of(value)?,
4820 };
4821 Some(mir::Mem::at(mir::Operand::read(base, self.gpr)))
4822 }
4823 None => None,
4824 };
4825 let symbol = self.names.intern(&text);
4826 let opcode = self.named(if a64 { aarch64::TEMPLATE } else { x86_64::TEMPLATE });
4827 let block = self.at.expect("a block is being filled");
4828 let span = self.source.span(inst);
4829 let mut build = self.out.build(block, opcode).at(span).symbol(symbol);
4830 for operand in defs.into_iter().chain(written).chain(uses) {
4831 build = build.operand(operand);
4832 }
4833 if let Some(mem) = at {
4834 build = build.mem(mem);
4835 }
4836 let made = build.finish();
4837 if let Some(local) = local {
4838 self.stack.addresses.push((made, local));
4839 }
4840 Ok(())
4841 }
4842
4843 /// The object in this function's frame a value is the address of, for one an `alloca` of a
4844 /// size known here made. See [`Self::reserve`], which is where it was put on the list.
4845 fn local_of(&self, value: Value) -> Option<usize> {
4846 let Def::Result { inst, .. } = self.source[value].def else { return None };
4847 if self.source[inst].opcode != Opcode::Alloca
4848 || !self.source[self.source[inst].args].is_empty()
4849 {
4850 return None;
4851 }
4852 self.frame_slots.get(&value).copied()
4853 }
4854
4855 /// The name a value is the address of, for one a `global_addr` defined.
4856 fn named_address(&self, value: Value) -> Option<Symbol> {
4857 let Def::Result { inst, .. } = self.source[value].def else { return None };
4858 if self.source[inst].opcode != Opcode::GlobalAddr {
4859 return None;
4860 }
4861 let Extra::Symbol(symbol) = self.source[inst].extra else { return None };
4862 Some(symbol)
4863 }
4864
4865 /// A register holding a zero, for an operand of a template that is read before anything filled
4866 /// it.
4867 ///
4868 /// Two things ask for this and they are the same thing twice. An output the template reads has
4869 /// nothing to be read out of until the instruction that writes it has run, and a loop carries
4870 /// an operand into a block before the instruction that fills it, so both are a use in front of
4871 /// every definition. What the program is owed there is nothing, since the value is undefined
4872 /// either way, and what the allocator is owed is a register something wrote.
4873 fn seeded(&mut self, inst: Inst, operand: AsmOperand<'_>) -> Result<mir::Reg, Unsupported> {
4874 let refused = || Unsupported::Assembly { inst, refused: Written::Operand };
4875 let value = operand.result.or(operand.value).ok_or_else(refused)?;
4876 let class = self.class_of(self.source[value].ty);
4877 if class != self.gpr {
4878 return Err(refused());
4879 }
4880 let block = self.at.expect("a block is being filled");
4881 let reg = self.out.new_vreg(class);
4882 let put = self.named("mov_ri_64");
4883 self.out.build(block, put).at(self.source.span(inst)).def(reg, class).imm(0).finish();
4884 Ok(reg)
4885 }
4886
4887 /// A template with labels in it, as the blocks its jumps leave and arrive at.
4888 ///
4889 /// A statement is an instruction of the IR and stands inside one block, so a template that
4890 /// jumps has to stop being one thing. Each label becomes a block, each jump ends the block it
4891 /// stands in and gives it two arms, and whatever follows the statement goes into whichever
4892 /// block the walk finished in, which is what [`Self::block`] already reads off `self.at` and
4893 /// what [`Self::saves_place`] already does for the same reason.
4894 ///
4895 /// # What is carried between them
4896 ///
4897 /// The machine IR here is in the form where a register is written once, so an operand written
4898 /// inside a loop and read again at the top of it cannot be one register. What arrives at the
4899 /// top is a parameter of that block, and every jump to it carries whichever register held the
4900 /// operand where the jump stands. That is the whole of the bookkeeping: every block a label
4901 /// made takes one parameter for each operand that is in a register at all, in one order, so an
4902 /// arm's arguments and a block's parameters are the same list read twice.
4903 ///
4904 /// Which register an operand is in at each point is kept in the read half of its place, since
4905 /// that is what the instructions below read it out of. An instruction that writes an operand
4906 /// leaves it in the register it wrote, and a jump below carries that one. The block an
4907 /// untaken jump falls into is arrived at one way only and so takes no parameters, and nothing
4908 /// about where the operands are changes there.
4909 ///
4910 /// An operand written by the template and filled by nothing is written as a zero first, for
4911 /// the reason [`Self::undefined`] gives and one more: a jump may carry it before the
4912 /// instruction that fills it has run, and an argument has to be a register something wrote.
4913 ///
4914 /// # The condition state
4915 ///
4916 /// Nothing carries it and nothing has to. The instruction that sets it and the jump that reads
4917 /// it are both written here, next to each other in one block, and what the allocator may put
4918 /// between them is a move, which on this machine leaves the condition state alone. The edge
4919 /// into a block a loop goes back to is a critical edge and `crate::split` gives it a block of
4920 /// its own, so the moves an arm turns into land behind the jump rather than in front of it.
4921 fn woven(
4922 &mut self,
4923 inst: Inst,
4924 steps: &[x86_64::Step],
4925 places: &mut [Place],
4926 list: &[AsmOperand<'_>],
4927 clobbered: &[PhysReg],
4928 writes: &[usize],
4929 ) -> Result<(), Unsupported> {
4930 let refused = || Unsupported::Assembly { inst, refused: Written::Operand };
4931 let span = self.source.span(inst);
4932
4933 // Which operands are carried, which is every one that is in a register at all. An operand
4934 // the template never puts in one, such as a constant it names only as the distance into an
4935 // address, is in the instruction and has nowhere to be carried from.
4936 let mut carried: Vec<(usize, RegClass)> = Vec::new();
4937 for (index, operand) in list.iter().enumerate() {
4938 if places[index].read.is_none() && places[index].write.is_none() {
4939 continue;
4940 }
4941 let value = operand.result.or(operand.value).ok_or_else(refused)?;
4942 let ty = self.source[value].ty;
4943 if on_x87(ty) {
4944 return Err(refused());
4945 }
4946 carried.push((index, self.class_of(ty)));
4947 }
4948
4949 // What each of them holds where the template starts.
4950 for &(index, _) in &carried {
4951 if places[index].read.is_some() {
4952 continue;
4953 }
4954 if writes[index] == 0 {
4955 places[index].read = places[index].write;
4956 continue;
4957 }
4958 places[index].read = Some(self.seeded(inst, list[index])?);
4959 }
4960
4961 // The blocks, made before the walk because a jump forwards names a label the walk has not
4962 // reached yet.
4963 let mut labels: Vec<(&str, mir::Block, Vec<mir::Reg>)> = Vec::new();
4964 for step in steps {
4965 let x86_64::Step::Label(name) = step else { continue };
4966 let block = self.out.create_block();
4967 let mut params = Vec::with_capacity(carried.len());
4968 for &(_, class) in &carried {
4969 params.push(self.out.append_param(block, class));
4970 }
4971 labels.push((name.as_str(), block, params));
4972 }
4973
4974 let mut wrote: Vec<usize> = Vec::new();
4975 for step in steps {
4976 match step {
4977 x86_64::Step::Label(name) => {
4978 let (block, params) = Self::went(&labels, name).ok_or_else(refused)?;
4979 let from = self.at.expect("a block is being filled");
4980 let args = Self::held(places, &carried).ok_or_else(refused)?;
4981 *self.out.succs_mut(from) = vec![mir::BlockCall::with(block, args)];
4982 self.at = Some(block);
4983 for (at, &(index, _)) in carried.iter().enumerate() {
4984 places[index].read = params.get(at).copied();
4985 }
4986 }
4987 x86_64::Step::Jump { opcode, to } => {
4988 let (block, _) = Self::went(&labels, to).ok_or_else(refused)?;
4989 let from = self.at.expect("a block is being filled");
4990 let args = Self::held(places, &carried).ok_or_else(refused)?;
4991 let opcode = self.named(opcode);
4992 self.out.build(from, opcode).at(span).finish();
4993 let next = self.out.create_block();
4994 *self.out.succs_mut(from) =
4995 vec![mir::BlockCall::with(block, args), mir::BlockCall::to(next)];
4996 self.at = Some(next);
4997 }
4998 x86_64::Step::Away { symbol } => {
4999 // Only in a function that is written without a prologue, which is the one
5000 // place the jump means what it says. Anywhere else there is an epilogue behind
5001 // the statement that puts the registers back and gives the frame up, and a
5002 // jump over it goes to the next function with this function's frame still
5003 // taken. The reader already made sure it is the last step of the template, so
5004 // what is left to ask is about the function around it.
5005 if !self.source.attrs.set.contains(AttrSet::NAKED) {
5006 return Err(Unsupported::Assembly { inst, refused: Written::Away });
5007 }
5008 let from = self.at.expect("a block is being filled");
5009 let opcode = self.named(AWAY);
5010 let symbol = self.names.intern(symbol);
5011 self.out.build(from, opcode).at(span).symbol(symbol).finish();
5012 // Nowhere, which is what a jump out of the function leaves behind it and is
5013 // the same list a `ret` leaves. The block after it is made for the walk above
5014 // rather than for the program: the statement may be in the middle of a body
5015 // that goes on being lowered, and what that lowering writes is reached by
5016 // nothing and thrown away with the block.
5017 *self.out.succs_mut(from) = Vec::new();
5018 self.at = Some(self.out.create_block());
5019 }
5020 x86_64::Step::Call { symbol } => {
5021 self.call_out(inst, symbol, places, list, clobbered, &carried, &mut wrote)?;
5022 }
5023 x86_64::Step::Line(line) => {
5024 let form = x86_64::form(line.opcode).ok_or_else(refused)?;
5025 let mut written = Vec::new();
5026 for (desc, piece) in form.operands().iter().zip(&line.operands) {
5027 if !desc.role.is_def() {
5028 continue;
5029 }
5030 let index = match *piece {
5031 x86_64::Piece::Operand { index, .. } => index,
5032 x86_64::Piece::Implicit { reg } => match bound(list, reg, desc.role) {
5033 Some(index) => index,
5034 None => continue,
5035 },
5036 x86_64::Piece::Reg { reg, .. } => match bound(list, reg, desc.role) {
5037 Some(index) => index,
5038 None => continue,
5039 },
5040 };
5041 written.push(index);
5042 }
5043 // A register is written once in this form of the machine IR, so an operand
5044 // an instruction above already wrote is written into a new one here, and what
5045 // reads it below reads that one.
5046 for &index in &written {
5047 if !wrote.contains(&index) {
5048 wrote.push(index);
5049 continue;
5050 }
5051 let &(_, class) =
5052 carried.iter().find(|&&(at, _)| at == index).ok_or_else(refused)?;
5053 let place = places.get_mut(index).ok_or_else(refused)?;
5054 place.write = Some(self.out.new_vreg(class));
5055 }
5056 self.instruction(inst, line, places, list, clobbered)?;
5057 for index in written {
5058 let place = places.get_mut(index).ok_or_else(refused)?;
5059 if place.write.is_some() {
5060 place.read = place.write;
5061 }
5062 }
5063 }
5064 }
5065 }
5066
5067 // Where the walk left each output, which is the parameter of the block a label made when
5068 // the template ends in one and the register an instruction wrote when it does not.
5069 for (index, operand) in list.iter().enumerate() {
5070 let Some(result) = operand.result else { continue };
5071 if let Some(reg) = places[index].read {
5072 self.regs[result.index()] = Some(reg);
5073 }
5074 }
5075 Ok(())
5076 }
5077
5078 /// A template's call to a function somewhere else, as the call the convention makes.
5079 ///
5080 /// The opcode is the one a call written in C becomes, so everything that asks whether a
5081 /// function calls anything gets the answer it would for one: the stack pointer is left aligned
5082 /// at the statement and nothing is kept in the red zone. What is not the same is the operands.
5083 /// Nothing is passed by the convention, since the template put the arguments where it wanted
5084 /// them, and what comes back is whatever an output is pinned to, since that is the only thing
5085 /// the template says about it. Every other register the callee may leave anything in is
5086 /// written here, which is what a program that calls from a template never says and always
5087 /// means.
5088 #[allow(clippy::too_many_arguments)]
5089 fn call_out(
5090 &mut self,
5091 inst: Inst,
5092 symbol: &str,
5093 places: &mut [Place],
5094 list: &[AsmOperand<'_>],
5095 clobbered: &[PhysReg],
5096 carried: &[(usize, RegClass)],
5097 wrote: &mut Vec<usize>,
5098 ) -> Result<(), Unsupported> {
5099 let refused = || Unsupported::Assembly { inst, refused: Written::Operand };
5100 let mut operands = Vec::new();
5101 let mut written = Vec::new();
5102 let lost = self.lost(list);
5103 for &(reg, class, index) in &lost {
5104 let Some(index) = index else {
5105 operands.push(mir::Operand::write(mir::Reg::physical(reg), class));
5106 continue;
5107 };
5108 // Written once in this form of the machine IR, so a second write is a new register,
5109 // the same as for an instruction in [`Self::woven`].
5110 if wrote.contains(&index) {
5111 let &(_, class) =
5112 carried.iter().find(|&&(at, _)| at == index).ok_or_else(refused)?;
5113 places.get_mut(index).ok_or_else(refused)?.write = Some(self.out.new_vreg(class));
5114 } else {
5115 wrote.push(index);
5116 }
5117 let place = places.get(index).ok_or_else(refused)?.write.ok_or_else(refused)?;
5118 operands.push(mir::Operand::write(place, class).with(Constraint::Fixed(reg)));
5119 written.push(index);
5120 }
5121 for ® in clobbered {
5122 if lost.iter().all(|&(gone, class, _)| gone != reg || class != self.gpr) {
5123 operands.push(mir::Operand::write(mir::Reg::physical(reg), self.gpr));
5124 }
5125 }
5126 let block = self.at.expect("a block is being filled");
5127 let span = self.source.span(inst);
5128 let opcode = mir::Opcode::new(self.names.intern(abi::CALL));
5129 let symbol = self.names.intern(symbol);
5130 let mut build = self.out.build(block, opcode).at(span).symbol(symbol);
5131 for operand in operands {
5132 build = build.operand(operand);
5133 }
5134 build.finish();
5135 let calls = &mut self.stack.calls;
5136 *calls = Some(calls.unwrap_or(0));
5137 for index in written {
5138 let place = places.get_mut(index).ok_or_else(refused)?;
5139 place.read = place.write;
5140 }
5141 Ok(())
5142 }
5143
5144 /// Every register a call may leave anything in, with its file and the output pinned to it if
5145 /// one is.
5146 ///
5147 /// A register is asked about with its file, since the two files are numbered from nought alike
5148 /// and a question about `v8` alone would find an output pinned to `x8`.
5149 ///
5150 /// The platform's own convention, whatever this function was written in, since what an `asm`
5151 /// statement calls is an ordinary function of the platform.
5152 fn lost(&self, list: &[AsmOperand<'_>]) -> Vec<(PhysReg, RegClass, Option<usize>)> {
5153 let conv = self.conv.under(Convention::Target).unwrap_or(self.conv);
5154 let ints = conv.int_order.iter().filter(|&®| !conv.preserves_int(reg));
5155 let sses = conv.sse_order.iter().filter(|&®| !conv.preserves_sse(reg));
5156 let written = |reg, class| {
5157 list.iter().position(|operand| {
5158 operand.result.is_some() && self.pinned_here(operand) == Some((reg, class))
5159 })
5160 };
5161 ints.map(|®| (reg, conv.int_class, written(reg, conv.int_class)))
5162 .chain(sses.map(|®| (reg, conv.sse_class, written(reg, conv.sse_class))))
5163 .collect()
5164 }
5165
5166 /// The input an output read before anything wrote it shares its register with, which is the
5167 /// one input that could be in that register, or nothing when there is none or more than one.
5168 ///
5169 /// Could be means nothing ties it elsewhere: it is in a register rather than in memory, no
5170 /// constraint pins it anywhere the output is not, and it is not tied to another output. An
5171 /// output written `&` shares nothing, since the assembly writes it before it reads the inputs.
5172 fn shared(&self, list: &[AsmOperand<'_>], index: usize) -> Option<Value> {
5173 let output = list.get(index)?;
5174 if output.early || output.tied.is_some() {
5175 return None;
5176 }
5177 let class = self.class_of(self.source[output.result?].ty);
5178 let mut fits = list.iter().filter(|operand| {
5179 operand.result.is_none()
5180 && !operand.memory
5181 && operand.tied.is_none()
5182 && operand.value.is_some_and(|value| self.class_of(self.source[value].ty) == class)
5183 && pinned(operand).is_none_or(|reg| pinned(output) == Some(reg))
5184 });
5185 let value = fits.next()?.value;
5186 if fits.next().is_some() {
5187 return None;
5188 }
5189 value
5190 }
5191
5192 /// The block one of the template's labels made, and the parameters it takes.
5193 fn went<'b>(
5194 labels: &'b [(&str, mir::Block, Vec<mir::Reg>)],
5195 name: &str,
5196 ) -> Option<(mir::Block, &'b [mir::Reg])> {
5197 labels
5198 .iter()
5199 .find(|(had, ..)| *had == name)
5200 .map(|(_, block, params)| (*block, params.as_slice()))
5201 }
5202
5203 /// The register each carried operand is in, which is what an arm to a label carries.
5204 fn held(places: &[Place], carried: &[(usize, RegClass)]) -> Option<Vec<mir::Reg>> {
5205 carried.iter().map(|&(index, _)| places.get(index)?.read).collect()
5206 }
5207
5208 /// The registers a clobber list names, in the order it named them.
5209 ///
5210 /// Nothing is dropped. A name this has no register for is refused, because the list is the
5211 /// program telling the compiler which registers it may not leave anything in, and an entry
5212 /// nobody read is a register something may still be left in. See [`Self::assembly`] for the
5213 /// two entries that are not registers and for why they are skipped rather than refused.
5214 fn clobbered(inst: Inst, clobbers: &str) -> Result<Vec<PhysReg>, Unsupported> {
5215 let refused = || Unsupported::Assembly { inst, refused: Written::Clobber };
5216 let mut named = Vec::new();
5217 for entry in clobbers.split(',') {
5218 let entry = entry.trim().trim_matches('"');
5219 // The sigil is optional in a clobber list and means nothing when it is there, unlike
5220 // in a template, where it is what tells a register from an operand.
5221 let entry = entry.strip_prefix('%').unwrap_or(entry);
5222 if entry.is_empty() || matches!(entry, "memory" | "cc" | "flags") {
5223 continue;
5224 }
5225 let (reg, _) = x86_64::gpr_named(entry).ok_or_else(refused)?;
5226 if !named.contains(®) {
5227 named.push(reg);
5228 }
5229 }
5230 Ok(named)
5231 }
5232
5233 /// [`Self::clobbered`] for a template kept as text, where a clobber may also name a vector
5234 /// register, `xmm0` or its wider spelling `ymm0`, which busybox's `xorbuf16_aligned_long` does.
5235 /// Each comes back with the file it is in, since `xmm0` and `rax` are both register nought.
5236 fn clobbered_x86(
5237 inst: Inst,
5238 clobbers: &str,
5239 gpr: RegClass,
5240 sse: RegClass,
5241 ) -> Result<Vec<(PhysReg, RegClass)>, Unsupported> {
5242 let mut named = Vec::new();
5243 let mut general = Vec::new();
5244 for entry in clobbers.split(',') {
5245 match vector_named(entry) {
5246 Some(reg) => {
5247 if !named.contains(&(reg, sse)) {
5248 named.push((reg, sse));
5249 }
5250 }
5251 None => general.push(entry),
5252 }
5253 }
5254 for reg in Self::clobbered(inst, &general.join(","))? {
5255 named.push((reg, gpr));
5256 }
5257 Ok(named)
5258 }
5259
5260 /// [`Self::clobbered`] on AArch64, where a clobber may name a vector register as well as a
5261 /// general purpose one, so each comes back with the file it is in. See [`aarch64::named`].
5262 fn clobbered_a64(inst: Inst, clobbers: &str) -> Result<Vec<(PhysReg, RegClass)>, Unsupported> {
5263 let refused = || Unsupported::Assembly { inst, refused: Written::Clobber };
5264 let mut named = Vec::new();
5265 for entry in clobbers.split(',') {
5266 let entry = entry.trim().trim_matches('"');
5267 if entry.is_empty() || matches!(entry, "memory" | "cc") {
5268 continue;
5269 }
5270 let reg = aarch64::named(entry).ok_or_else(refused)?;
5271 if !named.contains(®) {
5272 named.push(reg);
5273 }
5274 }
5275 Ok(named)
5276 }
5277
5278 /// Whether the machine being lowered for is AArch64.
5279 fn on_aarch64(&self) -> bool {
5280 std::ptr::eq(self.selector.shapes, &aarch64::MACHINE)
5281 }
5282
5283 /// The register an operand is pinned to on the machine being lowered for.
5284 ///
5285 /// [`pinned`] on x86, where it is always a general purpose register. AArch64 has no constraint
5286 /// letter for one register, so there only a local register variable pins anything, and its name
5287 /// is read against [`aarch64::named`], which may put it in either file. The file comes back with
5288 /// the register because the two are numbered from nought alike, and `x8` is not `v8`.
5289 fn pinned_here(&self, operand: &AsmOperand<'_>) -> Option<(PhysReg, RegClass)> {
5290 if !self.on_aarch64() {
5291 return pinned(operand).map(|reg| (reg, self.gpr));
5292 }
5293 let name = operand.named?;
5294 aarch64::named(name.strip_prefix('%').unwrap_or(name))
5295 }
5296
5297 /// An `asm` statement whose operands are `long double` values on the x87 stack.
5298 ///
5299 /// `t` is the top of the stack and `u` is the register under it, and those two letters, or a
5300 /// number tying an input to an output in one of them, are the only places taken here. That is
5301 /// what glibc's old `<bits/mathinline.h>` writes, `fpatan` with `=t`, `0` and `u` and `st(1)`
5302 /// in the clobber list, and it is gcc-torture `execute/990413-2.c`.
5303 ///
5304 /// The group is the shape every other one in [`Self::x87`] has. The inputs are pushed from the
5305 /// deepest up, so the `t` one is pushed last and ends up on top, then the template runs, then
5306 /// the outputs are popped into their slots from the top down. That leaves the stack as empty
5307 /// as it was found only when the template popped every input it was handed and pushed every
5308 /// output it says it leaves, and gcc's rule for these statements says when that is: an input
5309 /// tied to an output or named in the clobber list is one the template pops. So a statement
5310 /// with an input it leaves behind is refused, as is one with an operand anywhere other than
5311 /// `st(0)` and `st(1)`, since nothing here would know what to do with the stack after it.
5312 fn x87_assembly(&mut self, inst: Inst) -> Result<(), Unsupported> {
5313 let data = &self.source[inst];
5314 let Extra::Asm(asm) = data.extra else { return Err(self.unsupported(inst)) };
5315 let info = self.source[asm];
5316 if !self.source[info.targets].is_empty() {
5317 return Err(Unsupported::Assembly { inst, refused: Written::Goto });
5318 }
5319 let refused = || Unsupported::Assembly { inst, refused: Written::Operand };
5320 let constraints = self.names.resolve(info.constraints).to_string();
5321 let results: Vec<Value> = data.results().collect();
5322 let operands = AsmOperands::read(&constraints, &results, &self.source[data.args])
5323 .ok_or_else(refused)?;
5324 let list: Vec<AsmOperand<'_>> = operands.iter().copied().collect();
5325
5326 // Where on the stack each operand is, as a depth from the top.
5327 let letters: Vec<&str> = constraints.split(',').collect();
5328 let mut depths = Vec::with_capacity(list.len());
5329 for (operand, letter) in list.iter().zip(&letters) {
5330 let value = operand.result.or(operand.value).ok_or_else(refused)?;
5331 if operand.memory || !on_x87(self.source[value].ty) {
5332 return Err(refused());
5333 }
5334 let depth = match operand.tied {
5335 Some(output) => *depths.get(output).ok_or_else(refused)?,
5336 None => match letter.trim_start_matches(['=', '+', '&']) {
5337 "t" => 0,
5338 "u" => 1,
5339 _ => return Err(refused()),
5340 },
5341 };
5342 depths.push(depth);
5343 }
5344
5345 // Which depths the clobber list says the template pops.
5346 let clobbers = self.names.resolve(info.clobbers).to_string();
5347 let mut popped = [false; 2];
5348 for entry in clobbers.split(',') {
5349 let entry = entry.trim().trim_matches('"');
5350 let entry = entry.strip_prefix('%').unwrap_or(entry);
5351 match entry {
5352 "" | "memory" | "cc" | "flags" => {}
5353 "st" | "st(0)" => popped[0] = true,
5354 "st(1)" => popped[1] = true,
5355 _ => return Err(Unsupported::Assembly { inst, refused: Written::Clobber }),
5356 }
5357 }
5358
5359 // The inputs, one per depth and from the top down with no gap, and each one popped.
5360 let mut inputs: Vec<Option<Value>> = vec![None; 2];
5361 let mut outputs: Vec<Option<Value>> = vec![None; 2];
5362 for (index, operand) in list.iter().enumerate() {
5363 let depth = depths[index];
5364 if let Some(result) = operand.result {
5365 if outputs[depth].replace(result).is_some() {
5366 return Err(refused());
5367 }
5368 }
5369 let Some(value) = operand.value else { continue };
5370 // An output written `+` is an input tied to itself.
5371 let consumed = operand.result.is_some() || operand.tied.is_some() || popped[depth];
5372 if !consumed {
5373 return Err(refused());
5374 }
5375 if inputs[depth].replace(value).is_some() {
5376 return Err(refused());
5377 }
5378 }
5379 let gapless =
5380 |held: &[Option<Value>]| held.iter().skip_while(|it| it.is_some()).all(Option::is_none);
5381 if !gapless(&inputs) || !gapless(&outputs) {
5382 return Err(refused());
5383 }
5384
5385 // The text, with an operand spelled as the register it is in.
5386 let template = self.names.resolve(info.template).to_string();
5387 let mut text = String::with_capacity(template.len());
5388 let mut chars = template.chars().peekable();
5389 while let Some(c) = chars.next() {
5390 if c != '%' {
5391 text.push(c);
5392 continue;
5393 }
5394 match chars.peek().copied() {
5395 Some('%') => {
5396 chars.next();
5397 text.push('%');
5398 }
5399 Some('=') => {
5400 chars.next();
5401 text.push_str(&inst.index().to_string());
5402 }
5403 Some(digit) if digit.is_ascii_digit() => {
5404 chars.next();
5405 if chars.peek().is_some_and(char::is_ascii_digit) {
5406 return Err(refused());
5407 }
5408 let index = digit.to_digit(10).map_or(usize::MAX, |it| it as usize);
5409 match depths.get(index).ok_or_else(refused)? {
5410 0 => text.push_str("%st"),
5411 depth => text.push_str(&format!("%st({depth})")),
5412 }
5413 }
5414 _ => return Err(refused()),
5415 }
5416 }
5417
5418 let span = self.source.span(inst);
5419 for value in inputs.iter().rev().flatten() {
5420 let from = self.x87_slot(*value);
5421 let from = self.through(from);
5422 self.x87_at("fld_t", span, from);
5423 }
5424 let symbol = self.names.intern(&text);
5425 let opcode = self.named(x86_64::TEMPLATE);
5426 let block = self.at.expect("a block is being filled");
5427 self.out.build(block, opcode).at(span).symbol(symbol).finish();
5428 for value in outputs.iter().flatten() {
5429 let into = self.x87_slot(*value);
5430 let into = self.through(into);
5431 self.x87_at("fstp_t", span, into);
5432 }
5433 Ok(())
5434 }
5435
5436 /// An `asm` statement on AArch64, which is kept as text whatever is in it.
5437 ///
5438 /// Nothing reads AArch64 assembly back into instructions yet, so every template goes the way
5439 /// one the x86 reader could not take apart goes, which is [`Self::kept`]: the text is carried
5440 /// to the listing with a hole for each operand, and the operands are the instruction's own. A
5441 /// constraint with a letter whose meaning differs between the two machines is refused first.
5442 /// See [`shared_letters`].
5443 fn spelled(&mut self, inst: Inst) -> Result<(), Unsupported> {
5444 let data = &self.source[inst];
5445 let Extra::Asm(asm) = data.extra else { return Err(self.unsupported(inst)) };
5446 let info = self.source[asm];
5447 if self.jumps_from_text(inst) {
5448 return Err(Unsupported::Assembly { inst, refused: Written::Goto });
5449 }
5450 let refused = || Unsupported::Assembly { inst, refused: Written::Operand };
5451 let constraints = self.names.resolve(info.constraints).to_string();
5452 if !constraints.split(',').all(shared_letters) {
5453 return Err(refused());
5454 }
5455 // `Q` is memory addressed by one register and nothing else, which is how every operand in
5456 // memory is spelled here already, so it is read as `m`. See [`shared_letters`].
5457 let constraints = letters_outside(&constraints, |c| if c == 'Q' { 'm' } else { c });
5458 let results: Vec<Value> = data.results().collect();
5459 let operands = AsmOperands::read(&constraints, &results, &self.source[data.args])
5460 .ok_or_else(refused)?;
5461 let list: Vec<AsmOperand<'_>> = operands.iter().copied().collect();
5462 let widths = vec![None; list.len()];
5463 let memory: Vec<bool> = list.iter().map(|operand| operand.memory).collect();
5464 let template = self.names.resolve(info.template).to_string();
5465 self.kept(inst, &template, &list, &widths, &memory)
5466 }
5467
5468 /// One instruction of a template, as the machine instruction it was read back into.
5469 fn instruction(
5470 &mut self,
5471 inst: Inst,
5472 line: &x86_64::Line,
5473 places: &[Place],
5474 list: &[AsmOperand<'_>],
5475 clobbered: &[PhysReg],
5476 ) -> Result<(), Unsupported> {
5477 let refused = || Unsupported::Assembly { inst, refused: Written::Operand };
5478 let form = x86_64::form(line.opcode).ok_or_else(refused)?;
5479 // What the instruction reaches and what is in each of them. The description answers the
5480 // first for every opcode but one, and the pieces the template was read into answer the
5481 // second. Bytes a program wrote out itself are the one, since nothing in a number is a
5482 // register anybody could read, so the constraint letters answer both. See
5483 // [`Self::lettered`].
5484 let lettered = (line.opcode == x86_64::LITERAL).then(|| self.lettered(list));
5485 let (described, pieces) = match &lettered {
5486 Some((described, pieces)) => (described.as_slice(), pieces.as_slice()),
5487 None => (form.operands(), line.operands.as_slice()),
5488 };
5489 let mut built = Vec::with_capacity(pieces.len() + clobbered.len());
5490 for (desc, piece) in described.iter().zip(pieces) {
5491 built.push(self.placed(inst, *desc, *piece, places, list)?);
5492 }
5493 // The clobbers go in among the definitions rather than behind the reads, because an operand
5494 // vector in the machine IR is every definition and then every use and what counts them
5495 // reads that order rather than each operand's role.
5496 let defs = built.iter().take_while(|operand| operand.role.is_def()).count();
5497 let mut added = 0usize;
5498 for ® in clobbered {
5499 if described.iter().any(|desc| desc.constraint == Constraint::Fixed(reg)) {
5500 continue;
5501 }
5502 built.insert(defs, mir::Operand::write(mir::Reg::physical(reg), self.gpr));
5503 added += 1;
5504 }
5505 // A constraint tying one operand to another names it by its place in this vector, and the
5506 // clobbers were put in the middle of the vector, so everything behind them moved. The
5507 // description is written against an instruction with no clobbers in it and cannot know
5508 // that, which makes this the one place the two numberings have to be reconciled.
5509 for operand in &mut built {
5510 if let Constraint::Reuse(at) = operand.constraint {
5511 if usize::from(at) >= defs {
5512 let moved = usize::from(at) + added;
5513 operand.constraint =
5514 Constraint::Reuse(u8::try_from(moved).map_err(|_| refused())?);
5515 }
5516 }
5517 }
5518 let at = match line.at {
5519 Some(at) => Some(self.addressed(inst, at, places, list)?),
5520 None => None,
5521 };
5522
5523 let block = self.at.expect("a block is being filled");
5524 let span = self.source.span(inst);
5525 let opcode = self.named(line.opcode);
5526 let mut build = self.out.build(block, opcode).at(span);
5527 for operand in built {
5528 build = build.operand(operand);
5529 }
5530 if let Some(value) = line.imm {
5531 build = build.imm(value);
5532 }
5533 if let Some(mem) = at {
5534 build = build.mem(mem);
5535 }
5536 build.finish();
5537 Ok(())
5538 }
5539
5540 /// The registers a run of bytes reaches, taken from the constraint letters rather than from the
5541 /// description of an opcode.
5542 ///
5543 /// Every other instruction of a template has a description saying which registers it reaches
5544 /// without naming them, and [`Self::assembly`] matches the letters against that. Bytes a program
5545 /// wrote out itself have no such description and could not have one: what the instruction is, is
5546 /// a number, and nothing in a number is a register anything could read. So the letters are the
5547 /// whole of what is known, and they are enough, because a program writing an instruction this
5548 /// way has to say where its operands go for exactly the reason a program writing `cpuid` does.
5549 ///
5550 /// Each register named by a letter gets one entry for the write and one for the read, the same
5551 /// two `cpuid` has, and only the half the statement asked for: a register no output names is not
5552 /// written here and one no input names is not read. The writes come first because that is the
5553 /// order an operand vector in the machine IR is counted in. A register named by nothing is left
5554 /// out rather than given a spare one, which is the difference from `cpuid` and is right for the
5555 /// same reason: `cpuid` writes four registers whatever the program said, and what these bytes
5556 /// touch is known only from what the program said.
5557 fn lettered(&self, list: &[AsmOperand<'_>]) -> (Vec<OperandDesc>, Vec<x86_64::Piece>) {
5558 let mut named: Vec<PhysReg> = Vec::new();
5559 for operand in list {
5560 if let Some(reg) = pinned(operand) {
5561 if !named.contains(®) {
5562 named.push(reg);
5563 }
5564 }
5565 }
5566 let mut described = Vec::with_capacity(named.len() * 2);
5567 let mut pieces = Vec::with_capacity(named.len() * 2);
5568 for role in [Role::Def, Role::Use] {
5569 for ® in &named {
5570 if bound(list, reg, role).is_none() {
5571 continue;
5572 }
5573 let desc = if role.is_def() {
5574 OperandDesc::write(self.gpr)
5575 } else {
5576 OperandDesc::read(self.gpr)
5577 };
5578 described.push(desc.with(Constraint::Fixed(reg)));
5579 pieces.push(x86_64::Piece::Implicit { reg });
5580 }
5581 }
5582 (described, pieces)
5583 }
5584
5585 /// One operand of one instruction of a template, in the register the statement put it in.
5586 fn placed(
5587 &mut self,
5588 inst: Inst,
5589 desc: OperandDesc,
5590 piece: x86_64::Piece,
5591 places: &[Place],
5592 list: &[AsmOperand<'_>],
5593 ) -> Result<mir::Operand, Unsupported> {
5594 let refused = || Unsupported::Assembly { inst, refused: Written::Operand };
5595 // A register the instruction reaches without its text naming it belongs to whichever of the
5596 // statement's operands a constraint letter put there, and to nobody when no letter did.
5597 // There is no width to check in that case: the operand is the register the letter named and
5598 // the instruction does what it does to it, which is what a program writing `"=a"` asked for.
5599 let (index, spelled) = match piece {
5600 x86_64::Piece::Operand { index, width, stated } => (index, Some((width, stated))),
5601 x86_64::Piece::Implicit { reg } => match bound(list, reg, desc.role) {
5602 Some(index) => (index, None),
5603 None => return self.spare(inst, desc),
5604 },
5605 // A register the template named, which belongs to one of the statement's operands when
5606 // a constraint letter put that operand there and to nobody otherwise. Asked in that
5607 // order rather than placed straight away, because `"D" (p)` with `%rdi` in the text is
5608 // the program saying one thing twice, and answering it twice would hand the allocator
5609 // one register holding two values.
5610 x86_64::Piece::Reg { reg, .. } => match bound(list, reg, desc.role) {
5611 Some(index) => (index, None),
5612 None => return self.itself(inst, desc, reg),
5613 },
5614 };
5615 let operand = list.get(index).copied().ok_or_else(refused)?;
5616 // The two halves of an operand written `+`, which arrives in one register and leaves in
5617 // another with the allocator told to make them the same one. Everything else has one of
5618 // the two and asking for the other is the refusal below.
5619 let place = places.get(index).copied().ok_or_else(refused)?;
5620 let reg = match desc.role {
5621 Role::Use => place.read,
5622 Role::Def | Role::EarlyDef => place.write,
5623 }
5624 .ok_or_else(refused)?;
5625
5626 // Read where the opcode reads and written where it writes, which is what the first half of
5627 // this asks. An output has a result and an input has a value, an output written `+` has
5628 // both because it is read before it is written, and an output a matching constraint names
5629 // is read as the input that named it. See [`read_as`].
5630 // An output with neither is read as well, and what it holds there is undefined, which
5631 // [`Self::assembly`] says why and puts a zero in a register for.
5632 let placeable = match desc.role {
5633 Role::Use => read_as(list, index).is_some() || operand.result.is_some(),
5634 Role::Def | Role::EarlyDef => operand.result.is_some(),
5635 };
5636 let ty = match (operand.result, operand.value) {
5637 (Some(result), _) => self.source[result].ty,
5638 (None, Some(value)) => self.source[value].ty,
5639 (None, None) => return Err(refused()),
5640 };
5641 let bits = held_bits(ty);
5642 if !placeable || self.class_of(ty) != desc.class {
5643 return Err(refused());
5644 }
5645 if let Some((width, stated)) = spelled {
5646 // An operand the template wrote a width on may be written by an instruction that fills
5647 // more of the register than the object in it does, and the object is then the low part
5648 // of what was written. That is what gmp asks for when it counts the low zero bits of a
5649 // limb into an `unsigned` and spells the count `%q0`: one quadword instruction writes
5650 // the whole register and the `unsigned` is the bottom of it, which is every bit of an
5651 // answer that cannot exceed sixty four anyway.
5652 //
5653 // An operand read at a width the template wrote is the other way round: the object is
5654 // in the register and the instruction looks at the bottom of it. tcc tests the low bits
5655 // of a `size_t` count with `testb $2,%b4`, and every bit that test reads is one the
5656 // object put there.
5657 //
5658 // A write of less of a register than the object fills is right in one case, which is
5659 // an instruction that reads the register it writes and an operand that arrives with
5660 // the object in it. The top of the register is then the top of the object, and the
5661 // instruction leaves it alone. tcc swaps the bytes of an `unsigned` with `xchgb
5662 // %b0,%h0` and a rotate between two of them, and the swap only ever touches the low
5663 // half.
5664 //
5665 // The two that stay refused are a read of more of a register than its type fills,
5666 // which hands an instruction bits nothing ever put there, and a write of less of one
5667 // that nothing carried the object into, which leaves the top of the object holding
5668 // whatever the register held before. An operand the template left plain is refused
5669 // either way, because what gets spelled for that one is the register at the width of
5670 // its type and no other instruction is the one written down.
5671 let carried = matches!(desc.constraint, Constraint::Reuse(_) | Constraint::Fixed(_))
5672 && read_as(list, index).is_some();
5673 // The other case is the one the machine settles by itself: a write of the low four
5674 // bytes of a register clears the four above them, so a sixty four bit object written
5675 // that way holds the thirty two bit answer and nothing else. tcc loads a word through
5676 // `movl 4(%0),%k0` into a `long` and means exactly that.
5677 let cleared = desc.class == self.gpr && width == x86_64::Width::Long && bits == 64;
5678 let widened = stated && desc.role.is_def() && width.bits() > bits;
5679 let narrowed =
5680 stated && width.bits() < bits && (!desc.role.is_def() || carried || cleared);
5681 if bits != width.bits() && !widened && !narrowed {
5682 return Err(refused());
5683 }
5684 }
5685 // An operand the program pinned is in that register and nowhere else, whatever the opcode
5686 // would have allowed it. That is the whole of what a local register variable asks for, and
5687 // it is the same shape a division already has: the allocator is told the register, puts a
5688 // move in front or behind where it has to, and leaves it out where it does not.
5689 let constraint = match pinned(&operand) {
5690 Some(reg) => Constraint::Fixed(reg),
5691 None => desc.constraint,
5692 };
5693 Ok(mir::Operand { reg, class: desc.class, role: desc.role, constraint })
5694 }
5695
5696 /// A register the template named in its own text.
5697 ///
5698 /// Not one of the statement's operands and not something the allocator handed out. The program
5699 /// wrote `%rbx` in the middle of a template and meant that register, which is what code doing
5700 /// something the constraint letters cannot say is made of: micropython saves the callee-saved
5701 /// registers into a buffer by name because the whole point of the buffer is that those exact
5702 /// registers are in it, and there is no constraint letter for `%rsp`.
5703 ///
5704 /// So it is placed as itself, fixed to the register the template named. What that buys is the
5705 /// thing gcc does not do: the register becomes part of the instruction the allocator sees, so a
5706 /// write of one is a definition it knows about and will not leave anything of the program's
5707 /// across, and a read of one is a use it will not have put something else in first. gcc copies
5708 /// the text out and a register two things believe they own is a wrong program nothing reports.
5709 /// Here the allocator is told, and a program that also named the register in its clobber list
5710 /// says the same thing twice rather than something new.
5711 fn itself(
5712 &mut self,
5713 inst: Inst,
5714 desc: OperandDesc,
5715 reg: PhysReg,
5716 ) -> Result<mir::Operand, Unsupported> {
5717 let refused = Unsupported::Assembly { inst, refused: Written::Operand };
5718 if desc.class != self.gpr {
5719 return Err(refused);
5720 }
5721 Ok(mir::Operand {
5722 reg: mir::Reg::physical(reg),
5723 class: self.gpr,
5724 role: desc.role,
5725 constraint: Constraint::Fixed(reg),
5726 })
5727 }
5728
5729 /// A register an instruction of a template uses and the statement put nothing in.
5730 ///
5731 /// A write of one is the register being destroyed, which is what a clobber list is usually
5732 /// written to say and what an instruction with more answers than the program asked for does
5733 /// anyway: `cpuid` writes all four registers whether or not the statement wanted all four. A
5734 /// register of its own is the whole of what that needs, since a value nothing reads is one the
5735 /// allocator may put anywhere and is told about so that nothing else is put there.
5736 ///
5737 /// A read of one is a register the instruction looks at and the program never filled, which
5738 /// gcc leaves as whatever happened to be there. A zero is written instead, for the reason
5739 /// [`Self::undefined`] gives: the allocator has to be given a definition before a use, and a
5740 /// zero is the one answer that reads the same on every run.
5741 fn spare(&mut self, inst: Inst, desc: OperandDesc) -> Result<mir::Operand, Unsupported> {
5742 let refused = Unsupported::Assembly { inst, refused: Written::Operand };
5743 if desc.class != self.gpr {
5744 return Err(refused);
5745 }
5746 let reg = self.out.new_vreg(desc.class);
5747 if !desc.role.is_def() {
5748 let block = self.at.expect("a block is being filled");
5749 let span = self.source.span(inst);
5750 let put = self.named("mov_ri_64");
5751 self.out.build(block, put).at(span).def(reg, desc.class).imm(0).finish();
5752 }
5753 Ok(mir::Operand { reg, class: desc.class, role: desc.role, constraint: desc.constraint })
5754 }
5755
5756 /// The address one instruction of a template reads or writes.
5757 fn addressed(
5758 &mut self,
5759 inst: Inst,
5760 at: x86_64::At,
5761 places: &[Place],
5762 list: &[AsmOperand<'_>],
5763 ) -> Result<mir::Mem, Unsupported> {
5764 let refused = || Unsupported::Assembly { inst, refused: Written::Operand };
5765 let base = match at.base {
5766 None => None,
5767 Some(x86_64::Piece::Operand { index, .. }) => {
5768 // The register an address is counted from is read and never written, whatever the
5769 // instruction does to what it finds there.
5770 let reg = places.get(index).and_then(|place| place.read).ok_or_else(refused)?;
5771 Some(mir::Operand::read(reg, self.gpr))
5772 }
5773 // A register the template named, counted from as itself. See [`Self::itself`], and note
5774 // that this is the half of it every one of these templates needs: `movq %rax, 16(%rdi)`
5775 // names one register as the thing being stored and another as where to store it. An
5776 // operand a constraint letter put in that register is that operand, for the reason
5777 // [`Self::placed`] gives.
5778 Some(x86_64::Piece::Reg { reg, .. }) => match bound(list, reg, Role::Use) {
5779 Some(index) => {
5780 let reg = places.get(index).and_then(|place| place.read).ok_or_else(refused)?;
5781 Some(mir::Operand::read(reg, self.gpr))
5782 }
5783 None => Some(
5784 mir::Operand::read(mir::Reg::physical(reg), self.gpr)
5785 .with(Constraint::Fixed(reg)),
5786 ),
5787 },
5788 // An address counted from a register the instruction reaches without being told is
5789 // not something this machine has: every addressing mode is written out in the text it
5790 // is part of, so a base that got here another way is a base nothing wrote down.
5791 Some(x86_64::Piece::Implicit { .. }) => return Err(refused()),
5792 };
5793 // A distance the template wrote, or the one in an operand the template pointed at, which is
5794 // the same distance said by something that knows how big a thing is. It has to be a number
5795 // the compiler can read at translation time, since it goes in the instruction rather than
5796 // in a register, and an operand holding anything else is refused rather than put somewhere.
5797 let disp = match at.disp {
5798 x86_64::Disp::Number(disp) => disp,
5799 x86_64::Disp::Operand(index) => {
5800 let value =
5801 list.get(index).and_then(|operand| operand.value).ok_or_else(refused)?;
5802 let number = self.number(value).ok_or_else(refused)?;
5803 i32::try_from(number).map_err(|_| refused())?
5804 }
5805 };
5806 Ok(mir::Mem { base, scale: 1, disp, segment: at.segment, ..mir::Mem::default() })
5807 }
5808
5809 /// The number in that value, for one an `iconst` defined, read at the width of its own type.
5810 ///
5811 /// Signed, because the two things a template asks this for are a distance into an address and
5812 /// the number on an instruction, and both of those are signed wherever they land. A constant
5813 /// whose type is unsigned and whose top bit is set therefore reads as a negative number here,
5814 /// which is the same number and is the reading that fits in the thirty two bits an addressing
5815 /// mode has room for.
5816 fn number(&self, value: Value) -> Option<i128> {
5817 let Def::Result { inst, .. } = self.source[value].def else { return None };
5818 if self.source[inst].opcode != Opcode::IConst {
5819 return None;
5820 }
5821 let Extra::Imm(imm) = self.source[inst].extra else { return None };
5822 let bits = self.source[imm].bits();
5823 let width = self.source[value].ty.bits();
5824 if width == 0 || width > 128 {
5825 return None;
5826 }
5827 let spare = 128 - width;
5828 Some(((bits << spare) as i128) >> spare)
5829 }
5830
5831 /// A register holding a value the program has no claim on, written as a zero.
5832 ///
5833 /// Every other way of saying it costs the same instruction or needs a word the machine IR does
5834 /// not have, and a zero is the one that reads the same on every run.
5835 fn undefined(&mut self, inst: Inst, result: Value) -> Result<(), Unsupported> {
5836 let ty = self.source[result].ty;
5837 let refused = Unsupported::Assembly { inst, refused: Written::Operand };
5838 let bits = held_bits(ty);
5839 if self.class_of(ty) != self.gpr || !matches!(bits, 8 | 16 | 32 | 64) {
5840 return Err(refused);
5841 }
5842 let block = self.at.expect("a block is being filled");
5843 let span = self.source.span(inst);
5844 let reg = self.new_reg(result);
5845 let put = self.named(&format!("mov_ri_{bits}"));
5846 self.out.build(block, put).at(span).def(reg, self.gpr).imm(0).finish();
5847 Ok(())
5848 }
5849
5850 /// Whether a type is the width an address is, which is what makes a cast to or from one free.
5851 fn is_address_width(&self, ty: Type) -> bool {
5852 ty.is_ptr() || (ty.is_int() && ty.bits() == ADDRESS_BITS)
5853 }
5854
5855 /// Where a block goes, which in machine IR is on the block rather than on its terminator.
5856 ///
5857 /// That is why no rule ever names a block: a branch is selected for what it reads and the
5858 /// edges are copied across here, arguments and all. The arguments are read last, after every
5859 /// instruction of the block is written, because an argument that is a constant is
5860 /// materialized where it is first wanted and the end of the block is where an edge wants it.
5861 ///
5862 /// Which is not quite the end. A block that leaves two ways has the branch as its last
5863 /// instruction, and a block that leaves through a register has the indirect jump as its last,
5864 /// and anything appended after either is something it has already jumped past, so a constant
5865 /// materialized here would be a register the block below reads and nothing ever writes. The
5866 /// one that was there is put back on the end when that happened, which is the only reordering
5867 /// anything in this crate does and is why it is remembered before a single argument is read.
5868 fn edges(&mut self, block: Block, out: mir::Block) -> Result<(), Unsupported> {
5869 let Some(term) = self.source.terminator(block) else { return Ok(()) };
5870 // An `asm goto` whose template has nothing in it can only fall through, since there is no
5871 // instruction in it to jump with, so the only edge the machine block gets is the first
5872 // one. The labels it names are still arms in the IR, which is what kept the passes above
5873 // from assuming anything about the way into them, and here they are blocks nothing jumps
5874 // to, the same as a label no `goto` names. One that does have instructions was refused by
5875 // [`Self::jumps_from_text`] before this.
5876 if self.source[term].opcode == Opcode::InlineAsm {
5877 let Some(call) = self.source.successors(term).next() else { return Ok(()) };
5878 let args: Vec<Value> = self.source[call.args].to_vec();
5879 let regs =
5880 args.into_iter().map(|value| self.reg_of(value)).collect::<Result<_, _>>()?;
5881 *self.out.succs_mut(out) = vec![mir::BlockCall::with(self.out_block(call.block), regs)];
5882 return Ok(());
5883 }
5884 // A call's unwind edge, which is not an edge of the machine function at all. The branch was
5885 // never written, so what the block has is the arm control takes when the call returns, and
5886 // the pad is a block with nothing in front of it that the call site table is what reaches.
5887 // See [`Self::pad`] for why that is a block the allocator can be handed.
5888 if let Some(unwound) = self.unwind_edge(term) {
5889 let arms: Vec<rucc_ir::BlockCall> = self.source.successors(term).collect();
5890 let next = arms[1];
5891 let args: Vec<Value> = self.source[next.args].to_vec();
5892 let regs =
5893 args.into_iter().map(|value| self.reg_of(value)).collect::<Result<_, _>>()?;
5894 *self.out.succs_mut(out) = vec![mir::BlockCall::with(self.out_block(next.block), regs)];
5895 let call = self.source.prev_inst(unwound).and_then(|call| self.unwinding.get(&call));
5896 if let Some(&call) = call {
5897 let pad = self.out_block(arms[0].block);
5898 self.out.landings.push((call, pad));
5899 }
5900 return Ok(());
5901 }
5902 let leaves =
5903 matches!(self.source[term].opcode, Opcode::BrIf | Opcode::IndirectBr | Opcode::Switch);
5904 let branch = if leaves { self.out.terminator(out) } else { None };
5905
5906 let calls: Vec<rucc_ir::BlockCall> = self.source.successors(term).collect();
5907 let mut succs = Vec::with_capacity(calls.len());
5908 for call in calls {
5909 let args: Vec<Value> = self.source[call.args].to_vec();
5910 let mut regs = Vec::with_capacity(args.len());
5911 for value in args {
5912 // The address of where the value is rather than the value, for the one type a
5913 // register holds none of. The block on the other side copies the bytes out of it
5914 // into a slot of its own, which is what makes a second edge into the same block
5915 // safe.
5916 let reg = if on_x87(self.source[value].ty) {
5917 self.x87_slot(value)
5918 } else {
5919 self.reg_of(value)?
5920 };
5921 regs.push(reg);
5922 }
5923 succs.push(mir::BlockCall::with(self.out_block(call.block), regs));
5924 }
5925 if let Some(branch) = branch {
5926 if self.out.terminator(out) != Some(branch) {
5927 self.out.remove_inst(branch);
5928 self.out.append_inst(out, branch);
5929 }
5930 }
5931 *self.out.succs_mut(out) = succs;
5932 Ok(())
5933 }
5934
5935 /// The `unwound` a branch reads, when the branch is a call's unwind edge.
5936 fn unwind_edge(&self, inst: Inst) -> Option<Inst> {
5937 let data = &self.source[inst];
5938 if data.opcode != Opcode::BrIf {
5939 return None;
5940 }
5941 let &cond = self.source[data.args].first()?;
5942 match self.source[cond].def {
5943 Def::Result { inst, .. } if self.source[inst].opcode == Opcode::Unwound => Some(inst),
5944 _ => None,
5945 }
5946 }
5947
5948 /// The exception a landing pad was entered with, as a copy out of the register the unwinder
5949 /// left it in, which is the first register a value comes back in.
5950 fn landing(&mut self, inst: Inst) -> Result<(), Unsupported> {
5951 let result = self.source[inst].first_result.ok_or_else(|| self.unsupported(inst))?;
5952 let held = *self.conv.int_returns.first().ok_or_else(|| self.unsupported(inst))?;
5953 let block = self.at.expect("a block is being filled");
5954 let span = self.source.span(inst);
5955 let mov = self.selector.frame.moves(self.gpr).expect("a class the target says how to move");
5956 let mov = self.named(mov.mov);
5957 let into = self.new_reg(result);
5958 self.out
5959 .build(block, mov)
5960 .at(span)
5961 .operand(mir::Operand::write(into, self.gpr))
5962 .operand(
5963 mir::Operand::read(mir::Reg::physical(held), self.gpr)
5964 .with(Constraint::Fixed(held)),
5965 )
5966 .finish();
5967 Ok(())
5968 }
5969
5970 /// Makes a landing pad a block that reads nothing from the blocks around it, and says what to
5971 /// put back once it has been filled.
5972 ///
5973 /// The pad has no machine block in front of it, because the edge into it is not one the machine
5974 /// takes: control arrives from the unwinder, with the registers the frame rules at the call put
5975 /// back. So nothing the allocator keeps in a register can reach it, and a value it reads from
5976 /// elsewhere is made again inside it. What a pad reads is the address of each object a handler
5977 /// is owed, which is a slot of the frame, the address of a name, or a constant, and each of
5978 /// those can be written a second time from nothing. Anything else is refused.
5979 ///
5980 /// The registers the rest of the function knows those values by are put back afterwards,
5981 /// which is what the answer is for: the pad's copies are its own.
5982 fn pad(&mut self, block: Block) -> Result<Vec<(Value, Option<mir::Reg>)>, Unsupported> {
5983 let mut kept = Vec::new();
5984 let first = self.source.insts(block).next();
5985 if !first.is_some_and(|inst| self.source[inst].opcode == Opcode::Landing) {
5986 return Ok(kept);
5987 }
5988 let insts: Vec<Inst> = self.source.insts(block).collect();
5989 for inst in insts {
5990 let args: Vec<Value> = self.source[self.source[inst].args].to_vec();
5991 for value in args {
5992 let Def::Result { inst: def, .. } = self.source[value].def else {
5993 return Err(self.unsupported(inst));
5994 };
5995 if self.source.block_of(def) == Some(block)
5996 || kept.iter().any(|&(done, _)| done == value)
5997 {
5998 continue;
5999 }
6000 // A constant, a slot of the frame and most names are written again in every
6001 // block that reads them anyway, by [`Self::reg_of`], so there is nothing to do for
6002 // those here. See [`Rebuilt`].
6003 if self.rebuilt(value).is_some() {
6004 continue;
6005 }
6006 match self.source[def].opcode {
6007 Opcode::GlobalAddr => {
6008 kept.push((value, self.regs[value.index()]));
6009 self.regs[value.index()] = None;
6010 self.address_of(def)?;
6011 }
6012 _ => return Err(self.unsupported(def)),
6013 }
6014 }
6015 }
6016 Ok(kept)
6017 }
6018
6019 /// Whether an `asm goto` has instructions in its template, which is what it would jump with.
6020 ///
6021 /// One with an empty template is what a program writes to tell the optimizer that control may
6022 /// arrive at a label without saying how, and the torture suite has several of them. It never
6023 /// jumps, so it is written as the statement it would be without its labels and a fall through
6024 /// into its first arm. See [`Self::edges`]. One with anything in it needs the labels it names
6025 /// written into the text and an edge for each of them the allocator knows about, and that is
6026 /// still refused.
6027 fn jumps_from_text(&self, inst: Inst) -> bool {
6028 let Extra::Asm(asm) = self.source[inst].extra else { return false };
6029 let info = self.source[asm];
6030 !self.source[info.targets].is_empty()
6031 && !self.names.resolve(info.template).trim().is_empty()
6032 }
6033
6034 /// The machine IR block an IR block became.
6035 fn out_block(&self, block: Block) -> mir::Block {
6036 self.blocks[block.index()].expect("every block was created before any was filled")
6037 }
6038
6039 /// The parameters of the entry block, which are the function's arguments.
6040 ///
6041 /// They are not block parameters in the machine IR and they cannot be. A block parameter is
6042 /// given its value by a move on the edge into the block, and there is no edge into an entry
6043 /// block, so what arrives in a function is the convention's to say. [`crate::abi`] is what
6044 /// says it.
6045 ///
6046 /// The ones past the last register arrived in the caller's memory and are read out of it, and
6047 /// the loads that read them come back here so that the frame can finish them the way it
6048 /// finishes an `alloca`.
6049 fn arrive(&mut self, block: Block, out: mir::Block) -> Result<(), Unsupported> {
6050 let params = self.source[block].params.clone();
6051 // The type of each is the block's answer and what the ABI asks of it is the signature's,
6052 // and the two lists are the same list: a parameter the classification turned into a
6053 // pointer is a pointer in the block too. A block with more parameters than the signature
6054 // names is not one the front end writes, and each of those is taken as a plain value.
6055 let asked: Vec<Abi> = self.source.signature().params.iter().map(|it| it.abi).collect();
6056 let types: Vec<Param> = params
6057 .iter()
6058 .enumerate()
6059 .map(|(index, &value)| {
6060 let abi = asked.get(index).copied().unwrap_or_default();
6061 Param { ty: self.source[value].ty, abi }
6062 })
6063 .collect();
6064 // A save area for a function that takes arguments its signature does not name, which is a
6065 // block of this function's frame on one convention and the shadow space the caller already
6066 // reserved on the other. Which of the two it is is [`varargs::Area::of`]'s answer and
6067 // [`Self::save_area`] is where the difference is spent.
6068 //
6069 // Apple's AArch64 is neither. Every argument a signature does not name is in the caller's
6070 // memory, so there is nothing to save and the list starts at the first word past the named
6071 // ones.
6072 //
6073 // A function holding `__builtin_apply_args` asks for the same area whether it is variadic
6074 // or not, because what it saves is every argument register, and the area is where the
6075 // walk that binds them says where each one goes.
6076 //
6077 // Windows on AArch64 is the first kind seen from the other side. The caller reserves
6078 // nothing, so the function takes the words it homes its x registers in at the top of its
6079 // own frame, and from inside it that is a shadow space like Windows x64's. So the
6080 // registers the parameters are bound through are [`rucc_target::CallRegs::homed`], and
6081 // the prologue [`crate::finish`] writes takes the bytes before it saves anything.
6082 let variadic = self.source.signature().variadic;
6083 let foreign = self.source.signature().convention != Convention::Target;
6084 let homes = variadic && !foreign && self.conv.home > 0;
6085 let conv = if homes { self.conv.homed() } else { *self.conv };
6086 if homes {
6087 self.stack.home = self.conv.home;
6088 }
6089 let in_memory = self.conv.abi.variadic == Variadic::AlwaysMemory;
6090 let applies = self.saves_arguments();
6091 let area = (variadic && !in_memory || applies).then(|| varargs::Area::of(&conv));
6092 let arrived =
6093 abi::entry(&mut self.out, out, &types, &conv, self.selector.abi, self.names, area)
6094 .map_err(|(index, missing)| Unsupported::Argument { index, missing })?;
6095 for (¶m, reg) in params.iter().zip(&arrived.regs) {
6096 self.regs[param.index()] = Some(*reg);
6097 }
6098 if applies {
6099 self.save_arguments(out, &arrived);
6100 }
6101 // A variadic function of the convention the platform does not call its own has no list
6102 // this can start. Its `va_list` would have to be the other platform's, which is a type C
6103 // has no name for here, and the front end refuses a definition with `...` in it for that
6104 // reason. What is left is an old style definition, which is variadic to a caller and has
6105 // no `...` for a `va_start` to follow, so nothing is set up and a `va_start` that reached
6106 // here all the same would be refused rather than read the wrong list.
6107 let variadic = variadic && !foreign;
6108 if let (true, Some(area)) = (variadic && !in_memory, area) {
6109 self.save_area(out, &arrived, area, conv.shared_positions);
6110 } else if variadic {
6111 let incoming = arrived.beyond.next_multiple_of(self.conv.word);
6112 self.varargs = Some(Varargs::Pointer { incoming });
6113 }
6114 self.stack.arguments.extend(arrived.stack);
6115 Ok(())
6116 }
6117
6118 /// The prologue of a variadic function, which is every argument register it was handed written
6119 /// into the frame.
6120 ///
6121 /// Every one the signature did not name, that is. Which of those hold anything is a thing only
6122 /// the caller knew and there is nothing here to ask, so all of them are written, and the ones a
6123 /// named parameter took are not, because `va_start` sets the two offsets past them and nothing
6124 /// ever reads their slots.
6125 ///
6126 /// What that costs is up to fourteen stores in the prologue of a function that may read none of
6127 /// them, and the convention's answer to that is the count of vector registers in `%al`, which
6128 /// lets a callee skip the eight vector stores when the call passed no floats. Skipping them is a
6129 /// branch in a prologue, and a prologue is written long after this by [`crate::finish`], which
6130 /// has no blocks to branch between. So they are all written every time, which is correct and is
6131 /// what `-O0` costs. Issue #323 is the branch.
6132 ///
6133 /// A vector register is written all sixteen bytes at a time, because a `_Float128` fills one and
6134 /// a `va_arg` of a quad reads the slot back whole. gcc writes the same sixteen with the same
6135 /// instruction, which is what [`crate::varargs`] says a list has to be built out of.
6136 ///
6137 /// The address is computed once into a register rather than written as a displacement off the
6138 /// stack pointer, because a displacement into a frame is not known until after allocation and
6139 /// one `lea` costs less than a fixup list for a dozen stores. It is the same `lea` an `alloca`
6140 /// gets and [`crate::finish`] fills it in the same way.
6141 ///
6142 /// A convention that homes its register arguments has none of that. Its area is the shadow
6143 /// space the caller reserved above the return address, so there is no object to make and no
6144 /// address to work out: each store reaches into the caller's argument area the way the load of
6145 /// a parameter the registers ran out before does, which is the same waiting list and the same
6146 /// fixup. There are at most four of them and none is a vector register, since a float the
6147 /// signature does not name arrived in a general purpose register too and that is the copy the
6148 /// walk reads.
6149 ///
6150 /// Windows on AArch64 homes its registers the same way, in an area the function takes for
6151 /// itself rather than one the caller left, and `shared` is what says a function is one of these.
6152 fn save_area(
6153 &mut self,
6154 out: mir::Block,
6155 arrived: &abi::Arrived,
6156 area: varargs::Area,
6157 shared: bool,
6158 ) {
6159 if shared {
6160 self.varargs = Some(Varargs::Pointer { incoming: arrived.beyond });
6161 let head =
6162 (self.selector.abi.store)(Type::int(64)).expect("a store of a whole register");
6163 let store = mir::Opcode::new(self.names.intern(head));
6164 for &(reg, class, at) in &arrived.spare {
6165 let sp = mir::Operand::read(mir::Reg::physical(self.conv.stack_pointer), self.gpr);
6166 let made =
6167 self.out.build(out, store).uses(reg, class).mem(mir::Mem::at(sp)).finish();
6168 self.stack.arguments.push((made, at));
6169 }
6170 return;
6171 }
6172
6173 let save = self.stack.locals.len();
6174 self.stack.locals.push(Local { size: area.size, align: varargs::VECTOR_SLOT });
6175 let took = |count: usize, float: bool| {
6176 let count = u32::try_from(count).unwrap_or(0).min(area.holds(float));
6177 area.starts_at(float) + count * area.stride(float)
6178 };
6179 let integers = took(arrived.took.0, false);
6180 let floats = took(arrived.took.1, true);
6181 self.varargs = Some(if self.conv.list == VaList::Aapcs {
6182 // Minus what is left of each half, since the two offsets count up to its top.
6183 let left = |at: u32, float: bool| {
6184 i32::try_from(at).unwrap_or(0) - i32::try_from(area.ends_at(float)).unwrap_or(0)
6185 };
6186 Varargs::Aapcs {
6187 save,
6188 incoming: arrived.beyond,
6189 integers_end: area.ends_at(false),
6190 floats_end: area.ends_at(true),
6191 integers: left(integers, false),
6192 floats: left(floats, true),
6193 }
6194 } else {
6195 Varargs::Fields { save, incoming: arrived.beyond, integers, floats }
6196 });
6197
6198 // A vector register is saved all sixteen bytes wide, as a quad is, whatever it held.
6199 let base = self.frame_address(out, save);
6200 for &(reg, class, at) in &arrived.spare {
6201 let ty =
6202 if class == self.gpr { Type::int(64) } else { Type::float(rucc_ir::Float::F128) };
6203 let head = (self.selector.abi.store)(ty).expect("a store of a whole register");
6204 let store = mir::Opcode::new(self.names.intern(head));
6205 let up = i32::try_from(at).expect("a register save area under two gigabytes");
6206 let mem = mir::Mem::at(mir::Operand::read(base, self.gpr)).plus(up);
6207 self.out.build(out, store).uses(reg, class).mem(mem).finish();
6208 }
6209 }
6210
6211 /// Whether the function holds a `__builtin_apply_args`, on a convention this can save the
6212 /// arguments of.
6213 ///
6214 /// Only the one that keeps the two register files apart and saves them the way a SysV list
6215 /// does, since the block is that layout with one word in front of it. On any other the call is
6216 /// refused where it stands, which is [`Self::apply_args`] finding nothing saved.
6217 fn saves_arguments(&self) -> bool {
6218 if self.conv.list != VaList::SysV || self.conv.shared_positions {
6219 return false;
6220 }
6221 let source = self.source;
6222 source
6223 .blocks()
6224 .any(|block| source.insts(block).any(|inst| source[inst].opcode == Opcode::ApplyArgs))
6225 }
6226
6227 /// The prologue of a function holding `__builtin_apply_args`, which is every argument register
6228 /// it was handed and where the arguments in memory start, written into a block of its frame.
6229 ///
6230 /// The block is the one gcc lays out on this convention, so that a program reading it the way
6231 /// gcc's manual says reads the same bytes:
6232 ///
6233 /// ```text
6234 /// 0 where the arguments that came in memory are
6235 /// 8 nothing, so that what follows is sixteen byte aligned
6236 /// 16..64 the six general purpose argument registers, a word each
6237 /// 64..192 the eight vector argument registers, sixteen bytes each
6238 /// ```
6239 ///
6240 /// Which is the register save area of a variadic function with a word and a pad in front, so
6241 /// the offsets are that area's plus sixteen. What is different is that every register is
6242 /// written and not only the ones no parameter took: the one a parameter arrived in is written
6243 /// from the register the parameter was bound to, which holds it untouched because nothing has
6244 /// run yet, and the rest from the pseudos the walk made for them.
6245 fn save_arguments(&mut self, out: mir::Block, arrived: &abi::Arrived) {
6246 let applied = self.stack.locals.len();
6247 self.stack.locals.push(Local { size: APPLY_ARGS, align: varargs::VECTOR_SLOT });
6248 self.applied = Some(applied);
6249 let base = self.frame_address(out, applied);
6250 let overflow = self.overflow(out, 0, Span::DUMMY);
6251 let head = (self.selector.abi.store)(Type::int(64)).expect("a store of an address");
6252 let store = mir::Opcode::new(self.names.intern(head));
6253 let mem = mir::Mem::at(mir::Operand::read(base, self.gpr));
6254 self.out.build(out, store).uses(overflow, self.gpr).mem(mem).finish();
6255
6256 let named = arrived.named.iter().map(|&(index, at)| {
6257 let reg = arrived.regs[index];
6258 let class = self.out.class_of(reg).unwrap_or(self.gpr);
6259 (reg, class, at)
6260 });
6261 let every: Vec<_> = named.chain(arrived.spare.iter().copied()).collect();
6262 for (reg, class, at) in every {
6263 let ty =
6264 if class == self.gpr { Type::int(64) } else { Type::float(rucc_ir::Float::F128) };
6265 let head = (self.selector.abi.store)(ty).expect("a store of a whole register");
6266 let store = mir::Opcode::new(self.names.intern(head));
6267 let up = i32::try_from(at + APPLY_REGS).expect("a block of under two gigabytes");
6268 let mem = mir::Mem::at(mir::Operand::read(base, self.gpr)).plus(up);
6269 self.out.build(out, store).uses(reg, class).mem(mem).finish();
6270 }
6271 }
6272
6273 /// One `__builtin_apply_args`, which is the address of the block the prologue wrote.
6274 fn apply_args(&mut self, inst: Inst) -> Result<(), Unsupported> {
6275 let Some(applied) = self.applied else { return Err(self.unsupported(inst)) };
6276 let result = self.source[inst].first_result.ok_or_else(|| self.unsupported(inst))?;
6277 let block = self.at.expect("a block is being filled");
6278 let reg = self.frame_address(block, applied);
6279 self.regs[result.index()] = Some(reg);
6280 Ok(())
6281 }
6282
6283 /// One `__builtin_apply`, which is a call whose arguments are every register in a block
6284 /// `__builtin_apply_args` answered and some bytes of the memory it says the arguments in
6285 /// memory were in.
6286 ///
6287 /// Built as a call of fourteen arguments, six words and eight vectors, which puts each in the
6288 /// register it came out of, and one object of the size the program gave, which is copied into
6289 /// the bottom of the outgoing area the way a structure passed by value is. The call is made as
6290 /// to a variadic function, so the count of vector registers is eight and a variadic callee
6291 /// saves all of them.
6292 ///
6293 /// What comes back is every register a value can come back in, which is two of each file, and
6294 /// they are written into a block of this function's frame whose address is the answer: the two
6295 /// words at 0 and 8 and the two vectors at 16 and 32. An eighty bit value comes back on the x87
6296 /// stack and is not in it, which is the one thing gcc's block holds that this one does not.
6297 fn apply(&mut self, inst: Inst) -> Result<(), Unsupported> {
6298 if self.conv.list != VaList::SysV || self.conv.shared_positions {
6299 return Err(self.unsupported(inst));
6300 }
6301 let values: Vec<Value> = self.source[self.source[inst].args].to_vec();
6302 let [function, saved, size] = values[..] else { return Err(self.unsupported(inst)) };
6303 let size = self.number(size).ok_or_else(|| self.unsupported(inst))?;
6304 let size = u32::try_from(size).map_err(|_| self.unsupported(inst))?;
6305 let result = self.source[inst].first_result.ok_or_else(|| self.unsupported(inst))?;
6306 let function = self.reg_of(function)?;
6307 let saved = self.reg_of(saved)?;
6308 let block = self.at.expect("a block is being filled");
6309 let span = self.source.span(inst);
6310
6311 let word = Type::int(64);
6312 let vector = Type::float(rucc_ir::Float::F128);
6313 let area = varargs::Area::of(self.conv);
6314 let load = |ty: Type| (self.selector.abi.load)(ty).expect("a load of a whole register");
6315 let (load_word, load_vector) = (load(word), load(vector));
6316 let mut read = |ty: Type, head: &str, class: RegClass, at: u32| {
6317 let reg = self.out.new_vreg(class);
6318 let opcode = mir::Opcode::new(self.names.intern(head));
6319 let at = i32::try_from(at).expect("a block of under two gigabytes");
6320 let mem = mir::Mem::at(mir::Operand::read(saved, self.gpr)).plus(at);
6321 self.out.build(block, opcode).at(span).def(reg, class).mem(mem).finish();
6322 abi::Passing { ty, reg, abi: Abi::Plain }
6323 };
6324 let sse = self.conv.sse_class;
6325 let gpr = self.gpr;
6326 let mut args = Vec::with_capacity(15);
6327 for (float, ty, head, class) in
6328 [(false, word, load_word, gpr), (true, vector, load_vector, sse)]
6329 {
6330 for index in 0..area.holds(float) {
6331 let at = APPLY_REGS + area.starts_at(float) + index * area.stride(float);
6332 args.push(read(ty, head, class, at));
6333 }
6334 }
6335 if size > 0 {
6336 let memory = read(word, load_word, gpr, 0);
6337 let object =
6338 Abi::ByVal { size: u64::from(size), align: 8, drains: rucc_ir::Drains::Nothing };
6339 args.push(abi::Passing { abi: object, ..memory });
6340 }
6341 let returns = [word, word, vector, vector];
6342 let what = abi::Calling {
6343 callee: abi::Callee::Through(function),
6344 args: &args,
6345 returns: &returns,
6346 variadic: true,
6347 named: args.len(),
6348 at: span,
6349 };
6350 let made = abi::call(&mut self.out, block, &what, self.conv, self.selector.abi, self.names)
6351 .map_err(|refused| Unsupported::Call { inst, refused })?;
6352 let calls = &mut self.stack.calls;
6353 *calls = Some(calls.unwrap_or(0).max(made.outgoing));
6354
6355 let back = self.stack.locals.len();
6356 self.stack.locals.push(Local { size: APPLY_BACK, align: varargs::VECTOR_SLOT });
6357 let base = self.frame_address(block, back);
6358 for ((®, ty), at) in made.results.iter().zip(returns).zip([0, 8, 16, 32]) {
6359 let class = if ty == word { gpr } else { sse };
6360 let head = (self.selector.abi.store)(ty).expect("a store of a whole register");
6361 let store = mir::Opcode::new(self.names.intern(head));
6362 let mem = mir::Mem::at(mir::Operand::read(base, self.gpr)).plus(at);
6363 self.out.build(block, store).at(span).uses(reg, class).mem(mem).finish();
6364 }
6365 let answer = self.frame_address(block, back);
6366 self.regs[result.index()] = Some(answer);
6367 Ok(())
6368 }
6369
6370 /// The address of one of the function's stack objects, in a fresh register.
6371 ///
6372 /// Written with nothing in its displacement, because where an object is in a frame is not known
6373 /// until after allocation, and given to [`crate::finish`] to fill in the way an `alloca` is.
6374 fn frame_address(&mut self, out: mir::Block, local: usize) -> mir::Reg {
6375 self.frame_address_plus(out, local, 0)
6376 }
6377
6378 /// The address some way into a local, which the frame finishes the same way, adding where the
6379 /// local is to what is already there.
6380 fn frame_address_plus(&mut self, out: mir::Block, local: usize, plus: u32) -> mir::Reg {
6381 let reg = self.out.new_vreg(self.gpr);
6382 let lea = self.named(self.selector.frame.lea);
6383 let sp = mir::Operand::read(mir::Reg::physical(self.conv.stack_pointer), self.gpr);
6384 let plus = i32::try_from(plus).expect("an offset into a local under two gigabytes");
6385 let mem = mir::Mem::at(sp).plus(plus);
6386 let made = self.out.build(out, lea).def(reg, self.gpr).mem(mem).finish();
6387 self.stack.addresses.push((made, local));
6388 reg
6389 }
6390
6391 /// Whether an instruction is one no machine instruction is written for where it stands.
6392 ///
6393 /// Four of them, and none is a lowering decision, which is why none is a rule. A constant is
6394 /// written where a register for it is first wanted rather than where the IR put it, and every
6395 /// reader of one may have folded it into an immediate, in which case nowhere is the right
6396 /// place. A return of nothing has nothing to put anywhere: the epilogue gives the frame back
6397 /// and leaves, and it is appended to every block with no successors long after this has
6398 /// finished, so a return with a value is one instruction here and a return without one is
6399 /// none. Unless the value went back through memory, in which case there is something to put
6400 /// somewhere after all and the IR does not carry it: the address the caller handed over has
6401 /// to be in `rax` on the way out, and [`Lowering::returned`] is what writes that.
6402 ///
6403 /// An unconditional jump is the third, and there is even less of it: the edge is on the
6404 /// block, and whether the block it goes to is the next one and needs no jump at all is the
6405 /// block layout's answer rather than this one's.
6406 ///
6407 /// The fourth is a point control does not arrive at, in both of the forms the IR has for it:
6408 /// the `unreachable` terminator the front end puts at the end of a function whose body can run
6409 /// off the bottom, and the `unreachable_hint` a call to `__builtin_unreachable` becomes. What
6410 /// to write for a place nothing reaches is a question with no wrong answer, and nothing is the
6411 /// smallest one and the one gcc 16.2.0 gives at `-O0`. The terminator leaves the block with no
6412 /// successors, so the epilogue lands at the end of it the way it does on any other block that
6413 /// goes nowhere, and the function cannot fall out of its own last instruction into whatever
6414 /// the assembler puts next.
6415 fn writes_nothing(&self, inst: Inst) -> bool {
6416 let data = &self.source[inst];
6417 match data.opcode {
6418 Opcode::IConst | Opcode::Jump | Opcode::Unreachable | Opcode::UnreachableHint => true,
6419 // The question of whether a call unwound and the branch on its answer, neither of which
6420 // is an instruction. See [`Self::edges`].
6421 Opcode::Unwound => true,
6422 Opcode::BrIf => self.unwind_edge(inst).is_some(),
6423 Opcode::Return => self.source[data.args].is_empty() && self.sret().is_none(),
6424 _ => false,
6425 }
6426 }
6427
6428 /// What every instruction in one block matched, with a set of values nobody may take.
6429 ///
6430 /// Backwards, because an instruction that has been folded into a later one does not get to
6431 /// fold anything into itself: the rule that took it only reached one level down, so what is
6432 /// under it is not in the term the matcher saw and cannot be replaced.
6433 fn decide(&self, insts: &[Inst], refused: &Set<Value>) -> Decided {
6434 let mut found: Vec<Option<Match<Term>>> = (0..insts.len()).map(|_| None).collect();
6435 let mut plans: Vec<Option<Plan>> = vec![None; insts.len()];
6436 let mut folded: Vec<Inst> = Vec::new();
6437 for (index, &inst) in insts.iter().enumerate().rev() {
6438 if folded.contains(&inst) {
6439 continue;
6440 }
6441 if let Some((plan, matched)) = self.select(inst, refused) {
6442 folded.extend(self.folds(inst, plan));
6443 found[index] = Some(matched);
6444 plans[index] = Some(plan);
6445 }
6446 }
6447 Decided { found, plans, folded }
6448 }
6449
6450 /// A value some of its readers took and some of them did not, which is the one case folding
6451 /// buys nothing.
6452 ///
6453 /// Folding does not delete the instruction that computed a value for anybody else, so a
6454 /// reader that did not take it still needs it in a register and the instruction stays. The
6455 /// reader that did take it now does that work again. Either all of them take it, in which
6456 /// case nothing is left to read it and the instruction goes, or none of them do.
6457 ///
6458 /// The count is over the whole function rather than over the block, since a value read from
6459 /// another block is read from a register there whatever this block decides. An instruction
6460 /// built by name rather than matched, a call being the one that matters, has no plan and so
6461 /// takes nothing, which is the right answer for it as well.
6462 ///
6463 /// The count is kept only for the values this block's instructions take. It used to be a slot
6464 /// for every value in the function, cleared for every block, and on a function of thirty
6465 /// thousand blocks and a hundred and seventy thousand values that clearing was four percent of
6466 /// an optimized compile.
6467 fn left_alive(&self, insts: &[Inst], plans: &[Option<Plan>]) -> Option<Value> {
6468 let mut taken: Map<Value, u32> = Map::default();
6469 for (&inst, plan) in insts.iter().zip(plans) {
6470 let Some(plan) = plan else { continue };
6471 let args = &self.source[self.source[inst].args];
6472 for (index, &arg) in args.iter().take(MAX_ARGS).enumerate() {
6473 if plan[index] == Shown::Expand {
6474 *taken.entry(arg).or_default() += 1;
6475 }
6476 }
6477 }
6478 for (&inst, plan) in insts.iter().zip(plans) {
6479 let Some(plan) = plan else { continue };
6480 let args = &self.source[self.source[inst].args];
6481 for (index, &arg) in args.iter().take(MAX_ARGS).enumerate() {
6482 if plan[index] == Shown::Expand && taken[&arg] < self.uses[arg.index()] {
6483 return Some(arg);
6484 }
6485 }
6486 }
6487 None
6488 }
6489
6490 /// The rule that fires on an instruction, and what it bound.
6491 ///
6492 /// The plans are tried in order and the first that matches wins, which is the maximal munch
6493 /// `spec/10-backend.md` asks for: a plan that offers more to the matcher is tried before one
6494 /// that offers less.
6495 fn select(&self, inst: Inst, refused: &Set<Value>) -> Option<(Plan, Match<Term>)> {
6496 for plan in self.plans(inst, refused) {
6497 let terms = Terms::new(self.source, inst, plan);
6498 if let Some(matched) = self.selector.table.find(&terms, Term::Root) {
6499 return Some((plan, matched));
6500 }
6501 }
6502 None
6503 }
6504
6505 /// Every way this instruction can be shown to the matcher, most offered first.
6506 ///
6507 /// That is every choice of a way to show each operand, with the choice for the first operand
6508 /// changing slowest. The plans are counted out rather than collected, because this is asked
6509 /// for every instruction that is selected and the lists it used to build were an allocation
6510 /// or two per operand.
6511 fn plans(&self, inst: Inst, refused: &Set<Value>) -> impl Iterator<Item = Plan> {
6512 let args = &self.source[self.source[inst].args];
6513 let mut ways = [[Shown::Reg; 3]; MAX_ARGS];
6514 let mut counts = [1; MAX_ARGS];
6515 for (index, &arg) in args.iter().enumerate().take(MAX_ARGS) {
6516 let mut count = 0;
6517 if self.foldable(inst, arg, refused) {
6518 ways[index][count] = Shown::Expand;
6519 count += 1;
6520 }
6521 if Terms::new(self.source, inst, PLAIN).constant(arg).is_some() {
6522 ways[index][count] = Shown::Const;
6523 count += 1;
6524 }
6525 ways[index][count] = Shown::Reg;
6526 counts[index] = count + 1;
6527 }
6528 (0..counts.iter().product()).map(move |mut number: usize| {
6529 let mut plan = PLAIN;
6530 for index in (0..MAX_ARGS).rev() {
6531 plan[index] = ways[index][number % counts[index]];
6532 number /= counts[index];
6533 }
6534 plan
6535 })
6536 }
6537
6538 /// Whether an operand may be shown as the instruction that computed it.
6539 ///
6540 /// It has to be in the same block, because a rule that folds one instruction into another
6541 /// moves the work to where the second one is. It has to be something rather than a block
6542 /// parameter, and not a constant, which is shown as a constant instead. And it has to be a
6543 /// value [`Lowering::left_alive`] has not put back, which is how the one reader at a time
6544 /// question is asked here: this says yes to a value with any number of readers, and a value
6545 /// only some of them could take is refused after the fact and asked again.
6546 ///
6547 /// A value with several readers used to be refused outright, on the reasoning that folding
6548 /// does not delete the instruction for anybody else. That reasoning is about the set of
6549 /// readers and was being applied to one reader at a time, which is stricter than it needs to
6550 /// be: when every reader takes it there is nobody left to read it and the instruction goes.
6551 /// An address a store and a load share is the shape that matters, since a memory operand has
6552 /// room for the whole of it and both readers have a memory operand.
6553 fn foldable(&self, into: Inst, value: Value, refused: &Set<Value>) -> bool {
6554 let Def::Result { inst, .. } = self.source[value].def else { return false };
6555 if self.source[inst].opcode == Opcode::IConst || refused.contains(&value) {
6556 return false;
6557 }
6558 self.source.block_of(inst).is_some()
6559 && self.source.block_of(inst) == self.source.block_of(into)
6560 }
6561
6562 /// The instructions a match folded into the one it matched.
6563 ///
6564 /// The plan is what says this, not the bindings: a binding is a register or a number either
6565 /// way, and an operand shown as the instruction that computed it is one no rule could have
6566 /// matched without taking that instruction, because the plan offered the matcher nothing
6567 /// else to call it.
6568 fn folds(&self, inst: Inst, plan: Plan) -> Vec<Inst> {
6569 let args = &self.source[self.source[inst].args];
6570 args.iter()
6571 .take(MAX_ARGS)
6572 .enumerate()
6573 .filter(|&(index, _)| plan[index] == Shown::Expand)
6574 .filter_map(|(_, &arg)| match self.source[arg].def {
6575 Def::Result { inst, .. } => Some(inst),
6576 Def::Param { .. } => None,
6577 })
6578 .collect()
6579 }
6580
6581 /// What the IR instruction said about itself that the machine instruction has to keep saying.
6582 ///
6583 /// One flag today. `volatile` says the access happens exactly once and is never moved or
6584 /// merged, and nothing below here can work that out again: a `volatile` load and an ordinary
6585 /// one are the same instruction over the same address, so a pass that puts two accesses
6586 /// together would put these together too. Carried rather than checked here, because the pass
6587 /// that has to refuse is a long way down and this is the last place the answer is known.
6588 ///
6589 /// The instructions this compiler writes for itself get nothing, which is the right answer
6590 /// for all of them: a prologue, a spill and the moves around a call were asked for by the
6591 /// machine rather than by the program.
6592 ///
6593 /// Every access the flag is legal on carries it: the loads and the stores a rule matched,
6594 /// the two ends of a `long double` copy that are the program's own memory, and the compare
6595 /// and exchange and the read modify write. An `asm` statement does not, and it is the one
6596 /// exception on purpose. What the flag says there is that the statement stays even when
6597 /// nothing reads what it wrote, which is a different sentence about a different thing, and
6598 /// every `asm` is already fixed where it stands whether the word was written or not.
6599 fn carried(&self, inst: Inst) -> mir::Flags {
6600 if self.source[inst].flags.contains(Flags::VOLATILE) {
6601 mir::Flags::VOLATILE
6602 } else {
6603 mir::Flags::NONE
6604 }
6605 }
6606
6607 /// Build the machine instructions a match calls for.
6608 fn emit(&mut self, inst: Inst, matched: &Match<Term>) -> Result<(), Unsupported> {
6609 let rule: &Rule = self.selector.table.rule(matched);
6610 self.build(inst, rule.replacement, 0, &matched.bindings, true).map(|_| ())
6611 }
6612
6613 /// Build the machine term that starts at `at`, and give back the position after it and the
6614 /// register it wrote, if it wrote one.
6615 ///
6616 /// The outermost term computes what the IR instruction does, so what it writes is the
6617 /// register of the instruction's result. A term inside another is a step on the way and
6618 /// writes a register of its own, which the term around it then reads. Its operands are read
6619 /// before it is built and it is built before the term around it, so the instructions come
6620 /// out in the order the values are needed.
6621 fn build(
6622 &mut self,
6623 inst: Inst,
6624 pieces: &'static [Piece],
6625 at: usize,
6626 bindings: &[Term],
6627 outermost: bool,
6628 ) -> Result<(usize, Option<mir::Reg>), Unsupported> {
6629 let Some(Piece::App { head, arity }) = pieces.get(at) else {
6630 return Err(self.unsupported(inst));
6631 };
6632 let (opcode, descs) = self.head(inst, head)?;
6633
6634 let mut read = Read::default();
6635 let mut at = at + 1;
6636 for _ in 0..*arity {
6637 at = self.read(inst, pieces, at, bindings, &mut read)?;
6638 }
6639
6640 let writes = descs.iter().take_while(|desc| desc.role.is_def()).count();
6641 if descs.len() - writes != read.regs.len() {
6642 return Err(self.unsupported(inst));
6643 }
6644
6645 // The first thing the instruction writes is what it computes, and any others are
6646 // registers the machine destroys on the way, which are fresh because nothing else is in
6647 // them and nothing reads them. An instruction that writes nothing at all is one whose
6648 // whole purpose is its effect, which is what a store is, and there is no result to put
6649 // anywhere.
6650 let mut regs = Vec::new();
6651 if writes > 0 {
6652 // A term inside another computes a step rather than the result, into a register only
6653 // the term around it reads.
6654 let first = match outermost {
6655 true => {
6656 let result =
6657 self.source[inst].first_result.ok_or_else(|| self.unsupported(inst))?;
6658 self.new_reg(result)
6659 }
6660 false => self.out.new_vreg(descs[0].class),
6661 };
6662 regs.push(first);
6663 // The rest are the registers the machine destroys on the way, and the class each is in
6664 // is the one the instruction's description gives it rather than a guess, so that an
6665 // instruction that wrecks a register in the other file says so.
6666 regs.extend(descs[1..writes].iter().map(|desc| self.out.new_vreg(desc.class)));
6667 } else if !outermost || self.source[inst].first_result.is_some() {
6668 // A rule that throws away a value the IR gave a name to would leave every reader of
6669 // that name with nothing to read, so it is a rule this and the target disagree about.
6670 // So is a term inside another that writes nothing for the one around it to read.
6671 return Err(self.unsupported(inst));
6672 }
6673 let written = regs.first().copied();
6674 regs.extend(read.regs.iter().copied());
6675
6676 let block = self.at.expect("a block is being filled");
6677 let (span, flags) = (self.source.span(inst), self.carried(inst));
6678 let mut build = self.out.build(block, opcode).at(span).flags(flags);
6679 for (desc, reg) in descs.iter().zip(regs) {
6680 let operand = mir::Operand {
6681 reg,
6682 class: desc.class,
6683 role: desc.role,
6684 constraint: desc.constraint,
6685 };
6686 build = build.operand(operand);
6687 }
6688 if let Some(mem) = read.mem {
6689 build = build.mem(mem);
6690 }
6691 if let Some(imm) = read.imm {
6692 build = build.imm(imm);
6693 }
6694 build.finish();
6695 Ok((at, written))
6696 }
6697
6698 /// The machine opcode a rule's head names, and the operands the target says it has.
6699 ///
6700 /// Looked up by name the first time a head is met and kept after that. A function of any size
6701 /// builds the same few hundred heads over and over, and each lookup by name was a hash of the
6702 /// name into the target's table and another into the interner. The heads are strings in the
6703 /// rule table, which is static, so where one is in memory says which head it is.
6704 fn head(
6705 &mut self,
6706 inst: Inst,
6707 head: &'static str,
6708 ) -> Result<(mir::Opcode, &'static [OperandDesc]), Unsupported> {
6709 let key = (head.as_ptr().addr(), head.len());
6710 if let Some(&known) = self.heads.get(&key) {
6711 return Ok(known);
6712 }
6713 let name =
6714 head.strip_prefix(self.selector.prefix()).ok_or_else(|| self.unsupported(inst))?;
6715 let descs = self.selector.operands(name).ok_or_else(|| self.unsupported(inst))?;
6716 let known = (mir::Opcode::new(self.names.intern(head)), descs);
6717 self.heads.insert(key, known);
6718 Ok(known)
6719 }
6720
6721 /// Read one argument of a replacement, which is a register, a number, an address or another
6722 /// machine term.
6723 ///
6724 /// Gives back the position after it, because a replacement is flat and an address or a term
6725 /// takes arguments of its own. A machine term is built on the spot, and what is read is the
6726 /// register it wrote.
6727 fn read(
6728 &mut self,
6729 inst: Inst,
6730 pieces: &'static [Piece],
6731 at: usize,
6732 bindings: &[Term],
6733 out: &mut Read,
6734 ) -> Result<usize, Unsupported> {
6735 match pieces.get(at) {
6736 Some(Piece::Int(value)) => {
6737 out.imm = i64::try_from(*value).ok();
6738 Ok(at + 1)
6739 }
6740 // A number the rule worked out of the ones it matched rather than one it wrote down,
6741 // which is an immediate once it has been worked out and is read here as one. It gives
6742 // nothing back when a binding it reads is a register, and a replacement that cannot be
6743 // built is a rule this file and the matcher disagree about, which is what `unsupported`
6744 // is for.
6745 Some(Piece::Computed { work, .. }) => {
6746 let matched: Vec<Option<i128>> = bindings
6747 .iter()
6748 .map(|term| match *term {
6749 Term::Num(value) => Some(value),
6750 _ => None,
6751 })
6752 .collect();
6753 let number = work(&matched).ok_or_else(|| self.unsupported(inst))?;
6754 out.imm = i64::try_from(number).ok();
6755 Ok(at + 1)
6756 }
6757 Some(Piece::Var { index, .. }) => {
6758 match bindings.get(*index) {
6759 Some(&Term::Reg(value)) => {
6760 let reg = self.reg_of(value)?;
6761 out.regs.push(reg);
6762 }
6763 Some(&Term::Num(value)) => out.imm = i64::try_from(value).ok(),
6764 // A pattern binds a register or a number and nothing else, so this is a
6765 // rule the matcher and this file disagree about.
6766 _ => return Err(self.unsupported(inst)),
6767 }
6768 Ok(at + 1)
6769 }
6770 Some(Piece::App { head, .. }) if (self.selector.address)(head).is_none() => {
6771 let (next, reg) = self.build(inst, pieces, at, bindings, false)?;
6772 out.regs.push(reg.ok_or_else(|| self.unsupported(inst))?);
6773 Ok(next)
6774 }
6775 Some(Piece::App { head, arity }) => {
6776 let kind = (self.selector.address)(head).ok_or_else(|| self.unsupported(inst))?;
6777 let mut inner = Read::default();
6778 let mut next = at + 1;
6779 for _ in 0..*arity {
6780 next = self.read(inst, pieces, next, bindings, &mut inner)?;
6781 }
6782 let mem = address(kind, &inner, self.gpr).ok_or_else(|| self.unsupported(inst))?;
6783 out.mem = Some(mem);
6784 Ok(next)
6785 }
6786 None => Err(self.unsupported(inst)),
6787 }
6788 }
6789
6790 /// The register a value is in, writing it there first if it is one that is written where it
6791 /// is wanted rather than where the IR defined it.
6792 ///
6793 /// A constant is written where it is wanted, and where it is wanted is a block that need not
6794 /// be the one the IR defined it in. So the register holding one is only good inside the block
6795 /// it was written into, and a second block that wants the same constant gets its own. Anything
6796 /// else is a register read where nothing wrote it: the IR guarantees a definition dominates its
6797 /// uses, and this moved the definition.
6798 ///
6799 /// Writing the number again is also the right answer and not merely the safe one. It is one
6800 /// instruction that reads nothing, which is cheaper than holding a register live across a
6801 /// branch for it, and it is what a rematerializing allocator would do with the value anyway.
6802 /// The address of a local and the address of a name are the same kind of value, and
6803 /// [`Rebuilt`] is the list and the reasons.
6804 fn reg_of(&mut self, value: Value) -> Result<mir::Reg, Unsupported> {
6805 let rebuilt = self.rebuilt(value);
6806 let here = self.at.expect("a block is being filled");
6807 if let Some(reg) = self.regs[value.index()] {
6808 let good = match rebuilt {
6809 None => true,
6810 Some(Rebuilt::Local(_)) => false,
6811 Some(Rebuilt::Constant(_)) => {
6812 self.written[value.index()].is_some_and(|(block, _)| block == here)
6813 }
6814 Some(Rebuilt::Name(_)) => self.written[value.index()] == Some((here, self.crossed)),
6815 };
6816 if good {
6817 return Ok(reg);
6818 }
6819 }
6820 match rebuilt {
6821 Some(Rebuilt::Constant(inst)) => {
6822 // Cleared so that the register the constant is written into is a new one rather
6823 // than the one the block above wrote, which is still being read up there.
6824 self.regs[value.index()] = None;
6825 // Nothing is refused here. A constant is written on its own, out of the loop over
6826 // the block, and the operands of the rule that writes one are the number and
6827 // nothing else.
6828 let matched = self
6829 .select(inst, &Set::default())
6830 .map(|(_, matched)| matched)
6831 .ok_or_else(|| self.unsupported(inst))?;
6832 self.emit(inst, &matched)?;
6833 // The same mark the loop over the instructions makes, and it has to be made here as
6834 // well because this is the only place a constant is ever selected: the loop skips
6835 // one where the IR wrote it, so a rule that lowers a constant fires from nowhere
6836 // else and would be reported as a rule nothing reaches.
6837 self.fired.mark(matched.rule);
6838 self.written[value.index()] = Some((here, self.crossed));
6839 Ok(self.regs[value.index()].expect("a constant is written into a register"))
6840 }
6841 Some(Rebuilt::Local(inst)) => self.local_address(inst, value),
6842 Some(Rebuilt::Name(inst)) => {
6843 self.regs[value.index()] = None;
6844 self.address_of(inst)?;
6845 self.written[value.index()] = Some((here, self.crossed));
6846 Ok(self.regs[value.index()].expect("an address is written into a register"))
6847 }
6848 None => Ok(self.new_reg(value)),
6849 }
6850 }
6851
6852 /// Whether a value is one [`Self::reg_of`] writes again where it is read rather than keeping
6853 /// in the register it was first written into, and what writes it.
6854 fn rebuilt(&self, value: Value) -> Option<Rebuilt> {
6855 let Def::Result { inst, .. } = self.source[value].def else { return None };
6856 let data = &self.source[inst];
6857 match data.opcode {
6858 Opcode::IConst => Some(Rebuilt::Constant(inst)),
6859 Opcode::Alloca if self.source[data.args].is_empty() => Some(Rebuilt::Local(inst)),
6860 Opcode::GlobalAddr => match data.extra {
6861 Extra::Symbol(symbol) if !self.elsewhere.thread(symbol) => {
6862 Some(Rebuilt::Name(inst))
6863 }
6864 _ => None,
6865 },
6866 _ => None,
6867 }
6868 }
6869
6870 /// Writes an address that was just read as an argument of a call in front of the instruction
6871 /// that reads it, rather than in front of all of them.
6872 ///
6873 /// Every argument of a call is read before any of them is passed, so the addresses
6874 /// [`Self::reg_of`] writes for them all come out in a row ahead of the stores and the call,
6875 /// and all of them are live at once. A call with twelve string arguments then wants
6876 /// twelve registers, which is every register a call leaves alone and a push for each of them
6877 /// in the prologue. Moved down to the store that passes it, each address is live for one
6878 /// instruction, which is what gcc writes: a `lea` and a store, one argument at a time.
6879 ///
6880 /// `made` is the instructions [`Self::called`] saw written for each argument that is an
6881 /// address, and one is only moved when it reads nothing but the stack pointer, since then the
6882 /// only thing that could change what it computes on the way down is something writing the
6883 /// stack pointer, and the walk stops at one of those. A constant is left where it is, because
6884 /// some of the instructions a constant is written with write the flags as well.
6885 fn passed_late(&mut self, made: &[mir::Inst]) {
6886 let sp = mir::Reg::physical(self.conv.stack_pointer);
6887 for &inst in made {
6888 let operands = &self.out[self.out[inst].operands];
6889 let Some((first, rest)) = operands.split_first() else { continue };
6890 if !first.role.is_def()
6891 || rest.iter().any(|operand| operand.reg != sp || operand.role.is_def())
6892 {
6893 continue;
6894 }
6895 let reg = first.reg;
6896 let mut reader = None;
6897 let mut at = self.out.next_inst(inst);
6898 while let Some(next) = at {
6899 let operands = &self.out[self.out[next].operands];
6900 if operands.iter().any(|operand| operand.reg == reg && !operand.role.is_def()) {
6901 reader = Some(next);
6902 break;
6903 }
6904 if operands.iter().any(|operand| operand.reg == sp && operand.role.is_def()) {
6905 break;
6906 }
6907 at = self.out.next_inst(next);
6908 }
6909 let Some(reader) = reader else { continue };
6910 if self.out.next_inst(inst) != Some(reader) {
6911 self.out.remove_inst(inst);
6912 self.out.insert_before(reader, inst);
6913 }
6914 }
6915 }
6916
6917 /// Which register file a value of that type lives in.
6918 ///
6919 /// The vector one for the two float widths the machine has scalar instructions for and for the
6920 /// one it only moves, and the general purpose one for everything else. An eighty bit `long
6921 /// double` is in neither, and it is here rather than in the vector class on purpose: it would
6922 /// be put in a register that cannot hold it, and there is no rule that names one, so the
6923 /// instruction computing it is reported. The wrong class would make that a wrong program
6924 /// instead of a refused one.
6925 ///
6926 /// A hundred and twenty eight bit float is in the vector class and fits it exactly, which is
6927 /// the difference. Nothing computes in it, so every arithmetic on one is still reported, and
6928 /// what the class buys is the moves: a register that holds the whole value is a register a
6929 /// spill, a reload and a copy are each one instruction for.
6930 fn class_of(&self, ty: Type) -> RegClass {
6931 if crate::term::in_vector_file(ty) { self.conv.sse_class } else { self.gpr }
6932 }
6933
6934 /// A fresh register for a value, which is what the instruction computing it writes.
6935 ///
6936 /// Any declaration the value is a value of comes with it. Here rather than once at the end over
6937 /// the whole map, because a constant is written again in every block that wants one and the map
6938 /// only remembers the last of those registers, and a local held in a constant is a local that
6939 /// would otherwise be findable in one block of the function and nowhere else.
6940 fn new_reg(&mut self, value: Value) -> mir::Reg {
6941 if let Some(reg) = self.regs[value.index()] {
6942 return reg;
6943 }
6944 let ty = self.source[value].ty;
6945 let reg = self.out.new_vreg(self.class_of(ty));
6946 self.sized(reg, ty);
6947 self.regs[value.index()] = Some(reg);
6948 let source = self.source;
6949 for decl in source.value_decls(value) {
6950 self.out.named.push((decl, reg));
6951 }
6952 reg
6953 }
6954
6955 /// Says how much of its register a value of that type takes, when the register is a vector
6956 /// one, which is what lets a call that keeps only the bottom of one keep the value in it.
6957 fn sized(&mut self, reg: mir::Reg, ty: Type) {
6958 if crate::term::in_vector_file(ty) {
6959 self.out.set_width(reg, abi::float_bytes(ty));
6960 }
6961 }
6962
6963 fn unsupported(&self, inst: Inst) -> Unsupported {
6964 let data = &self.source[inst];
6965 Unsupported::Inst {
6966 inst,
6967 term: Terms::new(self.source, inst, PLAIN).name(inst),
6968 opcode: data.opcode,
6969 ty: data.first_result.map(|result| self.source[result].ty),
6970 }
6971 }
6972}
6973
6974/// A value [`Lowering::reg_of`] writes again where it is read, and the instruction that says what
6975/// it is.
6976///
6977/// Each of these is one instruction that reads nothing a program can change, so writing it again
6978/// costs what reloading it from a stack slot would and never needs the slot. Kept in one register
6979/// from where the IR defined it instead, an address of a local or a name is live from the entry
6980/// block to its last reader, and a function with more of those than registers pushes every
6981/// register a call leaves alone and then spills the rest, one eight byte slot each. That was most
6982/// of the difference between this compiler's frames and gcc's on PostgreSQL, tamnd/rucc#2200.
6983///
6984/// The address of a local also stops looking live between blocks, which is part of what
6985/// [`crate::slots`] asks before it lets two locals share bytes.
6986#[derive(Debug, Clone, Copy)]
6987enum Rebuilt {
6988 /// An integer constant, written once in each block that reads it.
6989 Constant(Inst),
6990 /// The address of a fixed size `alloca`, which is a `lea` off the stack pointer and is written
6991 /// for every reader, so that it is never live across anything, a call least of all. A reader
6992 /// that is a load or a store of the local then takes the whole of it into its own addressing
6993 /// mode in [`crate::fold`], which is how gcc writes an access to a local.
6994 Local(Inst),
6995 /// The address of a name that is not thread-local, written once in each block that reads it
6996 /// and again after each call in that block, so that it is not live across a call either.
6997 ///
6998 /// Once a block rather than once a reader, because [`crate::fold`] decides whether to put a
6999 /// symbol into the instructions that read it by counting them, and a symbol written into each
7000 /// of thirty readers is longer code than one `lea`. A name reached through the global offset
7001 /// table or a pointer the loader fills in is a load, and it is written again all the same:
7002 /// what it reads is written once before the program starts and never again, which is what
7003 /// makes gcc treat it the same way. A thread-local variable is not here, because its address
7004 /// is this thread's copy and on Mach-O that takes a call.
7005 Name(Inst),
7006}
7007
7008/// What the arguments of one replacement came to.
7009#[derive(Debug, Default)]
7010struct Read {
7011 regs: Vec<mir::Reg>,
7012 imm: Option<i64>,
7013 mem: Option<mir::Mem>,
7014}
7015
7016/// The addressing mode an address constructor's arguments make.
7017///
7018/// One arm per constructor rather than a question asked of the kind, because what the arguments
7019/// mean is the whole of what tells the four apart: the same register is a base in one and an
7020/// index in another, and the same constant is a scale in one and a displacement in another.
7021fn address(kind: Address, read: &Read, gpr: RegClass) -> Option<mir::Mem> {
7022 let mut regs = read.regs.iter().copied().map(|reg| mir::Operand::read(reg, gpr));
7023 match kind {
7024 Address::BaseIndexScale => {
7025 let base = regs.next()?;
7026 let index = regs.next()?;
7027 Some(mir::Mem::at(base).indexed(index, u8::try_from(read.imm?).ok()?))
7028 }
7029 Address::IndexScale => Some(mir::Mem {
7030 base: None,
7031 index: Some(regs.next()?),
7032 scale: u8::try_from(read.imm?).ok()?,
7033 disp: 0,
7034 symbol: None,
7035 block: None,
7036 table: None,
7037 reach: mir::Reach::Itself,
7038 segment: None,
7039 }),
7040 Address::Base => Some(mir::Mem::at(regs.next()?)),
7041 // The rule that writes this has a guard saying the constant fits, so a displacement that
7042 // does not is a rule and a target that disagree rather than a program this cannot compile.
7043 Address::BaseOffset => {
7044 Some(mir::Mem { disp: i32::try_from(read.imm?).ok()?, ..mir::Mem::at(regs.next()?) })
7045 }
7046 }
7047}
7048
7049#[cfg(test)]
7050mod tests {
7051 use rucc_ir::{
7052 AsmInfo, Builder, CallInfo, Flags, InstData, MemInfo, MemOrder, Restrict, Signature, Type,
7053 };
7054 use rucc_regalloc::assign::Env;
7055 use rucc_target::x86_64::{FRAME, REGS, SYSV};
7056
7057 use super::*;
7058 use crate::finish::{Convention, finish};
7059 use crate::frame::{Frame, Incoming, Layout};
7060 use crate::select::x86_64::SELECTOR;
7061
7062 /// A function of as many 64 bit parameters as the test wants, and the block they are in.
7063 fn blank(params: &[Type]) -> (Interner, Func, Block, Vec<Value>) {
7064 let mut names = Interner::new();
7065 let mut func = Func::new(names.intern("f"), Signature::new());
7066 let block = func.create_block();
7067 let values = params.iter().map(|&ty| func.append_param(block, ty)).collect();
7068 (names, func, block, values)
7069 }
7070
7071 /// An ordinary access: not atomic, and aligned enough that nothing here has an opinion.
7072 /// Neither field reaches selection, which is the point of saying it once here.
7073 fn plain() -> MemInfo {
7074 MemInfo {
7075 size: 0,
7076 align: 1,
7077 order: MemOrder::NotAtomic,
7078 tbaa: None,
7079 owns: 0,
7080 restrict: Restrict::NONE,
7081 }
7082 }
7083
7084 /// What the allocator is given: every integer register the convention offers except two, held
7085 /// back so that a move on an edge has somewhere to break a cycle and a spilled value has
7086 /// somewhere to be read into. Which two does not matter, and holding back the last two the
7087 /// convention would reach for leaves every expectation below unchanged.
7088 fn env() -> Env {
7089 const SCRATCH: [PhysReg; 2] = [x86_64::R10, x86_64::R11];
7090 let order: Vec<PhysReg> =
7091 SYSV.int_order.iter().copied().filter(|reg| !SCRATCH.contains(reg)).collect();
7092 Env::new().with(x86_64::GPR, &order, &SCRATCH)
7093 }
7094
7095 /// The machine IR text a function lowers to.
7096 fn lower(names: &mut Interner, source: &Func) -> String {
7097 let out = func(source, names, &SELECTOR, &SYSV, &Elsewhere::default())
7098 .expect("every instruction has a rule");
7099 mir::print_func(&out.func, names, ®S)
7100 }
7101
7102 /// The same function lowered for AArch64, which is the first thing this file writes for a
7103 /// machine other than x86-64. Nothing past selection runs here, so what is checked is that the
7104 /// arguments, the rule and the return all come out named for the machine that was asked for.
7105 #[test]
7106 fn an_addition_lowers_for_aarch64_with_its_own_names() {
7107 let i32 = Type::int(32);
7108 let (mut names, mut func, block, args) = blank(&[i32, i32]);
7109 let mut build = Builder::new(&mut func, block);
7110 let sum = build.binary(Opcode::Add, args[0], args[1], Flags::default());
7111 build.ret(&[sum]);
7112
7113 let conv = &aarch64::AAPCS64;
7114 let selector = &crate::select::aarch64::SELECTOR;
7115 let out = super::func(&func, &mut names, selector, conv, &Elsewhere::default())
7116 .expect("an addition and a return have AArch64 rules");
7117 let text = mir::print_func(&out.func, &names, &aarch64::REGS);
7118 assert!(!text.contains("x64."), "{text}");
7119 assert!(text.contains("= a64.arg_val_32"), "{text}");
7120 assert!(text.contains("= a64.add_rr_32 %0, %1"), "{text}");
7121 assert!(text.contains("a64.ret_val_32 %2"), "{text}");
7122 }
7123
7124 /// Lowers one function for AArch64 and prints it, or says why it could not.
7125 fn lower_a64(names: &mut Interner, func: &Func) -> Result<String, String> {
7126 let conv = &aarch64::AAPCS64;
7127 let selector = &crate::select::aarch64::SELECTOR;
7128 let out = super::func(func, names, selector, conv, &Elsewhere::default())
7129 .map_err(|why| why.to_string())?;
7130 Ok(mir::print_func(&out.func, names, &aarch64::REGS))
7131 }
7132
7133 /// Nothing reads AArch64 assembly back into instructions, so every template there is kept as
7134 /// its text. The operands are the instruction's own, with the output first and the inputs
7135 /// last, a hole in the text asks for the `w` or the `x` name of one, and a vector register the
7136 /// clobber list names is written by it as well as every register a call may leave anything in.
7137 #[test]
7138 fn a_template_on_aarch64_is_kept_as_text_with_its_operands_in_registers() {
7139 let (i32, i64) = (Type::int(32), Type::int(64));
7140 let (mut names, mut source, block, args) = blank(&[i32, i64]);
7141 let out = clobbering(
7142 &mut source,
7143 block,
7144 &mut names,
7145 "add %w0, %w1, #1\n\tstr %2, [sp]",
7146 "=r,r,r",
7147 "d8",
7148 &[args[0], args[1]],
7149 &[i32],
7150 );
7151 let produced = source[out].results().next().expect("one result");
7152 Builder::new(&mut source, block).ret(&[produced]);
7153
7154 // Forty one registers between the output and the inputs: `x0` to `x15`, the sixteen vector
7155 // registers a call does not keep, and `v8`, which is the one the program named.
7156 let text = lower_a64(&mut names, &source).expect("kept as text");
7157 assert!(text.contains("%2:gpr, early $x0, early $x1,"), "{text}");
7158 assert!(text.contains(
7159 "early $v31, early $v8 = a64.template %0, %1, \
7160 @add \u{1}r0w\u{2}, \u{1}r42w\u{2}, #1\n\tstr \u{1}r43x\u{2}, [sp]\n"
7161 ));
7162 }
7163
7164 /// A letter that means one thing on x86 and another on AArch64 is refused there rather than
7165 /// read as x86. `a` to `d` and `S` name one register each on x86 and nothing on AArch64.
7166 #[test]
7167 fn a_constraint_letter_the_two_machines_disagree_about_is_refused_on_aarch64() {
7168 let i64 = Type::int(64);
7169 for constraints in ["=a,r", "=r,S", "=r,c"] {
7170 let (mut names, mut source, block, args) = blank(&[i64]);
7171 let out = clobbering(
7172 &mut source,
7173 block,
7174 &mut names,
7175 "mov %0, %1",
7176 constraints,
7177 "",
7178 &[args[0]],
7179 &[i64],
7180 );
7181 let produced = source[out].results().next().expect("one result");
7182 Builder::new(&mut source, block).ret(&[produced]);
7183 let refused = lower_a64(&mut names, &source).expect_err(constraints);
7184 assert!(refused.contains("has an operand this cannot place"), "{refused}");
7185 }
7186 }
7187
7188 /// `Q` on AArch64 is memory addressed by one register, which is `[x3]` and is how an operand in
7189 /// memory is spelled there already.
7190 #[test]
7191 fn a_q_operand_on_aarch64_is_its_address_in_brackets() {
7192 let (i64, ptr) = (Type::int(64), Type::PTR);
7193 let (mut names, mut source, block, args) = blank(&[ptr]);
7194 let out =
7195 clobbering(&mut source, block, &mut names, "ldr %x0, %1", "=r,Q", "", &args, &[i64]);
7196 let produced = source[out].results().next().expect("one result");
7197 Builder::new(&mut source, block).ret(&[produced]);
7198 let text = lower_a64(&mut names, &source).expect("kept as text");
7199 assert!(text.contains("@ldr \u{1}r0x\u{2}, [\u{1}r"), "{text}");
7200 }
7201
7202 /// `w` on AArch64 is a vector register, named `v` with no modifier the way gcc names it and by
7203 /// its scalar view with one. An integer asked for in one is refused, since it would need a move
7204 /// into that file first.
7205 #[test]
7206 fn a_vector_operand_on_aarch64_is_in_the_vector_file() {
7207 let f64 = Type::float(rucc_ir::Float::F64);
7208 let (mut names, mut source, block, args) = blank(&[f64, f64]);
7209 let out = clobbering(
7210 &mut source,
7211 block,
7212 &mut names,
7213 "fadd %d0, %d1, %d2\n\tmov %0.16b, %0.16b",
7214 "=w,w,w",
7215 "",
7216 &[args[0], args[1]],
7217 &[f64],
7218 );
7219 let produced = source[out].results().next().expect("one result");
7220 Builder::new(&mut source, block).ret(&[produced]);
7221 let text = lower_a64(&mut names, &source).expect("kept as text");
7222 assert!(text.contains("%2:fpr, early $x0,"), "{text}");
7223 assert!(text.contains("@fadd \u{1}r0d\u{2}, \u{1}r"), "{text}");
7224 assert!(text.contains("\n\tmov \u{1}r0v\u{2}.16b, \u{1}r0v\u{2}.16b\n"), "{text}");
7225
7226 let i64 = Type::int(64);
7227 let (mut names, mut source, block, args) = blank(&[i64]);
7228 let out =
7229 clobbering(&mut source, block, &mut names, "fmov %d0, %d1", "=w,w", "", &args, &[i64]);
7230 let produced = source[out].results().next().expect("one result");
7231 Builder::new(&mut source, block).ret(&[produced]);
7232 assert!(lower_a64(&mut names, &source).is_err());
7233 }
7234
7235 #[test]
7236 fn an_addition_of_two_registers_is_one_instruction() {
7237 let i32 = Type::int(32);
7238 let (mut names, mut func, block, args) = blank(&[i32, i32]);
7239 let mut build = Builder::new(&mut func, block);
7240 build.binary(Opcode::Add, args[0], args[1], Flags::default());
7241
7242 assert_eq!(
7243 lower(&mut names, &func),
7244 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_32\n \
7245 %1:gpr($rsi) = x64.arg_val_32\n %2:gpr(reuse 1) = x64.add_rr_32 %0, %1\n}\n"
7246 );
7247 }
7248
7249 #[test]
7250 fn a_constant_operand_becomes_an_immediate() {
7251 let i32 = Type::int(32);
7252 let (mut names, mut func, block, args) = blank(&[i32]);
7253 let mut build = Builder::new(&mut func, block);
7254 let seven = build.iconst(i32, 7);
7255 build.binary(Opcode::Add, args[0], seven, Flags::default());
7256
7257 // The constant is in the instruction and nothing was written to hold it, which is what
7258 // materializing one where a register for it is wanted buys.
7259 assert_eq!(
7260 lower(&mut names, &func),
7261 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_32\n \
7262 %1:gpr(reuse 1) = x64.add_ri_32 %0, 7\n}\n"
7263 );
7264 }
7265
7266 #[test]
7267 fn a_constant_too_wide_for_an_immediate_goes_into_a_register() {
7268 let i64 = Type::int(64);
7269 let (mut names, mut func, block, args) = blank(&[i64]);
7270 let mut build = Builder::new(&mut func, block);
7271 let big = build.iconst(i64, i128::from(i32::MAX) + 1);
7272 build.binary(Opcode::Add, args[0], big, Flags::default());
7273
7274 // Nobody wrote this fallback down. The rule that takes an immediate has a guard that
7275 // turns a number this wide down, so it does not fire, and the next way of showing the
7276 // operand puts it in a register.
7277 assert_eq!(
7278 lower(&mut names, &func),
7279 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_64\n \
7280 %1:gpr = x64.mov_ri_64 2147483648\n %2:gpr(reuse 1) = x64.add_rr_64 %0, %1\n}\n"
7281 );
7282 }
7283
7284 #[test]
7285 fn an_index_calculation_folds_into_an_address() {
7286 let i64 = Type::int(64);
7287 let (mut names, mut func, block, args) = blank(&[i64, i64]);
7288 let mut build = Builder::new(&mut func, block);
7289 let four = build.iconst(i64, 4);
7290 let scaled = build.binary(Opcode::Mul, args[1], four, Flags::default());
7291 build.binary(Opcode::Add, args[0], scaled, Flags::default());
7292
7293 // Three IR instructions and one machine instruction. The multiply is gone because the
7294 // rule that matched reached down and took it.
7295 assert_eq!(
7296 lower(&mut names, &func),
7297 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_64\n \
7298 %1:gpr($rsi) = x64.arg_val_64\n %2:gpr = x64.lea_64 [%0 + %1*4]\n}\n"
7299 );
7300 }
7301
7302 #[test]
7303 fn an_instruction_every_reader_can_take_is_folded_into_all_of_them() {
7304 let i64 = Type::int(64);
7305 let (mut names, mut func, block, args) = blank(&[i64, i64]);
7306 let mut build = Builder::new(&mut func, block);
7307 let four = build.iconst(i64, 4);
7308 let scaled = build.binary(Opcode::Mul, args[1], four, Flags::default());
7309 let first = build.binary(Opcode::Add, args[0], scaled, Flags::default());
7310 build.binary(Opcode::Add, first, scaled, Flags::default());
7311
7312 // Both readers have room for a scaled index, so both of them take it and nothing is left
7313 // to read the multiply. Three IR instructions become two machine ones, where refusing to
7314 // fold into either reader would have left three.
7315 assert_eq!(
7316 lower(&mut names, &func),
7317 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_64\n \
7318 %1:gpr($rsi) = x64.arg_val_64\n %2:gpr = x64.lea_64 [%0 + %1*4]\n \
7319 %3:gpr = x64.lea_64 [%2 + %1*4]\n}\n"
7320 );
7321 }
7322
7323 #[test]
7324 fn an_instruction_one_of_its_readers_cannot_take_is_folded_into_none_of_them() {
7325 let i64 = Type::int(64);
7326 let (mut names, mut func, block, args) = blank(&[i64, i64]);
7327 let mut build = Builder::new(&mut func, block);
7328 let four = build.iconst(i64, 4);
7329 let scaled = build.binary(Opcode::Mul, args[1], four, Flags::default());
7330 build.binary(Opcode::Add, args[0], scaled, Flags::default());
7331 build.store(scaled, args[0], plain(), Flags::default());
7332
7333 // The addition has room for the multiply and the store does not: what a store writes is
7334 // a register, and no rule reaches through it. Folding into the addition alone would
7335 // leave the multiply where it is for the store to read and do the work twice, so the
7336 // multiply is put back and both readers read the register it wrote.
7337 let text = lower(&mut names, &func);
7338 assert!(text.contains("x64.lea_64 [%1*4]"), "{text}");
7339 assert!(text.contains("x64.add_rr_64"), "{text}");
7340 }
7341
7342 #[test]
7343 fn a_shift_by_a_register_asks_for_it_in_cl() {
7344 let i32 = Type::int(32);
7345 let (mut names, mut func, block, args) = blank(&[i32, i32]);
7346 let mut build = Builder::new(&mut func, block);
7347 build.binary(Opcode::Shl, args[0], args[1], Flags::default());
7348
7349 // The fixed register is not in the rule. It is what the target says the instruction does
7350 // with its operands, and the allocator is what will act on it.
7351 let text = lower(&mut names, &func);
7352 assert!(text.contains("x64.shl_rcl_32 %0, %1($rcx)"), "{text}");
7353 }
7354
7355 #[test]
7356 fn a_division_names_the_registers_and_the_register_it_destroys() {
7357 let i32 = Type::int(32);
7358 let (mut names, mut func, block, args) = blank(&[i32, i32]);
7359 let mut build = Builder::new(&mut func, block);
7360 build.binary(Opcode::SDiv, args[0], args[1], Flags::default());
7361
7362 // Two definitions, because a division writes the remainder whether anybody wanted it or
7363 // not, and the second one is early because it is destroyed before the operands are read.
7364 let text = lower(&mut names, &func);
7365 assert!(
7366 text.contains("%2:gpr($rax), early %3:gpr($rdx) = x64.idiv_quo_32 %0($rax), %1"),
7367 "{text}"
7368 );
7369 }
7370
7371 #[test]
7372 fn a_load_reads_through_the_register_the_address_is_in() {
7373 let i64 = Type::int(64);
7374 let (mut names, mut func, block, args) = blank(&[i64]);
7375 let mut build = Builder::new(&mut func, block);
7376 build.load(Type::int(32), args[0], plain(), Flags::default());
7377
7378 assert_eq!(
7379 lower(&mut names, &func),
7380 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_64\n \
7381 %1:gpr = x64.mov_rm_32 [%0]\n}\n"
7382 );
7383 }
7384
7385 #[test]
7386 fn a_store_writes_no_register_and_the_value_it_writes_is_the_one_the_ir_gave_it() {
7387 let (mut names, mut func, block, args) = blank(&[Type::int(32), Type::int(64)]);
7388 let mut build = Builder::new(&mut func, block);
7389 build.store(args[0], args[1], plain(), Flags::default());
7390
7391 // The value is the first parameter and the address is the second, and the instruction
7392 // takes them the other way round. Getting that backwards would compile to a store of the
7393 // address into the value, which is a program that runs and does the wrong thing.
7394 assert_eq!(
7395 lower(&mut names, &func),
7396 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_32\n \
7397 %1:gpr($rsi) = x64.arg_val_64\n x64.mov_mr_32 %0, [%1]\n}\n"
7398 );
7399 }
7400
7401 #[test]
7402 fn an_address_with_a_constant_added_folds_into_the_access() {
7403 let i64 = Type::int(64);
7404 let (mut names, mut func, block, args) = blank(&[i64]);
7405 let mut build = Builder::new(&mut func, block);
7406 let twelve = build.iconst(i64, 12);
7407 let field = build.binary(Opcode::Add, args[0], twelve, Flags::default());
7408 build.load(Type::int(64), field, plain(), Flags::default());
7409
7410 // Two IR instructions and one machine instruction, which is what every read of a field
7411 // of a structure comes to.
7412 assert_eq!(
7413 lower(&mut names, &func),
7414 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_64\n \
7415 %1:gpr = x64.mov_rm_64 [%0 + 12]\n}\n"
7416 );
7417 }
7418
7419 #[test]
7420 fn a_displacement_too_wide_to_encode_leaves_the_addition_where_it_is() {
7421 let i64 = Type::int(64);
7422 let (mut names, mut func, block, args) = blank(&[i64]);
7423 let mut build = Builder::new(&mut func, block);
7424 let big = build.iconst(i64, i128::from(i32::MAX) + 1);
7425 let far = build.binary(Opcode::Add, args[0], big, Flags::default());
7426 build.load(Type::int(32), far, plain(), Flags::default());
7427
7428 // A displacement is signed and 32 bits. The rule that folds one has a guard that turns
7429 // this down, so the addition stays and the load reads through what it produced. Nobody
7430 // wrote that fallback: it is the next way of showing the operand.
7431 let text = lower(&mut names, &func);
7432 assert!(text.contains("x64.mov_rm_32 [%2]"), "{text}");
7433 assert!(text.contains("x64.add_rr_64"), "{text}");
7434 }
7435
7436 #[test]
7437 fn a_store_of_a_value_that_was_loaded_is_two_instructions_and_no_arithmetic() {
7438 let i64 = Type::int(64);
7439 let (mut names, mut func, block, args) = blank(&[i64, i64]);
7440 let mut build = Builder::new(&mut func, block);
7441 let got = build.load(Type::int(8), args[0], plain(), Flags::default());
7442 build.store(got, args[1], plain(), Flags::default());
7443
7444 // A load feeding a store is the one place folding would be wrong: an x86-64 `mov` has at
7445 // most one memory operand, and there is no rule that takes two, so the load is left where
7446 // it is and the store reads the register it wrote.
7447 assert_eq!(
7448 lower(&mut names, &func),
7449 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_64\n \
7450 %1:gpr($rsi) = x64.arg_val_64\n %2:gpr = x64.mov_rm_8 [%0]\n \
7451 x64.mov_mr_8 %2, [%1]\n}\n"
7452 );
7453 }
7454
7455 #[test]
7456 fn an_access_at_a_width_no_rule_is_written_at_is_reported() {
7457 let i64 = Type::int(64);
7458 let (mut names, mut source, block, args) = blank(&[i64]);
7459 let mut build = Builder::new(&mut source, block);
7460 build.load(Type::int(128), args[0], plain(), Flags::default());
7461
7462 // The width is the whole of what is wrong here, so the width is in the message: `load`
7463 // on its own is written about at every other width and would send a reader looking in
7464 // the wrong place.
7465 let failed = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
7466 .expect_err("nothing loads 128 bits");
7467 assert_eq!(failed.to_string(), "no rule lowers a `load` producing a `i128`");
7468 }
7469
7470 #[test]
7471 fn a_return_asks_for_the_value_in_the_register_the_caller_reads() {
7472 let (mut names, mut func, block, args) = blank(&[Type::int(32)]);
7473 let mut build = Builder::new(&mut func, block);
7474 build.ret(&[args[0]]);
7475
7476 // The register is not in the rule, the same way `cl` is not in the rule for a shift. It
7477 // is what the target says the instruction does with its operand, and the allocator is
7478 // what will act on it. There is no `ret` here, because giving the frame back has to
7479 // happen between this and leaving and the frame is not worked out yet.
7480 assert_eq!(
7481 lower(&mut names, &func),
7482 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_32\n \
7483 x64.ret_val_32 %0($rax)\n}\n"
7484 );
7485 }
7486
7487 #[test]
7488 fn a_return_of_two_values_asks_for_the_second_register_as_well() {
7489 let i64 = Type::int(64);
7490 let (mut names, mut func, block, args) = blank(&[i64, i64]);
7491 let mut build = Builder::new(&mut func, block);
7492 build.ret(&[args[0], args[1]]);
7493
7494 // `struct { long a, b; } f(long a, long b)`, after the front end has classified it. Both
7495 // halves are integers, so the second is in the second integer return register, and both
7496 // pseudos say so the same way the one for a single value does.
7497 assert_eq!(
7498 lower(&mut names, &func),
7499 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_64\n \
7500 %1:gpr($rsi) = x64.arg_val_64\n x64.ret_val_64 %0($rax)\n \
7501 x64.ret_val2_64 %1($rdx)\n}\n"
7502 );
7503 }
7504
7505 #[test]
7506 fn two_values_back_in_different_files_are_both_the_first_of_their_own() {
7507 let f64 = Type::float(rucc_ir::Float::F64);
7508 let (mut names, mut func, block, args) = blank(&[f64, Type::int(64)]);
7509 let mut build = Builder::new(&mut func, block);
7510 build.ret(&[args[0], args[1]]);
7511
7512 // `struct { double a; long b; } f(double a, long b)`. The two files are counted apart, so
7513 // neither half is the second of anything and the `double` is in `xmm0` rather than in the
7514 // register a second `double` would have been in. Getting this wrong is not a crash: the
7515 // caller reads a register nobody wrote, and this is where that is ruled out.
7516 assert_eq!(
7517 lower(&mut names, &func),
7518 "mfunc @f {\nblock0:\n %0:xmm($xmm0) = x64.arg_val_f64\n \
7519 %1:gpr($rdi) = x64.arg_val_64\n x64.ret_val_f64 %0($xmm0)\n \
7520 x64.ret_val_64 %1($rax)\n}\n"
7521 );
7522 }
7523
7524 #[test]
7525 fn two_of_the_same_file_back_take_the_first_two_of_it() {
7526 let f64 = Type::float(rucc_ir::Float::F64);
7527 let (mut names, mut func, block, args) = blank(&[f64, f64]);
7528 let mut build = Builder::new(&mut func, block);
7529 build.ret(&[args[0], args[1]]);
7530
7531 // `struct { double x, y; } f(double x, double y)`, which is the vector half of the pair
7532 // above and counts in its own file the same way.
7533 assert_eq!(
7534 lower(&mut names, &func),
7535 "mfunc @f {\nblock0:\n %0:xmm($xmm0) = x64.arg_val_f64\n \
7536 %1:xmm($xmm1) = x64.arg_val_f64\n x64.ret_val_f64 %0($xmm0)\n \
7537 x64.ret_val2_f64 %1($xmm1)\n}\n"
7538 );
7539 }
7540
7541 /// A function whose answer goes back through memory, with the pointer to the space for it in
7542 /// front of whatever else it takes. Only the signature says it is one.
7543 fn returning_through_memory(params: &[Type]) -> (Interner, Func, Block, Vec<Value>) {
7544 let mut names = Interner::new();
7545 let sret = Abi::Sret { size: 32, align: 8 };
7546 let mut signature = Signature::new().and_param(Param::with_abi(Type::PTR, sret));
7547 signature.params.extend(params.iter().copied().map(Param::new));
7548 let mut func = Func::new(names.intern("f"), signature);
7549 let block = func.create_block();
7550 let space = func.append_param(block, Type::PTR);
7551 let values = std::iter::once(space)
7552 .chain(params.iter().map(|&ty| func.append_param(block, ty)))
7553 .collect();
7554 (names, func, block, values)
7555 }
7556
7557 #[test]
7558 fn the_space_a_return_through_memory_was_given_goes_back_in_the_first_return_register() {
7559 let (mut names, mut func, block, _) = returning_through_memory(&[]);
7560 Builder::new(&mut func, block).ret(&[]);
7561
7562 // `struct big f(void)`, where `big` is too large to come back in registers. The `return`
7563 // carries nothing, because the value went into the space the caller handed over, and the
7564 // document still says that address comes back in `rax`. Nothing in the IR says it, so the
7565 // convention says it, and the pseudo is the one any other pointer return would use.
7566 assert_eq!(
7567 lower(&mut names, &func),
7568 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_64\n \
7569 x64.ret_val_64 %0($rax)\n}\n"
7570 );
7571 }
7572
7573 #[test]
7574 fn what_the_function_did_in_between_does_not_take_the_register_off_it() {
7575 let (mut names, mut func, block, args) = returning_through_memory(&[Type::int(32)]);
7576 let mut build = Builder::new(&mut func, block);
7577 build.store(args[1], args[0], plain(), Flags::default());
7578 build.ret(&[]);
7579
7580 // The register is a read at the end and not a move at the start, so it is live across
7581 // everything between the two and the allocator has to keep it somewhere. In a function
7582 // with a call in it that somewhere is a callee saved register, and the address comes back
7583 // into `rax` here rather than whatever the last instruction happened to leave there. That
7584 // is issue #333, and a store is enough to show the value outlives the entry block.
7585 let text = lower(&mut names, &func);
7586 assert!(text.contains("x64.mov_mr_32 %1, [%0]"), "{text}");
7587 assert!(text.ends_with(" x64.ret_val_64 %0($rax)\n}\n"), "{text}");
7588 }
7589
7590 #[test]
7591 fn a_pointer_that_is_only_a_pointer_is_not_given_back() {
7592 let (mut names, mut func, block, args) = blank(&[Type::PTR]);
7593 let mut build = Builder::new(&mut func, block);
7594 build.store(args[0], args[0], plain(), Flags::default());
7595 build.ret(&[]);
7596
7597 // `void f(void **p)`. It takes a pointer first and returns nothing, which is the shape of
7598 // the one above and none of its meaning, and what tells them apart is the signature. A
7599 // `void` function leaves `rax` alone.
7600 assert!(!lower(&mut names, &func).contains("ret_val"));
7601 }
7602
7603 #[test]
7604 fn a_return_of_a_constant_puts_it_in_a_register_first() {
7605 let (mut names, mut func, block, _) = blank(&[]);
7606 let mut build = Builder::new(&mut func, block);
7607 let zero = build.iconst(Type::int(32), 0);
7608 build.ret(&[zero]);
7609
7610 // No rule returns an immediate, so the plan that offers one is turned down and the next
7611 // one materializes it. That is `int main(void) { return 0; }` in full, once the epilogue
7612 // is appended to it.
7613 assert_eq!(
7614 lower(&mut names, &func),
7615 "mfunc @f {\nblock0:\n %0:gpr = x64.mov_ri_32 0\n x64.ret_val_32 %0($rax)\n}\n"
7616 );
7617 }
7618
7619 #[test]
7620 fn the_rule_that_writes_a_constant_down_is_recorded_as_a_rule_that_fired() {
7621 let (mut names, mut func, block, _) = blank(&[]);
7622 let mut build = Builder::new(&mut func, block);
7623 let zero = build.iconst(Type::int(32), 0);
7624 build.ret(&[zero]);
7625
7626 // The loop over the instructions passes a constant by, because a constant is written where
7627 // a register for it is first wanted rather than where the IR put it. So the only place a
7628 // rule about one is ever selected is the materialization, and a mark made in the loop
7629 // alone would report every rule about a constant as a rule nothing reaches.
7630 let out = super::func(&func, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
7631 .expect("every instruction has a rule");
7632 let rules = &crate::select::x86_64::TABLE.rules;
7633 let fired: Vec<&str> = rules
7634 .iter()
7635 .enumerate()
7636 .filter(|(index, _)| out.fired.has(*index))
7637 .map(|(_, rule)| rule.pattern)
7638 .collect();
7639 assert!(fired.contains(&"(iconst.i32 k)"), "{fired:?}");
7640 }
7641
7642 #[test]
7643 fn a_return_of_nothing_is_no_instruction_at_all() {
7644 let (mut names, mut func, block, _) = blank(&[]);
7645 let mut build = Builder::new(&mut func, block);
7646 build.ret(&[]);
7647
7648 // Every part of leaving a function that returns nothing is the epilogue's, and the
7649 // epilogue goes in after allocation. A block with nothing in it is the right answer here
7650 // rather than a function that could not be lowered.
7651 assert_eq!(lower(&mut names, &func), "mfunc @f {\nblock0:\n}\n");
7652 }
7653
7654 #[test]
7655 fn the_allocator_is_what_moves_the_answer_into_the_return_register() {
7656 let (mut names, mut source, block, _) = blank(&[]);
7657 let mut build = Builder::new(&mut source, block);
7658 let zero = build.iconst(Type::int(32), 0);
7659 build.ret(&[zero]);
7660
7661 let mut out = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
7662 .expect("every instruction has a rule")
7663 .func;
7664 let env = env();
7665 let allocation = rucc_regalloc::run(&mut out, &env, "test", true);
7666 let frame = Frame::of(&out, &allocation, &Layout::new(&SYSV, REGS));
7667 finish(
7668 &mut out,
7669 &allocation,
7670 &frame,
7671 &Stack::default(),
7672 Convention::new(&SYSV, &FRAME),
7673 &mut names,
7674 );
7675
7676 // `int main(void) { return 0; }` end to end. Nothing here asked for `rax`: the rule said
7677 // the value goes back, the target said where, and the allocator is what made it true. The
7678 // epilogue is what leaves, and this function needs no frame, so it is the return alone.
7679 //
7680 // Two instructions and no copy, which is what a hint buys. The return insists on `rax`,
7681 // so `rax` is the register the allocator tries first for the value the return reads, and
7682 // the constant is written straight into it.
7683 assert_eq!(
7684 mir::print_func(&out, &names, ®S),
7685 "mfunc @f {\nblock0:\n $rax = x64.mov_ri_32 0\n \
7686 x64.ret_val_32 $rax($rax)\n x64.ret\n}\n"
7687 );
7688 }
7689
7690 #[test]
7691 fn a_function_of_two_arguments_is_a_whole_function_now() {
7692 let i32 = Type::int(32);
7693 let (mut names, mut source, block, args) = blank(&[i32, i32]);
7694 let mut build = Builder::new(&mut source, block);
7695 let sum = build.binary(Opcode::Add, args[0], args[1], Flags::default());
7696 build.ret(&[sum]);
7697
7698 let mut out = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
7699 .expect("every instruction has a rule")
7700 .func;
7701 let env = env();
7702 let allocation = rucc_regalloc::run(&mut out, &env, "test", true);
7703 let frame = Frame::of(&out, &allocation, &Layout::new(&SYSV, REGS));
7704 finish(
7705 &mut out,
7706 &allocation,
7707 &frame,
7708 &Stack::default(),
7709 Convention::new(&SYSV, &FRAME),
7710 &mut names,
7711 );
7712
7713 // `int f(int a, int b) { return a + b; }` end to end, and this is the test the argument
7714 // side exists for. Before it there was no way to write one: the allocator refuses a
7715 // function whose entry block takes parameters, because there is no edge into an entry
7716 // block for the moves that give a block parameter its value to go on.
7717 //
7718 // One move, and it is the one the machine's addition needs rather than one the allocator
7719 // owes anybody. Each argument stays in the register it arrived in, because the pseudo
7720 // that defines it insists on that register and the allocator now tries it first, and the
7721 // sum stays in the register the addition wrote it to until the return reads it out. The
7722 // copy in front of a two address instruction is what makes its destination one of the
7723 // registers it reads, and the source operand keeps its own name because the destination
7724 // is what the encoder writes.
7725 assert_eq!(
7726 mir::print_func(&out, &names, ®S),
7727 "mfunc @f {\nblock0:\n $rdi($rdi) = x64.arg_val_32\n \
7728 $rsi($rsi) = x64.arg_val_32\n \
7729 $rdi(reuse 1) = x64.add_rr_32 $rdi, $rsi\n $rax = x64.mov_rr_64 $rdi\n \
7730 x64.ret_val_32 $rax($rax)\n x64.ret\n}\n"
7731 );
7732 }
7733
7734 #[test]
7735 fn an_argument_with_no_register_left_for_it_is_read_out_of_the_caller_s_stack() {
7736 let i64 = Type::int(64);
7737 let (mut names, mut source, block, args) = blank(&[i64; 7]);
7738 let mut build = Builder::new(&mut source, block);
7739 build.ret(&[args[6]]);
7740
7741 let lowered = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
7742 .expect("the seventh is read from memory");
7743
7744 // SysV passes six integers in registers and the seventh in the caller's memory, so six of
7745 // these are pseudos that encode to nothing and the seventh is a load that encodes to real
7746 // bytes. Its displacement is nothing here for the reason a local's is: there is no frame
7747 // yet. What the walk hands on is which instruction is waiting, and for how far up the
7748 // caller's argument area, which is the bottom of it because it is the first one there.
7749 assert_eq!(lowered.stack.arguments.len(), 1);
7750 assert_eq!(lowered.stack.arguments[0].1, 0);
7751 let text = mir::print_func(&lowered.func, &names, ®S);
7752 assert!(text.contains("%6:gpr = x64.mov_rm_64 [$rsp]"), "{text}");
7753 assert_eq!(text.matches("x64.arg_val_64").count(), 6, "{text}");
7754 }
7755
7756 #[test]
7757 fn the_frame_is_what_says_how_far_up_the_caller_s_stack_an_argument_is() {
7758 let i64 = Type::int(64);
7759 let (mut names, mut source, block, args) = blank(&[i64; 8]);
7760 let mut build = Builder::new(&mut source, block);
7761 let sum = build.binary(Opcode::Add, args[6], args[7], Flags::default());
7762 build.ret(&[sum]);
7763
7764 let lowered = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
7765 .expect("both are read from memory");
7766 let stack = lowered.stack;
7767 let mut out = lowered.func;
7768 let env = env();
7769 let allocation = rucc_regalloc::run(&mut out, &env, "test", true);
7770 let layout = stack.layout(Layout::new(&SYSV, REGS));
7771 let frame = Frame::of(&out, &allocation, &layout);
7772 finish(&mut out, &allocation, &frame, &stack, Convention::new(&SYSV, &FRAME), &mut names);
7773
7774 // A leaf that takes no frame, so the stack pointer never moves and the only thing between
7775 // it and the caller's arguments is the return address the call pushed. The seventh
7776 // parameter is at the bottom of the caller's argument area and the eighth is one word
7777 // further up, which is the eight bytes between the two offsets.
7778 let text = mir::print_func(&out, &names, ®S);
7779 assert_eq!(frame.size(), 0);
7780 assert_eq!(frame.incoming(), Incoming::from_stack(8));
7781 assert!(text.contains("x64.mov_rm_64 [$rsp + 8]"), "{text}");
7782 assert!(text.contains("x64.mov_rm_64 [$rsp + 16]"), "{text}");
7783 }
7784
7785 #[test]
7786 fn a_realigned_frame_reaches_the_caller_s_arguments_through_the_frame_pointer() {
7787 let i64 = Type::int(64);
7788 let (mut names, mut source, block, args) = blank(&[i64; 7]);
7789 let wide = slot(&mut source, block, 64, 32);
7790 let mut build = Builder::new(&mut source, block);
7791 build.store(args[6], wide, plain(), Flags::default());
7792 build.ret(&[args[6]]);
7793
7794 let lowered = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
7795 .expect("every instruction has a rule");
7796 let stack = lowered.stack;
7797 let mut out = lowered.func;
7798 let env = env();
7799 let allocation = rucc_regalloc::run(&mut out, &env, "test", true);
7800 let layout = stack.layout(Layout::new(&SYSV, REGS));
7801 let frame = Frame::of(&out, &allocation, &layout);
7802 finish(&mut out, &allocation, &frame, &stack, Convention::new(&SYSV, &FRAME), &mut names);
7803
7804 // A local wanting thirty two byte alignment makes the prologue force the stack pointer,
7805 // which throws away how far the caller's stack was. So the load the lowering wrote off the
7806 // stack pointer is rewritten to read through the frame pointer, at the one distance that
7807 // survives: the word the prologue pushed the frame pointer into, and the return address
7808 // above it.
7809 let text = mir::print_func(&out, &names, ®S);
7810 assert_eq!(frame.realign(), Some(32));
7811 assert_eq!(frame.incoming(), Incoming::from_frame(16));
7812 assert!(text.contains("x64.mov_rm_64 [$rbp + 16]"), "{text}");
7813 assert!(!text.contains("x64.mov_rm_64 [$rsp"), "{text}");
7814 }
7815
7816 #[test]
7817 fn a_jump_is_the_edge_and_nothing_else() {
7818 let i32 = Type::int(32);
7819 let (mut names, mut source, entry, args) = blank(&[i32]);
7820 let next = source.create_block();
7821 let got = source.append_param(next, i32);
7822 Builder::new(&mut source, entry).jump(next, &[args[0]]);
7823 Builder::new(&mut source, next).ret(&[got]);
7824
7825 // Two blocks and two instructions, and the jump is neither of them. What it was is the
7826 // arm on the first block, and what the arm carries is the argument it was called with.
7827 assert_eq!(
7828 lower(&mut names, &source),
7829 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_32 block1(%0)\n\n\
7830 block1(%1:gpr):\n x64.ret_val_32 %1($rax)\n}\n"
7831 );
7832 }
7833
7834 /// A block that reads what a block below it writes is filled after it, not before it.
7835 ///
7836 /// The blocks are written entry, `early`, `late`, `exit`, and the entry jumps straight past
7837 /// `early` to `late`, so `late` dominates `early` while sitting below it in the function.
7838 /// Filling them in the order they are written reaches the read in `early` first, and reading
7839 /// a value with no register yet mints one. The cast in `late` is no instruction at all, so
7840 /// what it does is give its answer the register its operand is already in, and that is not
7841 /// the register the read minted. Nothing writes the register the read minted. The printer
7842 /// says `%?` for a register nothing defines, which is what this looks for, and what came out
7843 /// of the real bug was SQLite loading a stack slot no store ever reached.
7844 #[test]
7845 fn a_block_that_reads_what_a_block_below_it_writes_is_filled_after_it() {
7846 let i64 = Type::int(64);
7847 let (mut names, mut source, entry, args) = blank(&[i64, i64]);
7848 let early = source.create_block();
7849 let late = source.create_block();
7850 let exit = source.create_block();
7851
7852 Builder::new(&mut source, entry).jump(late, &[]);
7853 let ptr = cast(&mut source, late, Opcode::IntToPtr, args[0], Type::PTR);
7854 Builder::new(&mut source, early).ret(&[ptr]);
7855 let mut build = Builder::new(&mut source, late);
7856 let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
7857 build.br_if(cond, early, &[], exit, &[]);
7858 Builder::new(&mut source, exit).ret(&[args[1]]);
7859
7860 let text = lower(&mut names, &source);
7861 assert!(!text.contains("%?"), "every register has something that writes it: {text}");
7862 }
7863
7864 /// A constant is written where it is wanted rather than where the IR defined it, and two
7865 /// blocks wanting the same one is two places. Writing it once and reading it in both is a
7866 /// register read where nothing wrote it, unless the block it was written in happens to
7867 /// dominate the other, which nothing here checks and which the second arm of a branch never
7868 /// does. Each block gets its own copy of the number instead.
7869 #[test]
7870 fn a_constant_two_blocks_want_is_written_in_both_of_them() {
7871 let i32 = Type::int(32);
7872 let (mut names, mut source, entry, args) = blank(&[i32, i32]);
7873 let then = source.create_block();
7874 let other = source.create_block();
7875 let join = source.create_block();
7876 let got = source.append_param(join, i32);
7877
7878 let mut build = Builder::new(&mut source, entry);
7879 let seven = build.iconst(i32, 7);
7880 let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
7881 build.br_if(cond, then, &[], other, &[]);
7882 // Both arms want the seven in a register, because a block argument is never an immediate,
7883 // and neither arm dominates the other.
7884 Builder::new(&mut source, then).jump(join, &[seven]);
7885 Builder::new(&mut source, other).jump(join, &[seven]);
7886 Builder::new(&mut source, join).ret(&[got]);
7887
7888 let text = lower(&mut names, &source);
7889 assert_eq!(text.matches("x64.mov_ri_32 7").count(), 2, "one seven per block: {text}");
7890 }
7891
7892 /// An argument on an edge out of a block that leaves two ways is read after every instruction
7893 /// of the block is written, and reading one can write an instruction, which would land after
7894 /// the branch that has already jumped past it. The branch goes back on the end.
7895 #[test]
7896 fn a_constant_an_edge_wants_is_written_before_the_branch_and_not_after_it() {
7897 let i32 = Type::int(32);
7898 let (mut names, mut source, entry, args) = blank(&[i32, i32]);
7899 let then = source.create_block();
7900 let join = source.create_block();
7901 let got = source.append_param(join, i32);
7902
7903 let mut build = Builder::new(&mut source, entry);
7904 let nine = build.iconst(i32, 9);
7905 let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
7906 build.br_if(cond, then, &[], join, &[nine]);
7907 Builder::new(&mut source, then).jump(join, &[args[0]]);
7908 Builder::new(&mut source, join).ret(&[got]);
7909
7910 let out = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
7911 .expect("every instruction has a rule")
7912 .func;
7913 let entry = out.entry().expect("an entry block");
7914 let last = out.terminator(entry).expect("a block that leaves two ways has a branch");
7915 let branch = names.intern("x64.br_cond_8");
7916 assert_eq!(
7917 out[last].opcode,
7918 mir::Opcode::new(branch),
7919 "the branch is last: {}",
7920 mir::print_func(&out, &names, ®S)
7921 );
7922 }
7923
7924 #[test]
7925 fn a_conditional_branch_is_lowered_to_the_condition_and_nothing_about_where_it_goes() {
7926 let i32 = Type::int(32);
7927 let (mut names, mut source, entry, args) = blank(&[i32, i32]);
7928 let then = source.create_block();
7929 let other = source.create_block();
7930 let mut build = Builder::new(&mut source, entry);
7931 let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
7932 build.br_if(cond, then, &[], other, &[]);
7933 Builder::new(&mut source, then).ret(&[args[0]]);
7934 Builder::new(&mut source, other).ret(&[args[1]]);
7935
7936 // The comparison writes a byte and the branch reads it, and neither says a block. Both
7937 // arms are on the entry block, in the order the branch took them, so the arm that runs
7938 // when the condition holds is the first.
7939 assert_eq!(
7940 lower(&mut names, &source),
7941 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_32\n \
7942 %1:gpr($rsi) = x64.arg_val_32\n %2:gpr = x64.cmp_set_l_32 %0, %1\n \
7943 x64.br_cond_8 %2, block1, block2\n\n\
7944 block1:\n x64.ret_val_32 %0($rax)\n\n\
7945 block2:\n x64.ret_val_32 %1($rax)\n}\n"
7946 );
7947 }
7948
7949 /// A choice between two values, which is one instruction and no blocks at all.
7950 ///
7951 /// The arms come out the other way round from the IR, because a conditional move overwrites its
7952 /// destination and the destination is the arm taken when the condition does not hold. The
7953 /// condition arrives last for the same reason: it is read by the test in front of the move
7954 /// rather than by the move.
7955 #[test]
7956 fn a_select_is_lowered_to_a_test_and_a_conditional_move() {
7957 let i32 = Type::int(32);
7958 let (mut names, mut source, entry, args) = blank(&[i32, i32]);
7959 let mut build = Builder::new(&mut source, entry);
7960 let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
7961 let picked = build.select(cond, args[0], args[1]);
7962 build.ret(&[picked]);
7963
7964 assert_eq!(
7965 lower(&mut names, &source),
7966 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_32\n \
7967 %1:gpr($rsi) = x64.arg_val_32\n %2:gpr = x64.cmp_set_l_32 %0, %1\n \
7968 %3:gpr(reuse 1) = x64.test_cmov_ne_32 %1, %0, %2\n \
7969 x64.ret_val_32 %3($rax)\n}\n"
7970 );
7971 }
7972
7973 #[test]
7974 fn a_branch_over_a_block_is_a_whole_function_now() {
7975 let i32 = Type::int(32);
7976 let (mut names, mut source, entry, args) = blank(&[i32, i32]);
7977 let then = source.create_block();
7978 let other = source.create_block();
7979 let join = source.create_block();
7980 let got = source.append_param(join, i32);
7981 let mut build = Builder::new(&mut source, entry);
7982 let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
7983 build.br_if(cond, then, &[], other, &[]);
7984 let mut build = Builder::new(&mut source, then);
7985 let sum = build.binary(Opcode::Add, args[0], args[1], Flags::default());
7986 build.jump(join, &[sum]);
7987 Builder::new(&mut source, other).jump(join, &[args[1]]);
7988 Builder::new(&mut source, join).ret(&[got]);
7989
7990 // `int f(int a, int b) { if (a < b) return a + b; else return b; }` end to end, written
7991 // the way a front end writes it: both arms of the branch are blocks of their own and the
7992 // return is the block they meet at. No edge here is critical, because the two arms out of
7993 // the entry carry nothing and the two arms into the join each leave a block that goes
7994 // nowhere else, so each has its own end to put its move at.
7995 let mut out = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
7996 .expect("every instruction has a rule")
7997 .func;
7998 assert_eq!(crate::split::critical(&mut out), 0, "no edge here is critical");
7999 let env = env();
8000 let allocation = rucc_regalloc::run(&mut out, &env, "test", true);
8001 let frame = Frame::of(&out, &allocation, &Layout::new(&SYSV, REGS));
8002 finish(
8003 &mut out,
8004 &allocation,
8005 &frame,
8006 &Stack::default(),
8007 Convention::new(&SYSV, &FRAME),
8008 &mut names,
8009 );
8010
8011 // One epilogue, on the join, which is the one block the function leaves from, and the
8012 // moves that give the join its parameter are at the end of each arm. Every register is
8013 // physical and the branch is still a branch on a register, because turning it into a
8014 // `test` and a `jcc` is the block layout's and there is no block layout yet.
8015 let text = mir::print_func(&out, &names, ®S);
8016 assert_eq!(text.matches("x64.ret\n").count(), 1, "{text}");
8017 assert!(text.contains("x64.br_cond_8"), "{text}");
8018 assert!(text.contains("x64.add_rr_32"), "{text}");
8019 assert!(!text.contains('%'), "{text}");
8020 }
8021
8022 #[test]
8023 fn a_critical_edge_is_split_before_the_allocator_ever_sees_it() {
8024 let i32 = Type::int(32);
8025 let (mut names, mut source, entry, args) = blank(&[i32, i32]);
8026 let then = source.create_block();
8027 let join = source.create_block();
8028 let got = source.append_param(join, i32);
8029 let mut build = Builder::new(&mut source, entry);
8030 let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
8031 build.br_if(cond, then, &[], join, &[args[1]]);
8032 Builder::new(&mut source, then).jump(join, &[args[0]]);
8033 let mut build = Builder::new(&mut source, join);
8034 let twice = build.binary(Opcode::Add, got, got, Flags::default());
8035 build.ret(&[twice]);
8036
8037 // The else arm is critical: the entry block leaves two ways and the join is arrived at
8038 // two ways, and the arm carries a value. Without splitting it the allocator asserts,
8039 // because the move that gives the join its parameter would have to run at the end of a
8040 // block that also goes to the other arm.
8041 let mut out = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
8042 .expect("every instruction has a rule")
8043 .func;
8044 assert_eq!(crate::split::critical(&mut out), 1);
8045 let env = env();
8046 let allocation = rucc_regalloc::run(&mut out, &env, "test", true);
8047 let frame = Frame::of(&out, &allocation, &Layout::new(&SYSV, REGS));
8048 finish(
8049 &mut out,
8050 &allocation,
8051 &frame,
8052 &Stack::default(),
8053 Convention::new(&SYSV, &FRAME),
8054 &mut names,
8055 );
8056
8057 // The block the split added is where the move went, and it is the whole of that block.
8058 let text = mir::print_func(&out, &names, ®S);
8059 assert_eq!(out.block_count(), 4, "{text}");
8060 assert_eq!(text.matches("x64.ret\n").count(), 1, "{text}");
8061 }
8062
8063 #[test]
8064 fn a_call_passes_what_the_convention_says_and_takes_back_what_it_says() {
8065 let i32 = Type::int(32);
8066 let (mut names, mut source, block, args) = blank(&[i32, i32]);
8067 let sig =
8068 source.add_signature(Signature::new().with_params(&[i32, i32]).with_returns(&[i32]));
8069 let callee = names.intern("g");
8070 let call = Builder::new(&mut source, block).call(callee, sig, &[args[0], args[1]]);
8071 let got = source[call].first_result.expect("an integer comes back");
8072 Builder::new(&mut source, block).ret(&[got]);
8073
8074 // `int f(int a, int b) { return g(a, b); }`. The arguments arrived where the call wants
8075 // them, so what the call reads is what arrived, and the whole of the convention is in the
8076 // constraints rather than in a move.
8077 let text = lower(&mut names, &source);
8078 assert!(text.contains("= x64.call %0($rdi), %1($rsi), @g"), "{text}");
8079 assert!(text.contains("x64.ret_val_32 %2($rax)"), "{text}");
8080 // What the call writes is the value that comes back and then every register the callee is
8081 // free to destroy, in both classes, which is the whole of what stops the allocator from
8082 // leaving something in one of them.
8083 assert!(text.contains("%2:gpr($rax), $rcx, $rdx, $r8, $r9, $r10, $r11, $xmm0,"), "{text}");
8084 assert!(text.contains("$xmm15 = x64.call"), "{text}");
8085 }
8086
8087 #[test]
8088 fn what_the_frame_owes_a_call_comes_back_with_the_function() {
8089 let i32 = Type::int(32);
8090 let sig = |source: &mut Func| source.add_signature(Signature::new().with_params(&[i32]));
8091
8092 let (mut names, mut source, block, args) = blank(&[i32]);
8093 let sig = sig(&mut source);
8094 let callee = names.intern("g");
8095 Builder::new(&mut source, block).call(callee, sig, &[args[0]]);
8096 let out = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
8097 .expect("every instruction has a rule");
8098
8099 // Nothing on the stack, so nothing owed, but not a leaf either: a function that calls
8100 // owes the callee an aligned stack pointer and may not use the red zone.
8101 assert_eq!(out.stack.calls, Some(0));
8102 let layout = out.stack.layout(Layout::new(&SYSV, REGS));
8103 assert!(!layout.leaf);
8104 assert_eq!(layout.outgoing, 0);
8105
8106 // The same call under the other convention owes thirty two bytes for the callee to spill
8107 // its register arguments into, which is a fact about the convention and not about the call.
8108 let out = func(&source, &mut names, &SELECTOR, &x86_64::WIN64, &Elsewhere::default())
8109 .expect("every instruction has a rule");
8110 assert_eq!(out.stack.calls, Some(32));
8111
8112 // And a function that calls nothing is a leaf, which is what says it may use the red zone.
8113 let (mut names, mut source, block, args) = blank(&[i32]);
8114 Builder::new(&mut source, block).ret(&[args[0]]);
8115 let out = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
8116 .expect("every instruction has a rule");
8117 assert_eq!(out.stack.calls, None);
8118 assert!(out.stack.layout(Layout::new(&SYSV, REGS)).leaf);
8119 }
8120
8121 /// A Windows variadic prologue writes the argument registers the signature did not name into
8122 /// the shadow space the caller already reserved, which makes every argument one run of words up
8123 /// there and a `va_start` the address of the first of them. One `lea` and one store, and no
8124 /// counts, because a list that is a pointer has nowhere to put one and nothing that reads one.
8125 #[test]
8126 fn a_windows_variadic_function_homes_its_spare_registers_in_the_callers_area() {
8127 let mut names = Interner::new();
8128 let params = [Type::int(32), Type::PTR];
8129 let signature = Signature::new().with_params(¶ms).variadic();
8130 let mut source = Func::new(names.intern("f"), signature);
8131 let block = source.create_block();
8132 let values: Vec<Value> = params.iter().map(|&ty| source.append_param(block, ty)).collect();
8133 let mut build = Builder::new(&mut source, block);
8134 let args = build.func().push_values(&values[1..]);
8135 build.inst(InstData { args, ..InstData::new(Opcode::VaStart) }, &[]);
8136 build.ret(&[]);
8137
8138 let out = func(&source, &mut names, &SELECTOR, &x86_64::WIN64, &Elsewhere::default())
8139 .expect("every instruction has a rule");
8140 let text = mir::print_func(&out.func, &names, ®S);
8141
8142 // Two named parameters, so the registers at the next two positions hold arguments nobody
8143 // named and both are written up into the caller's area. The displacement is empty here and
8144 // `finish` fills it in, the same way it does for a parameter the registers ran out before.
8145 assert!(text.contains("($r8) = x64.arg_val_64"), "{text}");
8146 assert!(text.contains("($r9) = x64.arg_val_64"), "{text}");
8147 assert_eq!(text.matches("x64.mov_mr_64").count(), 3, "two homed and one stored: {text}");
8148 assert!(!text.contains("x64.mov_ri_32"), "and no field holds a count: {text}");
8149
8150 // All three waiting on the same fixup, and the last of them is the `lea` the list is given,
8151 // sixteen bytes up, which is where the two arguments the signature does name stopped.
8152 assert_eq!(out.stack.arguments.len(), 3);
8153 assert_eq!(out.stack.arguments[2].1, 16);
8154 }
8155
8156 #[test]
8157 fn a_value_that_outlives_a_call_is_not_left_where_the_call_destroys_it() {
8158 let i32 = Type::int(32);
8159 let (mut names, mut source, block, args) = blank(&[i32]);
8160 let sig = source.add_signature(Signature::new().with_params(&[i32]).with_returns(&[i32]));
8161 let callee = names.intern("g");
8162 let call = Builder::new(&mut source, block).call(callee, sig, &[args[0]]);
8163 let got = source[call].first_result.expect("an integer comes back");
8164 let mut build = Builder::new(&mut source, block);
8165 let sum = build.binary(Opcode::Add, got, args[0], Flags::default());
8166 build.ret(&[sum]);
8167
8168 // `int f(int a) { return g(a) + a; }`, which is the smallest program that asks the
8169 // question: `a` is read after the call and `rdi` is a register the call destroys.
8170 let lowered = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
8171 .expect("every instruction has a rule");
8172 let layout = lowered.stack.layout(Layout::new(&SYSV, REGS));
8173 let mut out = lowered.func;
8174 let env = env();
8175 let allocation = rucc_regalloc::run(&mut out, &env, "test", true);
8176 let frame = Frame::of(&out, &allocation, &layout);
8177 finish(
8178 &mut out,
8179 &allocation,
8180 &frame,
8181 &Stack::default(),
8182 Convention::new(&SYSV, &FRAME),
8183 &mut names,
8184 );
8185
8186 // It went to a register the callee has to put back, and the prologue and epilogue are what
8187 // put it back, which is the whole bargain the two halves of a convention make.
8188 let text = mir::print_func(&out, &names, ®S);
8189 assert!(text.contains("$rbx"), "{text}");
8190 assert!(!text.contains('%'), "{text}");
8191 assert_eq!(text.matches("x64.call").count(), 1, "{text}");
8192 }
8193
8194 #[test]
8195 fn a_call_with_more_arguments_than_registers_writes_the_rest_into_the_outgoing_area() {
8196 let i64 = Type::int(64);
8197 let (mut names, mut source, block, args) = blank(&[i64]);
8198 let seven = vec![i64; 7];
8199 let sig = source.add_signature(Signature::new().with_params(&seven));
8200 let callee = names.intern("g");
8201 let passed = vec![args[0]; 7];
8202 Builder::new(&mut source, block).call(callee, sig, &passed);
8203
8204 let lowered = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
8205 .expect("the seventh goes to memory");
8206 // The bytes the call needs are on the layout the frame is worked out from, so that the
8207 // frame reserves as many as the widest call in the function asked for.
8208 assert_eq!(lowered.stack.calls, Some(8));
8209 let text = mir::print_func(&lowered.func, &names, ®S);
8210 assert!(text.contains("x64.mov_mr_64 %0, [$rsp]\n"), "{text}");
8211 }
8212
8213 #[test]
8214 fn a_call_this_cannot_make_is_reported_rather_than_made() {
8215 let (mut names, mut source, block, _) = blank(&[]);
8216 let returns = [Type::float(rucc_ir::Float::F80), Type::int(64)];
8217 let sig = source.add_signature(Signature::new().with_returns(&returns));
8218 let callee = names.intern("g");
8219 Builder::new(&mut source, block).call(callee, sig, &[]);
8220 let failed = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
8221 .expect_err("a long double is on the x87");
8222 assert_eq!(failed.to_string(), "what this call gives back is on the x87 stack");
8223 }
8224
8225 /// A `long double` on its own is a different answer, because on its own it comes back on the
8226 /// x87 stack rather than in a register, which is somewhere the call cannot be said to write.
8227 ///
8228 /// So the call gives back nothing at all and the value is taken off the stack by the `fstp`
8229 /// straight after it. That instruction has to be straight after it: the stack is one place and
8230 /// anything else that touched it before this ran would be looking at the value still on it.
8231 #[test]
8232 fn a_call_that_gives_back_a_long_double_takes_it_off_the_stack_at_once() {
8233 let (mut names, mut source, block, _) = blank(&[]);
8234 let long_double = Type::float(rucc_ir::Float::F80);
8235 let sig = source.add_signature(Signature::new().with_returns(&[long_double]));
8236 let callee = names.intern("g");
8237 Builder::new(&mut source, block).call(callee, sig, &[]);
8238
8239 let lowered = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
8240 .expect("the value comes back in st0");
8241 let text = mir::print_func(&lowered.func, &names, ®S);
8242 let after: Vec<&str> =
8243 text.lines().skip_while(|line| !line.contains("x64.call")).skip(1).collect();
8244 assert_eq!(after[0].trim(), "%0:gpr = x64.lea_64 [$rsp]", "{text}");
8245 assert_eq!(after[1].trim(), "x64.fstp_t [%0]", "{text}");
8246 // And the slot it went into is the sixteen bytes the type takes, like every other one.
8247 assert_eq!(lowered.stack.locals.len(), 1, "{text}");
8248 assert_eq!(lowered.stack.locals[0].size, X87_BYTES);
8249 }
8250
8251 #[test]
8252 fn a_call_through_an_address_goes_through_the_register_the_address_is_in() {
8253 let i32 = Type::int(32);
8254 let (mut names, mut source, block, args) = blank(&[Type::PTR, i32]);
8255 let sig = source.add_signature(Signature::new().with_params(&[i32]).with_returns(&[i32]));
8256 let varargs = source.push_abis(&[]);
8257 let info = source.add_call(CallInfo { callee: None, signature: sig, varargs });
8258 let mut build = Builder::new(&mut source, block);
8259 let inst = InstData {
8260 args: build.func().push_values(&[args[0], args[1]]),
8261 extra: Extra::Call(info),
8262 ..InstData::new(Opcode::CallIndirect)
8263 };
8264 let called = build.inst(inst, &[i32]);
8265 let got = source[called].first_result.expect("an integer comes back");
8266 Builder::new(&mut source, block).ret(&[got]);
8267
8268 // `int f(int (*g)(int), int a) { return g(a); }`. The first operand is the address and
8269 // the arguments are the ones behind it, and everything else about the call is what a call
8270 // to a name would have been.
8271 let text = lower(&mut names, &source);
8272 assert!(text.contains("= x64.call_reg %0, %1($rdi)"), "{text}");
8273 assert!(text.contains("x64.ret_val_32 %2($rax)"), "{text}");
8274 assert!(!text.contains("@g"), "a call through an address names nobody: {text}");
8275 }
8276
8277 #[test]
8278 fn an_instruction_no_rule_covers_is_reported() {
8279 let (mut names, mut source, block, args) = blank(&[Type::PTR]);
8280 let mut build = Builder::new(&mut source, block);
8281 let operands = build.func().push_values(&[args[0]]);
8282 build.inst(InstData { args: operands, ..InstData::new(Opcode::MetaBegin) }, &[]);
8283
8284 // The mark that an object has come into being, which nothing writes an instruction for
8285 // yet: what it needs is a write over a range of the lifetime plane, and that is
8286 // `tamnd/rucc#856`. Nothing about it is a width or a register, so there is nothing for the
8287 // message to add beyond the name.
8288 let failed = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
8289 .expect_err("no rule writes the beginning of a lifetime");
8290 assert_eq!(failed.to_string(), "no rule lowers a `meta_begin`");
8291
8292 // It produces nothing, so there is no type in the message and nothing invents one, and the
8293 // instruction comes back so a caller can ask the function where it was.
8294 let inst = failed.inst().expect("the instruction it is about");
8295 assert_eq!(source[inst].opcode, Opcode::MetaBegin);
8296 }
8297
8298 /// A barrier is written by name here, and what it is depends on the ordering and on nothing
8299 /// else. `crate::expand` is where the reasoning about this machine's memory model lives.
8300 #[test]
8301 fn a_barrier_is_one_instruction_at_the_strongest_ordering_and_none_below_it() {
8302 for order in MemOrder::all().filter(|&order| order != MemOrder::NotAtomic) {
8303 let (mut names, mut source, block, _) = blank(&[]);
8304 let mut build = Builder::new(&mut source, block);
8305 build
8306 .inst(InstData { extra: Extra::Order(order), ..InstData::new(Opcode::Fence) }, &[]);
8307
8308 let text = lower(&mut names, &source);
8309 assert_eq!(text.contains("x64.mfence"), order == MemOrder::SeqCst, "{order:?}: {text}");
8310 }
8311 }
8312
8313 /// A compare and exchange is written by name too, and at the width of the value rather than at
8314 /// the width of the address, which is the mistake worth pinning: everything here is a pointer
8315 /// and only the value says how many bytes the instruction touches.
8316 #[test]
8317 fn a_compare_and_exchange_is_one_instruction_at_the_width_of_the_value() {
8318 for bits in [8, 16, 32, 64] {
8319 let ty = Type::int(bits);
8320 let (mut names, mut source, block, args) = blank(&[Type::PTR, ty, ty]);
8321 let mut build = Builder::new(&mut source, block);
8322 let mem = build.func().add_mem(MemInfo {
8323 size: u64::from(bits / 8),
8324 align: bits / 8,
8325 order: MemOrder::SeqCst,
8326 ..plain()
8327 });
8328 let operands = build.func().push_values(&[args[0], args[1], args[2]]);
8329 build.inst(
8330 InstData {
8331 args: operands,
8332 extra: Extra::Mem(mem),
8333 ..InstData::new(Opcode::Cmpxchg)
8334 },
8335 &[ty, Type::I1],
8336 );
8337
8338 // Two values out of one instruction, the first of them in the register the machine
8339 // reads the expected value out of, the second free for the allocator to place. The
8340 // address is the memory operand and neither of the two values is.
8341 let text = lower(&mut names, &source);
8342 let written = format!("%3:gpr($rax), %4:gpr = x64.cmpxchg_{bits} %1($rax), %2, [%0]");
8343 assert!(text.contains(&written), "{bits}: {text}");
8344 }
8345 }
8346
8347 #[test]
8348 fn more_values_back_than_the_convention_has_registers_for_is_reported() {
8349 let i64 = Type::int(64);
8350 let (mut names, mut source, block, args) = blank(&[i64, i64, i64]);
8351 let mut build = Builder::new(&mut source, block);
8352 build.ret(&[args[0], args[1], args[2]]);
8353
8354 // Two integers come back in `rax` and `rdx` and a third has nowhere to go, which is not a
8355 // gap in the rules but the convention saying no. The front end classifies before it gets
8356 // here, so this is the shape that would mean the classification went wrong.
8357 let failed = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
8358 .expect_err("only two come back");
8359 assert_eq!(
8360 failed.to_string(),
8361 "what this function gives back takes more registers than this convention has for it"
8362 );
8363
8364 let inst = failed.inst().expect("the instruction it is about");
8365 assert_eq!(source[inst].opcode, Opcode::Return);
8366 }
8367
8368 /// A refusal about a signature has no instruction, which is what makes it the one arm apart.
8369 ///
8370 /// Everything else is about something written somewhere in the body and hands it back so a
8371 /// caller can ask the function where it came from. A parameter arrives before the first
8372 /// instruction runs, so there is nothing in the body to point at and the message is about
8373 /// the function.
8374 #[test]
8375 fn a_refusal_about_a_parameter_has_no_instruction_to_point_at() {
8376 let missing = Unsupported::Argument { index: 0, missing: Missing::OnX87 };
8377 assert_eq!(missing.inst(), None);
8378 }
8379
8380 /// An `alloca` of a fixed size, which is what every local whose address is taken becomes.
8381 fn slot(source: &mut Func, block: Block, size: u64, align: u32) -> Value {
8382 let info = MemInfo { size, align, ..plain() };
8383 let mut build = Builder::new(source, block);
8384 let mem = build.func().add_mem(info);
8385 build.value(InstData { extra: Extra::Mem(mem), ..InstData::new(Opcode::Alloca) }, Type::PTR)
8386 }
8387
8388 #[test]
8389 fn a_local_is_memory_in_the_frame_and_one_instruction_that_says_where() {
8390 let (mut names, mut source, block, _) = blank(&[]);
8391 let slot = slot(&mut source, block, 4, 4);
8392 let mut build = Builder::new(&mut source, block);
8393 let nine = build.iconst(Type::int(32), 9);
8394 build.store(nine, slot, plain(), Flags::default());
8395 let loaded = build.load(Type::int(32), slot, plain(), Flags::default());
8396 build.ret(&[loaded]);
8397
8398 let lowered = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
8399 .expect("every instruction has a rule");
8400
8401 // Four bytes on the list the frame is laid out from, and one instruction that says where
8402 // they went in front of each of the two that read them. Its displacement is nothing here
8403 // because there is no frame yet, and which instruction is waiting for which local is what
8404 // `finish` is handed.
8405 assert_eq!(lowered.stack.locals, vec![Local { size: 4, align: 4 }]);
8406 let taken: Vec<usize> = lowered.stack.addresses.iter().map(|&(_, local)| local).collect();
8407 assert_eq!(taken, [0, 0]);
8408 assert_eq!(
8409 mir::print_func(&lowered.func, &names, ®S),
8410 "mfunc @f {\nblock0:\n %0:gpr = x64.lea_64 [$rsp]\n \
8411 %1:gpr = x64.mov_ri_32 9\n x64.mov_mr_32 %1, [%0]\n \
8412 %2:gpr = x64.lea_64 [$rsp]\n %3:gpr = x64.mov_rm_32 [%2]\n \
8413 x64.ret_val_32 %3($rax)\n}\n"
8414 );
8415 }
8416
8417 #[test]
8418 fn a_local_the_program_declared_says_which_declaration_it_is_and_the_rest_say_nothing() {
8419 let (mut names, mut source, block, _) = blank(&[]);
8420 let scratch = slot(&mut source, block, 4, 4);
8421 let mut build = Builder::new(&mut source, block);
8422 let mem = build.func().add_mem(MemInfo { size: 8, align: 8, ..plain() });
8423 let declared = build
8424 .value(InstData { extra: Extra::Mem(mem), ..InstData::new(Opcode::Alloca) }, Type::PTR);
8425 build.func().declare_mem(mem, 41);
8426 build.store(scratch, declared, MemInfo { size: 8, align: 8, ..plain() }, Flags::default());
8427 build.ret(&[]);
8428
8429 let lowered = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
8430 .expect("every instruction has a rule");
8431
8432 // Two locals and one declaration, held against the order the allocas were lowered in,
8433 // which is the only name a local has by the time the frame places it. The scratch one was
8434 // reached first and is local zero, so the declared one is local one.
8435 assert_eq!(lowered.stack.locals.len(), 2);
8436 assert_eq!(lowered.stack.declared, vec![(1, 41)]);
8437 }
8438
8439 /// A local the program kept in a value comes out saying which register holds it.
8440 ///
8441 /// The other half of the local above, which had a slot. This one has none, so what carries the
8442 /// declaration is the register the instruction computing it writes into.
8443 #[test]
8444 fn a_local_the_program_kept_in_a_value_says_which_register_holds_it() {
8445 let (mut names, mut source, block, _) = blank(&[]);
8446 let mut build = Builder::new(&mut source, block);
8447 let nine = build.iconst(Type::int(32), 9);
8448 let ten = build.iconst(Type::int(32), 10);
8449 let sum = build.binary(Opcode::Add, nine, ten, Flags::default());
8450 build.func().declare_value(sum, 41);
8451 build.ret(&[sum]);
8452
8453 let lowered = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
8454 .expect("every instruction has a rule");
8455
8456 // One pair and not three. The constants are values the program never declared, and a
8457 // register holding one of those is nobody's. The register is the one the addition writes,
8458 // which the listing under it is what pins down.
8459 assert_eq!(lowered.func.named, vec![(41, mir::Reg::virtual_reg(1))]);
8460 assert_eq!(
8461 mir::print_func(&lowered.func, &names, ®S),
8462 "mfunc @f {\nblock0:\n %0:gpr = x64.mov_ri_32 9\n \
8463 %1:gpr(reuse 1) = x64.add_ri_32 %0, 10\n x64.ret_val_32 %1($rax)\n}\n"
8464 );
8465 }
8466
8467 /// A local held in a constant two blocks want is two registers and both of them are it.
8468 ///
8469 /// Why the declaration is written down as each register is handed out rather than once at the
8470 /// end over the map from values to registers. That map remembers the last register a value was
8471 /// written into, and a constant is written again in every block that wants one, so a local held
8472 /// in one would come out findable in the last block of the function and nowhere else.
8473 #[test]
8474 fn a_local_held_in_a_constant_two_blocks_want_is_named_in_both_of_them() {
8475 let i32 = Type::int(32);
8476 let (mut names, mut source, entry, args) = blank(&[i32, i32]);
8477 let then = source.create_block();
8478 let other = source.create_block();
8479 let join = source.create_block();
8480 let got = source.append_param(join, i32);
8481
8482 let mut build = Builder::new(&mut source, entry);
8483 let seven = build.iconst(i32, 7);
8484 let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
8485 build.func().declare_value(seven, 41);
8486 build.br_if(cond, then, &[], other, &[]);
8487 Builder::new(&mut source, then).jump(join, &[seven]);
8488 Builder::new(&mut source, other).jump(join, &[seven]);
8489 Builder::new(&mut source, join).ret(&[got]);
8490
8491 let lowered = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
8492 .expect("every instruction has a rule");
8493
8494 let held = &lowered.func.named;
8495 assert_eq!(held.len(), 2, "one register per block that wanted the seven: {held:?}");
8496 assert!(held.iter().all(|&(decl, _)| decl == 41), "{held:?}");
8497 assert_ne!(held[0].1, held[1].1, "the same register in two blocks: {held:?}");
8498 }
8499
8500 /// A parameter the program declared comes out named too, in the register it arrived in.
8501 ///
8502 /// The case the walk over the map at the end is for. A parameter is put in a register the
8503 /// convention chose rather than in a fresh one, so nothing asks the mint for it and the pair
8504 /// would otherwise never be written down.
8505 #[test]
8506 fn a_parameter_the_program_declared_says_which_register_it_arrived_in() {
8507 let i32 = Type::int(32);
8508 let (mut names, mut source, block, args) = blank(&[i32]);
8509 let mut build = Builder::new(&mut source, block);
8510 build.func().declare_value(args[0], 41);
8511 build.ret(&[args[0]]);
8512
8513 let lowered = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
8514 .expect("every instruction has a rule");
8515
8516 let held = &lowered.func.named;
8517 assert_eq!(held.len(), 1, "one pair for the one parameter: {held:?}");
8518 assert_eq!(held[0].0, 41);
8519 }
8520
8521 /// A function with nothing declared in it says nothing, which is every function compiled
8522 /// without debugging information asked for.
8523 #[test]
8524 fn a_function_the_front_end_named_nothing_in_names_no_registers() {
8525 let (mut names, mut source, block, _) = blank(&[]);
8526 let mut build = Builder::new(&mut source, block);
8527 let nine = build.iconst(Type::int(32), 9);
8528 build.ret(&[nine]);
8529
8530 let lowered = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
8531 .expect("every instruction has a rule");
8532 assert!(lowered.func.named.is_empty(), "{:?}", lowered.func.named);
8533 }
8534
8535 #[test]
8536 fn the_frame_is_what_fills_the_address_of_a_local_in() {
8537 let (mut names, mut source, block, _) = blank(&[]);
8538 let slot = slot(&mut source, block, 4, 4);
8539 let mut build = Builder::new(&mut source, block);
8540 let nine = build.iconst(Type::int(32), 9);
8541 build.store(nine, slot, plain(), Flags::default());
8542 let loaded = build.load(Type::int(32), slot, plain(), Flags::default());
8543 build.ret(&[loaded]);
8544
8545 let lowered = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
8546 .expect("every instruction has a rule");
8547 let stack = lowered.stack;
8548 let mut out = lowered.func;
8549 let env = env();
8550 let allocation = rucc_regalloc::run(&mut out, &env, "test", true);
8551 let layout = stack.layout(Layout::new(&SYSV, REGS));
8552 let frame = Frame::of(&out, &allocation, &layout);
8553 finish(&mut out, &allocation, &frame, &stack, Convention::new(&SYSV, &FRAME), &mut names);
8554
8555 // `int f(void) { int x; x = 9; return x; }` with the address of `x` taken, end to end.
8556 // A leaf small enough to live in the red zone takes no frame at all, so the stack pointer
8557 // never moves and the four bytes are below it, which is what the negative offset is. The
8558 // instruction the lowering left with nothing in its displacement now has the answer in it.
8559 let text = mir::print_func(&out, &names, ®S);
8560 assert!(text.contains("= x64.lea_64 [$rsp - 8]"), "{text}");
8561 assert!(!text.contains("x64.sub_ri_64"), "{text}");
8562 assert_eq!(frame.size(), 0);
8563 assert_eq!(frame.local(0), Some(-8));
8564 }
8565
8566 /// An `alloca` whose size is an operand, which is a variable length array.
8567 fn growing(source: &mut Func, block: Block, size: Value, align: u32) -> Value {
8568 let info = MemInfo { size: 0, align, ..plain() };
8569 let mut build = Builder::new(source, block);
8570 let mem = build.func().add_mem(info);
8571 let args = build.func().push_values(&[size]);
8572 build.value(
8573 InstData { args, extra: Extra::Mem(mem), ..InstData::new(Opcode::Alloca) },
8574 Type::PTR,
8575 )
8576 }
8577
8578 #[test]
8579 fn a_stack_slot_whose_size_is_not_known_until_it_runs_takes_the_bytes_off_the_stack_pointer() {
8580 let (mut names, mut source, block, args) = blank(&[Type::int(64)]);
8581 let slot = growing(&mut source, block, args[0], 16);
8582 Builder::new(&mut source, block).ret(&[slot]);
8583
8584 let lowered = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
8585 .expect("every instruction has a rule");
8586
8587 // The bytes come off the stack pointer where the declaration stands and the address is
8588 // where the stack pointer then is, which is one subtraction and one `lea` rather than a
8589 // slot the frame laid out. Nothing is on the list of locals, because there is nothing
8590 // about this the frame could place.
8591 let text = mir::print_func(&lowered.func, &names, ®S);
8592 assert!(text.contains("$rsp = x64.sub_rr_64 $rsp, %0"), "{text}");
8593 assert!(text.contains("x64.lea_64 [$rsp]"), "{text}");
8594 assert!(lowered.stack.locals.is_empty(), "{text}");
8595 assert_eq!(lowered.stack.dynamic.len(), 1);
8596 assert!(lowered.stack.grown_at.is_some());
8597 }
8598
8599 #[test]
8600 fn a_growing_slot_wanting_more_alignment_than_the_stack_pointer_has_is_reported() {
8601 let (mut names, mut source, block, args) = blank(&[Type::int(64)]);
8602 let slot = growing(&mut source, block, args[0], 32);
8603 Builder::new(&mut source, block).ret(&[slot]);
8604
8605 // Thirty two is more than a call leaves the stack pointer on, so giving it what it asked
8606 // for means masking the stack pointer after moving it, and after that no constant reaches
8607 // the rest of the frame from the frame pointer either. A second pointer held for the
8608 // purpose is what fixes it and there is not one yet.
8609 let failed = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
8610 .expect_err("nothing realigns a frame that grows");
8611 assert_eq!(
8612 failed.to_string(),
8613 "this local wants more alignment than the stack pointer is left on, which needs a \
8614 base register nothing here keeps"
8615 );
8616 }
8617
8618 #[test]
8619 fn a_frame_that_grows_reaches_its_own_locals_through_the_frame_pointer() {
8620 let (mut names, mut source, block, args) = blank(&[Type::int(64)]);
8621 let fixed = slot(&mut source, block, 4, 4);
8622 let mut build = Builder::new(&mut source, block);
8623 let nine = build.iconst(Type::int(32), 9);
8624 build.store(nine, fixed, plain(), Flags::default());
8625 let grown = growing(&mut source, block, args[0], 16);
8626 Builder::new(&mut source, block).ret(&[grown]);
8627
8628 let lowered = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
8629 .expect("every instruction has a rule");
8630 let stack = lowered.stack;
8631 let mut out = lowered.func;
8632 let env = env();
8633 let allocation = rucc_regalloc::run(&mut out, &env, "test", true);
8634 let layout = stack.layout(Layout::new(&SYSV, REGS));
8635 let frame = Frame::of(&out, &allocation, &layout);
8636 finish(&mut out, &allocation, &frame, &stack, Convention::new(&SYSV, &FRAME), &mut names);
8637
8638 // The stack pointer moves in the middle of the function, so the four bytes of the fixed
8639 // local are not a constant away from it any more and the frame pointer is what reaches
8640 // them. The frame keeps one whatever the flags asked for, takes its bytes rather than
8641 // living in the red zone, and the address of the growing slot is off the stack pointer as
8642 // it stands after the subtraction rather than off anything the prologue left.
8643 let text = mir::print_func(&out, &names, ®S);
8644 assert!(frame.grows());
8645 assert!(frame.frame_pointer());
8646 assert!(frame.size() > 0, "{text}");
8647 assert!(text.contains("x64.lea_64 [$rbp"), "{text}");
8648 assert!(text.contains("$rsp = x64.sub_rr_64 $rsp"), "{text}");
8649 assert!(text.contains("x64.lea_64 [$rsp]"), "{text}");
8650 }
8651
8652 #[test]
8653 fn an_address_is_read_written_and_added_to_like_the_integer_it_is() {
8654 let (mut names, mut source, block, args) = blank(&[Type::PTR, Type::int(64)]);
8655 let mut build = Builder::new(&mut source, block);
8656 let stepped = build.func().push_values(&[args[0], args[1]]);
8657 let next =
8658 build.value(InstData { args: stepped, ..InstData::new(Opcode::PtrAdd) }, Type::PTR);
8659 let loaded = build.load(Type::int(32), next, plain(), Flags::default());
8660 build.ret(&[loaded]);
8661
8662 // `int f(int *p, long i) { return *(int *)((char *)p + i); }`. Nothing about this is new
8663 // in the rule set, which is the point: the two addresses arrive in registers because an
8664 // address is an integer as wide as one, and the arithmetic on them is the add it always
8665 // was, so every rule written about an add reaches it.
8666 //
8667 // The add stays its own instruction here rather than folding into the address the load
8668 // reads from. Two registers with no scale on either is the one addressing mode the rules
8669 // have no load through, because the folds that exist are the displacement one and the
8670 // scaled ones, and this is neither. `crate::fold` is what puts the two together, after
8671 // selection, and this is the pair it is handed.
8672 assert_eq!(
8673 lower(&mut names, &source),
8674 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_64\n \
8675 %1:gpr($rsi) = x64.arg_val_64\n %2:gpr(reuse 1) = x64.add_rr_64 %0, %1\n \
8676 %3:gpr = x64.mov_rm_32 [%2]\n x64.ret_val_32 %3($rax)\n}\n"
8677 );
8678 }
8679
8680 /// The address of a file scope name, which is what every use of a global and every string
8681 /// literal starts from.
8682 fn address_of(source: &mut Func, block: Block, names: &mut Interner, name: &str) -> Value {
8683 let symbol = names.intern(name);
8684 let mut build = Builder::new(source, block);
8685 build.value(
8686 InstData { extra: Extra::Symbol(symbol), ..InstData::new(Opcode::GlobalAddr) },
8687 Type::PTR,
8688 )
8689 }
8690
8691 #[test]
8692 fn the_address_of_a_name_is_one_instruction_carrying_the_name() {
8693 let (mut names, mut source, block, _) = blank(&[]);
8694 let counter = address_of(&mut source, block, &mut names, "counter");
8695 let mut build = Builder::new(&mut source, block);
8696 let loaded = build.load(Type::int(32), counter, plain(), Flags::default());
8697 build.ret(&[loaded]);
8698
8699 // `extern int counter; int f(void) { return counter; }`. The address is an addressing mode
8700 // that names no register and carries the symbol, which is what the assembler writes
8701 // relative to `%rip` and what the object writer leaves a relocation for.
8702 assert_eq!(
8703 lower(&mut names, &source),
8704 "mfunc @f {\nblock0:\n %0:gpr = x64.lea_64 [@counter]\n \
8705 %1:gpr = x64.mov_rm_32 [%0]\n x64.ret_val_32 %1($rax)\n}\n"
8706 );
8707 }
8708
8709 /// A local read in two arms and after them has its address written in each of the three
8710 /// blocks, and in none of them ahead of the branch. Kept in one register from the entry block,
8711 /// the address would be live across all three and the local would look carried between blocks.
8712 #[test]
8713 fn the_address_of_a_local_is_written_in_every_block_that_reads_it() {
8714 let i32 = Type::int(32);
8715 let (mut names, mut source, entry, args) = blank(&[i32, i32]);
8716 let local = slot(&mut source, entry, 4, 4);
8717 let then = source.create_block();
8718 let other = source.create_block();
8719 let join = source.create_block();
8720
8721 let mut build = Builder::new(&mut source, entry);
8722 let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
8723 build.br_if(cond, then, &[], other, &[]);
8724 let mut build = Builder::new(&mut source, then);
8725 build.store(args[0], local, plain(), Flags::default());
8726 build.jump(join, &[]);
8727 let mut build = Builder::new(&mut source, other);
8728 build.store(args[1], local, plain(), Flags::default());
8729 build.jump(join, &[]);
8730 let mut build = Builder::new(&mut source, join);
8731 let loaded = build.load(i32, local, plain(), Flags::default());
8732 build.ret(&[loaded]);
8733
8734 let lowered = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
8735 .expect("every instruction has a rule");
8736 let text = mir::print_func(&lowered.func, &names, ®S);
8737 let taken: Vec<usize> = lowered.stack.addresses.iter().map(|&(_, local)| local).collect();
8738 assert_eq!(taken, [0, 0, 0], "{text}");
8739 let (head, _) = text.split_once("block1:").expect("more than one block");
8740 assert!(!head.contains("x64.lea_64"), "{text}");
8741 }
8742
8743 /// The same for the address of a name, once in each block that reads it.
8744 #[test]
8745 fn the_address_of_a_name_is_written_in_every_block_that_reads_it() {
8746 let i32 = Type::int(32);
8747 let (mut names, mut source, entry, args) = blank(&[i32, i32]);
8748 let counter = address_of(&mut source, entry, &mut names, "counter");
8749 let then = source.create_block();
8750 let other = source.create_block();
8751 let join = source.create_block();
8752 let got = source.append_param(join, i32);
8753
8754 let mut build = Builder::new(&mut source, entry);
8755 let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
8756 build.br_if(cond, then, &[], other, &[]);
8757 let mut build = Builder::new(&mut source, then);
8758 let first = build.load(i32, counter, plain(), Flags::default());
8759 build.jump(join, &[first]);
8760 let mut build = Builder::new(&mut source, other);
8761 build.store(args[1], counter, plain(), Flags::default());
8762 let second = build.load(i32, counter, plain(), Flags::default());
8763 build.jump(join, &[second]);
8764 Builder::new(&mut source, join).ret(&[got]);
8765
8766 let text = lower(&mut names, &source);
8767 // One in each arm and not two in the second, which reads it twice.
8768 assert_eq!(text.matches("x64.lea_64 [@counter]").count(), 2, "{text}");
8769 let (head, _) = text.split_once("block1:").expect("more than one block");
8770 assert!(!head.contains("x64.lea_64"), "{text}");
8771 }
8772
8773 /// Seven strings to one call. The seventh goes to memory and its address is written in front
8774 /// of the store that passes it, and the six that go in registers are written in front of the
8775 /// call, so no more than the six are ever live at once.
8776 #[test]
8777 fn an_address_passed_to_a_call_is_written_next_to_what_passes_it() {
8778 let (mut names, mut source, block, _) = blank(&[]);
8779 let strings: Vec<Value> = (0..7)
8780 .map(|n| address_of(&mut source, block, &mut names, &format!(".LC{n}")))
8781 .collect();
8782 let sig = source.add_signature(Signature::new().with_params(&[Type::PTR; 7]));
8783 let callee = names.intern("g");
8784 Builder::new(&mut source, block).call(callee, sig, &strings);
8785 Builder::new(&mut source, block).ret(&[]);
8786
8787 let text = lower(&mut names, &source);
8788 let lines: Vec<&str> = text.lines().map(str::trim).collect();
8789 let at = |what: &str| {
8790 lines.iter().position(|line| line.contains(what)).unwrap_or_else(|| panic!("{text}"))
8791 };
8792 let store = at("x64.mov_mr_64");
8793 assert_eq!(at("[@.LC6]") + 1, store, "{text}");
8794 for n in 0..6 {
8795 assert!(at(&format!("[@.LC{n}]")) > store, "{text}");
8796 }
8797 }
8798
8799 #[test]
8800 fn the_address_of_a_name_outside_the_file_is_read_out_of_the_offset_table() {
8801 let (mut names, mut source, block, _) = blank(&[]);
8802 let away = address_of(&mut source, block, &mut names, "away");
8803 Builder::new(&mut source, block).ret(&[away]);
8804 let elsewhere: Elsewhere = [names.intern("away")].into_iter().collect();
8805
8806 // `extern void away(void); void *f(void) { return away; }`. A load and not an address
8807 // computation, because the distance from here to a name a shared library may be the one
8808 // that defines is not a number any link can work out, and the slot the linker fills in is
8809 // in this program and so is a distance it has.
8810 let out = func(&source, &mut names, &SELECTOR, &SYSV, &elsewhere)
8811 .expect("every instruction has a rule");
8812 assert_eq!(
8813 mir::print_func(&out.func, &names, ®S),
8814 "mfunc @f {\nblock0:\n %0:gpr = x64.mov_rm_64 [got @away]\n \
8815 x64.ret_val_64 %0($rax)\n}\n"
8816 );
8817 }
8818
8819 #[test]
8820 fn the_address_of_a_thread_local_is_an_offset_out_of_the_table_plus_where_this_thread_starts() {
8821 let (mut names, mut source, block, _) = blank(&[]);
8822 let own = address_of(&mut source, block, &mut names, "own");
8823 Builder::new(&mut source, block).ret(&[own]);
8824 let elsewhere = Elsewhere::default().with_threads([names.intern("own")]);
8825
8826 // `extern _Thread_local int own; void *f(void) { return &own; }`. Three instructions where
8827 // the two cases above are one, because there is no address to load or to work out: the
8828 // slot holds how far into a thread's block the variable sits, `%fs:0` is where this
8829 // thread's block starts, and the sum of the two is this thread's copy.
8830 let out = func(&source, &mut names, &SELECTOR, &SYSV, &elsewhere)
8831 .expect("every instruction has a rule");
8832 assert_eq!(
8833 mir::print_func(&out.func, &names, ®S),
8834 "mfunc @f {\nblock0:\n %0:gpr = x64.mov_rm_64 [thread @own]\n \
8835 %1:gpr = x64.mov_rm_64 [fs:0]\n %2:gpr(reuse 1) = x64.add_rr_64 %0, %1\n \
8836 x64.ret_val_64 %2($rax)\n}\n"
8837 );
8838 }
8839
8840 /// The same load with nothing added to it, which is the whole of `__builtin_thread_pointer`.
8841 #[test]
8842 fn the_start_of_this_thread_s_own_storage_is_the_one_load_and_no_arithmetic() {
8843 let (mut names, mut source, block, _) = blank(&[]);
8844 let here =
8845 Builder::new(&mut source, block).value(InstData::new(Opcode::ThreadPointer), Type::PTR);
8846 Builder::new(&mut source, block).ret(&[here]);
8847
8848 let out = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
8849 .expect("every instruction has a rule");
8850 assert_eq!(
8851 mir::print_func(&out.func, &names, ®S),
8852 "mfunc @f {\nblock0:\n %0:gpr = x64.mov_rm_64 [fs:0]\n \
8853 x64.ret_val_64 %0($rax)\n}\n"
8854 );
8855 }
8856
8857 /// One `asm` statement, with its template and its constraint list written as a program does.
8858 fn assembly(
8859 source: &mut Func,
8860 block: Block,
8861 names: &mut Interner,
8862 template: &str,
8863 constraints: &str,
8864 args: &[Value],
8865 results: &[Type],
8866 ) -> Inst {
8867 clobbering(source, block, names, template, constraints, "memory", args, results)
8868 }
8869
8870 /// The same with a clobber list of its own, for the statements that are about one.
8871 #[allow(clippy::too_many_arguments)]
8872 fn clobbering(
8873 source: &mut Func,
8874 block: Block,
8875 names: &mut Interner,
8876 template: &str,
8877 constraints: &str,
8878 clobbers: &str,
8879 args: &[Value],
8880 results: &[Type],
8881 ) -> Inst {
8882 let info = AsmInfo {
8883 template: names.intern(template),
8884 constraints: names.intern(constraints),
8885 clobbers: names.intern(clobbers),
8886 targets: rucc_ir::BlockCallList::EMPTY,
8887 };
8888 Builder::new(source, block).inline_asm(info, args, results, Flags::VOLATILE)
8889 }
8890
8891 /// What a program asking the processor what it can do writes, which is the instruction whose
8892 /// every operand is a register its text does not name.
8893 #[test]
8894 fn a_template_whose_registers_are_named_by_the_constraints_places_them_from_the_letters() {
8895 let u32 = Type::int(32);
8896 let (mut names, mut source, block, _) = blank(&[]);
8897 let zero = Builder::new(&mut source, block).iconst(u32, 0);
8898 let out = clobbering(
8899 &mut source,
8900 block,
8901 &mut names,
8902 "cpuid",
8903 "=a,a",
8904 "ebx,ecx,edx",
8905 &[zero],
8906 &[u32],
8907 );
8908 let produced = source[out].results().next().expect("one result");
8909 Builder::new(&mut source, block).ret(&[produced]);
8910
8911 // `asm ("cpuid" : "=a" (n) : "a" (0) : "ebx", "ecx", "edx")`, which is the first thing
8912 // every program that has a faster path on some machines writes. Four registers written and
8913 // two read, none of them in the template, all of them out of the description, and the two
8914 // that the letters named are the statement's own. The subleaf is a zero because the
8915 // instruction reads `ecx` and the program said nothing about what is in it. The three
8916 // clobbers are gone because `cpuid` writes those three anyway, and saying it twice is one
8917 // register with two definitions.
8918 assert_eq!(
8919 lower(&mut names, &source),
8920 "mfunc @f {\nblock0:\n %0:gpr = x64.mov_ri_32 0\n \
8921 %1:gpr = x64.mov_ri_64 0\n \
8922 %2:gpr($rax), %3:gpr($rbx), %4:gpr($rcx), %5:gpr($rdx) = x64.cpuid %0($rax), \
8923 %1($rcx)\n x64.ret_val_32 %2($rax)\n}\n"
8924 );
8925 }
8926
8927 /// An operand the program pinned, by declaring the object it comes from `register long x asm
8928 /// ("r12")`. The letter on its own leaves the allocator to pick, and a template that reads the
8929 /// register by name needs the two to be the same register, so the brace is what ties them
8930 /// together. That is the one use of a local register variable the GNU manual calls reliable,
8931 /// and it is what tcc's `tests/tcctest.c` counts on.
8932 #[test]
8933 fn an_operand_the_program_pinned_is_placed_in_the_register_it_named() {
8934 let u64 = Type::int(64);
8935 let (mut names, mut source, block, _) = blank(&[]);
8936 let out =
8937 assembly(&mut source, block, &mut names, "mov $0x4542, %r12", "=r{r12}", &[], &[u64]);
8938 let produced = source[out].results().next().expect("one result");
8939 Builder::new(&mut source, block).ret(&[produced]);
8940
8941 // The template is one instruction the table already has, so it lowers to that instruction
8942 // rather than to text nobody read, and the register it names is the statement's own output
8943 // because the brace put the output there. Without the brace the letter would have let the
8944 // allocator pick, the two `%r12` would have been different registers, and the program would
8945 // have come back with whatever was in the one it picked.
8946 assert_eq!(
8947 lower(&mut names, &source),
8948 "mfunc @f {\nblock0:\n %0:gpr($r12) = x64.mov_ri_64 17730\n \
8949 x64.ret_val_64 %0($rax)\n}\n"
8950 );
8951 }
8952
8953 /// A clobber the instruction does not write itself, which is the case the list is there for.
8954 /// It goes on as a definition of the register, in among the other definitions, because that is
8955 /// the whole of how a machine function says a register is not worth anything after this.
8956 #[test]
8957 fn a_clobber_the_instruction_does_not_write_itself_is_a_definition_of_that_register() {
8958 let (mut names, mut source, block, _) = blank(&[]);
8959 clobbering(&mut source, block, &mut names, "pause", "", "rsi,cc,memory", &[], &[]);
8960 Builder::new(&mut source, block).ret(&[]);
8961
8962 assert_eq!(lower(&mut names, &source), "mfunc @f {\nblock0:\n $rsi = x64.pause\n}\n");
8963 }
8964
8965 /// A clobber naming something this has no register for. Refused rather than dropped, since the
8966 /// list is the program saying which registers it may not leave anything in, and an entry
8967 /// nobody read is a register something may still be left in.
8968 #[test]
8969 fn a_clobber_this_has_no_register_for_is_refused() {
8970 let (mut names, mut source, block, _) = blank(&[]);
8971 clobbering(&mut source, block, &mut names, "pause", "", "zmm0", &[], &[]);
8972 Builder::new(&mut source, block).ret(&[]);
8973
8974 let failed = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
8975 .expect_err("there is no such register here");
8976 assert_eq!(
8977 failed.to_string(),
8978 "this `asm` says it destroys a register this has no name for"
8979 );
8980 }
8981
8982 #[test]
8983 fn an_asm_with_an_empty_template_and_no_operands_is_no_instructions() {
8984 let (mut names, mut source, block, _) = blank(&[]);
8985 assembly(&mut source, block, &mut names, "", "", &[], &[]);
8986 Builder::new(&mut source, block).ret(&[]);
8987
8988 // `asm volatile ("" : : : "memory")`, which is a barrier and nothing else. The barrier was
8989 // spent on the optimizer, which has finished by now, so what is left is nothing.
8990 assert_eq!(lower(&mut names, &source), "mfunc @f {\nblock0:\n}\n");
8991 }
8992
8993 #[test]
8994 fn an_output_an_input_is_tied_to_is_the_register_that_input_arrived_in() {
8995 let i32 = Type::int(32);
8996 let (mut names, mut source, block, args) = blank(&[i32]);
8997 let out = assembly(&mut source, block, &mut names, "", "=r,0", &args, &[i32]);
8998 let produced = source[out].results().next().expect("one result");
8999 Builder::new(&mut source, block).ret(&[produced]);
9000
9001 // `asm ("" : "=r" (x) : "0" (x))`, which is how a program stops the optimizer following a
9002 // value without changing it. The two share a place and the template writes nothing over
9003 // it, so the value comes back out of the register it went in.
9004 assert_eq!(
9005 lower(&mut names, &source),
9006 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_32\n \
9007 x64.ret_val_32 %0($rax)\n}\n"
9008 );
9009 }
9010
9011 #[test]
9012 fn an_output_written_plus_is_the_same_rename() {
9013 let i32 = Type::int(32);
9014 let (mut names, mut source, block, args) = blank(&[i32]);
9015 let out = assembly(&mut source, block, &mut names, "", "+r", &args, &[i32]);
9016 let produced = source[out].results().next().expect("one result");
9017 Builder::new(&mut source, block).ret(&[produced]);
9018
9019 // `asm ("" : "+r" (x))`, which says the same thing in one operand instead of two.
9020 assert_eq!(
9021 lower(&mut names, &source),
9022 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_32\n \
9023 x64.ret_val_32 %0($rax)\n}\n"
9024 );
9025 }
9026
9027 #[test]
9028 fn an_output_nothing_is_tied_to_is_a_zero() {
9029 let i32 = Type::int(32);
9030 let (mut names, mut source, block, _) = blank(&[]);
9031 let out = assembly(&mut source, block, &mut names, "", "=r", &[], &[i32]);
9032 let produced = source[out].results().next().expect("one result");
9033 Builder::new(&mut source, block).ret(&[produced]);
9034
9035 // `asm ("" : "=r" (y))`, whose answer is whatever the assembly left in the register, and
9036 // an empty template leaves nothing. A definite value rather than a register nothing wrote,
9037 // because the allocator is owed a definition before the use however little the program is.
9038 assert_eq!(
9039 lower(&mut names, &source),
9040 "mfunc @f {\nblock0:\n %0:gpr = x64.mov_ri_32 0\n x64.ret_val_32 %0($rax)\n}\n"
9041 );
9042 }
9043
9044 #[test]
9045 fn a_template_that_is_one_instruction_becomes_that_instruction() {
9046 let (mut names, mut source, block, _) = blank(&[]);
9047 assembly(&mut source, block, &mut names, "pause", "", &[], &[]);
9048 Builder::new(&mut source, block).ret(&[]);
9049
9050 // `asm volatile ("pause")`, which is what every spin lock in every allocator writes. One
9051 // instruction, no operands, and nothing between the template and the machine but the table
9052 // that already says what a `pause` is.
9053 assert_eq!(lower(&mut names, &source), "mfunc @f {\nblock0:\n x64.pause\n}\n");
9054 }
9055
9056 #[test]
9057 fn a_template_that_reads_a_segment_becomes_the_load_it_already_was() {
9058 let i64 = Type::int(64);
9059 let (mut names, mut source, block, _) = blank(&[]);
9060 let out = assembly(&mut source, block, &mut names, "movq %%fs:0, %0", "=r", &[], &[i64]);
9061 let produced = source[out].results().next().expect("one result");
9062 Builder::new(&mut source, block).ret(&[produced]);
9063
9064 // `asm ("movq %%fs:0, %0" : "=r" (tid))`, which is how a program finds the block its own
9065 // thread owns. The same instruction `crate::lower` already writes for a thread-local
9066 // variable, reached this time because a program wrote it out by hand.
9067 assert_eq!(
9068 lower(&mut names, &source),
9069 "mfunc @f {\nblock0:\n %0:gpr = x64.mov_rm_64 [fs:0]\n \
9070 x64.ret_val_64 %0($rax)\n}\n"
9071 );
9072 }
9073
9074 /// A template this cannot read is kept as its text, which is what gcc does with every template.
9075 /// Whether the text is an instruction is the assembler's question, asked when the unit is
9076 /// assembled from its listing.
9077 #[test]
9078 fn a_template_naming_an_instruction_this_machine_has_not_got_is_kept_as_text() {
9079 let (mut names, mut source, block, _) = blank(&[]);
9080 assembly(&mut source, block, &mut names, "hcf", "", &[], &[]);
9081 Builder::new(&mut source, block).ret(&[]);
9082
9083 let printed = lower(&mut names, &source);
9084 assert!(printed.contains("x64.template"), "{printed}");
9085 assert!(printed.contains("@hcf"), "{printed}");
9086 }
9087
9088 /// A template kept as text with an operand in a register reads the operand, and its text holds
9089 /// a hole naming that operand of the instruction, which the writer fills with the register the
9090 /// allocator chose. The input is the instruction's only use, behind every register a call may
9091 /// write.
9092 #[test]
9093 fn a_template_kept_as_text_reads_an_operand_in_a_register_through_a_hole() {
9094 let i32 = Type::int(32);
9095 let (mut names, mut source, block, args) = blank(&[i32]);
9096 assembly(&mut source, block, &mut names, "hcf %0", "r", &[args[0]], &[]);
9097 Builder::new(&mut source, block).ret(&[]);
9098
9099 let printed = lower(&mut names, &source);
9100 let line = printed.lines().find(|line| line.contains("x64.template")).unwrap_or_default();
9101 // Twenty five registers are written ahead of it, so the operand read is the twenty sixth,
9102 // spelled at the width of an `int`.
9103 assert!(line.contains("x64.template %0, @hcf \u{1}r25k\u{2}"), "{printed}");
9104 assert!(line.contains("early $rax"), "{printed}");
9105 }
9106
9107 /// A template kept as text with more outputs than the convention keeps registers across a call
9108 /// gets back as many of the registers a call may write as it needs, from the end of the order,
9109 /// and keeps the rest. Six outputs against five preserved registers is one handed back, which is
9110 /// `r9`. `r11` and `r10` come back ahead of it without counting, since they are the allocator's
9111 /// scratch and no operand is given one, but an output it spills is carried in one of them, which
9112 /// it cannot be while the template claims it. The shape is `sodium_sub` in libsodium, whose
9113 /// `sbbq` into memory the reader has no form for, and before this the allocator ran out of
9114 /// registers on it.
9115 #[test]
9116 fn a_template_kept_as_text_with_more_outputs_than_are_kept_gets_registers_back() {
9117 let i64 = Type::int(64);
9118 let (mut names, mut source, block, _) = blank(&[]);
9119 let outputs = [i64; 6];
9120 let asm = assembly(
9121 &mut source,
9122 block,
9123 &mut names,
9124 "hcf %0, %1, %2, %3, %4, %5",
9125 "=&r,=&r,=&r,=&r,=&r,=&r",
9126 &[],
9127 &outputs,
9128 );
9129 let produced: Vec<Value> = source[asm].results().collect();
9130 Builder::new(&mut source, block).ret(&produced[..1]);
9131
9132 let printed = lower(&mut names, &source);
9133 let line = printed.lines().find(|line| line.contains("x64.template")).unwrap_or_default();
9134 assert!(line.contains("early $r8"), "{printed}");
9135 for reg in ["r9", "r10", "r11"] {
9136 assert!(!line.contains(&format!("early ${reg}")), "{printed}");
9137 }
9138 }
9139
9140 /// A register the template named is placed as itself, fixed to the register the program wrote
9141 /// down. A register a constraint letter names is a different thing and is placed too, which the
9142 /// test above is about: there the statement said which of its own operands is in the register,
9143 /// and a name in the middle of a template says the register and nothing about any operand.
9144 #[test]
9145 fn a_template_naming_a_register_gets_that_register() {
9146 let i64 = Type::int(64);
9147 let (mut names, mut source, block, _) = blank(&[]);
9148 let out = assembly(&mut source, block, &mut names, "movq %%rax, %0", "=r", &[], &[i64]);
9149 let produced = source[out].results().next().expect("one result");
9150 Builder::new(&mut source, block).ret(&[produced]);
9151
9152 // `asm ("movq %%rax, %0" : "=r" (x))`, which is a program reading whatever is in `%rax`.
9153 // The source is the register itself and the destination is one the allocator picks.
9154 assert_eq!(
9155 lower(&mut names, &source),
9156 "mfunc @f {\nblock0:\n %0:gpr = x64.mov_rr_64 $rax($rax)\n \
9157 x64.ret_val_64 %0($rax)\n}\n"
9158 );
9159 }
9160
9161 /// The half of the same thing every register saving template needs. micropython writes the
9162 /// callee-saved registers into a buffer one `movq %%r12, 48(%%rdi)` at a time, and both halves
9163 /// of that line are a register the template named: the one being stored and the one the address
9164 /// is counted from.
9165 #[test]
9166 fn a_template_counting_an_address_from_a_register_it_named_gets_that_register() {
9167 let (mut names, mut source, block, _) = blank(&[]);
9168 assembly(&mut source, block, &mut names, "movq %%r12, 48(%%rdi)", "", &[], &[]);
9169 Builder::new(&mut source, block).ret(&[]);
9170
9171 assert_eq!(
9172 lower(&mut names, &source),
9173 "mfunc @f {\nblock0:\n x64.mov_mr_64 $r12($r12), [$rdi + 48]\n}\n"
9174 );
9175 }
9176
9177 /// A local kept in a named register, which is the same register named as itself and reached
9178 /// from the other side. micropython's collector writes six of these and reads them with
9179 /// ordinary C rather than with a template.
9180 #[test]
9181 fn a_local_kept_in_a_named_register_is_one_move_out_of_it() {
9182 let (mut names, mut source, block, _) = blank(&[]);
9183 let held = names.intern("rbx");
9184 let value = Builder::new(&mut source, block).value(
9185 InstData { extra: Extra::Symbol(held), ..InstData::new(Opcode::RegisterValue) },
9186 Type::int(64),
9187 );
9188 Builder::new(&mut source, block).ret(&[value]);
9189
9190 assert_eq!(
9191 lower(&mut names, &source),
9192 "mfunc @f {\nblock0:\n %0:gpr = x64.mov_rr_64 $rbx($rbx)\n \
9193 x64.ret_val_64 %0($rax)\n}\n"
9194 );
9195 }
9196
9197 /// The sigil gcc allows in front of the name is syntax and comes off, and a name that is not
9198 /// a register of this machine is refused in words that say which name it was.
9199 #[test]
9200 fn a_register_name_is_read_with_or_without_its_sigil_and_refused_when_there_is_no_such_one() {
9201 for written in ["%r12", "r12"] {
9202 let (mut names, mut source, block, _) = blank(&[]);
9203 let held = names.intern(written);
9204 let value = Builder::new(&mut source, block).value(
9205 InstData { extra: Extra::Symbol(held), ..InstData::new(Opcode::RegisterValue) },
9206 Type::int(64),
9207 );
9208 Builder::new(&mut source, block).ret(&[value]);
9209 assert!(lower(&mut names, &source).contains("$r12($r12)"), "{written} is not read");
9210 }
9211
9212 let (mut names, mut source, block, _) = blank(&[]);
9213 let held = names.intern("nowhere");
9214 let value = Builder::new(&mut source, block).value(
9215 InstData { extra: Extra::Symbol(held), ..InstData::new(Opcode::RegisterValue) },
9216 Type::int(64),
9217 );
9218 Builder::new(&mut source, block).ret(&[value]);
9219
9220 let failed = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
9221 .expect_err("there is no such register");
9222 assert_eq!(
9223 failed.to_string(),
9224 "this object is kept in `nowhere`, which is not a register this machine has"
9225 );
9226 }
9227
9228 #[test]
9229 fn a_constraint_list_that_does_not_describe_the_operands_is_refused() {
9230 let i32 = Type::int(32);
9231 let (mut names, mut source, block, args) = blank(&[i32]);
9232 assembly(&mut source, block, &mut names, "", "=r", &args, &[]);
9233 Builder::new(&mut source, block).ret(&[]);
9234
9235 // An output with no result to be, which is what the front end never writes and what a
9236 // hand written module can. Refused rather than placed by a guess.
9237 let failed = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
9238 .expect_err("the list and the instruction disagree");
9239 assert_eq!(failed.to_string(), "this `asm` has an operand this cannot place");
9240 }
9241
9242 /// A cast between a pointer and an integer, at whatever width the result is asked for.
9243 fn cast(source: &mut Func, block: Block, opcode: Opcode, from: Value, to: Type) -> Value {
9244 let mut build = Builder::new(source, block);
9245 let args = build.func().push_values(&[from]);
9246 build.value(InstData { args, ..InstData::new(opcode) }, to)
9247 }
9248
9249 #[test]
9250 fn a_cast_between_a_pointer_and_an_integer_as_wide_is_no_instruction_at_all() {
9251 let (mut names, mut source, block, args) = blank(&[Type::PTR]);
9252 let number = cast(&mut source, block, Opcode::PtrToInt, args[0], Type::int(64));
9253 Builder::new(&mut source, block).ret(&[number]);
9254
9255 // `long f(void *p) { return (long)p; }`. An address on this machine is an integer as wide
9256 // as the machine addresses, so the cast changes what the type system calls the value and
9257 // changes nothing about the value, and the register holding it is the one that held it.
9258 assert_eq!(
9259 lower(&mut names, &source),
9260 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_64\n \
9261 x64.ret_val_64 %0($rax)\n}\n"
9262 );
9263 }
9264
9265 #[test]
9266 fn a_null_pointer_is_a_constant_that_reaches_a_register_before_anything_reads_it() {
9267 let (mut names, mut source, block, _) = blank(&[]);
9268 let mut build = Builder::new(&mut source, block);
9269 let zero = build.iconst(Type::int(64), 0);
9270 let null = cast(&mut source, block, Opcode::IntToPtr, zero, Type::PTR);
9271 Builder::new(&mut source, block).ret(&[null]);
9272
9273 // `void *f(void) { return 0; }`. The cast is nothing, and reading its operand is what
9274 // writes the zero down: a constant is materialized where it is wanted rather than where
9275 // the IR defined it, and without the read there would be no instruction at all.
9276 assert_eq!(
9277 lower(&mut names, &source),
9278 "mfunc @f {\nblock0:\n %0:gpr = x64.mov_ri_64 0\n x64.ret_val_64 %0($rax)\n}\n"
9279 );
9280 }
9281
9282 #[test]
9283 fn the_five_linkages_the_ir_has_narrow_to_the_three_an_object_file_can_say() {
9284 let readings = [
9285 (Linkage::External, mir::Binding::Global),
9286 (Linkage::Common, mir::Binding::Global),
9287 (Linkage::Internal, mir::Binding::Local),
9288 (Linkage::Weak, mir::Binding::Weak),
9289 (Linkage::LinkOnce, mir::Binding::Weak),
9290 ];
9291 for (linkage, wanted) in readings {
9292 let (mut names, mut source, block, _) = blank(&[]);
9293 source.linkage = linkage;
9294 Builder::new(&mut source, block).ret(&[]);
9295 let out = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
9296 .expect("a return");
9297 // The narrowing is done here rather than where the object is written, because a
9298 // machine function is all the assembler and the writer are ever handed.
9299 assert_eq!(out.func.binding, wanted, "{linkage:?}");
9300 }
9301 }
9302
9303 /// The visibility makes the same trip and is not narrowed on the way, because ELF says all
9304 /// three of them.
9305 ///
9306 /// Here for the reason the linkage above is here. A machine function is the whole of what the
9307 /// assembler and the object writer are handed, so a fact about the symbol that does not get
9308 /// onto one is a fact that is gone by the time anything could write it down, and the way that
9309 /// shows up is a shared library exporting the wrong set of names with nothing said anywhere.
9310 #[test]
9311 fn the_visibility_survives_the_trip_from_the_ir_to_a_machine_function() {
9312 let readings = [
9313 (Visibility::Default, mir::Visibility::Default),
9314 (Visibility::Hidden, mir::Visibility::Hidden),
9315 (Visibility::Protected, mir::Visibility::Protected),
9316 ];
9317 for (visibility, wanted) in readings {
9318 let (mut names, mut source, block, _) = blank(&[]);
9319 source.visibility = visibility;
9320 Builder::new(&mut source, block).ret(&[]);
9321 let out = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
9322 .expect("a return");
9323 assert_eq!(out.func.visibility, wanted, "{visibility:?}");
9324 }
9325 }
9326
9327 #[test]
9328 fn a_cast_between_a_pointer_and_a_narrower_integer_is_reported() {
9329 let (mut names, mut source, block, args) = blank(&[Type::PTR]);
9330 let number = cast(&mut source, block, Opcode::PtrToInt, args[0], Type::int(32));
9331 Builder::new(&mut source, block).ret(&[number]);
9332
9333 // The front end never writes one: it casts at the address width and truncates or extends
9334 // around it, so both of those are the rules they always were. IR from somewhere else that
9335 // does write one is refused rather than compiled to a move that keeps the high half.
9336 let failed = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
9337 .expect_err("no rule narrows an address");
9338 assert_eq!(failed.to_string(), "no rule lowers a `ptrtoint` producing a `i32`");
9339 }
9340
9341 /// The type this machine has no register for.
9342 fn long_double() -> Type {
9343 Type::float(rucc_ir::Float::F80)
9344 }
9345
9346 #[test]
9347 fn a_double_widened_and_narrowed_again_goes_out_through_the_frame_and_back() {
9348 let f64 = Type::float(rucc_ir::Float::F64);
9349 let (mut names, mut source, block, args) = blank(&[f64]);
9350 let wide = cast(&mut source, block, Opcode::FPExt, args[0], long_double());
9351 let back = cast(&mut source, block, Opcode::FPTrunc, wide, f64);
9352 Builder::new(&mut source, block).ret(&[back]);
9353
9354 // `double f(double d) { long double x = d; return x; }`. The x87 reads memory and nothing
9355 // else, so the value is written to the crossing slot, loaded at the format that widens it
9356 // and put in the slot the eighty bit value lives in. Coming back is the same three the
9357 // other way. Both slots are addressed by a `lea` with nothing in it yet, which is what
9358 // every address in a frame looks like here until `finish` has the numbers.
9359 assert_eq!(
9360 lower(&mut names, &source),
9361 "mfunc @f {\nblock0:\n \
9362 %0:xmm($xmm0) = x64.arg_val_f64\n \
9363 %1:gpr = x64.lea_64 [$rsp]\n \
9364 %2:gpr = x64.lea_64 [$rsp]\n \
9365 x64.movsd_mr %0, [%1]\n \
9366 x64.fld_l [%1]\n \
9367 x64.fstp_t [%2]\n \
9368 %3:gpr = x64.lea_64 [$rsp]\n \
9369 %4:gpr = x64.lea_64 [$rsp]\n \
9370 x64.fld_t [%3]\n \
9371 x64.fstp_l [%4]\n \
9372 %5:xmm = x64.movsd_rm [%4]\n \
9373 x64.ret_val_f64 %5($xmm0)\n}\n"
9374 );
9375 }
9376
9377 #[test]
9378 fn a_long_double_has_sixteen_bytes_of_its_own_and_keeps_them() {
9379 let f64 = Type::float(rucc_ir::Float::F64);
9380 let (mut names, mut source, block, args) = blank(&[f64]);
9381 let wide = cast(&mut source, block, Opcode::FPExt, args[0], long_double());
9382 let once = cast(&mut source, block, Opcode::FPTrunc, wide, f64);
9383 let twice = cast(&mut source, block, Opcode::FPTrunc, wide, f64);
9384 let mut build = Builder::new(&mut source, block);
9385 let sum = build.binary(Opcode::FAdd, once, twice, Flags::default());
9386 build.ret(&[sum]);
9387
9388 let out = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
9389 .expect("every instruction is written");
9390
9391 // Two slots and not four: sixteen bytes for the one eighty bit value, which is what the
9392 // psABI says one takes and is aligned to, and eight for the crossing, which every group
9393 // in the function shares because nothing is ever left in it. The value's slot is its own
9394 // for the whole function, so reading it twice reads the same sixteen bytes.
9395 assert_eq!(
9396 out.stack.locals,
9397 vec![Local { size: 8, align: 8 }, Local { size: 16, align: 16 }]
9398 );
9399 }
9400
9401 #[test]
9402 fn an_integer_becomes_a_long_double_by_being_loaded_as_one() {
9403 let (mut names, mut source, block, args) = blank(&[Type::int(64)]);
9404 let wide = cast(&mut source, block, Opcode::SIToFP, args[0], long_double());
9405 let back =
9406 cast(&mut source, block, Opcode::FPTrunc, wide, Type::float(rucc_ir::Float::F64));
9407 Builder::new(&mut source, block).ret(&[back]);
9408
9409 // `double f(long n) { long double x = n; return x; }`. `fild` is the same push at another
9410 // format, so the conversion is the load and there is no instruction that converts.
9411 let text = lower(&mut names, &source);
9412 assert!(text.contains("x64.mov_mr_64 %0, [%1]"), "{text}");
9413 assert!(text.contains("x64.fild_ll [%1]"), "{text}");
9414 }
9415
9416 #[test]
9417 fn a_long_double_becoming_an_integer_cuts_towards_zero_with_the_control_word() {
9418 let (mut names, mut source, block, args) = blank(&[Type::float(rucc_ir::Float::F64)]);
9419 let wide = cast(&mut source, block, Opcode::FPExt, args[0], long_double());
9420 let whole = cast(&mut source, block, Opcode::FPToSI, wide, Type::int(32));
9421 Builder::new(&mut source, block).ret(&[whole]);
9422
9423 // The one conversion here with no single instruction behind it. C cuts towards zero and
9424 // the unit rounds the way its control word says, so the word is saved, ORed with the two
9425 // bits that mean truncate, loaded, used and put back. Nine instructions for what `fisttp`
9426 // does in one, and `spec/10-backend.md` section 10.8 says why that one is not used.
9427 let text = lower(&mut names, &source);
9428 let group: Vec<&str> = text
9429 .lines()
9430 .map(str::trim)
9431 .filter(|line| line.starts_with("x64.f") || line.contains("_16"))
9432 .collect();
9433 assert_eq!(
9434 group,
9435 [
9436 "x64.fld_l [%1]",
9437 "x64.fstp_t [%2]",
9438 "x64.fnstcw [%5]",
9439 "%6:gpr = x64.mov_rm_16 [%5]",
9440 "%7:gpr(reuse 1) = x64.or_ri_16 %6, 3072",
9441 "x64.mov_mr_16 %7, [%5 + 2]",
9442 "x64.fldcw [%5 + 2]",
9443 "x64.fld_t [%3]",
9444 "x64.fistp_l [%4]",
9445 "x64.fldcw [%5]",
9446 ],
9447 "{text}"
9448 );
9449 }
9450
9451 #[test]
9452 fn a_long_double_is_read_and_written_as_the_bits_it_already_is() {
9453 let (mut names, mut source, block, args) = blank(&[Type::PTR, Type::PTR]);
9454 let mut build = Builder::new(&mut source, block);
9455 let value = build.load(long_double(), args[0], plain(), Flags::default());
9456 build.store(value, args[1], plain(), Flags::default());
9457 build.ret(&[]);
9458
9459 // `void f(long double *a, long double *b) { *b = *a; }`. A copy is a push and a pop at the
9460 // format the value is already in, which neither converts nor looks: a signalling NaN stays
9461 // one and nothing is raised, which is the whole of what makes it a copy.
9462 let text = lower(&mut names, &source);
9463 let group: Vec<&str> =
9464 text.lines().map(str::trim).filter(|line| line.starts_with("x64.f")).collect();
9465 assert_eq!(
9466 group,
9467 ["x64.fld_t [%0]", "x64.fstp_t [%2]", "x64.fld_t [%3]", "x64.fstp_t [%1]"],
9468 "{text}"
9469 );
9470 }
9471
9472 /// Two `long double` values, from two `double` parameters, and the instructions that made
9473 /// them, which every test below this one throws away.
9474 fn two_long_doubles(source: &mut Func, block: Block, args: &[Value]) -> (Value, Value) {
9475 let left = cast(source, block, Opcode::FPExt, args[0], long_double());
9476 let right = cast(source, block, Opcode::FPExt, args[1], long_double());
9477 (left, right)
9478 }
9479
9480 /// The x87 instructions of a function, in order, with everything else dropped.
9481 fn stack_only(text: &str) -> Vec<&str> {
9482 text.lines().map(str::trim).filter(|line| line.contains("x64.f")).collect()
9483 }
9484
9485 /// The two frame slots the last two addresses of a function were taken of, which in a
9486 /// comparison are the two operands in the order they go on the stack.
9487 fn pushed(out: &Lowered) -> Vec<usize> {
9488 let taken: Vec<usize> = out.stack.addresses.iter().map(|&(_, local)| local).collect();
9489 taken[taken.len() - 2..].to_vec()
9490 }
9491
9492 #[test]
9493 fn adding_two_long_doubles_pushes_both_and_leaves_the_answer_in_a_slot() {
9494 let f64 = Type::float(rucc_ir::Float::F64);
9495 let (mut names, mut source, block, args) = blank(&[f64, f64]);
9496 let (left, right) = two_long_doubles(&mut source, block, &args);
9497 let sum =
9498 Builder::new(&mut source, block).binary(Opcode::FAdd, left, right, Flags::default());
9499 let back = cast(&mut source, block, Opcode::FPTrunc, sum, f64);
9500 Builder::new(&mut source, block).ret(&[back]);
9501
9502 // `double f(double a, double b) { return (long double) a + (long double) b; }`. The last
9503 // four lines are the add: both operands pushed, the instruction that names neither of
9504 // them because they are the top two of a stack, and the answer taken off into its slot.
9505 let text = lower(&mut names, &source);
9506 assert_eq!(
9507 stack_only(&text),
9508 [
9509 "x64.fld_l [%2]",
9510 "x64.fstp_t [%3]",
9511 "x64.fld_l [%4]",
9512 "x64.fstp_t [%5]",
9513 "x64.fld_t [%6]",
9514 "x64.fld_t [%7]",
9515 "x64.fadd_p",
9516 "x64.fstp_t [%8]",
9517 "x64.fld_t [%9]",
9518 "x64.fstp_l [%10]",
9519 ],
9520 "{text}"
9521 );
9522 }
9523
9524 #[test]
9525 fn a_subtraction_pushes_the_left_operand_first_and_asks_for_the_att_spelling() {
9526 let f64 = Type::float(rucc_ir::Float::F64);
9527 let (mut names, mut source, block, args) = blank(&[f64, f64]);
9528 let (left, right) = two_long_doubles(&mut source, block, &args);
9529 let less =
9530 Builder::new(&mut source, block).binary(Opcode::FSub, left, right, Flags::default());
9531 let back = cast(&mut source, block, Opcode::FPTrunc, less, f64);
9532 Builder::new(&mut source, block).ret(&[back]);
9533
9534 // The left one goes on first, so it ends up under the right one, and the answer wanted is
9535 // the one below minus the top. In AT&T that is `fsubrp`, since `fsubp` there is `DE E0+i`
9536 // and computes the other one. The `r` says which spelling this is and not which order the
9537 // pushes were in. `crates/rucc/tests/x87.rs` is what says the answer is right, because a
9538 // name is what got this wrong the first time.
9539 let text = lower(&mut names, &source);
9540 assert_eq!(
9541 &stack_only(&text)[4..8],
9542 ["x64.fld_t [%6]", "x64.fld_t [%7]", "x64.fsubr_p", "x64.fstp_t [%8]"],
9543 "{text}"
9544 );
9545 }
9546
9547 #[test]
9548 fn negating_a_long_double_turns_the_sign_over_and_reads_nothing() {
9549 let f64 = Type::float(rucc_ir::Float::F64);
9550 let (mut names, mut source, block, args) = blank(&[f64]);
9551 let wide = cast(&mut source, block, Opcode::FPExt, args[0], long_double());
9552 let flipped = Builder::new(&mut source, block).unary(Opcode::FNeg, wide, long_double());
9553 let back = cast(&mut source, block, Opcode::FPTrunc, flipped, f64);
9554 Builder::new(&mut source, block).ret(&[back]);
9555
9556 // `fchs` and not a subtraction from zero, which would give a different answer at a negative
9557 // zero and would signal at a NaN. It does not read the value as a number at all.
9558 let text = lower(&mut names, &source);
9559 assert_eq!(
9560 &stack_only(&text)[2..5],
9561 ["x64.fld_t [%3]", "x64.fchs", "x64.fstp_t [%4]"],
9562 "{text}"
9563 );
9564 }
9565
9566 #[test]
9567 fn comparing_two_long_doubles_puts_the_left_one_on_top() {
9568 let f64 = Type::float(rucc_ir::Float::F64);
9569 let (mut names, mut source, block, args) = blank(&[f64, f64]);
9570 let (left, right) = two_long_doubles(&mut source, block, &args);
9571 let mut build = Builder::new(&mut source, block);
9572 build.fcmp(FloatPred::Ogt, left, right, Flags::default());
9573 build.ret(&[]);
9574
9575 // `a > b`. `fucomip` asks about the top of the stack against what is under it, so the
9576 // operand the predicate is about has to go on last, which is the other way round from the
9577 // arithmetic above. The pop that clears the loser and the byte that reads the flags are
9578 // both inside the one opcode.
9579 let out = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
9580 .expect("every instruction is written");
9581 let slots = pushed(&out);
9582 assert_eq!(slots, [2, 1], "the right operand goes on first and the left one on top");
9583 let text = mir::print_func(&out.func, &names, ®S);
9584 assert_eq!(
9585 &stack_only(&text)[4..],
9586 ["x64.fld_t [%6]", "x64.fld_t [%7]", "%8:gpr = x64.fucomip_set_a"],
9587 "{text}"
9588 );
9589 }
9590
9591 #[test]
9592 fn a_comparison_that_the_machine_has_backwards_swaps_the_two_pushes() {
9593 let f64 = Type::float(rucc_ir::Float::F64);
9594 let (mut names, mut source, block, args) = blank(&[f64, f64]);
9595 let (left, right) = two_long_doubles(&mut source, block, &args);
9596 let mut build = Builder::new(&mut source, block);
9597 build.fcmp(FloatPred::Olt, left, right, Flags::default());
9598 build.ret(&[]);
9599
9600 // `a < b` is `b > a` and this machine has the one condition, so the same opcode runs with
9601 // the operands the other way round. The same trade the vector rules make, and it has to
9602 // be the same one: a `long double` comparison that picked a different condition from the
9603 // `double` comparison of the same two numbers would be wrong at exactly the unordered
9604 // cases the two conditions differ on.
9605 //
9606 // Which slot each push names is the whole of the difference from the test above, and the
9607 // text does not show it, since an address in a frame is a `lea` with nothing in it until
9608 // `finish` has the numbers. So the slots are what is read here.
9609 let out = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
9610 .expect("every instruction is written");
9611 let slots = pushed(&out);
9612 assert_eq!(slots, [1, 2], "the left operand goes on first and the right one on top");
9613 let text = mir::print_func(&out.func, &names, ®S);
9614 assert_eq!(
9615 &stack_only(&text)[4..],
9616 ["x64.fld_t [%6]", "x64.fld_t [%7]", "%8:gpr = x64.fucomip_set_a"],
9617 "{text}"
9618 );
9619 }
9620
9621 #[test]
9622 fn an_ordered_equal_needs_a_second_byte_to_put_the_two_conditions_together() {
9623 let f64 = Type::float(rucc_ir::Float::F64);
9624 let (mut names, mut source, block, args) = blank(&[f64, f64]);
9625 let (left, right) = two_long_doubles(&mut source, block, &args);
9626 let mut build = Builder::new(&mut source, block);
9627 build.fcmp(FloatPred::Oeq, left, right, Flags::default());
9628 build.ret(&[]);
9629
9630 // Equal and ordered are two conditions and the flags carry both, so the opcode writes a
9631 // second register as well as the one the value is in and ANDs them together. Said here by
9632 // handing it a spare, since an instruction that wrote a register nothing knew about would
9633 // be an instruction the allocator could put a live value in the way of.
9634 let text = lower(&mut names, &source);
9635 assert!(text.contains("%8:gpr, %9:gpr = x64.fucomip_set_e_and_np"), "{text}");
9636 }
9637
9638 #[test]
9639 fn a_comparison_that_is_never_asked_is_reported() {
9640 let f64 = Type::float(rucc_ir::Float::F64);
9641 let (mut names, mut source, block, args) = blank(&[f64, f64]);
9642 let (left, right) = two_long_doubles(&mut source, block, &args);
9643 let mut build = Builder::new(&mut source, block);
9644 build.fcmp(FloatPred::False, left, right, Flags::default());
9645 build.ret(&[]);
9646
9647 // Always false is a constant and not a comparison, so there is no condition to pick and
9648 // nothing here folds it into one: an instruction that quietly agreed with it would hide
9649 // that the optimizer left a comparison in that it should have taken out.
9650 let failed = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
9651 .expect_err("no condition is always false");
9652 assert_eq!(failed.to_string(), "no rule lowers a `fcmp` producing a `i1`");
9653 }
9654
9655 #[test]
9656 fn a_long_double_constant_is_the_bits_of_it_put_where_the_value_lives() {
9657 let (mut names, mut source, block, args) = blank(&[Type::PTR]);
9658 let mut build = Builder::new(&mut source, block);
9659 // `1.5L`, which is the leading bit and one more of significand, and an exponent of zero.
9660 let one_and_a_half = build.fconst(long_double(), 0x3fff_c000_0000_0000_0000);
9661 build.store(one_and_a_half, args[0], plain(), Flags::default());
9662 build.ret(&[]);
9663
9664 // No x87 instruction at all. A slot holding one of these is the value, so a constant is
9665 // its ten bytes written where the value lives, and whatever reads it does the `fld`.
9666 let text = lower(&mut names, &source);
9667 assert!(text.contains("x64.mov_ri_64 -4611686018427387904"), "{text}");
9668 assert!(text.contains("x64.mov_ri_16 16383"), "{text}");
9669 assert!(text.contains("x64.mov_mr_16 %3, [%1 + 8]"), "{text}");
9670 // The six bytes above the ten are the padding that makes the type sixteen wide, and they
9671 // are unspecified rather than zero, so nothing writes them.
9672 assert_eq!(text.matches("x64.mov_mr").count(), 2, "{text}");
9673 }
9674
9675 #[test]
9676 fn a_negative_long_double_constant_keeps_the_bit_above_its_exponent() {
9677 let (mut names, mut source, block, args) = blank(&[Type::PTR]);
9678 let mut build = Builder::new(&mut source, block);
9679 let minus = build.fconst(long_double(), 0xbfff_c000_0000_0000_0000);
9680 build.store(minus, args[0], plain(), Flags::default());
9681 build.ret(&[]);
9682
9683 // `-1.5L`. The sign is the top bit of the two byte half, so the immediate that half is put
9684 // in a register with is above the signed range of sixteen bits and has to stay there: read
9685 // as a number it would be negative, and it is not a number, it is two bytes.
9686 let text = lower(&mut names, &source);
9687 assert!(text.contains("x64.mov_ri_16 49151"), "{text}");
9688 }
9689
9690 #[test]
9691 fn a_long_double_crosses_an_edge_as_an_address_and_is_copied_where_it_lands() {
9692 let (mut names, mut source, block, args) = blank(&[Type::float(rucc_ir::Float::F64)]);
9693 let wide = cast(&mut source, block, Opcode::FPExt, args[0], long_double());
9694 let next = source.create_block();
9695 let param = source.append_param(next, long_double());
9696 Builder::new(&mut source, block).jump(next, &[wide]);
9697 Builder::new(&mut source, next).ret(&[param]);
9698
9699 // What the edge carries is the address of the slot the value is already in, which is an
9700 // ordinary register the allocator has an opinion about. The block on the other side copies
9701 // the sixteen bytes into a slot of its own before anything reads them, so a second edge
9702 // handing over a second address would still leave one place for a reader to look.
9703 let text = lower(&mut names, &source);
9704 let second: Vec<&str> = text
9705 .lines()
9706 .skip_while(|line| !line.starts_with("block1"))
9707 .skip(1)
9708 .take(3)
9709 .map(str::trim)
9710 .collect();
9711 assert_eq!(
9712 second,
9713 ["x64.fld_t [%4]", "%5:gpr = x64.lea_64 [$rsp]", "x64.fstp_t [%5]"],
9714 "{text}"
9715 );
9716 }
9717
9718 #[test]
9719 fn more_long_doubles_at_a_block_than_the_stack_is_deep_are_reported() {
9720 let f64 = Type::float(rucc_ir::Float::F64);
9721 let (mut names, mut source, block, args) = blank(&[f64]);
9722 let wide = cast(&mut source, block, Opcode::FPExt, args[0], long_double());
9723 let next = source.create_block();
9724 let params: Vec<Value> =
9725 (0..=X87_DEPTH).map(|_| source.append_param(next, long_double())).collect();
9726 let carried: Vec<Value> = params.iter().map(|_| wide).collect();
9727 Builder::new(&mut source, block).jump(next, &carried);
9728 Builder::new(&mut source, next).ret(&[params[0]]);
9729
9730 // The copies go through the x87 stack so that every one of them is read before any of them
9731 // is written, which is what makes a block that swaps two of these right. Nine of them do
9732 // not fit on the stack, and copying the ninth before or after the rest is the order that
9733 // could be wrong, so it is refused instead.
9734 let failed = func(&source, &mut names, &SELECTOR, &SYSV, &Elsewhere::default())
9735 .expect_err("nine do not fit on the stack");
9736 assert_eq!(
9737 failed.to_string(),
9738 "block1 takes 9 parameters of type `f80` and only 8 can cross an edge at once"
9739 );
9740 assert_eq!(failed.inst(), None);
9741 }
9742}