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