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