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