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, DeclId, DeclKind, Definition, Eval, ExprId, ExprKind, InitEntry, InitList,
38    Linkage, StorageDuration, StrId, Tast,
39};
40use rucc_target::TargetInfo;
41use rucc_types::{TypeId, TypeKind, Types};
42
43use crate::abi::{self, Plan};
44use crate::body;
45use crate::repr;
46
47/// Everything the walk reads, which is a checked translation unit and the target it is for.
48///
49/// The interner is mutable because the walk invents names the program never wrote: the label a
50/// string literal is emitted under, and the mangled name of a function-scope `static`.
51#[derive(Debug)]
52pub struct Context<'a> {
53    /// The typed tree.
54    pub tast: &'a Tast,
55    /// The types it points into.
56    pub types: &'a Types,
57    /// What is being compiled for, which is where every width and every alignment comes from.
58    pub target: &'a TargetInfo,
59    /// The name table.
60    pub names: &'a mut Interner,
61}
62
63/// What the walk produced.
64#[derive(Debug)]
65pub struct Lowered {
66    /// The module, which is complete even when something was reported: a construct that is not
67    /// supported yet leaves the rest of the function around it intact.
68    pub module: Module,
69    /// What was reported, in the order it was found.
70    pub diagnostics: Vec<Diagnostic>,
71}
72
73/// Walks a checked translation unit and builds the IR for it.
74///
75/// `name` is the module's name, which is the file the tree came from.
76#[must_use]
77pub fn lower(name: &str, cx: Context<'_>) -> Lowered {
78    let Context { tast, types, target, names } = cx;
79    let module = Module::new(names.intern(name), target);
80    let mut unit = Unit {
81        tast,
82        types,
83        target,
84        names,
85        module,
86        diagnostics: Vec::new(),
87        strings: HashMap::new(),
88        statics: HashMap::new(),
89        done: HashSet::new(),
90    };
91    unit.run();
92    Lowered { module: unit.module, diagnostics: unit.diagnostics }
93}
94
95/// The walk over one translation unit, and everything it has built so far.
96pub(crate) struct Unit<'a> {
97    pub(crate) tast: &'a Tast,
98    pub(crate) types: &'a Types,
99    pub(crate) target: &'a TargetInfo,
100    pub(crate) names: &'a mut Interner,
101    pub(crate) module: Module,
102    pub(crate) diagnostics: Vec<Diagnostic>,
103    /// The global each string literal was emitted as, so that two mentions of one literal are
104    /// one object.
105    strings: HashMap<StrId, Symbol>,
106    /// The name each object with no linkage was given.
107    statics: HashMap<DeclId, Symbol>,
108    /// What has been emitted, because a redeclaration is the same declaration seen twice.
109    done: HashSet<DeclId>,
110}
111
112// The debug is by hand and short: a translation unit is not something anybody wants printed as
113// a `{:?}`, and the module has a printer of its own for when they do.
114impl std::fmt::Debug for Unit<'_> {
115    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
116        f.debug_struct("Unit")
117            .field("module", &self.module.counts())
118            .field("diagnostics", &self.diagnostics.len())
119            .finish()
120    }
121}
122
123impl Unit<'_> {
124    /// Every declaration the file made, in the order it made them.
125    fn run(&mut self) {
126        for index in 0..self.tast.top_level().len() {
127            let decl = self.tast.top_level()[index];
128            if !self.done.insert(decl) {
129                continue;
130            }
131            match self.tast[decl].kind {
132                DeclKind::Function => self.function(decl),
133                DeclKind::Object => self.object(decl),
134            }
135        }
136    }
137
138    /// One object with static storage duration.
139    fn object(&mut self, decl: DeclId) {
140        let tast = self.tast;
141        let node = &tast[decl];
142        let (ty, state, init) = (node.ty, node.state, node.init);
143        let (linkage, duration, alignment) = (node.linkage, node.duration, node.alignment);
144        let span = tast.decl_span(decl);
145        if duration == StorageDuration::Automatic {
146            // A block-scope object with automatic storage is a slot or a value in the function
147            // that declares it, and the body is what makes it. Nothing is emitted here.
148            return;
149        }
150
151        let symbol = self.symbol_of(decl);
152        let size = repr::size_of(self.types, self.target, ty);
153        let align = alignment.unwrap_or_else(|| repr::align_of(self.types, self.target, ty));
154        let mut global = Global::new(symbol, size, align);
155        global.linkage = match linkage {
156            Linkage::External => IrLinkage::External,
157            Linkage::Internal | Linkage::None => IrLinkage::Internal,
158        };
159        global.tls = (duration == StorageDuration::Thread).then_some(TlsModel::GlobalDynamic);
160        global.constant = repr::is_read_only(self.types, ty);
161        global.init = match state {
162            // `extern int x;` and nothing else names an object another translation unit
163            // defines. The global is here so that a reference to it has something to resolve
164            // against, and it has no image, which is what makes it a declaration.
165            Definition::Declared => None,
166            Definition::Tentative => Some(self.zeros(size)),
167            Definition::Defined => Some(self.image(init, size, span)),
168        };
169        self.module.add_global(global);
170    }
171
172    /// One function, with its body when it has one.
173    fn function(&mut self, decl: DeclId) {
174        let tast = self.tast;
175        let node = &tast[decl];
176        let (ty, linkage, body) = (node.ty, node.linkage, node.body);
177        let span = tast.decl_span(decl);
178        let Some(name) = node.name else { return };
179        let Some(plan) = self.plan(ty, &[], span) else { return };
180
181        let mut func = Func::new(name, plan.signature.clone());
182        func.linkage = match linkage {
183            Linkage::Internal | Linkage::None => IrLinkage::Internal,
184            Linkage::External => IrLinkage::External,
185        };
186        if body.is_some() {
187            body::lower(self, decl, &mut func, &plan);
188        }
189        self.module.add_func(func);
190    }
191
192    /// How everything a call to this function type hands over travels, and [`None`] for one the
193    /// walk cannot make.
194    ///
195    /// `actual` is the types of the arguments at a call site, which matter only past the end of
196    /// the prototype: what a variadic argument does is decided from what was written there, and
197    /// there is no parameter to decide it from. A definition passes nothing for it.
198    pub(crate) fn plan(&mut self, ty: TypeId, actual: &[TypeId], span: Span) -> Option<Plan> {
199        let canonical = self.types.canonical(ty);
200        let canonical = match self.types.kind(canonical) {
201            // A call goes through a pointer to a function, and the type in hand may be either.
202            TypeKind::Pointer(pointee) => self.types.canonical(pointee),
203            _ => canonical,
204        };
205        let TypeKind::Function(id) = self.types.kind(canonical) else {
206            self.unsupported("a call through something that is not a function", span);
207            return None;
208        };
209        let signature = self.types.signature(id);
210        let ret = signature.ret;
211        // A function declared without a prototype takes what it is given, which is what a
212        // signature with no parameters and no end to them says. C23 removed these and this is
213        // what `int f();` means in every dialect before it.
214        let variadic = signature.variadic || !signature.prototyped;
215        let params = signature.params.clone();
216
217        match abi::plan(self.types, self.target, ret, &params, actual, variadic) {
218            Ok(plan) => Some(plan),
219            Err(what) => {
220                self.unsupported(what, span);
221                None
222            }
223        }
224    }
225
226    /// The image of an initializer: the entries in ascending order, with the gaps zeroed.
227    pub(crate) fn image(&mut self, init: Option<InitList>, size: u64, span: Span) -> DataList {
228        let Some(init) = init else { return self.zeros(size) };
229        let entries = self.in_image_order(&self.tast[init]);
230        let mut packed = self.packed(&entries, size);
231        let mut data: Vec<Datum> = Vec::with_capacity(entries.len());
232        let mut at = 0;
233        for entry in entries {
234            let Some(datum) = self.entry(entry, &mut packed, size) else { continue };
235            match entry.offset.cmp(&at) {
236                Ordering::Greater => data.push(Datum::Zero(entry.offset - at)),
237                // An entry that begins inside the one before it, which is neither the same
238                // place nor a later one. A union whose members are initialized through two
239                // designators is the way to write it. The earlier bytes are already in the
240                // list and the image cannot take them out again, so this is refused, and
241                // nothing here is wrong enough to drop the rest of the image.
242                Ordering::Less => {
243                    self.unsupported("an initializer that writes over an earlier one", span);
244                    continue;
245                }
246                Ordering::Equal => {}
247            }
248            at = entry.offset + datum.size(&self.module);
249            data.push(datum);
250        }
251        if at < size {
252            // The tail of a partly initialized object, which C says is zero. So is the tail of
253            // an array the initializer did not fill, and so is every byte of padding.
254            data.push(Datum::Zero(size - at));
255        }
256        self.module.push_data(&data)
257    }
258
259    /// The entries an image is written from, which is not the order they were written in.
260    ///
261    /// A designator names a place, and the places may be named in any order at all:
262    /// `{ .b = 2, .a = 1 }` is the same object as `{ .a = 1, .b = 2 }` and C says so in as many
263    /// words. An image is bytes in ascending order, so the entries are put in that order here.
264    /// The sort is stable, which is what makes the rest of the rule work: naming one place
265    /// twice is legal and the last of them is the one that stands, so among the entries at one
266    /// offset the written order is kept and all but the last are dropped.
267    ///
268    /// A bit-field is never dropped, because several of them share one offset without writing
269    /// over anything. Which bytes they came to is settled by [`Self::packed`] before this runs
270    /// and the whole run goes in under the first entry that has a bit in it.
271    fn in_image_order(&self, entries: &[InitEntry]) -> Vec<InitEntry> {
272        let mut sorted = entries.to_vec();
273        sorted.sort_by_key(|entry| entry.offset);
274        let mut kept: Vec<InitEntry> = Vec::with_capacity(sorted.len());
275        for entry in sorted {
276            if !entry.is_bit_field() {
277                let over = |last: &InitEntry| last.offset == entry.offset && !last.is_bit_field();
278                while kept.last().is_some_and(over) {
279                    kept.pop();
280                }
281            }
282            kept.push(entry);
283        }
284        kept
285    }
286
287    /// What one entry of an initializer puts in the image.
288    ///
289    /// A bit-field is not a datum of its own, because two of them can live in one byte and an
290    /// image is written in bytes. They were put together into their bytes by [`Self::packed`]
291    /// before this ran, and the whole run of bytes goes in under the first entry that has a
292    /// bit in it, which is why a later one in the same run answers with nothing.
293    fn entry(
294        &mut self,
295        entry: InitEntry,
296        packed: &mut BTreeMap<u64, u8>,
297        size: u64,
298    ) -> Option<Datum> {
299        if entry.is_bit_field() {
300            let bytes = take_run(packed, entry.offset)?;
301            return Some(Datum::Bytes(self.module.push_bytes(&bytes)));
302        }
303        let room = size.saturating_sub(entry.offset);
304        self.datum(entry.value, room)
305    }
306
307    /// The bit-fields of an initializer, put together into the bytes they lie in.
308    ///
309    /// Only the bytes something was stored in are in the map. A field whose value is zero
310    /// leaves nothing behind, which is right: what an image does not say is zero anyway. A
311    /// field named twice takes only the bits of the field, so the last of them stands and does
312    /// not read as the two values together.
313    fn packed(&mut self, entries: &[InitEntry], size: u64) -> BTreeMap<u64, u8> {
314        let mut bytes = BTreeMap::new();
315        for entry in entries.iter().filter(|entry| entry.is_bit_field()) {
316            let Some(folded) = self.fold(entry.value) else { continue };
317            let Const::Int(number) = folded else {
318                let span = self.tast.expr_span(entry.value);
319                let what = "a bit-field initialized by something that is not an integer";
320                self.unsupported(what, span);
321                continue;
322            };
323            let width = entry.bit_width;
324            let ones = if width >= 128 { u128::MAX } else { (1u128 << width) - 1 };
325            let mut mask = ones << entry.bit_offset;
326            let mut placed = ((number as u128) & ones) << entry.bit_offset;
327            let mut at = entry.offset;
328            while mask != 0 && at < size {
329                let (bits, keep) = ((placed & 0xff) as u8, !((mask & 0xff) as u8));
330                if bits != 0 || bytes.contains_key(&at) {
331                    let byte = bytes.entry(at).or_insert(0);
332                    *byte = (*byte & keep) | bits;
333                }
334                mask >>= 8;
335                placed >>= 8;
336                at += 1;
337            }
338        }
339        bytes
340    }
341
342    /// One entry of an image, given how many bytes are left in the object it goes in.
343    fn datum(&mut self, value: ExprId, room: u64) -> Option<Datum> {
344        let tast = self.tast;
345        let ty = tast[value].ty;
346        let span = tast.expr_span(value);
347        if let TypeKind::Array { .. } = self.types.kind(self.types.canonical(ty)) {
348            // An array in an initializer is a string literal initializing it, because that is
349            // the only way an array is ever a value. `char s[2] = "hi";` drops the terminator,
350            // which is the one case where the literal is longer than what it initializes.
351            let ExprKind::Str(id) = tast[value].kind else {
352                self.unsupported("this initializer", span);
353                return None;
354            };
355            let bytes = tast[id].bytes(self.target);
356            let take = bytes.len().min(usize::try_from(room).unwrap_or(usize::MAX));
357            return Some(Datum::Bytes(self.module.push_bytes(&bytes[..take])));
358        }
359
360        let size = repr::size_of(self.types, self.target, ty);
361        match self.fold(value)? {
362            Const::Int(number) => {
363                let ty = repr::value_type(self.types, self.target, ty)?;
364                // An integer constant of pointer type is a null pointer constant, which is what
365                // `NULL` is, or an address the program wrote as a number. An image is bytes and
366                // `ptr` says nothing about how many, so it goes in as the integer it is at the
367                // width the target's addresses have. An address the linker has to fill in is
368                // the arm below, and is the only one that stays a pointer.
369                let ty = if ty.is_ptr() { Type::int(self.target.pointer_width) } else { ty };
370                let imm = self.module.add_imm(Imm::int(number, ty));
371                Some(Datum::Scalar { ty, value: imm })
372            }
373            Const::Float(number) => {
374                let ty = repr::value_type(self.types, self.target, ty)?;
375                let imm = self.module.add_imm(Imm::from_bits(number.to_bits()));
376                Some(Datum::Scalar { ty, value: imm })
377            }
378            Const::Address(address) => {
379                let symbol = match address.base {
380                    Base::Decl(decl) => self.symbol_of(decl),
381                    Base::Str(id) => self.string(id),
382                };
383                let addend = i64::try_from(address.offset).unwrap_or(0);
384                let size = u32::try_from(size).unwrap_or(0);
385                Some(Datum::Addr(self.module.add_reloc(Reloc { symbol, addend, size })))
386            }
387        }
388    }
389
390    /// An image of nothing but zeros, which is what a tentative definition has.
391    fn zeros(&mut self, size: u64) -> DataList {
392        if size == 0 {
393            return DataList::EMPTY;
394        }
395        self.module.push_data(&[Datum::Zero(size)])
396    }
397
398    /// The global a string literal is emitted as, making it the first time it is asked for.
399    pub(crate) fn string(&mut self, id: StrId) -> Symbol {
400        if let Some(&symbol) = self.strings.get(&id) {
401            return symbol;
402        }
403        let literal = &self.tast[id];
404        let bytes = literal.bytes(self.target);
405        let align = literal.encoding.element_width(self.target) / 8;
406        let symbol = self.names.intern(&format!(".Lstr.{}", self.strings.len()));
407
408        let mut global = Global::new(symbol, bytes.len() as u64, align.max(1));
409        global.linkage = IrLinkage::Internal;
410        // Not because the type says so, since a literal is an array of `char` and not of
411        // `const char`, but because writing to one is undefined and every target puts them
412        // somewhere read-only.
413        global.constant = true;
414        let range = self.module.push_bytes(&bytes);
415        global.init = Some(self.module.push_data(&[Datum::Bytes(range)]));
416        self.module.add_global(global);
417        self.strings.insert(id, symbol);
418        symbol
419    }
420
421    /// The name an object or a function is known by in the object file.
422    pub(crate) fn symbol_of(&mut self, decl: DeclId) -> Symbol {
423        let tast = self.tast;
424        let node = &tast[decl];
425        if node.linkage != Linkage::None {
426            return node.name.unwrap_or_else(|| self.names.intern(".Lanon"));
427        }
428        if let Some(&symbol) = self.statics.get(&decl) {
429            return symbol;
430        }
431        // A `static` in a function, or a compound literal with static storage duration. The
432        // number is what makes two of them in two functions two objects.
433        let base = match node.name {
434            Some(name) => self.names.resolve(name).to_string(),
435            None => ".Lanon".to_string(),
436        };
437        let symbol = self.names.intern(&format!("{base}.{}", self.statics.len()));
438        self.statics.insert(decl, symbol);
439        symbol
440    }
441
442    /// Emits the global for an object with static storage duration declared inside a function.
443    pub(crate) fn local_static(&mut self, decl: DeclId) {
444        if !self.done.insert(decl) {
445            return;
446        }
447        match self.tast[decl].kind {
448            // A function declared inside a body is a declaration of the function, not an
449            // object with static storage that happens to be one.
450            DeclKind::Function => self.function(decl),
451            DeclKind::Object => self.object(decl),
452        }
453    }
454
455    /// The value of a constant expression, reporting what folding it reported.
456    fn fold(&mut self, expr: ExprId) -> Option<Const> {
457        let mut eval = Eval::new(self.tast, self.types, self.target, self.names);
458        let folded = eval.constant(expr);
459        let reported = eval.finish();
460        self.diagnostics.extend(reported);
461        match folded {
462            Ok(value) => Some(value),
463            Err(stop) => {
464                if !stop.poisoned {
465                    let span = self.tast.expr_span(stop.at);
466                    self.unsupported("an initializer this compiler cannot fold", span);
467                }
468                None
469            }
470        }
471    }
472
473    /// Reports a construct the walk does not build IR for yet.
474    pub(crate) fn unsupported(&mut self, what: &str, span: Span) {
475        self.diagnostics.push(
476            Diagnostic::error(format!("{what} is not supported yet"), span).with_code("E0519"),
477        );
478    }
479}
480
481/// The run of bytes a bit-field entry starts, taken out of the map.
482///
483/// [`None`] when there is no byte at that offset, which means either that every bit-field in
484/// it was initialized to zero or that an earlier entry in the same run already took it.
485fn take_run(bytes: &mut BTreeMap<u64, u8>, start: u64) -> Option<Vec<u8>> {
486    let mut run = vec![bytes.remove(&start)?];
487    let mut at = start + 1;
488    while let Some(byte) = bytes.remove(&at) {
489        run.push(byte);
490        at += 1;
491    }
492    Some(run)
493}