rucc_codegen/pipeline.rs
1//! One IR function to one machine function, which is every pass in this crate in order.
2//!
3//! Design: `spec/10-backend.md` section 10.1, which is where the order comes from.
4//!
5//! Each pass here is written and tested on its own and each is useful on its own, but there is
6//! exactly one order they run in and until now that order lived in the tests. A caller outside
7//! this crate would have had to know that splitting critical edges comes after lowering and
8//! before allocation, that the frame is worked out after allocation because the spill slots are
9//! the largest thing in it, and that the prologue is written after the frame. None of that is a
10//! decision a driver should be making, so it is written down once, here.
11//!
12//! # What comes out
13//!
14//! A function whose every register is physical, whose every offset into the frame is a constant,
15//! and whose blocks are in the order they run in with the jumps that order needs. That is the
16//! point at which a function is one an encoder could read, and there is nothing left in it that
17//! is not an instruction of the machine it was compiled for.
18//!
19//! # What is still missing from the middle
20//!
21//! The optimizing path, all of it. What runs here is `spec/10-backend.md` section 10.3's fast
22//! path: one rule per term, a linear scan, and a block order from the shape of the CFG rather
23//! than from block frequency. No scheduling, and the redundant moves a coalescer would take out
24//! are still in the output.
25
26use rucc_base::Interner;
27use rucc_cost::Goal;
28use rucc_ir as ir;
29use rucc_mir as mir;
30use rucc_regalloc::assign::Env;
31use rucc_target::{
32 BitInsts, BranchInsts, CallRegs, FlagInsts, FrameInsts, MachineInsts, PhysReg, RegFile,
33 ShortInsts, TargetInfo, TimingInsts, x86_64,
34};
35use rucc_tuple::Arch;
36
37use crate::bits;
38use crate::combine;
39use crate::compare;
40use crate::copies;
41use crate::coverage::Fired;
42use crate::elsewhere::Elsewhere;
43use crate::finish::{Convention, Padding, Probing, Protect, Tracing, finish};
44use crate::fold;
45use crate::frame::{self, Frame, Layout};
46use crate::kept;
47use crate::layout;
48use crate::lower::{self, Unsupported};
49use crate::lowering::{self, Lowerings};
50use crate::pressure::{Cost, Pressure};
51use crate::schedule;
52use crate::shorten;
53use crate::slots::{self, Slots};
54use crate::split;
55use crate::weights;
56
57/// Everything about a machine that compiling a function for it needs.
58///
59/// The fields are different kinds of fact and they come from different places: where the
60/// convention puts things, what registers the machine has, which instructions build a frame,
61/// which instructions a branch becomes, and which registers the allocator may hand out. The last
62/// one is not a target fact on its own, because holding a register back as scratch is a decision
63/// about the allocator rather than about the machine, which is why it is built here rather than
64/// in [`rucc_target`].
65#[derive(Debug)]
66pub struct Machine {
67 /// Where the convention this function is compiled for puts things.
68 pub conv: &'static CallRegs,
69 /// The registers the machine has, which is what says how wide a spill slot of a class is.
70 pub file: RegFile,
71 /// The instructions that take a frame and give it back.
72 pub insts: &'static FrameInsts,
73 /// The instructions a branch becomes once the blocks are in an order.
74 pub branch: &'static BranchInsts,
75 /// How much of a register each of the machine's instructions reads and writes.
76 pub bits: &'static BitInsts,
77 /// What each of the machine's instructions leaves in the condition state.
78 pub flags: &'static FlagInsts,
79 /// What shape each of the machine's instructions is, which is what a pass proposing a new one
80 /// has its proposal held against.
81 pub shapes: &'static MachineInsts,
82 /// How long each of the machine's instructions takes, and what it takes it on.
83 pub timing: &'static TimingInsts,
84 /// Which of the machine's instructions have a shorter spelling of the same answer.
85 pub short: &'static ShortInsts,
86 /// What the allocator may hand out, and what it holds back.
87 pub env: Env,
88}
89
90/// The scratch registers held back from the allocator on x86-64.
91///
92/// Two, because a move on an edge may have to break a cycle and a spilled value has to be read
93/// into something, and those can want a register at the same instruction. Two is also what nearly
94/// every instruction wants, including the one that looks larger: an instruction that reads two
95/// spilled values and writes a third sends the answer back into a register an operand arrived in
96/// rather than asking for one of its own, and `rewrite` says why that is allowed.
97///
98/// It is not two because two was enough to start with and nobody looked again. There is no third
99/// to hold back. A scratch register has to be one the convention passes nothing in, since the
100/// rewriter puts moves in wherever it likes, and one the callee does not owe back, since the
101/// rewriter runs after the prologue has been decided and cannot ask for a register to be saved. On
102/// SysV that is `r10`, `r11` and `rax`, and `rax` is not one to take: it is the return value, so
103/// holding it back costs a move at every return in the program, which is a price paid everywhere
104/// for a shape that turns up almost nowhere.
105///
106/// An instruction that wants a third is the indexed store with its base, its index and its value
107/// all on the stack, which is tamnd/rucc#913. `rewrite` answers that one by borrowing a register
108/// and putting back what was in it, which costs two memory accesses at the instruction that wanted
109/// it and nothing anywhere else.
110pub(crate) const SCRATCH: [PhysReg; 2] = [x86_64::R10, x86_64::R11];
111
112/// How many of each class are held back.
113const SCRATCH_COUNT: usize = SCRATCH.len();
114
115impl Machine {
116 /// The x86-64 machine under that convention.
117 ///
118 /// Both files are offered. A value the selector produces is in one or the other, which is
119 /// decided by its type: an integer and an address are general purpose and a `float` or a
120 /// `double` is in a vector register, and the allocator is given each file separately because
121 /// no move goes between them.
122 #[must_use]
123 pub fn x86_64(conv: &'static CallRegs) -> Self {
124 let order: Vec<PhysReg> =
125 conv.int_order.iter().copied().filter(|reg| !SCRATCH.contains(reg)).collect();
126 // The vector file wants its own two, for the same two jobs, and they have to be two the
127 // convention does not preserve: a scratch register is written by a move the rewriter puts
128 // in, which is after the prologue has already been decided, so one the callee owes back
129 // would be one nothing saved. That rules out the upper ten on Windows and nothing at all
130 // on SysV, and taking the last two that are left lands on `xmm14` and `xmm15` there and on
131 // `xmm4` and `xmm5` on Windows, neither of which any argument travels in.
132 let free: Vec<PhysReg> =
133 conv.sse_order.iter().copied().filter(|®| !conv.preserves_sse(reg)).collect();
134 let at = free.len().saturating_sub(SCRATCH_COUNT);
135 let sse_scratch: Vec<PhysReg> = free[at..].to_vec();
136 let sse_order: Vec<PhysReg> =
137 conv.sse_order.iter().copied().filter(|reg| !sse_scratch.contains(reg)).collect();
138 Self {
139 conv,
140 file: x86_64::REGS,
141 insts: &x86_64::FRAME,
142 branch: &x86_64::BRANCH,
143 bits: &x86_64::BITS,
144 flags: &x86_64::FLAGS,
145 shapes: &x86_64::MACHINE,
146 timing: &x86_64::TIMING,
147 short: &x86_64::SHORT,
148 env: Env::new().with(x86_64::GPR, &order, &SCRATCH).with(
149 x86_64::XMM,
150 &sse_order,
151 &sse_scratch,
152 ),
153 }
154 }
155
156 /// The machine a target describes, or `None` when no backend in this crate covers it.
157 ///
158 /// [`TargetInfo`] already carries the convention, because the front end needs it to lay a
159 /// `va_list` out, so the only thing this decides is which architecture's frame instructions
160 /// and register file go with it. AArch64 and RISC-V are `None` until M6 fills them in, and a
161 /// caller that gets one reports a target it cannot compile for rather than compiling wrongly.
162 #[must_use]
163 pub fn for_target(target: &TargetInfo) -> Option<Self> {
164 let conv = target.call_regs?;
165 match target.tuple.arch() {
166 Arch::X86_64 => Some(Self::x86_64(conv)),
167 _ => None,
168 }
169 }
170}
171
172/// Whether every function calls a profiler on the way in, and where that call goes.
173///
174/// What `-pg` asks for, with `-mfentry` and `-mno-fentry` choosing between the last two. The choice
175/// has already been made against the target by the time this is built, which is why there is no
176/// answer here for a command line that named neither.
177#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
178pub enum Profile {
179 /// It does not, which is what nearly every command line asks for.
180 #[default]
181 No,
182 /// In front of the prologue, which is the hook a tracer can replace while the program runs.
183 Early,
184 /// Once the frame is taken, which is the hook that reads the frame pointer.
185 Late,
186}
187
188/// How much room every function opens with for something to be written over it later.
189///
190/// What `-fpatchable-function-entry=` asks for, as the two halves a prologue deals in rather than
191/// as the total and the part the flag is written in. The room can be on either side of the
192/// function's own label and the two sides are not the same thing: what is after the label is inside
193/// the function, which is what a patcher redirecting a call into it wants, and what is in front of
194/// it is outside, which is where a patcher that needs a whole instruction it can reach from the
195/// first one puts it.
196#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
197pub struct Room {
198 /// How many bytes go after the function's own label.
199 pub after: u32,
200 /// How many go in front of it.
201 pub before: u32,
202}
203
204impl Room {
205 /// Whether any room at all was asked for, which is what decides whether a function gets one.
206 ///
207 /// `=0` is a command line that asked for none, and gcc takes it and writes nothing, so the
208 /// question is about the numbers rather than about whether the flag was written.
209 #[must_use]
210 pub const fn any(self) -> bool {
211 self.after > 0 || self.before > 0
212 }
213}
214
215/// What the command line says, as opposed to what the machine says.
216///
217/// Most of it is about a frame, which is what this held to begin with, and the rest is passes being
218/// asked for or turned off by name. [`Flags::goal`] is neither: it is the one thing here that no
219/// flag names on its own and that every pass below selection may read.
220#[derive(Debug, Clone, Copy, PartialEq, Eq)]
221pub struct Flags {
222 /// Whether every function keeps a frame pointer, which `-fno-omit-frame-pointer` asks for.
223 pub frame_pointer: bool,
224 /// Whether the red zone may be used, which `-mno-red-zone` and every kernel turns off.
225 pub red_zone: bool,
226 /// Whether a frame is taken a page at a time, which `-fstack-clash-protection` asks for.
227 pub stack_clash: bool,
228 /// Whether every address an indirect branch may arrive at opens with a landing pad, which
229 /// `-fcf-protection=branch` asks for. That is every function, and every label of a function
230 /// whose address the program took.
231 pub landing: bool,
232 /// Whether every function calls a profiler on the way in, which `-pg` asks for.
233 pub profile: Profile,
234 /// How much room every function opens with for a patcher, which
235 /// `-fpatchable-function-entry=` asks for. See [`Room`].
236 pub patch: Room,
237 /// Whether the blocks are put in the order the weights say rather than in the order the
238 /// shape of the graph says, which `-freorder-blocks` asks for and every level above `-O0`
239 /// turns on. See [`crate::layout`].
240 pub reorder: bool,
241 /// Whether two locals that are never both wanted may be the same bytes, which
242 /// `-fstack-reuse=none` turns off and `-O0` does not ask for. Spill slots share whatever this
243 /// says, since a spill slot is not a variable and nothing can ask a debugger for one. See
244 /// [`crate::slots`].
245 pub reuse: bool,
246 /// Whether the instructions of a block are put in the order the machine finishes soonest,
247 /// which `-fschedule-insns2` asks for and every level from `-O2` turns on. See
248 /// [`crate::schedule`].
249 pub schedule: bool,
250 /// Whether the target's timing model is believed about the machine's units as well as about
251 /// its latencies, which `-Zcycle-accurate-model=` says and the model itself answers otherwise.
252 ///
253 /// `None` is a command line that did not say, which is nearly every one, and then the model's
254 /// own answer decides. It is here rather than only on the model because section 38.1 asks for
255 /// a way to say the model is better or worse than it claims without editing the model, and
256 /// because the measurement section 38.8 owes is the same corpus compiled both ways.
257 pub accurate: Option<bool>,
258 /// Whether the register allocator runs its own checks on a build that has assertions compiled
259 /// out, which `-Zverify-each` asks for. See [`rucc_regalloc::run`].
260 pub verify: bool,
261 /// Whether the level asked for small code or for fast code.
262 ///
263 /// The level itself lives in `rucc-session`, which is above this crate, so what arrives here is
264 /// the answer rather than the question. It is on the flags rather than on the [`Machine`]
265 /// because it is not a fact about a machine: the same machine compiles the same function both
266 /// ways, and which way is what the command line said.
267 ///
268 /// tamnd/rucc#741 is the issue about this not being here at all, and about `-Os` having been a
269 /// shorter list of middle end passes and nothing else. [`crate::shorten`] is the first pass
270 /// below selection to read it.
271 pub goal: Goal,
272}
273
274impl Default for Flags {
275 /// No frame pointer, the red zone allowed, the frame taken in one subtraction, no landing pad,
276 /// no profiling, no room for a patcher, the blocks in the order the graph's shape gives,
277 /// nothing in the frame sharing with anything, no scheduling and code that is meant to be fast
278 /// rather than small, which is what a convention that has a red zone says at `-O0` when nobody
279 /// on the command line has said otherwise.
280 fn default() -> Self {
281 Self {
282 frame_pointer: false,
283 red_zone: true,
284 stack_clash: false,
285 landing: false,
286 profile: Profile::No,
287 patch: Room::default(),
288 reorder: false,
289 reuse: false,
290 schedule: false,
291 accurate: None,
292 verify: false,
293 goal: Goal::Speed,
294 }
295 }
296}
297
298/// Compiles one function, from the IR the middle end produced to machine instructions.
299///
300/// The function is taken by reference that can be written through, because the first pass is an
301/// IR to IR rewrite: a construct whose lowering is a new shape of control flow cannot be a rule,
302/// since a rule replaces a term with a term and has nowhere to put a block. So the IR that reaches
303/// selection is not quite the IR the middle end produced, and this is the only place that is true.
304/// `--emit=ir` prints before any of this runs.
305///
306/// `elsewhere` is the one thing here that is a fact about the module rather than about the
307/// function, and it is passed in rather than looked up because this only ever sees the one
308/// function. What it decides is how the address of a name is come by, which is the difference
309/// between an address this file can measure to and one only the linker knows.
310///
311/// # Errors
312///
313/// The first thing in it this cannot lower, which is what [`lower::func`] reports, and one thing
314/// after it that is about the shape of the function rather than about an instruction, which is a
315/// frame that grows while it runs in a function whose flags say no frame may. Everything else after
316/// lowering works on machine instructions that exist, so it either runs or it is a bug in this
317/// crate.
318pub fn compile(
319 source: &mut ir::Func,
320 names: &mut Interner,
321 machine: &Machine,
322 elsewhere: &Elsewhere,
323 flags: Flags,
324) -> Result<mir::Func, Unsupported> {
325 let (mut fired, mut pressure, mut lowerings) =
326 (Fired::new(), Pressure::new(), Lowerings::new());
327 compile_recording(
328 source,
329 names,
330 machine,
331 elsewhere,
332 flags,
333 &mut Recording { fired: &mut fired, pressure: &mut pressure, lowerings: &mut lowerings },
334 )
335}
336
337/// Somewhere to put what a compilation did along the way, for the flags that ask.
338///
339/// One of these rather than three parameters, because they are one thing: a caller either wants
340/// the measurements or does not, and a caller that does wants the same three to cover every
341/// function of every file on the command line.
342#[derive(Debug)]
343pub struct Recording<'a> {
344 /// Which lowering rules fired, for `-Zrule-coverage`.
345 pub fired: &'a mut Fired,
346 /// What the allocator had to put on the stack, for `-Zregister-pressure`.
347 pub pressure: &'a mut Pressure,
348 /// What the pre-selection lowering group did, for `-Zlowering`.
349 pub lowerings: &'a mut Lowerings,
350}
351
352/// The same compilation, with what it did along the way recorded.
353///
354/// Two functions rather than one that takes options, because a caller that does not want the
355/// numbers should not have to say so. What each field of the [`Recording`] is for is on the field,
356/// and all of them are added to rather than replaced, so a caller passes the same one for every
357/// function of a module and every module of a command line and gets the answer for all of them.
358///
359/// # Errors
360///
361/// The same as [`compile`]. A function that was refused contributes nothing to any of them, since
362/// a function that did not compile is not evidence about what a rule set or a frame would have
363/// done.
364pub fn compile_recording(
365 source: &mut ir::Func,
366 names: &mut Interner,
367 machine: &Machine,
368 elsewhere: &Elsewhere,
369 flags: Flags,
370 recording: &mut Recording<'_>,
371) -> Result<mir::Func, Unsupported> {
372 // Everything the machine has no rule for, rewritten into things it has, as one group rather
373 // than as a dozen lines here. What is in the group and what the order between its members is
374 // for are both in `crate::lowering`, which is where a new lowering is added.
375 let counting = recording.lowerings.wanted();
376 let ran = lowering::group(source, names, machine.conv, counting);
377 if counting {
378 let called = names.resolve(source.name).to_owned();
379 recording.lowerings.record(&called, ran);
380 }
381 // The function the program said it writes the whole of itself, which is what decides most of
382 // the frame below rather than being one more thing in it. Read here rather than beside the rest
383 // of the layout because the refusal a few lines down is the earliest thing that asks.
384 let naked = source.attrs.set.contains(ir::AttrSet::NAKED);
385 let lowered = lower::func(source, names, machine.conv, elsewhere)?;
386 recording.fired.merge(&lowered.fired);
387 let lower::Lowered { mut func, mut stack, blocks, .. } = lowered;
388 // Straight after selection, because this is the last moment the machine blocks and the IR
389 // blocks still stand one for one, and the pass that reads the numbers is the very last one
390 // there is. See `crate::weights`.
391 if flags.reorder {
392 weights::carry(source, &blocks, &mut func);
393 }
394 // The one thing a frame that grows while it runs cannot be asked for, which is a refusal rather
395 // than wrong code.
396 if let Some(inst) = stack.grown_at {
397 // And the one thing a naked function cannot be asked for either, from the other side of the
398 // same fact. A frame that grows is reached from a frame pointer the prologue establishes,
399 // and there is no prologue here, so the address the array hands out would be counted from a
400 // register holding whatever the caller left in it.
401 if naked {
402 return Err(Unsupported::Dynamic { inst, growing: lower::Growing::Naked });
403 }
404 // The lowering refuses a variable length array that asks for more alignment than a call
405 // leaves the stack pointer on. A fixed local asking for it in the same function is the same
406 // refusal arrived at from the other side: the prologue would force the alignment, and
407 // forcing it and moving the stack pointer afterwards are two frames that each want the one
408 // register that still reaches the rest of the frame. See `Growing` in [`crate::frame`].
409 if stack.locals.iter().any(|local| local.align > machine.conv.stack_align) {
410 return Err(Unsupported::Dynamic { inst, growing: lower::Growing::Aligned });
411 }
412 }
413
414 // Before the fold below, which is the order section 37.6 puts the two in. A widening this takes
415 // out is one whose readers are sent to its source, and one of those readers may be an address
416 // computation, so asking which bits are read first means the fold sees the addresses as they
417 // will be rather than as they were.
418 bits::dead(&mut func, machine.bits, machine.shapes, names);
419
420 // After selection, because the address instruction and the one that reads it are both machine
421 // instructions only once selection has written them, and before allocation, because what makes
422 // the pair safe to put together is that a virtual register is written once. The addresses into
423 // the frame and into the caller's argument area go through it like anything else, and the two
424 // lists `finish` reads are rewritten as they do, so an address that ends up inside its reader
425 // is still an address the frame layout knows to write an offset into.
426 let mut pending = fold::Pending {
427 addresses: &mut stack.addresses,
428 arguments: &mut stack.arguments,
429 dynamic: &mut stack.dynamic,
430 };
431 fold::addresses(&mut func, machine.insts, machine.shapes, names, &mut pending);
432
433 // After that fold rather than before it, because what this puts inside an arithmetic
434 // instruction is a load's addressing mode and a load whose address is still a `lea` in front of
435 // it has nothing in its own mode worth carrying. Before allocation for the reason the fold is:
436 // a virtual register is written once, which is the whole of why the value the load produced
437 // cannot have changed between the two instructions this joins.
438 // The run that reads a place, computes on it and writes it back goes first, because it is three
439 // instructions the selector wrote and taking the load out of the middle one first would leave
440 // the same run written a second way.
441 combine::stores(&mut func, machine.shapes, machine.flags, names, &mut pending);
442 combine::loads(&mut func, machine.shapes, names, &mut pending);
443
444 // Whether this function carries a canary is the front end's answer, because what
445 // `-fstack-protector` asks about is the kind of local a function has and the types are gone by
446 // here. What the machine does about it is this crate's answer, and a target with nowhere to
447 // keep the word a canary is copied from does nothing, which is what the driver refuses a
448 // command line over before any of this runs.
449 // Not in a naked function, whatever the command line asked of every function. The canary is a
450 // word the prologue copies into the frame and the check at the end reads back, so a function
451 // with neither has nowhere to put it and nowhere to read it from. gcc leaves one out too.
452 let protect = source.attrs.set.contains(ir::AttrSet::STACK_PROTECT) && !naked;
453 let guard = protect.then_some(machine.conv.guard.as_ref()).flatten();
454 // Nothing at all on a target with no hook to call, which is the same answer the protector gives
455 // on a target with nowhere to keep its word, and the driver refuses the command line over it
456 // before any of this runs.
457 let profile = match machine.conv.trace {
458 Some(_) => flags.profile,
459 None => Profile::No,
460 };
461 let base = stack.layout(Layout::new(machine.conv, machine.file));
462 let layout = Layout {
463 // The later hook reads the frame pointer to find out who called this function, so a
464 // function that calls it is given one whether or not anything else asked. A function that
465 // asked where its own frame is has the same claim on one, and for a plainer reason: the
466 // register is the answer.
467 //
468 // And not at all in a naked function, whatever any of that says. Establishing one is two
469 // instructions of a prologue there is none of, and a function that saves the machine state
470 // by hand is usually saving the frame pointer among it, which is what micropython's
471 // `nlr_push` does on its third line.
472 frame_pointer: !naked
473 && (flags.frame_pointer
474 || profile == Profile::Late
475 || stack.walks_frames
476 || stack.saves_place),
477 // And not in a naked function either, which is not about what the red zone costs but about
478 // what the refusal below has to be able to see. A local small enough to live below the
479 // stack pointer takes no bytes off it, so the frame comes out empty and a function that
480 // wanted somewhere to keep something would be told it asked for nothing. Taking the red
481 // zone away makes every local show up as bytes, and bytes are what gets refused.
482 red_zone: flags.red_zone && !naked,
483 protect: guard.is_some(),
484 naked,
485 // A protected function calls the one that does not come back, on the arm where the check
486 // failed, so it is not a leaf however few calls the program wrote in it. That is what
487 // takes the red zone away from it and what makes its frame leave the stack pointer where
488 // a call needs it. The later hook is a call in the same position and costs the same.
489 //
490 // The earlier one is not, and this is the one place the difference shows. It runs before
491 // the prologue has written anything, so the bytes below the stack pointer it uses are ones
492 // this function has not put anything in yet, and a leaf that keeps its locals down there
493 // stays a leaf. gcc leaves it alone too.
494 leaf: base.leaf && guard.is_none() && profile != Profile::Late,
495 ..base
496 };
497
498 // Before allocation as well, and asked here rather than where it is used because what it asks
499 // is whether anything but the branch reads the byte a comparison wrote. A virtual register is
500 // written once and a physical one is not, so after allocation that question no longer has an
501 // answer.
502 let fusable = layout::fusable(&func, machine.branch, names);
503
504 // In front of the splitting below, because what it does is take the values off the edges out of
505 // a computed `goto` and the splitting has no answer for one of those: the block they leave ends
506 // in a jump already, so neither end of the edge is somewhere a move can go.
507 split::indirect(&mut func, machine.branch, machine.insts, names);
508
509 // And after it, because what it puts a pad at is the block an address names and the pass above
510 // is what settles which block that is. The pad the prologue opens with is written much later,
511 // with the rest of the prologue, since the address it answers for is the function's own.
512 //
513 // Nothing at all on a target with nothing that marks an address as one an indirect branch may
514 // arrive at, which is the same answer the stack protector gives on a target with nowhere to
515 // keep its word, and the driver refuses the command line over it before any of this runs.
516 let landing = flags.landing.then_some(machine.insts.landing).flatten();
517 split::pads(&mut func, machine.insts, landing, names);
518
519 // Before allocation, because an edge that carries values into a block arrived at more than
520 // one way, out of a block that leaves more than one way, has nowhere to put the moves those
521 // values turn into, and the allocator asserts rather than guessing.
522 split::critical(&mut func);
523
524 // Before allocation, because how far the address of a local gets is a question about values and
525 // a value is written once only until the allocator's rewrite has been through. What is done
526 // with the answer waits until afterwards, since the liveness it is read against is the
527 // allocator's. See [`crate::slots`].
528 //
529 // Only asked at all where the locals are allowed to share, since this is the whole of what says
530 // whether a local may. The spill slots are laid out either way and this says nothing about
531 // them.
532 let reach = flags
533 .reuse
534 .then(|| slots::reach(&func, &stack.addresses, stack.locals.len(), machine.insts, names));
535
536 // The instructions as they are now, for the locals the front end kept in values. The
537 // allocator's liveness is counted along this order and the rewrite is about to put spills,
538 // reloads and edge moves in among them, so the list has to be taken before it runs. Only in a
539 // function that named something, since a function that named nothing has no use for it. See
540 // [`crate::kept`].
541 //
542 // Or where a local the program declared may share its bytes, which is only where there is a
543 // `reach`, since a local that shares is in the frame over part of the function and the part is
544 // asked about the same way.
545 let line = (!func.named.is_empty() || (reach.is_some() && !stack.declared.is_empty()))
546 .then(|| kept::before(&func));
547
548 let called = names.resolve(func.name).to_owned();
549 let allocation = rucc_regalloc::run(&mut func, &machine.env, &called, flags.verify);
550 recording.pressure.record(&called, Cost::of(&allocation));
551
552 // After allocation, because the largest area in most frames is the spill slots and nothing
553 // knows how many of those there are until the allocator has finished running out of registers,
554 // and because a spill slot cannot be shared with a local until it is known there is one.
555 let widths = frame::widths(&layout, &allocation);
556 let share = Slots::share(&func, reach.as_ref(), &allocation, &stack.locals, &widths);
557 let layout = Layout { share: Some(&share), ..layout };
558 let frame = Frame::of(&func, &allocation, &layout);
559 // The one thing a naked function cannot be given. Everything else the attribute asks for is
560 // something left out, and leaving something out always works; bytes are the one thing the body
561 // may want that only a prologue provides. A local, a spilled value and the arguments of a call
562 // are the three ways to want them, and the answer to all three is the same sentence.
563 if naked && frame.size() > 0 {
564 return Err(Unsupported::Naked { bytes: frame.size() });
565 }
566
567 // Here because this is where the two halves of the answer are both in hand: which local is
568 // which declaration came down from selection, and where a local is was settled a line ago.
569 // Nothing further on could work it out, since the frame is not carried past this function and
570 // an offset in a finished instruction says nothing about what the bytes it reaches are for.
571 //
572 // Whatever the command line said about debugging information, because the list is one entry
573 // per local the program named and a function has tens of those at most. Asking the flags would
574 // cost more to thread down here than the list costs to build.
575 //
576 // A local that went in beside something else is left off, because its bytes are its own only
577 // where it is wanted and an answer good at every address would have a debugger print whatever
578 // took its place. It gets stretches instead, at the end with the locals kept in values.
579 func.locals = stack
580 .declared
581 .iter()
582 .filter(|&&(local, _)| share.shared(local).is_none())
583 .filter_map(|&(local, decl)| Some((decl, frame.from_frame_base(local)?)))
584 .collect();
585 let framed: Vec<(u32, i32, &[rucc_regalloc::live::Range])> = stack
586 .declared
587 .iter()
588 .filter_map(|&(local, decl)| {
589 Some((decl, frame.from_frame_base(local)?, share.shared(local)?))
590 })
591 .collect();
592 func.sharing = framed.iter().map(|&(decl, _, _)| decl).collect();
593
594 let scratch = machine.env.scratch(machine.conv.int_class);
595 let protect = guard.map(|guard| Protect {
596 guard,
597 branch: machine.branch,
598 scratch: [scratch[0], scratch[1]],
599 });
600 // A target with no instruction that touches a page without changing it does nothing about the
601 // flag, which is the same answer the protector gives on a target with nowhere to keep its word.
602 // Every target this crate has a back end for has one.
603 //
604 // Or where the platform reaches the pages of every frame whatever the command line said, which
605 // is Windows. The prologue there calls a routine rather than walking, but a frame that grows
606 // while it runs is walked in the body either way: the routine takes its size in a register the
607 // allocator hands out and destroys two more, which is answerable in a prologue and not in the
608 // middle of a function, and the walk needs nothing but the two registers already held back.
609 let probe = (flags.stack_clash || machine.conv.chkstk.is_some())
610 .then_some(machine.insts.probe.as_ref())
611 .flatten()
612 .map(|probe| Probing { probe, branch: machine.branch, scratch: [scratch[0], scratch[1]] });
613 let trace = machine.conv.trace.and_then(|trace| match profile {
614 Profile::No => None,
615 Profile::Early => Some(Tracing { name: trace.early, early: true }),
616 Profile::Late => Some(Tracing { name: trace.late, early: false }),
617 });
618 // And once more for the room a patcher was promised, which is a run of the shortest
619 // instruction that does nothing and so needs the target to have one. Nothing is written on a
620 // target that does not, rather than a run of something longer: the flag counts bytes, and a
621 // patcher writing over the room starts at its front and wants every byte in it to be a place
622 // it could have started at.
623 let pad = flags.patch.any().then_some(machine.insts.pad).flatten().map(|name| Padding {
624 name,
625 before: flags.patch.before,
626 after: flags.patch.after,
627 });
628 let convention = Convention {
629 protect,
630 probe,
631 landing,
632 trace,
633 pad,
634 ..Convention::new(machine.conv, machine.insts)
635 };
636 let moves = finish(&mut func, &allocation, &frame, &stack, convention, names);
637
638 // After the moves are written, because a spill and the reload of it are written by different
639 // decisions of the allocator and what stands between the two is settled by the function they
640 // both went into. Before the layout, because the layout is where the instruction sequence
641 // stops being something a pass may edit.
642 copies::clean(&mut func, &moves, machine.shapes, machine.insts, machine.conv, names);
643
644 // After the allocator's moves have been cleaned up, because a schedule chosen around a move
645 // that is about to be taken out is a schedule built around an instruction that is not in the
646 // output. Before the layout, because the layout is the freeze: it writes the jumps the block
647 // order needs and it puts a comparison and the branch that reads it together, and neither
648 // survives an instruction being moved in afterwards. That is section 38.6's placement, and the
649 // reason it is after allocation rather than before is in [`crate::schedule`].
650 if flags.schedule {
651 schedule::insts(
652 &mut func,
653 machine.timing,
654 machine.shapes,
655 machine.flags,
656 names,
657 flags.accurate.unwrap_or(machine.timing.accurate),
658 &fusable,
659 );
660 }
661
662 // Last, because everything before this finds the blocks a function returns from by looking
663 // for the ones that go nowhere, and after this a block that falls through goes nowhere too.
664 layout::blocks(&mut func, machine.branch, names, &fusable, flags.reorder);
665
666 // After the layout rather than before it, which is the whole of what makes it safe. What a
667 // comparison leaves for the instruction behind it to read is not a register and nothing may
668 // come between the two, and the layout is the other pass that writes such a pair. Running
669 // here means there is nothing left that could put an instruction in the middle of one.
670 compare::redundant(&mut func, machine.flags, machine.shapes, names);
671
672 // After that rather than before it, because a comparison it takes out is a write of the
673 // condition state that is gone with it, and this pass is asking which writes of that state are
674 // read. Running in front would see writes the output does not have and turn down rewrites that
675 // are allowed. Nothing here moves an instruction or changes a block, so being behind the
676 // layout's freeze costs it nothing.
677 shorten::shorter(&mut func, machine.short, machine.flags, machine.shapes, names, flags.goal);
678
679 // Last of all, because a stretch is named by the instructions at either end of it and every
680 // pass above is free to take an instruction out or move one. The frame is wanted here as well
681 // as above, since a value the allocator spilled is in the frame over its stretch rather than in
682 // a register, and it is the same distance from the call frame address the locals were given.
683 func.kept = match line {
684 Some(line) => kept::of(&func, &line, &allocation, &frame, &framed),
685 None => Vec::new(),
686 };
687 Ok(func)
688}
689
690#[cfg(test)]
691mod tests {
692 use rucc_ir::{Builder, Flags as IrFlags, Func, Opcode, Restrict, Signature, Type};
693 use rucc_target::x86_64::{REGS, SYSV, WIN64};
694
695 use super::*;
696
697 /// A function of two integers, and the block to fill.
698 fn blank(params: &[Type]) -> (Interner, Func, ir::Block, Vec<ir::Value>) {
699 let mut names = Interner::new();
700 let mut func = Func::new(names.intern("f"), Signature::new());
701 let block = func.create_block();
702 let values = params.iter().map(|&ty| func.append_param(block, ty)).collect();
703 (names, func, block, values)
704 }
705
706 #[test]
707 fn a_function_comes_out_with_no_virtual_register_left_in_it() {
708 let i32 = Type::int(32);
709 let (mut names, mut source, block, args) = blank(&[i32, i32]);
710 let mut build = Builder::new(&mut source, block);
711 let sum = build.binary(Opcode::Add, args[0], args[1], IrFlags::default());
712 build.ret(&[sum]);
713
714 let machine = Machine::x86_64(&SYSV);
715 let out =
716 compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
717 .expect("every instruction has a rule");
718
719 // `int f(int a, int b) { return a + b; }` end to end. A leaf that spills nothing needs no
720 // frame at all, so there is no prologue to see. The one move left is the one the machine's
721 // addition needs, since the sum is written into the register the left operand was read
722 // from and the return wants it in `rax`.
723 assert_eq!(
724 mir::print_func(&out, &names, ®S),
725 "mfunc @f {\n\
726 block0:\n \
727 $rdi($rdi) = x64.arg_val_32\n \
728 $rsi($rsi) = x64.arg_val_32\n \
729 $rdi(reuse 1) = x64.add_rr_32 $rdi, $rsi\n \
730 $rax = x64.mov_rr_64 $rdi\n \
731 x64.ret_val_32 $rax($rax)\n \
732 x64.ret\n\
733 }\n"
734 );
735 }
736
737 #[test]
738 fn a_declared_local_comes_out_saying_how_far_below_the_call_frame_address_it_is() {
739 let i32 = Type::int(32);
740 let (mut names, mut source, block, args) = blank(&[i32]);
741 let mut build = Builder::new(&mut source, block);
742 let info = rucc_ir::MemInfo {
743 size: 4,
744 align: 4,
745 order: rucc_ir::MemOrder::NotAtomic,
746 tbaa: None,
747 owns: 0,
748 restrict: Restrict::NONE,
749 };
750 let mem = build.func().add_mem(info);
751 let slot = build.value(
752 ir::InstData { extra: ir::Extra::Mem(mem), ..ir::InstData::new(Opcode::Alloca) },
753 Type::PTR,
754 );
755 build.func().declare_mem(mem, 5);
756 build.store(args[0], slot, info, IrFlags::default());
757 let loaded = build.load(i32, slot, info, IrFlags::default());
758 build.ret(&[loaded]);
759
760 let machine = Machine::x86_64(&SYSV);
761 let out =
762 compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
763 .expect("every instruction has a rule");
764
765 // `int f(int a) { int x = a; return x; }` with the address of `x` taken, so it is four
766 // bytes in the frame. A leaf this small lives in the red zone, so the stack pointer never
767 // moves. What is below it is a whole word, since everything a frame holds is counted in
768 // words whether or not it fills one, and the call frame address is one more word above the
769 // stack pointer for the return address the call pushed.
770 assert_eq!(out.locals, vec![(5, -16)]);
771 }
772
773 #[test]
774 fn a_local_kept_in_a_value_comes_out_saying_which_register_holds_it_and_over_what() {
775 let i32 = Type::int(32);
776 let (mut names, mut source, block, args) = blank(&[i32]);
777 let mut build = Builder::new(&mut source, block);
778 let sum = build.binary(Opcode::Add, args[0], args[0], IrFlags::default());
779 build.func().declare_value(sum, 5);
780 build.ret(&[sum]);
781
782 let machine = Machine::x86_64(&SYSV);
783 let out =
784 compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
785 .expect("every instruction has a rule");
786
787 // `int f(int a) { int x = a + a; return x; }` with nothing taking the address of `x`, so
788 // it never reaches the frame and the only answer about it is a register. The sum is
789 // written by the addition and read by the move that puts it where the return wants it, so
790 // the stretch is one instruction long and it is the move rather than the addition.
791 assert_eq!(out.kept.len(), 1, "one stretch: {:?}", out.kept);
792 assert_eq!(out.kept[0].decl, 5);
793 assert!(matches!(out.kept[0].at, mir::Where::Reg { .. }), "a register: {:?}", out.kept[0]);
794 assert!(out.locals.is_empty(), "nothing in the frame: {:?}", out.locals);
795 }
796
797 /// What `-Zlowering` is built out of, and the reason it is worth a test here rather than only
798 /// in `crate::lowering`: the group has to be the thing this pipeline runs. A lowering added to
799 /// a line of this function instead of to `Step::GROUP` would still work and would still be
800 /// untested, and the record coming back with one entry per member is what catches it.
801 #[test]
802 fn every_member_of_the_lowering_group_is_run_by_the_compilation_and_says_what_it_did() {
803 let i32 = Type::int(32);
804 let (mut names, mut source, block, args) = blank(&[i32]);
805 let mut build = Builder::new(&mut source, block);
806 let swapped = build.unary(Opcode::Bswap, args[0], i32);
807 build.ret(&[swapped]);
808
809 let mut lowerings = Lowerings::asked(true);
810 compile_recording(
811 &mut source,
812 &mut names,
813 &Machine::x86_64(&SYSV),
814 &Elsewhere::default(),
815 Flags::default(),
816 &mut Recording {
817 fired: &mut Fired::new(),
818 pressure: &mut Pressure::new(),
819 lowerings: &mut lowerings,
820 },
821 )
822 .expect("every instruction has a rule");
823
824 assert_eq!(lowerings.functions(), 1);
825 let listing = lowerings.listing();
826 assert!(listing.contains("lowering f\n"), "{listing}");
827 for step in lowering::Step::GROUP {
828 assert!(listing.contains(step.name()), "{} did not run: {listing}", step.name());
829 }
830 // The byte reversal went through the group rather than reaching the selector, which has no
831 // rule for one.
832 assert!(listing.contains("bytes"), "{listing}");
833 assert!(!listing.contains("left 1"), "something the group answers for survived: {listing}");
834 }
835
836 /// What `-Zrule-coverage` is built out of: the rules a compilation fired, recorded as it went.
837 /// The second function adds to the first rather than replacing it, which is what makes one of
838 /// these files the answer for a whole command line rather than for whichever function was last.
839 #[test]
840 fn which_rules_lowered_a_function_is_something_the_compilation_can_be_asked_for() {
841 let i32 = Type::int(32);
842 let (mut names, mut source, block, args) = blank(&[i32, i32]);
843 let mut build = Builder::new(&mut source, block);
844 let sum = build.binary(Opcode::Add, args[0], args[1], IrFlags::default());
845 build.ret(&[sum]);
846
847 let machine = Machine::x86_64(&SYSV);
848 let mut fired = Fired::new();
849 compile_recording(
850 &mut source,
851 &mut names,
852 &machine,
853 &Elsewhere::default(),
854 Flags::default(),
855 &mut Recording {
856 fired: &mut fired,
857 pressure: &mut Pressure::new(),
858 lowerings: &mut Lowerings::asked(true),
859 },
860 )
861 .expect("every instruction has a rule");
862 let one = fired.count();
863 assert!(one > 0, "an add and a return went through the table and nothing was recorded");
864
865 let listing = fired.listing(&crate::select::x86_64::TABLE);
866 assert_eq!(listing.lines().filter(|line| line.starts_with("fired ")).count(), one);
867 assert!(
868 listing.contains(&format!("{one} of ")),
869 "{}",
870 listing.lines().next().unwrap_or("")
871 );
872
873 // The same rules again plus the ones a subtraction needs, into the same record.
874 let (mut names, mut source, block, args) = blank(&[i32, i32]);
875 let mut build = Builder::new(&mut source, block);
876 let difference = build.binary(Opcode::Sub, args[0], args[1], IrFlags::default());
877 build.ret(&[difference]);
878 compile_recording(
879 &mut source,
880 &mut names,
881 &machine,
882 &Elsewhere::default(),
883 Flags::default(),
884 &mut Recording {
885 fired: &mut fired,
886 pressure: &mut Pressure::new(),
887 lowerings: &mut Lowerings::asked(true),
888 },
889 )
890 .expect("every instruction has a rule");
891 assert!(fired.count() > one, "a subtraction is not an addition");
892 }
893
894 #[test]
895 fn a_function_that_calls_takes_a_frame_and_gives_it_back() {
896 let i32 = Type::int(32);
897 let (mut names, mut source, block, args) = blank(&[i32]);
898 let sig = source.add_signature(Signature::new().with_params(&[i32]).with_returns(&[i32]));
899 let callee = names.intern("g");
900 let call = Builder::new(&mut source, block).call(callee, sig, &[args[0]]);
901 let got = source[call].first_result.expect("an integer comes back");
902 let mut build = Builder::new(&mut source, block);
903 let sum = build.binary(Opcode::Add, got, args[0], IrFlags::default());
904 build.ret(&[sum]);
905
906 let machine = Machine::x86_64(&SYSV);
907 let out =
908 compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
909 .expect("every instruction has a rule");
910
911 // `int f(int a) { return g(a) + a; }`. Not a leaf, so the stack pointer moves and the
912 // register the value that outlives the call went to is one the prologue saves.
913 let text = mir::print_func(&out, &names, ®S);
914 assert!(text.contains("x64.push_64 $rbx"), "{text}");
915 assert!(text.contains("$rbx = x64.pop_64"), "{text}");
916 assert!(text.contains("x64.call $rdi($rdi), @g"), "{text}");
917 assert!(!text.contains('%'), "{text}");
918 }
919
920 #[test]
921 fn the_other_convention_is_the_same_function_somewhere_else() {
922 let i32 = Type::int(32);
923 let (mut names, mut source, block, args) = blank(&[i32, i32]);
924 let mut build = Builder::new(&mut source, block);
925 let sum = build.binary(Opcode::Add, args[0], args[1], IrFlags::default());
926 build.ret(&[sum]);
927
928 let machine = Machine::x86_64(&WIN64);
929 let out =
930 compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
931 .expect("every instruction has a rule");
932
933 // The arguments arrive in `rcx` and `rdx` here rather than in `rdi` and `rsi`, which is
934 // the whole of what changed, and it changed because the convention was asked.
935 let text = mir::print_func(&out, &names, ®S);
936 assert!(text.contains("$rcx($rcx) = x64.arg_val_32"), "{text}");
937 assert!(text.contains("$rdx($rdx) = x64.arg_val_32"), "{text}");
938 assert!(!text.contains("$rdi"), "{text}");
939 }
940
941 #[test]
942 fn a_function_with_a_branch_in_it_goes_through_every_pass() {
943 let i32 = Type::int(32);
944 let (mut names, mut source, entry, args) = blank(&[i32, i32]);
945 let then = source.create_block();
946 let join = source.create_block();
947 let got = source.append_param(join, i32);
948 let mut build = Builder::new(&mut source, entry);
949 let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
950 build.br_if(cond, then, &[], join, &[args[1]]);
951 Builder::new(&mut source, then).jump(join, &[args[0]]);
952 Builder::new(&mut source, join).ret(&[got]);
953
954 let machine = Machine::x86_64(&SYSV);
955 let out =
956 compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
957 .expect("every instruction has a rule");
958
959 // The else arm is a critical edge carrying a value, so a block that nothing lowered is in
960 // there, which is the pass between lowering and allocation doing its job. Without it the
961 // allocator would have asserted rather than compiled this.
962 assert_eq!(out.block_count(), 4);
963
964 // `int f(int a, int b) { return a < b ? a : b; }` end to end, and the last pass is what
965 // this pins. The branch became a test and one jump, and it is the jump taken when the
966 // condition failed, because the arm the condition is true for is the block laid out next
967 // and a block falls into the block laid out next. The other arm is the empty block the
968 // edge splitting left, which is where the move the edge carries ended up, and it falls
969 // into the join as well. What is left is one jump in the whole function. Both arms write
970 // the join's parameter straight into `rax`, because the return at the bottom insists on
971 // that register and the moves the edges carry are free to name it.
972 let text = mir::print_func(&out, &names, ®S);
973 assert_eq!(
974 text,
975 "mfunc @f {\n\
976 block0:\n \
977 $rdi($rdi) = x64.arg_val_32\n \
978 $rsi($rsi) = x64.arg_val_32\n \
979 x64.cmp_rr_32 $rdi, $rsi\n \
980 x64.jcc_ge block2, block1\n\
981 \nblock1:\n \
982 $rax = x64.mov_rr_64 $rdi\n \
983 x64.jmp block3\n\
984 \nblock2:\n \
985 $rax = x64.mov_rr_64 $rsi, block3\n\
986 \nblock3:\n \
987 x64.ret_val_32 $rax($rax)\n \
988 x64.ret\n\
989 }\n"
990 );
991 }
992
993 /// A loop that swaps its two values round every time it goes, which is `gcd`, and which is
994 /// the smallest program that caught two ways of losing a value. Both were found by running
995 /// what came out rather than by reading it, and both are pinned here rather than only where
996 /// they were fixed, because what is wrong with either of them is only visible in the whole
997 /// function.
998 #[test]
999 fn a_loop_that_carries_its_values_round_keeps_all_of_them() {
1000 let i32 = Type::int(32);
1001 let (mut names, mut source, entry, args) = blank(&[i32, i32]);
1002 let head = source.create_block();
1003 let body = source.create_block();
1004 let exit = source.create_block();
1005 let left = source.append_param(head, i32);
1006 let right = source.append_param(head, i32);
1007 Builder::new(&mut source, entry).jump(head, &[args[0], args[1]]);
1008 let mut build = Builder::new(&mut source, head);
1009 let zero = build.iconst(i32, 0);
1010 let more = build.icmp(rucc_ir::IntPred::Ne, right, zero);
1011 build.br_if(more, body, &[], exit, &[left]);
1012 let mut build = Builder::new(&mut source, body);
1013 let rest = build.binary(Opcode::SRem, left, right, IrFlags::default());
1014 build.jump(head, &[right, rest]);
1015 let result = source.append_param(exit, i32);
1016 Builder::new(&mut source, exit).ret(&[result]);
1017
1018 let machine = Machine::x86_64(&SYSV);
1019 let out =
1020 compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
1021 .expect("every instruction has a rule");
1022
1023 // `int gcd(int a, int b) { while (b) { int t = a % b; a = b; b = t; } return a; }`. Two
1024 // things in here were wrong and each of them returned three from a program that gcc
1025 // returns forty two from.
1026 //
1027 // The first is in the entry block. The move the edge into the loop asks for writes `rsi`,
1028 // and the second argument has to be taken out of `rsi` before it does. An edit at the end
1029 // of a block used to go in front of the last instruction, on the reasoning that the last
1030 // instruction is the branch, and the block's jump is not an instruction until the layout
1031 // has run, so it went in front of the `arg_val` whose own move had not been made yet.
1032 //
1033 // The second is in the loop body. A division writes both a quotient and a remainder, and
1034 // only the remainder is wanted here, so the quotient is a value nothing reads. It used to
1035 // be given the same register as the remainder, because a value written early was live at
1036 // one point and that point was in front of where the remainder was written. The copy that
1037 // takes the quotient nowhere then landed on top of the remainder. The remainder is written
1038 // early as well now, which is a separate thing the target has to say and is why both
1039 // answers read `early` here: `rdx` is filled by the sign extension before the division
1040 // reads its divisor, so nothing else may be sitting in it at that point either.
1041 //
1042 // What asks whether the second argument is zero reads as a test rather than a comparison
1043 // because `crate::shorten` runs last and writes the shorter of the two, which asks the
1044 // machine the same thing and leaves the same condition state for the jump behind it.
1045 assert_eq!(
1046 mir::print_func(&out, &names, ®S),
1047 "mfunc @f {\n\
1048 block0:\n \
1049 $rdi($rdi) = x64.arg_val_32\n \
1050 $rsi($rsi) = x64.arg_val_32\n \
1051 $rcx = x64.mov_rr_64 $rdi, block1\n\
1052 \nblock1:\n \
1053 x64.test_rr_32 $rsi\n \
1054 x64.jcc_e block3, block2\n\
1055 \nblock2:\n \
1056 $rax = x64.mov_rr_64 $rcx\n \
1057 early $rdx($rdx), early $rax($rax) = x64.idiv_rem_32 $rax($rax), $rsi\n \
1058 $rdi = x64.mov_rr_64 $rax\n \
1059 $rcx = x64.mov_rr_64 $rsi\n \
1060 $rsi = x64.mov_rr_64 $rdx\n \
1061 x64.jmp block1\n\
1062 \nblock3:\n \
1063 $rax = x64.mov_rr_64 $rcx\n \
1064 x64.ret_val_32 $rax($rax)\n \
1065 x64.ret\n\
1066 }\n"
1067 );
1068 }
1069
1070 /// `spec/10-backend.md` section 10.1 says `--emit=mir-final` round-trips, and a function with
1071 /// a branch in it is the one where that is worth checking: after the layout has run, where a
1072 /// jump goes is nowhere in the instruction, so the text has to carry it on the block and the
1073 /// parser has to put it back on the block it came off.
1074 #[test]
1075 fn a_function_that_has_been_laid_out_reads_back_as_the_same_function() {
1076 let i32 = Type::int(32);
1077 let (mut names, mut source, entry, args) = blank(&[i32, i32]);
1078 let then = source.create_block();
1079 let join = source.create_block();
1080 let got = source.append_param(join, i32);
1081 let mut build = Builder::new(&mut source, entry);
1082 let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
1083 build.br_if(cond, then, &[], join, &[args[1]]);
1084 Builder::new(&mut source, then).jump(join, &[args[0]]);
1085 Builder::new(&mut source, join).ret(&[got]);
1086
1087 let machine = Machine::x86_64(&SYSV);
1088 let out =
1089 compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
1090 .expect("every instruction has a rule");
1091
1092 let text = mir::print_func(&out, &names, ®S);
1093 let read = rucc_mir::parse(&text, &mut names, ®S).expect("what the printer wrote");
1094 assert_eq!(mir::print(&read, &names, ®S), text);
1095 }
1096
1097 #[test]
1098 fn a_function_this_cannot_lower_is_reported_rather_than_compiled() {
1099 let f80 = Type::float(rucc_ir::Float::F80);
1100 let (mut names, mut source, block, args) = blank(&[f80, Type::int(64)]);
1101 Builder::new(&mut source, block).ret(&args);
1102
1103 // One of these comes back on the x87 stack and a pair comes back in a pair of registers,
1104 // and there is no pair with that stack in it. So this is refused rather than lowered, and
1105 // it is the convention that refuses it rather than anything about the instructions.
1106 let machine = Machine::x86_64(&SYSV);
1107 let failed =
1108 compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
1109 .expect_err("a long double cannot come back beside another value");
1110 assert_eq!(failed.to_string(), "what this function gives back is on the x87 stack");
1111 }
1112
1113 /// A `long double` in and a `long double` out, which is the whole of what the convention says
1114 /// about the type and is two different answers rather than one.
1115 ///
1116 /// It arrives in the caller's argument area, so what the parameter is is the address of the
1117 /// bytes and the function reads them where they are. It goes back on the x87 stack, so the
1118 /// return is an `fld` and nothing else, and the value is still on that stack when the function
1119 /// returns, which is the one time anything here leaves it that way.
1120 ///
1121 /// The addresses are gone from the instruction listing, which is [`crate::fold`]: an argument's
1122 /// address is a `lea` off the stack pointer and the `fld` that reads it has room for that
1123 /// address itself, so the offset the frame layout works out is written into the `fld`.
1124 #[test]
1125 fn a_long_double_arrives_in_memory_and_goes_back_on_the_x87_stack() {
1126 let f80 = Type::float(rucc_ir::Float::F80);
1127 let (mut names, mut source, block, args) = blank(&[f80, f80]);
1128 let mut build = Builder::new(&mut source, block);
1129 let sum = build.binary(Opcode::FAdd, args[0], args[1], IrFlags::default());
1130 build.ret(&[sum]);
1131
1132 let machine = Machine::x86_64(&SYSV);
1133 let out =
1134 compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
1135 .expect("every instruction has a rule");
1136
1137 let text = mir::print_func(&out, &names, ®S);
1138 // The two parameters, sixteen bytes apart, read out of the caller's frame rather than out
1139 // of a register, and the answer left on the stack by the last instruction in the function.
1140 assert!(text.contains("x64.fld_t [$rsp + 32]"), "{text}");
1141 assert!(text.contains("x64.fld_t [$rsp + 48]"), "{text}");
1142 assert!(!text.contains("x64.lea_64"), "an address every reader took is gone: {text}");
1143 assert!(!text.contains("x64.ret_val"), "nothing comes back in a register: {text}");
1144 // What comes after the `fld` is the epilogue, which gives the frame back and touches
1145 // nothing in the unit, so the value is where the caller looks for it when the `ret` runs.
1146 let end: Vec<&str> = text.lines().rev().skip(1).take(3).map(str::trim).collect();
1147 assert_eq!(end, ["x64.ret", "$rsp = x64.add_ri_64 $rsp, 24", "x64.fld_t [$rsp]"], "{text}");
1148 }
1149
1150 /// The whole of the second register class, end to end: two floats arrive in vector registers,
1151 /// the arithmetic happens in one, and the answer goes back in the register the convention
1152 /// names. Nothing here touches the general purpose file, which is the point.
1153 #[test]
1154 fn a_float_is_added_in_the_register_file_it_arrives_in() {
1155 let f32 = Type::float(rucc_ir::Float::F32);
1156 let (mut names, mut source, block, args) = blank(&[f32, f32]);
1157 let mut build = Builder::new(&mut source, block);
1158 let sum = build.binary(Opcode::FAdd, args[0], args[1], ir::Flags::default());
1159 build.ret(&[sum]);
1160
1161 let machine = Machine::x86_64(&SYSV);
1162 let out =
1163 compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
1164 .expect("every instruction has a rule");
1165
1166 let text = mir::print_func(&out, &names, ®S);
1167 assert!(text.contains("x64.addss_rr"), "{text}");
1168 assert!(text.contains("$xmm0"), "{text}");
1169 assert!(!text.contains("$rax"), "{text}");
1170 }
1171
1172 /// A float moved between a register and memory, which is the instruction that decides which
1173 /// file the value is in and is a different one from the `mov` that moves the same four bytes.
1174 #[test]
1175 fn a_float_read_from_memory_and_written_back_uses_the_scalar_moves() {
1176 let f64 = Type::float(rucc_ir::Float::F64);
1177 let (mut names, mut source, block, args) = blank(&[Type::PTR, f64]);
1178 let mut build = Builder::new(&mut source, block);
1179 let info = rucc_ir::MemInfo {
1180 size: 8,
1181 align: 8,
1182 order: rucc_ir::MemOrder::NotAtomic,
1183 tbaa: None,
1184 owns: 0,
1185 restrict: Restrict::NONE,
1186 };
1187 let read = build.load(f64, args[0], info, ir::Flags::default());
1188 let sum = build.binary(Opcode::FAdd, read, args[1], ir::Flags::default());
1189 build.store(sum, args[0], info, ir::Flags::default());
1190 build.ret(&[sum]);
1191
1192 let machine = Machine::x86_64(&SYSV);
1193 let out =
1194 compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
1195 .expect("every instruction has a rule");
1196
1197 let text = mir::print_func(&out, &names, ®S);
1198 assert!(text.contains("x64.movsd_rm"), "{text}");
1199 assert!(text.contains("x64.movsd_mr"), "{text}");
1200 // Not the aligned whole register move, which is what a spill uses and is the one
1201 // instruction here that would read and write more than the program asked for.
1202 assert!(!text.contains("x64.movaps_rm"), "{text}");
1203 assert!(!text.contains("x64.movaps_mr"), "{text}");
1204 }
1205
1206 /// The same journey at the format the machine only moves, which is the whole of what it can do
1207 /// with one: in from memory, back out to memory, in and out of a register, and back to the
1208 /// caller.
1209 ///
1210 /// No arithmetic, because there is no instruction for any and every one of them is a call to
1211 /// the runtime. What this says is that the value gets where a call would need it to be.
1212 #[test]
1213 fn a_quad_float_read_from_memory_and_written_back_uses_the_whole_register_move() {
1214 let quad = Type::float(rucc_ir::Float::F128);
1215 let (mut names, mut source, block, args) = blank(&[Type::PTR, quad]);
1216 let mut build = Builder::new(&mut source, block);
1217 let info = rucc_ir::MemInfo {
1218 size: 16,
1219 align: 16,
1220 order: rucc_ir::MemOrder::NotAtomic,
1221 tbaa: None,
1222 owns: 0,
1223 restrict: Restrict::NONE,
1224 };
1225 let read = build.load(quad, args[0], info, ir::Flags::default());
1226 build.store(args[1], args[0], info, ir::Flags::default());
1227 build.ret(&[read]);
1228
1229 let machine = Machine::x86_64(&SYSV);
1230 let out =
1231 compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
1232 .expect("every instruction has a rule");
1233
1234 let text = mir::print_func(&out, &names, ®S);
1235 assert!(text.contains("x64.movaps_rm"), "{text}");
1236 assert!(text.contains("x64.movaps_mr"), "{text}");
1237 assert!(text.contains("x64.arg_val_f128"), "{text}");
1238 assert!(text.contains("x64.ret_val_f128"), "{text}");
1239 // In the vector file and not the general purpose one, which is where the two eightbytes
1240 // of this value would have gone if it had been classified as a pair of integers.
1241 assert!(text.contains("$xmm0"), "{text}");
1242 assert!(!text.contains("gpr($rax)"), "{text}");
1243 }
1244
1245 /// Both conversions between an unsigned word and a `long double`, all the way to instructions.
1246 ///
1247 /// What the rewrite writes and what the x87 group in [`crate::lower`] has are two lists put
1248 /// together in two different files, and this is where they meet. The rewrite is free to write
1249 /// any instruction it likes at any width, and at this width almost none of them can be
1250 /// lowered, so a correction written the way the narrower ones are written would pass its own
1251 /// tests next door and fail here.
1252 #[test]
1253 fn an_unsigned_word_and_a_long_double_convert_into_each_other() {
1254 let f80 = Type::float(rucc_ir::Float::F80);
1255 let (mut names, mut source, block, args) = blank(&[Type::PTR, Type::int(64)]);
1256 let mut build = Builder::new(&mut source, block);
1257 let info = rucc_ir::MemInfo {
1258 size: 16,
1259 align: 16,
1260 order: rucc_ir::MemOrder::NotAtomic,
1261 tbaa: None,
1262 owns: 0,
1263 restrict: Restrict::NONE,
1264 };
1265 let wide = build.unary(Opcode::UIToFP, args[1], f80);
1266 build.store(wide, args[0], info, ir::Flags::default());
1267 let read = build.load(f80, args[0], info, ir::Flags::default());
1268 let back = build.unary(Opcode::FPToUI, read, Type::int(64));
1269 build.ret(&[back]);
1270
1271 let machine = Machine::x86_64(&SYSV);
1272 let out =
1273 compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
1274 .expect("every instruction has a rule");
1275
1276 let text = mir::print_func(&out, &names, ®S);
1277 // The signed conversions in both directions, the constants that correct them, and the
1278 // multiply that takes a correction or leaves it. Nothing here reaches a wide register.
1279 assert!(text.contains("x64.fild_ll"), "the integer goes in as a signed one: {text}");
1280 assert!(text.contains("x64.fistp_ll"), "and comes back out as one: {text}");
1281 assert!(text.contains("x64.fmul_p"), "the correction is taken or not: {text}");
1282 assert!(text.contains("x64.fadd_p"), "and applied one way: {text}");
1283 assert!(text.contains("x64.fsubr_p"), "and the other: {text}");
1284 assert!(!text.contains("xmm"), "no part of this is in a vector register: {text}");
1285 }
1286
1287 /// A value carried from one register file to the other, which is what a conversion is. The
1288 /// instruction reads one file and writes the other, and the allocator has to know that: a
1289 /// conversion whose operands were both said to be in one file would put the answer in a
1290 /// register the next instruction cannot reach.
1291 #[test]
1292 fn a_conversion_carries_the_value_into_the_other_register_file() {
1293 let f64 = Type::float(rucc_ir::Float::F64);
1294 let (mut names, mut source, block, args) = blank(&[f64]);
1295 let mut build = Builder::new(&mut source, block);
1296 let whole = build.unary(Opcode::FPToSI, args[0], Type::int(32));
1297 let back = build.unary(Opcode::SIToFP, whole, f64);
1298 build.ret(&[back]);
1299
1300 let machine = Machine::x86_64(&SYSV);
1301 let out =
1302 compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
1303 .expect("every instruction has a rule");
1304
1305 // The conversion that cuts towards zero rather than the one that rounds, which is what C
1306 // means by the cast, and the argument and the answer in the register the convention names.
1307 let text = mir::print_func(&out, &names, ®S);
1308 assert!(text.contains("x64.cvttsd2si_32"), "{text}");
1309 assert!(text.contains("x64.cvtsi2sd_32"), "{text}");
1310 assert!(text.contains("$xmm0"), "{text}");
1311 }
1312
1313 /// The other way of putting a float and a number together, which keeps every bit rather than
1314 /// the value and is what a program reading the bits of a `double` asks for.
1315 #[test]
1316 fn a_bitcast_between_the_files_is_the_move_that_changes_no_bit() {
1317 let f64 = Type::float(rucc_ir::Float::F64);
1318 let (mut names, mut source, block, args) = blank(&[f64]);
1319 let mut build = Builder::new(&mut source, block);
1320 let bits = build.unary(Opcode::Bitcast, args[0], Type::int(64));
1321 build.ret(&[bits]);
1322
1323 let machine = Machine::x86_64(&SYSV);
1324 let out =
1325 compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
1326 .expect("every instruction has a rule");
1327
1328 let text = mir::print_func(&out, &names, ®S);
1329 assert!(text.contains("x64.movq_from_xmm"), "{text}");
1330 assert!(!text.contains("cvt"), "{text}");
1331 }
1332
1333 /// A comparison whose answer the machine has a condition for, which is most of them.
1334 #[test]
1335 fn a_float_comparison_is_the_compare_and_the_byte_a_condition_sets() {
1336 let f64 = Type::float(rucc_ir::Float::F64);
1337 let (mut names, mut source, block, args) = blank(&[f64, f64]);
1338 let mut build = Builder::new(&mut source, block);
1339 let less = build.fcmp(rucc_ir::FloatPred::Olt, args[0], args[1], ir::Flags::default());
1340 let wide = build.unary(Opcode::ZExt, less, Type::int(32));
1341 build.ret(&[wide]);
1342
1343 let machine = Machine::x86_64(&SYSV);
1344 let out =
1345 compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
1346 .expect("every instruction has a rule");
1347
1348 // Less than is greater than with the operands the other way round, and the machine has no
1349 // condition for the first, so the rule that fires is the one that swaps them.
1350 let text = mir::print_func(&out, &names, ®S);
1351 assert!(text.contains("x64.ucomisd_set_a"), "{text}");
1352 }
1353
1354 /// The two comparisons that are not one condition. An ordered equality is the flag that means
1355 /// equal or unordered and the flag that says it was ordered, so the instruction writes a
1356 /// second byte and reads it back, and what this is about is that the second byte gets a
1357 /// register of its own rather than the one the answer is in.
1358 #[test]
1359 fn an_equality_between_floats_gets_a_register_for_the_byte_it_needs_twice() {
1360 let f64 = Type::float(rucc_ir::Float::F64);
1361 let (mut names, mut source, block, args) = blank(&[f64, f64]);
1362 let mut build = Builder::new(&mut source, block);
1363 let same = build.fcmp(rucc_ir::FloatPred::Oeq, args[0], args[1], ir::Flags::default());
1364 let wide = build.unary(Opcode::ZExt, same, Type::int(32));
1365 build.ret(&[wide]);
1366
1367 let machine = Machine::x86_64(&SYSV);
1368 let out =
1369 compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
1370 .expect("every instruction has a rule");
1371
1372 let text = mir::print_func(&out, &names, ®S);
1373 let line = text
1374 .lines()
1375 .find(|line| line.contains("x64.ucomisd_set_e_and_np"))
1376 .expect("the rule for an ordered equality fired");
1377 let written: Vec<&str> = line
1378 .split_once('=')
1379 .expect("the instruction writes something")
1380 .0
1381 .split(',')
1382 .map(str::trim)
1383 .collect();
1384 assert_eq!(written.len(), 2, "{line}");
1385 assert_ne!(written[0], written[1], "{line}");
1386 }
1387
1388 /// A float literal, which is the last float thing a C program writes that had no lowering.
1389 /// The rewrite that puts it in reach is in `expand`, and what this is about is that the two
1390 /// halves meet: the constant is spelled in a general purpose register and moved across.
1391 #[test]
1392 fn a_float_constant_is_the_bits_in_a_register_and_the_move_that_carries_them_over() {
1393 let f64 = Type::float(rucc_ir::Float::F64);
1394 let (mut names, mut source, block, _) = blank(&[]);
1395 let mut build = Builder::new(&mut source, block);
1396 let half = build.fconst(f64, 0x3fe0_0000_0000_0000);
1397 build.ret(&[half]);
1398
1399 let machine = Machine::x86_64(&SYSV);
1400 let out =
1401 compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
1402 .expect("every instruction has a rule");
1403
1404 let text = mir::print_func(&out, &names, ®S);
1405 assert!(text.contains("x64.mov_ri_64"), "{text}");
1406 assert!(text.contains("x64.movq_to_xmm"), "{text}");
1407 }
1408
1409 /// A negation, which is the sign bit flipped and nothing else touched, so what the machine
1410 /// does is an exclusive or in a general purpose register rather than any float instruction.
1411 #[test]
1412 fn a_negation_is_the_sign_bit_flipped_and_no_float_instruction_at_all() {
1413 let f64 = Type::float(rucc_ir::Float::F64);
1414 let (mut names, mut source, block, args) = blank(&[f64]);
1415 let mut build = Builder::new(&mut source, block);
1416 let less = build.unary(Opcode::FNeg, args[0], f64);
1417 build.ret(&[less]);
1418
1419 let machine = Machine::x86_64(&SYSV);
1420 let out =
1421 compile(&mut source, &mut names, &machine, &Elsewhere::default(), Flags::default())
1422 .expect("every instruction has a rule");
1423
1424 let text = mir::print_func(&out, &names, ®S);
1425 assert!(text.contains("x64.xor_rr_64"), "{text}");
1426 assert!(!text.contains("sub"), "a negation is not a subtraction: {text}");
1427 }
1428
1429 #[test]
1430 fn the_flags_reach_the_frame() {
1431 let i32 = Type::int(32);
1432 let (mut names, mut source, block, args) = blank(&[i32]);
1433 Builder::new(&mut source, block).ret(&[args[0]]);
1434
1435 let machine = Machine::x86_64(&SYSV);
1436 let flags = Flags { frame_pointer: true, profile: Profile::No, ..Flags::default() };
1437 let out = compile(&mut source, &mut names, &machine, &Elsewhere::default(), flags)
1438 .expect("every instruction has a rule");
1439
1440 // A function that keeps a frame pointer keeps it whether it needed one or not, which is
1441 // what `-fno-omit-frame-pointer` is for and is the only thing this test is about.
1442 let text = mir::print_func(&out, &names, ®S);
1443 assert!(text.contains("x64.push_64 $rbp"), "{text}");
1444 assert!(text.contains("$rbp = x64.mov_rr_64 $rsp"), "{text}");
1445 }
1446
1447 #[test]
1448 fn a_target_says_which_machine_it_is_and_which_convention_it_uses() {
1449 let triple = |text: &str| text.parse::<rucc_target::Triple>().expect("a triple");
1450 let info = TargetInfo::new(triple("x86_64-unknown-linux-gnu"));
1451 let machine = Machine::for_target(&info).expect("x86-64 is the target this crate covers");
1452 assert!(std::ptr::eq(machine.conv, &SYSV));
1453
1454 let info = TargetInfo::new(triple("x86_64-pc-windows-msvc"));
1455 let machine = Machine::for_target(&info).expect("x86-64 is the target this crate covers");
1456 assert!(std::ptr::eq(machine.conv, &WIN64));
1457
1458 // Not a target this crate has a backend for, and saying so is the whole point: a caller
1459 // that got a machine here would compile x86-64 instructions for an AArch64 program.
1460 let info = TargetInfo::new(triple("aarch64-unknown-linux-gnu"));
1461 assert!(Machine::for_target(&info).is_none());
1462 }
1463}