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};
30
31use rucc_base::{Interner, Symbol};
32use rucc_diag::{Diagnostic, Span};
33use rucc_ir::{
34    DataList, Datum, Func, Global, Imm, Linkage as IrLinkage, Module, Reloc, TlsModel, Type,
35};
36use rucc_sema::{
37    Base, Const, Conversion, DeclId, DeclKind, Definition, Eval, ExprId, ExprKind, InitEntry,
38    InitList, Linkage, StorageDuration, StrId, Tast,
39};
40use rucc_target::TargetInfo;
41use rucc_types::{TypeId, TypeKind, Types, compatible};
42
43use crate::abi::{self, Plan};
44use crate::body;
45use crate::reach;
46use crate::repr;
47
48/// Everything the walk reads, which is a checked translation unit and the target it is for.
49///
50/// The interner is mutable because the walk invents names the program never wrote: the label a
51/// string literal is emitted under, and the mangled name of a function-scope `static`.
52#[derive(Debug)]
53pub struct Context<'a> {
54    /// The typed tree.
55    pub tast: &'a Tast,
56    /// The types it points into.
57    pub types: &'a Types,
58    /// What is being compiled for, which is where every width and every alignment comes from.
59    pub target: &'a TargetInfo,
60    /// The name table.
61    pub names: &'a mut Interner,
62}
63
64/// What the walk produced.
65#[derive(Debug)]
66pub struct Lowered {
67    /// The module, which is complete even when something was reported: a construct that is not
68    /// supported yet leaves the rest of the function around it intact.
69    pub module: Module,
70    /// What was reported, in the order it was found.
71    pub diagnostics: Vec<Diagnostic>,
72}
73
74/// Walks a checked translation unit and builds the IR for it.
75///
76/// `name` is the module's name, which is the file the tree came from.
77#[must_use]
78pub fn lower(name: &str, cx: Context<'_>) -> Lowered {
79    let Context { tast, types, target, names } = cx;
80    let module = Module::new(names.intern(name), target);
81    let mut unit = Unit {
82        tast,
83        types,
84        target,
85        names,
86        module,
87        diagnostics: Vec::new(),
88        strings: HashMap::new(),
89        statics: HashMap::new(),
90        done: HashSet::new(),
91        reachable: reach::reachable(tast),
92    };
93    unit.run();
94    Lowered { module: unit.module, diagnostics: unit.diagnostics }
95}
96
97/// The walk over one translation unit, and everything it has built so far.
98pub(crate) struct Unit<'a> {
99    pub(crate) tast: &'a Tast,
100    pub(crate) types: &'a Types,
101    pub(crate) target: &'a TargetInfo,
102    pub(crate) names: &'a mut Interner,
103    pub(crate) module: Module,
104    pub(crate) diagnostics: Vec<Diagnostic>,
105    /// The global each string literal was emitted as, so that two mentions of one literal are
106    /// one object.
107    strings: HashMap<StrId, Symbol>,
108    /// The name each object with no linkage was given.
109    statics: HashMap<DeclId, Symbol>,
110    /// What has been emitted, because a redeclaration is the same declaration seen twice.
111    done: HashSet<DeclId>,
112    /// What something in the file reaches, which is what decides whether a function with
113    /// internal linkage is emitted at all.
114    reachable: HashSet<DeclId>,
115}
116
117// The debug is by hand and short: a translation unit is not something anybody wants printed as
118// a `{:?}`, and the module has a printer of its own for when they do.
119impl std::fmt::Debug for Unit<'_> {
120    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
121        f.debug_struct("Unit")
122            .field("module", &self.module.counts())
123            .field("diagnostics", &self.diagnostics.len())
124            .finish()
125    }
126}
127
128impl Unit<'_> {
129    /// Every declaration the file made, in the order it made them.
130    fn run(&mut self) {
131        for index in 0..self.tast.top_level().len() {
132            let decl = self.tast.top_level()[index];
133            if !self.done.insert(decl) {
134                continue;
135            }
136            match self.tast[decl].kind {
137                DeclKind::Function => self.function(decl),
138                DeclKind::Object => self.object(decl),
139            }
140        }
141    }
142
143    /// One object with static storage duration.
144    fn object(&mut self, decl: DeclId) {
145        let tast = self.tast;
146        let node = &tast[decl];
147        let (ty, state, init) = (node.ty, node.state, node.init);
148        let (linkage, duration, alignment) = (node.linkage, node.duration, node.alignment);
149        let span = tast.decl_span(decl);
150        if duration == StorageDuration::Automatic {
151            // A block-scope object with automatic storage is a slot or a value in the function
152            // that declares it, and the body is what makes it. Nothing is emitted here.
153            return;
154        }
155
156        let symbol = self.symbol_of(decl);
157        let size = repr::size_of(self.types, self.target, ty);
158        let align = alignment.unwrap_or_else(|| repr::align_of(self.types, self.target, ty));
159        let mut global = Global::new(symbol, size, align);
160        global.linkage = match linkage {
161            Linkage::External => IrLinkage::External,
162            Linkage::Internal | Linkage::None => IrLinkage::Internal,
163        };
164        global.tls = (duration == StorageDuration::Thread).then_some(TlsModel::GlobalDynamic);
165        global.constant = repr::is_read_only(self.types, ty);
166        global.init = match state {
167            // `extern int x;` and nothing else names an object another translation unit
168            // defines. The global is here so that a reference to it has something to resolve
169            // against, and it has no image, which is what makes it a declaration.
170            Definition::Declared => None,
171            Definition::Tentative => Some(self.zeros(size)),
172            Definition::Defined => {
173                let (data, covered) = self.image(init, size, span);
174                // The object is as large as its image when the image is the larger of the two.
175                // A structure whose last member is a flexible array is the only way that
176                // happens: `sizeof` answers without the array and an initializer that fills it
177                // makes an object big enough to hold what was written. C 6.7.2.1p18 leaves the
178                // size to the implementation, gcc grows the object, and this does the same
179                // rather than hand the linker a size the image does not fit in.
180                global.size = size.max(covered);
181                Some(data)
182            }
183        };
184        self.module.add_global(global);
185    }
186
187    /// One function, with its body when it has one.
188    fn function(&mut self, decl: DeclId) {
189        if self.is_dropped(decl) {
190            return;
191        }
192        let tast = self.tast;
193        let node = &tast[decl];
194        let (ty, linkage, body, align) = (node.ty, node.linkage, node.body, node.alignment);
195        let span = tast.decl_span(decl);
196        let Some(name) = node.name else { return };
197        let name = self.library_name(name).unwrap_or(name);
198        let Some(plan) = self.plan(ty, &[], span) else { return };
199
200        let mut func = Func::new(name, plan.signature.clone());
201        func.align = align;
202        func.linkage = match linkage {
203            Linkage::Internal | Linkage::None => IrLinkage::Internal,
204            Linkage::External => IrLinkage::External,
205        };
206        if body.is_some() {
207            body::lower(self, decl, &mut func, &plan);
208        }
209        self.module.add_func(func);
210    }
211
212    /// Whether this function is one nothing can call, which is the set that is not emitted.
213    ///
214    /// A name with internal linkage is not visible to another translation unit, so a definition
215    /// of one that nothing here refers to is a definition of something that can never run.
216    /// [`reach`](mod@crate::reach) is what worked out which those are, and an attribute that asks
217    /// for the definition to be kept has already been read into the answer.
218    ///
219    /// Nothing is said about it. gcc has `-Wunused-function` for a `static` function nobody
220    /// wrote a call to, which is a warning about the program, and this is not that: the header
221    /// that defines six of them is not the file being compiled and its author is not the person
222    /// reading the output.
223    fn is_dropped(&self, decl: DeclId) -> bool {
224        self.tast[decl].linkage != Linkage::External && !self.reachable.contains(&decl)
225    }
226
227    /// How everything a call to this function type hands over travels, and [`None`] for one the
228    /// walk cannot make.
229    ///
230    /// `actual` is the types of the arguments at a call site, which matter only past the end of
231    /// the prototype: what a variadic argument does is decided from what was written there, and
232    /// there is no parameter to decide it from. A definition passes nothing for it.
233    pub(crate) fn plan(&mut self, ty: TypeId, actual: &[TypeId], span: Span) -> Option<Plan> {
234        self.plan_with(ty, actual, false, span)
235    }
236
237    /// The same, as the call site sees it rather than as the function does.
238    ///
239    /// The two differ for a type that is not a prototype. An old style definition is the one of
240    /// those that knows what its parameters are, and 6.5.2.2p6 checks a call against a prototype
241    /// and against nothing at all otherwise, so a parameter it disagrees with does not make the
242    /// call wrong and cannot be what the argument travels as either: the value at the call is
243    /// the argument's own type and nothing converted it. So a parameter the argument facing it
244    /// is compatible with is used, which is the usual case and is what makes the call go to the
245    /// name, and one it is not compatible with gives way to what was actually written. A call
246    /// like that is undefined behaviour if control reaches it and the file still has to
247    /// translate, which is the same position [`Body::direct`](crate::body) already takes.
248    pub(crate) fn call_plan(&mut self, ty: TypeId, actual: &[TypeId], span: Span) -> Option<Plan> {
249        self.plan_with(ty, actual, true, span)
250    }
251
252    fn plan_with(
253        &mut self,
254        ty: TypeId,
255        actual: &[TypeId],
256        at_call: bool,
257        span: Span,
258    ) -> Option<Plan> {
259        let canonical = self.types.canonical(ty);
260        let canonical = match self.types.kind(canonical) {
261            // A call goes through a pointer to a function, and the type in hand may be either.
262            TypeKind::Pointer(pointee) => self.types.canonical(pointee),
263            _ => canonical,
264        };
265        let TypeKind::Function(id) = self.types.kind(canonical) else {
266            self.unsupported("a call through something that is not a function", span);
267            return None;
268        };
269        let signature = self.types.signature(id);
270        let ret = signature.ret;
271        // A function declared without a prototype takes what it is given, which is what a
272        // signature with no parameters and no end to them says. C23 removed these and this is
273        // what `int f();` means in every dialect before it.
274        let variadic = signature.variadic || !signature.prototyped;
275        let params = if at_call && !signature.prototyped {
276            // An argument past the end of the list has no parameter to travel as, which is what
277            // a call to an unprototyped function with more arguments than the definition takes
278            // is, so the list ends where the arguments do.
279            signature
280                .params
281                .iter()
282                .zip(actual)
283                .map(|(&param, &arg)| if compatible(self.types, param, arg) { param } else { arg })
284                .collect()
285        } else {
286            signature.params.clone()
287        };
288
289        match abi::plan(self.types, self.target, ret, &params, actual, variadic) {
290            Ok(plan) => Some(plan),
291            Err(what) => {
292                self.unsupported(what, span);
293                None
294            }
295        }
296    }
297
298    /// The image of an initializer: the entries in ascending order, with the gaps zeroed, and
299    /// how many bytes it covers.
300    ///
301    /// The count is the size that was asked for except when a flexible array member was given
302    /// something to hold, which is the one case where an image is larger than the type it is an
303    /// image of.
304    pub(crate) fn image(
305        &mut self,
306        init: Option<InitList>,
307        size: u64,
308        span: Span,
309    ) -> (DataList, u64) {
310        let Some(init) = init else { return (self.zeros(size), size) };
311        let (data, at) = self.pieces(init, size, span);
312        (self.module.push_data(&data), at)
313    }
314
315    /// The data an image is made of, before it becomes a [`DataList`].
316    ///
317    /// This is apart from [`Self::image`] so that an image can be built inside another one,
318    /// which is what a compound literal used as a value in an initializer needs.
319    fn pieces(&mut self, init: InitList, size: u64, span: Span) -> (Vec<Datum>, u64) {
320        let entries = self.in_image_order(&self.tast[init]);
321        let mut packed = self.packed(&entries, size);
322        let mut data: Vec<Datum> = Vec::with_capacity(entries.len());
323        let mut at = 0;
324        for entry in entries {
325            let piece = self.entry(entry, &mut packed, size);
326            if piece.is_empty() {
327                continue;
328            }
329            let covered: u64 = piece.iter().map(|datum| datum.size(&self.module)).sum();
330            match entry.offset.cmp(&at) {
331                Ordering::Greater => data.push(Datum::Zero(entry.offset - at)),
332                // An entry that begins inside the one before it, which is neither the same
333                // place nor a later one. A union whose members are initialized through two
334                // designators is the way to write it. The earlier bytes are already in the
335                // list and the image cannot take them out again, so this is refused, and
336                // nothing here is wrong enough to drop the rest of the image.
337                Ordering::Less => {
338                    self.unsupported("an initializer that writes over an earlier one", span);
339                    continue;
340                }
341                Ordering::Equal => {}
342            }
343            at = entry.offset + covered;
344            data.extend(piece);
345        }
346        if at < size {
347            // The tail of a partly initialized object, which C says is zero. So is the tail of
348            // an array the initializer did not fill, and so is every byte of padding.
349            data.push(Datum::Zero(size - at));
350            at = size;
351        }
352        (data, at)
353    }
354
355    /// The entries an image is written from, which is not the order they were written in.
356    ///
357    /// A designator names a place, and the places may be named in any order at all:
358    /// `{ .b = 2, .a = 1 }` is the same object as `{ .a = 1, .b = 2 }` and C says so in as many
359    /// words. An image is bytes in ascending order, so the entries are put in that order here.
360    /// The sort is stable, which is what makes the rest of the rule work: naming one place
361    /// twice is legal and the last of them is the one that stands, so among the entries at one
362    /// offset the written order is kept and all but the last are dropped.
363    ///
364    /// A bit-field is never dropped, because several of them share one offset without writing
365    /// over anything. Which bytes they came to is settled by [`Self::packed`] before this runs
366    /// and the whole run goes in under the first entry that has a bit in it.
367    fn in_image_order(&self, entries: &[InitEntry]) -> Vec<InitEntry> {
368        let mut sorted = entries.to_vec();
369        sorted.sort_by_key(|entry| entry.offset);
370        let mut kept: Vec<InitEntry> = Vec::with_capacity(sorted.len());
371        for entry in sorted {
372            if !entry.is_bit_field() {
373                let over = |last: &InitEntry| last.offset == entry.offset && !last.is_bit_field();
374                while kept.last().is_some_and(over) {
375                    kept.pop();
376                }
377            }
378            kept.push(entry);
379        }
380        kept
381    }
382
383    /// What one entry of an initializer puts in the image.
384    ///
385    /// A bit-field is not a datum of its own, because two of them can live in one byte and an
386    /// image is written in bytes. They were put together into their bytes by [`Self::packed`]
387    /// before this ran, and the whole run of bytes goes in under the first entry that lies in
388    /// it, which is why a later one in the same run answers with nothing.
389    ///
390    /// The zeroes at the end of a run are left off it, and a run that is nothing but zeroes
391    /// answers with nothing at all. Either way the gap before the next entry covers them, which
392    /// is the same image and is a smaller one to carry, and it is what keeps an object whose
393    /// bit-fields are all zero in `.bss`. A zero at the front of a run or inside one stays, since
394    /// that is where the run starts and what makes it one run. The run comes out of the map
395    /// whatever is in it, so a later entry lying in it answers with nothing for the usual reason
396    /// rather than writing the run a second time.
397    ///
398    /// An entry is usually one datum and a compound literal read is the reason the answer is a
399    /// list: that entry is a whole object and puts as many data in as the object it is.
400    fn entry(&mut self, entry: InitEntry, packed: &mut BTreeMap<u64, u8>, size: u64) -> Vec<Datum> {
401        if entry.is_bit_field() {
402            let Some(bytes) = take_run(packed, entry.offset) else { return Vec::new() };
403            let Some(last) = bytes.iter().rposition(|&byte| byte != 0) else { return Vec::new() };
404            return vec![Datum::Bytes(self.module.push_bytes(&bytes[..=last]))];
405        }
406        if let Some(literal) = self.literal_read(entry.value) {
407            return self.literal_image(literal, self.tast.expr_span(entry.value));
408        }
409        // How much room is left in the object, which is what a string literal longer than the
410        // array it initializes is cut down to. An entry that begins where the object ends is the
411        // initializer of a flexible array member, and there the object grows to hold what was
412        // written rather than the value being cut to fit, so nothing is taken off it.
413        let room = if entry.offset < size { size - entry.offset } else { u64::MAX };
414        self.datum(entry.value, room).into_iter().collect()
415    }
416
417    /// The compound literal an entry reads, if that is what the entry is.
418    ///
419    /// Reading an object is a node of its own, so a literal used as a value comes through as a
420    /// read of a literal. A literal whose address is taken is not a read and is not this: that
421    /// one folds to an address and goes in as a relocation, with the object it points at emitted
422    /// on its own.
423    fn literal_read(&self, value: ExprId) -> Option<DeclId> {
424        let ExprKind::Convert { kind: Conversion::Lvalue, operand } = self.tast[value].kind else {
425            return None;
426        };
427        match self.tast[operand].kind {
428            ExprKind::CompoundLiteral(decl) => Some(decl),
429            _ => None,
430        }
431    }
432
433    /// The bytes a compound literal contributes where it is read, which are its own image.
434    ///
435    /// The literal has static storage duration here, since a file-scope initializer is the only
436    /// place this is reached from, and C 6.7.11p4 is what lets it stand as a constant element.
437    /// Its own initializer is built at the offset the entry is at, so the parent image ends up
438    /// with the literal's bytes laid into it rather than a name pointing at a second object.
439    fn literal_image(&mut self, literal: DeclId, span: Span) -> Vec<Datum> {
440        let size = repr::size_of(self.types, self.target, self.tast[literal].ty);
441        let Some(init) = self.tast[literal].init else {
442            return if size == 0 { Vec::new() } else { vec![Datum::Zero(size)] };
443        };
444        self.pieces(init, size, span).0
445    }
446
447    /// The bit-fields of an initializer, put together into the bytes they lie in.
448    ///
449    /// Every byte a field lies in is in the map, whatever the bits it put there are. It is
450    /// tempting to leave a zero byte out, on the grounds that what an image does not say is zero
451    /// anyway, and it is wrong: the run a field's bytes make is taken out of the map from the
452    /// byte the field starts at, so a field whose first byte happens to be zero would have its
453    /// whole run left behind and `struct { unsigned f : 20; } x = { 0x12300 };` would read as
454    /// zero. A run that is all zeroes is written as zeroes by [`Self::entry`], so an object that
455    /// really is zero still costs nothing in the image.
456    ///
457    /// A field named twice takes only the bits of the field, so the last of them stands and does
458    /// not read as the two values together.
459    fn packed(&mut self, entries: &[InitEntry], size: u64) -> BTreeMap<u64, u8> {
460        let mut bytes = BTreeMap::new();
461        for entry in entries.iter().filter(|entry| entry.is_bit_field()) {
462            let Some(folded) = self.fold(entry.value) else { continue };
463            let Const::Int(number) = folded else {
464                let span = self.tast.expr_span(entry.value);
465                let what = "a bit-field initialized by something that is not an integer";
466                self.unsupported(what, span);
467                continue;
468            };
469            let width = entry.bit_width;
470            let ones = if width >= 128 { u128::MAX } else { (1u128 << width) - 1 };
471            let mut mask = ones << entry.bit_offset;
472            let mut placed = ((number as u128) & ones) << entry.bit_offset;
473            let mut at = entry.offset;
474            while mask != 0 && at < size {
475                let (bits, keep) = ((placed & 0xff) as u8, !((mask & 0xff) as u8));
476                let byte = bytes.entry(at).or_insert(0);
477                *byte = (*byte & keep) | bits;
478                mask >>= 8;
479                placed >>= 8;
480                at += 1;
481            }
482        }
483        bytes
484    }
485
486    /// One entry of an image, given how many bytes are left in the object it goes in.
487    fn datum(&mut self, value: ExprId, room: u64) -> Option<Datum> {
488        let tast = self.tast;
489        let ty = tast[value].ty;
490        let span = tast.expr_span(value);
491        if let TypeKind::Array { .. } = self.types.kind(self.types.canonical(ty)) {
492            // An array in an initializer is a string literal initializing it, because that is
493            // the only way an array is ever a value. `char s[2] = "hi";` drops the terminator,
494            // which is the one case where the literal is longer than what it initializes, and
495            // the front end has already given the value the type of the array it is filling, so
496            // the type is what says how many of the literal's bytes are part of it. `room` is
497            // still consulted because a flexible array member is filled by a literal that keeps
498            // its own type and there is no size in the object for it to be cut to.
499            let ExprKind::Str(id) = tast[value].kind else {
500                self.unsupported("this initializer", span);
501                return None;
502            };
503            let bytes = tast[id].bytes(self.target);
504            let holds = repr::size_of(self.types, self.target, ty);
505            let take = bytes.len().min(cap(holds)).min(cap(room));
506            return Some(Datum::Bytes(self.module.push_bytes(&bytes[..take])));
507        }
508
509        let size = repr::size_of(self.types, self.target, ty);
510        match self.fold(value)? {
511            Const::Int(number) => {
512                let ty = repr::value_type(self.types, self.target, ty)?;
513                // An integer constant of pointer type is a null pointer constant, which is what
514                // `NULL` is, or an address the program wrote as a number. An image is bytes and
515                // `ptr` says nothing about how many, so it goes in as the integer it is at the
516                // width the target's addresses have. An address the linker has to fill in is
517                // the arm below, and is the only one that stays a pointer.
518                let ty = if ty.is_ptr() { Type::int(self.target.pointer_width) } else { ty };
519                let imm = self.module.add_imm(Imm::int(number, ty));
520                Some(Datum::Scalar { ty, value: imm })
521            }
522            Const::Float(number) => {
523                let ty = repr::value_type(self.types, self.target, ty)?;
524                let imm = self.module.add_imm(Imm::from_bits(number.to_bits()));
525                Some(Datum::Scalar { ty, value: imm })
526            }
527            Const::Address(address) => {
528                let symbol = match address.base {
529                    Base::Decl(decl) => {
530                        // A compound literal is an object nothing declares, so the address of
531                        // one is also the only thing that asks for it to be emitted. Without
532                        // this the image names a symbol the module never defines and the link
533                        // is what finds out. Anything with a name of its own is left alone,
534                        // since the walk over the unit reaches those on its own.
535                        if self.tast[decl].name.is_none() {
536                            self.local_static(decl);
537                        }
538                        self.symbol_of(decl)
539                    }
540                    Base::Str(id) => self.string(id),
541                };
542                let addend = i64::try_from(address.offset).unwrap_or(0);
543                let size = u32::try_from(size).unwrap_or(0);
544                Some(Datum::Addr(self.module.add_reloc(Reloc { symbol, addend, size })))
545            }
546        }
547    }
548
549    /// An image of nothing but zeros, which is what a tentative definition has.
550    fn zeros(&mut self, size: u64) -> DataList {
551        if size == 0 {
552            return DataList::EMPTY;
553        }
554        self.module.push_data(&[Datum::Zero(size)])
555    }
556
557    /// The global a string literal is emitted as, making it the first time it is asked for.
558    pub(crate) fn string(&mut self, id: StrId) -> Symbol {
559        if let Some(&symbol) = self.strings.get(&id) {
560            return symbol;
561        }
562        let literal = &self.tast[id];
563        let bytes = literal.bytes(self.target);
564        let align = literal.encoding.element_width(self.target) / 8;
565        let symbol = self.names.intern(&format!(".Lstr.{}", self.strings.len()));
566
567        let mut global = Global::new(symbol, bytes.len() as u64, align.max(1));
568        global.linkage = IrLinkage::Internal;
569        // Not because the type says so, since a literal is an array of `char` and not of
570        // `const char`, but because writing to one is undefined and every target puts them
571        // somewhere read-only.
572        global.constant = true;
573        let range = self.module.push_bytes(&bytes);
574        global.init = Some(self.module.push_data(&[Datum::Bytes(range)]));
575        self.module.add_global(global);
576        self.strings.insert(id, symbol);
577        symbol
578    }
579
580    /// The name the C library gives a function the program named with the `__builtin_` prefix,
581    /// and nothing for every other name.
582    ///
583    /// `__builtin_abort` is a call to `abort`: the prefix is how a program reaches the function
584    /// the library promises where a macro or a definition of its own has taken the plain name,
585    /// so the two spellings are one function and the one the linker will look for is the short
586    /// one. Which names those are is [`rucc_sema::library_name`]'s to say, since it is the same
587    /// answer the front end declared them out of.
588    fn library_name(&mut self, name: Symbol) -> Option<Symbol> {
589        let library = rucc_sema::library_name(self.names.resolve(name))?;
590        Some(self.names.intern(library))
591    }
592
593    /// The name an object or a function is known by in the object file.
594    pub(crate) fn symbol_of(&mut self, decl: DeclId) -> Symbol {
595        let tast = self.tast;
596        let node = &tast[decl];
597        if node.linkage != Linkage::None {
598            let Some(name) = node.name else { return self.names.intern(".Lanon") };
599            return self.library_name(name).unwrap_or(name);
600        }
601        if let Some(&symbol) = self.statics.get(&decl) {
602            return symbol;
603        }
604        // A `static` in a function, or a compound literal with static storage duration. The
605        // number is what makes two of them in two functions two objects.
606        let base = match node.name {
607            Some(name) => self.names.resolve(name).to_string(),
608            None => ".Lanon".to_string(),
609        };
610        let symbol = self.names.intern(&format!("{base}.{}", self.statics.len()));
611        self.statics.insert(decl, symbol);
612        symbol
613    }
614
615    /// Emits the global for an object with static storage duration declared inside a function.
616    pub(crate) fn local_static(&mut self, decl: DeclId) {
617        if !self.done.insert(decl) {
618            return;
619        }
620        match self.tast[decl].kind {
621            // A function declared inside a body is a declaration of the function, not an
622            // object with static storage that happens to be one.
623            DeclKind::Function => self.function(decl),
624            DeclKind::Object => self.object(decl),
625        }
626    }
627
628    /// The value of a constant expression, reporting what folding it reported.
629    fn fold(&mut self, expr: ExprId) -> Option<Const> {
630        let mut eval = Eval::new(self.tast, self.types, self.target, self.names);
631        let folded = eval.constant(expr);
632        let reported = eval.finish();
633        self.diagnostics.extend(reported);
634        match folded {
635            Ok(value) => Some(value),
636            Err(stop) => {
637                if !stop.poisoned {
638                    let span = self.tast.expr_span(stop.at);
639                    self.unsupported("an initializer this compiler cannot fold", span);
640                }
641                None
642            }
643        }
644    }
645
646    /// Reports a construct the walk does not build IR for yet.
647    pub(crate) fn unsupported(&mut self, what: &str, span: Span) {
648        self.diagnostics.push(
649            Diagnostic::error(format!("{what} is not supported yet"), span).with_code("E0519"),
650        );
651    }
652
653    /// Reports a call to a builtin this compiler knows the name of and does nothing with.
654    ///
655    /// It is its own message rather than [`Self::unsupported`] because the construct is not the
656    /// problem: a call is a call, and what is missing is the one function it goes to. The note is
657    /// what a reader needs, since a builtin is the one name a programmer does not expect to have
658    /// to provide and the alternative to this message is a linker asking them for it.
659    pub(crate) fn missing_builtin(&mut self, spelled: &str, span: Span) {
660        let message = format!("`{spelled}` is not implemented yet");
661        let note = "a call to it would go to a symbol no object file defines, so this is refused \
662                    here rather than at the link";
663        self.diagnostics.push(Diagnostic::error(message, span).with_code("E0686").note(note, span));
664    }
665}
666
667/// A count of bytes as a length of a slice of them, saturating on a target whose addresses are
668/// wider than this host's.
669fn cap(bytes: u64) -> usize {
670    usize::try_from(bytes).unwrap_or(usize::MAX)
671}
672
673/// The run of bytes a bit-field entry starts, taken out of the map.
674///
675/// [`None`] when there is no byte at that offset, which means an earlier entry in the same run
676/// already took it, since [`Unit::packed`] puts every byte a field lies in into the map.
677fn take_run(bytes: &mut BTreeMap<u64, u8>, start: u64) -> Option<Vec<u8>> {
678    let mut run = vec![bytes.remove(&start)?];
679    let mut at = start + 1;
680    while let Some(byte) = bytes.remove(&at) {
681        run.push(byte);
682        at += 1;
683    }
684    Some(run)
685}