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/// Which link the module is being compiled for.
171///
172/// Everything this compiler writes is position independent, so this is not about whether there are
173/// absolute addresses in the text. It is about whether the link that reads the object puts every
174/// name in the same program. An executable is such a link and a shared library is not, and that
175/// decides whether a name is one another object may define or replace, which is the question
176/// [`Self::replaceable`] answers and the reason the field is carried this far down.
177///
178/// `-fPIC` and `-fPIE` on the command line. The expensive answer is the one that has to be asked
179/// for, which is gcc's arrangement.
180#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
181pub enum Pic {
182 /// The link puts every name in one program. `-fPIE` and the default.
183 #[default]
184 Executable,
185 /// The output may end up in a shared library. `-fPIC`.
186 Library,
187}
188
189impl Pic {
190 /// Whether another object may define or replace a name with that linkage and that visibility.
191 ///
192 /// Nothing is replaceable in an executable. The definition in the executable is the one the
193 /// whole program uses, and a reference to a variable some library defines is answered by
194 /// making room for it in the executable and copying it there, so even a name this file only
195 /// declares ends up somewhere this file could have measured the distance to.
196 ///
197 /// In a shared library the exported names are, which is the whole of what exporting means: the
198 /// dynamic linker looks a name up in load order and the first definition it finds is the one
199 /// everything in the process uses, so a library that reached its own copy from the instruction
200 /// pointer would be the one part of the program not using it. Hidden and protected names are
201 /// not, since one is not in the table to be looked up and the other says a reference from
202 /// inside binds to the definition inside. `static` is not, for the reason it is never anything.
203 #[must_use]
204 pub const fn replaceable(self, linkage: Linkage, visibility: Visibility) -> bool {
205 match self {
206 Self::Executable => false,
207 Self::Library => match visibility {
208 Visibility::Hidden | Visibility::Protected => false,
209 Visibility::Default => !matches!(linkage, Linkage::Internal),
210 },
211 }
212 }
213}
214
215/// How a thread-local variable is reached.
216///
217/// The models are ordered from the most general to the fastest, and a model may always be
218/// replaced by a more general one. The frontend picks from the storage class and the
219/// visibility, `-ftls-model=` overrides it, and the linker may relax a general one into a
220/// faster one when it turns out the definition is in the executable.
221#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
222pub enum TlsModel {
223 /// Works for any variable in any object, at the cost of a call to `__tls_get_addr`.
224 #[default]
225 GlobalDynamic,
226 /// One call to `__tls_get_addr` for several variables that are known to share a module.
227 LocalDynamic,
228 /// The offset is loaded from the GOT. Needs the variable to be in a module loaded at
229 /// program start rather than by `dlopen`.
230 InitialExec,
231 /// The offset is a link-time constant. Only for a variable in the executable itself.
232 LocalExec,
233}
234
235impl TlsModel {
236 /// The spelling in the textual form.
237 #[must_use]
238 pub const fn name(self) -> &'static str {
239 match self {
240 Self::GlobalDynamic => "global_dynamic",
241 Self::LocalDynamic => "local_dynamic",
242 Self::InitialExec => "initial_exec",
243 Self::LocalExec => "local_exec",
244 }
245 }
246
247 /// The model that spelling names.
248 #[must_use]
249 pub fn from_name(name: &str) -> Option<Self> {
250 Self::all().find(|model| model.name() == name)
251 }
252
253 /// Every model, from the most general to the fastest.
254 pub fn all() -> impl Iterator<Item = Self> {
255 [Self::GlobalDynamic, Self::LocalDynamic, Self::InitialExec, Self::LocalExec].into_iter()
256 }
257}
258
259/// One piece of a global's initial image.
260///
261/// Sixteen bytes, so an initializer built out of them is a flat array and a table of a
262/// million bytes is one of these rather than a million.
263#[derive(Debug, Clone, Copy, PartialEq, Eq)]
264pub enum Datum {
265 /// That many zero bytes. What `.bss` is made of, and what the tail of a partly
266 /// initialized array is.
267 Zero(u64),
268 /// Those literal bytes, from the module's byte pool. String literals and anything the
269 /// frontend has already laid out.
270 Bytes(ByteRange),
271 /// One scalar of that IR type, from the module's immediate pool. An integer holds its
272 /// value and a float holds its bit pattern, both target-independently: which byte comes
273 /// first is decided by the datalayout when the object file is written, not here.
274 Scalar {
275 /// The type of the scalar, which gives its width.
276 ty: Type,
277 /// Its value, in the module's immediate pool.
278 value: Idx<Imm>,
279 },
280 /// The address of another symbol, from the module's relocation pool. `&x` in an
281 /// initializer, which the linker fills in.
282 Addr(Idx<Reloc>),
283 /// How far another symbol is from where this is written, from the same pool. `.long
284 /// target - .` in an `asm` at file scope, which is what a table of places in a program
285 /// holds when the table and the places are both in it: the distance fits in four bytes
286 /// where an address takes eight, and it is the same number wherever the image is loaded,
287 /// so nothing has to be written into it at startup.
288 Away(Idx<Reloc>),
289 /// How far the symbol in the relocation is from another, `.long to - from`. GNU C's
290 /// `&&to - &&from` in an initializer, where both are labels of one function and the distance
291 /// is a number once the function is laid out, so the assembler writes it and the linker is
292 /// never asked. The relocation says where it is measured to and how wide it is written.
293 Apart {
294 /// The place the distance is measured to, with what to add and the width.
295 to: Idx<Reloc>,
296 /// The place it is measured from.
297 from: Symbol,
298 },
299}
300
301impl Datum {
302 /// How many bytes it contributes to the image.
303 ///
304 /// The module is an argument because four of the five kinds keep what they are made of in
305 /// one of its pools, and a datum on its own is four words that mean nothing without it.
306 #[must_use]
307 pub fn size(self, module: &Module) -> u64 {
308 match self {
309 Self::Zero(bytes) => bytes,
310 Self::Bytes(range) => range.len() as u64,
311 // Rounded up, so that an `i1` in an image is a byte and a `_BitInt(24)` is three.
312 Self::Scalar { ty, .. } => u64::from(ty.bits().div_ceil(8)) * u64::from(ty.lanes()),
313 Self::Addr(reloc) | Self::Away(reloc) | Self::Apart { to: reloc, .. } => {
314 u64::from(module[reloc].size)
315 }
316 }
317 }
318}
319
320/// The address of a symbol, written into a global's image by the linker.
321#[derive(Debug, Clone, Copy, PartialEq, Eq)]
322pub struct Reloc {
323 /// The symbol whose address this is.
324 pub symbol: Symbol,
325 /// What to add to that address. `&array[2]` is the address of `array` plus eight.
326 pub addend: i64,
327 /// How many bytes the address occupies, which is the pointer width except where a target
328 /// has a smaller relocation for it.
329 pub size: u32,
330}
331
332/// A global variable.
333///
334/// A size and an alignment and an image, which is what the object writer needs. `init` is
335/// `None` for a declaration of something defined in another object, which is the only thing
336/// that distinguishes the two.
337#[derive(Debug, Clone)]
338pub struct Global {
339 /// The name it is reached by.
340 pub name: Symbol,
341 /// Its size in bytes, which the image must add up to.
342 pub size: u64,
343 /// Its required alignment in bytes, always a power of two.
344 pub align: u32,
345 /// How the linker sees it.
346 pub linkage: Linkage,
347 /// How the dynamic linker sees it.
348 pub visibility: Visibility,
349 /// The model to reach it by if it is thread-local, and `None` if it is not.
350 pub tls: Option<TlsModel>,
351 /// Whether writing through a pointer to it is undefined, which is what puts it in
352 /// `.rodata` rather than `.data`.
353 pub constant: bool,
354 /// The section to put it in, from `__attribute__((section(...)))`, or `None` to let the
355 /// object writer choose from the other fields.
356 pub section: Option<Symbol>,
357 /// Its initial image, or `None` if it is only declared here.
358 pub init: Option<DataList>,
359}
360
361impl Global {
362 /// A definition-less global of that size and alignment, external and not thread-local.
363 #[must_use]
364 pub fn new(name: Symbol, size: u64, align: u32) -> Self {
365 Self {
366 name,
367 size,
368 align,
369 linkage: Linkage::External,
370 visibility: Visibility::Default,
371 tls: None,
372 constant: false,
373 section: None,
374 init: None,
375 }
376 }
377
378 /// Whether this only says the variable exists somewhere.
379 #[must_use]
380 pub fn is_declaration(&self) -> bool {
381 self.init.is_none()
382 }
383}
384
385/// What an alias resolves to at link time.
386#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
387pub enum AliasKind {
388 /// A second name for a symbol in this same object, resolved by the assembler.
389 /// `__attribute__((alias("real")))`.
390 #[default]
391 Alias,
392 /// A name resolved once at program start by calling a resolver function in this object,
393 /// which picks an implementation from what the processor turns out to support.
394 /// `__attribute__((ifunc("resolver")))`, which is how glibc dispatches `memcpy`.
395 IFunc,
396}
397
398impl AliasKind {
399 /// The spelling in the textual form.
400 #[must_use]
401 pub const fn name(self) -> &'static str {
402 match self {
403 Self::Alias => "alias",
404 Self::IFunc => "ifunc",
405 }
406 }
407
408 /// The kind that spelling names.
409 #[must_use]
410 pub fn from_name(name: &str) -> Option<Self> {
411 match name {
412 "alias" => Some(Self::Alias),
413 "ifunc" => Some(Self::IFunc),
414 _ => None,
415 }
416 }
417}
418
419/// A second name for something else.
420#[derive(Debug, Clone, Copy, PartialEq, Eq)]
421pub struct Alias {
422 /// The name being defined.
423 pub name: Symbol,
424 /// What it resolves to: the aliased symbol, or for an ifunc the resolver to call.
425 pub target: Symbol,
426 /// Which of those two it is.
427 pub kind: AliasKind,
428 /// How the linker sees the new name.
429 pub linkage: Linkage,
430 /// How the dynamic linker sees the new name.
431 pub visibility: Visibility,
432}
433
434impl Alias {
435 /// An external alias of `target`.
436 #[must_use]
437 pub fn new(name: Symbol, target: Symbol) -> Self {
438 Self {
439 name,
440 target,
441 kind: AliasKind::Alias,
442 linkage: Linkage::External,
443 visibility: Visibility::Default,
444 }
445 }
446}
447
448/// What a name in a module refers to.
449#[derive(Debug, Clone, Copy, PartialEq, Eq)]
450pub enum SymbolRef {
451 /// A function, defined or declared.
452 Func(FuncId),
453 /// A global variable, defined or declared.
454 Global(GlobalId),
455 /// An alias or an ifunc.
456 Alias(AliasId),
457}
458
459/// The layout facts a printed module carries so it can be compiled without the command line
460/// that produced it.
461///
462/// A subset of the string LLVM writes, in the same syntax, because that syntax is what tools
463/// around the ecosystem already read. It says what the module was built assuming, and the
464/// verifier is what checks it against the target actually being compiled for: a module built
465/// for a 64-bit pointer cannot be finished for a 32-bit one, and finding that out here is
466/// better than finding it out as wrong output.
467#[derive(Debug, Clone, Copy, PartialEq, Eq)]
468pub struct DataLayout {
469 /// Whether the low byte of a scalar is stored first.
470 pub little_endian: bool,
471 /// The width of a pointer in bits.
472 pub pointer_bits: u32,
473 /// The alignment of a pointer in bits.
474 pub pointer_align: u32,
475 /// The alignment of a 64-bit integer in bits, which is the one integer alignment that
476 /// varies across the targets anybody still builds for.
477 pub i64_align: u32,
478 /// The alignment of the x87 eighty bit format in bits, and `None` on a target that does
479 /// not have it.
480 pub f80_align: Option<u32>,
481 /// The alignment the stack is kept at in bits, which is 128 on every target here.
482 pub stack_align: u32,
483}
484
485impl DataLayout {
486 /// The layout of that target.
487 ///
488 /// # Panics
489 ///
490 /// If the target aligns a `long long` to more than half a billion bytes, which no target
491 /// does. The alignment is a byte count here and a bit count in the IR, and the multiplication
492 /// between the two is the only arithmetic in this function.
493 #[must_use]
494 pub fn for_target(target: &TargetInfo) -> Self {
495 Self {
496 little_endian: target.little_endian,
497 pointer_bits: target.pointer_width,
498 pointer_align: target.pointer_width,
499 // Four on System V i386 and eight everywhere else, which is the one integer
500 // alignment that varies across the table and the reason this is a field. It changes
501 // the layout of every struct with a `long long` in it.
502 i64_align: u32::try_from(target.scalars.long_long_align * 8)
503 .expect("no integer alignment is four billion bits"),
504 f80_align: match target.long_double_format {
505 Format::X87Extended => Some(128),
506 _ => None,
507 },
508 stack_align: 128,
509 }
510 }
511
512 /// The layout back from the string [`Display`](fmt::Display) wrote, or `None` if the
513 /// string is not one.
514 ///
515 /// The fields may come in any order, because a string written by hand will not have them
516 /// in ours. A string this crate printed round-trips byte for byte, which is what
517 /// `spec/03-architecture.md` asks of the textual form.
518 #[must_use]
519 pub fn parse(text: &str) -> Option<Self> {
520 let mut little_endian = None;
521 let mut pointer = None;
522 let mut i64_align = None;
523 let mut f80_align = None;
524 let mut stack_align = None;
525 for field in text.split('-') {
526 let seen = match field {
527 "e" => little_endian.replace(true).is_some(),
528 "E" => little_endian.replace(false).is_some(),
529 _ if field.starts_with("p:") => {
530 let (bits, align) = field[2..].split_once(':')?;
531 pointer.replace((number(bits)?, number(align)?)).is_some()
532 }
533 _ if field.starts_with("i64:") => i64_align.replace(number(&field[4..])?).is_some(),
534 _ if field.starts_with("f80:") => f80_align.replace(number(&field[4..])?).is_some(),
535 _ if field.starts_with('S') => stack_align.replace(number(&field[1..])?).is_some(),
536 _ => return None,
537 };
538 if seen {
539 return None;
540 }
541 }
542 let (pointer_bits, pointer_align) = pointer?;
543 Some(Self {
544 little_endian: little_endian?,
545 pointer_bits,
546 pointer_align,
547 i64_align: i64_align?,
548 f80_align,
549 stack_align: stack_align?,
550 })
551 }
552}
553
554impl fmt::Display for DataLayout {
555 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
556 write!(f, "{}", if self.little_endian { "e" } else { "E" })?;
557 write!(f, "-p:{}:{}", self.pointer_bits, self.pointer_align)?;
558 write!(f, "-i64:{}", self.i64_align)?;
559 if let Some(align) = self.f80_align {
560 write!(f, "-f80:{align}")?;
561 }
562 write!(f, "-S{}", self.stack_align)
563 }
564}
565
566/// A number in the textual form: digits, no sign, and no leading zero.
567///
568/// `p:64:064` would otherwise parse and then print back as `p:64:64`, which breaks the
569/// round-trip for no benefit to anybody.
570fn number(text: &str) -> Option<u32> {
571 if text.is_empty() || (text.len() > 1 && text.starts_with('0')) {
572 return None;
573 }
574 if !text.bytes().all(|byte| byte.is_ascii_digit()) {
575 return None;
576 }
577 text.parse().ok()
578}
579
580/// One translation unit, or after LTO the several that were linked into one.
581#[derive(Debug)]
582pub struct Module {
583 /// What it is called, which is the source file name for a module from the frontend. It
584 /// appears in the textual form and in the debug info and nothing branches on it.
585 pub name: Symbol,
586 /// The target it is for.
587 pub tuple: TargetTuple,
588 /// The layout it was built assuming.
589 pub datalayout: DataLayout,
590
591 funcs: Vec<Func>,
592 globals: Vec<Global>,
593 aliases: Vec<Alias>,
594 metadata: Vec<MetaNode>,
595
596 data: Vec<Datum>,
597 bytes: Vec<u8>,
598 imms: Vec<Imm>,
599 relocs: Vec<Reloc>,
600
601 symbols: HashMap<Symbol, SymbolRef>,
602
603 /// The `asm` written at file scope that the lowering could not read into globals, which is one
604 /// with an instruction in it, kept as the text it was written as. See
605 /// [`Module::add_file_asm`].
606 file_asm: Vec<String>,
607}
608
609impl Module {
610 /// An empty module for that target.
611 #[must_use]
612 pub fn new(name: Symbol, target: &TargetInfo) -> Self {
613 Self {
614 name,
615 tuple: target.tuple,
616 datalayout: DataLayout::for_target(target),
617 funcs: Vec::new(),
618 globals: Vec::new(),
619 aliases: Vec::new(),
620 metadata: Vec::new(),
621 data: Vec::new(),
622 bytes: Vec::new(),
623 imms: Vec::new(),
624 relocs: Vec::new(),
625 symbols: HashMap::new(),
626 file_asm: Vec::new(),
627 }
628 }
629
630 /// Keeps the text of an `asm` at file scope to be handed to the assembler as it was written.
631 ///
632 /// What it defines is invisible here: a function written in one is a declaration as far as
633 /// the IR knows, and the definition turns up when the listing is read. That is gcc's contract
634 /// too, where the template goes into the output between `#APP` and `#NO_APP` and nothing
635 /// before the assembler looks inside it.
636 pub fn add_file_asm(&mut self, text: String) {
637 self.file_asm.push(text);
638 }
639
640 /// The text of each `asm` at file scope kept by [`Module::add_file_asm`], in the order they
641 /// were written.
642 #[must_use]
643 pub fn file_asms(&self) -> &[String] {
644 &self.file_asm
645 }
646
647 // Symbols.
648
649 /// Adds a function, which is a declaration if it has no blocks.
650 ///
651 /// # Panics
652 ///
653 /// Panics if the module already has a symbol of that name. Merging a declaration with a
654 /// definition is the frontend's job and it has the declarations to do it with; by the time
655 /// something is in the IR a name means one thing.
656 pub fn add_func(&mut self, func: Func) -> FuncId {
657 let id = Idx::from_usize(self.funcs.len());
658 self.claim(func.name, SymbolRef::Func(id));
659 self.funcs.push(func);
660 id
661 }
662
663 /// Adds a global variable, which is a declaration if it has no image.
664 ///
665 /// # Panics
666 ///
667 /// Panics if the module already has a symbol of that name.
668 pub fn add_global(&mut self, global: Global) -> GlobalId {
669 let id = Idx::from_usize(self.globals.len());
670 self.claim(global.name, SymbolRef::Global(id));
671 self.globals.push(global);
672 id
673 }
674
675 /// Adds an alias.
676 ///
677 /// The target is not resolved here, and it need not be in this module: an alias of
678 /// something in another object is a thing people write.
679 ///
680 /// # Panics
681 ///
682 /// Panics if the module already has a symbol of that name.
683 pub fn add_alias(&mut self, alias: Alias) -> AliasId {
684 let id = Idx::from_usize(self.aliases.len());
685 self.claim(alias.name, SymbolRef::Alias(id));
686 self.aliases.push(alias);
687 id
688 }
689
690 /// Adds an alias under a name the module so far only declared, which it then stands for.
691 ///
692 /// The declaration stays where it was and is still a declaration, so whatever refers to it
693 /// goes on naming the same symbol, and the symbol is now the alias. That is what an assembler
694 /// does with `.set f, g` below a C declaration of `f`.
695 ///
696 /// # Panics
697 ///
698 /// Panics if the module already defines that name.
699 pub fn add_alias_over(&mut self, alias: Alias) -> AliasId {
700 let declared = match self.symbols.remove(&alias.name) {
701 None => true,
702 Some(SymbolRef::Func(id)) => self[id].is_declaration(),
703 Some(SymbolRef::Global(id)) => self[id].is_declaration(),
704 Some(SymbolRef::Alias(_)) => false,
705 };
706 assert!(declared, "an alias can only take the place of a declaration");
707 self.add_alias(alias)
708 }
709
710 /// What that name refers to, or `None` if this module does not define or declare it.
711 #[must_use]
712 pub fn lookup(&self, name: Symbol) -> Option<SymbolRef> {
713 self.symbols.get(&name).copied()
714 }
715
716 /// Every function, in the order they were added.
717 pub fn funcs(&self) -> impl Iterator<Item = FuncId> + use<> {
718 (0..self.funcs.len()).map(Idx::from_usize)
719 }
720
721 /// Every global variable, in the order they were added.
722 pub fn globals(&self) -> impl Iterator<Item = GlobalId> + use<> {
723 (0..self.globals.len()).map(Idx::from_usize)
724 }
725
726 /// Every alias, in the order they were added.
727 pub fn aliases(&self) -> impl Iterator<Item = AliasId> + use<> {
728 (0..self.aliases.len()).map(Idx::from_usize)
729 }
730
731 fn claim(&mut self, name: Symbol, what: SymbolRef) {
732 assert!(
733 self.symbols.insert(name, what).is_none(),
734 "a module cannot have two symbols with the same name"
735 );
736 }
737
738 // Metadata.
739
740 /// Adds a metadata node and gives back the reference an instruction holds.
741 ///
742 /// The nodes live here rather than in a function because a TBAA tree is shared by every
743 /// memory operation in the module and duplicating it per function would make two accesses
744 /// to the same type look unrelated.
745 pub fn add_meta(&mut self, node: MetaNode) -> Meta {
746 self.metadata.push(node);
747 Idx::from_usize(self.metadata.len() - 1)
748 }
749
750 /// Every metadata node, in the order they were added.
751 pub fn metadata(&self) -> impl Iterator<Item = Meta> + use<> {
752 (0..self.metadata.len()).map(Idx::from_usize)
753 }
754
755 // Pools.
756
757 /// Records a run of data and gives back the list a global holds.
758 pub fn push_data(&mut self, data: &[Datum]) -> DataList {
759 let start = self.data.len();
760 self.data.extend_from_slice(data);
761 DataList::new(Idx::from_usize(start), Idx::from_usize(self.data.len()))
762 }
763
764 /// Records literal bytes and gives back the range a [`Datum::Bytes`] holds.
765 pub fn push_bytes(&mut self, bytes: &[u8]) -> ByteRange {
766 let start = self.bytes.len();
767 self.bytes.extend_from_slice(bytes);
768 ByteRange::new(Idx::from_usize(start), Idx::from_usize(self.bytes.len()))
769 }
770
771 /// Records a scalar value and gives back the index a [`Datum::Scalar`] holds.
772 pub fn add_imm(&mut self, imm: Imm) -> Idx<Imm> {
773 self.imms.push(imm);
774 Idx::from_usize(self.imms.len() - 1)
775 }
776
777 /// Records a relocation and gives back the index a [`Datum::Addr`] holds.
778 pub fn add_reloc(&mut self, reloc: Reloc) -> Idx<Reloc> {
779 self.relocs.push(reloc);
780 Idx::from_usize(self.relocs.len() - 1)
781 }
782
783 /// Every relocation in the module, to be read or edited in place.
784 ///
785 /// A pool rather than a tree, so a pass that wants to rename what an initializer points at has
786 /// nothing to walk: the data lists hold indices into this and the symbol lives here. The one
787 /// pass that wants that is `rucc_safety::wrap`, which turns `&read` in a static initializer
788 /// into `&__rucc_wrap_read` so that a call through the pointer is a call the monitor modelled.
789 pub fn relocs_mut(&mut self) -> &mut [Reloc] {
790 &mut self.relocs
791 }
792
793 /// The same pool, to read. `rucc_safety::summary` walks it to find the names an initializer
794 /// mentions that the build has no wrapper for, which is a boundary it did not model.
795 #[must_use]
796 pub fn relocs(&self) -> &[Reloc] {
797 &self.relocs
798 }
799
800 /// How much is in it, for the `-fstats` output and for a test that wants to say a pass
801 /// deleted something without saying which.
802 #[must_use]
803 pub fn counts(&self) -> ModuleCounts {
804 ModuleCounts {
805 funcs: self.funcs.len(),
806 globals: self.globals.len(),
807 aliases: self.aliases.len(),
808 metadata: self.metadata.len(),
809 data_bytes: self.bytes.len(),
810 }
811 }
812}
813
814/// How much is in a module, from [`Module::counts`].
815#[derive(Debug, Clone, Copy, PartialEq, Eq)]
816pub struct ModuleCounts {
817 /// Functions, defined and declared.
818 pub funcs: usize,
819 /// Global variables, defined and declared.
820 pub globals: usize,
821 /// Aliases and ifuncs.
822 pub aliases: usize,
823 /// Metadata nodes.
824 pub metadata: usize,
825 /// Bytes in the byte pool, which is the bulk of what a module with large initializers
826 /// weighs.
827 pub data_bytes: usize,
828}
829
830impl Index<FuncId> for Module {
831 type Output = Func;
832
833 fn index(&self, id: FuncId) -> &Func {
834 &self.funcs[id.index()]
835 }
836}
837
838impl IndexMut<FuncId> for Module {
839 fn index_mut(&mut self, id: FuncId) -> &mut Func {
840 &mut self.funcs[id.index()]
841 }
842}
843
844impl Index<GlobalId> for Module {
845 type Output = Global;
846
847 fn index(&self, id: GlobalId) -> &Global {
848 &self.globals[id.index()]
849 }
850}
851
852impl IndexMut<GlobalId> for Module {
853 fn index_mut(&mut self, id: GlobalId) -> &mut Global {
854 &mut self.globals[id.index()]
855 }
856}
857
858impl Index<AliasId> for Module {
859 type Output = Alias;
860
861 fn index(&self, id: AliasId) -> &Alias {
862 &self.aliases[id.index()]
863 }
864}
865
866impl Index<Meta> for Module {
867 type Output = MetaNode;
868
869 fn index(&self, meta: Meta) -> &MetaNode {
870 &self.metadata[meta.index()]
871 }
872}
873
874impl Index<Idx<Imm>> for Module {
875 type Output = Imm;
876
877 fn index(&self, imm: Idx<Imm>) -> &Imm {
878 &self.imms[imm.index()]
879 }
880}
881
882impl Index<Idx<Reloc>> for Module {
883 type Output = Reloc;
884
885 fn index(&self, reloc: Idx<Reloc>) -> &Reloc {
886 &self.relocs[reloc.index()]
887 }
888}
889
890impl Index<DataList> for Module {
891 type Output = [Datum];
892
893 fn index(&self, list: DataList) -> &[Datum] {
894 &self.data[list.as_usize_range()]
895 }
896}
897
898impl Index<ByteRange> for Module {
899 type Output = [u8];
900
901 fn index(&self, range: ByteRange) -> &[u8] {
902 &self.bytes[range.as_usize_range()]
903 }
904}
905
906#[cfg(test)]
907mod tests {
908 use rucc_base::Interner;
909 use rucc_target::{Arch, Env, Os, Triple};
910
911 use super::*;
912 use crate::inst::Signature;
913
914 fn target(arch: Arch, os: Os, env: Env) -> TargetInfo {
915 TargetInfo::new(Triple::new(arch, os, env))
916 }
917
918 fn linux() -> TargetInfo {
919 target(Arch::X86_64, Os::Linux, Env::Gnu)
920 }
921
922 #[test]
923 fn a_datum_is_sixteen_bytes() {
924 // A global with a large initializer is a flat array of these, so this is the tripwire
925 // on somebody adding a field that doubles the weight of every one.
926 assert_eq!(size_of::<Datum>(), 16);
927 }
928
929 #[test]
930 fn the_layout_of_x86_64_linux_is_the_one_in_the_spec() {
931 let layout = DataLayout::for_target(&linux());
932 assert_eq!(layout.to_string(), "e-p:64:64-i64:64-f80:128-S128");
933 }
934
935 #[test]
936 fn only_x86_has_the_eighty_bit_format() {
937 assert_eq!(DataLayout::for_target(&linux()).f80_align, Some(128));
938 let arm = DataLayout::for_target(&target(Arch::Aarch64, Os::Linux, Env::Gnu));
939 assert_eq!(arm.f80_align, None);
940 assert_eq!(arm.to_string(), "e-p:64:64-i64:64-S128");
941 }
942
943 #[test]
944 fn a_layout_round_trips() {
945 for triple in [
946 Triple::new(Arch::X86_64, Os::Linux, Env::Gnu),
947 Triple::new(Arch::X86_64, Os::Darwin, Env::None),
948 Triple::new(Arch::Aarch64, Os::Darwin, Env::None),
949 Triple::new(Arch::Riscv64, Os::Linux, Env::Musl),
950 ] {
951 let layout = DataLayout::for_target(&TargetInfo::new(triple));
952 let text = layout.to_string();
953 assert_eq!(DataLayout::parse(&text), Some(layout), "{text}");
954 }
955 }
956
957 #[test]
958 fn a_layout_may_be_written_in_any_order() {
959 let text = "S128-i64:64-f80:128-p:64:64-e";
960 assert_eq!(DataLayout::parse(text), Some(DataLayout::for_target(&linux())));
961 }
962
963 #[test]
964 fn a_layout_needs_every_field_it_prints() {
965 for text in ["", "e", "e-p:64:64-S128", "e-i64:64-S128", "e-p:64:64-i64:64"] {
966 assert_eq!(DataLayout::parse(text), None, "{text}");
967 }
968 }
969
970 #[test]
971 fn a_layout_refuses_a_second_spelling() {
972 // Each of these would print back as something else, which breaks the round-trip.
973 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"]
974 {
975 assert_eq!(DataLayout::parse(text), None, "{text}");
976 }
977 }
978
979 #[test]
980 fn a_module_finds_what_it_holds() {
981 let mut names = Interner::new();
982 let mut module = Module::new(names.intern("test.c"), &linux());
983
984 let counter = names.intern("counter");
985 let sum = names.intern("sum");
986 let total = names.intern("total");
987
988 let global = module.add_global(Global::new(counter, 4, 4));
989 let func = module.add_func(Func::new(sum, Signature::new()));
990 let alias = module.add_alias(Alias::new(total, counter));
991
992 assert_eq!(module.lookup(counter), Some(SymbolRef::Global(global)));
993 assert_eq!(module.lookup(sum), Some(SymbolRef::Func(func)));
994 assert_eq!(module.lookup(total), Some(SymbolRef::Alias(alias)));
995 assert_eq!(module.lookup(names.intern("nothing")), None);
996 assert_eq!(module[alias].target, counter);
997 assert!(module[global].is_declaration());
998 assert!(module[func].is_declaration());
999 }
1000
1001 #[test]
1002 #[should_panic(expected = "two symbols with the same name")]
1003 fn a_name_means_one_thing() {
1004 let mut names = Interner::new();
1005 let mut module = Module::new(names.intern("test.c"), &linux());
1006 let name = names.intern("x");
1007 module.add_global(Global::new(name, 4, 4));
1008 module.add_func(Func::new(name, Signature::new()));
1009 }
1010
1011 #[test]
1012 fn an_initializer_adds_up_to_the_size() {
1013 let mut names = Interner::new();
1014 let mut module = Module::new(names.intern("test.c"), &linux());
1015
1016 // struct { int n; const char *name; char pad[6]; } = { 7, "hi", { 0 } };
1017 let text = names.intern("hi.str");
1018 let seven = module.add_imm(Imm::int(7, Type::int(32)));
1019 let bytes = module.push_bytes(b"hi\0");
1020 let addr = module.add_reloc(Reloc { symbol: text, addend: 0, size: 8 });
1021 let init = module.push_data(&[
1022 Datum::Scalar { ty: Type::int(32), value: seven },
1023 Datum::Zero(4),
1024 Datum::Addr(addr),
1025 // The six bytes of `pad` and the two the struct is tailed out with. Padding is
1026 // the frontend's arithmetic, and the image is what it came out as.
1027 Datum::Zero(8),
1028 ]);
1029
1030 let mut global = Global::new(names.intern("entry"), 24, 8);
1031 global.init = Some(init);
1032 global.constant = true;
1033 let id = module.add_global(global);
1034
1035 assert!(!module[id].is_declaration());
1036 let size: u64 = module[init].iter().map(|datum| datum.size(&module)).sum();
1037 assert_eq!(size, module[id].size);
1038 assert_eq!(&module[bytes], b"hi\0");
1039 assert_eq!(module[seven].unsigned(), 7);
1040 assert_eq!(module.counts().data_bytes, 3);
1041 }
1042
1043 #[test]
1044 fn a_scalar_datum_is_as_wide_as_its_type() {
1045 let mut names = Interner::new();
1046 let mut module = Module::new(names.intern("test.c"), &linux());
1047 let value = module.add_imm(Imm::int(0, Type::int(32)));
1048 assert_eq!(Datum::Scalar { ty: Type::int(32), value }.size(&module), 4);
1049 // Rounded up to whole bytes, one lane at a time.
1050 assert_eq!(Datum::Scalar { ty: Type::I1, value }.size(&module), 1);
1051 assert_eq!(Datum::Scalar { ty: Type::int(24), value }.size(&module), 3);
1052 assert_eq!(Datum::Scalar { ty: Type::vector(Type::int(8), 16), value }.size(&module), 16);
1053 }
1054
1055 #[test]
1056 fn the_names_round_trip() {
1057 for linkage in Linkage::all() {
1058 assert_eq!(Linkage::from_name(linkage.name()), Some(linkage));
1059 }
1060 for visibility in Visibility::all() {
1061 assert_eq!(Visibility::from_name(visibility.name()), Some(visibility));
1062 }
1063 for model in TlsModel::all() {
1064 assert_eq!(TlsModel::from_name(model.name()), Some(model));
1065 }
1066 for kind in [AliasKind::Alias, AliasKind::IFunc] {
1067 assert_eq!(AliasKind::from_name(kind.name()), Some(kind));
1068 }
1069 assert_eq!(Linkage::from_name("static"), None);
1070 assert_eq!(Visibility::from_name("internal"), None);
1071 }
1072
1073 #[test]
1074 fn only_internal_linkage_is_local() {
1075 for linkage in Linkage::all() {
1076 assert_eq!(linkage.is_local(), linkage == Linkage::Internal);
1077 assert_eq!(
1078 linkage.may_be_replaced(),
1079 !matches!(linkage, Linkage::External | Linkage::Internal)
1080 );
1081 }
1082 }
1083
1084 #[test]
1085 fn metadata_is_shared_by_the_whole_module() {
1086 let mut names = Interner::new();
1087 let mut module = Module::new(names.intern("test.c"), &linux());
1088 let char_node = module.add_meta(MetaNode::Tbaa(TbaaNode {
1089 name: names.intern("omnipotent char"),
1090 parent: None,
1091 offset: 0,
1092 }));
1093 let int_node = module.add_meta(MetaNode::Tbaa(TbaaNode {
1094 name: names.intern("int"),
1095 parent: Some(char_node),
1096 offset: 0,
1097 }));
1098 assert_eq!(module[int_node].parent(), Some(char_node));
1099 assert_eq!(module.metadata().count(), 2);
1100 }
1101}