Skip to main content

rucc_ir/
module.rs

1//! The module: the target it is for, its functions, its globals, its aliases and its metadata.
2//!
3//! Design: `spec/08-ir.md` sections 8.1 and 8.8.
4//!
5//! A module is one translation unit, or after LTO the several that were linked into one. It
6//! owns the functions rather than pointing at them, so the whole of a compilation is one value
7//! that is dropped in one go, and a reference to anything in it is a four-byte index.
8//!
9//! # Globals are bytes, not values
10//!
11//! There are no aggregate types in the IR, so a global's initializer cannot be a typed
12//! constant the way it is in LLVM. It is a sized, aligned image described by a run of
13//! [`Datum`]s: zero bytes, literal bytes, a scalar of a given IR type, or the address of
14//! another symbol. That is what an object file wants anyway, it needs no type the type system
15//! does not have, and a large `static const` table costs one [`Datum`] rather than one per
16//! element.
17//!
18//! # What the module does not hold
19//!
20//! It does not hold an [`Interner`](rucc_base::Interner). Every name in here is a
21//! [`Symbol`], and resolving one back to text needs the interner it came from, which the
22//! printer takes as an argument the way `rucc_ast::print` does. A module that owned one could
23//! not be built from the same session as the AST it was lowered from.
24//!
25//! Function attributes are not here yet. They arrive with the printer, which is where their
26//! spelling has to be settled.
27
28use std::collections::HashMap;
29use std::fmt;
30use std::ops::{Index, IndexMut};
31
32use rucc_base::float::Format;
33use rucc_base::{Idx, IdxRange, Symbol};
34use rucc_target::TargetInfo;
35use rucc_tuple::TargetTuple;
36
37use crate::func::Func;
38#[cfg(test)]
39use crate::inst::TbaaNode;
40use crate::inst::{Imm, Meta, MetaNode};
41use crate::ty::Type;
42
43/// A function in a module.
44pub type FuncId = Idx<Func>;
45
46/// A global variable in a module.
47pub type GlobalId = Idx<Global>;
48
49/// An alias in a module.
50pub type AliasId = Idx<Alias>;
51
52/// A run of [`Datum`]s in a module's data pool, which is what a global's initializer is.
53pub type DataList = IdxRange<Datum>;
54
55/// Marker for the byte pool, so that a range into it cannot be confused with any other range.
56#[derive(Debug)]
57pub struct Byte;
58
59/// A run of literal bytes in a module's byte pool.
60pub type ByteRange = IdxRange<Byte>;
61
62/// How a symbol is seen outside the object it is defined in.
63///
64/// The set is the one C needs and no more. C++ vague linkage and the ODR variants are not
65/// here because nothing produces them.
66#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
67pub enum Linkage {
68    /// Defined here and visible to every other object. The default, and what a plain
69    /// definition at file scope gets.
70    #[default]
71    External,
72    /// Defined here and invisible outside it, which is what `static` at file scope means.
73    Internal,
74    /// Defined here, visible, and allowed to be replaced by a strong definition elsewhere.
75    /// `__attribute__((weak))`. A reference to one that nothing defines is a null address
76    /// rather than a link error.
77    Weak,
78    /// Defined here, visible, and allowed to be identical to a definition in another object,
79    /// with one of them kept and the rest discarded. What `extern inline` under the GNU
80    /// semantics and a compiler-generated helper get.
81    LinkOnce,
82    /// A tentative definition, which the linker merges with any other tentative definition of
83    /// the same name and any real definition. `int x;` at file scope under `-fcommon`.
84    Common,
85}
86
87impl Linkage {
88    /// The spelling in the textual form.
89    #[must_use]
90    pub const fn name(self) -> &'static str {
91        match self {
92            Self::External => "external",
93            Self::Internal => "internal",
94            Self::Weak => "weak",
95            Self::LinkOnce => "linkonce",
96            Self::Common => "common",
97        }
98    }
99
100    /// The linkage that spelling names.
101    #[must_use]
102    pub fn from_name(name: &str) -> Option<Self> {
103        Self::all().find(|linkage| linkage.name() == name)
104    }
105
106    /// Every linkage, in declaration order.
107    pub fn all() -> impl Iterator<Item = Self> {
108        [Self::External, Self::Internal, Self::Weak, Self::LinkOnce, Self::Common].into_iter()
109    }
110
111    /// Whether the symbol is invisible outside this object, so that a pass may rewrite every
112    /// use of it because it can see every use of it.
113    #[must_use]
114    pub const fn is_local(self) -> bool {
115        matches!(self, Self::Internal)
116    }
117
118    /// Whether the definition here may lose to one in another object at link time.
119    ///
120    /// The optimizer must not fold a use against the definition it can see when this is true,
121    /// because the definition that wins may be a different one.
122    #[must_use]
123    pub const fn may_be_replaced(self) -> bool {
124        matches!(self, Self::Weak | Self::LinkOnce | Self::Common)
125    }
126}
127
128/// What the dynamic linker is allowed to do with a symbol.
129///
130/// Orthogonal to [`Linkage`], which is about the static linker. A hidden symbol is still
131/// external as far as the object file is concerned; it just does not go in the dynamic symbol
132/// table, so nothing outside the shared object can interpose it.
133#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
134pub enum Visibility {
135    /// Exported and interposable, which is what a symbol in a shared library gets unless
136    /// something says otherwise.
137    #[default]
138    Default,
139    /// Not in the dynamic symbol table at all. `__attribute__((visibility("hidden")))` and
140    /// `-fvisibility=hidden`.
141    Hidden,
142    /// In the dynamic symbol table, but a reference from inside this shared object always
143    /// binds to the definition inside it.
144    Protected,
145}
146
147impl Visibility {
148    /// The spelling in the textual form.
149    #[must_use]
150    pub const fn name(self) -> &'static str {
151        match self {
152            Self::Default => "default",
153            Self::Hidden => "hidden",
154            Self::Protected => "protected",
155        }
156    }
157
158    /// The visibility that spelling names.
159    #[must_use]
160    pub fn from_name(name: &str) -> Option<Self> {
161        Self::all().find(|visibility| visibility.name() == name)
162    }
163
164    /// Every visibility, in declaration order.
165    pub fn all() -> impl Iterator<Item = Self> {
166        [Self::Default, Self::Hidden, Self::Protected].into_iter()
167    }
168}
169
170/// How a thread-local variable is reached.
171///
172/// The models are ordered from the most general to the fastest, and a model may always be
173/// replaced by a more general one. The frontend picks from the storage class and the
174/// visibility, `-ftls-model=` overrides it, and the linker may relax a general one into a
175/// faster one when it turns out the definition is in the executable.
176#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
177pub enum TlsModel {
178    /// Works for any variable in any object, at the cost of a call to `__tls_get_addr`.
179    #[default]
180    GlobalDynamic,
181    /// One call to `__tls_get_addr` for several variables that are known to share a module.
182    LocalDynamic,
183    /// The offset is loaded from the GOT. Needs the variable to be in a module loaded at
184    /// program start rather than by `dlopen`.
185    InitialExec,
186    /// The offset is a link-time constant. Only for a variable in the executable itself.
187    LocalExec,
188}
189
190impl TlsModel {
191    /// The spelling in the textual form.
192    #[must_use]
193    pub const fn name(self) -> &'static str {
194        match self {
195            Self::GlobalDynamic => "global_dynamic",
196            Self::LocalDynamic => "local_dynamic",
197            Self::InitialExec => "initial_exec",
198            Self::LocalExec => "local_exec",
199        }
200    }
201
202    /// The model that spelling names.
203    #[must_use]
204    pub fn from_name(name: &str) -> Option<Self> {
205        Self::all().find(|model| model.name() == name)
206    }
207
208    /// Every model, from the most general to the fastest.
209    pub fn all() -> impl Iterator<Item = Self> {
210        [Self::GlobalDynamic, Self::LocalDynamic, Self::InitialExec, Self::LocalExec].into_iter()
211    }
212}
213
214/// One piece of a global's initial image.
215///
216/// Sixteen bytes, so an initializer built out of them is a flat array and a table of a
217/// million bytes is one of these rather than a million.
218#[derive(Debug, Clone, Copy, PartialEq, Eq)]
219pub enum Datum {
220    /// That many zero bytes. What `.bss` is made of, and what the tail of a partly
221    /// initialized array is.
222    Zero(u64),
223    /// Those literal bytes, from the module's byte pool. String literals and anything the
224    /// frontend has already laid out.
225    Bytes(ByteRange),
226    /// One scalar of that IR type, from the module's immediate pool. An integer holds its
227    /// value and a float holds its bit pattern, both target-independently: which byte comes
228    /// first is decided by the datalayout when the object file is written, not here.
229    Scalar {
230        /// The type of the scalar, which gives its width.
231        ty: Type,
232        /// Its value, in the module's immediate pool.
233        value: Idx<Imm>,
234    },
235    /// The address of another symbol, from the module's relocation pool. `&x` in an
236    /// initializer, which the linker fills in.
237    Addr(Idx<Reloc>),
238}
239
240impl Datum {
241    /// How many bytes it contributes to the image.
242    ///
243    /// The module is an argument because three of the four kinds keep what they are made of in
244    /// one of its pools, and a datum on its own is four words that mean nothing without it.
245    #[must_use]
246    pub fn size(self, module: &Module) -> u64 {
247        match self {
248            Self::Zero(bytes) => bytes,
249            Self::Bytes(range) => range.len() as u64,
250            // Rounded up, so that an `i1` in an image is a byte and a `_BitInt(24)` is three.
251            Self::Scalar { ty, .. } => u64::from(ty.bits().div_ceil(8)) * u64::from(ty.lanes()),
252            Self::Addr(reloc) => u64::from(module[reloc].size),
253        }
254    }
255}
256
257/// The address of a symbol, written into a global's image by the linker.
258#[derive(Debug, Clone, Copy, PartialEq, Eq)]
259pub struct Reloc {
260    /// The symbol whose address this is.
261    pub symbol: Symbol,
262    /// What to add to that address. `&array[2]` is the address of `array` plus eight.
263    pub addend: i64,
264    /// How many bytes the address occupies, which is the pointer width except where a target
265    /// has a smaller relocation for it.
266    pub size: u32,
267}
268
269/// A global variable.
270///
271/// A size and an alignment and an image, which is what the object writer needs. `init` is
272/// `None` for a declaration of something defined in another object, which is the only thing
273/// that distinguishes the two.
274#[derive(Debug, Clone)]
275pub struct Global {
276    /// The name it is reached by.
277    pub name: Symbol,
278    /// Its size in bytes, which the image must add up to.
279    pub size: u64,
280    /// Its required alignment in bytes, always a power of two.
281    pub align: u32,
282    /// How the linker sees it.
283    pub linkage: Linkage,
284    /// How the dynamic linker sees it.
285    pub visibility: Visibility,
286    /// The model to reach it by if it is thread-local, and `None` if it is not.
287    pub tls: Option<TlsModel>,
288    /// Whether writing through a pointer to it is undefined, which is what puts it in
289    /// `.rodata` rather than `.data`.
290    pub constant: bool,
291    /// The section to put it in, from `__attribute__((section(...)))`, or `None` to let the
292    /// object writer choose from the other fields.
293    pub section: Option<Symbol>,
294    /// Its initial image, or `None` if it is only declared here.
295    pub init: Option<DataList>,
296}
297
298impl Global {
299    /// A definition-less global of that size and alignment, external and not thread-local.
300    #[must_use]
301    pub fn new(name: Symbol, size: u64, align: u32) -> Self {
302        Self {
303            name,
304            size,
305            align,
306            linkage: Linkage::External,
307            visibility: Visibility::Default,
308            tls: None,
309            constant: false,
310            section: None,
311            init: None,
312        }
313    }
314
315    /// Whether this only says the variable exists somewhere.
316    #[must_use]
317    pub fn is_declaration(&self) -> bool {
318        self.init.is_none()
319    }
320}
321
322/// What an alias resolves to at link time.
323#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
324pub enum AliasKind {
325    /// A second name for a symbol in this same object, resolved by the assembler.
326    /// `__attribute__((alias("real")))`.
327    #[default]
328    Alias,
329    /// A name resolved once at program start by calling a resolver function in this object,
330    /// which picks an implementation from what the processor turns out to support.
331    /// `__attribute__((ifunc("resolver")))`, which is how glibc dispatches `memcpy`.
332    IFunc,
333}
334
335impl AliasKind {
336    /// The spelling in the textual form.
337    #[must_use]
338    pub const fn name(self) -> &'static str {
339        match self {
340            Self::Alias => "alias",
341            Self::IFunc => "ifunc",
342        }
343    }
344
345    /// The kind that spelling names.
346    #[must_use]
347    pub fn from_name(name: &str) -> Option<Self> {
348        match name {
349            "alias" => Some(Self::Alias),
350            "ifunc" => Some(Self::IFunc),
351            _ => None,
352        }
353    }
354}
355
356/// A second name for something else.
357#[derive(Debug, Clone, Copy, PartialEq, Eq)]
358pub struct Alias {
359    /// The name being defined.
360    pub name: Symbol,
361    /// What it resolves to: the aliased symbol, or for an ifunc the resolver to call.
362    pub target: Symbol,
363    /// Which of those two it is.
364    pub kind: AliasKind,
365    /// How the linker sees the new name.
366    pub linkage: Linkage,
367    /// How the dynamic linker sees the new name.
368    pub visibility: Visibility,
369}
370
371impl Alias {
372    /// An external alias of `target`.
373    #[must_use]
374    pub fn new(name: Symbol, target: Symbol) -> Self {
375        Self {
376            name,
377            target,
378            kind: AliasKind::Alias,
379            linkage: Linkage::External,
380            visibility: Visibility::Default,
381        }
382    }
383}
384
385/// What a name in a module refers to.
386#[derive(Debug, Clone, Copy, PartialEq, Eq)]
387pub enum SymbolRef {
388    /// A function, defined or declared.
389    Func(FuncId),
390    /// A global variable, defined or declared.
391    Global(GlobalId),
392    /// An alias or an ifunc.
393    Alias(AliasId),
394}
395
396/// The layout facts a printed module carries so it can be compiled without the command line
397/// that produced it.
398///
399/// A subset of the string LLVM writes, in the same syntax, because that syntax is what tools
400/// around the ecosystem already read. It says what the module was built assuming, and the
401/// verifier is what checks it against the target actually being compiled for: a module built
402/// for a 64-bit pointer cannot be finished for a 32-bit one, and finding that out here is
403/// better than finding it out as wrong output.
404#[derive(Debug, Clone, Copy, PartialEq, Eq)]
405pub struct DataLayout {
406    /// Whether the low byte of a scalar is stored first.
407    pub little_endian: bool,
408    /// The width of a pointer in bits.
409    pub pointer_bits: u32,
410    /// The alignment of a pointer in bits.
411    pub pointer_align: u32,
412    /// The alignment of a 64-bit integer in bits, which is the one integer alignment that
413    /// varies across the targets anybody still builds for.
414    pub i64_align: u32,
415    /// The alignment of the x87 eighty bit format in bits, and `None` on a target that does
416    /// not have it.
417    pub f80_align: Option<u32>,
418    /// The alignment the stack is kept at in bits, which is 128 on every target here.
419    pub stack_align: u32,
420}
421
422impl DataLayout {
423    /// The layout of that target.
424    ///
425    /// # Panics
426    ///
427    /// If the target aligns a `long long` to more than half a billion bytes, which no target
428    /// does. The alignment is a byte count here and a bit count in the IR, and the multiplication
429    /// between the two is the only arithmetic in this function.
430    #[must_use]
431    pub fn for_target(target: &TargetInfo) -> Self {
432        Self {
433            little_endian: target.little_endian,
434            pointer_bits: target.pointer_width,
435            pointer_align: target.pointer_width,
436            // Four on System V i386 and eight everywhere else, which is the one integer
437            // alignment that varies across the table and the reason this is a field. It changes
438            // the layout of every struct with a `long long` in it.
439            i64_align: u32::try_from(target.scalars.long_long_align * 8)
440                .expect("no integer alignment is four billion bits"),
441            f80_align: match target.long_double_format {
442                Format::X87Extended => Some(128),
443                _ => None,
444            },
445            stack_align: 128,
446        }
447    }
448
449    /// The layout back from the string [`Display`](fmt::Display) wrote, or `None` if the
450    /// string is not one.
451    ///
452    /// The fields may come in any order, because a string written by hand will not have them
453    /// in ours. A string this crate printed round-trips byte for byte, which is what
454    /// `spec/03-architecture.md` asks of the textual form.
455    #[must_use]
456    pub fn parse(text: &str) -> Option<Self> {
457        let mut little_endian = None;
458        let mut pointer = None;
459        let mut i64_align = None;
460        let mut f80_align = None;
461        let mut stack_align = None;
462        for field in text.split('-') {
463            let seen = match field {
464                "e" => little_endian.replace(true).is_some(),
465                "E" => little_endian.replace(false).is_some(),
466                _ if field.starts_with("p:") => {
467                    let (bits, align) = field[2..].split_once(':')?;
468                    pointer.replace((number(bits)?, number(align)?)).is_some()
469                }
470                _ if field.starts_with("i64:") => i64_align.replace(number(&field[4..])?).is_some(),
471                _ if field.starts_with("f80:") => f80_align.replace(number(&field[4..])?).is_some(),
472                _ if field.starts_with('S') => stack_align.replace(number(&field[1..])?).is_some(),
473                _ => return None,
474            };
475            if seen {
476                return None;
477            }
478        }
479        let (pointer_bits, pointer_align) = pointer?;
480        Some(Self {
481            little_endian: little_endian?,
482            pointer_bits,
483            pointer_align,
484            i64_align: i64_align?,
485            f80_align,
486            stack_align: stack_align?,
487        })
488    }
489}
490
491impl fmt::Display for DataLayout {
492    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
493        write!(f, "{}", if self.little_endian { "e" } else { "E" })?;
494        write!(f, "-p:{}:{}", self.pointer_bits, self.pointer_align)?;
495        write!(f, "-i64:{}", self.i64_align)?;
496        if let Some(align) = self.f80_align {
497            write!(f, "-f80:{align}")?;
498        }
499        write!(f, "-S{}", self.stack_align)
500    }
501}
502
503/// A number in the textual form: digits, no sign, and no leading zero.
504///
505/// `p:64:064` would otherwise parse and then print back as `p:64:64`, which breaks the
506/// round-trip for no benefit to anybody.
507fn number(text: &str) -> Option<u32> {
508    if text.is_empty() || (text.len() > 1 && text.starts_with('0')) {
509        return None;
510    }
511    if !text.bytes().all(|byte| byte.is_ascii_digit()) {
512        return None;
513    }
514    text.parse().ok()
515}
516
517/// One translation unit, or after LTO the several that were linked into one.
518#[derive(Debug)]
519pub struct Module {
520    /// What it is called, which is the source file name for a module from the frontend. It
521    /// appears in the textual form and in the debug info and nothing branches on it.
522    pub name: Symbol,
523    /// The target it is for.
524    pub tuple: TargetTuple,
525    /// The layout it was built assuming.
526    pub datalayout: DataLayout,
527
528    funcs: Vec<Func>,
529    globals: Vec<Global>,
530    aliases: Vec<Alias>,
531    metadata: Vec<MetaNode>,
532
533    data: Vec<Datum>,
534    bytes: Vec<u8>,
535    imms: Vec<Imm>,
536    relocs: Vec<Reloc>,
537
538    symbols: HashMap<Symbol, SymbolRef>,
539}
540
541impl Module {
542    /// An empty module for that target.
543    #[must_use]
544    pub fn new(name: Symbol, target: &TargetInfo) -> Self {
545        Self {
546            name,
547            tuple: target.tuple,
548            datalayout: DataLayout::for_target(target),
549            funcs: Vec::new(),
550            globals: Vec::new(),
551            aliases: Vec::new(),
552            metadata: Vec::new(),
553            data: Vec::new(),
554            bytes: Vec::new(),
555            imms: Vec::new(),
556            relocs: Vec::new(),
557            symbols: HashMap::new(),
558        }
559    }
560
561    // Symbols.
562
563    /// Adds a function, which is a declaration if it has no blocks.
564    ///
565    /// # Panics
566    ///
567    /// Panics if the module already has a symbol of that name. Merging a declaration with a
568    /// definition is the frontend's job and it has the declarations to do it with; by the time
569    /// something is in the IR a name means one thing.
570    pub fn add_func(&mut self, func: Func) -> FuncId {
571        let id = Idx::from_usize(self.funcs.len());
572        self.claim(func.name, SymbolRef::Func(id));
573        self.funcs.push(func);
574        id
575    }
576
577    /// Adds a global variable, which is a declaration if it has no image.
578    ///
579    /// # Panics
580    ///
581    /// Panics if the module already has a symbol of that name.
582    pub fn add_global(&mut self, global: Global) -> GlobalId {
583        let id = Idx::from_usize(self.globals.len());
584        self.claim(global.name, SymbolRef::Global(id));
585        self.globals.push(global);
586        id
587    }
588
589    /// Adds an alias.
590    ///
591    /// The target is not resolved here, and it need not be in this module: an alias of
592    /// something in another object is a thing people write.
593    ///
594    /// # Panics
595    ///
596    /// Panics if the module already has a symbol of that name.
597    pub fn add_alias(&mut self, alias: Alias) -> AliasId {
598        let id = Idx::from_usize(self.aliases.len());
599        self.claim(alias.name, SymbolRef::Alias(id));
600        self.aliases.push(alias);
601        id
602    }
603
604    /// What that name refers to, or `None` if this module does not define or declare it.
605    #[must_use]
606    pub fn lookup(&self, name: Symbol) -> Option<SymbolRef> {
607        self.symbols.get(&name).copied()
608    }
609
610    /// Every function, in the order they were added.
611    pub fn funcs(&self) -> impl Iterator<Item = FuncId> + use<> {
612        (0..self.funcs.len()).map(Idx::from_usize)
613    }
614
615    /// Every global variable, in the order they were added.
616    pub fn globals(&self) -> impl Iterator<Item = GlobalId> + use<> {
617        (0..self.globals.len()).map(Idx::from_usize)
618    }
619
620    /// Every alias, in the order they were added.
621    pub fn aliases(&self) -> impl Iterator<Item = AliasId> + use<> {
622        (0..self.aliases.len()).map(Idx::from_usize)
623    }
624
625    fn claim(&mut self, name: Symbol, what: SymbolRef) {
626        assert!(
627            self.symbols.insert(name, what).is_none(),
628            "a module cannot have two symbols with the same name"
629        );
630    }
631
632    // Metadata.
633
634    /// Adds a metadata node and gives back the reference an instruction holds.
635    ///
636    /// The nodes live here rather than in a function because a TBAA tree is shared by every
637    /// memory operation in the module and duplicating it per function would make two accesses
638    /// to the same type look unrelated.
639    pub fn add_meta(&mut self, node: MetaNode) -> Meta {
640        self.metadata.push(node);
641        Idx::from_usize(self.metadata.len() - 1)
642    }
643
644    /// Every metadata node, in the order they were added.
645    pub fn metadata(&self) -> impl Iterator<Item = Meta> + use<> {
646        (0..self.metadata.len()).map(Idx::from_usize)
647    }
648
649    // Pools.
650
651    /// Records a run of data and gives back the list a global holds.
652    pub fn push_data(&mut self, data: &[Datum]) -> DataList {
653        let start = self.data.len();
654        self.data.extend_from_slice(data);
655        DataList::new(Idx::from_usize(start), Idx::from_usize(self.data.len()))
656    }
657
658    /// Records literal bytes and gives back the range a [`Datum::Bytes`] holds.
659    pub fn push_bytes(&mut self, bytes: &[u8]) -> ByteRange {
660        let start = self.bytes.len();
661        self.bytes.extend_from_slice(bytes);
662        ByteRange::new(Idx::from_usize(start), Idx::from_usize(self.bytes.len()))
663    }
664
665    /// Records a scalar value and gives back the index a [`Datum::Scalar`] holds.
666    pub fn add_imm(&mut self, imm: Imm) -> Idx<Imm> {
667        self.imms.push(imm);
668        Idx::from_usize(self.imms.len() - 1)
669    }
670
671    /// Records a relocation and gives back the index a [`Datum::Addr`] holds.
672    pub fn add_reloc(&mut self, reloc: Reloc) -> Idx<Reloc> {
673        self.relocs.push(reloc);
674        Idx::from_usize(self.relocs.len() - 1)
675    }
676
677    /// How much is in it, for the `-fstats` output and for a test that wants to say a pass
678    /// deleted something without saying which.
679    #[must_use]
680    pub fn counts(&self) -> ModuleCounts {
681        ModuleCounts {
682            funcs: self.funcs.len(),
683            globals: self.globals.len(),
684            aliases: self.aliases.len(),
685            metadata: self.metadata.len(),
686            data_bytes: self.bytes.len(),
687        }
688    }
689}
690
691/// How much is in a module, from [`Module::counts`].
692#[derive(Debug, Clone, Copy, PartialEq, Eq)]
693pub struct ModuleCounts {
694    /// Functions, defined and declared.
695    pub funcs: usize,
696    /// Global variables, defined and declared.
697    pub globals: usize,
698    /// Aliases and ifuncs.
699    pub aliases: usize,
700    /// Metadata nodes.
701    pub metadata: usize,
702    /// Bytes in the byte pool, which is the bulk of what a module with large initializers
703    /// weighs.
704    pub data_bytes: usize,
705}
706
707impl Index<FuncId> for Module {
708    type Output = Func;
709
710    fn index(&self, id: FuncId) -> &Func {
711        &self.funcs[id.index()]
712    }
713}
714
715impl IndexMut<FuncId> for Module {
716    fn index_mut(&mut self, id: FuncId) -> &mut Func {
717        &mut self.funcs[id.index()]
718    }
719}
720
721impl Index<GlobalId> for Module {
722    type Output = Global;
723
724    fn index(&self, id: GlobalId) -> &Global {
725        &self.globals[id.index()]
726    }
727}
728
729impl IndexMut<GlobalId> for Module {
730    fn index_mut(&mut self, id: GlobalId) -> &mut Global {
731        &mut self.globals[id.index()]
732    }
733}
734
735impl Index<AliasId> for Module {
736    type Output = Alias;
737
738    fn index(&self, id: AliasId) -> &Alias {
739        &self.aliases[id.index()]
740    }
741}
742
743impl Index<Meta> for Module {
744    type Output = MetaNode;
745
746    fn index(&self, meta: Meta) -> &MetaNode {
747        &self.metadata[meta.index()]
748    }
749}
750
751impl Index<Idx<Imm>> for Module {
752    type Output = Imm;
753
754    fn index(&self, imm: Idx<Imm>) -> &Imm {
755        &self.imms[imm.index()]
756    }
757}
758
759impl Index<Idx<Reloc>> for Module {
760    type Output = Reloc;
761
762    fn index(&self, reloc: Idx<Reloc>) -> &Reloc {
763        &self.relocs[reloc.index()]
764    }
765}
766
767impl Index<DataList> for Module {
768    type Output = [Datum];
769
770    fn index(&self, list: DataList) -> &[Datum] {
771        &self.data[list.as_usize_range()]
772    }
773}
774
775impl Index<ByteRange> for Module {
776    type Output = [u8];
777
778    fn index(&self, range: ByteRange) -> &[u8] {
779        &self.bytes[range.as_usize_range()]
780    }
781}
782
783#[cfg(test)]
784mod tests {
785    use rucc_base::Interner;
786    use rucc_target::{Arch, Env, Os, Triple};
787
788    use super::*;
789    use crate::inst::Signature;
790
791    fn target(arch: Arch, os: Os, env: Env) -> TargetInfo {
792        TargetInfo::new(Triple::new(arch, os, env))
793    }
794
795    fn linux() -> TargetInfo {
796        target(Arch::X86_64, Os::Linux, Env::Gnu)
797    }
798
799    #[test]
800    fn a_datum_is_sixteen_bytes() {
801        // A global with a large initializer is a flat array of these, so this is the tripwire
802        // on somebody adding a field that doubles the weight of every one.
803        assert_eq!(size_of::<Datum>(), 16);
804    }
805
806    #[test]
807    fn the_layout_of_x86_64_linux_is_the_one_in_the_spec() {
808        let layout = DataLayout::for_target(&linux());
809        assert_eq!(layout.to_string(), "e-p:64:64-i64:64-f80:128-S128");
810    }
811
812    #[test]
813    fn only_x86_has_the_eighty_bit_format() {
814        assert_eq!(DataLayout::for_target(&linux()).f80_align, Some(128));
815        let arm = DataLayout::for_target(&target(Arch::Aarch64, Os::Linux, Env::Gnu));
816        assert_eq!(arm.f80_align, None);
817        assert_eq!(arm.to_string(), "e-p:64:64-i64:64-S128");
818    }
819
820    #[test]
821    fn a_layout_round_trips() {
822        for triple in [
823            Triple::new(Arch::X86_64, Os::Linux, Env::Gnu),
824            Triple::new(Arch::X86_64, Os::Darwin, Env::None),
825            Triple::new(Arch::Aarch64, Os::Darwin, Env::None),
826            Triple::new(Arch::Riscv64, Os::Linux, Env::Musl),
827        ] {
828            let layout = DataLayout::for_target(&TargetInfo::new(triple));
829            let text = layout.to_string();
830            assert_eq!(DataLayout::parse(&text), Some(layout), "{text}");
831        }
832    }
833
834    #[test]
835    fn a_layout_may_be_written_in_any_order() {
836        let text = "S128-i64:64-f80:128-p:64:64-e";
837        assert_eq!(DataLayout::parse(text), Some(DataLayout::for_target(&linux())));
838    }
839
840    #[test]
841    fn a_layout_needs_every_field_it_prints() {
842        for text in ["", "e", "e-p:64:64-S128", "e-i64:64-S128", "e-p:64:64-i64:64"] {
843            assert_eq!(DataLayout::parse(text), None, "{text}");
844        }
845    }
846
847    #[test]
848    fn a_layout_refuses_a_second_spelling() {
849        // Each of these would print back as something else, which breaks the round-trip.
850        for text in ["e-p:64:064-i64:64-S128", "e-e-p:64:64-i64:64-S128", "e-p:64:64-i64:64-S128-x"]
851        {
852            assert_eq!(DataLayout::parse(text), None, "{text}");
853        }
854    }
855
856    #[test]
857    fn a_module_finds_what_it_holds() {
858        let mut names = Interner::new();
859        let mut module = Module::new(names.intern("test.c"), &linux());
860
861        let counter = names.intern("counter");
862        let sum = names.intern("sum");
863        let total = names.intern("total");
864
865        let global = module.add_global(Global::new(counter, 4, 4));
866        let func = module.add_func(Func::new(sum, Signature::new()));
867        let alias = module.add_alias(Alias::new(total, counter));
868
869        assert_eq!(module.lookup(counter), Some(SymbolRef::Global(global)));
870        assert_eq!(module.lookup(sum), Some(SymbolRef::Func(func)));
871        assert_eq!(module.lookup(total), Some(SymbolRef::Alias(alias)));
872        assert_eq!(module.lookup(names.intern("nothing")), None);
873        assert_eq!(module[alias].target, counter);
874        assert!(module[global].is_declaration());
875        assert!(module[func].is_declaration());
876    }
877
878    #[test]
879    #[should_panic(expected = "two symbols with the same name")]
880    fn a_name_means_one_thing() {
881        let mut names = Interner::new();
882        let mut module = Module::new(names.intern("test.c"), &linux());
883        let name = names.intern("x");
884        module.add_global(Global::new(name, 4, 4));
885        module.add_func(Func::new(name, Signature::new()));
886    }
887
888    #[test]
889    fn an_initializer_adds_up_to_the_size() {
890        let mut names = Interner::new();
891        let mut module = Module::new(names.intern("test.c"), &linux());
892
893        // struct { int n; const char *name; char pad[6]; } = { 7, "hi", { 0 } };
894        let text = names.intern("hi.str");
895        let seven = module.add_imm(Imm::int(7, Type::int(32)));
896        let bytes = module.push_bytes(b"hi\0");
897        let addr = module.add_reloc(Reloc { symbol: text, addend: 0, size: 8 });
898        let init = module.push_data(&[
899            Datum::Scalar { ty: Type::int(32), value: seven },
900            Datum::Zero(4),
901            Datum::Addr(addr),
902            // The six bytes of `pad` and the two the struct is tailed out with. Padding is
903            // the frontend's arithmetic, and the image is what it came out as.
904            Datum::Zero(8),
905        ]);
906
907        let mut global = Global::new(names.intern("entry"), 24, 8);
908        global.init = Some(init);
909        global.constant = true;
910        let id = module.add_global(global);
911
912        assert!(!module[id].is_declaration());
913        let size: u64 = module[init].iter().map(|datum| datum.size(&module)).sum();
914        assert_eq!(size, module[id].size);
915        assert_eq!(&module[bytes], b"hi\0");
916        assert_eq!(module[seven].unsigned(), 7);
917        assert_eq!(module.counts().data_bytes, 3);
918    }
919
920    #[test]
921    fn a_scalar_datum_is_as_wide_as_its_type() {
922        let mut names = Interner::new();
923        let mut module = Module::new(names.intern("test.c"), &linux());
924        let value = module.add_imm(Imm::int(0, Type::int(32)));
925        assert_eq!(Datum::Scalar { ty: Type::int(32), value }.size(&module), 4);
926        // Rounded up to whole bytes, one lane at a time.
927        assert_eq!(Datum::Scalar { ty: Type::I1, value }.size(&module), 1);
928        assert_eq!(Datum::Scalar { ty: Type::int(24), value }.size(&module), 3);
929        assert_eq!(Datum::Scalar { ty: Type::vector(Type::int(8), 16), value }.size(&module), 16);
930    }
931
932    #[test]
933    fn the_names_round_trip() {
934        for linkage in Linkage::all() {
935            assert_eq!(Linkage::from_name(linkage.name()), Some(linkage));
936        }
937        for visibility in Visibility::all() {
938            assert_eq!(Visibility::from_name(visibility.name()), Some(visibility));
939        }
940        for model in TlsModel::all() {
941            assert_eq!(TlsModel::from_name(model.name()), Some(model));
942        }
943        for kind in [AliasKind::Alias, AliasKind::IFunc] {
944            assert_eq!(AliasKind::from_name(kind.name()), Some(kind));
945        }
946        assert_eq!(Linkage::from_name("static"), None);
947        assert_eq!(Visibility::from_name("internal"), None);
948    }
949
950    #[test]
951    fn only_internal_linkage_is_local() {
952        for linkage in Linkage::all() {
953            assert_eq!(linkage.is_local(), linkage == Linkage::Internal);
954            assert_eq!(
955                linkage.may_be_replaced(),
956                !matches!(linkage, Linkage::External | Linkage::Internal)
957            );
958        }
959    }
960
961    #[test]
962    fn metadata_is_shared_by_the_whole_module() {
963        let mut names = Interner::new();
964        let mut module = Module::new(names.intern("test.c"), &linux());
965        let char_node = module.add_meta(MetaNode::Tbaa(TbaaNode {
966            name: names.intern("omnipotent char"),
967            parent: None,
968            offset: 0,
969        }));
970        let int_node = module.add_meta(MetaNode::Tbaa(TbaaNode {
971            name: names.intern("int"),
972            parent: Some(char_node),
973            offset: 0,
974        }));
975        assert_eq!(module[int_node].parent(), Some(char_node));
976        assert_eq!(module.metadata().count(), 2);
977    }
978}