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::Interner;
81use rucc_ir::{Abi, Block, Def, Extra, Func, Inst, MemOrder, Opcode, Param, Type, Value};
82use rucc_mir as mir;
83use rucc_target::x86_64;
84use rucc_target::{CallRegs, RegClass};
85
86use crate::abi::{self, Missing, Refused};
87use crate::coverage::Fired;
88use crate::frame::{Layout, Local};
89use crate::select::{Match, Piece, Rule, Table};
90use crate::term::{MAX_ARGS, PLAIN, Plan, Shown, Term, Terms};
91use crate::varargs;
92
93/// The prefix a rule file puts in front of a machine term, which says which target it belongs
94/// to and is not part of the opcode.
95pub(crate) const PREFIX: &str = "x64.";
96
97/// How wide an address is on this target, which is the width a cast between a pointer and an
98/// integer has to be at for the cast to be nothing.
99const ADDRESS_BITS: u32 = 64;
100
101/// Why a function could not be lowered.
102///
103/// One reason and then nothing. A function with no rule for something in it is a function this
104/// cannot finish, and the second thing it could not lower is not news.
105#[derive(Debug, Clone, PartialEq, Eq)]
106pub enum Unsupported {
107 /// An instruction no rule fires on.
108 Inst {
109 /// The instruction that stopped it.
110 inst: Inst,
111 /// What the rule file would call it, or nothing if the rule language has no name for it
112 /// at all, which is what an instruction at a width nothing is written about looks like.
113 term: Option<&'static str>,
114 /// The opcode, which is what gets named when the rule language has no word for it.
115 ///
116 /// An opcode the rule language has no word for is exactly the opcode no rule lowers, so
117 /// without this the message would be empty in every case where somebody needs it.
118 opcode: Opcode,
119 /// What it produces, or nothing for an instruction that is only an effect.
120 ty: Option<Type>,
121 },
122 /// A parameter that does not arrive somewhere this can bring it in from.
123 ///
124 /// Not an instruction, which is why it is a separate arm: it is a fact about the signature
125 /// and there is nothing in the body of the function to point at.
126 Argument {
127 /// Its position in the signature.
128 index: usize,
129 /// What is wrong with where it arrives.
130 missing: Missing,
131 },
132 /// A call that passes or gives back a value this cannot put where the convention wants it.
133 Call {
134 /// The call.
135 inst: Inst,
136 /// Which value, and what is wrong with where it travels.
137 refused: Refused,
138 },
139 /// A `return` this cannot put where the convention wants it.
140 ///
141 /// A separate arm from [`Unsupported::Inst`] because it is not an instruction no rule fires
142 /// on. A return of more than one value is built from the convention rather than matched, the
143 /// same way a call is, so what goes wrong with one is what goes wrong with a call and not the
144 /// absence of a rule.
145 Returned {
146 /// The `return`.
147 inst: Inst,
148 /// What is wrong with where one of the values travels.
149 missing: Missing,
150 },
151 /// A stack slot whose size is not known until the function runs, which is what a variable
152 /// length array is.
153 ///
154 /// Not an instruction no rule covers. Growing the stack where the declaration stands is
155 /// arithmetic on the stack pointer, and everything else in the frame then has to be reached
156 /// through a frame pointer instead, and neither of those is a term a rule could be written
157 /// about or a thing the frame here knows how to lay out.
158 Dynamic {
159 /// The `alloca`.
160 inst: Inst,
161 },
162}
163
164impl Unsupported {
165 /// The instruction it is about, or nothing for the one arm that is about a signature.
166 ///
167 /// What a caller wants this for is the span. The function knows where every instruction in
168 /// it came from, so a caller holding both can point a message at the line somebody wrote
169 /// rather than at the file as a whole, and nothing here has to carry a span of its own.
170 pub fn inst(&self) -> Option<Inst> {
171 match *self {
172 Unsupported::Inst { inst, .. }
173 | Unsupported::Call { inst, .. }
174 | Unsupported::Returned { inst, .. }
175 | Unsupported::Dynamic { inst, .. } => Some(inst),
176 Unsupported::Argument { .. } => None,
177 }
178 }
179}
180
181impl fmt::Display for Unsupported {
182 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
183 match *self {
184 Unsupported::Inst { term: Some(term), .. } => write!(f, "no rule lowers `{term}`"),
185 Unsupported::Inst { term: None, opcode, ty: Some(ty), .. } => {
186 write!(f, "no rule lowers a `{opcode}` producing a `{ty}`")
187 }
188 Unsupported::Inst { term: None, opcode, ty: None, .. } => {
189 write!(f, "no rule lowers a `{opcode}`")
190 }
191 Unsupported::Argument { index, missing } => {
192 write!(f, "parameter {index} {}", missing.why())
193 }
194 Unsupported::Call { refused: Refused { argument: Some(index), missing }, .. } => {
195 write!(f, "argument {index} of this call {}", missing.why())
196 }
197 Unsupported::Call { refused: Refused { argument: None, missing }, .. } => {
198 write!(f, "what this call gives back {}", missing.why())
199 }
200 Unsupported::Returned { missing, .. } => {
201 write!(f, "what this function gives back {}", missing.why())
202 }
203 Unsupported::Dynamic { .. } => {
204 f.write_str("nothing here grows the stack for a variable length array")
205 }
206 }
207 }
208}
209
210impl std::error::Error for Unsupported {}
211
212/// A lowered function, and what the frame needs that the machine IR does not hold.
213#[derive(Debug)]
214pub struct Lowered {
215 /// The function, in machine instructions.
216 pub func: mir::Func,
217 /// What it wants its stack to look like, which is separate from the function so that the two
218 /// can be read and written at the same time.
219 pub stack: Stack,
220 /// Which rules of the table lowered it, which is what `-Zrule-coverage` asks for and what
221 /// `crate::coverage` writes down.
222 pub fired: Fired,
223}
224
225/// What a function's stack has to hold, as far as selection is able to say.
226///
227/// All of it is answered here because selection is where a call is built and where an `alloca`
228/// is read, and nothing after it could tell what either of them needed.
229#[derive(Debug, Default)]
230pub struct Stack {
231 /// How many bytes the widest call in the function needs below the stack pointer for the
232 /// arguments it passes there, or `None` for a function that makes no call at all.
233 ///
234 /// `None` is a leaf, which is the function that may use the red zone and the one whose stack
235 /// pointer does not have to be left aligned for anybody.
236 pub calls: Option<u32>,
237 /// The memory the function asked for itself, one entry for every `alloca` in it, in the order
238 /// the walk reached them.
239 pub locals: Vec<Local>,
240 /// Which instruction computes the address of which of those locals.
241 ///
242 /// An address in the frame is a distance from the stack pointer, and there is no frame until
243 /// after allocation, so the instruction is written here with nothing in its displacement and
244 /// [`crate::finish`] writes the number in once [`crate::frame::Frame`] knows it.
245 pub addresses: Vec<(mir::Inst, usize)>,
246 /// Which instruction reads which of the arguments the caller passed on the stack, as how far up
247 /// the caller's argument area it reads.
248 ///
249 /// Waiting on [`crate::finish`] for the same reason the addresses above are, and on one thing
250 /// more: where the caller's argument area is from inside this function depends on whether the
251 /// prologue had to force the stack pointer's alignment, so which register the load reads
252 /// through is not settled here either.
253 pub arguments: Vec<(mir::Inst, u32)>,
254}
255
256impl Stack {
257 /// The layout given, with the three fields only the lowering knows the answer to filled in.
258 ///
259 /// Everything else in a layout comes from the flags the function is compiled under or from the
260 /// allocation, so this takes one and returns it rather than building one.
261 #[must_use]
262 pub fn layout<'a>(&'a self, base: Layout<'a>) -> Layout<'a> {
263 Layout {
264 leaf: self.calls.is_none(),
265 outgoing: self.calls.unwrap_or(0),
266 locals: &self.locals,
267 ..base
268 }
269 }
270}
271
272/// The x86-64 machine IR for that function.
273///
274/// # Errors
275///
276/// The first instruction no rule fires on, which today is anything at a width the rule set is not
277/// written at, a parameter that does not arrive in a register this can read, or a call that
278/// passes something this cannot put where the convention wants it.
279pub fn func(
280 source: &Func,
281 names: &mut Interner,
282 conv: &'static CallRegs,
283) -> Result<Lowered, Unsupported> {
284 Lowering::new(source, names, conv).run()
285}
286
287/// One function being lowered.
288struct Lowering<'a> {
289 source: &'a Func,
290 names: &'a mut Interner,
291 out: mir::Func,
292 /// The machine register each IR value is in, once it has one.
293 regs: Vec<Option<mir::Reg>>,
294 /// For a constant that has been written into a register, the block it was written into,
295 /// which is the only block that register is any good in.
296 written: Vec<Option<mir::Block>>,
297 /// How many times each IR value is read, which is what says whether an instruction may be
298 /// folded into the one that reads it.
299 uses: Vec<u32>,
300 /// The block being filled.
301 at: Option<mir::Block>,
302 /// The machine IR block each IR block became.
303 blocks: Vec<Option<mir::Block>>,
304 /// The class an address is in, which is the general purpose one and is not a question: every
305 /// register an addressing mode names holds part of an address, and there is no machine here
306 /// that computes an address anywhere but in this file. Which class a *value* is in is
307 /// [`Lowering::class_of`], and it is a question, because a float is in the other one.
308 gpr: RegClass,
309 /// Where the convention this function is compiled for puts things, which is read for the
310 /// arguments and for the calls.
311 conv: &'static CallRegs,
312 /// What the function wants its stack to look like, filled in as the walk finds out.
313 stack: Stack,
314 /// What a `va_start` in this function has to write, or nothing for a function that takes no
315 /// arguments its signature does not name.
316 ///
317 /// Worked out once, when the entry block binds the parameters, because every number in it is
318 /// about where those parameters left the walk over the argument registers and there is nowhere
319 /// else that knows.
320 varargs: Option<Varargs>,
321 /// Which rules have fired so far.
322 fired: Fired,
323}
324
325/// What a `va_start` in a variadic function writes into the list it is given.
326///
327/// Three of the four are settled here and the fourth is not a number at all yet: where the save
328/// area is and where the caller's argument area is are both distances into a frame that does not
329/// exist until after allocation, so both are `lea` instructions [`crate::finish`] fills in.
330#[derive(Debug, Clone, Copy, PartialEq, Eq)]
331struct Varargs {
332 /// Which of the function's stack objects is the register save area.
333 save: usize,
334 /// How far up the caller's argument area the first argument the signature does not name is,
335 /// which is the whole of that area the named ones did not take.
336 incoming: u32,
337 /// What `gp_offset` starts at, which is past the general purpose registers the named arguments
338 /// took.
339 integers: u32,
340 /// What `fp_offset` starts at, which is past the vector ones.
341 floats: u32,
342}
343
344impl<'a> Lowering<'a> {
345 fn new(source: &'a Func, names: &'a mut Interner, conv: &'static CallRegs) -> Self {
346 let counts = source.counts();
347 let name = source.name;
348 let mut uses = vec![0; counts.values];
349 for block in source.blocks() {
350 for inst in source.insts(block) {
351 for &arg in &source[source[inst].args] {
352 uses[arg.index()] += 1;
353 }
354 for call in source.successors(inst) {
355 for &arg in &source[call.args] {
356 uses[arg.index()] += 1;
357 }
358 }
359 }
360 }
361 let mut out = mir::Func::new(name);
362 out.align = source.align;
363 Self {
364 source,
365 names,
366 out,
367 regs: vec![None; counts.values],
368 written: vec![None; counts.values],
369 blocks: vec![None; counts.blocks],
370 uses,
371 at: None,
372 gpr: x86_64::GPR,
373 conv,
374 stack: Stack::default(),
375 varargs: None,
376 fired: Fired::new(),
377 }
378 }
379
380 fn run(mut self) -> Result<Lowered, Unsupported> {
381 // Every block before any of them is filled, because a block that jumps forward has to
382 // name the block it jumps to and a machine IR block is named by a handle rather than by
383 // the IR block it came from.
384 for block in self.source.blocks() {
385 let out = self.out.create_block();
386 self.blocks[block.index()] = Some(out);
387 }
388 for block in self.source.blocks() {
389 self.block(block)?;
390 }
391 Ok(Lowered { func: self.out, stack: self.stack, fired: self.fired })
392 }
393
394 /// One block: its parameters, then every instruction in it that is not folded into another.
395 fn block(&mut self, block: Block) -> Result<(), Unsupported> {
396 let out = self.out_block(block);
397 self.at = Some(out);
398 if self.source.entry() == Some(block) {
399 self.arrive(block, out)?;
400 } else {
401 for ¶m in self.source[block].params.iter() {
402 let reg = self.out.append_param(out, self.class_of(self.source[param].ty));
403 self.regs[param.index()] = Some(reg);
404 }
405 }
406
407 // What each instruction matched, and which instructions were folded into another. The
408 // instruction that is folded comes before the one that folds it, so the decision has to
409 // be made for the whole block before any of it is written, and it is made backwards: an
410 // instruction that has been folded into a later one does not get to fold anything into
411 // itself, because the rule that took it only reached one level down.
412 let insts: Vec<Inst> = self.source.insts(block).collect();
413 let mut found: Vec<Option<Match<Term>>> = (0..insts.len()).map(|_| None).collect();
414 let mut folded: Vec<Inst> = Vec::new();
415 for (index, &inst) in insts.iter().enumerate().rev() {
416 if folded.contains(&inst) {
417 continue;
418 }
419 if let Some((plan, matched)) = self.select(inst) {
420 folded.extend(self.folds(inst, plan));
421 found[index] = Some(matched);
422 }
423 }
424
425 for (&inst, matched) in insts.iter().zip(found) {
426 if folded.contains(&inst) || self.writes_nothing(inst) {
427 continue;
428 }
429 // A call is built from the convention rather than matched, which is why it is the one
430 // opcode looked at by name here. Through an address it is a different instruction and
431 // the same convention, so the two arrive at the same place and differ in one line of
432 // it.
433 match self.source[inst].opcode {
434 Opcode::Call | Opcode::CallIndirect => {
435 self.called(inst)?;
436 continue;
437 }
438 // Built from the frame rather than matched, for the same shape of reason a call
439 // is built from the convention: what a rule replaces a term with is instructions,
440 // and what an `alloca` needs first is bytes, which the rule language has no way
441 // to ask for.
442 Opcode::Alloca => {
443 self.reserve(inst)?;
444 continue;
445 }
446 // The address of a name, built here for the same reason an `alloca` is: what a
447 // rule replaces a term with is instructions over values, and the operand of this
448 // one is a symbol, which is a thing the rule language has no way to bind and the
449 // solver has no way to say anything about. There is nothing in `lea sym(%rip)` a
450 // proof over bitvectors could discharge, because what makes it the right answer
451 // is the relocation and what the linker does with it.
452 Opcode::GlobalAddr => {
453 self.address_of(inst)?;
454 continue;
455 }
456 // Built from the frame for the reason an `alloca` is, and from the convention for
457 // the reason a call is: three of the four fields it writes are distances that do
458 // not exist until the frame does, and the fourth is where the walk over the
459 // argument registers stopped. A function that is not variadic has no such walk to
460 // report, so it has nothing here and is refused below, which is the right answer
461 // for a `va_start` in one.
462 Opcode::VaStart if self.varargs.is_some() => {
463 self.va_start(inst)?;
464 continue;
465 }
466 // A return of more than one value, which is a structure small enough to come
467 // back in a pair of registers. Built from the convention for the reason a call
468 // is: which register each half goes in depends on the halves in front of it,
469 // because the two register files are walked separately, and a pattern over a term
470 // cannot see them. A return of one value is a term with a name and a rule, and it
471 // stays one.
472 //
473 // A return of none in a function whose answer went through memory is here too,
474 // and for a different reason: what it gives back is not written in the IR at all.
475 // The convention says the address the caller handed over comes back, and only the
476 // signature says this function was handed one.
477 Opcode::Return
478 if self.source[self.source[inst].args].len() > 1 || self.sret().is_some() =>
479 {
480 self.returned(inst)?;
481 continue;
482 }
483 // A cast between a pointer and an integer of the same width, which on this
484 // machine is every one the front end writes. No instruction at all, so no rule
485 // could name one.
486 Opcode::PtrToInt | Opcode::IntToPtr => {
487 self.rename(inst)?;
488 continue;
489 }
490 // A barrier, which is one instruction or none depending on the ordering. Written
491 // by name because there is nothing about it a rule could be proved against, the
492 // way there is nothing to prove about the address of a symbol.
493 Opcode::Fence => {
494 self.barrier(inst)?;
495 continue;
496 }
497 _ => {}
498 }
499 let matched = matched.ok_or_else(|| self.unsupported(inst))?;
500 self.emit(inst, &matched)?;
501 // After it is built rather than when it matched, so that what is recorded is the rules
502 // this function was lowered by and not the rules something was tried with.
503 self.fired.mark(matched.rule);
504 }
505 self.edges(block, out)
506 }
507
508 /// One call, which is built from the convention rather than matched against the table for the
509 /// same reason the arguments of the function itself are.
510 ///
511 /// The arguments are read before the call is built, which is what materializes a constant
512 /// argument into a register, since no call passes an immediate.
513 ///
514 /// A call to a name and a call through an address are both here, and what tells them apart is
515 /// the opcode rather than whether a callee was recorded, which is the same thing the verifier
516 /// reads. Through an address the first operand is the address and the arguments are the ones
517 /// behind it, and everything after that is the same: where each argument goes, where the value
518 /// comes back and which registers are gone across it are the convention's answers and the
519 /// convention does not ask what is being called.
520 fn called(&mut self, inst: Inst) -> Result<(), Unsupported> {
521 let data = &self.source[inst];
522 let Extra::Call(info) = data.extra else { return Err(self.unsupported(inst)) };
523 let info = self.source[info];
524 let indirect = data.opcode == Opcode::CallIndirect;
525
526 let values: Vec<Value> = self.source[data.args].to_vec();
527 let callee = if indirect {
528 let &address = values.first().ok_or_else(|| self.unsupported(inst))?;
529 abi::Callee::Through(self.reg_of(address)?)
530 } else {
531 abi::Callee::Named(info.callee.ok_or_else(|| self.unsupported(inst))?)
532 };
533
534 // What the ABI asks of each argument, read out before any of them is, because reading one
535 // borrows the function this is a table in. The ones the signature names are the signature's
536 // answer and the ones behind them are the call's, which is where a structure passed to a
537 // variadic callee by value says that its bytes travel: there is no parameter to say it on.
538 let signature = &self.source[info.signature];
539 let variadic = signature.variadic;
540 let named: Vec<Abi> = signature.params.iter().map(|param| param.abi).collect();
541 let beyond: Vec<Abi> = self.source[info.varargs].to_vec();
542 // Every value that comes back and not only the first. A structure small enough to travel
543 // in registers comes back in up to two of them, and which register each half is in is the
544 // convention's answer, which is why the whole list goes to the same place the arguments do
545 // rather than to a rule.
546 let returns: Vec<Type> = signature.return_types().collect();
547
548 let mut args = Vec::with_capacity(values.len());
549 for (index, value) in values.into_iter().skip(usize::from(indirect)).enumerate() {
550 let abi = named.get(index).or_else(|| beyond.get(index - named.len()));
551 let abi = abi.copied().unwrap_or_default();
552 args.push(abi::Passing { ty: self.source[value].ty, reg: self.reg_of(value)?, abi });
553 }
554 let block = self.at.expect("a block is being filled");
555 let what = abi::Calling { callee, args: &args, returns: &returns, variadic };
556 let made = abi::call(&mut self.out, block, &what, self.conv, self.names)
557 .map_err(|refused| Unsupported::Call { inst, refused })?;
558 let calls = &mut self.stack.calls;
559 *calls = Some(calls.unwrap_or(0).max(made.outgoing));
560 for (result, ®) in self.source[inst].results().zip(&made.results) {
561 self.regs[result.index()] = Some(reg);
562 }
563 Ok(())
564 }
565
566 /// The pointer a function returning through memory was handed, or nothing in a function that
567 /// was not.
568 ///
569 /// It is the first parameter and the signature is what says so, since in the IR it is an
570 /// ordinary pointer and reads like one everywhere in the body. A function with a signature
571 /// like that and no entry block has nothing to give back and no body to give it back from.
572 fn sret(&self) -> Option<Value> {
573 let first = self.source.signature().params.first()?;
574 if !matches!(first.abi, Abi::Sret { .. }) {
575 return None;
576 }
577 self.source[self.source.entry()?].params.first().copied()
578 }
579
580 /// One `return` the convention has to write, as the place each value has to be in by the end.
581 ///
582 /// One pseudo per value, each a read constrained to a return register, which is what a return
583 /// of one value already is and is the whole of what either does. The `ret` itself comes from
584 /// the epilogue for both, long after this, because the frame has to be given back first.
585 ///
586 /// The two register files are counted separately, so a structure of a `double` and a `long`
587 /// leaves the `double` in the first vector register and the `long` in the first integer one
588 /// rather than in the second of either. That is the same walk `rucc_codegen::abi` makes on
589 /// the other side of the call, which is what makes the two ends agree.
590 ///
591 /// A function whose answer went through memory gives back the address it was handed, in front
592 /// of nothing else, because a signature that returns that way returns nothing else. That the
593 /// caller already knows the address is not enough: it is allowed to read the register instead,
594 /// and a caller that does gets whatever the allocator last left there. In a leaf function that
595 /// is usually the right answer by accident, and one call in the body is enough to make it a
596 /// wild pointer, which is why this is written rather than left to luck.
597 ///
598 /// Where everything goes is worked out before anything is written, so a return this cannot
599 /// make leaves no half of one behind.
600 fn returned(&mut self, inst: Inst) -> Result<(), Unsupported> {
601 let values: Vec<Value> = self.source[self.source[inst].args].to_vec();
602 let (mut ints, mut floats) = (0usize, 0usize);
603 let mut parts = Vec::with_capacity(values.len() + 1);
604 for value in self.sret().into_iter().chain(values) {
605 let ty = self.source[value].ty;
606 let at = if crate::term::float_slot(ty).is_some() { &mut floats } else { &mut ints };
607 // Why it cannot come back, and not only that it cannot. A type that travels nowhere
608 // says so itself, and a type that travels perfectly well ran out of registers.
609 let missing = abi::refuses(ty).unwrap_or(Missing::NoRoom);
610 let name = abi::ret_of(ty, *at).ok_or(Unsupported::Returned { inst, missing })?;
611 *at += 1;
612 // The register is the target's answer and not one worked out here, the same as it is
613 // for a return of one value, so that both halves of a pair and every rule that writes
614 // half of one are reading the same table.
615 let opcode = name.strip_prefix(PREFIX).expect("a machine instruction of this target");
616 let form = x86_64::form(opcode).ok_or_else(|| self.unsupported(inst))?;
617 let [desc] = form.operands() else { return Err(self.unsupported(inst)) };
618 parts.push((self.names.intern(name), self.reg_of(value)?, *desc));
619 }
620
621 let block = self.at.expect("a block is being filled");
622 let span = self.source.span(inst);
623 for (opcode, reg, desc) in parts {
624 let operand = mir::Operand {
625 reg,
626 class: desc.class,
627 role: desc.role,
628 constraint: desc.constraint,
629 };
630 self.out.build(block, mir::Opcode::new(opcode)).at(span).operand(operand).finish();
631 }
632 Ok(())
633 }
634
635 /// One `alloca`: the bytes it asks for go on the list the frame is laid out from, and the
636 /// address of them is one instruction.
637 ///
638 /// The instruction is a `lea` off the stack pointer, which is the one register that reaches
639 /// the frame in every function, and its displacement is left at nothing because there is no
640 /// frame yet. Which instruction is waiting for which local is remembered, and
641 /// [`crate::finish`] fills the numbers in after [`crate::frame::Frame`] has placed them.
642 ///
643 /// There is deliberately no rule for `alloca` and no name for one in [`crate::term`], and
644 /// that is what stops it being folded into something else. An operand shown as the
645 /// instruction that computed it is offered to the matcher by its name, so an `alloca` with no
646 /// name is one no pattern can reach past, and the address it computes is always in a register
647 /// by the time anything reads it.
648 fn reserve(&mut self, inst: Inst) -> Result<(), Unsupported> {
649 let data = &self.source[inst];
650 // A variable length array carries the size it wants as an operand rather than in the
651 // instruction, which is the whole of what tells the two apart here.
652 if !self.source[data.args].is_empty() {
653 return Err(Unsupported::Dynamic { inst });
654 }
655 let Extra::Mem(mem) = data.extra else { return Err(self.unsupported(inst)) };
656 let info = self.source[mem];
657 let size = u32::try_from(info.size).map_err(|_| Unsupported::Dynamic { inst })?;
658 let result = data.first_result.ok_or_else(|| self.unsupported(inst))?;
659
660 // At least one, because the frame divides by the alignment and an object with no
661 // alignment at all is one the front end had nothing to say about rather than one that may
662 // go anywhere.
663 let index = self.stack.locals.len();
664 self.stack.locals.push(Local { size, align: info.align.max(1) });
665
666 let block = self.at.expect("a block is being filled");
667 let reg = self.new_reg(result);
668 let span = self.source.span(inst);
669 let lea = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{}", x86_64::FRAME.lea)));
670 let sp = mir::Operand::read(mir::Reg::physical(self.conv.stack_pointer), self.gpr);
671 let made =
672 self.out.build(block, lea).at(span).def(reg, self.gpr).mem(mir::Mem::at(sp)).finish();
673 self.stack.addresses.push((made, index));
674 Ok(())
675 }
676
677 /// One `va_start`, as the four fields of the list it was handed.
678 ///
679 /// Two of them are numbers this already knows, and each costs an instruction to put in a
680 /// register before it can be stored, because the machine here has no store of an immediate to
681 /// memory. The other two are addresses in the frame, and each is a `lea` [`crate::finish`]
682 /// finishes: the save area is one of the function's own stack objects, and the caller's
683 /// argument area is where the parameters that had no register came from, which is the same
684 /// place and the same fixup a parameter past the sixth already uses.
685 ///
686 /// What is written is exactly the four fields [`crate::varargs`] describes, in the order they
687 /// are laid out, so that reading this beside that table is the whole of the check.
688 fn va_start(&mut self, inst: Inst) -> Result<(), Unsupported> {
689 let Some(&list) = self.source[self.source[inst].args].first() else {
690 return Err(self.unsupported(inst));
691 };
692 let started = self.varargs.ok_or_else(|| self.unsupported(inst))?;
693 let list = self.reg_of(list)?;
694 let block = self.at.expect("a block is being filled");
695 let span = self.source.span(inst);
696
697 for (at, count) in
698 [(varargs::GP_OFFSET, started.integers), (varargs::FP_OFFSET, started.floats)]
699 {
700 let held = self.out.new_vreg(self.gpr);
701 let load = mir::Opcode::new(self.names.intern("x64.mov_ri_32"));
702 self.out.build(block, load).at(span).def(held, self.gpr).imm(i64::from(count)).finish();
703
704 let store = mir::Opcode::new(self.names.intern("x64.mov_mr_32"));
705 let mem = self.field(list, at);
706 self.out.build(block, store).at(span).uses(held, self.gpr).mem(mem).finish();
707 }
708
709 // The first argument the signature did not name, which is as far up the caller's argument
710 // area as the ones it did name reached. Nothing here knows where that area is, so the
711 // distance is recorded the way a parameter read out of it is and finished with it.
712 let overflow = self.out.new_vreg(self.gpr);
713 let lea = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{}", x86_64::FRAME.lea)));
714 let sp = mir::Operand::read(mir::Reg::physical(self.conv.stack_pointer), self.gpr);
715 let made = self
716 .out
717 .build(block, lea)
718 .at(span)
719 .def(overflow, self.gpr)
720 .mem(mir::Mem::at(sp))
721 .finish();
722 self.stack.arguments.push((made, started.incoming));
723
724 let save = self.frame_address(block, started.save);
725 for (at, held) in [(varargs::OVERFLOW, overflow), (varargs::SAVE_AREA, save)] {
726 let store = mir::Opcode::new(self.names.intern("x64.mov_mr_64"));
727 let mem = self.field(list, at);
728 self.out.build(block, store).at(span).uses(held, self.gpr).mem(mem).finish();
729 }
730 Ok(())
731 }
732
733 /// One field of a list, as the addressing mode that reaches it.
734 fn field(&self, list: mir::Reg, at: i64) -> mir::Mem {
735 let base = mir::Operand::read(list, self.gpr);
736 mir::Mem::at(base).plus(i32::try_from(at).expect("a field of a list is a small offset"))
737 }
738
739 /// The address of a name: one `lea` off the instruction pointer, with the name on it.
740 ///
741 /// The same instruction an `alloca` gets and for a related reason. An address that is not in
742 /// the program is a `lea` of an addressing mode that names no register, and the mode carries
743 /// the symbol so that [`rucc_asm`] can write it relative to `%rip` and leave the relocation
744 /// for the assembler. Both halves of that already existed: the printer writes `sym(%rip)` and
745 /// the encoder emits the relocation, because a call to a name the file does not define needed
746 /// them first.
747 ///
748 /// There is deliberately no name for this in [`crate::term`], which is what stops the address
749 /// being folded into the instruction that reads it. Folding it is the right thing to do and
750 /// is what turns a load of a global from two instructions into one, but it is a separate
751 /// question about addressing modes and issue #282 is it. Until then the address is in a
752 /// register before anything uses it, which is correct and one instruction longer.
753 ///
754 /// What this does not do is give the name anything to refer to. A module carries its globals
755 /// and nothing writes them out, so a file that defines the variable it reads compiles to a
756 /// reference the linker cannot resolve. Issue #293 is the other half.
757 fn address_of(&mut self, inst: Inst) -> Result<(), Unsupported> {
758 let data = &self.source[inst];
759 let Extra::Symbol(symbol) = data.extra else { return Err(self.unsupported(inst)) };
760 let result = data.first_result.ok_or_else(|| self.unsupported(inst))?;
761
762 let block = self.at.expect("a block is being filled");
763 let reg = self.new_reg(result);
764 let span = self.source.span(inst);
765 let lea = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{}", x86_64::FRAME.lea)));
766 self.out.build(block, lea).at(span).def(reg, self.gpr).mem(mir::Mem::of(symbol)).finish();
767 Ok(())
768 }
769
770 /// A conversion that converts nothing: the result is the operand under another type.
771 ///
772 /// `ptrtoint` and `inttoptr` at one width are the whole of this. An address on this machine is
773 /// an integer as wide as the machine addresses, so a cast between the two changes what the
774 /// type system calls the value and changes nothing about the value, and the register holding
775 /// it is the register that already held it. The front end never writes either of them at any
776 /// other width, because it widens or narrows around the cast rather than through it, so the
777 /// two widths disagreeing here means the IR came from somewhere else and is refused rather
778 /// than guessed at.
779 ///
780 /// Reading the operand first is what materializes it when it is a constant, which is the case
781 /// that matters: a null pointer is an `inttoptr` of zero, and that zero has to reach a
782 /// register before anything can call it an address.
783 fn rename(&mut self, inst: Inst) -> Result<(), Unsupported> {
784 let data = &self.source[inst];
785 let [arg] = self.source[data.args] else { return Err(self.unsupported(inst)) };
786 let result = data.first_result.ok_or_else(|| self.unsupported(inst))?;
787 if !self.is_address_width(self.source[arg].ty)
788 || !self.is_address_width(self.source[result].ty)
789 {
790 return Err(self.unsupported(inst));
791 }
792 let reg = self.reg_of(arg)?;
793 self.regs[result.index()] = Some(reg);
794 Ok(())
795 }
796
797 /// One barrier, which on this machine is one instruction at the strongest ordering and no
798 /// instruction at all at every other one.
799 ///
800 /// x86-64 is total store order, so the only reordering the machine does is a store followed by
801 /// a load of a different address, and the only ordering that forbids that is sequential
802 /// consistency. An acquire, a release and an acquire release fence are therefore already true
803 /// of every program running here, and what a program wanted from writing one is that the
804 /// compiler not move memory accesses across it. The optimizer has finished by the time this
805 /// runs and nothing below reorders one access past another, so the constraint is already
806 /// discharged and there is nothing to write.
807 ///
808 /// The strongest one is `mfence`, which is what gcc 16.2.0 writes for
809 /// `__atomic_thread_fence(__ATOMIC_SEQ_CST)` and for `__sync_synchronize`. A locked instruction
810 /// on the stack is faster on most parts and is what some compilers write instead; it is also a
811 /// write to memory the program did not ask for, and the plain barrier is the one that says what
812 /// it means.
813 ///
814 /// Written here by name rather than by a rule, for the same reason a `lea` of a symbol is:
815 /// there is nothing in a barrier that a proof over bitvectors could discharge. It computes
816 /// nothing, so there is no equality to state, and what makes it the right answer is the memory
817 /// model, which the rule language cannot talk about.
818 fn barrier(&mut self, inst: Inst) -> Result<(), Unsupported> {
819 let Extra::Order(order) = self.source[inst].extra else {
820 return Err(self.unsupported(inst));
821 };
822 if order != MemOrder::SeqCst {
823 return Ok(());
824 }
825 let block = self.at.expect("a block is being filled");
826 let span = self.source.span(inst);
827 let fence = mir::Opcode::new(self.names.intern("x64.mfence"));
828 self.out.build(block, fence).at(span).finish();
829 Ok(())
830 }
831
832 /// Whether a type is the width an address is, which is what makes a cast to or from one free.
833 fn is_address_width(&self, ty: Type) -> bool {
834 ty.is_ptr() || (ty.is_int() && ty.bits() == ADDRESS_BITS)
835 }
836
837 /// Where a block goes, which in machine IR is on the block rather than on its terminator.
838 ///
839 /// That is why no rule ever names a block: a branch is selected for what it reads and the
840 /// edges are copied across here, arguments and all. The arguments are read last, after every
841 /// instruction of the block is written, because an argument that is a constant is
842 /// materialized where it is first wanted and the end of the block is where an edge wants it.
843 ///
844 /// Which is not quite the end. A block that leaves two ways has the branch as its last
845 /// instruction, and anything appended after a branch is something the branch has already
846 /// jumped past, so a constant materialized here would be a register the block below reads and
847 /// nothing ever writes. The branch is put back on the end when that happened, which is the
848 /// only reordering anything in this crate does and is why the branch is remembered before a
849 /// single argument is read.
850 fn edges(&mut self, block: Block, out: mir::Block) -> Result<(), Unsupported> {
851 let Some(term) = self.source.terminator(block) else { return Ok(()) };
852 let branch =
853 if self.source[term].opcode == Opcode::BrIf { self.out.terminator(out) } else { None };
854
855 let calls: Vec<rucc_ir::BlockCall> = self.source.successors(term).collect();
856 let mut succs = Vec::with_capacity(calls.len());
857 for call in calls {
858 let args: Vec<Value> = self.source[call.args].to_vec();
859 let mut regs = Vec::with_capacity(args.len());
860 for value in args {
861 regs.push(self.reg_of(value)?);
862 }
863 succs.push(mir::BlockCall { block: self.out_block(call.block), args: regs });
864 }
865 if let Some(branch) = branch {
866 if self.out.terminator(out) != Some(branch) {
867 self.out.remove_inst(branch);
868 self.out.append_inst(out, branch);
869 }
870 }
871 *self.out.succs_mut(out) = succs;
872 Ok(())
873 }
874
875 /// The machine IR block an IR block became.
876 fn out_block(&self, block: Block) -> mir::Block {
877 self.blocks[block.index()].expect("every block was created before any was filled")
878 }
879
880 /// The parameters of the entry block, which are the function's arguments.
881 ///
882 /// They are not block parameters in the machine IR and they cannot be. A block parameter is
883 /// given its value by a move on the edge into the block, and there is no edge into an entry
884 /// block, so what arrives in a function is the convention's to say. [`crate::abi`] is what
885 /// says it.
886 ///
887 /// The ones past the last register arrived in the caller's memory and are read out of it, and
888 /// the loads that read them come back here so that the frame can finish them the way it
889 /// finishes an `alloca`.
890 fn arrive(&mut self, block: Block, out: mir::Block) -> Result<(), Unsupported> {
891 let params = self.source[block].params.clone();
892 // The type of each is the block's answer and what the ABI asks of it is the signature's,
893 // and the two lists are the same list: a parameter the classification turned into a
894 // pointer is a pointer in the block too. A block with more parameters than the signature
895 // names is not one the front end writes, and each of those is taken as a plain value.
896 let asked: Vec<Abi> = self.source.signature().params.iter().map(|it| it.abi).collect();
897 let types: Vec<Param> = params
898 .iter()
899 .enumerate()
900 .map(|(index, &value)| {
901 let abi = asked.get(index).copied().unwrap_or_default();
902 Param { ty: self.source[value].ty, abi }
903 })
904 .collect();
905 // A save area for a function that takes arguments its signature does not name, on a
906 // convention whose list is the four field one. Windows is the other kind and has no area at
907 // all, so a `va_start` in one is refused rather than built wrong.
908 let variadic = self.source.signature().variadic && !self.conv.shared_positions;
909 let area = variadic.then(|| varargs::Area::of(self.conv));
910 let arrived = abi::entry(&mut self.out, out, &types, self.conv, self.names, area)
911 .map_err(|(index, missing)| Unsupported::Argument { index, missing })?;
912 for (¶m, reg) in params.iter().zip(&arrived.regs) {
913 self.regs[param.index()] = Some(*reg);
914 }
915 if let Some(area) = area {
916 self.save_area(out, &arrived, area);
917 }
918 self.stack.arguments.extend(arrived.stack);
919 Ok(())
920 }
921
922 /// The prologue of a variadic function, which is every argument register it was handed written
923 /// into the frame.
924 ///
925 /// Every one the signature did not name, that is. Which of those hold anything is a thing only
926 /// the caller knew and there is nothing here to ask, so all of them are written, and the ones a
927 /// named parameter took are not, because `va_start` sets the two offsets past them and nothing
928 /// ever reads their slots.
929 ///
930 /// What that costs is up to fourteen stores in the prologue of a function that may read none of
931 /// them, and the convention's answer to that is the count of vector registers in `%al`, which
932 /// lets a callee skip the eight vector stores when the call passed no floats. Skipping them is a
933 /// branch in a prologue, and a prologue is written long after this by [`crate::finish`], which
934 /// has no blocks to branch between. So they are all written every time, which is correct and is
935 /// what `-O0` costs. Issue #323 is the branch.
936 ///
937 /// A vector register is written eight bytes at a time and not sixteen, for the reason
938 /// [`crate::varargs`] gives: the upper half of a slot is not something any reader of a list
939 /// looks at.
940 ///
941 /// The address is computed once into a register rather than written as a displacement off the
942 /// stack pointer, because a displacement into a frame is not known until after allocation and
943 /// one `lea` costs less than a fixup list for a dozen stores. It is the same `lea` an `alloca`
944 /// gets and [`crate::finish`] fills it in the same way.
945 fn save_area(&mut self, out: mir::Block, arrived: &abi::Arrived, area: varargs::Area) {
946 let save = self.stack.locals.len();
947 self.stack.locals.push(Local { size: area.size, align: varargs::VECTOR_SLOT });
948 self.varargs = Some(Varargs {
949 save,
950 incoming: arrived.used,
951 integers: u32::try_from(arrived.took.0).unwrap_or(0) * area.stride(false),
952 floats: area.starts_at(true)
953 + u32::try_from(arrived.took.1).unwrap_or(0) * area.stride(true),
954 });
955
956 let base = self.frame_address(out, save);
957 for &(reg, class, at) in &arrived.spare {
958 let name = if class == self.gpr { "x64.mov_mr_64" } else { "x64.movsd_mr" };
959 let store = mir::Opcode::new(self.names.intern(name));
960 let up = i32::try_from(at).expect("a register save area under two gigabytes");
961 let mem = mir::Mem::at(mir::Operand::read(base, self.gpr)).plus(up);
962 self.out.build(out, store).uses(reg, class).mem(mem).finish();
963 }
964 }
965
966 /// The address of one of the function's stack objects, in a fresh register.
967 ///
968 /// Written with nothing in its displacement, because where an object is in a frame is not known
969 /// until after allocation, and given to [`crate::finish`] to fill in the way an `alloca` is.
970 fn frame_address(&mut self, out: mir::Block, local: usize) -> mir::Reg {
971 let reg = self.out.new_vreg(self.gpr);
972 let lea = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{}", x86_64::FRAME.lea)));
973 let sp = mir::Operand::read(mir::Reg::physical(self.conv.stack_pointer), self.gpr);
974 let made = self.out.build(out, lea).def(reg, self.gpr).mem(mir::Mem::at(sp)).finish();
975 self.stack.addresses.push((made, local));
976 reg
977 }
978
979 /// Whether an instruction is one no machine instruction is written for where it stands.
980 ///
981 /// Four of them, and none is a lowering decision, which is why none is a rule. A constant is
982 /// written where a register for it is first wanted rather than where the IR put it, and every
983 /// reader of one may have folded it into an immediate, in which case nowhere is the right
984 /// place. A return of nothing has nothing to put anywhere: the epilogue gives the frame back
985 /// and leaves, and it is appended to every block with no successors long after this has
986 /// finished, so a return with a value is one instruction here and a return without one is
987 /// none. Unless the value went back through memory, in which case there is something to put
988 /// somewhere after all and the IR does not carry it: the address the caller handed over has
989 /// to be in `rax` on the way out, and [`Lowering::returned`] is what writes that.
990 ///
991 /// An unconditional jump is the third, and there is even less of it: the edge is on the
992 /// block, and whether the block it goes to is the next one and needs no jump at all is the
993 /// block layout's answer rather than this one's.
994 ///
995 /// The fourth is a point control does not arrive at, in both of the forms the IR has for it:
996 /// the `unreachable` terminator the front end puts at the end of a function whose body can run
997 /// off the bottom, and the `unreachable_hint` a call to `__builtin_unreachable` becomes. What
998 /// to write for a place nothing reaches is a question with no wrong answer, and nothing is the
999 /// smallest one and the one gcc 16.2.0 gives at `-O0`. The terminator leaves the block with no
1000 /// successors, so the epilogue lands at the end of it the way it does on any other block that
1001 /// goes nowhere, and the function cannot fall out of its own last instruction into whatever
1002 /// the assembler puts next.
1003 fn writes_nothing(&self, inst: Inst) -> bool {
1004 let data = &self.source[inst];
1005 match data.opcode {
1006 Opcode::IConst | Opcode::Jump | Opcode::Unreachable | Opcode::UnreachableHint => true,
1007 Opcode::Return => self.source[data.args].is_empty() && self.sret().is_none(),
1008 _ => false,
1009 }
1010 }
1011
1012 /// The rule that fires on an instruction, and what it bound.
1013 ///
1014 /// The plans are tried in order and the first that matches wins, which is the maximal munch
1015 /// `spec/10-backend.md` asks for: a plan that offers more to the matcher is tried before one
1016 /// that offers less.
1017 fn select(&self, inst: Inst) -> Option<(Plan, Match<Term>)> {
1018 for plan in self.plans(inst) {
1019 let terms = Terms::new(self.source, inst, plan);
1020 if let Some(matched) = TABLE.find(&terms, Term::Root) {
1021 return Some((plan, matched));
1022 }
1023 }
1024 None
1025 }
1026
1027 /// Every way this instruction can be shown to the matcher, most offered first.
1028 fn plans(&self, inst: Inst) -> Vec<Plan> {
1029 let args = &self.source[self.source[inst].args];
1030 let mut plans = vec![PLAIN];
1031 for (index, &arg) in args.iter().enumerate().take(MAX_ARGS) {
1032 let mut ways = Vec::new();
1033 if self.foldable(inst, arg) {
1034 ways.push(Shown::Expand);
1035 }
1036 if Terms::new(self.source, inst, PLAIN).constant(arg).is_some() {
1037 ways.push(Shown::Const);
1038 }
1039 ways.push(Shown::Reg);
1040 plans = plans
1041 .into_iter()
1042 .flat_map(|plan| {
1043 ways.iter().map(move |&way| {
1044 let mut next = plan;
1045 next[index] = way;
1046 next
1047 })
1048 })
1049 .collect();
1050 }
1051 plans
1052 }
1053
1054 /// Whether an operand may be shown as the instruction that computed it.
1055 ///
1056 /// It has to be in the same block, because a rule that folds one instruction into another
1057 /// moves the work to where the second one is. It has to be read only by this instruction,
1058 /// because folding it does not delete it for anybody else and doing the work twice is not a
1059 /// saving. And it has to be something rather than a block parameter, and not a constant,
1060 /// which is shown as a constant instead.
1061 fn foldable(&self, into: Inst, value: Value) -> bool {
1062 let Def::Result { inst, .. } = self.source[value].def else { return false };
1063 if self.source[inst].opcode == Opcode::IConst || self.uses[value.index()] != 1 {
1064 return false;
1065 }
1066 self.source.block_of(inst).is_some()
1067 && self.source.block_of(inst) == self.source.block_of(into)
1068 }
1069
1070 /// The instructions a match folded into the one it matched.
1071 ///
1072 /// The plan is what says this, not the bindings: a binding is a register or a number either
1073 /// way, and an operand shown as the instruction that computed it is one no rule could have
1074 /// matched without taking that instruction, because the plan offered the matcher nothing
1075 /// else to call it.
1076 fn folds(&self, inst: Inst, plan: Plan) -> Vec<Inst> {
1077 let args = &self.source[self.source[inst].args];
1078 args.iter()
1079 .take(MAX_ARGS)
1080 .enumerate()
1081 .filter(|&(index, _)| plan[index] == Shown::Expand)
1082 .filter_map(|(_, &arg)| match self.source[arg].def {
1083 Def::Result { inst, .. } => Some(inst),
1084 Def::Param { .. } => None,
1085 })
1086 .collect()
1087 }
1088
1089 /// Build the machine instruction a match calls for.
1090 fn emit(&mut self, inst: Inst, matched: &Match<Term>) -> Result<(), Unsupported> {
1091 let rule: &Rule = TABLE.rule(matched);
1092 let pieces = rule.replacement;
1093 let Some(Piece::App { head, arity }) = pieces.first() else {
1094 return Err(self.unsupported(inst));
1095 };
1096 let opcode = head.strip_prefix(PREFIX).ok_or_else(|| self.unsupported(inst))?;
1097 let form = x86_64::form(opcode).ok_or_else(|| self.unsupported(inst))?;
1098
1099 let mut read = Read::default();
1100 let mut at = 1;
1101 for _ in 0..*arity {
1102 at = self.read(inst, pieces, at, &matched.bindings, &mut read)?;
1103 }
1104
1105 let descs = form.operands();
1106 let writes = descs.iter().take_while(|desc| desc.role.is_def()).count();
1107 if descs.len() - writes != read.regs.len() {
1108 return Err(self.unsupported(inst));
1109 }
1110
1111 // The first thing the instruction writes is what it computes, and any others are
1112 // registers the machine destroys on the way, which are fresh because nothing else is in
1113 // them and nothing reads them. An instruction that writes nothing at all is one whose
1114 // whole purpose is its effect, which is what a store is, and there is no result to put
1115 // anywhere.
1116 let mut regs = Vec::new();
1117 if writes > 0 {
1118 let result = self.source[inst].first_result.ok_or_else(|| self.unsupported(inst))?;
1119 regs.push(self.new_reg(result));
1120 // The rest are the registers the machine destroys on the way, and the class each is in
1121 // is the one the instruction's description gives it rather than a guess, so that an
1122 // instruction that wrecks a register in the other file says so.
1123 regs.extend(descs[1..writes].iter().map(|desc| self.out.new_vreg(desc.class)));
1124 } else if self.source[inst].first_result.is_some() {
1125 // A rule that throws away a value the IR gave a name to would leave every reader of
1126 // that name with nothing to read, so it is a rule this and the target disagree about.
1127 return Err(self.unsupported(inst));
1128 }
1129 regs.extend(read.regs.iter().copied());
1130
1131 let block = self.at.expect("a block is being filled");
1132 let opcode = mir::Opcode::new(self.names.intern(head));
1133 let mut build = self.out.build(block, opcode).at(self.source.span(inst));
1134 for (desc, reg) in descs.iter().zip(regs) {
1135 let operand = mir::Operand {
1136 reg,
1137 class: desc.class,
1138 role: desc.role,
1139 constraint: desc.constraint,
1140 };
1141 build = build.operand(operand);
1142 }
1143 if let Some(mem) = read.mem {
1144 build = build.mem(mem);
1145 }
1146 if let Some(imm) = read.imm {
1147 build = build.imm(imm);
1148 }
1149 build.finish();
1150 Ok(())
1151 }
1152
1153 /// Read one argument of a replacement, which is a register, a number or an address.
1154 ///
1155 /// Gives back the position after it, because a replacement is flat and an address takes
1156 /// arguments of its own.
1157 fn read(
1158 &mut self,
1159 inst: Inst,
1160 pieces: &'static [Piece],
1161 at: usize,
1162 bindings: &[Term],
1163 out: &mut Read,
1164 ) -> Result<usize, Unsupported> {
1165 match pieces.get(at) {
1166 Some(Piece::Int(value)) => {
1167 out.imm = i64::try_from(*value).ok();
1168 Ok(at + 1)
1169 }
1170 Some(Piece::Var { index, .. }) => {
1171 match bindings.get(*index) {
1172 Some(&Term::Reg(value)) => {
1173 let reg = self.reg_of(value)?;
1174 out.regs.push(reg);
1175 }
1176 Some(&Term::Num(value)) => out.imm = i64::try_from(value).ok(),
1177 // A pattern binds a register or a number and nothing else, so this is a
1178 // rule the matcher and this file disagree about.
1179 _ => return Err(self.unsupported(inst)),
1180 }
1181 Ok(at + 1)
1182 }
1183 Some(Piece::App { head, arity }) => {
1184 let kind = x86_64::address(head).ok_or_else(|| self.unsupported(inst))?;
1185 let mut inner = Read::default();
1186 let mut next = at + 1;
1187 for _ in 0..*arity {
1188 next = self.read(inst, pieces, next, bindings, &mut inner)?;
1189 }
1190 let mem = address(kind, &inner, self.gpr).ok_or_else(|| self.unsupported(inst))?;
1191 out.mem = Some(mem);
1192 Ok(next)
1193 }
1194 None => Err(self.unsupported(inst)),
1195 }
1196 }
1197
1198 /// The register a value is in, materializing it if it is a constant that has not been put in
1199 /// one yet.
1200 ///
1201 /// A constant is written where it is wanted rather than where the IR defined it, and where it
1202 /// is wanted is a block that need not be the one the IR defined it in. So the register holding
1203 /// one is only good inside the block it was written into, and a second block that wants the
1204 /// same constant gets its own. Anything else is a register read where nothing wrote it: the
1205 /// IR guarantees a definition dominates its uses, and this moved the definition.
1206 ///
1207 /// Writing the number again is also the right answer and not merely the safe one. It is one
1208 /// instruction that reads nothing, which is cheaper than holding a register live across a
1209 /// branch for it, and it is what a rematerializing allocator would do with the value anyway.
1210 fn reg_of(&mut self, value: Value) -> Result<mir::Reg, Unsupported> {
1211 let constant = match self.source[value].def {
1212 Def::Result { inst, .. } => {
1213 (self.source[inst].opcode == Opcode::IConst).then_some(inst)
1214 }
1215 Def::Param { .. } => None,
1216 };
1217 let here = self.at.expect("a block is being filled");
1218 if let Some(reg) = self.regs[value.index()] {
1219 if constant.is_none() || self.written[value.index()] == Some(here) {
1220 return Ok(reg);
1221 }
1222 }
1223 if let Some(inst) = constant {
1224 // Cleared so that the register the constant is written into is a new one rather than
1225 // the one the block above wrote, which is still being read up there.
1226 self.regs[value.index()] = None;
1227 let matched = self
1228 .select(inst)
1229 .map(|(_, matched)| matched)
1230 .ok_or_else(|| self.unsupported(inst))?;
1231 self.emit(inst, &matched)?;
1232 // The same mark the loop over the instructions makes, and it has to be made here as
1233 // well because this is the only place a constant is ever selected: the loop skips one
1234 // where the IR wrote it, so a rule that lowers a constant fires from nowhere else and
1235 // would be reported as a rule nothing reaches.
1236 self.fired.mark(matched.rule);
1237 self.written[value.index()] = Some(here);
1238 return Ok(self.regs[value.index()].expect("a constant is written into a register"));
1239 }
1240 Ok(self.new_reg(value))
1241 }
1242
1243 /// Which register file a value of that type lives in.
1244 ///
1245 /// The vector one for the two float widths the machine has scalar instructions for, and the
1246 /// general purpose one for everything else. A `long double` is in neither, and it is here
1247 /// rather than in the vector class on purpose: it would be put in a register that cannot hold
1248 /// it, and there is no rule that names one, so the instruction computing it is reported. The
1249 /// wrong class would make that a wrong program instead of a refused one.
1250 fn class_of(&self, ty: Type) -> RegClass {
1251 match crate::term::float_slot(ty) {
1252 Some(_) => self.conv.sse_class,
1253 None => self.gpr,
1254 }
1255 }
1256
1257 /// A fresh register for a value, which is what the instruction computing it writes.
1258 fn new_reg(&mut self, value: Value) -> mir::Reg {
1259 if let Some(reg) = self.regs[value.index()] {
1260 return reg;
1261 }
1262 let reg = self.out.new_vreg(self.class_of(self.source[value].ty));
1263 self.regs[value.index()] = Some(reg);
1264 reg
1265 }
1266
1267 fn unsupported(&self, inst: Inst) -> Unsupported {
1268 let data = &self.source[inst];
1269 Unsupported::Inst {
1270 inst,
1271 term: Terms::new(self.source, inst, PLAIN).name(inst),
1272 opcode: data.opcode,
1273 ty: data.first_result.map(|result| self.source[result].ty),
1274 }
1275 }
1276}
1277
1278/// What the arguments of one replacement came to.
1279#[derive(Debug, Default)]
1280struct Read {
1281 regs: Vec<mir::Reg>,
1282 imm: Option<i64>,
1283 mem: Option<mir::Mem>,
1284}
1285
1286/// The addressing mode an address constructor's arguments make.
1287///
1288/// One arm per constructor rather than a question asked of the kind, because what the arguments
1289/// mean is the whole of what tells the four apart: the same register is a base in one and an
1290/// index in another, and the same constant is a scale in one and a displacement in another.
1291fn address(kind: x86_64::Address, read: &Read, gpr: RegClass) -> Option<mir::Mem> {
1292 let mut regs = read.regs.iter().copied().map(|reg| mir::Operand::read(reg, gpr));
1293 match kind {
1294 x86_64::Address::BaseIndexScale => {
1295 let base = regs.next()?;
1296 let index = regs.next()?;
1297 Some(mir::Mem::at(base).indexed(index, u8::try_from(read.imm?).ok()?))
1298 }
1299 x86_64::Address::IndexScale => Some(mir::Mem {
1300 base: None,
1301 index: Some(regs.next()?),
1302 scale: u8::try_from(read.imm?).ok()?,
1303 disp: 0,
1304 symbol: None,
1305 }),
1306 x86_64::Address::Base => Some(mir::Mem::at(regs.next()?)),
1307 // The rule that writes this has a guard saying the constant fits, so a displacement that
1308 // does not is a rule and a target that disagree rather than a program this cannot compile.
1309 x86_64::Address::BaseOffset => {
1310 Some(mir::Mem { disp: i32::try_from(read.imm?).ok()?, ..mir::Mem::at(regs.next()?) })
1311 }
1312 }
1313}
1314
1315/// The table this selector matches with.
1316///
1317/// One target for now, because one target has a rule file. Which table to use becomes a question
1318/// the moment a second one does, and the answer will be the target the session was given rather
1319/// than a constant here.
1320static TABLE: &Table = &crate::select::x86_64::TABLE;
1321
1322#[cfg(test)]
1323mod tests {
1324 use rucc_ir::{
1325 Builder, CallInfo, Flags, InstData, MemInfo, MemOrder, Restrict, Signature, Type,
1326 };
1327 use rucc_regalloc::assign::Env;
1328 use rucc_target::x86_64::{FRAME, REGS, SYSV};
1329
1330 use super::*;
1331 use crate::finish::finish;
1332 use crate::frame::{Frame, Incoming, Layout};
1333
1334 /// A function of as many 64 bit parameters as the test wants, and the block they are in.
1335 fn blank(params: &[Type]) -> (Interner, Func, Block, Vec<Value>) {
1336 let mut names = Interner::new();
1337 let mut func = Func::new(names.intern("f"), Signature::new());
1338 let block = func.create_block();
1339 let values = params.iter().map(|&ty| func.append_param(block, ty)).collect();
1340 (names, func, block, values)
1341 }
1342
1343 /// An ordinary access: not atomic, and aligned enough that nothing here has an opinion.
1344 /// Neither field reaches selection, which is the point of saying it once here.
1345 fn plain() -> MemInfo {
1346 MemInfo {
1347 size: 0,
1348 align: 1,
1349 order: MemOrder::NotAtomic,
1350 tbaa: None,
1351 restrict: Restrict::NONE,
1352 }
1353 }
1354
1355 /// What the allocator is given: every integer register the convention offers except two, held
1356 /// back so that a move on an edge has somewhere to break a cycle and a spilled value has
1357 /// somewhere to be read into. Which two does not matter, and holding back the last two the
1358 /// convention would reach for leaves every expectation below unchanged.
1359 fn env() -> Env {
1360 const SCRATCH: [rucc_target::PhysReg; 2] = [x86_64::R10, x86_64::R11];
1361 let order: Vec<rucc_target::PhysReg> =
1362 SYSV.int_order.iter().copied().filter(|reg| !SCRATCH.contains(reg)).collect();
1363 Env::new().with(x86_64::GPR, &order, &SCRATCH)
1364 }
1365
1366 /// The machine IR text a function lowers to.
1367 fn lower(names: &mut Interner, source: &Func) -> String {
1368 let out = func(source, names, &SYSV).expect("every instruction has a rule");
1369 mir::print_func(&out.func, names, ®S)
1370 }
1371
1372 #[test]
1373 fn an_addition_of_two_registers_is_one_instruction() {
1374 let i32 = Type::int(32);
1375 let (mut names, mut func, block, args) = blank(&[i32, i32]);
1376 let mut build = Builder::new(&mut func, block);
1377 build.binary(Opcode::Add, args[0], args[1], Flags::default());
1378
1379 assert_eq!(
1380 lower(&mut names, &func),
1381 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_32\n \
1382 %1:gpr($rsi) = x64.arg_val_32\n %2:gpr(reuse 1) = x64.add_rr_32 %0, %1\n}\n"
1383 );
1384 }
1385
1386 #[test]
1387 fn a_constant_operand_becomes_an_immediate() {
1388 let i32 = Type::int(32);
1389 let (mut names, mut func, block, args) = blank(&[i32]);
1390 let mut build = Builder::new(&mut func, block);
1391 let seven = build.iconst(i32, 7);
1392 build.binary(Opcode::Add, args[0], seven, Flags::default());
1393
1394 // The constant is in the instruction and nothing was written to hold it, which is what
1395 // materializing one where a register for it is wanted buys.
1396 assert_eq!(
1397 lower(&mut names, &func),
1398 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_32\n \
1399 %1:gpr(reuse 1) = x64.add_ri_32 %0, 7\n}\n"
1400 );
1401 }
1402
1403 #[test]
1404 fn a_constant_too_wide_for_an_immediate_goes_into_a_register() {
1405 let i64 = Type::int(64);
1406 let (mut names, mut func, block, args) = blank(&[i64]);
1407 let mut build = Builder::new(&mut func, block);
1408 let big = build.iconst(i64, i128::from(i32::MAX) + 1);
1409 build.binary(Opcode::Add, args[0], big, Flags::default());
1410
1411 // Nobody wrote this fallback down. The rule that takes an immediate has a guard that
1412 // turns a number this wide down, so it does not fire, and the next way of showing the
1413 // operand puts it in a register.
1414 assert_eq!(
1415 lower(&mut names, &func),
1416 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_64\n \
1417 %1:gpr = x64.mov_ri_64 2147483648\n %2:gpr(reuse 1) = x64.add_rr_64 %0, %1\n}\n"
1418 );
1419 }
1420
1421 #[test]
1422 fn an_index_calculation_folds_into_an_address() {
1423 let i64 = Type::int(64);
1424 let (mut names, mut func, block, args) = blank(&[i64, i64]);
1425 let mut build = Builder::new(&mut func, block);
1426 let four = build.iconst(i64, 4);
1427 let scaled = build.binary(Opcode::Mul, args[1], four, Flags::default());
1428 build.binary(Opcode::Add, args[0], scaled, Flags::default());
1429
1430 // Three IR instructions and one machine instruction. The multiply is gone because the
1431 // rule that matched reached down and took it.
1432 assert_eq!(
1433 lower(&mut names, &func),
1434 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_64\n \
1435 %1:gpr($rsi) = x64.arg_val_64\n %2:gpr = x64.lea_64 [%0 + %1*4]\n}\n"
1436 );
1437 }
1438
1439 #[test]
1440 fn an_instruction_read_twice_is_not_folded_into_either_reader() {
1441 let i64 = Type::int(64);
1442 let (mut names, mut func, block, args) = blank(&[i64, i64]);
1443 let mut build = Builder::new(&mut func, block);
1444 let four = build.iconst(i64, 4);
1445 let scaled = build.binary(Opcode::Mul, args[1], four, Flags::default());
1446 let first = build.binary(Opcode::Add, args[0], scaled, Flags::default());
1447 build.binary(Opcode::Add, first, scaled, Flags::default());
1448
1449 // Folding it into both would compute it twice, which is not a saving, so it stays where
1450 // it is and both readers read the register it wrote.
1451 let text = lower(&mut names, &func);
1452 assert!(text.contains("x64.lea_64 [%1*4]"), "{text}");
1453 assert_eq!(text.matches("x64.add_rr_64").count(), 2, "{text}");
1454 }
1455
1456 #[test]
1457 fn a_shift_by_a_register_asks_for_it_in_cl() {
1458 let i32 = Type::int(32);
1459 let (mut names, mut func, block, args) = blank(&[i32, i32]);
1460 let mut build = Builder::new(&mut func, block);
1461 build.binary(Opcode::Shl, args[0], args[1], Flags::default());
1462
1463 // The fixed register is not in the rule. It is what the target says the instruction does
1464 // with its operands, and the allocator is what will act on it.
1465 let text = lower(&mut names, &func);
1466 assert!(text.contains("x64.shl_rcl_32 %0, %1($rcx)"), "{text}");
1467 }
1468
1469 #[test]
1470 fn a_division_names_the_registers_and_the_register_it_destroys() {
1471 let i32 = Type::int(32);
1472 let (mut names, mut func, block, args) = blank(&[i32, i32]);
1473 let mut build = Builder::new(&mut func, block);
1474 build.binary(Opcode::SDiv, args[0], args[1], Flags::default());
1475
1476 // Two definitions, because a division writes the remainder whether anybody wanted it or
1477 // not, and the second one is early because it is destroyed before the operands are read.
1478 let text = lower(&mut names, &func);
1479 assert!(
1480 text.contains("%2:gpr($rax), early %3:gpr($rdx) = x64.idiv_quo_32 %0($rax), %1"),
1481 "{text}"
1482 );
1483 }
1484
1485 #[test]
1486 fn a_load_reads_through_the_register_the_address_is_in() {
1487 let i64 = Type::int(64);
1488 let (mut names, mut func, block, args) = blank(&[i64]);
1489 let mut build = Builder::new(&mut func, block);
1490 build.load(Type::int(32), args[0], plain(), Flags::default());
1491
1492 assert_eq!(
1493 lower(&mut names, &func),
1494 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_64\n \
1495 %1:gpr = x64.mov_rm_32 [%0]\n}\n"
1496 );
1497 }
1498
1499 #[test]
1500 fn a_store_writes_no_register_and_the_value_it_writes_is_the_one_the_ir_gave_it() {
1501 let (mut names, mut func, block, args) = blank(&[Type::int(32), Type::int(64)]);
1502 let mut build = Builder::new(&mut func, block);
1503 build.store(args[0], args[1], plain(), Flags::default());
1504
1505 // The value is the first parameter and the address is the second, and the instruction
1506 // takes them the other way round. Getting that backwards would compile to a store of the
1507 // address into the value, which is a program that runs and does the wrong thing.
1508 assert_eq!(
1509 lower(&mut names, &func),
1510 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_32\n \
1511 %1:gpr($rsi) = x64.arg_val_64\n x64.mov_mr_32 %0, [%1]\n}\n"
1512 );
1513 }
1514
1515 #[test]
1516 fn an_address_with_a_constant_added_folds_into_the_access() {
1517 let i64 = Type::int(64);
1518 let (mut names, mut func, block, args) = blank(&[i64]);
1519 let mut build = Builder::new(&mut func, block);
1520 let twelve = build.iconst(i64, 12);
1521 let field = build.binary(Opcode::Add, args[0], twelve, Flags::default());
1522 build.load(Type::int(64), field, plain(), Flags::default());
1523
1524 // Two IR instructions and one machine instruction, which is what every read of a field
1525 // of a structure comes to.
1526 assert_eq!(
1527 lower(&mut names, &func),
1528 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_64\n \
1529 %1:gpr = x64.mov_rm_64 [%0 + 12]\n}\n"
1530 );
1531 }
1532
1533 #[test]
1534 fn a_displacement_too_wide_to_encode_leaves_the_addition_where_it_is() {
1535 let i64 = Type::int(64);
1536 let (mut names, mut func, block, args) = blank(&[i64]);
1537 let mut build = Builder::new(&mut func, block);
1538 let big = build.iconst(i64, i128::from(i32::MAX) + 1);
1539 let far = build.binary(Opcode::Add, args[0], big, Flags::default());
1540 build.load(Type::int(32), far, plain(), Flags::default());
1541
1542 // A displacement is signed and 32 bits. The rule that folds one has a guard that turns
1543 // this down, so the addition stays and the load reads through what it produced. Nobody
1544 // wrote that fallback: it is the next way of showing the operand.
1545 let text = lower(&mut names, &func);
1546 assert!(text.contains("x64.mov_rm_32 [%2]"), "{text}");
1547 assert!(text.contains("x64.add_rr_64"), "{text}");
1548 }
1549
1550 #[test]
1551 fn a_store_of_a_value_that_was_loaded_is_two_instructions_and_no_arithmetic() {
1552 let i64 = Type::int(64);
1553 let (mut names, mut func, block, args) = blank(&[i64, i64]);
1554 let mut build = Builder::new(&mut func, block);
1555 let got = build.load(Type::int(8), args[0], plain(), Flags::default());
1556 build.store(got, args[1], plain(), Flags::default());
1557
1558 // A load feeding a store is the one place folding would be wrong: an x86-64 `mov` has at
1559 // most one memory operand, and there is no rule that takes two, so the load is left where
1560 // it is and the store reads the register it wrote.
1561 assert_eq!(
1562 lower(&mut names, &func),
1563 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_64\n \
1564 %1:gpr($rsi) = x64.arg_val_64\n %2:gpr = x64.mov_rm_8 [%0]\n \
1565 x64.mov_mr_8 %2, [%1]\n}\n"
1566 );
1567 }
1568
1569 #[test]
1570 fn an_access_at_a_width_no_rule_is_written_at_is_reported() {
1571 let i64 = Type::int(64);
1572 let (mut names, mut source, block, args) = blank(&[i64]);
1573 let mut build = Builder::new(&mut source, block);
1574 build.load(Type::int(128), args[0], plain(), Flags::default());
1575
1576 // The width is the whole of what is wrong here, so the width is in the message: `load`
1577 // on its own is written about at every other width and would send a reader looking in
1578 // the wrong place.
1579 let failed = func(&source, &mut names, &SYSV).expect_err("nothing loads 128 bits");
1580 assert_eq!(failed.to_string(), "no rule lowers a `load` producing a `i128`");
1581 }
1582
1583 #[test]
1584 fn a_return_asks_for_the_value_in_the_register_the_caller_reads() {
1585 let (mut names, mut func, block, args) = blank(&[Type::int(32)]);
1586 let mut build = Builder::new(&mut func, block);
1587 build.ret(&[args[0]]);
1588
1589 // The register is not in the rule, the same way `cl` is not in the rule for a shift. It
1590 // is what the target says the instruction does with its operand, and the allocator is
1591 // what will act on it. There is no `ret` here, because giving the frame back has to
1592 // happen between this and leaving and the frame is not worked out yet.
1593 assert_eq!(
1594 lower(&mut names, &func),
1595 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_32\n \
1596 x64.ret_val_32 %0($rax)\n}\n"
1597 );
1598 }
1599
1600 #[test]
1601 fn a_return_of_two_values_asks_for_the_second_register_as_well() {
1602 let i64 = Type::int(64);
1603 let (mut names, mut func, block, args) = blank(&[i64, i64]);
1604 let mut build = Builder::new(&mut func, block);
1605 build.ret(&[args[0], args[1]]);
1606
1607 // `struct { long a, b; } f(long a, long b)`, after the front end has classified it. Both
1608 // halves are integers, so the second is in the second integer return register, and both
1609 // pseudos say so the same way the one for a single value does.
1610 assert_eq!(
1611 lower(&mut names, &func),
1612 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_64\n \
1613 %1:gpr($rsi) = x64.arg_val_64\n x64.ret_val_64 %0($rax)\n \
1614 x64.ret_val2_64 %1($rdx)\n}\n"
1615 );
1616 }
1617
1618 #[test]
1619 fn two_values_back_in_different_files_are_both_the_first_of_their_own() {
1620 let f64 = Type::float(rucc_ir::Float::F64);
1621 let (mut names, mut func, block, args) = blank(&[f64, Type::int(64)]);
1622 let mut build = Builder::new(&mut func, block);
1623 build.ret(&[args[0], args[1]]);
1624
1625 // `struct { double a; long b; } f(double a, long b)`. The two files are counted apart, so
1626 // neither half is the second of anything and the `double` is in `xmm0` rather than in the
1627 // register a second `double` would have been in. Getting this wrong is not a crash: the
1628 // caller reads a register nobody wrote, and this is where that is ruled out.
1629 assert_eq!(
1630 lower(&mut names, &func),
1631 "mfunc @f {\nblock0:\n %0:xmm($xmm0) = x64.arg_val_f64\n \
1632 %1:gpr($rdi) = x64.arg_val_64\n x64.ret_val_f64 %0($xmm0)\n \
1633 x64.ret_val_64 %1($rax)\n}\n"
1634 );
1635 }
1636
1637 #[test]
1638 fn two_of_the_same_file_back_take_the_first_two_of_it() {
1639 let f64 = Type::float(rucc_ir::Float::F64);
1640 let (mut names, mut func, block, args) = blank(&[f64, f64]);
1641 let mut build = Builder::new(&mut func, block);
1642 build.ret(&[args[0], args[1]]);
1643
1644 // `struct { double x, y; } f(double x, double y)`, which is the vector half of the pair
1645 // above and counts in its own file the same way.
1646 assert_eq!(
1647 lower(&mut names, &func),
1648 "mfunc @f {\nblock0:\n %0:xmm($xmm0) = x64.arg_val_f64\n \
1649 %1:xmm($xmm1) = x64.arg_val_f64\n x64.ret_val_f64 %0($xmm0)\n \
1650 x64.ret_val2_f64 %1($xmm1)\n}\n"
1651 );
1652 }
1653
1654 /// A function whose answer goes back through memory, with the pointer to the space for it in
1655 /// front of whatever else it takes. Only the signature says it is one.
1656 fn returning_through_memory(params: &[Type]) -> (Interner, Func, Block, Vec<Value>) {
1657 let mut names = Interner::new();
1658 let sret = Abi::Sret { size: 32, align: 8 };
1659 let mut signature = Signature::new().and_param(Param::with_abi(Type::PTR, sret));
1660 signature.params.extend(params.iter().copied().map(Param::new));
1661 let mut func = Func::new(names.intern("f"), signature);
1662 let block = func.create_block();
1663 let space = func.append_param(block, Type::PTR);
1664 let values = std::iter::once(space)
1665 .chain(params.iter().map(|&ty| func.append_param(block, ty)))
1666 .collect();
1667 (names, func, block, values)
1668 }
1669
1670 #[test]
1671 fn the_space_a_return_through_memory_was_given_goes_back_in_the_first_return_register() {
1672 let (mut names, mut func, block, _) = returning_through_memory(&[]);
1673 Builder::new(&mut func, block).ret(&[]);
1674
1675 // `struct big f(void)`, where `big` is too large to come back in registers. The `return`
1676 // carries nothing, because the value went into the space the caller handed over, and the
1677 // document still says that address comes back in `rax`. Nothing in the IR says it, so the
1678 // convention says it, and the pseudo is the one any other pointer return would use.
1679 assert_eq!(
1680 lower(&mut names, &func),
1681 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_64\n \
1682 x64.ret_val_64 %0($rax)\n}\n"
1683 );
1684 }
1685
1686 #[test]
1687 fn what_the_function_did_in_between_does_not_take_the_register_off_it() {
1688 let (mut names, mut func, block, args) = returning_through_memory(&[Type::int(32)]);
1689 let mut build = Builder::new(&mut func, block);
1690 build.store(args[1], args[0], plain(), Flags::default());
1691 build.ret(&[]);
1692
1693 // The register is a read at the end and not a move at the start, so it is live across
1694 // everything between the two and the allocator has to keep it somewhere. In a function
1695 // with a call in it that somewhere is a callee saved register, and the address comes back
1696 // into `rax` here rather than whatever the last instruction happened to leave there. That
1697 // is issue #333, and a store is enough to show the value outlives the entry block.
1698 let text = lower(&mut names, &func);
1699 assert!(text.contains("x64.mov_mr_32 %1, [%0]"), "{text}");
1700 assert!(text.ends_with(" x64.ret_val_64 %0($rax)\n}\n"), "{text}");
1701 }
1702
1703 #[test]
1704 fn a_pointer_that_is_only_a_pointer_is_not_given_back() {
1705 let (mut names, mut func, block, args) = blank(&[Type::PTR]);
1706 let mut build = Builder::new(&mut func, block);
1707 build.store(args[0], args[0], plain(), Flags::default());
1708 build.ret(&[]);
1709
1710 // `void f(void **p)`. It takes a pointer first and returns nothing, which is the shape of
1711 // the one above and none of its meaning, and what tells them apart is the signature. A
1712 // `void` function leaves `rax` alone.
1713 assert!(!lower(&mut names, &func).contains("ret_val"));
1714 }
1715
1716 #[test]
1717 fn a_return_of_a_constant_puts_it_in_a_register_first() {
1718 let (mut names, mut func, block, _) = blank(&[]);
1719 let mut build = Builder::new(&mut func, block);
1720 let zero = build.iconst(Type::int(32), 0);
1721 build.ret(&[zero]);
1722
1723 // No rule returns an immediate, so the plan that offers one is turned down and the next
1724 // one materializes it. That is `int main(void) { return 0; }` in full, once the epilogue
1725 // is appended to it.
1726 assert_eq!(
1727 lower(&mut names, &func),
1728 "mfunc @f {\nblock0:\n %0:gpr = x64.mov_ri_32 0\n x64.ret_val_32 %0($rax)\n}\n"
1729 );
1730 }
1731
1732 #[test]
1733 fn the_rule_that_writes_a_constant_down_is_recorded_as_a_rule_that_fired() {
1734 let (mut names, mut func, block, _) = blank(&[]);
1735 let mut build = Builder::new(&mut func, block);
1736 let zero = build.iconst(Type::int(32), 0);
1737 build.ret(&[zero]);
1738
1739 // The loop over the instructions passes a constant by, because a constant is written where
1740 // a register for it is first wanted rather than where the IR put it. So the only place a
1741 // rule about one is ever selected is the materialization, and a mark made in the loop
1742 // alone would report every rule about a constant as a rule nothing reaches.
1743 let out = super::func(&func, &mut names, &SYSV).expect("every instruction has a rule");
1744 let rules = &crate::select::x86_64::TABLE.rules;
1745 let fired: Vec<&str> = rules
1746 .iter()
1747 .enumerate()
1748 .filter(|(index, _)| out.fired.has(*index))
1749 .map(|(_, rule)| rule.pattern)
1750 .collect();
1751 assert!(fired.contains(&"(iconst.i32 k)"), "{fired:?}");
1752 }
1753
1754 #[test]
1755 fn a_return_of_nothing_is_no_instruction_at_all() {
1756 let (mut names, mut func, block, _) = blank(&[]);
1757 let mut build = Builder::new(&mut func, block);
1758 build.ret(&[]);
1759
1760 // Every part of leaving a function that returns nothing is the epilogue's, and the
1761 // epilogue goes in after allocation. A block with nothing in it is the right answer here
1762 // rather than a function that could not be lowered.
1763 assert_eq!(lower(&mut names, &func), "mfunc @f {\nblock0:\n}\n");
1764 }
1765
1766 #[test]
1767 fn the_allocator_is_what_moves_the_answer_into_the_return_register() {
1768 let (mut names, mut source, block, _) = blank(&[]);
1769 let mut build = Builder::new(&mut source, block);
1770 let zero = build.iconst(Type::int(32), 0);
1771 build.ret(&[zero]);
1772
1773 let mut out = func(&source, &mut names, &SYSV).expect("every instruction has a rule").func;
1774 let env = env();
1775 let allocation = rucc_regalloc::run(&mut out, &env);
1776 let frame = Frame::of(&out, &allocation, &Layout::new(&SYSV, REGS));
1777 finish(&mut out, &allocation, &frame, &Stack::default(), &SYSV, &FRAME, &mut names);
1778
1779 // `int main(void) { return 0; }` end to end. Nothing here asked for `rax`: the rule said
1780 // the value goes back, the target said where, and the allocator is what made it true. The
1781 // epilogue is what leaves, and this function needs no frame, so it is the return alone.
1782 //
1783 // Two instructions and no copy, which is what a hint buys. The return insists on `rax`,
1784 // so `rax` is the register the allocator tries first for the value the return reads, and
1785 // the constant is written straight into it.
1786 assert_eq!(
1787 mir::print_func(&out, &names, ®S),
1788 "mfunc @f {\nblock0:\n $rax = x64.mov_ri_32 0\n \
1789 x64.ret_val_32 $rax($rax)\n x64.ret\n}\n"
1790 );
1791 }
1792
1793 #[test]
1794 fn a_function_of_two_arguments_is_a_whole_function_now() {
1795 let i32 = Type::int(32);
1796 let (mut names, mut source, block, args) = blank(&[i32, i32]);
1797 let mut build = Builder::new(&mut source, block);
1798 let sum = build.binary(Opcode::Add, args[0], args[1], Flags::default());
1799 build.ret(&[sum]);
1800
1801 let mut out = func(&source, &mut names, &SYSV).expect("every instruction has a rule").func;
1802 let env = env();
1803 let allocation = rucc_regalloc::run(&mut out, &env);
1804 let frame = Frame::of(&out, &allocation, &Layout::new(&SYSV, REGS));
1805 finish(&mut out, &allocation, &frame, &Stack::default(), &SYSV, &FRAME, &mut names);
1806
1807 // `int f(int a, int b) { return a + b; }` end to end, and this is the test the argument
1808 // side exists for. Before it there was no way to write one: the allocator refuses a
1809 // function whose entry block takes parameters, because there is no edge into an entry
1810 // block for the moves that give a block parameter its value to go on.
1811 //
1812 // One move, and it is the one the machine's addition needs rather than one the allocator
1813 // owes anybody. Each argument stays in the register it arrived in, because the pseudo
1814 // that defines it insists on that register and the allocator now tries it first, and the
1815 // sum stays in the register the addition wrote it to until the return reads it out. The
1816 // copy in front of a two address instruction is what makes its destination one of the
1817 // registers it reads, and the source operand keeps its own name because the destination
1818 // is what the encoder writes.
1819 assert_eq!(
1820 mir::print_func(&out, &names, ®S),
1821 "mfunc @f {\nblock0:\n $rdi($rdi) = x64.arg_val_32\n \
1822 $rsi($rsi) = x64.arg_val_32\n \
1823 $rdi(reuse 1) = x64.add_rr_32 $rdi, $rsi\n $rax = x64.mov_rr_64 $rdi\n \
1824 x64.ret_val_32 $rax($rax)\n x64.ret\n}\n"
1825 );
1826 }
1827
1828 #[test]
1829 fn an_argument_with_no_register_left_for_it_is_read_out_of_the_caller_s_stack() {
1830 let i64 = Type::int(64);
1831 let (mut names, mut source, block, args) = blank(&[i64; 7]);
1832 let mut build = Builder::new(&mut source, block);
1833 build.ret(&[args[6]]);
1834
1835 let lowered = func(&source, &mut names, &SYSV).expect("the seventh is read from memory");
1836
1837 // SysV passes six integers in registers and the seventh in the caller's memory, so six of
1838 // these are pseudos that encode to nothing and the seventh is a load that encodes to real
1839 // bytes. Its displacement is nothing here for the reason a local's is: there is no frame
1840 // yet. What the walk hands on is which instruction is waiting, and for how far up the
1841 // caller's argument area, which is the bottom of it because it is the first one there.
1842 assert_eq!(lowered.stack.arguments.len(), 1);
1843 assert_eq!(lowered.stack.arguments[0].1, 0);
1844 let text = mir::print_func(&lowered.func, &names, ®S);
1845 assert!(text.contains("%6:gpr = x64.mov_rm_64 [$rsp]"), "{text}");
1846 assert_eq!(text.matches("x64.arg_val_64").count(), 6, "{text}");
1847 }
1848
1849 #[test]
1850 fn the_frame_is_what_says_how_far_up_the_caller_s_stack_an_argument_is() {
1851 let i64 = Type::int(64);
1852 let (mut names, mut source, block, args) = blank(&[i64; 8]);
1853 let mut build = Builder::new(&mut source, block);
1854 let sum = build.binary(Opcode::Add, args[6], args[7], Flags::default());
1855 build.ret(&[sum]);
1856
1857 let lowered = func(&source, &mut names, &SYSV).expect("both are read from memory");
1858 let stack = lowered.stack;
1859 let mut out = lowered.func;
1860 let env = env();
1861 let allocation = rucc_regalloc::run(&mut out, &env);
1862 let layout = stack.layout(Layout::new(&SYSV, REGS));
1863 let frame = Frame::of(&out, &allocation, &layout);
1864 finish(&mut out, &allocation, &frame, &stack, &SYSV, &FRAME, &mut names);
1865
1866 // A leaf that takes no frame, so the stack pointer never moves and the only thing between
1867 // it and the caller's arguments is the return address the call pushed. The seventh
1868 // parameter is at the bottom of the caller's argument area and the eighth is one word
1869 // further up, which is the eight bytes between the two offsets.
1870 let text = mir::print_func(&out, &names, ®S);
1871 assert_eq!(frame.size(), 0);
1872 assert_eq!(frame.incoming(), Incoming::from_stack(8));
1873 assert!(text.contains("x64.mov_rm_64 [$rsp + 8]"), "{text}");
1874 assert!(text.contains("x64.mov_rm_64 [$rsp + 16]"), "{text}");
1875 }
1876
1877 #[test]
1878 fn a_realigned_frame_reaches_the_caller_s_arguments_through_the_frame_pointer() {
1879 let i64 = Type::int(64);
1880 let (mut names, mut source, block, args) = blank(&[i64; 7]);
1881 let wide = slot(&mut source, block, 64, 32);
1882 let mut build = Builder::new(&mut source, block);
1883 build.store(args[6], wide, plain(), Flags::default());
1884 build.ret(&[args[6]]);
1885
1886 let lowered = func(&source, &mut names, &SYSV).expect("every instruction has a rule");
1887 let stack = lowered.stack;
1888 let mut out = lowered.func;
1889 let env = env();
1890 let allocation = rucc_regalloc::run(&mut out, &env);
1891 let layout = stack.layout(Layout::new(&SYSV, REGS));
1892 let frame = Frame::of(&out, &allocation, &layout);
1893 finish(&mut out, &allocation, &frame, &stack, &SYSV, &FRAME, &mut names);
1894
1895 // A local wanting thirty two byte alignment makes the prologue force the stack pointer,
1896 // which throws away how far the caller's stack was. So the load the lowering wrote off the
1897 // stack pointer is rewritten to read through the frame pointer, at the one distance that
1898 // survives: the word the prologue pushed the frame pointer into, and the return address
1899 // above it.
1900 let text = mir::print_func(&out, &names, ®S);
1901 assert_eq!(frame.realign(), Some(32));
1902 assert_eq!(frame.incoming(), Incoming::from_frame(16));
1903 assert!(text.contains("x64.mov_rm_64 [$rbp + 16]"), "{text}");
1904 assert!(!text.contains("x64.mov_rm_64 [$rsp"), "{text}");
1905 }
1906
1907 #[test]
1908 fn a_jump_is_the_edge_and_nothing_else() {
1909 let i32 = Type::int(32);
1910 let (mut names, mut source, entry, args) = blank(&[i32]);
1911 let next = source.create_block();
1912 let got = source.append_param(next, i32);
1913 Builder::new(&mut source, entry).jump(next, &[args[0]]);
1914 Builder::new(&mut source, next).ret(&[got]);
1915
1916 // Two blocks and two instructions, and the jump is neither of them. What it was is the
1917 // arm on the first block, and what the arm carries is the argument it was called with.
1918 assert_eq!(
1919 lower(&mut names, &source),
1920 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_32 block1(%0)\n\n\
1921 block1(%1:gpr):\n x64.ret_val_32 %1($rax)\n}\n"
1922 );
1923 }
1924
1925 /// A constant is written where it is wanted rather than where the IR defined it, and two
1926 /// blocks wanting the same one is two places. Writing it once and reading it in both is a
1927 /// register read where nothing wrote it, unless the block it was written in happens to
1928 /// dominate the other, which nothing here checks and which the second arm of a branch never
1929 /// does. Each block gets its own copy of the number instead.
1930 #[test]
1931 fn a_constant_two_blocks_want_is_written_in_both_of_them() {
1932 let i32 = Type::int(32);
1933 let (mut names, mut source, entry, args) = blank(&[i32, i32]);
1934 let then = source.create_block();
1935 let other = source.create_block();
1936 let join = source.create_block();
1937 let got = source.append_param(join, i32);
1938
1939 let mut build = Builder::new(&mut source, entry);
1940 let seven = build.iconst(i32, 7);
1941 let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
1942 build.br_if(cond, then, &[], other, &[]);
1943 // Both arms want the seven in a register, because a block argument is never an immediate,
1944 // and neither arm dominates the other.
1945 Builder::new(&mut source, then).jump(join, &[seven]);
1946 Builder::new(&mut source, other).jump(join, &[seven]);
1947 Builder::new(&mut source, join).ret(&[got]);
1948
1949 let text = lower(&mut names, &source);
1950 assert_eq!(text.matches("x64.mov_ri_32 7").count(), 2, "one seven per block: {text}");
1951 }
1952
1953 /// An argument on an edge out of a block that leaves two ways is read after every instruction
1954 /// of the block is written, and reading one can write an instruction, which would land after
1955 /// the branch that has already jumped past it. The branch goes back on the end.
1956 #[test]
1957 fn a_constant_an_edge_wants_is_written_before_the_branch_and_not_after_it() {
1958 let i32 = Type::int(32);
1959 let (mut names, mut source, entry, args) = blank(&[i32, i32]);
1960 let then = source.create_block();
1961 let join = source.create_block();
1962 let got = source.append_param(join, i32);
1963
1964 let mut build = Builder::new(&mut source, entry);
1965 let nine = build.iconst(i32, 9);
1966 let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
1967 build.br_if(cond, then, &[], join, &[nine]);
1968 Builder::new(&mut source, then).jump(join, &[args[0]]);
1969 Builder::new(&mut source, join).ret(&[got]);
1970
1971 let out = func(&source, &mut names, &SYSV).expect("every instruction has a rule").func;
1972 let entry = out.entry().expect("an entry block");
1973 let last = out.terminator(entry).expect("a block that leaves two ways has a branch");
1974 let branch = names.intern("x64.br_cond_8");
1975 assert_eq!(
1976 out[last].opcode,
1977 mir::Opcode::new(branch),
1978 "the branch is last: {}",
1979 mir::print_func(&out, &names, ®S)
1980 );
1981 }
1982
1983 #[test]
1984 fn a_conditional_branch_is_lowered_to_the_condition_and_nothing_about_where_it_goes() {
1985 let i32 = Type::int(32);
1986 let (mut names, mut source, entry, args) = blank(&[i32, i32]);
1987 let then = source.create_block();
1988 let other = source.create_block();
1989 let mut build = Builder::new(&mut source, entry);
1990 let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
1991 build.br_if(cond, then, &[], other, &[]);
1992 Builder::new(&mut source, then).ret(&[args[0]]);
1993 Builder::new(&mut source, other).ret(&[args[1]]);
1994
1995 // The comparison writes a byte and the branch reads it, and neither says a block. Both
1996 // arms are on the entry block, in the order the branch took them, so the arm that runs
1997 // when the condition holds is the first.
1998 assert_eq!(
1999 lower(&mut names, &source),
2000 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_32\n \
2001 %1:gpr($rsi) = x64.arg_val_32\n %2:gpr = x64.cmp_set_l_32 %0, %1\n \
2002 x64.br_cond_8 %2, block1, block2\n\n\
2003 block1:\n x64.ret_val_32 %0($rax)\n\n\
2004 block2:\n x64.ret_val_32 %1($rax)\n}\n"
2005 );
2006 }
2007
2008 #[test]
2009 fn a_branch_over_a_block_is_a_whole_function_now() {
2010 let i32 = Type::int(32);
2011 let (mut names, mut source, entry, args) = blank(&[i32, i32]);
2012 let then = source.create_block();
2013 let other = source.create_block();
2014 let join = source.create_block();
2015 let got = source.append_param(join, i32);
2016 let mut build = Builder::new(&mut source, entry);
2017 let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
2018 build.br_if(cond, then, &[], other, &[]);
2019 let mut build = Builder::new(&mut source, then);
2020 let sum = build.binary(Opcode::Add, args[0], args[1], Flags::default());
2021 build.jump(join, &[sum]);
2022 Builder::new(&mut source, other).jump(join, &[args[1]]);
2023 Builder::new(&mut source, join).ret(&[got]);
2024
2025 // `int f(int a, int b) { if (a < b) return a + b; else return b; }` end to end, written
2026 // the way a front end writes it: both arms of the branch are blocks of their own and the
2027 // return is the block they meet at. No edge here is critical, because the two arms out of
2028 // the entry carry nothing and the two arms into the join each leave a block that goes
2029 // nowhere else, so each has its own end to put its move at.
2030 let mut out = func(&source, &mut names, &SYSV).expect("every instruction has a rule").func;
2031 assert_eq!(crate::split::critical(&mut out), 0, "no edge here is critical");
2032 let env = env();
2033 let allocation = rucc_regalloc::run(&mut out, &env);
2034 let frame = Frame::of(&out, &allocation, &Layout::new(&SYSV, REGS));
2035 finish(&mut out, &allocation, &frame, &Stack::default(), &SYSV, &FRAME, &mut names);
2036
2037 // One epilogue, on the join, which is the one block the function leaves from, and the
2038 // moves that give the join its parameter are at the end of each arm. Every register is
2039 // physical and the branch is still a branch on a register, because turning it into a
2040 // `test` and a `jcc` is the block layout's and there is no block layout yet.
2041 let text = mir::print_func(&out, &names, ®S);
2042 assert_eq!(text.matches("x64.ret\n").count(), 1, "{text}");
2043 assert!(text.contains("x64.br_cond_8"), "{text}");
2044 assert!(text.contains("x64.add_rr_32"), "{text}");
2045 assert!(!text.contains('%'), "{text}");
2046 }
2047
2048 #[test]
2049 fn a_critical_edge_is_split_before_the_allocator_ever_sees_it() {
2050 let i32 = Type::int(32);
2051 let (mut names, mut source, entry, args) = blank(&[i32, i32]);
2052 let then = source.create_block();
2053 let join = source.create_block();
2054 let got = source.append_param(join, i32);
2055 let mut build = Builder::new(&mut source, entry);
2056 let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
2057 build.br_if(cond, then, &[], join, &[args[1]]);
2058 Builder::new(&mut source, then).jump(join, &[args[0]]);
2059 let mut build = Builder::new(&mut source, join);
2060 let twice = build.binary(Opcode::Add, got, got, Flags::default());
2061 build.ret(&[twice]);
2062
2063 // The else arm is critical: the entry block leaves two ways and the join is arrived at
2064 // two ways, and the arm carries a value. Without splitting it the allocator asserts,
2065 // because the move that gives the join its parameter would have to run at the end of a
2066 // block that also goes to the other arm.
2067 let mut out = func(&source, &mut names, &SYSV).expect("every instruction has a rule").func;
2068 assert_eq!(crate::split::critical(&mut out), 1);
2069 let env = env();
2070 let allocation = rucc_regalloc::run(&mut out, &env);
2071 let frame = Frame::of(&out, &allocation, &Layout::new(&SYSV, REGS));
2072 finish(&mut out, &allocation, &frame, &Stack::default(), &SYSV, &FRAME, &mut names);
2073
2074 // The block the split added is where the move went, and it is the whole of that block.
2075 let text = mir::print_func(&out, &names, ®S);
2076 assert_eq!(out.block_count(), 4, "{text}");
2077 assert_eq!(text.matches("x64.ret\n").count(), 1, "{text}");
2078 }
2079
2080 #[test]
2081 fn a_call_passes_what_the_convention_says_and_takes_back_what_it_says() {
2082 let i32 = Type::int(32);
2083 let (mut names, mut source, block, args) = blank(&[i32, i32]);
2084 let sig =
2085 source.add_signature(Signature::new().with_params(&[i32, i32]).with_returns(&[i32]));
2086 let callee = names.intern("g");
2087 let call = Builder::new(&mut source, block).call(callee, sig, &[args[0], args[1]]);
2088 let got = source[call].first_result.expect("an integer comes back");
2089 Builder::new(&mut source, block).ret(&[got]);
2090
2091 // `int f(int a, int b) { return g(a, b); }`. The arguments arrived where the call wants
2092 // them, so what the call reads is what arrived, and the whole of the convention is in the
2093 // constraints rather than in a move.
2094 let text = lower(&mut names, &source);
2095 assert!(text.contains("= x64.call %0($rdi), %1($rsi), @g"), "{text}");
2096 assert!(text.contains("x64.ret_val_32 %2($rax)"), "{text}");
2097 // What the call writes is the value that comes back and then every register the callee is
2098 // free to destroy, in both classes, which is the whole of what stops the allocator from
2099 // leaving something in one of them.
2100 assert!(text.contains("%2:gpr($rax), $rcx, $rdx, $r8, $r9, $r10, $r11, $xmm0,"), "{text}");
2101 assert!(text.contains("$xmm15 = x64.call"), "{text}");
2102 }
2103
2104 #[test]
2105 fn what_the_frame_owes_a_call_comes_back_with_the_function() {
2106 let i32 = Type::int(32);
2107 let sig = |source: &mut Func| source.add_signature(Signature::new().with_params(&[i32]));
2108
2109 let (mut names, mut source, block, args) = blank(&[i32]);
2110 let sig = sig(&mut source);
2111 let callee = names.intern("g");
2112 Builder::new(&mut source, block).call(callee, sig, &[args[0]]);
2113 let out = func(&source, &mut names, &SYSV).expect("every instruction has a rule");
2114
2115 // Nothing on the stack, so nothing owed, but not a leaf either: a function that calls
2116 // owes the callee an aligned stack pointer and may not use the red zone.
2117 assert_eq!(out.stack.calls, Some(0));
2118 let layout = out.stack.layout(Layout::new(&SYSV, REGS));
2119 assert!(!layout.leaf);
2120 assert_eq!(layout.outgoing, 0);
2121
2122 // The same call under the other convention owes thirty two bytes for the callee to spill
2123 // its register arguments into, which is a fact about the convention and not about the call.
2124 let out = func(&source, &mut names, &x86_64::WIN64).expect("every instruction has a rule");
2125 assert_eq!(out.stack.calls, Some(32));
2126
2127 // And a function that calls nothing is a leaf, which is what says it may use the red zone.
2128 let (mut names, mut source, block, args) = blank(&[i32]);
2129 Builder::new(&mut source, block).ret(&[args[0]]);
2130 let out = func(&source, &mut names, &SYSV).expect("every instruction has a rule");
2131 assert_eq!(out.stack.calls, None);
2132 assert!(out.stack.layout(Layout::new(&SYSV, REGS)).leaf);
2133 }
2134
2135 #[test]
2136 fn a_value_that_outlives_a_call_is_not_left_where_the_call_destroys_it() {
2137 let i32 = Type::int(32);
2138 let (mut names, mut source, block, args) = blank(&[i32]);
2139 let sig = source.add_signature(Signature::new().with_params(&[i32]).with_returns(&[i32]));
2140 let callee = names.intern("g");
2141 let call = Builder::new(&mut source, block).call(callee, sig, &[args[0]]);
2142 let got = source[call].first_result.expect("an integer comes back");
2143 let mut build = Builder::new(&mut source, block);
2144 let sum = build.binary(Opcode::Add, got, args[0], Flags::default());
2145 build.ret(&[sum]);
2146
2147 // `int f(int a) { return g(a) + a; }`, which is the smallest program that asks the
2148 // question: `a` is read after the call and `rdi` is a register the call destroys.
2149 let lowered = func(&source, &mut names, &SYSV).expect("every instruction has a rule");
2150 let layout = lowered.stack.layout(Layout::new(&SYSV, REGS));
2151 let mut out = lowered.func;
2152 let env = env();
2153 let allocation = rucc_regalloc::run(&mut out, &env);
2154 let frame = Frame::of(&out, &allocation, &layout);
2155 finish(&mut out, &allocation, &frame, &Stack::default(), &SYSV, &FRAME, &mut names);
2156
2157 // It went to a register the callee has to put back, and the prologue and epilogue are what
2158 // put it back, which is the whole bargain the two halves of a convention make.
2159 let text = mir::print_func(&out, &names, ®S);
2160 assert!(text.contains("$rbx"), "{text}");
2161 assert!(!text.contains('%'), "{text}");
2162 assert_eq!(text.matches("x64.call").count(), 1, "{text}");
2163 }
2164
2165 #[test]
2166 fn a_call_with_more_arguments_than_registers_writes_the_rest_into_the_outgoing_area() {
2167 let i64 = Type::int(64);
2168 let (mut names, mut source, block, args) = blank(&[i64]);
2169 let seven = vec![i64; 7];
2170 let sig = source.add_signature(Signature::new().with_params(&seven));
2171 let callee = names.intern("g");
2172 let passed = vec![args[0]; 7];
2173 Builder::new(&mut source, block).call(callee, sig, &passed);
2174
2175 let lowered = func(&source, &mut names, &SYSV).expect("the seventh goes to memory");
2176 // The bytes the call needs are on the layout the frame is worked out from, so that the
2177 // frame reserves as many as the widest call in the function asked for.
2178 assert_eq!(lowered.stack.calls, Some(8));
2179 let text = mir::print_func(&lowered.func, &names, ®S);
2180 assert!(text.contains("x64.mov_mr_64 %0, [$rsp]\n"), "{text}");
2181 }
2182
2183 #[test]
2184 fn a_call_this_cannot_make_is_reported_rather_than_made() {
2185 let (mut names, mut source, block, _) = blank(&[]);
2186 let sig = source
2187 .add_signature(Signature::new().with_returns(&[Type::float(rucc_ir::Float::F80)]));
2188 let callee = names.intern("g");
2189 Builder::new(&mut source, block).call(callee, sig, &[]);
2190 let failed = func(&source, &mut names, &SYSV).expect_err("a long double is on the x87");
2191 assert_eq!(failed.to_string(), "what this call gives back is on the x87 stack");
2192 }
2193
2194 #[test]
2195 fn a_call_through_an_address_goes_through_the_register_the_address_is_in() {
2196 let i32 = Type::int(32);
2197 let (mut names, mut source, block, args) = blank(&[Type::PTR, i32]);
2198 let sig = source.add_signature(Signature::new().with_params(&[i32]).with_returns(&[i32]));
2199 let varargs = source.push_abis(&[]);
2200 let info = source.add_call(CallInfo { callee: None, signature: sig, varargs });
2201 let mut build = Builder::new(&mut source, block);
2202 let inst = InstData {
2203 args: build.func().push_values(&[args[0], args[1]]),
2204 extra: Extra::Call(info),
2205 ..InstData::new(Opcode::CallIndirect)
2206 };
2207 let called = build.inst(inst, &[i32]);
2208 let got = source[called].first_result.expect("an integer comes back");
2209 Builder::new(&mut source, block).ret(&[got]);
2210
2211 // `int f(int (*g)(int), int a) { return g(a); }`. The first operand is the address and
2212 // the arguments are the ones behind it, and everything else about the call is what a call
2213 // to a name would have been.
2214 let text = lower(&mut names, &source);
2215 assert!(text.contains("= x64.call_reg %0, %1($rdi)"), "{text}");
2216 assert!(text.contains("x64.ret_val_32 %2($rax)"), "{text}");
2217 assert!(!text.contains("@g"), "a call through an address names nobody: {text}");
2218 }
2219
2220 #[test]
2221 fn an_instruction_no_rule_covers_is_reported() {
2222 let (mut names, mut source, block, args) = blank(&[Type::PTR]);
2223 let mut build = Builder::new(&mut source, block);
2224 let operands = build.func().push_values(&[args[0]]);
2225 build.inst(InstData { args: operands, ..InstData::new(Opcode::Prefetch) }, &[]);
2226
2227 // A hint about an address, which nothing writes an instruction for yet. Nothing about it
2228 // is a width or a register, so there is nothing for the message to add beyond the name.
2229 let failed = func(&source, &mut names, &SYSV).expect_err("no rule writes a prefetch");
2230 assert_eq!(failed.to_string(), "no rule lowers a `prefetch`");
2231
2232 // A `prefetch` produces nothing, so there is no type in the message and nothing invents
2233 // one, and the instruction comes back so a caller can ask the function where it was.
2234 let inst = failed.inst().expect("the instruction it is about");
2235 assert_eq!(source[inst].opcode, Opcode::Prefetch);
2236 }
2237
2238 /// A barrier is written by name here, and what it is depends on the ordering and on nothing
2239 /// else. `crate::expand` is where the reasoning about this machine's memory model lives.
2240 #[test]
2241 fn a_barrier_is_one_instruction_at_the_strongest_ordering_and_none_below_it() {
2242 for order in MemOrder::all().filter(|&order| order != MemOrder::NotAtomic) {
2243 let (mut names, mut source, block, _) = blank(&[]);
2244 let mut build = Builder::new(&mut source, block);
2245 build
2246 .inst(InstData { extra: Extra::Order(order), ..InstData::new(Opcode::Fence) }, &[]);
2247
2248 let text = lower(&mut names, &source);
2249 assert_eq!(text.contains("x64.mfence"), order == MemOrder::SeqCst, "{order:?}: {text}");
2250 }
2251 }
2252
2253 #[test]
2254 fn more_values_back_than_the_convention_has_registers_for_is_reported() {
2255 let i64 = Type::int(64);
2256 let (mut names, mut source, block, args) = blank(&[i64, i64, i64]);
2257 let mut build = Builder::new(&mut source, block);
2258 build.ret(&[args[0], args[1], args[2]]);
2259
2260 // Two integers come back in `rax` and `rdx` and a third has nowhere to go, which is not a
2261 // gap in the rules but the convention saying no. The front end classifies before it gets
2262 // here, so this is the shape that would mean the classification went wrong.
2263 let failed = func(&source, &mut names, &SYSV).expect_err("only two come back");
2264 assert_eq!(
2265 failed.to_string(),
2266 "what this function gives back takes more registers than this convention has for it"
2267 );
2268
2269 let inst = failed.inst().expect("the instruction it is about");
2270 assert_eq!(source[inst].opcode, Opcode::Return);
2271 }
2272
2273 /// A refusal about a signature has no instruction, which is what makes it the one arm apart.
2274 ///
2275 /// Everything else is about something written somewhere in the body and hands it back so a
2276 /// caller can ask the function where it came from. A parameter arrives before the first
2277 /// instruction runs, so there is nothing in the body to point at and the message is about
2278 /// the function.
2279 #[test]
2280 fn a_refusal_about_a_parameter_has_no_instruction_to_point_at() {
2281 let missing = Unsupported::Argument { index: 0, missing: Missing::OnX87 };
2282 assert_eq!(missing.inst(), None);
2283 }
2284
2285 /// An `alloca` of a fixed size, which is what every local whose address is taken becomes.
2286 fn slot(source: &mut Func, block: Block, size: u64, align: u32) -> Value {
2287 let info = MemInfo { size, align, ..plain() };
2288 let mut build = Builder::new(source, block);
2289 let mem = build.func().add_mem(info);
2290 build.value(InstData { extra: Extra::Mem(mem), ..InstData::new(Opcode::Alloca) }, Type::PTR)
2291 }
2292
2293 #[test]
2294 fn a_local_is_memory_in_the_frame_and_one_instruction_that_says_where() {
2295 let (mut names, mut source, block, _) = blank(&[]);
2296 let slot = slot(&mut source, block, 4, 4);
2297 let mut build = Builder::new(&mut source, block);
2298 let nine = build.iconst(Type::int(32), 9);
2299 build.store(nine, slot, plain(), Flags::default());
2300 let loaded = build.load(Type::int(32), slot, plain(), Flags::default());
2301 build.ret(&[loaded]);
2302
2303 let lowered = func(&source, &mut names, &SYSV).expect("every instruction has a rule");
2304
2305 // Four bytes on the list the frame is laid out from, and the one instruction that reads
2306 // where they went. Its displacement is nothing here because there is no frame yet, and
2307 // which instruction is waiting for which local is what `finish` is handed.
2308 assert_eq!(lowered.stack.locals, vec![Local { size: 4, align: 4 }]);
2309 assert_eq!(lowered.stack.addresses.len(), 1);
2310 assert_eq!(lowered.stack.addresses[0].1, 0);
2311 assert_eq!(
2312 mir::print_func(&lowered.func, &names, ®S),
2313 "mfunc @f {\nblock0:\n %0:gpr = x64.lea_64 [$rsp]\n \
2314 %1:gpr = x64.mov_ri_32 9\n x64.mov_mr_32 %1, [%0]\n \
2315 %2:gpr = x64.mov_rm_32 [%0]\n x64.ret_val_32 %2($rax)\n}\n"
2316 );
2317 }
2318
2319 #[test]
2320 fn the_frame_is_what_fills_the_address_of_a_local_in() {
2321 let (mut names, mut source, block, _) = blank(&[]);
2322 let slot = slot(&mut source, block, 4, 4);
2323 let mut build = Builder::new(&mut source, block);
2324 let nine = build.iconst(Type::int(32), 9);
2325 build.store(nine, slot, plain(), Flags::default());
2326 let loaded = build.load(Type::int(32), slot, plain(), Flags::default());
2327 build.ret(&[loaded]);
2328
2329 let lowered = func(&source, &mut names, &SYSV).expect("every instruction has a rule");
2330 let stack = lowered.stack;
2331 let mut out = lowered.func;
2332 let env = env();
2333 let allocation = rucc_regalloc::run(&mut out, &env);
2334 let layout = stack.layout(Layout::new(&SYSV, REGS));
2335 let frame = Frame::of(&out, &allocation, &layout);
2336 finish(&mut out, &allocation, &frame, &stack, &SYSV, &FRAME, &mut names);
2337
2338 // `int f(void) { int x; x = 9; return x; }` with the address of `x` taken, end to end.
2339 // A leaf small enough to live in the red zone takes no frame at all, so the stack pointer
2340 // never moves and the four bytes are below it, which is what the negative offset is. The
2341 // instruction the lowering left with nothing in its displacement now has the answer in it.
2342 let text = mir::print_func(&out, &names, ®S);
2343 assert!(text.contains("$rax = x64.lea_64 [$rsp - 8]"), "{text}");
2344 assert!(!text.contains("x64.sub_ri_64"), "{text}");
2345 assert_eq!(frame.size(), 0);
2346 assert_eq!(frame.local(0), Some(-8));
2347 }
2348
2349 #[test]
2350 fn a_stack_slot_whose_size_is_not_known_until_it_runs_is_reported() {
2351 let i64 = Type::int(64);
2352 let (mut names, mut source, block, args) = blank(&[i64]);
2353 let info = MemInfo { size: 0, align: 16, ..plain() };
2354 let mut build = Builder::new(&mut source, block);
2355 let mem = build.func().add_mem(info);
2356 let size = build.func().push_values(&[args[0]]);
2357 let slot = build.value(
2358 InstData { args: size, extra: Extra::Mem(mem), ..InstData::new(Opcode::Alloca) },
2359 Type::PTR,
2360 );
2361 Builder::new(&mut source, block).ret(&[slot]);
2362
2363 // A variable length array. Growing the stack where the declaration stands means moving the
2364 // stack pointer in the middle of the function and reaching everything else through a
2365 // frame pointer afterwards, and the frame here lays out neither.
2366 let failed = func(&source, &mut names, &SYSV).expect_err("nothing grows the stack");
2367 assert_eq!(failed.to_string(), "nothing here grows the stack for a variable length array");
2368 }
2369
2370 #[test]
2371 fn an_address_is_read_written_and_added_to_like_the_integer_it_is() {
2372 let (mut names, mut source, block, args) = blank(&[Type::PTR, Type::int(64)]);
2373 let mut build = Builder::new(&mut source, block);
2374 let stepped = build.func().push_values(&[args[0], args[1]]);
2375 let next =
2376 build.value(InstData { args: stepped, ..InstData::new(Opcode::PtrAdd) }, Type::PTR);
2377 let loaded = build.load(Type::int(32), next, plain(), Flags::default());
2378 build.ret(&[loaded]);
2379
2380 // `int f(int *p, long i) { return *(int *)((char *)p + i); }`. Nothing about this is new
2381 // in the rule set, which is the point: the two addresses arrive in registers because an
2382 // address is an integer as wide as one, and the arithmetic on them is the add it always
2383 // was, so every rule written about an add reaches it.
2384 //
2385 // The add stays its own instruction rather than folding into the address the load reads
2386 // from. Two registers with no scale on either is the one addressing mode the rules have no
2387 // load through, because the folds that exist are the displacement one and the scaled ones,
2388 // and this is neither. That is a peephole worth having and not a thing this changes.
2389 assert_eq!(
2390 lower(&mut names, &source),
2391 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_64\n \
2392 %1:gpr($rsi) = x64.arg_val_64\n %2:gpr(reuse 1) = x64.add_rr_64 %0, %1\n \
2393 %3:gpr = x64.mov_rm_32 [%2]\n x64.ret_val_32 %3($rax)\n}\n"
2394 );
2395 }
2396
2397 /// The address of a file scope name, which is what every use of a global and every string
2398 /// literal starts from.
2399 fn address_of(source: &mut Func, block: Block, names: &mut Interner, name: &str) -> Value {
2400 let symbol = names.intern(name);
2401 let mut build = Builder::new(source, block);
2402 build.value(
2403 InstData { extra: Extra::Symbol(symbol), ..InstData::new(Opcode::GlobalAddr) },
2404 Type::PTR,
2405 )
2406 }
2407
2408 #[test]
2409 fn the_address_of_a_name_is_one_instruction_carrying_the_name() {
2410 let (mut names, mut source, block, _) = blank(&[]);
2411 let counter = address_of(&mut source, block, &mut names, "counter");
2412 let mut build = Builder::new(&mut source, block);
2413 let loaded = build.load(Type::int(32), counter, plain(), Flags::default());
2414 build.ret(&[loaded]);
2415
2416 // `extern int counter; int f(void) { return counter; }`. The address is an addressing mode
2417 // that names no register and carries the symbol, which is what the assembler writes
2418 // relative to `%rip` and what the object writer leaves a relocation for.
2419 assert_eq!(
2420 lower(&mut names, &source),
2421 "mfunc @f {\nblock0:\n %0:gpr = x64.lea_64 [@counter]\n \
2422 %1:gpr = x64.mov_rm_32 [%0]\n x64.ret_val_32 %1($rax)\n}\n"
2423 );
2424 }
2425
2426 /// A cast between a pointer and an integer, at whatever width the result is asked for.
2427 fn cast(source: &mut Func, block: Block, opcode: Opcode, from: Value, to: Type) -> Value {
2428 let mut build = Builder::new(source, block);
2429 let args = build.func().push_values(&[from]);
2430 build.value(InstData { args, ..InstData::new(opcode) }, to)
2431 }
2432
2433 #[test]
2434 fn a_cast_between_a_pointer_and_an_integer_as_wide_is_no_instruction_at_all() {
2435 let (mut names, mut source, block, args) = blank(&[Type::PTR]);
2436 let number = cast(&mut source, block, Opcode::PtrToInt, args[0], Type::int(64));
2437 Builder::new(&mut source, block).ret(&[number]);
2438
2439 // `long f(void *p) { return (long)p; }`. An address on this machine is an integer as wide
2440 // as the machine addresses, so the cast changes what the type system calls the value and
2441 // changes nothing about the value, and the register holding it is the one that held it.
2442 assert_eq!(
2443 lower(&mut names, &source),
2444 "mfunc @f {\nblock0:\n %0:gpr($rdi) = x64.arg_val_64\n \
2445 x64.ret_val_64 %0($rax)\n}\n"
2446 );
2447 }
2448
2449 #[test]
2450 fn a_null_pointer_is_a_constant_that_reaches_a_register_before_anything_reads_it() {
2451 let (mut names, mut source, block, _) = blank(&[]);
2452 let mut build = Builder::new(&mut source, block);
2453 let zero = build.iconst(Type::int(64), 0);
2454 let null = cast(&mut source, block, Opcode::IntToPtr, zero, Type::PTR);
2455 Builder::new(&mut source, block).ret(&[null]);
2456
2457 // `void *f(void) { return 0; }`. The cast is nothing, and reading its operand is what
2458 // writes the zero down: a constant is materialized where it is wanted rather than where
2459 // the IR defined it, and without the read there would be no instruction at all.
2460 assert_eq!(
2461 lower(&mut names, &source),
2462 "mfunc @f {\nblock0:\n %0:gpr = x64.mov_ri_64 0\n x64.ret_val_64 %0($rax)\n}\n"
2463 );
2464 }
2465
2466 #[test]
2467 fn a_cast_between_a_pointer_and_a_narrower_integer_is_reported() {
2468 let (mut names, mut source, block, args) = blank(&[Type::PTR]);
2469 let number = cast(&mut source, block, Opcode::PtrToInt, args[0], Type::int(32));
2470 Builder::new(&mut source, block).ret(&[number]);
2471
2472 // The front end never writes one: it casts at the address width and truncates or extends
2473 // around it, so both of those are the rules they always were. IR from somewhere else that
2474 // does write one is refused rather than compiled to a move that keeps the high half.
2475 let failed = func(&source, &mut names, &SYSV).expect_err("no rule narrows an address");
2476 assert_eq!(failed.to_string(), "no rule lowers a `ptrtoint` producing a `i32`");
2477 }
2478}