Skip to main content

rucc_driver/
compile.rs

1//! Running the front end over one file, from the bytes on disk to the typed tree.
2//!
3//! Design: `spec/04-driver-and-cli.md` section 4.3, and the `M2` exit criterion in
4//! `spec/17-milestones.md` that says `--emit=tast` works.
5//!
6//! [`preprocess`](mod@crate::preprocess) stops after phase 4 because `-E` stops there. This
7//! carries on: phase 7, the parse, and the checking. It is one function rather than four composed
8//! ones because of what the four share. The tokens hold interned symbols, the untyped tree holds
9//! tokens, the typed tree holds the untyped tree's spans, and none of them owns the table it is
10//! reading, so one [`Session`] has to outlive all of them and there has to be one place that
11//! holds it.
12
13use std::path::Path;
14
15use rucc_diag::{Diagnostic, Severity, Span};
16use rucc_lex::{Convert, Keywords, PpToken, convert};
17use rucc_sema::{Checker, Context as CheckContext};
18use rucc_session::{EmitKind, FileSystem, Options, Session};
19
20use crate::preprocess::render;
21
22/// What compiling one file produced.
23#[derive(Debug, Clone, PartialEq, Eq)]
24pub struct Compiled {
25    /// The text to write, empty when there was nothing to write or the compilation failed.
26    pub text: String,
27    /// The diagnostics, already rendered, one per element, in the order they were reported.
28    pub messages: Vec<String>,
29    /// How many of them were errors.
30    pub errors: u32,
31}
32
33impl Compiled {
34    /// Whether anything went wrong badly enough that the output should not be used.
35    #[must_use]
36    pub fn failed(&self) -> bool {
37        self.errors > 0
38    }
39}
40
41/// Compiles one file as far as `opts.emit` asks for and renders the result.
42///
43/// `name` is the path as the user wrote it, which is the name every diagnostic about the file
44/// uses. [`EmitKind::Tast`] and [`EmitKind::Ir`] produce text today. Every later kind runs the
45/// same front end and gives back nothing, so that a file with a mistake in it is reported the
46/// same way whichever of them was asked for, rather than compiling silently until the part
47/// that is written notices.
48///
49/// The checking is skipped when the parse reported an error. The two poisoning rules mean a
50/// diagnosed expression produces no further complaints, but a declaration the parser had to skip
51/// past leaves no declaration behind at all, and every later use of that name would be reported
52/// as undeclared. One mistake is worth one message.
53#[must_use]
54pub fn compile(opts: &Options, name: &str, fs: &dyn FileSystem) -> Compiled {
55    let mut sess = Session::new(opts.clone());
56    // Before anything else interns a name. The keyword symbols have to be one unbroken run for
57    // a lookup to be a subtraction, and the preprocessor interns every identifier it reads, so
58    // building this after the expansion would mean building it after `char` had been seen.
59    let keywords = Keywords::new(&mut sess.interner, opts.std, opts.gnu_extensions);
60    let mut diagnostics: Vec<Diagnostic> = Vec::new();
61
62    let bytes = match fs.read(Path::new(name)) {
63        Ok(bytes) => bytes,
64        Err(e) => return failure(format!("{name}: {e}")),
65    };
66    let Ok(file) = sess.sources.add_shared(name, bytes, None) else {
67        return failure(format!("{name}: the source map has no room left for this file"));
68    };
69
70    // Phases 1 to 4. The expanded stream is turned into pp-tokens straight away, because the
71    // include context borrows the source map that rendering a diagnostic reads and the borrow
72    // has to end before anything is rendered.
73    let mut pp = rucc_pp::Preprocessor::new();
74    let predef = rucc_pp::Predef::for_options(opts);
75    let expanded: Vec<PpToken> = {
76        let mut cx = rucc_pp::Context::new(&mut sess.interner, &mut sess.sources, fs, &opts.search);
77        cx.lex = rucc_lex::Options::for_dialect(opts.std, opts.gnu_extensions);
78        if pp.predefine(&sess.target, &predef, &mut cx).is_err() {
79            return failure(format!("{name}: the source map has no room for the built in macros"));
80        }
81        pp.run(file, &mut cx).iter().map(|token| token.to_pp()).collect()
82    };
83    diagnostics.extend(pp.take_diagnostics());
84
85    // Phase 7, which is where a spelling becomes a keyword and a preprocessing number becomes
86    // a constant of a type.
87    let cx = Convert {
88        keywords: &keywords,
89        interner: &sess.interner,
90        target: &sess.target,
91        std: opts.std,
92        gnu: opts.gnu_extensions,
93        pedantic: opts.pedantic,
94    };
95    let (tokens, complaints) = convert(&expanded, &cx);
96    diagnostics.extend(complaints);
97
98    let parsed = rucc_parse::parse(
99        &tokens,
100        rucc_parse::Context {
101            interner: &sess.interner,
102            std: opts.std,
103            gnu: opts.gnu_extensions,
104            pedantic: opts.pedantic,
105            error_limit: opts.error_limit as usize,
106        },
107    );
108    let parse_failed = parsed.diagnostics.iter().any(|d| d.severity.is_fatal());
109    diagnostics.extend(parsed.diagnostics);
110
111    let mut text = String::new();
112    if !parse_failed {
113        let mut checker = Checker::new(
114            &parsed.ast,
115            CheckContext {
116                names: &sess.interner,
117                target: &sess.target,
118                std: opts.std,
119                gnu: opts.gnu_extensions,
120                pedantic: opts.pedantic,
121                error_limit: opts.error_limit as usize,
122            },
123        );
124        checker.check_unit();
125        let checked = checker.finish();
126        if !checked.failed() {
127            match opts.emit {
128                EmitKind::Tast => {
129                    text = rucc_sema::print(&checked.tast, &checked.types, &sess.interner);
130                }
131                EmitKind::Ir => {
132                    let lowered = rucc_lower::lower(
133                        name,
134                        rucc_lower::Context {
135                            tast: &checked.tast,
136                            types: &checked.types,
137                            target: &sess.target,
138                            names: &mut sess.interner,
139                        },
140                    );
141                    // The walk reports what it cannot build, and what it did build is printed
142                    // anyway: a file with one construct missing from it is more use to read
143                    // than nothing at all, and the errors are what stop it being compiled.
144                    let failed = lowered.diagnostics.iter().any(|d| d.severity.is_fatal());
145                    if !failed {
146                        // The verifier runs on everything the walk builds, always. It is the
147                        // one check that a bug in the walk cannot talk its way past, and a
148                        // wrong instruction found here costs a message rather than an hour
149                        // in front of a debugger over the assembly it turned into.
150                        if let Err(errors) = rucc_ir::verify(&lowered.module, &sess.interner) {
151                            for error in errors {
152                                diagnostics.push(internal(&format!("invalid IR, {error}")));
153                            }
154                        } else {
155                            text = rucc_ir::print(&lowered.module, &sess.interner);
156                        }
157                    }
158                    diagnostics.extend(lowered.diagnostics);
159                }
160                _ => {}
161            }
162        }
163        diagnostics.extend(checked.diagnostics);
164    }
165
166    let mut messages = Vec::with_capacity(diagnostics.len());
167    let mut errors = 0;
168    for diag in &diagnostics {
169        if diag.severity.is_fatal()
170            || (diag.severity == Severity::Warning && opts.warnings_are_errors)
171        {
172            errors += 1;
173        }
174        messages.push(render(diag, &sess.sources, opts.warnings_are_errors));
175    }
176    if errors > 0 {
177        // A tree built from a file that did not compile is not a tree anything should read.
178        text.clear();
179    }
180    Compiled { text, messages, errors }
181}
182
183/// Reads one file of IR, checks it, and prints it back.
184///
185/// This is the compiler's own textual IR arriving as an input rather than leaving as an output,
186/// which is what makes the round trip in the M2 exit criterion something to run rather than
187/// something to believe: what the printer wrote is read back, verified, and written again, and
188/// the two files are either the same bytes or they are not.
189///
190/// The verifier runs here for the reason it runs after the walk. A module that was printed by
191/// this compiler has been through it once already, and one that a person edited has not.
192#[must_use]
193pub fn compile_ir(opts: &Options, name: &str, fs: &dyn FileSystem) -> Compiled {
194    let mut sess = Session::new(opts.clone());
195    if opts.emit != EmitKind::Ir {
196        return failure(format!(
197            "{name}: an input of IR can only be emitted as IR, and `--emit={}` asks for what \
198             the C in front of it became",
199            opts.emit.as_str()
200        ));
201    }
202    let bytes = match fs.read(Path::new(name)) {
203        Ok(bytes) => bytes,
204        Err(e) => return failure(format!("{name}: {e}")),
205    };
206    let Ok(text) = std::str::from_utf8(bytes.as_slice()) else {
207        return failure(format!("{name}: this is not text, so it is not IR"));
208    };
209
210    let module = match rucc_ir::parse(text, &mut sess.interner) {
211        Ok(module) => module,
212        Err(error) => {
213            return failure(format!("{name}:{}: {}", error.line, error.message));
214        }
215    };
216    let mut diagnostics: Vec<Diagnostic> = Vec::new();
217    if let Err(errors) = rucc_ir::verify(&module, &sess.interner) {
218        for error in errors {
219            diagnostics.push(invalid(&format!("invalid IR, {error}")));
220        }
221    }
222    let mut messages = Vec::with_capacity(diagnostics.len());
223    for diag in &diagnostics {
224        messages.push(render(diag, &sess.sources, opts.warnings_are_errors));
225    }
226    let errors = u32::try_from(messages.len()).unwrap_or(u32::MAX);
227    let text = if errors > 0 { String::new() } else { rucc_ir::print(&module, &sess.interner) };
228    Compiled { text, messages, errors }
229}
230
231/// A diagnostic about IR that was handed to us rather than built by us.
232fn invalid(message: &str) -> Diagnostic {
233    Diagnostic::error(message.to_owned(), Span::DUMMY).with_code("E0661")
234}
235
236/// A diagnostic about this compiler rather than about the program it was given.
237fn internal(message: &str) -> Diagnostic {
238    Diagnostic::error(format!("internal error: {message}"), Span::DUMMY)
239        .with_code("E0652")
240        .note("this is a bug in rucc rather than in the program, please report it", Span::DUMMY)
241}
242
243/// A result that is nothing but one message, for the failures that happen before there is
244/// anything to compile.
245fn failure(message: String) -> Compiled {
246    Compiled { text: String::new(), messages: vec![format!("rucc: error: {message}")], errors: 1 }
247}
248
249#[cfg(test)]
250mod tests {
251    use rucc_session::{MemoryFileSystem, Std};
252    use rucc_target::Triple;
253
254    use super::*;
255
256    fn options() -> Options {
257        let mut opts = Options::new("x86_64-unknown-linux-gnu".parse::<Triple>().unwrap());
258        opts.emit = EmitKind::Tast;
259        opts
260    }
261
262    fn run(opts: &Options, source: &str) -> Compiled {
263        let mut fs = MemoryFileSystem::new();
264        fs.insert("/main.c", source.to_owned().into_bytes());
265        compile(opts, "/main.c", &fs)
266    }
267
268    /// Options with the compiler's own headers on the search path and nothing else, which is
269    /// what a freestanding compilation is. There is no file system underneath these tests,
270    /// so a header that reached for one would fail to resolve and say so.
271    fn freestanding() -> Options {
272        let mut opts = options();
273        opts.hosted = false;
274        opts.search.push_system(rucc_session::runtime::DIR);
275        opts
276    }
277
278    /// The typed tree of a freestanding `source`, insisting that it compiled cleanly.
279    fn shipped(source: &str) -> String {
280        let result = run(&freestanding(), source);
281        assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
282        result.text
283    }
284
285    /// The typed tree of `source`, insisting that it compiled cleanly.
286    fn tast(source: &str) -> String {
287        let result = run(&options(), source);
288        assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
289        result.text
290    }
291
292    #[test]
293    fn the_shipped_stdarg_declares_a_list_and_the_four_operators() {
294        let text = shipped(concat!(
295            "#include <stdarg.h>\n",
296            "int sum(int n, ...) {\n",
297            "  va_list ap, copy;\n",
298            "  va_start(ap, n);\n",
299            "  va_copy(copy, ap);\n",
300            "  int total = va_arg(ap, int) + va_arg(copy, int);\n",
301            "  va_end(ap);\n",
302            "  va_end(copy);\n",
303            "  return total;\n",
304            "}\n",
305        ));
306        assert!(text.contains("va-start"), "{text}");
307        assert!(text.contains("va-copy"), "{text}");
308        assert!(text.contains("va-arg"), "{text}");
309        assert!(text.contains("va-end"), "{text}");
310    }
311
312    /// glibc includes `<stdarg.h>` this way from every header that declares a `vprintf`, and
313    /// what it wants is the type without the four macro names. Answering the whole header
314    /// would put `va_start` in the way of a program that has its own.
315    #[test]
316    fn stdarg_hands_out_the_type_alone_when_that_is_all_that_was_asked_for() {
317        let text = shipped(concat!(
318            "#define __need___va_list\n",
319            "#include <stdarg.h>\n",
320            "int vprint(const char *f, __gnuc_va_list ap);\n",
321            "#ifdef va_start\n",
322            "#error va_start should not be defined\n",
323            "#endif\n",
324            "#ifdef _VA_LIST_DEFINED\n",
325            "#error va_list should not have been made\n",
326            "#endif\n",
327        ));
328        assert!(text.contains("vprint"), "{text}");
329    }
330
331    /// The same protocol on `<stddef.h>`, which glibc uses far more heavily: `<stdio.h>` asks
332    /// for `size_t` and `NULL` and would be wrong to receive `offsetof` as well.
333    #[test]
334    fn stddef_answers_one_piece_at_a_time_and_the_next_request_still_gets_through() {
335        let text = shipped(concat!(
336            "#define __need_size_t\n",
337            "#include <stddef.h>\n",
338            "#ifdef offsetof\n",
339            "#error offsetof should not be defined yet\n",
340            "#endif\n",
341            "#define __need_ptrdiff_t\n",
342            "#include <stddef.h>\n",
343            "#include <stddef.h>\n",
344            "size_t a;\n",
345            "ptrdiff_t b;\n",
346            "wchar_t c;\n",
347            "max_align_t d;\n",
348            "void *e = NULL;\n",
349            "struct P { int x; long y; };\n",
350            "size_t f = offsetof(struct P, y);\n",
351        ));
352        assert!(text.contains("decl #0 a : unsigned long"), "{text}");
353        assert!(text.contains("decl #1 b : long"), "{text}");
354    }
355
356    #[test]
357    fn the_shipped_limits_and_float_are_the_targets_own_answers() {
358        let text = shipped(concat!(
359            "#include <limits.h>\n",
360            "#include <float.h>\n",
361            "int bits = CHAR_BIT;\n",
362            "long big = LONG_MAX;\n",
363            "int low = INT_MIN;\n",
364            "int radix = FLT_RADIX;\n",
365            "int digits = DBL_MANT_DIG;\n",
366        ));
367        assert!(text.contains("const 8 : int"), "{text}");
368        assert!(text.contains("const 9223372036854775807 : long"), "{text}");
369        assert!(text.contains("const 2 : int"), "{text}");
370        assert!(text.contains("const 53 : int"), "{text}");
371    }
372
373    /// Freestanding, so there is no library header to chain to and `<stdint.h>` writes the
374    /// whole set out itself. The widths are the ones the target picked, which is the only
375    /// reason this header is the compiler's.
376    #[test]
377    fn the_shipped_stdint_writes_the_whole_set_when_there_is_no_library_to_defer_to() {
378        let text = shipped(concat!(
379            "#include <stdint.h>\n",
380            "int64_t a = INT64_C(1);\n",
381            "uint_least16_t b;\n",
382            "intptr_t c;\n",
383            "uintmax_t d = UINTMAX_MAX;\n",
384            "int wide = sizeof(int_fast64_t);\n",
385        ));
386        assert!(text.contains("decl #0 a : long"), "{text}");
387        assert!(text.contains("decl #1 b : unsigned short"), "{text}");
388        assert!(text.contains("decl #2 c : long"), "{text}");
389    }
390
391    #[test]
392    fn the_three_formality_headers_still_have_to_work() {
393        let text = shipped(concat!(
394            "#include <stdbool.h>\n",
395            "#include <stdalign.h>\n",
396            "#include <iso646.h>\n",
397            "#include <stdnoreturn.h>\n",
398            "int t = true and not false;\n",
399            "_Alignas(16) char buf[16];\n",
400            "int a = alignof(long);\n",
401        ));
402        assert!(text.contains("decl #0 t : int"), "{text}");
403        assert!(text.contains("const 8 : unsigned long"), "{text}");
404    }
405
406    /// Including everything twice has to change nothing, because that is what happens in any
407    /// program large enough to matter and a guard that is wrong shows up nowhere else.
408    #[test]
409    fn every_shipped_header_can_be_included_twice() {
410        let mut source = String::new();
411        for _ in 0..2 {
412            for name in rucc_session::runtime::names() {
413                source.push_str(&format!("#include <{name}>\n"));
414            }
415        }
416        source.push_str("int x;\n");
417        let text = shipped(&source);
418        assert!(text.starts_with("decl #0 x : int"), "{text}");
419    }
420
421    #[test]
422    fn a_file_that_is_not_there_says_so_and_produces_nothing() {
423        let fs = MemoryFileSystem::new();
424        let result = compile(&options(), "/nope.c", &fs);
425        assert!(result.failed());
426        assert!(result.messages[0].contains("/nope.c"), "{:?}", result.messages);
427        assert!(result.text.is_empty());
428    }
429
430    #[test]
431    fn an_object_comes_out_with_its_type_its_linkage_and_how_much_of_a_definition_it_is() {
432        let text = tast("int x = 1;\n");
433        let expected = "\
434decl #0 x : int object external static defined
435  init
436    +0
437      const 1 : int
438";
439        assert_eq!(text, expected);
440    }
441
442    #[test]
443    fn the_macros_are_expanded_before_anything_is_parsed() {
444        // The whole pipeline in one line. The bound came out of a macro, so it was expanded,
445        // converted from a preprocessing number to a constant of a type, parsed as an
446        // expression, and folded to the number the array type carries.
447        let text = tast("#define N 2\nint a[N];\n");
448        assert!(text.starts_with("decl #0 a : int[2] object external static tentative"), "{text}");
449    }
450
451    /// A pragma survives the preprocessor on purpose, since what one means is not its
452    /// business, and nothing after it has a place for a `#` in the grammar. `pack` is the one
453    /// the parser reads and every other line is walked past. Both spellings are here because
454    /// they arrive by different routes and only one of them was ever on a line of its own in
455    /// the source.
456    #[test]
457    fn a_pragma_is_not_a_declaration_and_the_parse_walks_past_the_ones_it_does_not_read() {
458        let text = tast(concat!(
459            "#pragma pack(4)\n",
460            "struct s { int a; };\n",
461            "#pragma pack()\n",
462            "int b;\n",
463            "_Pragma(\"GCC visibility push(default)\") int c;\n",
464        ));
465        assert!(text.contains("decl #0 b : int"), "{text}");
466        assert!(text.contains("decl #1 c : int"), "{text}");
467    }
468
469    /// Every number in these two tests was read off gcc 16 on x86-64 under `-std=gnu23`
470    /// rather than reasoned about, which is why they are written as assertions the program
471    /// makes about itself: a compilation with no messages is every one of them holding.
472    ///
473    /// This half is the attributes. `packed` takes the padding out, on the record or on one
474    /// member, `aligned` raises and never lowers, and the two written together are the
475    /// combination that packs and then aligns the whole thing.
476    #[test]
477    fn the_layout_attributes_move_the_members_and_the_record_the_way_gcc_lays_them_out() {
478        tast(concat!(
479            "struct A { char c; int i; } __attribute__((packed));\n",
480            "_Static_assert(sizeof(struct A) == 5 && _Alignof(struct A) == 1, \"A\");\n",
481            "_Static_assert(__builtin_offsetof(struct A, i) == 1, \"A.i\");\n",
482            // `aligned` with nothing in the parentheses is the largest alignment the target
483            // has, which gcc calls BIGGEST_ALIGNMENT and which is sixteen everywhere here.
484            "struct B { char c; int i; } __attribute__((aligned));\n",
485            "_Static_assert(sizeof(struct B) == 16 && _Alignof(struct B) == 16, \"B\");\n",
486            "struct C { char c; int i __attribute__((packed)); };\n",
487            "_Static_assert(sizeof(struct C) == 5 && _Alignof(struct C) == 1, \"C\");\n",
488            "_Static_assert(__builtin_offsetof(struct C, i) == 1, \"C.i\");\n",
489            "struct D { char c; int i; } __attribute__((packed, aligned(4)));\n",
490            "_Static_assert(sizeof(struct D) == 8 && _Alignof(struct D) == 4, \"D\");\n",
491            "_Static_assert(__builtin_offsetof(struct D, i) == 1, \"D.i\");\n",
492            "struct E { char c; _Alignas(8) int i; };\n",
493            "_Static_assert(sizeof(struct E) == 16 && _Alignof(struct E) == 8, \"E\");\n",
494            "_Static_assert(__builtin_offsetof(struct E, i) == 8, \"E.i\");\n",
495            "struct F { char c; int i __attribute__((aligned(8))); };\n",
496            "_Static_assert(sizeof(struct F) == 16 && _Alignof(struct F) == 8, \"F\");\n",
497            // Two the record already had, so the attribute asks for nothing new, and two
498            // where four was already there, so the attribute is ignored rather than obeyed.
499            "struct G { char c; short s; } __attribute__((aligned(2)));\n",
500            "_Static_assert(sizeof(struct G) == 4 && _Alignof(struct G) == 2, \"G\");\n",
501            "struct H { char c; int i; } __attribute__((aligned(2)));\n",
502            "_Static_assert(sizeof(struct H) == 8 && _Alignof(struct H) == 4, \"H\");\n",
503            // `packed` on a member takes the padding out in front of that member alone, so on
504            // the first one it does nothing and on the second one it does all of it.
505            "struct I { [[gnu::packed]] char c; int i; };\n",
506            "_Static_assert(sizeof(struct I) == 8 && _Alignof(struct I) == 4, \"I\");\n",
507            "struct J { char c; [[gnu::packed]] int i; };\n",
508            "_Static_assert(sizeof(struct J) == 5 && _Alignof(struct J) == 1, \"J\");\n",
509            "struct M { char c; int i : 5; int j : 20; } __attribute__((packed));\n",
510            "_Static_assert(sizeof(struct M) == 5 && _Alignof(struct M) == 1, \"M\");\n",
511            "struct N { char c; long long l; } __attribute__((aligned(32)));\n",
512            "_Static_assert(sizeof(struct N) == 32 && _Alignof(struct N) == 32, \"N\");\n",
513            "union L { char c; int i; } __attribute__((packed));\n",
514            "_Static_assert(sizeof(union L) == 4 && _Alignof(union L) == 1, \"L\");\n",
515        ));
516    }
517
518    /// Where a bit-field goes, which packing decides and which is the part of all this that
519    /// is not what the names suggest. A bit-field goes at the next free bit unless that would
520    /// make it span more storage than its own type occupies, and then it moves to the next
521    /// boundary of its alignment. Any packing at all takes that rule out, and `#pragma pack`
522    /// counts even where it lowers nothing, which is the fourth and seventh cases here.
523    ///
524    /// Nothing in the language can be asked where a bit-field is, since `offsetof` refuses one
525    /// and every size below comes out the same either way, so what is asked is the byte a read
526    /// of the field loads from.
527    #[test]
528    fn packing_is_what_decides_whether_a_bit_field_may_straddle_its_own_storage() {
529        // A `char` field after twelve bits, which will not straddle unpacked and does packed.
530        assert_eq!(bit_field_byte("struct s { int x : 12; char y : 6; };"), 2);
531        assert_eq!(
532            bit_field_byte("struct s { int x : 12; char y : 6; } __attribute__((packed));"),
533            1
534        );
535        assert_eq!(
536            bit_field_byte("struct s { int x : 12; __attribute__((packed)) char y : 6; };"),
537            1
538        );
539        assert_eq!(bit_field_byte("#pragma pack(4)\nstruct s { int x : 12; char y : 6; };"), 1);
540        // A thirty bit field after a byte, which is the case the rule was written for.
541        assert_eq!(bit_field_byte("struct s { char x; int y : 30; };"), 4);
542        assert_eq!(bit_field_byte("struct s { char x; int y : 30; } __attribute__((packed));"), 1);
543        // Four is what an `int` asked for anyway, so this caps nothing and still counts.
544        assert_eq!(bit_field_byte("#pragma pack(4)\nstruct s { char x; int y : 30; };"), 1);
545        assert_eq!(bit_field_byte("#pragma pack(2)\nstruct s { char x; int y : 30; };"), 1);
546    }
547
548    /// The byte a read of `s.y` loads from, which is where the bit-field was placed.
549    fn bit_field_byte(record: &str) -> u64 {
550        let source = format!("{record}\nint f(struct s *p) {{ return p->y; }}\n");
551        let body = body(&source);
552        let Some((before, _)) = body.split_once("ptr_add") else { return 0 };
553        let (_, constant) = before.rsplit_once("iconst.i64 ").expect("an offset constant");
554        constant.lines().next().expect("a line").trim().parse().expect("a byte offset")
555    }
556
557    /// An attribute in the middle of a specifier list, which is where a member usually carries
558    /// one and which was read and then thrown away. The `[[...]]` spelling and whatever was
559    /// written in front of the declaration are collected as the list is walked and the
560    /// `__attribute__` spelling is put straight on the specifiers, and the two were assigned
561    /// over each other rather than joined.
562    #[test]
563    fn an_attribute_among_the_specifiers_is_kept_beside_the_ones_written_in_front() {
564        tast(concat!(
565            "struct a { char c; __attribute__((aligned(8))) int i; };\n",
566            "_Static_assert(sizeof(struct a) == 16 && _Alignof(struct a) == 8, \"a\");\n",
567            "_Static_assert(__builtin_offsetof(struct a, i) == 8, \"a.i\");\n",
568            "struct b { char c; __attribute__((packed)) int i; };\n",
569            "_Static_assert(sizeof(struct b) == 5 && _Alignof(struct b) == 1, \"b\");\n",
570            "_Static_assert(__builtin_offsetof(struct b, i) == 1, \"b.i\");\n",
571            "typedef struct { char c; int i; } __attribute__((packed)) c;\n",
572            "_Static_assert(sizeof(c) == 5 && _Alignof(c) == 1, \"c\");\n",
573        ));
574    }
575
576    /// The other half, which is `#pragma pack`. It caps a member's alignment where `packed`
577    /// drops it, so `pack(2)` leaves a `short` where it was and moves an `int`, and it caps a
578    /// member the program asked to align as well, which is where the two differ. It is read
579    /// at the closing brace of the body, so a line written in the middle of one settles the
580    /// whole record rather than the members after it, and `push` and `pop` nest.
581    #[test]
582    fn pragma_pack_caps_every_member_and_is_read_where_the_body_closes() {
583        tast(concat!(
584            "#pragma pack(1)\n",
585            "struct A { char c; int i; };\n",
586            "_Static_assert(sizeof(struct A) == 5 && _Alignof(struct A) == 1, \"A\");\n",
587            "_Static_assert(__builtin_offsetof(struct A, i) == 1, \"A.i\");\n",
588            "#pragma pack()\n",
589            "struct B { char c; int i; };\n",
590            "_Static_assert(sizeof(struct B) == 8 && _Alignof(struct B) == 4, \"B\");\n",
591            "#pragma pack(2)\n",
592            "struct C { char c; int i; double d; };\n",
593            "_Static_assert(sizeof(struct C) == 14 && _Alignof(struct C) == 2, \"C\");\n",
594            "_Static_assert(__builtin_offsetof(struct C, d) == 6, \"C.d\");\n",
595            // A member the program aligned, which `pack` caps and `packed` would not.
596            "struct K { char c; int i __attribute__((aligned(8))); };\n",
597            "_Static_assert(sizeof(struct K) == 6 && _Alignof(struct K) == 2, \"K\");\n",
598            "_Static_assert(__builtin_offsetof(struct K, i) == 2, \"K.i\");\n",
599            // The record's own `aligned` is not a member's, so it is not capped.
600            "struct J { char c; int i; } __attribute__((aligned(8)));\n",
601            "_Static_assert(sizeof(struct J) == 8 && _Alignof(struct J) == 8, \"J\");\n",
602            "#pragma pack()\n",
603            "#pragma pack(push, 1)\n",
604            "struct D { char c; short s; };\n",
605            "_Static_assert(sizeof(struct D) == 3 && _Alignof(struct D) == 1, \"D\");\n",
606            "#pragma pack(pop)\n",
607            "struct E { char c; short s; };\n",
608            "_Static_assert(sizeof(struct E) == 4 && _Alignof(struct E) == 2, \"E\");\n",
609            // Written in the middle of a body, and it still settles the whole record.
610            "struct H { char c;\n",
611            "#pragma pack(1)\n",
612            "  int i; };\n",
613            "_Static_assert(sizeof(struct H) == 5 && _Alignof(struct H) == 1, \"H\");\n",
614            "#pragma pack(1)\n",
615            "struct I { char c;\n",
616            "#pragma pack()\n",
617            "  int i; };\n",
618            "_Static_assert(sizeof(struct I) == 8 && _Alignof(struct I) == 4, \"I\");\n",
619            "#pragma pack()\n",
620            // Nested pushes, each one giving back what the one under it had.
621            "#pragma pack(push, 8)\n",
622            "#pragma pack(push, 1)\n",
623            "struct P { char c; int i; };\n",
624            "_Static_assert(sizeof(struct P) == 5 && _Alignof(struct P) == 1, \"P\");\n",
625            "#pragma pack(pop)\n",
626            "struct Q { char c; int i; };\n",
627            "_Static_assert(sizeof(struct Q) == 8 && _Alignof(struct Q) == 4, \"Q\");\n",
628            "#pragma pack(pop)\n",
629            // A cap above what every member already asks for changes nothing at all.
630            "#pragma pack(16)\n",
631            "struct R { char c; int i; };\n",
632            "_Static_assert(sizeof(struct R) == 8 && _Alignof(struct R) == 4, \"R\");\n",
633            "#pragma pack()\n",
634            "#pragma pack(1)\n",
635            "struct S { char c; int i : 5; int j : 20; };\n",
636            "_Static_assert(sizeof(struct S) == 5 && _Alignof(struct S) == 1, \"S\");\n",
637            "union T { char c; int i; };\n",
638            "_Static_assert(sizeof(union T) == 4 && _Alignof(union T) == 1, \"T\");\n",
639            "#pragma pack()\n",
640        ));
641    }
642
643    /// A line the reader cannot make sense of is a warning and the line is dropped, which is
644    /// what GCC does with one, and these are its words for each of them. The last line is the
645    /// one nothing else would reach, since it stands after every record in the file.
646    #[test]
647    fn a_pack_line_that_is_not_one_is_reported_in_the_words_gcc_uses() {
648        let result = run(
649            &options(),
650            concat!(
651                "#pragma pack 4\n",
652                "#pragma pack(pop)\n",
653                "#pragma pack(3)\n",
654                "#pragma pack(1) junk\n",
655                "#pragma pack(push, 1\n",
656                "#pragma pack(x)\n",
657                // These two are well formed and say nothing. Zero is how a line asks for the
658                // target's own alignments back without writing empty parentheses.
659                "#pragma pack(0)\n",
660                "#pragma pack(push)\n",
661                "struct s { char c; int i; };\n",
662                "#pragma pack(pop)\n",
663                "#pragma pack(pop, foo)\n",
664            ),
665        );
666        let expected = [
667            "missing `(` after `#pragma pack` - ignored",
668            "`#pragma pack (pop)` encountered without matching `#pragma pack (push)`",
669            "alignment must be a small power of two, not 3",
670            "junk at end of `#pragma pack`",
671            "malformed `#pragma pack(push[, id][, <n>])` - ignored",
672            "unknown action `x` for `#pragma pack` - ignored",
673            "`#pragma pack(pop, foo)` encountered without matching `#pragma pack(push, foo)`",
674        ];
675        assert_eq!(result.messages.len(), expected.len(), "{:?}", result.messages);
676        for (message, want) in result.messages.iter().zip(expected) {
677            assert!(message.contains(want), "expected {want:?} in {message:?}");
678        }
679    }
680
681    /// The two typedef spellings of the 128 bit types. gcc offers them as keywords rather
682    /// than as typedefs in a header, which is the only way a program that includes nothing at
683    /// all can still use them, and Apple's `<mach/arm/_structs.h>` is one such program.
684    #[test]
685    fn the_wide_integer_answers_to_all_three_of_its_names() {
686        let text = tast("__uint128_t a; __int128_t b; unsigned __int128 c;\n");
687        assert!(text.contains("decl #0 a : unsigned __int128"), "{text}");
688        assert!(text.contains("decl #1 b : __int128"), "{text}");
689        assert!(text.contains("decl #2 c : unsigned __int128"), "{text}");
690    }
691
692    #[test]
693    fn every_conversion_the_language_performs_is_a_node_in_the_output() {
694        // The point of a typed tree. The source has one operator and the output has the
695        // widening that operator asked for, spelled out, so that nothing downstream has to
696        // work out the conversion rules a second time.
697        let text = tast("long f(int a, long b) { return a + b; }\n");
698        assert!(text.contains("convert arithmetic"), "{text}");
699    }
700
701    #[test]
702    fn a_mistake_in_each_phase_reaches_the_caller_and_writes_no_tree() {
703        for source in [
704            "#error stop\n",
705            "int f(void) { return 1 + ; }\n",
706            "int f(void) { return undeclared; }\n",
707        ] {
708            let result = run(&options(), source);
709            assert!(result.failed(), "expected this to fail:\n{source}");
710            assert!(result.text.is_empty(), "a file that did not compile wrote a tree:\n{source}");
711        }
712    }
713
714    #[test]
715    fn one_undeclared_name_is_one_message_and_not_one_per_use() {
716        // The poisoning rule from `spec/06-lexer-and-parser.md` section 6.8, seen from the
717        // outside. Three uses of a name that was never declared, and the operators over them
718        // say nothing at all.
719        let result = run(&options(), "int f(void) { return nope + nope * nope; }\n");
720        assert_eq!(result.errors, 1, "{:?}", result.messages);
721    }
722
723    #[test]
724    fn a_declaration_the_parser_skipped_does_not_become_an_undeclared_name_as_well() {
725        // The reason the checking is skipped after a failed parse. The parser gave up on the
726        // first line and there is no `x` in the tree, so a checker run over it would report
727        // every use of `x` below as undeclared, which is a second message about one mistake.
728        let result = run(&options(), "int x = ;\nint f(void) { return x; }\n");
729        assert_eq!(result.errors, 1, "{:?}", result.messages);
730    }
731
732    #[test]
733    fn werror_turns_a_warning_into_an_error_in_the_count_and_in_the_word() {
734        let source = "int f(void) { char c = 300; return c; }\n";
735        let plain = run(&options(), source);
736        assert_eq!(plain.errors, 0, "{:?}", plain.messages);
737        assert_eq!(plain.messages.len(), 1, "expected a warning about the narrowed constant");
738        assert!(!plain.text.is_empty(), "a warning is not a reason to write nothing");
739
740        let mut opts = options();
741        opts.warnings_are_errors = true;
742        let strict = run(&opts, source);
743        assert!(strict.failed());
744        assert!(strict.text.is_empty(), "and under -Werror it is a reason to write nothing");
745        for message in &strict.messages {
746            assert!(!message.contains("warning:"), "{message}");
747        }
748    }
749
750    #[test]
751    fn the_dialect_reaches_the_keywords_and_the_checking() {
752        // `typeof` is C23's and GNU's, so the same source is a declaration under one dialect
753        // and a mistake under the other, which is the keyword table being built per dialect.
754        let source = "typeof(1) x;\n";
755        let mut opts = options();
756        opts.std = Std::C23;
757        opts.gnu_extensions = false;
758        assert!(!run(&opts, source).failed(), "{:?}", run(&opts, source).messages);
759
760        opts.std = Std::C17;
761        assert!(run(&opts, source).failed());
762    }
763
764    #[test]
765    fn asking_for_a_kind_that_is_not_written_yet_runs_the_front_end_and_writes_nothing() {
766        let mut opts = options();
767        opts.emit = EmitKind::MirFinal;
768        let result = run(&opts, "int x = 1;\n");
769        assert!(!result.failed(), "{:?}", result.messages);
770        assert!(result.text.is_empty());
771        // And it still finds what the checking finds, so a later kind on a broken file is not
772        // a silent success.
773        assert!(run(&opts, "int f(void) { return undeclared; }\n").failed());
774    }
775
776    /// The IR of `source`, insisting that it compiled cleanly.
777    fn ir(source: &str) -> String {
778        let mut opts = options();
779        opts.emit = EmitKind::Ir;
780        let result = run(&opts, source);
781        assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
782        result.text
783    }
784
785    /// The body of the one function in `source`, which is what most of these are about.
786    fn body(source: &str) -> String {
787        let text = ir(source);
788        let (_, rest) = text.split_once("{\n").expect("a function definition");
789        let (body, _) = rest.rsplit_once("}\n").expect("a function definition");
790        body.to_owned()
791    }
792
793    /// `__builtin_constant_p` is answered in the front end and never reaches the IR.
794    ///
795    /// gcc folds it after optimization, so its answer for an argument that is not written as a
796    /// constant can differ between `-O0` and `-O2`. What is checked here is the front end's
797    /// answer, which is the same at every level, and the four cases where gcc gives the same
798    /// answer at both levels are the ones measured on gcc 16: a literal is one, a variable is
799    /// zero, a string literal is one and the address of an object is zero.
800    #[test]
801    fn builtin_constant_p_is_folded_where_it_is_written_rather_than_called() {
802        let text = ir(concat!(
803            "int g;\n",
804            "int a = __builtin_constant_p(1);\n",
805            "int b = __builtin_constant_p(g);\n",
806            "int c = __builtin_constant_p(\"abc\");\n",
807            "int d = __builtin_constant_p(&g);\n",
808            "int e = __builtin_constant_p(1.5);\n",
809            "int h = __builtin_choose_expr(__builtin_constant_p(3), 11, 22);\n",
810        ));
811        assert!(text.contains("global @a : i32 = 1,"), "{text}");
812        assert!(text.contains("global @b : i32 = 0,"), "{text}");
813        assert!(text.contains("global @c : i32 = 1,"), "{text}");
814        assert!(text.contains("global @d : i32 = 0,"), "{text}");
815        assert!(text.contains("global @e : i32 = 1,"), "{text}");
816        assert!(text.contains("global @h : i32 = 11,"), "{text}");
817        assert!(!text.contains("__builtin_constant_p"), "it is not a call to anything:\n{text}");
818
819        // The argument is not evaluated, which is what gcc does with it as well, so `i` is
820        // still zero. The second constant is the answer, which nothing reads and which the
821        // first pass that looks for dead code will take out.
822        let text = body("int f(void) { int i = 0; __builtin_constant_p(i++); return i; }\n");
823        assert_eq!(text, "block0:\n    %0 = iconst.i32 0\n    %1 = iconst.i32 0\n    return %0\n");
824    }
825
826    /// A library builtin is the library function of the same name, and the call says so.
827    ///
828    /// A program writes `__builtin_strlen` rather than `strlen` to reach the function the C
829    /// library promises where its own name has been taken by a macro, and to say that the usual
830    /// meaning is the one intended. So the name in the program and the name in the object file
831    /// are two different names and the call carries the second one. gcc folds several of these
832    /// when the arguments allow it, which is an optimization on top of a call that is already
833    /// right rather than instead of it, so nothing here depends on any folding happening.
834    #[test]
835    fn a_call_to_a_library_builtin_reaches_the_library_function() {
836        let text = body("void f(void) { __builtin_abort(); }\n");
837        assert_eq!(text, "block0:\n    call @abort() : ()\n    return\n");
838
839        // Nothing declared either of these and nothing had to: the prefix is what says the name
840        // belongs to the implementation, and the type comes out of `features.toml`.
841        let text = ir("int f(const char *s) { return __builtin_puts(s) + __builtin_strlen(s); }\n");
842        assert!(text.contains("call @puts(%0) : (ptr) -> i32"), "{text}");
843        assert!(text.contains("call @strlen(%0) : (ptr) -> i64"), "{text}");
844        assert!(!text.contains("__builtin_"), "the prefix is not part of any name here:\n{text}");
845    }
846
847    /// The two names stay apart, which is what having both of them is for.
848    ///
849    /// The one the program wrote is what the call is checked against and what a diagnostic about
850    /// it says, and the one the library defines is what the call ends up carrying. A compiler
851    /// that kept only the second would report this against `abort`, which is a function the
852    /// program never mentions.
853    #[test]
854    fn a_library_builtin_is_diagnosed_under_the_name_the_program_wrote() {
855        let mut opts = options();
856        opts.emit = EmitKind::Ir;
857        let messages = run(&opts, "void f(void) { __builtin_abort(1); }\n").messages;
858        assert!(
859            messages.iter().any(|m| m.contains("__builtin_abort")),
860            "expected the written name in {messages:?}"
861        );
862    }
863
864    /// A `constexpr` object is a named constant, which is the whole reason the keyword exists.
865    ///
866    /// C23 6.6p8 puts two of them on the list an integer constant expression is built from: one
867    /// of an arithmetic type, and a member of one of a structure or union type. A subscript of
868    /// one is not on the list and is a variably modified type in gcc 16 as well, and every
869    /// number here is what gcc 16 gives on x86-64.
870    #[test]
871    fn a_constexpr_object_is_a_constant_wherever_one_is_required() {
872        let text = ir(concat!(
873            "constexpr int side = 4;\n",
874            "constexpr int wider = side + 1;\n",
875            "constexpr double half = 1.5;\n",
876            "struct point { int x; int y; };\n",
877            "constexpr struct point origin = { 5, 6 };\n",
878            "int square[side * side];\n",
879            "int rectangle[wider];\n",
880            "int rounded[(int)half * 2];\n",
881            "int across[origin.y];\n",
882            "enum named { four = side };\n",
883            "int e = four;\n",
884        ));
885        assert!(text.contains("global @square : bytes 64 ="), "{text}");
886        assert!(text.contains("global @rectangle : bytes 20 ="), "{text}");
887        assert!(text.contains("global @rounded : bytes 8 ="), "{text}");
888        assert!(text.contains("global @across : bytes 24 ="), "{text}");
889        assert!(text.contains("global @e : i32 = 4,"), "{text}");
890
891        // A `const` object is not one of them, which is what makes `int a[n];` a variable
892        // length array in C and is the distinction the keyword was added to draw.
893        let mut opts = options();
894        opts.emit = EmitKind::Ir;
895        let konst = "const int n = 1;\nint a[n];\n";
896        let message = "/main.c:2:5: error: variably modified 'a' at file scope [E0538]";
897        assert_eq!(run(&opts, konst).messages, [message]);
898
899        // Nor is a subscript of one, which gcc 16 refuses in the same words.
900        let subscript = "constexpr int t[3] = { 1, 2, 3 };\nint a[t[1]];\n";
901        assert_eq!(run(&opts, subscript).messages, [message]);
902
903        // And `constexpr` implies `const`, so the address of one is an address of a `const`.
904        let address = "constexpr int c = 3;\nint *p = &c;\n";
905        let warning = "/main.c:2:6: warning: initialization discards 'const' qualifier from \
906             pointer target type [E0514]";
907        assert_eq!(run(&opts, address).messages, [warning]);
908    }
909
910    /// A definition that names its parameters and then declares them under the list.
911    ///
912    /// The declarations say what the types are, 6.9.1p6, and what the function takes is those
913    /// types with the default argument promotions over them, which is what a caller of an
914    /// unprototyped function hands over. A prototype already in scope overrules the promoted
915    /// types, since a header saying `int narrow(char);` over a definition written this way is
916    /// the pairing all the code written this way relies on and 6.7.6.3p15 is read that way by
917    /// every compiler.
918    #[test]
919    fn an_old_style_definition_takes_its_types_from_the_declarations_under_its_list() {
920        // C17, since the default dialect is the one that warns about the form and this is
921        // about what it means rather than about the warning.
922        let mut opts = options();
923        opts.std = Std::C17;
924        let source = concat!(
925            "int add(a, b)\n",
926            "int a;\n",
927            "int b;\n",
928            "{ return a + b; }\n",
929            "int promoted(c)\n",
930            "char c;\n",
931            "{ return c; }\n",
932            "int narrow(char);\n",
933            "int narrow(c)\n",
934            "char c;\n",
935            "{ return c; }\n",
936            "int first(a)\n",
937            "int a[4];\n",
938            "{ return a[0]; }\n",
939        );
940        let result = run(&opts, source);
941        assert_eq!(result.messages, Vec::<String>::new(), "expected this to compile:\n{source}");
942        let text = result.text;
943        assert!(text.contains("add : int(int, int) function external defined"), "{text}");
944        assert!(text.contains("promoted : int(int) function external defined"), "{text}");
945        // The body still sees the `char` it was declared as, whatever the caller hands over.
946        assert!(text.contains("c : char object automatic defined"), "{text}");
947        assert!(text.contains("narrow : int(char) function external defined"), "{text}");
948        // An array parameter is a pointer here as much as it is in a prototype.
949        assert!(text.contains("first : int(int *) function external defined"), "{text}");
950    }
951
952    /// What the two halves of an old-style parameter list can disagree about.
953    ///
954    /// Each of these is a sentence gcc 16 has, and every message below is the one it prints,
955    /// read off it on x86-64 rather than reasoned about. The last two are the dialect: a name
956    /// with no declaration is an `int` in C89 and a diagnostic from C99 on, and the whole form
957    /// left the language in C23, where gcc still takes it and warns.
958    #[test]
959    fn the_two_halves_of_an_old_style_parameter_list_have_to_agree() {
960        let mut opts = options();
961        opts.std = Std::C17;
962        for (source, message) in [
963            ("int f(a, a)\nint a;\n{ return a; }\n", "1:10: error: multiple parameters named 'a'"),
964            (
965                "int f(a)\nint a;\nint b;\n{ return a; }\n",
966                "3:5: error: declaration for parameter 'b' but no such parameter",
967            ),
968            ("int f(a)\nint a;\nint a;\n{ return a; }\n", "3:5: error: redefinition of parameter"),
969            ("int f(a)\nint a = 1;\n{ return a; }\n", "2:5: error: parameter 'a' is initialized"),
970            (
971                "int f(a)\nstatic int a;\n{ return a; }\n",
972                "2:12: error: storage class specified for parameter 'a'",
973            ),
974            (
975                "int f(char);\nint f(a)\nshort a;\n{ return a; }\n",
976                "2:7: error: argument 'a' doesn't match prototype",
977            ),
978        ] {
979            let result = run(&opts, source);
980            assert!(result.failed(), "expected this to fail:\n{source}");
981            assert!(result.messages[0].contains(message), "{:?}", result.messages);
982        }
983
984        // A name the declarations never mention. C89 gave it an `int` and gcc still takes it
985        // in that dialect, and every dialect after it made the same line a diagnostic.
986        let implicit = "int f(a, b)\nint a;\n{ return a + b; }\n";
987        let mut older = options();
988        older.std = Std::C89;
989        assert!(!run(&older, implicit).failed(), "{:?}", run(&older, implicit).messages);
990        let result = run(&opts, implicit);
991        assert!(
992            result.messages[0].contains("1:10: error: type of 'b' defaults to 'int'"),
993            "{:?}",
994            result.messages
995        );
996
997        // C23 took the form out of the language and gcc kept accepting it with a warning, and
998        // a warning is what this is, because the code written this way is not going to be
999        // rewritten and refusing it would put the compiler out of reach of it.
1000        let mut newer = options();
1001        newer.std = Std::C23;
1002        let plain = "int f(a)\nint a;\n{ return a; }\n";
1003        let result = run(&newer, plain);
1004        assert!(!result.failed(), "{:?}", result.messages);
1005        assert_eq!(
1006            result.messages,
1007            ["/main.c:1:5: warning: old-style function definition [E0412]"]
1008        );
1009        assert!(run(&opts, plain).messages.is_empty(), "and nothing to say in the dialects before");
1010    }
1011
1012    /// A type nothing is ever an object of is a type `sizeof` still has to answer about, which
1013    /// is what `991014-1.c` in the gcc.c-torture execution suite asks.
1014    ///
1015    /// The limit is `PTRDIFF_MAX` and it is the same one for an array and for a record, so a
1016    /// record of every byte an object may have is laid out and one byte more is refused. All
1017    /// four numbers are what gcc 16 gives on x86-64.
1018    #[test]
1019    fn a_type_is_refused_when_it_passes_the_largest_object_and_not_before() {
1020        let text = ir(concat!(
1021            "struct huge_struct { short buf[(1L << 62) - 256]; int a, b, c, d; };\n",
1022            "struct brim { char buf[9223372036854775807L]; };\n",
1023            "struct bitty { char buf[9223372036854775800L]; int x : 1; };\n",
1024            "unsigned long h = sizeof(struct huge_struct);\n",
1025            "unsigned long b = sizeof(struct brim);\n",
1026            "unsigned long y = sizeof(struct bitty);\n",
1027        ));
1028        assert!(text.contains("global @h : i64 = 9223372036854775312,"), "{text}");
1029        assert!(text.contains("global @b : i64 = 9223372036854775807,"), "{text}");
1030        assert!(text.contains("global @y : i64 = 9223372036854775804,"), "{text}");
1031
1032        let mut opts = options();
1033        opts.emit = EmitKind::Ir;
1034        let over = "struct over { char buf[9223372036854775800L]; char x[8]; };\n";
1035        let message = "/main.c:1:1: error: type 'struct over' is too large [E0560]";
1036        assert_eq!(run(&opts, over).messages, [message]);
1037        let array = "struct wide { short buf[1L << 62]; };\n";
1038        let message = "/main.c:1:25: error: size of array 'buf' exceeds \
1039             maximum object size '9223372036854775807' [E0537]";
1040        assert_eq!(run(&opts, array).messages[0], message);
1041    }
1042
1043    /// A byte in the source that is not part of a character, which only a literal may hold.
1044    ///
1045    /// The source cannot be a `&str` here, which is the whole point: a file is bytes and only
1046    /// mostly text.
1047    fn compile_bytes(source: &[u8]) -> Compiled {
1048        let mut opts = options();
1049        opts.emit = EmitKind::Ir;
1050        let mut fs = MemoryFileSystem::new();
1051        fs.insert("/main.c", source.to_vec());
1052        compile(&opts, "/main.c", &fs)
1053    }
1054
1055    /// A raw byte inside a string literal is that byte, which gcc has always taken and which is
1056    /// the only place in a source file where a byte does not have to be part of a character.
1057    /// Replacing it would give the object three bytes rather than one, since the replacement
1058    /// character is three bytes of UTF-8, so the object would not be the one that was written
1059    /// even where the diagnostic is ignored. Anywhere else the byte is still a mistake, which
1060    /// is where gcc draws the same line.
1061    #[test]
1062    fn a_byte_that_is_not_a_character_is_kept_in_a_literal_and_refused_outside_one() {
1063        let mut source = b"char s[] = \"a".to_vec();
1064        source.push(0xff);
1065        source.extend_from_slice(b"b\";\nchar c = '");
1066        source.push(0xff);
1067        source.extend_from_slice(b"';\n");
1068        let result = compile_bytes(&source);
1069        assert_eq!(result.messages, Vec::<String>::new(), "a raw byte in a literal is that byte");
1070        assert!(result.text.contains(r#"bytes "a\ffb\00""#), "{}", result.text);
1071        // Plain `char` is signed on this target, so the constant is minus one rather than 255.
1072        assert!(result.text.contains("global @c : i8 = -1,"), "{}", result.text);
1073
1074        let mut stray = b"int a".to_vec();
1075        stray.push(0xff);
1076        stray.extend_from_slice(b" = 1;\n");
1077        let result = compile_bytes(&stray);
1078        assert!(
1079            result.messages.iter().any(|m| m.contains("source is not valid UTF-8 here")),
1080            "{:?}",
1081            result.messages
1082        );
1083    }
1084
1085    #[test]
1086    fn an_object_becomes_a_global_with_an_image_and_a_function_becomes_a_func() {
1087        let text = ir("int x = 7;\nint add(int a, int b) { return a + b; }\n");
1088        assert!(text.contains("global @x : i32 = 7, align 4, linkage(external)\n"), "{text}");
1089        let expected = "\
1090func @add(i32, i32) -> i32, linkage(external) {
1091block0(%0: i32, %1: i32):
1092    %2 = add.nsw %0, %1
1093    return %2
1094}
1095";
1096        assert!(text.contains(expected), "{text}");
1097    }
1098
1099    #[test]
1100    fn a_local_nothing_takes_the_address_of_is_a_value_and_never_a_stack_slot() {
1101        let text = body("int f(int n) { int a = n + 1; int b = a * 2; return a + b; }\n");
1102        assert!(!text.contains("alloca"), "{text}");
1103        assert!(!text.contains("load"), "{text}");
1104        assert!(!text.contains("store"), "{text}");
1105    }
1106
1107    #[test]
1108    fn a_local_whose_address_is_taken_gets_a_slot_in_the_entry_block() {
1109        let text = body("int g(int *);\nint f(void) { int a = 1; return g(&a); }\n");
1110        let expected = "\
1111block0:
1112    %0 = alloca, size 4, align 4
1113    %1 = iconst.i32 1
1114    store %1 -> %0, align 4
1115    %2 = call @g(%0) : (ptr) -> i32
1116    return %2
1117";
1118        assert_eq!(text, expected);
1119    }
1120
1121    #[test]
1122    fn a_loop_carries_what_it_changes_as_block_parameters() {
1123        // The whole point of building SSA during the walk rather than after it: `i` and
1124        // `total` are values that arrive on an edge, and neither has ever been in memory.
1125        let text = body(
1126            "int f(int n) {\n  int total = 0;\n  for (int i = 0; i < n; i++) total += i;\n  \
1127             return total;\n}\n",
1128        );
1129        assert!(!text.contains("alloca"), "{text}");
1130        assert!(text.contains("block1(%3: i32, %4: i32):"), "{text}");
1131        assert!(text.contains("jump block1("), "{text}");
1132    }
1133
1134    #[test]
1135    fn a_comparison_used_as_a_condition_is_not_widened_and_narrowed_again() {
1136        let text = body("int f(int a, int b) { if (a < b) return 1; return 0; }\n");
1137        assert!(text.contains("icmp slt %0, %1"), "{text}");
1138        assert!(!text.contains("zext"), "{text}");
1139    }
1140
1141    #[test]
1142    fn the_right_side_of_a_short_circuit_is_in_a_block_of_its_own() {
1143        let text = body("int f(int a, int b) { return a && b; }\n");
1144        let expected = "\
1145block0(%0: i32, %1: i32):
1146    %2 = iconst.i32 0
1147    %3 = icmp ne %0, %2
1148    %4 = iconst.i1 0
1149    br_if %3, block1, block2(%4)
1150
1151block1:
1152    %5 = iconst.i32 0
1153    %6 = icmp ne %1, %5
1154    jump block2(%6)
1155
1156block2(%7: i1):
1157    %8 = zext.i32 %7
1158    return %8
1159";
1160        assert_eq!(text, expected);
1161    }
1162
1163    #[test]
1164    fn code_after_a_return_is_not_built_and_does_not_leave_an_empty_block_behind() {
1165        let text = body("int f(int a) { if (a) return 1; else return 2; return 3; }\n");
1166        // Three blocks, the test and the two arms. The join the `return 3` would need is
1167        // never created, because a block nothing branches to is not a block.
1168        assert!(!text.contains("block3"), "{text}");
1169        assert!(!text.contains("iconst.i32 3"), "{text}");
1170    }
1171
1172    #[test]
1173    fn falling_off_the_end_returns_zero_from_main_and_nothing_from_a_void_function() {
1174        assert!(body("int main(void) { }\n").contains("iconst.i32 0\n    return"));
1175        assert_eq!(body("void f(void) { }\n"), "block0:\n    return\n");
1176        assert!(body("int f(void) { }\n").contains("unreachable"));
1177    }
1178
1179    #[test]
1180    fn a_structure_is_copied_rather_than_held_in_a_value() {
1181        let text = body(
1182            "struct point { int x, y; };\n\
1183             int f(void) { struct point p = { 1, 2 }; struct point q = p; return q.x; }\n",
1184        );
1185        assert!(text.contains("memcpy"), "{text}");
1186    }
1187
1188    #[test]
1189    fn an_initializer_that_leaves_part_of_an_object_unwritten_zeroes_it_first() {
1190        let text = body("int f(void) { int a[4] = { 1 }; return a[3]; }\n");
1191        assert!(text.contains("memset"), "{text}");
1192    }
1193
1194    #[test]
1195    fn a_switch_is_one_branch_and_a_case_that_falls_through_carries_what_it_wrote() {
1196        let text = body(
1197            "int f(int x) { int r = 0; switch (x) { case 1: r = 1; case 2: r += 2; break; \
1198             default: r = 4; } return r; }\n",
1199        );
1200        let expected = "\
1201block0(%0: i32):
1202    %1 = iconst.i32 0
1203    switch %0, block1, [1 => block2, 2 => block3(%1)]
1204
1205block1:
1206    %2 = iconst.i32 4
1207    jump block4(%2)
1208
1209block2:
1210    %3 = iconst.i32 1
1211    jump block3(%3)
1212
1213block3(%4: i32):
1214    %5 = iconst.i32 2
1215    %6 = add.nsw %4, %5
1216    jump block4(%6)
1217
1218block4(%7: i32):
1219    return %7
1220";
1221        assert_eq!(text, expected);
1222    }
1223
1224    #[test]
1225    fn a_case_range_is_tested_for_rather_than_put_in_the_table() {
1226        // GNU's `case 1 ... 9`. Nine table entries would be nine here and four billion for the
1227        // range a program is allowed to write, so it is a subtraction and one unsigned compare.
1228        let text = body("int f(int x) { switch (x) { case 1 ... 9: return 1; } return 0; }\n");
1229        assert!(text.contains("%2 = sub %0, %1"), "{text}");
1230        assert!(text.contains("icmp ule"), "{text}");
1231        assert!(!text.contains("switch"), "{text}");
1232    }
1233
1234    #[test]
1235    fn break_leaves_the_switch_and_continue_leaves_the_loop_around_it() {
1236        let text = body(
1237            "int f(int n) { int t = 0; for (int i = 0; i < n; i++) { switch (i) { \
1238             case 0: continue; case 1: break; default: t += i; } t++; } return t; }\n",
1239        );
1240        // The `continue` goes to the step and the `break` goes to the `t++` after the switch,
1241        // which is also where the default falls out to.
1242        assert!(text.contains("switch %3, block4, [0 => block5, 1 => block6]"), "{text}");
1243        assert!(text.contains("block5:\n    jump block7("), "{text}");
1244        assert!(text.contains("block6:\n    jump block8("), "{text}");
1245    }
1246
1247    #[test]
1248    fn a_switch_with_nothing_to_branch_on_still_runs_what_comes_after_it() {
1249        assert_eq!(body("void f(int x) { switch (x) { } }\n"), "block0(%0: i32):\n    return\n");
1250    }
1251
1252    #[test]
1253    fn a_label_a_loop_is_only_entered_through_builds_the_loop_around_it() {
1254        // A branch into the middle of a loop that nothing else reaches, the Duff's device shape.
1255        // The `while` is not reached in order, so the walk starts a block nothing branches to and
1256        // builds it from there. What comes out is the loop with an edge straight into its body,
1257        // and the header that nothing arrives at is pruned.
1258        let text = body(
1259            "int f(int x, int n) { switch (x) { case 1: break; while (n) { case 2: n--; } } \
1260             return n; }\n",
1261        );
1262        // `case 2` lands on the body, `case 1` and the default land on the return, and the test
1263        // at the bottom of the loop comes back round to the body.
1264        assert!(text.contains("switch %0, block1(%1), [1 => block2, 2 => block3(%1)]"), "{text}");
1265        assert!(text.contains("block3(%3: i32):\n    %4 = iconst.i32 1"), "{text}");
1266        assert!(text.contains("block5:\n    jump block3("), "{text}");
1267    }
1268
1269    #[test]
1270    fn a_goto_into_a_loop_body_enters_it_without_the_test() {
1271        // The same thing through a `goto`. The first pass through the body runs whatever the
1272        // label is on, and only then does the loop reach its own test.
1273        let text = body("int f(int x, int n) { goto in; while (n) { in: n--; } return n; }\n");
1274        assert!(text.starts_with("block0(%0: i32, %1: i32):\n    jump block1(%1)"), "{text}");
1275        assert!(text.contains("block1(%2: i32):\n    %3 = iconst.i32 1"), "{text}");
1276        assert!(text.contains("br_if %7, block3, block4"), "{text}");
1277    }
1278
1279    #[test]
1280    fn a_goto_is_a_jump_to_the_block_the_label_starts() {
1281        let text = body("int f(int x) { int r = 0; if (x) goto out; r = 1; out: return r; }\n");
1282        // Both edges into `out` carry what `r` holds on the way, and neither is a stack slot.
1283        assert!(!text.contains("alloca"), "{text}");
1284        assert!(text.contains("block3(%4: i32):\n    return %4"), "{text}");
1285        assert_eq!(text.matches("jump block3(").count(), 2, "{text}");
1286    }
1287
1288    #[test]
1289    fn a_backward_goto_is_a_loop_and_carries_what_it_changes() {
1290        let text =
1291            body("int f(int n) { int i = 0; again: if (i < n) { i++; goto again; } return i; }\n");
1292        assert!(!text.contains("alloca"), "{text}");
1293        assert!(text.contains("block1(%2: i32):"), "{text}");
1294        assert!(text.contains("jump block1(%5)"), "{text}");
1295    }
1296
1297    #[test]
1298    fn a_label_nothing_reaches_is_taken_out_rather_than_left_for_the_verifier() {
1299        // A block nothing branches to is not a legal function, and which labels are dead is not
1300        // known until the last statement has been walked, since the `goto` is allowed to be it.
1301        assert_eq!(
1302            body("int f(int x) { return x; spare: return 0; }\n"),
1303            "block0(%0: i32):\n    return %0\n"
1304        );
1305    }
1306
1307    #[test]
1308    fn a_bit_field_is_read_by_loading_the_bytes_it_lies_in_and_shifting() {
1309        let text = body(
1310            "struct s { unsigned a : 3; signed b : 5; };\nint f(struct s *p) { return p->b; }\n",
1311        );
1312        // One byte holds both fields, and the signed one needs no mask: shifting it down
1313        // arithmetically is what says its top bit is a sign.
1314        assert_eq!(
1315            text,
1316            "\
1317block0(%0: ptr):
1318    %1 = load.i8 %0, align 1
1319    %2 = iconst.i8 3
1320    %3 = ashr %1, %2
1321    %4 = sext.i32 %3
1322    return %4
1323"
1324        );
1325    }
1326
1327    #[test]
1328    fn a_store_to_a_bit_field_does_not_write_a_byte_it_has_no_bit_in() {
1329        // C11 says an ordinary member beside a bit-field is a memory location of its own, so
1330        // the four byte store this would take is a data race in a program that has none. The
1331        // three bytes of `a` go in as two and one, and `c` is not touched.
1332        let text =
1333            body("struct s { int a : 24; char c; };\nvoid f(struct s *p, int v) { p->a = v; }\n");
1334        assert_eq!(
1335            text,
1336            "\
1337block0(%0: ptr, %1: i32):
1338    %2 = iconst.i32 16777215
1339    %3 = and %1, %2
1340    %4 = trunc.i16 %3
1341    store %4 -> %0, align 2
1342    %5 = iconst.i32 16
1343    %6 = lshr %3, %5
1344    %7 = trunc.i8 %6
1345    %8 = iconst.i64 2
1346    %9 = ptr_add %0, %8
1347    store %7 -> %9, align 1
1348    return
1349"
1350        );
1351    }
1352
1353    #[test]
1354    fn what_an_assignment_to_a_bit_field_is_worth_is_what_fits_in_it() {
1355        let text =
1356            body("struct s { unsigned b : 5; };\nunsigned f(struct s *p) { return p->b = 33; }\n");
1357        // 33 does not fit in five bits, and 1 is both what goes in the field and what the
1358        // assignment is worth.
1359        assert!(text.contains("%3 = iconst.i8 31\n    %4 = and %2, %3"), "{text}");
1360        assert!(text.ends_with("%9 = zext.i32 %4\n    return %9\n"), "{text}");
1361    }
1362
1363    #[test]
1364    fn an_assignment_a_statement_throws_away_builds_none_of_what_it_is_worth() {
1365        // The value of an assignment to a bit-field takes a shift to build, and a statement
1366        // has no use for it. Nothing here reads back what was stored.
1367        let text = body("struct s { signed b : 5; };\nvoid f(struct s *p) { p->b = 3; }\n");
1368        assert_eq!(text.matches("ashr").count(), 0, "{text}");
1369        assert!(text.ends_with("store %8 -> %0, align 1\n    return\n"), "{text}");
1370    }
1371
1372    #[test]
1373    fn a_bit_field_in_an_initializer_goes_in_over_bytes_that_were_zeroed_first() {
1374        // A bit-field writes part of a byte and leaves the rest of it alone, so the object has
1375        // to be zero before it goes in or what the initializer did not name is whatever the
1376        // stack held.
1377        let text = body(
1378            "struct s { int a : 3; int b; };\nint f(void) { struct s v = { 1 }; return v.b; }\n",
1379        );
1380        assert!(text.contains("memset %0, %1, size 8, align 4"), "{text}");
1381    }
1382
1383    #[test]
1384    fn the_image_of_a_static_bit_field_is_the_bytes_the_fields_share() {
1385        // Two fields in one byte are not two entries in the image, because an image is written
1386        // in bytes: they are the byte they are both in.
1387        let text = ir("struct s { unsigned a : 3; unsigned b : 5; } g = { 1, 2 };\n");
1388        assert!(
1389            text.contains("global @g : bytes 4 = { bytes \"\\11\", zero 3 }, align 4"),
1390            "{text}"
1391        );
1392    }
1393
1394    #[test]
1395    fn an_initialized_flexible_array_member_makes_the_object_larger_than_its_type() {
1396        // `sizeof` answers without the array and the definition has to hold what was written, so
1397        // the object is the size of its image. gcc 16 gives these four, three and two bytes and
1398        // so does this. The image used to be written at the size the type had, which left the
1399        // verifier looking at twenty bytes going into four.
1400        let text = ir(concat!(
1401            "struct a { int i; int j[]; } x = { 1, { 2, 0, 2, 3 } };\n",
1402            "struct b { char c; char p[]; } y = { 'o', \"wx\" };\n",
1403            "struct c { char c; char p[]; } z = { '9', { 'e', 'b' } };\n",
1404            "char s[2] = \"hi\";\n",
1405        ));
1406        assert!(
1407            text.contains("global @x : bytes 20 = { i32 1, i32 2, i32 0, i32 2, i32 3 }"),
1408            "{text}"
1409        );
1410        assert!(text.contains("global @y : bytes 4 = { i8 111, bytes \"wx\\00\" }"), "{text}");
1411        assert!(text.contains("global @z : bytes 3 = { i8 57, i8 101, i8 98 }"), "{text}");
1412        // The array with a length of its own still cuts the literal down to it, which is the
1413        // one case in C where a string initializer drops its terminator.
1414        assert!(text.contains("global @s : bytes 2 = { bytes \"hi\" }"), "{text}");
1415    }
1416
1417    #[test]
1418    fn a_definition_takes_a_parameter_it_left_unnamed() {
1419        // The entry block's parameters are the definition's, and one the front end dropped for
1420        // having no name left the two lists different lengths, which the walk read as an
1421        // old-style definition and refused. gcc has taken these for far longer than C23 has.
1422        let text = ir("int f(int a, int) { return a; }\n");
1423        assert!(text.contains("func @f(i32, i32) -> i32"), "{text}");
1424        assert!(text.contains("block0(%0: i32, %1: i32):"), "{text}");
1425
1426        // The unnamed one first, so that the named one is the second parameter of the entry
1427        // block and not the first: the list says the order and not only how many there are.
1428        let text = ir("int g(int, int n) { return n; }\n");
1429        assert!(text.contains("block0(%0: i32, %1: i32):\n    return %1\n"), "{text}");
1430    }
1431
1432    #[test]
1433    fn an_assignment_of_a_structure_is_the_object_it_wrote() {
1434        // `d = e = c` used to be refused, because the middle assignment is a value of structure
1435        // type and the walk had nowhere to read one from. What an assignment is worth is the
1436        // value it stored, so the object it stored into is the answer and the chain is three
1437        // copies out of the one source with no temporary in it.
1438        let text = body(concat!(
1439            "struct s { int f; int g; };\n",
1440            "void h(struct s *a, struct s *c, struct s *d, struct s *e)\n",
1441            "{ *d = *e = a[0] = *c; }\n",
1442        ));
1443        assert_eq!(text.matches("memcpy").count(), 3, "{text}");
1444        assert!(text.contains("memcpy %8, %1, size 8, align 4\n"), "{text}");
1445        assert!(text.contains("memcpy %3, %8, size 8, align 4\n"), "{text}");
1446        assert!(text.contains("memcpy %2, %3, size 8, align 4\n"), "{text}");
1447    }
1448
1449    #[test]
1450    fn a_string_literal_stops_at_the_end_of_the_array_it_is_filling() {
1451        // The excess used to be laid into the object anyway, so the row after was written over
1452        // and the image refused the entry that came to it. C 6.7.10p14 says the terminator goes
1453        // in only if there is room for it, and gcc discards the rest of a literal that is longer
1454        // still, which is what the first of these is and why it warns.
1455        let mut opts = options();
1456        opts.emit = EmitKind::Ir;
1457        let result = run(
1458            &opts,
1459            concat!(
1460                "const char a[2][3] = { \"1234\", \"xyz\" };\n",
1461                "static const char b[3][5] = { \"12345\", \"678\", \"9\" };\n",
1462                "union u { struct { char x[4]; char y[4]; }; struct { char z[8]; }; };\n",
1463                "const union u c = { { \"1234\", \"567\" } };\n",
1464            ),
1465        );
1466        let text = result.text;
1467        assert_eq!(
1468            result.messages,
1469            ["/main.c:1:24: warning: initializer-string for array of 'const char' is too long \
1470              (5 chars into 3 available) [E0637]"]
1471        );
1472        assert!(text.contains("global @a : bytes 6 = { bytes \"123\", bytes \"xyz\" }"), "{text}");
1473        assert!(
1474            text.contains(
1475                "global @b : bytes 15 = { bytes \"12345\", bytes \"678\\00\", zero 1, \
1476                 bytes \"9\\00\", zero 3 }"
1477            ),
1478            "{text}"
1479        );
1480        // The eight bytes are four, three and a terminator, and then the byte the shorter
1481        // literal left for the string in the other member of the union to end at.
1482        assert!(
1483            text.contains("global @c : bytes 8 = { bytes \"1234\", bytes \"567\\00\" }"),
1484            "{text}"
1485        );
1486    }
1487
1488    #[test]
1489    fn a_cast_of_a_record_to_its_own_type_is_the_object_that_was_cast() {
1490        // gcc accepts one and does nothing with it, which sema already had. Lowering asked for
1491        // the object under it and had no arm for a cast, so `(struct s)x` in an initializer was
1492        // refused with E0519. It is one copy out of the object named, not two.
1493        let text = body(concat!(
1494            "struct s { int a, b; };\nstruct v { struct s s; int t; };\n",
1495            "void g(struct v *);\n",
1496            "void f(struct s *p) { struct v w = { (struct s)*p, 5 }; g(&w); }\n",
1497        ));
1498        assert_eq!(text.matches("memcpy").count(), 1, "{text}");
1499    }
1500
1501    #[test]
1502    fn a_compound_literal_read_in_a_static_initializer_lays_its_bytes_into_the_image() {
1503        // C 6.7.11p4 says a compound literal at file scope has static storage duration, which
1504        // makes it a constant element, and tcc and c-testsuite both write one. Sema used to call
1505        // it a non constant because reading it is a node of its own and the read was what it
1506        // looked at, and lowering had no way to put an object where it wanted a number.
1507        let text = ir(concat!(
1508            "struct s { int x; };\n",
1509            "struct t { struct s s; int o; } a = { (struct s){ 2 }, 3 };\n",
1510            "int n = (int){ 7 };\n",
1511            "struct u { struct s p; struct s q; } b = { (struct s){ 1 }, (struct s){ } };\n",
1512        ));
1513        assert!(text.contains("global @a : bytes 8 = { i32 2, i32 3 }"), "{text}");
1514        assert!(text.contains("global @n : i32 = 7,"), "{text}");
1515        // The second literal names nothing, so what it puts in is the zeros of its own size and
1516        // not the tail of the object it went in, which would have been the same bytes by luck.
1517        assert!(text.contains("global @b : bytes 8 = { i32 1, zero 4 }"), "{text}");
1518    }
1519
1520    #[test]
1521    fn the_address_of_a_compound_literal_asks_for_the_object_it_points_at() {
1522        // Nothing declares a compound literal, so the reference is the only thing that can ask
1523        // for it to be emitted. The image named `.Lanon.0` and the module defined no such
1524        // symbol, which the link would have been the first to find out.
1525        let text = ir("struct s { int x; };\nstruct s *q = &(struct s){ 9 };\n");
1526        assert!(text.contains("global @.Lanon.0 : i32 = 9, align 4, linkage(internal)"), "{text}");
1527        assert!(text.contains("global @q : bytes 8 = { addr.8 @.Lanon.0 }"), "{text}");
1528    }
1529
1530    #[test]
1531    fn an_object_of_no_size_at_all_has_an_image_with_nothing_in_it() {
1532        // A zero length array, which gcc allows and real code uses as the tail of a structure.
1533        // The image is there and holds nothing, which is not the global that has no image at
1534        // all, and the IR reader used to stop on the empty one.
1535        let text = ir("unsigned char foo[1][0];\n");
1536        assert!(text.contains("global @foo : bytes 0 = {}, align 1"), "{text}");
1537    }
1538
1539    #[test]
1540    fn a_null_pointer_in_an_image_is_the_bits_an_address_has_room_for() {
1541        // `NULL` in a static initializer, which every program has. The IR type is `ptr` and a
1542        // `ptr` has no width of its own, so the width the bits are cut to is the target's.
1543        let text = ir("void *p = 0;\nchar *q = (char *) 4096;\n");
1544        assert!(text.contains("global @p : i64 = 0, align 8"), "{text}");
1545        assert!(text.contains("global @q : i64 = 4096, align 8"), "{text}");
1546    }
1547
1548    #[test]
1549    fn an_object_another_module_defines_may_be_one_that_cannot_be_written_through() {
1550        // Which the verifier used to refuse, having read a declaration as a definition with
1551        // nothing in it. `extern const` is how a program names something in the library's read
1552        // only data, and glibc and Darwin both have one in a header a real program includes.
1553        let text = ir("extern const int limit;\nint f(void) { return limit; }\n");
1554        assert!(
1555            text.contains("global @limit : bytes 4, align 4, linkage(external), constant"),
1556            "{text}"
1557        );
1558    }
1559
1560    #[test]
1561    fn a_conditional_whose_value_is_an_object_answers_where_the_object_is() {
1562        // A structure is not a value in the IR, so the two arms cannot be joined as one. The
1563        // addresses can, and the answer is the address of whichever arm was taken rather than
1564        // a copy of it into a third place: both arms outlive the expression, so a copy would
1565        // be one nothing could observe. SQLite's parser writes one of these.
1566        let text = body(
1567            "\
1568struct s { int a, b; };
1569struct s pick(int c, struct s x, struct s y) { return c ? x : y; }
1570",
1571        );
1572        // The join takes an address, each arm hands it the one it has, and nothing is copied.
1573        assert!(text.contains("block3(%7: ptr)"), "{text}");
1574        assert!(text.contains("jump block3(%3)") && text.contains("jump block3(%4)"), "{text}");
1575        assert!(!text.contains("memcpy"), "the arms are joined rather than copied: {text}");
1576    }
1577
1578    #[test]
1579    fn a_structure_that_fits_in_registers_travels_as_the_registers_it_fits_in() {
1580        // `struct pair` is two eightbytes on SysV, one of them integer, so the signature says
1581        // one `i64` in each direction and the body takes the object apart and puts it back
1582        // together around the call.
1583        let text = ir("\
1584struct pair { int a, b; };
1585struct pair make(int a, int b);
1586struct pair twice(struct pair p) { return make(p.a, p.b); }
1587");
1588        assert!(text.contains("func @make(i32, i32) -> i64"), "{text}");
1589        assert!(text.contains("func @twice(i64) -> i64"), "{text}");
1590    }
1591
1592    #[test]
1593    fn a_structure_too_large_for_the_registers_travels_as_where_its_bytes_are() {
1594        // Over two eightbytes the caller passes the bytes in the argument area, which is
1595        // `byval`, and passes somewhere to write the return value, which is `sret`. Neither is
1596        // a parameter the program wrote and both are parameters the function has.
1597        let text = ir("\
1598struct big { double v[8]; };
1599struct big grow(struct big b);
1600struct big twice(struct big b) { return grow(grow(b)); }
1601");
1602        assert!(
1603            text.contains("func @grow(ptr sret(64, align 8), ptr byval(64, align 8))"),
1604            "{text}"
1605        );
1606        assert!(text.contains("block0(%0: ptr, %1: ptr):"), "{text}");
1607        // The inner call writes into a slot and the outer one reads the same slot, so the
1608        // object between the two calls is never copied anywhere.
1609        assert_eq!(text.matches("call @grow").count(), 2, "{text}");
1610    }
1611
1612    #[test]
1613    fn a_structure_passed_to_a_variadic_function_says_so_at_the_call() {
1614        // The bytes travel in the argument area the same way they would for a parameter, and
1615        // `printf` has no parameter there to say it on, so the call says it instead. The one
1616        // that fits in registers says nothing, because travelling as the registers it fits in
1617        // is what an argument does when nothing says otherwise.
1618        let text = ir("\
1619struct big { double v[8]; };
1620struct pair { int a, b; };
1621int p(const char *, ...);
1622int f(struct big b, struct pair q) { return p(\"\", 1, b, q); }
1623");
1624        assert!(
1625            text.contains("call @p(%4, %5, %2 byval(64, align 8), %6) : (ptr, ...) -> i32"),
1626            "{text}"
1627        );
1628    }
1629
1630    #[test]
1631    fn what_a_call_produced_is_somewhere_before_anything_is_read_out_of_it() {
1632        // `make(1, 2).b` has no object to read a member of until one is made, and what makes it
1633        // is a slot the returned registers are written to.
1634        let body = body(
1635            "\
1636struct pair { int a, b; };
1637struct pair make(int a, int b);
1638int second(void) { return make(1, 2).b; }
1639",
1640        );
1641        assert!(body.starts_with("block0:\n    %0 = alloca, size 8, align 4\n"), "{body}");
1642        assert!(body.contains("store %3 -> %0, align 4\n"), "{body}");
1643    }
1644
1645    #[test]
1646    fn a_structure_of_floats_travels_in_floating_point_registers_on_aarch64() {
1647        // The same declaration, classified by a different ABI: three `float` members are an
1648        // eightbyte of two of them and a half eightbyte of the third on SysV, and three vector
1649        // registers on AAPCS64.
1650        let source = "\
1651struct hfa { float x, y, z; };
1652int take(struct hfa h);
1653int give(struct hfa h) { return take(h); }
1654";
1655        assert!(ir(source).contains("func @take(f64, f32) -> i32"), "{}", ir(source));
1656        let mut opts = options();
1657        opts.emit = EmitKind::Ir;
1658        opts.target = "aarch64-unknown-linux-gnu".parse::<Triple>().unwrap();
1659        let result = run(&opts, source);
1660        assert_eq!(result.messages, Vec::<String>::new());
1661        assert!(result.text.contains("func @take(f32, f32, f32) -> i32"), "{}", result.text);
1662    }
1663
1664    #[test]
1665    fn an_array_whose_length_is_not_a_constant_is_a_slot_made_where_its_declaration_is() {
1666        // The size is a multiplication rather than a number, the slot is taken from the stack
1667        // where the declaration is, and the scope it was declared in gives it back.
1668        let source = "\
1669int use(int *);
1670void f(int n) {
1671  {
1672    int a[n];
1673    use(a);
1674  }
1675  use(0);
1676}
1677";
1678        let body = body(source);
1679        assert!(body.contains("mul.nsw"), "{body}");
1680        assert!(body.contains("stacksave"), "{body}");
1681        assert!(body.contains("alloca %"), "{body}");
1682        assert!(body.contains("stackrestore"), "{body}");
1683    }
1684
1685    #[test]
1686    fn a_goto_out_of_the_scope_of_one_gives_its_stack_back_on_the_way() {
1687        // The label is outside the block the array is in, so arriving there means the array is
1688        // gone, and the restore that says so goes in front of the branch. The `goto` is written
1689        // before the walk knows where the label is, which is why the restore is put there at
1690        // the end rather than built where the branch was.
1691        let source = "\
1692int use(int *);
1693int f(int n) {
1694  {
1695    int a[n];
1696    if (use(a)) goto out;
1697    use(0);
1698  }
1699out:
1700  return 0;
1701}
1702";
1703        let body = body(source);
1704        // Two ways out of the block and a restore on each: the jump and the end of the block.
1705        assert_eq!(body.matches("stackrestore").count(), 2, "{body}");
1706        let (_, after) = body.split_once("stackrestore").expect("the stack is given back");
1707        assert!(after.starts_with(" %4\n    jump block"), "{body}");
1708    }
1709
1710    #[test]
1711    fn a_goto_to_a_label_the_array_is_still_alive_at_leaves_the_stack_alone() {
1712        // The label is after the declaration and in the same block, so control that arrives
1713        // there arrives somewhere the array exists. Giving it back would be giving back an
1714        // object the next statement reads.
1715        let source = "\
1716int use(int *);
1717int f(int n) {
1718  int a[n];
1719again:
1720  if (use(a)) goto again;
1721  return 0;
1722}
1723";
1724        let body = body(source);
1725        assert!(body.contains("stacksave"), "{body}");
1726        assert!(!body.contains("stackrestore"), "{body}");
1727    }
1728
1729    #[test]
1730    fn a_goto_back_to_a_label_in_front_of_one_gives_it_back_every_time_round() {
1731        // A loop written out of a `goto`, with the array made inside it. The label is in the
1732        // same block as the declaration and before it, which is a place where the array does
1733        // not exist yet, so the jump there leaves its scope and has to give the stack back. A
1734        // compiler that skips this restore grows the stack once per iteration.
1735        let source = "\
1736int use(int *);
1737int f(int n) {
1738again:
1739  {
1740    int a[n];
1741    if (use(a)) goto again;
1742  }
1743  return 0;
1744}
1745";
1746        let body = body(source);
1747        assert_eq!(body.matches("stacksave").count(), 1, "{body}");
1748        let (_, after) = body.split_once("stackrestore").expect("the stack is given back");
1749        assert!(after.starts_with(" %4\n    jump block1\n"), "{body}");
1750    }
1751
1752    #[test]
1753    fn the_head_of_a_for_loop_is_a_scope_that_closes_where_the_loop_is_left() {
1754        // The scope opened for `for (int a[n];;)` used to stay open, and a scope left open is
1755        // not one mark nobody reads. The marks are a stack, so the next close took this one
1756        // instead of its own, and the body of the loop gave back nothing while the block after
1757        // the loop restored a pointer saved inside it. The verifier refused that, which is how
1758        // it was found.
1759        let source = "\
1760int f(void);
1761void t(void) {
1762  int count = 10;
1763  for (; count--;) {
1764    int b[f()];
1765    int i;
1766    for (i = 0; i < f(); i++) {
1767      b[i] = count;
1768    }
1769  }
1770}
1771";
1772        let body = body(source);
1773        // One save, in the body, and one restore for it, also in the body: the block the
1774        // restore is in is the one the inner loop leaves through, and it goes back round the
1775        // outer loop rather than out of it.
1776        assert_eq!(body.matches("stacksave").count(), 1, "{body}");
1777        let (_, after) = body.split_once("stackrestore").expect("the stack is given back");
1778        let (next, _) = after.split_once("\n\n").expect("a block after the restore");
1779        assert!(next.contains("jump block1("), "{body}");
1780    }
1781
1782    #[test]
1783    fn how_long_one_of_those_is_was_decided_where_it_was_declared_and_not_where_it_is_asked() {
1784        // What C says about the length being evaluated once: `sizeof a` after `n` changed is
1785        // still as long as the array is, which is what `n` was when the array came into being.
1786        let source = "\
1787unsigned long f(int n) {
1788  int a[n];
1789  n = 0;
1790  return sizeof a;
1791}
1792";
1793        let body = body(source);
1794        // One read of the parameter, at the declaration, and the answer is built out of it.
1795        assert_eq!(body.matches("sext.i64 %0").count(), 2, "{body}");
1796    }
1797
1798    #[test]
1799    fn a_block_in_the_middle_of_an_expression_is_walked_where_the_expression_is() {
1800        // GNU's statement expression: the statements happen where they are written and the last
1801        // one is the value, so the temporary in it never becomes a slot and never is copied.
1802        let source = "\
1803int use(int);
1804int f(int x) {
1805  return ({
1806    int t = use(x);
1807    t * t;
1808  });
1809}
1810";
1811        let expected = "\
1812block0(%0: i32):
1813    %1 = call @use(%0) : (i32) -> i32
1814    %2 = mul.nsw %1, %1
1815    return %2
1816";
1817        assert_eq!(body(source), expected);
1818    }
1819
1820    #[test]
1821    fn one_of_those_that_control_never_leaves_is_lowered_and_what_follows_it_is_dropped() {
1822        // A macro that always jumps, which is what this shape is in real code. The value is
1823        // never taken, and the block the rest of the expression would have been built in is
1824        // one nothing branches to, so it goes with the other unreachable blocks.
1825        let source = "int f(int x) { return ({ return x; 0; }); }\n";
1826        assert_eq!(body(source), "block0(%0: i32):\n    return %0\n");
1827    }
1828
1829    #[test]
1830    fn one_argument_off_a_variable_argument_list_stays_an_intrinsic() {
1831        // What it becomes is the target's answer, and this is not where the target's answers
1832        // are, so the walk writes down which list and which type and leaves it at that. Two of
1833        // them are two instructions, since each moves the list on.
1834        let source = "double f(__builtin_va_list ap) { return __builtin_va_arg(ap, double) + __builtin_va_arg(ap, double); }\n";
1835        let expected = "\
1836block0(%0: ptr):
1837    %1 = va_arg.f64 %0
1838    %2 = va_arg.f64 %0
1839    %3 = fadd %1, %2
1840    return %3
1841";
1842        assert_eq!(body(source), expected);
1843    }
1844
1845    #[test]
1846    fn one_that_reads_a_structure_answers_where_the_object_is() {
1847        // An aggregate is not a value, so there is nothing for the result of `va_arg` to be and
1848        // the object form is a second instruction. What it answers is an address, so it is a
1849        // place already and the walk copies nothing out of it: the copy here is the one the
1850        // initializer asks for, into the variable being declared. The size and the alignment
1851        // travel with it because they are what steps the list on and what a target that has to
1852        // put registers somewhere needs to know.
1853        let source = "\
1854struct s { int a; long b; };
1855long f(__builtin_va_list ap) { struct s v = __builtin_va_arg(ap, struct s); return v.b; }
1856";
1857        let expected = "\
1858block0(%0: ptr):
1859    %1 = alloca, size 16, align 8
1860    %2 = va_object %0, size 16, align 8
1861    memcpy %1, %2, size 16, align 8
1862    %3 = iconst.i64 8
1863    %4 = ptr_add %1, %3
1864    %5 = load.i64 %4, align 8
1865    return %5
1866";
1867        assert_eq!(body(source), expected);
1868    }
1869
1870    #[test]
1871    fn a_jump_to_an_address_branches_to_every_label_the_function_takes_the_address_of() {
1872        // GNU's computed goto. Which label the address holds is not known here, so all of them
1873        // are listed, and the values arriving at one are passed on every edge the same way they
1874        // are on an ordinary branch.
1875        let source = "\
1876int f(int c) {
1877  void *p = c ? &&one : &&two;
1878  goto *p;
1879one:
1880  return 1;
1881two:
1882  return 2;
1883}
1884";
1885        let expected = "\
1886block0(%0: i32):
1887    %1 = iconst.i32 0
1888    %2 = icmp ne %0, %1
1889    br_if %2, block1, block2
1890
1891block1:
1892    %3 = block_addr block3
1893    jump block4(%3)
1894
1895block2:
1896    %4 = block_addr block5
1897    jump block4(%4)
1898
1899block3:
1900    %5 = iconst.i32 1
1901    return %5
1902
1903block4(%6: ptr):
1904    indirect_br %6, block3, block5
1905
1906block5:
1907    %7 = iconst.i32 2
1908    return %7
1909";
1910        assert_eq!(body(source), expected);
1911    }
1912
1913    #[test]
1914    fn a_jump_to_an_address_no_label_in_the_function_has_arrives_nowhere() {
1915        // The address came from outside the function, and a jump to a label in another function
1916        // is undefined. The expression is still evaluated, since a call in it has to happen.
1917        let source = "void **next(void);
1918void f(void) { goto *next(); }
1919";
1920        let expected = "\
1921block0:
1922    %0 = call @next() : () -> ptr
1923    unreachable
1924";
1925        assert_eq!(body(source), expected);
1926    }
1927
1928    #[test]
1929    fn an_asm_with_no_operands_is_volatile_and_the_clobbers_are_the_whole_of_what_it_says() {
1930        // Nothing reads a result, so the only thing that keeps it is that it is volatile, which
1931        // a basic asm implies.
1932        let source = "void f(void) { __asm__(\"mfence\" ::: \"memory\"); }\n";
1933        let expected = "\
1934block0:
1935    inline_asm.volatile \"mfence\", \"\", \"memory\"()
1936    return
1937";
1938        assert_eq!(body(source), expected);
1939    }
1940
1941    #[test]
1942    fn the_constraints_are_one_list_in_the_order_the_template_counts_the_operands() {
1943        // The outputs first and then the inputs, which is the numbering `%0` and `%1` use. An
1944        // output in a register is a result, and one that is read as well is an argument too.
1945        let source = "\
1946int f(int x, int y) {
1947  int r;
1948  __asm__(\"addl %2, %0\" : \"=r\"(r), \"+r\"(y) : \"r\"(x));
1949  return r + y;
1950}
1951";
1952        let expected = "\
1953block0(%0: i32, %1: i32):
1954    %2, %3 = inline_asm.(i32, i32) \"addl %2, %0\", \"=r,+r,r\", \"\"(%1, %0)
1955    %4 = add.nsw %2, %3
1956    return %4
1957";
1958        assert_eq!(body(source), expected);
1959    }
1960
1961    #[test]
1962    fn a_memory_operand_travels_as_the_address_of_an_object_that_is_given_a_slot() {
1963        // The assembly is handed a pointer, so the object cannot live in a value, and the scan
1964        // that runs before the walk has to have known that or there would be nothing to point
1965        // at. A structure travels this way whatever else its constraint allows, since there is
1966        // no register that holds one.
1967        let source = "\
1968struct pair { int a, b; };
1969int f(int x) {
1970  int slot = x;
1971  struct pair p = { x, x };
1972  __asm__(\"incl %0\" : \"+m\"(slot), \"=m\"(p));
1973  return slot + p.a;
1974}
1975";
1976        let text = body(source);
1977        assert!(text.contains("inline_asm \"incl %0\", \"+m,=m\", \"\"(%1, %2)\n"), "{text}");
1978        assert!(text.contains("%1 = alloca, size 4, align 4\n"), "{text}");
1979        assert!(text.contains("%2 = alloca, size 8, align 4\n"), "{text}");
1980    }
1981
1982    #[test]
1983    fn an_asm_goto_falls_through_to_its_first_target_and_writes_its_outputs_there() {
1984        // The output is only in scope where the instruction dominates, which is the fall through
1985        // block, so the edge to the label carries the value the object had before the assembly
1986        // ran. That is what document 11 asks for and it is what putting the fall through first
1987        // buys.
1988        let source = "\
1989int f(int x) {
1990  int r = 7;
1991  __asm__ goto(\"cbnz %0, %l1\" : \"=r\"(r) : \"r\"(x) :: away);
1992  return r;
1993away:
1994  return r;
1995}
1996";
1997        let expected = "\
1998block0(%0: i32):
1999    %1 = iconst.i32 7
2000    %2 = inline_asm.volatile \"cbnz %0, %l1\", \"=r,r\", \"\"(%0), labels [block1, block2]
2001
2002block1:
2003    return %2
2004
2005block2:
2006    return %1
2007";
2008        assert_eq!(body(source), expected);
2009    }
2010
2011    #[test]
2012    fn an_asm_statement_that_is_not_well_formed_is_reported_in_the_words_gcc_uses() {
2013        // The operands are checked here rather than by the assembler, because by the time the
2014        // assembler sees the template the operands have become registers and it has nothing left
2015        // to say about the C that named them.
2016        let mut opts = options();
2017        opts.emit = EmitKind::Ir;
2018        for (source, expected) in [
2019            (
2020                "void f(int x) { __asm__(\"\" : \"r\"(x)); }\n",
2021                "output operand constraint lacks '='",
2022            ),
2023            (
2024                "void f(int x) { __asm__(\"\" : \"=r\"(x + 1)); }\n",
2025                "lvalue required in 'asm' statement",
2026            ),
2027            (
2028                "const int g = 1;\nvoid f(void) { __asm__(\"\" : \"=r\"(g)); }\n",
2029                "read-only variable 'g' used as 'asm' output",
2030            ),
2031            (
2032                "void f(int x) { __asm__(\"\" : : \"=r\"(x)); }\n",
2033                "input operand constraint contains '='",
2034            ),
2035            (
2036                "void f(void) { __asm__(\"\" : : \"m\"(1)); }\n",
2037                "memory input 0 is not directly addressable",
2038            ),
2039            ("void f(void) { __asm__(L\"\"); }\n", "wide string literal in 'asm'"),
2040            (
2041                "void f(int x, int y) { __asm__(\"\" : [a] \"=r\"(x) : [a] \"r\"(y)); }\n",
2042                "duplicate asm operand name 'a'",
2043            ),
2044            ("void f(int x) { __asm__(\"%[in]\" : \"=r\"(x)); }\n", "undefined named operand 'in'"),
2045        ] {
2046            let result = run(&opts, source);
2047            assert!(result.failed(), "expected this to be reported:\n{source}");
2048            assert!(
2049                result.messages.iter().any(|m| m.contains(expected)),
2050                "{expected}\n{:?}",
2051                result.messages
2052            );
2053        }
2054    }
2055
2056    #[test]
2057    fn what_the_walk_cannot_build_yet_is_reported_rather_than_mislowered() {
2058        let mut opts = options();
2059        opts.emit = EmitKind::Ir;
2060        for source in [
2061            "int f(int n) { void *p = &&out; if (n) goto *p; { int a[n]; out: return 1; } }\n",
2062            "int f(int n) { int a[n]; __asm__ goto(\"\" ::::out); out: return a[0]; }\n",
2063        ] {
2064            let result = run(&opts, source);
2065            assert!(result.failed(), "expected this to be reported:\n{source}");
2066            assert!(
2067                result.messages.iter().any(|m| m.contains("not supported yet")),
2068                "{:?}",
2069                result.messages
2070            );
2071        }
2072    }
2073
2074    /// Compiles `source` to IR, reads that back as an input, and gives back both texts.
2075    fn round_trip(source: &str) -> (String, String) {
2076        let printed = ir(source);
2077        let mut opts = options();
2078        opts.emit = EmitKind::Ir;
2079        let mut fs = MemoryFileSystem::new();
2080        fs.insert("/main.ir", printed.clone().into_bytes());
2081        let result = compile_ir(&opts, "/main.ir", &fs);
2082        assert_eq!(result.messages, Vec::<String>::new(), "expected this to read back:\n{printed}");
2083        (printed, result.text)
2084    }
2085
2086    #[test]
2087    fn ir_that_arrives_as_an_input_is_read_back_and_written_out_the_same() {
2088        // The other half of the round trip test below, through the driver rather than through
2089        // the library, which is what makes the property something to run over a real program
2090        // rather than over the modules a test builds.
2091        let (printed, again) = round_trip(
2092            "struct point { int x, y; };\n             static const char greeting[] = \"hi\";\n             int puts(const char *);\n             int f(int n) { struct point p = { n, 1 }; puts(greeting); return p.x; }\n",
2093        );
2094        assert_eq!(printed, again);
2095    }
2096
2097    #[test]
2098    fn ir_that_is_not_ir_says_which_line_stopped_it() {
2099        let mut opts = options();
2100        opts.emit = EmitKind::Ir;
2101        let mut fs = MemoryFileSystem::new();
2102        let text = "\
2103; ModuleID = 'a.c'
2104; format 0
2105target triple = \"x86_64-unknown-linux-gnu\"
2106target datalayout = \"e-p:64:64-i64:64-S128\"
2107
2108func @f(), linkage(external) {
2109block0:
2110    frobnicate
2111}
2112";
2113        fs.insert("/main.ir", text.as_bytes().to_vec());
2114        let result = compile_ir(&opts, "/main.ir", &fs);
2115        assert!(result.failed());
2116        assert!(result.messages[0].contains("/main.ir:8"), "{:?}", result.messages);
2117    }
2118
2119    #[test]
2120    fn ir_that_reads_but_does_not_hold_together_is_reported_by_the_verifier() {
2121        // A module that a person edited has not been through the verifier, and the return of
2122        // an `i32` from a function that returns nothing is the kind of thing editing produces.
2123        let mut opts = options();
2124        opts.emit = EmitKind::Ir;
2125        let mut fs = MemoryFileSystem::new();
2126        let text = "\
2127; ModuleID = 'a.c'
2128; format 0
2129target triple = \"x86_64-unknown-linux-gnu\"
2130target datalayout = \"e-p:64:64-i64:64-S128\"
2131
2132func @f(), linkage(external) {
2133block0:
2134    %0 = iconst.i32 1
2135    return %0
2136}
2137";
2138        fs.insert("/main.ir", text.as_bytes().to_vec());
2139        let result = compile_ir(&opts, "/main.ir", &fs);
2140        assert!(result.failed());
2141        assert!(result.messages[0].contains("invalid IR"), "{:?}", result.messages);
2142    }
2143
2144    #[test]
2145    fn a_typed_tree_is_not_something_an_input_of_ir_can_produce() {
2146        // The C that became this is not here any more, so there is nothing to print a tree of.
2147        let mut fs = MemoryFileSystem::new();
2148        fs.insert("/main.ir", Vec::new());
2149        let result = compile_ir(&options(), "/main.ir", &fs);
2150        assert!(result.failed());
2151        assert!(result.messages[0].contains("can only be emitted as IR"), "{:?}", result.messages);
2152    }
2153
2154    #[test]
2155    fn the_printed_ir_reads_back_as_the_same_module() {
2156        // The M2 exit criterion: the text is the module and nothing about it is lost by
2157        // writing it down. Anything the printer invents or the parser drops shows up here.
2158        let text = ir("\
2159struct point { int x, y; };
2160static const char greeting[] = \"hi\";
2161int table[4] = { 1, 2, 3 };
2162int puts(const char *);
2163double half(double x) { return x / 2.0; }
2164int f(int n) {
2165  int total = 0;
2166  for (int i = 0; i < n; i++) {
2167    if (i == 3) continue;
2168    total += table[i];
2169  }
2170  switch (n) {
2171    case 0: total = 1;
2172    case 1: total++; break;
2173    default: total = -total;
2174  }
2175  struct point p = { total, 1 };
2176  int *q = &p.y;
2177  puts(greeting);
2178  return p.x + *q;
2179}
2180int dispatch(int c) {
2181  void *p = c ? &&one : &&two;
2182  goto *p;
2183one:
2184  return 1;
2185two:
2186  return 2;
2187}
2188int assembly(int x, int *p) {
2189  int r;
2190  __asm__ volatile(\"xadd %0, %2\" : \"=r\"(r), \"+m\"(*p) : \"0\"(x) : \"cc\");
2191  __asm__ goto(\"cbnz %0, %l1\" : : \"r\"(r) : : away);
2192  return r;
2193away:
2194  return 0;
2195}
2196");
2197        let mut names = rucc_base::Interner::new();
2198        let module = rucc_ir::parse(&text, &mut names).expect("the printer writes what it reads");
2199        assert_eq!(rucc_ir::print(&module, &names), text);
2200    }
2201}