Skip to main content

rucc_ir/
inst.rs

1//! What one instruction is, and what a value is.
2//!
3//! Design: `spec/08-ir.md` sections 8.1 and 8.3.
4//!
5//! An instruction is an [`Opcode`], a set of [`Flags`], a run of value operands, and whatever
6//! else that opcode needs, which is [`Extra`]. Everything that fits in eight bytes is in the
7//! [`Extra`] itself and everything larger is an index into a side table, so the instruction
8//! stays small enough that walking a function is walking one dense array.
9//!
10//! A value is the result of an instruction or a parameter of a block, and it is nothing else.
11//! There is no constant operand kind: a constant is an [`Opcode::IConst`] with a result like
12//! any other instruction. That is what makes the dominance rule in the verifier a single rule
13//! with no exceptions, and it costs nothing, because a constant with no uses is deleted by the
14//! same pass that deletes anything else with no uses.
15
16use rucc_base::{Idx, IdxRange, Symbol};
17
18use rucc_target::Slot;
19
20use crate::{
21    ExtraKind, Flags, FloatPred, IntPred, MemOrder, Opcode, Owner, RmwOp, StorageClass, Type,
22};
23
24/// One value: the result of an instruction, or a parameter of a block.
25pub type Value = Idx<ValueData>;
26/// One instruction, in the function that owns it.
27pub type Inst = Idx<InstData>;
28/// One basic block, in the function that owns it.
29pub type Block = Idx<BlockData>;
30
31/// The table of references to values, which is what an operand list is a run of.
32#[derive(Debug)]
33pub struct ValueRef;
34/// A run of value operands.
35pub type ValueList = IdxRange<ValueRef>;
36/// A run of branch targets, which is what a terminator's successors are.
37pub type BlockCallList = IdxRange<BlockCall>;
38/// A run of immediates, which is what a `switch` holds its case values in.
39pub type ImmList = IdxRange<Imm>;
40/// A run of ABI attributes, which is what a call says about the arguments its signature does
41/// not name.
42pub type AbiList = IdxRange<Abi>;
43/// A run of eightbytes, which is how an object read off a variable argument list travelled.
44pub type SlotList = IdxRange<Slot>;
45
46/// A constant, in the immediate table.
47///
48/// The bits and nothing else. An integer is stored two's complement in as many of the low bits
49/// as its type is wide, and a floating point value is stored as its bit pattern, so the same
50/// table holds both and the type on the result says how to read it. That keeps a bit-preserving
51/// answer for a NaN payload, which a value of a Rust floating type would not.
52#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
53pub struct Imm(u128);
54
55impl Imm {
56    /// The bits, as they are stored.
57    #[must_use]
58    pub const fn bits(self) -> u128 {
59        self.0
60    }
61
62    /// An immediate holding these bits.
63    #[must_use]
64    pub const fn from_bits(bits: u128) -> Self {
65        Self(bits)
66    }
67
68    /// An integer, with the bits above `ty` cleared.
69    ///
70    /// A value is stored in exactly the width its type has, so two immediates are equal when
71    /// they are the same value, which is what lets an equality on the table stand in for an
72    /// equality on the numbers.
73    ///
74    /// # Panics
75    ///
76    /// Panics if `ty` is not an integer type.
77    #[must_use]
78    pub fn int(value: i128, ty: Type) -> Self {
79        assert!(ty.is_int(), "an integer immediate needs an integer type");
80        Self(value as u128 & mask(ty.bits()))
81    }
82
83    /// The value read as unsigned.
84    #[must_use]
85    pub const fn unsigned(self) -> u128 {
86        self.0
87    }
88
89    /// The value read as signed, with the sign bit of `ty` extended.
90    ///
91    /// # Panics
92    ///
93    /// Panics if `ty` is not an integer type.
94    #[must_use]
95    pub fn signed(self, ty: Type) -> i128 {
96        assert!(ty.is_int(), "an integer immediate needs an integer type");
97        let spare = 128 - ty.bits();
98        // Shifting left and then arithmetic right is the branch-free way to sign extend from
99        // an arbitrary width, and it is correct for a width of 128 because the shift is zero.
100        ((self.0 << spare) as i128) >> spare
101    }
102}
103
104/// The low `bits` bits set, and a width of 128 meaning all of them.
105fn mask(bits: u32) -> u128 {
106    if bits >= 128 { u128::MAX } else { (1u128 << bits) - 1 }
107}
108
109/// A branch target, and the values passed to it.
110///
111/// This is the whole reason there are no phi nodes. The arguments are here, in the branch,
112/// beside the block they go to, so removing a predecessor is one edit in one place and there
113/// is no second list anywhere that has to be kept in step with this one.
114#[derive(Clone, Copy, Debug, PartialEq, Eq)]
115pub struct BlockCall {
116    /// Where control goes.
117    pub block: Block,
118    /// What is passed, one for each of the block's parameters.
119    pub args: ValueList,
120}
121
122/// What defines a value.
123#[derive(Clone, Copy, Debug, PartialEq, Eq)]
124pub enum Def {
125    /// The result of an instruction, at this position among its results.
126    Result {
127        /// The instruction.
128        inst: Inst,
129        /// Which of its results this is.
130        index: u8,
131    },
132    /// A parameter of a block, at this position among its parameters.
133    Param {
134        /// The block.
135        block: Block,
136        /// Which of its parameters this is.
137        index: u32,
138    },
139}
140
141/// One value.
142#[derive(Clone, Copy, Debug, PartialEq, Eq)]
143pub struct ValueData {
144    /// Its type.
145    pub ty: Type,
146    /// Where it comes from.
147    pub def: Def,
148}
149
150/// What an access does beyond naming an address.
151#[derive(Clone, Copy, Debug, PartialEq, Eq)]
152pub struct MemInfo {
153    /// How many bytes the access covers, for the ones whose size is not their result type.
154    ///
155    /// A `load` takes its size from the type it produces. An `alloca` and a `memset` do not,
156    /// and this is where theirs is.
157    pub size: u64,
158    /// The alignment the access is known to have, in bytes.
159    pub align: u32,
160    /// How strongly it is ordered, with [`MemOrder::NotAtomic`] for an ordinary access.
161    pub order: MemOrder,
162    /// The type-based aliasing node, if the front end knew one.
163    pub tbaa: Option<Meta>,
164    /// How many bytes of its record this access owns, counting the padding after it.
165    ///
166    /// Zero for an access that is not a member of a record, and zero when the front end was not
167    /// asked to work it out. What it is for is the init plane of
168    /// `spec/safe-memory/09-type-init-and-races.md` section 9.3: under `-fsafety-init=nopadding`
169    /// a store through a member records the padding after the member as written too, so that a
170    /// record filled a member at a time comes out whole and the ordinary reads of it, which are a
171    /// `memcmp` or a hash or a `write` of the record, are not refused.
172    ///
173    /// Only the init plane reads it. A bounds check over these bytes would be asking about bytes
174    /// the access does not touch, and a type plane write over them would be saying the padding
175    /// holds a value of the member's type, which it does not.
176    pub owns: u32,
177    /// Which `restrict` scope the access is in and which pointer it went through.
178    pub restrict: Restrict,
179}
180
181/// Which `restrict` scope an access is in, and which pointer inside that scope it went through.
182///
183/// Two small numbers, which is the whole of the mechanism. GCC spells them
184/// `MR_DEPENDENCE_CLIQUE` and `MR_DEPENDENCE_BASE` at `gcc/tree-ssa-alias.cc:2503` and the rule
185/// is one line: same clique and different base means the two accesses cannot touch the same
186/// byte, because that is exactly what `restrict` promises. A clique is one scope, numbered as
187/// lowering enters it, and a base is one `restrict` pointer declared inside it. Clique zero
188/// means nothing is known, which is what every access that is not under a `restrict` gets.
189///
190/// This is spec 9.4's scope tree rather than a blanket assumption, and it costs four bytes that
191/// were padding in [`MemInfo`] already.
192#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
193pub struct Restrict {
194    /// The scope, with zero meaning no information.
195    pub clique: u16,
196    /// The pointer within that scope, which only means anything when the clique is not zero.
197    pub base: u16,
198}
199
200impl Restrict {
201    /// No information, which is what an access outside any `restrict` scope carries.
202    pub const NONE: Self = Self { clique: 0, base: 0 };
203
204    /// Whether `restrict` says these two accesses cannot touch the same byte.
205    ///
206    /// Only accesses. GCC's PR71062 is what happens when this answer is used to fold a
207    /// comparison of the two pointers: `restrict` constrains what is read and written through a
208    /// pointer and says nothing about what the pointer's value is, so two pointers that may not
209    /// be used to reach the same object can still compare equal. A rule that folds `p == q` to
210    /// false on the strength of this is wrong.
211    #[must_use]
212    pub const fn disjoint(self, other: Self) -> bool {
213        self.clique != 0 && self.clique == other.clique && self.base != other.base
214    }
215}
216
217/// A metadata node, in the module's table.
218pub type Meta = Idx<MetaNode>;
219
220/// A node of the metadata graph.
221///
222/// Two kinds share the one table and the one numbering, because both of them are the compiler's
223/// interned type universe seen from a different side and a reader chasing a `!3` should not have
224/// to know which table it came out of.
225#[derive(Clone, Copy, Debug, PartialEq, Eq)]
226pub enum MetaNode {
227    /// What aliasing needs: a type, and where it sits in the tree of types.
228    Tbaa(TbaaNode),
229    /// What the type plane needs: one entry in the vocabulary its bytes are written in.
230    Plane(PlaneNode),
231}
232
233impl MetaNode {
234    /// The aliasing node this is, or `None` when it is a plane entry.
235    #[must_use]
236    pub const fn tbaa(self) -> Option<TbaaNode> {
237        match self {
238            Self::Tbaa(node) => Some(node),
239            Self::Plane(_) => None,
240        }
241    }
242
243    /// The plane entry this is, or `None` when it is an aliasing node.
244    #[must_use]
245    pub const fn plane(self) -> Option<PlaneNode> {
246        match self {
247            Self::Plane(node) => Some(node),
248            Self::Tbaa(_) => None,
249        }
250    }
251
252    /// The node one level up, which a plane entry never has.
253    ///
254    /// The tree is the aliasing tree and a plane entry is not in it. A plane entry that names a
255    /// type points at a node of that tree, and that is a reference and not a parent: the walk
256    /// that answers an aliasing query has no business leaving the tree it is walking.
257    #[must_use]
258    pub const fn parent(self) -> Option<Meta> {
259        match self {
260            Self::Tbaa(node) => node.parent,
261            Self::Plane(_) => None,
262        }
263    }
264
265    /// The node it points at, which is the parent of an aliasing node and the type of a plane
266    /// entry, and is what has to come earlier in the table than the node itself.
267    #[must_use]
268    pub const fn points_at(self) -> Option<Meta> {
269        match self {
270            Self::Tbaa(node) => node.parent,
271            Self::Plane(PlaneNode::Type(node)) => Some(node),
272            Self::Plane(_) => None,
273        }
274    }
275}
276
277/// A node of the type based aliasing tree.
278///
279/// The tree this forms is checked by the verifier, since a cycle in it would make the aliasing
280/// query that walks it not terminate, and the place to find that out is here and not there.
281#[derive(Clone, Copy, Debug, PartialEq, Eq)]
282pub struct TbaaNode {
283    /// What this node is called, which is what the printer writes and the parser reads.
284    pub name: Symbol,
285    /// The node one level up, with the root having none.
286    pub parent: Option<Meta>,
287    /// The offset within the parent, for a member of a struct type.
288    pub offset: u64,
289}
290
291/// One entry in the type plane's vocabulary, per `spec/safe-memory/09-type-init-and-races.md`
292/// section 9.1.
293///
294/// The plane maps every byte to one of these, so this is what a `meta_type` writes and what a
295/// `check_type` is asking about. Three of the four are the distinguished values that document
296/// says the plane has beyond the types themselves, and they are why the plane needs a node kind
297/// of its own rather than pointing straight at an aliasing node: there is no aliasing node for
298/// "nobody has stored here yet".
299#[derive(Clone, Copy, Debug, PartialEq, Eq)]
300pub enum PlaneNode {
301    /// A type, named by the aliasing node that is that type.
302    ///
303    /// The same node the front end already interned, so the plane's vocabulary is exactly the
304    /// compiler's and a report can name a type in the spelling the source used.
305    Type(Meta),
306    /// Bytes nothing has stored through, or stored from an untyped source.
307    ///
308    /// Compatible with every access, because storage with no declared type takes its effective
309    /// type from the store, which is C's rule and is also the only choice that does not fire at
310    /// every boundary with uninstrumented code.
311    NoType,
312    /// Bytes stored through a character type, which is compatible with every access.
313    ///
314    /// This is what makes the byte-wise copy idiom work. C 6.5 says a character access is
315    /// always permitted and that a store through a character lvalue does not set an effective
316    /// type, so the plane says `character` over those bytes and the later read of the field
317    /// still passes.
318    Character,
319    /// Byte `k` of a pointer shaped word.
320    ///
321    /// A pointer is not one type over its bytes, it is a word whose bytes are only meaningful
322    /// together, so reading four bytes out of the middle of one is a different thing from
323    /// reading four bytes of an `int` and the plane has to be able to say which byte it is.
324    PointerSlot(u8),
325}
326
327/// What a call needs beyond its arguments.
328#[derive(Clone, Copy, Debug, PartialEq, Eq)]
329pub struct CallInfo {
330    /// The name, for a direct call. `None` for a call through an address, where the address is
331    /// the first operand.
332    pub callee: Option<Symbol>,
333    /// The signature it is called with, which is where the ABI attributes are.
334    pub signature: Sig,
335    /// What the ABI asks of the arguments the signature does not name, one entry for each of
336    /// them.
337    ///
338    /// Only a variadic call has any, because only a variadic call passes an argument no
339    /// parameter stands for, and it is empty when every one of them travels as the value in
340    /// hand, which is nearly always. A structure the classification puts in the argument area
341    /// is the case it exists for: the bytes travel and there is no parameter to hang the
342    /// [`Abi::ByVal`] on, so it hangs here instead.
343    pub varargs: AbiList,
344}
345
346/// A signature, in the function's table.
347pub type Sig = Idx<Signature>;
348
349/// What a `switch` needs beyond the value it switches on.
350#[derive(Clone, Copy, Debug, PartialEq, Eq)]
351pub struct SwitchInfo {
352    /// The targets, with the default first and one for each case after it.
353    pub targets: BlockCallList,
354    /// The case values, one for each target after the default.
355    pub cases: ImmList,
356}
357
358/// What an object read off a variable argument list is.
359///
360/// The access says how many bytes it is and what it is aligned to, which is the whole of what an
361/// object the convention put in the caller's argument area needs: it is there, and those two say
362/// where the argument behind it starts. An object that travelled in registers is not there at all.
363/// It is in the callee's own register save area, in as many places as it has eightbytes, and which
364/// register file each of those came from is not something the size and the alignment say. So the
365/// slots say it, and they are empty for the object that went in memory.
366///
367/// The classification is the front end's, because it is the one that still has the type. By the
368/// time an instruction reaches a backend the type is a size and an alignment, and the algorithm in
369/// section 3.5.7 of the psABI wants more than that.
370#[derive(Clone, Copy, Debug, PartialEq, Eq)]
371pub struct VaInfo {
372    /// The object, as any other access describes one.
373    pub mem: Idx<MemInfo>,
374    /// Where each of its eightbytes travelled, or nothing at all for one that travelled whole in
375    /// the caller's memory.
376    pub slots: SlotList,
377}
378
379/// What inline assembly needs.
380///
381/// The semantics belong to the inline assembly document. What is here is the shape: a
382/// template, the constraints, the clobbers, and the successors that make `asm goto` the one
383/// instruction whose being a terminator is a property of the instruction and not the opcode.
384#[derive(Clone, Copy, Debug, PartialEq, Eq)]
385pub struct AsmInfo {
386    /// The template string, as written.
387    pub template: Symbol,
388    /// The constraint list, as written.
389    pub constraints: Symbol,
390    /// The clobber list, as written.
391    pub clobbers: Symbol,
392    /// The labels, which are empty for everything except `asm goto`.
393    pub targets: BlockCallList,
394}
395
396/// Everything an instruction carries that is not a value operand.
397///
398/// Anything that fits in eight bytes is here and anything larger is an index into a side
399/// table, so that the common instructions, which are the arithmetic ones carrying nothing at
400/// all, do not pay for the rare ones.
401#[derive(Clone, Copy, Debug, PartialEq, Eq)]
402pub enum Extra {
403    /// Nothing, which is most instructions.
404    None,
405    /// A constant, for `iconst`, `fconst` and `splat`.
406    Imm(Idx<Imm>),
407    /// A name, for `global_addr` and for a target-specific intrinsic.
408    Symbol(Symbol),
409    /// Which comparison, for `icmp`.
410    IntPred(IntPred),
411    /// Which comparison, for `fcmp`.
412    FloatPred(FloatPred),
413    /// An access, for the loads, the stores, the copies and `alloca`.
414    Mem(Idx<MemInfo>),
415    /// An atomic read-modify-write, which is an access and which operation.
416    Rmw(RmwOp, Idx<MemInfo>),
417    /// A barrier's ordering, for `fence`.
418    Order(MemOrder),
419    /// The targets of a branch, with the default first for a `switch`.
420    Targets(BlockCallList),
421    /// A call.
422    Call(Idx<CallInfo>),
423    /// A `switch`, which is targets and the values that select them.
424    Switch(Idx<SwitchInfo>),
425    /// Inline assembly.
426    Asm(Idx<AsmInfo>),
427    /// An object read off a variable argument list, which is an access and how it travelled.
428    VaObject(Idx<VaInfo>),
429    /// What kind of storage an instance is, for `meta_begin`.
430    Class(StorageClass),
431    /// Who a range went to, for `meta_transfer`.
432    Owner(Owner),
433    /// A metadata node, for `meta_type`, which is the one plane write that names a type.
434    Node(Meta),
435    /// Why an exemption was declared, for `safe_region_begin`.
436    Reason(Symbol),
437}
438
439impl Extra {
440    /// Which shape this is, without the payload.
441    ///
442    /// The verifier compares this with [`Opcode::extra_kind`], because an instruction carrying
443    /// the payload of some other opcode prints as text the parser cannot read back.
444    #[must_use]
445    pub const fn kind(self) -> ExtraKind {
446        match self {
447            Self::None => ExtraKind::None,
448            Self::Imm(_) => ExtraKind::Imm,
449            Self::Symbol(_) => ExtraKind::Symbol,
450            Self::IntPred(_) => ExtraKind::IntPred,
451            Self::FloatPred(_) => ExtraKind::FloatPred,
452            Self::Mem(_) => ExtraKind::Mem,
453            Self::Rmw(..) => ExtraKind::Rmw,
454            Self::Order(_) => ExtraKind::Order,
455            Self::Targets(_) => ExtraKind::Targets,
456            Self::Call(_) => ExtraKind::Call,
457            Self::Switch(_) => ExtraKind::Switch,
458            Self::Asm(_) => ExtraKind::Asm,
459            Self::VaObject(_) => ExtraKind::VaObject,
460            Self::Class(_) => ExtraKind::Class,
461            Self::Owner(_) => ExtraKind::Owner,
462            Self::Node(_) => ExtraKind::Node,
463            Self::Reason(_) => ExtraKind::Reason,
464        }
465    }
466}
467
468/// One instruction.
469///
470/// There is no result type here. Each result is a value in the function's value table and the
471/// type is on the value, which means a reader asking what an instruction produces asks the
472/// same question about `add` as about `call`, and there is no second copy of the type to
473/// disagree with the first.
474#[derive(Clone, Copy, Debug, PartialEq, Eq)]
475pub struct InstData {
476    /// Which instruction this is.
477    pub opcode: Opcode,
478    /// What the optimizer is licensed to assume about it.
479    pub flags: Flags,
480    /// How many values it produces.
481    pub results: u8,
482    /// The first of them, with the rest following it in the value table.
483    pub first_result: Option<Value>,
484    /// Its value operands.
485    pub args: ValueList,
486    /// Everything else it carries.
487    pub extra: Extra,
488}
489
490impl InstData {
491    /// An instruction with no operands, no flags, no results and nothing extra.
492    #[must_use]
493    pub const fn new(opcode: Opcode) -> Self {
494        Self {
495            opcode,
496            flags: Flags::NONE,
497            results: 0,
498            first_result: None,
499            args: ValueList::EMPTY,
500            extra: Extra::None,
501        }
502    }
503
504    /// The values it produces, in order.
505    pub fn results(&self) -> impl Iterator<Item = Value> + use<> {
506        let first = self.first_result.map_or(0, Idx::raw);
507        (0..u32::from(self.results)).map(move |offset| Value::new(first + offset))
508    }
509
510    /// The run of targets it branches to, which is empty when it does not branch.
511    ///
512    /// A `switch` keeps its targets in a side table, so this reads `Extra::Targets` only and
513    /// the function is what answers for the rest.
514    #[must_use]
515    pub fn targets(&self) -> BlockCallList {
516        match self.extra {
517            Extra::Targets(targets) => targets,
518            _ => BlockCallList::EMPTY,
519        }
520    }
521}
522
523/// How one parameter or one return value travels, beyond what its type says.
524///
525/// The IR's types are the machine's and not C's, so a `ptr` parameter says nothing about
526/// whether the pointer is the argument or whether the object it points at is, and an `i8` says
527/// nothing about which half of the register above it the callee may read. Both are the ABI's
528/// answer rather than the type's, which is why they are here and not on [`Type`].
529///
530/// A signature carrying one of these has already had the ABI applied to it. What the walk to
531/// the IR builds first is the C-level form, where every parameter is [`Abi::Plain`], and the
532/// classification in `rucc-target` is what turns one into the other.
533#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
534pub enum Abi {
535    /// The value itself, in the type it is written as.
536    #[default]
537    Plain,
538    /// An integer narrower than a register, with the bits above it its own sign.
539    ///
540    /// Which of these an ABI asks for is not a property of the value: `unsigned char` is
541    /// [`Abi::Sext`] on the Darwin ABIs and [`Abi::Zext`] elsewhere, and on SysV neither the
542    /// caller nor the callee may assume anything about those bits at all.
543    Sext,
544    /// An integer narrower than a register, with zeroes above it.
545    Zext,
546    /// The bytes of the object the pointer points at, in the argument area, with no address
547    /// travelling anywhere.
548    ///
549    /// The caller makes the copy the callee is free to write to, which is what makes this a C
550    /// call by value rather than a pointer the callee must not keep.
551    ByVal {
552        /// How many bytes travel.
553        size: u64,
554        /// What the copy is aligned to, which is the C alignment of the type and not the
555        /// pointer's.
556        align: u32,
557    },
558    /// Somewhere for the return value to go, whose address the caller passes as the first
559    /// argument because the value does not fit in the registers a return comes back in.
560    Sret {
561        /// How many bytes the callee writes.
562        size: u64,
563        /// What the space is aligned to.
564        align: u32,
565    },
566}
567
568impl Abi {
569    /// Whether this describes an object behind a pointer rather than the value in hand.
570    #[must_use]
571    pub const fn indirect(self) -> bool {
572        matches!(self, Self::ByVal { .. } | Self::Sret { .. })
573    }
574
575    /// The size and alignment of that object, for the two that have one.
576    #[must_use]
577    pub const fn object(self) -> Option<(u64, u32)> {
578        match self {
579            Self::ByVal { size, align } | Self::Sret { size, align } => Some((size, align)),
580            _ => None,
581        }
582    }
583}
584
585/// One parameter, or one return value: a type and how it travels.
586#[derive(Clone, Copy, Debug, PartialEq, Eq)]
587pub struct Param {
588    /// The type the IR sees, which for the indirect forms is `ptr`.
589    pub ty: Type,
590    /// What the ABI asks of it.
591    pub abi: Abi,
592}
593
594impl Param {
595    /// A parameter of this type, in its C-level form.
596    #[must_use]
597    pub const fn new(ty: Type) -> Self {
598        Self { ty, abi: Abi::Plain }
599    }
600
601    /// A parameter of this type travelling this way.
602    #[must_use]
603    pub const fn with_abi(ty: Type, abi: Abi) -> Self {
604        Self { ty, abi }
605    }
606}
607
608/// What a function takes and returns.
609///
610/// A signature is not a type. Nothing in the IR has a function type, because a `ptr` has no
611/// pointee and there is nothing else a function type could sit on. A `call_indirect` names the
612/// signature it is called with, and that is where the ABI attributes are read from.
613#[derive(Clone, Debug, PartialEq, Eq, Default)]
614pub struct Signature {
615    /// What it takes, in their C-level form until the ABI has been applied.
616    pub params: Vec<Param>,
617    /// What it returns, which is empty for a `void` function and for one whose return value
618    /// comes back through an [`Abi::Sret`] parameter.
619    pub returns: Vec<Param>,
620    /// Whether it takes arguments beyond the ones named.
621    pub variadic: bool,
622}
623
624impl Signature {
625    /// A signature taking and returning nothing.
626    #[must_use]
627    pub fn new() -> Self {
628        Self::default()
629    }
630
631    /// The same signature with these parameters, each in its C-level form.
632    #[must_use]
633    pub fn with_params(mut self, params: &[Type]) -> Self {
634        self.params = params.iter().copied().map(Param::new).collect();
635        self
636    }
637
638    /// The same signature returning these, each in its C-level form.
639    #[must_use]
640    pub fn with_returns(mut self, returns: &[Type]) -> Self {
641        self.returns = returns.iter().copied().map(Param::new).collect();
642        self
643    }
644
645    /// The same signature with one more parameter, travelling the way the ABI said.
646    #[must_use]
647    pub fn and_param(mut self, param: Param) -> Self {
648        self.params.push(param);
649        self
650    }
651
652    /// The same signature with one more return value, travelling the way the ABI said.
653    #[must_use]
654    pub fn and_return(mut self, param: Param) -> Self {
655        self.returns.push(param);
656        self
657    }
658
659    /// The types it takes, without what the ABI asks of them.
660    pub fn param_types(&self) -> impl Iterator<Item = Type> + use<'_> {
661        self.params.iter().map(|param| param.ty)
662    }
663
664    /// The types it returns.
665    pub fn return_types(&self) -> impl Iterator<Item = Type> + use<'_> {
666        self.returns.iter().map(|param| param.ty)
667    }
668
669    /// The same signature, variadic.
670    #[must_use]
671    pub fn variadic(mut self) -> Self {
672        self.variadic = true;
673        self
674    }
675}
676
677/// One basic block: parameters, then instructions, then exactly one terminator.
678///
679/// The instructions are a doubly linked list rather than a vector, so that inserting one in
680/// the middle of a block does not move the ones after it. An optimizer does that constantly,
681/// and a move would invalidate every [`Inst`] anybody was holding.
682#[derive(Clone, Debug, Default, PartialEq, Eq)]
683pub struct BlockData {
684    /// The values arriving here, which is what other IRs spell as phi nodes.
685    ///
686    /// A `Vec` and not a run in a pool, because SSA construction adds a parameter to a loop
687    /// header long after the blocks that come after it have been built, and a run in a pool
688    /// cannot grow in the middle.
689    pub params: Vec<Value>,
690    /// The first instruction, or `None` for a block nothing has been put in yet.
691    pub first: Option<Inst>,
692    /// The last instruction, which is the terminator once the block is finished.
693    pub last: Option<Inst>,
694    /// The block before this one in layout order.
695    pub prev: Option<Block>,
696    /// The block after it.
697    pub next: Option<Block>,
698}
699
700/// Where one instruction sits.
701#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
702pub struct InstLayout {
703    /// The block it is in, or `None` if it has been made and not yet inserted.
704    pub block: Option<Block>,
705    /// The instruction before it in that block.
706    pub prev: Option<Inst>,
707    /// The instruction after it.
708    pub next: Option<Inst>,
709}
710
711#[cfg(test)]
712mod tests {
713    use super::*;
714
715    #[test]
716    fn an_immediate_keeps_only_the_bits_its_type_has() {
717        let byte = Type::int(8);
718        assert_eq!(Imm::int(-1, byte).unsigned(), 0xff);
719        assert_eq!(Imm::int(-1, byte).signed(byte), -1);
720        assert_eq!(Imm::int(255, byte), Imm::int(-1, byte));
721        assert_eq!(Imm::int(127, byte).signed(byte), 127);
722        assert_eq!(Imm::int(128, byte).signed(byte), -128);
723    }
724
725    #[test]
726    fn a_widest_immediate_is_not_truncated() {
727        let word = Type::int(128);
728        assert_eq!(Imm::int(i128::MIN, word).signed(word), i128::MIN);
729        assert_eq!(Imm::int(i128::MAX, word).signed(word), i128::MAX);
730        assert_eq!(Imm::int(-1, word).unsigned(), u128::MAX);
731    }
732
733    #[test]
734    fn a_one_bit_immediate_is_a_bit() {
735        let bit = Type::I1;
736        assert_eq!(Imm::int(1, bit).unsigned(), 1);
737        assert_eq!(Imm::int(3, bit).unsigned(), 1);
738        assert_eq!(Imm::int(2, bit).unsigned(), 0);
739        // The one bit is the sign bit, so the only two values are zero and minus one.
740        assert_eq!(Imm::int(1, bit).signed(bit), -1);
741    }
742
743    #[test]
744    fn a_floating_immediate_keeps_its_bits() {
745        let bits = f64::NAN.to_bits() | 0x7;
746        assert_eq!(Imm::from_bits(u128::from(bits)).bits(), u128::from(bits));
747    }
748
749    #[test]
750    fn an_instruction_with_no_results_yields_none() {
751        let inst = InstData::new(Opcode::Store);
752        assert_eq!(inst.results().count(), 0);
753    }
754
755    #[test]
756    fn results_follow_the_first_one() {
757        let mut inst = InstData::new(Opcode::SAddOverflow);
758        inst.first_result = Some(Value::new(4));
759        inst.results = 2;
760        let got: Vec<u32> = inst.results().map(Idx::raw).collect();
761        assert_eq!(got, [4, 5]);
762    }
763
764    #[test]
765    fn a_jump_says_where_it_goes() {
766        let mut inst = InstData::new(Opcode::Jump);
767        inst.extra = Extra::Targets(BlockCallList::new(Idx::new(0), Idx::new(1)));
768        assert_eq!(inst.targets().len(), 1);
769    }
770
771    #[test]
772    fn a_signature_is_built_by_saying_what_it_takes_and_returns() {
773        let sig = Signature::new()
774            .with_params(&[Type::int(32), Type::PTR])
775            .with_returns(&[Type::int(32)])
776            .variadic();
777        assert_eq!(sig.param_types().collect::<Vec<_>>(), [Type::int(32), Type::PTR]);
778        assert_eq!(sig.return_types().collect::<Vec<_>>(), [Type::int(32)]);
779        assert!(sig.variadic);
780        assert_eq!(Signature::new(), Signature::default());
781    }
782
783    #[test]
784    fn a_parameter_says_how_it_travels_and_not_only_what_it_is() {
785        let object = Abi::ByVal { size: 24, align: 8 };
786        let sig = Signature::new()
787            .and_param(Param::with_abi(Type::PTR, Abi::Sret { size: 32, align: 16 }))
788            .and_param(Param::with_abi(Type::PTR, object))
789            .and_param(Param::with_abi(Type::int(8), Abi::Zext));
790        // The types alone say `ptr, ptr, i8`, which is three of the calls in any C program and
791        // none of them the same call.
792        assert_eq!(sig.param_types().collect::<Vec<_>>(), [Type::PTR, Type::PTR, Type::int(8)]);
793        assert_eq!(sig.params[1].abi.object(), Some((24, 8)));
794        assert!(sig.params[0].abi.indirect() && !sig.params[2].abi.indirect());
795        assert_eq!(Param::new(Type::PTR).abi, Abi::Plain);
796        assert_eq!(Abi::Plain.object(), None);
797    }
798
799    #[test]
800    fn an_instruction_stays_small() {
801        // Not a promise, a tripwire. Every function in the program is a run of these, and a
802        // change that doubles this should be a change somebody decided to make.
803        assert!(size_of::<InstData>() <= 32, "{}", size_of::<InstData>());
804        assert_eq!(size_of::<ValueData>(), 16);
805        assert_eq!(size_of::<Extra>(), 12);
806    }
807}