Skip to main content

rucc_codegen/
lower.rs

1//! The selector: an IR function becomes a machine IR function.
2//!
3//! Design: `spec/10-backend.md` sections 10.2 and 10.3.
4//!
5//! What the matcher in [`crate::select`] does is answer one question about one term. What this
6//! does is ask it: walk a function, decide which terms are worth asking about, and build machine
7//! instructions out of what comes back. Nothing here decides what an IR term lowers to. That is
8//! in `rules/x86-64.rules` and it is proved before it is used, which is the whole point of the
9//! arrangement and the reason this file is short.
10//!
11//! # What it does with an instruction
12//!
13//! It tries the ways the instruction can be shown to the matcher, in order, and takes the first
14//! that a rule fires on. [`crate::term`] is what a way of showing one is, and the order is the
15//! most specific first: an operand that is a constant is offered as a constant before it is
16//! offered as a register, and an operand computed by an instruction of its own is offered as
17//! that instruction before it is offered as a register. A rule that wants an immediate too wide
18//! for the machine has a guard that turns it down, and the search carries on to the way of
19//! showing it that puts the constant in a register, which is the right answer and is one nobody
20//! had to write down.
21//!
22//! A constant is not lowered where it is written. It is materialized where a register for it is
23//! first wanted, which is what keeps a constant that every use folded into an immediate from
24//! leaving a dead instruction behind, and it also gives the value the shortest live range it
25//! could have. The instruction that materializes it comes from the rule set like everything else.
26//!
27//! # What it does not do yet
28//!
29//! Everything is in the general purpose registers, because every rule in the set is about an
30//! integer, so a call that passes a `double` and a function that returns one are both reported
31//! rather than lowered. So is an argument that travels on the stack, on either side of a call,
32//! and so is a call through an address rather than to a name.
33//!
34//! # A call
35//!
36//! Not a rule, because a rule pattern sees one term and what a call's operands are is whatever
37//! the signature made them. [`crate::abi`] builds one instead, out of the same description of the
38//! convention the arguments come from: the values it passes are reads constrained to the
39//! registers the convention places them in, what comes back is a write constrained to the
40//! register it comes back in, and every other register the callee is free to destroy is a write
41//! of that register and nothing else, which is all the allocator needs to keep a value out of it.
42//!
43//! What that costs the frame is an argument area, and nothing after selection could work out how
44//! big, so the size of the widest call is given back with the function. A function that makes no
45//! call at all is a leaf, and a leaf is the function that may use the red zone.
46//!
47//! # Where a block goes
48//!
49//! On the block, which is what machine IR does with an edge and is why the branches need no more
50//! rule language than the arithmetic did. A rule never names a block, so an unconditional jump
51//! has no rule at all and a conditional branch has one that is about its condition and nothing
52//! else. The arms are copied across after the block is filled, arguments and all, because an
53//! argument that is a constant is materialized where a register for it is first wanted and the
54//! end of the block is where an edge wants it.
55//!
56//! What this leaves behind is a function whose blocks are in the order the IR held them and whose
57//! branches are still branches on a register. Turning one into a `test` and a `jcc` is the block
58//! layout's, since which of the two arms falls through is the layout's answer, and [`crate::split`]
59//! has to run before allocation so that every edge carrying a value has somewhere to put it.
60//!
61//! A store and a return are the two things here that write no register. A store is emitted like
62//! everything else and the only difference is that there is no result to put anywhere, so the
63//! operands the target describes are all reads. A return is the same, and what it is for is its
64//! one operand: the target constrains it to the register the caller reads the value out of, and
65//! the allocator is what gets it there. The instruction that leaves is not chosen here at all,
66//! because the epilogue has to give the frame back first and [`crate::finish`] writes that after
67//! allocation, so a return of nothing is lowered to nothing.
68//!
69//! The entry block is the one block whose parameters are not block parameters here. They are the
70//! function's arguments, they are already somewhere when it starts, and [`crate::abi`] is what
71//! says where. An argument that arrives on the stack is reported rather than read, because where
72//! the stack put it is a distance into a frame and no frame exists until after allocation.
73//!
74//! Blocks are walked in the order the function holds them and a value is expected to be defined
75//! before it is used, which is true of the IR this is given because every pass before it keeps
76//! definitions ahead of uses.
77
78use std::fmt;
79
80use rucc_base::Interner;
81use rucc_ir::{Block, Def, Extra, Func, Inst, Opcode, Type, Value};
82use rucc_mir as mir;
83use rucc_target::x86_64;
84use rucc_target::{CallRegs, RegClass};
85
86use crate::abi::{self, Missing, Refused};
87use crate::frame::{Layout, Local};
88use crate::select::{Match, Piece, Rule, Table};
89use crate::term::{MAX_ARGS, PLAIN, Plan, Shown, Term, Terms};
90
91/// The prefix a rule file puts in front of a machine term, which says which target it belongs
92/// to and is not part of the opcode.
93const PREFIX: &str = "x64.";
94
95/// Why a function could not be lowered.
96///
97/// One reason and then nothing. A function with no rule for something in it is a function this
98/// cannot finish, and the second thing it could not lower is not news.
99#[derive(Debug, Clone, PartialEq, Eq)]
100pub enum Unsupported {
101    /// An instruction no rule fires on.
102    Inst {
103        /// The instruction that stopped it.
104        inst: Inst,
105        /// What the rule file would call it, or nothing if the rule language has no name for it
106        /// at all, which is what an instruction at a width nothing is written about looks like.
107        term: Option<&'static str>,
108    },
109    /// A parameter that does not arrive somewhere this can bring it in from.
110    ///
111    /// Not an instruction, which is why it is a separate arm: it is a fact about the signature
112    /// and there is nothing in the body of the function to point at.
113    Argument {
114        /// Its position in the signature.
115        index: usize,
116        /// What is wrong with where it arrives.
117        missing: Missing,
118    },
119    /// A call that passes or gives back a value this cannot put where the convention wants it.
120    Call {
121        /// The call.
122        inst: Inst,
123        /// Which value, and what is wrong with where it travels.
124        refused: Refused,
125    },
126    /// A call through an address rather than to a name.
127    ///
128    /// The address is a value in a register and the instruction that calls one is a different
129    /// instruction, which nothing describes yet.
130    Indirect {
131        /// The call.
132        inst: Inst,
133    },
134    /// A stack slot whose size is not known until the function runs, which is what a variable
135    /// length array is.
136    ///
137    /// Not an instruction no rule covers. Growing the stack where the declaration stands is
138    /// arithmetic on the stack pointer, and everything else in the frame then has to be reached
139    /// through a frame pointer instead, and neither of those is a term a rule could be written
140    /// about or a thing the frame here knows how to lay out.
141    Dynamic {
142        /// The `alloca`.
143        inst: Inst,
144    },
145}
146
147impl fmt::Display for Unsupported {
148    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
149        match *self {
150            Unsupported::Inst { term: Some(term), .. } => write!(f, "no rule lowers `{term}`"),
151            Unsupported::Inst { term: None, .. } => f.write_str("no rule lowers this instruction"),
152            Unsupported::Argument { index, missing } => {
153                write!(f, "parameter {index} {}", missing.why())
154            }
155            Unsupported::Call { refused: Refused { argument: Some(index), missing }, .. } => {
156                write!(f, "argument {index} of this call {}", missing.why())
157            }
158            Unsupported::Call { refused: Refused { argument: None, missing }, .. } => {
159                write!(f, "what this call gives back {}", missing.why())
160            }
161            Unsupported::Indirect { .. } => f.write_str("no rule calls through an address"),
162            Unsupported::Dynamic { .. } => {
163                f.write_str("nothing here grows the stack for a variable length array")
164            }
165        }
166    }
167}
168
169impl std::error::Error for Unsupported {}
170
171/// A lowered function, and what the frame needs that the machine IR does not hold.
172#[derive(Debug)]
173pub struct Lowered {
174    /// The function, in machine instructions.
175    pub func: mir::Func,
176    /// What it wants its stack to look like, which is separate from the function so that the two
177    /// can be read and written at the same time.
178    pub stack: Stack,
179}
180
181/// What a function's stack has to hold, as far as selection is able to say.
182///
183/// All of it is answered here because selection is where a call is built and where an `alloca`
184/// is read, and nothing after it could tell what either of them needed.
185#[derive(Debug, Default)]
186pub struct Stack {
187    /// How many bytes the widest call in the function needs below the stack pointer for the
188    /// arguments it passes there, or `None` for a function that makes no call at all.
189    ///
190    /// `None` is a leaf, which is the function that may use the red zone and the one whose stack
191    /// pointer does not have to be left aligned for anybody.
192    pub calls: Option<u32>,
193    /// The memory the function asked for itself, one entry for every `alloca` in it, in the order
194    /// the walk reached them.
195    pub locals: Vec<Local>,
196    /// Which instruction computes the address of which of those locals.
197    ///
198    /// An address in the frame is a distance from the stack pointer, and there is no frame until
199    /// after allocation, so the instruction is written here with nothing in its displacement and
200    /// [`crate::finish`] writes the number in once [`crate::frame::Frame`] knows it.
201    pub addresses: Vec<(mir::Inst, usize)>,
202}
203
204impl Stack {
205    /// The layout given, with the three fields only the lowering knows the answer to filled in.
206    ///
207    /// Everything else in a layout comes from the flags the function is compiled under or from the
208    /// allocation, so this takes one and returns it rather than building one.
209    #[must_use]
210    pub fn layout<'a>(&'a self, base: Layout<'a>) -> Layout<'a> {
211        Layout {
212            leaf: self.calls.is_none(),
213            outgoing: self.calls.unwrap_or(0),
214            locals: &self.locals,
215            ..base
216        }
217    }
218}
219
220/// The x86-64 machine IR for that function.
221///
222/// # Errors
223///
224/// The first instruction no rule fires on, which today is anything at a width the rule set is not
225/// written at, a parameter that does not arrive in a register this can read, or a call that
226/// passes something this cannot put where the convention wants it.
227pub fn func(
228    source: &Func,
229    names: &mut Interner,
230    conv: &'static CallRegs,
231) -> Result<Lowered, Unsupported> {
232    Lowering::new(source, names, conv).run()
233}
234
235/// One function being lowered.
236struct Lowering<'a> {
237    source: &'a Func,
238    names: &'a mut Interner,
239    out: mir::Func,
240    /// The machine register each IR value is in, once it has one.
241    regs: Vec<Option<mir::Reg>>,
242    /// For a constant that has been written into a register, the block it was written into,
243    /// which is the only block that register is any good in.
244    written: Vec<Option<mir::Block>>,
245    /// How many times each IR value is read, which is what says whether an instruction may be
246    /// folded into the one that reads it.
247    uses: Vec<u32>,
248    /// The block being filled.
249    at: Option<mir::Block>,
250    /// The machine IR block each IR block became.
251    blocks: Vec<Option<mir::Block>>,
252    /// The class everything is in until there is a rule about a float.
253    gpr: RegClass,
254    /// Where the convention this function is compiled for puts things, which is read for the
255    /// arguments and for the calls.
256    conv: &'static CallRegs,
257    /// What the function wants its stack to look like, filled in as the walk finds out.
258    stack: Stack,
259}
260
261impl<'a> Lowering<'a> {
262    fn new(source: &'a Func, names: &'a mut Interner, conv: &'static CallRegs) -> Self {
263        let counts = source.counts();
264        let name = source.name;
265        let mut uses = vec![0; counts.values];
266        for block in source.blocks() {
267            for inst in source.insts(block) {
268                for &arg in &source[source[inst].args] {
269                    uses[arg.index()] += 1;
270                }
271                for call in source.successors(inst) {
272                    for &arg in &source[call.args] {
273                        uses[arg.index()] += 1;
274                    }
275                }
276            }
277        }
278        Self {
279            source,
280            names,
281            out: mir::Func::new(name),
282            regs: vec![None; counts.values],
283            written: vec![None; counts.values],
284            blocks: vec![None; counts.blocks],
285            uses,
286            at: None,
287            gpr: x86_64::GPR,
288            conv,
289            stack: Stack::default(),
290        }
291    }
292
293    fn run(mut self) -> Result<Lowered, Unsupported> {
294        // Every block before any of them is filled, because a block that jumps forward has to
295        // name the block it jumps to and a machine IR block is named by a handle rather than by
296        // the IR block it came from.
297        for block in self.source.blocks() {
298            let out = self.out.create_block();
299            self.blocks[block.index()] = Some(out);
300        }
301        for block in self.source.blocks() {
302            self.block(block)?;
303        }
304        Ok(Lowered { func: self.out, stack: self.stack })
305    }
306
307    /// One block: its parameters, then every instruction in it that is not folded into another.
308    fn block(&mut self, block: Block) -> Result<(), Unsupported> {
309        let out = self.out_block(block);
310        self.at = Some(out);
311        if self.source.entry() == Some(block) {
312            self.arrive(block, out)?;
313        } else {
314            for &param in self.source[block].params.iter() {
315                let reg = self.out.append_param(out, self.gpr);
316                self.regs[param.index()] = Some(reg);
317            }
318        }
319
320        // What each instruction matched, and which instructions were folded into another. The
321        // instruction that is folded comes before the one that folds it, so the decision has to
322        // be made for the whole block before any of it is written, and it is made backwards: an
323        // instruction that has been folded into a later one does not get to fold anything into
324        // itself, because the rule that took it only reached one level down.
325        let insts: Vec<Inst> = self.source.insts(block).collect();
326        let mut found: Vec<Option<Match<Term>>> = (0..insts.len()).map(|_| None).collect();
327        let mut folded: Vec<Inst> = Vec::new();
328        for (index, &inst) in insts.iter().enumerate().rev() {
329            if folded.contains(&inst) {
330                continue;
331            }
332            if let Some((plan, matched)) = self.select(inst) {
333                folded.extend(self.folds(inst, plan));
334                found[index] = Some(matched);
335            }
336        }
337
338        for (&inst, matched) in insts.iter().zip(found) {
339            if folded.contains(&inst) || self.writes_nothing(inst) {
340                continue;
341            }
342            // A call is built from the convention rather than matched, which is why it is the one
343            // opcode looked at by name here. Through an address it is a different instruction and
344            // nothing describes that one yet, so it is reported as itself rather than as a term
345            // no rule covers, which would be true and would say nothing.
346            match self.source[inst].opcode {
347                Opcode::Call => {
348                    self.called(inst)?;
349                    continue;
350                }
351                Opcode::CallIndirect => return Err(Unsupported::Indirect { inst }),
352                // Built from the frame rather than matched, for the same shape of reason a call
353                // is built from the convention: what a rule replaces a term with is instructions,
354                // and what an `alloca` needs first is bytes, which the rule language has no way
355                // to ask for.
356                Opcode::Alloca => {
357                    self.reserve(inst)?;
358                    continue;
359                }
360                _ => {}
361            }
362            let matched = matched.ok_or_else(|| self.unsupported(inst))?;
363            self.emit(inst, &matched)?;
364        }
365        self.edges(block, out)
366    }
367
368    /// One call, which is built from the convention rather than matched against the table for the
369    /// same reason the arguments of the function itself are.
370    ///
371    /// The arguments are read before the call is built, which is what materializes a constant
372    /// argument into a register, since no call passes an immediate.
373    fn called(&mut self, inst: Inst) -> Result<(), Unsupported> {
374        let data = &self.source[inst];
375        let Extra::Call(info) = data.extra else { return Err(self.unsupported(inst)) };
376        let info = self.source[info];
377        let Some(callee) = info.callee else { return Err(Unsupported::Indirect { inst }) };
378
379        let values: Vec<Value> = self.source[data.args].to_vec();
380        let mut args = Vec::with_capacity(values.len());
381        for value in values {
382            args.push((self.source[value].ty, self.reg_of(value)?));
383        }
384        let signature = &self.source[info.signature];
385        let variadic = signature.variadic;
386        let returns = signature.return_types().next();
387        // More than one value back is the convention's answer rather than a term's, the same way
388        // a return of two values is, and nothing here has a name for it.
389        if signature.return_types().count() > 1 {
390            return Err(self.unsupported(inst));
391        }
392
393        let block = self.at.expect("a block is being filled");
394        let what = abi::Calling { callee, args: &args, returns, variadic };
395        let made = abi::call(&mut self.out, block, &what, self.conv, self.names)
396            .map_err(|refused| Unsupported::Call { inst, refused })?;
397        let calls = &mut self.stack.calls;
398        *calls = Some(calls.unwrap_or(0).max(made.outgoing));
399        if let (Some(result), Some(reg)) = (data.first_result, made.result) {
400            self.regs[result.index()] = Some(reg);
401        }
402        Ok(())
403    }
404
405    /// One `alloca`: the bytes it asks for go on the list the frame is laid out from, and the
406    /// address of them is one instruction.
407    ///
408    /// The instruction is a `lea` off the stack pointer, which is the one register that reaches
409    /// the frame in every function, and its displacement is left at nothing because there is no
410    /// frame yet. Which instruction is waiting for which local is remembered, and
411    /// [`crate::finish`] fills the numbers in after [`crate::frame::Frame`] has placed them.
412    ///
413    /// There is deliberately no rule for `alloca` and no name for one in [`crate::term`], and
414    /// that is what stops it being folded into something else. An operand shown as the
415    /// instruction that computed it is offered to the matcher by its name, so an `alloca` with no
416    /// name is one no pattern can reach past, and the address it computes is always in a register
417    /// by the time anything reads it.
418    fn reserve(&mut self, inst: Inst) -> Result<(), Unsupported> {
419        let data = &self.source[inst];
420        // A variable length array carries the size it wants as an operand rather than in the
421        // instruction, which is the whole of what tells the two apart here.
422        if !self.source[data.args].is_empty() {
423            return Err(Unsupported::Dynamic { inst });
424        }
425        let Extra::Mem(mem) = data.extra else { return Err(self.unsupported(inst)) };
426        let info = self.source[mem];
427        let size = u32::try_from(info.size).map_err(|_| Unsupported::Dynamic { inst })?;
428        let result = data.first_result.ok_or_else(|| self.unsupported(inst))?;
429
430        // At least one, because the frame divides by the alignment and an object with no
431        // alignment at all is one the front end had nothing to say about rather than one that may
432        // go anywhere.
433        let index = self.stack.locals.len();
434        self.stack.locals.push(Local { size, align: info.align.max(1) });
435
436        let block = self.at.expect("a block is being filled");
437        let reg = self.new_reg(result);
438        let span = self.source.span(inst);
439        let lea = mir::Opcode::new(self.names.intern(&format!("{PREFIX}{}", x86_64::FRAME.lea)));
440        let sp = mir::Operand::read(mir::Reg::physical(self.conv.stack_pointer), self.gpr);
441        let made =
442            self.out.build(block, lea).at(span).def(reg, self.gpr).mem(mir::Mem::at(sp)).finish();
443        self.stack.addresses.push((made, index));
444        Ok(())
445    }
446
447    /// Where a block goes, which in machine IR is on the block rather than on its terminator.
448    ///
449    /// That is why no rule ever names a block: a branch is selected for what it reads and the
450    /// edges are copied across here, arguments and all. The arguments are read last, after every
451    /// instruction of the block is written, because an argument that is a constant is
452    /// materialized where it is first wanted and the end of the block is where an edge wants it.
453    ///
454    /// Which is not quite the end. A block that leaves two ways has the branch as its last
455    /// instruction, and anything appended after a branch is something the branch has already
456    /// jumped past, so a constant materialized here would be a register the block below reads and
457    /// nothing ever writes. The branch is put back on the end when that happened, which is the
458    /// only reordering anything in this crate does and is why the branch is remembered before a
459    /// single argument is read.
460    fn edges(&mut self, block: Block, out: mir::Block) -> Result<(), Unsupported> {
461        let Some(term) = self.source.terminator(block) else { return Ok(()) };
462        let branch =
463            if self.source[term].opcode == Opcode::BrIf { self.out.terminator(out) } else { None };
464
465        let calls: Vec<rucc_ir::BlockCall> = self.source.successors(term).collect();
466        let mut succs = Vec::with_capacity(calls.len());
467        for call in calls {
468            let args: Vec<Value> = self.source[call.args].to_vec();
469            let mut regs = Vec::with_capacity(args.len());
470            for value in args {
471                regs.push(self.reg_of(value)?);
472            }
473            succs.push(mir::BlockCall { block: self.out_block(call.block), args: regs });
474        }
475        if let Some(branch) = branch {
476            if self.out.terminator(out) != Some(branch) {
477                self.out.remove_inst(branch);
478                self.out.append_inst(out, branch);
479            }
480        }
481        *self.out.succs_mut(out) = succs;
482        Ok(())
483    }
484
485    /// The machine IR block an IR block became.
486    fn out_block(&self, block: Block) -> mir::Block {
487        self.blocks[block.index()].expect("every block was created before any was filled")
488    }
489
490    /// The parameters of the entry block, which are the function's arguments.
491    ///
492    /// They are not block parameters in the machine IR and they cannot be. A block parameter is
493    /// given its value by a move on the edge into the block, and there is no edge into an entry
494    /// block, so what arrives in a function is the convention's to say. [`crate::abi`] is what
495    /// says it.
496    fn arrive(&mut self, block: Block, out: mir::Block) -> Result<(), Unsupported> {
497        let params = self.source[block].params.clone();
498        let types: Vec<Type> = params.iter().map(|&value| self.source[value].ty).collect();
499        let regs = abi::entry(&mut self.out, out, &types, self.conv, self.names)
500            .map_err(|(index, missing)| Unsupported::Argument { index, missing })?;
501        for (&param, reg) in params.iter().zip(regs) {
502            self.regs[param.index()] = Some(reg);
503        }
504        Ok(())
505    }
506
507    /// Whether an instruction is one no machine instruction is written for where it stands.
508    ///
509    /// Three of them, and none is a lowering decision, which is why none is a rule. A constant is
510    /// written where a register for it is first wanted rather than where the IR put it, and every
511    /// reader of one may have folded it into an immediate, in which case nowhere is the right
512    /// place. A return of nothing has nothing to put anywhere: the epilogue gives the frame back
513    /// and leaves, and it is appended to every block with no successors long after this has
514    /// finished, so a return with a value is one instruction here and a return without one is
515    /// none. An unconditional jump is the third, and there is even less of it: the edge is on the
516    /// block, and whether the block it goes to is the next one and needs no jump at all is the
517    /// block layout's answer rather than this one's.
518    fn writes_nothing(&self, inst: Inst) -> bool {
519        let data = &self.source[inst];
520        match data.opcode {
521            Opcode::IConst | Opcode::Jump => true,
522            Opcode::Return => self.source[data.args].is_empty(),
523            _ => false,
524        }
525    }
526
527    /// The rule that fires on an instruction, and what it bound.
528    ///
529    /// The plans are tried in order and the first that matches wins, which is the maximal munch
530    /// `spec/10-backend.md` asks for: a plan that offers more to the matcher is tried before one
531    /// that offers less.
532    fn select(&self, inst: Inst) -> Option<(Plan, Match<Term>)> {
533        for plan in self.plans(inst) {
534            let terms = Terms::new(self.source, inst, plan);
535            if let Some(matched) = TABLE.find(&terms, Term::Root) {
536                return Some((plan, matched));
537            }
538        }
539        None
540    }
541
542    /// Every way this instruction can be shown to the matcher, most offered first.
543    fn plans(&self, inst: Inst) -> Vec<Plan> {
544        let args = &self.source[self.source[inst].args];
545        let mut plans = vec![PLAIN];
546        for (index, &arg) in args.iter().enumerate().take(MAX_ARGS) {
547            let mut ways = Vec::new();
548            if self.foldable(inst, arg) {
549                ways.push(Shown::Expand);
550            }
551            if Terms::new(self.source, inst, PLAIN).constant(arg).is_some() {
552                ways.push(Shown::Const);
553            }
554            ways.push(Shown::Reg);
555            plans = plans
556                .into_iter()
557                .flat_map(|plan| {
558                    ways.iter().map(move |&way| {
559                        let mut next = plan;
560                        next[index] = way;
561                        next
562                    })
563                })
564                .collect();
565        }
566        plans
567    }
568
569    /// Whether an operand may be shown as the instruction that computed it.
570    ///
571    /// It has to be in the same block, because a rule that folds one instruction into another
572    /// moves the work to where the second one is. It has to be read only by this instruction,
573    /// because folding it does not delete it for anybody else and doing the work twice is not a
574    /// saving. And it has to be something rather than a block parameter, and not a constant,
575    /// which is shown as a constant instead.
576    fn foldable(&self, into: Inst, value: Value) -> bool {
577        let Def::Result { inst, .. } = self.source[value].def else { return false };
578        if self.source[inst].opcode == Opcode::IConst || self.uses[value.index()] != 1 {
579            return false;
580        }
581        self.source.block_of(inst).is_some()
582            && self.source.block_of(inst) == self.source.block_of(into)
583    }
584
585    /// The instructions a match folded into the one it matched.
586    ///
587    /// The plan is what says this, not the bindings: a binding is a register or a number either
588    /// way, and an operand shown as the instruction that computed it is one no rule could have
589    /// matched without taking that instruction, because the plan offered the matcher nothing
590    /// else to call it.
591    fn folds(&self, inst: Inst, plan: Plan) -> Vec<Inst> {
592        let args = &self.source[self.source[inst].args];
593        args.iter()
594            .take(MAX_ARGS)
595            .enumerate()
596            .filter(|&(index, _)| plan[index] == Shown::Expand)
597            .filter_map(|(_, &arg)| match self.source[arg].def {
598                Def::Result { inst, .. } => Some(inst),
599                Def::Param { .. } => None,
600            })
601            .collect()
602    }
603
604    /// Build the machine instruction a match calls for.
605    fn emit(&mut self, inst: Inst, matched: &Match<Term>) -> Result<(), Unsupported> {
606        let rule: &Rule = TABLE.rule(matched);
607        let pieces = rule.replacement;
608        let Some(Piece::App { head, arity }) = pieces.first() else {
609            return Err(self.unsupported(inst));
610        };
611        let opcode = head.strip_prefix(PREFIX).ok_or_else(|| self.unsupported(inst))?;
612        let form = x86_64::form(opcode).ok_or_else(|| self.unsupported(inst))?;
613
614        let mut read = Read::default();
615        let mut at = 1;
616        for _ in 0..*arity {
617            at = self.read(inst, pieces, at, &matched.bindings, &mut read)?;
618        }
619
620        let descs = form.operands();
621        let writes = descs.iter().take_while(|desc| desc.role.is_def()).count();
622        if descs.len() - writes != read.regs.len() {
623            return Err(self.unsupported(inst));
624        }
625
626        // The first thing the instruction writes is what it computes, and any others are
627        // registers the machine destroys on the way, which are fresh because nothing else is in
628        // them and nothing reads them. An instruction that writes nothing at all is one whose
629        // whole purpose is its effect, which is what a store is, and there is no result to put
630        // anywhere.
631        let mut regs = Vec::new();
632        if writes > 0 {
633            let result = self.source[inst].first_result.ok_or_else(|| self.unsupported(inst))?;
634            regs.push(self.new_reg(result));
635            regs.extend((1..writes).map(|_| self.out.new_vreg(self.gpr)));
636        } else if self.source[inst].first_result.is_some() {
637            // A rule that throws away a value the IR gave a name to would leave every reader of
638            // that name with nothing to read, so it is a rule this and the target disagree about.
639            return Err(self.unsupported(inst));
640        }
641        regs.extend(read.regs.iter().copied());
642
643        let block = self.at.expect("a block is being filled");
644        let opcode = mir::Opcode::new(self.names.intern(head));
645        let mut build = self.out.build(block, opcode).at(self.source.span(inst));
646        for (desc, reg) in descs.iter().zip(regs) {
647            let operand = mir::Operand {
648                reg,
649                class: desc.class,
650                role: desc.role,
651                constraint: desc.constraint,
652            };
653            build = build.operand(operand);
654        }
655        if let Some(mem) = read.mem {
656            build = build.mem(mem);
657        }
658        if let Some(imm) = read.imm {
659            build = build.imm(imm);
660        }
661        build.finish();
662        Ok(())
663    }
664
665    /// Read one argument of a replacement, which is a register, a number or an address.
666    ///
667    /// Gives back the position after it, because a replacement is flat and an address takes
668    /// arguments of its own.
669    fn read(
670        &mut self,
671        inst: Inst,
672        pieces: &'static [Piece],
673        at: usize,
674        bindings: &[Term],
675        out: &mut Read,
676    ) -> Result<usize, Unsupported> {
677        match pieces.get(at) {
678            Some(Piece::Int(value)) => {
679                out.imm = i64::try_from(*value).ok();
680                Ok(at + 1)
681            }
682            Some(Piece::Var { index, .. }) => {
683                match bindings.get(*index) {
684                    Some(&Term::Reg(value)) => {
685                        let reg = self.reg_of(value)?;
686                        out.regs.push(reg);
687                    }
688                    Some(&Term::Num(value)) => out.imm = i64::try_from(value).ok(),
689                    // A pattern binds a register or a number and nothing else, so this is a
690                    // rule the matcher and this file disagree about.
691                    _ => return Err(self.unsupported(inst)),
692                }
693                Ok(at + 1)
694            }
695            Some(Piece::App { head, arity }) => {
696                let kind = x86_64::address(head).ok_or_else(|| self.unsupported(inst))?;
697                let mut inner = Read::default();
698                let mut next = at + 1;
699                for _ in 0..*arity {
700                    next = self.read(inst, pieces, next, bindings, &mut inner)?;
701                }
702                let mem = address(kind, &inner, self.gpr).ok_or_else(|| self.unsupported(inst))?;
703                out.mem = Some(mem);
704                Ok(next)
705            }
706            None => Err(self.unsupported(inst)),
707        }
708    }
709
710    /// The register a value is in, materializing it if it is a constant that has not been put in
711    /// one yet.
712    ///
713    /// A constant is written where it is wanted rather than where the IR defined it, and where it
714    /// is wanted is a block that need not be the one the IR defined it in. So the register holding
715    /// one is only good inside the block it was written into, and a second block that wants the
716    /// same constant gets its own. Anything else is a register read where nothing wrote it: the
717    /// IR guarantees a definition dominates its uses, and this moved the definition.
718    ///
719    /// Writing the number again is also the right answer and not merely the safe one. It is one
720    /// instruction that reads nothing, which is cheaper than holding a register live across a
721    /// branch for it, and it is what a rematerializing allocator would do with the value anyway.
722    fn reg_of(&mut self, value: Value) -> Result<mir::Reg, Unsupported> {
723        let constant = match self.source[value].def {
724            Def::Result { inst, .. } => {
725                (self.source[inst].opcode == Opcode::IConst).then_some(inst)
726            }
727            Def::Param { .. } => None,
728        };
729        let here = self.at.expect("a block is being filled");
730        if let Some(reg) = self.regs[value.index()] {
731            if constant.is_none() || self.written[value.index()] == Some(here) {
732                return Ok(reg);
733            }
734        }
735        if let Some(inst) = constant {
736            // Cleared so that the register the constant is written into is a new one rather than
737            // the one the block above wrote, which is still being read up there.
738            self.regs[value.index()] = None;
739            let matched = self
740                .select(inst)
741                .map(|(_, matched)| matched)
742                .ok_or_else(|| self.unsupported(inst))?;
743            self.emit(inst, &matched)?;
744            self.written[value.index()] = Some(here);
745            return Ok(self.regs[value.index()].expect("a constant is written into a register"));
746        }
747        Ok(self.new_reg(value))
748    }
749
750    /// A fresh register for a value, which is what the instruction computing it writes.
751    fn new_reg(&mut self, value: Value) -> mir::Reg {
752        if let Some(reg) = self.regs[value.index()] {
753            return reg;
754        }
755        let reg = self.out.new_vreg(self.gpr);
756        self.regs[value.index()] = Some(reg);
757        reg
758    }
759
760    fn unsupported(&self, inst: Inst) -> Unsupported {
761        Unsupported::Inst { inst, term: Terms::new(self.source, inst, PLAIN).name(inst) }
762    }
763}
764
765/// What the arguments of one replacement came to.
766#[derive(Debug, Default)]
767struct Read {
768    regs: Vec<mir::Reg>,
769    imm: Option<i64>,
770    mem: Option<mir::Mem>,
771}
772
773/// The addressing mode an address constructor's arguments make.
774///
775/// One arm per constructor rather than a question asked of the kind, because what the arguments
776/// mean is the whole of what tells the four apart: the same register is a base in one and an
777/// index in another, and the same constant is a scale in one and a displacement in another.
778fn address(kind: x86_64::Address, read: &Read, gpr: RegClass) -> Option<mir::Mem> {
779    let mut regs = read.regs.iter().copied().map(|reg| mir::Operand::read(reg, gpr));
780    match kind {
781        x86_64::Address::BaseIndexScale => {
782            let base = regs.next()?;
783            let index = regs.next()?;
784            Some(mir::Mem::at(base).indexed(index, u8::try_from(read.imm?).ok()?))
785        }
786        x86_64::Address::IndexScale => Some(mir::Mem {
787            base: None,
788            index: Some(regs.next()?),
789            scale: u8::try_from(read.imm?).ok()?,
790            disp: 0,
791            symbol: None,
792        }),
793        x86_64::Address::Base => Some(mir::Mem::at(regs.next()?)),
794        // The rule that writes this has a guard saying the constant fits, so a displacement that
795        // does not is a rule and a target that disagree rather than a program this cannot compile.
796        x86_64::Address::BaseOffset => {
797            Some(mir::Mem { disp: i32::try_from(read.imm?).ok()?, ..mir::Mem::at(regs.next()?) })
798        }
799    }
800}
801
802/// The table this selector matches with.
803///
804/// One target for now, because one target has a rule file. Which table to use becomes a question
805/// the moment a second one does, and the answer will be the target the session was given rather
806/// than a constant here.
807static TABLE: &Table = &crate::select::x86_64::TABLE;
808
809#[cfg(test)]
810mod tests {
811    use rucc_ir::{Builder, CallInfo, Flags, InstData, MemInfo, MemOrder, Signature, Type};
812    use rucc_regalloc::assign::Env;
813    use rucc_target::x86_64::{FRAME, REGS, SYSV};
814
815    use super::*;
816    use crate::finish::finish;
817    use crate::frame::{Frame, Layout};
818
819    /// A function of as many 64 bit parameters as the test wants, and the block they are in.
820    fn blank(params: &[Type]) -> (Interner, Func, Block, Vec<Value>) {
821        let mut names = Interner::new();
822        let mut func = Func::new(names.intern("f"), Signature::new());
823        let block = func.create_block();
824        let values = params.iter().map(|&ty| func.append_param(block, ty)).collect();
825        (names, func, block, values)
826    }
827
828    /// An ordinary access: not atomic, and aligned enough that nothing here has an opinion.
829    /// Neither field reaches selection, which is the point of saying it once here.
830    fn plain() -> MemInfo {
831        MemInfo { size: 0, align: 1, order: MemOrder::NotAtomic, tbaa: None }
832    }
833
834    /// What the allocator is given: every integer register the convention offers except two, held
835    /// back so that a move on an edge has somewhere to break a cycle and a spilled value has
836    /// somewhere to be read into. Which two does not matter, and holding back the last two the
837    /// convention would reach for leaves every expectation below unchanged.
838    fn env() -> Env {
839        const SCRATCH: [rucc_target::PhysReg; 2] = [x86_64::R10, x86_64::R11];
840        let order: Vec<rucc_target::PhysReg> =
841            SYSV.int_order.iter().copied().filter(|reg| !SCRATCH.contains(reg)).collect();
842        Env::new().with(x86_64::GPR, &order, &SCRATCH)
843    }
844
845    /// The machine IR text a function lowers to.
846    fn lower(names: &mut Interner, source: &Func) -> String {
847        let out = func(source, names, &SYSV).expect("every instruction has a rule");
848        mir::print_func(&out.func, names, &REGS)
849    }
850
851    #[test]
852    fn an_addition_of_two_registers_is_one_instruction() {
853        let i32 = Type::int(32);
854        let (mut names, mut func, block, args) = blank(&[i32, i32]);
855        let mut build = Builder::new(&mut func, block);
856        build.binary(Opcode::Add, args[0], args[1], Flags::default());
857
858        assert_eq!(
859            lower(&mut names, &func),
860            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_32\n    \
861             %1:gpr($rsi) = x64.arg_val_32\n    %2:gpr(reuse 1) = x64.add_rr_32 %0, %1\n}\n"
862        );
863    }
864
865    #[test]
866    fn a_constant_operand_becomes_an_immediate() {
867        let i32 = Type::int(32);
868        let (mut names, mut func, block, args) = blank(&[i32]);
869        let mut build = Builder::new(&mut func, block);
870        let seven = build.iconst(i32, 7);
871        build.binary(Opcode::Add, args[0], seven, Flags::default());
872
873        // The constant is in the instruction and nothing was written to hold it, which is what
874        // materializing one where a register for it is wanted buys.
875        assert_eq!(
876            lower(&mut names, &func),
877            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_32\n    \
878             %1:gpr(reuse 1) = x64.add_ri_32 %0, 7\n}\n"
879        );
880    }
881
882    #[test]
883    fn a_constant_too_wide_for_an_immediate_goes_into_a_register() {
884        let i64 = Type::int(64);
885        let (mut names, mut func, block, args) = blank(&[i64]);
886        let mut build = Builder::new(&mut func, block);
887        let big = build.iconst(i64, i128::from(i32::MAX) + 1);
888        build.binary(Opcode::Add, args[0], big, Flags::default());
889
890        // Nobody wrote this fallback down. The rule that takes an immediate has a guard that
891        // turns a number this wide down, so it does not fire, and the next way of showing the
892        // operand puts it in a register.
893        assert_eq!(
894            lower(&mut names, &func),
895            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_64\n    \
896             %1:gpr = x64.mov_ri_64 2147483648\n    %2:gpr(reuse 1) = x64.add_rr_64 %0, %1\n}\n"
897        );
898    }
899
900    #[test]
901    fn an_index_calculation_folds_into_an_address() {
902        let i64 = Type::int(64);
903        let (mut names, mut func, block, args) = blank(&[i64, i64]);
904        let mut build = Builder::new(&mut func, block);
905        let four = build.iconst(i64, 4);
906        let scaled = build.binary(Opcode::Mul, args[1], four, Flags::default());
907        build.binary(Opcode::Add, args[0], scaled, Flags::default());
908
909        // Three IR instructions and one machine instruction. The multiply is gone because the
910        // rule that matched reached down and took it.
911        assert_eq!(
912            lower(&mut names, &func),
913            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_64\n    \
914             %1:gpr($rsi) = x64.arg_val_64\n    %2:gpr = x64.lea_64 [%0 + %1*4]\n}\n"
915        );
916    }
917
918    #[test]
919    fn an_instruction_read_twice_is_not_folded_into_either_reader() {
920        let i64 = Type::int(64);
921        let (mut names, mut func, block, args) = blank(&[i64, i64]);
922        let mut build = Builder::new(&mut func, block);
923        let four = build.iconst(i64, 4);
924        let scaled = build.binary(Opcode::Mul, args[1], four, Flags::default());
925        let first = build.binary(Opcode::Add, args[0], scaled, Flags::default());
926        build.binary(Opcode::Add, first, scaled, Flags::default());
927
928        // Folding it into both would compute it twice, which is not a saving, so it stays where
929        // it is and both readers read the register it wrote.
930        let text = lower(&mut names, &func);
931        assert!(text.contains("x64.lea_64 [%1*4]"), "{text}");
932        assert_eq!(text.matches("x64.add_rr_64").count(), 2, "{text}");
933    }
934
935    #[test]
936    fn a_shift_by_a_register_asks_for_it_in_cl() {
937        let i32 = Type::int(32);
938        let (mut names, mut func, block, args) = blank(&[i32, i32]);
939        let mut build = Builder::new(&mut func, block);
940        build.binary(Opcode::Shl, args[0], args[1], Flags::default());
941
942        // The fixed register is not in the rule. It is what the target says the instruction does
943        // with its operands, and the allocator is what will act on it.
944        let text = lower(&mut names, &func);
945        assert!(text.contains("x64.shl_rcl_32 %0, %1($rcx)"), "{text}");
946    }
947
948    #[test]
949    fn a_division_names_the_registers_and_the_register_it_destroys() {
950        let i32 = Type::int(32);
951        let (mut names, mut func, block, args) = blank(&[i32, i32]);
952        let mut build = Builder::new(&mut func, block);
953        build.binary(Opcode::SDiv, args[0], args[1], Flags::default());
954
955        // Two definitions, because a division writes the remainder whether anybody wanted it or
956        // not, and the second one is early because it is destroyed before the operands are read.
957        let text = lower(&mut names, &func);
958        assert!(
959            text.contains("%2:gpr($rax), early %3:gpr($rdx) = x64.idiv_quo_32 %0($rax), %1"),
960            "{text}"
961        );
962    }
963
964    #[test]
965    fn a_load_reads_through_the_register_the_address_is_in() {
966        let i64 = Type::int(64);
967        let (mut names, mut func, block, args) = blank(&[i64]);
968        let mut build = Builder::new(&mut func, block);
969        build.load(Type::int(32), args[0], plain(), Flags::default());
970
971        assert_eq!(
972            lower(&mut names, &func),
973            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_64\n    \
974             %1:gpr = x64.mov_rm_32 [%0]\n}\n"
975        );
976    }
977
978    #[test]
979    fn a_store_writes_no_register_and_the_value_it_writes_is_the_one_the_ir_gave_it() {
980        let (mut names, mut func, block, args) = blank(&[Type::int(32), Type::int(64)]);
981        let mut build = Builder::new(&mut func, block);
982        build.store(args[0], args[1], plain(), Flags::default());
983
984        // The value is the first parameter and the address is the second, and the instruction
985        // takes them the other way round. Getting that backwards would compile to a store of the
986        // address into the value, which is a program that runs and does the wrong thing.
987        assert_eq!(
988            lower(&mut names, &func),
989            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_32\n    \
990             %1:gpr($rsi) = x64.arg_val_64\n    x64.mov_mr_32 %0, [%1]\n}\n"
991        );
992    }
993
994    #[test]
995    fn an_address_with_a_constant_added_folds_into_the_access() {
996        let i64 = Type::int(64);
997        let (mut names, mut func, block, args) = blank(&[i64]);
998        let mut build = Builder::new(&mut func, block);
999        let twelve = build.iconst(i64, 12);
1000        let field = build.binary(Opcode::Add, args[0], twelve, Flags::default());
1001        build.load(Type::int(64), field, plain(), Flags::default());
1002
1003        // Two IR instructions and one machine instruction, which is what every read of a field
1004        // of a structure comes to.
1005        assert_eq!(
1006            lower(&mut names, &func),
1007            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_64\n    \
1008             %1:gpr = x64.mov_rm_64 [%0 + 12]\n}\n"
1009        );
1010    }
1011
1012    #[test]
1013    fn a_displacement_too_wide_to_encode_leaves_the_addition_where_it_is() {
1014        let i64 = Type::int(64);
1015        let (mut names, mut func, block, args) = blank(&[i64]);
1016        let mut build = Builder::new(&mut func, block);
1017        let big = build.iconst(i64, i128::from(i32::MAX) + 1);
1018        let far = build.binary(Opcode::Add, args[0], big, Flags::default());
1019        build.load(Type::int(32), far, plain(), Flags::default());
1020
1021        // A displacement is signed and 32 bits. The rule that folds one has a guard that turns
1022        // this down, so the addition stays and the load reads through what it produced. Nobody
1023        // wrote that fallback: it is the next way of showing the operand.
1024        let text = lower(&mut names, &func);
1025        assert!(text.contains("x64.mov_rm_32 [%2]"), "{text}");
1026        assert!(text.contains("x64.add_rr_64"), "{text}");
1027    }
1028
1029    #[test]
1030    fn a_store_of_a_value_that_was_loaded_is_two_instructions_and_no_arithmetic() {
1031        let i64 = Type::int(64);
1032        let (mut names, mut func, block, args) = blank(&[i64, i64]);
1033        let mut build = Builder::new(&mut func, block);
1034        let got = build.load(Type::int(8), args[0], plain(), Flags::default());
1035        build.store(got, args[1], plain(), Flags::default());
1036
1037        // A load feeding a store is the one place folding would be wrong: an x86-64 `mov` has at
1038        // most one memory operand, and there is no rule that takes two, so the load is left where
1039        // it is and the store reads the register it wrote.
1040        assert_eq!(
1041            lower(&mut names, &func),
1042            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_64\n    \
1043             %1:gpr($rsi) = x64.arg_val_64\n    %2:gpr = x64.mov_rm_8 [%0]\n    \
1044             x64.mov_mr_8 %2, [%1]\n}\n"
1045        );
1046    }
1047
1048    #[test]
1049    fn an_access_at_a_width_no_rule_is_written_at_is_reported() {
1050        let i64 = Type::int(64);
1051        let (mut names, mut source, block, args) = blank(&[i64]);
1052        let mut build = Builder::new(&mut source, block);
1053        build.load(Type::int(128), args[0], plain(), Flags::default());
1054
1055        let failed = func(&source, &mut names, &SYSV).expect_err("nothing loads 128 bits");
1056        assert_eq!(failed.to_string(), "no rule lowers this instruction");
1057    }
1058
1059    #[test]
1060    fn a_return_asks_for_the_value_in_the_register_the_caller_reads() {
1061        let (mut names, mut func, block, args) = blank(&[Type::int(32)]);
1062        let mut build = Builder::new(&mut func, block);
1063        build.ret(&[args[0]]);
1064
1065        // The register is not in the rule, the same way `cl` is not in the rule for a shift. It
1066        // is what the target says the instruction does with its operand, and the allocator is
1067        // what will act on it. There is no `ret` here, because giving the frame back has to
1068        // happen between this and leaving and the frame is not worked out yet.
1069        assert_eq!(
1070            lower(&mut names, &func),
1071            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_32\n    \
1072             x64.ret_val_32 %0($rax)\n}\n"
1073        );
1074    }
1075
1076    #[test]
1077    fn a_return_of_a_constant_puts_it_in_a_register_first() {
1078        let (mut names, mut func, block, _) = blank(&[]);
1079        let mut build = Builder::new(&mut func, block);
1080        let zero = build.iconst(Type::int(32), 0);
1081        build.ret(&[zero]);
1082
1083        // No rule returns an immediate, so the plan that offers one is turned down and the next
1084        // one materializes it. That is `int main(void) { return 0; }` in full, once the epilogue
1085        // is appended to it.
1086        assert_eq!(
1087            lower(&mut names, &func),
1088            "mfunc @f {\nblock0:\n    %0:gpr = x64.mov_ri_32 0\n    x64.ret_val_32 %0($rax)\n}\n"
1089        );
1090    }
1091
1092    #[test]
1093    fn a_return_of_nothing_is_no_instruction_at_all() {
1094        let (mut names, mut func, block, _) = blank(&[]);
1095        let mut build = Builder::new(&mut func, block);
1096        build.ret(&[]);
1097
1098        // Every part of leaving a function that returns nothing is the epilogue's, and the
1099        // epilogue goes in after allocation. A block with nothing in it is the right answer here
1100        // rather than a function that could not be lowered.
1101        assert_eq!(lower(&mut names, &func), "mfunc @f {\nblock0:\n}\n");
1102    }
1103
1104    #[test]
1105    fn the_allocator_is_what_moves_the_answer_into_the_return_register() {
1106        let (mut names, mut source, block, _) = blank(&[]);
1107        let mut build = Builder::new(&mut source, block);
1108        let zero = build.iconst(Type::int(32), 0);
1109        build.ret(&[zero]);
1110
1111        let mut out = func(&source, &mut names, &SYSV).expect("every instruction has a rule").func;
1112        let env = env();
1113        let allocation = rucc_regalloc::run(&mut out, &env);
1114        let frame = Frame::of(&out, &allocation, &Layout::new(&SYSV, REGS));
1115        finish(&mut out, &allocation, &frame, &[], &SYSV, &FRAME, &mut names);
1116
1117        // `int main(void) { return 0; }` end to end. Nothing here asked for `rax`: the rule said
1118        // the value goes back, the target said where, and the allocator is what made it true. The
1119        // epilogue is what leaves, and this function needs no frame, so it is the return alone.
1120        //
1121        // The copy is a register allocator that takes no hints. It hands `%0` a register at the
1122        // instruction that writes it, where it does not yet know that a later use insists on
1123        // `rax`, and `rax` is not free to hand out because that later use is holding it. So the
1124        // value goes somewhere else and is copied in. Every division and every shift by a
1125        // register already pays the same thing, and paying it once per return is what makes it
1126        // worth fixing rather than a new problem.
1127        assert_eq!(
1128            mir::print_func(&out, &names, &REGS),
1129            "mfunc @f {\nblock0:\n    $rcx = x64.mov_ri_32 0\n    $rax = x64.mov_rr_64 $rcx\n    \
1130             x64.ret_val_32 $rax($rax)\n    x64.ret\n}\n"
1131        );
1132    }
1133
1134    #[test]
1135    fn a_function_of_two_arguments_is_a_whole_function_now() {
1136        let i32 = Type::int(32);
1137        let (mut names, mut source, block, args) = blank(&[i32, i32]);
1138        let mut build = Builder::new(&mut source, block);
1139        let sum = build.binary(Opcode::Add, args[0], args[1], Flags::default());
1140        build.ret(&[sum]);
1141
1142        let mut out = func(&source, &mut names, &SYSV).expect("every instruction has a rule").func;
1143        let env = env();
1144        let allocation = rucc_regalloc::run(&mut out, &env);
1145        let frame = Frame::of(&out, &allocation, &Layout::new(&SYSV, REGS));
1146        finish(&mut out, &allocation, &frame, &[], &SYSV, &FRAME, &mut names);
1147
1148        // `int f(int a, int b) { return a + b; }` end to end, and this is the test the argument
1149        // side exists for. Before it there was no way to write one: the allocator refuses a
1150        // function whose entry block takes parameters, because there is no edge into an entry
1151        // block for the moves that give a block parameter its value to go on.
1152        //
1153        // Four moves that a good allocator writes none of, and it is the same allocator that
1154        // takes no hints as in the return above rather than anything new. It hands each argument
1155        // a register at the pseudo that defines it, without looking at the fixed register that
1156        // pseudo insists on, so every argument is copied straight back out of where it already
1157        // was. Issue #255 is this, and this function is the shortest program that shows what it
1158        // costs: one hint per argument and one per return would leave nothing here but the
1159        // addition. What the test is for meanwhile is that the answer is right, and it is: the
1160        // copy in front of a two address instruction is what makes its destination one of the
1161        // registers it reads, and the source operand keeps its own name because the destination
1162        // is what the encoder writes.
1163        assert_eq!(
1164            mir::print_func(&out, &names, &REGS),
1165            "mfunc @f {\nblock0:\n    $rdi($rdi) = x64.arg_val_32\n    \
1166             $rax = x64.mov_rr_64 $rdi\n    $rsi($rsi) = x64.arg_val_32\n    \
1167             $rcx = x64.mov_rr_64 $rsi\n    $rdx = x64.mov_rr_64 $rax\n    \
1168             $rdx(reuse 1) = x64.add_rr_32 $rax, $rcx\n    $rax = x64.mov_rr_64 $rdx\n    \
1169             x64.ret_val_32 $rax($rax)\n    x64.ret\n}\n"
1170        );
1171    }
1172
1173    #[test]
1174    fn an_argument_with_no_register_left_for_it_is_reported() {
1175        let i64 = Type::int(64);
1176        let (mut names, mut source, block, args) = blank(&[i64; 7]);
1177        let mut build = Builder::new(&mut source, block);
1178        build.ret(&[args[6]]);
1179
1180        // SysV passes six integers in registers and the seventh on the stack, and reading it from
1181        // there means knowing where the frame put it, which nothing knows until the allocator has
1182        // finished. So this is reported rather than compiled to a read of whatever `r9` still had.
1183        let failed = func(&source, &mut names, &SYSV).expect_err("the seventh is on the stack");
1184        assert_eq!(failed.to_string(), "parameter 6 is passed on the stack");
1185    }
1186
1187    #[test]
1188    fn a_jump_is_the_edge_and_nothing_else() {
1189        let i32 = Type::int(32);
1190        let (mut names, mut source, entry, args) = blank(&[i32]);
1191        let next = source.create_block();
1192        let got = source.append_param(next, i32);
1193        Builder::new(&mut source, entry).jump(next, &[args[0]]);
1194        Builder::new(&mut source, next).ret(&[got]);
1195
1196        // Two blocks and two instructions, and the jump is neither of them. What it was is the
1197        // arm on the first block, and what the arm carries is the argument it was called with.
1198        assert_eq!(
1199            lower(&mut names, &source),
1200            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_32 block1(%0)\n\n\
1201             block1(%1:gpr):\n    x64.ret_val_32 %1($rax)\n}\n"
1202        );
1203    }
1204
1205    /// A constant is written where it is wanted rather than where the IR defined it, and two
1206    /// blocks wanting the same one is two places. Writing it once and reading it in both is a
1207    /// register read where nothing wrote it, unless the block it was written in happens to
1208    /// dominate the other, which nothing here checks and which the second arm of a branch never
1209    /// does. Each block gets its own copy of the number instead.
1210    #[test]
1211    fn a_constant_two_blocks_want_is_written_in_both_of_them() {
1212        let i32 = Type::int(32);
1213        let (mut names, mut source, entry, args) = blank(&[i32, i32]);
1214        let then = source.create_block();
1215        let other = source.create_block();
1216        let join = source.create_block();
1217        let got = source.append_param(join, i32);
1218
1219        let mut build = Builder::new(&mut source, entry);
1220        let seven = build.iconst(i32, 7);
1221        let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
1222        build.br_if(cond, then, &[], other, &[]);
1223        // Both arms want the seven in a register, because a block argument is never an immediate,
1224        // and neither arm dominates the other.
1225        Builder::new(&mut source, then).jump(join, &[seven]);
1226        Builder::new(&mut source, other).jump(join, &[seven]);
1227        Builder::new(&mut source, join).ret(&[got]);
1228
1229        let text = lower(&mut names, &source);
1230        assert_eq!(text.matches("x64.mov_ri_32 7").count(), 2, "one seven per block: {text}");
1231    }
1232
1233    /// An argument on an edge out of a block that leaves two ways is read after every instruction
1234    /// of the block is written, and reading one can write an instruction, which would land after
1235    /// the branch that has already jumped past it. The branch goes back on the end.
1236    #[test]
1237    fn a_constant_an_edge_wants_is_written_before_the_branch_and_not_after_it() {
1238        let i32 = Type::int(32);
1239        let (mut names, mut source, entry, args) = blank(&[i32, i32]);
1240        let then = source.create_block();
1241        let join = source.create_block();
1242        let got = source.append_param(join, i32);
1243
1244        let mut build = Builder::new(&mut source, entry);
1245        let nine = build.iconst(i32, 9);
1246        let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
1247        build.br_if(cond, then, &[], join, &[nine]);
1248        Builder::new(&mut source, then).jump(join, &[args[0]]);
1249        Builder::new(&mut source, join).ret(&[got]);
1250
1251        let out = func(&source, &mut names, &SYSV).expect("every instruction has a rule").func;
1252        let entry = out.entry().expect("an entry block");
1253        let last = out.terminator(entry).expect("a block that leaves two ways has a branch");
1254        let branch = names.intern("x64.br_cond_8");
1255        assert_eq!(
1256            out[last].opcode,
1257            mir::Opcode::new(branch),
1258            "the branch is last: {}",
1259            mir::print_func(&out, &names, &REGS)
1260        );
1261    }
1262
1263    #[test]
1264    fn a_conditional_branch_is_lowered_to_the_condition_and_nothing_about_where_it_goes() {
1265        let i32 = Type::int(32);
1266        let (mut names, mut source, entry, args) = blank(&[i32, i32]);
1267        let then = source.create_block();
1268        let other = source.create_block();
1269        let mut build = Builder::new(&mut source, entry);
1270        let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
1271        build.br_if(cond, then, &[], other, &[]);
1272        Builder::new(&mut source, then).ret(&[args[0]]);
1273        Builder::new(&mut source, other).ret(&[args[1]]);
1274
1275        // The comparison writes a byte and the branch reads it, and neither says a block. Both
1276        // arms are on the entry block, in the order the branch took them, so the arm that runs
1277        // when the condition holds is the first.
1278        assert_eq!(
1279            lower(&mut names, &source),
1280            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_32\n    \
1281             %1:gpr($rsi) = x64.arg_val_32\n    %2:gpr = x64.cmp_set_l_32 %0, %1\n    \
1282             x64.br_cond_8 %2, block1, block2\n\n\
1283             block1:\n    x64.ret_val_32 %0($rax)\n\n\
1284             block2:\n    x64.ret_val_32 %1($rax)\n}\n"
1285        );
1286    }
1287
1288    #[test]
1289    fn a_branch_over_a_block_is_a_whole_function_now() {
1290        let i32 = Type::int(32);
1291        let (mut names, mut source, entry, args) = blank(&[i32, i32]);
1292        let then = source.create_block();
1293        let other = source.create_block();
1294        let join = source.create_block();
1295        let got = source.append_param(join, i32);
1296        let mut build = Builder::new(&mut source, entry);
1297        let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
1298        build.br_if(cond, then, &[], other, &[]);
1299        let mut build = Builder::new(&mut source, then);
1300        let sum = build.binary(Opcode::Add, args[0], args[1], Flags::default());
1301        build.jump(join, &[sum]);
1302        Builder::new(&mut source, other).jump(join, &[args[1]]);
1303        Builder::new(&mut source, join).ret(&[got]);
1304
1305        // `int f(int a, int b) { if (a < b) return a + b; else return b; }` end to end, written
1306        // the way a front end writes it: both arms of the branch are blocks of their own and the
1307        // return is the block they meet at. No edge here is critical, because the two arms out of
1308        // the entry carry nothing and the two arms into the join each leave a block that goes
1309        // nowhere else, so each has its own end to put its move at.
1310        let mut out = func(&source, &mut names, &SYSV).expect("every instruction has a rule").func;
1311        assert_eq!(crate::split::critical(&mut out), 0, "no edge here is critical");
1312        let env = env();
1313        let allocation = rucc_regalloc::run(&mut out, &env);
1314        let frame = Frame::of(&out, &allocation, &Layout::new(&SYSV, REGS));
1315        finish(&mut out, &allocation, &frame, &[], &SYSV, &FRAME, &mut names);
1316
1317        // One epilogue, on the join, which is the one block the function leaves from, and the
1318        // moves that give the join its parameter are at the end of each arm. Every register is
1319        // physical and the branch is still a branch on a register, because turning it into a
1320        // `test` and a `jcc` is the block layout's and there is no block layout yet.
1321        let text = mir::print_func(&out, &names, &REGS);
1322        assert_eq!(text.matches("x64.ret\n").count(), 1, "{text}");
1323        assert!(text.contains("x64.br_cond_8"), "{text}");
1324        assert!(text.contains("x64.add_rr_32"), "{text}");
1325        assert!(!text.contains('%'), "{text}");
1326    }
1327
1328    #[test]
1329    fn a_critical_edge_is_split_before_the_allocator_ever_sees_it() {
1330        let i32 = Type::int(32);
1331        let (mut names, mut source, entry, args) = blank(&[i32, i32]);
1332        let then = source.create_block();
1333        let join = source.create_block();
1334        let got = source.append_param(join, i32);
1335        let mut build = Builder::new(&mut source, entry);
1336        let cond = build.icmp(rucc_ir::IntPred::Slt, args[0], args[1]);
1337        build.br_if(cond, then, &[], join, &[args[1]]);
1338        Builder::new(&mut source, then).jump(join, &[args[0]]);
1339        let mut build = Builder::new(&mut source, join);
1340        let twice = build.binary(Opcode::Add, got, got, Flags::default());
1341        build.ret(&[twice]);
1342
1343        // The else arm is critical: the entry block leaves two ways and the join is arrived at
1344        // two ways, and the arm carries a value. Without splitting it the allocator asserts,
1345        // because the move that gives the join its parameter would have to run at the end of a
1346        // block that also goes to the other arm.
1347        let mut out = func(&source, &mut names, &SYSV).expect("every instruction has a rule").func;
1348        assert_eq!(crate::split::critical(&mut out), 1);
1349        let env = env();
1350        let allocation = rucc_regalloc::run(&mut out, &env);
1351        let frame = Frame::of(&out, &allocation, &Layout::new(&SYSV, REGS));
1352        finish(&mut out, &allocation, &frame, &[], &SYSV, &FRAME, &mut names);
1353
1354        // The block the split added is where the move went, and it is the whole of that block.
1355        let text = mir::print_func(&out, &names, &REGS);
1356        assert_eq!(out.block_count(), 4, "{text}");
1357        assert_eq!(text.matches("x64.ret\n").count(), 1, "{text}");
1358    }
1359
1360    #[test]
1361    fn a_call_passes_what_the_convention_says_and_takes_back_what_it_says() {
1362        let i32 = Type::int(32);
1363        let (mut names, mut source, block, args) = blank(&[i32, i32]);
1364        let sig =
1365            source.add_signature(Signature::new().with_params(&[i32, i32]).with_returns(&[i32]));
1366        let callee = names.intern("g");
1367        let call = Builder::new(&mut source, block).call(callee, sig, &[args[0], args[1]]);
1368        let got = source[call].first_result.expect("an integer comes back");
1369        Builder::new(&mut source, block).ret(&[got]);
1370
1371        // `int f(int a, int b) { return g(a, b); }`. The arguments arrived where the call wants
1372        // them, so what the call reads is what arrived, and the whole of the convention is in the
1373        // constraints rather than in a move.
1374        let text = lower(&mut names, &source);
1375        assert!(text.contains("= x64.call %0($rdi), %1($rsi), @g"), "{text}");
1376        assert!(text.contains("x64.ret_val_32 %2($rax)"), "{text}");
1377        // What the call writes is the value that comes back and then every register the callee is
1378        // free to destroy, in both classes, which is the whole of what stops the allocator from
1379        // leaving something in one of them.
1380        assert!(text.contains("%2:gpr($rax), $rcx, $rdx, $r8, $r9, $r10, $r11, $xmm0,"), "{text}");
1381        assert!(text.contains("$xmm15 = x64.call"), "{text}");
1382    }
1383
1384    #[test]
1385    fn what_the_frame_owes_a_call_comes_back_with_the_function() {
1386        let i32 = Type::int(32);
1387        let sig = |source: &mut Func| source.add_signature(Signature::new().with_params(&[i32]));
1388
1389        let (mut names, mut source, block, args) = blank(&[i32]);
1390        let sig = sig(&mut source);
1391        let callee = names.intern("g");
1392        Builder::new(&mut source, block).call(callee, sig, &[args[0]]);
1393        let out = func(&source, &mut names, &SYSV).expect("every instruction has a rule");
1394
1395        // Nothing on the stack, so nothing owed, but not a leaf either: a function that calls
1396        // owes the callee an aligned stack pointer and may not use the red zone.
1397        assert_eq!(out.stack.calls, Some(0));
1398        let layout = out.stack.layout(Layout::new(&SYSV, REGS));
1399        assert!(!layout.leaf);
1400        assert_eq!(layout.outgoing, 0);
1401
1402        // The same call under the other convention owes thirty two bytes for the callee to spill
1403        // its register arguments into, which is a fact about the convention and not about the call.
1404        let out = func(&source, &mut names, &x86_64::WIN64).expect("every instruction has a rule");
1405        assert_eq!(out.stack.calls, Some(32));
1406
1407        // And a function that calls nothing is a leaf, which is what says it may use the red zone.
1408        let (mut names, mut source, block, args) = blank(&[i32]);
1409        Builder::new(&mut source, block).ret(&[args[0]]);
1410        let out = func(&source, &mut names, &SYSV).expect("every instruction has a rule");
1411        assert_eq!(out.stack.calls, None);
1412        assert!(out.stack.layout(Layout::new(&SYSV, REGS)).leaf);
1413    }
1414
1415    #[test]
1416    fn a_value_that_outlives_a_call_is_not_left_where_the_call_destroys_it() {
1417        let i32 = Type::int(32);
1418        let (mut names, mut source, block, args) = blank(&[i32]);
1419        let sig = source.add_signature(Signature::new().with_params(&[i32]).with_returns(&[i32]));
1420        let callee = names.intern("g");
1421        let call = Builder::new(&mut source, block).call(callee, sig, &[args[0]]);
1422        let got = source[call].first_result.expect("an integer comes back");
1423        let mut build = Builder::new(&mut source, block);
1424        let sum = build.binary(Opcode::Add, got, args[0], Flags::default());
1425        build.ret(&[sum]);
1426
1427        // `int f(int a) { return g(a) + a; }`, which is the smallest program that asks the
1428        // question: `a` is read after the call and `rdi` is a register the call destroys.
1429        let lowered = func(&source, &mut names, &SYSV).expect("every instruction has a rule");
1430        let layout = lowered.stack.layout(Layout::new(&SYSV, REGS));
1431        let mut out = lowered.func;
1432        let env = env();
1433        let allocation = rucc_regalloc::run(&mut out, &env);
1434        let frame = Frame::of(&out, &allocation, &layout);
1435        finish(&mut out, &allocation, &frame, &[], &SYSV, &FRAME, &mut names);
1436
1437        // It went to a register the callee has to put back, and the prologue and epilogue are what
1438        // put it back, which is the whole bargain the two halves of a convention make.
1439        let text = mir::print_func(&out, &names, &REGS);
1440        assert!(text.contains("$rbx"), "{text}");
1441        assert!(!text.contains('%'), "{text}");
1442        assert_eq!(text.matches("x64.call").count(), 1, "{text}");
1443    }
1444
1445    #[test]
1446    fn a_call_this_cannot_make_is_reported_rather_than_made() {
1447        let i64 = Type::int(64);
1448        let (mut names, mut source, block, args) = blank(&[i64]);
1449        let seven = vec![i64; 7];
1450        let sig = source.add_signature(Signature::new().with_params(&seven));
1451        let callee = names.intern("g");
1452        let passed = vec![args[0]; 7];
1453        Builder::new(&mut source, block).call(callee, sig, &passed);
1454
1455        // The seventh argument travels on the stack, and where the stack put it is a distance into
1456        // a frame that does not exist until after allocation.
1457        let failed = func(&source, &mut names, &SYSV).expect_err("the seventh is on the stack");
1458        assert_eq!(failed.to_string(), "argument 6 of this call is passed on the stack");
1459
1460        let (mut names, mut source, block, _) = blank(&[]);
1461        let sig = source
1462            .add_signature(Signature::new().with_returns(&[Type::float(rucc_ir::Float::F64)]));
1463        let callee = names.intern("g");
1464        Builder::new(&mut source, block).call(callee, sig, &[]);
1465        let failed = func(&source, &mut names, &SYSV).expect_err("a double comes back in xmm0");
1466        assert_eq!(failed.to_string(), "what this call gives back is in a vector register");
1467    }
1468
1469    #[test]
1470    fn a_call_through_an_address_is_reported_as_one() {
1471        let i32 = Type::int(32);
1472        let (mut names, mut source, block, args) = blank(&[i32]);
1473        let sig = source.add_signature(Signature::new().with_params(&[i32]));
1474        let varargs = source.push_abis(&[]);
1475        let info = source.add_call(CallInfo { callee: None, signature: sig, varargs });
1476        let mut build = Builder::new(&mut source, block);
1477        let inst = InstData {
1478            args: build.func().push_values(&[args[0], args[0]]),
1479            extra: Extra::Call(info),
1480            ..InstData::new(Opcode::CallIndirect)
1481        };
1482        build.inst(inst, &[]);
1483
1484        // The address is a value in a register and the instruction that calls one of those is a
1485        // different instruction, which nothing describes yet.
1486        let failed = func(&source, &mut names, &SYSV).expect_err("nothing calls through a value");
1487        assert_eq!(failed.to_string(), "no rule calls through an address");
1488    }
1489
1490    #[test]
1491    fn an_instruction_no_rule_covers_is_reported() {
1492        let i64 = Type::int(64);
1493        let (mut names, mut source, block, args) = blank(&[i64, i64]);
1494        let mut build = Builder::new(&mut source, block);
1495        build.ret(&[args[0], args[1]]);
1496
1497        // Two values back at once. Where each of them goes is the convention's answer rather than
1498        // a term's, so the rule language has no name for it and no rule fires.
1499        let failed = func(&source, &mut names, &SYSV).expect_err("nothing returns two values");
1500        assert_eq!(failed.to_string(), "no rule lowers this instruction");
1501    }
1502
1503    /// An `alloca` of a fixed size, which is what every local whose address is taken becomes.
1504    fn slot(source: &mut Func, block: Block, size: u64, align: u32) -> Value {
1505        let info = MemInfo { size, align, ..plain() };
1506        let mut build = Builder::new(source, block);
1507        let mem = build.func().add_mem(info);
1508        build.value(InstData { extra: Extra::Mem(mem), ..InstData::new(Opcode::Alloca) }, Type::PTR)
1509    }
1510
1511    #[test]
1512    fn a_local_is_memory_in_the_frame_and_one_instruction_that_says_where() {
1513        let (mut names, mut source, block, _) = blank(&[]);
1514        let slot = slot(&mut source, block, 4, 4);
1515        let mut build = Builder::new(&mut source, block);
1516        let nine = build.iconst(Type::int(32), 9);
1517        build.store(nine, slot, plain(), Flags::default());
1518        let loaded = build.load(Type::int(32), slot, plain(), Flags::default());
1519        build.ret(&[loaded]);
1520
1521        let lowered = func(&source, &mut names, &SYSV).expect("every instruction has a rule");
1522
1523        // Four bytes on the list the frame is laid out from, and the one instruction that reads
1524        // where they went. Its displacement is nothing here because there is no frame yet, and
1525        // which instruction is waiting for which local is what `finish` is handed.
1526        assert_eq!(lowered.stack.locals, vec![Local { size: 4, align: 4 }]);
1527        assert_eq!(lowered.stack.addresses.len(), 1);
1528        assert_eq!(lowered.stack.addresses[0].1, 0);
1529        assert_eq!(
1530            mir::print_func(&lowered.func, &names, &REGS),
1531            "mfunc @f {\nblock0:\n    %0:gpr = x64.lea_64 [$rsp]\n    \
1532             %1:gpr = x64.mov_ri_32 9\n    x64.mov_mr_32 %1, [%0]\n    \
1533             %2:gpr = x64.mov_rm_32 [%0]\n    x64.ret_val_32 %2($rax)\n}\n"
1534        );
1535    }
1536
1537    #[test]
1538    fn the_frame_is_what_fills_the_address_of_a_local_in() {
1539        let (mut names, mut source, block, _) = blank(&[]);
1540        let slot = slot(&mut source, block, 4, 4);
1541        let mut build = Builder::new(&mut source, block);
1542        let nine = build.iconst(Type::int(32), 9);
1543        build.store(nine, slot, plain(), Flags::default());
1544        let loaded = build.load(Type::int(32), slot, plain(), Flags::default());
1545        build.ret(&[loaded]);
1546
1547        let lowered = func(&source, &mut names, &SYSV).expect("every instruction has a rule");
1548        let stack = lowered.stack;
1549        let mut out = lowered.func;
1550        let env = env();
1551        let allocation = rucc_regalloc::run(&mut out, &env);
1552        let layout = stack.layout(Layout::new(&SYSV, REGS));
1553        let frame = Frame::of(&out, &allocation, &layout);
1554        finish(&mut out, &allocation, &frame, &stack.addresses, &SYSV, &FRAME, &mut names);
1555
1556        // `int f(void) { int x; x = 9; return x; }` with the address of `x` taken, end to end.
1557        // A leaf small enough to live in the red zone takes no frame at all, so the stack pointer
1558        // never moves and the four bytes are below it, which is what the negative offset is. The
1559        // instruction the lowering left with nothing in its displacement now has the answer in it.
1560        let text = mir::print_func(&out, &names, &REGS);
1561        assert!(text.contains("$rax = x64.lea_64 [$rsp - 8]"), "{text}");
1562        assert!(!text.contains("x64.sub_ri_64"), "{text}");
1563        assert_eq!(frame.size(), 0);
1564        assert_eq!(frame.local(0), Some(-8));
1565    }
1566
1567    #[test]
1568    fn a_stack_slot_whose_size_is_not_known_until_it_runs_is_reported() {
1569        let i64 = Type::int(64);
1570        let (mut names, mut source, block, args) = blank(&[i64]);
1571        let info = MemInfo { size: 0, align: 16, ..plain() };
1572        let mut build = Builder::new(&mut source, block);
1573        let mem = build.func().add_mem(info);
1574        let size = build.func().push_values(&[args[0]]);
1575        let slot = build.value(
1576            InstData { args: size, extra: Extra::Mem(mem), ..InstData::new(Opcode::Alloca) },
1577            Type::PTR,
1578        );
1579        Builder::new(&mut source, block).ret(&[slot]);
1580
1581        // A variable length array. Growing the stack where the declaration stands means moving the
1582        // stack pointer in the middle of the function and reaching everything else through a
1583        // frame pointer afterwards, and the frame here lays out neither.
1584        let failed = func(&source, &mut names, &SYSV).expect_err("nothing grows the stack");
1585        assert_eq!(failed.to_string(), "nothing here grows the stack for a variable length array");
1586    }
1587
1588    #[test]
1589    fn an_address_is_read_written_and_added_to_like_the_integer_it_is() {
1590        let (mut names, mut source, block, args) = blank(&[Type::PTR, Type::int(64)]);
1591        let mut build = Builder::new(&mut source, block);
1592        let stepped = build.func().push_values(&[args[0], args[1]]);
1593        let next =
1594            build.value(InstData { args: stepped, ..InstData::new(Opcode::PtrAdd) }, Type::PTR);
1595        let loaded = build.load(Type::int(32), next, plain(), Flags::default());
1596        build.ret(&[loaded]);
1597
1598        // `int f(int *p, long i) { return *(int *)((char *)p + i); }`. Nothing about this is new
1599        // in the rule set, which is the point: the two addresses arrive in registers because an
1600        // address is an integer as wide as one, and the arithmetic on them is the add it always
1601        // was, so every rule written about an add reaches it.
1602        //
1603        // The add stays its own instruction rather than folding into the address the load reads
1604        // from. Two registers with no scale on either is the one addressing mode the rules have no
1605        // load through, because the folds that exist are the displacement one and the scaled ones,
1606        // and this is neither. That is a peephole worth having and not a thing this changes.
1607        assert_eq!(
1608            lower(&mut names, &source),
1609            "mfunc @f {\nblock0:\n    %0:gpr($rdi) = x64.arg_val_64\n    \
1610             %1:gpr($rsi) = x64.arg_val_64\n    %2:gpr(reuse 1) = x64.add_rr_64 %0, %1\n    \
1611             %3:gpr = x64.mov_rm_32 [%2]\n    x64.ret_val_32 %3($rax)\n}\n"
1612        );
1613    }
1614}