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 Alias, AttrSet, DataList, Datum, Func, Global, Imm, Linkage as IrLinkage, Module, Reloc,
35 SymbolRef, TlsModel, Type, Visibility as IrVisibility,
36};
37use rucc_sema::{
38 Base, Const, Conversion, DeclId, DeclKind, Definition, Eval, ExprId, ExprKind, InitEntry,
39 InitList, Linkage, StorageDuration, StrId, Tast, Visibility,
40};
41use rucc_target::TargetInfo;
42use rucc_types::{TypeId, TypeKind, Types, compatible};
43
44use crate::abi::{self, Plan};
45use crate::body;
46use crate::reach;
47use crate::repr;
48
49/// Which functions get a stack protector, which is what the `-fstack-protector` family decides.
50///
51/// The question is about the locals a function has, so it is answered here and not in the back
52/// end: by the time a frame is laid out the types are gone and every local is a size and an
53/// alignment. What the back end then does about the answer is its own business, and it is carried
54/// to it as [`rucc_ir::AttrSet::STACK_PROTECT`] on the function.
55///
56/// The names are gcc's, and so are the rules. A build that has been compiled with one of these for
57/// twenty years is entitled to the same set of protected functions from a compiler claiming to be
58/// compatible, because the ones left out are the ones an exploit goes looking for.
59#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
60pub enum Protector {
61 /// None of them, which is `-fno-stack-protector` and what a command line that says nothing
62 /// gets.
63 #[default]
64 None,
65 /// A function with a local array of at least eight bytes, or one whose stack grows while it
66 /// runs. `-fstack-protector`, which is the original and the narrowest.
67 Buffers,
68 /// Any of those, and any function with a local array at all, a local holding one, or a local
69 /// whose address is taken. `-fstack-protector-strong`, which is what every distribution builds
70 /// its packages with and therefore the one a real build line carries.
71 Strong,
72 /// Every function that has a frame at all. `-fstack-protector-all`.
73 All,
74}
75
76/// Everything the walk reads, which is a checked translation unit and the target it is for.
77///
78/// The interner is mutable because the walk invents names the program never wrote: the label a
79/// string literal is emitted under, and the mangled name of a function-scope `static`.
80#[derive(Debug)]
81pub struct Context<'a> {
82 /// The typed tree.
83 pub tast: &'a Tast,
84 /// The types it points into.
85 pub types: &'a Types,
86 /// What is being compiled for, which is where every width and every alignment comes from.
87 pub target: &'a TargetInfo,
88 /// The name table.
89 pub names: &'a mut Interner,
90 /// What a name that no declaration of it said anything about gets, which is `-fvisibility=`.
91 ///
92 /// A fact about the compilation rather than about any declaration, which is why it arrives
93 /// here rather than on the tree: the checker knows what was written and this knows what the
94 /// command line asked for, and the answer is the first of those where there is one.
95 pub visibility: IrVisibility,
96 /// Which functions get a stack protector, which is `-fstack-protector` and its relatives.
97 pub protector: Protector,
98}
99
100/// What the walk produced.
101#[derive(Debug)]
102pub struct Lowered {
103 /// The module, which is complete even when something was reported: a construct that is not
104 /// supported yet leaves the rest of the function around it intact.
105 pub module: Module,
106 /// What was reported, in the order it was found.
107 pub diagnostics: Vec<Diagnostic>,
108}
109
110/// Walks a checked translation unit and builds the IR for it.
111///
112/// `name` is the module's name, which is the file the tree came from.
113#[must_use]
114pub fn lower(name: &str, cx: Context<'_>) -> Lowered {
115 let Context { tast, types, target, names, visibility, protector } = cx;
116 let module = Module::new(names.intern(name), target);
117 let mut unit = Unit {
118 tast,
119 types,
120 target,
121 names,
122 visibility,
123 protector,
124 module,
125 diagnostics: Vec::new(),
126 strings: HashMap::new(),
127 statics: HashMap::new(),
128 done: HashSet::new(),
129 aliases: Vec::new(),
130 aliased: HashSet::new(),
131 reachable: reach::reachable(tast),
132 };
133 unit.run();
134 Lowered { module: unit.module, diagnostics: unit.diagnostics }
135}
136
137/// The walk over one translation unit, and everything it has built so far.
138pub(crate) struct Unit<'a> {
139 pub(crate) tast: &'a Tast,
140 pub(crate) types: &'a Types,
141 pub(crate) target: &'a TargetInfo,
142 pub(crate) names: &'a mut Interner,
143 /// What a name no declaration said anything about gets. See [`Context::visibility`].
144 visibility: IrVisibility,
145 /// Which functions get a stack protector. See [`Context::protector`].
146 pub(crate) protector: Protector,
147 pub(crate) module: Module,
148 pub(crate) diagnostics: Vec<Diagnostic>,
149 /// The global each string literal was emitted as, so that two mentions of one literal are
150 /// one object.
151 strings: HashMap<StrId, Symbol>,
152 /// The name each object with no linkage was given.
153 statics: HashMap<DeclId, Symbol>,
154 /// What has been emitted, because a redeclaration is the same declaration seen twice.
155 done: HashSet<DeclId>,
156 /// The declarations that are a second name for something rather than a thing of their own,
157 /// in the order the file made them.
158 ///
159 /// Held back rather than emitted where they are met, because what an alias points at may be
160 /// written below it and whether anything defines it is a question only the whole file
161 /// answers.
162 aliases: Vec<DeclId>,
163 /// The symbols something in the file is a second name for.
164 ///
165 /// A `static` function nothing calls is not emitted, and being what an alias points at is a
166 /// reason to emit one that no reference in the file says: the string an alias names is not a
167 /// use of anything as far as the walk over the tree is concerned.
168 aliased: HashSet<Symbol>,
169 /// What something in the file reaches, which is what decides whether a function with
170 /// internal linkage is emitted at all.
171 reachable: HashSet<DeclId>,
172}
173
174// The debug is by hand and short: a translation unit is not something anybody wants printed as
175// a `{:?}`, and the module has a printer of its own for when they do.
176impl std::fmt::Debug for Unit<'_> {
177 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
178 f.debug_struct("Unit")
179 .field("module", &self.module.counts())
180 .field("diagnostics", &self.diagnostics.len())
181 .finish()
182 }
183}
184
185impl Unit<'_> {
186 /// Every declaration the file made, in the order it made them.
187 fn run(&mut self) {
188 self.find_aliased();
189 for index in 0..self.tast.top_level().len() {
190 let decl = self.tast.top_level()[index];
191 if !self.done.insert(decl) {
192 continue;
193 }
194 match self.tast[decl].kind {
195 DeclKind::Function => self.function(decl),
196 DeclKind::Object => self.object(decl),
197 }
198 }
199 for index in 0..self.aliases.len() {
200 self.alias(self.aliases[index]);
201 }
202 }
203
204 /// Which symbols the file gives a second name to, before anything is emitted.
205 ///
206 /// Ahead of the walk rather than during it, because a `static` function is emitted or not on
207 /// the strength of what reaches it and the alias that reaches one may be written below it.
208 fn find_aliased(&mut self) {
209 for index in 0..self.tast.top_level().len() {
210 let decl = self.tast.top_level()[index];
211 let Some(target) = self.tast[decl].alias else { continue };
212 let spelling = self.spelled(target);
213 let symbol = self.names.intern(&spelling);
214 self.aliased.insert(symbol);
215 }
216 }
217
218 /// The bytes of a string literal as a name, which is what a symbol in an attribute is.
219 fn spelled(&self, id: StrId) -> String {
220 self.tast[id].elements.iter().filter_map(|&unit| char::from_u32(unit)).collect()
221 }
222
223 /// One object with static storage duration.
224 fn object(&mut self, decl: DeclId) {
225 let tast = self.tast;
226 let node = &tast[decl];
227 let (ty, state, init) = (node.ty, node.state, node.init);
228 let (linkage, duration, alignment) = (node.linkage, node.duration, node.alignment);
229 let span = tast.decl_span(decl);
230 if duration == StorageDuration::Automatic {
231 // A block-scope object with automatic storage is a slot or a value in the function
232 // that declares it, and the body is what makes it. Nothing is emitted here.
233 return;
234 }
235 // A second name for something else is not an object of its own, so nothing is laid out
236 // and no image is built. It is held back until the rest of the file has been walked,
237 // because what it points at may be below it.
238 if node.alias.is_some() {
239 self.aliases.push(decl);
240 return;
241 }
242
243 let symbol = self.symbol_of(decl);
244 let size = repr::size_of(self.types, self.target, ty);
245 let align = alignment.unwrap_or_else(|| repr::align_of(self.types, self.target, ty));
246 let mut global = Global::new(symbol, size, align);
247 global.linkage = match linkage {
248 Linkage::External => IrLinkage::External,
249 Linkage::Internal | Linkage::None => IrLinkage::Internal,
250 };
251 global.visibility = self.seen(decl);
252 global.tls = (duration == StorageDuration::Thread).then_some(TlsModel::GlobalDynamic);
253 global.constant = repr::is_read_only(self.types, ty);
254 global.init = match state {
255 // `extern int x;` and nothing else names an object another translation unit
256 // defines. The global is here so that a reference to it has something to resolve
257 // against, and it has no image, which is what makes it a declaration.
258 Definition::Declared => None,
259 Definition::Tentative => Some(self.zeros(size)),
260 Definition::Defined => {
261 let (data, covered) = self.image(init, size, span);
262 // The object is as large as its image when the image is the larger of the two.
263 // A structure whose last member is a flexible array is the only way that
264 // happens: `sizeof` answers without the array and an initializer that fills it
265 // makes an object big enough to hold what was written. C 6.7.2.1p18 leaves the
266 // size to the implementation, gcc grows the object, and this does the same
267 // rather than hand the linker a size the image does not fit in.
268 global.size = size.max(covered);
269 Some(data)
270 }
271 };
272 self.place_global(global);
273 }
274
275 /// One function, with its body when it has one.
276 fn function(&mut self, decl: DeclId) {
277 let tast = self.tast;
278 let node = &tast[decl];
279 let (ty, linkage, body, align) = (node.ty, node.linkage, node.body, node.alignment);
280 let noreturn = node.noreturn;
281 let span = tast.decl_span(decl);
282 if node.name.is_none() {
283 return;
284 }
285 // The same as for an object: a second name is not a function of its own, and it is held
286 // back until what it points at has been emitted.
287 if node.alias.is_some() {
288 self.aliases.push(decl);
289 return;
290 }
291 // Which asks the one question the reference to it asks, so that a declaration that
292 // renamed the symbol renames the definition as well and the two still meet.
293 let name = self.symbol_of(decl);
294 if self.is_dropped(decl, name) {
295 return;
296 }
297 let Some(plan) = self.plan(ty, &[], span) else { return };
298
299 let mut func = Func::new(name, plan.signature.clone());
300 func.align = align;
301 // The one thing a declaration says that nobody downstream can work out for themselves.
302 // What `abort` does belongs to `abort`, and a translation unit that only declares it has
303 // nothing to look at, so the claim has to travel on the declaration or not at all.
304 if noreturn {
305 func.attrs.set |= AttrSet::NORETURN;
306 }
307 func.linkage = match linkage {
308 Linkage::Internal | Linkage::None => IrLinkage::Internal,
309 Linkage::External => IrLinkage::External,
310 };
311 func.visibility = self.seen(decl);
312 // An inline definition is not an external definition, so what goes in the module is the
313 // declaration and not the body. C 6.7.4p7 says the calls in this unit go to the definition
314 // some other unit holds, which is what the declaration gives them, and glibc's headers
315 // rely on it: every one of their inline definitions would otherwise be a second definition
316 // of a name the library already defines.
317 if body.is_some() && node.inline.emits() {
318 body::lower(self, decl, &mut func, &plan);
319 }
320 self.place_func(func);
321 }
322
323 /// Puts a function in the module under a name something may already be under.
324 ///
325 /// Two declarations of one identifier were merged before this, so the only way one name
326 /// arrives twice is an assembler name that renames one identifier onto another: a
327 /// declaration of `f` renamed to `g` beside a definition of `g` is one symbol written two
328 /// ways, which is what the program asked for and what the linker is going to see. The
329 /// definition wins wherever there is one, since what the declaration is here for is to give
330 /// the calls something to resolve against and the definition does that as well.
331 ///
332 /// A name already carrying a definition keeps it. That is the program defining one symbol
333 /// twice, and the assembler says so with the name in front of it, which is a better message
334 /// than anything available here.
335 fn place_func(&mut self, func: Func) {
336 match self.module.lookup(func.name) {
337 None => {
338 self.module.add_func(func);
339 }
340 Some(SymbolRef::Func(id))
341 if self.module[id].is_declaration() && !func.is_declaration() =>
342 {
343 self.module[id] = func;
344 }
345 Some(_) => {}
346 }
347 }
348
349 /// One declaration that is a second name for something the same file defines.
350 ///
351 /// Emitted after everything else, so the target is looked up in a module that already holds
352 /// whatever the file defines whether it was written above the alias or below it.
353 ///
354 /// The target has to be defined here and not merely declared, which is gcc's rule and is
355 /// what the object format can express: an alias is a symbol at another symbol's address, and
356 /// a name this file does not define has no address for one to be at. A program that writes
357 /// an alias of something in another object wants a reference rather than a definition, and
358 /// what it gets from gcc is this same error rather than a name the linker cannot resolve.
359 fn alias(&mut self, decl: DeclId) {
360 let Some(written) = self.tast[decl].alias else { return };
361 let span = self.tast.decl_span(decl);
362 let name = self.symbol_of(decl);
363 let spelling = self.spelled(written);
364 let target = self.names.intern(&spelling);
365 let spelled = self.names.resolve(name).to_owned();
366 if name == target {
367 let what = format!("'{spelled}' is aliased to itself");
368 self.diagnostics.push(Diagnostic::error(what, span).with_code("E0697"));
369 return;
370 }
371 let defined = match self.module.lookup(target) {
372 Some(SymbolRef::Func(id)) => !self.module[id].is_declaration(),
373 Some(SymbolRef::Global(id)) => self.module[id].init.is_some(),
374 // A chain of them is a thing gcc takes and this does not yet, because resolving one
375 // wants the aliases put in an order that the file they were written in need not be
376 // in. It is reported rather than written out as a name pointing at a name.
377 Some(SymbolRef::Alias(_)) | None => false,
378 };
379 if !defined {
380 let what = format!("'{spelled}' is aliased to undefined symbol '{spelling}'");
381 let note = "the target of an alias has to be defined in this same file, since an \
382 alias is a second name for an address and not a reference to one";
383 let refused = Diagnostic::error(what, span).with_code("E0697");
384 self.diagnostics.push(refused.note(note, span));
385 return;
386 }
387 // Something already under this name, which is the program defining one symbol twice. The
388 // definition that is there stands, the way it does for a function and for an object.
389 if self.module.lookup(name).is_some() {
390 return;
391 }
392 let mut alias = Alias::new(name, target);
393 alias.linkage = match self.tast[decl].linkage {
394 Linkage::Internal | Linkage::None => IrLinkage::Internal,
395 Linkage::External => IrLinkage::External,
396 };
397 // Its own answer, because the attribute is written on the alias and an alias is a symbol
398 // of its own. `weak, alias, visibility("hidden")` is a name a library keeps to itself
399 // while the thing it points at stays exported, which is how glibc writes half of them.
400 alias.visibility = self.seen(decl);
401 self.module.add_alias(alias);
402 }
403
404 /// How far a name reaches outside a shared library, which is what a declaration of it said
405 /// where one said anything and what the command line asked for where none did.
406 ///
407 /// gcc's `-fvisibility=` is written as the default rather than as an override, so the
408 /// attribute wins wherever it was written, and that is the whole reason a library compiled
409 /// with `-fvisibility=hidden` can still export the dozen names it means to export.
410 ///
411 /// Every symbol gets an answer, including a declaration of something defined elsewhere. That
412 /// is what gcc does too and it is not a technicality: a hidden reference is one the link has
413 /// to satisfy inside the library, which is the half of the flag that makes the calls cheaper
414 /// rather than the half that shortens the table.
415 fn seen(&self, decl: DeclId) -> IrVisibility {
416 match self.tast[decl].visibility {
417 Some(Visibility::Default) => IrVisibility::Default,
418 Some(Visibility::Hidden) => IrVisibility::Hidden,
419 Some(Visibility::Protected) => IrVisibility::Protected,
420 None => self.visibility,
421 }
422 }
423
424 /// The same for an object, where a global with no image is the declaration.
425 fn place_global(&mut self, global: Global) {
426 match self.module.lookup(global.name) {
427 None => {
428 self.module.add_global(global);
429 }
430 Some(SymbolRef::Global(id))
431 if self.module[id].init.is_none() && global.init.is_some() =>
432 {
433 self.module[id] = global;
434 }
435 Some(_) => {}
436 }
437 }
438
439 /// Whether this function is one nothing can call, which is the set that is not emitted.
440 ///
441 /// A name with internal linkage is not visible to another translation unit, so a definition
442 /// of one that nothing here refers to is a definition of something that can never run.
443 /// [`reach`](mod@crate::reach) is what worked out which those are, and an attribute that asks
444 /// for the definition to be kept has already been read into the answer.
445 ///
446 /// A second name for it is the one reason to keep it that the walk over the tree cannot see,
447 /// since what an alias points at is a string and not a reference to anything. So the symbol
448 /// is what is asked about here rather than the declaration: an alias names what the linker
449 /// will look for, which is what a declaration that renamed itself with `__asm__` is under.
450 ///
451 /// Nothing is said about it. gcc has `-Wunused-function` for a `static` function nobody
452 /// wrote a call to, which is a warning about the program, and this is not that: the header
453 /// that defines six of them is not the file being compiled and its author is not the person
454 /// reading the output.
455 fn is_dropped(&self, decl: DeclId, symbol: Symbol) -> bool {
456 self.tast[decl].linkage != Linkage::External
457 && !self.reachable.contains(&decl)
458 && !self.aliased.contains(&symbol)
459 }
460
461 /// How everything a call to this function type hands over travels, and [`None`] for one the
462 /// walk cannot make.
463 ///
464 /// `actual` is the types of the arguments at a call site, which matter only past the end of
465 /// the prototype: what a variadic argument does is decided from what was written there, and
466 /// there is no parameter to decide it from. A definition passes nothing for it.
467 pub(crate) fn plan(&mut self, ty: TypeId, actual: &[TypeId], span: Span) -> Option<Plan> {
468 self.plan_with(ty, actual, false, span)
469 }
470
471 /// The same, as the call site sees it rather than as the function does.
472 ///
473 /// The two differ for a type that is not a prototype. An old style definition is the one of
474 /// those that knows what its parameters are, and 6.5.2.2p6 checks a call against a prototype
475 /// and against nothing at all otherwise, so a parameter it disagrees with does not make the
476 /// call wrong and cannot be what the argument travels as either: the value at the call is
477 /// the argument's own type and nothing converted it. So a parameter the argument facing it
478 /// is compatible with is used, which is the usual case and is what makes the call go to the
479 /// name, and one it is not compatible with gives way to what was actually written. A call
480 /// like that is undefined behaviour if control reaches it and the file still has to
481 /// translate, which is the same position [`Body::direct`](crate::body) already takes.
482 pub(crate) fn call_plan(&mut self, ty: TypeId, actual: &[TypeId], span: Span) -> Option<Plan> {
483 self.plan_with(ty, actual, true, span)
484 }
485
486 fn plan_with(
487 &mut self,
488 ty: TypeId,
489 actual: &[TypeId],
490 at_call: bool,
491 span: Span,
492 ) -> Option<Plan> {
493 let canonical = self.types.canonical(ty);
494 let canonical = match self.types.kind(canonical) {
495 // A call goes through a pointer to a function, and the type in hand may be either.
496 TypeKind::Pointer(pointee) => self.types.canonical(pointee),
497 _ => canonical,
498 };
499 let TypeKind::Function(id) = self.types.kind(canonical) else {
500 self.unsupported("a call through something that is not a function", span);
501 return None;
502 };
503 let signature = self.types.signature(id);
504 let ret = signature.ret;
505 // A function declared without a prototype takes what it is given, which is what a
506 // signature with no parameters and no end to them says. C23 removed these and this is
507 // what `int f();` means in every dialect before it.
508 let variadic = signature.variadic || !signature.prototyped;
509 let params = if at_call && !signature.prototyped {
510 // An argument past the end of the list has no parameter to travel as, which is what
511 // a call to an unprototyped function with more arguments than the definition takes
512 // is, so the list ends where the arguments do.
513 signature
514 .params
515 .iter()
516 .zip(actual)
517 .map(|(¶m, &arg)| if compatible(self.types, param, arg) { param } else { arg })
518 .collect()
519 } else {
520 signature.params.clone()
521 };
522
523 match abi::plan(self.types, self.target, ret, ¶ms, actual, variadic) {
524 Ok(plan) => Some(plan),
525 Err(what) => {
526 self.unsupported(what, span);
527 None
528 }
529 }
530 }
531
532 /// The image of an initializer: the entries in ascending order, with the gaps zeroed, and
533 /// how many bytes it covers.
534 ///
535 /// The count is the size that was asked for except when a flexible array member was given
536 /// something to hold, which is the one case where an image is larger than the type it is an
537 /// image of.
538 pub(crate) fn image(
539 &mut self,
540 init: Option<InitList>,
541 size: u64,
542 span: Span,
543 ) -> (DataList, u64) {
544 let Some(init) = init else { return (self.zeros(size), size) };
545 let (data, at) = self.pieces(init, size, span);
546 (self.module.push_data(&data), at)
547 }
548
549 /// The data an image is made of, before it becomes a [`DataList`].
550 ///
551 /// This is apart from [`Self::image`] so that an image can be built inside another one,
552 /// which is what a compound literal used as a value in an initializer needs.
553 fn pieces(&mut self, init: InitList, size: u64, span: Span) -> (Vec<Datum>, u64) {
554 let entries = self.in_image_order(&self.tast[init]);
555 let mut packed = self.packed(&entries, size);
556 let mut data: Vec<Datum> = Vec::with_capacity(entries.len());
557 let mut at = 0;
558 for entry in entries {
559 let piece = self.entry(entry, &mut packed, size);
560 if piece.is_empty() {
561 continue;
562 }
563 let covered: u64 = piece.iter().map(|datum| datum.size(&self.module)).sum();
564 match entry.offset.cmp(&at) {
565 Ordering::Greater => data.push(Datum::Zero(entry.offset - at)),
566 // An entry that begins inside the one before it, which is neither the same
567 // place nor a later one. A union whose members are initialized through two
568 // designators is the way to write it. The earlier bytes are already in the
569 // list and the image cannot take them out again, so this is refused, and
570 // nothing here is wrong enough to drop the rest of the image.
571 Ordering::Less => {
572 self.unsupported("an initializer that writes over an earlier one", span);
573 continue;
574 }
575 Ordering::Equal => {}
576 }
577 at = entry.offset + covered;
578 data.extend(piece);
579 }
580 if at < size {
581 // The tail of a partly initialized object, which C says is zero. So is the tail of
582 // an array the initializer did not fill, and so is every byte of padding.
583 data.push(Datum::Zero(size - at));
584 at = size;
585 }
586 (data, at)
587 }
588
589 /// The entries an image is written from, which is not the order they were written in.
590 ///
591 /// A designator names a place, and the places may be named in any order at all:
592 /// `{ .b = 2, .a = 1 }` is the same object as `{ .a = 1, .b = 2 }` and C says so in as many
593 /// words. An image is bytes in ascending order, so the entries are put in that order here.
594 /// The sort is stable, which is what makes the rest of the rule work: naming one place
595 /// twice is legal and the last of them is the one that stands, so among the entries at one
596 /// offset the written order is kept and all but the last are dropped.
597 ///
598 /// A bit-field is never dropped, because several of them share one offset without writing
599 /// over anything. Which bytes they came to is settled by [`Self::packed`] before this runs
600 /// and the whole run goes in under the first entry that has a bit in it.
601 fn in_image_order(&self, entries: &[InitEntry]) -> Vec<InitEntry> {
602 let mut sorted = entries.to_vec();
603 sorted.sort_by_key(|entry| entry.offset);
604 let mut kept: Vec<InitEntry> = Vec::with_capacity(sorted.len());
605 for entry in sorted {
606 if !entry.is_bit_field() {
607 let over = |last: &InitEntry| last.offset == entry.offset && !last.is_bit_field();
608 while kept.last().is_some_and(over) {
609 kept.pop();
610 }
611 }
612 kept.push(entry);
613 }
614 kept
615 }
616
617 /// What one entry of an initializer puts in the image.
618 ///
619 /// A bit-field is not a datum of its own, because two of them can live in one byte and an
620 /// image is written in bytes. They were put together into their bytes by [`Self::packed`]
621 /// before this ran, and the whole run of bytes goes in under the first entry that lies in
622 /// it, which is why a later one in the same run answers with nothing.
623 ///
624 /// The zeroes at the end of a run are left off it, and a run that is nothing but zeroes
625 /// answers with nothing at all. Either way the gap before the next entry covers them, which
626 /// is the same image and is a smaller one to carry, and it is what keeps an object whose
627 /// bit-fields are all zero in `.bss`. A zero at the front of a run or inside one stays, since
628 /// that is where the run starts and what makes it one run. The run comes out of the map
629 /// whatever is in it, so a later entry lying in it answers with nothing for the usual reason
630 /// rather than writing the run a second time.
631 ///
632 /// An entry is usually one datum and a compound literal read is the reason the answer is a
633 /// list: that entry is a whole object and puts as many data in as the object it is.
634 fn entry(&mut self, entry: InitEntry, packed: &mut BTreeMap<u64, u8>, size: u64) -> Vec<Datum> {
635 if entry.is_bit_field() {
636 let Some(bytes) = take_run(packed, entry.offset) else { return Vec::new() };
637 let Some(last) = bytes.iter().rposition(|&byte| byte != 0) else { return Vec::new() };
638 return vec![Datum::Bytes(self.module.push_bytes(&bytes[..=last]))];
639 }
640 if let Some(literal) = self.literal_read(entry.value) {
641 return self.literal_image(literal, self.tast.expr_span(entry.value));
642 }
643 // How much room is left in the object, which is what a string literal longer than the
644 // array it initializes is cut down to. An entry that begins where the object ends is the
645 // initializer of a flexible array member, and there the object grows to hold what was
646 // written rather than the value being cut to fit, so nothing is taken off it.
647 let room = if entry.offset < size { size - entry.offset } else { u64::MAX };
648 self.datum(entry.value, room).into_iter().collect()
649 }
650
651 /// The compound literal an entry reads, if that is what the entry is.
652 ///
653 /// Reading an object is a node of its own, so a literal used as a value comes through as a
654 /// read of a literal. A literal whose address is taken is not a read and is not this: that
655 /// one folds to an address and goes in as a relocation, with the object it points at emitted
656 /// on its own.
657 fn literal_read(&self, value: ExprId) -> Option<DeclId> {
658 let ExprKind::Convert { kind: Conversion::Lvalue, operand } = self.tast[value].kind else {
659 return None;
660 };
661 match self.tast[operand].kind {
662 ExprKind::CompoundLiteral(decl) => Some(decl),
663 _ => None,
664 }
665 }
666
667 /// The bytes a compound literal contributes where it is read, which are its own image.
668 ///
669 /// The literal has static storage duration here, since a file-scope initializer is the only
670 /// place this is reached from, and C 6.7.11p4 is what lets it stand as a constant element.
671 /// Its own initializer is built at the offset the entry is at, so the parent image ends up
672 /// with the literal's bytes laid into it rather than a name pointing at a second object.
673 fn literal_image(&mut self, literal: DeclId, span: Span) -> Vec<Datum> {
674 let size = repr::size_of(self.types, self.target, self.tast[literal].ty);
675 let Some(init) = self.tast[literal].init else {
676 return if size == 0 { Vec::new() } else { vec![Datum::Zero(size)] };
677 };
678 self.pieces(init, size, span).0
679 }
680
681 /// The bit-fields of an initializer, put together into the bytes they lie in.
682 ///
683 /// Every byte a field lies in is in the map, whatever the bits it put there are. It is
684 /// tempting to leave a zero byte out, on the grounds that what an image does not say is zero
685 /// anyway, and it is wrong: the run a field's bytes make is taken out of the map from the
686 /// byte the field starts at, so a field whose first byte happens to be zero would have its
687 /// whole run left behind and `struct { unsigned f : 20; } x = { 0x12300 };` would read as
688 /// zero. A run that is all zeroes is written as zeroes by [`Self::entry`], so an object that
689 /// really is zero still costs nothing in the image.
690 ///
691 /// A field named twice takes only the bits of the field, so the last of them stands and does
692 /// not read as the two values together.
693 fn packed(&mut self, entries: &[InitEntry], size: u64) -> BTreeMap<u64, u8> {
694 let mut bytes = BTreeMap::new();
695 for entry in entries.iter().filter(|entry| entry.is_bit_field()) {
696 let Some(folded) = self.fold(entry.value) else { continue };
697 let Const::Int(number) = folded else {
698 let span = self.tast.expr_span(entry.value);
699 let what = "a bit-field initialized by something that is not an integer";
700 self.unsupported(what, span);
701 continue;
702 };
703 let width = entry.bit_width;
704 let ones = if width >= 128 { u128::MAX } else { (1u128 << width) - 1 };
705 let mut mask = ones << entry.bit_offset;
706 let mut placed = ((number as u128) & ones) << entry.bit_offset;
707 let mut at = entry.offset;
708 while mask != 0 && at < size {
709 let (bits, keep) = ((placed & 0xff) as u8, !((mask & 0xff) as u8));
710 let byte = bytes.entry(at).or_insert(0);
711 *byte = (*byte & keep) | bits;
712 mask >>= 8;
713 placed >>= 8;
714 at += 1;
715 }
716 }
717 bytes
718 }
719
720 /// One entry of an image, given how many bytes are left in the object it goes in.
721 fn datum(&mut self, value: ExprId, room: u64) -> Option<Datum> {
722 let tast = self.tast;
723 let ty = tast[value].ty;
724 let span = tast.expr_span(value);
725 if let TypeKind::Array { .. } = self.types.kind(self.types.canonical(ty)) {
726 // An array in an initializer is a string literal initializing it, because that is
727 // the only way an array is ever a value. `char s[2] = "hi";` drops the terminator,
728 // which is the one case where the literal is longer than what it initializes, and
729 // the front end has already given the value the type of the array it is filling, so
730 // the type is what says how many of the literal's bytes are part of it. `room` is
731 // still consulted because a flexible array member is filled by a literal that keeps
732 // its own type and there is no size in the object for it to be cut to.
733 let ExprKind::Str(id) = tast[value].kind else {
734 self.unsupported("this initializer", span);
735 return None;
736 };
737 let bytes = tast[id].bytes(self.target);
738 let holds = repr::size_of(self.types, self.target, ty);
739 let take = bytes.len().min(cap(holds)).min(cap(room));
740 return Some(Datum::Bytes(self.module.push_bytes(&bytes[..take])));
741 }
742
743 let size = repr::size_of(self.types, self.target, ty);
744 match self.fold(value)? {
745 Const::Int(number) => {
746 let ty = repr::value_type(self.types, self.target, ty)?;
747 // An integer constant of pointer type is a null pointer constant, which is what
748 // `NULL` is, or an address the program wrote as a number. An image is bytes and
749 // `ptr` says nothing about how many, so it goes in as the integer it is at the
750 // width the target's addresses have. An address the linker has to fill in is
751 // the arm below, and is the only one that stays a pointer.
752 let ty = if ty.is_ptr() { Type::int(self.target.pointer_width) } else { ty };
753 let imm = self.module.add_imm(Imm::int(number, ty));
754 Some(Datum::Scalar { ty, value: imm })
755 }
756 Const::Float(number) => {
757 let ty = repr::value_type(self.types, self.target, ty)?;
758 let imm = self.module.add_imm(Imm::from_bits(number.to_bits()));
759 Some(Datum::Scalar { ty, value: imm })
760 }
761 Const::Address(address) => {
762 let symbol = match address.base {
763 Base::Decl(decl) => {
764 // A compound literal is an object nothing declares, so the address of
765 // one is also the only thing that asks for it to be emitted. Without
766 // this the image names a symbol the module never defines and the link
767 // is what finds out. Anything with a name of its own is left alone,
768 // since the walk over the unit reaches those on its own.
769 if self.tast[decl].name.is_none() {
770 self.local_static(decl);
771 }
772 self.symbol_of(decl)
773 }
774 Base::Str(id) => self.string(id),
775 };
776 let addend = i64::try_from(address.offset).unwrap_or(0);
777 let size = u32::try_from(size).unwrap_or(0);
778 Some(Datum::Addr(self.module.add_reloc(Reloc { symbol, addend, size })))
779 }
780 }
781 }
782
783 /// An image of nothing but zeros, which is what a tentative definition has.
784 fn zeros(&mut self, size: u64) -> DataList {
785 if size == 0 {
786 return DataList::EMPTY;
787 }
788 self.module.push_data(&[Datum::Zero(size)])
789 }
790
791 /// The global a string literal is emitted as, making it the first time it is asked for.
792 pub(crate) fn string(&mut self, id: StrId) -> Symbol {
793 if let Some(&symbol) = self.strings.get(&id) {
794 return symbol;
795 }
796 let literal = &self.tast[id];
797 let bytes = literal.bytes(self.target);
798 let align = literal.encoding.element_width(self.target) / 8;
799 let symbol = self.names.intern(&format!(".Lstr.{}", self.strings.len()));
800
801 let mut global = Global::new(symbol, bytes.len() as u64, align.max(1));
802 global.linkage = IrLinkage::Internal;
803 // Not because the type says so, since a literal is an array of `char` and not of
804 // `const char`, but because writing to one is undefined and every target puts them
805 // somewhere read-only.
806 global.constant = true;
807 let range = self.module.push_bytes(&bytes);
808 global.init = Some(self.module.push_data(&[Datum::Bytes(range)]));
809 self.module.add_global(global);
810 self.strings.insert(id, symbol);
811 symbol
812 }
813
814 /// The name the C library gives a function the program named with the `__builtin_` prefix,
815 /// and nothing for every other name.
816 ///
817 /// `__builtin_abort` is a call to `abort`: the prefix is how a program reaches the function
818 /// the library promises where a macro or a definition of its own has taken the plain name,
819 /// so the two spellings are one function and the one the linker will look for is the short
820 /// one. Which names those are is [`rucc_sema::library_name`]'s to say, since it is the same
821 /// answer the front end declared them out of.
822 fn library_name(&mut self, name: Symbol) -> Option<Symbol> {
823 let library = rucc_sema::library_name(self.names.resolve(name))?;
824 Some(self.names.intern(library))
825 }
826
827 /// The name an object or a function is known by in the object file.
828 pub(crate) fn symbol_of(&mut self, decl: DeclId) -> Symbol {
829 let tast = self.tast;
830 let node = &tast[decl];
831 // The assembler name a declaration wrote, which is the symbol whatever the identifier
832 // spells. It stands for a `static` and for a local one as well as for a name the linker
833 // sees, so it is read before anything else here: a program that renames a name has said
834 // what the symbol is, and the numbering below is for the ones that have not.
835 if let Some(label) = node.asm_label {
836 let spelling: String =
837 tast[label].elements.iter().filter_map(|&unit| char::from_u32(unit)).collect();
838 return self.names.intern(&spelling);
839 }
840 if node.linkage != Linkage::None {
841 let Some(name) = node.name else { return self.names.intern(".Lanon") };
842 return self.library_name(name).unwrap_or(name);
843 }
844 if let Some(&symbol) = self.statics.get(&decl) {
845 return symbol;
846 }
847 // A `static` in a function, or a compound literal with static storage duration. The
848 // number is what makes two of them in two functions two objects.
849 let base = match node.name {
850 Some(name) => self.names.resolve(name).to_string(),
851 None => ".Lanon".to_string(),
852 };
853 let symbol = self.names.intern(&format!("{base}.{}", self.statics.len()));
854 self.statics.insert(decl, symbol);
855 symbol
856 }
857
858 /// Emits the global for an object with static storage duration declared inside a function.
859 pub(crate) fn local_static(&mut self, decl: DeclId) {
860 if !self.done.insert(decl) {
861 return;
862 }
863 match self.tast[decl].kind {
864 // A function declared inside a body is a declaration of the function, not an
865 // object with static storage that happens to be one.
866 DeclKind::Function => self.function(decl),
867 DeclKind::Object => self.object(decl),
868 }
869 }
870
871 /// The value of a constant expression, reporting what folding it reported.
872 fn fold(&mut self, expr: ExprId) -> Option<Const> {
873 let mut eval = Eval::new(self.tast, self.types, self.target, self.names);
874 let folded = eval.constant(expr);
875 let reported = eval.finish();
876 self.diagnostics.extend(reported);
877 match folded {
878 Ok(value) => Some(value),
879 Err(stop) => {
880 if !stop.poisoned {
881 let span = self.tast.expr_span(stop.at);
882 self.unsupported("an initializer this compiler cannot fold", span);
883 }
884 None
885 }
886 }
887 }
888
889 /// Reports a construct the walk does not build IR for yet.
890 pub(crate) fn unsupported(&mut self, what: &str, span: Span) {
891 self.diagnostics.push(
892 Diagnostic::error(format!("{what} is not supported yet"), span).with_code("E0519"),
893 );
894 }
895
896 /// Reports a call to a builtin this compiler knows the name of and does nothing with.
897 ///
898 /// It is its own message rather than [`Self::unsupported`] because the construct is not the
899 /// problem: a call is a call, and what is missing is the one function it goes to. The note is
900 /// what a reader needs, since a builtin is the one name a programmer does not expect to have
901 /// to provide and the alternative to this message is a linker asking them for it.
902 pub(crate) fn missing_builtin(&mut self, spelled: &str, span: Span) {
903 let message = format!("`{spelled}` is not implemented yet");
904 let note = "a call to it would go to a symbol no object file defines, so this is refused \
905 here rather than at the link";
906 self.diagnostics.push(Diagnostic::error(message, span).with_code("E0686").note(note, span));
907 }
908}
909
910/// A count of bytes as a length of a slice of them, saturating on a target whose addresses are
911/// wider than this host's.
912fn cap(bytes: u64) -> usize {
913 usize::try_from(bytes).unwrap_or(usize::MAX)
914}
915
916/// The run of bytes a bit-field entry starts, taken out of the map.
917///
918/// [`None`] when there is no byte at that offset, which means an earlier entry in the same run
919/// already took it, since [`Unit::packed`] puts every byte a field lies in into the map.
920fn take_run(bytes: &mut BTreeMap<u64, u8>, start: u64) -> Option<Vec<u8>> {
921 let mut run = vec![bytes.remove(&start)?];
922 let mut at = start + 1;
923 while let Some(byte) = bytes.remove(&at) {
924 run.push(byte);
925 at += 1;
926 }
927 Some(run)
928}