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