Skip to main content

rucc_lower/
unit.rs

1//! The module level of the walk: what a translation unit's declarations become.
2//!
3//! Design: `spec/08-ir.md` section 8.9.
4//!
5//! One typed tree becomes one [`Module`]. A file-scope object becomes a global with an image
6//! built from its initializer, a function becomes a [`Func`] whose body is built by
7//! [`body`](mod@crate::body), and a string literal becomes an unnamed constant global that
8//! whatever mentioned it points at.
9//!
10//! # What an image is
11//!
12//! An initializer arrives here already flattened: one entry per scalar that is stored, each
13//! with the byte offset it goes at, with every designator and every nested brace already
14//! resolved. So building the image is a walk over the entries in offset order, filling the gaps
15//! between them with zeros, and the only thing that has to be worked out per entry is whether
16//! the value is a number, a run of bytes from a string literal, or the address of something the
17//! linker has to place.
18//!
19//! # Names
20//!
21//! An object with linkage is known by the name it was written with, and there is nothing to
22//! invent. A `static` inside a function has no linkage and still needs a name in the object
23//! file, so it gets `name.N`, which is what gcc does and is why two functions may each have a
24//! `static int count;` without colliding. A string literal has no name at all and gets
25//! `.Lstr.N`, whose leading dot keeps it out of the symbol table on every target that has the
26//! convention.
27
28use std::cmp::Ordering;
29use std::collections::{BTreeMap, HashMap, HashSet};
30use std::fmt;
31
32use rucc_base::{Interner, Symbol};
33use rucc_diag::{Diagnostic, Span};
34use rucc_ir::{
35    Alias, AttrSet, DataList, Datum, FpContract, Func, Global, Imm, Linkage as IrLinkage, Meta,
36    Module, Reloc, SymbolRef, TlsModel, Type, Visibility as IrVisibility,
37};
38use rucc_sema::{
39    Address, Base, Const, Conversion, DeclFlags, DeclId, DeclKind, Definition, Effects, Emission,
40    Eval, ExprId, ExprKind, InitEntry, InitList, LabelId, Linkage, Priority, StorageDuration,
41    StrId, Tast, Visibility,
42};
43use rucc_target::{ObjectFormat, TargetInfo};
44use rucc_types::{TypeId, TypeKind, Types, compatible, is_complex, is_scalar};
45
46use crate::abi::{self, Plan};
47use crate::aliasing;
48use crate::body;
49use crate::directives;
50use crate::reach;
51use crate::repr;
52
53/// Which functions get a stack protector, which is what the `-fstack-protector` family decides.
54///
55/// The question is about the locals a function has, so it is answered here and not in the back
56/// end: by the time a frame is laid out the types are gone and every local is a size and an
57/// alignment. What the back end then does about the answer is its own business, and it is carried
58/// to it as [`rucc_ir::AttrSet::STACK_PROTECT`] on the function.
59///
60/// The names are gcc's, and so are the rules. A build that has been compiled with one of these for
61/// twenty years is entitled to the same set of protected functions from a compiler claiming to be
62/// compatible, because the ones left out are the ones an exploit goes looking for.
63#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
64pub enum Protector {
65    /// None of them, which is `-fno-stack-protector` and what a command line that says nothing
66    /// gets.
67    #[default]
68    None,
69    /// A function with a local array of at least eight bytes, or one whose stack grows while it
70    /// runs. `-fstack-protector`, which is the original and the narrowest.
71    Buffers,
72    /// Any of those, and any function with a local array at all, a local holding one, or a local
73    /// whose address is taken. `-fstack-protector-strong`, which is what every distribution builds
74    /// its packages with and therefore the one a real build line carries.
75    Strong,
76    /// Every function that has a frame at all. `-fstack-protector-all`.
77    All,
78}
79
80/// What overflows rather than being undefined, which is `-fwrapv` and its relatives.
81///
82/// Every licence the walk grants the optimizer about overflow is one flag on one instruction, and
83/// withdrawing a licence is not setting it. So this is read where the flags are chosen and nowhere
84/// else, and a unit built with either of these is a unit whose IR carries less rather than a unit
85/// the passes are told something extra about. That is also what makes it correct across link time
86/// optimization: a body from a unit that wraps and a body from one that does not keep their own
87/// answers when they end up in the same module.
88///
89/// `-ftrapv` is the exception and is the reason this is not simply two flags. It is the other
90/// answer to the question `-fwrapv` answers, and it is the only one of the three that asks for
91/// something to be generated rather than for something to be left out.
92#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
93pub struct Wrapping {
94    /// Whether signed arithmetic wraps, from `-fwrapv`. Set, and an add, a subtract, a multiply, a
95    /// shift and a negation in a signed type stop saying they do not wrap.
96    pub signed: bool,
97    /// Whether pointer arithmetic wraps, from `-fwrapv-pointer`. Set, and the multiply that turns
98    /// an index into a number of bytes stops saying so.
99    ///
100    /// That multiply is the whole of it here, because the addition itself never claimed anything: a
101    /// `ptradd` carries no flags in this IR and no pass reads one off it.
102    pub pointer: bool,
103    /// Whether a signed overflow stops the program, from `-ftrapv`. Set, and an add, a subtract, a
104    /// multiply and a negation in a signed type become calls to the routine in the runtime that
105    /// does the arithmetic and checks it.
106    ///
107    /// Never set at the same time as [`Wrapping::signed`], because a program cannot both wrap and
108    /// stop. The driver is what keeps that true.
109    pub trap: bool,
110}
111
112/// Everything the walk reads, which is a checked translation unit and the target it is for.
113///
114/// The interner is mutable because the walk invents names the program never wrote: the label a
115/// string literal is emitted under, and the mangled name of a function-scope `static`.
116pub struct Context<'a> {
117    /// The typed tree.
118    pub tast: &'a Tast,
119    /// The types it points into.
120    pub types: &'a Types,
121    /// What is being compiled for, which is where every width and every alignment comes from.
122    pub target: &'a TargetInfo,
123    /// The name table.
124    pub names: &'a mut Interner,
125    /// What a name that no declaration of it said anything about gets, which is `-fvisibility=`.
126    ///
127    /// A fact about the compilation rather than about any declaration, which is why it arrives
128    /// here rather than on the tree: the checker knows what was written and this knows what the
129    /// command line asked for, and the answer is the first of those where there is one.
130    pub visibility: IrVisibility,
131    /// Which functions get a stack protector, which is `-fstack-protector` and its relatives.
132    pub protector: Protector,
133    /// What overflows rather than being undefined, which is `-fwrapv` and its relatives.
134    ///
135    /// A fact about the compilation for the same reason the two above it are: what was written is
136    /// on the tree and what was asked for is on the command line.
137    pub wrapping: Wrapping,
138    /// Whether an access carries the node for the type it goes through, which is
139    /// `-fstrict-aliasing` and is on unless `-fno-strict-aliasing` cleared it.
140    ///
141    /// Clearing it here rather than in the optimizer is what makes the flag one condition in one
142    /// place: an access with no node conflicts with every other access, so a unit built with the
143    /// flag off is a unit whose IR says less rather than a unit the passes are told something
144    /// extra about. That is also what keeps it right across link time optimization, the way
145    /// [`Context::wrapping`] is: a body from a unit that named its types and a body from one that
146    /// did not keep their own answers when they end up in the same module.
147    pub aliasing: bool,
148    /// Whether an access says how far the padding after it reaches, which is
149    /// `-fsafety-init=nopadding` and is what a build with no safety tier gets too, since nothing
150    /// reads the number then.
151    ///
152    /// Here rather than in the safety pass for the reason [`Context::aliasing`] is here: what the
153    /// number is takes a record's layout, and the layout is a thing the walk has in hand and the
154    /// pass over the IR does not. The pass reads it and does not decide anything, which keeps the
155    /// flag one condition in one place and keeps it right across link time optimization.
156    pub padding: bool,
157    /// How far a multiply and an addition may be fused into one rounding, which is
158    /// `-ffp-contract=`.
159    ///
160    /// A fact about the compilation like the ones above it, and the one of them that is written
161    /// down rather than acted on: it goes onto every function with a body as
162    /// [`rucc_ir::Attrs::fp_contract`], because the place that would fuse anything is the code
163    /// generator and by the time it runs the command line is gone and the two operations it might
164    /// fuse may have come from different statements.
165    pub contract: FpContract,
166    /// What every function in the unit is aligned to unless it asked for more itself, which is
167    /// `-falign-functions` and is `None` for the alignment the target gives anyway.
168    ///
169    /// A fact about the compilation like the ones above it, and it meets a fact about a
170    /// declaration here rather than further down: `__attribute__((aligned(N)))` is a statement
171    /// about one function and this is a preference about all of them, so the function takes the
172    /// larger of the two and everything below reads one number.
173    pub align: Option<u32>,
174    /// Whether every function calls the two profiling hooks on the way in and on the way out,
175    /// which is `-finstrument-functions`.
176    ///
177    /// Done here rather than in a pass because gcc does it before it inlines anything, so a body
178    /// that is inlined takes its two calls with it and they still name the function they were
179    /// written for. A pass over the IR would see the body only after that had happened to it.
180    pub instrument: bool,
181    /// How a file named by a `.incbin` in an `asm` at file scope is read, given the name as the
182    /// template wrote it and handing back either the bytes or what went wrong.
183    ///
184    /// Passed in rather than reached for, because the walk has no business opening files and
185    /// because a caller that put its sources somewhere other than a disk has put this file there
186    /// too. The name is resolved the way an assembler resolves it, which is against the directory
187    /// the compiler was run in and not against the directory the source was found in.
188    pub read: &'a mut dyn FnMut(&str) -> Result<Vec<u8>, String>,
189}
190
191// Written out rather than derived because a closure has no `Debug`, and printing one would say
192// nothing anyway. What is worth reading here is the settings, so those are what this prints.
193impl fmt::Debug for Context<'_> {
194    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
195        f.debug_struct("Context")
196            .field("visibility", &self.visibility)
197            .field("protector", &self.protector)
198            .field("wrapping", &self.wrapping)
199            .field("aliasing", &self.aliasing)
200            .field("padding", &self.padding)
201            .field("contract", &self.contract)
202            .field("align", &self.align)
203            .field("instrument", &self.instrument)
204            .finish_non_exhaustive()
205    }
206}
207
208/// One function that runs without anything calling it, waiting for the section it goes in.
209///
210/// Held back rather than written where the definition is met, because the order they go in is not
211/// always the order the file defined them: a format with one section for all of them is a format
212/// where the only record of the priority is the position in that section, so they have to be
213/// sorted, and sorting means having all of them.
214#[derive(Debug, Clone, Copy)]
215struct Start {
216    /// The function the entry is the address of.
217    func: Symbol,
218    /// Whether it runs in the run-up to `main` rather than in the run-down after it.
219    before: bool,
220    /// Where in the order the attribute asked for it to go.
221    priority: Priority,
222    /// The definition it came from, for the diagnostic a format with no way to say it needs.
223    span: Span,
224}
225
226impl Start {
227    /// Where this goes among the others, which is the order the entries are written in.
228    ///
229    /// A lower number first, and the unnumbered ones after every numbered one, which is the order
230    /// an ELF linker puts the sections in and therefore the order every format has to come out in
231    /// for the three of them to agree. The sort is stable, so two at the same priority stay in the
232    /// order the file defined them, which is all that decides between them.
233    fn order(&self) -> (u8, u16) {
234        match self.priority {
235            Priority::Numbered(number) => (0, number),
236            Priority::Unnumbered => (1, 0),
237        }
238    }
239}
240
241/// What the walk produced.
242#[derive(Debug)]
243pub struct Lowered {
244    /// The module, which is complete even when something was reported: a construct that is not
245    /// supported yet leaves the rest of the function around it intact.
246    pub module: Module,
247    /// What was reported, in the order it was found.
248    pub diagnostics: Vec<Diagnostic>,
249}
250
251/// Walks a checked translation unit and builds the IR for it.
252///
253/// `name` is the module's name, which is the file the tree came from.
254#[must_use]
255pub fn lower(name: &str, cx: Context<'_>) -> Lowered {
256    let Context {
257        tast,
258        types,
259        target,
260        names,
261        visibility,
262        protector,
263        wrapping,
264        aliasing,
265        padding,
266        contract,
267        align,
268        instrument,
269        read,
270    } = cx;
271    let module = Module::new(names.intern(name), target);
272    let reachable = reach::reachable(reach::Decide::new(tast, types, target, names));
273    let mut unit = Unit {
274        tast,
275        types,
276        target,
277        names,
278        visibility,
279        protector,
280        wrapping,
281        aliasing,
282        padding,
283        cliques: 0,
284        tree: aliasing::Tree::default(),
285        contract,
286        align,
287        instrument,
288        read,
289        module,
290        diagnostics: Vec::new(),
291        strings: HashMap::new(),
292        anonymous: 0,
293        statics: HashMap::new(),
294        labels: HashMap::new(),
295        done: HashSet::new(),
296        aliases: Vec::new(),
297        sets: Vec::new(),
298        aliased: HashSet::new(),
299        starts: Vec::new(),
300        renamed: HashMap::new(),
301        reachable,
302    };
303    unit.run();
304    Lowered { module: unit.module, diagnostics: unit.diagnostics }
305}
306
307/// The walk over one translation unit, and everything it has built so far.
308pub(crate) struct Unit<'a> {
309    pub(crate) tast: &'a Tast,
310    pub(crate) types: &'a Types,
311    pub(crate) target: &'a TargetInfo,
312    pub(crate) names: &'a mut Interner,
313    /// What a name no declaration said anything about gets. See [`Context::visibility`].
314    visibility: IrVisibility,
315    /// Which functions get a stack protector. See [`Context::protector`].
316    pub(crate) protector: Protector,
317    /// What wraps rather than being undefined. See [`Context::wrapping`].
318    pub(crate) wrapping: Wrapping,
319    /// Whether an access names the type it goes through. See [`Context::aliasing`].
320    aliasing: bool,
321    /// Whether an access says how far the padding after it reaches. See [`Context::padding`].
322    pub(crate) padding: bool,
323    /// How many `restrict` scopes have been handed out, which is a number the whole module shares
324    /// so that no two functions promise different things with the same one. See
325    /// [`restrict`](mod@crate::restrict) for why that matters before there is an inliner.
326    pub(crate) cliques: u16,
327    /// The type based aliasing tree built so far, which is one per module.
328    tree: aliasing::Tree,
329    /// How far a multiply and an addition may be fused. See [`Context::contract`].
330    pub(crate) contract: FpContract,
331    /// What every function is aligned to unless it asked for more. See [`Context::align`].
332    align: Option<u32>,
333    /// Whether the profiling hooks are called. See [`Context::instrument`].
334    pub(crate) instrument: bool,
335    /// How a file a `.incbin` names is read. See [`Context::read`].
336    read: &'a mut dyn FnMut(&str) -> Result<Vec<u8>, String>,
337    pub(crate) module: Module,
338    pub(crate) diagnostics: Vec<Diagnostic>,
339    /// The global each string literal was emitted as, so that two mentions of one literal are
340    /// one object.
341    strings: HashMap<StrId, Symbol>,
342    /// How many runs of bytes written under no label in an `asm` at file scope have been given a
343    /// name, which is what keeps the next one from being given the same one.
344    anonymous: usize,
345    /// The name each object with no linkage was given.
346    statics: HashMap<DeclId, Symbol>,
347    /// The name each label an image holds the address of was given.
348    ///
349    /// A label is a place inside a function and has no name in the object file, because a jump to
350    /// one is a distance the assembler works out and never a symbol. An image is the one thing
351    /// that cannot do that: it is in another section, so what it holds is a relocation, and a
352    /// relocation names a symbol. So a label an image points at gets one, minted here because the
353    /// image is lowered before the body is walked and the block the label starts does not exist
354    /// yet when the name is first asked for.
355    labels: HashMap<LabelId, Symbol>,
356    /// What has been emitted, because a redeclaration is the same declaration seen twice.
357    done: HashSet<DeclId>,
358    /// The declarations that are a second name for something rather than a thing of their own,
359    /// in the order the file made them.
360    ///
361    /// Held back rather than emitted where they are met, because what an alias points at may be
362    /// written below it and whether anything defines it is a question only the whole file
363    /// answers.
364    aliases: Vec<DeclId>,
365    /// The names a `.set` in an `asm` at file scope gave to something else, with the block each
366    /// one was written in, in the order the file wrote them.
367    ///
368    /// Held back for the reason above and written out beside the aliases, since the two are the
369    /// same thing said two ways: a second symbol at an address this object already has.
370    sets: Vec<(directives::Set, Span)>,
371    /// The symbols something in the file is a second name for.
372    ///
373    /// A `static` function nothing calls is not emitted, and being what an alias points at is a
374    /// reason to emit one that no reference in the file says: the string an alias names is not a
375    /// use of anything as far as the walk over the tree is concerned.
376    aliased: HashSet<Symbol>,
377    /// The functions the file asked to have run without anything calling them, in the order it
378    /// defined them.
379    ///
380    /// Held back rather than emitted where they are met, because the entries go in the order the
381    /// priorities put them and a function written at the top of the file may have asked to run
382    /// last. Only the whole file settles that order.
383    starts: Vec<Start>,
384    /// The assembler name the file gave to a name with linkage, kept by the name that was
385    /// written rather than by the declaration that wrote it.
386    ///
387    /// For [`Unit::library_name`], which knows what the C library calls a function and not what
388    /// this file has said about it. The declaration that renames `memcpy` is a different
389    /// declaration from the implicit one the checker made for `__builtin_memcpy`, so the label
390    /// on the first is never reached from the second, and a program that renames a function and
391    /// then calls the builtin means the call to go to the new name.
392    renamed: HashMap<Symbol, Symbol>,
393    /// What something in the file reaches, which is what decides whether a function with
394    /// internal linkage is emitted at all.
395    reachable: HashSet<DeclId>,
396}
397
398// The debug is by hand and short: a translation unit is not something anybody wants printed as
399// a `{:?}`, and the module has a printer of its own for when they do.
400impl fmt::Debug for Unit<'_> {
401    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
402        f.debug_struct("Unit")
403            .field("module", &self.module.counts())
404            .field("diagnostics", &self.diagnostics.len())
405            .finish()
406    }
407}
408
409impl Unit<'_> {
410    /// The aliasing node an access through `ty` carries, and [`None`] when it carries none.
411    ///
412    /// [`None`] is also every answer under `-fno-strict-aliasing`, which is the whole of what that
413    /// flag does here. See [`aliasing`](mod@crate::aliasing) for which types have a node.
414    pub(crate) fn alias_node(&mut self, ty: TypeId) -> Option<Meta> {
415        if !self.aliasing {
416            return None;
417        }
418        self.tree.node(&mut self.module, self.names, self.types, ty)
419    }
420
421    /// The root of the aliasing tree, which is the node an access that may be punned carries.
422    ///
423    /// The root is `char` and it conflicts with everything, so an access carrying it is an access
424    /// nothing may be reordered across and, in the type plane, a byte nothing has settled the type
425    /// of. `crate::body` says which accesses those are.
426    pub(crate) fn alias_root(&mut self) -> Option<Meta> {
427        if !self.aliasing {
428            return None;
429        }
430        Some(self.tree.root(&mut self.module, self.names))
431    }
432
433    /// Every declaration the file made, in the order it made them.
434    fn run(&mut self) {
435        self.file_asms();
436        self.find_aliased();
437        self.find_renamed();
438        for index in 0..self.tast.top_level().len() {
439            let decl = self.tast.top_level()[index];
440            if !self.done.insert(decl) {
441                continue;
442            }
443            match self.tast[decl].kind {
444                DeclKind::Function => self.function(decl),
445                DeclKind::Object => self.object(decl),
446                // A name for a type is only in the tree at block scope and nothing is emitted
447                // for one.
448                DeclKind::Type => {}
449            }
450        }
451        for index in 0..self.aliases.len() {
452            self.alias(self.aliases[index]);
453        }
454        for index in 0..self.sets.len() {
455            let (set, span) = self.sets[index].clone();
456            self.equated(&set, span);
457        }
458        self.startups();
459    }
460
461    /// The `asm` written at file scope, read into the globals they define.
462    ///
463    /// Ahead of the declarations rather than among them. A block usually names more than one
464    /// thing and means them to be next to each other, the object writer lays globals out in the
465    /// order the module holds them, and adding a block's globals together is what makes them a
466    /// run. A declaration of one of those names below the block then finds a definition already
467    /// there and leaves it alone, which is the division the program wrote: the template says what
468    /// the bytes are and the C declaration says what they are to be read as.
469    fn file_asms(&mut self) {
470        for index in 0..self.tast.file_asms().len() {
471            let asm = self.tast.file_asms()[index];
472            let template = self.spelled(asm.template);
473            let read = match directives::assemble(&template, &mut *self.read) {
474                Ok(read) => read,
475                Err(directives::Failed::Unsupported(what)) => {
476                    self.unsupported(&format!("{what} in an `asm` at file scope"), asm.span);
477                    continue;
478                }
479                Err(directives::Failed::Missing(name, why)) => {
480                    let message = format!("cannot open '{name}' for reading: {why}");
481                    self.diagnostics.push(Diagnostic::error(message, asm.span).with_code("E0702"));
482                    continue;
483                }
484            };
485            // The name of every global of the block first, because a distance one of them writes
486            // is measured to a place in another of them and a relocation names a symbol, so the
487            // name has to be to hand before the bytes that refer to it are built.
488            let symbols: Vec<Symbol> = read
489                .pieces
490                .iter()
491                .map(|piece| match &piece.name {
492                    Some(name) => self.names.intern(name),
493                    None => {
494                        let name = format!(".Lasm.{}", self.anonymous);
495                        self.anonymous += 1;
496                        self.names.intern(&name)
497                    }
498                })
499                .collect();
500            for (index, piece) in read.pieces.into_iter().enumerate() {
501                self.piece(piece, symbols[index], &symbols);
502            }
503            // Held back until the file has been walked, because a name a block equates may be
504            // defined below the block, and remembered as a name something points at, because a
505            // `static` function an equate is the only reference to is one that has to be emitted.
506            for set in read.sets {
507                let target = self.names.intern(&set.target);
508                self.aliased.insert(target);
509                self.sets.push((set, asm.span));
510            }
511        }
512    }
513
514    /// One global an `asm` at file scope defined, under the name minted for it and with the names
515    /// of the whole block to hand.
516    ///
517    /// The bytes a template writes before it writes any label are a global like the rest and a
518    /// global has to have a name, so one is minted for them. Nothing refers to it by that name, so
519    /// the only thing it has to be is one nothing else takes, and the leading dot keeps it out of
520    /// the symbol table the way the name of a string literal does.
521    fn piece(&mut self, piece: directives::Piece, symbol: Symbol, symbols: &[Symbol]) {
522        let mut global = Global::new(symbol, piece.size, piece.align.max(1));
523        global.linkage = piece.linkage;
524        global.visibility = piece.visibility;
525        let bss = matches!(piece.section, directives::Section::Bss);
526        match piece.section {
527            // Which of the sections the object writer has an answer of its own for. Asking for
528            // `.rodata` by name would produce a second section with that spelling and with the
529            // flags of a writable one, so what is said here is what the global is instead.
530            directives::Section::ReadOnly => global.constant = true,
531            directives::Section::Data | directives::Section::Bss => {}
532            directives::Section::Named(name) => global.section = Some(self.names.intern(&name)),
533            // Refused where the template was read, since what goes in that section is
534            // instructions and there is nothing here that makes one.
535            directives::Section::Text => return,
536        }
537        let mut data = Vec::with_capacity(piece.items.len());
538        if piece.items.is_empty() && bss {
539            // A label at the end of the zero filled section, which has nothing under it and
540            // still has to land there rather than in the section of written bytes. An image of
541            // no zeros is what says so, since being all zeros is how a global asks for that
542            // section and an empty image asks for nothing.
543            data.push(Datum::Zero(0));
544        }
545        for item in piece.items {
546            data.push(match item {
547                directives::Item::Bytes(bytes) => Datum::Bytes(self.module.push_bytes(&bytes)),
548                directives::Item::Int { width, value } => {
549                    let ty = Type::int(u32::from(width) * 8);
550                    Datum::Scalar {
551                        ty,
552                        value: self.module.add_imm(Imm::int(i128::from(value), ty)),
553                    }
554                }
555                directives::Item::Zero(bytes) => Datum::Zero(bytes),
556                // Four bytes holding how far that global is from these bytes, which the reader
557                // said in globals of this block rather than in names because the place it
558                // measures to is usually a label the object file holds no name for.
559                directives::Item::Away { piece, addend } => {
560                    let reloc = Reloc { symbol: symbols[piece], addend, size: 4 };
561                    Datum::Away(self.module.add_reloc(reloc))
562                }
563            });
564        }
565        global.init = Some(self.module.push_data(&data));
566        self.place_global(global);
567    }
568
569    /// Which symbols the file gives a second name to, before anything is emitted.
570    ///
571    /// Ahead of the walk rather than during it, because a `static` function is emitted or not on
572    /// the strength of what reaches it and the alias that reaches one may be written below it.
573    fn find_aliased(&mut self) {
574        for index in 0..self.tast.top_level().len() {
575            let decl = self.tast.top_level()[index];
576            let Some(target) = self.tast[decl].alias else { continue };
577            let spelling = self.spelled(target);
578            let symbol = self.names.intern(&spelling);
579            self.aliased.insert(symbol);
580        }
581    }
582
583    /// Which names the file gave an assembler name of their own, before anything is emitted.
584    ///
585    /// Ahead of the walk for the reason [`Unit::find_aliased`] is: the call to
586    /// `__builtin_memcpy` may be written above the declaration of `memcpy` that renames it, and
587    /// the two spellings are one function.
588    fn find_renamed(&mut self) {
589        for index in 0..self.tast.top_level().len() {
590            let decl = self.tast.top_level()[index];
591            let node = &self.tast[decl];
592            let (linkage, name, label) = (node.linkage, node.name, node.asm_label);
593            if linkage == Linkage::None {
594                continue;
595            }
596            let (Some(name), Some(label)) = (name, label) else { continue };
597            let spelling = self.spelled(label);
598            let symbol = self.names.intern(&spelling);
599            self.renamed.insert(name, symbol);
600        }
601    }
602
603    /// The bytes of a string literal as a name, which is what a symbol in an attribute is.
604    fn spelled(&self, id: StrId) -> String {
605        self.tast[id].elements.iter().filter_map(|&unit| char::from_u32(unit)).collect()
606    }
607
608    /// One object with static storage duration.
609    fn object(&mut self, decl: DeclId) {
610        let tast = self.tast;
611        let node = &tast[decl];
612        let (ty, state, init) = (node.ty, node.state, node.init);
613        let (linkage, duration, alignment) = (node.linkage, node.duration, node.alignment);
614        let span = tast.decl_span(decl);
615        if duration == StorageDuration::Automatic {
616            // A block-scope object with automatic storage is a slot or a value in the function
617            // that declares it, and the body is what makes it. Nothing is emitted here.
618            return;
619        }
620        // A second name for something else is not an object of its own, so nothing is laid out
621        // and no image is built. It is held back until the rest of the file has been walked,
622        // because what it points at may be below it.
623        if node.alias.is_some() {
624            self.aliases.push(decl);
625            return;
626        }
627
628        let symbol = self.symbol_of(decl);
629        let size = repr::size_of(self.types, self.target, ty);
630        let align = alignment.unwrap_or_else(|| repr::align_of(self.types, self.target, ty));
631        let mut global = Global::new(symbol, size, align);
632        global.linkage = self.told(decl, linkage);
633        // A tentative definition counts as one, because it is one: `int x;` at file scope puts a
634        // symbol in this object and the linker never has to look anywhere else for it.
635        global.visibility = self.seen(decl, state != Definition::Declared);
636        global.tls = (duration == StorageDuration::Thread).then_some(TlsModel::GlobalDynamic);
637        global.constant = repr::is_read_only(self.types, ty);
638        global.init = match state {
639            // `extern int x;` and nothing else names an object another translation unit
640            // defines. The global is here so that a reference to it has something to resolve
641            // against, and it has no image, which is what makes it a declaration.
642            Definition::Declared => None,
643            Definition::Tentative => Some(self.zeros(size)),
644            Definition::Defined => {
645                let (data, covered) = self.image(init, size, span);
646                // The object is as large as its image when the image is the larger of the two.
647                // A structure whose last member is a flexible array is the only way that
648                // happens: `sizeof` answers without the array and an initializer that fills it
649                // makes an object big enough to hold what was written. C 6.7.2.1p18 leaves the
650                // size to the implementation, gcc grows the object, and this does the same
651                // rather than hand the linker a size the image does not fit in.
652                global.size = size.max(covered);
653                Some(data)
654            }
655        };
656        self.place_global(global);
657    }
658
659    /// One function, with its body when it has one.
660    fn function(&mut self, decl: DeclId) {
661        let tast = self.tast;
662        let node = &tast[decl];
663        let (ty, linkage, body, align) = (node.ty, node.linkage, node.body, node.alignment);
664        let noreturn = node.flags.contains(DeclFlags::NORETURN);
665        let naked = node.flags.contains(DeclFlags::NAKED);
666        let effects = node.effects;
667        let startup = node.startup;
668        let span = tast.decl_span(decl);
669        if node.name.is_none() {
670            return;
671        }
672        // The same as for an object: a second name is not a function of its own, and it is held
673        // back until what it points at has been emitted.
674        if node.alias.is_some() {
675            self.aliases.push(decl);
676            return;
677        }
678        // Which asks the one question the reference to it asks, so that a declaration that
679        // renamed the symbol renames the definition as well and the two still meet.
680        let name = self.symbol_of(decl);
681        if self.is_dropped(decl, name) {
682            return;
683        }
684        let Some(plan) = self.plan(ty, &[], span) else { return };
685
686        let mut func = Func::new(name, plan.signature.clone());
687        // The name the source spelled, where an assembler name says the symbol is not it. A
688        // declaration of `strstr` renamed to `my_strstr` is a declaration of `strstr` still, and
689        // once the symbol is the only name left there is nothing to find that out again from.
690        if node.asm_label.is_some() {
691            func.spelled = node.name.filter(|&spelled| spelled != name);
692        }
693        // Where the body begins, which is the line a debugger names over the prologue. gcc says the
694        // line the opening brace is on rather than the line the declarator is on, and the two
695        // differ in the style that puts the brace underneath. No instruction in a prologue has a
696        // span of its own, so this is the only place the fact can come from. A declaration has no
697        // body and produces no prologue, so it falls back to the declarator and nothing reads it.
698        func.declared = body.map_or(span, |body| tast.stmt_span(body));
699        // The larger of what this function asked for and what the command line asked of all of
700        // them, since the attribute is a requirement and the flag is a preference, and a
701        // preference does not get to move a function off a boundary its own source named.
702        func.align = match (align, self.align) {
703            (Some(mine), Some(everyones)) => Some(mine.max(everyones)),
704            (mine, everyones) => mine.or(everyones),
705        };
706        // The one thing a declaration says that nobody downstream can work out for themselves.
707        // What `abort` does belongs to `abort`, and a translation unit that only declares it has
708        // nothing to look at, so the claim has to travel on the declaration or not at all.
709        if noreturn {
710            func.attrs.set |= AttrSet::NORETURN;
711        }
712        // Which is not a claim about what a call to it does but a fact about how the function
713        // itself is written, so unlike the two around it there is nothing here for a declaration
714        // alone to be useful for. It travels the same way because the attribute is written in the
715        // same places. See [`rucc_codegen`] for what reads it, which is the frame.
716        if naked {
717            func.attrs.set |= AttrSet::NAKED;
718        }
719        // And the other one, for the same reason. What a call to `strtol` reads belongs to
720        // `strtol`, and the purity analysis answers opaque for everything it cannot see a body
721        // for, so a unit that only declares the function gets nothing out of it unless the
722        // promise arrives here. `const` says the result comes from the arguments alone, which
723        // is `readnone`, and `pure` says it may read memory, which is `readonly`. The two are
724        // an incompatible pair in the IR and only one of them is ever set.
725        func.attrs.set |= match effects {
726            Effects::Any => AttrSet::NONE,
727            Effects::Pure => AttrSet::READONLY,
728            Effects::Const => AttrSet::READNONE,
729        };
730        // Whether to inline it, which `rucc_opt::inline` reads for `always_inline` at every level
731        // and for a plain `inline` from `-O1` up. The IR will not have both of the first two, so a
732        // name that said both gets the one gcc keeps, which is `always_inline` after a warning that
733        // the other was ignored, and either of them says more than the keyword does.
734        if node.flags.contains(DeclFlags::ALWAYS_INLINE) {
735            func.attrs.set |= AttrSet::ALWAYS_INLINE;
736        } else if node.flags.contains(DeclFlags::NOINLINE) {
737            func.attrs.set |= AttrSet::NOINLINE;
738        } else if node.flags.contains(DeclFlags::DECLARED_INLINE) {
739            func.attrs.set |= AttrSet::INLINE_HINT;
740        }
741        // An inline definition this unit calls, which this unit puts a copy of out of line for
742        // every call the inliner leaves alone. See [`Self::out_of_line`].
743        let copied = body.is_some() && self.out_of_line(decl, node.inline);
744        func.linkage = if copied { IrLinkage::LinkOnce } else { self.told(decl, linkage) };
745        // The same question as for an object, and the same answer, with one wrinkle: an inline
746        // definition this unit neither emits nor calls is a declaration here, since C 6.7.4p7
747        // sends the calls to whatever unit holds the external definition, so it is not this
748        // file's to describe. That is the condition the body is lowered under, a few lines below.
749        func.visibility = self.seen(decl, body.is_some() && (node.inline.emits() || copied));
750        // An inline definition is not an external definition, so what goes in the module is the
751        // declaration and not the body. C 6.7.4p7 says the calls in this unit go to the definition
752        // some other unit holds, which is what the declaration gives them, and glibc's headers
753        // rely on it: every one of their inline definitions would otherwise be a second definition
754        // of a name the library already defines. Unless this unit is one of the callers, which is
755        // the case [`Self::out_of_line`] is about.
756        if body.is_some() && (node.inline.emits() || copied) {
757            // `optimize ("no-strict-aliasing")` on the function, which has to be kept in the IR
758            // rather than on the command line because the inliner may copy this body into a
759            // function that is under the rule.
760            let strict = self.aliasing;
761            self.aliasing &= !node.flags.contains(DeclFlags::NO_STRICT_ALIASING);
762            body::lower(self, decl, &mut func, &plan);
763            self.aliasing = strict;
764            // Only for a definition, because an entry is an address and a declaration of something
765            // another file defines has none to put there. gcc reads the attribute off whichever
766            // declaration carried it and then waits for the definition in the same way, which is
767            // why writing `__attribute__((constructor)) void f(void);` in a header costs every
768            // file that includes it nothing.
769            if let Some(priority) = startup.before {
770                self.starts.push(Start { func: name, before: true, priority, span });
771            }
772            if let Some(priority) = startup.after {
773                self.starts.push(Start { func: name, before: false, priority, span });
774            }
775        }
776        self.place_func(func);
777    }
778
779    /// Puts a function in the module under a name something may already be under.
780    ///
781    /// Two declarations of one identifier were merged before this, so the only way one name
782    /// arrives twice is an assembler name that renames one identifier onto another: a
783    /// declaration of `f` renamed to `g` beside a definition of `g` is one symbol written two
784    /// ways, which is what the program asked for and what the linker is going to see. The
785    /// definition wins wherever there is one, since what the declaration is here for is to give
786    /// the calls something to resolve against and the definition does that as well.
787    ///
788    /// A name already carrying a definition keeps it. That is the program defining one symbol
789    /// twice, and the assembler says so with the name in front of it, which is a better message
790    /// than anything available here.
791    fn place_func(&mut self, func: Func) {
792        match self.module.lookup(func.name) {
793            None => {
794                self.module.add_func(func);
795            }
796            Some(SymbolRef::Func(id))
797                if self.module[id].is_declaration() && !func.is_declaration() =>
798            {
799                self.module[id] = func;
800            }
801            Some(_) => {}
802        }
803    }
804
805    /// One declaration that is a second name for something the same file defines.
806    ///
807    /// Emitted after everything else, so the target is looked up in a module that already holds
808    /// whatever the file defines whether it was written above the alias or below it.
809    ///
810    /// The target has to be defined here and not merely declared, which is gcc's rule and is
811    /// what the object format can express: an alias is a symbol at another symbol's address, and
812    /// a name this file does not define has no address for one to be at. A program that writes
813    /// an alias of something in another object wants a reference rather than a definition, and
814    /// what it gets from gcc is this same error rather than a name the linker cannot resolve.
815    fn alias(&mut self, decl: DeclId) {
816        let Some(written) = self.tast[decl].alias else { return };
817        let span = self.tast.decl_span(decl);
818        let name = self.symbol_of(decl);
819        let spelling = self.spelled(written);
820        let target = self.names.intern(&spelling);
821        if self.no_address(name, target, span) {
822            return;
823        }
824        // Something already under this name, which is the program defining one symbol twice. The
825        // definition that is there stands, the way it does for a function and for an object.
826        if self.module.lookup(name).is_some() {
827            return;
828        }
829        let mut alias = Alias::new(name, target);
830        alias.linkage = self.told(decl, self.tast[decl].linkage);
831        // Its own answer, because the attribute is written on the alias and an alias is a symbol
832        // of its own. `weak, alias, visibility("hidden")` is a name a library keeps to itself
833        // while the thing it points at stays exported, which is how glibc writes half of them.
834        // Always a definition. An alias is a symbol this object puts at an address in this object,
835        // and one whose target is merely declared was refused a few lines above.
836        alias.visibility = self.seen(decl, true);
837        self.module.add_alias(alias);
838    }
839
840    /// One name a `.set` in an `asm` at file scope gave to something else.
841    ///
842    /// The same thing as the alias above it and written out the same way, with the two answers
843    /// about the name coming from the directives around the `.set` rather than from an attribute:
844    /// `.globl` and `.weak` say how the linker sees it, `.hidden` and `.protected` say how far it
845    /// reaches, and a name no directive spoke about is local, which is what an assembler does with
846    /// one. A name the file also defines keeps its own definition, which is the rule everything
847    /// else here follows and is what gcc's output shows for a `.set` written above a definition of
848    /// the same name.
849    fn equated(&mut self, set: &directives::Set, span: Span) {
850        let name = self.names.intern(&set.name);
851        let target = self.names.intern(&set.target);
852        if self.no_address(name, target, span) {
853            return;
854        }
855        // A name the file only declared is one the `.set` gives an address to, and tcc's test
856        // calls a function declared `extern` in C and defined by `.set` in a file-scope `asm`.
857        let declared = match self.module.lookup(name) {
858            None => true,
859            Some(SymbolRef::Func(id)) => self.module[id].is_declaration(),
860            Some(SymbolRef::Global(id)) => self.module[id].is_declaration(),
861            Some(SymbolRef::Alias(_)) => false,
862        };
863        if !declared {
864            return;
865        }
866        let mut alias = Alias::new(name, target);
867        alias.linkage = set.linkage;
868        alias.visibility = set.visibility;
869        self.module.add_alias_over(alias);
870    }
871
872    /// Whether there is no address for a second name to be at, reporting why when there is not.
873    ///
874    /// The target has to be defined here and not merely declared, because an alias is a symbol at
875    /// another symbol's address and a name this file does not define has no address in it. A
876    /// program that writes one of these about something in another object wants a reference rather
877    /// than a definition, and gcc turns that down as well.
878    fn no_address(&mut self, name: Symbol, target: Symbol, span: Span) -> bool {
879        let spelled = self.names.resolve(name).to_owned();
880        if name == target {
881            let what = format!("'{spelled}' is aliased to itself");
882            self.diagnostics.push(Diagnostic::error(what, span).with_code("E0697"));
883            return true;
884        }
885        let defined = match self.module.lookup(target) {
886            Some(SymbolRef::Func(id)) => !self.module[id].is_declaration(),
887            Some(SymbolRef::Global(id)) => self.module[id].init.is_some(),
888            // A chain of them is a thing gcc takes and this does not yet, because resolving one
889            // wants the aliases put in an order that the file they were written in need not be
890            // in. It is reported rather than written out as a name pointing at a name.
891            Some(SymbolRef::Alias(_)) | None => false,
892        };
893        if !defined {
894            let spelling = self.names.resolve(target).to_owned();
895            let what = format!("'{spelled}' is aliased to undefined symbol '{spelling}'");
896            let note = "the target of an alias has to be defined in this same file, since an \
897                        alias is a second name for an address and not a reference to one";
898            let refused = Diagnostic::error(what, span).with_code("E0697");
899            self.diagnostics.push(refused.note(note, span));
900            return true;
901        }
902        false
903    }
904
905    /// The list of functions to run around `main`, written out as the entries that run them.
906    ///
907    /// In priority order rather than in the order the file defined them, because two of the three
908    /// formats get their order from the order the entries are in and only ELF sorts anything at
909    /// link time.
910    fn startups(&mut self) {
911        let mut starts = std::mem::take(&mut self.starts);
912        starts.sort_by_key(Start::order);
913        for start in starts {
914            self.start_entry(&start);
915        }
916    }
917
918    /// One entry, which is a pointer wide object in the section the format runs.
919    ///
920    /// A relocation against the function rather than a value, since the address is not known until
921    /// the link. The object has internal linkage and a name nothing refers to: the only thing that
922    /// reads it is the CRT walking the section, which finds it by where it is and not by what it is
923    /// called. gcc emits no symbol at all for one, and a name with a dot in it is the nearest thing
924    /// to that here, being one no C program can write and therefore one no program collides with.
925    fn start_entry(&mut self, start: &Start) {
926        let Some(section) = self.start_section(start) else {
927            self.no_start(start);
928            return;
929        };
930        let size = u64::from(self.target.pointer_width / 8);
931        let align = u32::try_from(size).unwrap_or(1);
932        let called = self.names.resolve(start.func).to_owned();
933        let which = if start.before { "ctor" } else { "dtor" };
934        let name = self.names.intern(&format!("__rucc_{which}.{called}"));
935        let section = self.names.intern(&section);
936        let mut global = Global::new(name, size, align);
937        global.linkage = IrLinkage::Internal;
938        global.section = Some(section);
939        let size = u32::try_from(size).unwrap_or(0);
940        let reloc = self.module.add_reloc(Reloc { symbol: start.func, addend: 0, size });
941        global.init = Some(self.module.push_data(&[Datum::Addr(reloc)]));
942        self.place_global(global);
943    }
944
945    /// The section an entry goes in, and [`None`] for a format with no way to ask for one.
946    ///
947    /// ELF has both halves and the linker sorts the numbered sections ahead of the plain one, so
948    /// the number goes in the name and the order comes out right however the files were linked.
949    ///
950    /// COFF has the run-up only. The name is sorted by what follows the `$` and the CRT walks
951    /// everything between the `.CRT$XCA` and `.CRT$XCZ` markers, so a numbered entry goes just
952    /// after the first marker and an unnumbered one at `U`, which keeps the numbered ones first.
953    ///
954    /// Mach-O has the run-up only as well, and it has no sorting at all: the entries run in the
955    /// order the section holds them, which is the order [`Self::startups`] put them in.
956    fn start_section(&self, start: &Start) -> Option<String> {
957        match self.target.object_format {
958            ObjectFormat::Elf => {
959                let base = if start.before { ".init_array" } else { ".fini_array" };
960                Some(match start.priority {
961                    Priority::Numbered(number) => format!("{base}.{number:05}"),
962                    Priority::Unnumbered => base.to_owned(),
963                })
964            }
965            ObjectFormat::Coff if start.before => Some(match start.priority {
966                Priority::Numbered(number) => format!(".CRT$XCA{number:05}"),
967                Priority::Unnumbered => ".CRT$XCU".to_owned(),
968            }),
969            ObjectFormat::MachO if start.before => {
970                Some("__DATA,__mod_init_func,mod_init_funcs".to_owned())
971            }
972            ObjectFormat::Coff | ObjectFormat::MachO | ObjectFormat::Wasm => None,
973        }
974    }
975
976    /// Reports an attribute this format has nowhere to put.
977    ///
978    /// Refused rather than dropped, because the whole point of the attribute is that something
979    /// else calls the function and a program that quietly does not get its call has no way of
980    /// noticing until whatever the function set up is missing.
981    ///
982    /// The run-down is what is missing on the two formats that have a run-up. Mach-O used to have
983    /// a terminator list and dyld stopped running it, so clang registers the call with
984    /// `__cxa_atexit` from a constructor it writes for the purpose, and nothing in the CRT a COFF
985    /// target links against has been confirmed to walk one either. Doing the same here is a
986    /// feature rather than a section name, which is why this is a message and not a branch above.
987    fn no_start(&mut self, start: &Start) {
988        let which = if start.before { "constructor" } else { "destructor" };
989        let format = self.target.object_format.as_str();
990        let what = format!("the '{which}' attribute on a {format} target");
991        self.unsupported(&what, start.span);
992    }
993
994    /// How far a name reaches outside a shared library, which is what a declaration of it said
995    /// where one said anything and what the command line asked for where none did.
996    ///
997    /// gcc's `-fvisibility=` is written as the default rather than as an override, so the
998    /// attribute wins wherever it was written, and that is the whole reason a library compiled
999    /// with `-fvisibility=hidden` can still export the dozen names it means to export.
1000    ///
1001    /// The default reaches what this unit defines and stops there, which is the `defined`
1002    /// argument and is the whole of tamnd/rucc#1234. `-fvisibility=hidden` is a claim about the
1003    /// names this file puts into the library, and a name it only mentions is one it knows nothing
1004    /// about: `stderr` is in libc however the file that reads it was compiled, and calling it
1005    /// hidden tells the linker to resolve it inside this object, which it cannot do. The attribute
1006    /// on a declaration is a different thing and still counts, because a program that writes it
1007    /// has said where the definition is going to come from.
1008    ///
1009    /// Measured against gcc 16.2.0 rather than read off the manual, since the manual says the flag
1010    /// applies to declarations and does not say which ones. For `extern int plain;` beside
1011    /// `__attribute__((visibility("hidden"))) extern int marked;` at `-fPIC -fvisibility=hidden`,
1012    /// gcc writes `plain` as `GLOBAL DEFAULT UND` and reaches it through the global offset table,
1013    /// and writes `marked` as `GLOBAL HIDDEN UND` and reaches it from the instruction pointer.
1014    fn seen(&self, decl: DeclId, defined: bool) -> IrVisibility {
1015        match self.tast[decl].visibility {
1016            Some(Visibility::Default) => IrVisibility::Default,
1017            Some(Visibility::Hidden) => IrVisibility::Hidden,
1018            Some(Visibility::Protected) => IrVisibility::Protected,
1019            None if defined => self.visibility,
1020            None => IrVisibility::Default,
1021        }
1022    }
1023
1024    /// What the linker is told about a name, which is its C linkage unless a declaration of it
1025    /// wrote `weak`.
1026    ///
1027    /// The attribute is refused on internal linkage where it is read, so external is the only
1028    /// thing it can change, and the two things a program means by it are one thing to the linker.
1029    /// On a definition it says another object's definition of the name beats this one, which is
1030    /// how a library ships a default. On a reference to something this file does not define it
1031    /// says the link may leave the name undefined and hand the reference a zero address, which is
1032    /// how a library offers a hook and why zstd's thirty files link at all.
1033    fn told(&self, decl: DeclId, linkage: Linkage) -> IrLinkage {
1034        match linkage {
1035            Linkage::External if self.tast[decl].flags.contains(DeclFlags::WEAK) => IrLinkage::Weak,
1036            Linkage::External => IrLinkage::External,
1037            Linkage::Internal | Linkage::None => IrLinkage::Internal,
1038        }
1039    }
1040
1041    /// Whether a body this unit is not meant to emit has to be emitted anyway, because this unit
1042    /// calls it and has nothing else to send the call to.
1043    ///
1044    /// C 6.7.4p7 says an inline definition is not an external definition, and the bargain it
1045    /// offers is that the call is replaced by the body, so nobody ever has to resolve the name.
1046    /// A compiler that inlines keeps its end of it. This one inlines only a function marked
1047    /// `always_inline`, so any other call left standing is a call to a name no object file
1048    /// defines, and the program fails at the link on a function it can see the body of. micropython is a program that does exactly that:
1049    /// `py/misc.h` writes `MP_COMPRESSED_ROM_TEXT` as `inline __attribute__((always_inline))`,
1050    /// nothing anywhere defines it out of line, and every file that reports an error calls it.
1051    ///
1052    /// So a copy goes out of line, under [`IrLinkage::LinkOnce`]. Every unit that calls one emits
1053    /// its own copy of the same body, the linker keeps one and the rest are discarded, and a unit
1054    /// that holds the real external definition beats all of them because a strong definition
1055    /// beats a weak one. What that costs is object size in the units that call one. What it buys
1056    /// is that the address of the function is the same everywhere and that the program links,
1057    /// which is the whole of what the program was asking for.
1058    ///
1059    /// Only when this unit names it, which is why [`reach`] stopped treating one of these as a
1060    /// root. An unreferenced inline definition is still emitted as nothing at all, which is what
1061    /// keeps a file that includes `stdio.h` from carrying its own `vprintf`, `putchar`, `getchar`
1062    /// and the dozen more glibc writes beside them.
1063    fn out_of_line(&self, decl: DeclId, emission: Emission) -> bool {
1064        !emission.emits() && self.reachable.contains(&decl)
1065    }
1066
1067    /// The same for an object, where a global with no image is the declaration.
1068    fn place_global(&mut self, global: Global) {
1069        match self.module.lookup(global.name) {
1070            None => {
1071                self.module.add_global(global);
1072            }
1073            Some(SymbolRef::Global(id))
1074                if self.module[id].init.is_none() && global.init.is_some() =>
1075            {
1076                self.module[id] = global;
1077            }
1078            Some(_) => {}
1079        }
1080    }
1081
1082    /// Whether this function is one nothing can call, which is the set that is not emitted.
1083    ///
1084    /// A name with internal linkage is not visible to another translation unit, so a definition
1085    /// of one that nothing here refers to is a definition of something that can never run.
1086    /// [`reach`](mod@crate::reach) is what worked out which those are, and an attribute that asks
1087    /// for the definition to be kept has already been read into the answer.
1088    ///
1089    /// A second name for it is the one reason to keep it that the walk over the tree cannot see,
1090    /// since what an alias points at is a string and not a reference to anything. So the symbol
1091    /// is what is asked about here rather than the declaration: an alias names what the linker
1092    /// will look for, which is what a declaration that renamed itself with `__asm__` is under.
1093    ///
1094    /// Nothing is said about it. gcc has `-Wunused-function` for a `static` function nobody
1095    /// wrote a call to, which is a warning about the program, and this is not that: the header
1096    /// that defines six of them is not the file being compiled and its author is not the person
1097    /// reading the output.
1098    fn is_dropped(&self, decl: DeclId, symbol: Symbol) -> bool {
1099        self.tast[decl].linkage != Linkage::External
1100            && !self.reachable.contains(&decl)
1101            && !self.aliased.contains(&symbol)
1102    }
1103
1104    /// How everything a call to this function type hands over travels, and [`None`] for one the
1105    /// walk cannot make.
1106    ///
1107    /// `actual` is the types of the arguments at a call site, which matter only past the end of
1108    /// the prototype: what a variadic argument does is decided from what was written there, and
1109    /// there is no parameter to decide it from. A definition passes nothing for it.
1110    pub(crate) fn plan(&mut self, ty: TypeId, actual: &[TypeId], span: Span) -> Option<Plan> {
1111        self.plan_with(ty, actual, false, span)
1112    }
1113
1114    /// The same, as the call site sees it rather than as the function does.
1115    ///
1116    /// The two differ for a type that is not a prototype. An old style definition is the one of
1117    /// those that knows what its parameters are, and 6.5.2.2p6 checks a call against a prototype
1118    /// and against nothing at all otherwise, so a parameter it disagrees with does not make the
1119    /// call wrong and cannot be what the argument travels as either: the value at the call is
1120    /// the argument's own type and nothing converted it. So a parameter the argument facing it
1121    /// is compatible with is used, which is the usual case and is what makes the call go to the
1122    /// name, and one it is not compatible with gives way to what was actually written. A call
1123    /// like that is undefined behaviour if control reaches it and the file still has to
1124    /// translate, which is the same position [`Body::direct`](crate::body) already takes.
1125    pub(crate) fn call_plan(&mut self, ty: TypeId, actual: &[TypeId], span: Span) -> Option<Plan> {
1126        self.plan_with(ty, actual, true, span)
1127    }
1128
1129    fn plan_with(
1130        &mut self,
1131        ty: TypeId,
1132        actual: &[TypeId],
1133        at_call: bool,
1134        span: Span,
1135    ) -> Option<Plan> {
1136        let canonical = self.types.canonical(ty);
1137        let canonical = match self.types.kind(canonical) {
1138            // A call goes through a pointer to a function, and the type in hand may be either.
1139            TypeKind::Pointer(pointee) => self.types.canonical(pointee),
1140            _ => canonical,
1141        };
1142        let TypeKind::Function(id) = self.types.kind(canonical) else {
1143            self.unsupported("a call through something that is not a function", span);
1144            return None;
1145        };
1146        let signature = self.types.signature(id);
1147        let ret = signature.ret;
1148        // A function declared without a prototype takes what it is given, which is what a
1149        // signature with no parameters and no end to them says. C23 removed these and this is
1150        // what `int f();` means in every dialect before it.
1151        let variadic = signature.variadic || !signature.prototyped;
1152        let params = if at_call && !signature.prototyped {
1153            // An argument past the end of the list has no parameter to travel as, which is what
1154            // a call to an unprototyped function with more arguments than the definition takes
1155            // is, so the list ends where the arguments do.
1156            signature
1157                .params
1158                .iter()
1159                .zip(actual)
1160                .map(|(&param, &arg)| if compatible(self.types, param, arg) { param } else { arg })
1161                .collect()
1162        } else {
1163            signature.params.clone()
1164        };
1165
1166        match abi::plan(self.types, self.target, ret, &params, actual, variadic) {
1167            Ok(plan) => Some(plan),
1168            Err(what) => {
1169                self.unsupported(what, span);
1170                None
1171            }
1172        }
1173    }
1174
1175    /// The image of an initializer: the entries in ascending order, with the gaps zeroed, and
1176    /// how many bytes it covers.
1177    ///
1178    /// The count is the size that was asked for except when a flexible array member was given
1179    /// something to hold, which is the one case where an image is larger than the type it is an
1180    /// image of.
1181    pub(crate) fn image(
1182        &mut self,
1183        init: Option<InitList>,
1184        size: u64,
1185        span: Span,
1186    ) -> (DataList, u64) {
1187        let Some(init) = init else { return (self.zeros(size), size) };
1188        let (data, at) = self.pieces(init, size, span);
1189        (self.module.push_data(&data), at)
1190    }
1191
1192    /// The data an image is made of, before it becomes a [`DataList`].
1193    ///
1194    /// This is apart from [`Self::image`] so that an image can be built inside another one,
1195    /// which is what a compound literal used as a value in an initializer needs.
1196    fn pieces(&mut self, init: InitList, size: u64, span: Span) -> (Vec<Datum>, u64) {
1197        let entries = self.in_image_order(&self.tast[init]);
1198        let mut packed = self.packed(&entries, size);
1199        let mut data: Vec<Datum> = Vec::with_capacity(entries.len());
1200        let mut at = 0;
1201        for entry in entries {
1202            let piece = self.entry(entry, &mut packed, size);
1203            if piece.is_empty() {
1204                continue;
1205            }
1206            let covered: u64 = piece.iter().map(|datum| datum.size(&self.module)).sum();
1207            match entry.offset.cmp(&at) {
1208                Ordering::Greater => data.push(Datum::Zero(entry.offset - at)),
1209                // An entry that begins inside the one before it, which is neither the same
1210                // place nor a later one. A union whose members are initialized through two
1211                // designators is the way to write it. The earlier bytes are already in the
1212                // list and the image cannot take them out again, so this is refused, and
1213                // nothing here is wrong enough to drop the rest of the image.
1214                Ordering::Less => {
1215                    self.unsupported("an initializer that writes over an earlier one", span);
1216                    continue;
1217                }
1218                Ordering::Equal => {}
1219            }
1220            at = entry.offset + covered;
1221            data.extend(piece);
1222        }
1223        if at < size {
1224            // The tail of a partly initialized object, which C says is zero. So is the tail of
1225            // an array the initializer did not fill, and so is every byte of padding.
1226            data.push(Datum::Zero(size - at));
1227            at = size;
1228        }
1229        (data, at)
1230    }
1231
1232    /// The entries an image is written from, which is not the order they were written in.
1233    ///
1234    /// A designator names a place, and the places may be named in any order at all:
1235    /// `{ .b = 2, .a = 1 }` is the same object as `{ .a = 1, .b = 2 }` and C says so in as many
1236    /// words. An image is bytes in ascending order, so the entries are put in that order here.
1237    /// The sort is stable, which is what makes the rest of the rule work: naming one place
1238    /// twice is legal and the last of them is the one that stands, so among the entries at one
1239    /// offset the written order is kept and all but the last are dropped.
1240    ///
1241    /// A bit-field is never dropped, because several of them share one offset without writing
1242    /// over anything. Which bytes they came to is settled by [`Self::packed`] before this runs
1243    /// and the whole run goes in under the first entry that has a bit in it.
1244    fn in_image_order(&self, entries: &[InitEntry]) -> Vec<InitEntry> {
1245        let mut sorted = entries.to_vec();
1246        sorted.sort_by_key(|entry| entry.offset);
1247        let mut kept: Vec<InitEntry> = Vec::with_capacity(sorted.len());
1248        for entry in sorted {
1249            if !entry.is_bit_field() {
1250                let over = |last: &InitEntry| last.offset == entry.offset && !last.is_bit_field();
1251                while kept.last().is_some_and(over) {
1252                    kept.pop();
1253                }
1254            }
1255            kept.push(entry);
1256        }
1257        kept
1258    }
1259
1260    /// What one entry of an initializer puts in the image.
1261    ///
1262    /// A bit-field is not a datum of its own, because two of them can live in one byte and an
1263    /// image is written in bytes. They were put together into their bytes by [`Self::packed`]
1264    /// before this ran, and the whole run of bytes goes in under the first entry that lies in
1265    /// it, which is why a later one in the same run answers with nothing.
1266    ///
1267    /// The zeroes at the end of a run are left off it, and a run that is nothing but zeroes
1268    /// answers with nothing at all. Either way the gap before the next entry covers them, which
1269    /// is the same image and is a smaller one to carry, and it is what keeps an object whose
1270    /// bit-fields are all zero in `.bss`. A zero at the front of a run or inside one stays, since
1271    /// that is where the run starts and what makes it one run. The run comes out of the map
1272    /// whatever is in it, so a later entry lying in it answers with nothing for the usual reason
1273    /// rather than writing the run a second time.
1274    ///
1275    /// An entry is usually one datum and a compound literal read is the reason the answer is a
1276    /// list: that entry is a whole object and puts as many data in as the object it is.
1277    fn entry(&mut self, entry: InitEntry, packed: &mut BTreeMap<u64, u8>, size: u64) -> Vec<Datum> {
1278        if entry.is_bit_field() {
1279            let Some(bytes) = take_run(packed, entry.offset) else { return Vec::new() };
1280            let Some(last) = bytes.iter().rposition(|&byte| byte != 0) else { return Vec::new() };
1281            return vec![Datum::Bytes(self.module.push_bytes(&bytes[..=last]))];
1282        }
1283        if let Some(literal) = self.literal_read(entry.value) {
1284            return self.literal_image(literal, self.tast.expr_span(entry.value));
1285        }
1286        if entry.reverse {
1287            if let Some(reversed) = self.reversed_datum(entry) {
1288                return reversed;
1289            }
1290        }
1291        // How much room is left in the object, which is what a string literal longer than the
1292        // array it initializes is cut down to. An entry that begins where the object ends is the
1293        // initializer of a flexible array member, and there the object grows to hold what was
1294        // written rather than the value being cut to fit, so nothing is taken off it.
1295        let room = if entry.offset < size { size - entry.offset } else { u64::MAX };
1296        if let Some(halves) = self.complex_image(entry.value) {
1297            return halves;
1298        }
1299        self.datum(entry.value, room).into_iter().collect()
1300    }
1301
1302    /// A complex constant as the two data an image holds it in, and [`None`] for anything else.
1303    ///
1304    /// A complex value is two real ones and an image is bytes, so `1.0 + 2.0i` goes in as the two
1305    /// halves one after the other, which is the layout every ABI here already reads it as. It is
1306    /// two data rather than one because a datum is one scalar, and it is here rather than in
1307    /// [`Self::datum`] for the same reason.
1308    fn complex_image(&mut self, value: ExprId) -> Option<Vec<Datum>> {
1309        let ty = self.tast[value].ty;
1310        let part = rucc_types::real_part(self.types, ty)?;
1311        let span = self.tast.expr_span(value);
1312        // Everything below this point answers with something, because the folding reports its own
1313        // failure and asking for the value a second time would report it twice.
1314        let folded = match self.fold(value) {
1315            Some(folded) => folded,
1316            None => return Some(Vec::new()),
1317        };
1318        let Some(ty) = repr::value_type(self.types, self.target, part) else {
1319            self.unsupported("this complex initializer", span);
1320            return Some(Vec::new());
1321        };
1322        // Each half goes in as the half's own type would, which is the bits of a floating value
1323        // and the number of an integer one.
1324        let halves = match folded {
1325            Const::Complex { real, imag } => {
1326                [real, imag].map(|half| Imm::from_bits(half.to_bits()))
1327            }
1328            Const::ComplexInt { real, imag } => [real, imag].map(|half| Imm::int(half, ty)),
1329            _ => {
1330                self.unsupported("this complex initializer", span);
1331                return Some(Vec::new());
1332            }
1333        };
1334        let data = halves
1335            .into_iter()
1336            .map(|half| {
1337                let imm = self.module.add_imm(half);
1338                Datum::Scalar { ty, value: imm }
1339            })
1340            .collect();
1341        Some(data)
1342    }
1343
1344    /// The compound literal an entry reads, if that is what the entry is.
1345    ///
1346    /// Reading an object is a node of its own, so a literal used as a value comes through as a
1347    /// read of a literal. A literal whose address is taken is not a read and is not this: that
1348    /// one folds to an address and goes in as a relocation, with the object it points at emitted
1349    /// on its own.
1350    fn literal_read(&self, value: ExprId) -> Option<DeclId> {
1351        let ExprKind::Convert { kind: Conversion::Lvalue, operand } = self.tast[value].kind else {
1352            return None;
1353        };
1354        match self.tast[operand].kind {
1355            ExprKind::CompoundLiteral(decl) => Some(decl),
1356            _ => None,
1357        }
1358    }
1359
1360    /// The bytes a compound literal contributes where it is read, which are its own image.
1361    ///
1362    /// The literal has static storage duration here, since a file-scope initializer is the only
1363    /// place this is reached from, and C 6.7.11p4 is what lets it stand as a constant element.
1364    /// Its own initializer is built at the offset the entry is at, so the parent image ends up
1365    /// with the literal's bytes laid into it rather than a name pointing at a second object.
1366    fn literal_image(&mut self, literal: DeclId, span: Span) -> Vec<Datum> {
1367        let size = repr::size_of(self.types, self.target, self.tast[literal].ty);
1368        let Some(init) = self.tast[literal].init else {
1369            return if size == 0 { Vec::new() } else { vec![Datum::Zero(size)] };
1370        };
1371        self.pieces(init, size, span).0
1372    }
1373
1374    /// The bit-fields of an initializer, put together into the bytes they lie in.
1375    ///
1376    /// Every byte a field lies in is in the map, whatever the bits it put there are. It is
1377    /// tempting to leave a zero byte out, on the grounds that what an image does not say is zero
1378    /// anyway, and it is wrong: the run a field's bytes make is taken out of the map from the
1379    /// byte the field starts at, so a field whose first byte happens to be zero would have its
1380    /// whole run left behind and `struct { unsigned f : 20; } x = { 0x12300 };` would read as
1381    /// zero. A run that is all zeroes is written as zeroes by [`Self::entry`], so an object that
1382    /// really is zero still costs nothing in the image.
1383    ///
1384    /// A field named twice takes only the bits of the field, so the last of them stands and does
1385    /// not read as the two values together.
1386    fn packed(&mut self, entries: &[InitEntry], size: u64) -> BTreeMap<u64, u8> {
1387        let mut bytes = BTreeMap::new();
1388        for entry in entries.iter().filter(|entry| entry.is_bit_field()) {
1389            let Some(folded) = self.fold(entry.value) else { continue };
1390            let Const::Int(number) = folded else {
1391                let span = self.tast.expr_span(entry.value);
1392                let what = "a bit-field initialized by something that is not an integer";
1393                self.unsupported(what, span);
1394                continue;
1395            };
1396            let width = entry.bit_width;
1397            let ones = if width >= 128 { u128::MAX } else { (1u128 << width) - 1 };
1398            // Which bytes the field lies in and where in them it sits. A reversed field lies in
1399            // the same bytes and is counted from the top of them, and the byte at its address is
1400            // then the most significant of the ones the value is assembled in rather than the
1401            // least, which is why the walk below runs the other way as well.
1402            let span = u64::from((entry.bit_offset + width).div_ceil(8));
1403            let start = if entry.reverse {
1404                u32::try_from(span * 8).unwrap_or(u32::MAX) - entry.bit_offset - width
1405            } else {
1406                entry.bit_offset
1407            };
1408            let mut mask = ones << start;
1409            let mut placed = ((number as u128) & ones) << start;
1410            let mut step = 0;
1411            while mask != 0 && step < span {
1412                let at = if entry.reverse {
1413                    entry.offset + span - 1 - step
1414                } else {
1415                    entry.offset + step
1416                };
1417                if at < size {
1418                    let (bits, keep) = ((placed & 0xff) as u8, !((mask & 0xff) as u8));
1419                    let byte = bytes.entry(at).or_insert(0);
1420                    *byte = (*byte & keep) | bits;
1421                }
1422                mask >>= 8;
1423                placed >>= 8;
1424                step += 1;
1425            }
1426        }
1427        bytes
1428    }
1429
1430    /// What one entry of a record whose scalars are stored the other way round puts in the image.
1431    ///
1432    /// The bytes of the value, written in the order opposite to the target's, which is the whole of
1433    /// what the attribute asks for. It answers with nothing where the ordinary path is already
1434    /// right: a value one byte wide has only one order, and an aggregate is bytes its own members
1435    /// put there in whatever order each of them is stored in.
1436    ///
1437    /// Two things are refused rather than written the wrong way. A complex value is two scalars and
1438    /// this is one, and an address is a number the linker fills in later and there is nowhere to
1439    /// say it goes in backwards. Both are worth an answer one day and neither is worth a wrong one.
1440    fn reversed_datum(&mut self, entry: InitEntry) -> Option<Vec<Datum>> {
1441        let ty = self.tast[entry.value].ty;
1442        let span = self.tast.expr_span(entry.value);
1443        if is_complex(self.types, ty) {
1444            let what = "a complex member of a record whose scalars are stored the other way round";
1445            self.unsupported(what, span);
1446            return Some(Vec::new());
1447        }
1448        let size = repr::size_of(self.types, self.target, ty);
1449        if size < 2 || !is_scalar(self.types, ty) {
1450            return None;
1451        }
1452        let bits = match self.fold(entry.value) {
1453            Some(Const::Int(number)) => number as u128,
1454            Some(Const::Float(number)) => number.to_bits(),
1455            Some(Const::Address(Address { base: Base::Absolute, offset })) => offset as u128,
1456            Some(_) => {
1457                let what = "an address in a record whose scalars are stored the other way round";
1458                self.unsupported(what, span);
1459                return Some(Vec::new());
1460            }
1461            None => return Some(Vec::new()),
1462        };
1463        let take = cap(size).min(16);
1464        let mut bytes = bits.to_le_bytes()[..take].to_vec();
1465        if self.target.little_endian {
1466            bytes.reverse();
1467        }
1468        Some(vec![Datum::Bytes(self.module.push_bytes(&bytes))])
1469    }
1470
1471    /// One entry of an image, given how many bytes are left in the object it goes in.
1472    fn datum(&mut self, value: ExprId, room: u64) -> Option<Datum> {
1473        let tast = self.tast;
1474        let ty = tast[value].ty;
1475        let span = tast.expr_span(value);
1476        if let TypeKind::Array { .. } = self.types.kind(self.types.canonical(ty)) {
1477            // An array in an initializer is a string literal initializing it, because that is
1478            // the only way an array is ever a value. `char s[2] = "hi";` drops the terminator,
1479            // which is the one case where the literal is longer than what it initializes, and
1480            // the front end has already given the value the type of the array it is filling, so
1481            // the type is what says how many of the literal's bytes are part of it. `room` is
1482            // still consulted because a flexible array member is filled by a literal that keeps
1483            // its own type and there is no size in the object for it to be cut to.
1484            let ExprKind::Str(id) = tast[value].kind else {
1485                self.unsupported("this initializer", span);
1486                return None;
1487            };
1488            let bytes = tast[id].bytes(self.target);
1489            let holds = repr::size_of(self.types, self.target, ty);
1490            let take = bytes.len().min(cap(holds)).min(cap(room));
1491            return Some(Datum::Bytes(self.module.push_bytes(&bytes[..take])));
1492        }
1493
1494        let size = repr::size_of(self.types, self.target, ty);
1495        match self.fold(value)? {
1496            Const::Int(number) => {
1497                let ty = repr::value_type(self.types, self.target, ty)?;
1498                // An integer constant of pointer type is a null pointer constant, which is what
1499                // `NULL` is, or an address the program wrote as a number. An image is bytes and
1500                // `ptr` says nothing about how many, so it goes in as the integer it is at the
1501                // width the target's addresses have. An address the linker has to fill in is
1502                // the arm below, and is the only one that stays a pointer.
1503                let ty = if ty.is_ptr() { Type::int(self.target.pointer_width) } else { ty };
1504                let imm = self.module.add_imm(Imm::int(number, ty));
1505                Some(Datum::Scalar { ty, value: imm })
1506            }
1507            Const::Float(number) => {
1508                let ty = repr::value_type(self.types, self.target, ty)?;
1509                let imm = self.module.add_imm(Imm::from_bits(number.to_bits()));
1510                Some(Datum::Scalar { ty, value: imm })
1511            }
1512            // A complex constant is two scalars and this answers with one, so it is not one of
1513            // these. [`Self::complex_image`] puts one in before this is reached.
1514            Const::Complex { .. } | Const::ComplexInt { .. } => None,
1515            // An address into nothing is a number, so it goes into the image as one and there is
1516            // no relocation for the linker to fill in. `static char *p = &((struct S *)0)->f;` is
1517            // a pointer whose value is known here, and the walk that folded it already said so.
1518            Const::Address(Address { base: Base::Absolute, offset }) => {
1519                let ty = repr::value_type(self.types, self.target, ty)?;
1520                let ty = if ty.is_ptr() { Type::int(self.target.pointer_width) } else { ty };
1521                let imm = self.module.add_imm(Imm::int(offset, ty));
1522                Some(Datum::Scalar { ty, value: imm })
1523            }
1524            // Two labels, both named for the image the way one is for `&&l`, and the width is
1525            // the type's since the distance is a number and not an address.
1526            Const::Apart { to, from } => {
1527                let to = self.label_name(to);
1528                let from = self.label_name(from);
1529                let size = u32::try_from(size).unwrap_or(0);
1530                let to = self.module.add_reloc(Reloc { symbol: to, addend: 0, size });
1531                Some(Datum::Apart { to, from })
1532            }
1533            Const::Address(address) => {
1534                let symbol = match address.base {
1535                    Base::Decl(decl) => {
1536                        // A compound literal is an object nothing declares, so the address of
1537                        // one is also the only thing that asks for it to be emitted. Without
1538                        // this the image names a symbol the module never defines and the link
1539                        // is what finds out. Anything with a name of its own is left alone,
1540                        // since the walk over the unit reaches those on its own.
1541                        if self.tast[decl].name.is_none() {
1542                            self.local_static(decl);
1543                        }
1544                        self.symbol_of(decl)
1545                    }
1546                    Base::Str(id) => self.string(id),
1547                    Base::Label(label) => self.label_name(label),
1548                    // Answered above, where it becomes a number rather than a reference.
1549                    Base::Absolute => return None,
1550                };
1551                let addend = i64::try_from(address.offset).unwrap_or(0);
1552                let size = u32::try_from(size).unwrap_or(0);
1553                Some(Datum::Addr(self.module.add_reloc(Reloc { symbol, addend, size })))
1554            }
1555        }
1556    }
1557
1558    /// An image of nothing but zeros, which is what a tentative definition has.
1559    fn zeros(&mut self, size: u64) -> DataList {
1560        if size == 0 {
1561            return DataList::EMPTY;
1562        }
1563        self.module.push_data(&[Datum::Zero(size)])
1564    }
1565
1566    /// The global a string literal is emitted as, making it the first time it is asked for.
1567    pub(crate) fn string(&mut self, id: StrId) -> Symbol {
1568        if let Some(&symbol) = self.strings.get(&id) {
1569            return symbol;
1570        }
1571        let literal = &self.tast[id];
1572        let bytes = literal.bytes(self.target);
1573        let align = literal.encoding.element_width(self.target) / 8;
1574        let symbol = self.names.intern(&format!(".Lstr.{}", self.strings.len()));
1575
1576        let mut global = Global::new(symbol, bytes.len() as u64, align.max(1));
1577        global.linkage = IrLinkage::Internal;
1578        // Not because the type says so, since a literal is an array of `char` and not of
1579        // `const char`, but because writing to one is undefined and every target puts them
1580        // somewhere read-only.
1581        global.constant = true;
1582        let range = self.module.push_bytes(&bytes);
1583        global.init = Some(self.module.push_data(&[Datum::Bytes(range)]));
1584        self.module.add_global(global);
1585        self.strings.insert(id, symbol);
1586        symbol
1587    }
1588
1589    /// The name a label an image holds the address of is known by, minting one the first time.
1590    ///
1591    /// The number is what makes two labels in two functions two names, the same way it does for a
1592    /// `static` inside a function. Nothing but the relocation and the definition the back end
1593    /// writes for it ever reads this, so the spelling only has to be one the object format lets a
1594    /// local symbol have, and the leading dot is what keeps it out of the symbol table on the
1595    /// formats that have the convention.
1596    pub(crate) fn label_name(&mut self, label: LabelId) -> Symbol {
1597        if let Some(&symbol) = self.labels.get(&label) {
1598            return symbol;
1599        }
1600        let symbol = self.names.intern(&format!(".Llbl.{}", self.labels.len()));
1601        self.labels.insert(label, symbol);
1602        symbol
1603    }
1604
1605    /// The name a label was given, or `None` for a label no image points at.
1606    pub(crate) fn named_label(&self, label: LabelId) -> Option<Symbol> {
1607        self.labels.get(&label).copied()
1608    }
1609
1610    /// The name the C library gives a function the program named with the `__builtin_` prefix,
1611    /// and nothing for every other name.
1612    ///
1613    /// `__builtin_abort` is a call to `abort`: the prefix is how a program reaches the function
1614    /// the library promises where a macro or a definition of its own has taken the plain name,
1615    /// so the two spellings are one function and the one the linker will look for is the short
1616    /// one. Which names those are is [`rucc_sema::library_name`]'s to say, since it is the same
1617    /// answer the front end declared them out of.
1618    fn library_name(&mut self, name: Symbol) -> Option<Symbol> {
1619        let library = rucc_sema::library_name(self.names.resolve(name))?;
1620        let symbol = self.names.intern(library);
1621        // And then whatever the file said that name is called in the object file. A program is
1622        // allowed to declare `memcpy` with an assembler name of its own and go on calling
1623        // `__builtin_memcpy`, and what it means by that is the renamed one: the prefix picks the
1624        // function out of the library, it does not ask for a symbol the file has renamed away.
1625        Some(self.renamed.get(&symbol).copied().unwrap_or(symbol))
1626    }
1627
1628    /// The name an object or a function is known by in the object file.
1629    pub(crate) fn symbol_of(&mut self, decl: DeclId) -> Symbol {
1630        let tast = self.tast;
1631        let node = &tast[decl];
1632        // The assembler name a declaration wrote, which is the symbol whatever the identifier
1633        // spells. It stands for a `static` and for a local one as well as for a name the linker
1634        // sees, so it is read before anything else here: a program that renames a name has said
1635        // what the symbol is, and the numbering below is for the ones that have not.
1636        if let Some(label) = node.asm_label {
1637            let spelling: String =
1638                tast[label].elements.iter().filter_map(|&unit| char::from_u32(unit)).collect();
1639            return self.names.intern(&spelling);
1640        }
1641        if node.linkage != Linkage::None {
1642            let Some(name) = node.name else { return self.names.intern(".Lanon") };
1643            return self.library_name(name).unwrap_or(name);
1644        }
1645        if let Some(&symbol) = self.statics.get(&decl) {
1646            return symbol;
1647        }
1648        // A `static` in a function, or a compound literal with static storage duration. The
1649        // number is what makes two of them in two functions two objects.
1650        let base = match node.name {
1651            Some(name) => self.names.resolve(name).to_string(),
1652            None => ".Lanon".to_string(),
1653        };
1654        let symbol = self.names.intern(&format!("{base}.{}", self.statics.len()));
1655        self.statics.insert(decl, symbol);
1656        symbol
1657    }
1658
1659    /// Emits the global for an object with static storage duration declared inside a function.
1660    pub(crate) fn local_static(&mut self, decl: DeclId) {
1661        if !self.done.insert(decl) {
1662            return;
1663        }
1664        match self.tast[decl].kind {
1665            // A function declared inside a body is a declaration of the function, not an
1666            // object with static storage that happens to be one.
1667            DeclKind::Function => self.function(decl),
1668            DeclKind::Object => self.object(decl),
1669            DeclKind::Type => {}
1670        }
1671    }
1672
1673    /// The value of a constant expression, reporting what folding it reported.
1674    ///
1675    /// Everything this is asked about is part of the image of an object that exists before the
1676    /// program runs, which is the one place C23 6.6p10 lets a compiler take more than the rest of
1677    /// 6.6 does, so it asks for the reading the front end already accepted there. Asking the
1678    /// strict way instead would refuse here what was allowed a pass earlier, which is a wrong
1679    /// answer arriving late rather than an extra check.
1680    fn fold(&mut self, expr: ExprId) -> Option<Const> {
1681        let mut eval = Eval::new(self.tast, self.types, self.target, self.names);
1682        let folded = eval.initializer(expr);
1683        let reported = eval.finish();
1684        self.diagnostics.extend(reported);
1685        match folded {
1686            Ok(value) => Some(value),
1687            Err(stop) => {
1688                if !stop.poisoned {
1689                    let span = self.tast.expr_span(stop.at);
1690                    self.unsupported("an initializer this compiler cannot fold", span);
1691                }
1692                None
1693            }
1694        }
1695    }
1696
1697    /// Reports a construct the walk does not build IR for yet.
1698    pub(crate) fn unsupported(&mut self, what: &str, span: Span) {
1699        self.diagnostics.push(
1700            Diagnostic::error(format!("{what} is not supported yet"), span).with_code("E0519"),
1701        );
1702    }
1703
1704    /// Reports a call to a builtin this compiler knows the name of and does nothing with.
1705    ///
1706    /// It is its own message rather than [`Self::unsupported`] because the construct is not the
1707    /// problem: a call is a call, and what is missing is the one function it goes to. The note is
1708    /// what a reader needs, since a builtin is the one name a programmer does not expect to have
1709    /// to provide and the alternative to this message is a linker asking them for it.
1710    pub(crate) fn missing_builtin(&mut self, spelled: &str, span: Span) {
1711        let message = format!("`{spelled}` is not implemented yet");
1712        let note = "a call to it would go to a symbol no object file defines, so this is refused \
1713                    here rather than at the link";
1714        self.diagnostics.push(Diagnostic::error(message, span).with_code("E0686").note(note, span));
1715    }
1716}
1717
1718/// A count of bytes as a length of a slice of them, saturating on a target whose addresses are
1719/// wider than this host's.
1720fn cap(bytes: u64) -> usize {
1721    usize::try_from(bytes).unwrap_or(usize::MAX)
1722}
1723
1724/// The run of bytes a bit-field entry starts, taken out of the map.
1725///
1726/// [`None`] when there is no byte at that offset, which means an earlier entry in the same run
1727/// already took it, since [`Unit::packed`] puts every byte a field lies in into the map.
1728fn take_run(bytes: &mut BTreeMap<u64, u8>, start: u64) -> Option<Vec<u8>> {
1729    let mut run = vec![bytes.remove(&start)?];
1730    let mut at = start + 1;
1731    while let Some(byte) = bytes.remove(&at) {
1732        run.push(byte);
1733        at += 1;
1734    }
1735    Some(run)
1736}